π© clear the deferred backlog and ship class phase 2
Browse files at this commitafff737e03cd0a6e266903bfe7abea0f8172d410Parent: 8c0ba1e- fix
- π© clear the deferred backlog and ship class phase 2
56 changed files +4498 -461
- README.md +200 -29
- src/constant.rs +39 -3
- src/database.rs +112 -0
- src/domain/board.rs +16 -26
- src/domain/board_stroke.rs +73 -7
- src/domain/class_blueprint.rs +573 -0
- src/domain/class_course.rs +57 -19
- src/domain/class_group.rs +15 -0
- src/domain/class_member.rs +22 -6
- src/domain/class_pump.rs +17 -49
- src/domain/event.rs +119 -1
- src/domain/exam_attempt.rs +16 -0
- src/domain/exam_question.rs +55 -0
- src/domain/mod.rs +1 -0
- src/domain/note.rs +90 -17
- src/domain/parent_link.rs +5 -20
- src/domain/registration.rs +7 -48
- src/domain/user.rs +190 -18
- src/lib.rs +6 -6
- src/migration_sql.rs +78 -0
- src/rate_limit.rs +53 -10
- src/web/appointments.rs +8 -2
- src/web/auth.rs +2 -0
- src/web/bank_questions.rs +4 -2
- src/web/boards.rs +59 -17
- src/web/chatbot.rs +3 -0
- src/web/classes.rs +342 -1
- src/web/courses.rs +11 -3
- src/web/events.rs +30 -5
- src/web/exams/attempts.rs +13 -2
- src/web/exams/mod.rs +3 -1
- src/web/exams/questions.rs +15 -4
- src/web/exams/review.rs +60 -4
- src/web/homework.rs +3 -0
- src/web/meals.rs +8 -0
- src/web/messages.rs +2 -0
- src/web/mod.rs +2 -1
- src/web/notes.rs +5 -3
- src/web/payments.rs +6 -0
- src/web/questions.rs +3 -0
- src/web/sessions.rs +2 -0
- src/web/settings.rs +1 -0
- src/web/subjects.rs +1 -0
- src/web/terms.rs +2 -0
- src/web/users.rs +30 -79
- src/web/work.rs +1 -0
- tests/integration.rs +285 -77
- tests/limits_completeness.rs +13 -0
- tests/pagination.rs +40 -0
- tests/rate_limit.rs +34 -0
- tests/regress_blueprints.rs +644 -0
- tests/regress_boards.rs +181 -0
- tests/regress_event_class_audience.rs +268 -0
- tests/regress_review.rs +363 -0
- tests/regress_roles.rs +243 -1
- tests/spec_bounds.rs +67 -0
README.mdmodified+200 -29
| @@ -12,8 +12,8 @@ per-file size cap is school policy in settings (`max_file_bytes`, default | |||
| 12 | body into the recipient's inbox, each side filing its own copy through | 12 | body into the recipient's inbox, each side filing its own copy through |
| 13 | archive/trash with a read flag the sender sees as a receipt (the only place a | 13 | archive/trash with a read flag the sender sees as a receipt (the only place a |
| 14 | `parent` writes). Attendance is event + attendees: create an event with an **audience** | 14 | `parent` writes). Attendance is event + attendees: create an event with an **audience** |
| 15 | -(the whole school, one role, a course's enrollment, or a **registration** | 15 | +(the whole school, one role, a course's enrollment, a **class section's** |
| 16 | -signup list β omit for school-wide), then teachers mark the expected attendees | 16 | +roster, or a **registration** signup list β omit for school-wide), then teachers mark the expected attendees |
| 17 | present / absent / late / excused (students never self-mark), and a **roster | 17 | present / absent / late / excused (students never self-mark), and a **roster |
| 18 | report** shows who was expected and who missed. Registration lists fill seat | 18 | report** shows who was expected and who missed. Registration lists fill seat |
| 19 | by seat: teachers register students (never the other way round), staff | 19 | by seat: teachers register students (never the other way round), staff |
| @@ -46,7 +46,11 @@ name a **homeroom teacher** (*sΔ±nΔ±f ΓΆΔretmeni*, `teacher_id` β any teacher | |||
| 46 | account, cleared automatically when that account is demoted), and while every | 46 | account, cleared automatically when that account is demoted), and while every |
| 47 | other class read is teacher+, a student reads their own section at | 47 | other class read is teacher+, a student reads their own section at |
| 48 | `GET /classes/me` (staff and a linked parent read anyone's at | 48 | `GET /classes/me` (staff and a linked parent read anyone's at |
| 49 | -`GET /classes/user/{user}`). Students read a per-course weighted average and | 49 | +`GET /classes/user/{user}`). A grade can also carry a **blueprint** β the |
| 50 | +course list every section at that grade takes (`/classes/blueprints`), applied | ||
| 51 | +to each section best-effort, with anything a limit refuses returned in | ||
| 52 | +`skipped` and anything a human attached by hand left alone. Students read a | ||
| 53 | +per-course weighted average and | ||
| 50 | an overall average from their mark report β each exam weighted by its **kind** | 54 | an overall average from their mark report β each exam weighted by its **kind** |
| 51 | (midterms can count double, orals once: weights are set per kind in settings, | 55 | (midterms can count double, orals once: weights are set per kind in settings, |
| 52 | not per exam). Exams run **sync** (one | 56 | not per exam). Exams run **sync** (one |
| @@ -422,6 +426,25 @@ Notes: | |||
| 422 | uploadable `image_content_types` are the exact accepted spellings β build | 426 | uploadable `image_content_types` are the exact accepted spellings β build |
| 423 | pickers from these rather than from a literal list. | 427 | pickers from these rather than from a literal list. |
| 424 | 428 | ||
| 429 | +**`422` versus `400`.** The two refusals mean different things and a client | ||
| 430 | +must not treat them alike. Every JSON-bodied route can answer **`422`**: the | ||
| 431 | +body never became the type the handler asked for β a field of the wrong type, | ||
| 432 | +or a required field missing. It answers with a **`text/plain` diagnostic**, not | ||
| 433 | +the `{"error": β¦}` envelope every other failure carries β e.g. `Failed to | ||
| 434 | +deserialize the JSON body into the target type: username: invalid type: | ||
| 435 | +integer 5, expected a string at line 1 column 14` β so a client must not try to | ||
| 436 | +parse it like the other errors: log it, and show the user the field rules | ||
| 437 | +`/limits` publishes. **`400`** is the other failure and it does carry the usual | ||
| 438 | +`{"error": "β¦"}`: either the bytes were not JSON (`{not json`), or the body | ||
| 439 | +parsed cleanly and then broke a domain rule β `{"username":"a"}` answers | ||
| 440 | +`400 {"error": "username must be at least 3 characters (got 1)"}`. So `422` | ||
| 441 | +says the shape is wrong and `400` says the value is. **Multipart uploads never | ||
| 442 | +answer `422`** β a bad boundary or the wrong content type on a file route is a | ||
| 443 | +`400`, since there is no JSON body to reject. Each JSON operation declares its | ||
| 444 | +`422` in the OpenAPI spec and a drift test (`spec_bounds.rs`) checks that in | ||
| 445 | +both directions, so the spec cannot fall behind the handlers and the multipart | ||
| 446 | +routes cannot quietly gain a status they never return. | ||
| 447 | + | ||
| 425 | ## Rate limiting | 448 | ## Rate limiting |
| 426 | 449 | ||
| 427 | Requests are limited per client IP over a fixed 60-second window, in two tiers: | 450 | Requests are limited per client IP over a fixed 60-second window, in two tiers: |
| @@ -448,6 +471,19 @@ a just-started process can spend up to the tier's budget in the 2 seconds | |||
| 448 | before its first fold tightens it. If the database is down the tiers simply | 471 | before its first fold tightens it. If the database is down the tiers simply |
| 449 | fall back to their own local budgets β nobody is refused for it. | 472 | fall back to their own local budgets β nobody is refused for it. |
| 450 | 473 | ||
| 474 | +One client, one bucket, so the bucket map is only as bounded as the client | ||
| 475 | +set β and a single IPv6 /64 is not bounded at all. Past 10 000 live clients a | ||
| 476 | +new key first sweeps out lapsed windows, then evicts the least-spent live | ||
| 477 | +buckets, and never a bucket that has reached its limit (freeing one would hand | ||
| 478 | +back the refusal it was enforcing). If every bucket is exhausted there is | ||
| 479 | +nothing to evict, and a client that has never been seen gets no bucket of its | ||
| 480 | +own: those clients are metered together against one shared budget of 600 | ||
| 481 | +requests a minute for all of them. Refusing them outright would let an attacker | ||
| 482 | +who can fill the map `429` the whole school; admitting them freely would make a | ||
| 483 | +filled map the way to buy unmetered throughput. Only reachable under a | ||
| 484 | +deliberate flood, and only newcomers during it are affected β every client | ||
| 485 | +already in the map keeps its own counter. | ||
| 486 | + | ||
| 451 | Behind a reverse proxy every connection carries the proxy's address, so also | 487 | Behind a reverse proxy every connection carries the proxy's address, so also |
| 452 | set `TRUST_PROXY=true` to key clients by the rightmost `X-Forwarded-For` entry | 488 | set `TRUST_PROXY=true` to key clients by the rightmost `X-Forwarded-For` entry |
| 453 | (the one the proxy itself appends). Leave it off when clients reach the server | 489 | (the one the proxy itself appends). Leave it off when clients reach the server |
| @@ -497,13 +533,22 @@ own seats by hand. Seats on lists that have already closed (the event started, | |||
| 497 | or its `ends_at`-only deadline passed) are never touched β that roster is | 533 | or its `ends_at`-only deadline passed) are never touched β that roster is |
| 498 | history, and re-registering is refused. | 534 | history, and re-registering is refused. |
| 499 | 535 | ||
| 536 | +The role write and every sweep it implies β class memberships and their | ||
| 537 | +counters, all enrollments and their seats, parent ties on both sides, a | ||
| 538 | +demoted parent's still-freeable event seats, whiteboard rosters, course | ||
| 539 | +staffing and homeroom-teacher columns β commit as **one transaction**. It | ||
| 540 | +either all lands or none of it does: a failure answers `500` with the account | ||
| 541 | +still holding its old role and every grant of it still standing, and the same | ||
| 542 | +`PATCH` retried applies the lot. Signup lists that have already frozen are | ||
| 543 | +still left exactly as they stand. | ||
| 544 | + | ||
| 500 | | Action | Minimum role | Notes | | 545 | | Action | Minimum role | Notes | |
| 501 | |------------------------------------------|--------------|-----------------------------------------------| | 546 | |------------------------------------------|--------------|-----------------------------------------------| |
| 502 | | Register / login / view own account | (any) | Registration always creates a `student` | | 547 | | Register / login / view own account | (any) | Registration always creates a `student` | |
| 503 | | View events, own notes; CRUD notes + their files | student | Everyone can read events and keep notes; note files (upload/download) are walled per owner like the notes themselves | | 548 | | View events, own notes; CRUD notes + their files | student | Everyone can read events and keep notes; note files (upload/download) are walled per owner like the notes themselves | |
| 504 | | Send / read / file / delete messages | (any) | One-to-one, any user to any user (`parent` included β the role's one write); each party only ever touches their own copy | | 549 | | Send / read / file / delete messages | (any) | One-to-one, any user to any user (`parent` included β the role's one write); each party only ever touches their own copy | |
| 505 | | Mark event attendance; remove attendance rows | teacher | Only users in the event's **audience** can be marked; students never mark β a teacher+ may mark anyone expected, themselves included | | 550 | | Mark event attendance; remove attendance rows | teacher | Only users in the event's **audience** can be marked; students never mark β a teacher+ may mark anyone expected, themselves included | |
| 506 | -| Create events | teacher | The audience (school / role / course / registration) is set at creation and editable later | | 551 | +| Create events | teacher | The audience (school / role / course / class / registration) is set at creation and editable later | |
| 507 | | Register users onto a registration event | teacher | Teachers place **students** (students never register themselves) and take a seat for **themselves** β never for another staff member. Unregistering mirrors the same rule | | 552 | | Register users onto a registration event | teacher | Teachers place **students** (students never register themselves) and take a seat for **themselves** β never for another staff member. Unregistering mirrors the same rule | |
| 508 | | List an event's attendance or its roster report | teacher | Students read their own tallies via the attendance report | | 553 | | List an event's attendance or its roster report | teacher | Students read their own tallies via the attendance report | |
| 509 | | Edit / delete an event | teacher | Only the **creator**, or a `manager`+ for any event β in both cases only while still `teacher`+ | | 554 | | Edit / delete an event | teacher | Only the **creator**, or a `manager`+ for any event β in both cases only while still `teacher`+ | |
| @@ -748,6 +793,12 @@ window filtering, before paging; negative values are a `400` naming the field. | |||
| 748 | | 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`) | | 793 | | 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`) | |
| 749 | | GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first Β· paged | | 794 | | GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first Β· paged | |
| 750 | | 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 | | 795 | | 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 | |
| 796 | +| POST | `/classes/blueprints` | manager | Create a grade's course blueprint and stock every section already at that grade (best-effort; returns `skipped`) | | ||
| 797 | +| GET | `/classes/blueprints` | manager | List every grade blueprint Β· paged | | ||
| 798 | +| GET | `/classes/blueprints/{grade}` | manager | One grade's blueprint | | ||
| 799 | +| PATCH | `/classes/blueprints/{grade}` | manager | Replace the course list and reconcile every section at that grade (returns `skipped`) | | ||
| 800 | +| DELETE | `/classes/blueprints/{grade}` | manager | Delete the blueprint and detach every attachment it made | | ||
| 801 | +| POST | `/classes/{id}/blueprint` | manager | Stock one section from its grade's blueprint (returns `skipped`) | | ||
| 751 | | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` β add a lesson (course manager; teacher defaults to the caller) | | 802 | | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` β add a lesson (course manager; teacher defaults to the caller) | |
| 752 | | GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) Β· paged | | 803 | | GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) Β· paged | |
| 753 | | POST | `/courses/{id}/subjects` | teacher | `{name, description?}` β add a curriculum subject (course manager) | | 804 | | POST | `/courses/{id}/subjects` | teacher | `{name, description?}` β add a curriculum subject (course manager) | |
| @@ -915,13 +966,13 @@ window filtering, before paging; negative values are a `400` naming the field. | |||
| 915 | | GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` | | 966 | | GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` | |
| 916 | | GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` β or one `error` β and close; an already-finished answer replays (see "Chatbot") | | 967 | | GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` β or one `error` β and close; an already-finished answer replays (see "Chatbot") | |
| 917 | | POST | `/boards` | student | `{title, participants?}` β open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` | | 968 | | POST | `/boards` | student | `{title, participants?}` β open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` | |
| 918 | -| GET | `/boards` | student | Boards the caller created or was invited to, newest first Β· paged | | 969 | +| GET | `/boards` | student | Boards the caller created or was invited to, newest first. `?open=true\|false` narrows by the closing stamp Β· paged | |
| 919 | | GET | `/boards/{id}` | student | One board β a `404`, never a `403`, for anyone not on it | | 970 | | GET | `/boards/{id}` | student | One board β a `404`, never a `403`, for anyone not on it | |
| 920 | | GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first Β· paged | | 971 | | GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first Β· paged | |
| 921 | | GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included Β· `?epoch=` for one epoch Β· paged | | 972 | | GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included Β· `?epoch=` for one epoch Β· paged | |
| 922 | | 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 | | 973 | | 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 | |
| 923 | | PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` β re-title (any participant); the roster and the lock are the creator's alone (`403`) | | 974 | | PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` β re-title (any participant); the roster and the lock are the creator's alone (`403`) | |
| 924 | -| 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) | | 975 | +| 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, on a **locked** 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) | |
| 925 | | POST | `/boards/{id}/close` | student | **Creator only**: retire the board β permanently read-only, still fully readable; idempotent, and there is no reopen | | 976 | | POST | `/boards/{id}/close` | student | **Creator only**: retire the board β permanently read-only, still fully readable; idempotent, and there is no reopen | |
| 926 | | DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats | | 977 | | DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats | |
| 927 | | 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") | | 978 | | 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") | |
| @@ -968,11 +1019,18 @@ the past (else `400`). On `PATCH`, an omitted time keeps its value and an | |||
| 968 | explicit `null` clears it. | 1019 | explicit `null` clears it. |
| 969 | An event's `audience` is a tagged object β `{"kind": "school"}` (the default), | 1020 | An event's `audience` is a tagged object β `{"kind": "school"}` (the default), |
| 970 | `{"kind": "role", "role": "student"}` (that exact role, no "and above"), | 1021 | `{"kind": "role", "role": "student"}` (that exact role, no "and above"), |
| 971 | -`{"kind": "course", "course": "<id>"}` (the course's current enrollment), or | 1022 | +`{"kind": "course", "course": "<id>"}` (the course's current enrollment), |
| 1023 | +`{"kind": "class", "class": "<class id>"}` (the students currently in that | ||
| 1024 | +class section β Εube), or | ||
| 972 | `{"kind": "registration", "capacity": 30}` (a signup list; `capacity` optional, | 1025 | `{"kind": "registration", "capacity": 30}` (a signup list; `capacity` optional, |
| 973 | `null` = unlimited) β and is the event's **expected-attendee roster**, resolved | 1026 | `null` = unlimited) β and is the event's **expected-attendee roster**, resolved |
| 974 | -live at read time: role changes, (un)enrollments, and (un)registrations move | 1027 | +live at read time: role changes, (un)enrollments, class-roster changes, and |
| 975 | -people in and out by themselves. It never hides the event β everyone sees every | 1028 | +(un)registrations move people in and out by themselves. A class audience is |
| 1029 | +live like the rest: adding a student to the class puts them on every one of its | ||
| 1030 | +events' rosters at once, and removing them takes them off. The homeroom teacher | ||
| 1031 | +is not implied β a mixed gathering wants a `role` or `registration` audience. | ||
| 1032 | +An unknown class id is a `400`, and a class deleted later leaves the event | ||
| 1033 | +standing with an empty roster, exactly as a deleted course does. It never hides the event β everyone sees every | ||
| 976 | event. Only audience members can be marked; `GET /events/{id}/roster` joins the | 1034 | event. Only audience members can be marked; `GET /events/{id}/roster` joins the |
| 977 | live roster with the recorded marks (`status: null` = expected but never | 1035 | live roster with the recorded marks (`status: null` = expected but never |
| 978 | marked). Attendance rows for people a later audience edit (or unenrollment / | 1036 | marked). Attendance rows for people a later audience edit (or unenrollment / |
| @@ -1843,14 +1901,36 @@ Two per-exam policy knobs ride along, both **live-editable** at any point: | |||
| 1843 | midway through sitting 2. Submit the sitting first; an expired one reviews | 1901 | midway through sitting 2. Submit the sitting first; an expired one reviews |
| 1844 | fine. | 1902 | fine. |
| 1845 | 1903 | ||
| 1846 | - **Known limit, accepted:** that gate is *per exam*. Instantiating one question | 1904 | + That gate is *per exam*, and a second, narrower one covers what it cannot see. |
| 1847 | - bank template into two exams copies its `correct` verbatim into both (the bank | 1905 | + Instantiating one question bank template into two exams copies its `correct` |
| 1848 | - is a copy-into-exam model, not a link), so a student sitting exam A can read | 1906 | + verbatim into both (the bank is a copy-into-exam model, not a link), so |
| 1849 | - the same question's answer off exam B if B is graded and has review on. The | 1907 | + reviewing exam A used to hand out the answer to a question the caller was |
| 1850 | - narrower gate cannot see it, and widening review to "no in-progress sitting on | 1908 | + still writing in exam B. Review now blanks those questions instead of closing: |
| 1851 | - *any* exam" would close review far too broadly, since `open`-mode sittings | 1909 | + a question whose bank template also sits under an exam the caller has an |
| 1852 | - never expire on their own. Teachers reusing one template across a live exam | 1910 | + in-progress sitting on comes back with `correct: null` from `GET |
| 1853 | - and a reviewable one should expect that overlap. | 1911 | + /exams/{id}/review/questions`, and with `is_correct: null` and no share of |
| 1912 | + `auto_score` on the answer sheet. The key is what is hidden, never the | ||
| 1913 | + question or the caller's own answer. Keyed on the template rather than the | ||
| 1914 | + exam deliberately: widening the gate to "no in-progress sitting on *any* exam" | ||
| 1915 | + would close review far too broadly, since `open`-mode sittings never expire on | ||
| 1916 | + their own, whereas this hides only the overlapping questions and gives the key | ||
| 1917 | + back the moment that other sitting is submitted or expires. A question links | ||
| 1918 | + to a template whichever way it got there, and both links are matched: the | ||
| 1919 | + template it was instantiated from (`from_bank`) *and* the template minted by | ||
| 1920 | + saving it into the bank (`banked_as`). So a question written by hand into | ||
| 1921 | + exam A, saved to the bank, and then instantiated into exam B is hidden while | ||
| 1922 | + B is live β the two copies hold the identical `correct` even though A's copy | ||
| 1923 | + never came out of the bank. Only a question with no bank link at all, in | ||
| 1924 | + either direction, is never hidden. | ||
| 1925 | + | ||
| 1926 | + **Known limit, accepted:** deleting a bank template clears *both* columns β | ||
| 1927 | + `from_bank` on every question it produced and `banked_as` on the question it | ||
| 1928 | + was saved out of β so a pair linked through a template that was since deleted | ||
| 1929 | + keeps the identical `correct` with nothing left to join them by. That overlap | ||
| 1930 | + is invisible to the redaction. It is the only one left: the copy is made at | ||
| 1931 | + instantiate time and the link is written in the same request, so a shared | ||
| 1932 | + `correct` and a live template link are created together and only a template | ||
| 1933 | + delete separates them again. | ||
| 1854 | 1934 | ||
| 1855 | A student **sits** an exam through attempts (sitting 1, 2, β¦ β each row id is | 1935 | A student **sits** an exam through attempts (sitting 1, 2, β¦ β each row id is |
| 1856 | the composite `exam_user[_seq]` key, so a sitting exists at most once by | 1936 | the composite `exam_user[_seq]` key, so a sitting exists at most once by |
| @@ -2466,6 +2546,54 @@ space is exactly the unbounded transaction the ceilings exist to prevent. Only | |||
| 2466 | a class that predates the ceilings can be there, and only shrinking the | 2546 | a class that predates the ceilings can be there, and only shrinking the |
| 2467 | overloaded axis clears it. | 2547 | overloaded axis clears it. |
| 2468 | 2548 | ||
| 2549 | +### Grade blueprints | ||
| 2550 | + | ||
| 2551 | +A Turkish school runs many Εube at one grade and stocks each with the same | ||
| 2552 | +courses. A blueprint says that list once: `POST /classes/blueprints` with a | ||
| 2553 | +`grade` label and `course_ids`, and every section already at that grade is | ||
| 2554 | +stocked immediately. `POST /classes/{id}/blueprint` stocks one section from its | ||
| 2555 | +grade's template β idempotent, so it is safe on a class that already carries | ||
| 2556 | +some of the courses. | ||
| 2557 | + | ||
| 2558 | +The blueprint is a template, not a new kind of membership. Applying it calls | ||
| 2559 | +the same attach a manager's own `POST /classes/{id}/courses` does, so what | ||
| 2560 | +lands is ordinary `class_course` links and ordinary `enrollment` rows, and an | ||
| 2561 | +elective a student takes alone stays an individual enrollment nothing here can | ||
| 2562 | +see. | ||
| 2563 | + | ||
| 2564 | +**Editing retro-pumps.** `PATCH /classes/blueprints/{grade}` takes the whole | ||
| 2565 | +new list (a set, not a delta) and reconciles every section at the grade, | ||
| 2566 | +including the ones that existed before the blueprint did. | ||
| 2567 | + | ||
| 2568 | +**Pumping is best-effort.** Each (section, course) pair is one all-or-nothing | ||
| 2569 | +transaction. A pair that would breach a limit β the section is at | ||
| 2570 | +`max_class_courses`, or the course has no free seat for the whole section β is | ||
| 2571 | +skipped and reported in `skipped`, naming the class, the class's name, the | ||
| 2572 | +course and the reason; every other section is still stocked. So a blueprint | ||
| 2573 | +edit is allowed to leave a partial state: one full course must not stop the | ||
| 2574 | +other eleven sections from being set up. Nothing moves on a skipped section β | ||
| 2575 | +not its attachment count, not a seat on the course. | ||
| 2576 | + | ||
| 2577 | +A skip names the record that failed: `the class was deleted while the blueprint | ||
| 2578 | +was being applied` (the section vanished mid-pump), `this course no longer | ||
| 2579 | +exists β it has been dropped from the blueprint` (the course was deleted; the | ||
| 2580 | +pump also removes the dangling id from the template, so the template shrinks | ||
| 2581 | +and the skip is reported once and never again), `the class is already at its | ||
| 2582 | +course ceiling`, `the class holds more students than a course attach is allowed | ||
| 2583 | +to enroll at once`, `the course has no free seat for the whole class`, and | ||
| 2584 | +`another course attached to this class no longer exists β detach it first`. | ||
| 2585 | + | ||
| 2586 | +**Removal spares what a human placed.** Every attachment a blueprint makes is | ||
| 2587 | +tagged with it. Dropping a course from the list detaches it only where the | ||
| 2588 | +blueprint attached it (sweeping the enrollments it pumped, repairing to a rival | ||
| 2589 | +class first exactly as a manual detach does), and a course a human attached to | ||
| 2590 | +that class by hand carries no tag and is left exactly where it is. Deleting a | ||
| 2591 | +blueprint applies that to its whole list. | ||
| 2592 | + | ||
| 2593 | +A blueprint names no term β the class names its own. The grade label is the | ||
| 2594 | +blueprint's id, so there is one per grade (a second is a `409`), and it must be | ||
| 2595 | +non-empty and contain none of `/ \ ? # %`. | ||
| 2596 | + | ||
| 2469 | ## Quick tour (curl) | 2597 | ## Quick tour (curl) |
| 2470 | 2598 | ||
| 2471 | ```sh | 2599 | ```sh |
| @@ -2859,13 +2987,24 @@ The roster is spelled `participants` everywhere β in the `POST` body, in the | |||
| 2859 | `PATCH` body and in every board response β so the field never changes name | 2987 | `PATCH` body and in every board response β so the field never changes name |
| 2860 | between a request and a reply. That is the *only* thing the shared spelling | 2988 | between a request and a reply. That is the *only* thing the shared spelling |
| 2861 | buys: unlike the rest of this API, the two board request bodies **reject an | 2989 | buys: unlike the rest of this API, the two board request bodies **reject an |
| 2862 | -unknown key** (`422`) rather than ignoring it, because a misspelled roster | 2990 | +unknown key** rather than ignoring it β the same `422` any JSON-bodied route |
| 2991 | +answers a malformed body with β because a misspelled roster | ||
| 2863 | would otherwise open a board its author is silently alone on. So a body must | 2992 | would otherwise open a board its author is silently alone on. So a body must |
| 2864 | carry **only** the fields that request accepts β a board it just read is not a | 2993 | carry **only** the fields that request accepts β a board it just read is not a |
| 2865 | legal body, since `id`, `creator`, `locked_by`, `epoch` and the rest are all | 2994 | legal body, since `id`, `creator`, `locked_by`, `epoch` and the rest are all |
| 2866 | unknown to `POST` and `PATCH`. A read-modify-write client sends the writable | 2995 | unknown to `POST` and `PATCH`. A read-modify-write client sends the writable |
| 2867 | fields it changed, never the whole board object back. | 2996 | fields it changed, never the whole board object back. |
| 2868 | 2997 | ||
| 2998 | +**Roster repair.** A roster only ever holds users of at least the `student` | ||
| 2999 | +role. A demotion sweeps the user off every board they were on, and the first | ||
| 3000 | +boot of this version repaired the rosters an older binary left behind β | ||
| 3001 | +parents, and ids of users deleted since. On top of that, a `PATCH` may always | ||
| 3002 | +send back the roster it was just served: an id already on the board that has | ||
| 3003 | +stopped qualifying is dropped silently rather than refused, so a | ||
| 3004 | +read-modify-write never wedges on a value the server itself handed over. | ||
| 3005 | +Naming a *new* id that is unknown or a parent is still a `400`, and the whole | ||
| 3006 | +call is refused β the roster is never half-applied. | ||
| 3007 | + | ||
| 2869 | **No parents, anywhere.** The `parent` role is the school's read-only observer, | 3008 | **No parents, anywhere.** The `parent` role is the school's read-only observer, |
| 2870 | and it has no whiteboard access at all β not a view-only tier, none. It is | 3009 | and it has no whiteboard access at all β not a view-only tier, none. It is |
| 2871 | refused `POST /boards` and `GET /boards` with a `403`, and it cannot be *named* | 3010 | refused `POST /boards` and `GET /boards` with a `403`, and it cannot be *named* |
| @@ -2894,13 +3033,22 @@ markers *are* the epoch index, which is why there is no epochs table and why | |||
| 2894 | the open (unclosed) epoch is deliberately absent from `GET /boards/{id}/epochs`. | 3033 | the open (unclosed) epoch is deliberately absent from `GET /boards/{id}/epochs`. |
| 2895 | `DELETE /boards/{id}` is the one operation here that really destroys marks. | 3034 | `DELETE /boards/{id}` is the one operation here that really destroys marks. |
| 2896 | 3035 | ||
| 2897 | -**A blank canvas cannot be cleared** (`409` β as a closed board is, while a | 3036 | +**A blank canvas cannot be cleared** (`409` β as a closed board is, and as a |
| 2898 | -participant who is not the creator gets the `403` the two doors above give | 3037 | +**locked** one is, while a participant who is not the creator gets the `403` |
| 2899 | -them). The marker is a real stored row and it is charged to the board's | 3038 | +the two doors above give them). The marker is a real stored row and it is |
| 3039 | +charged to the board's | ||
| 2900 | lifetime budget, so a clear has to close at least one mark to be worth one β | 3040 | lifetime budget, so a clear has to close at least one mark to be worth one β |
| 2901 | without that rule every press of a button the creator can hold down minted a | 3041 | without that rule every press of a button the creator can hold down minted a |
| 2902 | free row, and the epoch index filled with zero-stroke sessions. | 3042 | free row, and the epoch index filled with zero-stroke sessions. |
| 2903 | 3043 | ||
| 3044 | +**A locked board cannot be cleared.** The lock is the creator's pause on the | ||
| 3045 | +canvas and it holds against every write to it, including their own | ||
| 3046 | +`POST /boards/{id}/clear` (and the socket's `clear` command, | ||
| 3047 | +`error{code:"locked"}`). A locked board that is also at `max_epoch_strokes` is | ||
| 3048 | +therefore recovered by unlock β clear β relock; that cost is deliberate, so | ||
| 3049 | +that "locked" means one thing everywhere rather than "locked, except for one | ||
| 3050 | +caller". | ||
| 3051 | + | ||
| 2904 | **Three caps, and only one of them is terminal** (all three published at `GET | 3052 | **Three caps, and only one of them is terminal** (all three published at `GET |
| 2905 | /limits` under `board`): | 3053 | /limits` under `board`): |
| 2906 | 3054 | ||
| @@ -2937,13 +3085,25 @@ rides the socket. History is an explicit paged REST read: | |||
| 2937 | markers included, `?epoch=` for a single one) and `GET /boards/{id}/epochs` | 3085 | markers included, `?epoch=` for a single one) and `GET /boards/{id}/epochs` |
| 2938 | (the marker index β enough to offer "replay session 3" without scanning the | 3086 | (the marker index β enough to offer "replay session 3" without scanning the |
| 2939 | log). `GET /boards/{id}/strokes` is the current epoch over REST, the catch-up | 3087 | log). `GET /boards/{id}/strokes` is the current epoch over REST, the catch-up |
| 2940 | -and fallback path for the same canvas the socket replays β with one deliberate | 3088 | +and fallback path for the same canvas the socket replays. For a live canvas the |
| 2941 | -difference: the REST read is *not* filtered by kind, while the socket serves | 3089 | +socket is the authority. |
| 2942 | -`kind: "stroke"` rows only. In the steady state that is a distinction without a | 3090 | + |
| 2943 | -difference, since a marker is written with the epoch it *closed* and the open | 3091 | +**The live canvas never shows a marker.** `GET /boards/{id}/strokes` serves |
| 2944 | -epoch has none; the case where it shows is a clear landing between the board | 3092 | +drawn marks only. The current epoch holds no `clear` marker by construction β a |
| 2945 | -read and the row read, which surfaces that epoch's closing marker in the page. | 3093 | +marker records the epoch it *closed* β but a clear committing between the board |
| 2946 | -For a live canvas the socket is the authority. | 3094 | +read and the row read would otherwise put one in the page, and the board room's |
| 3095 | +socket, which replays strokes only, would never show it. The markers are not | ||
| 3096 | +lost: `GET /boards/{id}/history` and `GET /boards/{id}/epochs` are where they | ||
| 3097 | +live. | ||
| 3098 | + | ||
| 3099 | +**Listing.** `GET /boards?open=true` is every board of the caller's that has | ||
| 3100 | +not been closed; `?open=false` is the closed ones; omit it for both. The filter | ||
| 3101 | +reaches the database, so `total` is the filtered count and `?open=true&limit=1` | ||
| 3102 | +is a cheap "do I have a live board" probe. It reads `closed_at` and only that β | ||
| 3103 | +a locked board is still an open board, and so is one whose lifetime stroke | ||
| 3104 | +budget is spent but which was never drawn on again, because nothing has stamped | ||
| 3105 | +it. A closed board is never deleted, so with `max_boards_per_creator` at 200 | ||
| 3106 | +this is the only way a heavy creator keeps the list readable. | ||
| 2947 | 3107 | ||
| 2948 | **The board room (WebSocket)** β `GET /boards/{id}/ws`, cookie-authed like | 3108 | **The board room (WebSocket)** β `GET /boards/{id}/ws`, cookie-authed like |
| 2949 | everything else and, like the exam room, outside the OpenAPI spec (an upgrade | 3109 | everything else and, like the exam room, outside the OpenAPI spec (an upgrade |
| @@ -3078,7 +3238,8 @@ throughput or an accepted race; removing the conditional write behind it costs | |||
| 3078 | the invariant. | 3238 | the invariant. |
| 3079 | 3239 | ||
| 3080 | Boot is unconditional: the schema batches, the backfills and the admin seed all | 3240 | Boot is unconditional: the schema batches, the backfills and the admin seed all |
| 3081 | -run on every start, because exactly one process ever starts. Deployment is | 3241 | +run on every start, because exactly one process ever starts (the one exception |
| 3242 | +is the marked one-time repair below). Deployment is | ||
| 3082 | stop-the-world β `podman compose down` then `up`, never overlapping β and a | 3243 | stop-the-world β `podman compose down` then `up`, never overlapping β and a |
| 3083 | release that adds or renames a stored counter *requires* it. An old binary | 3244 | release that adds or renames a stored counter *requires* it. An old binary |
| 3084 | writes rows without touching the new counter, the `= NONE` backfill guard | 3245 | writes rows without touching the new counter, the `= NONE` backfill guard |
| @@ -3090,6 +3251,14 @@ that repair heals an under-count the `= NONE` guard would have skipped. | |||
| 3090 | In-flight work does not survive | 3251 | In-flight work does not survive |
| 3091 | a restart either: a chatbot turn mid-inference settles `failed`/`interrupted`. | 3252 | a restart either: a chatbot turn mid-inference settles `failed`/`interrupted`. |
| 3092 | 3253 | ||
| 3254 | +The one thing boot does *not* redo is tracked in `migration_mark` β one row per | ||
| 3255 | +backfill that is genuinely one-time, keyed by the backfill's own name. Most | ||
| 3256 | +backfills converge to a `WHERE` that matches nothing and are free to re-run, so | ||
| 3257 | +they carry no mark; the board-roster repair is different because its cost is | ||
| 3258 | +the **scan** (a `user` pass per board) rather than the write, so it is gated on | ||
| 3259 | +`migration_mark:board_roster` and skipped entirely once done. A volume that | ||
| 3260 | +never ran the repair holds no mark and still gets repaired on its next boot. | ||
| 3261 | + | ||
| 3093 | ## Layout | 3262 | ## Layout |
| 3094 | 3263 | ||
| 3095 | ``` | 3264 | ``` |
| @@ -3151,6 +3320,8 @@ src/ | |||
| 3151 | them into every course the class holds) | 3320 | them into every course the class holds) |
| 3152 | class_course.rs ClassCourse (one course on a class; attaching it enrolls | 3321 | class_course.rs ClassCourse (one course on a class; attaching it enrolls |
| 3153 | the class's whole roster) | 3322 | the class's whole roster) |
| 3323 | + class_blueprint.rs ClassBlueprintId Β· ClassBlueprint (a grade's course list; | ||
| 3324 | + applying it stocks every section at that grade, best-effort) | ||
| 3154 | class_pump.rs attach/detach (the shared transaction behind both of those: | 3325 | class_pump.rs attach/detach (the shared transaction behind both of those: |
| 3155 | link row, class counter and the enrollments it implies move | 3326 | link row, class counter and the enrollments it implies move |
| 3156 | together or not at all) | 3327 | together or not at all) |
src/constant.rsmodified+39 -3
| @@ -569,11 +569,29 @@ pub const DEFAULT_CHATBOT_RATE_LIMIT: u32 = 20; | |||
| 569 | /// Evicting a bucket that had reached its limit would hand back the very | 569 | /// Evicting a bucket that had reached its limit would hand back the very |
| 570 | /// refusal it was enforcing, so a flood cannot make the limiter fail open; the | 570 | /// refusal it was enforcing, so a flood cannot make the limiter fail open; the |
| 571 | /// concession is that while the map is saturated with exhausted buckets a | 571 | /// concession is that while the map is saturated with exhausted buckets a |
| 572 | -/// never-before-seen client is admitted unmetered, which is preferred to | 572 | +/// never-before-seen client gets no bucket of its own and is metered against |
| 573 | -/// refusing it (that would let an attacker `429` the world). Keeps memory | 573 | +/// the one shared [`RATE_LIMIT_OVERFLOW_MAX`] budget instead β so newcomers |
| 574 | -/// bounded without a reaper task. | 574 | +/// during a flood can be refused, while every client already in the map keeps |
| 575 | +/// its own counter untouched. Keeps memory bounded without a reaper task. | ||
| 575 | pub const PURGE_AT: usize = 10_000; | 576 | pub const PURGE_AT: usize = 10_000; |
| 576 | 577 | ||
| 578 | +/// Requests per window every client that finds the bucket map saturated shares | ||
| 579 | +/// between them β one aggregate counter, no key, no map entry. | ||
| 580 | +/// | ||
| 581 | +/// It is the bound on the fail-open path: without it a new key arriving at a | ||
| 582 | +/// full map is admitted unmetered, so an attacker who first fills the map with | ||
| 583 | +/// exhausted buckets buys unlimited throughput from fresh keys. With it that | ||
| 584 | +/// bypass is capped at this many requests a minute, fleet-wide, and a genuine | ||
| 585 | +/// newcomer gets in on whatever of it is left β an attacker who burns the lot | ||
| 586 | +/// does `429` the newcomers, which refusing them outright would have done for | ||
| 587 | +/// free. Clients already in the map are unaffected throughout. Sized for the | ||
| 588 | +/// genuine side: this is a *request* budget, not a client one (a keyless client | ||
| 589 | +/// spends it on every request, not just its first), so roughly 10 requests a | ||
| 590 | +/// second for all newcomers together β far under any single client's API tier, | ||
| 591 | +/// and only ever in force while 10k buckets sit exhausted at once, which is an | ||
| 592 | +/// attack and not a school day. | ||
| 593 | +pub const RATE_LIMIT_OVERFLOW_MAX: u32 = 600; | ||
| 594 | + | ||
| 577 | /// The shared counter the limiter folds its local admits into, so a window's | 595 | /// The shared counter the limiter folds its local admits into, so a window's |
| 578 | /// budget survives a restart (see [`crate::rate_limit`]). | 596 | /// budget survives a restart (see [`crate::rate_limit`]). |
| 579 | pub const RATE_LIMIT_TABLE: &str = "rate_limit"; | 597 | pub const RATE_LIMIT_TABLE: &str = "rate_limit"; |
| @@ -733,6 +751,7 @@ pub const ENROLLMENT_TABLE: &str = "enrollment"; | |||
| 733 | pub const CLASS_GROUP_TABLE: &str = "class_group"; | 751 | pub const CLASS_GROUP_TABLE: &str = "class_group"; |
| 734 | pub const CLASS_MEMBER_TABLE: &str = "class_member"; | 752 | pub const CLASS_MEMBER_TABLE: &str = "class_member"; |
| 735 | pub const CLASS_COURSE_TABLE: &str = "class_course"; | 753 | pub const CLASS_COURSE_TABLE: &str = "class_course"; |
| 754 | +pub const CLASS_BLUEPRINT_TABLE: &str = "class_blueprint"; | ||
| 736 | pub const PARENT_LINK_TABLE: &str = "parent_link"; | 755 | pub const PARENT_LINK_TABLE: &str = "parent_link"; |
| 737 | pub const COURSE_SESSION_TABLE: &str = "course_session"; | 756 | pub const COURSE_SESSION_TABLE: &str = "course_session"; |
| 738 | pub const SESSION_ATTENDANCE_TABLE: &str = "session_attendance"; | 757 | pub const SESSION_ATTENDANCE_TABLE: &str = "session_attendance"; |
| @@ -870,6 +889,23 @@ pub const SUBMISSION_OPEN_GUARD: &str = "graded_by_result = NONE"; | |||
| 870 | /// open" and the write it licenses are one conditional single-record write β | 889 | /// open" and the write it licenses are one conditional single-record write β |
| 871 | /// a lock landing mid-draw beats the stroke instead of racing it. | 890 | /// a lock landing mid-draw beats the stroke instead of racing it. |
| 872 | pub const BOARD_OPEN_GUARD: &str = "locked = false AND closed_at = NONE"; | 891 | pub const BOARD_OPEN_GUARD: &str = "locked = false AND closed_at = NONE"; |
| 892 | +/// A signup list has **frozen**: the event takes registrations at all *and* it | ||
| 893 | +/// started, or β for an ends_at-only event (a pure signup deadline) β that end | ||
| 894 | +/// passed. A timeless event never freezes. Matched against `$now` in millis, on | ||
| 895 | +/// an `event` row. | ||
| 896 | +/// | ||
| 897 | +/// This is `Event::registration_capacity`'s `Conflict` arm re-spelled in | ||
| 898 | +/// SurrealQL, because the role cascade (`User::set_role`) frees a demoted | ||
| 899 | +/// parent's seats *inside* its transaction and cannot call Rust from there. The | ||
| 900 | +/// audience conjunct is what keeps it that arm and only that arm: an event that | ||
| 901 | +/// takes no registrations is refused earlier, by the `Validation` arm, so a | ||
| 902 | +/// stray row on one is deleted rather than frozen β which is what the pre-fold | ||
| 903 | +/// sweep did, and dropping the conjunct would silently change it. Two spellings | ||
| 904 | +/// of one rule is a drift risk, so it is spelled once here and | ||
| 905 | +/// `event::tests::the_sql_freeze_guard_matches_the_rust_one` fails the suite the | ||
| 906 | +/// day the two disagree. | ||
| 907 | +pub const REGISTRATION_FROZEN_GUARD: &str = "audience.kind = 'registration' \ | ||
| 908 | + AND (starts_at ?? ends_at) != NONE AND (starts_at ?? ends_at) <= $now"; | ||
| 873 | 909 | ||
| 874 | /// How hard a counter write tries before giving up, and the first backoff step | 910 | /// How hard a counter write tries before giving up, and the first backoff step |
| 875 | /// it sleeps between attempts (doubling, plus jitter). Contention on one record | 911 | /// it sleeps between attempts (doubling, plus jitter). Contention on one record |
src/database.rsmodified+112 -0
| @@ -469,6 +469,118 @@ mod tests { | |||
| 469 | assert!(free.delete(&db).await.unwrap()); | 469 | assert!(free.delete(&db).await.unwrap()); |
| 470 | } | 470 | } |
| 471 | 471 | ||
| 472 | + /// Stale-data path for the 2026-08-02 board-roster repair. `set_role` | ||
| 473 | + /// sweeps a demoted user off every board going forward, but an existing | ||
| 474 | + /// volume still names parents on rosters β and ids of users deleted before | ||
| 475 | + /// any sweep existed. Both freeze the creator's roster `PATCH` at a 400 | ||
| 476 | + /// (see `web::boards::resolve_participants`), so boot has to clean them. | ||
| 477 | + #[tokio::test] | ||
| 478 | + async fn a_board_roster_written_before_the_sweep_is_repaired_at_boot() { | ||
| 479 | + let db = super::init_mem().await.unwrap(); | ||
| 480 | + db.query( | ||
| 481 | + "CREATE user:s SET username = 's', password_hash = 'x', role = 'student'; | ||
| 482 | + CREATE user:p SET username = 'p', password_hash = 'x', role = 'parent'; | ||
| 483 | + CREATE board:keep SET creator = user:s, title = 'B', | ||
| 484 | + participants = [user:s, user:p, user:ghost], created_at = 1; | ||
| 485 | + CREATE board:gone SET creator = user:s, title = 'C', | ||
| 486 | + participants = [user:p], created_at = 1; | ||
| 487 | + CREATE board:clean SET creator = user:s, title = 'D', | ||
| 488 | + participants = [user:s], created_at = 1; | ||
| 489 | + DELETE migration_mark:board_roster;", | ||
| 490 | + ) | ||
| 491 | + .await | ||
| 492 | + .unwrap() | ||
| 493 | + .check() | ||
| 494 | + .unwrap(); | ||
| 495 | + // `init_mem` boots a *migrated* database, so it has already marked the | ||
| 496 | + // repair done on an empty store β which is right, and is exactly why the | ||
| 497 | + // mark is dropped here: a volume written before the mark existed carries | ||
| 498 | + // stale rosters and no mark at all, and that is the state under test. | ||
| 499 | + // A write probe on the table under repair: the event fires *inside* the | ||
| 500 | + // UPDATE, so it counts real writes rather than trusting a re-read. | ||
| 501 | + db.query( | ||
| 502 | + "DEFINE TABLE board_write_probe SCHEMALESS; | ||
| 503 | + DEFINE EVENT board_write ON board WHEN $event = 'UPDATE' THEN { | ||
| 504 | + UPSERT type::record('board_write_probe', 'n') SET n = (n ?? 0) + 1; | ||
| 505 | + };", | ||
| 506 | + ) | ||
| 507 | + .await | ||
| 508 | + .unwrap() | ||
| 509 | + .check() | ||
| 510 | + .unwrap(); | ||
| 511 | + | ||
| 512 | + super::migrate(&db).await.unwrap(); | ||
| 513 | + | ||
| 514 | + async fn rosters(db: &super::Database) -> Vec<Vec<surrealdb::types::RecordId>> { | ||
| 515 | + let mut rows = db | ||
| 516 | + .query("SELECT VALUE participants FROM board ORDER BY id") | ||
| 517 | + .await | ||
| 518 | + .unwrap(); | ||
| 519 | + rows.take(0).unwrap() | ||
| 520 | + } | ||
| 521 | + let after_first = rosters(&db).await; | ||
| 522 | + let s = surrealdb::types::RecordId::new("user", "s"); | ||
| 523 | + // `clean`, `gone`, `keep` by id. The parent and the vanished user are | ||
| 524 | + // both gone; a board whose whole roster was stale ends empty, which is | ||
| 525 | + // the same shape a board opened without invites carries. | ||
| 526 | + assert_eq!( | ||
| 527 | + after_first, | ||
| 528 | + vec![vec![s.clone()], vec![], vec![s.clone()]], | ||
| 529 | + "{after_first:?}" | ||
| 530 | + ); | ||
| 531 | + | ||
| 532 | + async fn writes(db: &super::Database) -> Vec<i64> { | ||
| 533 | + let mut rows = db | ||
| 534 | + .query("SELECT VALUE n FROM board_write_probe:n") | ||
| 535 | + .await | ||
| 536 | + .unwrap(); | ||
| 537 | + rows.take(0).unwrap() | ||
| 538 | + } | ||
| 539 | + assert_eq!( | ||
| 540 | + writes(&db).await, | ||
| 541 | + vec![2], | ||
| 542 | + "only the two stale rows repaired" | ||
| 543 | + ); | ||
| 544 | + | ||
| 545 | + // The second boot: every boot runs the backfill, and a converged row | ||
| 546 | + // must not be written again. | ||
| 547 | + super::migrate(&db).await.unwrap(); | ||
| 548 | + assert_eq!(rosters(&db).await, after_first); | ||
| 549 | + assert_eq!(writes(&db).await, vec![2], "the second pass wrote nothing"); | ||
| 550 | + | ||
| 551 | + // β¦and it did not *look*, either, which is the whole point of the mark: | ||
| 552 | + // the repair's cost is a `user` table scan per board, and writing | ||
| 553 | + // nothing is not the same as scanning nothing. A roster made stale after | ||
| 554 | + // the mark landed is the probe β it survives the next boot untouched, | ||
| 555 | + // which no converging `WHERE` could produce. | ||
| 556 | + let mut mark = db | ||
| 557 | + .query("SELECT VALUE done_at FROM migration_mark:board_roster") | ||
| 558 | + .await | ||
| 559 | + .unwrap(); | ||
| 560 | + assert_eq!( | ||
| 561 | + mark.take::<Vec<i64>>(0).unwrap().len(), | ||
| 562 | + 1, | ||
| 563 | + "the repair marks itself finished" | ||
| 564 | + ); | ||
| 565 | + db.query("CREATE board:late SET creator = user:s, title = 'E', participants = [user:p], created_at = 1") | ||
| 566 | + .await | ||
| 567 | + .unwrap() | ||
| 568 | + .check() | ||
| 569 | + .unwrap(); | ||
| 570 | + super::migrate(&db).await.unwrap(); | ||
| 571 | + assert_eq!( | ||
| 572 | + rosters(&db).await, | ||
| 573 | + vec![ | ||
| 574 | + vec![s.clone()], | ||
| 575 | + vec![], | ||
| 576 | + vec![s.clone()], | ||
| 577 | + vec![surrealdb::types::RecordId::new("user", "p")] | ||
| 578 | + ], | ||
| 579 | + "a marked database skips the scan entirely" | ||
| 580 | + ); | ||
| 581 | + assert_eq!(writes(&db).await, vec![2]); | ||
| 582 | + } | ||
| 583 | + | ||
| 472 | #[tokio::test] | 584 | #[tokio::test] |
| 473 | async fn the_retired_claim_columns_are_dropped_off_a_live_row() { | 585 | async fn the_retired_claim_columns_are_dropped_off_a_live_row() { |
| 474 | // Stale-data path for the 2026-07-30 removal of the chat claim queue. | 586 | // Stale-data path for the 2026-07-30 removal of the chat claim queue. |
src/domain/board.rsmodified+16 -26
| @@ -202,14 +202,25 @@ impl Board { | |||
| 202 | /// Every board `user` may open: the ones they created and the ones they | 202 | /// Every board `user` may open: the ones they created and the ones they |
| 203 | /// were invited to. Newest first β the ids are monotonic, so `id` is the | 203 | /// were invited to. Newest first β the ids are monotonic, so `id` is the |
| 204 | /// creation order. | 204 | /// creation order. |
| 205 | + /// | ||
| 206 | + /// `open` narrows by `closed_at`, and it means exactly that flag: a board | ||
| 207 | + /// that is locked, or full at its lifetime cap but never drawn on again, is | ||
| 208 | + /// never stamped and so reads as **open** β because it is. Only a creator's | ||
| 209 | + /// `/close` and the lifetime cap's own refusal ever stamp one. | ||
| 205 | pub async fn list_for_user( | 210 | pub async fn list_for_user( |
| 206 | user: &UserId, | 211 | user: &UserId, |
| 212 | + open: Option<bool>, | ||
| 207 | limit: Option<i64>, | 213 | limit: Option<i64>, |
| 208 | offset: i64, | 214 | offset: i64, |
| 209 | db: &Database, | 215 | db: &Database, |
| 210 | ) -> Result<(Vec<Board>, i64), AppError> { | 216 | ) -> Result<(Vec<Board>, i64), AppError> { |
| 217 | + let open_clause = match open { | ||
| 218 | + Some(true) => " AND closed_at = NONE", | ||
| 219 | + Some(false) => " AND closed_at != NONE", | ||
| 220 | + None => "", | ||
| 221 | + }; | ||
| 211 | PagedList::new( | 222 | PagedList::new( |
| 212 | - "board WHERE creator = $usr OR participants CONTAINS $usr", | 223 | + format!("board WHERE (creator = $usr OR participants CONTAINS $usr){open_clause}"), |
| 213 | "ORDER BY id DESC", | 224 | "ORDER BY id DESC", |
| 214 | ) | 225 | ) |
| 215 | .bind("usr", user.record()) | 226 | .bind("usr", user.record()) |
| @@ -270,31 +281,10 @@ impl Board { | |||
| 270 | one(result.take::<Vec<Board>>(0)?) | 281 | one(result.take::<Vec<Board>>(0)?) |
| 271 | } | 282 | } |
| 272 | 283 | ||
| 273 | - /// Strip `user` off every board roster they are listed on β the sweep for a | 284 | + // The demotion sweep β stripping a user off every roster they are listed |
| 274 | - /// user demoted below `student`, who may no longer touch a whiteboard at | 285 | + // on, deleting nothing, and handing the affected rooms back so the caller |
| 275 | - /// all ([`crate::web::boards`] keeps such a role off every roster at | 286 | + // can prompt them β lives in [`crate::domain::user::User::set_role`], where |
| 276 | - /// invite time, so a stale row is exactly what a demotion used to leave). | 287 | + // it commits with the role write that invalidates the membership. |
| 277 | - /// Nothing is deleted: no board, no stroke, not even a board whose roster | ||
| 278 | - /// this empties β a role change must never destroy other people's work. | ||
| 279 | - /// | ||
| 280 | - /// Boards the user *created* come back too, and deliberately unchanged: the | ||
| 281 | - /// creator is not a roster entry (`is_participant` reads the column) and | ||
| 282 | - /// removing them is not expressible. They are returned so the caller can | ||
| 283 | - /// prompt those rooms as well. | ||
| 284 | - pub async fn drop_participant_everywhere( | ||
| 285 | - user: &UserId, | ||
| 286 | - db: &Database, | ||
| 287 | - ) -> Result<Vec<Board>, AppError> { | ||
| 288 | - let mut result = db | ||
| 289 | - .query( | ||
| 290 | - "UPDATE board SET participants -= $usr \ | ||
| 291 | - WHERE $usr IN participants OR creator = $usr RETURN AFTER", | ||
| 292 | - ) | ||
| 293 | - .bind(("usr", user.record())) | ||
| 294 | - .await? | ||
| 295 | - .check()?; | ||
| 296 | - Ok(result.take::<Vec<Board>>(0)?) | ||
| 297 | - } | ||
| 298 | 288 | ||
| 299 | /// Retire the board: permanently read-only, history still readable. | 289 | /// Retire the board: permanently read-only, history still readable. |
| 300 | /// Idempotent by the `WHERE` β a second call matches nothing and the first | 290 | /// Idempotent by the `WHERE` β a second call matches nothing and the first |
src/domain/board_stroke.rsmodified+73 -7
| @@ -39,8 +39,8 @@ const KIND_STROKE: &str = BOARD_STROKE_KINDS[0]; | |||
| 39 | const KIND_CLEAR: &str = BOARD_STROKE_KINDS[1]; | 39 | const KIND_CLEAR: &str = BOARD_STROKE_KINDS[1]; |
| 40 | 40 | ||
| 41 | /// The `THROW` the clear transaction refuses with: a blank canvas, not the | 41 | /// The `THROW` the clear transaction refuses with: a blank canvas, not the |
| 42 | -/// creator, or the board is already closed. A decision, so it outranks a lost | 42 | +/// creator, or the board is locked or already closed. A decision, so it |
| 43 | -/// round. | 43 | +/// outranks a lost round. |
| 44 | const CLEAR_REFUSED: &str = "board_clear_refused"; | 44 | const CLEAR_REFUSED: &str = "board_clear_refused"; |
| 45 | 45 | ||
| 46 | /// The public words of every refusal this module raises. `pub` because | 46 | /// The public words of every refusal this module raises. `pub` because |
| @@ -254,6 +254,13 @@ impl BoardStroke { | |||
| 254 | /// honest answer to the call it refuses. The epochs index keeps its meaning | 254 | /// honest answer to the call it refuses. The epochs index keeps its meaning |
| 255 | /// too: no zero-stroke epoch can enter it. | 255 | /// too: no zero-stroke epoch can enter it. |
| 256 | /// | 256 | /// |
| 257 | + /// **A locked board cannot be cleared.** The lock is the creator's own | ||
| 258 | + /// pause on the canvas, and it holds against every write to it including | ||
| 259 | + /// theirs β [`BOARD_OPEN_GUARD`] is the same condition the stroke path | ||
| 260 | + /// claims under, so "locked" means one thing everywhere. The cost is | ||
| 261 | + /// accepted: a locked board sitting at `MAX_EPOCH_STROKES` is recovered by | ||
| 262 | + /// unlock, clear, relock. | ||
| 263 | + /// | ||
| 257 | /// The marker's own increment is not capped: the last stroke of a board's | 264 | /// The marker's own increment is not capped: the last stroke of a board's |
| 258 | /// budget may be closed by a marker, so a board holds at most | 265 | /// budget may be closed by a marker, so a board holds at most |
| 259 | /// `MAX_BOARD_STROKES + 1` rows. Capping it would refuse the clear that | 266 | /// `MAX_BOARD_STROKES + 1` rows. Capping it would refuse the clear that |
| @@ -271,7 +278,7 @@ impl BoardStroke { | |||
| 271 | "BEGIN TRANSACTION; | 278 | "BEGIN TRANSACTION; |
| 272 | LET $before = (UPDATE $b SET epoch += 1, {BOARD_EPOCH_STROKE_COUNT_FIELD} = 0, \ | 279 | LET $before = (UPDATE $b SET epoch += 1, {BOARD_EPOCH_STROKE_COUNT_FIELD} = 0, \ |
| 273 | {BOARD_TOTAL_STROKE_COUNT_FIELD} = ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) + 1 \ | 280 | {BOARD_TOTAL_STROKE_COUNT_FIELD} = ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) + 1 \ |
| 274 | - WHERE creator = $by AND closed_at = NONE \ | 281 | + WHERE creator = $by AND {BOARD_OPEN_GUARD} \ |
| 275 | AND ({BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0) > 0 RETURN BEFORE); | 282 | AND ({BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0) > 0 RETURN BEFORE); |
| 276 | IF array::len($before) = 0 {{ THROW '{CLEAR_REFUSED}' }}; | 283 | IF array::len($before) = 0 {{ THROW '{CLEAR_REFUSED}' }}; |
| 277 | CREATE $mid CONTENT {{ board: $b, author: $by, kind: $kind, \ | 284 | CREATE $mid CONTENT {{ board: $b, author: $by, kind: $kind, \ |
| @@ -312,7 +319,7 @@ impl BoardStroke { | |||
| 312 | .ok_or_else(|| AppError::Internal("board clear wrote no marker".into())) | 319 | .ok_or_else(|| AppError::Internal("board clear wrote no marker".into())) |
| 313 | } | 320 | } |
| 314 | 321 | ||
| 315 | - /// Which of the clear guard's three conditions said no. One `WHERE` cannot | 322 | + /// Which of the clear guard's four conditions said no. One `WHERE` cannot |
| 316 | /// report that itself, so the board is re-read β on the refusal path only, | 323 | /// report that itself, so the board is re-read β on the refusal path only, |
| 317 | /// like [`Self::why_refused`]. The distinction is not cosmetic: a closed | 324 | /// like [`Self::why_refused`]. The distinction is not cosmetic: a closed |
| 318 | /// board is terminal for the room, a blank canvas is an ordinary "nothing | 325 | /// board is terminal for the room, a blank canvas is an ordinary "nothing |
| @@ -329,6 +336,12 @@ impl BoardStroke { | |||
| 329 | if !board.is_creator(by) { | 336 | if !board.is_creator(by) { |
| 330 | return Ok(AppError::Forbidden(NOT_THE_CREATOR)); | 337 | return Ok(AppError::Forbidden(NOT_THE_CREATOR)); |
| 331 | } | 338 | } |
| 339 | + // A lock pauses the *creator* too, and it is a state the caller can | ||
| 340 | + // undo β a `Conflict`, not the `Forbidden` a wrong caller gets. Unlock, | ||
| 341 | + // clear, relock is the recovery for a locked board that is also full. | ||
| 342 | + if board.is_locked() { | ||
| 343 | + return Ok(AppError::Conflict(BOARD_LOCKED)); | ||
| 344 | + } | ||
| 332 | Ok(AppError::Conflict(CANVAS_BLANK)) | 345 | Ok(AppError::Conflict(CANVAS_BLANK)) |
| 333 | } | 346 | } |
| 334 | 347 | ||
| @@ -370,9 +383,17 @@ impl BoardStroke { | |||
| 370 | /// The whole log, oldest first β every epoch, or one named epoch. Both | 383 | /// The whole log, oldest first β every epoch, or one named epoch. Both |
| 371 | /// kinds of row come back: the `clear` markers are what tell a reader where | 384 | /// kinds of row come back: the `clear` markers are what tell a reader where |
| 372 | /// one epoch ended and the next began. | 385 | /// one epoch ended and the next began. |
| 386 | + /// | ||
| 387 | + /// `marks_only` drops the markers, which is what the *live canvas* wants: | ||
| 388 | + /// the current epoch holds no marker by construction, except in the one | ||
| 389 | + /// race where a clear commits between the board read and this read and | ||
| 390 | + /// files its marker under the epoch just named. The room's replay filters | ||
| 391 | + /// to `kind = 'stroke'` ([`Self::replay_current`]), so without this the two | ||
| 392 | + /// views disagree in exactly that window. | ||
| 373 | pub async fn history( | 393 | pub async fn history( |
| 374 | board: &BoardId, | 394 | board: &BoardId, |
| 375 | epoch: Option<i64>, | 395 | epoch: Option<i64>, |
| 396 | + marks_only: bool, | ||
| 376 | limit: Option<i64>, | 397 | limit: Option<i64>, |
| 377 | offset: i64, | 398 | offset: i64, |
| 378 | db: &Database, | 399 | db: &Database, |
| @@ -381,12 +402,18 @@ impl BoardStroke { | |||
| 381 | Some(_) => " AND epoch = $e", | 402 | Some(_) => " AND epoch = $e", |
| 382 | None => "", | 403 | None => "", |
| 383 | }; | 404 | }; |
| 405 | + let kinds = if marks_only { | ||
| 406 | + " AND kind != $clear" | ||
| 407 | + } else { | ||
| 408 | + "" | ||
| 409 | + }; | ||
| 384 | PagedList::new( | 410 | PagedList::new( |
| 385 | - format!("{BOARD_STROKE_TABLE} WHERE board = $b{scope}"), | 411 | + format!("{BOARD_STROKE_TABLE} WHERE board = $b{scope}{kinds}"), |
| 386 | "ORDER BY id", | 412 | "ORDER BY id", |
| 387 | ) | 413 | ) |
| 388 | .bind("b", board.record()) | 414 | .bind("b", board.record()) |
| 389 | .bind("e", epoch.unwrap_or_default()) | 415 | .bind("e", epoch.unwrap_or_default()) |
| 416 | + .bind("clear", KIND_CLEAR.to_string()) | ||
| 390 | .run(limit, offset, db) | 417 | .run(limit, offset, db) |
| 391 | .await | 418 | .await |
| 392 | } | 419 | } |
| @@ -678,6 +705,38 @@ mod tests { | |||
| 678 | assert_eq!(stored.len(), 4); | 705 | assert_eq!(stored.len(), 4); |
| 679 | } | 706 | } |
| 680 | 707 | ||
| 708 | + /// The lock pauses the canvas against *every* write to it, its creator's | ||
| 709 | + /// clear included β a `Conflict`, since unlocking undoes it, not the | ||
| 710 | + /// `Forbidden` a non-creator gets. Asserted off stored rows: the refusal | ||
| 711 | + /// must mint no marker and must not bump the epoch. | ||
| 712 | + #[tokio::test] | ||
| 713 | + async fn a_locked_board_refuses_its_creator_s_clear() { | ||
| 714 | + let db = a_db().await; | ||
| 715 | + let board = a_board(&db).await; | ||
| 716 | + draw(&board, &db).await.unwrap(); | ||
| 717 | + let board = board.set_locked(true, &user("c"), &db).await.unwrap(); | ||
| 718 | + | ||
| 719 | + let refused = BoardStroke::clear(board.get_id(), &user("c"), &db).await; | ||
| 720 | + assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg == BOARD_LOCKED)); | ||
| 721 | + assert_eq!(rows(board.get_id(), &db).await.len(), 1); | ||
| 722 | + assert_eq!(reread(&board, &db).await.get_epoch(), 0); | ||
| 723 | + assert!( | ||
| 724 | + BoardStroke::epochs(board.get_id(), &db) | ||
| 725 | + .await | ||
| 726 | + .unwrap() | ||
| 727 | + .is_empty() | ||
| 728 | + ); | ||
| 729 | + | ||
| 730 | + // Unlock, and the same clear lands: unlock β clear β relock is the | ||
| 731 | + // recovery for a locked board sitting at the epoch cap. | ||
| 732 | + let board = board.set_locked(false, &user("c"), &db).await.unwrap(); | ||
| 733 | + let marker = BoardStroke::clear(board.get_id(), &user("c"), &db) | ||
| 734 | + .await | ||
| 735 | + .unwrap(); | ||
| 736 | + assert_eq!(marker.get_count(), Some(1)); | ||
| 737 | + assert_eq!(reread(&board, &db).await.get_epoch(), 1); | ||
| 738 | + } | ||
| 739 | + | ||
| 681 | /// The `next_ulid` hazard: rows minted inside one millisecond must replay | 740 | /// The `next_ulid` hazard: rows minted inside one millisecond must replay |
| 682 | /// in mint order, not at random (src/domain/monotonic_id.rs:41-46). | 741 | /// in mint order, not at random (src/domain/monotonic_id.rs:41-46). |
| 683 | #[tokio::test] | 742 | #[tokio::test] |
| @@ -760,14 +819,21 @@ mod tests { | |||
| 760 | let board = reread(&board, &db).await; | 819 | let board = reread(&board, &db).await; |
| 761 | draw(&board, &db).await.unwrap(); | 820 | draw(&board, &db).await.unwrap(); |
| 762 | 821 | ||
| 763 | - let (all, total) = BoardStroke::history(board.get_id(), None, None, 0, &db) | 822 | + let (all, total) = BoardStroke::history(board.get_id(), None, false, None, 0, &db) |
| 764 | .await | 823 | .await |
| 765 | .unwrap(); | 824 | .unwrap(); |
| 766 | assert_eq!((all.len(), total), (3, 3)); | 825 | assert_eq!((all.len(), total), (3, 3)); |
| 767 | - let (first, total) = BoardStroke::history(board.get_id(), Some(0), None, 0, &db) | 826 | + let (first, total) = BoardStroke::history(board.get_id(), Some(0), false, None, 0, &db) |
| 768 | .await | 827 | .await |
| 769 | .unwrap(); | 828 | .unwrap(); |
| 770 | // Epoch 0: its stroke and the marker that closed it. | 829 | // Epoch 0: its stroke and the marker that closed it. |
| 771 | assert_eq!((first.len(), total), (2, 2)); | 830 | assert_eq!((first.len(), total), (2, 2)); |
| 831 | + // `marks_only` drops the marker from that same epoch β and its `total` | ||
| 832 | + // with it, so the envelope's count stays the count of what is served. | ||
| 833 | + let (marks, total) = BoardStroke::history(board.get_id(), Some(0), true, None, 0, &db) | ||
| 834 | + .await | ||
| 835 | + .unwrap(); | ||
| 836 | + assert_eq!((marks.len(), total), (1, 1)); | ||
| 837 | + assert!(marks.iter().all(|row| !row.is_clear())); | ||
| 772 | } | 838 | } |
| 773 | } | 839 | } |
src/domain/class_blueprint.rsadded+573 -0
| @@ -0,0 +1,573 @@ | |||
| 1 | +//! A grade's course template: the courses every class section (Εube) at one | ||
| 2 | +//! grade carries. | ||
| 3 | +//! | ||
| 4 | +//! A school runs many Εube at grade "9" and stocks each of them by hand, one | ||
| 5 | +//! attach at a time. A blueprint is that list said once. It is a layer *above* | ||
| 6 | +//! [`crate::domain::class_pump`], never a replacement for it: applying a | ||
| 7 | +//! blueprint calls the same [`ClassCourse::attach`] a manager's own call does, | ||
| 8 | +//! so the rows it lands are ordinary `class_course` links and ordinary | ||
| 9 | +//! `enrollment` rows, and an elective (seΓ§meli) placed by hand next to them is | ||
| 10 | +//! still an individual enrollment nothing here can see. | ||
| 11 | +//! | ||
| 12 | +//! Two rules shape everything below. | ||
| 13 | +//! | ||
| 14 | +//! **An edit retro-pumps.** Changing the list reaches every class already at | ||
| 15 | +//! that grade, not just the ones made afterwards. That is an unbounded write | ||
| 16 | +//! loop β one transaction per (class, course), and no ceiling bounds the number | ||
| 17 | +//! of classes β chosen deliberately over a template that only new classes see. | ||
| 18 | +//! | ||
| 19 | +//! **A pump is best-effort.** Each (class, course) pair is one all-or-nothing | ||
| 20 | +//! transaction of the existing pump, and a pair that would breach a limit is | ||
| 21 | +//! *skipped and reported* rather than aborting the other classes' share. So a | ||
| 22 | +//! blueprint edit can leave a partial state β which is the point: one full | ||
| 23 | +//! course must not stop the other eleven sections from being stocked. Every | ||
| 24 | +//! skip is returned, naming the class, the course and the reason. | ||
| 25 | +//! | ||
| 26 | +//! Removal is the mirror, and it is where the provenance tag earns its keep: a | ||
| 27 | +//! `class_course` row this blueprint wrote carries `source`, a row a human | ||
| 28 | +//! attached carries no such key at all, and dropping a course from the | ||
| 29 | +//! blueprint sweeps only the former. The sweep is the pump's own | ||
| 30 | +//! [`crate::domain::class_pump::detach`], so a class losing a course still | ||
| 31 | +//! repairs before it deletes β and it runs one transaction per pair too, for | ||
| 32 | +//! the same reason the pump does. | ||
| 33 | + | ||
| 34 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 35 | + | ||
| 36 | +use crate::constant::{CLASS_BLUEPRINT_TABLE, CLASS_COURSE_TABLE, MAX_CLASS_COURSES}; | ||
| 37 | +use crate::database::Database; | ||
| 38 | +use crate::domain::class_course::ClassCourse; | ||
| 39 | +use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId}; | ||
| 40 | +use crate::domain::class_pump::{Attached, Axis, detach}; | ||
| 41 | +use crate::domain::course::CourseId; | ||
| 42 | +use crate::domain::page::PagedList; | ||
| 43 | +use crate::domain::user::UserId; | ||
| 44 | +use crate::error::{AppError, ValidationError}; | ||
| 45 | + | ||
| 46 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 47 | +pub struct ClassBlueprintId(RecordId); | ||
| 48 | + | ||
| 49 | +impl ClassBlueprintId { | ||
| 50 | + /// The record one grade label always maps to. The label is the key, so | ||
| 51 | + /// "one blueprint per grade" holds by construction rather than by a | ||
| 52 | + /// find-then-insert that two managers can race β the shape | ||
| 53 | + /// [`crate::domain::menu::MenuId::for_slot`] uses. | ||
| 54 | + pub fn for_grade(grade: &ClassGrade) -> Self { | ||
| 55 | + Self(RecordId::new(CLASS_BLUEPRINT_TABLE, grade.as_str())) | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + pub fn from_key(key: &str) -> Self { | ||
| 59 | + Self(RecordId::new(CLASS_BLUEPRINT_TABLE, key)) | ||
| 60 | + } | ||
| 61 | + | ||
| 62 | + pub fn record(&self) -> RecordId { | ||
| 63 | + self.0.clone() | ||
| 64 | + } | ||
| 65 | + | ||
| 66 | + pub fn key(&self) -> &str { | ||
| 67 | + match &self.0.key { | ||
| 68 | + RecordIdKey::String(key) => key, | ||
| 69 | + _ => "", | ||
| 70 | + } | ||
| 71 | + } | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +/// One grade's template. `grade` is stored beside the key it *is*, so a read | ||
| 75 | +/// never has to parse a record id back into a domain value. | ||
| 76 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 77 | +pub struct ClassBlueprint { | ||
| 78 | + id: ClassBlueprintId, | ||
| 79 | + grade: ClassGrade, | ||
| 80 | + courses: Vec<CourseId>, | ||
| 81 | + creator: UserId, | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +/// One (class, course) pair a pump refused, and why. Precise enough to act on: | ||
| 85 | +/// the class is named as well as identified, because a manager reading "12 | ||
| 86 | +/// skipped" needs to know *which* section is short a course. | ||
| 87 | +#[derive(Debug, Clone)] | ||
| 88 | +pub struct Skip { | ||
| 89 | + pub class: ClassGroupId, | ||
| 90 | + pub class_name: String, | ||
| 91 | + pub course: CourseId, | ||
| 92 | + pub reason: &'static str, | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +/// Why this attach did not land, or `None` when it did. A duplicate is not a | ||
| 96 | +/// skip: the course is already on the class, which is exactly what the | ||
| 97 | +/// blueprint asks for, and re-running a pump must therefore report nothing. | ||
| 98 | +/// | ||
| 99 | +/// Each reason names the record that actually failed. The pump's two "gone" | ||
| 100 | +/// answers are a *class* delete ([`Attached::Gone`], the class counter's claim | ||
| 101 | +/// matching nothing on a row a re-read no longer finds) and a *course* delete | ||
| 102 | +/// ([`Attached::PivotGone`], the course's own claim matching nothing) β and | ||
| 103 | +/// telling a manager the class vanished when the course did sends them to look | ||
| 104 | +/// at a section that is standing right there. | ||
| 105 | +fn skip_reason(landed: &Attached<ClassCourse>) -> Option<&'static str> { | ||
| 106 | + match landed { | ||
| 107 | + Attached::Made(_) | Attached::Duplicate => None, | ||
| 108 | + Attached::Gone => Some("the class was deleted while the blueprint was being applied"), | ||
| 109 | + Attached::PivotGone => { | ||
| 110 | + Some("this course no longer exists β it has been dropped from the blueprint") | ||
| 111 | + } | ||
| 112 | + Attached::ClassFull => Some("the class is already at its course ceiling"), | ||
| 113 | + Attached::ClassOverloaded => { | ||
| 114 | + Some("the class holds more students than a course attach is allowed to enroll at once") | ||
| 115 | + } | ||
| 116 | + Attached::Full(_) => Some("the course has no free seat for the whole class"), | ||
| 117 | + Attached::CourseGone(_) => { | ||
| 118 | + Some("another course attached to this class no longer exists β detach it first") | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +impl ClassBlueprint { | ||
| 124 | + pub fn get_id(&self) -> &ClassBlueprintId { | ||
| 125 | + &self.id | ||
| 126 | + } | ||
| 127 | + | ||
| 128 | + pub fn get_grade(&self) -> &ClassGrade { | ||
| 129 | + &self.grade | ||
| 130 | + } | ||
| 131 | + | ||
| 132 | + pub fn get_courses(&self) -> &[CourseId] { | ||
| 133 | + &self.courses | ||
| 134 | + } | ||
| 135 | + | ||
| 136 | + pub fn get_creator(&self) -> &UserId { | ||
| 137 | + &self.creator | ||
| 138 | + } | ||
| 139 | + | ||
| 140 | + /// The grade a blueprint may be keyed on. Non-empty, because the label is | ||
| 141 | + /// the record id and there is no blueprint for "no grade"; and free of the | ||
| 142 | + /// characters that would make that id unaddressable as a URL path segment, | ||
| 143 | + /// the second gate [`crate::domain::menu::MenuSlot`] carries for the same | ||
| 144 | + /// reason. Grades were never validated for this, so a *class* may already | ||
| 145 | + /// carry a label refused here β it simply cannot have a blueprint until it | ||
| 146 | + /// is renamed, which is a 400 the caller can read rather than a route | ||
| 147 | + /// nobody can reach. | ||
| 148 | + pub fn grade_key(value: &str) -> Result<ClassGrade, AppError> { | ||
| 149 | + if value.is_empty() { | ||
| 150 | + return Err(AppError::Validation(ValidationError::Empty("grade"))); | ||
| 151 | + } | ||
| 152 | + if value | ||
| 153 | + .chars() | ||
| 154 | + .any(|c| matches!(c, '/' | '\\' | '?' | '#' | '%')) | ||
| 155 | + { | ||
| 156 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 157 | + field: "grade", | ||
| 158 | + reason: "must not contain / \\ ? # or %", | ||
| 159 | + })); | ||
| 160 | + } | ||
| 161 | + Ok(ClassGrade::try_new(value)?) | ||
| 162 | + } | ||
| 163 | + | ||
| 164 | + /// The course list a blueprint may hold: deduplicated, and no longer than | ||
| 165 | + /// one class may carry β a blueprint above that ceiling would guarantee a | ||
| 166 | + /// skip on every class it ever reached. | ||
| 167 | + fn course_list(courses: Vec<CourseId>) -> Result<Vec<CourseId>, AppError> { | ||
| 168 | + let mut list: Vec<CourseId> = Vec::new(); | ||
| 169 | + for course in courses { | ||
| 170 | + if !list.contains(&course) { | ||
| 171 | + list.push(course); | ||
| 172 | + } | ||
| 173 | + } | ||
| 174 | + if list.len() as i64 > MAX_CLASS_COURSES { | ||
| 175 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 176 | + field: "course_ids", | ||
| 177 | + reason: "a blueprint cannot hold more courses than a class may carry \ | ||
| 178 | + (max_class_courses)", | ||
| 179 | + })); | ||
| 180 | + } | ||
| 181 | + Ok(list) | ||
| 182 | + } | ||
| 183 | + | ||
| 184 | + /// Write the blueprint. A second one for the same grade is a 409 the store | ||
| 185 | + /// itself decides β the grade is the record key, so the duplicate is seen | ||
| 186 | + /// rather than raced. | ||
| 187 | + pub async fn create( | ||
| 188 | + creator: &UserId, | ||
| 189 | + grade: ClassGrade, | ||
| 190 | + courses: Vec<CourseId>, | ||
| 191 | + db: &Database, | ||
| 192 | + ) -> Result<ClassBlueprint, AppError> { | ||
| 193 | + let blueprint = ClassBlueprint { | ||
| 194 | + id: ClassBlueprintId::for_grade(&grade), | ||
| 195 | + grade, | ||
| 196 | + courses: Self::course_list(courses)?, | ||
| 197 | + creator: creator.clone(), | ||
| 198 | + }; | ||
| 199 | + match db | ||
| 200 | + .create::<Option<ClassBlueprint>>(blueprint.id.record()) | ||
| 201 | + .content(blueprint) | ||
| 202 | + .await | ||
| 203 | + { | ||
| 204 | + Ok(Some(created)) => Ok(created), | ||
| 205 | + Ok(None) => Err(AppError::Internal("failed to create blueprint".into())), | ||
| 206 | + Err(error) if error.is_already_exists() => Err(AppError::Conflict( | ||
| 207 | + "a blueprint already exists for that grade", | ||
| 208 | + )), | ||
| 209 | + Err(error) => Err(error.into()), | ||
| 210 | + } | ||
| 211 | + } | ||
| 212 | + | ||
| 213 | + pub async fn read( | ||
| 214 | + id: &ClassBlueprintId, | ||
| 215 | + db: &Database, | ||
| 216 | + ) -> Result<Option<ClassBlueprint>, AppError> { | ||
| 217 | + Ok(db.select(id.record()).await?) | ||
| 218 | + } | ||
| 219 | + | ||
| 220 | + /// Every blueprint, by grade label β the id *is* the label, so this is the | ||
| 221 | + /// only ordering that means anything here. | ||
| 222 | + pub async fn list_all( | ||
| 223 | + limit: Option<i64>, | ||
| 224 | + offset: i64, | ||
| 225 | + db: &Database, | ||
| 226 | + ) -> Result<(Vec<ClassBlueprint>, i64), AppError> { | ||
| 227 | + PagedList::new(CLASS_BLUEPRINT_TABLE, "ORDER BY id ASC") | ||
| 228 | + .run(limit, offset, db) | ||
| 229 | + .await | ||
| 230 | + } | ||
| 231 | + | ||
| 232 | + /// Replace the course list, then reconcile every class at this grade with | ||
| 233 | + /// it: the courses this blueprint no longer holds are detached from the | ||
| 234 | + /// classes *it* attached them to, and the ones it holds are pumped into | ||
| 235 | + /// every class that fits. | ||
| 236 | + /// | ||
| 237 | + /// The write is a compare-and-set on the list this caller read, so two | ||
| 238 | + /// managers editing the same grade cannot have one's list silently pump the | ||
| 239 | + /// other's diff β the loser is a 409 and re-reads. | ||
| 240 | + /// | ||
| 241 | + /// Removals run first: a course leaving frees a place under the per-class | ||
| 242 | + /// course ceiling that the same edit's additions can then use. | ||
| 243 | + pub async fn set_courses( | ||
| 244 | + self, | ||
| 245 | + courses: Vec<CourseId>, | ||
| 246 | + by: &UserId, | ||
| 247 | + db: &Database, | ||
| 248 | + ) -> Result<(ClassBlueprint, Vec<Skip>), AppError> { | ||
| 249 | + let wanted = Self::course_list(courses)?; | ||
| 250 | + let dropped: Vec<CourseId> = self | ||
| 251 | + .courses | ||
| 252 | + .iter() | ||
| 253 | + .filter(|course| !wanted.contains(course)) | ||
| 254 | + .cloned() | ||
| 255 | + .collect(); | ||
| 256 | + let mut result = db | ||
| 257 | + .query("UPDATE $id SET courses = $wanted WHERE courses = $held RETURN AFTER") | ||
| 258 | + .bind(("id", self.id.record())) | ||
| 259 | + .bind(("wanted", wanted)) | ||
| 260 | + .bind(("held", self.courses.clone())) | ||
| 261 | + .await? | ||
| 262 | + .check()?; | ||
| 263 | + let Some(saved) = result.take::<Vec<ClassBlueprint>>(0)?.into_iter().next() else { | ||
| 264 | + // The conditional write matched nothing: the row is gone, or its | ||
| 265 | + // list moved since this caller read it. Only this path pays for the | ||
| 266 | + // read that tells those apart. | ||
| 267 | + return match Self::read(&self.id, db).await? { | ||
| 268 | + Some(_) => Err(AppError::Conflict( | ||
| 269 | + "this blueprint changed since you read it β re-read and retry", | ||
| 270 | + )), | ||
| 271 | + None => Err(AppError::NotFound), | ||
| 272 | + }; | ||
| 273 | + }; | ||
| 274 | + saved.drop_courses(&dropped, db).await?; | ||
| 275 | + let skipped = saved.pump(by, db).await?; | ||
| 276 | + Ok((saved, skipped)) | ||
| 277 | + } | ||
| 278 | + | ||
| 279 | + /// Delete the blueprint, taking every attachment it made with it. Courses a | ||
| 280 | + /// human attached to those classes by hand carry no `source` and are left | ||
| 281 | + /// exactly where they are β the same cut a single removal makes, applied to | ||
| 282 | + /// the whole list, because a template that is gone owns nothing. | ||
| 283 | + pub async fn delete(self, db: &Database) -> Result<(), AppError> { | ||
| 284 | + self.drop_courses(&self.courses.clone(), db).await?; | ||
| 285 | + let gone: Option<ClassBlueprint> = db.delete(self.id.record()).await?; | ||
| 286 | + gone.map(|_| ()).ok_or(AppError::NotFound) | ||
| 287 | + } | ||
| 288 | + | ||
| 289 | + /// Attach every course in this blueprint to `class`, skipping β never | ||
| 290 | + /// aborting on β the ones that do not fit. A course already on the class is | ||
| 291 | + /// a no-op, whoever attached it: this is what makes a pump repeatable, and | ||
| 292 | + /// what stops it re-tagging a hand-attached course as its own. | ||
| 293 | + pub async fn apply_to( | ||
| 294 | + &self, | ||
| 295 | + class: &ClassGroup, | ||
| 296 | + by: &UserId, | ||
| 297 | + db: &Database, | ||
| 298 | + ) -> Result<Vec<Skip>, AppError> { | ||
| 299 | + let mut skipped = Vec::new(); | ||
| 300 | + for course in &self.courses { | ||
| 301 | + let landed = | ||
| 302 | + ClassCourse::attach_sourced(class.get_id(), course, by, Some(&self.id), db).await?; | ||
| 303 | + if matches!(landed, Attached::PivotGone) { | ||
| 304 | + self.prune(course, db).await?; | ||
| 305 | + } | ||
| 306 | + if let Some(reason) = skip_reason(&landed) { | ||
| 307 | + skipped.push(Skip { | ||
| 308 | + class: class.get_id().clone(), | ||
| 309 | + class_name: class.get_name().as_str().to_string(), | ||
| 310 | + course: course.clone(), | ||
| 311 | + reason, | ||
| 312 | + }); | ||
| 313 | + } | ||
| 314 | + } | ||
| 315 | + Ok(skipped) | ||
| 316 | + } | ||
| 317 | + | ||
| 318 | + /// [`Self::apply_to`] every class at this blueprint's grade. The write loop | ||
| 319 | + /// is one transaction per (class, course) and bounded by neither β see the | ||
| 320 | + /// module note. | ||
| 321 | + pub async fn pump(&self, by: &UserId, db: &Database) -> Result<Vec<Skip>, AppError> { | ||
| 322 | + let mut skipped = Vec::new(); | ||
| 323 | + for class in ClassGroup::list_for_grade(&self.grade, db).await? { | ||
| 324 | + skipped.extend(self.apply_to(&class, by, db).await?); | ||
| 325 | + } | ||
| 326 | + Ok(skipped) | ||
| 327 | + } | ||
| 328 | + | ||
| 329 | + /// Drop a course that no longer exists out of this blueprint's list. | ||
| 330 | + /// | ||
| 331 | + /// [`crate::domain::course::Course::delete`] takes the `class_course` links | ||
| 332 | + /// a course had, but nothing it can reach names the blueprints holding its | ||
| 333 | + /// id β so a deleted course stays in the list and every future pump refuses | ||
| 334 | + /// it again, on every class, forever. A skip a manager cannot act on is | ||
| 335 | + /// noise, so the pump that *finds* the dangling id also removes it, and the | ||
| 336 | + /// removal is reported once (the skip) rather than every time. | ||
| 337 | + /// | ||
| 338 | + /// Not a compare-and-set, unlike [`Self::set_courses`]: "a course that does | ||
| 339 | + /// not exist is not in this list" holds for every version of the list, so | ||
| 340 | + /// there is nothing a concurrent edit could make this write wrong about, | ||
| 341 | + /// and re-running it changes nothing. No sweep follows it either β the | ||
| 342 | + /// attachments it would sweep are exactly the ones the course's own delete | ||
| 343 | + /// already took. | ||
| 344 | + async fn prune(&self, course: &CourseId, db: &Database) -> Result<(), AppError> { | ||
| 345 | + db.query("UPDATE $id SET courses = array::complement(courses ?? [], [$course])") | ||
| 346 | + .bind(("id", self.id.record())) | ||
| 347 | + .bind(("course", course.record())) | ||
| 348 | + .await? | ||
| 349 | + .check()?; | ||
| 350 | + Ok(()) | ||
| 351 | + } | ||
| 352 | + | ||
| 353 | + /// Detach `courses` from every class *this blueprint* attached them to, and | ||
| 354 | + /// sweep the enrollments those attachments pumped. | ||
| 355 | + /// | ||
| 356 | + /// `source` is the whole filter, so a row without the key β a hand attach β | ||
| 357 | + /// is never matched, and a class that acquired the same course by hand | ||
| 358 | + /// keeps it. The sweep underneath is the pump's own, so a student a second | ||
| 359 | + /// class still claims is re-tagged rather than unenrolled. | ||
| 360 | + /// | ||
| 361 | + /// One transaction per *link row*, which is the module note's "one | ||
| 362 | + /// transaction per (class, course)" and the mirror of the pump's | ||
| 363 | + /// best-effort rule. One statement per course would be shorter, but it puts | ||
| 364 | + /// every section at the grade into a single unbounded transaction: its write | ||
| 365 | + /// loop is one enrollment sweep per (class, member) with no ceiling over the | ||
| 366 | + /// class count, and a failure anywhere in it rolls back the whole grade β | ||
| 367 | + /// so one contended section keeps the other eleven attached to a course the | ||
| 368 | + /// template no longer holds. Per row, a failure leaves the pairs already | ||
| 369 | + /// detached detached, each with its counter released and its enrollments | ||
| 370 | + /// swept, and the rest exactly as they were: a partial removal, which is the | ||
| 371 | + /// same partial state a pump is allowed to leave. | ||
| 372 | + /// | ||
| 373 | + /// The rows are read first rather than derived from the classes at this | ||
| 374 | + /// grade: a class whose grade was edited after the pump still carries this | ||
| 375 | + /// blueprint's attachments, and only the `source` tag can find it. | ||
| 376 | + async fn drop_courses(&self, courses: &[CourseId], db: &Database) -> Result<(), AppError> { | ||
| 377 | + for course in courses { | ||
| 378 | + let mut found = db | ||
| 379 | + .query(format!( | ||
| 380 | + "SELECT VALUE id FROM {CLASS_COURSE_TABLE} \ | ||
| 381 | + WHERE course = $course AND source = $blueprint" | ||
| 382 | + )) | ||
| 383 | + .bind(("course", course.record())) | ||
| 384 | + .bind(("blueprint", self.id.record())) | ||
| 385 | + .await? | ||
| 386 | + .check()?; | ||
| 387 | + for link in found.take::<Vec<RecordId>>(0)? { | ||
| 388 | + detach( | ||
| 389 | + "$link", | ||
| 390 | + Axis::Course, | ||
| 391 | + &[("link".into(), link.into_value())], | ||
| 392 | + db, | ||
| 393 | + ) | ||
| 394 | + .await?; | ||
| 395 | + } | ||
| 396 | + } | ||
| 397 | + Ok(()) | ||
| 398 | + } | ||
| 399 | +} | ||
| 400 | + | ||
| 401 | +#[cfg(test)] | ||
| 402 | +mod tests { | ||
| 403 | + use super::*; | ||
| 404 | + use crate::domain::class_member::tests::{a_class, a_course}; | ||
| 405 | + | ||
| 406 | + /// A blueprint holding `courses`, at grade "9". | ||
| 407 | + async fn a_blueprint(courses: Vec<CourseId>, db: &Database) -> ClassBlueprint { | ||
| 408 | + ClassBlueprint::create( | ||
| 409 | + &UserId::from_key("manager"), | ||
| 410 | + ClassBlueprint::grade_key("9").unwrap(), | ||
| 411 | + courses, | ||
| 412 | + db, | ||
| 413 | + ) | ||
| 414 | + .await | ||
| 415 | + .unwrap() | ||
| 416 | + } | ||
| 417 | + | ||
| 418 | + /// Every skip names the record that actually failed. | ||
| 419 | + /// | ||
| 420 | + /// The three refusals a manager can meet come out of two different claims | ||
| 421 | + /// in one transaction, and they used to be reported by one string that | ||
| 422 | + /// guessed: a deleted *course* was announced as a deleted *class*, on a | ||
| 423 | + /// section standing right there. Each is provoked from the state that | ||
| 424 | + /// really produces it, not from the enum. | ||
| 425 | + #[tokio::test] | ||
| 426 | + async fn a_skip_names_what_actually_failed() { | ||
| 427 | + let manager = UserId::from_key("manager"); | ||
| 428 | + | ||
| 429 | + // The course is deleted out from under the pump: the pivot claim | ||
| 430 | + // matches nothing. | ||
| 431 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 432 | + let course = a_course("algebra", None, &db).await; | ||
| 433 | + let class = ClassGroup::read(&a_class("9-A", &db).await, &db) | ||
| 434 | + .await | ||
| 435 | + .unwrap() | ||
| 436 | + .unwrap(); | ||
| 437 | + let blueprint = a_blueprint(vec![course.clone()], &db).await; | ||
| 438 | + db.query("DELETE $c") | ||
| 439 | + .bind(("c", course.record())) | ||
| 440 | + .await | ||
| 441 | + .unwrap() | ||
| 442 | + .check() | ||
| 443 | + .unwrap(); | ||
| 444 | + let skipped = blueprint.apply_to(&class, &manager, &db).await.unwrap(); | ||
| 445 | + assert_eq!(skipped.len(), 1, "{skipped:?}"); | ||
| 446 | + assert!( | ||
| 447 | + skipped[0].reason.contains("course no longer exists"), | ||
| 448 | + "the course went, not the class: {}", | ||
| 449 | + skipped[0].reason | ||
| 450 | + ); | ||
| 451 | + // β¦and the dangling id is taken out of the list, so the skip is | ||
| 452 | + // reported once instead of on every pump forever. | ||
| 453 | + assert!( | ||
| 454 | + ClassBlueprint::read(blueprint.get_id(), &db) | ||
| 455 | + .await | ||
| 456 | + .unwrap() | ||
| 457 | + .unwrap() | ||
| 458 | + .get_courses() | ||
| 459 | + .is_empty(), | ||
| 460 | + "a course that no longer exists is pruned from the blueprint" | ||
| 461 | + ); | ||
| 462 | + | ||
| 463 | + // The class is deleted out from under the pump: the counter claim | ||
| 464 | + // matches nothing and the read that follows finds no row. | ||
| 465 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 466 | + let course = a_course("algebra", None, &db).await; | ||
| 467 | + let class = ClassGroup::read(&a_class("9-A", &db).await, &db) | ||
| 468 | + .await | ||
| 469 | + .unwrap() | ||
| 470 | + .unwrap(); | ||
| 471 | + let blueprint = a_blueprint(vec![course.clone()], &db).await; | ||
| 472 | + db.query("DELETE $c") | ||
| 473 | + .bind(("c", class.get_id().record())) | ||
| 474 | + .await | ||
| 475 | + .unwrap() | ||
| 476 | + .check() | ||
| 477 | + .unwrap(); | ||
| 478 | + let skipped = blueprint.apply_to(&class, &manager, &db).await.unwrap(); | ||
| 479 | + assert_eq!(skipped.len(), 1, "{skipped:?}"); | ||
| 480 | + assert!( | ||
| 481 | + skipped[0].reason.contains("class was deleted"), | ||
| 482 | + "the class went, not the course: {}", | ||
| 483 | + skipped[0].reason | ||
| 484 | + ); | ||
| 485 | + assert_eq!( | ||
| 486 | + ClassBlueprint::read(blueprint.get_id(), &db) | ||
| 487 | + .await | ||
| 488 | + .unwrap() | ||
| 489 | + .unwrap() | ||
| 490 | + .get_courses(), | ||
| 491 | + &[course], | ||
| 492 | + "a live course is not pruned because a class vanished" | ||
| 493 | + ); | ||
| 494 | + | ||
| 495 | + // The class stands at its own ceiling: the same claim matches nothing, | ||
| 496 | + // but the row is there β and that is the one a manager can act on. | ||
| 497 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 498 | + let course = a_course("algebra", None, &db).await; | ||
| 499 | + let class = ClassGroup::read(&a_class("9-A", &db).await, &db) | ||
| 500 | + .await | ||
| 501 | + .unwrap() | ||
| 502 | + .unwrap(); | ||
| 503 | + let blueprint = a_blueprint(vec![course], &db).await; | ||
| 504 | + db.query(format!( | ||
| 505 | + "UPDATE $c SET {} = $cap", | ||
| 506 | + crate::constant::CLASS_COURSE_COUNT_FIELD | ||
| 507 | + )) | ||
| 508 | + .bind(("c", class.get_id().record())) | ||
| 509 | + .bind(("cap", MAX_CLASS_COURSES)) | ||
| 510 | + .await | ||
| 511 | + .unwrap() | ||
| 512 | + .check() | ||
| 513 | + .unwrap(); | ||
| 514 | + let skipped = blueprint.apply_to(&class, &manager, &db).await.unwrap(); | ||
| 515 | + assert_eq!(skipped.len(), 1, "{skipped:?}"); | ||
| 516 | + assert!( | ||
| 517 | + skipped[0].reason.contains("ceiling"), | ||
| 518 | + "a full class is not a deleted one: {}", | ||
| 519 | + skipped[0].reason | ||
| 520 | + ); | ||
| 521 | + } | ||
| 522 | + | ||
| 523 | + #[test] | ||
| 524 | + fn a_grade_key_must_be_addressable() { | ||
| 525 | + assert!(ClassBlueprint::grade_key("").is_err()); | ||
| 526 | + assert!(ClassBlueprint::grade_key("9/A").is_err()); | ||
| 527 | + assert!(ClassBlueprint::grade_key("9%A").is_err()); | ||
| 528 | + assert_eq!( | ||
| 529 | + ClassBlueprint::grade_key("9-A") | ||
| 530 | + .unwrap() | ||
| 531 | + .as_str() | ||
| 532 | + .to_string(), | ||
| 533 | + "9-A" | ||
| 534 | + ); | ||
| 535 | + assert!(ClassBlueprint::grade_key(&"x".repeat(1000)).is_err()); | ||
| 536 | + } | ||
| 537 | + | ||
| 538 | + /// The list is a *set*: a caller sending the same course twice must not | ||
| 539 | + /// make the pump attach it twice (the second is a duplicate anyway) nor | ||
| 540 | + /// spend two of the ceiling's places on one course. | ||
| 541 | + #[test] | ||
| 542 | + fn a_course_list_is_deduplicated_and_bounded() { | ||
| 543 | + let algebra = CourseId::from_key("algebra"); | ||
| 544 | + let held = ClassBlueprint::course_list(vec![algebra.clone(), algebra.clone()]).unwrap(); | ||
| 545 | + assert_eq!(held, vec![algebra]); | ||
| 546 | + | ||
| 547 | + let too_many: Vec<CourseId> = (0..=MAX_CLASS_COURSES) | ||
| 548 | + .map(|n| CourseId::from_key(&n.to_string())) | ||
| 549 | + .collect(); | ||
| 550 | + assert!(ClassBlueprint::course_list(too_many).is_err()); | ||
| 551 | + } | ||
| 552 | + | ||
| 553 | + /// A blueprint pumps best-effort, so every refusal the pump can answer must | ||
| 554 | + /// map to a reported skip rather than fall through as a success β and the | ||
| 555 | + /// two "nothing to do" answers must map to no skip at all. | ||
| 556 | + #[test] | ||
| 557 | + fn every_refusal_the_pump_can_answer_is_a_skip() { | ||
| 558 | + assert!(skip_reason(&Attached::Duplicate).is_none()); | ||
| 559 | + for refusal in [ | ||
| 560 | + Attached::Gone, | ||
| 561 | + Attached::PivotGone, | ||
| 562 | + Attached::ClassFull, | ||
| 563 | + Attached::ClassOverloaded, | ||
| 564 | + Attached::Full("course:algebra".into()), | ||
| 565 | + Attached::CourseGone("course:algebra".into()), | ||
| 566 | + ] { | ||
| 567 | + assert!( | ||
| 568 | + skip_reason(&refusal).is_some(), | ||
| 569 | + "{refusal:?} must be reported, not swallowed" | ||
| 570 | + ); | ||
| 571 | + } | ||
| 572 | + } | ||
| 573 | +} | ||
src/domain/class_course.rsmodified+57 -19
| @@ -8,6 +8,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | |||
| 8 | 8 | ||
| 9 | use crate::constant::{CLASS_COURSE_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; | 9 | use crate::constant::{CLASS_COURSE_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; |
| 10 | use crate::database::Database; | 10 | use crate::database::Database; |
| 11 | +use crate::domain::class_blueprint::ClassBlueprintId; | ||
| 11 | use crate::domain::class_group::ClassGroupId; | 12 | use crate::domain::class_group::ClassGroupId; |
| 12 | use crate::domain::class_pump::{Attached, Axis, attach, detach, link_id}; | 13 | use crate::domain::class_pump::{Attached, Axis, attach, detach, link_id}; |
| 13 | use crate::domain::course::CourseId; | 14 | use crate::domain::course::CourseId; |
| @@ -44,6 +45,13 @@ pub struct ClassCourse { | |||
| 44 | class: ClassGroupId, | 45 | class: ClassGroupId, |
| 45 | course: CourseId, | 46 | course: CourseId, |
| 46 | attached_by: UserId, | 47 | attached_by: UserId, |
| 48 | + /// The grade blueprint that placed this attachment, absent when a human | ||
| 49 | + /// attached the course to this class directly β the mirror of | ||
| 50 | + /// [`crate::domain::enrollment`]'s `source`, and read the same way: only a | ||
| 51 | + /// row carrying the key is a blueprint's to take back, so a hand-attached | ||
| 52 | + /// course survives every blueprint sweep. Rows written before the column | ||
| 53 | + /// carry no key at all, which is exactly "hand-attached". | ||
| 54 | + source: Option<ClassBlueprintId>, | ||
| 47 | /// When it was attached, and the *only* thing "newest first" can mean here: | 55 | /// When it was attached, and the *only* thing "newest first" can mean here: |
| 48 | /// the row's id is the (class, course) pair, so ordering by it sorts the | 56 | /// the row's id is the (class, course) pair, so ordering by it sorts the |
| 49 | /// list by the course's own ULID. Optional because rows written before this | 57 | /// list by the course's own ULID. Optional because rows written before this |
| @@ -68,6 +76,11 @@ impl ClassCourse { | |||
| 68 | &self.attached_by | 76 | &self.attached_by |
| 69 | } | 77 | } |
| 70 | 78 | ||
| 79 | + /// The blueprint that placed this attachment, or `None` for a hand attach. | ||
| 80 | + pub fn get_source(&self) -> Option<&ClassBlueprintId> { | ||
| 81 | + self.source.as_ref() | ||
| 82 | + } | ||
| 83 | + | ||
| 71 | /// Attach `course` to `class` and enroll the class's whole roster into it, | 84 | /// Attach `course` to `class` and enroll the class's whole roster into it, |
| 72 | /// in one transaction. | 85 | /// in one transaction. |
| 73 | /// | 86 | /// |
| @@ -80,27 +93,13 @@ impl ClassCourse { | |||
| 80 | attached_by: &UserId, | 93 | attached_by: &UserId, |
| 81 | db: &Database, | 94 | db: &Database, |
| 82 | ) -> Result<ClassCourse, AppError> { | 95 | ) -> Result<ClassCourse, AppError> { |
| 83 | - let link = ClassCourse { | 96 | + match Self::attach_sourced(class, course, attached_by, None, db).await? { |
| 84 | - id: ClassCourseId::composite(class, course), | ||
| 85 | - class: class.clone(), | ||
| 86 | - course: course.clone(), | ||
| 87 | - attached_by: attached_by.clone(), | ||
| 88 | - attached_at: Some(Timestamp::now()), | ||
| 89 | - }; | ||
| 90 | - match attach( | ||
| 91 | - class, | ||
| 92 | - Axis::Course, | ||
| 93 | - &link.id.record(), | ||
| 94 | - &link, | ||
| 95 | - course.record(), | ||
| 96 | - attached_by.record(), | ||
| 97 | - db, | ||
| 98 | - ) | ||
| 99 | - .await? | ||
| 100 | - { | ||
| 101 | Attached::Made(saved) => Ok(saved), | 97 | Attached::Made(saved) => Ok(saved), |
| 102 | Attached::Duplicate => Err(AppError::Conflict("the course is already on this class")), | 98 | Attached::Duplicate => Err(AppError::Conflict("the course is already on this class")), |
| 103 | - Attached::Gone => Err(AppError::NotFound), | 99 | + // The class or the course: either end of the link being gone is a |
| 100 | + // 404 on this route, and only a blueprint's skip list needs them | ||
| 101 | + // told apart. | ||
| 102 | + Attached::Gone | Attached::PivotGone => Err(AppError::NotFound), | ||
| 104 | Attached::ClassFull => Err(AppError::ConflictOwned(format!( | 103 | Attached::ClassFull => Err(AppError::ConflictOwned(format!( |
| 105 | "this class already holds {MAX_CLASS_COURSES} courses" | 104 | "this class already holds {MAX_CLASS_COURSES} courses" |
| 106 | ))), | 105 | ))), |
| @@ -122,6 +121,45 @@ impl ClassCourse { | |||
| 122 | } | 121 | } |
| 123 | } | 122 | } |
| 124 | 123 | ||
| 124 | + /// The attach itself, with the refusals left *unmapped*. | ||
| 125 | + /// | ||
| 126 | + /// A hand attach ([`ClassCourse::attach`]) turns each of them into the | ||
| 127 | + /// error the route answers with, because one call is one course and a | ||
| 128 | + /// refusal is that call's whole answer. A blueprint pump cannot: it runs | ||
| 129 | + /// one of these per (class, course), and a course that does not fit one | ||
| 130 | + /// section must not abort the other eleven β so it needs to *read* the | ||
| 131 | + /// refusal and carry on ([`crate::domain::class_blueprint`]). | ||
| 132 | + /// | ||
| 133 | + /// `source` is the provenance tag, and it is written by the same statement | ||
| 134 | + /// that writes the link, so no attachment can exist without the answer to | ||
| 135 | + /// "may a blueprint take this back". | ||
| 136 | + pub(crate) async fn attach_sourced( | ||
| 137 | + class: &ClassGroupId, | ||
| 138 | + course: &CourseId, | ||
| 139 | + attached_by: &UserId, | ||
| 140 | + source: Option<&ClassBlueprintId>, | ||
| 141 | + db: &Database, | ||
| 142 | + ) -> Result<Attached<ClassCourse>, AppError> { | ||
| 143 | + let link = ClassCourse { | ||
| 144 | + id: ClassCourseId::composite(class, course), | ||
| 145 | + class: class.clone(), | ||
| 146 | + course: course.clone(), | ||
| 147 | + attached_by: attached_by.clone(), | ||
| 148 | + source: source.cloned(), | ||
| 149 | + attached_at: Some(Timestamp::now()), | ||
| 150 | + }; | ||
| 151 | + attach( | ||
| 152 | + class, | ||
| 153 | + Axis::Course, | ||
| 154 | + &link.id.record(), | ||
| 155 | + &link, | ||
| 156 | + course.record(), | ||
| 157 | + attached_by.record(), | ||
| 158 | + db, | ||
| 159 | + ) | ||
| 160 | + .await | ||
| 161 | + } | ||
| 162 | + | ||
| 125 | /// Detach `course` from `class` and sweep the enrollments the class pumped | 163 | /// Detach `course` from `class` and sweep the enrollments the class pumped |
| 126 | /// into it. A course that was not attached is a [`AppError::NotFound`], | 164 | /// into it. A course that was not attached is a [`AppError::NotFound`], |
| 127 | /// raised here rather than left to each caller to re-derive from a boolean. | 165 | /// raised here rather than left to each caller to re-derive from a boolean. |
src/domain/class_group.rsmodified+15 -0
| @@ -257,6 +257,21 @@ impl ClassGroup { | |||
| 257 | Ok(result.take::<Vec<ClassGroup>>(0)?) | 257 | Ok(result.take::<Vec<ClassGroup>>(0)?) |
| 258 | } | 258 | } |
| 259 | 259 | ||
| 260 | + /// Every class section at one grade label, in no particular order β what a | ||
| 261 | + /// grade blueprint pumps. Unpaged on purpose: the caller is reconciling all | ||
| 262 | + /// of them, and a page would silently stock only the first window. | ||
| 263 | + pub async fn list_for_grade( | ||
| 264 | + grade: &ClassGrade, | ||
| 265 | + db: &Database, | ||
| 266 | + ) -> Result<Vec<ClassGroup>, AppError> { | ||
| 267 | + let mut result = db | ||
| 268 | + .query("SELECT * FROM class_group WHERE grade = $grade") | ||
| 269 | + .bind(("grade", grade.as_str().to_string())) | ||
| 270 | + .await? | ||
| 271 | + .check()?; | ||
| 272 | + Ok(result.take::<Vec<ClassGroup>>(0)?) | ||
| 273 | + } | ||
| 274 | + | ||
| 260 | /// Strip `user` from every class they were the homeroom teacher of β the | 275 | /// Strip `user` from every class they were the homeroom teacher of β the |
| 261 | /// sweep for a user demoted below `teacher`, who may no longer hold one. | 276 | /// sweep for a user demoted below `teacher`, who may no longer hold one. |
| 262 | /// The mirror of [`crate::domain::course::Course::unassign_everywhere`]; | 277 | /// The mirror of [`crate::domain::course::Course::unassign_everywhere`]; |
src/domain/class_member.rsmodified+22 -6
| @@ -101,7 +101,9 @@ impl ClassMember { | |||
| 101 | { | 101 | { |
| 102 | Attached::Made(saved) => Ok(saved), | 102 | Attached::Made(saved) => Ok(saved), |
| 103 | Attached::Duplicate => Err(AppError::Conflict("the student is already in this class")), | 103 | Attached::Duplicate => Err(AppError::Conflict("the student is already in this class")), |
| 104 | - Attached::Gone => Err(AppError::NotFound), | 104 | + // The member axis claims no pivot, so `PivotGone` cannot arrive |
| 105 | + // here; the class being gone is the only 404 this route can see. | ||
| 106 | + Attached::Gone | Attached::PivotGone => Err(AppError::NotFound), | ||
| 105 | Attached::ClassFull => Err(AppError::ConflictOwned(format!( | 107 | Attached::ClassFull => Err(AppError::ConflictOwned(format!( |
| 106 | "this class already holds {MAX_CLASS_MEMBERS} students" | 108 | "this class already holds {MAX_CLASS_MEMBERS} students" |
| 107 | ))), | 109 | ))), |
| @@ -504,15 +506,28 @@ pub(crate) mod tests { | |||
| 504 | assert_eq!(counter("class_member_count", class.record(), &db).await, 0); | 506 | assert_eq!(counter("class_member_count", class.record(), &db).await, 0); |
| 505 | } | 507 | } |
| 506 | 508 | ||
| 507 | - /// The role-change sweep, which is now one transaction over both tables: | 509 | + /// The role-change sweep, which is one transaction with the role write |
| 508 | - /// the memberships go with their counters, the enrollment rows go with | 510 | + /// itself: the memberships go with their counters, the enrollment rows go |
| 509 | - /// their seats, and each seat comes back exactly once β the double | 511 | + /// with their seats, and each seat comes back exactly once β the double |
| 510 | /// decrement the old two-call split existed to avoid. | 512 | /// decrement the old two-call split existed to avoid. |
| 511 | #[tokio::test] | 513 | #[tokio::test] |
| 512 | async fn the_role_sweep_takes_memberships_and_enrollments_together() { | 514 | async fn the_role_sweep_takes_memberships_and_enrollments_together() { |
| 513 | let db = crate::database::init_mem().await.unwrap(); | 515 | let db = crate::database::init_mem().await.unwrap(); |
| 514 | let manager = UserId::from_key("manager"); | 516 | let manager = UserId::from_key("manager"); |
| 515 | - let student = UserId::from_key("student"); | 517 | + // A real row, because the sweep now rides on the role write. |
| 518 | + let hash = crate::domain::user::Password::try_new("secret1") | ||
| 519 | + .unwrap() | ||
| 520 | + .hash_async() | ||
| 521 | + .await | ||
| 522 | + .unwrap(); | ||
| 523 | + let account = crate::domain::user::User::create( | ||
| 524 | + crate::domain::user::Username::try_new("ogrenci").unwrap(), | ||
| 525 | + hash, | ||
| 526 | + &db, | ||
| 527 | + ) | ||
| 528 | + .await | ||
| 529 | + .unwrap(); | ||
| 530 | + let student = account.get_id().clone(); | ||
| 516 | let first = a_class("9-A", &db).await; | 531 | let first = a_class("9-A", &db).await; |
| 517 | let second = a_class("club", &db).await; | 532 | let second = a_class("club", &db).await; |
| 518 | let algebra = a_course("algebra", None, &db).await; | 533 | let algebra = a_course("algebra", None, &db).await; |
| @@ -526,7 +541,8 @@ pub(crate) mod tests { | |||
| 526 | .await | 541 | .await |
| 527 | .unwrap(); | 542 | .unwrap(); |
| 528 | 543 | ||
| 529 | - crate::domain::class_pump::sweep_non_student(&student, &db) | 544 | + account |
| 545 | + .set_role(crate::domain::role::Role::Teacher, &db) | ||
| 530 | .await | 546 | .await |
| 531 | .unwrap(); | 547 | .unwrap(); |
| 532 | assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); | 548 | assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); |
src/domain/class_pump.rsmodified+17 -49
| @@ -32,7 +32,6 @@ use crate::constant::{ | |||
| 32 | use crate::database::{Database, transaction_with_retry}; | 32 | use crate::database::{Database, transaction_with_retry}; |
| 33 | use crate::domain::cap; | 33 | use crate::domain::cap; |
| 34 | use crate::domain::class_group::{ClassGroup, ClassGroupId}; | 34 | use crate::domain::class_group::{ClassGroup, ClassGroupId}; |
| 35 | -use crate::domain::user::UserId; | ||
| 36 | use crate::error::AppError; | 35 | use crate::error::AppError; |
| 37 | 36 | ||
| 38 | /// The `THROW` markers [`attach`] aborts with. `FULL_MARK` and `MISSING_MARK` | 37 | /// The `THROW` markers [`attach`] aborts with. `FULL_MARK` and `MISSING_MARK` |
| @@ -67,6 +66,7 @@ const FULL_MARK: &str = "class_full:"; | |||
| 67 | const MISSING_MARK: &str = "class_no_course:"; | 66 | const MISSING_MARK: &str = "class_no_course:"; |
| 68 | 67 | ||
| 69 | /// What [`attach`] settled. | 68 | /// What [`attach`] settled. |
| 69 | +#[derive(Debug)] | ||
| 70 | pub(crate) enum Attached<T> { | 70 | pub(crate) enum Attached<T> { |
| 71 | /// The link row, the counter and every enrollment it implied committed | 71 | /// The link row, the counter and every enrollment it implied committed |
| 72 | /// together. | 72 | /// together. |
| @@ -74,9 +74,13 @@ pub(crate) enum Attached<T> { | |||
| 74 | /// The link already exists β nothing was written, and no seat was spent | 74 | /// The link already exists β nothing was written, and no seat was spent |
| 75 | /// finding that out. | 75 | /// finding that out. |
| 76 | Duplicate, | 76 | Duplicate, |
| 77 | - /// The class row β or, on the course axis, the course being attached β is | 77 | + /// The class row is gone (a concurrent delete won). Nothing was written. |
| 78 | - /// gone (a concurrent delete won). Nothing was written. | ||
| 79 | Gone, | 78 | Gone, |
| 79 | + /// The *pivot* β on the course axis, the course being attached β is gone. | ||
| 80 | + /// Nothing was written. Told apart from [`Attached::Gone`] because the two | ||
| 81 | + /// send a caller to look at different records, and a report that guesses | ||
| 82 | + /// between them names the wrong one half the time. | ||
| 83 | + PivotGone, | ||
| 80 | /// The class is at its own ceiling on this axis. Nothing was written, and | 84 | /// The class is at its own ceiling on this axis. Nothing was written, and |
| 81 | /// it is told apart from [`Attached::Gone`] because a full class is a | 85 | /// it is told apart from [`Attached::Gone`] because a full class is a |
| 82 | /// standing row someone can make room in, not a 404. | 86 | /// standing row someone can make room in, not a 404. |
| @@ -212,51 +216,15 @@ impl Axis { | |||
| 212 | } | 216 | } |
| 213 | } | 217 | } |
| 214 | 218 | ||
| 215 | -/// Everything a user's role change *off* `student` invalidates, in one | 219 | +// The sweep a role change *off* `student` owes β every class membership (each |
| 216 | -/// transaction: every class membership they hold (each class getting its member | 220 | +// class getting its member count back) and every enrollment row (each course |
| 217 | -/// count back) and every enrollment row they hold (each course getting its seat | 221 | +// getting its seat back) β is two of the arms of |
| 218 | -/// back). | 222 | +// [`crate::domain::user::User::set_role`], because it belongs in the same |
| 219 | -/// | 223 | +// transaction as the role write that invalidates them. It stays one fact with |
| 220 | -/// One transaction because the two halves are one fact. Run as two, a failure | 224 | +// the counters either way: released separately, a failure between the halves |
| 221 | -/// between them released the memberships and both class counters while the | 225 | +// left enrollment rows tagged `source = class_group:X` while the class had its |
| 222 | -/// enrollment rows kept `source = class_group:X` β the class then passed its | 226 | +// counters back, so the class passed its zero-zero delete guard and the rows |
| 223 | -/// zero-zero delete guard, and the rows were left tagged with a class that no | 227 | +// were left pointing at a class no sweep could ever reach again. |
| 224 | -/// longer existed and that no sweep could ever reach. Ordering them the other | ||
| 225 | -/// way only swaps which corruption is reachable: memberships surviving on a | ||
| 226 | -/// non-student are memberships the next attach pumps back into a course. | ||
| 227 | -/// | ||
| 228 | -/// The enrollment side takes *every* row, hand-placed ones included, and that | ||
| 229 | -/// is the rule rather than an oversight: what the role change invalidates is | ||
| 230 | -/// not "rows a class wrote" but enrollment itself β only students enroll, and | ||
| 231 | -/// enrollment is what gates sitting exams, being graded and appearing on a | ||
| 232 | -/// roster. A row kept for a teacher would grant nothing and count a seat. | ||
| 233 | -/// Nothing restores them on a demotion back to `student`; a promotion is a | ||
| 234 | -/// roster decision of its own. | ||
| 235 | -pub(crate) async fn sweep_non_student(user: &UserId, db: &Database) -> Result<(), AppError> { | ||
| 236 | - let sql = format!( | ||
| 237 | - "BEGIN TRANSACTION; | ||
| 238 | - LET $links = (DELETE {CLASS_MEMBER_TABLE} WHERE user = $usr RETURN BEFORE); | ||
| 239 | - FOR $link IN ($links ?? []) {{ | ||
| 240 | - UPDATE $link.class SET {CLASS_MEMBER_COUNT_FIELD} = \ | ||
| 241 | - math::max([({CLASS_MEMBER_COUNT_FIELD} ?? 0) - 1, 0]); | ||
| 242 | - }}; | ||
| 243 | - LET $gone = (DELETE {ENROLLMENT_TABLE} WHERE user = $usr RETURN BEFORE); | ||
| 244 | - FOR $row IN ($gone ?? []) {{ | ||
| 245 | - UPDATE $row.course SET {ENROLLMENT_COUNT_FIELD} = \ | ||
| 246 | - math::max([({ENROLLMENT_COUNT_FIELD} ?? 0) - 1, 0]); | ||
| 247 | - }}; | ||
| 248 | - COMMIT TRANSACTION;" | ||
| 249 | - ); | ||
| 250 | - // Admissible by construction: `DELETE` and `UPDATE` only, so no statement | ||
| 251 | - // can answer "already exists" and every lost round is a plain re-send. | ||
| 252 | - let (_, mut errors) = | ||
| 253 | - transaction_with_retry(db, &sql, &[("usr".into(), user.record().into_value())], &[]) | ||
| 254 | - .await?; | ||
| 255 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 256 | - return Err(error.into()); | ||
| 257 | - } | ||
| 258 | - Ok(()) | ||
| 259 | -} | ||
| 260 | 228 | ||
| 261 | /// Write `link` and enroll everything it implies, or write nothing at all. | 229 | /// Write `link` and enroll everything it implies, or write nothing at all. |
| 262 | /// | 230 | /// |
| @@ -374,7 +342,7 @@ pub(crate) async fn attach<T: SurrealValue + Clone>( | |||
| 374 | .values() | 342 | .values() |
| 375 | .any(|error| error.to_string().contains(GONE_MARK)) | 343 | .any(|error| error.to_string().contains(GONE_MARK)) |
| 376 | { | 344 | { |
| 377 | - return Ok(Attached::Gone); | 345 | + return Ok(Attached::PivotGone); |
| 378 | } | 346 | } |
| 379 | // Read before the ceiling below: a class over the *other* axis's ceiling is | 347 | // Read before the ceiling below: a class over the *other* axis's ceiling is |
| 380 | // refused whether or not this axis has room, and being told it is full on | 348 | // refused whether or not this axis has room, and being told it is full on |
src/domain/event.rsmodified+119 -1
| @@ -4,6 +4,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; | |||
| 4 | 4 | ||
| 5 | use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; | 5 | use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; |
| 6 | use crate::database::Database; | 6 | use crate::database::Database; |
| 7 | +use crate::domain::class_group::ClassGroupId; | ||
| 8 | +use crate::domain::class_member::{ClassMember, ClassMemberId}; | ||
| 7 | use crate::domain::course::CourseId; | 9 | use crate::domain::course::CourseId; |
| 8 | use crate::domain::enrollment::Enrollment; | 10 | use crate::domain::enrollment::Enrollment; |
| 9 | use crate::domain::field_update::FieldUpdate; | 11 | use crate::domain::field_update::FieldUpdate; |
| @@ -78,7 +80,8 @@ impl EventDescription { | |||
| 78 | /// expected and who may be marked. | 80 | /// expected and who may be marked. |
| 79 | /// | 81 | /// |
| 80 | /// Stored internally tagged: `{kind: 'school'}`, `{kind: 'role', role: 'student'}`, | 82 | /// Stored internally tagged: `{kind: 'school'}`, `{kind: 'role', role: 'student'}`, |
| 81 | -/// `{kind: 'course', course: course:β¦}`, `{kind: 'registration', capacity: 30}`. | 83 | +/// `{kind: 'course', course: course:β¦}`, `{kind: 'class', class: class_group:β¦}`, |
| 84 | +/// `{kind: 'registration', capacity: 30}`. | ||
| 82 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 85 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 83 | #[surreal(tag = "kind", rename_all = "lowercase")] | 86 | #[surreal(tag = "kind", rename_all = "lowercase")] |
| 84 | pub enum EventAudience { | 87 | pub enum EventAudience { |
| @@ -89,6 +92,13 @@ pub enum EventAudience { | |||
| 89 | /// A course's enrolled students. Staff running the course are not implied | 92 | /// A course's enrolled students. Staff running the course are not implied |
| 90 | /// members β a mixed gathering wants a registration or role audience. | 93 | /// members β a mixed gathering wants a registration or role audience. |
| 91 | Course { course: CourseId }, | 94 | Course { course: CourseId }, |
| 95 | + /// A class section's (Εube) students, read live off `class_member` β the | ||
| 96 | + /// same live resolution `Course` and `Role` get, so adding a student to the | ||
| 97 | + /// class puts them on every one of its events' rosters at once. The | ||
| 98 | + /// homeroom teacher is not implied, matching `Course`. A deleted class | ||
| 99 | + /// leaves the event standing with an empty roster, exactly as a deleted | ||
| 100 | + /// course does (`Course::delete` never touches `event`). | ||
| 101 | + Class { class: ClassGroupId }, | ||
| 92 | /// A signup list built one person at a time through the register | 102 | /// A signup list built one person at a time through the register |
| 93 | /// endpoints β teachers place students, staff take their own seat. The | 103 | /// endpoints β teachers place students, staff take their own seat. The |
| 94 | /// list is capped at `capacity` seats when set (`None` = unlimited) and | 104 | /// list is capped at `capacity` seats when set (`None` = unlimited) and |
| @@ -115,6 +125,14 @@ impl EventAudience { | |||
| 115 | .await? | 125 | .await? |
| 116 | .is_some()) | 126 | .is_some()) |
| 117 | } | 127 | } |
| 128 | + // The (class, user) pair is the membership row's own id, so the | ||
| 129 | + // point check is a single select β no scan, no index needed. | ||
| 130 | + EventAudience::Class { class } => { | ||
| 131 | + let member: Option<ClassMember> = db | ||
| 132 | + .select(ClassMemberId::composite(class, user.get_id()).record()) | ||
| 133 | + .await?; | ||
| 134 | + Ok(member.is_some()) | ||
| 135 | + } | ||
| 118 | EventAudience::Registration { .. } => { | 136 | EventAudience::Registration { .. } => { |
| 119 | Ok(Registration::read_for_user(event, user.get_id(), db) | 137 | Ok(Registration::read_for_user(event, user.get_id(), db) |
| 120 | .await? | 138 | .await? |
| @@ -147,6 +165,12 @@ impl EventAudience { | |||
| 147 | .map(|enrollment| enrollment.get_user().clone()) | 165 | .map(|enrollment| enrollment.get_user().clone()) |
| 148 | .collect()) | 166 | .collect()) |
| 149 | } | 167 | } |
| 168 | + EventAudience::Class { class } => Ok(ClassMember::list_for_class(class, None, 0, db) | ||
| 169 | + .await? | ||
| 170 | + .0 | ||
| 171 | + .iter() | ||
| 172 | + .map(|member| member.get_user().clone()) | ||
| 173 | + .collect()), | ||
| 150 | EventAudience::Registration { .. } => Ok(Registration::list_for_event(event, db) | 174 | EventAudience::Registration { .. } => Ok(Registration::list_for_event(event, db) |
| 151 | .await? | 175 | .await? |
| 152 | .iter() | 176 | .iter() |
| @@ -316,6 +340,94 @@ impl Event { | |||
| 316 | mod tests { | 340 | mod tests { |
| 317 | use super::*; | 341 | use super::*; |
| 318 | 342 | ||
| 343 | + /// The forcing function behind the one rule with two spellings: the freeze | ||
| 344 | + /// this file decides in Rust ([`Event::registration_capacity`]) and | ||
| 345 | + /// [`crate::constant::REGISTRATION_FROZEN_GUARD`], its SurrealQL copy, which | ||
| 346 | + /// the role cascade (`User::set_role`) carries because it frees a demoted | ||
| 347 | + /// parent's seats inside a transaction and cannot call Rust from there. | ||
| 348 | + /// | ||
| 349 | + /// Every schedule shape is put to both, including the three the SQL is most | ||
| 350 | + /// likely to get wrong: the ends_at-only event (`??` must fall through to | ||
| 351 | + /// it), the boundary itself (closed *at* the instant, not after it β `>=` in | ||
| 352 | + /// Rust, `<=` in SQL, and the two read opposite ways round; `$now` is bound | ||
| 353 | + /// to that exact instant so the boundary is really exercised), and an event | ||
| 354 | + /// that takes no registrations at all, which Rust refuses one arm *earlier* | ||
| 355 | + /// β so the SQL must not report it frozen, or a stray row on it would be | ||
| 356 | + /// preserved forever instead of swept. | ||
| 357 | + #[tokio::test] | ||
| 358 | + async fn the_sql_freeze_guard_matches_the_rust_one() { | ||
| 359 | + use crate::constant::REGISTRATION_FROZEN_GUARD; | ||
| 360 | + | ||
| 361 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 362 | + let now = Timestamp::now().as_millis(); | ||
| 363 | + let past = Some(Timestamp::from_millis(now - 60_000)); | ||
| 364 | + let future = Some(Timestamp::from_millis(now + 3_600_000)); | ||
| 365 | + let later = Some(Timestamp::from_millis(now + 7_200_000)); | ||
| 366 | + let signup = EventAudience::Registration { capacity: None }; | ||
| 367 | + let cases = [ | ||
| 368 | + ("timeless", signup.clone(), None, None), | ||
| 369 | + ("deadline ahead", signup.clone(), None, future), | ||
| 370 | + ("deadline passed", signup.clone(), None, past), | ||
| 371 | + ("starts later", signup.clone(), future, later), | ||
| 372 | + ("already started", signup.clone(), past, None), | ||
| 373 | + ("started, ends later", signup.clone(), past, future), | ||
| 374 | + ( | ||
| 375 | + "closing this instant", | ||
| 376 | + signup.clone(), | ||
| 377 | + Some(Timestamp::from_millis(now)), | ||
| 378 | + None, | ||
| 379 | + ), | ||
| 380 | + // No signup list to freeze: `registration_capacity` refuses these on | ||
| 381 | + // the audience, before it ever looks at the clock. | ||
| 382 | + ("started school event", EventAudience::School, past, None), | ||
| 383 | + ( | ||
| 384 | + "started class event", | ||
| 385 | + EventAudience::Class { | ||
| 386 | + class: ClassGroupId::from_key("g1"), | ||
| 387 | + }, | ||
| 388 | + past, | ||
| 389 | + None, | ||
| 390 | + ), | ||
| 391 | + ]; | ||
| 392 | + for (name, audience, starts_at, ends_at) in cases { | ||
| 393 | + let event = Event::create( | ||
| 394 | + &UserId::from_key("teacher"), | ||
| 395 | + EventTitle::try_new(name).unwrap(), | ||
| 396 | + EventDescription::try_new("").unwrap(), | ||
| 397 | + audience, | ||
| 398 | + starts_at, | ||
| 399 | + ends_at, | ||
| 400 | + &db, | ||
| 401 | + ) | ||
| 402 | + .await | ||
| 403 | + .unwrap(); | ||
| 404 | + let rust = matches!( | ||
| 405 | + event.registration_capacity(), | ||
| 406 | + Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) | ||
| 407 | + ); | ||
| 408 | + let mut result = db | ||
| 409 | + .query(format!( | ||
| 410 | + "SELECT VALUE id FROM $ev WHERE {REGISTRATION_FROZEN_GUARD}" | ||
| 411 | + )) | ||
| 412 | + .bind(("ev", event.get_id().record())) | ||
| 413 | + .bind(("now", now)) | ||
| 414 | + .await | ||
| 415 | + .unwrap() | ||
| 416 | + .check() | ||
| 417 | + .unwrap(); | ||
| 418 | + let sql = !result | ||
| 419 | + .take::<Vec<surrealdb::types::RecordId>>(0) | ||
| 420 | + .unwrap() | ||
| 421 | + .is_empty(); | ||
| 422 | + assert_eq!( | ||
| 423 | + sql, rust, | ||
| 424 | + "the SQL freeze guard and registration_capacity disagree on a \ | ||
| 425 | + {name} event β the role cascade would rewrite a closed signup \ | ||
| 426 | + list, or strand a seat on an open one" | ||
| 427 | + ); | ||
| 428 | + } | ||
| 429 | + } | ||
| 430 | + | ||
| 319 | #[tokio::test] | 431 | #[tokio::test] |
| 320 | async fn title_is_required() { | 432 | async fn title_is_required() { |
| 321 | assert!(EventTitle::try_new("standup").is_ok()); | 433 | assert!(EventTitle::try_new("standup").is_ok()); |
| @@ -350,6 +462,12 @@ mod tests { | |||
| 350 | }, | 462 | }, |
| 351 | "course", | 463 | "course", |
| 352 | ), | 464 | ), |
| 465 | + ( | ||
| 466 | + EventAudience::Class { | ||
| 467 | + class: ClassGroupId::from_key("g1"), | ||
| 468 | + }, | ||
| 469 | + "class", | ||
| 470 | + ), | ||
| 353 | ( | 471 | ( |
| 354 | EventAudience::Registration { capacity: Some(30) }, | 472 | EventAudience::Registration { capacity: Some(30) }, |
| 355 | "registration", | 473 | "registration", |
src/domain/exam_attempt.rsmodified+16 -0
| @@ -305,6 +305,22 @@ impl ExamAttempt { | |||
| 305 | Ok(result.take::<Vec<ExamAttempt>>(0)?) | 305 | Ok(result.take::<Vec<ExamAttempt>>(0)?) |
| 306 | } | 306 | } |
| 307 | 307 | ||
| 308 | + /// Every sitting of `user` nobody has submitted yet, across all exams. Only | ||
| 309 | + /// the *candidates* for "in progress": a deadline comes off the exam's live | ||
| 310 | + /// schedule, so the caller still judges [`Self::status`] per exam rather | ||
| 311 | + /// than re-spelling that rule in SurrealQL. | ||
| 312 | + pub async fn list_unfinished_for_user( | ||
| 313 | + user: &UserId, | ||
| 314 | + db: &Database, | ||
| 315 | + ) -> Result<Vec<ExamAttempt>, AppError> { | ||
| 316 | + let mut result = db | ||
| 317 | + .query("SELECT * FROM exam_attempt WHERE user = $usr AND finished_at = NONE") | ||
| 318 | + .bind(("usr", user.record())) | ||
| 319 | + .await? | ||
| 320 | + .check()?; | ||
| 321 | + Ok(result.take::<Vec<ExamAttempt>>(0)?) | ||
| 322 | + } | ||
| 323 | + | ||
| 308 | pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<ExamAttempt>, AppError> { | 324 | pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<ExamAttempt>, AppError> { |
| 309 | let mut result = db | 325 | let mut result = db |
| 310 | .query("SELECT * FROM exam_attempt WHERE exam = $ex ORDER BY id DESC") | 326 | .query("SELECT * FROM exam_attempt WHERE exam = $ex ORDER BY id DESC") |
src/domain/exam_question.rsmodified+55 -0
| @@ -1,3 +1,5 @@ | |||
| 1 | +use std::collections::HashSet; | ||
| 2 | + | ||
| 1 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 3 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 2 | use ulid::Ulid; | 4 | use ulid::Ulid; |
| 3 | 5 | ||
| @@ -489,6 +491,59 @@ impl ExamQuestion { | |||
| 489 | .await | 491 | .await |
| 490 | } | 492 | } |
| 491 | 493 | ||
| 494 | + /// The ids of `exam`'s questions that share a bank template with a question | ||
| 495 | + /// under one of `live` β the questions two exams hold identical `correct` | ||
| 496 | + /// for, because the bank copies the key into every instantiation. Keyed on | ||
| 497 | + /// the template, never on the exam, so only the overlapping questions are | ||
| 498 | + /// named. Empty when `live` is empty. | ||
| 499 | + /// | ||
| 500 | + /// A question links to a template through *either* column and both must be | ||
| 501 | + /// read, on both sides of the join: `from_bank` is the template it was | ||
| 502 | + /// instantiated from, `banked_as` the template minted by saving it into the | ||
| 503 | + /// bank ([`Self::link_banked_as`]). A question authored by hand in exam A | ||
| 504 | + /// and then saved to the bank holds only `banked_as`, while its copy in | ||
| 505 | + /// exam B holds only `from_bank` β matching `from_bank` to `from_bank` saw | ||
| 506 | + /// neither and leaked A's key while B was live. A single coalesced key per | ||
| 507 | + /// row is not enough either: a question instantiated from one template and | ||
| 508 | + /// re-saved as another carries *both*, and only the second one may be the | ||
| 509 | + /// shared link. | ||
| 510 | + /// | ||
| 511 | + /// So: collect every template id reachable from a live exam by either | ||
| 512 | + /// column, then name any of `exam`'s questions pointing at one by either | ||
| 513 | + /// column. `$shared` is built from `!= NONE` filters, so it never holds a | ||
| 514 | + /// `NONE` for an unlinked question's absent column to match against. | ||
| 515 | + pub async fn list_shared_with( | ||
| 516 | + exam: &ExamId, | ||
| 517 | + live: &[ExamId], | ||
| 518 | + db: &Database, | ||
| 519 | + ) -> Result<HashSet<String>, AppError> { | ||
| 520 | + if live.is_empty() { | ||
| 521 | + return Ok(HashSet::new()); | ||
| 522 | + } | ||
| 523 | + let mut result = db | ||
| 524 | + .query( | ||
| 525 | + "LET $shared = array::union( | ||
| 526 | + (SELECT VALUE from_bank FROM exam_question | ||
| 527 | + WHERE exam IN $live AND from_bank != NONE), | ||
| 528 | + (SELECT VALUE banked_as FROM exam_question | ||
| 529 | + WHERE exam IN $live AND banked_as != NONE)); | ||
| 530 | + SELECT VALUE id FROM exam_question | ||
| 531 | + WHERE exam = $ex AND (from_bank IN $shared OR banked_as IN $shared)", | ||
| 532 | + ) | ||
| 533 | + .bind(("ex", exam.record())) | ||
| 534 | + .bind(( | ||
| 535 | + "live", | ||
| 536 | + live.iter().map(ExamId::record).collect::<Vec<RecordId>>(), | ||
| 537 | + )) | ||
| 538 | + .await? | ||
| 539 | + .check()?; | ||
| 540 | + Ok(result | ||
| 541 | + .take::<Vec<ExamQuestionId>>(1)? | ||
| 542 | + .iter() | ||
| 543 | + .map(|id| id.key().to_string()) | ||
| 544 | + .collect()) | ||
| 545 | + } | ||
| 546 | + | ||
| 492 | /// Write the editable fields, refused outright once the exam has an | 547 | /// Write the editable fields, refused outright once the exam has an |
| 493 | /// attempt β the freeze gate is part of this transaction, not a check the | 548 | /// attempt β the freeze gate is part of this transaction, not a check the |
| 494 | /// caller made a moment earlier under a lock. | 549 | /// caller made a moment earlier under a lock. |
src/domain/mod.rsmodified+1 -0
| @@ -13,6 +13,7 @@ pub mod board_stroke; | |||
| 13 | pub mod cap; | 13 | pub mod cap; |
| 14 | pub mod chatbot_message; | 14 | pub mod chatbot_message; |
| 15 | pub mod chatbot_thread; | 15 | pub mod chatbot_thread; |
| 16 | +pub mod class_blueprint; | ||
| 16 | pub mod class_course; | 17 | pub mod class_course; |
| 17 | pub mod class_group; | 18 | pub mod class_group; |
| 18 | pub mod class_member; | 19 | pub mod class_member; |
src/domain/note.rsmodified+90 -17
| @@ -4,6 +4,7 @@ use crate::constant::{MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN, NOTE_TABLE}; | |||
| 4 | use crate::database::Database; | 4 | use crate::database::Database; |
| 5 | use crate::domain::field_update::FieldUpdate; | 5 | use crate::domain::field_update::FieldUpdate; |
| 6 | use crate::domain::monotonic_id::next_ulid; | 6 | use crate::domain::monotonic_id::next_ulid; |
| 7 | +use crate::domain::note_file::NoteFile; | ||
| 7 | use crate::domain::page::PagedList; | 8 | use crate::domain::page::PagedList; |
| 8 | use crate::domain::user::UserId; | 9 | use crate::domain::user::UserId; |
| 9 | use crate::error::{AppError, ValidationError}; | 10 | use crate::error::{AppError, ValidationError}; |
| @@ -64,6 +65,15 @@ impl NoteContent { | |||
| 64 | } | 65 | } |
| 65 | } | 66 | } |
| 66 | 67 | ||
| 68 | +/// What [`Note::delete`]'s transaction removed: the note row (empty if it had | ||
| 69 | +/// already vanished) and every attachment row the cascade took with it β the | ||
| 70 | +/// only set whose blobs are safe to unlink. | ||
| 71 | +#[derive(Debug, SurrealValue)] | ||
| 72 | +struct DeleteOutcome { | ||
| 73 | + note: Vec<Note>, | ||
| 74 | + files: Vec<NoteFile>, | ||
| 75 | +} | ||
| 76 | + | ||
| 67 | #[derive(Debug, Clone, SurrealValue)] | 77 | #[derive(Debug, Clone, SurrealValue)] |
| 68 | pub struct Note { | 78 | pub struct Note { |
| 69 | id: NoteId, | 79 | id: NoteId, |
| @@ -142,39 +152,38 @@ impl Note { | |||
| 142 | .await | 152 | .await |
| 143 | } | 153 | } |
| 144 | 154 | ||
| 145 | - /// Delete the note and cascade-remove its attachment rows. Blob files on | 155 | + /// Delete the note and cascade-remove its attachment rows, returning both: |
| 146 | - /// disk are the web layer's to remove (it lists them before calling this); | 156 | + /// the note, and the attachment rows this transaction actually removed. |
| 147 | - /// a crash in between leaves at worst an unreachable blob, never a row | 157 | + /// Blob files on disk are the web layer's to remove, but only for *these* |
| 148 | - /// pointing at nothing. | 158 | + /// rows β a row uploaded after the caller listed the note's files is |
| 159 | + /// deleted here too, and a pre-read snapshot would strand its blob. A crash | ||
| 160 | + /// between commit and unlink leaves at worst an unreachable blob, never a | ||
| 161 | + /// row pointing at nothing. | ||
| 149 | /// | 162 | /// |
| 150 | /// Children first, in one transaction, the way | 163 | /// Children first, in one transaction, the way |
| 151 | /// [`crate::domain::course::Course::delete`] does it: as two queries, an | 164 | /// [`crate::domain::course::Course::delete`] does it: as two queries, an |
| 152 | /// upload that committed in between kept its row while the note went, and | 165 | /// upload that committed in between kept its row while the note went, and |
| 153 | /// nothing could ever list or delete it again. | 166 | /// nothing could ever list or delete it again. |
| 154 | - /// | 167 | + pub async fn delete(self, db: &Database) -> Result<(Note, Vec<NoteFile>), AppError> { |
| 155 | - /// ponytail: the blob of *that* upload is still orphaned on disk β the web | ||
| 156 | - /// layer snapshots the file list before this call, so a row created inside | ||
| 157 | - /// the window is deleted here but its file is never unlinked. Ceiling: one | ||
| 158 | - /// leaked blob per racing upload-vs-delete, unreachable but not reclaimed. | ||
| 159 | - /// Upgrade path: return the deleted `note_file` rows from this transaction | ||
| 160 | - /// and have the handler unlink *those* instead of its snapshot. | ||
| 161 | - pub async fn delete(self, db: &Database) -> Result<Note, AppError> { | ||
| 162 | let mut result = db | 168 | let mut result = db |
| 163 | .query( | 169 | .query( |
| 164 | "BEGIN TRANSACTION; | 170 | "BEGIN TRANSACTION; |
| 165 | - DELETE note_file WHERE note = $note; | 171 | + LET $files = (DELETE note_file WHERE note = $note RETURN BEFORE); |
| 166 | LET $gone = (DELETE $note RETURN BEFORE); | 172 | LET $gone = (DELETE $note RETURN BEFORE); |
| 167 | - RETURN $gone; | 173 | + RETURN { note: $gone, files: $files }; |
| 168 | COMMIT TRANSACTION;", | 174 | COMMIT TRANSACTION;", |
| 169 | ) | 175 | ) |
| 170 | .bind(("note", self.id.record())) | 176 | .bind(("note", self.id.record())) |
| 171 | .await? | 177 | .await? |
| 172 | .check()?; | 178 | .check()?; |
| 173 | - result | 179 | + // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3. |
| 174 | - .take::<Vec<Note>>(3)? | 180 | + let outcome = result |
| 181 | + .take::<Vec<DeleteOutcome>>(3)? | ||
| 175 | .into_iter() | 182 | .into_iter() |
| 176 | .next() | 183 | .next() |
| 177 | - .ok_or(AppError::NotFound) | 184 | + .ok_or_else(|| AppError::Internal("failed to delete note".into()))?; |
| 185 | + let note = outcome.note.into_iter().next().ok_or(AppError::NotFound)?; | ||
| 186 | + Ok((note, outcome.files)) | ||
| 178 | } | 187 | } |
| 179 | } | 188 | } |
| 180 | 189 | ||
| @@ -188,6 +197,70 @@ mod tests { | |||
| 188 | assert!(NoteTitle::try_new(" ").is_err()); | 197 | assert!(NoteTitle::try_new(" ").is_err()); |
| 189 | } | 198 | } |
| 190 | 199 | ||
| 200 | + /// The blobs the handler unlinks are exactly the rows this transaction | ||
| 201 | + /// removed β including one uploaded after any pre-read snapshot would have | ||
| 202 | + /// been taken, which is the row whose blob used to leak. | ||
| 203 | + #[tokio::test] | ||
| 204 | + async fn delete_returns_the_attachment_rows_it_removed() { | ||
| 205 | + use crate::domain::note_file::{FileContentType, FileName}; | ||
| 206 | + | ||
| 207 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 208 | + let owner = crate::domain::user::UserId::generate(); | ||
| 209 | + let note = Note::create( | ||
| 210 | + &owner, | ||
| 211 | + NoteTitle::try_new("a").unwrap(), | ||
| 212 | + NoteContent::try_new("body").unwrap(), | ||
| 213 | + &db, | ||
| 214 | + ) | ||
| 215 | + .await | ||
| 216 | + .unwrap(); | ||
| 217 | + // What a handler snapshot would have seen... | ||
| 218 | + let early = NoteFile::new( | ||
| 219 | + note.get_id(), | ||
| 220 | + FileName::try_new("early.pdf").unwrap(), | ||
| 221 | + FileContentType::try_new("application/pdf").unwrap(), | ||
| 222 | + 3, | ||
| 223 | + ) | ||
| 224 | + .insert(&db) | ||
| 225 | + .await | ||
| 226 | + .unwrap(); | ||
| 227 | + let (snapshot, _) = NoteFile::list_for(note.get_id(), None, 0, &db) | ||
| 228 | + .await | ||
| 229 | + .unwrap(); | ||
| 230 | + assert_eq!(snapshot.len(), 1); | ||
| 231 | + // ...and the upload that races in after it. | ||
| 232 | + let late = NoteFile::new( | ||
| 233 | + note.get_id(), | ||
| 234 | + FileName::try_new("late.pdf").unwrap(), | ||
| 235 | + FileContentType::try_new("application/pdf").unwrap(), | ||
| 236 | + 3, | ||
| 237 | + ) | ||
| 238 | + .insert(&db) | ||
| 239 | + .await | ||
| 240 | + .unwrap(); | ||
| 241 | + | ||
| 242 | + let (gone, files) = note.delete(&db).await.unwrap(); | ||
| 243 | + assert_eq!(gone.get_title().as_str(), "a"); | ||
| 244 | + let mut keys: Vec<_> = files | ||
| 245 | + .iter() | ||
| 246 | + .map(|file| file.get_id().key().to_string()) | ||
| 247 | + .collect(); | ||
| 248 | + keys.sort(); | ||
| 249 | + let mut want = vec![ | ||
| 250 | + early.get_id().key().to_string(), | ||
| 251 | + late.get_id().key().to_string(), | ||
| 252 | + ]; | ||
| 253 | + want.sort(); | ||
| 254 | + assert_eq!(keys, want); | ||
| 255 | + assert!( | ||
| 256 | + NoteFile::list_for(gone.get_id(), None, 0, &db) | ||
| 257 | + .await | ||
| 258 | + .unwrap() | ||
| 259 | + .0 | ||
| 260 | + .is_empty() | ||
| 261 | + ); | ||
| 262 | + } | ||
| 263 | + | ||
| 191 | #[tokio::test] | 264 | #[tokio::test] |
| 192 | async fn content_is_optional() { | 265 | async fn content_is_optional() { |
| 193 | assert_eq!(NoteContent::try_new("").unwrap().as_str(), ""); | 266 | assert_eq!(NoteContent::try_new("").unwrap().as_str(), ""); |
src/domain/parent_link.rsmodified+5 -20
| @@ -120,24 +120,9 @@ impl ParentLink { | |||
| 120 | Ok(result.take::<Vec<ParentLink>>(0)?.into_iter().next()) | 120 | Ok(result.take::<Vec<ParentLink>>(0)?.into_iter().next()) |
| 121 | } | 121 | } |
| 122 | 122 | ||
| 123 | - /// Drop every link where `user` is the observed student β called when a | 123 | + // Both role-change sweeps (the observed student leaving `student`, the |
| 124 | - /// role change takes the student side out of the `student` role, mirroring | 124 | + // observing parent leaving `parent`) live in |
| 125 | - /// the enrollment sweep. | 125 | + // [`crate::domain::user::User::set_role`]: they commit with the role write |
| 126 | - pub async fn delete_where_student(user: &UserId, db: &Database) -> Result<(), AppError> { | 126 | + // itself, so there is no window where a link outlives the role that |
| 127 | - db.query("DELETE parent_link WHERE student = $usr") | 127 | + // justified it. |
| 128 | - .bind(("usr", user.record())) | ||
| 129 | - .await? | ||
| 130 | - .check()?; | ||
| 131 | - Ok(()) | ||
| 132 | - } | ||
| 133 | - | ||
| 134 | - /// Drop every link where `user` is the observing parent β called when a | ||
| 135 | - /// role change takes the parent side out of the `parent` role. | ||
| 136 | - pub async fn delete_where_parent(user: &UserId, db: &Database) -> Result<(), AppError> { | ||
| 137 | - db.query("DELETE parent_link WHERE parent = $usr") | ||
| 138 | - .bind(("usr", user.record())) | ||
| 139 | - .await? | ||
| 140 | - .check()?; | ||
| 141 | - Ok(()) | ||
| 142 | - } | ||
| 143 | } | 128 | } |
src/domain/registration.rsmodified+7 -48
| @@ -173,52 +173,11 @@ impl Registration { | |||
| 173 | Ok(result.take::<Vec<Registration>>(3)?.into_iter().next()) | 173 | Ok(result.take::<Vec<Registration>>(3)?.into_iter().next()) |
| 174 | } | 174 | } |
| 175 | 175 | ||
| 176 | - /// Free every *still-freeable* seat a demotion to `parent` strands. | 176 | + // The demotion sweep β freeing every seat a fall to `parent` would strand, |
| 177 | - /// | 177 | + // and leaving a list that has already frozen exactly as it stands β is an |
| 178 | - /// Only a `parent` is swept, and that is the whole rule rather than the | 178 | + // arm of [`crate::domain::user::User::set_role`], so the seat comes back in |
| 179 | - /// non-student sweep the enrollment side runs: staff free their own seats | 179 | + // the same transaction as the role that invalidated it. The freeze it obeys |
| 180 | - /// by hand (`unregister` allows the self case), so a promoted student is | 180 | + // is [`Event::registration_capacity`]'s `Conflict` arm, re-spelled for |
| 181 | - /// never stranded and their signups are theirs to keep. A parent holds no | 181 | + // SurrealQL as [`crate::constant::REGISTRATION_FROZEN_GUARD`] and held to it |
| 182 | - /// such door β the route is `RequireTeacher`, and no one else may free a | 182 | + // by `event::tests::the_sql_freeze_guard_matches_the_rust_one`. |
| 183 | - /// non-student's seat β so their row is the one thing on a signup list | ||
| 184 | - /// nothing can ever remove: the event answers "full" forever and the | ||
| 185 | - /// parent stays on the roster and stays markable, because the registration | ||
| 186 | - /// audience resolves on the row's mere existence. | ||
| 187 | - /// | ||
| 188 | - /// A list that has already **frozen** is left exactly as it stands. The | ||
| 189 | - /// freeze is not re-spelled here β [`Event::registration_capacity`] is the | ||
| 190 | - /// one place it is decided, and its `Conflict` arm *is* the freeze (its | ||
| 191 | - /// other refusal is the audience). Past that point the list is historical | ||
| 192 | - /// record, the way a roll-call row keeps its retired exam kind: the seat | ||
| 193 | - /// costs nothing (nobody can book the event again either) and deleting the | ||
| 194 | - /// row would rewrite an attendance roster behind the freeze's back, | ||
| 195 | - /// irrecoverably β re-registering answers 409. | ||
| 196 | - /// | ||
| 197 | - /// Row and seat still move together: each removal is | ||
| 198 | - /// [`Registration::remove`]'s single transaction. Per row rather than one | ||
| 199 | - /// transaction for all of them, because the seats are independent facts on | ||
| 200 | - /// unrelated events β nothing is left inconsistent by stopping halfway. | ||
| 201 | - pub async fn sweep_for_parent(user: &UserId, db: &Database) -> Result<(), AppError> { | ||
| 202 | - let mut result = db | ||
| 203 | - .query("SELECT * FROM registration WHERE user = $usr") | ||
| 204 | - .bind(("usr", user.record())) | ||
| 205 | - .await? | ||
| 206 | - .check()?; | ||
| 207 | - for row in result.take::<Vec<Registration>>(0)? { | ||
| 208 | - // A row whose event record is *gone* is deleted, never skipped: | ||
| 209 | - // there is no seat to hand back and no list to freeze, so the | ||
| 210 | - // carve-out below cannot apply to it β and `unregister` answers 404 | ||
| 211 | - // on the missing event, so a skipped orphan is stranded forever. | ||
| 212 | - if let Some(event) = Event::read(&row.event, db).await? | ||
| 213 | - && matches!( | ||
| 214 | - event.registration_capacity(), | ||
| 215 | - Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) | ||
| 216 | - ) | ||
| 217 | - { | ||
| 218 | - continue; | ||
| 219 | - } | ||
| 220 | - Self::remove(&row.event, user, db).await?; | ||
| 221 | - } | ||
| 222 | - Ok(()) | ||
| 223 | - } | ||
| 224 | } | 183 | } |
src/domain/user.rsmodified+190 -18
| @@ -4,8 +4,13 @@ use argon2::password_hash::SaltString; | |||
| 4 | use argon2::{Argon2, PasswordHasher, PasswordVerifier}; | 4 | use argon2::{Argon2, PasswordHasher, PasswordVerifier}; |
| 5 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 5 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 6 | 6 | ||
| 7 | -use crate::constant::{DECOY_PASSWORD, USER_TABLE}; | 7 | +use crate::constant::{ |
| 8 | -use crate::database::Database; | 8 | + BOARD_TABLE, CLASS_GROUP_TABLE, CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE, COURSE_TABLE, |
| 9 | + DECOY_PASSWORD, ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE, PARENT_LINK_TABLE, | ||
| 10 | + REGISTRATION_COUNT_FIELD, REGISTRATION_FROZEN_GUARD, REGISTRATION_TABLE, USER_TABLE, | ||
| 11 | +}; | ||
| 12 | +use crate::database::{Database, transaction_with_retry}; | ||
| 13 | +use crate::domain::board::Board; | ||
| 9 | use crate::domain::field_update::FieldUpdate; | 14 | use crate::domain::field_update::FieldUpdate; |
| 10 | use crate::domain::monotonic_id::next_ulid; | 15 | use crate::domain::monotonic_id::next_ulid; |
| 11 | use crate::domain::page::PagedList; | 16 | use crate::domain::page::PagedList; |
| @@ -13,6 +18,7 @@ use crate::domain::preferences::{Language, PaletteColor, Theme}; | |||
| 13 | use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; | 18 | use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; |
| 14 | use crate::domain::role::Role; | 19 | use crate::domain::role::Role; |
| 15 | use crate::domain::text_fold::{search_fold, search_fold_sql}; | 20 | use crate::domain::text_fold::{search_fold, search_fold_sql}; |
| 21 | +use crate::domain::timestamp::Timestamp; | ||
| 16 | use crate::error::{AppError, ValidationError}; | 22 | use crate::error::{AppError, ValidationError}; |
| 17 | use crate::validate::{validate_password, validate_username}; | 23 | use crate::validate::{validate_password, validate_username}; |
| 18 | 24 | ||
| @@ -447,28 +453,145 @@ impl User { | |||
| 447 | list.run(limit, offset, db).await | 453 | list.run(limit, offset, db).await |
| 448 | } | 454 | } |
| 449 | 455 | ||
| 450 | - /// Overwrite this user's role. The caller is responsible for authorizing it. | 456 | + /// Overwrite this user's role **and** shed every grant the new role may not |
| 457 | + /// hold, in one transaction. The caller is responsible for authorizing it. | ||
| 451 | /// | 458 | /// |
| 452 | - /// Writes *only* the `role` field (never the whole row): the row mixes | 459 | + /// Writes *only* the `role` field of the user row (never the whole row): |
| 453 | - /// admin-owned (role) and self-service (profile, preferences) fields, and | 460 | + /// the row mixes admin-owned (role) and self-service (profile, preferences) |
| 454 | - /// each writer starts from a snapshot read at request start. A whole-row | 461 | + /// fields, and each writer starts from a snapshot read at request start. A |
| 455 | - /// write would carry the snapshot's copy of the *other* group back over a | 462 | + /// whole-row write would carry the snapshot's copy of the *other* group back |
| 456 | - /// concurrent edit β an in-flight profile save silently reverting an | 463 | + /// over a concurrent edit β an in-flight profile save silently reverting an |
| 457 | /// admin's demotion, or this write erasing a profile edit that raced it. | 464 | /// admin's demotion, or this write erasing a profile edit that raced it. |
| 458 | /// [`User::set_profile`] and [`User::set_preferences`] are scoped for the | 465 | /// [`User::set_profile`] and [`User::set_preferences`] are scoped for the |
| 459 | /// same reason. | 466 | /// same reason. |
| 460 | - pub async fn set_role(self, role: Role, db: &Database) -> Result<User, AppError> { | 467 | + /// |
| 461 | - let mut result = db | 468 | + /// One transaction and not eight statements, which is what this used to be: |
| 462 | - .query("UPDATE $id SET role = $role RETURN AFTER") | 469 | + /// a sweep that errored answered 500 with the role already lowered and some |
| 463 | - .bind(("id", self.id.record())) | 470 | + /// of the old grants still standing β exactly the state the sweeps exist to |
| 464 | - .bind(("role", role)) | 471 | + /// prevent, and a crash between them left it with nobody to answer to. |
| 465 | - .await? | 472 | + /// Nothing here is a security hole either way (every gate re-reads the live |
| 466 | - .check()?; | 473 | + /// role, `web::mod`), but the residue pollutes rosters, counts and signup |
| 467 | - result | 474 | + /// lists, and one of those, the event seat, nothing could ever free again. |
| 468 | - .take::<Vec<User>>(0)? | 475 | + /// |
| 476 | + /// What is swept, and why the conditions differ: | ||
| 477 | + /// | ||
| 478 | + /// * **Non-student** sheds class memberships, *every* enrollment row | ||
| 479 | + /// (hand-placed ones included β only students enroll, and a kept row | ||
| 480 | + /// would grant nothing and count a seat) and the parent links observing | ||
| 481 | + /// them. Memberships and enrollments were already one transaction and | ||
| 482 | + /// still are: released apart, an enrollment row could be left tagged with | ||
| 483 | + /// a class whose counters had been given back, so the class passed its | ||
| 484 | + /// zero-zero delete guard and no sweep could ever reach the row again. | ||
| 485 | + /// * **Parent** additionally frees event seats and comes off every | ||
| 486 | + /// whiteboard roster. The seat is the one thing on a signup list nothing | ||
| 487 | + /// else could remove: staff free their own by hand (`unregister` allows | ||
| 488 | + /// the self case) but a parent can reach no such door, so a promotion | ||
| 489 | + /// strands nothing and only this demotion does. A list that has already | ||
| 490 | + /// **frozen** ([`REGISTRATION_FROZEN_GUARD`]) is left exactly as it | ||
| 491 | + /// stands β past the freeze it is historical record, re-registering | ||
| 492 | + /// answers 409, and rewriting it here would be irrecoverable. A signup | ||
| 493 | + /// whose event record is *gone* has no seat to hand back and no list that | ||
| 494 | + /// can freeze, so it is deleted rather than skipped: skipped, it is | ||
| 495 | + /// stranded forever (`unregister` 404s on the missing event). | ||
| 496 | + /// * **Below teacher** gives up course staffing and homeroom-teacher | ||
| 497 | + /// columns β only teacher+ may hold either. | ||
| 498 | + /// | ||
| 499 | + /// The returned boards are the rooms whose roster this changed (plus those | ||
| 500 | + /// the user created, which cannot be changed and are returned so their room | ||
| 501 | + /// is prompted too). Publishing to them is the caller's job: an in-process | ||
| 502 | + /// fan-out cannot sit inside a database transaction, and a room told before | ||
| 503 | + /// the commit would re-read the pre-commit state. | ||
| 504 | + /// | ||
| 505 | + /// Admissible for [`transaction_with_retry`] by construction: `SELECT`, | ||
| 506 | + /// `UPDATE` and `DELETE` only, so no statement can answer "already exists" | ||
| 507 | + /// and every lost round is a plain re-send. | ||
| 508 | + pub async fn set_role(self, role: Role, db: &Database) -> Result<(User, Vec<Board>), AppError> { | ||
| 509 | + // Built as a statement list rather than one string so the result slot | ||
| 510 | + // of the board write is *counted*, not hand-tallied against arms that | ||
| 511 | + // may or may not be in the batch. Slot 0 is `BEGIN`, as everywhere. | ||
| 512 | + let mut batch = vec![ | ||
| 513 | + "BEGIN TRANSACTION".to_string(), | ||
| 514 | + "UPDATE $usr SET role = $role RETURN AFTER".to_string(), | ||
| 515 | + ]; | ||
| 516 | + if role != Role::Student { | ||
| 517 | + batch.push(format!( | ||
| 518 | + "LET $links = (DELETE {CLASS_MEMBER_TABLE} WHERE user = $usr RETURN BEFORE)" | ||
| 519 | + )); | ||
| 520 | + batch.push(format!( | ||
| 521 | + "FOR $link IN ($links ?? []) {{ UPDATE $link.class SET \ | ||
| 522 | + {CLASS_MEMBER_COUNT_FIELD} = \ | ||
| 523 | + math::max([({CLASS_MEMBER_COUNT_FIELD} ?? 0) - 1, 0]); }}" | ||
| 524 | + )); | ||
| 525 | + batch.push(format!( | ||
| 526 | + "LET $rows = (DELETE {ENROLLMENT_TABLE} WHERE user = $usr RETURN BEFORE)" | ||
| 527 | + )); | ||
| 528 | + batch.push(format!( | ||
| 529 | + "FOR $row IN ($rows ?? []) {{ UPDATE $row.course SET \ | ||
| 530 | + {ENROLLMENT_COUNT_FIELD} = \ | ||
| 531 | + math::max([({ENROLLMENT_COUNT_FIELD} ?? 0) - 1, 0]); }}" | ||
| 532 | + )); | ||
| 533 | + batch.push(format!("DELETE {PARENT_LINK_TABLE} WHERE student = $usr")); | ||
| 534 | + } | ||
| 535 | + let mut board_slot = None; | ||
| 536 | + if role == Role::Parent { | ||
| 537 | + batch.push(format!( | ||
| 538 | + "LET $signups = (SELECT * FROM {REGISTRATION_TABLE} WHERE user = $usr)" | ||
| 539 | + )); | ||
| 540 | + // Row and seat move together per signup, the way `unregister` does: | ||
| 541 | + // the seats are independent facts on unrelated events. A missing | ||
| 542 | + // event matches nothing in the guard *and* nothing in the counter | ||
| 543 | + // write, which is precisely the orphan rule. | ||
| 544 | + batch.push(format!( | ||
| 545 | + "FOR $signup IN ($signups ?? []) {{ \ | ||
| 546 | + IF array::len((SELECT VALUE id FROM $signup.event \ | ||
| 547 | + WHERE {REGISTRATION_FROZEN_GUARD})) = 0 {{ \ | ||
| 548 | + LET $freed = (DELETE $signup.id RETURN BEFORE); \ | ||
| 549 | + UPDATE $signup.event SET {REGISTRATION_COUNT_FIELD} = \ | ||
| 550 | + math::max([({REGISTRATION_COUNT_FIELD} ?? 0) - array::len($freed), 0]); \ | ||
| 551 | + }}; }}" | ||
| 552 | + )); | ||
| 553 | + board_slot = Some(batch.len()); | ||
| 554 | + batch.push(format!( | ||
| 555 | + "UPDATE {BOARD_TABLE} SET participants -= $usr \ | ||
| 556 | + WHERE $usr IN participants OR creator = $usr RETURN AFTER" | ||
| 557 | + )); | ||
| 558 | + } | ||
| 559 | + if role != Role::Parent { | ||
| 560 | + batch.push(format!("DELETE {PARENT_LINK_TABLE} WHERE parent = $usr")); | ||
| 561 | + } | ||
| 562 | + if !role.at_least(Role::Teacher) { | ||
| 563 | + batch.push(format!( | ||
| 564 | + "UPDATE {COURSE_TABLE} SET teachers -= $usr WHERE $usr IN teachers" | ||
| 565 | + )); | ||
| 566 | + batch.push(format!( | ||
| 567 | + "UPDATE {CLASS_GROUP_TABLE} SET teacher = NONE WHERE teacher = $usr" | ||
| 568 | + )); | ||
| 569 | + } | ||
| 570 | + let sql = format!("{};\nCOMMIT TRANSACTION;", batch.join(";\n")); | ||
| 571 | + let (mut result, mut errors) = transaction_with_retry( | ||
| 572 | + db, | ||
| 573 | + &sql, | ||
| 574 | + &[ | ||
| 575 | + ("usr".into(), self.id.record().into_value()), | ||
| 576 | + ("role".into(), role.into_value()), | ||
| 577 | + ("now".into(), Timestamp::now().as_millis().into_value()), | ||
| 578 | + ], | ||
| 579 | + &[], | ||
| 580 | + ) | ||
| 581 | + .await?; | ||
| 582 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 583 | + return Err(error.into()); | ||
| 584 | + } | ||
| 585 | + let updated = result | ||
| 586 | + .take::<Vec<User>>(1)? | ||
| 469 | .into_iter() | 587 | .into_iter() |
| 470 | .next() | 588 | .next() |
| 471 | - .ok_or(AppError::NotFound) | 589 | + .ok_or(AppError::NotFound)?; |
| 590 | + let boards = match board_slot { | ||
| 591 | + Some(slot) => result.take::<Vec<Board>>(slot)?, | ||
| 592 | + None => Vec::new(), | ||
| 593 | + }; | ||
| 594 | + Ok((updated, boards)) | ||
| 472 | } | 595 | } |
| 473 | 596 | ||
| 474 | /// Write the personal-info fields the request actually carried. Every | 597 | /// Write the personal-info fields the request actually carried. Every |
| @@ -534,6 +657,55 @@ mod tests { | |||
| 534 | use super::*; | 657 | use super::*; |
| 535 | use crate::database::init_mem; | 658 | use crate::database::init_mem; |
| 536 | 659 | ||
| 660 | + /// The board result slot is an *index* into a batch whose length depends on | ||
| 661 | + /// which arms the role selected, so it is the one number in the cascade a | ||
| 662 | + /// silent mistake would not show up in the store: pointed at the wrong | ||
| 663 | + /// statement it yields an empty list, and every whiteboard room whose roster | ||
| 664 | + /// just changed is simply never told. Assert the rows come back. | ||
| 665 | + #[tokio::test] | ||
| 666 | + async fn the_cascade_returns_the_boards_it_stripped() { | ||
| 667 | + use crate::domain::board::{Board, BoardTitle}; | ||
| 668 | + | ||
| 669 | + let db = init_mem().await.unwrap(); | ||
| 670 | + let creator = User::create( | ||
| 671 | + Username::try_new("ogretmen").unwrap(), | ||
| 672 | + Password::try_new("secret1").unwrap().hash().unwrap(), | ||
| 673 | + &db, | ||
| 674 | + ) | ||
| 675 | + .await | ||
| 676 | + .unwrap(); | ||
| 677 | + let guest = User::create( | ||
| 678 | + Username::try_new("ogrenci").unwrap(), | ||
| 679 | + Password::try_new("secret1").unwrap().hash().unwrap(), | ||
| 680 | + &db, | ||
| 681 | + ) | ||
| 682 | + .await | ||
| 683 | + .unwrap(); | ||
| 684 | + let board = Board::create( | ||
| 685 | + creator.get_id(), | ||
| 686 | + BoardTitle::try_new("Geometri").unwrap(), | ||
| 687 | + vec![guest.get_id().clone()], | ||
| 688 | + &db, | ||
| 689 | + ) | ||
| 690 | + .await | ||
| 691 | + .unwrap(); | ||
| 692 | + | ||
| 693 | + // A promotion touches no roster and must report none. | ||
| 694 | + let (guest, boards) = guest.set_role(Role::Teacher, &db).await.unwrap(); | ||
| 695 | + assert!( | ||
| 696 | + boards.is_empty(), | ||
| 697 | + "only a demotion to parent strips rosters" | ||
| 698 | + ); | ||
| 699 | + | ||
| 700 | + let (_, boards) = guest.set_role(Role::Parent, &db).await.unwrap(); | ||
| 701 | + assert_eq!(boards.len(), 1, "the stripped room must be reported back"); | ||
| 702 | + assert_eq!(boards[0].get_id(), board.get_id()); | ||
| 703 | + assert!( | ||
| 704 | + boards[0].get_participants().is_empty(), | ||
| 705 | + "and carry the roster the room is about to be told about" | ||
| 706 | + ); | ||
| 707 | + } | ||
| 708 | + | ||
| 537 | #[tokio::test] | 709 | #[tokio::test] |
| 538 | async fn a_stale_profile_write_cannot_revert_a_role_change() { | 710 | async fn a_stale_profile_write_cannot_revert_a_role_change() { |
| 539 | let db = init_mem().await.unwrap(); | 711 | let db = init_mem().await.unwrap(); |
src/lib.rsmodified+6 -6
| @@ -40,31 +40,31 @@ use crate::state::AppState; | |||
| 40 | ), | 40 | ), |
| 41 | modifiers(&SecurityAddon), | 41 | modifiers(&SecurityAddon), |
| 42 | tags( | 42 | tags( |
| 43 | - (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /limits` publishes every fixed bound the API enforces β field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) β so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off)"), | 43 | + (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /limits` publishes every fixed bound the API enforces β field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) β so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. Two refusals split that contract: every JSON-bodied operation answers `422` when the request never became the type the handler asked for (a wrong-typed field, a missing required one), and that one is a plain-text deserializer diagnostic rather than the `{error}` envelope, so it is read by a human and not parsed by a client; `400` carries the usual `{error}` and means either non-JSON bytes or a well-typed value that broke a rule published here. Multipart upload routes have no JSON body and so answer `400`, never `422`. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off). Those tiers are per client; a server whose client table is saturated by a flood meters otherwise-unknown callers against one shared budget instead, so an unfamiliar client can briefly see a `429` it did not itself earn β always with a `Retry-After`, never longer than the window"), |
| 44 | (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling β public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With no certificate configured the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"), | 44 | (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling β public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With no certificate configured the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"), |
| 45 | (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` β the echoed name and the `student` role every fresh account gets β and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"), | 45 | (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` β the echoed name and the `student` role every fresh account gets β and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"), |
| 46 | (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner β nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed β or its name cleared β with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is a claimed job rather than an in-process task: whichever backend process holds a `chat.reply` worker picks it up (within ~200ms), dispatches it and stamps the result, so a restart no longer strands an accepted turn and a claim its owner never finishes is retried after 90 seconds. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) β both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` β the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"), | 46 | (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner β nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed β or its name cleared β with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is a claimed job rather than an in-process task: whichever backend process holds a `chat.reply` worker picks it up (within ~200ms), dispatches it and stamps the result, so a restart no longer strands an accepted turn and a claim its owner never finishes is retried after 90 seconds. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) β both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` β the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"), |
| 47 | - (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` β returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). Also the parentβstudent ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink β a role change on either side drops its ties), and a parent lists their own students at `/users/me/students`; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else"), | 47 | + (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` β returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). Also the parentβstudent ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink β a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else"), |
| 48 | (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete β at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"), | 48 | (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete β at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"), |
| 49 | (name = "messages", description = "One-to-one mail-style messages between any two users (parents included β messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread β with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), | 49 | (name = "messages", description = "One-to-one mail-style messages between any two users (parents included β messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread β with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), |
| 50 | (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00β10:30 and 10:30β11:00 are two slots and not a collision, and a weekly publish is all-or-nothing β one colliding occurrence refuses the whole series. Students and parents book one with a required reason β a parent books for themselves, this is the parent-teacher conference β and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked, an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel β declining included, since a decline *is* a cancel β only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) β visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"), | 50 | (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00β10:30 and 10:30β11:00 are two slots and not a collision, and a weekly publish is all-or-nothing β one colliding occurrence refuses the whole series. Students and parents book one with a required reason β a parent books for themselves, this is the parent-teacher conference β and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked, an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel β declining included, since a decline *is* a cancel β only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) β visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"), |
| 51 | - (name = "events", description = "Events with an audience (school-wide, one role, a course's enrollment, or a registration signup list β the expected-attendee roster; every event stays visible to all) and their attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"), | 51 | + (name = "events", description = "Calendar events and attendance. An event's `audience` is its expected-attendee roster, not a visibility wall: everyone sees every event. Aim it at the whole school, one role, a course's enrollment, a class section's (Εube) roster, or a hand-built registration list. Rosters resolve live, so role changes, (un)enrollments and class-roster changes move people in and out by themselves. Attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"), |
| 52 | (name = "courses", description = "Courses β kind `course` (a regular taught course), `study` (etΓΌt, a supervised study session), or `club` (kulΓΌp, a student club; same behavior, different label) β optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. Both rights are re-checked against the caller's live role on every request: `creator` is a historical column no demotion sweeps, so an account that falls below `teacher` keeps neither management nor deletion of a course it made (the course stays reachable to its assigned teachers and to manager+), and the course drops out of their `/courses`, `/exams` and `/homework` catalogs unless they are enrolled in it. A session's `teacher` column carries the same floor: teaching a session grants neither its roll call nor a view of it once the account falls below `teacher`. A roster is also filled in bulk by attaching the course to a class (see `classes`), which writes the same ordinary enrollment rows one at a time. A course with anyone still enrolled refuses deletion (409) β empty the roster first"), | 52 | (name = "courses", description = "Courses β kind `course` (a regular taught course), `study` (etΓΌt, a supervised study session), or `club` (kulΓΌp, a student club; same behavior, different label) β optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. Both rights are re-checked against the caller's live role on every request: `creator` is a historical column no demotion sweeps, so an account that falls below `teacher` keeps neither management nor deletion of a course it made (the course stays reachable to its assigned teachers and to manager+), and the course drops out of their `/courses`, `/exams` and `/homework` catalogs unless they are enrolled in it. A session's `teacher` column carries the same floor: teaching a session grants neither its roll call nor a view of it once the account falls below `teacher`. A roster is also filled in bulk by attaching the course to a class (see `classes`), which writes the same ordinary enrollment rows one at a time. A course with anyone still enrolled refuses deletion (409) β empty the roster first"), |
| 53 | - (name = "classes", description = "Class sections (Εube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership β adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class β the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept β and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent β the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sΔ±nΔ±f ΓΆΔretmeni) with `teacher_id` β any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role β staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole"), | 53 | + (name = "classes", description = "Class sections (Εube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership β adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class β the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept β and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent β the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sΔ±nΔ±f ΓΆΔretmeni) with `teacher_id` β any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role β staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole. A grade may also carry a **blueprint** (`/classes/blueprints`): the list of courses every section at that grade takes. Creating or editing one retro-pumps every class already at the grade, and does so best-effort β a section that cannot take a course (it is at its course ceiling, or the course has no free seat for the whole section) is skipped and returned in `skipped`, while every other section is still stocked, so a blueprint edit can leave a deliberately partial state. Dropping a course from a blueprint detaches it wherever the blueprint attached it (and deleting the blueprint drops its whole list), but a course a human attached to a class by hand carries no blueprint tag and always survives β the same absent-key rule that protects an individually placed enrollment. A blueprint names no term; the class names its own. The grade label is the blueprint's id, so there is exactly one per grade, and it must be non-empty and free of `/ \\ ? # %`"), |
| 54 | (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), | 54 | (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), |
| 55 | (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), | 55 | (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), |
| 56 | (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend β the backend records only focus stints"), | 56 | (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend β the backend records only focus stints"), |
| 57 | (name = "questions", description = "The school question pool. Students ask (`POST /questions`, optionally attaching one photo of the problem via `POST /questions/{id}/image` β raster types only, β€ the school's `max_file_bytes`, only while pending); teacher+ approve (`POST /questions/{id}/approve`) into the school-wide pool, or reject by deleting. Everyone student-and-up sees every approved question and may offer solutions under it (oldest first); parents stay out. Pending questions are visible only to their asker and to teacher+ (`GET /questions?status=pending` = the approval queue), and approval freezes title, body, and image β moderated content cannot be edited afterwards, only deleted (asker or teacher+; solutions and every image blob go with it). Solutions are the unmoderated half, so they never freeze: the author may edit the body (`PATCH /questions/{id}/solutions/{sid}` β author only, teacher+ included out; moderation stays delete-only) and attach/replace/remove one photo of the worked steps anytime (`/questions/{id}/solutions/{sid}/image`, same raster rules and size cap as the question's). Question rows carry a `solution_count`; solutions are deletable by their author or teacher+ (photo blob included)"), | 57 | (name = "questions", description = "The school question pool. Students ask (`POST /questions`, optionally attaching one photo of the problem via `POST /questions/{id}/image` β raster types only, β€ the school's `max_file_bytes`, only while pending); teacher+ approve (`POST /questions/{id}/approve`) into the school-wide pool, or reject by deleting. Everyone student-and-up sees every approved question and may offer solutions under it (oldest first); parents stay out. Pending questions are visible only to their asker and to teacher+ (`GET /questions?status=pending` = the approval queue), and approval freezes title, body, and image β moderated content cannot be edited afterwards, only deleted (asker or teacher+; solutions and every image blob go with it). Solutions are the unmoderated half, so they never freeze: the author may edit the body (`PATCH /questions/{id}/solutions/{sid}` β author only, teacher+ included out; moderation stays delete-only) and attach/replace/remove one photo of the worked steps anytime (`/questions/{id}/solutions/{sid}/image`, same raster rules and size cap as the question's). Question rows carry a `solution_count`; solutions are deletable by their author or teacher+ (photo blob included)"), |
| 58 | (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), and every one of those rights is re-checked against the caller's live role: `owner` is a historical column no demotion sweeps, so an account below `teacher` reads and edits nothing here, its own templates included; 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"), | 58 | (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), and every one of those rights is re-checked against the caller's live role: `owner` is a historical column no demotion sweeps, so an account below `teacher` reads and edits nothing here, its own templates included; 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"), |
| 59 | (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"), | 59 | (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"), |
| 60 | - (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"), | 60 | + (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). Those reads are refused (`409`) while the caller's own latest sitting on that exam is in progress, and a question sharing a question-bank template with a question in *another* exam the caller has a sitting open on comes back with `correct: null` β and with no correctness flag and no `auto_score` contribution on the answer sheet β since the bank copies `correct` into every instantiation. A question links to a template whichever way it got there, and both directions are matched: the template it was instantiated from (`from_bank`) and the one minted by saving it into the bank (`banked_as`), so a hand-written question that was saved to the bank and then instantiated elsewhere is hidden too. That redaction is per question, keyed on the template: the rest of the reviewed exam reads normally, a question with no bank link in either direction is never hidden, and the key comes back once the other sitting is submitted or expires. Known limit, accepted: deleting a template clears both columns on every question that pointed at it, so a pair whose template was since deleted keeps the identical `correct` with nothing left to join them by. 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"), |
| 61 | (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"), | 61 | (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"), |
| 62 | (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 `<target>_k_<key>` (`_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 `<line>_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"), | 62 | (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 `<target>_k_<key>` (`_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 `<line>_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"), |
| 63 | (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"), | 63 | (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"), |
| 64 | (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+"), | 64 | (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+"), |
| 65 | (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"), | 65 | (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"), |
| 66 | (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"), | 66 | (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"), |
| 67 | - (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. Every frame the room delivers is authorized against the database first, so a caller who loses the right to be there β taken off the roster, or demoted below `student` β is served no further content: they get one `error{code:\"forbidden\"}` naming which of the two happened, and the room closes. That is separate from a refused *command*: `clear` and `lock` by a non-creator answer `error{code:\"forbidden\"}` and deliberately keep the socket open, since a participant who clicked the wrong button has made a mistake, not left the room. A demotion to `parent` also sweeps that account off every board roster it was on, though a board whose *creator* was demoted is left standing β barred to them, unchanged for everyone else. 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"), | 67 | + (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. `GET /boards` takes `?open=true|false` to narrow the list by the closing stamp (`total` counts the filtered list) β a closed board is never deleted, so this is how a creator holding many boards trims the retired ones out of sight. It filters `closed_at` and nothing else: a **locked** board, and one that has spent its lifetime stroke budget but was never drawn on again, are both still open, because the stamp is written only by `/close` or by the append the lifetime cap refuses. 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. Every frame the room delivers is authorized against the database first, so a caller who loses the right to be there β taken off the roster, or demoted below `student` β is served no further content: they get one `error{code:\"forbidden\"}` naming which of the two happened, and the room closes. That is separate from a refused *command*: `clear` and `lock` by a non-creator answer `error{code:\"forbidden\"}` and deliberately keep the socket open, since a participant who clicked the wrong button has made a mistake, not left the room. A demotion below `student` also sweeps that account off every roster it was on, and the rosters an older binary left behind were repaired at boot: a board written before that sweep can name a parent, or a user since deleted, and every such id is stripped the first time this binary starts. A board whose *creator* was demoted is left standing β barred to them, unchanged for everyone else. 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 β drawn marks only, never a `clear` marker, exactly as the room's socket replays it, so the REST catch-up and the live canvas can never disagree, `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 and the **locked** one β the pause the creator set holds against their own clear too, so a locked board sitting at `max_epoch_strokes` is recovered by unlock, clear, relock β 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"), |
| 68 | (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+"), | 68 | (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+"), |
| 69 | ), | 69 | ), |
| 70 | )] | 70 | )] |
src/migration_sql.rsmodified+78 -0
| @@ -207,6 +207,7 @@ pub const MIGRATION: &str = " | |||
| 207 | DEFINE FIELD IF NOT EXISTS audience.kind ON event TYPE string; | 207 | DEFINE FIELD IF NOT EXISTS audience.kind ON event TYPE string; |
| 208 | DEFINE FIELD IF NOT EXISTS audience.role ON event TYPE option<string>; | 208 | DEFINE FIELD IF NOT EXISTS audience.role ON event TYPE option<string>; |
| 209 | DEFINE FIELD IF NOT EXISTS audience.course ON event TYPE option<record<course>>; | 209 | DEFINE FIELD IF NOT EXISTS audience.course ON event TYPE option<record<course>>; |
| 210 | + DEFINE FIELD IF NOT EXISTS audience.class ON event TYPE option<record<class_group>>; | ||
| 210 | DEFINE FIELD IF NOT EXISTS audience.capacity ON event TYPE option<int>; | 211 | DEFINE FIELD IF NOT EXISTS audience.capacity ON event TYPE option<int>; |
| 211 | -- Seats taken on the signup list, the stored capacity guard that closes | 212 | -- Seats taken on the signup list, the stored capacity guard that closes |
| 212 | -- write-skew between concurrent request tasks (see `crate::domain::cap`). | 213 | -- write-skew between concurrent request tasks (see `crate::domain::cap`). |
| @@ -276,6 +277,20 @@ pub const MIGRATION: &str = " | |||
| 276 | DEFINE FIELD IF NOT EXISTS teacher ON class_group TYPE option<record<user>>; | 277 | DEFINE FIELD IF NOT EXISTS teacher ON class_group TYPE option<record<user>>; |
| 277 | DEFINE FIELD IF NOT EXISTS class_member_count ON class_group TYPE option<int>; | 278 | DEFINE FIELD IF NOT EXISTS class_member_count ON class_group TYPE option<int>; |
| 278 | DEFINE FIELD IF NOT EXISTS class_course_count ON class_group TYPE option<int>; | 279 | DEFINE FIELD IF NOT EXISTS class_course_count ON class_group TYPE option<int>; |
| 280 | + -- Every class at one grade is what a blueprint pumps, so the grade label is | ||
| 281 | + -- that read's whole `WHERE`. | ||
| 282 | + DEFINE INDEX IF NOT EXISTS class_group_grade ON class_group FIELDS grade; | ||
| 283 | + | ||
| 284 | + -- A grade's course template: the courses every class section at that grade | ||
| 285 | + -- carries. The grade label *is* the record key, so a second blueprint for | ||
| 286 | + -- one grade cannot exist and no find-then-insert has to race for it (the shape | ||
| 287 | + -- `menu` uses for its date+slot). It holds no term β the class names its | ||
| 288 | + -- own β and `courses` carries no DEFAULT: a defaulted array on a SCHEMAFULL | ||
| 289 | + -- row is what broke every settings PATCH. | ||
| 290 | + DEFINE TABLE IF NOT EXISTS class_blueprint SCHEMAFULL; | ||
| 291 | + DEFINE FIELD IF NOT EXISTS grade ON class_blueprint TYPE string; | ||
| 292 | + DEFINE FIELD IF NOT EXISTS courses ON class_blueprint TYPE array<record<course>>; | ||
| 293 | + DEFINE FIELD IF NOT EXISTS creator ON class_blueprint TYPE record<user>; | ||
| 279 | 294 | ||
| 280 | DEFINE TABLE IF NOT EXISTS class_member SCHEMAFULL; | 295 | DEFINE TABLE IF NOT EXISTS class_member SCHEMAFULL; |
| 281 | DEFINE FIELD IF NOT EXISTS class ON class_member TYPE record<class_group>; | 296 | DEFINE FIELD IF NOT EXISTS class ON class_member TYPE record<class_group>; |
| @@ -300,6 +315,16 @@ pub const MIGRATION: &str = " | |||
| 300 | -- The mirror of `class_member.added_at`, for the same reason: without it | 315 | -- The mirror of `class_member.added_at`, for the same reason: without it |
| 301 | -- the course list is ordered by the *course's* ULID. | 316 | -- the course list is ordered by the *course's* ULID. |
| 302 | DEFINE FIELD IF NOT EXISTS attached_at ON class_course TYPE option<int>; | 317 | DEFINE FIELD IF NOT EXISTS attached_at ON class_course TYPE option<int>; |
| 318 | + -- The blueprint that attached this course, absent when a human attached it | ||
| 319 | + -- by hand β the same shape, and the same meaning, as `enrollment.source` | ||
| 320 | + -- one table down. The line is not optional bookkeeping: `class_course` is | ||
| 321 | + -- SCHEMAFULL with a definition per key, so an undefined column is silently | ||
| 322 | + -- stripped on write and a blueprint could never take back what it placed. | ||
| 323 | + -- Absence *is* the meaning, so there is nothing to backfill: a row written | ||
| 324 | + -- before this column reads back as hand-attached, and `source = $blueprint` | ||
| 325 | + -- is false for an absent key, which is what keeps a hand-attached course | ||
| 326 | + -- unreachable by every blueprint sweep. | ||
| 327 | + DEFINE FIELD IF NOT EXISTS source ON class_course TYPE option<record<class_blueprint>>; | ||
| 303 | DEFINE INDEX IF NOT EXISTS class_course_class_course ON class_course FIELDS class, course UNIQUE; | 328 | DEFINE INDEX IF NOT EXISTS class_course_class_course ON class_course FIELDS class, course UNIQUE; |
| 304 | DEFINE INDEX IF NOT EXISTS class_course_class ON class_course FIELDS class; | 329 | DEFINE INDEX IF NOT EXISTS class_course_class ON class_course FIELDS class; |
| 305 | DEFINE INDEX IF NOT EXISTS class_course_course ON class_course FIELDS course; | 330 | DEFINE INDEX IF NOT EXISTS class_course_course ON class_course FIELDS course; |
| @@ -796,6 +821,18 @@ pub const MIGRATION: &str = " | |||
| 796 | DEFINE TABLE IF NOT EXISTS slot_ref SCHEMAFULL; | 821 | DEFINE TABLE IF NOT EXISTS slot_ref SCHEMAFULL; |
| 797 | DEFINE FIELD IF NOT EXISTS count ON slot_ref TYPE option<int>; | 822 | DEFINE FIELD IF NOT EXISTS count ON slot_ref TYPE option<int>; |
| 798 | DEFINE FIELD IF NOT EXISTS retired ON slot_ref TYPE option<bool>; | 823 | DEFINE FIELD IF NOT EXISTS retired ON slot_ref TYPE option<bool>; |
| 824 | + | ||
| 825 | + -- One row per backfill that is genuinely *one-time*, keyed by the backfill's | ||
| 826 | + -- own name (2026-08-02). Most of `BACKFILL` is a `WHERE` that matches no row | ||
| 827 | + -- once it has converged, so re-running it is free β but a repair whose cost | ||
| 828 | + -- is the *scan* rather than the write pays that cost on every boot forever, | ||
| 829 | + -- and the board-roster sweep's scan is one full `user` pass per board. A | ||
| 830 | + -- marker row is the smallest thing that can say 'this one is finished': the | ||
| 831 | + -- boot loop carries no lock and no fingerprint any more (2026-07-30), so | ||
| 832 | + -- there is nowhere else for that fact to live. A database that never ran the | ||
| 833 | + -- repair holds no row and runs it; the row is written by the same query. | ||
| 834 | + DEFINE TABLE IF NOT EXISTS migration_mark SCHEMAFULL; | ||
| 835 | + DEFINE FIELD IF NOT EXISTS done_at ON migration_mark TYPE int; | ||
| 799 | "; | 836 | "; |
| 800 | 837 | ||
| 801 | /// Data backfills for rows written by older binaries. Runs *after* (and apart | 838 | /// Data backfills for rows written by older binaries. Runs *after* (and apart |
| @@ -1086,6 +1123,47 @@ pub const BACKFILL: &str = " | |||
| 1086 | FOR $row IN ((SELECT board, count() AS n FROM board_stroke GROUP BY board) ?? []) { | 1123 | FOR $row IN ((SELECT board, count() AS n FROM board_stroke GROUP BY board) ?? []) { |
| 1087 | UPDATE $row.board SET total_stroke_count = $row.n WHERE total_stroke_count != $row.n; | 1124 | UPDATE $row.board SET total_stroke_count = $row.n WHERE total_stroke_count != $row.n; |
| 1088 | }; | 1125 | }; |
| 1126 | + | ||
| 1127 | + -- Board rosters became self-repairing (2026-08-02). `set_role` sweeps a | ||
| 1128 | + -- demoted user off every board *going forward*, but a volume written before | ||
| 1129 | + -- that sweep still holds rosters naming parents β and ids of users who have | ||
| 1130 | + -- since been deleted outright, which no sweep ever covered. | ||
| 1131 | + -- | ||
| 1132 | + -- It is not a cosmetic staleness: the roster is served back on every read | ||
| 1133 | + -- and `resolve_participants` refuses an id that no longer resolves to a | ||
| 1134 | + -- student-or-above, so the creator's next read-modify-write roster PATCH | ||
| 1135 | + -- echoes the stale id and takes a 400 β the board's invite list is frozen | ||
| 1136 | + -- until the row is repaired. | ||
| 1137 | + -- | ||
| 1138 | + -- `parent` is the only role below `student` (domain::role), so `!= 'parent'` | ||
| 1139 | + -- is the same cut `Role::at_least(Student)` makes; a missing user matches no | ||
| 1140 | + -- row and so falls out of `$keep` for free. A board whose whole roster is | ||
| 1141 | + -- stale ends with `participants = []` β the creator alone on it, which is | ||
| 1142 | + -- the same shape a board created without invites carries. Not `= NONE` | ||
| 1143 | + -- guarded and it need not be: `$keep` is derived from the rows that exist, | ||
| 1144 | + -- so it converges, and `WHERE participants != $keep` writes nothing on the | ||
| 1145 | + -- next boot. `$keep` comes back deduped and in record-id order, so a | ||
| 1146 | + -- repaired row can be *reordered* relative to what it stored, never | ||
| 1147 | + -- duplicated β and the roster is a set to every reader. | ||
| 1148 | + -- | ||
| 1149 | + -- Marked one-time (`migration_mark`), unlike every backfill above it. Those | ||
| 1150 | + -- converge to a `WHERE` that matches nothing, so their second run is a cheap | ||
| 1151 | + -- index probe; this one's cost is the *scan* β a `board` table scan whose | ||
| 1152 | + -- body runs a full `user` scan per row, measured at 773ms for 300 boards | ||
| 1153 | + -- over 2000 users on a boot with nothing left to write. That is paid on | ||
| 1154 | + -- every restart forever, and it buys nothing: `set_role` sweeps rosters | ||
| 1155 | + -- going forward and a deleted user is swept with its row, so no new stale id | ||
| 1156 | + -- is ever created. The mark is written *after* the loop and in the same | ||
| 1157 | + -- statement batch, so a boot killed mid-repair writes no mark and the next | ||
| 1158 | + -- one redoes the whole sweep β which is free, because the sweep is | ||
| 1159 | + -- idempotent. `UPSERT`, not `CREATE`: re-marking must never be an error. | ||
| 1160 | + IF array::len((SELECT VALUE id FROM migration_mark:board_roster)) = 0 { | ||
| 1161 | + FOR $row IN ((SELECT id, participants FROM board WHERE array::len(participants ?? []) > 0) ?? []) { | ||
| 1162 | + LET $keep = (SELECT VALUE id FROM user WHERE id IN $row.participants AND role != 'parent'); | ||
| 1163 | + UPDATE $row.id SET participants = $keep WHERE participants != $keep; | ||
| 1164 | + }; | ||
| 1165 | + UPSERT migration_mark:board_roster SET done_at = time::unix(time::now()) * 1000; | ||
| 1166 | + }; | ||
| 1089 | "; | 1167 | "; |
| 1090 | 1168 | ||
| 1091 | /// The migration batches, in the order a boot applies them β and the *only* | 1169 | /// The migration batches, in the order a boot applies them β and the *only* |
src/rate_limit.rsmodified+53 -10
| @@ -37,10 +37,28 @@ | |||
| 37 | //! Exhausted buckets are exempt from eviction: they are the only ones actually | 37 | //! Exhausted buckets are exempt from eviction: they are the only ones actually |
| 38 | //! refusing anyone, and freeing one *raises* the limit for a client that had | 38 | //! refusing anyone, and freeing one *raises* the limit for a client that had |
| 39 | //! reached it. When every bucket is exhausted there is nothing to evict and | 39 | //! reached it. When every bucket is exhausted there is nothing to evict and |
| 40 | -//! the map stays at the cap; the unknown key is then admitted without a bucket | 40 | +//! the map stays at the cap; the unknown key is then metered against one shared |
| 41 | -//! rather than refused, which concedes that a new client is unmetered while | 41 | +//! overflow counter ([`crate::constant::RATE_LIMIT_OVERFLOW_MAX`] per window, |
| 42 | -//! the map is saturated but keeps an attacker from `429`-ing everyone at once | 42 | +//! for every keyless client together) instead of getting a bucket. |
| 43 | -//! simply by filling it. | 43 | +//! |
| 44 | +//! Be precise about what that buys, because it is not everyone. A client | ||
| 45 | +//! **already in the map** keeps its own counter throughout: no flood can starve | ||
| 46 | +//! it, evict it, or spend its budget, which is the property worth having. | ||
| 47 | +//! A **newcomer during** the flood is a different story β it never gets a | ||
| 48 | +//! bucket while the map stays saturated, so *all* of its traffic (not just its | ||
| 49 | +//! first request) comes out of the one shared budget, and once that budget is | ||
| 50 | +//! spent every further newcomer is refused. An attacker who first fills the map | ||
| 51 | +//! and then burns the shared budget therefore does `429` every newcomer for the | ||
| 52 | +//! rest of the window; `tests/rate_limit.rs` asserts exactly that, ending on a | ||
| 53 | +//! refused `newcomer-last`. | ||
| 54 | +//! | ||
| 55 | +//! That is the accepted trade, not an oversight. The alternative β admitting | ||
| 56 | +//! keyless clients freely β makes a filled map the way to buy unmetered | ||
| 57 | +//! throughput from fresh keys, which is an unbounded bypass rather than a | ||
| 58 | +//! bounded outage, and refusing them outright would hand the attacker the same | ||
| 59 | +//! `429`-the-newcomers result for free. The shared budget costs an attacker the | ||
| 60 | +//! flood *plus* [`crate::constant::RATE_LIMIT_OVERFLOW_MAX`] requests a minute, | ||
| 61 | +//! every minute, to keep it going. | ||
| 44 | //! | 62 | //! |
| 45 | //! # The shared window | 63 | //! # The shared window |
| 46 | //! | 64 | //! |
| @@ -75,7 +93,8 @@ use surrealdb::types::RecordId; | |||
| 75 | use tokio::time::Instant; | 93 | use tokio::time::Instant; |
| 76 | 94 | ||
| 77 | use crate::constant::{ | 95 | use crate::constant::{ |
| 78 | - PURGE_AT, RATE_LIMIT_TABLE, RATE_SYNC_INTERVAL_SECS, RATE_SYNC_MAX_KEYS, RATE_SYNC_TIMEOUT_SECS, | 96 | + PURGE_AT, RATE_LIMIT_OVERFLOW_MAX, RATE_LIMIT_TABLE, RATE_SYNC_INTERVAL_SECS, |
| 97 | + RATE_SYNC_MAX_KEYS, RATE_SYNC_TIMEOUT_SECS, | ||
| 79 | }; | 98 | }; |
| 80 | use crate::database::Database; | 99 | use crate::database::Database; |
| 81 | use crate::domain::timestamp::Timestamp; | 100 | use crate::domain::timestamp::Timestamp; |
| @@ -117,6 +136,10 @@ pub struct RateLimiter<K = IpAddr> { | |||
| 117 | /// Only meaningful for the IP tiers; the keyed tiers never look at it. | 136 | /// Only meaningful for the IP tiers; the keyed tiers never look at it. |
| 118 | trust_proxy: bool, | 137 | trust_proxy: bool, |
| 119 | buckets: Arc<Mutex<HashMap<K, Bucket>>>, | 138 | buckets: Arc<Mutex<HashMap<K, Bucket>>>, |
| 139 | + /// The single bucket every client shares once the map is saturated and no | ||
| 140 | + /// eviction is allowed (see the module docs). Local only: it is keyless, so | ||
| 141 | + /// it is never synced to the shared table. | ||
| 142 | + overflow: Arc<Mutex<Bucket>>, | ||
| 120 | } | 143 | } |
| 121 | 144 | ||
| 122 | struct Bucket { | 145 | struct Bucket { |
| @@ -225,7 +248,24 @@ impl<K: Eq + Hash> RateLimiter<K> { | |||
| 225 | window: Duration::from_secs(60), | 248 | window: Duration::from_secs(60), |
| 226 | trust_proxy, | 249 | trust_proxy, |
| 227 | buckets: Arc::new(Mutex::new(HashMap::new())), | 250 | buckets: Arc::new(Mutex::new(HashMap::new())), |
| 251 | + overflow: Arc::new(Mutex::new(Bucket::opened_at(Instant::now()))), | ||
| 252 | + } | ||
| 253 | + } | ||
| 254 | + | ||
| 255 | + /// Meter one keyless request against the shared overflow budget. Same fixed | ||
| 256 | + /// window as a real bucket, one counter for everyone who lands here. | ||
| 257 | + fn check_overflow(&self, now: Instant) -> Result<(), u64> { | ||
| 258 | + let mut bucket = self.overflow.lock().expect("rate limiter mutex poisoned"); | ||
| 259 | + if now.duration_since(bucket.window_start) >= self.window { | ||
| 260 | + *bucket = Bucket::opened_at(now); | ||
| 261 | + } | ||
| 262 | + // `count` and not `spent()`: nothing shared ever reaches this bucket. | ||
| 263 | + if bucket.count < RATE_LIMIT_OVERFLOW_MAX { | ||
| 264 | + bucket.count += 1; | ||
| 265 | + return Ok(()); | ||
| 228 | } | 266 | } |
| 267 | + let remaining = self.window - now.duration_since(bucket.window_start); | ||
| 268 | + Err((remaining.as_secs_f64().ceil() as u64).max(1)) | ||
| 229 | } | 269 | } |
| 230 | 270 | ||
| 231 | /// Count one request from `key`. `Err` carries the whole seconds (rounded | 271 | /// Count one request from `key`. `Err` carries the whole seconds (rounded |
| @@ -253,11 +293,14 @@ impl<K: Eq + Hash> RateLimiter<K> { | |||
| 253 | evict_cheapest(&mut buckets, PURGE_AT - PURGE_AT / 4, self.max); | 293 | evict_cheapest(&mut buckets, PURGE_AT - PURGE_AT / 4, self.max); |
| 254 | } | 294 | } |
| 255 | if buckets.len() >= PURGE_AT { | 295 | if buckets.len() >= PURGE_AT { |
| 256 | - // Every bucket left is exhausted and none may be dropped. Admit | 296 | + // Every bucket left is exhausted and none may be dropped. This |
| 257 | - // this unknown key without a bucket rather than refuse it: an | 297 | + // key gets no bucket, but it is still metered: everyone in that |
| 258 | - // attacker who can saturate the map must not be able to 429 the | 298 | + // position shares one aggregate counter. Refusing outright |
| 259 | - // world, and every client already in the map keeps its counter. | 299 | + // would 429 every newcomer for free; admitting freely would |
| 260 | - return Ok(()); | 300 | + // make a saturated map the bypass. Clients already in the map |
| 301 | + // are untouched either way (see the module docs). | ||
| 302 | + drop(buckets); | ||
| 303 | + return self.check_overflow(now); | ||
| 261 | } | 304 | } |
| 262 | } | 305 | } |
| 263 | 306 | ||
src/web/appointments.rsmodified+8 -2
| @@ -310,6 +310,7 @@ async fn for_decision( | |||
| 310 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 310 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 311 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 311 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 312 | (status = 409, description = "The window overlaps one the caller has already published, or (weekly) two occurrences overlap each other β the whole publish is refused, nothing is written", body = ErrorResponse), | 312 | (status = 409, description = "The window overlaps one the caller has already published, or (weekly) two occurrences overlap each other β the whole publish is refused, nothing is written", body = ErrorResponse), |
| 313 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 313 | ), | 314 | ), |
| 314 | )] | 315 | )] |
| 315 | async fn publish_slots( | 316 | async fn publish_slots( |
| @@ -508,6 +509,7 @@ async fn delete_slot_series( | |||
| 508 | (status = 403, description = "Only students and parents book appointments", body = ErrorResponse), | 509 | (status = 403, description = "Only students and parents book appointments", body = ErrorResponse), |
| 509 | (status = 404, description = "Slot not found", body = ErrorResponse), | 510 | (status = 404, description = "Slot not found", body = ErrorResponse), |
| 510 | (status = 409, description = "The slot has started or is taken, the requester is busy, or its teacher is no longer staff", body = ErrorResponse), | 511 | (status = 409, description = "The slot has started or is taken, the requester is busy, or its teacher is no longer staff", body = ErrorResponse), |
| 512 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 511 | ), | 513 | ), |
| 512 | )] | 514 | )] |
| 513 | async fn book( | 515 | async fn book( |
| @@ -628,6 +630,7 @@ async fn approve( | |||
| 628 | (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse), | 630 | (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse), |
| 629 | (status = 404, description = "Not found", body = ErrorResponse), | 631 | (status = 404, description = "Not found", body = ErrorResponse), |
| 630 | (status = 409, description = "No longer pending", body = ErrorResponse), | 632 | (status = 409, description = "No longer pending", body = ErrorResponse), |
| 633 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 631 | ), | 634 | ), |
| 632 | )] | 635 | )] |
| 633 | async fn reject( | 636 | async fn reject( |
| @@ -670,6 +673,7 @@ async fn reject( | |||
| 670 | (status = 403, description = "Not the requester", body = ErrorResponse), | 673 | (status = 403, description = "Not the requester", body = ErrorResponse), |
| 671 | (status = 404, description = "Not found", body = ErrorResponse), | 674 | (status = 404, description = "Not found", body = ErrorResponse), |
| 672 | (status = 409, description = "Already settled, or the appointment has already started", body = ErrorResponse), | 675 | (status = 409, description = "Already settled, or the appointment has already started", body = ErrorResponse), |
| 676 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 673 | ), | 677 | ), |
| 674 | )] | 678 | )] |
| 675 | async fn cancel( | 679 | async fn cancel( |
| @@ -729,6 +733,7 @@ async fn cancel( | |||
| 729 | (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse), | 733 | (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse), |
| 730 | (status = 404, description = "Not found", body = ErrorResponse), | 734 | (status = 404, description = "Not found", body = ErrorResponse), |
| 731 | (status = 409, description = "The appointment is already settled, or the proposed window has already started", body = ErrorResponse), | 735 | (status = 409, description = "The appointment is already settled, or the proposed window has already started", body = ErrorResponse), |
| 736 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 732 | ), | 737 | ), |
| 733 | )] | 738 | )] |
| 734 | async fn reschedule( | 739 | async fn reschedule( |
| @@ -775,6 +780,7 @@ async fn reschedule( | |||
| 775 | (status = 403, description = "Not the requester", body = ErrorResponse), | 780 | (status = 403, description = "Not the requester", body = ErrorResponse), |
| 776 | (status = 404, description = "Not found", body = ErrorResponse), | 781 | (status = 404, description = "Not found", body = ErrorResponse), |
| 777 | (status = 409, description = "No time has been proposed, the proposal has since changed (re-read it), the booking is no longer pending, the proposed time has already started, or it collides with another approved appointment", body = ErrorResponse), | 782 | (status = 409, description = "No time has been proposed, the proposal has since changed (re-read it), the booking is no longer pending, the proposed time has already started, or it collides with another approved appointment", body = ErrorResponse), |
| 783 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 778 | ), | 784 | ), |
| 779 | )] | 785 | )] |
| 780 | async fn accept_reschedule( | 786 | async fn accept_reschedule( |
| @@ -866,7 +872,7 @@ mod tests { | |||
| 866 | let user = User::create(Username::try_new(username).unwrap(), hash, db) | 872 | let user = User::create(Username::try_new(username).unwrap(), hash, db) |
| 867 | .await | 873 | .await |
| 868 | .unwrap(); | 874 | .unwrap(); |
| 869 | - user.set_role(role, db).await.unwrap() | 875 | + user.set_role(role, db).await.unwrap().0 |
| 870 | } | 876 | } |
| 871 | 877 | ||
| 872 | /// All five `can_manage` sites are `RequireTeacher` today, so this is | 878 | /// All five `can_manage` sites are `RequireTeacher` today, so this is |
| @@ -888,7 +894,7 @@ mod tests { | |||
| 888 | assert!(can_manage(&slot, &owner)); | 894 | assert!(can_manage(&slot, &owner)); |
| 889 | 895 | ||
| 890 | for role in [Role::Student, Role::Parent] { | 896 | for role in [Role::Student, Role::Parent] { |
| 891 | - let demoted = owner.clone().set_role(role, &db).await.unwrap(); | 897 | + let demoted = owner.clone().set_role(role, &db).await.unwrap().0; |
| 892 | assert!( | 898 | assert!( |
| 893 | !can_manage(&slot, &demoted), | 899 | !can_manage(&slot, &demoted), |
| 894 | "{role:?} slot owner still decides its bookings" | 900 | "{role:?} slot owner still decides its bookings" |
src/web/auth.rsmodified+2 -0
| @@ -82,6 +82,7 @@ struct RegisterResponse { | |||
| 82 | (status = 201, description = "Account created, or the username was already taken β deliberately indistinguishable. Carries no `id`: on the taken path there is no row to name, so log in to learn who you are", body = RegisterResponse), | 82 | (status = 201, description = "Account created, or the username was already taken β deliberately indistinguishable. Carries no `id`: on the taken path there is no row to name, so log in to learn who you are", body = RegisterResponse), |
| 83 | (status = 400, description = "Invalid username or password", body = ErrorResponse), | 83 | (status = 400, description = "Invalid username or password", body = ErrorResponse), |
| 84 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), | 84 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), |
| 85 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 85 | ), | 86 | ), |
| 86 | )] | 87 | )] |
| 87 | async fn register( | 88 | async fn register( |
| @@ -135,6 +136,7 @@ async fn register( | |||
| 135 | (status = 200, description = "Logged in; session cookie set", body = UserResponse), | 136 | (status = 200, description = "Logged in; session cookie set", body = UserResponse), |
| 136 | (status = 401, description = "Bad credentials", body = ErrorResponse), | 137 | (status = 401, description = "Bad credentials", body = ErrorResponse), |
| 137 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), | 138 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), |
| 139 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 138 | ), | 140 | ), |
| 139 | )] | 141 | )] |
| 140 | async fn login( | 142 | async fn login( |
src/web/bank_questions.rsmodified+4 -2
| @@ -437,6 +437,7 @@ pub(crate) async fn store_image( | |||
| 437 | (status = 400, description = "Invalid text, kind, points, choices, or correct β or an unknown subject", body = ErrorResponse), | 437 | (status = 400, description = "Invalid text, kind, points, choices, or correct β or an unknown subject", body = ErrorResponse), |
| 438 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 438 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 439 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 439 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 440 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 440 | ), | 441 | ), |
| 441 | )] | 442 | )] |
| 442 | async fn create_question( | 443 | async fn create_question( |
| @@ -625,6 +626,7 @@ async fn get_question( | |||
| 625 | (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse), | 626 | (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse), |
| 626 | (status = 404, description = "No such template", body = ErrorResponse), | 627 | (status = 404, description = "No such template", body = ErrorResponse), |
| 627 | (status = 409, description = "The template kept changing under concurrent edits β retry", body = ErrorResponse), | 628 | (status = 409, description = "The template kept changing under concurrent edits β retry", body = ErrorResponse), |
| 629 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 628 | ), | 630 | ), |
| 629 | )] | 631 | )] |
| 630 | async fn update_question( | 632 | async fn update_question( |
| @@ -947,7 +949,7 @@ mod tests { | |||
| 947 | let user = User::create(Username::try_new(username).unwrap(), hash, db) | 949 | let user = User::create(Username::try_new(username).unwrap(), hash, db) |
| 948 | .await | 950 | .await |
| 949 | .unwrap(); | 951 | .unwrap(); |
| 950 | - user.set_role(role, db).await.unwrap() | 952 | + user.set_role(role, db).await.unwrap().0 |
| 951 | } | 953 | } |
| 952 | 954 | ||
| 953 | /// Every bank route is `RequireTeacher` today, so this is pinned at the | 955 | /// Every bank route is `RequireTeacher` today, so this is pinned at the |
| @@ -973,7 +975,7 @@ mod tests { | |||
| 973 | assert!(ensure_owner(&question, &owner).is_ok()); | 975 | assert!(ensure_owner(&question, &owner).is_ok()); |
| 974 | 976 | ||
| 975 | for role in [Role::Student, Role::Parent] { | 977 | for role in [Role::Student, Role::Parent] { |
| 976 | - let demoted = owner.clone().set_role(role, &db).await.unwrap(); | 978 | + let demoted = owner.clone().set_role(role, &db).await.unwrap().0; |
| 977 | assert!( | 979 | assert!( |
| 978 | !can_see(&question, &demoted), | 980 | !can_see(&question, &demoted), |
| 979 | "{role:?} owner still reads their template" | 981 | "{role:?} owner still reads their template" |
src/web/boards.rsmodified+59 -17
| @@ -93,8 +93,17 @@ fn ensure_creator(board: &Board, user: &User) -> Result<(), AppError> { | |||
| 93 | /// | 93 | /// |
| 94 | /// The creator is a participant by construction, so they are neither injected | 94 | /// The creator is a participant by construction, so they are neither injected |
| 95 | /// into the list nor rejected from it. | 95 | /// into the list nor rejected from it. |
| 96 | +/// | ||
| 97 | +/// `current` is the board's roster as it stands (empty when a board is being | ||
| 98 | +/// created), and it is what makes a read-modify-write PATCH survive: an id | ||
| 99 | +/// *already* on the board that no longer qualifies β demoted, or deleted | ||
| 100 | +/// outright β is dropped silently instead of failing the whole call, so a | ||
| 101 | +/// creator echoing back the roster they were just served gets a 200 and a | ||
| 102 | +/// cleaned list. An id that is **new** to the board still 400s; without that | ||
| 103 | +/// split the drop would be a hole letting a caller seed a roster with anyone. | ||
| 96 | async fn resolve_participants( | 104 | async fn resolve_participants( |
| 97 | ids: Option<Vec<String>>, | 105 | ids: Option<Vec<String>>, |
| 106 | + current: &[UserId], | ||
| 98 | db: &Database, | 107 | db: &Database, |
| 99 | ) -> Result<Vec<UserId>, AppError> { | 108 | ) -> Result<Vec<UserId>, AppError> { |
| 100 | let Some(mut ids) = ids else { | 109 | let Some(mut ids) = ids else { |
| @@ -114,6 +123,9 @@ async fn resolve_participants( | |||
| 114 | let user = UserId::from_key(&id); | 123 | let user = UserId::from_key(&id); |
| 115 | let found = User::read(&user, db).await?; | 124 | let found = User::read(&user, db).await?; |
| 116 | if !found.is_some_and(|found| found.get_role().at_least(Role::Student)) { | 125 | if !found.is_some_and(|found| found.get_role().at_least(Role::Student)) { |
| 126 | + if current.contains(&user) { | ||
| 127 | + continue; | ||
| 128 | + } | ||
| 117 | return Err(AppError::Validation(ValidationError::Invalid { | 129 | return Err(AppError::Validation(ValidationError::Invalid { |
| 118 | field: "participants", | 130 | field: "participants", |
| 119 | reason: "every participant must be an existing user of at least the student role", | 131 | reason: "every participant must be an existing user of at least the student role", |
| @@ -239,7 +251,7 @@ struct CreateBoard { | |||
| 239 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 251 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 240 | (status = 403, description = "The caller is a parent", body = ErrorResponse), | 252 | (status = 403, description = "The caller is a parent", body = ErrorResponse), |
| 241 | (status = 409, description = "The caller already holds the maximum number of boards", body = ErrorResponse), | 253 | (status = 409, description = "The caller already holds the maximum number of boards", body = ErrorResponse), |
| 242 | - (status = 422, description = "The body carries a key this request does not accept β a board response cannot be posted back verbatim"), | 254 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, a required field is missing, or it carries a key this request does not accept β a board response cannot be posted back verbatim"), |
| 243 | ), | 255 | ), |
| 244 | )] | 256 | )] |
| 245 | async fn create_board( | 257 | async fn create_board( |
| @@ -248,20 +260,35 @@ async fn create_board( | |||
| 248 | Json(req): Json<CreateBoard>, | 260 | Json(req): Json<CreateBoard>, |
| 249 | ) -> Result<(StatusCode, Json<BoardResponse>), AppError> { | 261 | ) -> Result<(StatusCode, Json<BoardResponse>), AppError> { |
| 250 | let title = BoardTitle::try_new(&req.title)?; | 262 | let title = BoardTitle::try_new(&req.title)?; |
| 251 | - let participants = resolve_participants(req.participants, &st.db).await?; | 263 | + // No roster yet, so nothing is grandfathered: every id must qualify. |
| 264 | + let participants = resolve_participants(req.participants, &[], &st.db).await?; | ||
| 252 | let board = Board::create(user.get_id(), title, participants, &st.db).await?; | 265 | let board = Board::create(user.get_id(), title, participants, &st.db).await?; |
| 253 | Ok((StatusCode::CREATED, Json(BoardResponse::new(&board)))) | 266 | Ok((StatusCode::CREATED, Json(BoardResponse::new(&board)))) |
| 254 | } | 267 | } |
| 255 | 268 | ||
| 269 | +#[derive(Deserialize, utoipa::IntoParams)] | ||
| 270 | +struct ListFilter { | ||
| 271 | + /// Narrow by `closed_at`: `true` = still open, `false` = closed only. Omit | ||
| 272 | + /// for both. A closed board is never deleted, so this is how a heavy | ||
| 273 | + /// creator trims a list of retired boards. | ||
| 274 | + open: Option<bool>, | ||
| 275 | +} | ||
| 276 | + | ||
| 256 | /// Every board the caller may open β the ones they created and the ones they | 277 | /// Every board the caller may open β the ones they created and the ones they |
| 257 | -/// were invited to β newest first. Paged via `?limit=&offset=` (omit `limit` | 278 | +/// were invited to β newest first. `?open=` narrows by the closed flag, and |
| 279 | +/// `total` counts the filtered list. Paged via `?limit=&offset=` (omit `limit` | ||
| 258 | /// for all of them). | 280 | /// for all of them). |
| 281 | +/// | ||
| 282 | +/// `?open=true` means "not closed", nothing more: a **locked** board, and one | ||
| 283 | +/// that has spent its lifetime stroke budget but was never drawn on again, are | ||
| 284 | +/// both still open β the closing stamp is only ever written by `/close` or by | ||
| 285 | +/// the append that the lifetime cap refuses. | ||
| 259 | #[utoipa::path( | 286 | #[utoipa::path( |
| 260 | get, | 287 | get, |
| 261 | path = "/", | 288 | path = "/", |
| 262 | tag = "boards", | 289 | tag = "boards", |
| 263 | security(("session_cookie" = [])), | 290 | security(("session_cookie" = [])), |
| 264 | - params(PageParams), | 291 | + params(ListFilter, PageParams), |
| 265 | responses( | 292 | responses( |
| 266 | (status = 200, description = "A page of the caller's boards", body = Page<BoardResponse>), | 293 | (status = 200, description = "A page of the caller's boards", body = Page<BoardResponse>), |
| 267 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), | 294 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| @@ -272,10 +299,12 @@ async fn create_board( | |||
| 272 | async fn list_boards( | 299 | async fn list_boards( |
| 273 | State(st): State<AppState>, | 300 | State(st): State<AppState>, |
| 274 | RequireStudent(user): RequireStudent, | 301 | RequireStudent(user): RequireStudent, |
| 302 | + Query(filter): Query<ListFilter>, | ||
| 275 | Query(page): Query<PageParams>, | 303 | Query(page): Query<PageParams>, |
| 276 | ) -> Result<Json<Page<BoardResponse>>, AppError> { | 304 | ) -> Result<Json<Page<BoardResponse>>, AppError> { |
| 277 | let (limit, offset) = page.resolve()?; | 305 | let (limit, offset) = page.resolve()?; |
| 278 | - let (boards, total) = Board::list_for_user(user.get_id(), limit, offset, &st.db).await?; | 306 | + let (boards, total) = |
| 307 | + Board::list_for_user(user.get_id(), filter.open, limit, offset, &st.db).await?; | ||
| 279 | let items = boards.iter().map(BoardResponse::new).collect(); | 308 | let items = boards.iter().map(BoardResponse::new).collect(); |
| 280 | Ok(Json(Page::new(items, total, limit, offset))) | 309 | Ok(Json(Page::new(items, total, limit, offset))) |
| 281 | } | 310 | } |
| @@ -306,7 +335,9 @@ async fn get_board( | |||
| 306 | 335 | ||
| 307 | /// The live canvas: the current epoch's strokes, oldest first, paged via | 336 | /// The live canvas: the current epoch's strokes, oldest first, paged via |
| 308 | /// `?limit=&offset=`. This is what a client draws to catch up β earlier epochs | 337 | /// `?limit=&offset=`. This is what a client draws to catch up β earlier epochs |
| 309 | -/// are still stored, and read through `/history`. | 338 | +/// are still stored, and read through `/history`. Drawn marks only: a `clear` |
| 339 | +/// marker never appears here, exactly as it never appears on the board room's | ||
| 340 | +/// socket. Read `/history` or `/epochs` for the markers. | ||
| 310 | #[utoipa::path( | 341 | #[utoipa::path( |
| 311 | get, | 342 | get, |
| 312 | path = "/{id}/strokes", | 343 | path = "/{id}/strokes", |
| @@ -328,12 +359,16 @@ async fn list_strokes( | |||
| 328 | ) -> Result<Json<Page<StrokeResponse>>, AppError> { | 359 | ) -> Result<Json<Page<StrokeResponse>>, AppError> { |
| 329 | let (limit, offset) = page.resolve()?; | 360 | let (limit, offset) = page.resolve()?; |
| 330 | let board = board_for(&id, &user, &st.db).await?; | 361 | let board = board_for(&id, &user, &st.db).await?; |
| 331 | - // The current epoch has no `clear` marker yet β a marker is written with | 362 | + // The current epoch holds no `clear` marker β a marker is written with the |
| 332 | - // the epoch it *closed* β so scoping history to it is exactly the live | 363 | + // epoch it *closed* β so scoping history to it is the live canvas. Markers |
| 333 | - // canvas, and needs no second query shape. | 364 | + // are dropped anyway: a clear committing between the board read above and |
| 365 | + // this read files one under the epoch just named, and the room's socket | ||
| 366 | + // never shows it, so without the filter the two views disagree in exactly | ||
| 367 | + // that race. | ||
| 334 | let (strokes, total) = BoardStroke::history( | 368 | let (strokes, total) = BoardStroke::history( |
| 335 | board.get_id(), | 369 | board.get_id(), |
| 336 | Some(board.get_epoch()), | 370 | Some(board.get_epoch()), |
| 371 | + true, | ||
| 337 | limit, | 372 | limit, |
| 338 | offset, | 373 | offset, |
| 339 | &st.db, | 374 | &st.db, |
| @@ -376,7 +411,7 @@ async fn list_history( | |||
| 376 | let (limit, offset) = page.resolve()?; | 411 | let (limit, offset) = page.resolve()?; |
| 377 | let board = board_for(&id, &user, &st.db).await?; | 412 | let board = board_for(&id, &user, &st.db).await?; |
| 378 | let (strokes, total) = | 413 | let (strokes, total) = |
| 379 | - BoardStroke::history(board.get_id(), scope.epoch, limit, offset, &st.db).await?; | 414 | + BoardStroke::history(board.get_id(), scope.epoch, false, limit, offset, &st.db).await?; |
| 380 | let items = strokes.iter().map(StrokeResponse::new).collect(); | 415 | let items = strokes.iter().map(StrokeResponse::new).collect(); |
| 381 | Ok(Json(Page::new(items, total, limit, offset))) | 416 | Ok(Json(Page::new(items, total, limit, offset))) |
| 382 | } | 417 | } |
| @@ -441,6 +476,10 @@ struct UpdateBoard { | |||
| 441 | /// A roster change and a lock change are both fanned out to the live room at | 476 | /// A roster change and a lock change are both fanned out to the live room at |
| 442 | /// once β a participant removed here would otherwise keep drawing over the | 477 | /// once β a participant removed here would otherwise keep drawing over the |
| 443 | /// socket they already hold. | 478 | /// socket they already hold. |
| 479 | +/// | ||
| 480 | +/// The roster this route just served can always be sent back: an id already on | ||
| 481 | +/// the board that stopped qualifying is dropped rather than refused (see | ||
| 482 | +/// [`resolve_participants`]). Adding an unqualified id is still a 400. | ||
| 444 | #[utoipa::path( | 483 | #[utoipa::path( |
| 445 | patch, | 484 | patch, |
| 446 | path = "/{id}", | 485 | path = "/{id}", |
| @@ -450,11 +489,11 @@ struct UpdateBoard { | |||
| 450 | request_body = UpdateBoard, | 489 | request_body = UpdateBoard, |
| 451 | responses( | 490 | responses( |
| 452 | (status = 200, description = "The updated board", body = BoardResponse), | 491 | (status = 200, description = "The updated board", body = BoardResponse), |
| 453 | - (status = 400, description = "Invalid title, or a participant list that is too long, names an unknown user, or names a parent", body = ErrorResponse), | 492 | + (status = 400, description = "Invalid title, or a participant list that is too long, or one that newly names an unknown user or a parent. An id already on the board that no longer qualifies is dropped instead, so the roster just read can be sent back verbatim", body = ErrorResponse), |
| 454 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 493 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 455 | (status = 403, description = "Only the creator may change the participants or the lock", body = ErrorResponse), | 494 | (status = 403, description = "Only the creator may change the participants or the lock", body = ErrorResponse), |
| 456 | (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse), | 495 | (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse), |
| 457 | - (status = 422, description = "The body carries a key this request does not accept β a board response cannot be posted back verbatim"), | 496 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, a required field is missing, or it carries a key this request does not accept β a board response cannot be posted back verbatim"), |
| 458 | ), | 497 | ), |
| 459 | )] | 498 | )] |
| 460 | async fn update_board( | 499 | async fn update_board( |
| @@ -472,7 +511,8 @@ async fn update_board( | |||
| 472 | board = board.set_title(BoardTitle::try_new(title)?, &st.db).await?; | 511 | board = board.set_title(BoardTitle::try_new(title)?, &st.db).await?; |
| 473 | } | 512 | } |
| 474 | if let Some(participants) = req.participants { | 513 | if let Some(participants) = req.participants { |
| 475 | - let participants = resolve_participants(participants, &st.db).await?; | 514 | + let participants = |
| 515 | + resolve_participants(participants, board.get_participants(), &st.db).await?; | ||
| 476 | board = board.set_participants(participants, &st.db).await?; | 516 | board = board.set_participants(participants, &st.db).await?; |
| 477 | fan_out( | 517 | fan_out( |
| 478 | &st, | 518 | &st, |
| @@ -504,9 +544,11 @@ async fn update_board( | |||
| 504 | /// stroke count, so the live canvas is blank while every mark ever drawn stays | 544 | /// stroke count, so the live canvas is blank while every mark ever drawn stays |
| 505 | /// readable through `/history`. Also resets the live-canvas cap, which is how a | 545 | /// readable through `/history`. Also resets the live-canvas cap, which is how a |
| 506 | /// board that answered "clear it to keep drawing" is recovered. `409` on a | 546 | /// board that answered "clear it to keep drawing" is recovered. `409` on a |
| 507 | -/// closed board, and on a canvas that is **already blank** β the marker is a | 547 | +/// closed board, on a **locked** one β the pause holds against its own creator, |
| 508 | -/// real stroke row charged to the board's lifetime cap, so a clear has to close | 548 | +/// so a locked full board is recovered by unlock, clear, relock β and on a |
| 509 | -/// at least one mark to be worth a row. | 549 | +/// canvas that is **already blank**: the marker is a real stroke row charged to |
| 550 | +/// the board's lifetime cap, so a clear has to close at least one mark to be | ||
| 551 | +/// worth a row. | ||
| 510 | #[utoipa::path( | 552 | #[utoipa::path( |
| 511 | post, | 553 | post, |
| 512 | path = "/{id}/clear", | 554 | path = "/{id}/clear", |
| @@ -518,7 +560,7 @@ async fn update_board( | |||
| 518 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 560 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 519 | (status = 403, description = "Only the creator may clear the board", body = ErrorResponse), | 561 | (status = 403, description = "Only the creator may clear the board", body = ErrorResponse), |
| 520 | (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse), | 562 | (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse), |
| 521 | - (status = 409, description = "The canvas is already blank, or the board is closed", body = ErrorResponse), | 563 | + (status = 409, description = "The canvas is already blank, or the board is locked or closed", body = ErrorResponse), |
| 522 | ), | 564 | ), |
| 523 | )] | 565 | )] |
| 524 | async fn clear_board( | 566 | async fn clear_board( |
src/web/chatbot.rsmodified+3 -0
| @@ -111,6 +111,7 @@ impl ChatbotThreadResponse { | |||
| 111 | (status = 400, description = "Invalid title", body = ErrorResponse), | 111 | (status = 400, description = "Invalid title", body = ErrorResponse), |
| 112 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 112 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 113 | (status = 409, description = "At the school's thread cap", body = ErrorResponse), | 113 | (status = 409, description = "At the school's thread cap", body = ErrorResponse), |
| 114 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 114 | ), | 115 | ), |
| 115 | )] | 116 | )] |
| 116 | async fn create_thread( | 117 | async fn create_thread( |
| @@ -187,6 +188,7 @@ struct RenameChatbotThread { | |||
| 187 | (status = 400, description = "Invalid title", body = ErrorResponse), | 188 | (status = 400, description = "Invalid title", body = ErrorResponse), |
| 188 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 189 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 189 | (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse), | 190 | (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse), |
| 191 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 190 | ), | 192 | ), |
| 191 | )] | 193 | )] |
| 192 | async fn rename_thread( | 194 | async fn rename_thread( |
| @@ -364,6 +366,7 @@ async fn list_messages( | |||
| 364 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 366 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 365 | (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse), | 367 | (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse), |
| 366 | (status = 429, description = "Over the per-user message rate limit; see `Retry-After`", body = ErrorResponse), | 368 | (status = 429, description = "Over the per-user message rate limit; see `Retry-After`", body = ErrorResponse), |
| 369 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 367 | (status = 503, description = "No AI service is available β nothing was written, retry later", body = ErrorResponse), | 370 | (status = 503, description = "No AI service is available β nothing was written, retry later", body = ErrorResponse), |
| 368 | ), | 371 | ), |
| 369 | )] | 372 | )] |
src/web/classes.rsmodified+342 -1
| @@ -16,6 +16,7 @@ use utoipa_axum::router::OpenApiRouter; | |||
| 16 | use utoipa_axum::routes; | 16 | use utoipa_axum::routes; |
| 17 | 17 | ||
| 18 | use crate::database::Database; | 18 | use crate::database::Database; |
| 19 | +use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId, Skip}; | ||
| 19 | use crate::domain::class_course::ClassCourse; | 20 | use crate::domain::class_course::ClassCourse; |
| 20 | use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName}; | 21 | use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName}; |
| 21 | use crate::domain::class_member::ClassMember; | 22 | use crate::domain::class_member::ClassMember; |
| @@ -48,6 +49,12 @@ pub fn routes() -> OpenApiRouter<AppState> { | |||
| 48 | .routes(routes!(remove_member)) | 49 | .routes(routes!(remove_member)) |
| 49 | .routes(routes!(attach_course, list_class_courses)) | 50 | .routes(routes!(attach_course, list_class_courses)) |
| 50 | .routes(routes!(detach_course)) | 51 | .routes(routes!(detach_course)) |
| 52 | + // Static before parameter is a matchit rule, not a registration order β | ||
| 53 | + // `/classes/blueprints` reaches the template list and never `get_class` | ||
| 54 | + // with an id of `"blueprints"`, exactly as `/classes/me` does. | ||
| 55 | + .routes(routes!(create_blueprint, list_blueprints)) | ||
| 56 | + .routes(routes!(get_blueprint, update_blueprint, delete_blueprint)) | ||
| 57 | + .routes(routes!(apply_blueprint)) | ||
| 51 | } | 58 | } |
| 52 | 59 | ||
| 53 | #[derive(Deserialize, ToSchema)] | 60 | #[derive(Deserialize, ToSchema)] |
| @@ -302,6 +309,7 @@ async fn classes_page( | |||
| 302 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 309 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 303 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 310 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 304 | (status = 409, description = "The named homeroom teacher was demoted below teacher while the request ran β the class was rolled back, nothing was created", body = ErrorResponse), | 311 | (status = 409, description = "The named homeroom teacher was demoted below teacher while the request ran β the class was rolled back, nothing was created", body = ErrorResponse), |
| 312 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 305 | ), | 313 | ), |
| 306 | )] | 314 | )] |
| 307 | async fn create_class( | 315 | async fn create_class( |
| @@ -435,6 +443,7 @@ async fn get_class( | |||
| 435 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 443 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 436 | (status = 404, description = "Not found", body = ErrorResponse), | 444 | (status = 404, description = "Not found", body = ErrorResponse), |
| 437 | (status = 409, description = "The term this update moves the class off changed since the caller read it (nothing was written, re-read and retry), or the named homeroom teacher was demoted below teacher while the request ran (the assignment was undone)", body = ErrorResponse), | 445 | (status = 409, description = "The term this update moves the class off changed since the caller read it (nothing was written, re-read and retry), or the named homeroom teacher was demoted below teacher while the request ran (the assignment was undone)", body = ErrorResponse), |
| 446 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 438 | ), | 447 | ), |
| 439 | )] | 448 | )] |
| 440 | async fn update_class( | 449 | async fn update_class( |
| @@ -623,6 +632,7 @@ async fn delete_class( | |||
| 623 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 632 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 624 | (status = 404, description = "Class not found", body = ErrorResponse), | 633 | (status = 404, description = "Class not found", body = ErrorResponse), |
| 625 | (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), | 634 | (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), |
| 635 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 626 | ), | 636 | ), |
| 627 | )] | 637 | )] |
| 628 | async fn add_member( | 638 | async fn add_member( |
| @@ -749,6 +759,7 @@ async fn remove_member( | |||
| 749 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | 759 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 750 | (status = 404, description = "Class not found", body = ErrorResponse), | 760 | (status = 404, description = "Class not found", body = ErrorResponse), |
| 751 | (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), | 761 | (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), |
| 762 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 752 | ), | 763 | ), |
| 753 | )] | 764 | )] |
| 754 | async fn attach_course( | 765 | async fn attach_course( |
| @@ -859,6 +870,336 @@ async fn detach_course( | |||
| 859 | Ok(StatusCode::NO_CONTENT) | 870 | Ok(StatusCode::NO_CONTENT) |
| 860 | } | 871 | } |
| 861 | 872 | ||
| 873 | +// ---- grade blueprints ------------------------------------------------------ | ||
| 874 | + | ||
| 875 | +#[derive(Deserialize, ToSchema)] | ||
| 876 | +struct CreateBlueprint { | ||
| 877 | + /// The grade label this template stocks β the same free text a class | ||
| 878 | + /// carries in `grade` ("9", "10-A"). It is the blueprint's own id, so it | ||
| 879 | + /// must be non-empty and free of `/ \ ? # %`. | ||
| 880 | + #[schema(max_length = 20, example = "9")] | ||
| 881 | + grade: String, | ||
| 882 | + /// The courses every class section at that grade takes. | ||
| 883 | + course_ids: Vec<String>, | ||
| 884 | +} | ||
| 885 | + | ||
| 886 | +#[derive(Deserialize, ToSchema)] | ||
| 887 | +struct UpdateBlueprint { | ||
| 888 | + /// The whole new course list β a *set*, not a delta: courses missing from | ||
| 889 | + /// it are dropped from the blueprint and detached from the classes it | ||
| 890 | + /// attached them to. | ||
| 891 | + course_ids: Vec<String>, | ||
| 892 | +} | ||
| 893 | + | ||
| 894 | +#[derive(Serialize, ToSchema)] | ||
| 895 | +struct BlueprintResponse { | ||
| 896 | + /// The grade label, which is also the blueprint's id in every path here. | ||
| 897 | + #[schema(example = "9")] | ||
| 898 | + grade: String, | ||
| 899 | + /// The course ids this grade's sections take. | ||
| 900 | + courses: Vec<String>, | ||
| 901 | + /// Who wrote the template. | ||
| 902 | + creator: PersonRef, | ||
| 903 | +} | ||
| 904 | + | ||
| 905 | +impl BlueprintResponse { | ||
| 906 | + fn new( | ||
| 907 | + blueprint: &ClassBlueprint, | ||
| 908 | + people: &std::collections::HashMap<String, PersonRef>, | ||
| 909 | + ) -> Self { | ||
| 910 | + Self { | ||
| 911 | + grade: blueprint.get_grade().as_str().to_string(), | ||
| 912 | + courses: blueprint | ||
| 913 | + .get_courses() | ||
| 914 | + .iter() | ||
| 915 | + .map(|course| course.key().to_string()) | ||
| 916 | + .collect(), | ||
| 917 | + creator: PersonRef::resolve(people, blueprint.get_creator()), | ||
| 918 | + } | ||
| 919 | + } | ||
| 920 | +} | ||
| 921 | + | ||
| 922 | +/// One class a pump did *not* stock, and why. The class is named as well as | ||
| 923 | +/// identified: a manager reading a skip list has to know which section is short | ||
| 924 | +/// a course, and a bare ULID is not that. | ||
| 925 | +#[derive(Serialize, ToSchema)] | ||
| 926 | +struct SkipResponse { | ||
| 927 | + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | ||
| 928 | + class: String, | ||
| 929 | + #[schema(example = "9-C")] | ||
| 930 | + class_name: String, | ||
| 931 | + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | ||
| 932 | + course: String, | ||
| 933 | + /// Why that course could not be attached to that class. | ||
| 934 | + #[schema(example = "the course has no free seat for the whole class")] | ||
| 935 | + reason: String, | ||
| 936 | +} | ||
| 937 | + | ||
| 938 | +impl SkipResponse { | ||
| 939 | + fn new(skip: &Skip) -> Self { | ||
| 940 | + Self { | ||
| 941 | + class: skip.class.key().to_string(), | ||
| 942 | + class_name: skip.class_name.clone(), | ||
| 943 | + course: skip.course.key().to_string(), | ||
| 944 | + reason: skip.reason.to_string(), | ||
| 945 | + } | ||
| 946 | + } | ||
| 947 | +} | ||
| 948 | + | ||
| 949 | +#[derive(Serialize, ToSchema)] | ||
| 950 | +struct BlueprintPumpResponse { | ||
| 951 | + blueprint: BlueprintResponse, | ||
| 952 | + /// Every (class, course) pair this write could not place. Empty when every | ||
| 953 | + /// section at the grade took the whole list. The blueprint itself was still | ||
| 954 | + /// saved β a pump is best-effort by design. | ||
| 955 | + skipped: Vec<SkipResponse>, | ||
| 956 | +} | ||
| 957 | + | ||
| 958 | +#[derive(Serialize, ToSchema)] | ||
| 959 | +struct ApplyResponse { | ||
| 960 | + /// The courses this class could not take, empty when it took them all. | ||
| 961 | + skipped: Vec<SkipResponse>, | ||
| 962 | +} | ||
| 963 | + | ||
| 964 | +/// The courses a request names, each of which must exist. Order and duplicates | ||
| 965 | +/// are the blueprint's to settle ([`ClassBlueprint`] deduplicates). | ||
| 966 | +async fn resolve_courses(ids: &[String], db: &Database) -> Result<Vec<CourseId>, AppError> { | ||
| 967 | + let mut courses = Vec::with_capacity(ids.len()); | ||
| 968 | + for id in ids { | ||
| 969 | + let course = CourseId::from_key(id); | ||
| 970 | + if Course::read(&course, db).await?.is_none() { | ||
| 971 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 972 | + field: "course_ids", | ||
| 973 | + reason: "one of these courses does not exist", | ||
| 974 | + })); | ||
| 975 | + } | ||
| 976 | + courses.push(course); | ||
| 977 | + } | ||
| 978 | + Ok(courses) | ||
| 979 | +} | ||
| 980 | + | ||
| 981 | +/// The blueprint a path grade names, or a 404. | ||
| 982 | +async fn blueprint_or_404(grade: &str, db: &Database) -> Result<ClassBlueprint, AppError> { | ||
| 983 | + ClassBlueprint::read(&ClassBlueprintId::from_key(grade), db) | ||
| 984 | + .await? | ||
| 985 | + .ok_or(AppError::NotFound) | ||
| 986 | +} | ||
| 987 | + | ||
| 988 | +async fn blueprint_body( | ||
| 989 | + blueprint: &ClassBlueprint, | ||
| 990 | + skipped: &[Skip], | ||
| 991 | + db: &Database, | ||
| 992 | +) -> Result<BlueprintPumpResponse, AppError> { | ||
| 993 | + let people = person_map([blueprint.get_creator().clone()], db).await?; | ||
| 994 | + Ok(BlueprintPumpResponse { | ||
| 995 | + blueprint: BlueprintResponse::new(blueprint, &people), | ||
| 996 | + skipped: skipped.iter().map(SkipResponse::new).collect(), | ||
| 997 | + }) | ||
| 998 | +} | ||
| 999 | + | ||
| 1000 | +/// Create a grade's course blueprint and stock every class section already at | ||
| 1001 | +/// that grade with it. Requires manager+. | ||
| 1002 | +/// | ||
| 1003 | +/// The pump is **best-effort**: a class that cannot take one of the courses (it | ||
| 1004 | +/// is at its own course ceiling, or the course has no free seat for the whole | ||
| 1005 | +/// section) is skipped and reported in `skipped`, while every other class is | ||
| 1006 | +/// still stocked. The blueprint is saved either way. | ||
| 1007 | +#[utoipa::path( | ||
| 1008 | + post, | ||
| 1009 | + path = "/blueprints", | ||
| 1010 | + tag = "classes", | ||
| 1011 | + security(("session_cookie" = [])), | ||
| 1012 | + request_body = CreateBlueprint, | ||
| 1013 | + responses( | ||
| 1014 | + (status = 201, description = "Blueprint created, with the classes it could not stock", body = BlueprintPumpResponse), | ||
| 1015 | + (status = 400, description = "Invalid or unaddressable grade, too many courses, or a course that does not exist", body = ErrorResponse), | ||
| 1016 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 1017 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 1018 | + (status = 409, description = "A blueprint already exists for that grade", body = ErrorResponse), | ||
| 1019 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 1020 | + ), | ||
| 1021 | +)] | ||
| 1022 | +async fn create_blueprint( | ||
| 1023 | + State(st): State<AppState>, | ||
| 1024 | + RequireManager(user): RequireManager, | ||
| 1025 | + Json(req): Json<CreateBlueprint>, | ||
| 1026 | +) -> Result<(StatusCode, Json<BlueprintPumpResponse>), AppError> { | ||
| 1027 | + let grade = ClassBlueprint::grade_key(&req.grade)?; | ||
| 1028 | + let courses = resolve_courses(&req.course_ids, &st.db).await?; | ||
| 1029 | + let blueprint = ClassBlueprint::create(user.get_id(), grade, courses, &st.db).await?; | ||
| 1030 | + let skipped = blueprint.pump(user.get_id(), &st.db).await?; | ||
| 1031 | + let body = blueprint_body(&blueprint, &skipped, &st.db).await?; | ||
| 1032 | + Ok((StatusCode::CREATED, Json(body))) | ||
| 1033 | +} | ||
| 1034 | + | ||
| 1035 | +/// List every grade blueprint, by grade label. Requires manager+. Paged via | ||
| 1036 | +/// `?limit=&offset=` (omit `limit` for all of them). | ||
| 1037 | +#[utoipa::path( | ||
| 1038 | + get, | ||
| 1039 | + path = "/blueprints", | ||
| 1040 | + tag = "classes", | ||
| 1041 | + security(("session_cookie" = [])), | ||
| 1042 | + params(PageParams), | ||
| 1043 | + responses( | ||
| 1044 | + (status = 200, description = "A page of blueprints (all of them when unpaged)", body = Page<BlueprintResponse>), | ||
| 1045 | + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), | ||
| 1046 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 1047 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 1048 | + ), | ||
| 1049 | +)] | ||
| 1050 | +async fn list_blueprints( | ||
| 1051 | + State(st): State<AppState>, | ||
| 1052 | + RequireManager(_user): RequireManager, | ||
| 1053 | + Query(page): Query<PageParams>, | ||
| 1054 | +) -> Result<Json<Page<BlueprintResponse>>, AppError> { | ||
| 1055 | + let (limit, offset) = page.resolve()?; | ||
| 1056 | + let (blueprints, total) = ClassBlueprint::list_all(limit, offset, &st.db).await?; | ||
| 1057 | + let people = person_map( | ||
| 1058 | + blueprints | ||
| 1059 | + .iter() | ||
| 1060 | + .map(|blueprint| blueprint.get_creator().clone()), | ||
| 1061 | + &st.db, | ||
| 1062 | + ) | ||
| 1063 | + .await?; | ||
| 1064 | + let items = blueprints | ||
| 1065 | + .iter() | ||
| 1066 | + .map(|blueprint| BlueprintResponse::new(blueprint, &people)) | ||
| 1067 | + .collect(); | ||
| 1068 | + Ok(Json(Page::new(items, total, limit, offset))) | ||
| 1069 | +} | ||
| 1070 | + | ||
| 1071 | +/// Fetch one grade's blueprint. Requires manager+. | ||
| 1072 | +#[utoipa::path( | ||
| 1073 | + get, | ||
| 1074 | + path = "/blueprints/{grade}", | ||
| 1075 | + tag = "classes", | ||
| 1076 | + security(("session_cookie" = [])), | ||
| 1077 | + params(("grade" = String, Path, description = "Grade label")), | ||
| 1078 | + responses( | ||
| 1079 | + (status = 200, description = "The blueprint", body = BlueprintResponse), | ||
| 1080 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 1081 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 1082 | + (status = 404, description = "No blueprint for that grade", body = ErrorResponse), | ||
| 1083 | + ), | ||
| 1084 | +)] | ||
| 1085 | +async fn get_blueprint( | ||
| 1086 | + State(st): State<AppState>, | ||
| 1087 | + RequireManager(_user): RequireManager, | ||
| 1088 | + Path(grade): Path<String>, | ||
| 1089 | +) -> Result<Json<BlueprintResponse>, AppError> { | ||
| 1090 | + let blueprint = blueprint_or_404(&grade, &st.db).await?; | ||
| 1091 | + let people = person_map([blueprint.get_creator().clone()], &st.db).await?; | ||
| 1092 | + Ok(Json(BlueprintResponse::new(&blueprint, &people))) | ||
| 1093 | +} | ||
| 1094 | + | ||
| 1095 | +/// Replace a blueprint's course list and reconcile every class section at that | ||
| 1096 | +/// grade with it. Requires manager+. | ||
| 1097 | +/// | ||
| 1098 | +/// `course_ids` is the whole list, not a delta. A course dropped from it is | ||
| 1099 | +/// **detached** from the classes this blueprint attached it to (their pumped | ||
| 1100 | +/// enrollments swept the usual way) β but a course a human attached to a class | ||
| 1101 | +/// by hand carries no blueprint tag and is left exactly where it is. Courses | ||
| 1102 | +/// still in the list are pumped into every class at the grade that does not | ||
| 1103 | +/// already carry them. | ||
| 1104 | +/// | ||
| 1105 | +/// The pump is **best-effort**: a class that cannot take a course is skipped | ||
| 1106 | +/// and reported in `skipped`, and the rest are still stocked. A `409` means the | ||
| 1107 | +/// list changed since you read it β nothing was written; re-read and retry. | ||
| 1108 | +#[utoipa::path( | ||
| 1109 | + patch, | ||
| 1110 | + path = "/blueprints/{grade}", | ||
| 1111 | + tag = "classes", | ||
| 1112 | + security(("session_cookie" = [])), | ||
| 1113 | + params(("grade" = String, Path, description = "Grade label")), | ||
| 1114 | + request_body = UpdateBlueprint, | ||
| 1115 | + responses( | ||
| 1116 | + (status = 200, description = "Updated blueprint, with the classes it could not stock", body = BlueprintPumpResponse), | ||
| 1117 | + (status = 400, description = "Too many courses, or a course that does not exist", body = ErrorResponse), | ||
| 1118 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 1119 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 1120 | + (status = 404, description = "No blueprint for that grade", body = ErrorResponse), | ||
| 1121 | + (status = 409, description = "The course list changed since the caller read it β nothing was written, re-read and retry", body = ErrorResponse), | ||
| 1122 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 1123 | + ), | ||
| 1124 | +)] | ||
| 1125 | +async fn update_blueprint( | ||
| 1126 | + State(st): State<AppState>, | ||
| 1127 | + RequireManager(user): RequireManager, | ||
| 1128 | + Path(grade): Path<String>, | ||
| 1129 | + Json(req): Json<UpdateBlueprint>, | ||
| 1130 | +) -> Result<Json<BlueprintPumpResponse>, AppError> { | ||
| 1131 | + let blueprint = blueprint_or_404(&grade, &st.db).await?; | ||
| 1132 | + let courses = resolve_courses(&req.course_ids, &st.db).await?; | ||
| 1133 | + let (saved, skipped) = blueprint | ||
| 1134 | + .set_courses(courses, user.get_id(), &st.db) | ||
| 1135 | + .await?; | ||
| 1136 | + Ok(Json(blueprint_body(&saved, &skipped, &st.db).await?)) | ||
| 1137 | +} | ||
| 1138 | + | ||
| 1139 | +/// Delete a grade's blueprint. Requires manager+. Every attachment the | ||
| 1140 | +/// blueprint made is detached with it (their pumped enrollments swept the usual | ||
| 1141 | +/// way); a course a human attached to one of those classes by hand carries no | ||
| 1142 | +/// blueprint tag and survives. | ||
| 1143 | +#[utoipa::path( | ||
| 1144 | + delete, | ||
| 1145 | + path = "/blueprints/{grade}", | ||
| 1146 | + tag = "classes", | ||
| 1147 | + security(("session_cookie" = [])), | ||
| 1148 | + params(("grade" = String, Path, description = "Grade label")), | ||
| 1149 | + responses( | ||
| 1150 | + (status = 204, description = "Deleted"), | ||
| 1151 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 1152 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 1153 | + (status = 404, description = "No blueprint for that grade", body = ErrorResponse), | ||
| 1154 | + ), | ||
| 1155 | +)] | ||
| 1156 | +async fn delete_blueprint( | ||
| 1157 | + State(st): State<AppState>, | ||
| 1158 | + RequireManager(_user): RequireManager, | ||
| 1159 | + Path(grade): Path<String>, | ||
| 1160 | +) -> Result<StatusCode, AppError> { | ||
| 1161 | + blueprint_or_404(&grade, &st.db) | ||
| 1162 | + .await? | ||
| 1163 | + .delete(&st.db) | ||
| 1164 | + .await?; | ||
| 1165 | + Ok(StatusCode::NO_CONTENT) | ||
| 1166 | +} | ||
| 1167 | + | ||
| 1168 | +/// Stock one class section from its grade's blueprint. Requires manager+ β this | ||
| 1169 | +/// writes the roster of every course in the template, which is the office's | ||
| 1170 | +/// call, not one course owner's. | ||
| 1171 | +/// | ||
| 1172 | +/// Idempotent: a course the class already carries is left alone, whoever | ||
| 1173 | +/// attached it. Best-effort like every other pump β the courses that did not | ||
| 1174 | +/// fit come back in `skipped` and the rest are attached. A class with no grade, | ||
| 1175 | +/// or a grade no blueprint covers, is a 404. | ||
| 1176 | +#[utoipa::path( | ||
| 1177 | + post, | ||
| 1178 | + path = "/{id}/blueprint", | ||
| 1179 | + tag = "classes", | ||
| 1180 | + security(("session_cookie" = [])), | ||
| 1181 | + params(("id" = String, Path, description = "Class id")), | ||
| 1182 | + responses( | ||
| 1183 | + (status = 200, description = "The class was stocked, minus the courses it could not take", body = ApplyResponse), | ||
| 1184 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 1185 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 1186 | + (status = 404, description = "Class not found, or no blueprint covers its grade", body = ErrorResponse), | ||
| 1187 | + ), | ||
| 1188 | +)] | ||
| 1189 | +async fn apply_blueprint( | ||
| 1190 | + State(st): State<AppState>, | ||
| 1191 | + RequireManager(user): RequireManager, | ||
| 1192 | + Path(id): Path<String>, | ||
| 1193 | +) -> Result<Json<ApplyResponse>, AppError> { | ||
| 1194 | + let class = class_or_404(&id, &st.db).await?; | ||
| 1195 | + let grade = class.get_grade().ok_or(AppError::NotFound)?; | ||
| 1196 | + let blueprint = blueprint_or_404(grade.as_str(), &st.db).await?; | ||
| 1197 | + let skipped = blueprint.apply_to(&class, user.get_id(), &st.db).await?; | ||
| 1198 | + Ok(Json(ApplyResponse { | ||
| 1199 | + skipped: skipped.iter().map(SkipResponse::new).collect(), | ||
| 1200 | + })) | ||
| 1201 | +} | ||
| 1202 | + | ||
| 862 | #[cfg(test)] | 1203 | #[cfg(test)] |
| 863 | mod tests { | 1204 | mod tests { |
| 864 | use super::*; | 1205 | use super::*; |
| @@ -904,7 +1245,7 @@ mod tests { | |||
| 904 | ) | 1245 | ) |
| 905 | .await | 1246 | .await |
| 906 | .unwrap(); | 1247 | .unwrap(); |
| 907 | - user.set_role(role, &db).await.unwrap() | 1248 | + user.set_role(role, &db).await.unwrap().0 |
| 908 | }; | 1249 | }; |
| 909 | let student = make("ali", Role::Student).await; | 1250 | let student = make("ali", Role::Student).await; |
| 910 | let teacher = make("ada", Role::Teacher).await; | 1251 | let teacher = make("ada", Role::Teacher).await; |
src/web/courses.rsmodified+11 -3
| @@ -292,6 +292,7 @@ fn check_capacity(capacity: Option<i64>) -> Result<(), AppError> { | |||
| 292 | (status = 400, description = "Invalid fields, kind, or capacity", body = ErrorResponse), | 292 | (status = 400, description = "Invalid fields, kind, or capacity", body = ErrorResponse), |
| 293 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 293 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 294 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 294 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 295 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 295 | ), | 296 | ), |
| 296 | )] | 297 | )] |
| 297 | async fn create_course( | 298 | async fn create_course( |
| @@ -444,6 +445,7 @@ async fn get_course( | |||
| 444 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | 445 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 445 | (status = 404, description = "Not found", body = ErrorResponse), | 446 | (status = 404, description = "Not found", body = ErrorResponse), |
| 446 | (status = 409, description = "The term this update moves the course off changed since the caller read it β nothing was written, re-read and retry", body = ErrorResponse), | 447 | (status = 409, description = "The term this update moves the course off changed since the caller read it β nothing was written, re-read and retry", body = ErrorResponse), |
| 448 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 447 | ), | 449 | ), |
| 448 | )] | 450 | )] |
| 449 | async fn update_course( | 451 | async fn update_course( |
| @@ -567,6 +569,7 @@ async fn delete_course( | |||
| 567 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 569 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 568 | (status = 404, description = "Course not found", body = ErrorResponse), | 570 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 569 | (status = 409, description = "That user was demoted below teacher while the request ran β the assignment was undone", body = ErrorResponse), | 571 | (status = 409, description = "That user was demoted below teacher while the request ran β the assignment was undone", body = ErrorResponse), |
| 572 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 570 | ), | 573 | ), |
| 571 | )] | 574 | )] |
| 572 | async fn assign_teacher( | 575 | async fn assign_teacher( |
| @@ -665,6 +668,7 @@ async fn unassign_teacher( | |||
| 665 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | 668 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 666 | (status = 404, description = "Course not found", body = ErrorResponse), | 669 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 667 | (status = 409, description = "The course is full", body = ErrorResponse), | 670 | (status = 409, description = "The course is full", body = ErrorResponse), |
| 671 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 668 | ), | 672 | ), |
| 669 | )] | 673 | )] |
| 670 | async fn enroll( | 674 | async fn enroll( |
| @@ -818,6 +822,7 @@ async fn unenroll( | |||
| 818 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 822 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 819 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | 823 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 820 | (status = 404, description = "Course not found", body = ErrorResponse), | 824 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 825 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 821 | ), | 826 | ), |
| 822 | )] | 827 | )] |
| 823 | async fn create_exam_in_course( | 828 | async fn create_exam_in_course( |
| @@ -946,6 +951,7 @@ struct CreateSubject { | |||
| 946 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 951 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 947 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | 952 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 948 | (status = 404, description = "Course not found", body = ErrorResponse), | 953 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 954 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 949 | ), | 955 | ), |
| 950 | )] | 956 | )] |
| 951 | async fn create_subject_in_course( | 957 | async fn create_subject_in_course( |
| @@ -1053,6 +1059,7 @@ struct CreateHomework { | |||
| 1053 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 1059 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1054 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | 1060 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 1055 | (status = 404, description = "Course not found", body = ErrorResponse), | 1061 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 1062 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 1056 | ), | 1063 | ), |
| 1057 | )] | 1064 | )] |
| 1058 | async fn create_homework_in_course( | 1065 | async fn create_homework_in_course( |
| @@ -1178,6 +1185,7 @@ struct CreateSessionInCourse { | |||
| 1178 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 1185 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1179 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | 1186 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 1180 | (status = 404, description = "Course not found", body = ErrorResponse), | 1187 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 1188 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 1181 | ), | 1189 | ), |
| 1182 | )] | 1190 | )] |
| 1183 | async fn create_session_in_course( | 1191 | async fn create_session_in_course( |
| @@ -1280,7 +1288,7 @@ mod tests { | |||
| 1280 | let user = User::create(Username::try_new(username).unwrap(), hash, db) | 1288 | let user = User::create(Username::try_new(username).unwrap(), hash, db) |
| 1281 | .await | 1289 | .await |
| 1282 | .unwrap(); | 1290 | .unwrap(); |
| 1283 | - user.set_role(role, db).await.unwrap() | 1291 | + user.set_role(role, db).await.unwrap().0 |
| 1284 | } | 1292 | } |
| 1285 | 1293 | ||
| 1286 | /// A course `creator` made, with nobody assigned. | 1294 | /// A course `creator` made, with nobody assigned. |
| @@ -1309,7 +1317,7 @@ mod tests { | |||
| 1309 | assert!(owns_course(&course, &creator)); | 1317 | assert!(owns_course(&course, &creator)); |
| 1310 | 1318 | ||
| 1311 | for role in [Role::Student, Role::Parent] { | 1319 | for role in [Role::Student, Role::Parent] { |
| 1312 | - let demoted = creator.clone().set_role(role, &db).await.unwrap(); | 1320 | + let demoted = creator.clone().set_role(role, &db).await.unwrap().0; |
| 1313 | assert!( | 1321 | assert!( |
| 1314 | !can_manage_course(&course, &demoted), | 1322 | !can_manage_course(&course, &demoted), |
| 1315 | "{role:?} creator still manages the course" | 1323 | "{role:?} creator still manages the course" |
| @@ -1338,7 +1346,7 @@ mod tests { | |||
| 1338 | // ...but never an owner, assigned or not. | 1346 | // ...but never an owner, assigned or not. |
| 1339 | assert!(!owns_course(&course, &assigned)); | 1347 | assert!(!owns_course(&course, &assigned)); |
| 1340 | 1348 | ||
| 1341 | - let demoted = assigned.set_role(Role::Student, &db).await.unwrap(); | 1349 | + let demoted = assigned.set_role(Role::Student, &db).await.unwrap().0; |
| 1342 | assert!(!can_manage_course(&course, &demoted)); | 1350 | assert!(!can_manage_course(&course, &demoted)); |
| 1343 | } | 1351 | } |
| 1344 | 1352 | ||
src/web/events.rsmodified+30 -5
| @@ -10,6 +10,7 @@ use utoipa_axum::routes; | |||
| 10 | 10 | ||
| 11 | use crate::database::Database; | 11 | use crate::database::Database; |
| 12 | use crate::domain::attendance::{Attendance, AttendanceStatus}; | 12 | use crate::domain::attendance::{Attendance, AttendanceStatus}; |
| 13 | +use crate::domain::class_group::{ClassGroup, ClassGroupId}; | ||
| 13 | use crate::domain::course::{Course, CourseId}; | 14 | use crate::domain::course::{Course, CourseId}; |
| 14 | use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle}; | 15 | use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle}; |
| 15 | use crate::domain::registration::Registration; | 16 | use crate::domain::registration::Registration; |
| @@ -64,6 +65,11 @@ enum AudienceDto { | |||
| 64 | /// The students currently enrolled in this course (live β enrollment | 65 | /// The students currently enrolled in this course (live β enrollment |
| 65 | /// changes move people in and out). | 66 | /// changes move people in and out). |
| 66 | Course { course: String }, | 67 | Course { course: String }, |
| 68 | + /// The students currently in this class section (Εube) β live, so adding | ||
| 69 | + /// or removing a member moves them in and out. The homeroom teacher is not | ||
| 70 | + /// implied. If the class is later deleted the event survives with an empty | ||
| 71 | + /// roster. | ||
| 72 | + Class { class: String }, | ||
| 67 | /// A signup list built through `POST /events/{id}/register` β teachers | 73 | /// A signup list built through `POST /events/{id}/register` β teachers |
| 68 | /// place students, staff take their own seat. `capacity` caps the seats; | 74 | /// place students, staff take their own seat. `capacity` caps the seats; |
| 69 | /// `null` or omitted = unlimited. The list closes when the event starts. | 75 | /// `null` or omitted = unlimited. The list closes when the event starts. |
| @@ -92,6 +98,16 @@ impl AudienceDto { | |||
| 92 | } | 98 | } |
| 93 | Ok(EventAudience::Course { course }) | 99 | Ok(EventAudience::Course { course }) |
| 94 | } | 100 | } |
| 101 | + AudienceDto::Class { class } => { | ||
| 102 | + let class = ClassGroupId::from_key(&class); | ||
| 103 | + if ClassGroup::read(&class, db).await?.is_none() { | ||
| 104 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 105 | + field: "audience", | ||
| 106 | + reason: "class does not exist", | ||
| 107 | + })); | ||
| 108 | + } | ||
| 109 | + Ok(EventAudience::Class { class }) | ||
| 110 | + } | ||
| 95 | AudienceDto::Registration { capacity } => { | 111 | AudienceDto::Registration { capacity } => { |
| 96 | if capacity.is_some_and(|capacity| capacity < 1) { | 112 | if capacity.is_some_and(|capacity| capacity < 1) { |
| 97 | return Err(AppError::Validation(ValidationError::Invalid { | 113 | return Err(AppError::Validation(ValidationError::Invalid { |
| @@ -113,6 +129,9 @@ impl AudienceDto { | |||
| 113 | EventAudience::Course { course } => AudienceDto::Course { | 129 | EventAudience::Course { course } => AudienceDto::Course { |
| 114 | course: course.key().to_string(), | 130 | course: course.key().to_string(), |
| 115 | }, | 131 | }, |
| 132 | + EventAudience::Class { class } => AudienceDto::Class { | ||
| 133 | + class: class.key().to_string(), | ||
| 134 | + }, | ||
| 116 | EventAudience::Registration { capacity } => AudienceDto::Registration { | 135 | EventAudience::Registration { capacity } => AudienceDto::Registration { |
| 117 | capacity: *capacity, | 136 | capacity: *capacity, |
| 118 | }, | 137 | }, |
| @@ -234,8 +253,9 @@ impl AttendanceResponse { | |||
| 234 | // ---- events ------------------------------------------------------------- | 253 | // ---- events ------------------------------------------------------------- |
| 235 | 254 | ||
| 236 | /// Create an event owned by the current user. Requires the `teacher` role or | 255 | /// Create an event owned by the current user. Requires the `teacher` role or |
| 237 | -/// higher. `audience` targets it at a role, a course's enrollment, or a | 256 | +/// higher. `audience` targets it at a role, a course's enrollment, a class |
| 238 | -/// registration list (filled via `POST /events/{id}/register`); omitted it is | 257 | +/// section's roster, or a registration list (filled via |
| 258 | +/// `POST /events/{id}/register`); omitted it is | ||
| 239 | /// school-wide. Everyone still sees every event β the audience is the | 259 | /// school-wide. Everyone still sees every event β the audience is the |
| 240 | /// expected-attendee roster, not a visibility wall. | 260 | /// expected-attendee roster, not a visibility wall. |
| 241 | #[utoipa::path( | 261 | #[utoipa::path( |
| @@ -249,6 +269,7 @@ impl AttendanceResponse { | |||
| 249 | (status = 400, description = "Invalid fields, audience, time range, or times in the past", body = ErrorResponse), | 269 | (status = 400, description = "Invalid fields, audience, time range, or times in the past", body = ErrorResponse), |
| 250 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 270 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 251 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 271 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 272 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 252 | ), | 273 | ), |
| 253 | )] | 274 | )] |
| 254 | async fn create_event( | 275 | async fn create_event( |
| @@ -360,6 +381,7 @@ async fn get_event( | |||
| 360 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 381 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 361 | (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), | 382 | (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), |
| 362 | (status = 404, description = "Not found", body = ErrorResponse), | 383 | (status = 404, description = "Not found", body = ErrorResponse), |
| 384 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 363 | ), | 385 | ), |
| 364 | )] | 386 | )] |
| 365 | async fn update_event( | 387 | async fn update_event( |
| @@ -472,6 +494,7 @@ async fn delete_event( | |||
| 472 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 494 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 473 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 495 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 474 | (status = 404, description = "Event not found", body = ErrorResponse), | 496 | (status = 404, description = "Event not found", body = ErrorResponse), |
| 497 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 475 | ), | 498 | ), |
| 476 | )] | 499 | )] |
| 477 | async fn mark( | 500 | async fn mark( |
| @@ -609,7 +632,8 @@ struct RosterEntry { | |||
| 609 | 632 | ||
| 610 | /// The event's expected-attendee roster joined with its attendance marks β the | 633 | /// The event's expected-attendee roster joined with its attendance marks β the |
| 611 | /// who-came/who-missed report. Resolved live from the audience (today's role | 634 | /// who-came/who-missed report. Resolved live from the audience (today's role |
| 612 | -/// holders, current enrollment, the current signup list), so it always reflects | 635 | +/// holders, current enrollment, the current class roster, the current signup |
| 636 | +/// list), so it always reflects | ||
| 613 | /// the present roster; | 637 | /// the present roster; |
| 614 | /// attendance rows for people no longer in the audience are omitted here (they | 638 | /// attendance rows for people no longer in the audience are omitted here (they |
| 615 | /// remain in `GET /events/{id}/attendance`). Requires teacher+. Paged via | 639 | /// remain in `GET /events/{id}/attendance`). Requires teacher+. Paged via |
| @@ -713,6 +737,7 @@ struct RegistrationResponse { | |||
| 713 | (status = 403, description = "Requires teacher role or higher, or the target is another staff member", body = ErrorResponse), | 737 | (status = 403, description = "Requires teacher role or higher, or the target is another staff member", body = ErrorResponse), |
| 714 | (status = 404, description = "Event not found", body = ErrorResponse), | 738 | (status = 404, description = "Event not found", body = ErrorResponse), |
| 715 | (status = 409, description = "The event is full, or it already started or ended", body = ErrorResponse), | 739 | (status = 409, description = "The event is full, or it already started or ended", body = ErrorResponse), |
| 740 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 716 | ), | 741 | ), |
| 717 | )] | 742 | )] |
| 718 | async fn register( | 743 | async fn register( |
| @@ -836,7 +861,7 @@ mod tests { | |||
| 836 | let user = User::create(Username::try_new(username).unwrap(), hash, db) | 861 | let user = User::create(Username::try_new(username).unwrap(), hash, db) |
| 837 | .await | 862 | .await |
| 838 | .unwrap(); | 863 | .unwrap(); |
| 839 | - user.set_role(role, db).await.unwrap() | 864 | + user.set_role(role, db).await.unwrap().0 |
| 840 | } | 865 | } |
| 841 | 866 | ||
| 842 | /// `can_manage` is only reached behind `RequireTeacher` today, so this is | 867 | /// `can_manage` is only reached behind `RequireTeacher` today, so this is |
| @@ -860,7 +885,7 @@ mod tests { | |||
| 860 | assert!(can_manage(&event, &creator)); | 885 | assert!(can_manage(&event, &creator)); |
| 861 | 886 | ||
| 862 | for role in [Role::Student, Role::Parent] { | 887 | for role in [Role::Student, Role::Parent] { |
| 863 | - let demoted = creator.clone().set_role(role, &db).await.unwrap(); | 888 | + let demoted = creator.clone().set_role(role, &db).await.unwrap().0; |
| 864 | assert!( | 889 | assert!( |
| 865 | !can_manage(&event, &demoted), | 890 | !can_manage(&event, &demoted), |
| 866 | "{role:?} creator still manages the event" | 891 | "{role:?} creator still manages the event" |
src/web/exams/attempts.rsmodified+13 -2
| @@ -850,6 +850,7 @@ pub(crate) async fn attempt_questions( | |||
| 850 | (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), | 850 | (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), |
| 851 | (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse), | 851 | (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse), |
| 852 | (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), | 852 | (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), |
| 853 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 853 | ), | 854 | ), |
| 854 | )] | 855 | )] |
| 855 | pub(crate) async fn save_answer( | 856 | pub(crate) async fn save_answer( |
| @@ -924,19 +925,29 @@ pub(crate) async fn attempt_answers( | |||
| 924 | .await? | 925 | .await? |
| 925 | .ok_or(AppError::NotFound)? | 926 | .ok_or(AppError::NotFound)? |
| 926 | .get_seq(); | 927 | .get_seq(); |
| 927 | - Ok(Json(answer_sheet(&exam, &target, seq, &st.db).await?)) | 928 | + Ok(Json( |
| 929 | + answer_sheet(&exam, &target, seq, &HashSet::new(), &st.db).await?, | ||
| 930 | + )) | ||
| 928 | } | 931 | } |
| 929 | 932 | ||
| 930 | /// One sitting's judged answer sheet: the `seq`th attempt's answers, drawing | 933 | /// One sitting's judged answer sheet: the `seq`th attempt's answers, drawing |
| 931 | /// refs, correctness flags, and auto-score suggestion. Shared by the latest- | 934 | /// refs, correctness flags, and auto-score suggestion. Shared by the latest- |
| 932 | /// sitting grading view and the per-attempt history endpoint. | 935 | /// sitting grading view and the per-attempt history endpoint. |
| 936 | +/// | ||
| 937 | +/// `hidden` names the questions whose answer key must not leak out of this | ||
| 938 | +/// sheet (empty for a teacher). Dropping them from the question list is the | ||
| 939 | +/// whole redaction: their `is_correct` falls to `null` for want of a question, | ||
| 940 | +/// and they leave `auto_score` entirely β a per-question score still standing | ||
| 941 | +/// in the total is the same bit, arrived at by subtraction. | ||
| 933 | pub(crate) async fn answer_sheet( | 942 | pub(crate) async fn answer_sheet( |
| 934 | exam: &Exam, | 943 | exam: &Exam, |
| 935 | target: &UserId, | 944 | target: &UserId, |
| 936 | seq: i64, | 945 | seq: i64, |
| 946 | + hidden: &HashSet<String>, | ||
| 937 | db: &Database, | 947 | db: &Database, |
| 938 | ) -> Result<AttemptAnswersResponse, AppError> { | 948 | ) -> Result<AttemptAnswersResponse, AppError> { |
| 939 | - let (questions, _) = ExamQuestion::list_for_exam(exam.get_id(), None, 0, db).await?; | 949 | + let (mut questions, _) = ExamQuestion::list_for_exam(exam.get_id(), None, 0, db).await?; |
| 950 | + questions.retain(|question| !hidden.contains(question.get_id().key())); | ||
| 940 | let answers = ExamAnswer::list_for_exam_user(exam.get_id(), target, seq, db).await?; | 951 | let answers = ExamAnswer::list_for_exam_user(exam.get_id(), target, seq, db).await?; |
| 941 | let answer_images: HashMap<String, AnswerImage> = | 952 | let answer_images: HashMap<String, AnswerImage> = |
| 942 | AnswerImage::list_for_exam_user(exam.get_id(), target, seq, db) | 953 | AnswerImage::list_for_exam_user(exam.get_id(), target, seq, db) |
src/web/exams/mod.rsmodified+3 -1
| @@ -1,4 +1,4 @@ | |||
| 1 | -use std::collections::HashMap; | 1 | +use std::collections::{HashMap, HashSet}; |
| 2 | 2 | ||
| 3 | use axum::Json; | 3 | use axum::Json; |
| 4 | use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; | 4 | use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; |
| @@ -399,6 +399,7 @@ async fn get_exam( | |||
| 399 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | 399 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 400 | (status = 404, description = "Not found", body = ErrorResponse), | 400 | (status = 404, description = "Not found", body = ErrorResponse), |
| 401 | (status = 409, description = "Mode change after attempts started, re-drafting an exam that has attempts or results, a kind change on an exam that already carries marks, or the exam kept changing under concurrent edits", body = ErrorResponse), | 401 | (status = 409, description = "Mode change after attempts started, re-drafting an exam that has attempts or results, a kind change on an exam that already carries marks, or the exam kept changing under concurrent edits", body = ErrorResponse), |
| 402 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 402 | ), | 403 | ), |
| 403 | )] | 404 | )] |
| 404 | async fn update_exam( | 405 | async fn update_exam( |
| @@ -621,6 +622,7 @@ async fn delete_exam( | |||
| 621 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse), | 622 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse), |
| 622 | (status = 404, description = "Exam not found", body = ErrorResponse), | 623 | (status = 404, description = "Exam not found", body = ErrorResponse), |
| 623 | (status = 409, description = "The exam is a draft, or its kind has been removed from the school's settings", body = ErrorResponse), | 624 | (status = 409, description = "The exam is a draft, or its kind has been removed from the school's settings", body = ErrorResponse), |
| 625 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 624 | ), | 626 | ), |
| 625 | )] | 627 | )] |
| 626 | async fn grade( | 628 | async fn grade( |
src/web/exams/questions.rsmodified+15 -4
| @@ -201,6 +201,7 @@ pub(crate) fn choice_slot(question: &ExamQuestion, choice_id: &str) -> Result<Ch | |||
| 201 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | 201 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 202 | (status = 404, description = "Exam not found", body = ErrorResponse), | 202 | (status = 404, description = "Exam not found", body = ErrorResponse), |
| 203 | (status = 409, description = "Attempts have started β questions are frozen", body = ErrorResponse), | 203 | (status = 409, description = "Attempts have started β questions are frozen", body = ErrorResponse), |
| 204 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 204 | ), | 205 | ), |
| 205 | )] | 206 | )] |
| 206 | pub(crate) async fn create_question( | 207 | pub(crate) async fn create_question( |
| @@ -278,16 +279,20 @@ pub(crate) async fn list_questions( | |||
| 278 | "only the course creator, an assigned teacher, or a manager/admin can read the question list", | 279 | "only the course creator, an assigned teacher, or a manager/admin can read the question list", |
| 279 | )); | 280 | )); |
| 280 | } | 281 | } |
| 281 | - Ok(Json(question_page(&exam, limit, offset, &st.db).await?)) | 282 | + Ok(Json( |
| 283 | + question_page(&exam, limit, offset, &HashSet::new(), &st.db).await?, | ||
| 284 | + )) | ||
| 282 | } | 285 | } |
| 283 | 286 | ||
| 284 | /// The paged answer-key list (`correct` included) shared by the teacher | 287 | /// The paged answer-key list (`correct` included) shared by the teacher |
| 285 | /// `list_questions` read and the student `review_questions` read β the two | 288 | /// `list_questions` read and the student `review_questions` read β the two |
| 286 | -/// differ only in the access wall they run first. | 289 | +/// differ only in the access wall they run first, and in `hidden`: the question |
| 290 | +/// ids whose `correct` must come back `null` (empty for a teacher). | ||
| 287 | pub(crate) async fn question_page( | 291 | pub(crate) async fn question_page( |
| 288 | exam: &Exam, | 292 | exam: &Exam, |
| 289 | limit: Option<i64>, | 293 | limit: Option<i64>, |
| 290 | offset: i64, | 294 | offset: i64, |
| 295 | + hidden: &HashSet<String>, | ||
| 291 | db: &Database, | 296 | db: &Database, |
| 292 | ) -> Result<Page<QuestionResponse>, AppError> { | 297 | ) -> Result<Page<QuestionResponse>, AppError> { |
| 293 | let (questions, total) = ExamQuestion::list_for_exam(exam.get_id(), limit, offset, db).await?; | 298 | let (questions, total) = ExamQuestion::list_for_exam(exam.get_id(), limit, offset, db).await?; |
| @@ -295,12 +300,16 @@ pub(crate) async fn question_page( | |||
| 295 | let items = questions | 300 | let items = questions |
| 296 | .iter() | 301 | .iter() |
| 297 | .map(|question| { | 302 | .map(|question| { |
| 298 | - QuestionResponse::new( | 303 | + let mut item = QuestionResponse::new( |
| 299 | question, | 304 | question, |
| 300 | images | 305 | images |
| 301 | .get(question.get_id().key()) | 306 | .get(question.get_id().key()) |
| 302 | .map_or(&[][..], Vec::as_slice), | 307 | .map_or(&[][..], Vec::as_slice), |
| 303 | - ) | 308 | + ); |
| 309 | + if hidden.contains(question.get_id().key()) { | ||
| 310 | + item.correct = None; | ||
| 311 | + } | ||
| 312 | + item | ||
| 304 | }) | 313 | }) |
| 305 | .collect(); | 314 | .collect(); |
| 306 | Ok(Page::new(items, total, limit, offset)) | 315 | Ok(Page::new(items, total, limit, offset)) |
| @@ -330,6 +339,7 @@ pub(crate) async fn question_page( | |||
| 330 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | 339 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 331 | (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), | 340 | (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), |
| 332 | (status = 409, description = "Attempts have started β questions are frozen, or the subject the question was read on changed since β nothing was written, re-read and retry", body = ErrorResponse), | 341 | (status = 409, description = "Attempts have started β questions are frozen, or the subject the question was read on changed since β nothing was written, re-read and retry", body = ErrorResponse), |
| 342 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 333 | ), | 343 | ), |
| 334 | )] | 344 | )] |
| 335 | pub(crate) async fn update_question( | 345 | pub(crate) async fn update_question( |
| @@ -487,6 +497,7 @@ pub(crate) struct InstantiateFromBank { | |||
| 487 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | 497 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 488 | (status = 404, description = "No such exam, or no bank template the caller may see", body = ErrorResponse), | 498 | (status = 404, description = "No such exam, or no bank template the caller may see", body = ErrorResponse), |
| 489 | (status = 409, description = "Attempts have started β questions are frozen", body = ErrorResponse), | 499 | (status = 409, description = "Attempts have started β questions are frozen", body = ErrorResponse), |
| 500 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 490 | ), | 501 | ), |
| 491 | )] | 502 | )] |
| 492 | pub(crate) async fn question_from_bank( | 503 | pub(crate) async fn question_from_bank( |
src/web/exams/review.rsmodified+60 -4
| @@ -83,7 +83,9 @@ pub(crate) async fn student_attempt_answers( | |||
| 83 | ) -> Result<Json<AttemptAnswersResponse>, AppError> { | 83 | ) -> Result<Json<AttemptAnswersResponse>, AppError> { |
| 84 | let exam = gradable_exam(&st, &user, &id).await?; | 84 | let exam = gradable_exam(&st, &user, &id).await?; |
| 85 | let target = UserId::from_key(&target); | 85 | let target = UserId::from_key(&target); |
| 86 | - Ok(Json(answer_sheet(&exam, &target, seq, &st.db).await?)) | 86 | + Ok(Json( |
| 87 | + answer_sheet(&exam, &target, seq, &HashSet::new(), &st.db).await?, | ||
| 88 | + )) | ||
| 87 | } | 89 | } |
| 88 | 90 | ||
| 89 | /// A prior sitting's drawn-answer bytes. Requires teacher+ and management | 91 | /// A prior sitting's drawn-answer bytes. Requires teacher+ and management |
| @@ -207,6 +209,43 @@ pub(crate) async fn reviewable_exam( | |||
| 207 | Ok(exam) | 209 | Ok(exam) |
| 208 | } | 210 | } |
| 209 | 211 | ||
| 212 | +/// The questions of `exam` whose answer key is live somewhere else right now: | ||
| 213 | +/// the bank templates that were also copied into an exam the caller has a | ||
| 214 | +/// sitting open on. The bank is copy-into-exam, so one template's `correct` | ||
| 215 | +/// lands verbatim in every exam it is instantiated into β reviewing a graded | ||
| 216 | +/// exam A would otherwise hand out the key to the very question the caller is | ||
| 217 | +/// still answering in exam B. | ||
| 218 | +/// | ||
| 219 | +/// Keyed on the template, never on the exam: a reviewed exam still reviews in | ||
| 220 | +/// full, and only the overlapping questions blank out. Both link directions | ||
| 221 | +/// count β a question authored by hand and *saved* to the bank shares its key | ||
| 222 | +/// with every later instantiation just as an instantiated one does, so only a | ||
| 223 | +/// question with no bank link at all is never hidden | ||
| 224 | +/// ([`ExamQuestion::list_shared_with`]). | ||
| 225 | +/// | ||
| 226 | +/// The open sittings are read whole and judged here rather than filtered in | ||
| 227 | +/// SurrealQL, because "in progress" is [`ExamAttempt::status`]'s call off the | ||
| 228 | +/// exam's *live* schedule and that rule lives in one place. One exam read per | ||
| 229 | +/// unsubmitted sitting β a student has at most a handful, and none of it scales | ||
| 230 | +/// with the page being read. | ||
| 231 | +async fn live_elsewhere( | ||
| 232 | + st: &AppState, | ||
| 233 | + user: &User, | ||
| 234 | + exam: &Exam, | ||
| 235 | +) -> Result<HashSet<String>, AppError> { | ||
| 236 | + let now = Timestamp::now(); | ||
| 237 | + let mut live = Vec::new(); | ||
| 238 | + for attempt in ExamAttempt::list_unfinished_for_user(user.get_id(), &st.db).await? { | ||
| 239 | + let Some(other) = Exam::read(attempt.get_exam(), &st.db).await? else { | ||
| 240 | + continue; | ||
| 241 | + }; | ||
| 242 | + if attempt.status(&other, now) == AttemptStatus::InProgress { | ||
| 243 | + live.push(other.get_id().clone()); | ||
| 244 | + } | ||
| 245 | + } | ||
| 246 | + ExamQuestion::list_shared_with(exam.get_id(), &live, &st.db).await | ||
| 247 | +} | ||
| 248 | + | ||
| 210 | /// The caller's own sitting numbers at an exam β every seq that carries answers | 249 | /// The caller's own sitting numbers at an exam β every seq that carries answers |
| 211 | /// or a mark, ascending. Own-scoped review view; opens once the teacher enables | 250 | /// or a mark, ascending. Own-scoped review view; opens once the teacher enables |
| 212 | /// review and has marked the caller, and closes again (409) while the caller has | 251 | /// review and has marked the caller, and closes again (409) while the caller has |
| @@ -246,6 +285,13 @@ pub(crate) async fn review_attempts( | |||
| 246 | /// self-review reads; revealing `correct` is the point (the gate already proves | 285 | /// self-review reads; revealing `correct` is the point (the gate already proves |
| 247 | /// the caller was marked and has no sitting still open). Paged via | 286 | /// the caller was marked and has no sitting still open). Paged via |
| 248 | /// `?limit=&offset=`. | 287 | /// `?limit=&offset=`. |
| 288 | +/// | ||
| 289 | +/// One exception, per question: a question tied to a question-bank template β | ||
| 290 | +/// added out of the bank, or saved into it β comes back with `correct: null` | ||
| 291 | +/// while the caller has a sitting open on *another* exam holding a question | ||
| 292 | +/// tied to that same template, since the copy would be that sitting's answer | ||
| 293 | +/// key. The rest of the list is unaffected, and the `correct` | ||
| 294 | +/// returns once that sitting is submitted or expires. | ||
| 249 | #[utoipa::path( | 295 | #[utoipa::path( |
| 250 | get, | 296 | get, |
| 251 | path = "/{id}/review/questions", | 297 | path = "/{id}/review/questions", |
| @@ -253,7 +299,7 @@ pub(crate) async fn review_attempts( | |||
| 253 | security(("session_cookie" = [])), | 299 | security(("session_cookie" = [])), |
| 254 | params(("id" = String, Path, description = "Exam id"), PageParams), | 300 | params(("id" = String, Path, description = "Exam id"), PageParams), |
| 255 | responses( | 301 | responses( |
| 256 | - (status = 200, description = "A page of the exam's questions with `correct` (all of them when unpaged)", body = Page<QuestionResponse>), | 302 | + (status = 200, description = "A page of the exam's questions with `correct` (all of them when unpaged); `correct` is `null` on a question whose bank template the caller has live under an open sitting elsewhere", body = Page<QuestionResponse>), |
| 257 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), | 303 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 258 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 304 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 259 | (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), | 305 | (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), |
| @@ -269,13 +315,20 @@ pub(crate) async fn review_questions( | |||
| 269 | ) -> Result<Json<Page<QuestionResponse>>, AppError> { | 315 | ) -> Result<Json<Page<QuestionResponse>>, AppError> { |
| 270 | let (limit, offset) = page.resolve()?; | 316 | let (limit, offset) = page.resolve()?; |
| 271 | let exam = reviewable_exam(&st, &user, &id).await?; | 317 | let exam = reviewable_exam(&st, &user, &id).await?; |
| 272 | - Ok(Json(question_page(&exam, limit, offset, &st.db).await?)) | 318 | + let hidden = live_elsewhere(&st, &user, &exam).await?; |
| 319 | + Ok(Json( | ||
| 320 | + question_page(&exam, limit, offset, &hidden, &st.db).await?, | ||
| 321 | + )) | ||
| 273 | } | 322 | } |
| 274 | 323 | ||
| 275 | /// One of the caller's own sittings, judged β the `seq`th attempt's answers, | 324 | /// One of the caller's own sittings, judged β the `seq`th attempt's answers, |
| 276 | /// drawing refs, correctness flags, and auto-score suggestion. Own-scoped | 325 | /// drawing refs, correctness flags, and auto-score suggestion. Own-scoped |
| 277 | /// review view; 409 while the caller has a sitting in progress, so a retake | 326 | /// review view; 409 while the caller has a sitting in progress, so a retake |
| 278 | /// can't read its own correctness off an earlier seq. | 327 | /// can't read its own correctness off an earlier seq. |
| 328 | +/// | ||
| 329 | +/// A question the caller has live under an open sitting on another exam (same | ||
| 330 | +/// bank template) comes back with `is_correct: null` and is left out of | ||
| 331 | +/// `auto_score` β the same redaction `GET /{id}/review/questions` makes. | ||
| 279 | #[utoipa::path( | 332 | #[utoipa::path( |
| 280 | get, | 333 | get, |
| 281 | path = "/{id}/review/attempts/{seq}/answers", | 334 | path = "/{id}/review/attempts/{seq}/answers", |
| @@ -299,7 +352,10 @@ pub(crate) async fn review_attempt_answers( | |||
| 299 | Path((id, seq)): Path<(String, i64)>, | 352 | Path((id, seq)): Path<(String, i64)>, |
| 300 | ) -> Result<Json<AttemptAnswersResponse>, AppError> { | 353 | ) -> Result<Json<AttemptAnswersResponse>, AppError> { |
| 301 | let exam = reviewable_exam(&st, &user, &id).await?; | 354 | let exam = reviewable_exam(&st, &user, &id).await?; |
| 302 | - Ok(Json(answer_sheet(&exam, user.get_id(), seq, &st.db).await?)) | 355 | + let hidden = live_elsewhere(&st, &user, &exam).await?; |
| 356 | + Ok(Json( | ||
| 357 | + answer_sheet(&exam, user.get_id(), seq, &hidden, &st.db).await?, | ||
| 358 | + )) | ||
| 303 | } | 359 | } |
| 304 | 360 | ||
| 305 | /// The caller's own drawn-answer bytes for one of their sittings β the | 361 | /// The caller's own drawn-answer bytes for one of their sittings β the |
src/web/homework.rsmodified+3 -0
| @@ -301,6 +301,7 @@ struct UpdateHomework { | |||
| 301 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | 301 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 302 | (status = 404, description = "Not found", body = ErrorResponse), | 302 | (status = 404, description = "Not found", body = ErrorResponse), |
| 303 | (status = 409, description = "Narrowing the assigned list would orphan an existing submission or result, or the subject this update re-tags from changed since the caller read it β nothing was written, re-read and retry", body = ErrorResponse), | 303 | (status = 409, description = "Narrowing the assigned list would orphan an existing submission or result, or the subject this update re-tags from changed since the caller read it β nothing was written, re-read and retry", body = ErrorResponse), |
| 304 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 304 | ), | 305 | ), |
| 305 | )] | 306 | )] |
| 306 | async fn update_homework( | 307 | async fn update_homework( |
| @@ -616,6 +617,7 @@ struct SubmitHomework { | |||
| 616 | (status = 403, description = "Not a student, or not enrolled in the homework's course", body = ErrorResponse), | 617 | (status = 403, description = "Not a student, or not enrolled in the homework's course", body = ErrorResponse), |
| 617 | (status = 404, description = "No such homework (or a subset assignment the caller is not part of)", body = ErrorResponse), | 618 | (status = 404, description = "No such homework (or a subset assignment the caller is not part of)", body = ErrorResponse), |
| 618 | (status = 409, description = "The homework has been graded β the submission is frozen until the grade is removed", body = ErrorResponse), | 619 | (status = 409, description = "The homework has been graded β the submission is frozen until the grade is removed", body = ErrorResponse), |
| 620 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 619 | ), | 621 | ), |
| 620 | )] | 622 | )] |
| 621 | async fn submit( | 623 | async fn submit( |
| @@ -1028,6 +1030,7 @@ struct GradeHomework { | |||
| 1028 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 1030 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1029 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse), | 1031 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse), |
| 1030 | (status = 404, description = "Homework not found", body = ErrorResponse), | 1032 | (status = 404, description = "Homework not found", body = ErrorResponse), |
| 1033 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 1031 | ), | 1034 | ), |
| 1032 | )] | 1035 | )] |
| 1033 | async fn grade_homework( | 1036 | async fn grade_homework( |
src/web/meals.rsmodified+8 -0
| @@ -244,6 +244,7 @@ async fn one_menu( | |||
| 244 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 244 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 245 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 245 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 246 | (status = 409, description = "A menu already exists for that date and slot, or the slot was removed from the settings mid-request", body = ErrorResponse), | 246 | (status = 409, description = "A menu already exists for that date and slot, or the slot was removed from the settings mid-request", body = ErrorResponse), |
| 247 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 247 | ), | 248 | ), |
| 248 | )] | 249 | )] |
| 249 | async fn create_menu( | 250 | async fn create_menu( |
| @@ -329,6 +330,7 @@ async fn get_menu( | |||
| 329 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 330 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 330 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 331 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 331 | (status = 404, description = "Not found", body = ErrorResponse), | 332 | (status = 404, description = "Not found", body = ErrorResponse), |
| 333 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 332 | ), | 334 | ), |
| 333 | )] | 335 | )] |
| 334 | async fn update_menu( | 336 | async fn update_menu( |
| @@ -394,6 +396,7 @@ async fn delete_menu( | |||
| 394 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 396 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 395 | (status = 404, description = "No such menu", body = ErrorResponse), | 397 | (status = 404, description = "No such menu", body = ErrorResponse), |
| 396 | (status = 409, description = "The menu already carries the maximum number of dishes", body = ErrorResponse), | 398 | (status = 409, description = "The menu already carries the maximum number of dishes", body = ErrorResponse), |
| 399 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 397 | ), | 400 | ), |
| 398 | )] | 401 | )] |
| 399 | async fn add_dish( | 402 | async fn add_dish( |
| @@ -454,6 +457,7 @@ async fn add_dish( | |||
| 454 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 457 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 455 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 458 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 456 | (status = 404, description = "Not found", body = ErrorResponse), | 459 | (status = 404, description = "Not found", body = ErrorResponse), |
| 460 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 457 | ), | 461 | ), |
| 458 | )] | 462 | )] |
| 459 | async fn update_dish( | 463 | async fn update_dish( |
| @@ -636,6 +640,7 @@ async fn user_profile( | |||
| 636 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 640 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 637 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 641 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 638 | (status = 404, description = "No such user", body = ErrorResponse), | 642 | (status = 404, description = "No such user", body = ErrorResponse), |
| 643 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 639 | ), | 644 | ), |
| 640 | )] | 645 | )] |
| 641 | async fn update_profile( | 646 | async fn update_profile( |
| @@ -809,6 +814,7 @@ async fn booking_target( | |||
| 809 | (status = 403, description = "Not a student booking for themselves, nor a parent booking for a linked student", body = ErrorResponse), | 814 | (status = 403, description = "Not a student booking for themselves, nor a parent booking for a linked student", body = ErrorResponse), |
| 810 | (status = 404, description = "No such menu", body = ErrorResponse), | 815 | (status = 404, description = "No such menu", body = ErrorResponse), |
| 811 | (status = 409, description = "The menu is full, its cutoff has passed, or the menu kept being edited while the seat was being taken", body = ErrorResponse), | 816 | (status = 409, description = "The menu is full, its cutoff has passed, or the menu kept being edited while the seat was being taken", body = ErrorResponse), |
| 817 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 812 | ), | 818 | ), |
| 813 | )] | 819 | )] |
| 814 | async fn book_meal( | 820 | async fn book_meal( |
| @@ -1059,6 +1065,7 @@ async fn attendance_responses( | |||
| 1059 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 1065 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1060 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 1066 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 1061 | (status = 404, description = "No such menu", body = ErrorResponse), | 1067 | (status = 404, description = "No such menu", body = ErrorResponse), |
| 1068 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 1062 | ), | 1069 | ), |
| 1063 | )] | 1070 | )] |
| 1064 | async fn mark_attendance( | 1071 | async fn mark_attendance( |
| @@ -1397,6 +1404,7 @@ struct RecordCredit { | |||
| 1397 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 1404 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1398 | (status = 403, description = "Requires the admin role", body = ErrorResponse), | 1405 | (status = 403, description = "Requires the admin role", body = ErrorResponse), |
| 1399 | (status = 404, description = "No such user", body = ErrorResponse), | 1406 | (status = 404, description = "No such user", body = ErrorResponse), |
| 1407 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 1400 | ), | 1408 | ), |
| 1401 | )] | 1409 | )] |
| 1402 | async fn record_credit( | 1410 | async fn record_credit( |
src/web/messages.rsmodified+2 -0
| @@ -172,6 +172,7 @@ impl MessageResponse { | |||
| 172 | (status = 400, description = "Invalid subject or body, or the recipient is yourself", body = ErrorResponse), | 172 | (status = 400, description = "Invalid subject or body, or the recipient is yourself", body = ErrorResponse), |
| 173 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 173 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 174 | (status = 404, description = "No such recipient", body = ErrorResponse), | 174 | (status = 404, description = "No such recipient", body = ErrorResponse), |
| 175 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 175 | ), | 176 | ), |
| 176 | )] | 177 | )] |
| 177 | async fn send_message( | 178 | async fn send_message( |
| @@ -270,6 +271,7 @@ async fn list( | |||
| 270 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 271 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 271 | (status = 403, description = "Only the recipient can change the read flag", body = ErrorResponse), | 272 | (status = 403, description = "Only the recipient can change the read flag", body = ErrorResponse), |
| 272 | (status = 404, description = "Not found (or not a party to it)", body = ErrorResponse), | 273 | (status = 404, description = "Not found (or not a party to it)", body = ErrorResponse), |
| 274 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 273 | ), | 275 | ), |
| 274 | )] | 276 | )] |
| 275 | async fn update_message( | 277 | async fn update_message( |
src/web/mod.rsmodified+2 -1
| @@ -402,7 +402,8 @@ mod tests { | |||
| 402 | .unwrap() | 402 | .unwrap() |
| 403 | .set_role(Role::Teacher, &db) | 403 | .set_role(Role::Teacher, &db) |
| 404 | .await | 404 | .await |
| 405 | - .unwrap(); | 405 | + .unwrap() |
| 406 | + .0; | ||
| 406 | 407 | ||
| 407 | let assigned = async |db: &Database| { | 408 | let assigned = async |db: &Database| { |
| 408 | let class = ClassGroup::create( | 409 | let class = ClassGroup::create( |
src/web/notes.rsmodified+5 -3
| @@ -81,6 +81,7 @@ impl NoteResponse { | |||
| 81 | (status = 400, description = "Invalid title or content", body = ErrorResponse), | 81 | (status = 400, description = "Invalid title or content", body = ErrorResponse), |
| 82 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 82 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 83 | (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | 83 | (status = 403, description = "Requires the student role or higher", body = ErrorResponse), |
| 84 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 84 | ), | 85 | ), |
| 85 | )] | 86 | )] |
| 86 | async fn create( | 87 | async fn create( |
| @@ -160,6 +161,7 @@ async fn get_one( | |||
| 160 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 161 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 161 | (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | 162 | (status = 403, description = "Requires the student role or higher", body = ErrorResponse), |
| 162 | (status = 404, description = "Not found", body = ErrorResponse), | 163 | (status = 404, description = "Not found", body = ErrorResponse), |
| 164 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 163 | ), | 165 | ), |
| 164 | )] | 166 | )] |
| 165 | async fn update( | 167 | async fn update( |
| @@ -211,9 +213,9 @@ async fn delete_one( | |||
| 211 | .ok_or(AppError::NotFound)?; | 213 | .ok_or(AppError::NotFound)?; |
| 212 | // Rows go first (the note delete cascades them), blobs after: a crash in | 214 | // Rows go first (the note delete cascades them), blobs after: a crash in |
| 213 | // between strands at worst an unreachable blob, never a row whose blob is | 215 | // between strands at worst an unreachable blob, never a row whose blob is |
| 214 | - // already gone. | 216 | + // already gone. The files to unlink come from the delete itself, not a |
| 215 | - let (files, _) = NoteFile::list_for(note.get_id(), None, 0, &st.db).await?; | 217 | + // pre-read list β an upload that landed in between is in the cascade too. |
| 216 | - note.delete(&st.db).await?; | 218 | + let (_, files) = note.delete(&st.db).await?; |
| 217 | for file in &files { | 219 | for file in &files { |
| 218 | remove_blob(&st.files_path, file.get_id().key()).await; | 220 | remove_blob(&st.files_path, file.get_id().key()).await; |
| 219 | } | 221 | } |
src/web/payments.rsmodified+6 -0
| @@ -170,6 +170,7 @@ async fn require_plan(id: &str, db: &Database) -> Result<FeePlan, AppError> { | |||
| 170 | (status = 400, description = "Invalid name, amount, or installment count", body = ErrorResponse), | 170 | (status = 400, description = "Invalid name, amount, or installment count", body = ErrorResponse), |
| 171 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 171 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 172 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 172 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 173 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 173 | ), | 174 | ), |
| 174 | )] | 175 | )] |
| 175 | async fn create_plan( | 176 | async fn create_plan( |
| @@ -267,6 +268,7 @@ async fn get_plan( | |||
| 267 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 268 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 268 | (status = 404, description = "No such plan", body = ErrorResponse), | 269 | (status = 404, description = "No such plan", body = ErrorResponse), |
| 269 | (status = 409, description = "The plan is already assigned to a student", body = ErrorResponse), | 270 | (status = 409, description = "The plan is already assigned to a student", body = ErrorResponse), |
| 271 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 270 | ), | 272 | ), |
| 271 | )] | 273 | )] |
| 272 | async fn update_plan( | 274 | async fn update_plan( |
| @@ -376,6 +378,7 @@ struct FeePlanAssignmentResponse { | |||
| 376 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 378 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 377 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 379 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 378 | (status = 404, description = "No such plan", body = ErrorResponse), | 380 | (status = 404, description = "No such plan", body = ErrorResponse), |
| 381 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 379 | ), | 382 | ), |
| 380 | )] | 383 | )] |
| 381 | async fn assign_plan( | 384 | async fn assign_plan( |
| @@ -630,6 +633,7 @@ fn request_key_of(raw: Option<&str>) -> Result<Option<PaymentRequestKey>, AppErr | |||
| 630 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 633 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 631 | (status = 404, description = "No such ledger line", body = ErrorResponse), | 634 | (status = 404, description = "No such ledger line", body = ErrorResponse), |
| 632 | (status = 409, description = "The charge is already paid in full, or the request_key was used for a different amount or charge", body = ErrorResponse), | 635 | (status = 409, description = "The charge is already paid in full, or the request_key was used for a different amount or charge", body = ErrorResponse), |
| 636 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 633 | ), | 637 | ), |
| 634 | )] | 638 | )] |
| 635 | async fn record_payment( | 639 | async fn record_payment( |
| @@ -671,6 +675,7 @@ async fn record_payment( | |||
| 671 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 675 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 672 | (status = 404, description = "No such ledger line", body = ErrorResponse), | 676 | (status = 404, description = "No such ledger line", body = ErrorResponse), |
| 673 | (status = 409, description = "The payment is already refunded in full, or the request_key was used for a different amount or payment", body = ErrorResponse), | 677 | (status = 409, description = "The payment is already refunded in full, or the request_key was used for a different amount or payment", body = ErrorResponse), |
| 678 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 674 | ), | 679 | ), |
| 675 | )] | 680 | )] |
| 676 | async fn record_refund( | 681 | async fn record_refund( |
| @@ -709,6 +714,7 @@ async fn record_refund( | |||
| 709 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 714 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 710 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 715 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 711 | (status = 404, description = "No such ledger line", body = ErrorResponse), | 716 | (status = 404, description = "No such ledger line", body = ErrorResponse), |
| 717 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 712 | ), | 718 | ), |
| 713 | )] | 719 | )] |
| 714 | async fn record_reversal( | 720 | async fn record_reversal( |
src/web/questions.rsmodified+3 -0
| @@ -251,6 +251,7 @@ async fn question_responses( | |||
| 251 | (status = 400, description = "Invalid title or body", body = ErrorResponse), | 251 | (status = 400, description = "Invalid title or body", body = ErrorResponse), |
| 252 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 252 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 253 | (status = 403, description = "Requires the student role", body = ErrorResponse), | 253 | (status = 403, description = "Requires the student role", body = ErrorResponse), |
| 254 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 254 | ), | 255 | ), |
| 255 | )] | 256 | )] |
| 256 | async fn ask_question( | 257 | async fn ask_question( |
| @@ -618,6 +619,7 @@ async fn author_solution( | |||
| 618 | (status = 403, description = "Requires student role or higher", body = ErrorResponse), | 619 | (status = 403, description = "Requires student role or higher", body = ErrorResponse), |
| 619 | (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse), | 620 | (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse), |
| 620 | (status = 409, description = "The question is not approved yet", body = ErrorResponse), | 621 | (status = 409, description = "The question is not approved yet", body = ErrorResponse), |
| 622 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 621 | ), | 623 | ), |
| 622 | )] | 624 | )] |
| 623 | async fn offer_solution( | 625 | async fn offer_solution( |
| @@ -742,6 +744,7 @@ async fn delete_solution( | |||
| 742 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 744 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 743 | (status = 403, description = "Not the author", body = ErrorResponse), | 745 | (status = 403, description = "Not the author", body = ErrorResponse), |
| 744 | (status = 404, description = "No such question or solution", body = ErrorResponse), | 746 | (status = 404, description = "No such question or solution", body = ErrorResponse), |
| 747 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 745 | ), | 748 | ), |
| 746 | )] | 749 | )] |
| 747 | async fn edit_solution( | 750 | async fn edit_solution( |
src/web/sessions.rsmodified+2 -0
| @@ -191,6 +191,7 @@ async fn get_session( | |||
| 191 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 191 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 192 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | 192 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 193 | (status = 404, description = "Not found", body = ErrorResponse), | 193 | (status = 404, description = "Not found", body = ErrorResponse), |
| 194 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 194 | ), | 195 | ), |
| 195 | )] | 196 | )] |
| 196 | async fn update_session( | 197 | async fn update_session( |
| @@ -295,6 +296,7 @@ async fn delete_session( | |||
| 295 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 296 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 296 | (status = 403, description = "Not the session teacher or a course manager; or marking the teacher without manager+", body = ErrorResponse), | 297 | (status = 403, description = "Not the session teacher or a course manager; or marking the teacher without manager+", body = ErrorResponse), |
| 297 | (status = 404, description = "Session not found", body = ErrorResponse), | 298 | (status = 404, description = "Session not found", body = ErrorResponse), |
| 299 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 298 | ), | 300 | ), |
| 299 | )] | 301 | )] |
| 300 | async fn mark_roll_call( | 302 | async fn mark_roll_call( |
src/web/settings.rsmodified+1 -0
| @@ -258,6 +258,7 @@ async fn get_settings( | |||
| 258 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 258 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 259 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 259 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 260 | (status = 409, description = "A removed exam kind still has graded exams, a removed meal slot still has published menus, or concurrent edits kept changing the settings mid-save", body = ErrorResponse), | 260 | (status = 409, description = "A removed exam kind still has graded exams, a removed meal slot still has published menus, or concurrent edits kept changing the settings mid-save", body = ErrorResponse), |
| 261 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 261 | ), | 262 | ), |
| 262 | )] | 263 | )] |
| 263 | async fn update_settings( | 264 | async fn update_settings( |
src/web/subjects.rsmodified+1 -0
| @@ -125,6 +125,7 @@ async fn get_subject( | |||
| 125 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 125 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 126 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | 126 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 127 | (status = 404, description = "Not found", body = ErrorResponse), | 127 | (status = 404, description = "Not found", body = ErrorResponse), |
| 128 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 128 | ), | 129 | ), |
| 129 | )] | 130 | )] |
| 130 | async fn update_subject( | 131 | async fn update_subject( |
src/web/terms.rsmodified+2 -0
| @@ -95,6 +95,7 @@ pub(crate) async fn resolve_term( | |||
| 95 | (status = 400, description = "Invalid name or range", body = ErrorResponse), | 95 | (status = 400, description = "Invalid name or range", body = ErrorResponse), |
| 96 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 96 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 97 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 97 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 98 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 98 | ), | 99 | ), |
| 99 | )] | 100 | )] |
| 100 | async fn create_term( | 101 | async fn create_term( |
| @@ -176,6 +177,7 @@ async fn get_term( | |||
| 176 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 177 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 177 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 178 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 178 | (status = 404, description = "Not found", body = ErrorResponse), | 179 | (status = 404, description = "Not found", body = ErrorResponse), |
| 180 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 179 | ), | 181 | ), |
| 180 | )] | 182 | )] |
| 181 | async fn update_term( | 183 | async fn update_term( |
src/web/users.rsmodified+30 -79
| @@ -8,14 +8,9 @@ use utoipa_axum::router::OpenApiRouter; | |||
| 8 | use utoipa_axum::routes; | 8 | use utoipa_axum::routes; |
| 9 | 9 | ||
| 10 | use crate::database::Database; | 10 | use crate::database::Database; |
| 11 | -use crate::domain::board::Board; | ||
| 12 | -use crate::domain::class_group::ClassGroup; | ||
| 13 | -use crate::domain::class_pump; | ||
| 14 | -use crate::domain::course::Course; | ||
| 15 | use crate::domain::parent_link::ParentLink; | 11 | use crate::domain::parent_link::ParentLink; |
| 16 | use crate::domain::preferences::{Language, PaletteColor, Theme}; | 12 | use crate::domain::preferences::{Language, PaletteColor, Theme}; |
| 17 | use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; | 13 | use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; |
| 18 | -use crate::domain::registration::Registration; | ||
| 19 | use crate::domain::role::Role; | 14 | use crate::domain::role::Role; |
| 20 | use crate::domain::user::{User, UserId}; | 15 | use crate::domain::user::{User, UserId}; |
| 21 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 16 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| @@ -239,6 +234,7 @@ async fn list_users( | |||
| 239 | (status = 200, description = "Updated user", body = UserResponse), | 234 | (status = 200, description = "Updated user", body = UserResponse), |
| 240 | (status = 400, description = "Invalid field", body = ErrorResponse), | 235 | (status = 400, description = "Invalid field", body = ErrorResponse), |
| 241 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 236 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 237 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 242 | ), | 238 | ), |
| 243 | )] | 239 | )] |
| 244 | async fn update_my_profile( | 240 | async fn update_my_profile( |
| @@ -265,6 +261,7 @@ async fn update_my_profile( | |||
| 265 | (status = 200, description = "Updated user", body = UserResponse), | 261 | (status = 200, description = "Updated user", body = UserResponse), |
| 266 | (status = 400, description = "Invalid theme, language, or palette color", body = ErrorResponse), | 262 | (status = 400, description = "Invalid theme, language, or palette color", body = ErrorResponse), |
| 267 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 263 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 264 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 268 | ), | 265 | ), |
| 269 | )] | 266 | )] |
| 270 | async fn update_my_preferences( | 267 | async fn update_my_preferences( |
| @@ -316,6 +313,7 @@ async fn get_user( | |||
| 316 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 313 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 317 | (status = 403, description = "Requires admin role", body = ErrorResponse), | 314 | (status = 403, description = "Requires admin role", body = ErrorResponse), |
| 318 | (status = 404, description = "User not found", body = ErrorResponse), | 315 | (status = 404, description = "User not found", body = ErrorResponse), |
| 316 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 319 | ), | 317 | ), |
| 320 | )] | 318 | )] |
| 321 | async fn update_user_profile( | 319 | async fn update_user_profile( |
| @@ -346,6 +344,7 @@ async fn update_user_profile( | |||
| 346 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 344 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 347 | (status = 403, description = "Requires admin role", body = ErrorResponse), | 345 | (status = 403, description = "Requires admin role", body = ErrorResponse), |
| 348 | (status = 404, description = "User not found", body = ErrorResponse), | 346 | (status = 404, description = "User not found", body = ErrorResponse), |
| 347 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 349 | ), | 348 | ), |
| 350 | )] | 349 | )] |
| 351 | async fn update_user_preferences( | 350 | async fn update_user_preferences( |
| @@ -383,6 +382,7 @@ async fn update_user_preferences( | |||
| 383 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 382 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 384 | (status = 403, description = "Requires admin, or attempted to change own role", body = ErrorResponse), | 383 | (status = 403, description = "Requires admin, or attempted to change own role", body = ErrorResponse), |
| 385 | (status = 404, description = "User not found", body = ErrorResponse), | 384 | (status = 404, description = "User not found", body = ErrorResponse), |
| 385 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 386 | ), | 386 | ), |
| 387 | )] | 387 | )] |
| 388 | async fn set_role( | 388 | async fn set_role( |
| @@ -399,80 +399,30 @@ async fn set_role( | |||
| 399 | let user = User::read(&target, &st.db) | 399 | let user = User::read(&target, &st.db) |
| 400 | .await? | 400 | .await? |
| 401 | .ok_or(AppError::NotFound)?; | 401 | .ok_or(AppError::NotFound)?; |
| 402 | - let updated = user.set_role(role, &st.db).await?; | 402 | + // The role write and every sweep it owes commit together ([`User::set_role`] |
| 403 | - // KNOWN GAP (deliberate, not an oversight): the role write above and the | 403 | + // carries the whole list and the reasoning behind each arm). The write |
| 404 | - // sweeps below are separate statements, so a sweep that errors answers 500 | 404 | + // ordering *within* a request is closed from the other end: a handler that |
| 405 | - // with the role already lowered and some of the old grants still standing. | 405 | + // assigns a teacher-only role re-reads the live role after its write |
| 406 | - // Every one of them is idempotent and re-running the same PATCH repairs it, | 406 | + // ([`super::undo_if_demoted`]), so a demotion racing an assignment is caught |
| 407 | - // and every security gate re-reads the live role rather than trusting a | 407 | + // by whichever side is second. |
| 408 | - // swept row β the residue pollutes rosters and lists, it does not grant | 408 | + let (updated, boards) = user.set_role(role, &st.db).await?; |
| 409 | - // anything. Folding it into one transaction means folding eight tables plus | 409 | + // Whiteboard rooms whose roster the commit above changed, prompted with the |
| 410 | - // `class_pump`'s own transaction and the board-hub publish (an in-process | 410 | + // same `participants` frame the roster PATCH publishes β after the commit, |
| 411 | - // side effect that cannot sit inside a database transaction) β see the | 411 | + // because the room re-reads the database before it acts on the frame. |
| 412 | - // report accompanying this change. The write ordering *within* a request is | 412 | + for board in boards { |
| 413 | - // closed from the other end instead: a handler that assigns a teacher-only | 413 | + st.board_hub.publish( |
| 414 | - // role re-reads the live role after its write ([`super::undo_if_demoted`]), | 414 | + board.get_id().key(), |
| 415 | - // so a demotion racing an assignment is caught by whichever side is second. | 415 | + json!({ |
| 416 | - // Roster hygiene: only students enroll, so a non-student sheds all their | 416 | + "type": "participants", |
| 417 | - // enrollment rows (security checks re-read the live role and never | 417 | + "creator": board.get_creator().key(), |
| 418 | - // trusted these; this just stops them polluting rosters and counts). | 418 | + "participants": board |
| 419 | - // Parent links get the same sweep on both sides: only students are | 419 | + .get_participants() |
| 420 | - // observed and only parents observe, so a role change off either end | 420 | + .iter() |
| 421 | - // drops the rows instead of leaving dead grants around. | 421 | + .map(|user| user.key()) |
| 422 | - // The class memberships and the enrollments go in *one* transaction: run | 422 | + .collect::<Vec<_>>(), |
| 423 | - // as two, a failure between them left enrollment rows tagged with a class | 423 | + }) |
| 424 | - // whose counters had already been released, so the class could be deleted | 424 | + .to_string(), |
| 425 | - // and nothing could ever sweep the rows again. | 425 | + ); |
| 426 | - if role != Role::Student { | ||
| 427 | - class_pump::sweep_non_student(&target, &st.db).await?; | ||
| 428 | - ParentLink::delete_where_student(&target, &st.db).await?; | ||
| 429 | - } | ||
| 430 | - // Event signups are swept for a `parent` only β not for every non-student. | ||
| 431 | - // Staff free their own seats by hand (`DELETE /events/{id}/register/{me}` | ||
| 432 | - // allows the self case), so a promotion strands nothing and those signups | ||
| 433 | - // are the teacher's to keep; a parent can reach no such door, and nobody | ||
| 434 | - // else may free a non-student's seat, so theirs is the seat that would | ||
| 435 | - // stay claimed forever. Frozen lists are left alone β see the sweep. | ||
| 436 | - if role == Role::Parent { | ||
| 437 | - Registration::sweep_for_parent(&target, &st.db).await?; | ||
| 438 | - // Whiteboards: the role is barred from them outright, so a demoted user | ||
| 439 | - // comes off every roster they are listed on β otherwise they stay a | ||
| 440 | - // participant forever and their stale id 400s the creator's next roster | ||
| 441 | - // PATCH (`resolve_participants` refuses a below-student id). Nothing is | ||
| 442 | - // deleted, not even a board this empties: their own boards keep every | ||
| 443 | - // stroke and stay readable to the rest of the room, they simply have a | ||
| 444 | - // creator who can no longer use them. Each affected room is prompted | ||
| 445 | - // with the same `participants` frame the roster PATCH publishes β the | ||
| 446 | - // room re-reads the database before it acts on it. | ||
| 447 | - for board in Board::drop_participant_everywhere(&target, &st.db).await? { | ||
| 448 | - st.board_hub.publish( | ||
| 449 | - board.get_id().key(), | ||
| 450 | - json!({ | ||
| 451 | - "type": "participants", | ||
| 452 | - "creator": board.get_creator().key(), | ||
| 453 | - "participants": board | ||
| 454 | - .get_participants() | ||
| 455 | - .iter() | ||
| 456 | - .map(|user| user.key()) | ||
| 457 | - .collect::<Vec<_>>(), | ||
| 458 | - }) | ||
| 459 | - .to_string(), | ||
| 460 | - ); | ||
| 461 | - } | ||
| 462 | - } | ||
| 463 | - if role != Role::Parent { | ||
| 464 | - ParentLink::delete_where_parent(&target, &st.db).await?; | ||
| 465 | - } | ||
| 466 | - // Course staffing gets the same sweep: only teacher+ may be assigned to | ||
| 467 | - // run a course, so a demotion drops every assignment instead of leaving | ||
| 468 | - // rows that grant nothing and still list a demoted user as its teacher. | ||
| 469 | - if !role.at_least(Role::Teacher) { | ||
| 470 | - Course::unassign_everywhere(&target, &st.db).await?; | ||
| 471 | - // Same story for a class's homeroom teacher (sΔ±nΔ±f ΓΆΔretmeni): only | ||
| 472 | - // teacher+ may hold one, so a demotion clears the column everywhere | ||
| 473 | - // rather than leaving a class section (Εube) listing a demoted account | ||
| 474 | - // as its teacher. | ||
| 475 | - ClassGroup::unassign_everywhere(&target, &st.db).await?; | ||
| 476 | } | 426 | } |
| 477 | Ok(Json(UserResponse::new(&updated))) | 427 | Ok(Json(UserResponse::new(&updated))) |
| 478 | } | 428 | } |
| @@ -537,6 +487,7 @@ async fn students_page( | |||
| 537 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 487 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 538 | (status = 403, description = "Requires admin role", body = ErrorResponse), | 488 | (status = 403, description = "Requires admin role", body = ErrorResponse), |
| 539 | (status = 404, description = "Parent user not found", body = ErrorResponse), | 489 | (status = 404, description = "Parent user not found", body = ErrorResponse), |
| 490 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 540 | ), | 491 | ), |
| 541 | )] | 492 | )] |
| 542 | async fn link_student( | 493 | async fn link_student( |
src/web/work.rsmodified+1 -0
| @@ -182,6 +182,7 @@ async fn user_work( | |||
| 182 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 182 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 183 | (status = 404, description = "Not found", body = ErrorResponse), | 183 | (status = 404, description = "Not found", body = ErrorResponse), |
| 184 | (status = 409, description = "Entry is still open", body = ErrorResponse), | 184 | (status = 409, description = "Entry is still open", body = ErrorResponse), |
| 185 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 185 | ), | 186 | ), |
| 186 | )] | 187 | )] |
| 187 | async fn update_entry( | 188 | async fn update_entry( |
tests/integration.rsmodified+285 -77
| @@ -333,89 +333,101 @@ async fn login_rejects_bad_credentials() { | |||
| 333 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); | 333 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); |
| 334 | } | 334 | } |
| 335 | 335 | ||
| 336 | +/// Routes that answer without a session, on purpose. Adding a route here is a | ||
| 337 | +/// deliberate, reviewable decision to leave a door open β everything else in | ||
| 338 | +/// the spec is asserted to reject an anonymous caller with a 401. | ||
| 339 | +const PUBLIC: &[(&str, &str)] = &[ | ||
| 340 | + ("GET", "/health"), | ||
| 341 | + ("GET", "/time"), | ||
| 342 | + ("GET", "/limits"), | ||
| 343 | + ("POST", "/auth/register"), | ||
| 344 | + ("POST", "/auth/login"), | ||
| 345 | + // Idempotent: revokes the session if there is one, `204` either way. | ||
| 346 | + ("POST", "/auth/logout"), | ||
| 347 | + // A server certificate is handed to every peer in the TLS handshake, so | ||
| 348 | + // publishing it discloses nothing (see the module doc in `web/ai.rs`). | ||
| 349 | + ("GET", "/ai/certificate"), | ||
| 350 | +]; | ||
| 351 | + | ||
| 352 | +/// Router paths that carry no OpenAPI operation, so the derived sweep below | ||
| 353 | +/// cannot see them: `OpenApiRouter` has no way to describe a WebSocket | ||
| 354 | +/// upgrade, so both rooms are plain `.route()`s. They authenticate before they | ||
| 355 | +/// upgrade, so a rejection is an ordinary HTTP status here. | ||
| 356 | +const UNDOCUMENTED_WS: &[(&str, &str)] = &[("GET", "/exams/x/attempt/ws"), ("GET", "/boards/x/ws")]; | ||
| 357 | + | ||
| 358 | +/// Every protected operation the server publishes must reject a caller with no | ||
| 359 | +/// cookie β derived from the emitted OpenAPI document, never from a list | ||
| 360 | +/// somebody keeps by hand. A hand-kept list drifts silently, and the drift is | ||
| 361 | +/// auth coverage: ~10 route families were missing from the one this replaced. | ||
| 362 | +/// | ||
| 363 | +/// Route and spec entry come from the same `routes!()` macro, so a family that | ||
| 364 | +/// leaves the router leaves the document too; `MIN_PROTECTED` is what makes | ||
| 365 | +/// that visible instead of a quietly shorter sweep. | ||
| 336 | #[tokio::test] | 366 | #[tokio::test] |
| 337 | async fn protected_routes_require_session() { | 367 | async fn protected_routes_require_session() { |
| 368 | + /// Floor on the number of protected operations swept. It only ever goes | ||
| 369 | + /// up: raise it when routes are added. Without it, deleting a route family | ||
| 370 | + /// would delete its own coverage and still pass. | ||
| 371 | + const MIN_PROTECTED: usize = 254; | ||
| 372 | + | ||
| 338 | let app = mem_app().await; | 373 | let app = mem_app().await; |
| 339 | - for (method, uri) in [ | 374 | + let spec = send(&app, "GET", "/api-docs/openapi.json", None, None) |
| 340 | - ("GET", "/auth/me"), | 375 | + .await |
| 341 | - ("GET", "/notes"), | 376 | + .body; |
| 342 | - ("POST", "/notes"), | 377 | + let paths = spec["paths"].as_object().expect("spec has paths"); |
| 343 | - ("GET", "/events"), | 378 | + |
| 344 | - ("POST", "/events"), | 379 | + let mut checked = 0; |
| 345 | - ("POST", "/events/x/attendance"), | 380 | + for (path, item) in paths { |
| 346 | - ("GET", "/events/x/roster"), | 381 | + let item = item.as_object().expect("path item is an object"); |
| 347 | - ("GET", "/exams"), | 382 | + for (method, operation) in item { |
| 348 | - ("GET", "/courses"), | 383 | + let secured = operation["security"] |
| 349 | - ("POST", "/courses"), | 384 | + .as_array() |
| 350 | - ("GET", "/courses/me"), | 385 | + .is_some_and(|requirements| { |
| 351 | - ("GET", "/marks/me"), | 386 | + requirements |
| 352 | - ("POST", "/exams/x/attempt"), | 387 | + .iter() |
| 353 | - ("GET", "/exams/x/attempt"), | 388 | + .any(|requirement| requirement.get("session_cookie").is_some()) |
| 354 | - ("POST", "/exams/x/attempt/finish"), | 389 | + }); |
| 355 | - ("GET", "/exams/x/live"), | 390 | + let method = method.to_uppercase(); |
| 356 | - ("POST", "/exams/x/questions"), | 391 | + if !secured { |
| 357 | - ("GET", "/exams/x/questions"), | 392 | + assert!( |
| 358 | - ("PATCH", "/exams/x/questions/y"), | 393 | + PUBLIC.contains(&(method.as_str(), path.as_str())), |
| 359 | - ("DELETE", "/exams/x/questions/y"), | 394 | + "{method} {path} declares no session requirement and is not \ |
| 360 | - ("GET", "/exams/x/attempt/questions"), | 395 | + in the deliberate PUBLIC list" |
| 361 | - ("POST", "/exams/x/attempt/answers"), | 396 | + ); |
| 362 | - ("GET", "/exams/x/attempts/u/answers"), | 397 | + continue; |
| 363 | - ("POST", "/exams/x/questions/y/image"), | 398 | + } |
| 364 | - ("GET", "/exams/x/questions/y/image"), | 399 | + |
| 365 | - ("DELETE", "/exams/x/questions/y/image"), | 400 | + // `{id}` β `x`, but an integer-typed parameter (a choice index) |
| 366 | - ("POST", "/exams/x/questions/y/choices/0/image"), | 401 | + // has to stay parseable or axum answers 400 before the extractor |
| 367 | - ("GET", "/exams/x/questions/y/choices/0/image"), | 402 | + // that would have answered 401. |
| 368 | - ("DELETE", "/exams/x/questions/y/choices/0/image"), | 403 | + let mut uri = path.clone(); |
| 369 | - // The WebSocket room authenticates before it upgrades. | 404 | + for parameter in operation["parameters"].as_array().unwrap_or(&vec![]) { |
| 370 | - ("GET", "/exams/x/attempt/ws"), | 405 | + let name = parameter["name"].as_str().expect("parameter name"); |
| 371 | - ("POST", "/courses/x/sessions"), | 406 | + let placeholder = if parameter["schema"]["type"] == "integer" { |
| 372 | - ("GET", "/courses/x/sessions"), | 407 | + "0" |
| 373 | - ("GET", "/sessions/x"), | 408 | + } else { |
| 374 | - ("PATCH", "/sessions/x"), | 409 | + "x" |
| 375 | - ("DELETE", "/sessions/x"), | 410 | + }; |
| 376 | - ("POST", "/sessions/x/attendance"), | 411 | + uri = uri.replace(&format!("{{{name}}}"), placeholder); |
| 377 | - ("GET", "/sessions/x/attendance"), | 412 | + } |
| 378 | - ("DELETE", "/sessions/x/attendance/u"), | 413 | + assert!(!uri.contains('{'), "unsubstituted path parameter: {uri}"); |
| 379 | - ("POST", "/work/check-in"), | 414 | + |
| 380 | - ("POST", "/work/check-out"), | 415 | + let res = send(&app, &method, &uri, None, None).await; |
| 381 | - ("GET", "/work/me"), | 416 | + assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{method} {uri}"); |
| 382 | - ("GET", "/work/u"), | 417 | + checked += 1; |
| 383 | - ("PATCH", "/work/entries/x"), | 418 | + } |
| 384 | - ("DELETE", "/work/entries/x"), | 419 | + } |
| 385 | - ("POST", "/pomodoro/start"), | 420 | + |
| 386 | - ("POST", "/pomodoro/finish"), | 421 | + for (method, uri) in UNDOCUMENTED_WS { |
| 387 | - ("GET", "/pomodoro/me"), | ||
| 388 | - ("GET", "/pomodoro/u"), | ||
| 389 | - ("GET", "/attendance/me"), | ||
| 390 | - ("GET", "/attendance/u"), | ||
| 391 | - ("GET", "/boards"), | ||
| 392 | - ("POST", "/boards"), | ||
| 393 | - ("GET", "/boards/x"), | ||
| 394 | - ("PATCH", "/boards/x"), | ||
| 395 | - ("DELETE", "/boards/x"), | ||
| 396 | - ("GET", "/boards/x/strokes"), | ||
| 397 | - ("GET", "/boards/x/history"), | ||
| 398 | - ("GET", "/boards/x/epochs"), | ||
| 399 | - ("POST", "/boards/x/clear"), | ||
| 400 | - ("POST", "/boards/x/close"), | ||
| 401 | - // The board room authenticates before it upgrades, so a rejection is | ||
| 402 | - // an HTTP status here and not an instant close. | ||
| 403 | - ("GET", "/boards/x/ws"), | ||
| 404 | - ("GET", "/classes"), | ||
| 405 | - ("POST", "/classes"), | ||
| 406 | - ("GET", "/classes/x"), | ||
| 407 | - ("PATCH", "/classes/x"), | ||
| 408 | - ("DELETE", "/classes/x"), | ||
| 409 | - ("POST", "/classes/x/members"), | ||
| 410 | - ("GET", "/classes/x/members"), | ||
| 411 | - ("DELETE", "/classes/x/members/u"), | ||
| 412 | - ("POST", "/classes/x/courses"), | ||
| 413 | - ("GET", "/classes/x/courses"), | ||
| 414 | - ("DELETE", "/classes/x/courses/c"), | ||
| 415 | - ] { | ||
| 416 | let res = send(&app, method, uri, None, None).await; | 422 | let res = send(&app, method, uri, None, None).await; |
| 417 | assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{method} {uri}"); | 423 | assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{method} {uri}"); |
| 418 | } | 424 | } |
| 425 | + | ||
| 426 | + assert!( | ||
| 427 | + checked >= MIN_PROTECTED, | ||
| 428 | + "swept only {checked} protected operations, expected at least \ | ||
| 429 | + {MIN_PROTECTED} β did a route family leave the router?" | ||
| 430 | + ); | ||
| 419 | } | 431 | } |
| 420 | 432 | ||
| 421 | #[tokio::test] | 433 | #[tokio::test] |
| @@ -987,6 +999,126 @@ async fn concurrent_uploads_never_exceed_the_file_cap() { | |||
| 987 | ); | 999 | ); |
| 988 | } | 1000 | } |
| 989 | 1001 | ||
| 1002 | +/// The crate-wide `422` is a *behaviour*, not just 74 utoipa annotations. | ||
| 1003 | +/// | ||
| 1004 | +/// Every JSON-bodied operation declares `422` with no `ErrorResponse`, and the | ||
| 1005 | +/// only thing making that true is axum's default [`JsonRejection`]: a custom | ||
| 1006 | +/// mapping added anywhere (an `AppError` `From`, a `WithRejection` wrapper, a | ||
| 1007 | +/// hand-rolled `Json`) would silently turn the whole surface into `400`, or into | ||
| 1008 | +/// a `422` carrying an `ErrorResponse` the annotations say it does not, and the | ||
| 1009 | +/// spec-drift test in `spec_bounds.rs` β which only reads the document β would | ||
| 1010 | +/// still pass. | ||
| 1011 | +/// | ||
| 1012 | +/// Four extractor shapes stand in for all 74 sites, because the rejection is a | ||
| 1013 | +/// property of the *extractor*, never of the route: | ||
| 1014 | +/// 1. plain `Json<T>`, unauthenticated β the bare shape most sites are; | ||
| 1015 | +/// 2. `Json<T>` behind a role gate (`RequireTeacher`), where the gate runs | ||
| 1016 | +/// first: proves the gate passing still leaves the body rejection in | ||
| 1017 | +/// charge (a `403`/`400` here would mean the order had changed); | ||
| 1018 | +/// 3. `deny_unknown_fields` β the only DTO flavour that can reject a body | ||
| 1019 | +/// that is otherwise perfectly typed; | ||
| 1020 | +/// 4. `Multipart`, which has a different rejection entirely and must answer | ||
| 1021 | +/// `400`, never `422` β that is why those routes declare no `422`. | ||
| 1022 | +/// Both `422` triggers are covered (a type-mismatched field and a missing | ||
| 1023 | +/// required one), as is the `400` line either side of them: unparseable JSON | ||
| 1024 | +/// and a well-typed value that a domain rule refuses. | ||
| 1025 | +#[tokio::test] | ||
| 1026 | +async fn malformed_json_bodies_answer_422_across_every_extractor_shape() { | ||
| 1027 | + let (app, db) = app_and_db().await; | ||
| 1028 | + let ali = login(&app, "ali").await; | ||
| 1029 | + let ogretmen = login_as(&app, &db, "ogretmen", "teacher").await; | ||
| 1030 | + let json = Some("application/json"); | ||
| 1031 | + | ||
| 1032 | + // 422: the body reached serde and did not fit the target type. | ||
| 1033 | + for (uri, cookie, body, shape) in [ | ||
| 1034 | + ( | ||
| 1035 | + "/auth/register", | ||
| 1036 | + None, | ||
| 1037 | + r#"{"username": 5, "password": "secret1"}"#, | ||
| 1038 | + "plain Json, type mismatch", | ||
| 1039 | + ), | ||
| 1040 | + ( | ||
| 1041 | + "/auth/register", | ||
| 1042 | + None, | ||
| 1043 | + r#"{"username": "veli"}"#, | ||
| 1044 | + "plain Json, missing required field", | ||
| 1045 | + ), | ||
| 1046 | + ( | ||
| 1047 | + "/courses", | ||
| 1048 | + Some(ogretmen.as_str()), | ||
| 1049 | + r#"{"title": 42}"#, | ||
| 1050 | + "role-gated Json, type mismatch", | ||
| 1051 | + ), | ||
| 1052 | + ( | ||
| 1053 | + "/boards", | ||
| 1054 | + Some(ali.as_str()), | ||
| 1055 | + r#"{"title": "Geometri", "participant_ids": []}"#, | ||
| 1056 | + "deny_unknown_fields, unknown key", | ||
| 1057 | + ), | ||
| 1058 | + ] { | ||
| 1059 | + let (status, headers, bytes) = | ||
| 1060 | + common::send_raw(&app, "POST", uri, cookie, json, body.as_bytes().to_vec()).await; | ||
| 1061 | + assert_eq!( | ||
| 1062 | + status, | ||
| 1063 | + StatusCode::UNPROCESSABLE_ENTITY, | ||
| 1064 | + "{shape} ({uri}) must be 422" | ||
| 1065 | + ); | ||
| 1066 | + // The declared shape is "422, no `ErrorResponse`": axum answers a | ||
| 1067 | + // plain-text explanation, *not* the `{"error": ...}` body every other | ||
| 1068 | + // failure carries. A custom mapping that started emitting one would | ||
| 1069 | + // make the annotations lie, so pin the negative rather than the text. | ||
| 1070 | + assert_eq!( | ||
| 1071 | + headers.get("content-type").and_then(|v| v.to_str().ok()), | ||
| 1072 | + Some("text/plain; charset=utf-8"), | ||
| 1073 | + "{shape} ({uri}) must not answer an ErrorResponse body" | ||
| 1074 | + ); | ||
| 1075 | + assert!( | ||
| 1076 | + serde_json::from_slice::<serde_json::Value>(&bytes).is_err(), | ||
| 1077 | + "{shape} ({uri}) body must not be JSON, got {}", | ||
| 1078 | + String::from_utf8_lossy(&bytes) | ||
| 1079 | + ); | ||
| 1080 | + } | ||
| 1081 | + | ||
| 1082 | + // 400, both flavours: never a 422. Syntax that serde cannot even parse, and | ||
| 1083 | + // a value that parsed fine but a domain rule refuses. | ||
| 1084 | + for (body, why) in [ | ||
| 1085 | + ("not json at all", "unparseable JSON"), | ||
| 1086 | + ( | ||
| 1087 | + r#"{"username": "a", "password": "secret1"}"#, | ||
| 1088 | + "well-typed value refused by a domain rule", | ||
| 1089 | + ), | ||
| 1090 | + ] { | ||
| 1091 | + let (status, _, _) = common::send_raw( | ||
| 1092 | + &app, | ||
| 1093 | + "POST", | ||
| 1094 | + "/auth/register", | ||
| 1095 | + None, | ||
| 1096 | + json, | ||
| 1097 | + body.as_bytes().to_vec(), | ||
| 1098 | + ) | ||
| 1099 | + .await; | ||
| 1100 | + assert_eq!(status, StatusCode::BAD_REQUEST, "{why} must be 400"); | ||
| 1101 | + } | ||
| 1102 | + | ||
| 1103 | + // The multipart shape: a different rejection, and it must stay 400 β those | ||
| 1104 | + // routes deliberately declare no 422 at all. | ||
| 1105 | + let note = create_note(&app, &ali, "attachments").await; | ||
| 1106 | + let (status, _, _) = common::send_raw( | ||
| 1107 | + &app, | ||
| 1108 | + "POST", | ||
| 1109 | + &format!("/notes/{note}/files"), | ||
| 1110 | + Some(&ali), | ||
| 1111 | + Some("multipart/form-data; boundary=hezarfen-test-boundary"), | ||
| 1112 | + b"not a multipart body".to_vec(), | ||
| 1113 | + ) | ||
| 1114 | + .await; | ||
| 1115 | + assert_eq!( | ||
| 1116 | + status, | ||
| 1117 | + StatusCode::BAD_REQUEST, | ||
| 1118 | + "a multipart route must answer 400, never 422" | ||
| 1119 | + ); | ||
| 1120 | +} | ||
| 1121 | + | ||
| 990 | #[tokio::test] | 1122 | #[tokio::test] |
| 991 | async fn note_file_upload_validation() { | 1123 | async fn note_file_upload_validation() { |
| 992 | let app = mem_app().await; | 1124 | let app = mem_app().await; |
| @@ -24491,6 +24623,82 @@ async fn a_parent_gets_no_whiteboard_at_all() { | |||
| 24491 | assert!(stored_board(&db, &board).await.is_some()); | 24623 | assert!(stored_board(&db, &board).await.is_some()); |
| 24492 | } | 24624 | } |
| 24493 | 24625 | ||
| 24626 | +/// The read-modify-write half of the same defect. A roster the creator was just | ||
| 24627 | +/// served carries a participant who has since stopped qualifying, and echoing | ||
| 24628 | +/// it back used to be a `400` β the invite list frozen by a value the server | ||
| 24629 | +/// itself handed over. It is dropped now, silently. What must NOT be dropped is | ||
| 24630 | +/// a *newly named* unqualified id: that split is the whole of the fix, and | ||
| 24631 | +/// backwards it would let any caller seed a roster with anyone. | ||
| 24632 | +#[tokio::test] | ||
| 24633 | +async fn a_creator_can_patch_back_a_roster_holding_a_participant_who_no_longer_qualifies() { | ||
| 24634 | + let (app, db) = app_and_db().await; | ||
| 24635 | + let ali = login(&app, "ali").await; | ||
| 24636 | + let veli = login(&app, "veli").await; | ||
| 24637 | + let veli_id = me_id(&app, &veli).await; | ||
| 24638 | + let anne = login_as(&app, &db, "anne", "parent").await; | ||
| 24639 | + let anne_id = me_id(&app, &anne).await; | ||
| 24640 | + | ||
| 24641 | + let board = create_board(&app, &ali, "Geometri", &[&veli_id]).await; | ||
| 24642 | + // Demoted straight in the store: `set_role` would sweep the roster, and the | ||
| 24643 | + // stale row is exactly the shape a volume written before that sweep holds. | ||
| 24644 | + db.query("UPDATE $u SET role = 'parent'") | ||
| 24645 | + .bind(("u", UserId::from_key(&veli_id).record())) | ||
| 24646 | + .await | ||
| 24647 | + .unwrap() | ||
| 24648 | + .check() | ||
| 24649 | + .unwrap(); | ||
| 24650 | + | ||
| 24651 | + // What the client sees, and sends straight back. | ||
| 24652 | + let read = send(&app, "GET", &format!("/boards/{board}"), Some(&ali), None).await; | ||
| 24653 | + assert_eq!(read.status, StatusCode::OK, "{}", read.body); | ||
| 24654 | + let roster = read.body["participants"].clone(); | ||
| 24655 | + assert_eq!( | ||
| 24656 | + roster, | ||
| 24657 | + json!([&veli_id]), | ||
| 24658 | + "the stale id is served, not hidden" | ||
| 24659 | + ); | ||
| 24660 | + | ||
| 24661 | + let res = send( | ||
| 24662 | + &app, | ||
| 24663 | + "PATCH", | ||
| 24664 | + &format!("/boards/{board}"), | ||
| 24665 | + Some(&ali), | ||
| 24666 | + Some(json!({ "participants": roster })), | ||
| 24667 | + ) | ||
| 24668 | + .await; | ||
| 24669 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 24670 | + assert_eq!(res.body["participants"], json!([]), "{}", res.body); | ||
| 24671 | + assert!( | ||
| 24672 | + stored_board(&db, &board) | ||
| 24673 | + .await | ||
| 24674 | + .unwrap() | ||
| 24675 | + .get_participants() | ||
| 24676 | + .is_empty(), | ||
| 24677 | + "the drop is stored, not just rendered" | ||
| 24678 | + ); | ||
| 24679 | + | ||
| 24680 | + // The other half: a fresh unqualified id still fails the whole call, and | ||
| 24681 | + // both flavours of it β a parent, and an id no user answers to. | ||
| 24682 | + for id in [anne_id.as_str(), "nosuchuser"] { | ||
| 24683 | + let res = send( | ||
| 24684 | + &app, | ||
| 24685 | + "PATCH", | ||
| 24686 | + &format!("/boards/{board}"), | ||
| 24687 | + Some(&ali), | ||
| 24688 | + Some(json!({ "participants": [id] })), | ||
| 24689 | + ) | ||
| 24690 | + .await; | ||
| 24691 | + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{id}: {}", res.body); | ||
| 24692 | + } | ||
| 24693 | + assert!( | ||
| 24694 | + stored_board(&db, &board) | ||
| 24695 | + .await | ||
| 24696 | + .unwrap() | ||
| 24697 | + .get_participants() | ||
| 24698 | + .is_empty() | ||
| 24699 | + ); | ||
| 24700 | +} | ||
| 24701 | + | ||
| 24494 | /// The roster is spelled `participants` on the way in, out and through `PATCH`. | 24702 | /// The roster is spelled `participants` on the way in, out and through `PATCH`. |
| 24495 | /// It used to be `participant_ids` on `POST` alone, and with serde ignoring the | 24703 | /// It used to be `participant_ids` on `POST` alone, and with serde ignoring the |
| 24496 | /// unknown key a client that posted back a board it had just read got a `201` | 24704 | /// unknown key a client that posted back a board it had just read got a `201` |
tests/limits_completeness.rsmodified+13 -0
| @@ -63,6 +63,12 @@ const EXCLUDED: &[(&str, &str)] = &[ | |||
| 63 | locked or closed board freezes in the database; the client sees the \ | 63 | locked or closed board freezes in the database; the client sees the \ |
| 64 | freeze as a 409, never as a number", | 64 | freeze as a 409, never as a number", |
| 65 | ), | 65 | ), |
| 66 | + ( | ||
| 67 | + "REGISTRATION_FROZEN_GUARD", | ||
| 68 | + "SQL fragment: the condition the role cascade carries so a frozen signup \ | ||
| 69 | + list is left exactly as it stands; the client sees the freeze as a 409, \ | ||
| 70 | + never as a number", | ||
| 71 | + ), | ||
| 66 | ( | 72 | ( |
| 67 | "BOARD_REPLAY_CHUNK", | 73 | "BOARD_REPLAY_CHUNK", |
| 68 | "how the board-room socket batches its join replay; the client reads the \ | 74 | "how the board-room socket batches its join replay; the client reads the \ |
| @@ -171,6 +177,13 @@ const EXCLUDED: &[(&str, &str)] = &[ | |||
| 171 | "ETag middleware's own buffering ceiling", | 177 | "ETag middleware's own buffering ceiling", |
| 172 | ), | 178 | ), |
| 173 | ("PURGE_AT", "rate-limiter bucket eviction threshold"), | 179 | ("PURGE_AT", "rate-limiter bucket eviction threshold"), |
| 180 | + // Not a per-client budget: one fleet-wide counter that only exists while | ||
| 181 | + // the bucket map is saturated. A client cannot compute its own allowance | ||
| 182 | + // from it, and publishing it would advertise the flood threshold. | ||
| 183 | + ( | ||
| 184 | + "RATE_LIMIT_OVERFLOW_MAX", | ||
| 185 | + "aggregate budget for keyless clients while the bucket map is full", | ||
| 186 | + ), | ||
| 174 | // How a tier's window is carried through a restart. A client is held to | 187 | // How a tier's window is carried through a restart. A client is held to |
| 175 | // the tier itself (published live in /limits `rate`), never to the cadence | 188 | // the tier itself (published live in /limits `rate`), never to the cadence |
| 176 | // it is reconciled at β publishing that would invite pacing against it. | 189 | // it is reconciled at β publishing that would invite pacing against it. |
tests/pagination.rsmodified+40 -0
| @@ -528,6 +528,46 @@ async fn board_lists_are_paged() { | |||
| 528 | .await; | 528 | .await; |
| 529 | assert_eq!(total(&res.body), 3, "the scoped total is the scoped count"); | 529 | assert_eq!(total(&res.body), 3, "the scoped total is the scoped count"); |
| 530 | assert_eq!(items(&res.body).len(), 1, "offset 2 of 3 leaves 1"); | 530 | assert_eq!(items(&res.body).len(), 1, "offset 2 of 3 leaves 1"); |
| 531 | + | ||
| 532 | + // `?open=` narrows the board list the same way `?read=` narrows a message | ||
| 533 | + // folder: the filter reaches the database, so `total` is the filtered count | ||
| 534 | + // and the window still pages. A closed board is never deleted, so this is | ||
| 535 | + // the only way a heavy creator trims the retired ones out. | ||
| 536 | + let res = send( | ||
| 537 | + &app, | ||
| 538 | + "POST", | ||
| 539 | + &format!("/boards/{}/close", boards[2]), | ||
| 540 | + Some(&ali), | ||
| 541 | + None, | ||
| 542 | + ) | ||
| 543 | + .await; | ||
| 544 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 545 | + for (query, count) in [("", 3), ("?open=true", 2), ("?open=false", 1)] { | ||
| 546 | + let res = send(&app, "GET", &format!("/boards{query}"), Some(&ali), None).await; | ||
| 547 | + assert_eq!( | ||
| 548 | + res.status, | ||
| 549 | + StatusCode::OK, | ||
| 550 | + "GET /boards{query}: {}", | ||
| 551 | + res.body | ||
| 552 | + ); | ||
| 553 | + assert_eq!(total(&res.body), count, "GET /boards{query} total"); | ||
| 554 | + assert_eq!(items(&res.body).len() as i64, count, "GET /boards{query}"); | ||
| 555 | + } | ||
| 556 | + // The board that is merely *locked* is still open β `?open=` filters | ||
| 557 | + // `closed_at` and nothing else. | ||
| 558 | + let res = send( | ||
| 559 | + &app, | ||
| 560 | + "PATCH", | ||
| 561 | + &format!("/boards/{}", boards[1]), | ||
| 562 | + Some(&ali), | ||
| 563 | + Some(json!({ "locked": true })), | ||
| 564 | + ) | ||
| 565 | + .await; | ||
| 566 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 567 | + let res = send(&app, "GET", "/boards?open=true&limit=1", Some(&ali), None).await; | ||
| 568 | + assert_eq!(total(&res.body), 2, "a locked board is still an open one"); | ||
| 569 | + assert_eq!(items(&res.body).len(), 1, "the filtered list still windows"); | ||
| 570 | + assert_eq!(res.body["limit"], 1); | ||
| 531 | } | 571 | } |
| 532 | 572 | ||
| 533 | /// The class layer's three lists speak the same envelope: the class index, one | 573 | /// The class layer's three lists speak the same envelope: the class index, one |
tests/rate_limit.rsmodified+34 -0
| @@ -343,6 +343,40 @@ async fn concurrent_bursts_never_over_admit() { | |||
| 343 | assert_eq!((ok, limited), (5, 15)); | 343 | assert_eq!((ok, limited), (5, 15)); |
| 344 | } | 344 | } |
| 345 | 345 | ||
| 346 | +/// A saturated bucket map must not be a bypass. Fill it to `PURGE_AT` with | ||
| 347 | +/// exhausted buckets β nothing lapsed, nothing evictable β and every further | ||
| 348 | +/// *new* key gets no bucket of its own. It is still metered: all of them share | ||
| 349 | +/// one aggregate budget, `RATE_LIMIT_OVERFLOW_MAX` per window, and past that | ||
| 350 | +/// they are refused. Admitting them unmetered would let an attacker buy | ||
| 351 | +/// unlimited throughput from fresh keys after paying to fill the map once. | ||
| 352 | +#[tokio::test] | ||
| 353 | +async fn keyless_clients_share_one_budget_once_the_map_is_saturated() { | ||
| 354 | + use hezarfen_backend::constant::{PURGE_AT, RATE_LIMIT_OVERFLOW_MAX}; | ||
| 355 | + | ||
| 356 | + // One request per key exhausts it, so the map fills with buckets that can | ||
| 357 | + // neither be swept (same window) nor evicted (all at their limit). | ||
| 358 | + let limiter = UserRateLimiter::per_user_minute(1); | ||
| 359 | + for i in 0..PURGE_AT { | ||
| 360 | + assert!(limiter.enforce_user(&format!("flood-{i}")).is_ok()); | ||
| 361 | + } | ||
| 362 | + assert!( | ||
| 363 | + limiter.enforce_user("flood-0").is_err(), | ||
| 364 | + "the map must be full of exhausted buckets" | ||
| 365 | + ); | ||
| 366 | + | ||
| 367 | + // Distinct newcomers, none of which can get into the map. | ||
| 368 | + for i in 0..RATE_LIMIT_OVERFLOW_MAX { | ||
| 369 | + assert!( | ||
| 370 | + limiter.enforce_user(&format!("newcomer-{i}")).is_ok(), | ||
| 371 | + "newcomer {i} is within the shared overflow budget" | ||
| 372 | + ); | ||
| 373 | + } | ||
| 374 | + assert!( | ||
| 375 | + limiter.enforce_user("newcomer-last").is_err(), | ||
| 376 | + "past the shared budget a keyless client must be refused, not admitted" | ||
| 377 | + ); | ||
| 378 | +} | ||
| 379 | + | ||
| 346 | // --- the window outlives the process ------------------------------------ | 380 | // --- the window outlives the process ------------------------------------ |
| 347 | // | 381 | // |
| 348 | // Two `UserRateLimiter`s over one database stand in for the process before and | 382 | // Two `UserRateLimiter`s over one database stand in for the process before and |
tests/regress_blueprints.rsadded+644 -0
| @@ -0,0 +1,644 @@ | |||
| 1 | +//! Grade blueprints: the course template a whole grade's class sections are | ||
| 2 | +//! stocked from. | ||
| 3 | +//! | ||
| 4 | +//! Every assertion reads STORED state out of the database rather than a | ||
| 5 | +//! response body β the in-memory engine forges wins, and a blueprint's whole | ||
| 6 | +//! job is what ends up in `class_course` and `enrollment`. | ||
| 7 | +//! | ||
| 8 | +//! The three rules under test are the ones that make this layer more than a | ||
| 9 | +//! loop: an edit retro-pumps the classes that already exist, a class that does | ||
| 10 | +//! not fit is *skipped and reported* rather than aborting the others, and a | ||
| 11 | +//! removal reaches only the attachments the blueprint itself made. | ||
| 12 | + | ||
| 13 | +mod common; | ||
| 14 | + | ||
| 15 | +use axum::http::StatusCode; | ||
| 16 | +use common::{Res, app_and_db, create_course, login_as, me_id, send}; | ||
| 17 | +use hezarfen_backend::database::Database; | ||
| 18 | +use serde_json::{Value, json}; | ||
| 19 | + | ||
| 20 | +/// One counter, re-read out of the store. | ||
| 21 | +async fn counter(sql: &str, db: &Database) -> i64 { | ||
| 22 | + let mut result = db.query(sql).await.unwrap().check().unwrap(); | ||
| 23 | + result | ||
| 24 | + .take::<Vec<i64>>(0) | ||
| 25 | + .unwrap() | ||
| 26 | + .first() | ||
| 27 | + .copied() | ||
| 28 | + .unwrap_or(0) | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +/// How many rows `sql` selects ids for. | ||
| 32 | +async fn rows(sql: &str, db: &Database) -> i64 { | ||
| 33 | + let mut result = db.query(sql).await.unwrap().check().unwrap(); | ||
| 34 | + result | ||
| 35 | + .take::<Vec<surrealdb::types::RecordId>>(0) | ||
| 36 | + .unwrap() | ||
| 37 | + .len() as i64 | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +/// Is that course on that class, in the store? | ||
| 41 | +async fn attached(class: &str, course: &str, db: &Database) -> bool { | ||
| 42 | + rows( | ||
| 43 | + &format!( | ||
| 44 | + "SELECT VALUE id FROM class_course WHERE class = class_group:{class} \ | ||
| 45 | + AND course = course:{course}" | ||
| 46 | + ), | ||
| 47 | + db, | ||
| 48 | + ) | ||
| 49 | + .await | ||
| 50 | + == 1 | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +/// The blueprint key stored on one attachment, or `None` when the row carries | ||
| 54 | +/// no such key at all β which is the whole provenance rule: absent means a | ||
| 55 | +/// human attached it. | ||
| 56 | +async fn source_of(class: &str, course: &str, db: &Database) -> Option<String> { | ||
| 57 | + let mut result = db | ||
| 58 | + .query(format!( | ||
| 59 | + "SELECT VALUE (IF source != NONE THEN record::id(source) ELSE '' END) \ | ||
| 60 | + FROM class_course WHERE class = class_group:{class} AND course = course:{course}" | ||
| 61 | + )) | ||
| 62 | + .await | ||
| 63 | + .unwrap() | ||
| 64 | + .check() | ||
| 65 | + .unwrap(); | ||
| 66 | + result | ||
| 67 | + .take::<Vec<String>>(0) | ||
| 68 | + .unwrap() | ||
| 69 | + .into_iter() | ||
| 70 | + .next() | ||
| 71 | + .filter(|key| !key.is_empty()) | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +/// Create a class section as `cookie`; returns its id. | ||
| 75 | +async fn create_class(app: &axum::Router, cookie: &str, name: &str, grade: &str) -> String { | ||
| 76 | + let res = send( | ||
| 77 | + app, | ||
| 78 | + "POST", | ||
| 79 | + "/classes", | ||
| 80 | + Some(cookie), | ||
| 81 | + Some(json!({ "name": name, "grade": grade })), | ||
| 82 | + ) | ||
| 83 | + .await; | ||
| 84 | + assert_eq!(res.status, StatusCode::CREATED, "create class {name}"); | ||
| 85 | + res.body["id"].as_str().expect("class id").to_string() | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +/// Register a student, put them in a class, and hand back their id. | ||
| 89 | +async fn student_in( | ||
| 90 | + app: &axum::Router, | ||
| 91 | + db: &Database, | ||
| 92 | + class: &str, | ||
| 93 | + manager: &str, | ||
| 94 | + name: &str, | ||
| 95 | +) -> String { | ||
| 96 | + let cookie = login_as(app, db, name, "student").await; | ||
| 97 | + let id = me_id(app, &cookie).await; | ||
| 98 | + let res = send( | ||
| 99 | + app, | ||
| 100 | + "POST", | ||
| 101 | + &format!("/classes/{class}/members"), | ||
| 102 | + Some(manager), | ||
| 103 | + Some(json!({ "user_id": id })), | ||
| 104 | + ) | ||
| 105 | + .await; | ||
| 106 | + assert_eq!(res.status, StatusCode::CREATED, "add {name} to {class}"); | ||
| 107 | + id | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +/// A course with a seat `capacity`, which `create_course` cannot express. | ||
| 111 | +async fn create_capped_course(app: &axum::Router, cookie: &str, title: &str, cap: i64) -> String { | ||
| 112 | + let res = send( | ||
| 113 | + app, | ||
| 114 | + "POST", | ||
| 115 | + "/courses", | ||
| 116 | + Some(cookie), | ||
| 117 | + Some(json!({ "title": title, "capacity": cap })), | ||
| 118 | + ) | ||
| 119 | + .await; | ||
| 120 | + assert_eq!(res.status, StatusCode::CREATED, "create course {title}"); | ||
| 121 | + res.body["id"].as_str().expect("course id").to_string() | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +fn skips(res: &Res) -> &Vec<Value> { | ||
| 125 | + res.body["skipped"].as_array().expect("a skip list") | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +/// The whole CRUD surface, and the 409s that keep one blueprint per grade. | ||
| 129 | +#[tokio::test] | ||
| 130 | +async fn a_blueprint_is_created_read_updated_and_deleted() { | ||
| 131 | + let (app, db) = app_and_db().await; | ||
| 132 | + let manager = login_as(&app, &db, "mgr", "manager").await; | ||
| 133 | + let algebra = create_course(&app, &manager, "algebra").await; | ||
| 134 | + let physics = create_course(&app, &manager, "physics").await; | ||
| 135 | + | ||
| 136 | + let made = send( | ||
| 137 | + &app, | ||
| 138 | + "POST", | ||
| 139 | + "/classes/blueprints", | ||
| 140 | + Some(&manager), | ||
| 141 | + Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), | ||
| 142 | + ) | ||
| 143 | + .await; | ||
| 144 | + assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); | ||
| 145 | + assert_eq!(made.body["blueprint"]["grade"], "9"); | ||
| 146 | + assert_eq!(made.body["blueprint"]["courses"][0], algebra.as_str()); | ||
| 147 | + assert!(skips(&made).is_empty(), "no class exists to skip"); | ||
| 148 | + | ||
| 149 | + // The grade is the record key, so a second blueprint for it is a 409 the | ||
| 150 | + // store decides rather than a find-then-insert two managers can race. | ||
| 151 | + let again = send( | ||
| 152 | + &app, | ||
| 153 | + "POST", | ||
| 154 | + "/classes/blueprints", | ||
| 155 | + Some(&manager), | ||
| 156 | + Some(json!({ "grade": "9", "course_ids": [] })), | ||
| 157 | + ) | ||
| 158 | + .await; | ||
| 159 | + assert_eq!(again.status, StatusCode::CONFLICT, "{:?}", again.body); | ||
| 160 | + | ||
| 161 | + let read = send(&app, "GET", "/classes/blueprints/9", Some(&manager), None).await; | ||
| 162 | + assert_eq!(read.status, StatusCode::OK); | ||
| 163 | + assert_eq!(read.body["courses"][0], algebra.as_str()); | ||
| 164 | + | ||
| 165 | + let listed = send(&app, "GET", "/classes/blueprints", Some(&manager), None).await; | ||
| 166 | + assert_eq!(listed.status, StatusCode::OK); | ||
| 167 | + assert_eq!(listed.body["items"].as_array().unwrap().len(), 1); | ||
| 168 | + | ||
| 169 | + let patched = send( | ||
| 170 | + &app, | ||
| 171 | + "PATCH", | ||
| 172 | + "/classes/blueprints/9", | ||
| 173 | + Some(&manager), | ||
| 174 | + Some(json!({ "course_ids": [physics.clone()] })), | ||
| 175 | + ) | ||
| 176 | + .await; | ||
| 177 | + assert_eq!(patched.status, StatusCode::OK, "{:?}", patched.body); | ||
| 178 | + assert_eq!(patched.body["blueprint"]["courses"][0], physics.as_str()); | ||
| 179 | + assert_eq!( | ||
| 180 | + patched.body["blueprint"]["courses"] | ||
| 181 | + .as_array() | ||
| 182 | + .unwrap() | ||
| 183 | + .len(), | ||
| 184 | + 1, | ||
| 185 | + "the list is a set, not a delta β algebra is gone" | ||
| 186 | + ); | ||
| 187 | + | ||
| 188 | + let dropped = send( | ||
| 189 | + &app, | ||
| 190 | + "DELETE", | ||
| 191 | + "/classes/blueprints/9", | ||
| 192 | + Some(&manager), | ||
| 193 | + None, | ||
| 194 | + ) | ||
| 195 | + .await; | ||
| 196 | + assert_eq!(dropped.status, StatusCode::NO_CONTENT); | ||
| 197 | + assert_eq!(rows("SELECT VALUE id FROM class_blueprint", &db).await, 0); | ||
| 198 | + let gone = send(&app, "GET", "/classes/blueprints/9", Some(&manager), None).await; | ||
| 199 | + assert_eq!(gone.status, StatusCode::NOT_FOUND); | ||
| 200 | + | ||
| 201 | + // An unaddressable grade is a 400, not a record nobody can ever read back. | ||
| 202 | + for bad in ["", "9/A"] { | ||
| 203 | + let refused = send( | ||
| 204 | + &app, | ||
| 205 | + "POST", | ||
| 206 | + "/classes/blueprints", | ||
| 207 | + Some(&manager), | ||
| 208 | + Some(json!({ "grade": bad, "course_ids": [] })), | ||
| 209 | + ) | ||
| 210 | + .await; | ||
| 211 | + assert_eq!( | ||
| 212 | + refused.status, | ||
| 213 | + StatusCode::BAD_REQUEST, | ||
| 214 | + "grade {bad:?}: {:?}", | ||
| 215 | + refused.body | ||
| 216 | + ); | ||
| 217 | + } | ||
| 218 | +} | ||
| 219 | + | ||
| 220 | +/// A section made after the template exists is stocked in one call, and the | ||
| 221 | +/// stocking is the ordinary pump: real enrollment rows for its roster. | ||
| 222 | +#[tokio::test] | ||
| 223 | +async fn a_fresh_class_takes_its_grades_blueprint() { | ||
| 224 | + let (app, db) = app_and_db().await; | ||
| 225 | + let manager = login_as(&app, &db, "mgr", "manager").await; | ||
| 226 | + let algebra = create_course(&app, &manager, "algebra").await; | ||
| 227 | + let physics = create_course(&app, &manager, "physics").await; | ||
| 228 | + let made = send( | ||
| 229 | + &app, | ||
| 230 | + "POST", | ||
| 231 | + "/classes/blueprints", | ||
| 232 | + Some(&manager), | ||
| 233 | + Some(json!({ "grade": "9", "course_ids": [algebra.clone(), physics.clone()] })), | ||
| 234 | + ) | ||
| 235 | + .await; | ||
| 236 | + assert_eq!(made.status, StatusCode::CREATED); | ||
| 237 | + | ||
| 238 | + let class = create_class(&app, &manager, "9-A", "9").await; | ||
| 239 | + let student = student_in(&app, &db, &class, &manager, "ali").await; | ||
| 240 | + | ||
| 241 | + let applied = send( | ||
| 242 | + &app, | ||
| 243 | + "POST", | ||
| 244 | + &format!("/classes/{class}/blueprint"), | ||
| 245 | + Some(&manager), | ||
| 246 | + None, | ||
| 247 | + ) | ||
| 248 | + .await; | ||
| 249 | + assert_eq!(applied.status, StatusCode::OK, "{:?}", applied.body); | ||
| 250 | + assert!(skips(&applied).is_empty(), "{:?}", applied.body); | ||
| 251 | + | ||
| 252 | + for course in [&algebra, &physics] { | ||
| 253 | + assert!(attached(&class, course, &db).await); | ||
| 254 | + assert_eq!( | ||
| 255 | + source_of(&class, course, &db).await, | ||
| 256 | + Some("9".to_string()), | ||
| 257 | + "the blueprint must own what it attached" | ||
| 258 | + ); | ||
| 259 | + assert_eq!( | ||
| 260 | + rows( | ||
| 261 | + &format!( | ||
| 262 | + "SELECT VALUE id FROM enrollment WHERE course = course:{course} \ | ||
| 263 | + AND user = user:{student}" | ||
| 264 | + ), | ||
| 265 | + &db | ||
| 266 | + ) | ||
| 267 | + .await, | ||
| 268 | + 1, | ||
| 269 | + "stocking a class enrolls its roster, in real rows" | ||
| 270 | + ); | ||
| 271 | + } | ||
| 272 | + assert_eq!( | ||
| 273 | + counter( | ||
| 274 | + &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"), | ||
| 275 | + &db | ||
| 276 | + ) | ||
| 277 | + .await, | ||
| 278 | + 2 | ||
| 279 | + ); | ||
| 280 | + | ||
| 281 | + // Idempotent: a second apply attaches nothing new and skips nothing. | ||
| 282 | + let twice = send( | ||
| 283 | + &app, | ||
| 284 | + "POST", | ||
| 285 | + &format!("/classes/{class}/blueprint"), | ||
| 286 | + Some(&manager), | ||
| 287 | + None, | ||
| 288 | + ) | ||
| 289 | + .await; | ||
| 290 | + assert_eq!(twice.status, StatusCode::OK); | ||
| 291 | + assert!(skips(&twice).is_empty()); | ||
| 292 | + assert_eq!(rows("SELECT VALUE id FROM class_course", &db).await, 2); | ||
| 293 | + | ||
| 294 | + // A class whose grade no blueprint covers is a 404, not an empty success. | ||
| 295 | + let other = create_class(&app, &manager, "10-A", "10").await; | ||
| 296 | + let none = send( | ||
| 297 | + &app, | ||
| 298 | + "POST", | ||
| 299 | + &format!("/classes/{other}/blueprint"), | ||
| 300 | + Some(&manager), | ||
| 301 | + None, | ||
| 302 | + ) | ||
| 303 | + .await; | ||
| 304 | + assert_eq!(none.status, StatusCode::NOT_FOUND); | ||
| 305 | +} | ||
| 306 | + | ||
| 307 | +/// The ruling that costs the most: editing the template reaches every section | ||
| 308 | +/// already at the grade, not just the ones made afterwards. And the sections at | ||
| 309 | +/// *other* grades are left alone. | ||
| 310 | +#[tokio::test] | ||
| 311 | +async fn an_edit_retro_pumps_every_class_at_the_grade() { | ||
| 312 | + let (app, db) = app_and_db().await; | ||
| 313 | + let manager = login_as(&app, &db, "mgr", "manager").await; | ||
| 314 | + let algebra = create_course(&app, &manager, "algebra").await; | ||
| 315 | + let a = create_class(&app, &manager, "9-A", "9").await; | ||
| 316 | + let b = create_class(&app, &manager, "9-B", "9").await; | ||
| 317 | + let ten = create_class(&app, &manager, "10-A", "10").await; | ||
| 318 | + let ali = student_in(&app, &db, &a, &manager, "ali").await; | ||
| 319 | + student_in(&app, &db, &ten, &manager, "veli").await; | ||
| 320 | + | ||
| 321 | + // Created empty, so the create's own pump has nothing to place⦠| ||
| 322 | + let made = send( | ||
| 323 | + &app, | ||
| 324 | + "POST", | ||
| 325 | + "/classes/blueprints", | ||
| 326 | + Some(&manager), | ||
| 327 | + Some(json!({ "grade": "9", "course_ids": [] })), | ||
| 328 | + ) | ||
| 329 | + .await; | ||
| 330 | + assert_eq!(made.status, StatusCode::CREATED); | ||
| 331 | + assert_eq!(rows("SELECT VALUE id FROM class_course", &db).await, 0); | ||
| 332 | + | ||
| 333 | + // β¦and the edit is what has to reach the two classes standing there. | ||
| 334 | + let patched = send( | ||
| 335 | + &app, | ||
| 336 | + "PATCH", | ||
| 337 | + "/classes/blueprints/9", | ||
| 338 | + Some(&manager), | ||
| 339 | + Some(json!({ "course_ids": [algebra.clone()] })), | ||
| 340 | + ) | ||
| 341 | + .await; | ||
| 342 | + assert_eq!(patched.status, StatusCode::OK, "{:?}", patched.body); | ||
| 343 | + assert!(skips(&patched).is_empty(), "{:?}", patched.body); | ||
| 344 | + | ||
| 345 | + assert!(attached(&a, &algebra, &db).await); | ||
| 346 | + assert!(attached(&b, &algebra, &db).await); | ||
| 347 | + assert!( | ||
| 348 | + !attached(&ten, &algebra, &db).await, | ||
| 349 | + "a blueprint pumps its own grade and no other" | ||
| 350 | + ); | ||
| 351 | + // Counters exact after the retro-pump: one attachment each on the two | ||
| 352 | + // classes, none on the third, one enrolled seat for the one student at the | ||
| 353 | + // grade. | ||
| 354 | + for class in [&a, &b] { | ||
| 355 | + assert_eq!( | ||
| 356 | + counter( | ||
| 357 | + &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"), | ||
| 358 | + &db | ||
| 359 | + ) | ||
| 360 | + .await, | ||
| 361 | + 1 | ||
| 362 | + ); | ||
| 363 | + } | ||
| 364 | + assert_eq!( | ||
| 365 | + counter( | ||
| 366 | + &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{ten}"), | ||
| 367 | + &db | ||
| 368 | + ) | ||
| 369 | + .await, | ||
| 370 | + 0 | ||
| 371 | + ); | ||
| 372 | + assert_eq!( | ||
| 373 | + counter( | ||
| 374 | + &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{algebra}"), | ||
| 375 | + &db | ||
| 376 | + ) | ||
| 377 | + .await, | ||
| 378 | + 1, | ||
| 379 | + "one student at the grade, one seat" | ||
| 380 | + ); | ||
| 381 | + assert_eq!( | ||
| 382 | + rows( | ||
| 383 | + &format!("SELECT VALUE id FROM enrollment WHERE user = user:{ali}"), | ||
| 384 | + &db | ||
| 385 | + ) | ||
| 386 | + .await, | ||
| 387 | + 1 | ||
| 388 | + ); | ||
| 389 | +} | ||
| 390 | + | ||
| 391 | +/// Best-effort, the ruling that accepts a partial state: a section that cannot | ||
| 392 | +/// take a course is skipped and *reported*, the others are still stocked, and | ||
| 393 | +/// the skipped one has not moved a single counter. | ||
| 394 | +#[tokio::test] | ||
| 395 | +async fn a_class_that_does_not_fit_is_reported_not_aborted() { | ||
| 396 | + let (app, db) = app_and_db().await; | ||
| 397 | + let manager = login_as(&app, &db, "mgr", "manager").await; | ||
| 398 | + // One seat, and a section with two students β the attach cannot hold the | ||
| 399 | + // whole class, so the pump's own transaction refuses it whole. | ||
| 400 | + let tight = create_capped_course(&app, &manager, "seminar", 1).await; | ||
| 401 | + let full = create_class(&app, &manager, "9-A", "9").await; | ||
| 402 | + let fits = create_class(&app, &manager, "9-B", "9").await; | ||
| 403 | + student_in(&app, &db, &full, &manager, "ali").await; | ||
| 404 | + student_in(&app, &db, &full, &manager, "veli").await; | ||
| 405 | + | ||
| 406 | + let made = send( | ||
| 407 | + &app, | ||
| 408 | + "POST", | ||
| 409 | + "/classes/blueprints", | ||
| 410 | + Some(&manager), | ||
| 411 | + Some(json!({ "grade": "9", "course_ids": [tight.clone()] })), | ||
| 412 | + ) | ||
| 413 | + .await; | ||
| 414 | + assert_eq!( | ||
| 415 | + made.status, | ||
| 416 | + StatusCode::CREATED, | ||
| 417 | + "one class that does not fit may not fail the whole edit: {:?}", | ||
| 418 | + made.body | ||
| 419 | + ); | ||
| 420 | + let skipped = skips(&made); | ||
| 421 | + assert_eq!(skipped.len(), 1, "{skipped:?}"); | ||
| 422 | + assert_eq!(skipped[0]["class"], full.as_str()); | ||
| 423 | + assert_eq!(skipped[0]["class_name"], "9-A", "name the section"); | ||
| 424 | + assert_eq!(skipped[0]["course"], tight.as_str()); | ||
| 425 | + assert!( | ||
| 426 | + skipped[0]["reason"].as_str().unwrap().contains("seat"), | ||
| 427 | + "the reason must be actionable: {:?}", | ||
| 428 | + skipped[0]["reason"] | ||
| 429 | + ); | ||
| 430 | + | ||
| 431 | + assert!( | ||
| 432 | + attached(&fits, &tight, &db).await, | ||
| 433 | + "the class that fits is still stocked" | ||
| 434 | + ); | ||
| 435 | + assert!(!attached(&full, &tight, &db).await); | ||
| 436 | + // Nothing moved on the skipped class: not its attachment counter, and not | ||
| 437 | + // one of the seats the refused attach touched on its way to the refusal. | ||
| 438 | + assert_eq!( | ||
| 439 | + counter( | ||
| 440 | + &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{full}"), | ||
| 441 | + &db | ||
| 442 | + ) | ||
| 443 | + .await, | ||
| 444 | + 0 | ||
| 445 | + ); | ||
| 446 | + assert_eq!( | ||
| 447 | + counter( | ||
| 448 | + &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{tight}"), | ||
| 449 | + &db | ||
| 450 | + ) | ||
| 451 | + .await, | ||
| 452 | + 0, | ||
| 453 | + "the empty class took no seat, and the refused one gave every seat back" | ||
| 454 | + ); | ||
| 455 | + assert_eq!(rows("SELECT VALUE id FROM enrollment", &db).await, 0); | ||
| 456 | +} | ||
| 457 | + | ||
| 458 | +/// The provenance rule, both halves: dropping a course from the template | ||
| 459 | +/// detaches it wherever the *blueprint* attached it, and leaves it standing | ||
| 460 | +/// wherever a human did. | ||
| 461 | +#[tokio::test] | ||
| 462 | +async fn a_removal_spares_a_hand_attached_course() { | ||
| 463 | + let (app, db) = app_and_db().await; | ||
| 464 | + let manager = login_as(&app, &db, "mgr", "manager").await; | ||
| 465 | + let algebra = create_course(&app, &manager, "algebra").await; | ||
| 466 | + let pumped = create_class(&app, &manager, "9-A", "9").await; | ||
| 467 | + let byhand = create_class(&app, &manager, "9-B", "9").await; | ||
| 468 | + let ali = student_in(&app, &db, &pumped, &manager, "ali").await; | ||
| 469 | + student_in(&app, &db, &byhand, &manager, "veli").await; | ||
| 470 | + | ||
| 471 | + // 9-B gets algebra the old way, *before* the blueprint exists. | ||
| 472 | + let attached_by_hand = send( | ||
| 473 | + &app, | ||
| 474 | + "POST", | ||
| 475 | + &format!("/classes/{byhand}/courses"), | ||
| 476 | + Some(&manager), | ||
| 477 | + Some(json!({ "course_id": algebra.clone() })), | ||
| 478 | + ) | ||
| 479 | + .await; | ||
| 480 | + assert_eq!(attached_by_hand.status, StatusCode::CREATED); | ||
| 481 | + assert_eq!( | ||
| 482 | + source_of(&byhand, &algebra, &db).await, | ||
| 483 | + None, | ||
| 484 | + "a hand attach carries no blueprint key at all" | ||
| 485 | + ); | ||
| 486 | + | ||
| 487 | + let made = send( | ||
| 488 | + &app, | ||
| 489 | + "POST", | ||
| 490 | + "/classes/blueprints", | ||
| 491 | + Some(&manager), | ||
| 492 | + Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), | ||
| 493 | + ) | ||
| 494 | + .await; | ||
| 495 | + assert_eq!(made.status, StatusCode::CREATED); | ||
| 496 | + assert!(skips(&made).is_empty(), "{:?}", made.body); | ||
| 497 | + assert_eq!( | ||
| 498 | + source_of(&byhand, &algebra, &db).await, | ||
| 499 | + None, | ||
| 500 | + "a pump may not adopt an attachment it did not make" | ||
| 501 | + ); | ||
| 502 | + assert_eq!(source_of(&pumped, &algebra, &db).await, Some("9".into())); | ||
| 503 | + | ||
| 504 | + // Drop it from the template. | ||
| 505 | + let patched = send( | ||
| 506 | + &app, | ||
| 507 | + "PATCH", | ||
| 508 | + "/classes/blueprints/9", | ||
| 509 | + Some(&manager), | ||
| 510 | + Some(json!({ "course_ids": [] })), | ||
| 511 | + ) | ||
| 512 | + .await; | ||
| 513 | + assert_eq!(patched.status, StatusCode::OK, "{:?}", patched.body); | ||
| 514 | + | ||
| 515 | + assert!( | ||
| 516 | + !attached(&pumped, &algebra, &db).await, | ||
| 517 | + "the blueprint takes back what it placed" | ||
| 518 | + ); | ||
| 519 | + assert!( | ||
| 520 | + attached(&byhand, &algebra, &db).await, | ||
| 521 | + "β¦and nothing else β a hand attach survives" | ||
| 522 | + ); | ||
| 523 | + assert_eq!( | ||
| 524 | + counter( | ||
| 525 | + &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{pumped}"), | ||
| 526 | + &db | ||
| 527 | + ) | ||
| 528 | + .await, | ||
| 529 | + 0, | ||
| 530 | + "the detach gives the class its count back" | ||
| 531 | + ); | ||
| 532 | + assert_eq!( | ||
| 533 | + counter( | ||
| 534 | + &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{byhand}"), | ||
| 535 | + &db | ||
| 536 | + ) | ||
| 537 | + .await, | ||
| 538 | + 1 | ||
| 539 | + ); | ||
| 540 | + assert_eq!( | ||
| 541 | + rows( | ||
| 542 | + &format!("SELECT VALUE id FROM enrollment WHERE user = user:{ali}"), | ||
| 543 | + &db | ||
| 544 | + ) | ||
| 545 | + .await, | ||
| 546 | + 0, | ||
| 547 | + "the enrollments the blueprint pumped go with it" | ||
| 548 | + ); | ||
| 549 | + assert_eq!( | ||
| 550 | + counter( | ||
| 551 | + &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{algebra}"), | ||
| 552 | + &db | ||
| 553 | + ) | ||
| 554 | + .await, | ||
| 555 | + 1, | ||
| 556 | + "the hand-attached class keeps its student's seat" | ||
| 557 | + ); | ||
| 558 | +} | ||
| 559 | + | ||
| 560 | +/// The migration's whole stale-data claim, made from the state a pre-migration | ||
| 561 | +/// row is actually in: `class_course` carries no `source` key. | ||
| 562 | +/// | ||
| 563 | +/// There is no backfill, because absence *is* the meaning β so this is what | ||
| 564 | +/// pins that `source = $blueprint` is false for an absent key, exactly as it is | ||
| 565 | +/// on `enrollment.source`. If it were not, a blueprint's first removal would | ||
| 566 | +/// detach every course the school had ever attached by hand. | ||
| 567 | +#[tokio::test] | ||
| 568 | +async fn a_row_written_before_the_column_reads_as_hand_attached() { | ||
| 569 | + let (app, db) = app_and_db().await; | ||
| 570 | + let manager = login_as(&app, &db, "mgr", "manager").await; | ||
| 571 | + let algebra = create_course(&app, &manager, "algebra").await; | ||
| 572 | + let class = create_class(&app, &manager, "9-A", "9").await; | ||
| 573 | + student_in(&app, &db, &class, &manager, "ali").await; | ||
| 574 | + let attached_by_hand = send( | ||
| 575 | + &app, | ||
| 576 | + "POST", | ||
| 577 | + &format!("/classes/{class}/courses"), | ||
| 578 | + Some(&manager), | ||
| 579 | + Some(json!({ "course_id": algebra.clone() })), | ||
| 580 | + ) | ||
| 581 | + .await; | ||
| 582 | + assert_eq!(attached_by_hand.status, StatusCode::CREATED); | ||
| 583 | + // Age the row to before the column existed. `UNSET`, not `= NONE`: an | ||
| 584 | + // absent key is what the store holds today, and it is what the rule reads. | ||
| 585 | + db.query("UPDATE class_course UNSET source") | ||
| 586 | + .await | ||
| 587 | + .unwrap() | ||
| 588 | + .check() | ||
| 589 | + .unwrap(); | ||
| 590 | + assert_eq!(source_of(&class, &algebra, &db).await, None); | ||
| 591 | + | ||
| 592 | + // Every read still decodes it⦠| ||
| 593 | + let listed = send( | ||
| 594 | + &app, | ||
| 595 | + "GET", | ||
| 596 | + &format!("/classes/{class}/courses"), | ||
| 597 | + Some(&manager), | ||
| 598 | + None, | ||
| 599 | + ) | ||
| 600 | + .await; | ||
| 601 | + assert_eq!(listed.status, StatusCode::OK, "{:?}", listed.body); | ||
| 602 | + assert_eq!(listed.body["items"].as_array().unwrap().len(), 1); | ||
| 603 | + | ||
| 604 | + // β¦a blueprint that names the same course does not adopt itβ¦ | ||
| 605 | + let made = send( | ||
| 606 | + &app, | ||
| 607 | + "POST", | ||
| 608 | + "/classes/blueprints", | ||
| 609 | + Some(&manager), | ||
| 610 | + Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), | ||
| 611 | + ) | ||
| 612 | + .await; | ||
| 613 | + assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); | ||
| 614 | + assert!( | ||
| 615 | + skips(&made).is_empty(), | ||
| 616 | + "a course the class already carries is not a skip: {:?}", | ||
| 617 | + made.body | ||
| 618 | + ); | ||
| 619 | + assert_eq!(source_of(&class, &algebra, &db).await, None); | ||
| 620 | + | ||
| 621 | + // β¦and deleting that blueprint β which drops every course it holds β leaves | ||
| 622 | + // the aged row exactly where it is. | ||
| 623 | + let dropped = send( | ||
| 624 | + &app, | ||
| 625 | + "DELETE", | ||
| 626 | + "/classes/blueprints/9", | ||
| 627 | + Some(&manager), | ||
| 628 | + None, | ||
| 629 | + ) | ||
| 630 | + .await; | ||
| 631 | + assert_eq!(dropped.status, StatusCode::NO_CONTENT); | ||
| 632 | + assert!( | ||
| 633 | + attached(&class, &algebra, &db).await, | ||
| 634 | + "a pre-migration row is hand-attached and unreachable by any blueprint sweep" | ||
| 635 | + ); | ||
| 636 | + assert_eq!( | ||
| 637 | + counter( | ||
| 638 | + &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{algebra}"), | ||
| 639 | + &db | ||
| 640 | + ) | ||
| 641 | + .await, | ||
| 642 | + 1 | ||
| 643 | + ); | ||
| 644 | +} | ||
tests/regress_boards.rsadded+181 -0
| @@ -0,0 +1,181 @@ | |||
| 1 | +//! Whiteboard defects that must stay fixed: the REST canvas agreeing with the | ||
| 2 | +//! room's socket about `clear` markers, and the lock holding against its own | ||
| 3 | +//! creator's clear. | ||
| 4 | + | ||
| 5 | +mod common; | ||
| 6 | + | ||
| 7 | +use axum::http::StatusCode; | ||
| 8 | +use common::{app_and_db, items, login, me_id, send}; | ||
| 9 | +use hezarfen_backend::domain::board::BoardId; | ||
| 10 | +use hezarfen_backend::domain::board_stroke::BoardStroke; | ||
| 11 | +use hezarfen_backend::domain::user::UserId; | ||
| 12 | +use serde_json::json; | ||
| 13 | + | ||
| 14 | +async fn a_board(app: &axum::Router, session: &str) -> String { | ||
| 15 | + let res = send( | ||
| 16 | + app, | ||
| 17 | + "POST", | ||
| 18 | + "/boards", | ||
| 19 | + Some(session), | ||
| 20 | + Some(json!({ "title": "Tahta" })), | ||
| 21 | + ) | ||
| 22 | + .await; | ||
| 23 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 24 | + res.body["id"].as_str().unwrap().to_string() | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +/// `GET /strokes` scopes to the board's current epoch, which by construction | ||
| 28 | +/// holds no `clear` marker β except when a clear commits between the board read | ||
| 29 | +/// and the row read and files its marker under the epoch just named. The room's | ||
| 30 | +/// socket filters markers out and never shows it, so an unfiltered page made | ||
| 31 | +/// the two views disagree in exactly that race. The race is pinned here by | ||
| 32 | +/// leaving a marker in the epoch the board still points at. | ||
| 33 | +#[tokio::test] | ||
| 34 | +async fn a_strokes_page_never_carries_a_clear_marker() { | ||
| 35 | + let (app, db) = app_and_db().await; | ||
| 36 | + let ali = login(&app, "ali").await; | ||
| 37 | + let ali_id = me_id(&app, &ali).await; | ||
| 38 | + let board = a_board(&app, &ali).await; | ||
| 39 | + | ||
| 40 | + for n in 0..2 { | ||
| 41 | + BoardStroke::append( | ||
| 42 | + &BoardId::from_key(&board), | ||
| 43 | + &UserId::from_key(&ali_id), | ||
| 44 | + &format!("{{\"p\":[0,{n}]}}"), | ||
| 45 | + 0, | ||
| 46 | + &db, | ||
| 47 | + ) | ||
| 48 | + .await | ||
| 49 | + .expect("append"); | ||
| 50 | + } | ||
| 51 | + let res = send( | ||
| 52 | + &app, | ||
| 53 | + "POST", | ||
| 54 | + &format!("/boards/{board}/clear"), | ||
| 55 | + Some(&ali), | ||
| 56 | + None, | ||
| 57 | + ) | ||
| 58 | + .await; | ||
| 59 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 60 | + | ||
| 61 | + // The clear left a marker on epoch 0 and moved the board to epoch 1. Point | ||
| 62 | + // the board back at 0: that is precisely what a reader that read the board | ||
| 63 | + // one instant before the clear committed is looking at. | ||
| 64 | + db.query("UPDATE $b SET epoch = 0") | ||
| 65 | + .bind(("b", BoardId::from_key(&board).record())) | ||
| 66 | + .await | ||
| 67 | + .expect("rewind") | ||
| 68 | + .check() | ||
| 69 | + .expect("rewind"); | ||
| 70 | + | ||
| 71 | + let res = send( | ||
| 72 | + &app, | ||
| 73 | + "GET", | ||
| 74 | + &format!("/boards/{board}/strokes"), | ||
| 75 | + Some(&ali), | ||
| 76 | + None, | ||
| 77 | + ) | ||
| 78 | + .await; | ||
| 79 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 80 | + let page = items(&res.body); | ||
| 81 | + assert_eq!(page.len(), 2, "the two marks, and only them: {}", res.body); | ||
| 82 | + assert_eq!( | ||
| 83 | + res.body["total"], 2, | ||
| 84 | + "the envelope's total counts what is served: {}", | ||
| 85 | + res.body | ||
| 86 | + ); | ||
| 87 | + assert!( | ||
| 88 | + page.iter().all(|row| row["kind"] == "stroke"), | ||
| 89 | + "a clear marker reached the live canvas: {}", | ||
| 90 | + res.body | ||
| 91 | + ); | ||
| 92 | + | ||
| 93 | + // The markers are not lost β /history and /epochs are where they live. | ||
| 94 | + let res = send( | ||
| 95 | + &app, | ||
| 96 | + "GET", | ||
| 97 | + &format!("/boards/{board}/history"), | ||
| 98 | + Some(&ali), | ||
| 99 | + None, | ||
| 100 | + ) | ||
| 101 | + .await; | ||
| 102 | + assert_eq!( | ||
| 103 | + items(&res.body) | ||
| 104 | + .iter() | ||
| 105 | + .filter(|row| row["kind"] == "clear") | ||
| 106 | + .count(), | ||
| 107 | + 1, | ||
| 108 | + "{}", | ||
| 109 | + res.body | ||
| 110 | + ); | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +/// The lock pauses the canvas against every write to it, the creator's own | ||
| 114 | +/// clear included: a `409`, not a `403` β a lock is a state the caller can | ||
| 115 | +/// undo, while the `403` on this route means "not your board". The accepted | ||
| 116 | +/// cost is the recovery: unlock, clear, relock. | ||
| 117 | +#[tokio::test] | ||
| 118 | +async fn a_locked_board_refuses_the_creator_s_clear_with_409() { | ||
| 119 | + let (app, db) = app_and_db().await; | ||
| 120 | + let ali = login(&app, "ali").await; | ||
| 121 | + let ali_id = me_id(&app, &ali).await; | ||
| 122 | + let board = a_board(&app, &ali).await; | ||
| 123 | + BoardStroke::append( | ||
| 124 | + &BoardId::from_key(&board), | ||
| 125 | + &UserId::from_key(&ali_id), | ||
| 126 | + "{\"p\":[1,2]}", | ||
| 127 | + 0, | ||
| 128 | + &db, | ||
| 129 | + ) | ||
| 130 | + .await | ||
| 131 | + .expect("append"); | ||
| 132 | + | ||
| 133 | + let lock = async |locked: bool| { | ||
| 134 | + send( | ||
| 135 | + &app, | ||
| 136 | + "PATCH", | ||
| 137 | + &format!("/boards/{board}"), | ||
| 138 | + Some(&ali), | ||
| 139 | + Some(json!({ "locked": locked })), | ||
| 140 | + ) | ||
| 141 | + .await | ||
| 142 | + }; | ||
| 143 | + let res = lock(true).await; | ||
| 144 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 145 | + | ||
| 146 | + let res = send( | ||
| 147 | + &app, | ||
| 148 | + "POST", | ||
| 149 | + &format!("/boards/{board}/clear"), | ||
| 150 | + Some(&ali), | ||
| 151 | + None, | ||
| 152 | + ) | ||
| 153 | + .await; | ||
| 154 | + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | ||
| 155 | + // Nothing was minted and the epoch did not move. | ||
| 156 | + let res = send( | ||
| 157 | + &app, | ||
| 158 | + "GET", | ||
| 159 | + &format!("/boards/{board}/epochs"), | ||
| 160 | + Some(&ali), | ||
| 161 | + None, | ||
| 162 | + ) | ||
| 163 | + .await; | ||
| 164 | + assert!(items(&res.body).is_empty(), "{}", res.body); | ||
| 165 | + let res = send(&app, "GET", &format!("/boards/{board}"), Some(&ali), None).await; | ||
| 166 | + assert_eq!(res.body["epoch"], 0, "{}", res.body); | ||
| 167 | + | ||
| 168 | + // Unlocked, the same clear lands. | ||
| 169 | + let res = lock(false).await; | ||
| 170 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 171 | + let res = send( | ||
| 172 | + &app, | ||
| 173 | + "POST", | ||
| 174 | + &format!("/boards/{board}/clear"), | ||
| 175 | + Some(&ali), | ||
| 176 | + None, | ||
| 177 | + ) | ||
| 178 | + .await; | ||
| 179 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 180 | + assert_eq!(res.body["count"], 1, "{}", res.body); | ||
| 181 | +} | ||
tests/regress_event_class_audience.rsadded+268 -0
| @@ -0,0 +1,268 @@ | |||
| 1 | +//! The `class` event audience (Εube): an event aimed at a class section. | ||
| 2 | +//! | ||
| 3 | +//! The rule under test is that the roster resolves LIVE from `class_member`, | ||
| 4 | +//! exactly as `course` resolves from `enrollment` and `role` from the user row | ||
| 5 | +//! β never snapshotted at create time. The class layer's own membership stays | ||
| 6 | +//! real rows written by the pump; nothing here touches that. | ||
| 7 | + | ||
| 8 | +mod common; | ||
| 9 | + | ||
| 10 | +use axum::Router; | ||
| 11 | +use axum::http::StatusCode; | ||
| 12 | +use common::{id_of, items, login_as, send, total}; | ||
| 13 | +use hezarfen_backend::database::Database; | ||
| 14 | +use serde_json::json; | ||
| 15 | + | ||
| 16 | +async fn create_class(app: &Router, cookie: &str, name: &str) -> String { | ||
| 17 | + let res = send( | ||
| 18 | + app, | ||
| 19 | + "POST", | ||
| 20 | + "/classes", | ||
| 21 | + Some(cookie), | ||
| 22 | + Some(json!({"name": name})), | ||
| 23 | + ) | ||
| 24 | + .await; | ||
| 25 | + assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body); | ||
| 26 | + id_of(&res.body) | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +/// An event aimed at `class`, created by a teacher+. | ||
| 30 | +async fn class_event(app: &Router, cookie: &str, class: &str) -> String { | ||
| 31 | + let res = send( | ||
| 32 | + app, | ||
| 33 | + "POST", | ||
| 34 | + "/events", | ||
| 35 | + Some(cookie), | ||
| 36 | + Some(json!({"title": "Veli toplantΔ±sΔ±", "audience": {"kind": "class", "class": class}})), | ||
| 37 | + ) | ||
| 38 | + .await; | ||
| 39 | + assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body); | ||
| 40 | + id_of(&res.body) | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +/// The event's live roster, as user ids. | ||
| 44 | +async fn roster(app: &Router, cookie: &str, event: &str) -> Vec<String> { | ||
| 45 | + let res = send( | ||
| 46 | + app, | ||
| 47 | + "GET", | ||
| 48 | + &format!("/events/{event}/roster"), | ||
| 49 | + Some(cookie), | ||
| 50 | + None, | ||
| 51 | + ) | ||
| 52 | + .await; | ||
| 53 | + assert_eq!(res.status, StatusCode::OK, "{:?}", res.body); | ||
| 54 | + assert_eq!(total(&res.body), items(&res.body).len() as i64); | ||
| 55 | + items(&res.body) | ||
| 56 | + .iter() | ||
| 57 | + .map(|entry| entry["user"]["id"].as_str().unwrap().to_string()) | ||
| 58 | + .collect() | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +async fn student(app: &Router, db: &Database, username: &str) -> (String, String) { | ||
| 62 | + let cookie = login_as(app, db, username, "student").await; | ||
| 63 | + let id = common::me_id(app, &cookie).await; | ||
| 64 | + (cookie, id) | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +async fn add_member(app: &Router, cookie: &str, class: &str, user: &str) -> StatusCode { | ||
| 68 | + send( | ||
| 69 | + app, | ||
| 70 | + "POST", | ||
| 71 | + &format!("/classes/{class}/members"), | ||
| 72 | + Some(cookie), | ||
| 73 | + Some(json!({"user_id": user})), | ||
| 74 | + ) | ||
| 75 | + .await | ||
| 76 | + .status | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +/// (a) the roster is exactly the class's current members, and (b) a student | ||
| 80 | +/// added *after* the event was created is on it β the live-resolution proof. | ||
| 81 | +#[tokio::test] | ||
| 82 | +async fn class_roster_resolves_live() { | ||
| 83 | + let (app, db) = common::app_and_db().await; | ||
| 84 | + let boss = login_as(&app, &db, "mudur", "manager").await; | ||
| 85 | + let (_, ayse) = student(&app, &db, "ayse").await; | ||
| 86 | + let (_, mehmet) = student(&app, &db, "mehmet").await; | ||
| 87 | + let (_, outsider) = student(&app, &db, "kenan").await; | ||
| 88 | + | ||
| 89 | + let class = create_class(&app, &boss, "9-A").await; | ||
| 90 | + assert_eq!( | ||
| 91 | + add_member(&app, &boss, &class, &ayse).await, | ||
| 92 | + StatusCode::CREATED | ||
| 93 | + ); | ||
| 94 | + | ||
| 95 | + let event = class_event(&app, &boss, &class).await; | ||
| 96 | + assert_eq!(roster(&app, &boss, &event).await, vec![ayse.clone()]); | ||
| 97 | + | ||
| 98 | + // Added after the event exists: a frozen roster would miss them. | ||
| 99 | + assert_eq!( | ||
| 100 | + add_member(&app, &boss, &class, &mehmet).await, | ||
| 101 | + StatusCode::CREATED | ||
| 102 | + ); | ||
| 103 | + let mut live = roster(&app, &boss, &event).await; | ||
| 104 | + live.sort(); | ||
| 105 | + let mut expected = vec![ayse.clone(), mehmet.clone()]; | ||
| 106 | + expected.sort(); | ||
| 107 | + assert_eq!( | ||
| 108 | + live, expected, | ||
| 109 | + "the roster must follow the class, not a snapshot" | ||
| 110 | + ); | ||
| 111 | + assert!(!live.contains(&outsider), "a non-member must never appear"); | ||
| 112 | + | ||
| 113 | + // ...and removal takes them straight back off it. | ||
| 114 | + let removed = send( | ||
| 115 | + &app, | ||
| 116 | + "DELETE", | ||
| 117 | + &format!("/classes/{class}/members/{mehmet}"), | ||
| 118 | + Some(&boss), | ||
| 119 | + None, | ||
| 120 | + ) | ||
| 121 | + .await; | ||
| 122 | + assert_eq!(removed.status, StatusCode::NO_CONTENT, "{:?}", removed.body); | ||
| 123 | + assert_eq!(roster(&app, &boss, &event).await, vec![ayse.clone()]); | ||
| 124 | + | ||
| 125 | + // The point check behind marking agrees with the roster: a member can be | ||
| 126 | + // marked, an outsider is refused. | ||
| 127 | + for (user, expect) in [ | ||
| 128 | + (&ayse, StatusCode::OK), | ||
| 129 | + (&outsider, StatusCode::BAD_REQUEST), | ||
| 130 | + ] { | ||
| 131 | + let marked = send( | ||
| 132 | + &app, | ||
| 133 | + "POST", | ||
| 134 | + &format!("/events/{event}/attendance"), | ||
| 135 | + Some(&boss), | ||
| 136 | + Some(json!({"status": "present", "user_id": user})), | ||
| 137 | + ) | ||
| 138 | + .await; | ||
| 139 | + assert_eq!(marked.status, expect, "{user}: {:?}", marked.body); | ||
| 140 | + } | ||
| 141 | +} | ||
| 142 | + | ||
| 143 | +/// (c) deleting the class leaves the event alive with an empty roster β the | ||
| 144 | +/// behaviour a deleted *course* audience already has (`Course::delete` never | ||
| 145 | +/// touches `event`), copied deliberately. | ||
| 146 | +#[tokio::test] | ||
| 147 | +async fn deleting_the_class_empties_the_roster_without_erroring() { | ||
| 148 | + let (app, db) = common::app_and_db().await; | ||
| 149 | + let boss = login_as(&app, &db, "mudur", "manager").await; | ||
| 150 | + let (_, ayse) = student(&app, &db, "ayse").await; | ||
| 151 | + | ||
| 152 | + let class = create_class(&app, &boss, "9-A").await; | ||
| 153 | + assert_eq!( | ||
| 154 | + add_member(&app, &boss, &class, &ayse).await, | ||
| 155 | + StatusCode::CREATED | ||
| 156 | + ); | ||
| 157 | + let event = class_event(&app, &boss, &class).await; | ||
| 158 | + assert_eq!(roster(&app, &boss, &event).await, vec![ayse.clone()]); | ||
| 159 | + | ||
| 160 | + // `ClassGroup::delete` refuses a class that still holds members, so the | ||
| 161 | + // roster is emptied first β the only route by which a class can go away. | ||
| 162 | + let held = send( | ||
| 163 | + &app, | ||
| 164 | + "DELETE", | ||
| 165 | + &format!("/classes/{class}"), | ||
| 166 | + Some(&boss), | ||
| 167 | + None, | ||
| 168 | + ) | ||
| 169 | + .await; | ||
| 170 | + assert_eq!(held.status, StatusCode::CONFLICT, "{:?}", held.body); | ||
| 171 | + send( | ||
| 172 | + &app, | ||
| 173 | + "DELETE", | ||
| 174 | + &format!("/classes/{class}/members/{ayse}"), | ||
| 175 | + Some(&boss), | ||
| 176 | + None, | ||
| 177 | + ) | ||
| 178 | + .await; | ||
| 179 | + let gone = send( | ||
| 180 | + &app, | ||
| 181 | + "DELETE", | ||
| 182 | + &format!("/classes/{class}"), | ||
| 183 | + Some(&boss), | ||
| 184 | + None, | ||
| 185 | + ) | ||
| 186 | + .await; | ||
| 187 | + assert_eq!(gone.status, StatusCode::NO_CONTENT, "{:?}", gone.body); | ||
| 188 | + | ||
| 189 | + // The event survives its class, pointing at a record that no longer exists. | ||
| 190 | + let read = send(&app, "GET", &format!("/events/{event}"), Some(&boss), None).await; | ||
| 191 | + assert_eq!(read.status, StatusCode::OK, "{:?}", read.body); | ||
| 192 | + assert_eq!(read.body["audience"]["kind"], "class"); | ||
| 193 | + assert_eq!( | ||
| 194 | + roster(&app, &boss, &event).await, | ||
| 195 | + Vec::<String>::new(), | ||
| 196 | + "a dangling class resolves empty, it does not error" | ||
| 197 | + ); | ||
| 198 | +} | ||
| 199 | + | ||
| 200 | +/// (d) the DTO round-trips: what create echoes, what a read echoes, and what a | ||
| 201 | +/// PATCH onto and off the kind stores. | ||
| 202 | +#[tokio::test] | ||
| 203 | +async fn the_audience_dto_round_trips() { | ||
| 204 | + let (app, db) = common::app_and_db().await; | ||
| 205 | + let boss = login_as(&app, &db, "mudur", "manager").await; | ||
| 206 | + let class = create_class(&app, &boss, "9-A").await; | ||
| 207 | + | ||
| 208 | + let created = send( | ||
| 209 | + &app, | ||
| 210 | + "POST", | ||
| 211 | + "/events", | ||
| 212 | + Some(&boss), | ||
| 213 | + Some(json!({"title": "Gezi", "audience": {"kind": "class", "class": class}})), | ||
| 214 | + ) | ||
| 215 | + .await; | ||
| 216 | + assert_eq!(created.status, StatusCode::CREATED, "{:?}", created.body); | ||
| 217 | + let wire = json!({"kind": "class", "class": class}); | ||
| 218 | + assert_eq!(created.body["audience"], wire); | ||
| 219 | + let event = id_of(&created.body); | ||
| 220 | + | ||
| 221 | + // Re-read off the stored row: SCHEMAFULL must have kept `audience.class`. | ||
| 222 | + let read = send(&app, "GET", &format!("/events/{event}"), Some(&boss), None).await; | ||
| 223 | + assert_eq!(read.body["audience"], wire); | ||
| 224 | + | ||
| 225 | + // PATCH onto the kind from another one, and back off it again. | ||
| 226 | + let school = send( | ||
| 227 | + &app, | ||
| 228 | + "PATCH", | ||
| 229 | + &format!("/events/{event}"), | ||
| 230 | + Some(&boss), | ||
| 231 | + Some(json!({"audience": {"kind": "school"}})), | ||
| 232 | + ) | ||
| 233 | + .await; | ||
| 234 | + assert_eq!(school.body["audience"], json!({"kind": "school"})); | ||
| 235 | + let back = send( | ||
| 236 | + &app, | ||
| 237 | + "PATCH", | ||
| 238 | + &format!("/events/{event}"), | ||
| 239 | + Some(&boss), | ||
| 240 | + Some(json!({"audience": {"kind": "class", "class": class}})), | ||
| 241 | + ) | ||
| 242 | + .await; | ||
| 243 | + assert_eq!(back.status, StatusCode::OK, "{:?}", back.body); | ||
| 244 | + assert_eq!(back.body["audience"], wire); | ||
| 245 | + | ||
| 246 | + // An unknown class is a 400, not a stored dangling reference. | ||
| 247 | + let bogus = send( | ||
| 248 | + &app, | ||
| 249 | + "POST", | ||
| 250 | + "/events", | ||
| 251 | + Some(&boss), | ||
| 252 | + Some(json!({"title": "Yok", "audience": {"kind": "class", "class": "01JNOPE"}})), | ||
| 253 | + ) | ||
| 254 | + .await; | ||
| 255 | + assert_eq!(bogus.status, StatusCode::BAD_REQUEST, "{:?}", bogus.body); | ||
| 256 | + | ||
| 257 | + // A class-audience event takes no registrations β the two kinds are | ||
| 258 | + // exclusive, so no signup row can collide with a class roster. | ||
| 259 | + let seat = send( | ||
| 260 | + &app, | ||
| 261 | + "POST", | ||
| 262 | + &format!("/events/{event}/register"), | ||
| 263 | + Some(&boss), | ||
| 264 | + Some(json!({})), | ||
| 265 | + ) | ||
| 266 | + .await; | ||
| 267 | + assert_eq!(seat.status, StatusCode::BAD_REQUEST, "{:?}", seat.body); | ||
| 268 | +} | ||
tests/regress_review.rsmodified+363 -0
| @@ -6,6 +6,12 @@ | |||
| 6 | //! | 6 | //! |
| 7 | //! The gate now refuses (409) while the caller's latest sitting is in progress. | 7 | //! The gate now refuses (409) while the caller's latest sitting is in progress. |
| 8 | //! Deterministic: the retake is started over HTTP, no clock or race involved. | 8 | //! Deterministic: the retake is started over HTTP, no clock or race involved. |
| 9 | +//! | ||
| 10 | +//! And its cross-exam twin: the question bank copies `correct` into every exam | ||
| 11 | +//! a template is instantiated into, so a graded exam's review used to hand out | ||
| 12 | +//! the key to the copy the caller was still answering in *another* exam. Those | ||
| 13 | +//! questions now come back keyless β keyed on the template, so the rest of the | ||
| 14 | +//! reviewed exam is untouched. | ||
| 9 | 15 | ||
| 10 | mod common; | 16 | mod common; |
| 11 | 17 | ||
| @@ -16,6 +22,363 @@ use common::{ | |||
| 16 | }; | 22 | }; |
| 17 | use serde_json::json; | 23 | use serde_json::json; |
| 18 | 24 | ||
| 25 | +/// A bank template instantiated into two exams copies its `correct` into both. | ||
| 26 | +/// Reviewing the graded one must not hand out the key to the copy the caller is | ||
| 27 | +/// still answering in the other β but only that question blanks out. | ||
| 28 | +#[tokio::test] | ||
| 29 | +async fn review_hides_the_key_of_a_bank_question_live_under_another_sitting() { | ||
| 30 | + let (app, db) = app_and_db().await; | ||
| 31 | + let teacher = login_as(&app, &db, "rev_bank_t", "teacher").await; | ||
| 32 | + let student = login(&app, "rev_bank_s").await; | ||
| 33 | + let student_id = me_id(&app, &student).await; | ||
| 34 | + | ||
| 35 | + let course = create_course(&app, &teacher, "maths").await; | ||
| 36 | + let subject = create_subject(&app, &teacher, &course, "arithmetic").await; | ||
| 37 | + enroll(&app, &teacher, &course, &student_id).await; | ||
| 38 | + | ||
| 39 | + // One template, instantiated into both exams below. | ||
| 40 | + let res = send( | ||
| 41 | + &app, | ||
| 42 | + "POST", | ||
| 43 | + "/bank-questions", | ||
| 44 | + Some(&teacher), | ||
| 45 | + Some(json!({ "subject_id": subject, "text": "2 + 2?", "kind": "choice", | ||
| 46 | + "points": 10, "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], | ||
| 47 | + "correct": "c1" })), | ||
| 48 | + ) | ||
| 49 | + .await; | ||
| 50 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 51 | + let template = id_of(&res.body); | ||
| 52 | + | ||
| 53 | + let exam = |title: &str, review: bool| { | ||
| 54 | + create_exam_with( | ||
| 55 | + &app, | ||
| 56 | + &teacher, | ||
| 57 | + &course, | ||
| 58 | + json!({ "title": title, "kind": "quiz", "mode": "open", | ||
| 59 | + "max_attempts": 1, "allow_review": review }), | ||
| 60 | + ) | ||
| 61 | + }; | ||
| 62 | + let res = exam("graded quiz", true).await; | ||
| 63 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 64 | + let graded = id_of(&res.body); | ||
| 65 | + let res = exam("live quiz", false).await; | ||
| 66 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 67 | + let live = id_of(&res.body); | ||
| 68 | + | ||
| 69 | + let from_bank = async |exam: &str| { | ||
| 70 | + let res = send( | ||
| 71 | + &app, | ||
| 72 | + "POST", | ||
| 73 | + &format!("/exams/{exam}/questions/from-bank/{template}"), | ||
| 74 | + Some(&teacher), | ||
| 75 | + Some(json!({ "subject_id": subject })), | ||
| 76 | + ) | ||
| 77 | + .await; | ||
| 78 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 79 | + res | ||
| 80 | + }; | ||
| 81 | + let res = from_bank(&graded).await; | ||
| 82 | + let shared = id_of(&res.body); | ||
| 83 | + let shared_right = res.body["correct"].as_str().expect("key").to_string(); | ||
| 84 | + from_bank(&live).await; | ||
| 85 | + | ||
| 86 | + // A hand-written question in the same exam: no template, never hidden. | ||
| 87 | + let res = send( | ||
| 88 | + &app, | ||
| 89 | + "POST", | ||
| 90 | + &format!("/exams/{graded}/questions"), | ||
| 91 | + Some(&teacher), | ||
| 92 | + Some(json!({ "text": "3 + 3?", "kind": "choice", "points": 10, | ||
| 93 | + "subject_id": subject, | ||
| 94 | + "choices": [{"id": "c0", "text": "5"}, {"id": "c1", "text": "6"}], | ||
| 95 | + "correct": "c1" })), | ||
| 96 | + ) | ||
| 97 | + .await; | ||
| 98 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 99 | + let own = id_of(&res.body); | ||
| 100 | + | ||
| 101 | + // Sit the graded exam, answer the shared question right, get marked, finish. | ||
| 102 | + let res = send( | ||
| 103 | + &app, | ||
| 104 | + "POST", | ||
| 105 | + &format!("/exams/{graded}/attempt"), | ||
| 106 | + Some(&student), | ||
| 107 | + None, | ||
| 108 | + ) | ||
| 109 | + .await; | ||
| 110 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 111 | + let res = send( | ||
| 112 | + &app, | ||
| 113 | + "POST", | ||
| 114 | + &format!("/exams/{graded}/attempt/answers"), | ||
| 115 | + Some(&student), | ||
| 116 | + Some(json!({ "question_id": shared, "selected": shared_right })), | ||
| 117 | + ) | ||
| 118 | + .await; | ||
| 119 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 120 | + let res = send( | ||
| 121 | + &app, | ||
| 122 | + "POST", | ||
| 123 | + &format!("/exams/{graded}/results"), | ||
| 124 | + Some(&teacher), | ||
| 125 | + Some(json!({ "mark": 90, "user_id": student_id })), | ||
| 126 | + ) | ||
| 127 | + .await; | ||
| 128 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 129 | + let res = send( | ||
| 130 | + &app, | ||
| 131 | + "POST", | ||
| 132 | + &format!("/exams/{graded}/attempt/finish"), | ||
| 133 | + Some(&student), | ||
| 134 | + None, | ||
| 135 | + ) | ||
| 136 | + .await; | ||
| 137 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 138 | + | ||
| 139 | + let key_uri = format!("/exams/{graded}/review/questions"); | ||
| 140 | + let sheet_uri = format!("/exams/{graded}/review/attempts/1/answers"); | ||
| 141 | + let key_of = |body: &serde_json::Value, id: &str| { | ||
| 142 | + common::items(body) | ||
| 143 | + .iter() | ||
| 144 | + .find(|q| q["id"] == id) | ||
| 145 | + .expect("question in the review list")["correct"] | ||
| 146 | + .clone() | ||
| 147 | + }; | ||
| 148 | + | ||
| 149 | + // Nothing live yet: the whole key is readable, both questions score. | ||
| 150 | + let res = send(&app, "GET", &key_uri, Some(&student), None).await; | ||
| 151 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 152 | + assert_eq!(key_of(&res.body, &shared), json!(shared_right)); | ||
| 153 | + let res = send(&app, "GET", &sheet_uri, Some(&student), None).await; | ||
| 154 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 155 | + assert_eq!(res.body["answers"][0]["is_correct"], json!(true)); | ||
| 156 | + assert_eq!( | ||
| 157 | + res.body["auto_score"], | ||
| 158 | + json!({"earned": 10, "possible": 20}) | ||
| 159 | + ); | ||
| 160 | + | ||
| 161 | + // Now the caller sits the other exam, which holds a copy of the template. | ||
| 162 | + let res = send( | ||
| 163 | + &app, | ||
| 164 | + "POST", | ||
| 165 | + &format!("/exams/{live}/attempt"), | ||
| 166 | + Some(&student), | ||
| 167 | + None, | ||
| 168 | + ) | ||
| 169 | + .await; | ||
| 170 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 171 | + assert_eq!(res.body["status"], "in_progress", "{}", res.body); | ||
| 172 | + | ||
| 173 | + // The leak: the shared question's key is gone, the hand-written one's is | ||
| 174 | + // not, and review itself stays open. | ||
| 175 | + let res = send(&app, "GET", &key_uri, Some(&student), None).await; | ||
| 176 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 177 | + assert_eq!(key_of(&res.body, &shared), json!(null), "{}", res.body); | ||
| 178 | + assert_ne!(key_of(&res.body, &own), json!(null), "{}", res.body); | ||
| 179 | + | ||
| 180 | + // Same on the sheet: no correctness flag, and no score to subtract it out of. | ||
| 181 | + let res = send(&app, "GET", &sheet_uri, Some(&student), None).await; | ||
| 182 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 183 | + assert_eq!(res.body["answers"][0]["question"], shared, "{}", res.body); | ||
| 184 | + assert_eq!(res.body["answers"][0]["is_correct"], json!(null)); | ||
| 185 | + assert_eq!(res.body["auto_score"], json!({"earned": 0, "possible": 10})); | ||
| 186 | + | ||
| 187 | + // Submitting the other sitting gives the key back. | ||
| 188 | + let res = send( | ||
| 189 | + &app, | ||
| 190 | + "POST", | ||
| 191 | + &format!("/exams/{live}/attempt/finish"), | ||
| 192 | + Some(&student), | ||
| 193 | + None, | ||
| 194 | + ) | ||
| 195 | + .await; | ||
| 196 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 197 | + let res = send(&app, "GET", &key_uri, Some(&student), None).await; | ||
| 198 | + assert_eq!( | ||
| 199 | + key_of(&res.body, &shared), | ||
| 200 | + json!(shared_right), | ||
| 201 | + "{}", | ||
| 202 | + res.body | ||
| 203 | + ); | ||
| 204 | +} | ||
| 205 | + | ||
| 206 | +/// The template link runs both ways, and the join has to see both columns. A | ||
| 207 | +/// question authored by hand inside exam A and *saved* to the bank carries | ||
| 208 | +/// `banked_as` and no `from_bank`; its copy in exam B carries `from_bank` and | ||
| 209 | +/// no `banked_as`. Matching either side on `from_bank` alone saw neither, and | ||
| 210 | +/// reviewing A handed out the key to a question live in B. Covered here: | ||
| 211 | +/// - A holds `banked_as`, B holds `from_bank` (the reported probe), | ||
| 212 | +/// - A holds `from_bank`, B holds `banked_as` (the mirror), | ||
| 213 | +/// - A holds both (instantiated from one template, re-saved as another) and | ||
| 214 | +/// B holds only the second β the chain a coalesce would miss. | ||
| 215 | +#[tokio::test] | ||
| 216 | +async fn review_hides_a_question_banked_out_of_it_and_live_elsewhere() { | ||
| 217 | + let (app, db) = app_and_db().await; | ||
| 218 | + let teacher = login_as(&app, &db, "rev_bank2_t", "teacher").await; | ||
| 219 | + let student = login(&app, "rev_bank2_s").await; | ||
| 220 | + let student_id = me_id(&app, &student).await; | ||
| 221 | + | ||
| 222 | + let course = create_course(&app, &teacher, "physics").await; | ||
| 223 | + let subject = create_subject(&app, &teacher, &course, "optics").await; | ||
| 224 | + enroll(&app, &teacher, &course, &student_id).await; | ||
| 225 | + | ||
| 226 | + let exam = async |title: &str, review: bool| { | ||
| 227 | + let res = create_exam_with( | ||
| 228 | + &app, | ||
| 229 | + &teacher, | ||
| 230 | + &course, | ||
| 231 | + json!({ "title": title, "kind": "quiz", "mode": "open", | ||
| 232 | + "max_attempts": 1, "allow_review": review }), | ||
| 233 | + ) | ||
| 234 | + .await; | ||
| 235 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 236 | + id_of(&res.body) | ||
| 237 | + }; | ||
| 238 | + let graded = exam("reviewed quiz", true).await; | ||
| 239 | + let live = exam("live quiz", false).await; | ||
| 240 | + | ||
| 241 | + // A question written by hand into `exam` β no provenance either way. | ||
| 242 | + let hand = async |exam: &str, text: &str| { | ||
| 243 | + let res = send( | ||
| 244 | + &app, | ||
| 245 | + "POST", | ||
| 246 | + &format!("/exams/{exam}/questions"), | ||
| 247 | + Some(&teacher), | ||
| 248 | + Some(json!({ "text": text, "kind": "choice", "points": 10, | ||
| 249 | + "subject_id": subject, | ||
| 250 | + "choices": [{"id": "c0", "text": "no"}, {"id": "c1", "text": "yes"}], | ||
| 251 | + "correct": "c1" })), | ||
| 252 | + ) | ||
| 253 | + .await; | ||
| 254 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 255 | + id_of(&res.body) | ||
| 256 | + }; | ||
| 257 | + // Save it into the bank: writes `banked_as`, leaves `from_bank` alone. | ||
| 258 | + let to_bank = async |exam: &str, question: &str| { | ||
| 259 | + let res = send( | ||
| 260 | + &app, | ||
| 261 | + "POST", | ||
| 262 | + &format!("/exams/{exam}/questions/{question}/to-bank"), | ||
| 263 | + Some(&teacher), | ||
| 264 | + None, | ||
| 265 | + ) | ||
| 266 | + .await; | ||
| 267 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 268 | + id_of(&res.body) | ||
| 269 | + }; | ||
| 270 | + // Instantiate a template into `exam`: writes `from_bank`. | ||
| 271 | + let from_bank = async |exam: &str, template: &str| { | ||
| 272 | + let res = send( | ||
| 273 | + &app, | ||
| 274 | + "POST", | ||
| 275 | + &format!("/exams/{exam}/questions/from-bank/{template}"), | ||
| 276 | + Some(&teacher), | ||
| 277 | + Some(json!({ "subject_id": subject })), | ||
| 278 | + ) | ||
| 279 | + .await; | ||
| 280 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 281 | + id_of(&res.body) | ||
| 282 | + }; | ||
| 283 | + | ||
| 284 | + // 1. banked out of the reviewed exam, instantiated into the live one. | ||
| 285 | + let banked = hand(&graded, "banked out of A").await; | ||
| 286 | + from_bank(&live, &to_bank(&graded, &banked).await).await; | ||
| 287 | + | ||
| 288 | + // 2. the mirror: banked out of the live exam, instantiated into the | ||
| 289 | + // reviewed one. | ||
| 290 | + let mirrored = from_bank( | ||
| 291 | + &graded, | ||
| 292 | + &to_bank(&live, &hand(&live, "banked out of B").await).await, | ||
| 293 | + ) | ||
| 294 | + .await; | ||
| 295 | + | ||
| 296 | + // 3. the chain: instantiated into the reviewed exam from one template, then | ||
| 297 | + // re-saved as a second β and only the second reached the live exam. | ||
| 298 | + let res = send( | ||
| 299 | + &app, | ||
| 300 | + "POST", | ||
| 301 | + "/bank-questions", | ||
| 302 | + Some(&teacher), | ||
| 303 | + Some(json!({ "subject_id": subject, "text": "chained", "kind": "choice", | ||
| 304 | + "points": 10, "choices": [{"id": "c0", "text": "no"}, {"id": "c1", "text": "yes"}], | ||
| 305 | + "correct": "c1" })), | ||
| 306 | + ) | ||
| 307 | + .await; | ||
| 308 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 309 | + let chained = from_bank(&graded, &id_of(&res.body)).await; | ||
| 310 | + from_bank(&live, &to_bank(&graded, &chained).await).await; | ||
| 311 | + | ||
| 312 | + // The control: hand-written, never banked, never instantiated. | ||
| 313 | + let own = hand(&graded, "purely local").await; | ||
| 314 | + | ||
| 315 | + // Sit the reviewed exam, get marked, finish. | ||
| 316 | + let res = send( | ||
| 317 | + &app, | ||
| 318 | + "POST", | ||
| 319 | + &format!("/exams/{graded}/attempt"), | ||
| 320 | + Some(&student), | ||
| 321 | + None, | ||
| 322 | + ) | ||
| 323 | + .await; | ||
| 324 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 325 | + let res = send( | ||
| 326 | + &app, | ||
| 327 | + "POST", | ||
| 328 | + &format!("/exams/{graded}/results"), | ||
| 329 | + Some(&teacher), | ||
| 330 | + Some(json!({ "mark": 90, "user_id": student_id })), | ||
| 331 | + ) | ||
| 332 | + .await; | ||
| 333 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 334 | + let res = send( | ||
| 335 | + &app, | ||
| 336 | + "POST", | ||
| 337 | + &format!("/exams/{graded}/attempt/finish"), | ||
| 338 | + Some(&student), | ||
| 339 | + None, | ||
| 340 | + ) | ||
| 341 | + .await; | ||
| 342 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 343 | + | ||
| 344 | + let key_uri = format!("/exams/{graded}/review/questions"); | ||
| 345 | + let key_of = |body: &serde_json::Value, id: &str| { | ||
| 346 | + common::items(body) | ||
| 347 | + .iter() | ||
| 348 | + .find(|q| q["id"] == id) | ||
| 349 | + .expect("question in the review list")["correct"] | ||
| 350 | + .clone() | ||
| 351 | + }; | ||
| 352 | + | ||
| 353 | + // Nothing live: the whole key reads. | ||
| 354 | + let res = send(&app, "GET", &key_uri, Some(&student), None).await; | ||
| 355 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 356 | + for id in [&banked, &mirrored, &chained, &own] { | ||
| 357 | + assert_ne!(key_of(&res.body, id), json!(null), "{}", res.body); | ||
| 358 | + } | ||
| 359 | + | ||
| 360 | + // The caller opens a sitting on the exam holding the copies. | ||
| 361 | + let res = send( | ||
| 362 | + &app, | ||
| 363 | + "POST", | ||
| 364 | + &format!("/exams/{live}/attempt"), | ||
| 365 | + Some(&student), | ||
| 366 | + None, | ||
| 367 | + ) | ||
| 368 | + .await; | ||
| 369 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 370 | + assert_eq!(res.body["status"], "in_progress", "{}", res.body); | ||
| 371 | + | ||
| 372 | + // The leak: all three shared questions blank out, the local one does not, | ||
| 373 | + // and review itself stays open. | ||
| 374 | + let res = send(&app, "GET", &key_uri, Some(&student), None).await; | ||
| 375 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 376 | + assert_eq!(key_of(&res.body, &banked), json!(null), "{}", res.body); | ||
| 377 | + assert_eq!(key_of(&res.body, &mirrored), json!(null), "{}", res.body); | ||
| 378 | + assert_eq!(key_of(&res.body, &chained), json!(null), "{}", res.body); | ||
| 379 | + assert_ne!(key_of(&res.body, &own), json!(null), "{}", res.body); | ||
| 380 | +} | ||
| 381 | + | ||
| 19 | /// A student mid-retake must not be able to read the answer key or the | 382 | /// A student mid-retake must not be able to read the answer key or the |
| 20 | /// correctness flags on any of their own sittings β but the same reads must | 383 | /// correctness flags on any of their own sittings β but the same reads must |
| 21 | /// still work before the retake starts and again once it is submitted. | 384 | /// still work before the retake starts and again once it is submitted. |
tests/regress_roles.rsmodified+243 -1
| @@ -396,6 +396,247 @@ async fn a_demotion_to_parent_leaves_every_board_roster_and_deletes_nothing() { | |||
| 396 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); | 396 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); |
| 397 | } | 397 | } |
| 398 | 398 | ||
| 399 | +/// Everything a demotion to `parent` must sweep, set up on one student: an | ||
| 400 | +/// enrollment (with its seat), a parent link, a board roster entry and an event | ||
| 401 | +/// signup. Answers `(admin cookie, teacher cookie, ali's id)`. | ||
| 402 | +async fn a_student_holding_every_grant( | ||
| 403 | + app: &axum::Router, | ||
| 404 | + db: &Database, | ||
| 405 | +) -> (String, String, String) { | ||
| 406 | + let admin = login_as(app, db, "yonetici", "admin").await; | ||
| 407 | + let teacher = login_as(app, db, "ogretmen", "teacher").await; | ||
| 408 | + let anne = login_as(app, db, "anne", "parent").await; | ||
| 409 | + let anne_id = me_id(app, &anne).await; | ||
| 410 | + let ali = login(app, "ali").await; | ||
| 411 | + let veli = login(app, "veli").await; | ||
| 412 | + let ali_id = me_id(app, &ali).await; | ||
| 413 | + | ||
| 414 | + let course = common::create_course(app, &teacher, "Fizik").await; | ||
| 415 | + common::enroll(app, &teacher, &course, &ali_id).await; | ||
| 416 | + let res = send( | ||
| 417 | + app, | ||
| 418 | + "POST", | ||
| 419 | + &format!("/users/{anne_id}/students"), | ||
| 420 | + Some(&admin), | ||
| 421 | + Some(json!({ "user_id": ali_id })), | ||
| 422 | + ) | ||
| 423 | + .await; | ||
| 424 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 425 | + let res = send( | ||
| 426 | + app, | ||
| 427 | + "POST", | ||
| 428 | + "/boards", | ||
| 429 | + Some(&veli), | ||
| 430 | + Some(json!({ "title": "Geometri", "participants": [ali_id] })), | ||
| 431 | + ) | ||
| 432 | + .await; | ||
| 433 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 434 | + let event = capped_event(app, &teacher, Some(1)).await; | ||
| 435 | + let res = seat(app, &teacher, &event, &ali_id).await; | ||
| 436 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 437 | + | ||
| 438 | + (admin, teacher, ali_id) | ||
| 439 | +} | ||
| 440 | + | ||
| 441 | +/// `user`'s live role, read out of the store. | ||
| 442 | +async fn role_of(user: &str, db: &Database) -> String { | ||
| 443 | + let mut result = db | ||
| 444 | + .query("SELECT VALUE role FROM type::record('user', $u)") | ||
| 445 | + .bind(("u", user.to_string())) | ||
| 446 | + .await | ||
| 447 | + .unwrap() | ||
| 448 | + .check() | ||
| 449 | + .unwrap(); | ||
| 450 | + result | ||
| 451 | + .take::<Vec<String>>(0) | ||
| 452 | + .unwrap() | ||
| 453 | + .first() | ||
| 454 | + .cloned() | ||
| 455 | + .expect("the user row must exist") | ||
| 456 | +} | ||
| 457 | + | ||
| 458 | +/// Make the next write of `kind` on `table` fail, from inside whatever | ||
| 459 | +/// transaction performs it: a `DEFINE EVENT` on the table under write fires | ||
| 460 | +/// *within* that write, which is the only way to fail one statement of a | ||
| 461 | +/// cascade deterministically (no sleeps, no racing tasks). | ||
| 462 | +async fn poison(table: &str, kind: &str, db: &Database) { | ||
| 463 | + db.query(format!( | ||
| 464 | + "DEFINE EVENT poison ON TABLE {table} WHEN $event = '{kind}' \ | ||
| 465 | + THEN {{ THROW 'poisoned' }}" | ||
| 466 | + )) | ||
| 467 | + .await | ||
| 468 | + .unwrap() | ||
| 469 | + .check() | ||
| 470 | + .unwrap(); | ||
| 471 | +} | ||
| 472 | + | ||
| 473 | +/// Every grant of `ali_id` still standing, and the old role with them β what | ||
| 474 | +/// must hold after a cascade that failed anywhere in its middle. | ||
| 475 | +async fn nothing_was_swept(ali_id: &str, db: &Database) { | ||
| 476 | + assert_eq!( | ||
| 477 | + role_of(ali_id, db).await, | ||
| 478 | + "student", | ||
| 479 | + "the role write must roll back with the sweep that failed" | ||
| 480 | + ); | ||
| 481 | + assert_eq!( | ||
| 482 | + rows("SELECT VALUE id FROM enrollment", db).await, | ||
| 483 | + 1, | ||
| 484 | + "the enrollment must survive a failed cascade" | ||
| 485 | + ); | ||
| 486 | + assert_eq!( | ||
| 487 | + counter("SELECT VALUE enrollment_count ?? 0 FROM course", db).await, | ||
| 488 | + 1, | ||
| 489 | + "β¦and so must its seat, or the roster and the count disagree forever" | ||
| 490 | + ); | ||
| 491 | + assert_eq!( | ||
| 492 | + rows("SELECT VALUE id FROM parent_link", db).await, | ||
| 493 | + 1, | ||
| 494 | + "the parent link must survive a failed cascade" | ||
| 495 | + ); | ||
| 496 | + assert_eq!( | ||
| 497 | + rows("SELECT VALUE id FROM registration", db).await, | ||
| 498 | + 1, | ||
| 499 | + "the signup must survive a failed cascade" | ||
| 500 | + ); | ||
| 501 | + assert_eq!( | ||
| 502 | + counter("SELECT VALUE registration_count ?? 0 FROM event", db).await, | ||
| 503 | + 1, | ||
| 504 | + "β¦with its seat still claimed" | ||
| 505 | + ); | ||
| 506 | + assert_eq!( | ||
| 507 | + boards_listing(ali_id, db).await, | ||
| 508 | + 1, | ||
| 509 | + "the board roster must be untouched" | ||
| 510 | + ); | ||
| 511 | +} | ||
| 512 | + | ||
| 513 | +/// The demotion, re-sent with the fault gone: it must land whole, and the seat | ||
| 514 | +/// it frees must be a seat somebody else can actually take β the capacity check | ||
| 515 | +/// reads the counter, so a row deleted without its counter frees nothing. | ||
| 516 | +async fn the_retry_takes_everything( | ||
| 517 | + app: &axum::Router, | ||
| 518 | + db: &Database, | ||
| 519 | + admin: &str, | ||
| 520 | + teacher: &str, | ||
| 521 | + ali_id: &str, | ||
| 522 | +) { | ||
| 523 | + let res = send( | ||
| 524 | + app, | ||
| 525 | + "PATCH", | ||
| 526 | + &format!("/users/{ali_id}/role"), | ||
| 527 | + Some(admin), | ||
| 528 | + Some(json!({ "role": "parent" })), | ||
| 529 | + ) | ||
| 530 | + .await; | ||
| 531 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 532 | + assert_eq!(role_of(ali_id, db).await, "parent"); | ||
| 533 | + for table in ["enrollment", "parent_link", "registration", "class_member"] { | ||
| 534 | + assert_eq!( | ||
| 535 | + rows(&format!("SELECT VALUE id FROM {table}"), db).await, | ||
| 536 | + 0, | ||
| 537 | + "{table} must be swept by the re-sent PATCH" | ||
| 538 | + ); | ||
| 539 | + } | ||
| 540 | + assert_eq!(boards_listing(ali_id, db).await, 0); | ||
| 541 | + assert_eq!( | ||
| 542 | + counter("SELECT VALUE enrollment_count ?? 0 FROM course", db).await, | ||
| 543 | + 0 | ||
| 544 | + ); | ||
| 545 | + assert_eq!( | ||
| 546 | + counter("SELECT VALUE registration_count ?? 0 FROM event", db).await, | ||
| 547 | + 0 | ||
| 548 | + ); | ||
| 549 | + // The seat is usable, which is the whole point of freeing it: the one-seat | ||
| 550 | + // list took the demoted user's row back and answers a new booking. | ||
| 551 | + let kemal_id = me_id(app, &login(app, "kemal").await).await; | ||
| 552 | + let event = ids(&send(app, "GET", "/events", Some(teacher), None).await.body) | ||
| 553 | + .first() | ||
| 554 | + .cloned() | ||
| 555 | + .expect("the event"); | ||
| 556 | + let res = seat(app, teacher, &event, &kemal_id).await; | ||
| 557 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 558 | +} | ||
| 559 | + | ||
| 560 | +/// The role write and every sweep it owes are **one** transaction, and this is | ||
| 561 | +/// what proves it: a statement in the middle of the cascade is made to fail, and | ||
| 562 | +/// the whole thing must be as if the PATCH never ran β the *old* role, and every | ||
| 563 | +/// grant of it still standing. Run as the eight separate queries this used to | ||
| 564 | +/// be, the same failure answered 500 with the role already lowered, the | ||
| 565 | +/// enrollment, the parent link and the event seat already gone, and nothing to | ||
| 566 | +/// ever put them back. | ||
| 567 | +/// | ||
| 568 | +/// The failure is injected the way `regress_classes` does it: a `DEFINE EVENT` | ||
| 569 | +/// on a table the cascade writes fires *inside* that write, so the abort is | ||
| 570 | +/// deterministic instead of a race the in-memory engine would lie about. Both | ||
| 571 | +/// ends of the cascade are poisoned, in two tests, because they fail different | ||
| 572 | +/// things: the board roster is the *last* statement of the parent arm (so every | ||
| 573 | +/// assertion below it is about a write that already succeeded and must be | ||
| 574 | +/// undone), the enrollment delete is one of the *first* (so the assertions are | ||
| 575 | +/// about writes that must never be reached). | ||
| 576 | +#[tokio::test] | ||
| 577 | +async fn a_failure_late_in_the_cascade_leaves_the_old_role_and_every_grant_standing() { | ||
| 578 | + let (app, db) = app_and_db().await; | ||
| 579 | + let (admin, teacher, ali_id) = a_student_holding_every_grant(&app, &db).await; | ||
| 580 | + | ||
| 581 | + poison("board", "UPDATE", &db).await; | ||
| 582 | + let res = send( | ||
| 583 | + &app, | ||
| 584 | + "PATCH", | ||
| 585 | + &format!("/users/{ali_id}/role"), | ||
| 586 | + Some(&admin), | ||
| 587 | + Some(json!({ "role": "parent" })), | ||
| 588 | + ) | ||
| 589 | + .await; | ||
| 590 | + assert!( | ||
| 591 | + res.status.is_server_error(), | ||
| 592 | + "the injected failure must not be answered as success: {} {}", | ||
| 593 | + res.status, | ||
| 594 | + res.body | ||
| 595 | + ); | ||
| 596 | + nothing_was_swept(&ali_id, &db).await; | ||
| 597 | + | ||
| 598 | + db.query("REMOVE EVENT poison ON TABLE board") | ||
| 599 | + .await | ||
| 600 | + .unwrap() | ||
| 601 | + .check() | ||
| 602 | + .unwrap(); | ||
| 603 | + the_retry_takes_everything(&app, &db, &admin, &teacher, &ali_id).await; | ||
| 604 | +} | ||
| 605 | + | ||
| 606 | +/// The same fold, failed at the other end: the enrollment delete is an *early* | ||
| 607 | +/// statement of the cascade, so what this pins is that the role write ahead of | ||
| 608 | +/// it and every arm behind it come down with it too β a cascade that only rolls | ||
| 609 | +/// back what ran after the fault is no transaction at all. | ||
| 610 | +#[tokio::test] | ||
| 611 | +async fn a_failure_early_in_the_cascade_rolls_the_role_write_back_with_it() { | ||
| 612 | + let (app, db) = app_and_db().await; | ||
| 613 | + let (admin, teacher, ali_id) = a_student_holding_every_grant(&app, &db).await; | ||
| 614 | + | ||
| 615 | + poison("enrollment", "DELETE", &db).await; | ||
| 616 | + let res = send( | ||
| 617 | + &app, | ||
| 618 | + "PATCH", | ||
| 619 | + &format!("/users/{ali_id}/role"), | ||
| 620 | + Some(&admin), | ||
| 621 | + Some(json!({ "role": "parent" })), | ||
| 622 | + ) | ||
| 623 | + .await; | ||
| 624 | + assert!( | ||
| 625 | + res.status.is_server_error(), | ||
| 626 | + "the injected failure must not be answered as success: {} {}", | ||
| 627 | + res.status, | ||
| 628 | + res.body | ||
| 629 | + ); | ||
| 630 | + nothing_was_swept(&ali_id, &db).await; | ||
| 631 | + | ||
| 632 | + db.query("REMOVE EVENT poison ON TABLE enrollment") | ||
| 633 | + .await | ||
| 634 | + .unwrap() | ||
| 635 | + .check() | ||
| 636 | + .unwrap(); | ||
| 637 | + the_retry_takes_everything(&app, &db, &admin, &teacher, &ali_id).await; | ||
| 638 | +} | ||
| 639 | + | ||
| 399 | /// The cascade and the parent row now commit together. Run as two queries, a | 640 | /// The cascade and the parent row now commit together. Run as two queries, a |
| 400 | /// register or a mark landing in between outlived its event β an orphan keyed | 641 | /// register or a mark landing in between outlived its event β an orphan keyed |
| 401 | /// on a row that no longer exists, so no read path could reach it and no delete | 642 | /// on a row that no longer exists, so no read path could reach it and no delete |
| @@ -446,7 +687,8 @@ async fn deleting_an_event_takes_its_children_with_it() { | |||
| 446 | 687 | ||
| 447 | /// The note half of the same defect: the attachment rows and the note commit | 688 | /// The note half of the same defect: the attachment rows and the note commit |
| 448 | /// together, so an upload can no longer leave a `note_file` pointing at a note | 689 | /// together, so an upload can no longer leave a `note_file` pointing at a note |
| 449 | -/// that is gone (its *blob* is a known, documented leak β see `Note::delete`). | 690 | +/// that is gone (its *blob* goes too: `Note::delete` returns the rows it |
| 691 | +/// removed and the handler unlinks exactly those). | ||
| 450 | #[tokio::test] | 692 | #[tokio::test] |
| 451 | async fn deleting_a_note_takes_its_attachment_rows_with_it() { | 693 | async fn deleting_a_note_takes_its_attachment_rows_with_it() { |
| 452 | let (app, db) = app_and_db().await; | 694 | let (app, db) = app_and_db().await; |
tests/spec_bounds.rsmodified+67 -0
| @@ -219,6 +219,12 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { | |||
| 219 | "maxLength", | 219 | "maxLength", |
| 220 | MAX_CLASS_GRADE_LEN as i64, | 220 | MAX_CLASS_GRADE_LEN as i64, |
| 221 | ), | 221 | ), |
| 222 | + ( | ||
| 223 | + "CreateBlueprint", | ||
| 224 | + "grade", | ||
| 225 | + "maxLength", | ||
| 226 | + MAX_CLASS_GRADE_LEN as i64, | ||
| 227 | + ), | ||
| 222 | ( | 228 | ( |
| 223 | "UpdateClass", | 229 | "UpdateClass", |
| 224 | "name", | 230 | "name", |
| @@ -862,6 +868,67 @@ async fn published_bounds_match_the_constants() { | |||
| 862 | ); | 868 | ); |
| 863 | } | 869 | } |
| 864 | 870 | ||
| 871 | +/// Every JSON-bodied operation must publish its `422`. | ||
| 872 | +/// | ||
| 873 | +/// axum's `Json` extractor answers `422 Unprocessable Entity` whenever the body | ||
| 874 | +/// parses as JSON but does not fit the DTO β a number where a string belongs, a | ||
| 875 | +/// missing required field, or (on the three `deny_unknown_fields` DTOs) a key | ||
| 876 | +/// the request does not accept. That is a status the server really returns on | ||
| 877 | +/// *every* route taking a JSON body, so a generated client that has no case for | ||
| 878 | +/// it will mishandle the most common client mistake there is. (`400` is a | ||
| 879 | +/// different failure: a body that is not JSON at all, or one whose values are | ||
| 880 | +/// well-typed but violate a domain rule β those already carry an `{error}` | ||
| 881 | +/// payload and their own declarations.) | ||
| 882 | +/// | ||
| 883 | +/// Hand-applying that declaration across ~24 files drifts the moment someone | ||
| 884 | +/// adds a route, so the emitted document is what gets asserted, not the source: | ||
| 885 | +/// a new JSON-bodied operation fails this test until it declares its `422`. | ||
| 886 | +/// Multipart operations are out of scope on purpose β their rejection is | ||
| 887 | +/// `400`, and they are checked by the same walk below. | ||
| 888 | +#[tokio::test] | ||
| 889 | +async fn every_json_body_operation_declares_422() { | ||
| 890 | + let spec = spec().await; | ||
| 891 | + | ||
| 892 | + let mut missing = Vec::new(); | ||
| 893 | + let mut wrongly_declared = Vec::new(); | ||
| 894 | + for (path, item) in spec["paths"].as_object().expect("paths").iter() { | ||
| 895 | + for (method, operation) in item.as_object().expect("path item").iter() { | ||
| 896 | + let Some(content) = operation["requestBody"]["content"].as_object() else { | ||
| 897 | + continue; | ||
| 898 | + }; | ||
| 899 | + let declares_422 = operation["responses"]["422"].is_object(); | ||
| 900 | + if content.contains_key("application/json") { | ||
| 901 | + if !declares_422 { | ||
| 902 | + missing.push(format!(" {} {path}", method.to_uppercase())); | ||
| 903 | + } | ||
| 904 | + } else if declares_422 { | ||
| 905 | + wrongly_declared.push(format!( | ||
| 906 | + " {} {path} ({})", | ||
| 907 | + method.to_uppercase(), | ||
| 908 | + content.keys().cloned().collect::<Vec<_>>().join(", ") | ||
| 909 | + )); | ||
| 910 | + } | ||
| 911 | + } | ||
| 912 | + } | ||
| 913 | + | ||
| 914 | + assert!( | ||
| 915 | + missing.is_empty(), | ||
| 916 | + "{} operation(s) take a JSON body but do not declare the `422` axum answers \ | ||
| 917 | + when that body does not fit the DTO β a generated client has no case for a \ | ||
| 918 | + status the server really returns:\n{}\n\nAdd \ | ||
| 919 | + `(status = 422, description = \"β¦\")` to each `responses(...)` block.", | ||
| 920 | + missing.len(), | ||
| 921 | + missing.join("\n") | ||
| 922 | + ); | ||
| 923 | + assert!( | ||
| 924 | + wrongly_declared.is_empty(), | ||
| 925 | + "{} non-JSON operation(s) declare a `422` they never return β a malformed \ | ||
| 926 | + multipart body is rejected with `400`:\n{}", | ||
| 927 | + wrongly_declared.len(), | ||
| 928 | + wrongly_declared.join("\n") | ||
| 929 | + ); | ||
| 930 | +} | ||
| 931 | + | ||
| 865 | #[tokio::test] | 932 | #[tokio::test] |
| 866 | async fn every_page_limit_param_matches_its_constant() { | 933 | async fn every_page_limit_param_matches_its_constant() { |
| 867 | // `#[param(maximum = 500)]` is written out beside MAX_PAGE_LIMIT, and | 934 | // `#[param(maximum = 500)]` is written out beside MAX_PAGE_LIMIT, and |