forge
Explore
Log in

Don't you dare go Hollow

🪢 guard writes in the database, not the process

Browse files at this commit

6c87ecad6de69b1f38d7a3696d447e33e52cd1a0Ahmet Kaan GümüşParent: 0787b14
  • fix
    • 🪢 guard writes in the database, not the process
Show full message
fix: 🪢 guard writes in the database, not the process

Two replicas are live; every process-local lock silently stopped
meaning anything. Move the invariants into the writes themselves:

- count caps (enroll/register/files/threads) become a counter column
  claimed by UPDATE .. WHERE n < cap (domain/cap.rs), backfilled once,
  decremented in the same transaction as every child delete
- exam freeze, re-draft and grade gates ride inside the write's own
  transaction (IF .. THROW); SESSION/WORK_ENTRY/EVENT locks die, range
  checks fold into the UPDATE's WHERE (FieldUpdate::ordered)
- appointment decisions CAS on status+proposed window+decided_by;
  bank/exam updates CAS on their editable columns
- rate limiter syncs local windows to a shared minute row every 2s,
  fail-open when the database is down
- paged GETs run LIMIT/START in the database (domain/page.rs); sites
  that post-filter in Rust stay web-sliced and say so
- exams.rs (3629 lines) splits into web/exams/{mod,attempts,questions,
  images,review}; image uploads single-source in web/image.rs; the
  bare-seq key rule lives once in domain/key.rs; migration SQL moves
  to migration_sql.rs

Every new guard is mutation-proven (removing it fails a named test).
Migration adds counter columns + rate_limit table; backfill is
one-time, guarded by = NONE, and verified against the live volume.

Traps recorded: SurrealQL 'x ?? 0 > 0' parses as 'x ?? (0 > 0)'; the
embedded mem engine drops one of two concurrent writes yet answers Ok.

78 changed files +7515 -5379

README.mdmodified+21 -3
@@ -390,6 +390,15 @@ student's budget on another's. `0` disables it like the other two. It is
390 charged before anything is written, so a `429` leaves no trace (see390 charged before anything is written, so a `429` leaves no trace (see
391 "Chatbot").391 "Chatbot").
392 392
393+All three tiers are **fleet-wide, not per replica**. Admission stays in memory
394+(no request ever waits on the database to be let in), and a background task in
395+each replica folds its new admits into one shared `rate_limit` row per tier +
396+client + minute every 2 seconds, then caps itself by the total that comes back.
397+Two replicas therefore enforce one budget, with one caveat: within a single
398+2-second interval a client that reaches both can spend up to the tier's budget
399+on each before the shared total tightens them. If the database is down the
400+tiers simply fall back to their own local budgets — nobody is refused for it.
401+
393 Behind a reverse proxy every connection carries the proxy's address, so also402 Behind a reverse proxy every connection carries the proxy's address, so also
394 set `TRUST_PROXY=true` to key clients by the rightmost `X-Forwarded-For` entry403 set `TRUST_PROXY=true` to key clients by the rightmost `X-Forwarded-For` entry
395 (the one the proxy itself appends). Leave it off when clients reach the server404 (the one the proxy itself appends). Leave it off when clients reach the server
@@ -666,7 +675,7 @@ window filtering, before paging; negative values are a `400` naming the field.
666 | GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) · paged |675 | GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) · paged |
667 | GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) · paged · `?starts_after=&ends_after=` window (soonest first) |676 | GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) · paged · `?starts_after=&ends_after=` window (soonest first) |
668 | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |677 | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |
669-| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `mode` frozen once attempted, re-drafting frozen once attempts/results exist — the rest stays live) |678+| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `mode` frozen once attempted, re-drafting frozen once attempts/results exist — the rest stays live; concurrent edits merge, never silently revert each other) |
670 | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |679 | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |
671 | POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled student** (upsert; course manager; students only; drafts can't be graded, `409`) |680 | POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled student** (upsert; course manager; students only; drafts can't be graded, `409`) |
672 | GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) · paged |681 | GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) · paged |
@@ -709,7 +718,7 @@ window filtering, before paging; negative values are a `400` naming the field.
709 | GET | `/bank-questions` | teacher | The school-wide question bank — `?subject=<id>` filters by origin subject, `?owner=<id>` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) · paged |718 | GET | `/bank-questions` | teacher | The school-wide question bank — `?subject=<id>` filters by origin subject, `?owner=<id>` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) · paged |
710 | POST | `/bank-questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` — save a reusable question template into the bank (owner = caller; `subject_id` is origin metadata, but must exist — `400` otherwise) |719 | POST | `/bank-questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` — save a reusable question template into the bank (owner = caller; `subject_id` is origin metadata, but must exist — `400` otherwise) |
711 | GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) |720 | GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) |
712-| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question — the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze) |721+| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question — the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze; concurrent edits merge, never silently revert each other) |
713 | DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) |722 | DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) |
714 | POST | `/bank-questions/{bid}/image` | teacher | Attach/replace the bank question's illustration: `multipart/form-data`, one `file` part — raster images only (`png`/`jpeg`/`webp`/`gif`), ≤ `max_file_bytes` (**owner only**, admin bypass) |723 | POST | `/bank-questions/{bid}/image` | teacher | Attach/replace the bank question's illustration: `multipart/form-data`, one `file` part — raster images only (`png`/`jpeg`/`webp`/`gif`), ≤ `max_file_bytes` (**owner only**, admin bypass) |
715 | GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) |724 | GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) |
@@ -2276,6 +2285,8 @@ src/
2276 validate.rs field validators (used by every newtype's try_new)2285 validate.rs field validators (used by every newtype's try_new)
2277 error.rs ValidationError + AppError -> HTTP responses2286 error.rs ValidationError + AppError -> HTTP responses
2278 database.rs SurrealDB server connect (ws) + SCHEMAFULL migration2287 database.rs SurrealDB server connect (ws) + SCHEMAFULL migration
2288+ migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR,
2289+ MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them
2279 rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier2290 rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier
2280 state.rs AppState { db, files_path, cookie_secure, rate_limit, ai }2291 state.rs AppState { db, files_path, cookie_secure, rate_limit, ai }
2281 ai/ QUIC bridge to the out-of-process AI services2292 ai/ QUIC bridge to the out-of-process AI services
@@ -2294,6 +2305,12 @@ src/
2294 PATCH actually carried (an omitted field is never written)2305 PATCH actually carried (an omitted field is never written)
2295 monotonic_id.rs next_ulid: ids that sort in write order — one process-wide2306 monotonic_id.rs next_ulid: ids that sort in write order — one process-wide
2296 Generator, so same-millisecond rows never scramble2307 Generator, so same-millisecond rows never scramble
2308+ key.rs sitting(): the deterministic per-sitting record key shared by
2309+ attempts, answers, answer images and results (seq 1 stays bare)
2310+ cap.rs claim()/release(): the cross-replica count caps — an atomic
2311+ `UPDATE parent SET n += 1 WHERE n < cap` on a counter column
2312+ of the parent row, replacing the per-process mutexes that
2313+ only held while one instance owned the database
2297 text_fold.rs case- and diacritic-insensitive folding for search, shared by2314 text_fold.rs case- and diacritic-insensitive folding for search, shared by
2298 the Rust needle and the SurrealQL column (Turkish İ/ı, ü, ö…)2315 the Rust needle and the SurrealQL column (Turkish İ/ı, ü, ö…)
2299 session.rs SessionId · SessionToken · Session (7-day expiry)2316 session.rs SessionId · SessionToken · Session (7-day expiry)
@@ -2393,7 +2410,8 @@ src/
2393 2410
2394 Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory2411 Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory
2395 db), rate-limit (both tiers, proxy-header and peer-address keying, shipped2412 db), rate-limit (both tiers, proxy-header and peer-address keying, shipped
2396-limits over every route), e2e (real TCP + reqwest cookie jar), persistence2413+limits over every route, two "replicas" sharing one budget over one db), e2e
2414+(real TCP + reqwest cookie jar), persistence
2397 (tempfile file engine, including close + reopen), ai-bridge (real QUIC on2415 (tempfile file engine, including close + reopen), ai-bridge (real QUIC on
2398 loopback against a fake AI service), ai-protocol (the `hab/1` wire contract,2416 loopback against a fake AI service), ai-protocol (the `hab/1` wire contract,
2399 driven by a client that shares no code with the backend).2417 driven by a client that shares no code with the backend).
src/constant.rsmodified+51 -730
@@ -131,9 +131,12 @@ pub const MAX_SETTINGS_ITEM_LEN: usize = 50;
131 pub const MAX_GRADE_BANDS: usize = 20;131 pub const MAX_GRADE_BANDS: usize = 20;
132 pub const MAX_GRADE_LABEL_LEN: usize = 20;132 pub const MAX_GRADE_LABEL_LEN: usize = 20;
133 133
134-/// How many times `PATCH /settings` re-merges and retries when a concurrent134+/// How many times a read-then-compare-and-set path (`PATCH /settings`, `PATCH
135-/// edit lands between its snapshot and its compare-and-set save.135+/// /bank/{bid}`, every appointment decision) re-reads and retries when a
136-pub const SETTINGS_UPDATE_RETRIES: usize = 3;136+/// concurrent edit lands between its snapshot and its save. A miss normally
137+/// re-validates into a `409`, so this only covers a write racing a legal
138+/// transition.
139+pub const CAS_UPDATE_RETRIES: usize = 3;
137 140
138 pub const MAX_TERM_NAME_LEN: usize = 100;141 pub const MAX_TERM_NAME_LEN: usize = 100;
139 142
@@ -574,6 +577,27 @@ pub const DEFAULT_CHATBOT_RATE_LIMIT: u32 = 20;
574 /// swept out on the next check. Keeps memory bounded without a reaper task.577 /// swept out on the next check. Keeps memory bounded without a reaper task.
575 pub const PURGE_AT: usize = 10_000;578 pub const PURGE_AT: usize = 10_000;
576 579
580+/// The shared counter every replica folds its local admits into, so N replicas
581+/// enforce one budget instead of N (see [`crate::rate_limit`]).
582+pub const RATE_LIMIT_TABLE: &str = "rate_limit";
583+
584+/// How often a limiter pushes its admits and reads the fleet's total back.
585+/// The knob that decides the worst case: within one interval a replica can
586+/// admit up to its full local budget before the shared total tightens it, so
587+/// short enough to matter and long enough to stay one query per tier per tick.
588+pub const RATE_SYNC_INTERVAL_SECS: u64 = 2;
589+
590+/// How long one sync round may wait on the database. The SDK *parks* a query
591+/// while the socket is down instead of failing it, so the liveness flag alone
592+/// cannot stop a round wedging the task forever — this is the backstop that
593+/// keeps the limiter purely local through an outage instead of stalled.
594+pub const RATE_SYNC_TIMEOUT_SECS: u64 = 5;
595+
596+/// How many client buckets one round syncs. A round is a single query holding
597+/// one statement per bucket, so this bounds both its size and the write volume
598+/// a burst of distinct clients can put on the database.
599+pub const RATE_SYNC_MAX_KEYS: usize = 512;
600+
577 // --- time spans --------------------------------------------------------601 // --- time spans --------------------------------------------------------
578 602
579 pub const MILLIS_PER_DAY: i64 = 24 * 60 * 60 * 1000;603 pub const MILLIS_PER_DAY: i64 = 24 * 60 * 60 * 1000;
@@ -719,6 +743,30 @@ pub const MEAL_BOOKING_TABLE: &str = "meal_booking";
719 pub const MEAL_ATTENDANCE_TABLE: &str = "meal_attendance";743 pub const MEAL_ATTENDANCE_TABLE: &str = "meal_attendance";
720 pub const MEAL_LEDGER_TABLE: &str = "meal_ledger";744 pub const MEAL_LEDGER_TABLE: &str = "meal_ledger";
721 745
746+// --- cross-replica cap counters ----------------------------------------
747+
748+/// The counter columns behind the count caps (see [`crate::domain::cap`]).
749+/// Each one lives on the *parent* row, because a single-record conditional
750+/// `UPDATE` is the only guard that holds when the writers are in different
751+/// processes. Spelled here rather than at the call site so the field a claim
752+/// increments and the field a delete decrements cannot drift apart; the
753+/// definitions themselves are in `MIGRATION`, and a typo there is caught by
754+/// SCHEMAFULL refusing the write.
755+pub const ENROLLMENT_COUNT_FIELD: &str = "enrollment_count";
756+pub const REGISTRATION_COUNT_FIELD: &str = "registration_count";
757+pub const NOTE_FILE_COUNT_FIELD: &str = "file_count";
758+pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count";
759+pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count";
760+
761+/// How hard a counter write tries before giving up, and the first backoff step
762+/// it sleeps between attempts (doubling, plus jitter). Contention on one record
763+/// is the guard working as designed, and SurrealDB answers it by aborting the
764+/// loser's transaction — so these two numbers are what turn "retry the
765+/// transaction" into a queue. Sized for one HTTP burst of racers on a single
766+/// parent: seven doublings from 2ms is a quarter of a second of patience.
767+pub const CAP_WRITE_TRIES: usize = 8;
768+pub const CAP_WRITE_BACKOFF_MS: u64 = 2;
769+
722 // --- boot leader election ----------------------------------------------770 // --- boot leader election ----------------------------------------------
723 771
724 /// The lock row every booting process races for (see772 /// The lock row every booting process races for (see
@@ -799,730 +847,3 @@ pub const MIGRATION_LOCK_HEARTBEAT_SECS: u64 = 5;
799 /// serving on a schema nobody confirmed — is worse.847 /// serving on a schema nobody confirmed — is worse.
800 pub const MIGRATION_LOCK_WAIT_SECS: u64 = 180;848 pub const MIGRATION_LOCK_WAIT_SECS: u64 = 180;
801 pub const MIGRATION_LOCK_POLL_MS: u64 = 200;849 pub const MIGRATION_LOCK_POLL_MS: u64 = 200;
802-
803-// --- schema migration SQL ----------------------------------------------
804-
805-/// Repairs that must run *before* the DDL batch, because the DDL is what makes
806-/// them impossible.
807-///
808-/// `MIGRATION` retires `exam_question.source_bank` with `REMOVE FIELD`, and
809-/// once the column is gone SCHEMAFULL rejects every write to a row that still
810-/// stores it ("Found field 'source_bank', but no such field exists") — an
811-/// UNSET included. So the value has to go while its definition is still
812-/// standing. Runs as its own query for the usual reason (see `MIGRATION`).
813-///
814-/// The table-exists guard is load-bearing: on a fresh database `MIGRATION` has
815-/// not run yet, and an UPDATE against an undefined table is an error, not an
816-/// empty result. On a database that has the table but never had the column the
817-/// `WHERE` simply matches nothing.
818-pub const PRE_REPAIR: &str = "
819- IF 'exam_question' IN object::keys((INFO FOR DB).tables) {
820- UPDATE exam_question UNSET source_bank WHERE source_bank != NONE
821- };
822-";
823-
824-/// SCHEMAFULL schema: every column is typed, references use `record<..>`.
825-/// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the
826-/// definitions and `REMOVE ... IF EXISTS` retires schema (like the
827-/// single-attempt unique index) exactly once. DDL only — data backfills live
828-/// in `BACKFILL`, which runs as a *separate* query: statements inside one
829-/// batch see the schema as it stood when the batch started, so an UPDATE next
830-/// to a fresh `DEFINE FIELD audience.*` writes against the old field set and
831-/// SCHEMAFULL silently strips the very keys being backfilled.
832-pub const MIGRATION: &str = "
833- DEFINE TABLE IF NOT EXISTS user SCHEMAFULL;
834- DEFINE FIELD IF NOT EXISTS username ON user TYPE string;
835- DEFINE FIELD IF NOT EXISTS password_hash ON user TYPE string;
836- DEFINE FIELD IF NOT EXISTS role ON user TYPE string DEFAULT 'student';
837- DEFINE FIELD IF NOT EXISTS name ON user TYPE option<string>;
838- DEFINE FIELD IF NOT EXISTS surname ON user TYPE option<string>;
839- DEFINE FIELD IF NOT EXISTS email ON user TYPE option<string>;
840- DEFINE FIELD IF NOT EXISTS phone ON user TYPE option<string>;
841- DEFINE FIELD IF NOT EXISTS birth_date ON user TYPE option<string>;
842- DEFINE FIELD IF NOT EXISTS theme ON user TYPE option<string>;
843- DEFINE FIELD IF NOT EXISTS language ON user TYPE option<string>;
844- DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE;
845-
846- DEFINE TABLE IF NOT EXISTS session SCHEMAFULL;
847- DEFINE FIELD IF NOT EXISTS user ON session TYPE record<user>;
848- DEFINE FIELD IF NOT EXISTS token ON session TYPE string;
849- DEFINE FIELD IF NOT EXISTS expires_at ON session TYPE int;
850- DEFINE INDEX IF NOT EXISTS session_token ON session FIELDS token UNIQUE;
851- DEFINE INDEX IF NOT EXISTS session_expires ON session FIELDS expires_at;
852-
853- DEFINE TABLE IF NOT EXISTS note SCHEMAFULL;
854- DEFINE FIELD IF NOT EXISTS user ON note TYPE record<user>;
855- DEFINE FIELD IF NOT EXISTS title ON note TYPE string;
856- DEFINE FIELD IF NOT EXISTS content ON note TYPE string;
857- DEFINE INDEX IF NOT EXISTS note_user ON note FIELDS user;
858-
859- DEFINE TABLE IF NOT EXISTS message SCHEMAFULL;
860- DEFINE FIELD IF NOT EXISTS sender ON message TYPE record<user>;
861- DEFINE FIELD IF NOT EXISTS recipient ON message TYPE record<user>;
862- DEFINE FIELD IF NOT EXISTS subject ON message TYPE string;
863- DEFINE FIELD IF NOT EXISTS body ON message TYPE string;
864- DEFINE FIELD IF NOT EXISTS label ON message TYPE option<string>;
865- DEFINE FIELD IF NOT EXISTS sent_at ON message TYPE int;
866- DEFINE FIELD IF NOT EXISTS read ON message TYPE bool DEFAULT false;
867- DEFINE FIELD IF NOT EXISTS sender_folder ON message TYPE string DEFAULT 'sent';
868- DEFINE FIELD IF NOT EXISTS recipient_folder ON message TYPE string DEFAULT 'inbox';
869- -- Where each side's copy sat before it was filed into archive/trash, so a
870- -- restore lands where it came from. NONE while the copy is in its home
871- -- folder — and on rows filed before this field existed (2026-07-23), which
872- -- restore to the home folder just as they always did.
873- DEFINE FIELD IF NOT EXISTS sender_origin ON message TYPE option<string>;
874- DEFINE FIELD IF NOT EXISTS recipient_origin ON message TYPE option<string>;
875- DEFINE INDEX IF NOT EXISTS message_sender ON message FIELDS sender;
876- DEFINE INDEX IF NOT EXISTS message_recipient ON message FIELDS recipient;
877-
878- DEFINE TABLE IF NOT EXISTS note_file SCHEMAFULL;
879- DEFINE FIELD IF NOT EXISTS note ON note_file TYPE record<note>;
880- DEFINE FIELD IF NOT EXISTS name ON note_file TYPE string;
881- DEFINE FIELD IF NOT EXISTS content_type ON note_file TYPE string;
882- DEFINE FIELD IF NOT EXISTS size ON note_file TYPE int;
883- DEFINE INDEX IF NOT EXISTS note_file_note ON note_file FIELDS note;
884-
885- -- Chatbot relay (2026-07-23): a `thread` groups the turns, one
886- -- `chatbot_message` is one turn. `user_id` rides on the message too so an
887- -- ownership check needs no join. An assistant turn is born `pending` and
888- -- is completed (or failed) by the task holding the AI-bridge stream —
889- -- hence the BACKFILL sweep, since that task dies with the process.
890- DEFINE TABLE IF NOT EXISTS chatbot_thread SCHEMAFULL;
891- DEFINE FIELD IF NOT EXISTS user_id ON chatbot_thread TYPE record<user> READONLY;
892- DEFINE FIELD IF NOT EXISTS title ON chatbot_thread TYPE option<string>;
893- DEFINE FIELD IF NOT EXISTS created_at ON chatbot_thread TYPE int READONLY;
894- DEFINE FIELD IF NOT EXISTS updated_at ON chatbot_thread TYPE int;
895- DEFINE INDEX IF NOT EXISTS chatbot_thread_user_updated ON chatbot_thread FIELDS user_id, updated_at;
896-
897- DEFINE TABLE IF NOT EXISTS chatbot_message SCHEMAFULL;
898- DEFINE FIELD IF NOT EXISTS thread_id ON chatbot_message TYPE record<chatbot_thread> READONLY;
899- DEFINE FIELD IF NOT EXISTS user_id ON chatbot_message TYPE record<user> READONLY;
900- DEFINE FIELD IF NOT EXISTS role ON chatbot_message TYPE string READONLY;
901- DEFINE FIELD IF NOT EXISTS content ON chatbot_message TYPE string;
902- DEFINE FIELD IF NOT EXISTS status ON chatbot_message TYPE string;
903- DEFINE FIELD IF NOT EXISTS truncated ON chatbot_message TYPE bool DEFAULT false;
904- DEFINE FIELD IF NOT EXISTS error_code ON chatbot_message TYPE option<string>;
905- DEFINE FIELD IF NOT EXISTS created_at ON chatbot_message TYPE int READONLY;
906- DEFINE FIELD IF NOT EXISTS completed_at ON chatbot_message TYPE option<int>;
907- -- The claim (2026-07-27): which replica's claim loop owes this turn an
908- -- answer, and when it said so. Absent = nobody has taken it yet; a claim
909- -- older than CHATBOT_CLAIM_RECLAIM_SECS is a dead claimer and the turn is
910- -- taken back (see `CHATBOT_CLAIM`).
911- DEFINE FIELD IF NOT EXISTS claimed_by ON chatbot_message TYPE option<string>;
912- DEFINE FIELD IF NOT EXISTS claimed_at ON chatbot_message TYPE option<int>;
913- DEFINE INDEX IF NOT EXISTS chatbot_message_thread_created ON chatbot_message FIELDS thread_id, created_at;
914- DEFINE INDEX IF NOT EXISTS chatbot_message_user ON chatbot_message FIELDS user_id;
915- -- The claim loop's sweep: every poll asks for pending rows by age.
916- DEFINE INDEX IF NOT EXISTS chatbot_message_status_created ON chatbot_message FIELDS status, created_at;
917-
918- -- Which AI workers are connected to *any* replica (2026-07-27). The GATE
919- -- and nothing else: a row only says a socket existed somewhere at
920- -- `seen_at`, so it may spare a user a 503 but must never pick who answers
921- -- — that is the in-process registry's call. Heartbeated by the replica
922- -- owning the connection; a stale row is ignored by the read and swept.
923- DEFINE TABLE IF NOT EXISTS ai_worker SCHEMAFULL;
924- DEFINE FIELD IF NOT EXISTS service ON ai_worker TYPE string;
925- DEFINE FIELD IF NOT EXISTS capabilities ON ai_worker TYPE array<string>;
926- DEFINE FIELD IF NOT EXISTS seen_at ON ai_worker TYPE int;
927-
928- DEFINE TABLE IF NOT EXISTS event SCHEMAFULL;
929- DEFINE FIELD IF NOT EXISTS creator ON event TYPE record<user>;
930- DEFINE FIELD IF NOT EXISTS title ON event TYPE string;
931- DEFINE FIELD IF NOT EXISTS description ON event TYPE string;
932- DEFINE FIELD IF NOT EXISTS audience ON event TYPE object;
933- DEFINE FIELD IF NOT EXISTS audience.kind ON event TYPE string;
934- DEFINE FIELD IF NOT EXISTS audience.role ON event TYPE option<string>;
935- DEFINE FIELD IF NOT EXISTS audience.course ON event TYPE option<record<course>>;
936- DEFINE FIELD IF NOT EXISTS audience.capacity ON event TYPE option<int>;
937- REMOVE FIELD IF EXISTS audience.users ON TABLE event;
938- DEFINE FIELD IF NOT EXISTS starts_at ON event TYPE option<int>;
939- DEFINE FIELD IF NOT EXISTS ends_at ON event TYPE option<int>;
940-
941- DEFINE TABLE IF NOT EXISTS attendance SCHEMAFULL;
942- DEFINE FIELD IF NOT EXISTS event ON attendance TYPE record<event>;
943- DEFINE FIELD IF NOT EXISTS user ON attendance TYPE record<user>;
944- DEFINE FIELD IF NOT EXISTS status ON attendance TYPE string;
945- DEFINE FIELD IF NOT EXISTS marked_by ON attendance TYPE record<user>;
946- DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE;
947- DEFINE INDEX IF NOT EXISTS attendance_user ON attendance FIELDS user;
948-
949- DEFINE TABLE IF NOT EXISTS registration SCHEMAFULL;
950- DEFINE FIELD IF NOT EXISTS event ON registration TYPE record<event>;
951- DEFINE FIELD IF NOT EXISTS user ON registration TYPE record<user>;
952- DEFINE FIELD IF NOT EXISTS registered_by ON registration TYPE record<user>;
953- DEFINE INDEX IF NOT EXISTS registration_event_user ON registration FIELDS event, user UNIQUE;
954- DEFINE INDEX IF NOT EXISTS registration_event ON registration FIELDS event;
955-
956- DEFINE TABLE IF NOT EXISTS term SCHEMAFULL;
957- DEFINE FIELD IF NOT EXISTS name ON term TYPE string;
958- DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int;
959- DEFINE FIELD IF NOT EXISTS ends_at ON term TYPE int;
960-
961- DEFINE TABLE IF NOT EXISTS course SCHEMAFULL;
962- DEFINE FIELD IF NOT EXISTS creator ON course TYPE record<user>;
963- DEFINE FIELD IF NOT EXISTS teachers ON course TYPE array<record<user>> DEFAULT [];
964- DEFINE FIELD IF NOT EXISTS teachers[*] ON course TYPE record<user>;
965- DEFINE FIELD IF NOT EXISTS title ON course TYPE string;
966- DEFINE FIELD IF NOT EXISTS description ON course TYPE string;
967- DEFINE FIELD IF NOT EXISTS kind ON course TYPE string DEFAULT 'course';
968- DEFINE FIELD IF NOT EXISTS term ON course TYPE option<record<term>>;
969- DEFINE FIELD IF NOT EXISTS capacity ON course TYPE option<int>;
970-
971- DEFINE TABLE IF NOT EXISTS subject SCHEMAFULL;
972- DEFINE FIELD IF NOT EXISTS course ON subject TYPE record<course>;
973- DEFINE FIELD IF NOT EXISTS name ON subject TYPE string;
974- DEFINE FIELD IF NOT EXISTS description ON subject TYPE string;
975- DEFINE INDEX IF NOT EXISTS subject_course ON subject FIELDS course;
976-
977- DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL;
978- DEFINE FIELD IF NOT EXISTS course ON enrollment TYPE record<course>;
979- DEFINE FIELD IF NOT EXISTS user ON enrollment TYPE record<user>;
980- DEFINE FIELD IF NOT EXISTS enrolled_by ON enrollment TYPE record<user>;
981- DEFINE INDEX IF NOT EXISTS enrollment_course_user ON enrollment FIELDS course, user UNIQUE;
982- DEFINE INDEX IF NOT EXISTS enrollment_user ON enrollment FIELDS user;
983-
984- DEFINE TABLE IF NOT EXISTS parent_link SCHEMAFULL;
985- DEFINE FIELD IF NOT EXISTS parent ON parent_link TYPE record<user>;
986- DEFINE FIELD IF NOT EXISTS student ON parent_link TYPE record<user>;
987- DEFINE FIELD IF NOT EXISTS linked_by ON parent_link TYPE record<user>;
988- DEFINE INDEX IF NOT EXISTS parent_link_parent_student ON parent_link FIELDS parent, student UNIQUE;
989- DEFINE INDEX IF NOT EXISTS parent_link_parent ON parent_link FIELDS parent;
990- DEFINE INDEX IF NOT EXISTS parent_link_student ON parent_link FIELDS student;
991-
992- DEFINE TABLE IF NOT EXISTS course_session SCHEMAFULL;
993- DEFINE FIELD IF NOT EXISTS course ON course_session TYPE record<course>;
994- DEFINE FIELD IF NOT EXISTS teacher ON course_session TYPE record<user>;
995- DEFINE FIELD IF NOT EXISTS topic ON course_session TYPE string;
996- DEFINE FIELD IF NOT EXISTS starts_at ON course_session TYPE int;
997- DEFINE FIELD IF NOT EXISTS ends_at ON course_session TYPE option<int>;
998- DEFINE INDEX IF NOT EXISTS course_session_course ON course_session FIELDS course;
999-
1000- DEFINE TABLE IF NOT EXISTS session_attendance SCHEMAFULL;
1001- DEFINE FIELD IF NOT EXISTS session ON session_attendance TYPE record<course_session>;
1002- DEFINE FIELD IF NOT EXISTS course ON session_attendance TYPE record<course>;
1003- DEFINE FIELD IF NOT EXISTS user ON session_attendance TYPE record<user>;
1004- DEFINE FIELD IF NOT EXISTS status ON session_attendance TYPE string;
1005- DEFINE FIELD IF NOT EXISTS marked_by ON session_attendance TYPE record<user>;
1006- DEFINE INDEX IF NOT EXISTS session_attendance_session_user ON session_attendance FIELDS session, user UNIQUE;
1007- DEFINE INDEX IF NOT EXISTS session_attendance_session ON session_attendance FIELDS session;
1008- DEFINE INDEX IF NOT EXISTS session_attendance_user ON session_attendance FIELDS user;
1009- DEFINE INDEX IF NOT EXISTS session_attendance_course ON session_attendance FIELDS course;
1010-
1011- DEFINE TABLE IF NOT EXISTS work_entry SCHEMAFULL;
1012- DEFINE FIELD IF NOT EXISTS user ON work_entry TYPE record<user>;
1013- DEFINE FIELD IF NOT EXISTS check_in ON work_entry TYPE int;
1014- DEFINE FIELD IF NOT EXISTS check_out ON work_entry TYPE option<int>;
1015- DEFINE INDEX IF NOT EXISTS work_entry_user ON work_entry FIELDS user;
1016-
1017- DEFINE TABLE IF NOT EXISTS pomodoro_session SCHEMAFULL;
1018- DEFINE FIELD IF NOT EXISTS user ON pomodoro_session TYPE record<user>;
1019- DEFINE FIELD IF NOT EXISTS started_at ON pomodoro_session TYPE int;
1020- DEFINE FIELD IF NOT EXISTS finished_at ON pomodoro_session TYPE option<int>;
1021- DEFINE INDEX IF NOT EXISTS pomodoro_session_user ON pomodoro_session FIELDS user;
1022-
1023- DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL;
1024- DEFINE FIELD IF NOT EXISTS creator ON exam TYPE record<user>;
1025- DEFINE FIELD IF NOT EXISTS course ON exam TYPE record<course>;
1026- DEFINE FIELD IF NOT EXISTS title ON exam TYPE string;
1027- DEFINE FIELD IF NOT EXISTS description ON exam TYPE string;
1028- DEFINE FIELD IF NOT EXISTS kind ON exam TYPE string;
1029- DEFINE FIELD IF NOT EXISTS mode ON exam TYPE option<string>;
1030- DEFINE FIELD IF NOT EXISTS starts_at ON exam TYPE option<int>;
1031- DEFINE FIELD IF NOT EXISTS ends_at ON exam TYPE option<int>;
1032- DEFINE FIELD IF NOT EXISTS duration_ms ON exam TYPE option<int>;
1033- DEFINE FIELD IF NOT EXISTS max_attempts ON exam TYPE int DEFAULT 1;
1034- DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true;
1035- DEFINE FIELD IF NOT EXISTS allow_review ON exam TYPE bool DEFAULT false;
1036- DEFINE FIELD IF NOT EXISTS draft ON exam TYPE bool DEFAULT false;
1037- DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course;
1038-
1039- DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL;
1040- DEFINE FIELD IF NOT EXISTS exam ON exam_attempt TYPE record<exam>;
1041- DEFINE FIELD IF NOT EXISTS user ON exam_attempt TYPE record<user>;
1042- DEFINE FIELD IF NOT EXISTS seq ON exam_attempt TYPE int DEFAULT 1;
1043- DEFINE FIELD IF NOT EXISTS started_at ON exam_attempt TYPE int;
1044- DEFINE FIELD IF NOT EXISTS finished_at ON exam_attempt TYPE option<int>;
1045- DEFINE FIELD IF NOT EXISTS left_at ON exam_attempt TYPE option<int>;
1046- DEFINE INDEX IF NOT EXISTS exam_attempt_exam_user_seq ON exam_attempt FIELDS exam, user, seq UNIQUE;
1047- DEFINE INDEX IF NOT EXISTS exam_attempt_exam ON exam_attempt FIELDS exam;
1048-
1049- DEFINE TABLE IF NOT EXISTS exam_question SCHEMAFULL;
1050- DEFINE FIELD IF NOT EXISTS exam ON exam_question TYPE record<exam>;
1051- DEFINE FIELD IF NOT EXISTS text ON exam_question TYPE string;
1052- DEFINE FIELD IF NOT EXISTS kind ON exam_question TYPE string;
1053- DEFINE FIELD IF NOT EXISTS points ON exam_question TYPE int;
1054- -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices
1055- -- gained stable ids (`array<string>`/`int` -> `array<object>`/`string`),
1056- -- and IF NOT EXISTS would leave an existing database on the old types.
1057- DEFINE FIELD OVERWRITE choices ON exam_question TYPE option<array<object>>;
1058- -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice
1059- -- object's own fields are declared too (same shape as `settings.exam_kinds`).
1060- DEFINE FIELD OVERWRITE choices.*.id ON exam_question TYPE string;
1061- DEFINE FIELD OVERWRITE choices.*.text ON exam_question TYPE string;
1062- DEFINE FIELD OVERWRITE correct ON exam_question TYPE option<string>;
1063- DEFINE FIELD IF NOT EXISTS subject ON exam_question TYPE record<subject>;
1064- -- Provenance, one column per direction: `from_bank` is the template this
1065- -- question was inserted from, `banked_as` the template most recently minted
1066- -- by saving it into the bank. They replace the single `source_bank`, which
1067- -- both directions wrote — so a question inserted from the bank read as
1068- -- already-saved. OVERWRITE (not IF NOT EXISTS): the old column has to
1069- -- actually go on an existing database, or SCHEMAFULL keeps accepting it
1070- -- while the struct no longer writes it.
1071- DEFINE FIELD OVERWRITE from_bank ON exam_question TYPE option<record<bank_question>>;
1072- DEFINE FIELD OVERWRITE banked_as ON exam_question TYPE option<record<bank_question>>;
1073- REMOVE FIELD IF EXISTS source_bank ON TABLE exam_question;
1074- DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam;
1075- DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject;
1076-
1077- DEFINE TABLE IF NOT EXISTS question_image SCHEMAFULL;
1078- DEFINE FIELD IF NOT EXISTS exam ON question_image TYPE record<exam>;
1079- DEFINE FIELD IF NOT EXISTS question ON question_image TYPE record<exam_question>;
1080- -- OVERWRITE: `slot` is now the choice's id, not its position.
1081- DEFINE FIELD OVERWRITE slot ON question_image TYPE option<string>;
1082- DEFINE FIELD IF NOT EXISTS file ON question_image TYPE string;
1083- DEFINE FIELD IF NOT EXISTS content_type ON question_image TYPE string;
1084- DEFINE FIELD IF NOT EXISTS size ON question_image TYPE int;
1085- DEFINE INDEX IF NOT EXISTS question_image_exam ON question_image FIELDS exam;
1086- DEFINE INDEX IF NOT EXISTS question_image_question ON question_image FIELDS question;
1087-
1088- DEFINE TABLE IF NOT EXISTS bank_question SCHEMAFULL;
1089- DEFINE FIELD IF NOT EXISTS owner ON bank_question TYPE record<user>;
1090- -- OVERWRITE, not IF NOT EXISTS: the field started life as a required
1091- -- `record<subject>` and has to actually change type on an existing database,
1092- -- otherwise the subject-delete cascade (`SET subject = NONE`) is rejected.
1093- DEFINE FIELD OVERWRITE subject ON bank_question TYPE option<record<subject>>;
1094- DEFINE FIELD IF NOT EXISTS text ON bank_question TYPE string;
1095- DEFINE FIELD IF NOT EXISTS kind ON bank_question TYPE string;
1096- DEFINE FIELD IF NOT EXISTS points ON bank_question TYPE int;
1097- -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices
1098- -- gained stable ids (`array<string>`/`int` -> `array<object>`/`string`),
1099- -- and IF NOT EXISTS would leave an existing database on the old types.
1100- DEFINE FIELD OVERWRITE choices ON bank_question TYPE option<array<object>>;
1101- -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice
1102- -- object's own fields are declared too (same shape as `settings.exam_kinds`).
1103- DEFINE FIELD OVERWRITE choices.*.id ON bank_question TYPE string;
1104- DEFINE FIELD OVERWRITE choices.*.text ON bank_question TYPE string;
1105- DEFINE FIELD OVERWRITE correct ON bank_question TYPE option<string>;
1106- DEFINE FIELD IF NOT EXISTS source_exam ON bank_question TYPE option<record<exam>>;
1107- -- 'private' | 'school'. DEFAULT so a row that predates the field (or any
1108- -- partial write) can never come out published: the answer key stays the
1109- -- owner's until they publish it.
1110- DEFINE FIELD IF NOT EXISTS visibility ON bank_question TYPE string DEFAULT 'private';
1111- DEFINE FIELD IF NOT EXISTS created_at ON bank_question TYPE int READONLY;
1112- DEFINE INDEX IF NOT EXISTS bank_question_owner ON bank_question FIELDS owner;
1113- DEFINE INDEX IF NOT EXISTS bank_question_subject ON bank_question FIELDS subject;
1114-
1115- DEFINE TABLE IF NOT EXISTS bank_question_image SCHEMAFULL;
1116- DEFINE FIELD IF NOT EXISTS bank_question ON bank_question_image TYPE record<bank_question>;
1117- -- OVERWRITE: `slot` is now the choice's id, not its position.
1118- DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option<string>;
1119- DEFINE FIELD IF NOT EXISTS file ON bank_question_image TYPE string;
1120- DEFINE FIELD IF NOT EXISTS content_type ON bank_question_image TYPE string;
1121- DEFINE FIELD IF NOT EXISTS size ON bank_question_image TYPE int;
1122- DEFINE INDEX IF NOT EXISTS bank_question_image_question ON bank_question_image FIELDS bank_question;
1123-
1124- DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL;
1125- DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record<exam>;
1126- DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record<exam_question>;
1127- DEFINE FIELD IF NOT EXISTS user ON exam_answer TYPE record<user>;
1128- -- OVERWRITE: `selected` now names the picked option by id.
1129- DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option<string>;
1130- DEFINE FIELD IF NOT EXISTS text ON exam_answer TYPE option<string>;
1131- DEFINE FIELD IF NOT EXISTS updated_at ON exam_answer TYPE int;
1132- -- `seq` numbers the sitting an answer belongs to (1, 2, …), mirroring
1133- -- exam_attempt. It rides the record key too, so a retake's answer is a new
1134- -- row, not an overwrite of the prior sitting.
1135- DEFINE FIELD IF NOT EXISTS seq ON exam_answer TYPE int DEFAULT 1;
1136- -- Retire the pre-history unique index: (question, user) is no longer unique
1137- -- once a student re-sits; (question, user, seq) is.
1138- REMOVE INDEX IF EXISTS exam_answer_question_user ON exam_answer;
1139- DEFINE INDEX IF NOT EXISTS exam_answer_question_user_seq ON exam_answer FIELDS question, user, seq UNIQUE;
1140- DEFINE INDEX IF NOT EXISTS exam_answer_exam_user ON exam_answer FIELDS exam, user;
1141- DEFINE INDEX IF NOT EXISTS exam_answer_exam ON exam_answer FIELDS exam;
1142-
1143- DEFINE TABLE IF NOT EXISTS answer_image SCHEMAFULL;
1144- DEFINE FIELD IF NOT EXISTS exam ON answer_image TYPE record<exam>;
1145- DEFINE FIELD IF NOT EXISTS question ON answer_image TYPE record<exam_question>;
1146- DEFINE FIELD IF NOT EXISTS user ON answer_image TYPE record<user>;
1147- DEFINE FIELD IF NOT EXISTS file ON answer_image TYPE string;
1148- DEFINE FIELD IF NOT EXISTS content_type ON answer_image TYPE string;
1149- DEFINE FIELD IF NOT EXISTS size ON answer_image TYPE int;
1150- -- `seq` numbers the sitting this drawing belongs to; it rides the record
1151- -- key so a retake's image never overwrites the prior sitting's.
1152- DEFINE FIELD IF NOT EXISTS seq ON answer_image TYPE int DEFAULT 1;
1153- DEFINE INDEX IF NOT EXISTS answer_image_exam ON answer_image FIELDS exam;
1154- DEFINE INDEX IF NOT EXISTS answer_image_user ON answer_image FIELDS user;
1155-
1156- DEFINE TABLE IF NOT EXISTS exam_result SCHEMAFULL;
1157- DEFINE FIELD IF NOT EXISTS exam ON exam_result TYPE record<exam>;
1158- DEFINE FIELD IF NOT EXISTS user ON exam_result TYPE record<user>;
1159- DEFINE FIELD IF NOT EXISTS mark ON exam_result TYPE int;
1160- DEFINE FIELD IF NOT EXISTS graded_by ON exam_result TYPE record<user>;
1161- -- `seq` numbers the sitting a mark belongs to; a retake earns its own mark
1162- -- row, and the latest seq is the student's standing.
1163- DEFINE FIELD IF NOT EXISTS seq ON exam_result TYPE int DEFAULT 1;
1164- REMOVE INDEX IF EXISTS exam_result_exam_user ON exam_result;
1165- DEFINE INDEX IF NOT EXISTS exam_result_exam_user_seq ON exam_result FIELDS exam, user, seq UNIQUE;
1166-
1167- DEFINE TABLE IF NOT EXISTS pool_question SCHEMAFULL;
1168- DEFINE FIELD IF NOT EXISTS asker ON pool_question TYPE record<user>;
1169- DEFINE FIELD IF NOT EXISTS title ON pool_question TYPE string;
1170- DEFINE FIELD IF NOT EXISTS body ON pool_question TYPE string;
1171- DEFINE FIELD IF NOT EXISTS status ON pool_question TYPE string DEFAULT 'pending';
1172- DEFINE FIELD IF NOT EXISTS asked_at ON pool_question TYPE int;
1173- DEFINE FIELD IF NOT EXISTS approved_by ON pool_question TYPE option<record<user>>;
1174- DEFINE FIELD IF NOT EXISTS image_file ON pool_question TYPE option<string>;
1175- DEFINE FIELD IF NOT EXISTS image_content_type ON pool_question TYPE option<string>;
1176- DEFINE FIELD IF NOT EXISTS image_size ON pool_question TYPE option<int>;
1177- DEFINE INDEX IF NOT EXISTS pool_question_status ON pool_question FIELDS status;
1178- DEFINE INDEX IF NOT EXISTS pool_question_asker ON pool_question FIELDS asker;
1179-
1180- DEFINE TABLE IF NOT EXISTS solution SCHEMAFULL;
1181- DEFINE FIELD IF NOT EXISTS question ON solution TYPE record<pool_question>;
1182- DEFINE FIELD IF NOT EXISTS author ON solution TYPE record<user>;
1183- DEFINE FIELD IF NOT EXISTS body ON solution TYPE string;
1184- DEFINE FIELD IF NOT EXISTS offered_at ON solution TYPE int;
1185- DEFINE FIELD IF NOT EXISTS image_file ON solution TYPE option<string>;
1186- DEFINE FIELD IF NOT EXISTS image_content_type ON solution TYPE option<string>;
1187- DEFINE FIELD IF NOT EXISTS image_size ON solution TYPE option<int>;
1188- DEFINE INDEX IF NOT EXISTS solution_question ON solution FIELDS question;
1189-
1190- DEFINE TABLE IF NOT EXISTS settings SCHEMAFULL;
1191- DEFINE FIELD IF NOT EXISTS exam_kinds ON settings TYPE array<object>;
1192- DEFINE FIELD IF NOT EXISTS exam_kinds.*.name ON settings TYPE string;
1193- DEFINE FIELD IF NOT EXISTS exam_kinds.*.weight ON settings TYPE int;
1194- DEFINE FIELD IF NOT EXISTS attendance_statuses ON settings TYPE array<string>;
1195- DEFINE FIELD IF NOT EXISTS grade_bands ON settings TYPE array<object>;
1196- DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int;
1197- DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string;
1198- DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option<int>;
1199- DEFINE FIELD IF NOT EXISTS chatbot_history_turns ON settings TYPE option<int>;
1200- DEFINE FIELD IF NOT EXISTS max_chatbot_threads ON settings TYPE option<int>;
1201- DEFINE FIELD IF NOT EXISTS max_chatbot_message_len ON settings TYPE option<int>;
1202- -- Food program (2026-07-26). `meal_slots` mirrors the `exam_kinds` shape —
1203- -- a named list a menu snapshots from — and `dietary_tags` mirrors
1204- -- `attendance_statuses`. `meal_cancel_cutoff_minutes` is ONE knob for both
1205- -- the booking and the cancel deadline; absent means no cutoff at all. All
1206- -- three are `option<>`, exactly like `max_file_bytes`: NOT `DEFAULT []`.
1207- -- `DEFAULT` fires on create only, and `PATCH /settings` writes the whole
1208- -- row with `UPDATE ... CONTENT`, so a required-with-default field a writer
1209- -- omits coerces to NONE and fails every settings write until the domain
1210- -- struct carries it. `option<>` also means the existing singleton reads
1211- -- fine, which is why the food program needs no BACKFILL anywhere.
1212- DEFINE FIELD IF NOT EXISTS meal_slots ON settings TYPE option<array<object>>;
1213- DEFINE FIELD IF NOT EXISTS meal_slots.*.name ON settings TYPE string;
1214- -- Minutes past midnight UTC at which the slot is served (2026-07-26).
1215- -- `option<int>` for the same reason the list itself is: slots written
1216- -- before the field existed simply have no key, and read back as NONE ->
1217- -- the booking cutoff falls back to midnight UTC, its old meaning. No
1218- -- BACKFILL, and no DEFAULT — see the note above.
1219- DEFINE FIELD IF NOT EXISTS meal_slots.*.serving_minute ON settings TYPE option<int>;
1220- DEFINE FIELD IF NOT EXISTS dietary_tags ON settings TYPE option<array<string>>;
1221- DEFINE FIELD IF NOT EXISTS meal_cancel_cutoff_minutes ON settings TYPE option<int>;
1222-
1223- -- Homework (greenfield, 2026-07-22): a teacher assigns per course, students
1224- -- submit files + optional text, a teacher grades a status + optional mark.
1225- -- `course`/`created_by`/`created_at` are READONLY (a homework never moves
1226- -- course, and stamps never rewrite); `subject` is NOT — it is re-taggable
1227- -- via PATCH. `assigned` NONE/empty means the whole course. No BACKFILL: the
1228- -- tables are new, so the whole migration stays additive and idempotent.
1229- DEFINE TABLE IF NOT EXISTS homework SCHEMAFULL;
1230- DEFINE FIELD IF NOT EXISTS course ON homework TYPE record<course> READONLY;
1231- DEFINE FIELD IF NOT EXISTS subject ON homework TYPE record<subject>;
1232- DEFINE FIELD IF NOT EXISTS title ON homework TYPE string;
1233- DEFINE FIELD IF NOT EXISTS description ON homework TYPE option<string>;
1234- DEFINE FIELD IF NOT EXISTS due_at ON homework TYPE int;
1235- DEFINE FIELD IF NOT EXISTS assigned ON homework TYPE option<array<record<user>>>;
1236- DEFINE FIELD IF NOT EXISTS assigned[*] ON homework TYPE record<user>;
1237- DEFINE FIELD IF NOT EXISTS created_by ON homework TYPE record<user> READONLY;
1238- DEFINE FIELD IF NOT EXISTS created_at ON homework TYPE int READONLY;
1239- DEFINE INDEX IF NOT EXISTS homework_course ON homework FIELDS course;
1240-
1241- DEFINE TABLE IF NOT EXISTS homework_submission SCHEMAFULL;
1242- DEFINE FIELD IF NOT EXISTS homework ON homework_submission TYPE record<homework> READONLY;
1243- DEFINE FIELD IF NOT EXISTS user ON homework_submission TYPE record<user> READONLY;
1244- DEFINE FIELD IF NOT EXISTS text ON homework_submission TYPE option<string>;
1245- DEFINE FIELD IF NOT EXISTS submitted_at ON homework_submission TYPE int READONLY;
1246- DEFINE FIELD IF NOT EXISTS updated_at ON homework_submission TYPE int;
1247- DEFINE INDEX IF NOT EXISTS homework_submission_homework ON homework_submission FIELDS homework;
1248-
1249- DEFINE TABLE IF NOT EXISTS homework_file SCHEMAFULL;
1250- DEFINE FIELD IF NOT EXISTS submission ON homework_file TYPE record<homework_submission> READONLY;
1251- DEFINE FIELD IF NOT EXISTS name ON homework_file TYPE string;
1252- DEFINE FIELD IF NOT EXISTS content_type ON homework_file TYPE string;
1253- DEFINE FIELD IF NOT EXISTS size ON homework_file TYPE int;
1254- DEFINE FIELD IF NOT EXISTS file ON homework_file TYPE string READONLY;
1255- DEFINE FIELD IF NOT EXISTS created_at ON homework_file TYPE int READONLY;
1256- DEFINE INDEX IF NOT EXISTS homework_file_submission ON homework_file FIELDS submission;
1257-
1258- DEFINE TABLE IF NOT EXISTS homework_result SCHEMAFULL;
1259- DEFINE FIELD IF NOT EXISTS homework ON homework_result TYPE record<homework> READONLY;
1260- DEFINE FIELD IF NOT EXISTS user ON homework_result TYPE record<user> READONLY;
1261- DEFINE FIELD IF NOT EXISTS status ON homework_result TYPE string;
1262- DEFINE FIELD IF NOT EXISTS mark ON homework_result TYPE option<int>;
1263- DEFINE FIELD IF NOT EXISTS graded_by ON homework_result TYPE record<user>;
1264- DEFINE FIELD IF NOT EXISTS created_at ON homework_result TYPE int;
1265- DEFINE INDEX IF NOT EXISTS homework_result_homework ON homework_result FIELDS homework;
1266-
1267- -- Appointments (greenfield, 2026-07-23): a teacher publishes availability
1268- -- slots, a student or parent books one. `series` groups the occurrences a
1269- -- weekly repeat expanded into, so one cancel deletes one row and a series
1270- -- delete finds the rest. A booking's live/dead state is the `status`
1271- -- string; occupancy is derived from it under the appointment lock rather
1272- -- than stored, so a rejected or cancelled booking frees its slot again.
1273- -- The `proposed_*` fields carry a teacher's counter-proposal on the same
1274- -- row until the requester accepts. No BACKFILL: both tables are new.
1275- DEFINE TABLE IF NOT EXISTS appointment_slot SCHEMAFULL;
1276- DEFINE FIELD IF NOT EXISTS teacher ON appointment_slot TYPE record<user>;
1277- DEFINE FIELD IF NOT EXISTS starts_at ON appointment_slot TYPE int;
1278- DEFINE FIELD IF NOT EXISTS ends_at ON appointment_slot TYPE int;
1279- DEFINE FIELD IF NOT EXISTS note ON appointment_slot TYPE option<string>;
1280- DEFINE FIELD IF NOT EXISTS series ON appointment_slot TYPE option<string>;
1281- DEFINE FIELD IF NOT EXISTS created_at ON appointment_slot TYPE int;
1282- DEFINE INDEX IF NOT EXISTS appointment_slot_teacher_starts ON appointment_slot FIELDS teacher, starts_at;
1283- DEFINE INDEX IF NOT EXISTS appointment_slot_series ON appointment_slot FIELDS series;
1284-
1285- DEFINE TABLE IF NOT EXISTS appointment SCHEMAFULL;
1286- DEFINE FIELD IF NOT EXISTS slot ON appointment TYPE record<appointment_slot>;
1287- DEFINE FIELD IF NOT EXISTS requester ON appointment TYPE record<user>;
1288- DEFINE FIELD IF NOT EXISTS status ON appointment TYPE string DEFAULT 'pending';
1289- DEFINE FIELD IF NOT EXISTS reason ON appointment TYPE string;
1290- DEFINE FIELD IF NOT EXISTS proposed_starts_at ON appointment TYPE option<int>;
1291- DEFINE FIELD IF NOT EXISTS proposed_ends_at ON appointment TYPE option<int>;
1292- DEFINE FIELD IF NOT EXISTS proposed_by ON appointment TYPE option<record<user>>;
1293- DEFINE FIELD IF NOT EXISTS decided_by ON appointment TYPE option<record<user>>;
1294- DEFINE FIELD IF NOT EXISTS cancelled_by ON appointment TYPE option<record<user>>;
1295- DEFINE FIELD IF NOT EXISTS cancel_reason ON appointment TYPE option<string>;
1296- DEFINE FIELD IF NOT EXISTS reject_reason ON appointment TYPE option<string>;
1297- DEFINE FIELD IF NOT EXISTS created_at ON appointment TYPE int;
1298- DEFINE INDEX IF NOT EXISTS appointment_slot_ref ON appointment FIELDS slot;
1299- DEFINE INDEX IF NOT EXISTS appointment_requester ON appointment FIELDS requester;
1300- DEFINE INDEX IF NOT EXISTS appointment_status ON appointment FIELDS status;
1301-
1302- -- Food program (greenfield, 2026-07-26): a published menu per day+slot,
1303- -- dishes on it, a dietary profile per student, bookings against a menu's
1304- -- capacity, who actually ate, and the money that moved. `date` is a
1305- -- calendar day as `YYYY-MM-DD` text, not a timestamp: the unique index is
1306- -- an equality test and a midnight-in-millis day is only unique for one
1307- -- timezone. `slot` is snapshotted text, not a link, so retiring a slot in
1308- -- settings never rewrites a past menu. Stamps stay `int` millis like the
1309- -- rest of the schema. No BACKFILL: all six tables are new.
1310- DEFINE TABLE IF NOT EXISTS menu SCHEMAFULL;
1311- DEFINE FIELD IF NOT EXISTS date ON menu TYPE string READONLY;
1312- DEFINE FIELD IF NOT EXISTS slot ON menu TYPE string READONLY;
1313- DEFINE FIELD IF NOT EXISTS capacity ON menu TYPE option<int>;
1314- DEFINE FIELD IF NOT EXISTS created_by ON menu TYPE record<user> READONLY;
1315- DEFINE FIELD IF NOT EXISTS created_at ON menu TYPE int READONLY;
1316- DEFINE INDEX IF NOT EXISTS menu_date_slot ON menu FIELDS date, slot UNIQUE;
1317-
1318- DEFINE TABLE IF NOT EXISTS menu_dish SCHEMAFULL;
1319- DEFINE FIELD IF NOT EXISTS menu ON menu_dish TYPE record<menu> READONLY;
1320- DEFINE FIELD IF NOT EXISTS name ON menu_dish TYPE string;
1321- DEFINE FIELD IF NOT EXISTS description ON menu_dish TYPE option<string>;
1322- -- Money is minor units (kuruş) as an integer, everywhere. Never decimal.
1323- DEFINE FIELD IF NOT EXISTS price_minor ON menu_dish TYPE int;
1324- DEFINE FIELD IF NOT EXISTS tags ON menu_dish TYPE array<string> DEFAULT [];
1325- DEFINE FIELD IF NOT EXISTS tags[*] ON menu_dish TYPE string;
1326- DEFINE FIELD IF NOT EXISTS created_at ON menu_dish TYPE int READONLY;
1327- DEFINE INDEX IF NOT EXISTS menu_dish_menu ON menu_dish FIELDS menu;
1328-
1329- DEFINE TABLE IF NOT EXISTS dietary_profile SCHEMAFULL;
1330- DEFINE FIELD IF NOT EXISTS student ON dietary_profile TYPE record<user> READONLY;
1331- DEFINE FIELD IF NOT EXISTS tags ON dietary_profile TYPE array<string> DEFAULT [];
1332- DEFINE FIELD IF NOT EXISTS tags[*] ON dietary_profile TYPE string;
1333- DEFINE FIELD IF NOT EXISTS note ON dietary_profile TYPE option<string>;
1334- DEFINE FIELD IF NOT EXISTS updated_by ON dietary_profile TYPE record<user>;
1335- DEFINE FIELD IF NOT EXISTS updated_at ON dietary_profile TYPE int;
1336- DEFINE INDEX IF NOT EXISTS dietary_profile_student ON dietary_profile FIELDS student UNIQUE;
1337-
1338- -- A cancel flips `status` and stamps `cancelled_at`; the row stays so the
1339- -- freed seat is still auditable against the ledger line it charged.
1340- DEFINE TABLE IF NOT EXISTS meal_booking SCHEMAFULL;
1341- DEFINE FIELD IF NOT EXISTS menu ON meal_booking TYPE record<menu> READONLY;
1342- DEFINE FIELD IF NOT EXISTS student ON meal_booking TYPE record<user> READONLY;
1343- DEFINE FIELD IF NOT EXISTS booked_by ON meal_booking TYPE record<user> READONLY;
1344- DEFINE FIELD IF NOT EXISTS status ON meal_booking TYPE string DEFAULT 'booked';
1345- -- How many times this seat has been taken, and what it cost when the
1346- -- *current* attempt took it (NONE = the menu was free then). Together they
1347- -- key the attempt's ledger lines, which is what makes billing idempotent
1348- -- by identity rather than by scanning for an outstanding charge.
1349- DEFINE FIELD IF NOT EXISTS attempt ON meal_booking TYPE int DEFAULT 1;
1350- DEFINE FIELD IF NOT EXISTS price_minor ON meal_booking TYPE option<int>;
1351- DEFINE FIELD IF NOT EXISTS cancelled_at ON meal_booking TYPE option<int>;
1352- DEFINE FIELD IF NOT EXISTS created_at ON meal_booking TYPE int READONLY;
1353- DEFINE INDEX IF NOT EXISTS meal_booking_menu ON meal_booking FIELDS menu;
1354- DEFINE INDEX IF NOT EXISTS meal_booking_student ON meal_booking FIELDS student;
1355-
1356- DEFINE TABLE IF NOT EXISTS meal_attendance SCHEMAFULL;
1357- DEFINE FIELD IF NOT EXISTS menu ON meal_attendance TYPE record<menu> READONLY;
1358- DEFINE FIELD IF NOT EXISTS student ON meal_attendance TYPE record<user> READONLY;
1359- DEFINE FIELD IF NOT EXISTS status ON meal_attendance TYPE string;
1360- DEFINE FIELD IF NOT EXISTS marked_by ON meal_attendance TYPE record<user>;
1361- DEFINE FIELD IF NOT EXISTS marked_at ON meal_attendance TYPE int;
1362- DEFINE INDEX IF NOT EXISTS meal_attendance_menu_student ON meal_attendance FIELDS menu, student UNIQUE;
1363-
1364- -- APPEND-ONLY by design: a mistake is corrected with an opposing
1365- -- `reversal` line, never by editing or deleting one. Hence every field is
1366- -- READONLY. `source` is untyped on purpose — a charge points at the
1367- -- booking that caused it, a reversal at the line it undoes.
1368- DEFINE TABLE IF NOT EXISTS meal_ledger SCHEMAFULL;
1369- DEFINE FIELD IF NOT EXISTS student ON meal_ledger TYPE record<user> READONLY;
1370- DEFINE FIELD IF NOT EXISTS kind ON meal_ledger TYPE string READONLY;
1371- DEFINE FIELD IF NOT EXISTS amount_minor ON meal_ledger TYPE int READONLY;
1372- DEFINE FIELD IF NOT EXISTS source ON meal_ledger TYPE option<record> READONLY;
1373- DEFINE FIELD IF NOT EXISTS method ON meal_ledger TYPE option<string> READONLY;
1374- DEFINE FIELD IF NOT EXISTS note ON meal_ledger TYPE option<string> READONLY;
1375- DEFINE FIELD IF NOT EXISTS recorded_by ON meal_ledger TYPE record<user> READONLY;
1376- DEFINE FIELD IF NOT EXISTS created_at ON meal_ledger TYPE int READONLY;
1377- DEFINE INDEX IF NOT EXISTS meal_ledger_student ON meal_ledger FIELDS student;
1378-";
1379-
1380-/// Data backfills for rows written by older binaries. Runs *after* (and apart
1381-/// from) the DDL batch so every statement sees the freshly defined schema —
1382-/// see the `MIGRATION` doc for why sharing the batch corrupts the writes.
1383-/// Idempotent: each backfill's `WHERE` only matches unconverted rows.
1384-pub const BACKFILL: &str = "
1385- UPDATE user SET role = 'student' WHERE role = NONE;
1386-
1387- UPDATE course SET kind = 'course' WHERE kind = NONE;
1388-
1389- -- Courses predate assignable teachers (2026-07-21): every existing course
1390- -- was run by its creator alone, so it starts with nobody else assigned.
1391- UPDATE course SET teachers = [] WHERE teachers = NONE;
1392-
1393- -- Exams predate the draft flag (2026-07-19): everything already out there
1394- -- was live for its course, so it stays published.
1395- UPDATE exam SET draft = false WHERE draft = NONE;
1396-
1397- -- Exams predate the review toggle (2026-07-24): default it closed (opt-in).
1398- UPDATE exam SET allow_review = false WHERE allow_review = NONE;
1399-
1400- UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {};
1401-
1402- -- Questions written before subjects existed (2026-07-17) are destroyed, not
1403- -- backfilled: a subject is mandatory and there is nothing truthful to
1404- -- assign. Their answers go first so no answer row outlives its question.
1405- DELETE exam_answer WHERE question IN (SELECT VALUE id FROM exam_question WHERE subject = NONE);
1406- DELETE exam_question WHERE subject = NONE;
1407-
1408- -- The hand-picked `users` audience retired into `registration` (2026-07-16):
1409- -- each listed user becomes a signup row credited to the event's creator, and
1410- -- the event becomes an uncapped registration list. Runs once — converted
1411- -- events no longer match the `kind = 'users'` filter. (`?? []`: an empty
1412- -- statement-subquery evaluates to NONE, which FOR refuses to iterate.)
1413- FOR $ev IN ((SELECT id, creator, audience FROM event WHERE audience.kind = 'users') ?? []) {
1414- FOR $usr IN ($ev.audience.users ?? []) {
1415- UPSERT type::record('registration', string::concat(record::id($ev.id), '_', record::id($usr))) CONTENT {
1416- event: $ev.id,
1417- user: $usr,
1418- registered_by: $ev.creator,
1419- };
1420- };
1421- UPDATE $ev.id SET audience = { kind: 'registration' };
1422- };
1423-
1424- -- Turns written before the clipped-answer flag existed (2026-07-23): the
1425- -- clip was silent then, so nothing can be recovered — they read as whole,
1426- -- which is what they were presented as all along.
1427- UPDATE chatbot_message SET truncated = false WHERE truncated = NONE;
1428-
1429- -- An assistant turn is answered by a claim loop in some replica's process,
1430- -- so a restart can leave its row `pending` with nobody left to complete it.
1431- -- Only rows past the stale horizon ($stale_ms, from
1432- -- `CHATBOT_PENDING_STALE_SECS`) are certainly abandoned though: a young one
1433- -- may still be being answered on the other side of the AI bridge, and a
1434- -- deploy must not shoot down a turn dispatched seconds ago. Nothing is lost
1435- -- by waiting — a reader already presents an over-age `pending` row as
1436- -- failed, and the next boot sweeps for real whatever crossed the horizon in
1437- -- the meantime.
1438- --
1439- -- Claim-aware since 2026-07-27, because the sweep is no longer school-wide
1440- -- truth: under N replicas the row may belong to a *live peer's* claim loop,
1441- -- and failing it here would shoot down another process's in-flight turn.
1442- -- So a claim restamped within the window is left alone. Both disjuncts
1443- -- matter — `claimed_by = NONE` alone would strand every row whose claimer
1444- -- died, which is the one case the sweep exists for.
1445- --
1446- -- The claim age is measured against $stale_ms rather than
1447- -- CHATBOT_CLAIM_RECLAIM_SECS only because the boot binds one horizon (see
1448- -- `database::migration_binds`); erring long is the safe direction — the
1449- -- cost is that a row claimed just before it aged out waits one more boot
1450- -- for its durable stamp, while readers have shown it failed all along.
1451- UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted',
1452- completed_at = time::unix(time::now()) * 1000
1453- WHERE status = 'pending' AND created_at < time::unix(time::now()) * 1000 - $stale_ms
1454- AND (claimed_by = NONE
1455- OR claimed_at < time::unix(time::now()) * 1000 - $stale_ms);
1456-
1457- -- Promotion out of student now deletes the user's enrollments (2026-07-18);
1458- -- this sweeps rows promoted before that fix. A deleted user reads as
1459- -- `user.role = NONE`, which is also != 'student' — those rows go too.
1460- DELETE enrollment WHERE user.role != 'student';
1461-
1462- -- Choices gained stable ids (2026-07-24): `choices` held bare strings and
1463- -- `correct`/`selected`/`slot` held the option's *position*. The DDL above
1464- -- retypes those columns, which leaves every old-shaped row readable but
1465- -- unwritable ('Expected `none | array<object>` but found `[..]`'), so this
1466- -- conversion is repair, not cosmetics.
1467- --
1468- -- Ids are minted in array order, so the id at position i *is* the id for
1469- -- old index i — that identity is what keeps a stored answer, and an option
1470- -- picture, pointing at the option the student actually saw. Hence the
1471- -- dependent rows are remapped inside the loop that mints `$new`, against
1472- -- that same array: once the ids are stored the positions are still
1473- -- recoverable, but nothing guarantees a later pass would look them up the
1474- -- same way. `WHERE choices[0] != NONE AND type::is_string(choices[0])`
1475- -- matches only unconverted rows, so a second boot re-mints nothing; an
1476- -- empty or absent `choices` needs no conversion at all. A question-level
1477- -- picture (`slot = NONE`) is not an index and is left alone.
1478- --
1479- -- Runs *before* every other backfill that writes these rows (the `seq`
1480- -- stamps below): a write coerces the whole record, so touching a row for
1481- -- any reason fails while its choices are still positional. For the same
1482- -- reason the answer's remap stamps `seq` itself — the two legacy gaps sit
1483- -- on the same row, and a write that fixes only one of them is rejected for
1484- -- the other. `seq ?? 1` leaves an already-numbered sitting alone (DEFAULT
1485- -- fills a CREATE, not an UPDATE of a row that predates the column).
1486- FOR $q IN ((SELECT id, choices, correct FROM exam_question
1487- WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) {
1488- LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c });
1489- UPDATE $q.id SET choices = $new,
1490- correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id };
1491- FOR $img IN ((SELECT id, slot FROM question_image
1492- WHERE question = $q.id AND type::is_int(slot)) ?? []) {
1493- UPDATE $img.id SET slot = $new[$img.slot].id;
1494- };
1495- FOR $ans IN ((SELECT id, selected FROM exam_answer
1496- WHERE question = $q.id AND type::is_int(selected)) ?? []) {
1497- UPDATE $ans.id SET selected = $new[$ans.selected].id, seq = seq ?? 1;
1498- };
1499- };
1500-
1501- FOR $q IN ((SELECT id, choices, correct FROM bank_question
1502- WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) {
1503- LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c });
1504- UPDATE $q.id SET choices = $new,
1505- correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id };
1506- FOR $img IN ((SELECT id, slot FROM bank_question_image
1507- WHERE bank_question = $q.id AND type::is_int(slot)) ?? []) {
1508- UPDATE $img.id SET slot = $new[$img.slot].id;
1509- };
1510- };
1511-
1512- -- Per-attempt history (2026-07-24): answers, drawings, and marks written
1513- -- before retakes stopped wiping belong to the student's first sitting.
1514- -- They already use the bare (seq==1) record key, so only the denormalized
1515- -- `seq` field needs stamping.
1516- UPDATE exam_answer SET seq = 1 WHERE seq = NONE;
1517- UPDATE answer_image SET seq = 1 WHERE seq = NONE;
1518- UPDATE exam_result SET seq = 1 WHERE seq = NONE;
1519-";
1520-
1521-/// The migration batches, in the order a boot applies them — and the *only*
1522-/// list of them. [`crate::database::migrate`] runs exactly these and
1523-/// [`crate::database::migration_fingerprint`] hashes exactly these, so a fourth
1524-/// batch cannot be executed without changing the fingerprint that decides
1525-/// whether a peer's schema is ours. They stay three separate queries: statements
1526-/// in one batch see the schema as it stood when the batch started (see
1527-/// `MIGRATION`).
1528-pub const MIGRATION_BATCHES: [&str; 3] = [PRE_REPAIR, MIGRATION, BACKFILL];
src/database.rsmodified+6 -6
@@ -7,13 +7,13 @@ use surrealdb::types::SurrealValue;
7 7
8 use crate::config::Config;8 use crate::config::Config;
9 use crate::constant::{9 use crate::constant::{
10- CHATBOT_PENDING_STALE_SECS, MIGRATION_BATCHES, MIGRATION_LOCK_CLAIM, MIGRATION_LOCK_DDL,10+ CHATBOT_PENDING_STALE_SECS, MIGRATION_LOCK_CLAIM, MIGRATION_LOCK_DDL, MIGRATION_LOCK_HEARTBEAT,
11- MIGRATION_LOCK_HEARTBEAT, MIGRATION_LOCK_HEARTBEAT_SECS, MIGRATION_LOCK_LEASE_SECS,11+ MIGRATION_LOCK_HEARTBEAT_SECS, MIGRATION_LOCK_LEASE_SECS, MIGRATION_LOCK_POLL_MS,
12- MIGRATION_LOCK_POLL_MS, MIGRATION_LOCK_STAMP, MIGRATION_LOCK_STATE, MIGRATION_LOCK_TAKEOVER,12+ MIGRATION_LOCK_STAMP, MIGRATION_LOCK_STATE, MIGRATION_LOCK_TAKEOVER, MIGRATION_LOCK_WAIT_SECS,
13- MIGRATION_LOCK_WAIT_SECS,
14 };13 };
15 use crate::domain::user::{Password, User, Username};14 use crate::domain::user::{Password, User, Username};
16 use crate::error::AppError;15 use crate::error::AppError;
16+use crate::migration_sql::MIGRATION_BATCHES;
17 17
18 /// The shared database handle.18 /// The shared database handle.
19 ///19 ///
@@ -259,7 +259,7 @@ async fn claim(db: &Database, sql: &str, me: &str, lease_ms: i64) -> Result<bool
259 /// WebSocket, where the SDK rebuilds them from the wire (`Error::from_parts`),259 /// WebSocket, where the SDK rebuilds them from the wire (`Error::from_parts`),
260 /// and a server that omitted the typed details would otherwise turn a lost race260 /// and a server that omitted the typed details would otherwise turn a lost race
261 /// into a failed boot. Widest known wordings, cheap, and belt-and-braces.261 /// into a failed boot. Widest known wordings, cheap, and belt-and-braces.
262-fn lost_the_race(err: &surrealdb::Error) -> bool {262+pub(crate) fn lost_the_race(err: &surrealdb::Error) -> bool {
263 use surrealdb::types::{ErrorDetails, QueryError};263 use surrealdb::types::{ErrorDetails, QueryError};
264 if err.is_already_exists()264 if err.is_already_exists()
265 || matches!(265 || matches!(
@@ -685,7 +685,7 @@ mod tests {
685 }685 }
686 hex::encode(hasher.finalize())686 hex::encode(hasher.finalize())
687 };687 };
688- let batches: Vec<String> = crate::constant::MIGRATION_BATCHES688+ let batches: Vec<String> = crate::migration_sql::MIGRATION_BATCHES
689 .iter()689 .iter()
690 .map(|sql| (*sql).to_string())690 .map(|sql| (*sql).to_string())
691 .collect();691 .collect();
src/domain/answer_image.rsmodified+5 -12
@@ -20,6 +20,7 @@ use crate::database::Database;
20 use crate::domain::course::CourseId;20 use crate::domain::course::CourseId;
21 use crate::domain::exam::ExamId;21 use crate::domain::exam::ExamId;
22 use crate::domain::exam_question::ExamQuestionId;22 use crate::domain::exam_question::ExamQuestionId;
23+use crate::domain::key;
23 use crate::domain::note_file::FileContentType;24 use crate::domain::note_file::FileContentType;
24 use crate::domain::user::UserId;25 use crate::domain::user::UserId;
25 use crate::error::AppError;26 use crate::error::AppError;
@@ -28,19 +29,11 @@ use crate::error::AppError;
28 pub struct AnswerImageId(RecordId);29 pub struct AnswerImageId(RecordId);
29 30
30 impl AnswerImageId {31 impl AnswerImageId {
31- /// The one id a (question, user, seq) triple can have — the same32+ /// The one id a (question, user, seq) triple can have, so "one drawing per
32- /// deterministic shape as [`crate::domain::exam_attempt::ExamAttemptId::composite`],33+ /// student per question per sitting" needs no index. See [`key::sitting`]
33- /// so "one drawing per student per question per sitting" needs no index.34+ /// for the key shape and why the first sitting stays bare.
34- /// The first sitting keeps the historical `{question}_{user}` shape (rows
35- /// written before per-attempt history existed stay addressable); later
36- /// sittings append their number. ULID keys are alphanumeric, so `_` is an
37- /// unambiguous joiner.
38 pub fn composite(question: &ExamQuestionId, user: &UserId, seq: i64) -> Self {35 pub fn composite(question: &ExamQuestionId, user: &UserId, seq: i64) -> Self {
39- let key = if seq == 1 {36+ let key = key::sitting(question.key(), user.key(), seq);
40- format!("{}_{}", question.key(), user.key())
41- } else {
42- format!("{}_{}_{}", question.key(), user.key(), seq)
43- };
44 Self(RecordId::new(ANSWER_IMAGE_TABLE, key))37 Self(RecordId::new(ANSWER_IMAGE_TABLE, key))
45 }38 }
46 39
src/domain/appointment.rsmodified+254 -87
@@ -2,8 +2,8 @@
2 //! for the meeting with a reason; the teacher approves, rejects, or2 //! for the meeting with a reason; the teacher approves, rejects, or
3 //! counter-proposes another time.3 //! counter-proposes another time.
4 //!4 //!
5-//! Two invariants live here, and both are guarded by [`APPOINTMENT_LOCK`]5+//! Two *cross-record* invariants live here, and both are guarded by
6-//! rather than by the database:6+//! [`APPOINTMENT_LOCK`] rather than by the database:
7 //!7 //!
8 //! - **One live booking per slot.** Occupancy is counted from the rows, not8 //! - **One live booking per slot.** Occupancy is counted from the rows, not
9 //! stored — so rejecting or cancelling frees the slot with nothing to reset.9 //! stored — so rejecting or cancelling frees the slot with nothing to reset.
@@ -12,8 +12,18 @@
12 //!12 //!
13 //! Both are count-then-write checks across records, which a `BEGIN…COMMIT`13 //! Both are count-then-write checks across records, which a `BEGIN…COMMIT`
14 //! does not serialize in SurrealDB (write-skew: two racing bookings each see a14 //! does not serialize in SurrealDB (write-skew: two racing bookings each see a
15-//! free slot). This backend is the database's only writer, so one process-wide15+//! free slot).
16-//! lock closes it, exactly as `REGISTER_LOCK` does for event seats.16+//!
17+//! The *single-row* invariant — a decision must be written onto the state it
18+//! was validated against — is **not** the lock's job, and never was: the lock
19+//! is process-local, so two replicas each take their own copy of it and a
20+//! whole-row save would silently drop the other's decision. That one is a
21+//! compare-and-set ([`Appointment::save_if_unchanged`]), which holds across
22+//! replicas. The lock stays for the two counts above, which no per-row
23+//! conditional write can cover.
24+// ponytail: with more than one replica those two counts are only
25+// replica-local. Closing them needs a stored occupancy counter (`domain::cap`)
26+// rather than a lock — deliberately not built here.
17 27
18 use std::sync::LazyLock;28 use std::sync::LazyLock;
19 29
@@ -21,9 +31,10 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
21 use tokio::sync::Mutex;31 use tokio::sync::Mutex;
22 use ulid::Generator;32 use ulid::Generator;
23 33
24-use crate::constant::{APPOINTMENT_TABLE, MAX_APPOINTMENT_REASON_LEN};34+use crate::constant::{APPOINTMENT_TABLE, CAS_UPDATE_RETRIES, MAX_APPOINTMENT_REASON_LEN};
25-use crate::database::Database;35+use crate::database::{Database, lost_the_race};
26 use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId};36 use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId};
37+use crate::domain::page::PagedList;
27 use crate::domain::timestamp::Timestamp;38 use crate::domain::timestamp::Timestamp;
28 use crate::domain::user::UserId;39 use crate::domain::user::UserId;
29 use crate::error::{AppError, ValidationError};40 use crate::error::{AppError, ValidationError};
@@ -34,7 +45,7 @@ use crate::validate::validate_required;
34 /// conflict-check a cross-record `count()` against a concurrent insert.45 /// conflict-check a cross-record `count()` against a concurrent insert.
35 ///46 ///
36 /// Lock order: no path ever holds this together with `ENROLL_LOCK`,47 /// Lock order: no path ever holds this together with `ENROLL_LOCK`,
37-/// `TERM_LOCK`, `REGISTER_LOCK`, `EXAM_LOCK`, or `PRESENCE_LOCK` — appointments48+/// `TERM_LOCK`, `EXAM_LOCK`, or `PRESENCE_LOCK` — appointments
38 /// touch no roster, term, event seat, or exam room, and none of those touch49 /// touch no roster, term, event seat, or exam room, and none of those touch
39 /// appointments — so they cannot deadlock. Should a future path ever need two,50 /// appointments — so they cannot deadlock. Should a future path ever need two,
40 /// take this one *last*.51 /// take this one *last*.
@@ -407,28 +418,34 @@ impl Appointment {
407 418
408 pub async fn list_for_requester(419 pub async fn list_for_requester(
409 requester: &UserId,420 requester: &UserId,
421+ limit: Option<i64>,
422+ offset: i64,
410 db: &Database,423 db: &Database,
411- ) -> Result<Vec<Appointment>, AppError> {424+ ) -> Result<(Vec<Appointment>, i64), AppError> {
412- let mut result = db425+ PagedList::new(
413- .query("SELECT * FROM appointment WHERE requester = $requester ORDER BY id DESC")426+ "appointment WHERE requester = $requester",
414- .bind(("requester", requester.record()))427+ "ORDER BY id DESC",
415- .await?428+ )
416- .check()?;429+ .bind("requester", requester.record())
417- Ok(result.take::<Vec<Appointment>>(0)?)430+ .run(limit, offset, db)
431+ .await
418 }432 }
419 433
420 /// Every booking aimed at `teacher`, across all their slots — the teacher's434 /// Every booking aimed at `teacher`, across all their slots — the teacher's
421 /// request inbox.435 /// request inbox.
422 pub async fn list_for_teacher(436 pub async fn list_for_teacher(
423 teacher: &UserId,437 teacher: &UserId,
438+ limit: Option<i64>,
439+ offset: i64,
424 db: &Database,440 db: &Database,
425- ) -> Result<Vec<Appointment>, AppError> {441+ ) -> Result<(Vec<Appointment>, i64), AppError> {
426- let mut result = db442+ PagedList::new(
427- .query("SELECT * FROM appointment WHERE slot.teacher = $teacher ORDER BY id DESC")443+ "appointment WHERE slot.teacher = $teacher",
428- .bind(("teacher", teacher.record()))444+ "ORDER BY id DESC",
429- .await?445+ )
430- .check()?;446+ .bind("teacher", teacher.record())
431- Ok(result.take::<Vec<Appointment>>(0)?)447+ .run(limit, offset, db)
448+ .await
432 }449 }
433 450
434 pub async fn list_for_slot(451 pub async fn list_for_slot(
@@ -454,36 +471,42 @@ impl Appointment {
454 db: &Database,471 db: &Database,
455 ) -> Result<Appointment, AppError> {472 ) -> Result<Appointment, AppError> {
456 let _guard = APPOINTMENT_LOCK.lock().await;473 let _guard = APPOINTMENT_LOCK.lock().await;
457- let mut appointment = Self::read_pending(id, db).await?;474+ for _ in 0..CAS_UPDATE_RETRIES {
458- let slot = AppointmentSlot::read(&appointment.slot, db)475+ let expected = Self::read_pending(id, db).await?;
476+ let slot = AppointmentSlot::read(&expected.slot, db)
477+ .await?
478+ .ok_or(AppError::NotFound)?;
479+ let (starts_at, ends_at) = expected.window(&slot);
480+ // The effective window — the proposal's when one stands — must still
481+ // be ahead. Mutual agreement does not help: `cancel` refuses a
482+ // meeting that started, so committing to a passed window would mint
483+ // a booking nobody can ever undo. Refused, the row stays `pending`
484+ // and the teacher can propose a time that can actually happen.
485+ if starts_at.as_millis() <= Timestamp::now().as_millis() {
486+ return Err(AppError::Conflict("that time has already started"));
487+ }
488+ if Self::conflicts(
489+ slot.get_teacher(),
490+ &expected.requester,
491+ starts_at,
492+ ends_at,
493+ Some(id),
494+ db,
495+ )
459 .await?496 .await?
460- .ok_or(AppError::NotFound)?;497+ {
461- let (starts_at, ends_at) = appointment.window(&slot);498+ return Err(AppError::Conflict(
462- // The effective window — the proposal's when one stands — must still be499+ "that time collides with another approved appointment",
463- // ahead. Mutual agreement does not help: `cancel` refuses a meeting500+ ));
464- // that started, so committing to a passed window would mint a booking501+ }
465- // nobody can ever undo. Refused, the row stays `pending` and the502+ let mut approved = expected.clone();
466- // teacher can propose a time that can actually happen.503+ approved.status = AppointmentStatus::Approved;
467- if starts_at.as_millis() <= Timestamp::now().as_millis() {504+ approved.decided_by = Some(decided_by.clone());
468- return Err(AppError::Conflict("that time has already started"));505+ if let Some(saved) = approved.save_if_unchanged(&expected, db).await? {
469- }506+ return Ok(saved);
470- if Self::conflicts(507+ }
471- slot.get_teacher(),
472- &appointment.requester,
473- starts_at,
474- ends_at,
475- Some(id),
476- db,
477- )
478- .await?
479- {
480- return Err(AppError::Conflict(
481- "that time collides with another approved appointment",
482- ));
483 }508 }
484- appointment.status = AppointmentStatus::Approved;509+ Err(contended())
485- appointment.decided_by = Some(decided_by.clone());
486- Self::save(appointment, db).await
487 }510 }
488 511
489 /// Turn the request down. Frees the slot: occupancy counts live rows only.512 /// Turn the request down. Frees the slot: occupancy counts live rows only.
@@ -494,11 +517,17 @@ impl Appointment {
494 db: &Database,517 db: &Database,
495 ) -> Result<Appointment, AppError> {518 ) -> Result<Appointment, AppError> {
496 let _guard = APPOINTMENT_LOCK.lock().await;519 let _guard = APPOINTMENT_LOCK.lock().await;
497- let mut appointment = Self::read_pending(id, db).await?;520+ for _ in 0..CAS_UPDATE_RETRIES {
498- appointment.status = AppointmentStatus::Rejected;521+ let expected = Self::read_pending(id, db).await?;
499- appointment.decided_by = Some(decided_by.clone());522+ let mut rejected = expected.clone();
500- appointment.reject_reason = reason;523+ rejected.status = AppointmentStatus::Rejected;
501- Self::save(appointment, db).await524+ rejected.decided_by = Some(decided_by.clone());
525+ rejected.reject_reason = reason.clone();
526+ if let Some(saved) = rejected.save_if_unchanged(&expected, db).await? {
527+ return Ok(saved);
528+ }
529+ }
530+ Err(contended())
502 }531 }
503 532
504 /// Call the meeting off. Legal from either live state, so an approved533 /// Call the meeting off. Legal from either live state, so an approved
@@ -519,20 +548,26 @@ impl Appointment {
519 db: &Database,548 db: &Database,
520 ) -> Result<Appointment, AppError> {549 ) -> Result<Appointment, AppError> {
521 let _guard = APPOINTMENT_LOCK.lock().await;550 let _guard = APPOINTMENT_LOCK.lock().await;
522- let mut appointment = Self::read(id, db).await?.ok_or(AppError::NotFound)?;551+ for _ in 0..CAS_UPDATE_RETRIES {
523- if !appointment.status.is_live() {552+ let expected = Self::read(id, db).await?.ok_or(AppError::NotFound)?;
524- return Err(AppError::Conflict("the appointment is already settled"));553+ if !expected.status.is_live() {
525- }554+ return Err(AppError::Conflict("the appointment is already settled"));
526- let slot = AppointmentSlot::read(&appointment.slot, db)555+ }
527- .await?556+ let slot = AppointmentSlot::read(&expected.slot, db)
528- .ok_or(AppError::NotFound)?;557+ .await?
529- if appointment.window(&slot).0.as_millis() <= Timestamp::now().as_millis() {558+ .ok_or(AppError::NotFound)?;
530- return Err(AppError::Conflict("the appointment has already started"));559+ if expected.window(&slot).0.as_millis() <= Timestamp::now().as_millis() {
560+ return Err(AppError::Conflict("the appointment has already started"));
561+ }
562+ let mut cancelled = expected.clone();
563+ cancelled.status = AppointmentStatus::Cancelled;
564+ cancelled.cancelled_by = Some(cancelled_by.clone());
565+ cancelled.cancel_reason = reason.clone();
566+ if let Some(saved) = cancelled.save_if_unchanged(&expected, db).await? {
567+ return Ok(saved);
568+ }
531 }569 }
532- appointment.status = AppointmentStatus::Cancelled;570+ Err(contended())
533- appointment.cancelled_by = Some(cancelled_by.clone());
534- appointment.cancel_reason = reason;
535- Self::save(appointment, db).await
536 }571 }
537 572
538 /// Counter-propose another time on the same booking (no second row, so the573 /// Counter-propose another time on the same booking (no second row, so the
@@ -561,19 +596,25 @@ impl Appointment {
561 .into());596 .into());
562 }597 }
563 let _guard = APPOINTMENT_LOCK.lock().await;598 let _guard = APPOINTMENT_LOCK.lock().await;
564- let mut appointment = Self::read(id, db).await?.ok_or(AppError::NotFound)?;599+ for _ in 0..CAS_UPDATE_RETRIES {
565- if !appointment.status.is_live() {600+ let expected = Self::read(id, db).await?.ok_or(AppError::NotFound)?;
566- return Err(AppError::Conflict("the appointment is already settled"));601+ if !expected.status.is_live() {
567- }602+ return Err(AppError::Conflict("the appointment is already settled"));
568- if starts_at.as_millis() <= Timestamp::now().as_millis() {603+ }
569- return Err(AppError::Conflict("that time has already started"));604+ if starts_at.as_millis() <= Timestamp::now().as_millis() {
605+ return Err(AppError::Conflict("that time has already started"));
606+ }
607+ let mut proposed = expected.clone();
608+ proposed.status = AppointmentStatus::Pending;
609+ proposed.decided_by = None;
610+ proposed.proposed_starts_at = Some(starts_at);
611+ proposed.proposed_ends_at = Some(ends_at);
612+ proposed.proposed_by = Some(proposed_by.clone());
613+ if let Some(saved) = proposed.save_if_unchanged(&expected, db).await? {
614+ return Ok(saved);
615+ }
570 }616 }
571- appointment.status = AppointmentStatus::Pending;617+ Err(contended())
572- appointment.decided_by = None;
573- appointment.proposed_starts_at = Some(starts_at);
574- appointment.proposed_ends_at = Some(ends_at);
575- appointment.proposed_by = Some(proposed_by.clone());
576- Self::save(appointment, db).await
577 }618 }
578 619
579 /// Accept the standing proposal — approval at the proposed time. The620 /// Accept the standing proposal — approval at the proposed time. The
@@ -603,15 +644,66 @@ impl Appointment {
603 Ok(appointment)644 Ok(appointment)
604 }645 }
605 646
606- async fn save(appointment: Appointment, db: &Database) -> Result<Appointment, AppError> {647+ /// Write the decision only while the stored row still carries the state it
607- let updated: Option<Appointment> = db648+ /// was validated against. `None` means it does not: another decision landed
608- .update(appointment.id.record())649+ /// between the read and the write, so reload, re-validate, and try again.
609- .content(appointment)650+ ///
610- .await?;651+ /// Four columns discriminate every write, and `status` alone would not:
611- updated.ok_or(AppError::NotFound)652+ /// `propose` leaves a pending booking pending, so an approval built from a
653+ /// snapshot taken *before* that proposal would sail through a status-only
654+ /// guard and confirm the meeting at the old, superseded time. With the
655+ /// proposed window and `decided_by` alongside it, every mutator moves at
656+ /// least one of the four. The fields only a terminal transition writes
657+ /// (`cancelled_by`, `cancel_reason`, `reject_reason`) need no compare of
658+ /// their own: they always travel with a `status` change into a state no
659+ /// later decision is allowed from. All four are top-level columns, so an
660+ /// absent one reads back as `NONE` and `NONE = NONE` holds — the object-key
661+ /// dropping that forces `settings` to compare a rebuilt projection cannot
662+ /// bite here.
663+ ///
664+ /// A store-level write conflict is reported the same way as a miss: it
665+ /// means a concurrent write committed on this row, which is exactly the
666+ /// "reload and re-decide" case.
667+ async fn save_if_unchanged(
668+ self,
669+ expected: &Appointment,
670+ db: &Database,
671+ ) -> Result<Option<Appointment>, AppError> {
672+ let attempted = async {
673+ let mut result = db
674+ .query(
675+ "UPDATE $id CONTENT $new \
676+ WHERE status = $status \
677+ AND proposed_starts_at = $proposed_starts_at \
678+ AND proposed_ends_at = $proposed_ends_at \
679+ AND decided_by = $decided_by",
680+ )
681+ .bind(("id", expected.id.record()))
682+ .bind(("status", expected.status))
683+ .bind(("proposed_starts_at", expected.proposed_starts_at))
684+ .bind(("proposed_ends_at", expected.proposed_ends_at))
685+ .bind(("decided_by", expected.decided_by.clone()))
686+ .bind(("new", self))
687+ .await?
688+ .check()?;
689+ result.take::<Vec<Appointment>>(0)
690+ }
691+ .await;
692+ match attempted {
693+ Ok(rows) => Ok(rows.into_iter().next()),
694+ Err(err) if lost_the_race(&err) => Ok(None),
695+ Err(err) => Err(err.into()),
696+ }
612 }697 }
613 }698 }
614 699
700+/// Every retry lost the row to another decision. A 409 rather than a 500: the
701+/// caller's request was refused, nothing was half-applied, and re-reading the
702+/// booking shows what happened to it.
703+fn contended() -> AppError {
704+ AppError::Conflict("the appointment is being decided elsewhere")
705+}
706+
615 #[cfg(test)]707 #[cfg(test)]
616 mod tests {708 mod tests {
617 use super::*;709 use super::*;
@@ -749,13 +841,18 @@ mod tests {
749 // And approval judges the effective window again, for a proposal whose841 // And approval judges the effective window again, for a proposal whose
750 // time simply passed while it stood: forced onto the row directly,842 // time simply passed while it stood: forced onto the row directly,
751 // since `propose` no longer mints one.843 // since `propose` no longer mints one.
752- let mut standing = Appointment::read(booking.get_id(), &db)844+ let current = Appointment::read(booking.get_id(), &db)
753 .await845 .await
754 .unwrap()846 .unwrap()
755 .unwrap();847 .unwrap();
848+ let mut standing = current.clone();
756 standing.proposed_starts_at = Some(soon(-30_000));849 standing.proposed_starts_at = Some(soon(-30_000));
757 standing.proposed_ends_at = Some(soon(30_000));850 standing.proposed_ends_at = Some(soon(30_000));
758- Appointment::save(standing, &db).await.unwrap();851+ standing
852+ .save_if_unchanged(&current, &db)
853+ .await
854+ .unwrap()
855+ .unwrap();
759 assert!(matches!(856 assert!(matches!(
760 Appointment::accept_proposal(booking.get_id(), &student, &db).await,857 Appointment::accept_proposal(booking.get_id(), &student, &db).await,
761 Err(AppError::Conflict("that time has already started"))858 Err(AppError::Conflict("that time has already started"))
@@ -773,6 +870,76 @@ mod tests {
773 assert_eq!(accepted.get_status(), AppointmentStatus::Approved);870 assert_eq!(accepted.get_status(), AppointmentStatus::Approved);
774 }871 }
775 872
873+ /// The compare-and-set every decision writes through. `APPOINTMENT_LOCK` is
874+ /// process-local, so with two replicas serving, nothing else stands between
875+ /// an approval and a counter-proposal landing on the same booking — and the
876+ /// interleaving that matters is the one a status-only guard would miss,
877+ /// since `propose` leaves a pending booking pending.
878+ ///
879+ /// Deliberately sequential: the mem engine answers `Ok` to a write it then
880+ /// drops, so a `join!` of two decisions proves nothing. This drives the
881+ /// primitive itself with the exact snapshot a second replica would hold.
882+ #[tokio::test]
883+ async fn a_decision_built_on_a_stale_snapshot_never_lands() {
884+ let db = crate::database::init_mem().await.unwrap();
885+ let teacher = UserId::from_key("t1");
886+ let student = UserId::from_key("s1");
887+ let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db)
888+ .await
889+ .unwrap();
890+ let booking = Appointment::book(
891+ slot.get_id(),
892+ &student,
893+ AppointmentReason::try_new("görüşme").unwrap(),
894+ &db,
895+ )
896+ .await
897+ .unwrap();
898+
899+ // Replica A counter-proposes. Replica B is still holding the snapshot
900+ // it read before that — same id, same `pending` status.
901+ let stale = booking.clone();
902+ let (proposed_starts_at, proposed_ends_at) = (soon(180_000), soon(240_000));
903+ Appointment::propose(
904+ booking.get_id(),
905+ proposed_starts_at,
906+ proposed_ends_at,
907+ &teacher,
908+ &db,
909+ )
910+ .await
911+ .unwrap();
912+
913+ let mut late = stale.clone();
914+ late.status = AppointmentStatus::Approved;
915+ late.decided_by = Some(teacher.clone());
916+ assert!(late.save_if_unchanged(&stale, &db).await.unwrap().is_none());
917+
918+ // The proposal survived: the row was not confirmed at the slot's old
919+ // window behind the requester's back.
920+ let after = Appointment::read(booking.get_id(), &db)
921+ .await
922+ .unwrap()
923+ .unwrap();
924+ assert_eq!(after.get_status(), AppointmentStatus::Pending);
925+ assert_eq!(after.get_proposed_starts_at(), Some(proposed_starts_at));
926+ assert_eq!(after.get_proposed_ends_at(), Some(proposed_ends_at));
927+ assert_eq!(after.get_decided_by(), None);
928+
929+ // And the same decision, re-validated against the row as it now
930+ // stands, does land — a miss is a retry signal, not a wall.
931+ let mut fresh = after.clone();
932+ fresh.status = AppointmentStatus::Approved;
933+ fresh.decided_by = Some(teacher.clone());
934+ let saved = fresh
935+ .save_if_unchanged(&after, &db)
936+ .await
937+ .unwrap()
938+ .expect("a current snapshot must write");
939+ assert_eq!(saved.get_status(), AppointmentStatus::Approved);
940+ assert_eq!(saved.get_proposed_starts_at(), Some(proposed_starts_at));
941+ }
942+
776 /// Occupancy is derived, so a rejected booking must hand the slot back.943 /// Occupancy is derived, so a rejected booking must hand the slot back.
777 #[tokio::test]944 #[tokio::test]
778 async fn rejecting_frees_the_slot_for_re_booking() {945 async fn rejecting_frees_the_slot_for_re_booking() {
src/domain/attendance.rsmodified+8 -7
@@ -3,6 +3,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
3 use crate::constant::ATTENDANCE_TABLE;3 use crate::constant::ATTENDANCE_TABLE;
4 use crate::database::Database;4 use crate::database::Database;
5 use crate::domain::event::EventId;5 use crate::domain::event::EventId;
6+use crate::domain::page::PagedList;
6 use crate::domain::user::UserId;7 use crate::domain::user::UserId;
7 use crate::error::{AppError, ValidationError};8 use crate::error::{AppError, ValidationError};
8 9
@@ -113,14 +114,14 @@ impl Attendance {
113 114
114 pub async fn list_for_event(115 pub async fn list_for_event(
115 event: &EventId,116 event: &EventId,
117+ limit: Option<i64>,
118+ offset: i64,
116 db: &Database,119 db: &Database,
117- ) -> Result<Vec<Attendance>, AppError> {120+ ) -> Result<(Vec<Attendance>, i64), AppError> {
118- let mut result = db121+ PagedList::new("attendance WHERE event = $ev", "ORDER BY id DESC")
119- .query("SELECT * FROM attendance WHERE event = $ev ORDER BY id DESC")122+ .bind("ev", event.record())
120- .bind(("ev", event.record()))123+ .run(limit, offset, db)
121- .await?124+ .await
122- .check()?;
123- Ok(result.take::<Vec<Attendance>>(0)?)
124 }125 }
125 126
126 /// Every event-attendance row recorded for `user` — the events half of the127 /// Every event-attendance row recorded for `user` — the events half of the
src/domain/bank_question.rsmodified+87 -17
@@ -379,15 +379,22 @@ impl BankQuestion {
379 .collect())379 .collect())
380 }380 }
381 381
382- /// Write the editable fields of the template.382+ /// Write the editable fields of the template, but only while the row still
383+ /// reads as the snapshot `self` was loaded from — `None` means a concurrent
384+ /// edit (or the subject-delete cascade that clears `subject`) landed inside
385+ /// the handler's read-merge window, so nothing was written: reload,
386+ /// re-merge, retry. This is a genuine read-modify-write — every editable
387+ /// field is re-stated from the snapshot, and the kind/choices/correct trio
388+ /// has to be (a text-only edit re-submits the stored options *with their
389+ /// ids* so each keeps its picture) — so without the compare-and-set the
390+ /// later writer silently reverts the earlier one. An in-process `RwLock`
391+ /// only stopped that between requests of *one* replica.
383 ///392 ///
384- /// Field-scoped, never a whole-row content-replace save: the handler reads393+ /// Every field the merge re-states is in the guard, which is the same list
385- /// the row, then awaits an ownership check and a subject lookup before394+ /// the `SET` writes. `choices` is compared whole: its objects carry two
386- /// getting here, so a concurrent PATCH (or the subject-delete cascade that395+ /// required string keys, so none is ever dropped for being `NONE` (the trap
387- /// clears `subject`) can land inside that window — a whole-row save would396+ /// [`crate::domain::settings::Settings::save_if_unchanged`] works around).
388- /// silently revert it. Same shape, same reason as397+ pub async fn update_if_unchanged(
389- /// [`crate::domain::exam_question::ExamQuestion::link_banked_as`].
390- pub async fn update(
391 self,398 self,
392 subject: Option<SubjectId>,399 subject: Option<SubjectId>,
393 text: QuestionText,400 text: QuestionText,
@@ -395,14 +402,26 @@ impl BankQuestion {
395 spec: QuestionSpec,402 spec: QuestionSpec,
396 visibility: BankVisibility,403 visibility: BankVisibility,
397 db: &Database,404 db: &Database,
398- ) -> Result<BankQuestion, AppError> {405+ ) -> Result<Option<BankQuestion>, AppError> {
399 let (kind, choices, correct) = spec.into_parts();406 let (kind, choices, correct) = spec.into_parts();
400 let mut result = db407 let mut result = db
401 .query(408 .query(
402 "UPDATE $id SET subject = $subject, text = $text, points = $points,409 "UPDATE $id SET subject = $subject, text = $text, points = $points,
403 kind = $kind, choices = $choices, correct = $correct,410 kind = $kind, choices = $choices, correct = $correct,
404- visibility = $visibility RETURN AFTER",411+ visibility = $visibility
412+ WHERE subject = $was_subject AND text = $was_text
413+ AND points = $was_points AND kind = $was_kind
414+ AND choices = $was_choices AND correct = $was_correct
415+ AND visibility = $was_visibility
416+ RETURN AFTER",
405 )417 )
418+ .bind(("was_subject", self.subject.clone().map(|s| s.record())))
419+ .bind(("was_text", self.text.clone()))
420+ .bind(("was_points", self.points))
421+ .bind(("was_kind", self.kind.clone()))
422+ .bind(("was_choices", self.choices.clone()))
423+ .bind(("was_correct", self.correct.clone()))
424+ .bind(("was_visibility", self.visibility.clone()))
406 .bind(("id", self.id.record()))425 .bind(("id", self.id.record()))
407 .bind(("subject", subject.map(|s| s.record())))426 .bind(("subject", subject.map(|s| s.record())))
408 .bind(("text", text))427 .bind(("text", text))
@@ -413,11 +432,7 @@ impl BankQuestion {
413 .bind(("visibility", visibility))432 .bind(("visibility", visibility))
414 .await?433 .await?
415 .check()?;434 .check()?;
416- result435+ Ok(result.take::<Vec<BankQuestion>>(0)?.into_iter().next())
417- .take::<Vec<BankQuestion>>(0)?
418- .into_iter()
419- .next()
420- .ok_or(AppError::NotFound)
421 }436 }
422 437
423 /// Delete the template and cascade-remove its bank images, so none points438 /// Delete the template and cascade-remove its bank images, so none points
@@ -556,7 +571,7 @@ mod tests {
556 .unwrap();571 .unwrap();
557 let subject = published.get_subject().cloned();572 let subject = published.get_subject().cloned();
558 published573 published
559- .update(574+ .update_if_unchanged(
560 subject,575 subject,
561 QuestionText::try_new("shared").unwrap(),576 QuestionText::try_new("shared").unwrap(),
562 QuestionPoints::try_new(1).unwrap(),577 QuestionPoints::try_new(1).unwrap(),
@@ -591,6 +606,61 @@ mod tests {
591 assert_eq!(private.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE);606 assert_eq!(private.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE);
592 }607 }
593 608
609+ /// The bite test for the compare-and-set that replaced the writer lease of
610+ /// `BANK_LOCK` on the PATCH path: a merge built on a snapshot the row has
611+ /// since moved past must be refused, not written — otherwise it reverts
612+ /// whatever landed in between. Asserts the *stored* row, never a race
613+ /// outcome: the in-memory engine can drop one of two concurrent writes and
614+ /// still answer `Ok`.
615+ #[tokio::test]
616+ async fn a_merge_built_on_a_stale_snapshot_is_refused() {
617+ let db = crate::database::init_mem().await.unwrap();
618+ let owner = UserId::generate();
619+ let stale = BankQuestion::create(
620+ owner,
621+ SubjectId::generate(),
622+ QuestionText::try_new("first").unwrap(),
623+ QuestionPoints::try_new(1).unwrap(),
624+ spec(),
625+ &db,
626+ )
627+ .await
628+ .unwrap();
629+ // Somebody else's edit lands on the row this snapshot came from.
630+ let landed = stale
631+ .clone()
632+ .update_if_unchanged(
633+ None,
634+ QuestionText::try_new("theirs").unwrap(),
635+ QuestionPoints::try_new(2).unwrap(),
636+ spec(),
637+ BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(),
638+ &db,
639+ )
640+ .await
641+ .unwrap();
642+ assert!(landed.is_some(), "the first write is on a fresh snapshot");
643+
644+ let refused = stale
645+ .update_if_unchanged(
646+ None,
647+ QuestionText::try_new("mine").unwrap(),
648+ QuestionPoints::try_new(3).unwrap(),
649+ spec(),
650+ BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(),
651+ &db,
652+ )
653+ .await
654+ .unwrap();
655+ assert!(refused.is_none(), "a stale merge must not be written");
656+ let stored = BankQuestion::read(landed.unwrap().get_id(), &db)
657+ .await
658+ .unwrap()
659+ .unwrap();
660+ assert_eq!(stored.get_text().as_str(), "theirs");
661+ assert_eq!(stored.get_points().as_i64(), 2);
662+ }
663+
594 /// The `visibility` filter ANDs onto the security gate, so it narrows and664 /// The `visibility` filter ANDs onto the security gate, so it narrows and
595 /// never widens: a stranger asking for `school` still can't see a private665 /// never widens: a stranger asking for `school` still can't see a private
596 /// row, and `private` means "my own drafts" for everyone but an admin.666 /// row, and `private` means "my own drafts" for everyone but an admin.
@@ -613,7 +683,7 @@ mod tests {
613 let published = mine("shared").await.unwrap();683 let published = mine("shared").await.unwrap();
614 let subject = published.get_subject().cloned();684 let subject = published.get_subject().cloned();
615 published685 published
616- .update(686+ .update_if_unchanged(
617 subject,687 subject,
618 QuestionText::try_new("shared").unwrap(),688 QuestionText::try_new("shared").unwrap(),
619 QuestionPoints::try_new(1).unwrap(),689 QuestionPoints::try_new(1).unwrap(),
src/domain/bank_question_image.rsmodified+4 -11
@@ -17,6 +17,7 @@ use crate::constant::BANK_QUESTION_IMAGE_TABLE;
17 use crate::database::Database;17 use crate::database::Database;
18 use crate::domain::bank_question::BankQuestionId;18 use crate::domain::bank_question::BankQuestionId;
19 use crate::domain::exam_question::ChoiceId;19 use crate::domain::exam_question::ChoiceId;
20+use crate::domain::key;
20 use crate::domain::note_file::FileContentType;21 use crate::domain::note_file::FileContentType;
21 use crate::error::AppError;22 use crate::error::AppError;
22 23
@@ -24,20 +25,12 @@ use crate::error::AppError;
24 pub struct BankQuestionImageId(RecordId);25 pub struct BankQuestionImageId(RecordId);
25 26
26 impl BankQuestionImageId {27 impl BankQuestionImageId {
27- /// The one id a (question, slot) pair can have: `{bid}_q` for the28+ /// The one id a (question, slot) pair can have — see [`key::slot`] for the
28- /// question's own image, `{bid}_{choice id}` for one option's picture —29+ /// key shape and why the two forms can never collide.
29- /// uniqueness per slot needs no index this way. Keyed by the option's
30- /// *stable id*, so reordering the choice list moves no picture.
31 pub fn for_slot(question: &BankQuestionId, slot: Option<&ChoiceId>) -> Self {30 pub fn for_slot(question: &BankQuestionId, slot: Option<&ChoiceId>) -> Self {
32- // `_` is not in Crockford base32 and a ULID is never `"q"`, so
33- // `{qid}_{cid}` and `{qid}_q` can never collide.
34- let suffix = match slot {
35- None => "q",
36- Some(id) => id.as_str(),
37- };
38 Self(RecordId::new(31 Self(RecordId::new(
39 BANK_QUESTION_IMAGE_TABLE,32 BANK_QUESTION_IMAGE_TABLE,
40- format!("{}_{suffix}", question.key()),33+ key::slot(question.key(), slot.map(|id| id.as_str())),
41 ))34 ))
42 }35 }
43 36
src/domain/cap.rsadded+133 -0
@@ -0,0 +1,133 @@
1+//! Count caps that hold across replicas.
2+//!
3+//! Every "at most N children per parent" rule used to be a count-then-write
4+//! under a process-wide `Mutex`, because a `BEGIN…COMMIT` cannot enforce it:
5+//! SurrealDB does not conflict-check a cross-record `count()` against a
6+//! concurrent insert (write-skew), so two racing writers both saw a free slot.
7+//! A mutex only serializes the writers *inside one process*, and the backend
8+//! now runs as two replicas against one database — so every one of those caps
9+//! was open again.
10+//!
11+//! The guard that does survive is a single-record conditional write: an
12+//! `UPDATE … SET n += 1 WHERE n < cap` on the *parent* row is atomic, so of N
13+//! concurrent claimers exactly `cap` get a non-empty result and the rest are
14+//! refused, whatever process they run in. The counter is therefore the
15+//! authority on how many slots are taken, and the child rows follow it:
16+//! [`claim`] before the insert, [`release`] if the insert then fails, and a
17+//! decrement in the *same transaction* as every delete of a child row.
18+//!
19+//! The counters are `option<int>` columns on the parent table, absent meaning
20+//! zero, so no Rust struct carries them and no whole-row save can clobber one
21+//! (every parent's `.content()` write is a create of a fresh row).
22+//
23+// ponytail: a counter can only drift if a future delete path forgets its
24+// decrement, and the boot backfill seeds counters once rather than recomputing
25+// them (recomputing on every boot would clobber a live peer's increments). If
26+// drift is ever observed, the repair is the same GROUP BY count the backfill
27+// runs, issued by hand with the field's `= NONE` guard dropped.
28+
29+use surrealdb::types::RecordId;
30+use tokio::sync::Mutex;
31+
32+use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES};
33+use crate::database::{Database, lost_the_race};
34+use crate::domain::timestamp::Timestamp;
35+use crate::error::AppError;
36+
37+/// One writer per process at a time, over every counter.
38+///
39+/// Not the cap — the `WHERE` clause is the cap, and it holds with or without
40+/// this. What the lock buys is that a replica sends its counter writes one at a
41+/// time, so the only contention the database ever sees on a parent row is
42+/// between replicas: at most as many concurrent writers as there are processes,
43+/// instead of as many as there are in-flight requests. That keeps the optimistic
44+/// retry loop below to a beat or two rather than a storm.
45+///
46+/// It is also what keeps the test suite deterministic. The embedded in-memory
47+/// engine the tests run on does *not* have the real server's conflict
48+/// detection: under two concurrent writes to one record it can drop one and
49+/// still answer `Ok` (probed — the stored counter stays correct, but ~13% of a
50+/// 16-racer round had one more caller told it had won than the counter agreed
51+/// to). The real ws server never did this in 150 rounds of the same probe.
52+//
53+// ponytail: one lock for every cap. Per-parent locks (a keyed map) if unrelated
54+// caps ever contend measurably — the counters are already independent, this is
55+// only about how many writes a process has in flight.
56+static CLAIM_LOCK: Mutex<()> = Mutex::const_new(());
57+
58+/// "No cap" as a number, so the guard stays one comparison instead of a
59+/// nullable branch: `NONE`/`NULL` bind ambiguity is a worse trade than a
60+/// sentinel no roster will ever reach.
61+pub(crate) const UNLIMITED: i64 = i64::MAX;
62+
63+/// Take one slot on `parent`'s `field` counter. `false` means the cap is full
64+/// (or the parent row is gone) and the caller must refuse — nothing was
65+/// written. `field` is always an in-crate constant, never user input.
66+pub(crate) async fn claim(
67+ parent: &RecordId,
68+ field: &str,
69+ cap: i64,
70+ db: &Database,
71+) -> Result<bool, AppError> {
72+ let sql = format!(
73+ "UPDATE $parent SET {field} = ({field} ?? 0) + 1 \
74+ WHERE ({field} ?? 0) < $cap RETURN VALUE id"
75+ );
76+ Ok(!write(&sql, parent, cap, db).await?.is_empty())
77+}
78+
79+/// Give a claimed slot back, for the insert that never landed. Clamped at zero
80+/// so a double release can never push a counter negative and open the cap.
81+pub(crate) async fn release(parent: &RecordId, field: &str, db: &Database) -> Result<(), AppError> {
82+ let sql =
83+ format!("UPDATE $parent SET {field} = math::max([({field} ?? 0) - 1, 0]) RETURN VALUE id");
84+ write(&sql, parent, UNLIMITED, db).await?;
85+ Ok(())
86+}
87+
88+/// Run one conditional counter write, retrying while the store reports a write
89+/// conflict.
90+///
91+/// Claimers contend on a single record by design — that contention *is* the
92+/// guard — and SurrealDB resolves it optimistically: the loser's transaction is
93+/// aborted with "can be retried" rather than queued, which the old mutex hid by
94+/// never letting two writers reach the database at once. So the queueing has to
95+/// happen here. Backoff is exponential with jitter, because racers arrive in
96+/// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them.
97+async fn write(
98+ sql: &str,
99+ parent: &RecordId,
100+ cap: i64,
101+ db: &Database,
102+) -> Result<Vec<RecordId>, AppError> {
103+ let _guard = CLAIM_LOCK.lock().await;
104+ let mut last = None;
105+ for attempt in 0..CAP_WRITE_TRIES {
106+ if attempt > 0 {
107+ let step = CAP_WRITE_BACKOFF_MS << (attempt - 1);
108+ let jitter = Timestamp::now().as_millis().unsigned_abs() % step.max(1);
109+ tokio::time::sleep(std::time::Duration::from_millis(step + jitter)).await;
110+ }
111+ let attempted = async {
112+ let mut result = db
113+ .query(sql)
114+ .bind(("parent", parent.clone()))
115+ .bind(("cap", cap))
116+ .await?
117+ .check()?;
118+ result.take::<Vec<RecordId>>(0)
119+ }
120+ .await;
121+ match attempted {
122+ Ok(hit) => return Ok(hit),
123+ // `lost_the_race` also matches "already exists", which an UPDATE
124+ // cannot produce — what is being reused here is its transaction
125+ // conflict detection, typed details first and wording second.
126+ Err(err) if lost_the_race(&err) => last = Some(err),
127+ Err(err) => return Err(err.into()),
128+ }
129+ }
130+ Err(last
131+ .map(AppError::from)
132+ .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into())))
133+}
src/domain/chatbot_message.rsmodified+18 -15
@@ -21,6 +21,7 @@ use crate::constant::{
21 };21 };
22 use crate::database::Database;22 use crate::database::Database;
23 use crate::domain::chatbot_thread::ChatbotThreadId;23 use crate::domain::chatbot_thread::ChatbotThreadId;
24+use crate::domain::page::PagedList;
24 use crate::domain::timestamp::Timestamp;25 use crate::domain::timestamp::Timestamp;
25 use crate::domain::user::UserId;26 use crate::domain::user::UserId;
26 use crate::error::{AppError, ValidationError};27 use crate::error::{AppError, ValidationError};
@@ -283,21 +284,21 @@ impl ChatbotMessage {
283 /// history payload read in.284 /// history payload read in.
284 pub async fn list_for_thread(285 pub async fn list_for_thread(
285 thread: &ChatbotThreadId,286 thread: &ChatbotThreadId,
287+ limit: Option<i64>,
288+ offset: i64,
286 db: &Database,289 db: &Database,
287- ) -> Result<Vec<ChatbotMessage>, AppError> {290+ ) -> Result<(Vec<ChatbotMessage>, i64), AppError> {
288- let mut result = db291+ let (rows, total) = PagedList::new(
289- .query(292+ "chatbot_message WHERE thread_id = $conv",
290- "SELECT * FROM chatbot_message WHERE thread_id = $conv \293+ "ORDER BY created_at ASC, id ASC",
291- ORDER BY created_at ASC, id ASC",294+ )
292- )295+ .bind("conv", thread.record())
293- .bind(("conv", thread.record()))296+ .run::<ChatbotMessage>(limit, offset, db)
294- .await?297+ .await?;
295- .check()?;298+ Ok((
296- Ok(result299+ rows.into_iter().map(ChatbotMessage::projected).collect(),
297- .take::<Vec<ChatbotMessage>>(0)?300+ total,
298- .into_iter()301+ ))
299- .map(ChatbotMessage::projected)
300- .collect())
301 }302 }
302 303
303 /// The last `limit` turns, still oldest-first — the tail replayed to the304 /// The last `limit` turns, still oldest-first — the tail replayed to the
@@ -549,7 +550,9 @@ mod tests {
549 .unwrap();550 .unwrap();
550 }551 }
551 552
552- let whole = ChatbotMessage::list_for_thread(&thread, &db).await.unwrap();553+ let (whole, _) = ChatbotMessage::list_for_thread(&thread, None, 0, &db)
554+ .await
555+ .unwrap();
553 let tail = ChatbotMessage::list_tail(&thread, TURNS * 2, &db)556 let tail = ChatbotMessage::list_tail(&thread, TURNS * 2, &db)
554 .await557 .await
555 .unwrap();558 .unwrap();
src/domain/chatbot_thread.rsmodified+36 -27
@@ -4,23 +4,20 @@
4 //! [`crate::domain::chatbot_message`], and deleting a thread cascades them.4 //! [`crate::domain::chatbot_message`], and deleting a thread cascades them.
5 5
6 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};6 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
7-use tokio::sync::Mutex;
8 use ulid::Ulid;7 use ulid::Ulid;
9 8
10-use crate::constant::{CHATBOT_THREAD_TABLE, MAX_CHATBOT_THREAD_TITLE_LEN};9+use crate::constant::{
10+ CHATBOT_THREAD_COUNT_FIELD, CHATBOT_THREAD_TABLE, MAX_CHATBOT_THREAD_TITLE_LEN,
11+};
11 use crate::database::Database;12 use crate::database::Database;
13+use crate::domain::cap;
14+use crate::domain::page::PagedList;
12 use crate::domain::settings::Settings;15 use crate::domain::settings::Settings;
13 use crate::domain::timestamp::Timestamp;16 use crate::domain::timestamp::Timestamp;
14 use crate::domain::user::UserId;17 use crate::domain::user::UserId;
15 use crate::error::{AppError, ValidationError};18 use crate::error::{AppError, ValidationError};
16 use crate::validate::validate_required;19 use crate::validate::validate_required;
17 20
18-/// Serializes thread creation so the `max_chatbot_threads` check (count,
19-/// then write) can't over-admit under concurrency — the database's optimistic
20-/// transactions don't serialize cross-record counts against concurrent
21-/// inserts. Same reasoning, and the same shape, as `ENROLL_LOCK`.
22-static CHATBOT_THREAD_LOCK: Mutex<()> = Mutex::const_new(());
23-
24 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]21 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
25 pub struct ChatbotThreadId(RecordId);22 pub struct ChatbotThreadId(RecordId);
26 23
@@ -109,37 +106,46 @@ impl ChatbotThread {
109 }106 }
110 107
111 /// Start a thread unless `user` is already at the school's108 /// Start a thread unless `user` is already at the school's
112- /// `max_chatbot_threads`. The whole check-then-write runs under109+ /// `max_chatbot_threads`. The slot is taken by [`cap::claim`] on the user
113- /// [`CHATBOT_THREAD_LOCK`], and the cap is re-read inside it, since neither110+ /// row — an atomic single-record write, so two replicas racing the same
114- /// the transaction model nor a caller-supplied number survives a concurrent111+ /// user's last slot cannot both win, and the cap is read fresh so a
115- /// settings PATCH.112+ /// concurrent settings PATCH is respected.
116 pub async fn create_capped(113 pub async fn create_capped(
117 user: &UserId,114 user: &UserId,
118 title: Option<ChatbotThreadTitle>,115 title: Option<ChatbotThreadTitle>,
119 db: &Database,116 db: &Database,
120 ) -> Result<ChatbotThread, AppError> {117 ) -> Result<ChatbotThread, AppError> {
121- let _guard = CHATBOT_THREAD_LOCK.lock().await;118+ let limit = Settings::load(db).await?.get_max_chatbot_threads();
122- let cap = Settings::load(db).await?.get_max_chatbot_threads();119+ let owner = user.record();
123- if Self::count_for_user(user, db).await? as i64 >= cap {120+ if !cap::claim(&owner, CHATBOT_THREAD_COUNT_FIELD, limit, db).await? {
124 return Err(AppError::Conflict(121 return Err(AppError::Conflict(
125 "you have reached the school's limit on saved threads — delete one first",122 "you have reached the school's limit on saved threads — delete one first",
126 ));123 ));
127 }124 }
128- Self::create(user, title, db).await125+ match Self::create(user, title, db).await {
126+ Ok(thread) => Ok(thread),
127+ Err(err) => {
128+ cap::release(&owner, CHATBOT_THREAD_COUNT_FIELD, db).await?;
129+ Err(err)
130+ }
131+ }
129 }132 }
130 133
131 /// A user's threads, most recently active first — the sort the134 /// A user's threads, most recently active first — the sort the
132 /// `chatbot_thread_user_updated` index exists for.135 /// `chatbot_thread_user_updated` index exists for.
133 pub async fn list_for_user(136 pub async fn list_for_user(
134 user: &UserId,137 user: &UserId,
138+ limit: Option<i64>,
139+ offset: i64,
135 db: &Database,140 db: &Database,
136- ) -> Result<Vec<ChatbotThread>, AppError> {141+ ) -> Result<(Vec<ChatbotThread>, i64), AppError> {
137- let mut result = db142+ PagedList::new(
138- .query("SELECT * FROM chatbot_thread WHERE user_id = $usr ORDER BY updated_at DESC")143+ "chatbot_thread WHERE user_id = $usr",
139- .bind(("usr", user.record()))144+ "ORDER BY updated_at DESC",
140- .await?145+ )
141- .check()?;146+ .bind("usr", user.record())
142- Ok(result.take::<Vec<ChatbotThread>>(0)?)147+ .run(limit, offset, db)
148+ .await
143 }149 }
144 150
145 /// How many threads `user` keeps — the `max_chatbot_threads` cap check.151 /// How many threads `user` keeps — the `max_chatbot_threads` cap check.
@@ -207,21 +213,24 @@ impl ChatbotThread {
207 }213 }
208 214
209 /// Delete the thread and every turn in it — one transaction, so a crash215 /// Delete the thread and every turn in it — one transaction, so a crash
210- /// can't orphan messages under a vanished thread.216+ /// can't orphan messages under a vanished thread. The owner's slot comes
217+ /// back in that same transaction, or the cap would ratchet shut.
211 pub async fn delete(self, db: &Database) -> Result<ChatbotThread, AppError> {218 pub async fn delete(self, db: &Database) -> Result<ChatbotThread, AppError> {
212 let mut result = db219 let mut result = db
213 .query(220 .query(
214 "BEGIN TRANSACTION;221 "BEGIN TRANSACTION;
215 DELETE chatbot_message WHERE thread_id = $conv;222 DELETE chatbot_message WHERE thread_id = $conv;
216- DELETE $conv RETURN BEFORE;223+ LET $gone = (DELETE $conv RETURN BEFORE);
224+ UPDATE $usr SET chatbot_thread_count = math::max([(chatbot_thread_count ?? 0) - array::len($gone), 0]);
225+ RETURN $gone;
217 COMMIT TRANSACTION;",226 COMMIT TRANSACTION;",
218 )227 )
219 .bind(("conv", self.id.record()))228 .bind(("conv", self.id.record()))
229+ .bind(("usr", self.user_id.record()))
220 .await?230 .await?
221 .check()?;231 .check()?;
222- // BEGIN is slot 0; the thread's own DELETE is slot 2.
223 let deleted: Option<ChatbotThread> =232 let deleted: Option<ChatbotThread> =
224- result.take::<Vec<ChatbotThread>>(2)?.into_iter().next();233+ result.take::<Vec<ChatbotThread>>(4)?.into_iter().next();
225 deleted.ok_or(AppError::NotFound)234 deleted.ok_or(AppError::NotFound)
226 }235 }
227 }236 }
src/domain/course.rsmodified+14 -11
@@ -4,6 +4,7 @@ use ulid::Ulid;
4 use crate::constant::{COURSE_TABLE, MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN};4 use crate::constant::{COURSE_TABLE, MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN};
5 use crate::database::Database;5 use crate::database::Database;
6 use crate::domain::field_update::FieldUpdate;6 use crate::domain::field_update::FieldUpdate;
7+use crate::domain::page::PagedList;
7 use crate::domain::term::TermId;8 use crate::domain::term::TermId;
8 use crate::domain::user::UserId;9 use crate::domain::user::UserId;
9 use crate::error::{AppError, ValidationError};10 use crate::error::{AppError, ValidationError};
@@ -189,17 +190,19 @@ impl Course {
189 190
190 /// The courses `user` is enrolled in — the spine of `/courses/me` and the191 /// The courses `user` is enrolled in — the spine of `/courses/me` and the
191 /// marks report.192 /// marks report.
192- pub async fn list_enrolled(user: &UserId, db: &Database) -> Result<Vec<Course>, AppError> {193+ pub async fn list_enrolled(
193- let mut result = db194+ user: &UserId,
194- .query(195+ limit: Option<i64>,
195- "SELECT * FROM course196+ offset: i64,
196- WHERE id IN (SELECT VALUE course FROM enrollment WHERE user = $usr)197+ db: &Database,
197- ORDER BY id DESC",198+ ) -> Result<(Vec<Course>, i64), AppError> {
198- )199+ PagedList::new(
199- .bind(("usr", user.record()))200+ "course WHERE id IN (SELECT VALUE course FROM enrollment WHERE user = $usr)",
200- .await?201+ "ORDER BY id DESC",
201- .check()?;202+ )
202- Ok(result.take::<Vec<Course>>(0)?)203+ .bind("usr", user.record())
204+ .run(limit, offset, db)
205+ .await
203 }206 }
204 207
205 /// The courses `user` runs — the ones they created plus the ones a manager208 /// The courses `user` runs — the ones they created plus the ones a manager
src/domain/course_session.rsmodified+17 -27
@@ -1,30 +1,16 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2-use tokio::sync::Mutex;
3 use ulid::Ulid;2 use ulid::Ulid;
4 3
5 use crate::constant::{COURSE_SESSION_TABLE, MAX_SESSION_TOPIC_LEN};4 use crate::constant::{COURSE_SESSION_TABLE, MAX_SESSION_TOPIC_LEN};
6 use crate::database::Database;5 use crate::database::Database;
7 use crate::domain::course::CourseId;6 use crate::domain::course::CourseId;
8 use crate::domain::field_update::FieldUpdate;7 use crate::domain::field_update::FieldUpdate;
9-use crate::domain::timestamp::Timestamp;8+use crate::domain::page::PagedList;
9+use crate::domain::timestamp::{Timestamp, range_error};
10 use crate::domain::user::UserId;10 use crate::domain::user::UserId;
11 use crate::error::{AppError, ValidationError};11 use crate::error::{AppError, ValidationError};
12 use crate::validate::validate_optional;12 use crate::validate::validate_optional;
13 13
14-/// Serializes a lesson's time-range check against the write it guards, exactly
15-/// as [`crate::domain::event::EVENT_LOCK`] does for events: `starts_at <=
16-/// ends_at` is a cross-field check, so a PATCH carrying one end validates it
17-/// against the *stored* other end — two such PATCHes, each fine on its own
18-/// snapshot, would otherwise commit an inverted lesson between them. A PATCH
19-/// that moves neither end checks nothing cross-field and stays lock-free.
20-///
21-/// Lock order: this is a leaf — the only path that takes it (`PATCH
22-/// /sessions/{id}`) takes no other lock, and no path holding `EXAM_LOCK`,
23-/// `BANK_LOCK`, `HOMEWORK_LOCK`, `ENROLL_LOCK` or any other takes this one, so
24-/// it cannot sit in a cycle. Should a future path need both, take the other
25-/// lock first and this one innermost.
26-pub(crate) static SESSION_LOCK: Mutex<()> = Mutex::const_new(());
27-
28 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]14 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
29 pub struct CourseSessionId(RecordId);15 pub struct CourseSessionId(RecordId);
30 16
@@ -140,18 +126,21 @@ impl CourseSession {
140 /// the row was created.126 /// the row was created.
141 pub async fn list_for_course(127 pub async fn list_for_course(
142 course: &CourseId,128 course: &CourseId,
129+ limit: Option<i64>,
130+ offset: i64,
143 db: &Database,131 db: &Database,
144- ) -> Result<Vec<CourseSession>, AppError> {132+ ) -> Result<(Vec<CourseSession>, i64), AppError> {
145- let mut result = db133+ PagedList::new(
146- .query("SELECT * FROM course_session WHERE course = $course ORDER BY starts_at DESC")134+ "course_session WHERE course = $course",
147- .bind(("course", course.record()))135+ "ORDER BY starts_at DESC",
148- .await?136+ )
149- .check()?;137+ .bind("course", course.record())
150- Ok(result.take::<Vec<CourseSession>>(0)?)138+ .run(limit, offset, db)
151- }139+ .await
152-140+ }
153- /// Request-scoped: the handler holds no lock across its read and this write141+
154- /// unless a schedule end arrives ([`SESSION_LOCK`]), so a field the request142+ /// Request-scoped: the handler holds nothing across its read and this
143+ /// write — the range check rides in the `WHERE` — so a field the request
155 /// omitted (`None`) is not written at all. Re-sending the snapshot's value144 /// omitted (`None`) is not written at all. Re-sending the snapshot's value
156 /// instead would revert a concurrent PATCH of that field — scoping the145 /// instead would revert a concurrent PATCH of that field — scoping the
157 /// `SET` alone does not stop that, the values have to come from the146 /// `SET` alone does not stop that, the values have to come from the
@@ -170,6 +159,7 @@ impl CourseSession {
170 .set("topic", topic)159 .set("topic", topic)
171 .set("starts_at", starts_at)160 .set("starts_at", starts_at)
172 .set("ends_at", ends_at)161 .set("ends_at", ends_at)
162+ .ordered("starts_at", "ends_at", range_error())
173 .run::<CourseSession>(db)163 .run::<CourseSession>(db)
174 .await164 .await
175 }165 }
src/domain/enrollment.rsmodified+77 -35
@@ -1,17 +1,22 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 use tokio::sync::Mutex;2 use tokio::sync::Mutex;
3 3
4-use crate::constant::ENROLLMENT_TABLE;4+use crate::constant::{ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE};
5-use crate::database::Database;5+use crate::database::{Database, lost_the_race};
6+use crate::domain::cap;
6 use crate::domain::course::{Course, CourseId};7 use crate::domain::course::{Course, CourseId};
8+use crate::domain::page::PagedList;
7 use crate::domain::user::UserId;9 use crate::domain::user::UserId;
8 use crate::error::AppError;10 use crate::error::AppError;
9 11
10-/// Serializes enrolls so the capacity check (count, then write) can't12+/// Serializes the roster check of a course delete against a concurrent enroll,
11-/// over-admit under concurrency — the database's optimistic transactions13+/// so a student can't join a course that is already on its way out.
12-/// don't serialize cross-record counts against concurrent inserts.14+//
13-/// It also serializes the roster check of a course delete against a concurrent15+// ponytail: process-local, so with two replicas the delete-vs-enroll window is
14-/// enroll, so a student can't join a course that is already on its way out.16+// only narrowed, not closed — a student can still land on a course another
17+// replica is deleting, and the cascade then leaves nothing behind but a 404 on
18+// the next read. Closing it needs the same treatment the capacity cap got: a
19+// deleting flag on the course row that the enroll's conditional UPDATE checks.
15 pub(crate) static ENROLL_LOCK: Mutex<()> = Mutex::const_new(());20 pub(crate) static ENROLL_LOCK: Mutex<()> = Mutex::const_new(());
16 21
17 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]22 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
@@ -69,14 +74,14 @@ impl Enrollment {
69 }74 }
70 75
71 /// Enroll (idempotently) `user` into `course`. One row per (course, user),76 /// Enroll (idempotently) `user` into `course`. One row per (course, user),
72- /// keyed by a deterministic composite id so this is a single atomic UPSERT —77+ /// keyed by a deterministic composite id, so concurrent enrolls of the same
73- /// concurrent enrolls for the same pair converge on one row instead of78+ /// pair converge on one row instead of racing the unique index into a 500:
74- /// racing the unique index into a 500. When the course carries a capacity,79+ /// the loser of the `CREATE` reads the winner's row back and returns it.
75- /// a full roster refuses new members (409) — the whole check-then-write80+ /// When the course carries a capacity, a full roster refuses new members
76- /// runs under [`ENROLL_LOCK`], and the cap is re-derived from a fresh81+ /// (409) — the seat is taken by [`cap::claim`] on the course row, an atomic
77- /// course read inside it, since neither the transaction model nor a82+ /// single-record conditional write, so the cap holds across replicas and
78- /// caller-supplied course survives a concurrent capacity PATCH. An already83+ /// against a concurrent capacity PATCH alike. An already enrolled user is
79- /// enrolled user is returned as-is even when the roster is full.84+ /// returned as-is even when the roster is full, and never charged a seat.
80 pub async fn enroll(85 pub async fn enroll(
81 course: &CourseId,86 course: &CourseId,
82 user: &UserId,87 user: &UserId,
@@ -91,8 +96,14 @@ impl Enrollment {
91 .await?96 .await?
92 .ok_or(AppError::NotFound)?97 .ok_or(AppError::NotFound)?
93 .get_capacity();98 .get_capacity();
94- if let Some(capacity) = capacity99+ let seats = course.record();
95- && Self::list_for_course(course, db).await?.len() as i64 >= capacity100+ if !cap::claim(
101+ &seats,
102+ ENROLLMENT_COUNT_FIELD,
103+ capacity.unwrap_or(cap::UNLIMITED),
104+ db,
105+ )
106+ .await?
96 {107 {
97 return Err(AppError::Conflict("the course is full"));108 return Err(AppError::Conflict("the course is full"));
98 }109 }
@@ -102,11 +113,27 @@ impl Enrollment {
102 user: user.clone(),113 user: user.clone(),
103 enrolled_by: enrolled_by.clone(),114 enrolled_by: enrolled_by.clone(),
104 };115 };
105- let saved: Option<Enrollment> = db116+ // CREATE, not UPSERT: a duplicate has to be *seen*, or the pair's second
106- .upsert(enrollment.id.record())117+ // writer would silently keep the seat it claimed for a row that already
107- .content(enrollment)118+ // existed and the counter would drift above the roster forever.
108- .await?;119+ let saved: Result<Option<Enrollment>, _> =
109- saved.ok_or_else(|| AppError::Internal("failed to enroll user".into()))120+ db.create(enrollment.id.record()).content(enrollment).await;
121+ match saved {
122+ Ok(Some(saved)) => Ok(saved),
123+ Ok(None) => {
124+ cap::release(&seats, ENROLLMENT_COUNT_FIELD, db).await?;
125+ Err(AppError::Internal("failed to enroll user".into()))
126+ }
127+ Err(err) => {
128+ cap::release(&seats, ENROLLMENT_COUNT_FIELD, db).await?;
129+ if !lost_the_race(&err) {
130+ return Err(err.into());
131+ }
132+ Self::read_for_user(course, user, db)
133+ .await?
134+ .ok_or_else(|| AppError::Internal("failed to enroll user".into()))
135+ }
136+ }
110 }137 }
111 138
112 /// Some(_) iff `user` is enrolled in `course` — the grading gate.139 /// Some(_) iff `user` is enrolled in `course` — the grading gate.
@@ -136,23 +163,30 @@ impl Enrollment {
136 163
137 pub async fn list_for_course(164 pub async fn list_for_course(
138 course: &CourseId,165 course: &CourseId,
166+ limit: Option<i64>,
167+ offset: i64,
139 db: &Database,168 db: &Database,
140- ) -> Result<Vec<Enrollment>, AppError> {169+ ) -> Result<(Vec<Enrollment>, i64), AppError> {
141- let mut result = db170+ PagedList::new("enrollment WHERE course = $course", "ORDER BY id DESC")
142- .query("SELECT * FROM enrollment WHERE course = $course ORDER BY id DESC")171+ .bind("course", course.record())
143- .bind(("course", course.record()))172+ .run(limit, offset, db)
144- .await?173+ .await
145- .check()?;
146- Ok(result.take::<Vec<Enrollment>>(0)?)
147 }174 }
148 175
149 /// Drop every enrollment `user` holds, across all courses. Only students176 /// Drop every enrollment `user` holds, across all courses. Only students
150 /// enroll, so promotion out of `student` calls this to clear the rosters.177 /// enroll, so promotion out of `student` calls this to clear the rosters.
151 pub async fn delete_for_user(user: &UserId, db: &Database) -> Result<(), AppError> {178 pub async fn delete_for_user(user: &UserId, db: &Database) -> Result<(), AppError> {
152- db.query("DELETE enrollment WHERE user = $usr")179+ db.query(
153- .bind(("usr", user.record()))180+ "BEGIN TRANSACTION;
154- .await?181+ LET $gone = (DELETE enrollment WHERE user = $usr RETURN BEFORE);
155- .check()?;182+ FOR $row IN ($gone ?? []) {
183+ UPDATE $row.course SET enrollment_count = math::max([(enrollment_count ?? 0) - 1, 0]);
184+ };
185+ COMMIT TRANSACTION;",
186+ )
187+ .bind(("usr", user.record()))
188+ .await?
189+ .check()?;
156 Ok(())190 Ok(())
157 }191 }
158 192
@@ -161,12 +195,20 @@ impl Enrollment {
161 user: &UserId,195 user: &UserId,
162 db: &Database,196 db: &Database,
163 ) -> Result<Option<Enrollment>, AppError> {197 ) -> Result<Option<Enrollment>, AppError> {
198+ // The seat comes back in the same transaction as the row that held it,
199+ // so nothing but a lost transaction can drift the counter.
164 let mut result = db200 let mut result = db
165- .query("DELETE enrollment WHERE course = $course AND user = $usr RETURN BEFORE")201+ .query(
202+ "BEGIN TRANSACTION;
203+ LET $gone = (DELETE enrollment WHERE course = $course AND user = $usr RETURN BEFORE);
204+ UPDATE $course SET enrollment_count = math::max([(enrollment_count ?? 0) - array::len($gone), 0]);
205+ RETURN $gone;
206+ COMMIT TRANSACTION;",
207+ )
166 .bind(("course", course.record()))208 .bind(("course", course.record()))
167 .bind(("usr", user.record()))209 .bind(("usr", user.record()))
168 .await?210 .await?
169 .check()?;211 .check()?;
170- Ok(result.take::<Vec<Enrollment>>(0)?.into_iter().next())212+ Ok(result.take::<Vec<Enrollment>>(3)?.into_iter().next())
171 }213 }
172 }214 }
src/domain/event.rsmodified+12 -22
@@ -1,7 +1,6 @@
1 // `Value` looks unused but is load-bearing: the `SurrealValue` derive on the1 // `Value` looks unused but is load-bearing: the `SurrealValue` derive on the
2 // tagged `EventAudience` enum expands to code that names `Value` unqualified.2 // tagged `EventAudience` enum expands to code that names `Value` unqualified.
3 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value};3 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value};
4-use tokio::sync::Mutex;
5 use ulid::Ulid;4 use ulid::Ulid;
6 5
7 use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN};6 use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN};
@@ -11,25 +10,11 @@ use crate::domain::enrollment::Enrollment;
11 use crate::domain::field_update::FieldUpdate;10 use crate::domain::field_update::FieldUpdate;
12 use crate::domain::registration::Registration;11 use crate::domain::registration::Registration;
13 use crate::domain::role::Role;12 use crate::domain::role::Role;
14-use crate::domain::timestamp::Timestamp;13+use crate::domain::timestamp::{Timestamp, range_error};
15 use crate::domain::user::{User, UserId};14 use crate::domain::user::{User, UserId};
16 use crate::error::{AppError, ValidationError};15 use crate::error::{AppError, ValidationError};
17 use crate::validate::{validate_optional, validate_required};16 use crate::validate::{validate_optional, validate_required};
18 17
19-/// Serializes the schedule-range check against the write it guards, exactly as
20-/// `TERM_LOCK` does for terms: `starts_at <= ends_at` is a cross-field check,
21-/// so a partial PATCH validates the end it carries against the *stored* other
22-/// end — two such PATCHes, each fine on its own snapshot, would otherwise
23-/// commit an inverted range between them. A PATCH that moves neither end
24-/// checks nothing cross-field and stays lock-free.
25-///
26-/// Lock order: this is a leaf — the only path that takes it (`PATCH
27-/// /events/{id}`) takes no other lock, and no path that holds `REGISTER_LOCK`,
28-/// `ENROLL_LOCK`, `TERM_LOCK`, `EXAM_LOCK` or any other takes this one, so it
29-/// cannot sit in a cycle. Should a future path need both, take the other lock
30-/// first and this one innermost.
31-pub(crate) static EVENT_LOCK: Mutex<()> = Mutex::const_new(());
32-
33 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]18 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
34 pub struct EventId(RecordId);19 pub struct EventId(RecordId);
35 20
@@ -140,8 +125,9 @@ impl EventAudience {
140 /// are kept; the caller degrades their display like any stale reference.125 /// are kept; the caller degrades their display like any stale reference.
141 pub async fn members(&self, event: &EventId, db: &Database) -> Result<Vec<UserId>, AppError> {126 pub async fn members(&self, event: &EventId, db: &Database) -> Result<Vec<UserId>, AppError> {
142 match self {127 match self {
143- EventAudience::School => Ok(User::list_all(db)128+ EventAudience::School => Ok(User::list_all(None, 0, db)
144 .await?129 .await?
130+ .0
145 .iter()131 .iter()
146 .map(|user| user.get_id().clone())132 .map(|user| user.get_id().clone())
147 .collect()),133 .collect()),
@@ -150,11 +136,14 @@ impl EventAudience {
150 .iter()136 .iter()
151 .map(|user| user.get_id().clone())137 .map(|user| user.get_id().clone())
152 .collect()),138 .collect()),
153- EventAudience::Course { course } => Ok(Enrollment::list_for_course(course, db)139+ EventAudience::Course { course } => {
154- .await?140+ Ok(Enrollment::list_for_course(course, None, 0, db)
155- .iter()141+ .await?
156- .map(|enrollment| enrollment.get_user().clone())142+ .0
157- .collect()),143+ .iter()
144+ .map(|enrollment| enrollment.get_user().clone())
145+ .collect())
146+ }
158 EventAudience::Registration { .. } => Ok(Registration::list_for_event(event, db)147 EventAudience::Registration { .. } => Ok(Registration::list_for_event(event, db)
159 .await?148 .await?
160 .iter()149 .iter()
@@ -287,6 +276,7 @@ impl Event {
287 .set("audience", audience)276 .set("audience", audience)
288 .set("starts_at", starts_at)277 .set("starts_at", starts_at)
289 .set("ends_at", ends_at)278 .set("ends_at", ends_at)
279+ .ordered("starts_at", "ends_at", range_error())
290 .run::<Event>(db)280 .run::<Event>(db)
291 .await281 .await
292 }282 }
src/domain/exam.rsmodified+212 -5
@@ -10,6 +10,15 @@ use crate::domain::settings::ExamKindDef;
10 use crate::domain::timestamp::Timestamp;10 use crate::domain::timestamp::Timestamp;
11 use crate::domain::user::UserId;11 use crate::domain::user::UserId;
12 use crate::error::{AppError, ValidationError};12 use crate::error::{AppError, ValidationError};
13+
14+/// The one spelling of the re-draft refusal, shared by the handler's
15+/// pre-flight gate and the in-transaction guard that re-makes it at write
16+/// time — a client cannot tell which of the two refused.
17+pub(crate) fn redraft_error() -> AppError {
18+ AppError::Conflict(
19+ "cannot turn a published exam back into a draft after attempts or results exist",
20+ )
21+}
13 use crate::validate::{22 use crate::validate::{
14 validate_attempt_limit, validate_exam_duration, validate_exam_mode, validate_optional,23 validate_attempt_limit, validate_exam_duration, validate_exam_mode, validate_optional,
15 validate_required,24 validate_required,
@@ -444,7 +453,17 @@ impl Exam {
444 clippy::too_many_arguments,453 clippy::too_many_arguments,
445 reason = "mirrors the sibling entities' update(field, field, ..) shape"454 reason = "mirrors the sibling entities' update(field, field, ..) shape"
446 )]455 )]
447- pub async fn update(456+ /// Save the merged exam, but only while the row still reads as the
457+ /// snapshot the caller merged over — `None` means a concurrent PATCH
458+ /// landed in between and nothing was written: re-read, re-merge, retry.
459+ ///
460+ /// Every column this write replaces is in the guard, which is what makes
461+ /// the whole-row `CONTENT` save safe without a lock held across the
462+ /// handler's read: the compare-and-set refuses precisely when that save
463+ /// would have reverted somebody. `course`/`creator` are not editable and
464+ /// ride along unchanged. Same shape as
465+ /// [`crate::domain::settings::Settings::save_if_unchanged`].
466+ pub async fn update_if_unchanged(
448 mut self,467 mut self,
449 title: ExamTitle,468 title: ExamTitle,
450 description: ExamDescription,469 description: ExamDescription,
@@ -455,7 +474,26 @@ impl Exam {
455 allow_review: bool,474 allow_review: bool,
456 draft: bool,475 draft: bool,
457 db: &Database,476 db: &Database,
458- ) -> Result<Exam, AppError> {477+ ) -> Result<Option<Exam>, AppError> {
478+ // Re-drafting hides an exam: it must be refused while any sitting or
479+ // mark exists, and that check has to be *in this transaction*. Holding
480+ // it under a lock outside would only order the two writers inside one
481+ // process — and it did not even do that, since grading takes the reader
482+ // lease this write does.
483+ let redraft = draft && !self.draft;
484+ let was = (
485+ self.title.clone(),
486+ self.description.clone(),
487+ self.kind.clone(),
488+ self.mode.clone(),
489+ self.starts_at,
490+ self.ends_at,
491+ self.duration_ms,
492+ self.max_attempts,
493+ self.allow_rejoin,
494+ self.allow_review,
495+ self.draft,
496+ );
459 self.title = title;497 self.title = title;
460 self.description = description;498 self.description = description;
461 self.kind = kind;499 self.kind = kind;
@@ -467,9 +505,56 @@ impl Exam {
467 self.allow_rejoin = allow_rejoin;505 self.allow_rejoin = allow_rejoin;
468 self.allow_review = allow_review;506 self.allow_review = allow_review;
469 self.draft = draft;507 self.draft = draft;
470- // whole-row-save-ok: the only caller takes EXAM_LOCK.write() before the row read (web/exams.rs:354)508+ // whole-row-save-ok: the WHERE below pins every column this replaces to
471- let updated: Option<Exam> = db.update(self.id.record()).content(self).await?;509+ // the caller's snapshot, so no concurrent write can be reverted
472- updated.ok_or(AppError::NotFound)510+ let mut result = db
511+ .query(
512+ "BEGIN TRANSACTION;
513+ IF $redraft AND (
514+ array::len((SELECT VALUE id FROM exam_attempt WHERE exam = $id LIMIT 1)) > 0
515+ OR array::len((SELECT VALUE id FROM exam_result WHERE exam = $id LIMIT 1)) > 0
516+ ) { THROW 'exam_redraft' };
517+ UPDATE $id CONTENT $new
518+ WHERE title = $was_title AND description = $was_description
519+ AND kind = $was_kind AND mode = $was_mode
520+ AND starts_at = $was_starts AND ends_at = $was_ends
521+ AND duration_ms = $was_duration
522+ AND max_attempts = $was_max_attempts
523+ AND allow_rejoin = $was_allow_rejoin
524+ AND allow_review = $was_allow_review
525+ AND draft = $was_draft
526+ RETURN AFTER;
527+ COMMIT TRANSACTION;",
528+ )
529+ .bind(("redraft", redraft))
530+ .bind(("id", self.id.record()))
531+ .bind(("was_title", was.0))
532+ .bind(("was_description", was.1))
533+ .bind(("was_kind", was.2))
534+ .bind(("was_mode", was.3))
535+ .bind(("was_starts", was.4))
536+ .bind(("was_ends", was.5))
537+ .bind(("was_duration", was.6))
538+ .bind(("was_max_attempts", was.7))
539+ .bind(("was_allow_rejoin", was.8))
540+ .bind(("was_allow_review", was.9))
541+ .bind(("was_draft", was.10))
542+ .bind(("new", self))
543+ .await?;
544+ // An aborted transaction errors every slot; only the THROW's names the
545+ // marker (the `frozen_check` treatment).
546+ let mut errors = result.take_errors();
547+ if errors
548+ .values()
549+ .any(|error| error.to_string().contains("exam_redraft"))
550+ {
551+ return Err(redraft_error());
552+ }
553+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
554+ return Err(error.into());
555+ }
556+ // BEGIN and the IF take a slot each.
557+ Ok(result.take::<Vec<Exam>>(2)?.into_iter().next())
473 }558 }
474 559
475 /// Delete the exam and cascade-remove its result, attempt, question,560 /// Delete the exam and cascade-remove its result, attempt, question,
@@ -516,6 +601,128 @@ impl Exam {
516 mod tests {601 mod tests {
517 use super::*;602 use super::*;
518 603
604+ /// An unscheduled published exam, the minimum this file's write tests need.
605+ async fn published(db: &Database) -> Exam {
606+ let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
607+ .get_exam_kinds()
608+ .to_vec();
609+ Exam::create(
610+ &UserId::generate(),
611+ &CourseId::generate(),
612+ ExamTitle::try_new("midterm").unwrap(),
613+ ExamDescription::try_new("").unwrap(),
614+ ExamKind::try_new("midterm", &allowed).unwrap(),
615+ ExamSchedule::try_new(None, None, None, None).unwrap(),
616+ ExamAttemptLimit::try_new(1).unwrap(),
617+ true,
618+ false,
619+ false,
620+ db,
621+ )
622+ .await
623+ .unwrap()
624+ }
625+
626+ fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) {
627+ (
628+ exam.get_title().clone(),
629+ exam.get_description().clone(),
630+ exam.get_kind().clone(),
631+ ExamSchedule::try_new(None, None, None, None).unwrap(),
632+ )
633+ }
634+
635+ /// The bite test for the compare-and-set that replaced the writer lease on
636+ /// `PATCH /exams/{id}`: a merge built on a snapshot the row has moved past
637+ /// must be refused (the handler then re-reads and re-merges), never
638+ /// written over somebody else's edit. Asserts the *stored* row.
639+ #[tokio::test]
640+ async fn a_merge_built_on_a_stale_snapshot_is_refused() {
641+ let db = crate::database::init_mem().await.unwrap();
642+ let stale = published(&db).await;
643+ let (_, description, kind, schedule) = edit(&stale);
644+ let landed = stale
645+ .clone()
646+ .update_if_unchanged(
647+ ExamTitle::try_new("theirs").unwrap(),
648+ description,
649+ kind,
650+ schedule,
651+ ExamAttemptLimit::try_new(1).unwrap(),
652+ true,
653+ false,
654+ false,
655+ &db,
656+ )
657+ .await
658+ .unwrap();
659+ assert!(landed.is_some(), "the first write is on a fresh snapshot");
660+
661+ let (_, description, kind, schedule) = edit(&stale);
662+ let refused = stale
663+ .update_if_unchanged(
664+ ExamTitle::try_new("mine").unwrap(),
665+ description,
666+ kind,
667+ schedule,
668+ ExamAttemptLimit::try_new(1).unwrap(),
669+ true,
670+ false,
671+ false,
672+ &db,
673+ )
674+ .await
675+ .unwrap();
676+ assert!(refused.is_none(), "a stale merge must not be written");
677+ let stored = Exam::read(landed.unwrap().get_id(), &db)
678+ .await
679+ .unwrap()
680+ .unwrap();
681+ assert_eq!(stored.get_title().as_str(), "theirs");
682+ }
683+
684+ /// The bite test for the re-draft guard now living *inside* the update's
685+ /// transaction: a mark that lands after the handler's pre-flight gate (the
686+ /// grade path is a lock reader, exactly like this one) must still stop the
687+ /// exam from being hidden.
688+ #[tokio::test]
689+ async fn re_drafting_is_refused_by_the_write_itself_once_a_mark_exists() {
690+ use crate::domain::exam_result::{ExamResult, Mark};
691+ let db = crate::database::init_mem().await.unwrap();
692+ let exam = published(&db).await;
693+ let student = UserId::generate();
694+ ExamResult::grade(
695+ exam.get_id(),
696+ &student,
697+ 1,
698+ Mark::try_new(80).unwrap(),
699+ &UserId::generate(),
700+ &db,
701+ )
702+ .await
703+ .unwrap();
704+
705+ let (title, description, kind, schedule) = edit(&exam);
706+ let refused = exam
707+ .clone()
708+ .update_if_unchanged(
709+ title,
710+ description,
711+ kind,
712+ schedule,
713+ ExamAttemptLimit::try_new(1).unwrap(),
714+ true,
715+ false,
716+ true,
717+ &db,
718+ )
719+ .await
720+ .expect_err("a graded exam cannot be re-drafted");
721+ assert!(refused.to_string().contains("back into a draft"));
722+ let stored = Exam::read(exam.get_id(), &db).await.unwrap().unwrap();
723+ assert!(!stored.is_draft(), "nothing may have been written");
724+ }
725+
519 #[tokio::test]726 #[tokio::test]
520 async fn title_is_required() {727 async fn title_is_required() {
521 assert!(ExamTitle::try_new("midterm").is_ok());728 assert!(ExamTitle::try_new("midterm").is_ok());
src/domain/exam_answer.rsmodified+5 -11
@@ -4,6 +4,7 @@ use crate::constant::{EXAM_ANSWER_TABLE, MAX_ANSWER_TEXT_LEN};
4 use crate::database::Database;4 use crate::database::Database;
5 use crate::domain::exam::ExamId;5 use crate::domain::exam::ExamId;
6 use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId};6 use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId};
7+use crate::domain::key;
7 use crate::domain::timestamp::Timestamp;8 use crate::domain::timestamp::Timestamp;
8 use crate::domain::user::UserId;9 use crate::domain::user::UserId;
9 use crate::error::{AppError, ValidationError};10 use crate::error::{AppError, ValidationError};
@@ -13,20 +14,13 @@ use crate::validate::validate_optional;
13 pub struct ExamAnswerId(RecordId);14 pub struct ExamAnswerId(RecordId);
14 15
15 impl ExamAnswerId {16 impl ExamAnswerId {
16- /// A deterministic id for the (question, user, seq) triple — the question17+ /// A deterministic id for the (question, user, seq) triple. Saving is a
17- /// key is its own ULID, so the triple key is unambiguous. Saving is a
18 /// single atomic UPSERT keyed by seq: re-answering *within a sitting*18 /// single atomic UPSERT keyed by seq: re-answering *within a sitting*
19 /// overwrites its one row, but a retake's `seq` writes a new row, so every19 /// overwrites its one row, but a retake's `seq` writes a new row, so every
20- /// sitting keeps its own answer history. The first sitting keeps the20+ /// sitting keeps its own answer history. See [`key::sitting`] for the key
21- /// historical `{question}_{user}` shape (rows written before history21+ /// shape and why the first sitting stays bare.
22- /// existed stay addressable); later sittings append their number. ULID
23- /// keys are alphanumeric, so `_` is an unambiguous joiner.
24 pub fn composite(question: &ExamQuestionId, user: &UserId, seq: i64) -> Self {22 pub fn composite(question: &ExamQuestionId, user: &UserId, seq: i64) -> Self {
25- let key = if seq == 1 {23+ let key = key::sitting(question.key(), user.key(), seq);
26- format!("{}_{}", question.key(), user.key())
27- } else {
28- format!("{}_{}_{}", question.key(), user.key(), seq)
29- };
30 Self(RecordId::new(EXAM_ANSWER_TABLE, key))24 Self(RecordId::new(EXAM_ANSWER_TABLE, key))
31 }25 }
32 26
src/domain/exam_attempt.rsmodified+66 -12
@@ -4,27 +4,30 @@ use crate::constant::EXAM_ATTEMPT_TABLE;
4 use crate::database::Database;4 use crate::database::Database;
5 use crate::domain::exam::Exam;5 use crate::domain::exam::Exam;
6 use crate::domain::exam::ExamId;6 use crate::domain::exam::ExamId;
7+use crate::domain::key;
7 use crate::domain::timestamp::Timestamp;8 use crate::domain::timestamp::Timestamp;
8 use crate::domain::user::UserId;9 use crate::domain::user::UserId;
9 use crate::error::AppError;10 use crate::error::AppError;
10 11
12+/// The `THROW` marker the freeze gate aborts with, and the one 409 both it and
13+/// the handler's pre-flight check answer with — a client cannot tell which of
14+/// the two refused.
15+const FROZEN_MARK: &str = "questions_frozen";
16+
17+pub(crate) fn frozen_error() -> AppError {
18+ AppError::Conflict("cannot change questions after attempts have started")
19+}
20+
11 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]21 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
12 pub struct ExamAttemptId(RecordId);22 pub struct ExamAttemptId(RecordId);
13 23
14 impl ExamAttemptId {24 impl ExamAttemptId {
15- /// A deterministic id for the (exam, user, seq) triple. The same triple25+ /// A deterministic id for the (exam, user, seq) triple, so sitting `seq`
16- /// always maps to the same record id, so sitting `seq` exists at most once26+ /// exists at most once by construction — a concurrent double "start" races
17- /// by construction — a concurrent double "start" races on the same id and27+ /// on the same id and exactly one create wins. See [`key::sitting`] for the
18- /// exactly one create wins. The first sitting keeps the historical28+ /// key shape and why the first sitting stays bare.
19- /// `{exam}_{user}` shape (rows written before retakes existed stay
20- /// addressable); later sittings append their number. ULID keys are
21- /// alphanumeric, so `_` is an unambiguous joiner.
22 pub fn composite(exam: &ExamId, user: &UserId, seq: i64) -> Self {29 pub fn composite(exam: &ExamId, user: &UserId, seq: i64) -> Self {
23- let key = if seq == 1 {30+ let key = key::sitting(exam.key(), user.key(), seq);
24- format!("{}_{}", exam.key(), user.key())
25- } else {
26- format!("{}_{}_{}", exam.key(), user.key(), seq)
27- };
28 Self(RecordId::new(EXAM_ATTEMPT_TABLE, key))31 Self(RecordId::new(EXAM_ATTEMPT_TABLE, key))
29 }32 }
30 33
@@ -311,6 +314,57 @@ impl ExamAttempt {
311 Ok(result.take::<Vec<ExamAttempt>>(0)?)314 Ok(result.take::<Vec<ExamAttempt>>(0)?)
312 }315 }
313 316
317+ /// Wrap `statements` in a transaction that refuses to run them at all once
318+ /// `$freeze_exam` has an attempt — the freeze gate, made atomic with the
319+ /// write it guards instead of merely preceding it. Callers bind
320+ /// `freeze_exam` and read their own results from
321+ /// [`Self::FROZEN_SLOT`] onwards (`BEGIN` and the `IF` take a slot each).
322+ ///
323+ /// This replaces a process-wide `EXAM_LOCK.write()` held across the check
324+ /// and the write. That lock served one process; the gate serves the
325+ /// database, so a question edit on replica A can no longer sail past an
326+ /// attempt started on replica B.
327+ //
328+ // ponytail: the count and a concurrent `CREATE exam_attempt` are still not
329+ // serialized against each other — SurrealDB does not conflict-check a
330+ // cross-record count (the write skew `domain::cap` exists for), so an
331+ // attempt landing in the same instant as an edit can still interleave
332+ // either way. The mutex this replaces closed that inside one process only,
333+ // and there are two, so nothing is lost. Closing it properly means the
334+ // cap.rs shape: an attempt counter on the exam row, incremented by the
335+ // attempt create, and the write conditioned on `count ?? 0 = 0`.
336+ pub(crate) fn unfrozen(statements: &str) -> String {
337+ format!(
338+ "BEGIN TRANSACTION;
339+ IF array::len((SELECT VALUE id FROM exam_attempt \
340+ WHERE exam = $freeze_exam LIMIT 1)) > 0 {{ THROW '{FROZEN_MARK}' }};
341+ {statements}
342+ COMMIT TRANSACTION;"
343+ )
344+ }
345+
346+ /// The first slot a [`Self::unfrozen`] caller's own statements land in.
347+ pub(crate) const FROZEN_SLOT: usize = 2;
348+
349+ /// Turn a gate abort into the 409 the pre-flight check answers with, so
350+ /// losing the race and failing the check read identically to a client.
351+ /// An aborted transaction errors *every* slot with a generic "not
352+ /// executed" — only the `THROW`'s own slot names the marker, so every slot
353+ /// is scanned.
354+ pub(crate) fn frozen_check(result: &mut surrealdb::IndexedResults) -> Result<(), AppError> {
355+ let mut errors = result.take_errors();
356+ if errors
357+ .values()
358+ .any(|error| error.to_string().contains(FROZEN_MARK))
359+ {
360+ return Err(frozen_error());
361+ }
362+ match errors.drain().map(|(_, error)| error).next() {
363+ Some(error) => Err(error.into()),
364+ None => Ok(()),
365+ }
366+ }
367+
314 /// Whether anyone has started this exam — the gate that freezes `mode`368 /// Whether anyone has started this exam — the gate that freezes `mode`
315 /// edits once an attempt exists.369 /// edits once an attempt exists.
316 pub async fn any_for_exam(exam: &ExamId, db: &Database) -> Result<bool, AppError> {370 pub async fn any_for_exam(exam: &ExamId, db: &Database) -> Result<bool, AppError> {
src/domain/exam_question.rsmodified+74 -29
@@ -8,7 +8,9 @@ use crate::constant::{
8 use crate::database::Database;8 use crate::database::Database;
9 use crate::domain::bank_question::BankQuestionId;9 use crate::domain::bank_question::BankQuestionId;
10 use crate::domain::exam::ExamId;10 use crate::domain::exam::ExamId;
11+use crate::domain::exam_attempt::ExamAttempt;
11 use crate::domain::monotonic_id::next_ulid;12 use crate::domain::monotonic_id::next_ulid;
13+use crate::domain::page::PagedList;
12 use crate::domain::subject::SubjectId;14 use crate::domain::subject::SubjectId;
13 use crate::error::{AppError, ValidationError};15 use crate::error::{AppError, ValidationError};
14 use crate::validate::{validate_question_kind, validate_question_points, validate_required};16 use crate::validate::{validate_question_kind, validate_question_points, validate_required};
@@ -404,9 +406,21 @@ impl ExamQuestion {
404 // An insert never banks anything: only a to-bank save writes this.406 // An insert never banks anything: only a to-bank save writes this.
405 banked_as: None,407 banked_as: None,
406 };408 };
407- let created: Option<ExamQuestion> =409+ // The freeze gate rides in the same transaction as the insert: a
408- db.create(question.id.record()).content(question).await?;410+ // question cannot appear under an exam somebody has already started,
409- created.ok_or_else(|| AppError::Internal("failed to create exam question".into()))411+ // whichever replica the two requests hit.
412+ let mut result = db
413+ .query(ExamAttempt::unfrozen("CREATE $id CONTENT $question;"))
414+ .bind(("freeze_exam", exam.record()))
415+ .bind(("id", question.id.record()))
416+ .bind(("question", question))
417+ .await?;
418+ ExamAttempt::frozen_check(&mut result)?;
419+ result
420+ .take::<Vec<ExamQuestion>>(ExamAttempt::FROZEN_SLOT)?
421+ .into_iter()
422+ .next()
423+ .ok_or_else(|| AppError::Internal("failed to create exam question".into()))
410 }424 }
411 425
412 pub async fn read(426 pub async fn read(
@@ -419,14 +433,14 @@ impl ExamQuestion {
419 /// The exam's questions in presentation order (ULID ids sort by creation).433 /// The exam's questions in presentation order (ULID ids sort by creation).
420 pub async fn list_for_exam(434 pub async fn list_for_exam(
421 exam: &ExamId,435 exam: &ExamId,
436+ limit: Option<i64>,
437+ offset: i64,
422 db: &Database,438 db: &Database,
423- ) -> Result<Vec<ExamQuestion>, AppError> {439+ ) -> Result<(Vec<ExamQuestion>, i64), AppError> {
424- let mut result = db440+ PagedList::new("exam_question WHERE exam = $ex", "ORDER BY id ASC")
425- .query("SELECT * FROM exam_question WHERE exam = $ex ORDER BY id ASC")441+ .bind("ex", exam.record())
426- .bind(("ex", exam.record()))442+ .run(limit, offset, db)
427- .await?443+ .await
428- .check()?;
429- Ok(result.take::<Vec<ExamQuestion>>(0)?)
430 }444 }
431 445
432 /// Whether any question anywhere references `subject` — the gate that446 /// Whether any question anywhere references `subject` — the gate that
@@ -440,23 +454,44 @@ impl ExamQuestion {
440 Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())454 Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
441 }455 }
442 456
457+ /// Write the editable fields, refused outright once the exam has an
458+ /// attempt — the freeze gate is part of this transaction, not a check the
459+ /// caller made a moment earlier under a lock.
460+ ///
461+ /// Field-scoped, no longer a whole-row save. The row also carries
462+ /// `from_bank`/`banked_as`, which [`Self::link_banked_as`] writes from a
463+ /// *different* request: re-stating this snapshot's copy of them would
464+ /// revert a to-bank save that landed in between. That is exactly what the
465+ /// caller's `EXAM_LOCK.write()` used to order (inside one process), and
466+ /// naming the columns removes the need for any ordering at all.
443 pub async fn update(467 pub async fn update(
444- mut self,468+ self,
445 subject: SubjectId,469 subject: SubjectId,
446 text: QuestionText,470 text: QuestionText,
447 points: QuestionPoints,471 points: QuestionPoints,
448 spec: QuestionSpec,472 spec: QuestionSpec,
449 db: &Database,473 db: &Database,
450 ) -> Result<ExamQuestion, AppError> {474 ) -> Result<ExamQuestion, AppError> {
451- self.subject = subject;475+ let mut result = db
452- self.text = text;476+ .query(ExamAttempt::unfrozen(
453- self.points = points;477+ "UPDATE $id SET subject = $subject, text = $text, points = $points,
454- self.kind = spec.kind;478+ kind = $kind, choices = $choices, correct = $correct RETURN AFTER;",
455- self.choices = spec.choices;479+ ))
456- self.correct = spec.correct;480+ .bind(("freeze_exam", self.exam.record()))
457- // whole-row-save-ok: callers hold EXAM_LOCK.write() across the read and this write481+ .bind(("id", self.id.record()))
458- let updated: Option<ExamQuestion> = db.update(self.id.record()).content(self).await?;482+ .bind(("subject", subject.record()))
459- updated.ok_or(AppError::NotFound)483+ .bind(("text", text))
484+ .bind(("points", points))
485+ .bind(("kind", spec.kind))
486+ .bind(("choices", spec.choices))
487+ .bind(("correct", spec.correct))
488+ .await?;
489+ ExamAttempt::frozen_check(&mut result)?;
490+ result
491+ .take::<Vec<ExamQuestion>>(ExamAttempt::FROZEN_SLOT)?
492+ .into_iter()
493+ .next()
494+ .ok_or(AppError::NotFound)
460 }495 }
461 496
462 /// Point the question's `banked_as` at the bank template it was just saved497 /// Point the question's `banked_as` at the bank template it was just saved
@@ -495,16 +530,26 @@ impl ExamQuestion {
495 /// Delete the question and cascade-remove its answers and image rows, so530 /// Delete the question and cascade-remove its answers and image rows, so
496 /// neither can point at a missing question. The image *blobs* are the web531 /// neither can point at a missing question. The image *blobs* are the web
497 /// layer's to remove — it collects their names before calling this.532 /// layer's to remove — it collects their names before calling this.
533+ /// Refused once the exam has an attempt, in the same transaction as the
534+ /// delete — and the cascade now shares that transaction too, so a failure
535+ /// mid-way can no longer strand answers whose question survived.
498 pub async fn delete(self, db: &Database) -> Result<ExamQuestion, AppError> {536 pub async fn delete(self, db: &Database) -> Result<ExamQuestion, AppError> {
499- db.query(537+ let mut result = db
500- "DELETE exam_answer WHERE question = $q;538+ .query(ExamAttempt::unfrozen(
501- DELETE question_image WHERE question = $q;",539+ "DELETE exam_answer WHERE question = $q;
502- )540+ DELETE question_image WHERE question = $q;
503- .bind(("q", self.id.record()))541+ DELETE $q RETURN BEFORE;",
504- .await?542+ ))
505- .check()?;543+ .bind(("freeze_exam", self.exam.record()))
506- let deleted: Option<ExamQuestion> = db.delete(self.id.record()).await?;544+ .bind(("q", self.id.record()))
507- deleted.ok_or(AppError::NotFound)545+ .await?;
546+ ExamAttempt::frozen_check(&mut result)?;
547+ // Two cascade statements ahead of the delete itself.
548+ result
549+ .take::<Vec<ExamQuestion>>(ExamAttempt::FROZEN_SLOT + 2)?
550+ .into_iter()
551+ .next()
552+ .ok_or(AppError::NotFound)
508 }553 }
509 554
510 /// A question constructed without a database, for pure-function tests.555 /// A question constructed without a database, for pure-function tests.
src/domain/exam_result.rsmodified+43 -13
@@ -6,27 +6,27 @@ use crate::constant::EXAM_RESULT_TABLE;
6 use crate::database::Database;6 use crate::database::Database;
7 use crate::domain::course::CourseId;7 use crate::domain::course::CourseId;
8 use crate::domain::exam::ExamId;8 use crate::domain::exam::ExamId;
9+use crate::domain::key;
9 use crate::domain::user::UserId;10 use crate::domain::user::UserId;
10 use crate::error::{AppError, ValidationError};11 use crate::error::{AppError, ValidationError};
11 use crate::validate::validate_mark;12 use crate::validate::validate_mark;
12 13
14+/// The one spelling of "this exam is hidden", shared by the grade handler's
15+/// pre-flight gate and the in-transaction guard on the mark write.
16+pub(crate) fn draft_error() -> AppError {
17+ AppError::Conflict("this exam is a draft — publish it before grading")
18+}
19+
13 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]20 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
14 pub struct ExamResultId(RecordId);21 pub struct ExamResultId(RecordId);
15 22
16 impl ExamResultId {23 impl ExamResultId {
17 /// A deterministic id for the (exam, user, seq) triple — one mark row per24 /// A deterministic id for the (exam, user, seq) triple — one mark row per
18- /// sitting. The same triple always maps to the same record id, so grading a25+ /// sitting, so grading is a single atomic UPSERT with no find-then-insert
19- /// sitting is a single atomic UPSERT with no find-then-insert race. The26+ /// race. See [`key::sitting`] for the key shape and why the first sitting
20- /// first sitting keeps the historical `{exam}_{user}` shape (marks written27+ /// stays bare.
21- /// before per-attempt history existed stay addressable unchanged); later
22- /// sittings append their number. ULID keys are alphanumeric, so `_` is an
23- /// unambiguous joiner.
24 pub fn composite(exam: &ExamId, user: &UserId, seq: i64) -> Self {28 pub fn composite(exam: &ExamId, user: &UserId, seq: i64) -> Self {
25- let key = if seq == 1 {29+ let key = key::sitting(exam.key(), user.key(), seq);
26- format!("{}_{}", exam.key(), user.key())
27- } else {
28- format!("{}_{}_{}", exam.key(), user.key(), seq)
29- };
30 Self(RecordId::new(EXAM_RESULT_TABLE, key))30 Self(RecordId::new(EXAM_RESULT_TABLE, key))
31 }31 }
32 32
@@ -171,8 +171,38 @@ impl ExamResult {
171 mark,171 mark,
172 graded_by: graded_by.clone(),172 graded_by: graded_by.clone(),
173 };173 };
174- let saved: Option<ExamResult> = db.upsert(result.id.record()).content(result).await?;174+ // The "not a draft" gate rides in the same transaction as the mark, the
175- saved.ok_or_else(|| AppError::Internal("failed to record exam result".into()))175+ // mirror of the re-draft gate on `Exam::update_if_unchanged`: between
176+ // them, a mark and a re-draft racing each other can only ever leave one
177+ // of the two applied, whichever process either ran in. The caller's
178+ // pre-flight check answers the same 409 one round trip earlier.
179+ let mut written = db
180+ .query(
181+ "BEGIN TRANSACTION;
182+ IF (SELECT VALUE draft FROM ONLY $exam) { THROW 'exam_draft' };
183+ UPSERT $id CONTENT $result RETURN AFTER;
184+ COMMIT TRANSACTION;",
185+ )
186+ .bind(("exam", exam.record()))
187+ .bind(("id", result.id.record()))
188+ .bind(("result", result))
189+ .await?;
190+ let mut errors = written.take_errors();
191+ if errors
192+ .values()
193+ .any(|error| error.to_string().contains("exam_draft"))
194+ {
195+ return Err(draft_error());
196+ }
197+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
198+ return Err(error.into());
199+ }
200+ // BEGIN and the IF take a slot each.
201+ written
202+ .take::<Vec<ExamResult>>(2)?
203+ .into_iter()
204+ .next()
205+ .ok_or_else(|| AppError::Internal("failed to record exam result".into()))
176 }206 }
177 207
178 /// The user's graded results restricted to one course's exams — the raw208 /// The user's graded results restricted to one course's exams — the raw
src/domain/field_update.rsmodified+52 -3
@@ -32,6 +32,8 @@ pub struct FieldUpdate {
32 /// `field = $field` fragments, in the order they were set.32 /// `field = $field` fragments, in the order they were set.
33 assignments: Vec<String>,33 assignments: Vec<String>,
34 bindings: Vec<(String, Value)>,34 bindings: Vec<(String, Value)>,
35+ /// `(low, high, refusal)` for [`FieldUpdate::ordered`].
36+ ordered: Option<(&'static str, &'static str, AppError)>,
35 }37 }
36 38
37 impl FieldUpdate {39 impl FieldUpdate {
@@ -40,6 +42,7 @@ impl FieldUpdate {
40 id,42 id,
41 assignments: Vec::new(),43 assignments: Vec::new(),
42 bindings: Vec::new(),44 bindings: Vec::new(),
45+ ordered: None,
43 }46 }
44 }47 }
45 48
@@ -54,25 +57,71 @@ impl FieldUpdate {
54 self57 self
55 }58 }
56 59
60+ /// Refuse the write unless `low <= high` still holds on the *merged* row —
61+ /// the new value for an end this PATCH carries, the stored column for one it
62+ /// omits. Emitted as a `WHERE` on the same `UPDATE`, so the comparison the
63+ /// handler made against its snapshot is re-made by the database at write
64+ /// time, against the row as it is *then*: two PATCHes each moving one end,
65+ /// each fine on its own, cannot commit an inverted range between them. That
66+ /// is what an in-process `Mutex` used to buy, and this holds across replicas.
67+ ///
68+ /// Call it after the `.set()`s of both fields. A PATCH that moves neither
69+ /// end emits no guard at all (nothing to race), matching the lock window it
70+ /// replaces — so a pre-existing inverted row stays editable field by field.
71+ /// `NONE` on either side passes, exactly like
72+ /// [`crate::web::check_time_range`] skipping an absent end.
73+ #[must_use]
74+ pub fn ordered(mut self, low: &'static str, high: &'static str, refused: AppError) -> Self {
75+ self.ordered = Some((low, high, refused));
76+ self
77+ }
78+
57 /// Run the update and return the stored row. An empty request writes79 /// Run the update and return the stored row. An empty request writes
58 /// nothing at all and reads the row back unchanged.80 /// nothing at all and reads the row back unchanged.
59- pub async fn run<T: SurrealValue>(self, db: &Database) -> Result<T, AppError> {81+ pub async fn run<T: SurrealValue>(mut self, db: &Database) -> Result<T, AppError> {
60 if self.assignments.is_empty() {82 if self.assignments.is_empty() {
61 let row: Option<T> = db.select(self.id).await?;83 let row: Option<T> = db.select(self.id).await?;
62 return row.ok_or(AppError::NotFound);84 return row.ok_or(AppError::NotFound);
63 }85 }
86+ let (guard, mut refused) = match self.ordered.take() {
87+ // Both ends stored: name the bound variable for an end this request
88+ // set, the column for one it left alone.
89+ Some((low, high, err)) if self.is_set(low) || self.is_set(high) => {
90+ let side = |field: &str, set| {
91+ if set {
92+ format!("${field}")
93+ } else {
94+ field.into()
95+ }
96+ };
97+ let low = side(low, self.is_set(low));
98+ let high = side(high, self.is_set(high));
99+ (
100+ format!(" WHERE ({low} = NONE OR {high} = NONE OR {low} <= {high})"),
101+ Some(err),
102+ )
103+ }
104+ _ => (String::new(), None),
105+ };
64 let sets = self.assignments.join(", ");106 let sets = self.assignments.join(", ");
65 let mut query = db107 let mut query = db
66- .query(format!("UPDATE $id SET {sets} RETURN AFTER"))108+ .query(format!("UPDATE $id SET {sets}{guard} RETURN AFTER"))
67 .bind(("id", self.id));109 .bind(("id", self.id));
68 for (name, value) in self.bindings {110 for (name, value) in self.bindings {
69 query = query.bind((name, value));111 query = query.bind((name, value));
70 }112 }
71 let mut result = query.await?.check()?;113 let mut result = query.await?.check()?;
114+ // No row back means the guard bit (or, in the window after the handler's
115+ // read, the row was deleted — the guard cannot tell the two apart, and
116+ // reports the refusal it was given).
72 result117 result
73 .take::<Vec<T>>(0)?118 .take::<Vec<T>>(0)?
74 .into_iter()119 .into_iter()
75 .next()120 .next()
76- .ok_or(AppError::NotFound)121+ .ok_or_else(|| refused.take().unwrap_or(AppError::NotFound))
122+ }
123+
124+ fn is_set(&self, field: &str) -> bool {
125+ self.bindings.iter().any(|(name, _)| name == field)
77 }126 }
78 }127 }
src/domain/homework_file.rsmodified+49 -22
@@ -9,11 +9,13 @@
9 //! upload, row before blob on delete); this module owns the rows.9 //! upload, row before blob on delete); this module owns the rows.
10 10
11 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};11 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
12-use tokio::sync::Mutex;
13 use ulid::Ulid;12 use ulid::Ulid;
14 13
15-use crate::constant::{HOMEWORK_FILE_TABLE, MAX_HOMEWORK_FILES_PER_SUBMISSION};14+use crate::constant::{
15+ HOMEWORK_FILE_TABLE, MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD,
16+};
16 use crate::database::Database;17 use crate::database::Database;
18+use crate::domain::cap;
17 use crate::domain::course::CourseId;19 use crate::domain::course::CourseId;
18 use crate::domain::homework::HomeworkId;20 use crate::domain::homework::HomeworkId;
19 use crate::domain::homework_submission::HomeworkSubmissionId;21 use crate::domain::homework_submission::HomeworkSubmissionId;
@@ -21,14 +23,6 @@ use crate::domain::note_file::{FileContentType, FileName};
21 use crate::domain::timestamp::Timestamp;23 use crate::domain::timestamp::Timestamp;
22 use crate::error::AppError;24 use crate::error::AppError;
23 25
24-/// Serializes the files-per-submission cap check against the insert (see
25-/// [`HomeworkFile::insert`]). Its own lock, not note files' `FILE_CAP_LOCK`:
26-/// the two caps are independent counts and must not needlessly contend on one
27-/// mutex. This backend is the database's only writer, so one process-wide lock
28-/// suffices.
29-// ponytail: global lock, per-submission locks if uploads ever see real contention.
30-static SUBMISSION_FILE_LOCK: Mutex<()> = Mutex::const_new(());
31-
32 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]26 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
33 pub struct HomeworkFileId(RecordId);27 pub struct HomeworkFileId(RecordId);
34 28
@@ -117,23 +111,38 @@ impl HomeworkFile {
117 }111 }
118 112
119 /// Persist the row assembled by [`Self::new`], refusing once its submission113 /// Persist the row assembled by [`Self::new`], refusing once its submission
120- /// already holds [`MAX_HOMEWORK_FILES_PER_SUBMISSION`]. The114+ /// already holds [`MAX_HOMEWORK_FILES_PER_SUBMISSION`]. The slot is taken by
121- /// count-then-create runs under [`SUBMISSION_FILE_LOCK`]: a `BEGIN…COMMIT`115+ /// [`cap::claim`] on the submission row — a conditional single-record write,
122- /// can't enforce the cap because SurrealDB doesn't conflict-check a116+ /// the only guard that holds when the racing uploads are in two replicas,
123- /// cross-record count against a concurrent insert (write-skew), the same117+ /// the same story as `NoteFile::insert`.
124- /// story as `NoteFile::insert`.
125 pub async fn insert(self, db: &Database) -> Result<HomeworkFile, AppError> {118 pub async fn insert(self, db: &Database) -> Result<HomeworkFile, AppError> {
126- let _guard = SUBMISSION_FILE_LOCK.lock().await;119+ let submission = self.submission.record();
127- if Self::count_for_submission(&self.submission, db).await?120+ if !cap::claim(
128- >= MAX_HOMEWORK_FILES_PER_SUBMISSION121+ &submission,
122+ SUBMISSION_FILE_COUNT_FIELD,
123+ MAX_HOMEWORK_FILES_PER_SUBMISSION as i64,
124+ db,
125+ )
126+ .await?
129 {127 {
130 return Err(AppError::Conflict(128 return Err(AppError::Conflict(
131 "the submission already holds the maximum of 10 files — delete one first",129 "the submission already holds the maximum of 10 files — delete one first",
132 ));130 ));
133 }131 }
134 // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber132 // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber
135- let created: Option<HomeworkFile> = db.create(self.id.record()).content(self).await?;133+ let created: Result<Option<HomeworkFile>, _> =
136- created.ok_or_else(|| AppError::Internal("failed to create homework file".into()))134+ db.create(self.id.record()).content(self).await;
135+ match created {
136+ Ok(Some(created)) => Ok(created),
137+ Ok(None) => {
138+ cap::release(&submission, SUBMISSION_FILE_COUNT_FIELD, db).await?;
139+ Err(AppError::Internal("failed to create homework file".into()))
140+ }
141+ Err(err) => {
142+ cap::release(&submission, SUBMISSION_FILE_COUNT_FIELD, db).await?;
143+ Err(err.into())
144+ }
145+ }
137 }146 }
138 147
139 /// Read a file's row only if it belongs to `submission` — callers have148 /// Read a file's row only if it belongs to `submission` — callers have
@@ -230,9 +239,27 @@ impl HomeworkFile {
230 Ok(result.take::<Vec<String>>(0)?)239 Ok(result.take::<Vec<String>>(0)?)
231 }240 }
232 241
242+ /// Delete the row and give its slot back in the same transaction. The
243+ /// submission survives, so its counter has to be corrected; the cascades
244+ /// that delete the submission itself take the counter with it.
233 pub async fn delete(self, db: &Database) -> Result<HomeworkFile, AppError> {245 pub async fn delete(self, db: &Database) -> Result<HomeworkFile, AppError> {
234- let deleted: Option<HomeworkFile> = db.delete(self.id.record()).await?;246+ let mut result = db
235- deleted.ok_or(AppError::NotFound)247+ .query(
248+ "BEGIN TRANSACTION;
249+ LET $gone = (DELETE $id RETURN BEFORE);
250+ UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]);
251+ RETURN $gone;
252+ COMMIT TRANSACTION;",
253+ )
254+ .bind(("id", self.id.record()))
255+ .bind(("sub", self.submission.record()))
256+ .await?
257+ .check()?;
258+ result
259+ .take::<Vec<HomeworkFile>>(3)?
260+ .into_iter()
261+ .next()
262+ .ok_or(AppError::NotFound)
236 }263 }
237 }264 }
238 265
src/domain/key.rsadded+54 -0
@@ -0,0 +1,54 @@
1+//! Deterministic record keys shared by the per-sitting exam tables and the
2+//! image-slot tables.
3+
4+/// The key for a `(scope, user, seq)` triple, where `scope` is whatever the row
5+/// hangs off — an exam for attempts and results, a question for answers and
6+/// drawings. The same triple always maps to the same key, so "one row per
7+/// student per sitting" holds by construction: a concurrent double write races
8+/// on one id instead of creating two rows, and no unique index is needed.
9+///
10+/// The first sitting keeps the historical `{scope}_{user}` shape — rows written
11+/// before per-attempt history existed stay addressable, unchanged, forever — so
12+/// only later sittings carry their number. That bare-`seq == 1` case is
13+/// migration law, not a style choice: change it and every pre-history row
14+/// becomes unreachable. ULID keys are alphanumeric, so `_` is an unambiguous
15+/// joiner.
16+pub fn sitting(scope: &str, user: &str, seq: i64) -> String {
17+ if seq == 1 {
18+ format!("{scope}_{user}")
19+ } else {
20+ format!("{scope}_{user}_{seq}")
21+ }
22+}
23+
24+/// The key for one image slot on `owner` — `{owner}_q` for the thing's own
25+/// illustration, `{owner}_{choice id}` for one option's picture. Uniqueness per
26+/// slot needs no index this way, and keying by the option's *stable id* means
27+/// reordering the choice list moves no picture. `_` is not in Crockford base32
28+/// and a ULID is never `"q"`, so the two shapes can never collide — the rule
29+/// behind every image table's ids, spelled once.
30+pub fn slot(owner: &str, slot: Option<&str>) -> String {
31+ format!("{owner}_{}", slot.unwrap_or("q"))
32+}
33+
34+#[cfg(test)]
35+mod tests {
36+ use super::{sitting, slot};
37+
38+ #[test]
39+ fn a_slot_key_never_collides_with_the_illustration() {
40+ assert_eq!(slot("Q", None), "Q_q");
41+ assert_eq!(slot("Q", Some("01J8XZ")), "Q_01J8XZ");
42+ // A choice id is a ULID, so it can never be the literal "q".
43+ assert_ne!(slot("Q", Some("01J8XZ")), slot("Q", None));
44+ }
45+
46+ #[test]
47+ fn the_first_sitting_stays_bare_and_later_ones_are_numbered() {
48+ // Byte-for-byte the shape the four exam id types wrote before this
49+ // helper existed; a pre-history row is keyed by the bare pair.
50+ assert_eq!(sitting("EXAM", "USER", 1), "EXAM_USER");
51+ assert_eq!(sitting("EXAM", "USER", 2), "EXAM_USER_2");
52+ assert_eq!(sitting("Q", "U", 11), "Q_U_11");
53+ }
54+}
src/domain/meal_attendance.rsmodified+25 -24
@@ -20,6 +20,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
20 use crate::constant::{MEAL_ATTENDANCE_STATUSES, MEAL_ATTENDANCE_TABLE};20 use crate::constant::{MEAL_ATTENDANCE_STATUSES, MEAL_ATTENDANCE_TABLE};
21 use crate::database::Database;21 use crate::database::Database;
22 use crate::domain::menu::{MenuDate, MenuId};22 use crate::domain::menu::{MenuDate, MenuId};
23+use crate::domain::page::PagedList;
23 use crate::domain::timestamp::Timestamp;24 use crate::domain::timestamp::Timestamp;
24 use crate::domain::user::UserId;25 use crate::domain::user::UserId;
25 use crate::error::{AppError, ValidationError};26 use crate::error::{AppError, ValidationError};
@@ -131,17 +132,17 @@ impl MealAttendance {
131 /// The kitchen's list for one menu.132 /// The kitchen's list for one menu.
132 pub async fn list_for_menu(133 pub async fn list_for_menu(
133 menu: &MenuId,134 menu: &MenuId,
135+ limit: Option<i64>,
136+ offset: i64,
134 db: &Database,137 db: &Database,
135- ) -> Result<Vec<MealAttendance>, AppError> {138+ ) -> Result<(Vec<MealAttendance>, i64), AppError> {
136- let mut result = db139+ PagedList::new(
137- .query(140+ "meal_attendance WHERE menu = $menu",
138- "SELECT * FROM meal_attendance WHERE menu = $menu \141+ "ORDER BY marked_at DESC, id DESC",
139- ORDER BY marked_at DESC, id DESC",142+ )
140- )143+ .bind("menu", menu.record())
141- .bind(("menu", menu.record()))144+ .run(limit, offset, db)
142- .await?145+ .await
143- .check()?;
144- Ok(result.take::<Vec<MealAttendance>>(0)?)
145 }146 }
146 147
147 /// One student's marks, newest first. `from`/`to` are inclusive148 /// One student's marks, newest first. `from`/`to` are inclusive
@@ -153,21 +154,21 @@ impl MealAttendance {
153 student: &UserId,154 student: &UserId,
154 from: Option<&MenuDate>,155 from: Option<&MenuDate>,
155 to: Option<&MenuDate>,156 to: Option<&MenuDate>,
157+ limit: Option<i64>,
158+ offset: i64,
156 db: &Database,159 db: &Database,
157- ) -> Result<Vec<MealAttendance>, AppError> {160+ ) -> Result<(Vec<MealAttendance>, i64), AppError> {
158- let mut result = db161+ PagedList::new(
159- .query(162+ "meal_attendance WHERE student = $usr \
160- "SELECT * FROM meal_attendance WHERE student = $usr \163+ AND ($from = NONE OR menu.date >= $from) \
161- AND ($from = NONE OR menu.date >= $from) \164+ AND ($to = NONE OR menu.date <= $to)",
162- AND ($to = NONE OR menu.date <= $to) \165+ "ORDER BY marked_at DESC, id DESC",
163- ORDER BY marked_at DESC, id DESC",166+ )
164- )167+ .bind("usr", student.record())
165- .bind(("usr", student.record()))168+ .bind("from", from.map(|date| date.as_str().to_string()))
166- .bind(("from", from.map(|date| date.as_str().to_string())))169+ .bind("to", to.map(|date| date.as_str().to_string()))
167- .bind(("to", to.map(|date| date.as_str().to_string())))170+ .run(limit, offset, db)
168- .await?171+ .await
169- .check()?;
170- Ok(result.take::<Vec<MealAttendance>>(0)?)
171 }172 }
172 }173 }
173 174
src/domain/meal_booking.rsmodified+27 -23
@@ -25,6 +25,7 @@ use crate::constant::MEAL_BOOKING_TABLE;
25 use crate::database::Database;25 use crate::database::Database;
26 use crate::domain::meal_ledger::{LedgerAmount, MealLedger};26 use crate::domain::meal_ledger::{LedgerAmount, MealLedger};
27 use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId, MenuSlot};27 use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId, MenuSlot};
28+use crate::domain::page::PagedList;
28 use crate::domain::settings::{MealSlotDef, Settings};29 use crate::domain::settings::{MealSlotDef, Settings};
29 use crate::domain::timestamp::Timestamp;30 use crate::domain::timestamp::Timestamp;
30 use crate::domain::user::UserId;31 use crate::domain::user::UserId;
@@ -266,16 +267,19 @@ impl MealBooking {
266 }267 }
267 268
268 /// Every booking on a menu, cancelled ones included — the kitchen's list.269 /// Every booking on a menu, cancelled ones included — the kitchen's list.
269- pub async fn list_for_menu(menu: &MenuId, db: &Database) -> Result<Vec<MealBooking>, AppError> {270+ pub async fn list_for_menu(
270- let mut result = db271+ menu: &MenuId,
271- .query(272+ limit: Option<i64>,
272- "SELECT * FROM meal_booking WHERE menu = $menu \273+ offset: i64,
273- ORDER BY created_at DESC, id DESC",274+ db: &Database,
274- )275+ ) -> Result<(Vec<MealBooking>, i64), AppError> {
275- .bind(("menu", menu.record()))276+ PagedList::new(
276- .await?277+ "meal_booking WHERE menu = $menu",
277- .check()?;278+ "ORDER BY created_at DESC, id DESC",
278- Ok(result.take::<Vec<MealBooking>>(0)?)279+ )
280+ .bind("menu", menu.record())
281+ .run(limit, offset, db)
282+ .await
279 }283 }
280 284
281 /// The seats actually held — the capacity count.285 /// The seats actually held — the capacity count.
@@ -318,20 +322,20 @@ impl MealBooking {
318 /// dies with the link.322 /// dies with the link.
319 pub async fn list_for_students(323 pub async fn list_for_students(
320 students: &[UserId],324 students: &[UserId],
325+ limit: Option<i64>,
326+ offset: i64,
321 db: &Database,327 db: &Database,
322- ) -> Result<Vec<MealBooking>, AppError> {328+ ) -> Result<(Vec<MealBooking>, i64), AppError> {
323- let mut result = db329+ PagedList::new(
324- .query(330+ "meal_booking WHERE student IN $students",
325- "SELECT * FROM meal_booking WHERE student IN $students \331+ "ORDER BY created_at DESC, id DESC",
326- ORDER BY created_at DESC, id DESC",332+ )
327- )333+ .bind(
328- .bind((334+ "students",
329- "students",335+ students.iter().map(UserId::record).collect::<Vec<_>>(),
330- students.iter().map(UserId::record).collect::<Vec<_>>(),336+ )
331- ))337+ .run(limit, offset, db)
332- .await?338+ .await
333- .check()?;
334- Ok(result.take::<Vec<MealBooking>>(0)?)
335 }339 }
336 }340 }
337 341
src/domain/meal_ledger.rsmodified+13 -11
@@ -52,6 +52,7 @@ use crate::database::Database;
52 use crate::domain::meal_booking::{MealBooking, MealBookingId};52 use crate::domain::meal_booking::{MealBooking, MealBookingId};
53 use crate::domain::menu::MenuId;53 use crate::domain::menu::MenuId;
54 use crate::domain::menu_dish::MenuDish;54 use crate::domain::menu_dish::MenuDish;
55+use crate::domain::page::PagedList;
55 use crate::domain::timestamp::Timestamp;56 use crate::domain::timestamp::Timestamp;
56 use crate::domain::user::UserId;57 use crate::domain::user::UserId;
57 use crate::error::{AppError, ValidationError};58 use crate::error::{AppError, ValidationError};
@@ -436,17 +437,17 @@ impl MealLedger {
436 /// A student's whole statement, newest first.437 /// A student's whole statement, newest first.
437 pub async fn list_for_student(438 pub async fn list_for_student(
438 student: &UserId,439 student: &UserId,
440+ limit: Option<i64>,
441+ offset: i64,
439 db: &Database,442 db: &Database,
440- ) -> Result<Vec<MealLedger>, AppError> {443+ ) -> Result<(Vec<MealLedger>, i64), AppError> {
441- let mut result = db444+ PagedList::new(
442- .query(445+ "meal_ledger WHERE student = $student",
443- "SELECT * FROM meal_ledger WHERE student = $student \446+ "ORDER BY created_at DESC, id DESC",
444- ORDER BY created_at DESC, id DESC",447+ )
445- )448+ .bind("student", student.record())
446- .bind(("student", student.record()))449+ .run(limit, offset, db)
447- .await?450+ .await
448- .check()?;
449- Ok(result.take::<Vec<MealLedger>>(0)?)
450 }451 }
451 452
452 /// The derived balance: `credits + reversals - charges`, in minor units.453 /// The derived balance: `credits + reversals - charges`, in minor units.
@@ -454,8 +455,9 @@ impl MealLedger {
454 // ponytail: folds the student's lines in-process (a few hundred a year);455 // ponytail: folds the student's lines in-process (a few hundred a year);
455 // push it into a `math::sum` aggregate if a statement ever gets long.456 // push it into a `math::sum` aggregate if a statement ever gets long.
456 pub async fn balance_of(student: &UserId, db: &Database) -> Result<i64, AppError> {457 pub async fn balance_of(student: &UserId, db: &Database) -> Result<i64, AppError> {
457- Ok(Self::list_for_student(student, db)458+ Ok(Self::list_for_student(student, None, 0, db)
458 .await?459 .await?
460+ .0
459 .iter()461 .iter()
460 .fold(0i64, |sum, line| {462 .fold(0i64, |sum, line| {
461 sum + line.kind.sign() * line.amount_minor.as_minor()463 sum + line.kind.sign() * line.amount_minor.as_minor()
src/domain/menu.rsmodified+12 -12
@@ -20,6 +20,7 @@ use crate::constant::{MAX_MENU_CAPACITY, MENU_TABLE};
20 use crate::database::Database;20 use crate::database::Database;
21 use crate::domain::field_update::FieldUpdate;21 use crate::domain::field_update::FieldUpdate;
22 use crate::domain::menu_dish::MenuDish;22 use crate::domain::menu_dish::MenuDish;
23+use crate::domain::page::PagedList;
23 use crate::domain::settings::MealSlotDef;24 use crate::domain::settings::MealSlotDef;
24 use crate::domain::timestamp::Timestamp;25 use crate::domain::timestamp::Timestamp;
25 use crate::domain::user::UserId;26 use crate::domain::user::UserId;
@@ -237,19 +238,18 @@ impl Menu {
237 pub async fn list(238 pub async fn list(
238 from: Option<&MenuDate>,239 from: Option<&MenuDate>,
239 to: Option<&MenuDate>,240 to: Option<&MenuDate>,
241+ limit: Option<i64>,
242+ offset: i64,
240 db: &Database,243 db: &Database,
241- ) -> Result<Vec<Menu>, AppError> {244+ ) -> Result<(Vec<Menu>, i64), AppError> {
242- let mut result = db245+ PagedList::new(
243- .query(246+ "menu WHERE ($from = NONE OR date >= $from) AND ($to = NONE OR date <= $to)",
244- "SELECT * FROM menu \247+ "ORDER BY date DESC, slot ASC, id DESC",
245- WHERE ($from = NONE OR date >= $from) AND ($to = NONE OR date <= $to) \248+ )
246- ORDER BY date DESC, slot ASC, id DESC",249+ .bind("from", from.map(|date| date.as_str().to_string()))
247- )250+ .bind("to", to.map(|date| date.as_str().to_string()))
248- .bind(("from", from.map(|date| date.as_str().to_string())))251+ .run(limit, offset, db)
249- .bind(("to", to.map(|date| date.as_str().to_string())))252+ .await
250- .await?
251- .check()?;
252- Ok(result.take::<Vec<Menu>>(0)?)
253 }253 }
254 254
255 /// Only `capacity` is writable: `date` and `slot` are `READONLY` columns,255 /// Only `capacity` is writable: `date` and `slot` are `READONLY` columns,
src/domain/message.rsmodified+13 -11
@@ -14,6 +14,7 @@ use crate::constant::{
14 RECIPIENT_FOLDERS, SENDER_FOLDERS,14 RECIPIENT_FOLDERS, SENDER_FOLDERS,
15 };15 };
16 use crate::database::Database;16 use crate::database::Database;
17+use crate::domain::page::PagedList;
17 use crate::domain::timestamp::Timestamp;18 use crate::domain::timestamp::Timestamp;
18 use crate::domain::user::UserId;19 use crate::domain::user::UserId;
19 use crate::error::{AppError, ValidationError};20 use crate::error::{AppError, ValidationError};
@@ -276,8 +277,10 @@ impl Message {
276 user: &UserId,277 user: &UserId,
277 folder: Folder,278 folder: Folder,
278 read: Option<bool>,279 read: Option<bool>,
280+ limit: Option<i64>,
281+ offset: i64,
279 db: &Database,282 db: &Database,
280- ) -> Result<Vec<Message>, AppError> {283+ ) -> Result<(Vec<Message>, i64), AppError> {
281 let condition = match folder {284 let condition = match folder {
282 Folder::Sent => "sender = $usr AND sender_folder = 'sent'",285 Folder::Sent => "sender = $usr AND sender_folder = 'sent'",
283 Folder::Archive => {286 Folder::Archive => {
@@ -295,16 +298,15 @@ impl Message {
295 } else {298 } else {
296 ""299 ""
297 };300 };
298- let mut result = db301+ PagedList::new(
299- .query(format!(302+ format!("message WHERE ({condition}){read_clause}"),
300- "SELECT * FROM message WHERE ({condition}){read_clause} ORDER BY id DESC"303+ "ORDER BY id DESC",
301- ))304+ )
302- .bind(("usr", user.record()))305+ .bind("usr", user.record())
303- .bind(("folder", folder.as_str().to_string()))306+ .bind("folder", folder.as_str().to_string())
304- .bind(("read", read.unwrap_or_default()))307+ .bind("read", read.unwrap_or_default())
305- .await?308+ .run(limit, offset, db)
306- .check()?;309+ .await
307- Ok(result.take::<Vec<Message>>(0)?)
308 }310 }
309 311
310 /// Read a message only if `user` is its sender or recipient and their312 /// Read a message only if `user` is its sender or recipient and their
src/domain/mod.rsmodified+3 -0
@@ -8,6 +8,7 @@ pub mod appointment_slot;
8 pub mod attendance;8 pub mod attendance;
9 pub mod bank_question;9 pub mod bank_question;
10 pub mod bank_question_image;10 pub mod bank_question_image;
11+pub mod cap;
11 pub mod chatbot_message;12 pub mod chatbot_message;
12 pub mod chatbot_thread;13 pub mod chatbot_thread;
13 pub mod course;14 pub mod course;
@@ -25,6 +26,7 @@ pub mod homework;
25 pub mod homework_file;26 pub mod homework_file;
26 pub mod homework_result;27 pub mod homework_result;
27 pub mod homework_submission;28 pub mod homework_submission;
29+pub mod key;
28 pub mod meal_attendance;30 pub mod meal_attendance;
29 pub mod meal_booking;31 pub mod meal_booking;
30 pub mod meal_ledger;32 pub mod meal_ledger;
@@ -34,6 +36,7 @@ pub mod message;
34 pub mod monotonic_id;36 pub mod monotonic_id;
35 pub mod note;37 pub mod note;
36 pub mod note_file;38 pub mod note_file;
39+pub mod page;
37 pub mod parent_link;40 pub mod parent_link;
38 pub mod pomodoro;41 pub mod pomodoro;
39 pub mod pool_question;42 pub mod pool_question;
src/domain/note.rsmodified+11 -7
@@ -4,6 +4,7 @@ use ulid::Ulid;
4 use crate::constant::{MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN, NOTE_TABLE};4 use crate::constant::{MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN, NOTE_TABLE};
5 use crate::database::Database;5 use crate::database::Database;
6 use crate::domain::field_update::FieldUpdate;6 use crate::domain::field_update::FieldUpdate;
7+use crate::domain::page::PagedList;
7 use crate::domain::user::UserId;8 use crate::domain::user::UserId;
8 use crate::error::{AppError, ValidationError};9 use crate::error::{AppError, ValidationError};
9 use crate::validate::{validate_optional, validate_required};10 use crate::validate::{validate_optional, validate_required};
@@ -107,13 +108,16 @@ impl Note {
107 Ok(note.filter(|note| &note.user == owner))108 Ok(note.filter(|note| &note.user == owner))
108 }109 }
109 110
110- pub async fn list_for(owner: &UserId, db: &Database) -> Result<Vec<Note>, AppError> {111+ pub async fn list_for(
111- let mut result = db112+ owner: &UserId,
112- .query("SELECT * FROM note WHERE user = $usr ORDER BY id DESC")113+ limit: Option<i64>,
113- .bind(("usr", owner.record()))114+ offset: i64,
114- .await?115+ db: &Database,
115- .check()?;116+ ) -> Result<(Vec<Note>, i64), AppError> {
116- Ok(result.take::<Vec<Note>>(0)?)117+ PagedList::new("note WHERE user = $usr", "ORDER BY id DESC")
118+ .bind("usr", owner.record())
119+ .run(limit, offset, db)
120+ .await
117 }121 }
118 122
119 /// Request-scoped: no lock spans the handler's read and this write, so an123 /// Request-scoped: no lock spans the handler's read and this write, so an
src/domain/note_file.rsmodified+72 -31
@@ -6,22 +6,18 @@
6 //! before blob on delete); this module owns the rows.6 //! before blob on delete); this module owns the rows.
7 7
8 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};8 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
9-use tokio::sync::Mutex;
10 use ulid::Ulid;9 use ulid::Ulid;
11 10
12 use crate::constant::{11 use crate::constant::{
13- MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN, MAX_NOTE_FILES, NOTE_FILE_TABLE,12+ MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN, MAX_NOTE_FILES, NOTE_FILE_COUNT_FIELD,
13+ NOTE_FILE_TABLE,
14 };14 };
15 use crate::database::Database;15 use crate::database::Database;
16+use crate::domain::cap;
16 use crate::domain::note::NoteId;17 use crate::domain::note::NoteId;
18+use crate::domain::page::PagedList;
17 use crate::error::{AppError, ValidationError};19 use crate::error::{AppError, ValidationError};
18 20
19-/// Serializes the files-per-note cap check against the insert (see
20-/// [`NoteFile::insert`]). This backend is the database's only
21-/// writer (single instance) — so one process-wide lock is sufficient.
22-// ponytail: global lock, per-note locks if uploads ever see real contention.
23-static FILE_CAP_LOCK: Mutex<()> = Mutex::const_new(());
24-
25 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]21 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
26 pub struct NoteFileId(RecordId);22 pub struct NoteFileId(RecordId);
27 23
@@ -158,21 +154,31 @@ impl NoteFile {
158 }154 }
159 155
160 /// Persist the row assembled by [`Self::new`], refusing once its note156 /// Persist the row assembled by [`Self::new`], refusing once its note
161- /// already holds [`MAX_NOTE_FILES`]. The count-then-create runs under157+ /// already holds [`MAX_NOTE_FILES`]. The slot is taken by [`cap::claim`] on
162- /// [`FILE_CAP_LOCK`] — a `BEGIN…COMMIT` can't enforce the cap because158+ /// the note row: a `BEGIN…COMMIT` around a count can't enforce the cap
163- /// SurrealDB doesn't conflict-check a cross-record count against a159+ /// (SurrealDB doesn't conflict-check a cross-record count against a
164- /// concurrent insert (write-skew), the same story as160+ /// concurrent insert) and a process-wide mutex can't either once the
165- /// `Registration::register`.161+ /// backend runs as two replicas — a conditional single-record write can.
166 pub async fn insert(self, db: &Database) -> Result<NoteFile, AppError> {162 pub async fn insert(self, db: &Database) -> Result<NoteFile, AppError> {
167- let _guard = FILE_CAP_LOCK.lock().await;163+ let note = self.note.record();
168- if Self::list_for(&self.note, db).await?.len() >= MAX_NOTE_FILES {164+ if !cap::claim(&note, NOTE_FILE_COUNT_FIELD, MAX_NOTE_FILES as i64, db).await? {
169 return Err(AppError::Conflict(165 return Err(AppError::Conflict(
170 "the note already holds the maximum of 10 files — delete one first",166 "the note already holds the maximum of 10 files — delete one first",
171 ));167 ));
172 }168 }
173 // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber169 // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber
174- let created: Option<NoteFile> = db.create(self.id.record()).content(self).await?;170+ let created: Result<Option<NoteFile>, _> = db.create(self.id.record()).content(self).await;
175- created.ok_or_else(|| AppError::Internal("failed to create note file".into()))171+ match created {
172+ Ok(Some(created)) => Ok(created),
173+ Ok(None) => {
174+ cap::release(&note, NOTE_FILE_COUNT_FIELD, db).await?;
175+ Err(AppError::Internal("failed to create note file".into()))
176+ }
177+ Err(err) => {
178+ cap::release(&note, NOTE_FILE_COUNT_FIELD, db).await?;
179+ Err(err.into())
180+ }
181+ }
176 }182 }
177 183
178 /// Read a file's row only if it belongs to `note` — callers have already184 /// Read a file's row only if it belongs to `note` — callers have already
@@ -187,18 +193,39 @@ impl NoteFile {
187 }193 }
188 194
189 /// All of `note`'s attachment rows, newest first.195 /// All of `note`'s attachment rows, newest first.
190- pub async fn list_for(note: &NoteId, db: &Database) -> Result<Vec<NoteFile>, AppError> {196+ pub async fn list_for(
191- let mut result = db197+ note: &NoteId,
192- .query("SELECT * FROM note_file WHERE note = $note ORDER BY id DESC")198+ limit: Option<i64>,
193- .bind(("note", note.record()))199+ offset: i64,
194- .await?200+ db: &Database,
195- .check()?;201+ ) -> Result<(Vec<NoteFile>, i64), AppError> {
196- Ok(result.take::<Vec<NoteFile>>(0)?)202+ PagedList::new("note_file WHERE note = $note", "ORDER BY id DESC")
203+ .bind("note", note.record())
204+ .run(limit, offset, db)
205+ .await
197 }206 }
198 207
208+ /// Delete the row and give its slot back in the same transaction — the note
209+ /// itself is untouched, so unlike the note-delete cascade this one has a
210+ /// counter to correct. (Deleting a *note* takes its counter with it.)
199 pub async fn delete(self, db: &Database) -> Result<NoteFile, AppError> {211 pub async fn delete(self, db: &Database) -> Result<NoteFile, AppError> {
200- let deleted: Option<NoteFile> = db.delete(self.id.record()).await?;212+ let mut result = db
201- deleted.ok_or(AppError::NotFound)213+ .query(
214+ "BEGIN TRANSACTION;
215+ LET $gone = (DELETE $id RETURN BEFORE);
216+ UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]);
217+ RETURN $gone;
218+ COMMIT TRANSACTION;",
219+ )
220+ .bind(("id", self.id.record()))
221+ .bind(("note", self.note.record()))
222+ .await?
223+ .check()?;
224+ result
225+ .take::<Vec<NoteFile>>(3)?
226+ .into_iter()
227+ .next()
228+ .ok_or(AppError::NotFound)
202 }229 }
203 }230 }
204 231
@@ -243,8 +270,21 @@ mod tests {
243 #[tokio::test]270 #[tokio::test]
244 async fn rows_scope_to_their_note() {271 async fn rows_scope_to_their_note() {
245 let db = crate::database::init_mem().await.unwrap();272 let db = crate::database::init_mem().await.unwrap();
246- let note_a = NoteId::generate();273+ // Real note rows: the cap counter lives on the note, so an insert whose
247- let note_b = NoteId::generate();274+ // note does not exist has no slot to take (a 409, like a full note).
275+ let owner = crate::domain::user::UserId::generate();
276+ let note_of = async |title: &str| {
277+ crate::domain::note::Note::create(
278+ &owner,
279+ crate::domain::note::NoteTitle::try_new(title).unwrap(),
280+ crate::domain::note::NoteContent::try_new("body").unwrap(),
281+ &db,
282+ )
283+ .await
284+ .unwrap()
285+ };
286+ let note_a = note_of("a").await.get_id().clone();
287+ let note_b = note_of("b").await.get_id().clone();
248 let file = NoteFile::new(288 let file = NoteFile::new(
249 &note_a,289 &note_a,
250 FileName::try_new("plan.pdf").unwrap(),290 FileName::try_new("plan.pdf").unwrap(),
@@ -267,10 +307,11 @@ mod tests {
267 .is_none()307 .is_none()
268 );308 );
269 309
270- assert_eq!(NoteFile::list_for(&note_a, &db).await.unwrap().len(), 1);310+ let listed = async |note: &NoteId| NoteFile::list_for(note, None, 0, &db).await.unwrap().0;
271- assert!(NoteFile::list_for(&note_b, &db).await.unwrap().is_empty());311+ assert_eq!(listed(&note_a).await.len(), 1);
312+ assert!(listed(&note_b).await.is_empty());
272 313
273 file.delete(&db).await.unwrap();314 file.delete(&db).await.unwrap();
274- assert!(NoteFile::list_for(&note_a, &db).await.unwrap().is_empty());315+ assert!(listed(&note_a).await.is_empty());
275 }316 }
276 }317 }
src/domain/page.rsadded+205 -0
@@ -0,0 +1,205 @@
1+//! One paged `SELECT` — the window and the `total` that goes with it, both
2+//! done by the database.
3+//!
4+//! WHY: `?limit=10` used to run an unbounded `SELECT *`, hand the whole table
5+//! to the web layer and slice ten rows off it. The scan (and the decode of
6+//! every row) grew with the table no matter how small the page was. Here the
7+//! window is `LIMIT/START` in SQL, and `total` is a `count()` over the *same*
8+//! `WHERE`, so a page can never disagree with the count that pages it.
9+//!
10+//! ```ignore
11+//! PagedList::new("note WHERE user = $usr", "ORDER BY id DESC")
12+//! .bind("usr", owner.record())
13+//! .run::<Note>(limit, offset, db)
14+//! .await
15+//! ```
16+//!
17+//! Paging stays opt-in: `limit = None, offset = 0` is the unpaged read, and it
18+//! emits exactly one statement (no count — the rows in hand *are* the total),
19+//! so internal callers that just want the list pay nothing.
20+//!
21+//! Only for lists the database can express whole. A handler that filters rows
22+//! in Rust after the read (visibility, audience resolution, a schedule window)
23+//! must keep slicing in the web layer: a DB `LIMIT` in front of a Rust filter
24+//! silently returns a short page.
25+
26+use surrealdb::types::{SurrealValue, Value};
27+
28+use crate::database::Database;
29+use crate::error::AppError;
30+
31+pub struct PagedList {
32+ /// Everything after `FROM`, e.g. `note WHERE user = $usr`. Shared verbatim
33+ /// by the page and the count.
34+ from_where: String,
35+ /// The full `ORDER BY ...`, applied to the page only.
36+ order: &'static str,
37+ bindings: Vec<(String, Value)>,
38+}
39+
40+impl PagedList {
41+ /// `from_where` is a whole-table read (`"term"`) or a filtered one
42+ /// (`"note WHERE user = $usr"`).
43+ pub fn new(from_where: impl Into<String>, order: &'static str) -> Self {
44+ let from_where = from_where.into();
45+ Self {
46+ // A *bare* `SELECT VALUE count() FROM t GROUP ALL` comes back as an
47+ // object rather than the projected int ("Expected int, got object")
48+ // — the whole-table read takes a path that drops the `VALUE`. Any
49+ // `WHERE`, even a trivial one, keeps it an int, so an unfiltered
50+ // list gets one. Cheaper than special-casing the take.
51+ from_where: match from_where.contains(" WHERE ") {
52+ true => from_where,
53+ false => format!("{from_where} WHERE true"),
54+ },
55+ order,
56+ bindings: Vec::new(),
57+ }
58+ }
59+
60+ /// Bind one variable of the `WHERE`. `limit` and `offset` are the two names
61+ /// a caller must not use.
62+ #[must_use]
63+ pub fn bind<T: SurrealValue>(mut self, name: &'static str, value: T) -> Self {
64+ self.bindings.push((name.to_string(), value.into_value()));
65+ self
66+ }
67+
68+ /// The statements to run, and whether the second one (the count) is among
69+ /// them. Split out so a test can read the SQL: the whole point of this type
70+ /// is that `LIMIT`/`START` reach the database instead of a `Vec` slice.
71+ fn statements(&self, limit: Option<i64>, offset: i64) -> (String, bool) {
72+ let from_where = &self.from_where;
73+ let window = match limit {
74+ Some(_) => "LIMIT $limit START $offset",
75+ None => "START $offset",
76+ };
77+ let mut sql = format!("SELECT * FROM {from_where} {} {window};", self.order);
78+ // A window that can hide rows needs the count; an unpaged read from row
79+ // zero already holds every row, so it stays a single statement.
80+ let counted = limit.is_some() || offset > 0;
81+ if counted {
82+ sql.push_str(&format!(
83+ "SELECT VALUE count() FROM {from_where} GROUP ALL;"
84+ ));
85+ }
86+ (sql, counted)
87+ }
88+
89+ /// The page plus the full row count. `limit = None` runs from `offset` to
90+ /// the end, matching the unpaged envelope.
91+ pub async fn run<T: SurrealValue>(
92+ self,
93+ limit: Option<i64>,
94+ offset: i64,
95+ db: &Database,
96+ ) -> Result<(Vec<T>, i64), AppError> {
97+ let (sql, counted) = self.statements(limit, offset);
98+ let mut query = db
99+ .query(sql)
100+ .bind(("offset", offset))
101+ .bind(("limit", limit.unwrap_or(0)));
102+ for (name, value) in self.bindings {
103+ query = query.bind((name, value));
104+ }
105+ let mut result = query.await?.check()?;
106+ let rows = result.take::<Vec<T>>(0)?;
107+ let total = if counted {
108+ // `GROUP ALL` yields no row at all when nothing matched.
109+ result.take::<Vec<i64>>(1)?.first().copied().unwrap_or(0)
110+ } else {
111+ rows.len() as i64
112+ };
113+ Ok((rows, total))
114+ }
115+}
116+
117+#[cfg(test)]
118+mod tests {
119+ use super::*;
120+ use crate::database;
121+ use crate::domain::note::{Note, NoteContent, NoteTitle};
122+ use crate::domain::user::UserId;
123+ use ulid::Ulid;
124+
125+ fn list() -> PagedList {
126+ PagedList::new("note WHERE user = $usr", "ORDER BY id DESC")
127+ }
128+
129+ /// The window has to be SQL — a `Vec` slice would leave the scan unbounded,
130+ /// which is the whole reason this type exists.
131+ #[test]
132+ fn a_paged_read_windows_and_counts_in_sql() {
133+ let (sql, counted) = list().statements(Some(10), 20);
134+ assert!(sql.contains("ORDER BY id DESC LIMIT $limit START $offset;"));
135+ assert!(sql.contains("SELECT VALUE count() FROM note WHERE user = $usr GROUP ALL;"));
136+ assert!(counted);
137+ }
138+
139+ /// A whole-table read still gets a `WHERE`, or its count comes back as an
140+ /// object instead of an int.
141+ #[test]
142+ fn an_unfiltered_list_still_counts_as_an_int() {
143+ let (sql, _) = PagedList::new("term", "ORDER BY starts_at DESC").statements(Some(5), 0);
144+ assert!(sql.contains("SELECT VALUE count() FROM term WHERE true GROUP ALL;"));
145+ }
146+
147+ /// Unpaged from row zero: the rows in hand are the total, so no count runs.
148+ #[test]
149+ fn an_unpaged_read_stays_one_statement() {
150+ let (sql, counted) = list().statements(None, 0);
151+ assert!(sql.ends_with("ORDER BY id DESC START $offset;"));
152+ assert!(!sql.contains("count()"));
153+ assert!(!counted);
154+ // An offset without a limit still hides rows, so it needs the count.
155+ assert!(list().statements(None, 3).1);
156+ }
157+
158+ #[tokio::test]
159+ async fn the_window_walks_the_rows_and_total_stays_the_whole_list() {
160+ let db = database::init_mem().await.unwrap();
161+ let user = UserId::from_key(&Ulid::new().to_string());
162+ for i in 0..5 {
163+ Note::create(
164+ &user,
165+ NoteTitle::try_new(&format!("n{i}")).unwrap(),
166+ NoteContent::try_new("x").unwrap(),
167+ &db,
168+ )
169+ .await
170+ .unwrap();
171+ }
172+
173+ // Every page is `limit` long and `total` ignores the window.
174+ let (page, total) = Note::list_for(&user, Some(2), 0, &db).await.unwrap();
175+ assert_eq!((page.len(), total), (2, 5));
176+ let (tail, total) = Note::list_for(&user, Some(2), 4, &db).await.unwrap();
177+ assert_eq!((tail.len(), total), (1, 5));
178+ // Offset past the end is an empty page, not an error.
179+ assert_eq!(
180+ Note::list_for(&user, Some(2), 9, &db)
181+ .await
182+ .unwrap()
183+ .0
184+ .len(),
185+ 0
186+ );
187+ // Unpaged, and unpaged-from-an-offset: the count still covers everything.
188+ let (all, total) = Note::list_for(&user, None, 0, &db).await.unwrap();
189+ assert_eq!((all.len(), total), (5, 5));
190+ let (rest, total) = Note::list_for(&user, None, 3, &db).await.unwrap();
191+ assert_eq!((rest.len(), total), (2, 5));
192+
193+ // The pages are consecutive slices of the unpaged list — page
194+ // boundaries match the order the ORDER BY already produced.
195+ let keys: Vec<&str> = all.iter().map(|note| note.get_id().key()).collect();
196+ assert_eq!(
197+ page.iter().map(|n| n.get_id().key()).collect::<Vec<_>>(),
198+ keys[..2]
199+ );
200+ assert_eq!(
201+ tail.iter().map(|n| n.get_id().key()).collect::<Vec<_>>(),
202+ keys[4..]
203+ );
204+ }
205+}
src/domain/pool_question.rsmodified+2 -1
@@ -459,9 +459,10 @@ mod tests {
459 assert_eq!(swept[0].get_id(), offered.get_id());459 assert_eq!(swept[0].get_id(), offered.get_id());
460 assert!(PoolQuestion::read(q.get_id(), &db).await.unwrap().is_none());460 assert!(PoolQuestion::read(q.get_id(), &db).await.unwrap().is_none());
461 assert!(461 assert!(
462- Solution::list_for(q.get_id(), &db)462+ Solution::list_for(q.get_id(), None, 0, &db)
463 .await463 .await
464 .unwrap()464 .unwrap()
465+ .0
465 .is_empty()466 .is_empty()
466 );467 );
467 468
src/domain/question_image.rsmodified+33 -16
@@ -16,7 +16,9 @@ use crate::constant::QUESTION_IMAGE_TABLE;
16 use crate::database::Database;16 use crate::database::Database;
17 use crate::domain::course::CourseId;17 use crate::domain::course::CourseId;
18 use crate::domain::exam::ExamId;18 use crate::domain::exam::ExamId;
19+use crate::domain::exam_attempt::ExamAttempt;
19 use crate::domain::exam_question::{ChoiceId, ExamQuestionId};20 use crate::domain::exam_question::{ChoiceId, ExamQuestionId};
21+use crate::domain::key;
20 use crate::domain::note_file::FileContentType;22 use crate::domain::note_file::FileContentType;
21 use crate::error::AppError;23 use crate::error::AppError;
22 24
@@ -24,20 +26,12 @@ use crate::error::AppError;
24 pub struct QuestionImageId(RecordId);26 pub struct QuestionImageId(RecordId);
25 27
26 impl QuestionImageId {28 impl QuestionImageId {
27- /// The one id a (question, slot) pair can have: `{qid}_q` for the29+ /// The one id a (question, slot) pair can have — see [`key::slot`] for the
28- /// question's own image, `{qid}_{choice id}` for one option's picture —30+ /// key shape and why the two forms can never collide.
29- /// uniqueness per slot needs no index this way. Keyed by the option's
30- /// *stable id*, so reordering the choice list moves no picture.
31 pub fn for_slot(question: &ExamQuestionId, slot: Option<&ChoiceId>) -> Self {31 pub fn for_slot(question: &ExamQuestionId, slot: Option<&ChoiceId>) -> Self {
32- // `_` is not in Crockford base32 and a ULID is never `"q"`, so
33- // `{qid}_{cid}` and `{qid}_q` can never collide.
34- let suffix = match slot {
35- None => "q",
36- Some(id) => id.as_str(),
37- };
38 Self(RecordId::new(32 Self(RecordId::new(
39 QUESTION_IMAGE_TABLE,33 QUESTION_IMAGE_TABLE,
40- format!("{}_{suffix}", question.key()),34+ key::slot(question.key(), slot.map(|id| id.as_str())),
41 ))35 ))
42 }36 }
43 37
@@ -110,11 +104,23 @@ impl QuestionImage {
110 }104 }
111 105
112 /// Create or replace the slot's image row — the deterministic id makes106 /// Create or replace the slot's image row — the deterministic id makes
113- /// this the whole "one image per slot" story.107+ /// this the whole "one image per slot" story. Refused once the exam has an
108+ /// attempt: pictures are part of the question, so they freeze with it, and
109+ /// the gate is in this transaction rather than in a lock the caller held.
114 pub async fn upsert(self, db: &Database) -> Result<QuestionImage, AppError> {110 pub async fn upsert(self, db: &Database) -> Result<QuestionImage, AppError> {
115 // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic111 // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic
116- let written: Option<QuestionImage> = db.upsert(self.id.record()).content(self).await?;112+ let mut result = db
117- written.ok_or_else(|| AppError::Internal("failed to store question image".into()))113+ .query(ExamAttempt::unfrozen("UPSERT $id CONTENT $image;"))
114+ .bind(("freeze_exam", self.exam.record()))
115+ .bind(("id", self.id.record()))
116+ .bind(("image", self))
117+ .await?;
118+ ExamAttempt::frozen_check(&mut result)?;
119+ result
120+ .take::<Vec<QuestionImage>>(ExamAttempt::FROZEN_SLOT)?
121+ .into_iter()
122+ .next()
123+ .ok_or_else(|| AppError::Internal("failed to store question image".into()))
118 }124 }
119 125
120 pub async fn read_slot(126 pub async fn read_slot(
@@ -196,9 +202,20 @@ impl QuestionImage {
196 Ok(result.take::<Vec<String>>(0)?)202 Ok(result.take::<Vec<String>>(0)?)
197 }203 }
198 204
205+ /// Refused once the exam has an attempt, in the same transaction — same
206+ /// gate, same reason as [`Self::upsert`].
199 pub async fn delete(self, db: &Database) -> Result<QuestionImage, AppError> {207 pub async fn delete(self, db: &Database) -> Result<QuestionImage, AppError> {
200- let deleted: Option<QuestionImage> = db.delete(self.id.record()).await?;208+ let mut result = db
201- deleted.ok_or(AppError::NotFound)209+ .query(ExamAttempt::unfrozen("DELETE $id RETURN BEFORE;"))
210+ .bind(("freeze_exam", self.exam.record()))
211+ .bind(("id", self.id.record()))
212+ .await?;
213+ ExamAttempt::frozen_check(&mut result)?;
214+ result
215+ .take::<Vec<QuestionImage>>(ExamAttempt::FROZEN_SLOT)?
216+ .into_iter()
217+ .next()
218+ .ok_or(AppError::NotFound)
202 }219 }
203 }220 }
204 221
src/domain/registration.rsmodified+45 -24
@@ -1,21 +1,12 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2-use tokio::sync::Mutex;
3 2
4-use crate::constant::REGISTRATION_TABLE;3+use crate::constant::{REGISTRATION_COUNT_FIELD, REGISTRATION_TABLE};
5-use crate::database::Database;4+use crate::database::{Database, lost_the_race};
5+use crate::domain::cap;
6 use crate::domain::event::{Event, EventId};6 use crate::domain::event::{Event, EventId};
7 use crate::domain::user::UserId;7 use crate::domain::user::UserId;
8 use crate::error::AppError;8 use crate::error::AppError;
9 9
10-/// Serializes seat-taking. A `BEGIN…COMMIT` around the count can't do this:
11-/// SurrealDB transactions don't conflict-check a cross-record `count()`
12-/// against a concurrent insert (write-skew), so two racing registrations both
13-/// saw a free seat and a full event over-admitted. This backend is the database's only
14-/// writer (single instance) — so one process-wide lock is sufficient.
15-// ponytail: global lock, per-event locks (or DB-side serialization) if
16-// registration ever sees real contention.
17-static REGISTER_LOCK: Mutex<()> = Mutex::const_new(());
18-
19 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]10 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
20 pub struct RegistrationId(RecordId);11 pub struct RegistrationId(RecordId);
21 12
@@ -75,17 +66,16 @@ impl Registration {
75 /// Register (idempotently) `user` onto `event`, refusing when a capacity66 /// Register (idempotently) `user` onto `event`, refusing when a capacity
76 /// cap is set and every seat is taken. Someone already listed gets their67 /// cap is set and every seat is taken. Someone already listed gets their
77 /// existing row back untouched — a true no-op that never counts against68 /// existing row back untouched — a true no-op that never counts against
78- /// the cap and never rewrites who placed them. The whole check-then-write69+ /// the cap and never rewrites who placed them. The seat is taken by
79- /// runs under [`REGISTER_LOCK`], and the gate + cap are re-derived from a70+ /// [`cap::claim`] on the event row — an atomic single-record conditional
80- /// fresh event read under that lock, so neither a racing registration nor71+ /// write, so neither a racing registration in another replica nor a
81- /// a concurrent capacity/audience/schedule PATCH can over-admit.72+ /// concurrent capacity/audience/schedule PATCH can over-admit.
82 pub async fn register(73 pub async fn register(
83 event: &EventId,74 event: &EventId,
84 user: &UserId,75 user: &UserId,
85 registered_by: &UserId,76 registered_by: &UserId,
86 db: &Database,77 db: &Database,
87 ) -> Result<Registration, AppError> {78 ) -> Result<Registration, AppError> {
88- let _guard = REGISTER_LOCK.lock().await;
89 if let Some(existing) = Self::read_for_user(event, user, db).await? {79 if let Some(existing) = Self::read_for_user(event, user, db).await? {
90 return Ok(existing);80 return Ok(existing);
91 }81 }
@@ -93,8 +83,14 @@ impl Registration {
93 .await?83 .await?
94 .ok_or(AppError::NotFound)?84 .ok_or(AppError::NotFound)?
95 .registration_capacity()?;85 .registration_capacity()?;
96- if let Some(capacity) = capacity86+ let seats = event.record();
97- && Self::list_for_event(event, db).await?.len() as i64 >= capacity87+ if !cap::claim(
88+ &seats,
89+ REGISTRATION_COUNT_FIELD,
90+ capacity.unwrap_or(cap::UNLIMITED),
91+ db,
92+ )
93+ .await?
98 {94 {
99 return Err(AppError::Conflict("the event is full"));95 return Err(AppError::Conflict("the event is full"));
100 }96 }
@@ -104,11 +100,29 @@ impl Registration {
104 user: user.clone(),100 user: user.clone(),
105 registered_by: registered_by.clone(),101 registered_by: registered_by.clone(),
106 };102 };
107- let created: Option<Registration> = db103+ let created: Result<Option<Registration>, _> = db
108 .create(registration.id.record())104 .create(registration.id.record())
109 .content(registration)105 .content(registration)
110- .await?;106+ .await;
111- created.ok_or_else(|| AppError::Internal("failed to register user".into()))107+ match created {
108+ Ok(Some(created)) => Ok(created),
109+ Ok(None) => {
110+ cap::release(&seats, REGISTRATION_COUNT_FIELD, db).await?;
111+ Err(AppError::Internal("failed to register user".into()))
112+ }
113+ // A concurrent placement of the same pair got there first: give the
114+ // seat back and hand its row over, the same no-op the early return
115+ // above would have made.
116+ Err(err) => {
117+ cap::release(&seats, REGISTRATION_COUNT_FIELD, db).await?;
118+ if !lost_the_race(&err) {
119+ return Err(err.into());
120+ }
121+ Self::read_for_user(event, user, db)
122+ .await?
123+ .ok_or_else(|| AppError::Internal("failed to register user".into()))
124+ }
125+ }
112 }126 }
113 127
114 /// Some(_) iff `user` holds a seat on `event` — the audience point check.128 /// Some(_) iff `user` holds a seat on `event` — the audience point check.
@@ -143,12 +157,19 @@ impl Registration {
143 user: &UserId,157 user: &UserId,
144 db: &Database,158 db: &Database,
145 ) -> Result<Option<Registration>, AppError> {159 ) -> Result<Option<Registration>, AppError> {
160+ // The seat comes back in the same transaction as the row that held it.
146 let mut result = db161 let mut result = db
147- .query("DELETE registration WHERE event = $ev AND user = $usr RETURN BEFORE")162+ .query(
163+ "BEGIN TRANSACTION;
164+ LET $gone = (DELETE registration WHERE event = $ev AND user = $usr RETURN BEFORE);
165+ UPDATE $ev SET registration_count = math::max([(registration_count ?? 0) - array::len($gone), 0]);
166+ RETURN $gone;
167+ COMMIT TRANSACTION;",
168+ )
148 .bind(("ev", event.record()))169 .bind(("ev", event.record()))
149 .bind(("usr", user.record()))170 .bind(("usr", user.record()))
150 .await?171 .await?
151 .check()?;172 .check()?;
152- Ok(result.take::<Vec<Registration>>(0)?.into_iter().next())173+ Ok(result.take::<Vec<Registration>>(3)?.into_iter().next())
153 }174 }
154 }175 }
src/domain/session_attendance.rsmodified+8 -7
@@ -5,6 +5,7 @@ use crate::database::Database;
5 use crate::domain::attendance::AttendanceStatus;5 use crate::domain::attendance::AttendanceStatus;
6 use crate::domain::course::CourseId;6 use crate::domain::course::CourseId;
7 use crate::domain::course_session::{CourseSession, CourseSessionId};7 use crate::domain::course_session::{CourseSession, CourseSessionId};
8+use crate::domain::page::PagedList;
8 use crate::domain::user::UserId;9 use crate::domain::user::UserId;
9 use crate::error::AppError;10 use crate::error::AppError;
10 11
@@ -100,14 +101,14 @@ impl SessionAttendance {
100 101
101 pub async fn list_for_session(102 pub async fn list_for_session(
102 session: &CourseSessionId,103 session: &CourseSessionId,
104+ limit: Option<i64>,
105+ offset: i64,
103 db: &Database,106 db: &Database,
104- ) -> Result<Vec<SessionAttendance>, AppError> {107+ ) -> Result<(Vec<SessionAttendance>, i64), AppError> {
105- let mut result = db108+ PagedList::new("session_attendance WHERE session = $s", "ORDER BY id DESC")
106- .query("SELECT * FROM session_attendance WHERE session = $s ORDER BY id DESC")109+ .bind("s", session.record())
107- .bind(("s", session.record()))110+ .run(limit, offset, db)
108- .await?111+ .await
109- .check()?;
110- Ok(result.take::<Vec<SessionAttendance>>(0)?)
111 }112 }
112 113
113 /// Every roll-call row ever recorded for `user` — the session half of the114 /// Every roll-call row ever recorded for `user` — the session half of the
src/domain/solution.rsmodified+22 -10
@@ -15,6 +15,7 @@ use ulid::Ulid;
15 use crate::constant::{MAX_SOLUTION_BODY_LEN, SOLUTION_TABLE};15 use crate::constant::{MAX_SOLUTION_BODY_LEN, SOLUTION_TABLE};
16 use crate::database::Database;16 use crate::database::Database;
17 use crate::domain::note_file::FileContentType;17 use crate::domain::note_file::FileContentType;
18+use crate::domain::page::PagedList;
18 use crate::domain::pool_question::PoolQuestionId;19 use crate::domain::pool_question::PoolQuestionId;
19 use crate::domain::timestamp::Timestamp;20 use crate::domain::timestamp::Timestamp;
20 use crate::domain::user::UserId;21 use crate::domain::user::UserId;
@@ -149,14 +150,17 @@ impl Solution {
149 /// are random within a millisecond, so same-ms order is arbitrary).150 /// are random within a millisecond, so same-ms order is arbitrary).
150 pub async fn list_for(151 pub async fn list_for(
151 question: &PoolQuestionId,152 question: &PoolQuestionId,
153+ limit: Option<i64>,
154+ offset: i64,
152 db: &Database,155 db: &Database,
153- ) -> Result<Vec<Solution>, AppError> {156+ ) -> Result<(Vec<Solution>, i64), AppError> {
154- let mut result = db157+ PagedList::new(
155- .query("SELECT * FROM solution WHERE question = $q ORDER BY offered_at ASC, id ASC")158+ "solution WHERE question = $q",
156- .bind(("q", question.record()))159+ "ORDER BY offered_at ASC, id ASC",
157- .await?160+ )
158- .check()?;161+ .bind("q", question.record())
159- Ok(result.take::<Vec<Solution>>(0)?)162+ .run(limit, offset, db)
163+ .await
160 }164 }
161 165
162 /// Per-question solution tallies for a page of questions, in one grouped166 /// Per-question solution tallies for a page of questions, in one grouped
@@ -273,14 +277,15 @@ mod tests {
273 second.offered_at = Timestamp::from_millis(2);277 second.offered_at = Timestamp::from_millis(2);
274 let second = second.insert(&db).await.unwrap();278 let second = second.insert(&db).await.unwrap();
275 279
276- let listed = Solution::list_for(&question_a, &db).await.unwrap();280+ let (listed, _) = Solution::list_for(&question_a, None, 0, &db).await.unwrap();
277 assert_eq!(listed.len(), 2);281 assert_eq!(listed.len(), 2);
278 assert_eq!(listed[0].get_id(), first.get_id());282 assert_eq!(listed[0].get_id(), first.get_id());
279 assert_eq!(listed[1].get_id(), second.get_id());283 assert_eq!(listed[1].get_id(), second.get_id());
280 assert!(284 assert!(
281- Solution::list_for(&question_b, &db)285+ Solution::list_for(&question_b, None, 0, &db)
282 .await286 .await
283 .unwrap()287 .unwrap()
288+ .0
284 .is_empty()289 .is_empty()
285 );290 );
286 291
@@ -299,7 +304,14 @@ mod tests {
299 );304 );
300 305
301 first.delete(&db).await.unwrap();306 first.delete(&db).await.unwrap();
302- assert_eq!(Solution::list_for(&question_a, &db).await.unwrap().len(), 1);307+ assert_eq!(
308+ Solution::list_for(&question_a, None, 0, &db)
309+ .await
310+ .unwrap()
311+ .0
312+ .len(),
313+ 1
314+ );
303 }315 }
304 316
305 #[tokio::test]317 #[tokio::test]
src/domain/subject.rsmodified+8 -7
@@ -5,6 +5,7 @@ use crate::database::Database;
5 use crate::domain::course::CourseId;5 use crate::domain::course::CourseId;
6 use crate::domain::field_update::FieldUpdate;6 use crate::domain::field_update::FieldUpdate;
7 use crate::domain::monotonic_id::next_ulid;7 use crate::domain::monotonic_id::next_ulid;
8+use crate::domain::page::PagedList;
8 use crate::error::{AppError, ValidationError};9 use crate::error::{AppError, ValidationError};
9 use crate::validate::{validate_optional, validate_required};10 use crate::validate::{validate_optional, validate_required};
10 11
@@ -131,14 +132,14 @@ impl Subject {
131 /// The course's subjects in curriculum order (ULID ids sort by creation).132 /// The course's subjects in curriculum order (ULID ids sort by creation).
132 pub async fn list_for_course(133 pub async fn list_for_course(
133 course: &CourseId,134 course: &CourseId,
135+ limit: Option<i64>,
136+ offset: i64,
134 db: &Database,137 db: &Database,
135- ) -> Result<Vec<Subject>, AppError> {138+ ) -> Result<(Vec<Subject>, i64), AppError> {
136- let mut result = db139+ PagedList::new("subject WHERE course = $course", "ORDER BY id ASC")
137- .query("SELECT * FROM subject WHERE course = $course ORDER BY id ASC")140+ .bind("course", course.record())
138- .bind(("course", course.record()))141+ .run(limit, offset, db)
139- .await?142+ .await
140- .check()?;
141- Ok(result.take::<Vec<Subject>>(0)?)
142 }143 }
143 144
144 /// Request-scoped: no lock spans the handler's read and this write, so an145 /// Request-scoped: no lock spans the handler's read and this write, so an
src/domain/term.rsmodified+47 -13
@@ -13,7 +13,8 @@ use ulid::Ulid;
13 use crate::constant::{MAX_TERM_NAME_LEN, TERM_TABLE};13 use crate::constant::{MAX_TERM_NAME_LEN, TERM_TABLE};
14 use crate::database::Database;14 use crate::database::Database;
15 use crate::domain::field_update::FieldUpdate;15 use crate::domain::field_update::FieldUpdate;
16-use crate::domain::timestamp::Timestamp;16+use crate::domain::page::PagedList;
17+use crate::domain::timestamp::{Timestamp, range_error};
17 use crate::error::{AppError, ValidationError};18 use crate::error::{AppError, ValidationError};
18 use crate::validate::validate_required;19 use crate::validate::validate_required;
19 20
@@ -22,12 +23,12 @@ use crate::validate::validate_required;
22 /// is already on its way out. Course writes take it only when they actually23 /// is already on its way out. Course writes take it only when they actually
23 /// link a term.24 /// link a term.
24 ///25 ///
25-/// A PATCH that moves either end of the range takes it too: `starts_at <=26+/// Two leases remain, both cross-record and both replica-*local*: the delete
26-/// ends_at` is a cross-field check, so a partial PATCH validates the value it27+/// guard in `web::terms::delete_term`, and the term lookup in
27-/// carries against the *stored* other end — two such PATCHes, each fine on its28+/// `web::courses`' create/update. The range check a PATCH makes is no longer
28-/// own, would otherwise commit an inverted range between them. Holding this29+/// one of them — it is a `WHERE` on the update itself
29-/// across read-check-write serializes them; name-only PATCHes check nothing30+/// ([`crate::domain::field_update::FieldUpdate::ordered`]), which holds across
30-/// cross-field and stay lock-free.31+/// replicas as this mutex never did.
31 ///32 ///
32 /// Lock order: no path ever holds this and `ENROLL_LOCK` at the same time — the33 /// Lock order: no path ever holds this and `ENROLL_LOCK` at the same time — the
33 /// course writes that take this one touch no roster, and the course delete that34 /// course writes that take this one touch no roster, and the course delete that
@@ -121,12 +122,14 @@ impl Term {
121 }122 }
122 123
123 /// Every term, newest first — the school calendar is small by nature.124 /// Every term, newest first — the school calendar is small by nature.
124- pub async fn list_all(db: &Database) -> Result<Vec<Term>, AppError> {125+ pub async fn list_all(
125- let mut result = db126+ limit: Option<i64>,
126- .query("SELECT * FROM term ORDER BY starts_at DESC")127+ offset: i64,
127- .await?128+ db: &Database,
128- .check()?;129+ ) -> Result<(Vec<Term>, i64), AppError> {
129- Ok(result.take::<Vec<Term>>(0)?)130+ PagedList::new("term", "ORDER BY starts_at DESC")
131+ .run(limit, offset, db)
132+ .await
130 }133 }
131 134
132 /// Write only the fields the PATCH carried — `None` means the request135 /// Write only the fields the PATCH carried — `None` means the request
@@ -144,6 +147,7 @@ impl Term {
144 .set("name", name)147 .set("name", name)
145 .set("starts_at", starts_at)148 .set("starts_at", starts_at)
146 .set("ends_at", ends_at)149 .set("ends_at", ends_at)
150+ .ordered("starts_at", "ends_at", range_error())
147 .run::<Term>(db)151 .run::<Term>(db)
148 .await152 .await
149 }153 }
@@ -171,6 +175,36 @@ impl Term {
171 mod tests {175 mod tests {
172 use super::*;176 use super::*;
173 177
178+ /// The bite test for the `WHERE` guard that replaced `TERM_LOCK` on the
179+ /// PATCH path: the handler's pre-flight check is not in play here, so only
180+ /// the guard can refuse a moved end that inverts the range — and it must
181+ /// refuse it with the same error, having written nothing.
182+ #[tokio::test]
183+ async fn a_moved_end_is_refused_against_the_stored_other_end() {
184+ let db = crate::database::init_mem().await.unwrap();
185+ let at = Timestamp::from_millis;
186+ let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db)
187+ .await
188+ .unwrap();
189+
190+ let refused = term
191+ .clone()
192+ .update(None, None, Some(at(50)), &db)
193+ .await
194+ .expect_err("an end before the stored start must be refused");
195+ assert!(refused.to_string().contains("at or after starts_at"));
196+ let stored = Term::read(term.get_id(), &db).await.unwrap().unwrap();
197+ assert_eq!(
198+ stored.get_ends_at(),
199+ at(200),
200+ "nothing may have been written"
201+ );
202+
203+ // A move that keeps the range ordered still lands, guard and all.
204+ let moved = term.update(None, None, Some(at(300)), &db).await.unwrap();
205+ assert_eq!(moved.get_ends_at(), at(300));
206+ }
207+
174 #[tokio::test]208 #[tokio::test]
175 async fn name_is_required_and_bounded() {209 async fn name_is_required_and_bounded() {
176 assert!(TermName::try_new("2026 Fall").is_ok());210 assert!(TermName::try_new("2026 Fall").is_ok());
src/domain/timestamp.rsmodified+11 -0
@@ -14,6 +14,17 @@
14 use surrealdb::types::SurrealValue;14 use surrealdb::types::SurrealValue;
15 15
16 use crate::constant::MILLIS_PER_DAY;16 use crate::constant::MILLIS_PER_DAY;
17+use crate::error::{AppError, ValidationError};
18+
19+/// The one spelling of "this range is inverted", so the pre-flight check
20+/// ([`crate::web::check_time_range`]) and the write-time `WHERE` guard that
21+/// re-makes it against the stored row answer a client identically.
22+pub(crate) fn range_error() -> AppError {
23+ AppError::Validation(ValidationError::Invalid {
24+ field: "ends_at",
25+ reason: "must be at or after starts_at",
26+ })
27+}
17 28
18 /// A unix-millisecond instant (UTC by construction). Stored as an `int`.29 /// A unix-millisecond instant (UTC by construction). Stored as an `int`.
19 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, SurrealValue)]30 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, SurrealValue)]
src/domain/user.rsmodified+16 -15
@@ -8,6 +8,7 @@ use ulid::Ulid;
8 use crate::constant::{DECOY_PASSWORD, USER_TABLE};8 use crate::constant::{DECOY_PASSWORD, USER_TABLE};
9 use crate::database::Database;9 use crate::database::Database;
10 use crate::domain::field_update::FieldUpdate;10 use crate::domain::field_update::FieldUpdate;
11+use crate::domain::page::PagedList;
11 use crate::domain::preferences::{Language, Theme};12 use crate::domain::preferences::{Language, Theme};
12 use crate::domain::profile::{BirthDate, Email, PersonName, Phone};13 use crate::domain::profile::{BirthDate, Email, PersonName, Phone};
13 use crate::domain::role::Role;14 use crate::domain::role::Role;
@@ -355,12 +356,14 @@ impl User {
355 Ok(db.select(id.record()).await?)356 Ok(db.select(id.record()).await?)
356 }357 }
357 358
358- pub async fn list_all(db: &Database) -> Result<Vec<User>, AppError> {359+ pub async fn list_all(
359- let mut result = db360+ limit: Option<i64>,
360- .query("SELECT * FROM user ORDER BY id DESC")361+ offset: i64,
361- .await?362+ db: &Database,
362- .check()?;363+ ) -> Result<(Vec<User>, i64), AppError> {
363- Ok(result.take::<Vec<User>>(0)?)364+ PagedList::new("user", "ORDER BY id DESC")
365+ .run(limit, offset, db)
366+ .await
364 }367 }
365 368
366 /// Fetch the users behind `ids` in one query. Ids with no row are simply369 /// Fetch the users behind `ids` in one query. Ids with no row are simply
@@ -402,8 +405,10 @@ impl User {
402 pub async fn search(405 pub async fn search(
403 query: &str,406 query: &str,
404 role: Option<Role>,407 role: Option<Role>,
408+ limit: Option<i64>,
409+ offset: i64,
405 db: &Database,410 db: &Database,
406- ) -> Result<Vec<User>, AppError> {411+ ) -> Result<(Vec<User>, i64), AppError> {
407 let needle = search_fold(query.trim());412 let needle = search_fold(query.trim());
408 let text_clause = format!(413 let text_clause = format!(
409 "({} CONTAINS $q OR {} CONTAINS $q OR {} CONTAINS $q)",414 "({} CONTAINS $q OR {} CONTAINS $q OR {} CONTAINS $q)",
@@ -423,16 +428,12 @@ impl User {
423 } else {428 } else {
424 clauses.join(" AND ")429 clauses.join(" AND ")
425 };430 };
426- let mut query = db431+ let mut list = PagedList::new(format!("user WHERE {where_clause}"), "ORDER BY username")
427- .query(format!(432+ .bind("q", needle);
428- "SELECT * FROM user WHERE {where_clause} ORDER BY username"
429- ))
430- .bind(("q", needle));
431 if let Some(role) = role {433 if let Some(role) = role {
432- query = query.bind(("role", role));434+ list = list.bind("role", role);
433 }435 }
434- let mut result = query.await?.check()?;436+ list.run(limit, offset, db).await
435- Ok(result.take::<Vec<User>>(0)?)
436 }437 }
437 438
438 /// Overwrite this user's role. The caller is responsible for authorizing it.439 /// Overwrite this user's role. The caller is responsible for authorizing it.
src/domain/work_entry.rsmodified+28 -25
@@ -1,27 +1,23 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2-use tokio::sync::Mutex;
3 use ulid::Ulid;2 use ulid::Ulid;
4 3
5 use crate::constant::WORK_ENTRY_TABLE;4 use crate::constant::WORK_ENTRY_TABLE;
6 use crate::database::Database;5 use crate::database::Database;
7 use crate::domain::field_update::FieldUpdate;6 use crate::domain::field_update::FieldUpdate;
7+use crate::domain::page::PagedList;
8 use crate::domain::timestamp::Timestamp;8 use crate::domain::timestamp::Timestamp;
9 use crate::domain::user::UserId;9 use crate::domain::user::UserId;
10-use crate::error::AppError;10+use crate::error::{AppError, ValidationError};
11-11+
12-/// Serializes a stint correction's ordering check against the write it guards,12+/// The one spelling of "this stint is inverted", shared by the handler's
13-/// exactly as `TERM_LOCK` does for terms: `check_in <= check_out` is a13+/// pre-flight check and the write-time `WHERE` guard that re-makes it against
14-/// cross-field check, so a correction of one instant validates against the14+/// the stored row.
15-/// *stored* other one — two such corrections, each fine on its own snapshot,15+pub(crate) fn out_before_in_error() -> AppError {
16-/// would otherwise commit an inverted stint between them. Check-in/check-out16+ AppError::Validation(ValidationError::Invalid {
17-/// themselves stay lock-free (they are atomic single-row writes), and a PATCH17+ field: "check_out",
18-/// carrying neither instant checks nothing cross-field.18+ reason: "must be at or after check_in",
19-///19+ })
20-/// Lock order: this is a leaf — the only path that takes it (`PATCH20+}
21-/// /work/entries/{id}`) takes no other lock, and no path holding another lock
22-/// takes this one, so it cannot sit in a cycle. Should a future path need
23-/// both, take the other lock first and this one innermost.
24-pub(crate) static WORK_ENTRY_LOCK: Mutex<()> = Mutex::const_new(());
25 21
26 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]22 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
27 pub struct WorkEntryId(RecordId);23 pub struct WorkEntryId(RecordId);
@@ -163,13 +159,16 @@ impl WorkEntry {
163 /// Every stint of `user`, newest first — the open one (if any) included.159 /// Every stint of `user`, newest first — the open one (if any) included.
164 /// Ordered by `check_in`: the open entry's `open_` key doesn't sort with160 /// Ordered by `check_in`: the open entry's `open_` key doesn't sort with
165 /// the ULIDs, so id order would misplace it.161 /// the ULIDs, so id order would misplace it.
166- pub async fn list_for_user(user: &UserId, db: &Database) -> Result<Vec<WorkEntry>, AppError> {162+ pub async fn list_for_user(
167- let mut result = db163+ user: &UserId,
168- .query("SELECT * FROM work_entry WHERE user = $usr ORDER BY check_in DESC")164+ limit: Option<i64>,
169- .bind(("usr", user.record()))165+ offset: i64,
170- .await?166+ db: &Database,
171- .check()?;167+ ) -> Result<(Vec<WorkEntry>, i64), AppError> {
172- Ok(result.take::<Vec<WorkEntry>>(0)?)168+ PagedList::new("work_entry WHERE user = $usr", "ORDER BY check_in DESC")
169+ .bind("usr", user.record())
170+ .run(limit, offset, db)
171+ .await
173 }172 }
174 173
175 /// Persist corrected instants (manager fix-ups on closed entries; the web174 /// Persist corrected instants (manager fix-ups on closed entries; the web
@@ -188,6 +187,10 @@ impl WorkEntry {
188 FieldUpdate::new(self.id.record())187 FieldUpdate::new(self.id.record())
189 .set("check_in", check_in)188 .set("check_in", check_in)
190 .set("check_out", check_out)189 .set("check_out", check_out)
190+ // Same race closer as the schedule ranges, with this table's own
191+ // field names and message: a correction of one instant is only
192+ // written while it still orders against the other as *stored*.
193+ .ordered("check_in", "check_out", out_before_in_error())
191 .run::<WorkEntry>(db)194 .run::<WorkEntry>(db)
192 .await195 .await
193 }196 }
@@ -216,7 +219,7 @@ mod tests {
216 // Second check-in must not create a second stint or reset the clock.219 // Second check-in must not create a second stint or reset the clock.
217 let dup = WorkEntry::check_in(&user, &db).await;220 let dup = WorkEntry::check_in(&user, &db).await;
218 assert!(matches!(dup, Err(AppError::Conflict(_))));221 assert!(matches!(dup, Err(AppError::Conflict(_))));
219- let entries = WorkEntry::list_for_user(&user, &db).await.unwrap();222+ let (entries, _) = WorkEntry::list_for_user(&user, None, 0, &db).await.unwrap();
220 assert_eq!(entries.len(), 1);223 assert_eq!(entries.len(), 1);
221 assert_eq!(entries[0].get_check_in(), open.get_check_in());224 assert_eq!(entries[0].get_check_in(), open.get_check_in());
222 225
@@ -230,7 +233,7 @@ mod tests {
230 Err(AppError::Conflict(_))233 Err(AppError::Conflict(_))
231 ));234 ));
232 WorkEntry::check_in(&user, &db).await.unwrap();235 WorkEntry::check_in(&user, &db).await.unwrap();
233- let entries = WorkEntry::list_for_user(&user, &db).await.unwrap();236+ let (entries, _) = WorkEntry::list_for_user(&user, None, 0, &db).await.unwrap();
234 assert_eq!(entries.len(), 2);237 assert_eq!(entries.len(), 2);
235 }238 }
236 }239 }
src/lib.rsmodified+9 -1
@@ -4,6 +4,7 @@ pub mod constant;
4 pub mod database;4 pub mod database;
5 pub mod domain;5 pub mod domain;
6 pub mod error;6 pub mod error;
7+pub mod migration_sql;
7 pub mod rate_limit;8 pub mod rate_limit;
8 pub mod state;9 pub mod state;
9 pub mod validate;10 pub mod validate;
@@ -103,7 +104,7 @@ pub fn build_router(state: AppState) -> Router {
103 .routes(routes!(server_time))104 .routes(routes!(server_time))
104 .merge(web::limits::routes())105 .merge(web::limits::routes())
105 .nest("/ai", web::ai::routes())106 .nest("/ai", web::ai::routes())
106- .nest("/auth", web::auth::routes(&state.rate_limit))107+ .nest("/auth", web::auth::routes(&state))
107 .nest("/chatbot", web::chatbot::routes())108 .nest("/chatbot", web::chatbot::routes())
108 .nest("/users", web::users::routes())109 .nest("/users", web::users::routes())
109 .nest("/notes", web::notes::routes())110 .nest("/notes", web::notes::routes())
@@ -133,6 +134,13 @@ pub fn build_router(state: AppState) -> Router {
133 state.rate_limit.api_per_minute,134 state.rate_limit.api_per_minute,
134 state.rate_limit.trust_proxy,135 state.rate_limit.trust_proxy,
135 );136 );
137+ // Every tier's budget is fleet-wide, not per process (see
138+ // [`rate_limit::RateLimiter::share`]). The chatbot tier is shared here too
139+ // rather than in `main`, so it holds in every process that serves it.
140+ api_limiter.share("api", state.db.clone(), state.db_up.clone());
141+ state
142+ .chatbot_limit
143+ .share("chatbot", state.db.clone(), state.db_up.clone());
136 144
137 let db_up = state.db_up.clone();145 let db_up = state.db_up.clone();
138 146
src/migration_sql.rsadded+787 -0
@@ -0,0 +1,787 @@
1+//! The boot migration, as SurrealQL text.
2+//!
3+//! Split out of [`crate::constant`] purely for size: these three batches are
4+//! ~700 lines of schema, and left in the constants file they buried the
5+//! validation bounds that file exists to hold. Nothing else changed — they are
6+//! still `pub const`, still the only migration text, and
7+//! [`crate::database::migrate`] and [`crate::database::migration_fingerprint`]
8+//! still both read [`MIGRATION_BATCHES`] and nothing else.
9+//!
10+//! Numbers stay in `constant.rs`: `tests/limits_completeness.rs` sweeps `src/`
11+//! for stray bounds, and a bound hidden here would reach neither `GET /limits`
12+//! nor the OpenAPI spec. Only SurrealQL strings live in this file.
13+
14+/// Repairs that must run *before* the DDL batch, because the DDL is what makes
15+/// them impossible.
16+///
17+/// `MIGRATION` retires `exam_question.source_bank` with `REMOVE FIELD`, and
18+/// once the column is gone SCHEMAFULL rejects every write to a row that still
19+/// stores it ("Found field 'source_bank', but no such field exists") — an
20+/// UNSET included. So the value has to go while its definition is still
21+/// standing. Runs as its own query for the usual reason (see `MIGRATION`).
22+///
23+/// The table-exists guard is load-bearing: on a fresh database `MIGRATION` has
24+/// not run yet, and an UPDATE against an undefined table is an error, not an
25+/// empty result. On a database that has the table but never had the column the
26+/// `WHERE` simply matches nothing.
27+pub const PRE_REPAIR: &str = "
28+ IF 'exam_question' IN object::keys((INFO FOR DB).tables) {
29+ UPDATE exam_question UNSET source_bank WHERE source_bank != NONE
30+ };
31+";
32+
33+/// SCHEMAFULL schema: every column is typed, references use `record<..>`.
34+/// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the
35+/// definitions and `REMOVE ... IF EXISTS` retires schema (like the
36+/// single-attempt unique index) exactly once. DDL only — data backfills live
37+/// in `BACKFILL`, which runs as a *separate* query: statements inside one
38+/// batch see the schema as it stood when the batch started, so an UPDATE next
39+/// to a fresh `DEFINE FIELD audience.*` writes against the old field set and
40+/// SCHEMAFULL silently strips the very keys being backfilled.
41+pub const MIGRATION: &str = "
42+ DEFINE TABLE IF NOT EXISTS user SCHEMAFULL;
43+ DEFINE FIELD IF NOT EXISTS username ON user TYPE string;
44+ DEFINE FIELD IF NOT EXISTS password_hash ON user TYPE string;
45+ DEFINE FIELD IF NOT EXISTS role ON user TYPE string DEFAULT 'student';
46+ DEFINE FIELD IF NOT EXISTS name ON user TYPE option<string>;
47+ DEFINE FIELD IF NOT EXISTS surname ON user TYPE option<string>;
48+ DEFINE FIELD IF NOT EXISTS email ON user TYPE option<string>;
49+ DEFINE FIELD IF NOT EXISTS phone ON user TYPE option<string>;
50+ DEFINE FIELD IF NOT EXISTS birth_date ON user TYPE option<string>;
51+ DEFINE FIELD IF NOT EXISTS theme ON user TYPE option<string>;
52+ DEFINE FIELD IF NOT EXISTS language ON user TYPE option<string>;
53+ DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option<int>;
54+ DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE;
55+
56+ DEFINE TABLE IF NOT EXISTS session SCHEMAFULL;
57+ DEFINE FIELD IF NOT EXISTS user ON session TYPE record<user>;
58+ DEFINE FIELD IF NOT EXISTS token ON session TYPE string;
59+ DEFINE FIELD IF NOT EXISTS expires_at ON session TYPE int;
60+ DEFINE INDEX IF NOT EXISTS session_token ON session FIELDS token UNIQUE;
61+ DEFINE INDEX IF NOT EXISTS session_expires ON session FIELDS expires_at;
62+
63+ DEFINE TABLE IF NOT EXISTS note SCHEMAFULL;
64+ DEFINE FIELD IF NOT EXISTS user ON note TYPE record<user>;
65+ DEFINE FIELD IF NOT EXISTS title ON note TYPE string;
66+ DEFINE FIELD IF NOT EXISTS content ON note TYPE string;
67+ DEFINE FIELD IF NOT EXISTS file_count ON note TYPE option<int>;
68+ DEFINE INDEX IF NOT EXISTS note_user ON note FIELDS user;
69+
70+ DEFINE TABLE IF NOT EXISTS message SCHEMAFULL;
71+ DEFINE FIELD IF NOT EXISTS sender ON message TYPE record<user>;
72+ DEFINE FIELD IF NOT EXISTS recipient ON message TYPE record<user>;
73+ DEFINE FIELD IF NOT EXISTS subject ON message TYPE string;
74+ DEFINE FIELD IF NOT EXISTS body ON message TYPE string;
75+ DEFINE FIELD IF NOT EXISTS label ON message TYPE option<string>;
76+ DEFINE FIELD IF NOT EXISTS sent_at ON message TYPE int;
77+ DEFINE FIELD IF NOT EXISTS read ON message TYPE bool DEFAULT false;
78+ DEFINE FIELD IF NOT EXISTS sender_folder ON message TYPE string DEFAULT 'sent';
79+ DEFINE FIELD IF NOT EXISTS recipient_folder ON message TYPE string DEFAULT 'inbox';
80+ -- Where each side's copy sat before it was filed into archive/trash, so a
81+ -- restore lands where it came from. NONE while the copy is in its home
82+ -- folder — and on rows filed before this field existed (2026-07-23), which
83+ -- restore to the home folder just as they always did.
84+ DEFINE FIELD IF NOT EXISTS sender_origin ON message TYPE option<string>;
85+ DEFINE FIELD IF NOT EXISTS recipient_origin ON message TYPE option<string>;
86+ DEFINE INDEX IF NOT EXISTS message_sender ON message FIELDS sender;
87+ DEFINE INDEX IF NOT EXISTS message_recipient ON message FIELDS recipient;
88+
89+ DEFINE TABLE IF NOT EXISTS note_file SCHEMAFULL;
90+ DEFINE FIELD IF NOT EXISTS note ON note_file TYPE record<note>;
91+ DEFINE FIELD IF NOT EXISTS name ON note_file TYPE string;
92+ DEFINE FIELD IF NOT EXISTS content_type ON note_file TYPE string;
93+ DEFINE FIELD IF NOT EXISTS size ON note_file TYPE int;
94+ DEFINE INDEX IF NOT EXISTS note_file_note ON note_file FIELDS note;
95+
96+ -- Chatbot relay (2026-07-23): a `thread` groups the turns, one
97+ -- `chatbot_message` is one turn. `user_id` rides on the message too so an
98+ -- ownership check needs no join. An assistant turn is born `pending` and
99+ -- is completed (or failed) by the task holding the AI-bridge stream —
100+ -- hence the BACKFILL sweep, since that task dies with the process.
101+ DEFINE TABLE IF NOT EXISTS chatbot_thread SCHEMAFULL;
102+ DEFINE FIELD IF NOT EXISTS user_id ON chatbot_thread TYPE record<user> READONLY;
103+ DEFINE FIELD IF NOT EXISTS title ON chatbot_thread TYPE option<string>;
104+ DEFINE FIELD IF NOT EXISTS created_at ON chatbot_thread TYPE int READONLY;
105+ DEFINE FIELD IF NOT EXISTS updated_at ON chatbot_thread TYPE int;
106+ DEFINE INDEX IF NOT EXISTS chatbot_thread_user_updated ON chatbot_thread FIELDS user_id, updated_at;
107+
108+ DEFINE TABLE IF NOT EXISTS chatbot_message SCHEMAFULL;
109+ DEFINE FIELD IF NOT EXISTS thread_id ON chatbot_message TYPE record<chatbot_thread> READONLY;
110+ DEFINE FIELD IF NOT EXISTS user_id ON chatbot_message TYPE record<user> READONLY;
111+ DEFINE FIELD IF NOT EXISTS role ON chatbot_message TYPE string READONLY;
112+ DEFINE FIELD IF NOT EXISTS content ON chatbot_message TYPE string;
113+ DEFINE FIELD IF NOT EXISTS status ON chatbot_message TYPE string;
114+ DEFINE FIELD IF NOT EXISTS truncated ON chatbot_message TYPE bool DEFAULT false;
115+ DEFINE FIELD IF NOT EXISTS error_code ON chatbot_message TYPE option<string>;
116+ DEFINE FIELD IF NOT EXISTS created_at ON chatbot_message TYPE int READONLY;
117+ DEFINE FIELD IF NOT EXISTS completed_at ON chatbot_message TYPE option<int>;
118+ -- The claim (2026-07-27): which replica's claim loop owes this turn an
119+ -- answer, and when it said so. Absent = nobody has taken it yet; a claim
120+ -- older than CHATBOT_CLAIM_RECLAIM_SECS is a dead claimer and the turn is
121+ -- taken back (see `CHATBOT_CLAIM`).
122+ DEFINE FIELD IF NOT EXISTS claimed_by ON chatbot_message TYPE option<string>;
123+ DEFINE FIELD IF NOT EXISTS claimed_at ON chatbot_message TYPE option<int>;
124+ DEFINE INDEX IF NOT EXISTS chatbot_message_thread_created ON chatbot_message FIELDS thread_id, created_at;
125+ DEFINE INDEX IF NOT EXISTS chatbot_message_user ON chatbot_message FIELDS user_id;
126+ -- The claim loop's sweep: every poll asks for pending rows by age.
127+ DEFINE INDEX IF NOT EXISTS chatbot_message_status_created ON chatbot_message FIELDS status, created_at;
128+
129+ -- Which AI workers are connected to *any* replica (2026-07-27). The GATE
130+ -- and nothing else: a row only says a socket existed somewhere at
131+ -- `seen_at`, so it may spare a user a 503 but must never pick who answers
132+ -- — that is the in-process registry's call. Heartbeated by the replica
133+ -- owning the connection; a stale row is ignored by the read and swept.
134+ DEFINE TABLE IF NOT EXISTS ai_worker SCHEMAFULL;
135+ DEFINE FIELD IF NOT EXISTS service ON ai_worker TYPE string;
136+ DEFINE FIELD IF NOT EXISTS capabilities ON ai_worker TYPE array<string>;
137+ DEFINE FIELD IF NOT EXISTS seen_at ON ai_worker TYPE int;
138+
139+ -- How much of a rate-limit budget the whole fleet has spent in one wall
140+ -- window (2026-07-27). One row per tier+client+window, id-keyed so every
141+ -- replica lands on the same record; `hits` is the cross-replica total each
142+ -- replica folds its local admits into (see `crate::rate_limit`). Rows are
143+ -- swept by the same task once their window is past.
144+ DEFINE TABLE IF NOT EXISTS rate_limit SCHEMAFULL;
145+ DEFINE FIELD IF NOT EXISTS hits ON rate_limit TYPE int DEFAULT 0;
146+ DEFINE FIELD IF NOT EXISTS window_start ON rate_limit TYPE int;
147+
148+ DEFINE TABLE IF NOT EXISTS event SCHEMAFULL;
149+ DEFINE FIELD IF NOT EXISTS creator ON event TYPE record<user>;
150+ DEFINE FIELD IF NOT EXISTS title ON event TYPE string;
151+ DEFINE FIELD IF NOT EXISTS description ON event TYPE string;
152+ DEFINE FIELD IF NOT EXISTS audience ON event TYPE object;
153+ DEFINE FIELD IF NOT EXISTS audience.kind ON event TYPE string;
154+ DEFINE FIELD IF NOT EXISTS audience.role ON event TYPE option<string>;
155+ DEFINE FIELD IF NOT EXISTS audience.course ON event TYPE option<record<course>>;
156+ DEFINE FIELD IF NOT EXISTS audience.capacity ON event TYPE option<int>;
157+ -- Seats taken on the signup list, the cross-replica capacity guard (see
158+ -- `crate::domain::cap`). Absent reads as zero, so no Rust struct needs it.
159+ DEFINE FIELD IF NOT EXISTS registration_count ON event TYPE option<int>;
160+ REMOVE FIELD IF EXISTS audience.users ON TABLE event;
161+ DEFINE FIELD IF NOT EXISTS starts_at ON event TYPE option<int>;
162+ DEFINE FIELD IF NOT EXISTS ends_at ON event TYPE option<int>;
163+
164+ DEFINE TABLE IF NOT EXISTS attendance SCHEMAFULL;
165+ DEFINE FIELD IF NOT EXISTS event ON attendance TYPE record<event>;
166+ DEFINE FIELD IF NOT EXISTS user ON attendance TYPE record<user>;
167+ DEFINE FIELD IF NOT EXISTS status ON attendance TYPE string;
168+ DEFINE FIELD IF NOT EXISTS marked_by ON attendance TYPE record<user>;
169+ DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE;
170+ DEFINE INDEX IF NOT EXISTS attendance_user ON attendance FIELDS user;
171+
172+ DEFINE TABLE IF NOT EXISTS registration SCHEMAFULL;
173+ DEFINE FIELD IF NOT EXISTS event ON registration TYPE record<event>;
174+ DEFINE FIELD IF NOT EXISTS user ON registration TYPE record<user>;
175+ DEFINE FIELD IF NOT EXISTS registered_by ON registration TYPE record<user>;
176+ DEFINE INDEX IF NOT EXISTS registration_event_user ON registration FIELDS event, user UNIQUE;
177+ DEFINE INDEX IF NOT EXISTS registration_event ON registration FIELDS event;
178+
179+ DEFINE TABLE IF NOT EXISTS term SCHEMAFULL;
180+ DEFINE FIELD IF NOT EXISTS name ON term TYPE string;
181+ DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int;
182+ DEFINE FIELD IF NOT EXISTS ends_at ON term TYPE int;
183+
184+ DEFINE TABLE IF NOT EXISTS course SCHEMAFULL;
185+ DEFINE FIELD IF NOT EXISTS creator ON course TYPE record<user>;
186+ DEFINE FIELD IF NOT EXISTS teachers ON course TYPE array<record<user>> DEFAULT [];
187+ DEFINE FIELD IF NOT EXISTS teachers[*] ON course TYPE record<user>;
188+ DEFINE FIELD IF NOT EXISTS title ON course TYPE string;
189+ DEFINE FIELD IF NOT EXISTS description ON course TYPE string;
190+ DEFINE FIELD IF NOT EXISTS kind ON course TYPE string DEFAULT 'course';
191+ DEFINE FIELD IF NOT EXISTS term ON course TYPE option<record<term>>;
192+ DEFINE FIELD IF NOT EXISTS capacity ON course TYPE option<int>;
193+ DEFINE FIELD IF NOT EXISTS enrollment_count ON course TYPE option<int>;
194+
195+ DEFINE TABLE IF NOT EXISTS subject SCHEMAFULL;
196+ DEFINE FIELD IF NOT EXISTS course ON subject TYPE record<course>;
197+ DEFINE FIELD IF NOT EXISTS name ON subject TYPE string;
198+ DEFINE FIELD IF NOT EXISTS description ON subject TYPE string;
199+ DEFINE INDEX IF NOT EXISTS subject_course ON subject FIELDS course;
200+
201+ DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL;
202+ DEFINE FIELD IF NOT EXISTS course ON enrollment TYPE record<course>;
203+ DEFINE FIELD IF NOT EXISTS user ON enrollment TYPE record<user>;
204+ DEFINE FIELD IF NOT EXISTS enrolled_by ON enrollment TYPE record<user>;
205+ DEFINE INDEX IF NOT EXISTS enrollment_course_user ON enrollment FIELDS course, user UNIQUE;
206+ DEFINE INDEX IF NOT EXISTS enrollment_user ON enrollment FIELDS user;
207+
208+ DEFINE TABLE IF NOT EXISTS parent_link SCHEMAFULL;
209+ DEFINE FIELD IF NOT EXISTS parent ON parent_link TYPE record<user>;
210+ DEFINE FIELD IF NOT EXISTS student ON parent_link TYPE record<user>;
211+ DEFINE FIELD IF NOT EXISTS linked_by ON parent_link TYPE record<user>;
212+ DEFINE INDEX IF NOT EXISTS parent_link_parent_student ON parent_link FIELDS parent, student UNIQUE;
213+ DEFINE INDEX IF NOT EXISTS parent_link_parent ON parent_link FIELDS parent;
214+ DEFINE INDEX IF NOT EXISTS parent_link_student ON parent_link FIELDS student;
215+
216+ DEFINE TABLE IF NOT EXISTS course_session SCHEMAFULL;
217+ DEFINE FIELD IF NOT EXISTS course ON course_session TYPE record<course>;
218+ DEFINE FIELD IF NOT EXISTS teacher ON course_session TYPE record<user>;
219+ DEFINE FIELD IF NOT EXISTS topic ON course_session TYPE string;
220+ DEFINE FIELD IF NOT EXISTS starts_at ON course_session TYPE int;
221+ DEFINE FIELD IF NOT EXISTS ends_at ON course_session TYPE option<int>;
222+ DEFINE INDEX IF NOT EXISTS course_session_course ON course_session FIELDS course;
223+
224+ DEFINE TABLE IF NOT EXISTS session_attendance SCHEMAFULL;
225+ DEFINE FIELD IF NOT EXISTS session ON session_attendance TYPE record<course_session>;
226+ DEFINE FIELD IF NOT EXISTS course ON session_attendance TYPE record<course>;
227+ DEFINE FIELD IF NOT EXISTS user ON session_attendance TYPE record<user>;
228+ DEFINE FIELD IF NOT EXISTS status ON session_attendance TYPE string;
229+ DEFINE FIELD IF NOT EXISTS marked_by ON session_attendance TYPE record<user>;
230+ DEFINE INDEX IF NOT EXISTS session_attendance_session_user ON session_attendance FIELDS session, user UNIQUE;
231+ DEFINE INDEX IF NOT EXISTS session_attendance_session ON session_attendance FIELDS session;
232+ DEFINE INDEX IF NOT EXISTS session_attendance_user ON session_attendance FIELDS user;
233+ DEFINE INDEX IF NOT EXISTS session_attendance_course ON session_attendance FIELDS course;
234+
235+ DEFINE TABLE IF NOT EXISTS work_entry SCHEMAFULL;
236+ DEFINE FIELD IF NOT EXISTS user ON work_entry TYPE record<user>;
237+ DEFINE FIELD IF NOT EXISTS check_in ON work_entry TYPE int;
238+ DEFINE FIELD IF NOT EXISTS check_out ON work_entry TYPE option<int>;
239+ DEFINE INDEX IF NOT EXISTS work_entry_user ON work_entry FIELDS user;
240+
241+ DEFINE TABLE IF NOT EXISTS pomodoro_session SCHEMAFULL;
242+ DEFINE FIELD IF NOT EXISTS user ON pomodoro_session TYPE record<user>;
243+ DEFINE FIELD IF NOT EXISTS started_at ON pomodoro_session TYPE int;
244+ DEFINE FIELD IF NOT EXISTS finished_at ON pomodoro_session TYPE option<int>;
245+ DEFINE INDEX IF NOT EXISTS pomodoro_session_user ON pomodoro_session FIELDS user;
246+
247+ DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL;
248+ DEFINE FIELD IF NOT EXISTS creator ON exam TYPE record<user>;
249+ DEFINE FIELD IF NOT EXISTS course ON exam TYPE record<course>;
250+ DEFINE FIELD IF NOT EXISTS title ON exam TYPE string;
251+ DEFINE FIELD IF NOT EXISTS description ON exam TYPE string;
252+ DEFINE FIELD IF NOT EXISTS kind ON exam TYPE string;
253+ DEFINE FIELD IF NOT EXISTS mode ON exam TYPE option<string>;
254+ DEFINE FIELD IF NOT EXISTS starts_at ON exam TYPE option<int>;
255+ DEFINE FIELD IF NOT EXISTS ends_at ON exam TYPE option<int>;
256+ DEFINE FIELD IF NOT EXISTS duration_ms ON exam TYPE option<int>;
257+ DEFINE FIELD IF NOT EXISTS max_attempts ON exam TYPE int DEFAULT 1;
258+ DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true;
259+ DEFINE FIELD IF NOT EXISTS allow_review ON exam TYPE bool DEFAULT false;
260+ DEFINE FIELD IF NOT EXISTS draft ON exam TYPE bool DEFAULT false;
261+ DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course;
262+
263+ DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL;
264+ DEFINE FIELD IF NOT EXISTS exam ON exam_attempt TYPE record<exam>;
265+ DEFINE FIELD IF NOT EXISTS user ON exam_attempt TYPE record<user>;
266+ DEFINE FIELD IF NOT EXISTS seq ON exam_attempt TYPE int DEFAULT 1;
267+ DEFINE FIELD IF NOT EXISTS started_at ON exam_attempt TYPE int;
268+ DEFINE FIELD IF NOT EXISTS finished_at ON exam_attempt TYPE option<int>;
269+ DEFINE FIELD IF NOT EXISTS left_at ON exam_attempt TYPE option<int>;
270+ DEFINE INDEX IF NOT EXISTS exam_attempt_exam_user_seq ON exam_attempt FIELDS exam, user, seq UNIQUE;
271+ DEFINE INDEX IF NOT EXISTS exam_attempt_exam ON exam_attempt FIELDS exam;
272+
273+ DEFINE TABLE IF NOT EXISTS exam_question SCHEMAFULL;
274+ DEFINE FIELD IF NOT EXISTS exam ON exam_question TYPE record<exam>;
275+ DEFINE FIELD IF NOT EXISTS text ON exam_question TYPE string;
276+ DEFINE FIELD IF NOT EXISTS kind ON exam_question TYPE string;
277+ DEFINE FIELD IF NOT EXISTS points ON exam_question TYPE int;
278+ -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices
279+ -- gained stable ids (`array<string>`/`int` -> `array<object>`/`string`),
280+ -- and IF NOT EXISTS would leave an existing database on the old types.
281+ DEFINE FIELD OVERWRITE choices ON exam_question TYPE option<array<object>>;
282+ -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice
283+ -- object's own fields are declared too (same shape as `settings.exam_kinds`).
284+ DEFINE FIELD OVERWRITE choices.*.id ON exam_question TYPE string;
285+ DEFINE FIELD OVERWRITE choices.*.text ON exam_question TYPE string;
286+ DEFINE FIELD OVERWRITE correct ON exam_question TYPE option<string>;
287+ DEFINE FIELD IF NOT EXISTS subject ON exam_question TYPE record<subject>;
288+ -- Provenance, one column per direction: `from_bank` is the template this
289+ -- question was inserted from, `banked_as` the template most recently minted
290+ -- by saving it into the bank. They replace the single `source_bank`, which
291+ -- both directions wrote — so a question inserted from the bank read as
292+ -- already-saved. OVERWRITE (not IF NOT EXISTS): the old column has to
293+ -- actually go on an existing database, or SCHEMAFULL keeps accepting it
294+ -- while the struct no longer writes it.
295+ DEFINE FIELD OVERWRITE from_bank ON exam_question TYPE option<record<bank_question>>;
296+ DEFINE FIELD OVERWRITE banked_as ON exam_question TYPE option<record<bank_question>>;
297+ REMOVE FIELD IF EXISTS source_bank ON TABLE exam_question;
298+ DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam;
299+ DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject;
300+
301+ DEFINE TABLE IF NOT EXISTS question_image SCHEMAFULL;
302+ DEFINE FIELD IF NOT EXISTS exam ON question_image TYPE record<exam>;
303+ DEFINE FIELD IF NOT EXISTS question ON question_image TYPE record<exam_question>;
304+ -- OVERWRITE: `slot` is now the choice's id, not its position.
305+ DEFINE FIELD OVERWRITE slot ON question_image TYPE option<string>;
306+ DEFINE FIELD IF NOT EXISTS file ON question_image TYPE string;
307+ DEFINE FIELD IF NOT EXISTS content_type ON question_image TYPE string;
308+ DEFINE FIELD IF NOT EXISTS size ON question_image TYPE int;
309+ DEFINE INDEX IF NOT EXISTS question_image_exam ON question_image FIELDS exam;
310+ DEFINE INDEX IF NOT EXISTS question_image_question ON question_image FIELDS question;
311+
312+ DEFINE TABLE IF NOT EXISTS bank_question SCHEMAFULL;
313+ DEFINE FIELD IF NOT EXISTS owner ON bank_question TYPE record<user>;
314+ -- OVERWRITE, not IF NOT EXISTS: the field started life as a required
315+ -- `record<subject>` and has to actually change type on an existing database,
316+ -- otherwise the subject-delete cascade (`SET subject = NONE`) is rejected.
317+ DEFINE FIELD OVERWRITE subject ON bank_question TYPE option<record<subject>>;
318+ DEFINE FIELD IF NOT EXISTS text ON bank_question TYPE string;
319+ DEFINE FIELD IF NOT EXISTS kind ON bank_question TYPE string;
320+ DEFINE FIELD IF NOT EXISTS points ON bank_question TYPE int;
321+ -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices
322+ -- gained stable ids (`array<string>`/`int` -> `array<object>`/`string`),
323+ -- and IF NOT EXISTS would leave an existing database on the old types.
324+ DEFINE FIELD OVERWRITE choices ON bank_question TYPE option<array<object>>;
325+ -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice
326+ -- object's own fields are declared too (same shape as `settings.exam_kinds`).
327+ DEFINE FIELD OVERWRITE choices.*.id ON bank_question TYPE string;
328+ DEFINE FIELD OVERWRITE choices.*.text ON bank_question TYPE string;
329+ DEFINE FIELD OVERWRITE correct ON bank_question TYPE option<string>;
330+ DEFINE FIELD IF NOT EXISTS source_exam ON bank_question TYPE option<record<exam>>;
331+ -- 'private' | 'school'. DEFAULT so a row that predates the field (or any
332+ -- partial write) can never come out published: the answer key stays the
333+ -- owner's until they publish it.
334+ DEFINE FIELD IF NOT EXISTS visibility ON bank_question TYPE string DEFAULT 'private';
335+ DEFINE FIELD IF NOT EXISTS created_at ON bank_question TYPE int READONLY;
336+ DEFINE INDEX IF NOT EXISTS bank_question_owner ON bank_question FIELDS owner;
337+ DEFINE INDEX IF NOT EXISTS bank_question_subject ON bank_question FIELDS subject;
338+
339+ DEFINE TABLE IF NOT EXISTS bank_question_image SCHEMAFULL;
340+ DEFINE FIELD IF NOT EXISTS bank_question ON bank_question_image TYPE record<bank_question>;
341+ -- OVERWRITE: `slot` is now the choice's id, not its position.
342+ DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option<string>;
343+ DEFINE FIELD IF NOT EXISTS file ON bank_question_image TYPE string;
344+ DEFINE FIELD IF NOT EXISTS content_type ON bank_question_image TYPE string;
345+ DEFINE FIELD IF NOT EXISTS size ON bank_question_image TYPE int;
346+ DEFINE INDEX IF NOT EXISTS bank_question_image_question ON bank_question_image FIELDS bank_question;
347+
348+ DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL;
349+ DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record<exam>;
350+ DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record<exam_question>;
351+ DEFINE FIELD IF NOT EXISTS user ON exam_answer TYPE record<user>;
352+ -- OVERWRITE: `selected` now names the picked option by id.
353+ DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option<string>;
354+ DEFINE FIELD IF NOT EXISTS text ON exam_answer TYPE option<string>;
355+ DEFINE FIELD IF NOT EXISTS updated_at ON exam_answer TYPE int;
356+ -- `seq` numbers the sitting an answer belongs to (1, 2, …), mirroring
357+ -- exam_attempt. It rides the record key too, so a retake's answer is a new
358+ -- row, not an overwrite of the prior sitting.
359+ DEFINE FIELD IF NOT EXISTS seq ON exam_answer TYPE int DEFAULT 1;
360+ -- Retire the pre-history unique index: (question, user) is no longer unique
361+ -- once a student re-sits; (question, user, seq) is.
362+ REMOVE INDEX IF EXISTS exam_answer_question_user ON exam_answer;
363+ DEFINE INDEX IF NOT EXISTS exam_answer_question_user_seq ON exam_answer FIELDS question, user, seq UNIQUE;
364+ DEFINE INDEX IF NOT EXISTS exam_answer_exam_user ON exam_answer FIELDS exam, user;
365+ DEFINE INDEX IF NOT EXISTS exam_answer_exam ON exam_answer FIELDS exam;
366+
367+ DEFINE TABLE IF NOT EXISTS answer_image SCHEMAFULL;
368+ DEFINE FIELD IF NOT EXISTS exam ON answer_image TYPE record<exam>;
369+ DEFINE FIELD IF NOT EXISTS question ON answer_image TYPE record<exam_question>;
370+ DEFINE FIELD IF NOT EXISTS user ON answer_image TYPE record<user>;
371+ DEFINE FIELD IF NOT EXISTS file ON answer_image TYPE string;
372+ DEFINE FIELD IF NOT EXISTS content_type ON answer_image TYPE string;
373+ DEFINE FIELD IF NOT EXISTS size ON answer_image TYPE int;
374+ -- `seq` numbers the sitting this drawing belongs to; it rides the record
375+ -- key so a retake's image never overwrites the prior sitting's.
376+ DEFINE FIELD IF NOT EXISTS seq ON answer_image TYPE int DEFAULT 1;
377+ DEFINE INDEX IF NOT EXISTS answer_image_exam ON answer_image FIELDS exam;
378+ DEFINE INDEX IF NOT EXISTS answer_image_user ON answer_image FIELDS user;
379+
380+ DEFINE TABLE IF NOT EXISTS exam_result SCHEMAFULL;
381+ DEFINE FIELD IF NOT EXISTS exam ON exam_result TYPE record<exam>;
382+ DEFINE FIELD IF NOT EXISTS user ON exam_result TYPE record<user>;
383+ DEFINE FIELD IF NOT EXISTS mark ON exam_result TYPE int;
384+ DEFINE FIELD IF NOT EXISTS graded_by ON exam_result TYPE record<user>;
385+ -- `seq` numbers the sitting a mark belongs to; a retake earns its own mark
386+ -- row, and the latest seq is the student's standing.
387+ DEFINE FIELD IF NOT EXISTS seq ON exam_result TYPE int DEFAULT 1;
388+ REMOVE INDEX IF EXISTS exam_result_exam_user ON exam_result;
389+ DEFINE INDEX IF NOT EXISTS exam_result_exam_user_seq ON exam_result FIELDS exam, user, seq UNIQUE;
390+
391+ DEFINE TABLE IF NOT EXISTS pool_question SCHEMAFULL;
392+ DEFINE FIELD IF NOT EXISTS asker ON pool_question TYPE record<user>;
393+ DEFINE FIELD IF NOT EXISTS title ON pool_question TYPE string;
394+ DEFINE FIELD IF NOT EXISTS body ON pool_question TYPE string;
395+ DEFINE FIELD IF NOT EXISTS status ON pool_question TYPE string DEFAULT 'pending';
396+ DEFINE FIELD IF NOT EXISTS asked_at ON pool_question TYPE int;
397+ DEFINE FIELD IF NOT EXISTS approved_by ON pool_question TYPE option<record<user>>;
398+ DEFINE FIELD IF NOT EXISTS image_file ON pool_question TYPE option<string>;
399+ DEFINE FIELD IF NOT EXISTS image_content_type ON pool_question TYPE option<string>;
400+ DEFINE FIELD IF NOT EXISTS image_size ON pool_question TYPE option<int>;
401+ DEFINE INDEX IF NOT EXISTS pool_question_status ON pool_question FIELDS status;
402+ DEFINE INDEX IF NOT EXISTS pool_question_asker ON pool_question FIELDS asker;
403+
404+ DEFINE TABLE IF NOT EXISTS solution SCHEMAFULL;
405+ DEFINE FIELD IF NOT EXISTS question ON solution TYPE record<pool_question>;
406+ DEFINE FIELD IF NOT EXISTS author ON solution TYPE record<user>;
407+ DEFINE FIELD IF NOT EXISTS body ON solution TYPE string;
408+ DEFINE FIELD IF NOT EXISTS offered_at ON solution TYPE int;
409+ DEFINE FIELD IF NOT EXISTS image_file ON solution TYPE option<string>;
410+ DEFINE FIELD IF NOT EXISTS image_content_type ON solution TYPE option<string>;
411+ DEFINE FIELD IF NOT EXISTS image_size ON solution TYPE option<int>;
412+ DEFINE INDEX IF NOT EXISTS solution_question ON solution FIELDS question;
413+
414+ DEFINE TABLE IF NOT EXISTS settings SCHEMAFULL;
415+ DEFINE FIELD IF NOT EXISTS exam_kinds ON settings TYPE array<object>;
416+ DEFINE FIELD IF NOT EXISTS exam_kinds.*.name ON settings TYPE string;
417+ DEFINE FIELD IF NOT EXISTS exam_kinds.*.weight ON settings TYPE int;
418+ DEFINE FIELD IF NOT EXISTS attendance_statuses ON settings TYPE array<string>;
419+ DEFINE FIELD IF NOT EXISTS grade_bands ON settings TYPE array<object>;
420+ DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int;
421+ DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string;
422+ DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option<int>;
423+ DEFINE FIELD IF NOT EXISTS chatbot_history_turns ON settings TYPE option<int>;
424+ DEFINE FIELD IF NOT EXISTS max_chatbot_threads ON settings TYPE option<int>;
425+ DEFINE FIELD IF NOT EXISTS max_chatbot_message_len ON settings TYPE option<int>;
426+ -- Food program (2026-07-26). `meal_slots` mirrors the `exam_kinds` shape —
427+ -- a named list a menu snapshots from — and `dietary_tags` mirrors
428+ -- `attendance_statuses`. `meal_cancel_cutoff_minutes` is ONE knob for both
429+ -- the booking and the cancel deadline; absent means no cutoff at all. All
430+ -- three are `option<>`, exactly like `max_file_bytes`: NOT `DEFAULT []`.
431+ -- `DEFAULT` fires on create only, and `PATCH /settings` writes the whole
432+ -- row with `UPDATE ... CONTENT`, so a required-with-default field a writer
433+ -- omits coerces to NONE and fails every settings write until the domain
434+ -- struct carries it. `option<>` also means the existing singleton reads
435+ -- fine, which is why the food program needs no BACKFILL anywhere.
436+ DEFINE FIELD IF NOT EXISTS meal_slots ON settings TYPE option<array<object>>;
437+ DEFINE FIELD IF NOT EXISTS meal_slots.*.name ON settings TYPE string;
438+ -- Minutes past midnight UTC at which the slot is served (2026-07-26).
439+ -- `option<int>` for the same reason the list itself is: slots written
440+ -- before the field existed simply have no key, and read back as NONE ->
441+ -- the booking cutoff falls back to midnight UTC, its old meaning. No
442+ -- BACKFILL, and no DEFAULT — see the note above.
443+ DEFINE FIELD IF NOT EXISTS meal_slots.*.serving_minute ON settings TYPE option<int>;
444+ DEFINE FIELD IF NOT EXISTS dietary_tags ON settings TYPE option<array<string>>;
445+ DEFINE FIELD IF NOT EXISTS meal_cancel_cutoff_minutes ON settings TYPE option<int>;
446+
447+ -- Homework (greenfield, 2026-07-22): a teacher assigns per course, students
448+ -- submit files + optional text, a teacher grades a status + optional mark.
449+ -- `course`/`created_by`/`created_at` are READONLY (a homework never moves
450+ -- course, and stamps never rewrite); `subject` is NOT — it is re-taggable
451+ -- via PATCH. `assigned` NONE/empty means the whole course. No BACKFILL: the
452+ -- tables are new, so the whole migration stays additive and idempotent.
453+ DEFINE TABLE IF NOT EXISTS homework SCHEMAFULL;
454+ DEFINE FIELD IF NOT EXISTS course ON homework TYPE record<course> READONLY;
455+ DEFINE FIELD IF NOT EXISTS subject ON homework TYPE record<subject>;
456+ DEFINE FIELD IF NOT EXISTS title ON homework TYPE string;
457+ DEFINE FIELD IF NOT EXISTS description ON homework TYPE option<string>;
458+ DEFINE FIELD IF NOT EXISTS due_at ON homework TYPE int;
459+ DEFINE FIELD IF NOT EXISTS assigned ON homework TYPE option<array<record<user>>>;
460+ DEFINE FIELD IF NOT EXISTS assigned[*] ON homework TYPE record<user>;
461+ DEFINE FIELD IF NOT EXISTS created_by ON homework TYPE record<user> READONLY;
462+ DEFINE FIELD IF NOT EXISTS created_at ON homework TYPE int READONLY;
463+ DEFINE INDEX IF NOT EXISTS homework_course ON homework FIELDS course;
464+
465+ DEFINE TABLE IF NOT EXISTS homework_submission SCHEMAFULL;
466+ DEFINE FIELD IF NOT EXISTS homework ON homework_submission TYPE record<homework> READONLY;
467+ DEFINE FIELD IF NOT EXISTS user ON homework_submission TYPE record<user> READONLY;
468+ DEFINE FIELD IF NOT EXISTS text ON homework_submission TYPE option<string>;
469+ DEFINE FIELD IF NOT EXISTS submitted_at ON homework_submission TYPE int READONLY;
470+ DEFINE FIELD IF NOT EXISTS updated_at ON homework_submission TYPE int;
471+ DEFINE FIELD IF NOT EXISTS file_count ON homework_submission TYPE option<int>;
472+ DEFINE INDEX IF NOT EXISTS homework_submission_homework ON homework_submission FIELDS homework;
473+
474+ DEFINE TABLE IF NOT EXISTS homework_file SCHEMAFULL;
475+ DEFINE FIELD IF NOT EXISTS submission ON homework_file TYPE record<homework_submission> READONLY;
476+ DEFINE FIELD IF NOT EXISTS name ON homework_file TYPE string;
477+ DEFINE FIELD IF NOT EXISTS content_type ON homework_file TYPE string;
478+ DEFINE FIELD IF NOT EXISTS size ON homework_file TYPE int;
479+ DEFINE FIELD IF NOT EXISTS file ON homework_file TYPE string READONLY;
480+ DEFINE FIELD IF NOT EXISTS created_at ON homework_file TYPE int READONLY;
481+ DEFINE INDEX IF NOT EXISTS homework_file_submission ON homework_file FIELDS submission;
482+
483+ DEFINE TABLE IF NOT EXISTS homework_result SCHEMAFULL;
484+ DEFINE FIELD IF NOT EXISTS homework ON homework_result TYPE record<homework> READONLY;
485+ DEFINE FIELD IF NOT EXISTS user ON homework_result TYPE record<user> READONLY;
486+ DEFINE FIELD IF NOT EXISTS status ON homework_result TYPE string;
487+ DEFINE FIELD IF NOT EXISTS mark ON homework_result TYPE option<int>;
488+ DEFINE FIELD IF NOT EXISTS graded_by ON homework_result TYPE record<user>;
489+ DEFINE FIELD IF NOT EXISTS created_at ON homework_result TYPE int;
490+ DEFINE INDEX IF NOT EXISTS homework_result_homework ON homework_result FIELDS homework;
491+
492+ -- Appointments (greenfield, 2026-07-23): a teacher publishes availability
493+ -- slots, a student or parent books one. `series` groups the occurrences a
494+ -- weekly repeat expanded into, so one cancel deletes one row and a series
495+ -- delete finds the rest. A booking's live/dead state is the `status`
496+ -- string; occupancy is derived from it under the appointment lock rather
497+ -- than stored, so a rejected or cancelled booking frees its slot again.
498+ -- The `proposed_*` fields carry a teacher's counter-proposal on the same
499+ -- row until the requester accepts. No BACKFILL: both tables are new.
500+ DEFINE TABLE IF NOT EXISTS appointment_slot SCHEMAFULL;
501+ DEFINE FIELD IF NOT EXISTS teacher ON appointment_slot TYPE record<user>;
502+ DEFINE FIELD IF NOT EXISTS starts_at ON appointment_slot TYPE int;
503+ DEFINE FIELD IF NOT EXISTS ends_at ON appointment_slot TYPE int;
504+ DEFINE FIELD IF NOT EXISTS note ON appointment_slot TYPE option<string>;
505+ DEFINE FIELD IF NOT EXISTS series ON appointment_slot TYPE option<string>;
506+ DEFINE FIELD IF NOT EXISTS created_at ON appointment_slot TYPE int;
507+ DEFINE INDEX IF NOT EXISTS appointment_slot_teacher_starts ON appointment_slot FIELDS teacher, starts_at;
508+ DEFINE INDEX IF NOT EXISTS appointment_slot_series ON appointment_slot FIELDS series;
509+
510+ DEFINE TABLE IF NOT EXISTS appointment SCHEMAFULL;
511+ DEFINE FIELD IF NOT EXISTS slot ON appointment TYPE record<appointment_slot>;
512+ DEFINE FIELD IF NOT EXISTS requester ON appointment TYPE record<user>;
513+ DEFINE FIELD IF NOT EXISTS status ON appointment TYPE string DEFAULT 'pending';
514+ DEFINE FIELD IF NOT EXISTS reason ON appointment TYPE string;
515+ DEFINE FIELD IF NOT EXISTS proposed_starts_at ON appointment TYPE option<int>;
516+ DEFINE FIELD IF NOT EXISTS proposed_ends_at ON appointment TYPE option<int>;
517+ DEFINE FIELD IF NOT EXISTS proposed_by ON appointment TYPE option<record<user>>;
518+ DEFINE FIELD IF NOT EXISTS decided_by ON appointment TYPE option<record<user>>;
519+ DEFINE FIELD IF NOT EXISTS cancelled_by ON appointment TYPE option<record<user>>;
520+ DEFINE FIELD IF NOT EXISTS cancel_reason ON appointment TYPE option<string>;
521+ DEFINE FIELD IF NOT EXISTS reject_reason ON appointment TYPE option<string>;
522+ DEFINE FIELD IF NOT EXISTS created_at ON appointment TYPE int;
523+ DEFINE INDEX IF NOT EXISTS appointment_slot_ref ON appointment FIELDS slot;
524+ DEFINE INDEX IF NOT EXISTS appointment_requester ON appointment FIELDS requester;
525+ DEFINE INDEX IF NOT EXISTS appointment_status ON appointment FIELDS status;
526+
527+ -- Food program (greenfield, 2026-07-26): a published menu per day+slot,
528+ -- dishes on it, a dietary profile per student, bookings against a menu's
529+ -- capacity, who actually ate, and the money that moved. `date` is a
530+ -- calendar day as `YYYY-MM-DD` text, not a timestamp: the unique index is
531+ -- an equality test and a midnight-in-millis day is only unique for one
532+ -- timezone. `slot` is snapshotted text, not a link, so retiring a slot in
533+ -- settings never rewrites a past menu. Stamps stay `int` millis like the
534+ -- rest of the schema. No BACKFILL: all six tables are new.
535+ DEFINE TABLE IF NOT EXISTS menu SCHEMAFULL;
536+ DEFINE FIELD IF NOT EXISTS date ON menu TYPE string READONLY;
537+ DEFINE FIELD IF NOT EXISTS slot ON menu TYPE string READONLY;
538+ DEFINE FIELD IF NOT EXISTS capacity ON menu TYPE option<int>;
539+ DEFINE FIELD IF NOT EXISTS created_by ON menu TYPE record<user> READONLY;
540+ DEFINE FIELD IF NOT EXISTS created_at ON menu TYPE int READONLY;
541+ DEFINE INDEX IF NOT EXISTS menu_date_slot ON menu FIELDS date, slot UNIQUE;
542+
543+ DEFINE TABLE IF NOT EXISTS menu_dish SCHEMAFULL;
544+ DEFINE FIELD IF NOT EXISTS menu ON menu_dish TYPE record<menu> READONLY;
545+ DEFINE FIELD IF NOT EXISTS name ON menu_dish TYPE string;
546+ DEFINE FIELD IF NOT EXISTS description ON menu_dish TYPE option<string>;
547+ -- Money is minor units (kuruş) as an integer, everywhere. Never decimal.
548+ DEFINE FIELD IF NOT EXISTS price_minor ON menu_dish TYPE int;
549+ DEFINE FIELD IF NOT EXISTS tags ON menu_dish TYPE array<string> DEFAULT [];
550+ DEFINE FIELD IF NOT EXISTS tags[*] ON menu_dish TYPE string;
551+ DEFINE FIELD IF NOT EXISTS created_at ON menu_dish TYPE int READONLY;
552+ DEFINE INDEX IF NOT EXISTS menu_dish_menu ON menu_dish FIELDS menu;
553+
554+ DEFINE TABLE IF NOT EXISTS dietary_profile SCHEMAFULL;
555+ DEFINE FIELD IF NOT EXISTS student ON dietary_profile TYPE record<user> READONLY;
556+ DEFINE FIELD IF NOT EXISTS tags ON dietary_profile TYPE array<string> DEFAULT [];
557+ DEFINE FIELD IF NOT EXISTS tags[*] ON dietary_profile TYPE string;
558+ DEFINE FIELD IF NOT EXISTS note ON dietary_profile TYPE option<string>;
559+ DEFINE FIELD IF NOT EXISTS updated_by ON dietary_profile TYPE record<user>;
560+ DEFINE FIELD IF NOT EXISTS updated_at ON dietary_profile TYPE int;
561+ DEFINE INDEX IF NOT EXISTS dietary_profile_student ON dietary_profile FIELDS student UNIQUE;
562+
563+ -- A cancel flips `status` and stamps `cancelled_at`; the row stays so the
564+ -- freed seat is still auditable against the ledger line it charged.
565+ DEFINE TABLE IF NOT EXISTS meal_booking SCHEMAFULL;
566+ DEFINE FIELD IF NOT EXISTS menu ON meal_booking TYPE record<menu> READONLY;
567+ DEFINE FIELD IF NOT EXISTS student ON meal_booking TYPE record<user> READONLY;
568+ DEFINE FIELD IF NOT EXISTS booked_by ON meal_booking TYPE record<user> READONLY;
569+ DEFINE FIELD IF NOT EXISTS status ON meal_booking TYPE string DEFAULT 'booked';
570+ -- How many times this seat has been taken, and what it cost when the
571+ -- *current* attempt took it (NONE = the menu was free then). Together they
572+ -- key the attempt's ledger lines, which is what makes billing idempotent
573+ -- by identity rather than by scanning for an outstanding charge.
574+ DEFINE FIELD IF NOT EXISTS attempt ON meal_booking TYPE int DEFAULT 1;
575+ DEFINE FIELD IF NOT EXISTS price_minor ON meal_booking TYPE option<int>;
576+ DEFINE FIELD IF NOT EXISTS cancelled_at ON meal_booking TYPE option<int>;
577+ DEFINE FIELD IF NOT EXISTS created_at ON meal_booking TYPE int READONLY;
578+ DEFINE INDEX IF NOT EXISTS meal_booking_menu ON meal_booking FIELDS menu;
579+ DEFINE INDEX IF NOT EXISTS meal_booking_student ON meal_booking FIELDS student;
580+
581+ DEFINE TABLE IF NOT EXISTS meal_attendance SCHEMAFULL;
582+ DEFINE FIELD IF NOT EXISTS menu ON meal_attendance TYPE record<menu> READONLY;
583+ DEFINE FIELD IF NOT EXISTS student ON meal_attendance TYPE record<user> READONLY;
584+ DEFINE FIELD IF NOT EXISTS status ON meal_attendance TYPE string;
585+ DEFINE FIELD IF NOT EXISTS marked_by ON meal_attendance TYPE record<user>;
586+ DEFINE FIELD IF NOT EXISTS marked_at ON meal_attendance TYPE int;
587+ DEFINE INDEX IF NOT EXISTS meal_attendance_menu_student ON meal_attendance FIELDS menu, student UNIQUE;
588+
589+ -- APPEND-ONLY by design: a mistake is corrected with an opposing
590+ -- `reversal` line, never by editing or deleting one. Hence every field is
591+ -- READONLY. `source` is untyped on purpose — a charge points at the
592+ -- booking that caused it, a reversal at the line it undoes.
593+ DEFINE TABLE IF NOT EXISTS meal_ledger SCHEMAFULL;
594+ DEFINE FIELD IF NOT EXISTS student ON meal_ledger TYPE record<user> READONLY;
595+ DEFINE FIELD IF NOT EXISTS kind ON meal_ledger TYPE string READONLY;
596+ DEFINE FIELD IF NOT EXISTS amount_minor ON meal_ledger TYPE int READONLY;
597+ DEFINE FIELD IF NOT EXISTS source ON meal_ledger TYPE option<record> READONLY;
598+ DEFINE FIELD IF NOT EXISTS method ON meal_ledger TYPE option<string> READONLY;
599+ DEFINE FIELD IF NOT EXISTS note ON meal_ledger TYPE option<string> READONLY;
600+ DEFINE FIELD IF NOT EXISTS recorded_by ON meal_ledger TYPE record<user> READONLY;
601+ DEFINE FIELD IF NOT EXISTS created_at ON meal_ledger TYPE int READONLY;
602+ DEFINE INDEX IF NOT EXISTS meal_ledger_student ON meal_ledger FIELDS student;
603+";
604+
605+/// Data backfills for rows written by older binaries. Runs *after* (and apart
606+/// from) the DDL batch so every statement sees the freshly defined schema —
607+/// see the `MIGRATION` doc for why sharing the batch corrupts the writes.
608+/// Idempotent: each backfill's `WHERE` only matches unconverted rows.
609+pub const BACKFILL: &str = "
610+ UPDATE user SET role = 'student' WHERE role = NONE;
611+
612+ UPDATE course SET kind = 'course' WHERE kind = NONE;
613+
614+ -- Courses predate assignable teachers (2026-07-21): every existing course
615+ -- was run by its creator alone, so it starts with nobody else assigned.
616+ UPDATE course SET teachers = [] WHERE teachers = NONE;
617+
618+ -- Exams predate the draft flag (2026-07-19): everything already out there
619+ -- was live for its course, so it stays published.
620+ UPDATE exam SET draft = false WHERE draft = NONE;
621+
622+ -- Exams predate the review toggle (2026-07-24): default it closed (opt-in).
623+ UPDATE exam SET allow_review = false WHERE allow_review = NONE;
624+
625+ UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {};
626+
627+ -- Questions written before subjects existed (2026-07-17) are destroyed, not
628+ -- backfilled: a subject is mandatory and there is nothing truthful to
629+ -- assign. Their answers go first so no answer row outlives its question.
630+ DELETE exam_answer WHERE question IN (SELECT VALUE id FROM exam_question WHERE subject = NONE);
631+ DELETE exam_question WHERE subject = NONE;
632+
633+ -- The hand-picked `users` audience retired into `registration` (2026-07-16):
634+ -- each listed user becomes a signup row credited to the event's creator, and
635+ -- the event becomes an uncapped registration list. Runs once — converted
636+ -- events no longer match the `kind = 'users'` filter. (`?? []`: an empty
637+ -- statement-subquery evaluates to NONE, which FOR refuses to iterate.)
638+ FOR $ev IN ((SELECT id, creator, audience FROM event WHERE audience.kind = 'users') ?? []) {
639+ FOR $usr IN ($ev.audience.users ?? []) {
640+ UPSERT type::record('registration', string::concat(record::id($ev.id), '_', record::id($usr))) CONTENT {
641+ event: $ev.id,
642+ user: $usr,
643+ registered_by: $ev.creator,
644+ };
645+ };
646+ UPDATE $ev.id SET audience = { kind: 'registration' };
647+ };
648+
649+ -- Turns written before the clipped-answer flag existed (2026-07-23): the
650+ -- clip was silent then, so nothing can be recovered — they read as whole,
651+ -- which is what they were presented as all along.
652+ UPDATE chatbot_message SET truncated = false WHERE truncated = NONE;
653+
654+ -- An assistant turn is answered by a claim loop in some replica's process,
655+ -- so a restart can leave its row `pending` with nobody left to complete it.
656+ -- Only rows past the stale horizon ($stale_ms, from
657+ -- `CHATBOT_PENDING_STALE_SECS`) are certainly abandoned though: a young one
658+ -- may still be being answered on the other side of the AI bridge, and a
659+ -- deploy must not shoot down a turn dispatched seconds ago. Nothing is lost
660+ -- by waiting — a reader already presents an over-age `pending` row as
661+ -- failed, and the next boot sweeps for real whatever crossed the horizon in
662+ -- the meantime.
663+ --
664+ -- Claim-aware since 2026-07-27, because the sweep is no longer school-wide
665+ -- truth: under N replicas the row may belong to a *live peer's* claim loop,
666+ -- and failing it here would shoot down another process's in-flight turn.
667+ -- So a claim restamped within the window is left alone. Both disjuncts
668+ -- matter — `claimed_by = NONE` alone would strand every row whose claimer
669+ -- died, which is the one case the sweep exists for.
670+ --
671+ -- The claim age is measured against $stale_ms rather than
672+ -- CHATBOT_CLAIM_RECLAIM_SECS only because the boot binds one horizon (see
673+ -- `database::migration_binds`); erring long is the safe direction — the
674+ -- cost is that a row claimed just before it aged out waits one more boot
675+ -- for its durable stamp, while readers have shown it failed all along.
676+ UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted',
677+ completed_at = time::unix(time::now()) * 1000
678+ WHERE status = 'pending' AND created_at < time::unix(time::now()) * 1000 - $stale_ms
679+ AND (claimed_by = NONE
680+ OR claimed_at < time::unix(time::now()) * 1000 - $stale_ms);
681+
682+ -- Promotion out of student now deletes the user's enrollments (2026-07-18);
683+ -- this sweeps rows promoted before that fix. A deleted user reads as
684+ -- `user.role = NONE`, which is also != 'student' — those rows go too.
685+ DELETE enrollment WHERE user.role != 'student';
686+
687+ -- Choices gained stable ids (2026-07-24): `choices` held bare strings and
688+ -- `correct`/`selected`/`slot` held the option's *position*. The DDL above
689+ -- retypes those columns, which leaves every old-shaped row readable but
690+ -- unwritable ('Expected `none | array<object>` but found `[..]`'), so this
691+ -- conversion is repair, not cosmetics.
692+ --
693+ -- Ids are minted in array order, so the id at position i *is* the id for
694+ -- old index i — that identity is what keeps a stored answer, and an option
695+ -- picture, pointing at the option the student actually saw. Hence the
696+ -- dependent rows are remapped inside the loop that mints `$new`, against
697+ -- that same array: once the ids are stored the positions are still
698+ -- recoverable, but nothing guarantees a later pass would look them up the
699+ -- same way. `WHERE choices[0] != NONE AND type::is_string(choices[0])`
700+ -- matches only unconverted rows, so a second boot re-mints nothing; an
701+ -- empty or absent `choices` needs no conversion at all. A question-level
702+ -- picture (`slot = NONE`) is not an index and is left alone.
703+ --
704+ -- Runs *before* every other backfill that writes these rows (the `seq`
705+ -- stamps below): a write coerces the whole record, so touching a row for
706+ -- any reason fails while its choices are still positional. For the same
707+ -- reason the answer's remap stamps `seq` itself — the two legacy gaps sit
708+ -- on the same row, and a write that fixes only one of them is rejected for
709+ -- the other. `seq ?? 1` leaves an already-numbered sitting alone (DEFAULT
710+ -- fills a CREATE, not an UPDATE of a row that predates the column).
711+ FOR $q IN ((SELECT id, choices, correct FROM exam_question
712+ WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) {
713+ LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c });
714+ UPDATE $q.id SET choices = $new,
715+ correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id };
716+ FOR $img IN ((SELECT id, slot FROM question_image
717+ WHERE question = $q.id AND type::is_int(slot)) ?? []) {
718+ UPDATE $img.id SET slot = $new[$img.slot].id;
719+ };
720+ FOR $ans IN ((SELECT id, selected FROM exam_answer
721+ WHERE question = $q.id AND type::is_int(selected)) ?? []) {
722+ UPDATE $ans.id SET selected = $new[$ans.selected].id, seq = seq ?? 1;
723+ };
724+ };
725+
726+ FOR $q IN ((SELECT id, choices, correct FROM bank_question
727+ WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) {
728+ LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c });
729+ UPDATE $q.id SET choices = $new,
730+ correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id };
731+ FOR $img IN ((SELECT id, slot FROM bank_question_image
732+ WHERE bank_question = $q.id AND type::is_int(slot)) ?? []) {
733+ UPDATE $img.id SET slot = $new[$img.slot].id;
734+ };
735+ };
736+
737+ -- Per-attempt history (2026-07-24): answers, drawings, and marks written
738+ -- before retakes stopped wiping belong to the student's first sitting.
739+ -- They already use the bare (seq==1) record key, so only the denormalized
740+ -- `seq` field needs stamping.
741+ UPDATE exam_answer SET seq = 1 WHERE seq = NONE;
742+ UPDATE answer_image SET seq = 1 WHERE seq = NONE;
743+ UPDATE exam_result SET seq = 1 WHERE seq = NONE;
744+
745+ -- Count caps became cross-replica (2026-07-27): the authority moved from a
746+ -- process-wide mutex to a counter column on the parent row, so every parent
747+ -- that predates the column is seeded from the children it actually has.
748+ -- Runs LAST, after the sweeps above have deleted whatever they delete.
749+ --
750+ -- Deliberately one-time (`= NONE` guards every write): a peer replica is
751+ -- serving while this boots, and recomputing a counter it is concurrently
752+ -- incrementing would hand back a seat that is already taken. An absent
753+ -- counter reads as zero, so the group pass runs before the zero pass.
754+ FOR $row IN ((SELECT course, count() AS n FROM enrollment GROUP BY course) ?? []) {
755+ UPDATE $row.course SET enrollment_count = $row.n WHERE enrollment_count = NONE;
756+ };
757+ UPDATE course SET enrollment_count = 0 WHERE enrollment_count = NONE;
758+
759+ FOR $row IN ((SELECT event, count() AS n FROM registration GROUP BY event) ?? []) {
760+ UPDATE $row.event SET registration_count = $row.n WHERE registration_count = NONE;
761+ };
762+ UPDATE event SET registration_count = 0 WHERE registration_count = NONE;
763+
764+ FOR $row IN ((SELECT note, count() AS n FROM note_file GROUP BY note) ?? []) {
765+ UPDATE $row.note SET file_count = $row.n WHERE file_count = NONE;
766+ };
767+ UPDATE note SET file_count = 0 WHERE file_count = NONE;
768+
769+ FOR $row IN ((SELECT submission, count() AS n FROM homework_file GROUP BY submission) ?? []) {
770+ UPDATE $row.submission SET file_count = $row.n WHERE file_count = NONE;
771+ };
772+ UPDATE homework_submission SET file_count = 0 WHERE file_count = NONE;
773+
774+ FOR $row IN ((SELECT user_id, count() AS n FROM chatbot_thread GROUP BY user_id) ?? []) {
775+ UPDATE $row.user_id SET chatbot_thread_count = $row.n WHERE chatbot_thread_count = NONE;
776+ };
777+ UPDATE user SET chatbot_thread_count = 0 WHERE chatbot_thread_count = NONE;
778+";
779+
780+/// The migration batches, in the order a boot applies them — and the *only*
781+/// list of them. [`crate::database::migrate`] runs exactly these and
782+/// [`crate::database::migration_fingerprint`] hashes exactly these, so a fourth
783+/// batch cannot be executed without changing the fingerprint that decides
784+/// whether a peer's schema is ours. They stay three separate queries: statements
785+/// in one batch see the schema as it stood when the batch started (see
786+/// `MIGRATION`).
787+pub const MIGRATION_BATCHES: [&str; 3] = [PRE_REPAIR, MIGRATION, BACKFILL];
src/rate_limit.rsmodified+256 -9
@@ -1,5 +1,6 @@
1 //! Rate limiting, hand-rolled on a fixed 60-second window — no extra crates,1 //! Rate limiting, hand-rolled on a fixed 60-second window — no extra crates,
2-//! no background tasks. The counter is keyed generically: by client IP for the2+//! and nothing on the request path but a mutex (the one background task below
3+//! only shares counters). The counter is keyed generically: by client IP for the
3 //! middleware tiers below, by user id for the per-user chatbot tier4 //! middleware tiers below, by user id for the per-user chatbot tier
4 //! ([`UserRateLimiter`]), which cannot be middleware because the caller is only5 //! ([`UserRateLimiter`]), which cannot be middleware because the caller is only
5 //! known once `CurrentUser` has run.6 //! known once `CurrentUser` has run.
@@ -23,6 +24,24 @@
23 //! Fixed windows admit up to a 2× burst straddling a window boundary. That is24 //! Fixed windows admit up to a 2× burst straddling a window boundary. That is
24 //! an accepted trade-off for an implementation simple enough to read in one25 //! an accepted trade-off for an implementation simple enough to read in one
25 //! sitting; argon2 keeps each allowed login attempt expensive anyway.26 //! sitting; argon2 keeps each allowed login attempt expensive anyway.
27+//!
28+//! # Across replicas
29+//!
30+//! The counters above are per process, and the backend runs as two replicas —
31+//! so a client hitting both got twice its budget. [`RateLimiter::share`] closes
32+//! that: a background task folds each bucket's new admits into one shared row
33+//! per tier + client + wall window (`rate_limit`, see
34+//! [`crate::constant::RATE_LIMIT_TABLE`]) every
35+//! [`crate::constant::RATE_SYNC_INTERVAL_SECS`], and the fleet-wide total that
36+//! comes back caps what the local bucket admits for the rest of that window.
37+//!
38+//! Admission itself stays in memory and stays synchronous — no request ever
39+//! waits on the database to be let in, and a database that is down or slow
40+//! costs nothing but the sharing (the tiers fall back to their local budgets
41+//! rather than failing anyone). The cost is a lag: within one interval a
42+//! replica can spend up to its own full budget before the shared total tells
43+//! it to stop, so the fleet's worst case is `replicas × max` for one interval
44+//! and `max` from then on.
26 45
27 use std::collections::HashMap;46 use std::collections::HashMap;
28 use std::hash::Hash;47 use std::hash::Hash;
@@ -33,13 +52,19 @@ use std::time::Duration;
33 use axum::extract::{ConnectInfo, Request};52 use axum::extract::{ConnectInfo, Request};
34 use axum::middleware::Next;53 use axum::middleware::Next;
35 use axum::response::Response;54 use axum::response::Response;
55+use surrealdb::types::RecordId;
36 // tokio's `Instant` wraps `std::time::Instant` in production but obeys56 // tokio's `Instant` wraps `std::time::Instant` in production but obeys
37 // `tokio::time::pause`/`advance` under `start_paused` tests, which makes the57 // `tokio::time::pause`/`advance` under `start_paused` tests, which makes the
38 // window arithmetic below testable without sleeping.58 // window arithmetic below testable without sleeping.
39 use tokio::time::Instant;59 use tokio::time::Instant;
40 60
41-use crate::constant::PURGE_AT;61+use crate::constant::{
62+ PURGE_AT, RATE_LIMIT_TABLE, RATE_SYNC_INTERVAL_SECS, RATE_SYNC_MAX_KEYS, RATE_SYNC_TIMEOUT_SECS,
63+};
64+use crate::database::Database;
65+use crate::domain::timestamp::Timestamp;
42 use crate::error::AppError;66 use crate::error::AppError;
67+use crate::state::DbHealth;
43 68
44 /// Per-IP rate-limit knobs, sourced from the environment (see `.env.example`) and69 /// Per-IP rate-limit knobs, sourced from the environment (see `.env.example`) and
45 /// carried in [`crate::state::AppState`]. A `0` limit disables that tier.70 /// carried in [`crate::state::AppState`]. A `0` limit disables that tier.
@@ -80,7 +105,40 @@ pub struct RateLimiter<K = IpAddr> {
80 105
81 struct Bucket {106 struct Bucket {
82 window_start: Instant,107 window_start: Instant,
108+ /// Requests this process admitted in the current local window.
83 count: u32,109 count: u32,
110+ /// How many of `count` the sync task has already folded into the shared
111+ /// row. Never above `count`, so `count - pushed` is what is still ours to
112+ /// report.
113+ pushed: u32,
114+ /// The fleet-wide total the last sync read back — everyone's admits,
115+ /// `pushed` included. Zero until a sync lands, which is what makes an
116+ /// unshared limiter behave exactly like the local-only one it replaced.
117+ remote: u32,
118+ /// The wall window (`RATE_LIMIT_TABLE` row) `pushed`/`remote` describe.
119+ /// The local window rolls per client while the shared one is aligned to the
120+ /// clock, so this says which shared row those two numbers came from.
121+ epoch: i64,
122+}
123+
124+impl Bucket {
125+ /// A fresh window: nothing admitted, nothing shared, nothing known.
126+ fn opened_at(now: Instant) -> Self {
127+ Self {
128+ window_start: now,
129+ count: 0,
130+ pushed: 0,
131+ remote: 0,
132+ epoch: 0,
133+ }
134+ }
135+
136+ /// Requests the whole fleet has spent in this window as far as this process
137+ /// can tell: what every replica had reported at the last sync, plus our own
138+ /// admits since. Equals `count` until a sync lands.
139+ fn spent(&self) -> u32 {
140+ self.remote.saturating_add(self.count - self.pushed)
141+ }
84 }142 }
85 143
86 impl<K> RateLimiter<K> {144 impl<K> RateLimiter<K> {
@@ -168,16 +226,15 @@ impl<K: Eq + Hash> RateLimiter<K> {
168 buckets.retain(|_, b| now.duration_since(b.window_start) < self.window);226 buckets.retain(|_, b| now.duration_since(b.window_start) < self.window);
169 }227 }
170 228
171- let bucket = buckets.entry(key).or_insert(Bucket {229+ let bucket = buckets.entry(key).or_insert_with(|| Bucket::opened_at(now));
172- window_start: now,
173- count: 0,
174- });
175 if now.duration_since(bucket.window_start) >= self.window {230 if now.duration_since(bucket.window_start) >= self.window {
176- bucket.window_start = now;231+ // A fresh window starts owing nothing and knowing nothing: keeping
177- bucket.count = 0;232+ // the old total would hold the client at a budget it no longer
233+ // spent. The next sync re-reads what the fleet has spent since.
234+ *bucket = Bucket::opened_at(now);
178 }235 }
179 236
180- if bucket.count < self.max {237+ if bucket.spent() < self.max {
181 bucket.count += 1;238 bucket.count += 1;
182 Ok(())239 Ok(())
183 } else {240 } else {
@@ -187,6 +244,196 @@ impl<K: Eq + Hash> RateLimiter<K> {
187 }244 }
188 }245 }
189 246
247+/// One bucket's report, taken while the map was locked so the round can run
248+/// its query without holding it. `counted` is the `count` the delta was read
249+/// from — a request admitted mid-round bumps `count` past it and is simply
250+/// carried into the next round.
251+struct Pending<K> {
252+ key: K,
253+ delta: u32,
254+ counted: u32,
255+ window_start: Instant,
256+}
257+
258+impl<K> RateLimiter<K>
259+where
260+ K: Eq + Hash + Clone + std::fmt::Display + Send + Sync + 'static,
261+{
262+ /// Make this tier's budget fleet-wide: every
263+ /// [`RATE_SYNC_INTERVAL_SECS`] a background task reports what this replica
264+ /// has admitted and reads back what everyone has, which caps further local
265+ /// admits in the same window (see the module docs).
266+ ///
267+ /// `tier` names the counter's namespace in the shared table — two limiters
268+ /// sharing a name share a budget, which is exactly what the two processes
269+ /// running the same tier want and what `auth` and `api` must avoid.
270+ ///
271+ /// The task holds a *weak* reference to the buckets, so it stops with the
272+ /// limiter rather than keeping a dropped one alive (test suites build
273+ /// dozens).
274+ pub fn share(&self, tier: &'static str, db: Database, db_up: DbHealth) {
275+ if self.max == 0 {
276+ // The tier is off: `check` records nothing, so there is nothing to
277+ // share and no reason to hold a task or a table row.
278+ return;
279+ }
280+ let buckets = Arc::downgrade(&self.buckets);
281+ let window = self.window;
282+ tokio::spawn(async move {
283+ let mut swept = 0;
284+ loop {
285+ tokio::time::sleep(Duration::from_secs(RATE_SYNC_INTERVAL_SECS)).await;
286+ let Some(buckets) = buckets.upgrade() else {
287+ return;
288+ };
289+ // Never queue work on a database that is down: the SDK parks a
290+ // query instead of failing it, so this task would sit on a
291+ // round for the whole outage and then apply a stale total.
292+ if !db_up.is_up() {
293+ continue;
294+ }
295+ let epoch = current_epoch(window);
296+ sync_once(tier, &buckets, window, epoch, &db).await;
297+ // Piggybacked cleanup, once per window: rows for a window that
298+ // has passed can never be read again.
299+ if swept != epoch {
300+ swept = epoch;
301+ let sql = format!("DELETE {RATE_LIMIT_TABLE} WHERE window_start < $cutoff");
302+ if let Err(err) = with_deadline(db.query(sql).bind(("cutoff", epoch))).await {
303+ tracing::warn!(%err, "rate-limit sweep failed; retrying next window");
304+ }
305+ }
306+ }
307+ });
308+ }
309+}
310+
311+/// Fold every live bucket's new admits into its shared row and take the
312+/// fleet-wide total back.
313+///
314+/// One statement per bucket in one query, and each statement is its own
315+/// transaction — so a statement that loses a write race fails alone. Its bucket
316+/// simply keeps the delta unreported and the next round (2s later) carries it,
317+/// which is why no retry loop is needed here: retrying the *query* would
318+/// double-apply the statements that did land, since `hits` accumulates.
319+async fn sync_once<K: Eq + Hash + Clone + std::fmt::Display>(
320+ tier: &str,
321+ buckets: &Mutex<HashMap<K, Bucket>>,
322+ window: Duration,
323+ epoch: i64,
324+ db: &Database,
325+) {
326+ let now = Instant::now();
327+ let pending: Vec<Pending<K>> = {
328+ let mut guard = buckets.lock().expect("rate limiter mutex poisoned");
329+ guard
330+ .iter_mut()
331+ .filter(|(_, b)| b.count > 0 && now.duration_since(b.window_start) < window)
332+ .take(RATE_SYNC_MAX_KEYS)
333+ .map(|(key, b)| {
334+ if b.epoch != epoch {
335+ // The shared window rolled: the row this bucket is about to
336+ // write knows nothing of us, so the whole local count is
337+ // the delta and the previous total describes a dead row.
338+ b.epoch = epoch;
339+ b.pushed = 0;
340+ b.remote = 0;
341+ }
342+ Pending {
343+ key: key.clone(),
344+ delta: b.count - b.pushed,
345+ counted: b.count,
346+ window_start: b.window_start,
347+ }
348+ })
349+ .collect()
350+ };
351+ if pending.is_empty() {
352+ return;
353+ }
354+
355+ let sql: String = (0..pending.len())
356+ .map(|i| {
357+ format!("UPSERT $id{i} SET hits = (hits ?? 0) + $delta{i}, window_start = $window RETURN VALUE hits;")
358+ })
359+ .collect();
360+ let mut query = db.query(sql).bind(("window", epoch));
361+ for (i, p) in pending.iter().enumerate() {
362+ let id = RecordId::new(RATE_LIMIT_TABLE, row_key(tier, &p.key, epoch));
363+ query = query
364+ .bind((format!("id{i}"), id))
365+ .bind((format!("delta{i}"), i64::from(p.delta)));
366+ }
367+ let mut response = match with_deadline(query).await {
368+ Ok(response) => response,
369+ Err(err) => {
370+ tracing::warn!(%err, "rate-limit sync failed; counting locally until it recovers");
371+ return;
372+ }
373+ };
374+
375+ let mut guard = buckets.lock().expect("rate limiter mutex poisoned");
376+ for (i, p) in pending.iter().enumerate() {
377+ // A statement that failed (a lost write race) leaves its bucket
378+ // untouched: the delta stays unreported and the next round carries it.
379+ let Ok(total) = response.take::<Vec<i64>>(i) else {
380+ continue;
381+ };
382+ let (Some(total), Some(bucket)) = (total.first(), guard.get_mut(&p.key)) else {
383+ continue;
384+ };
385+ // The window may have rolled while the query was in flight, in which
386+ // case this total is about a bucket that no longer exists.
387+ if bucket.epoch != epoch || bucket.window_start != p.window_start {
388+ continue;
389+ }
390+ bucket.pushed = p.counted;
391+ bucket.remote = (*total).clamp(0, u32::MAX.into()) as u32;
392+ }
393+}
394+
395+/// The wall-clock window a shared row is keyed by, aligned so every replica
396+/// agrees on it — the local windows cannot be used for this, since each one
397+/// starts whenever that client's first request happened to land.
398+fn current_epoch(window: Duration) -> i64 {
399+ let ms = i64::try_from(window.as_millis()).unwrap_or(i64::MAX).max(1);
400+ Timestamp::now().as_millis().div_euclid(ms) * ms
401+}
402+
403+/// The shared row's key: tier, client, window. The client part is hashed
404+/// because it is a raw IP or user id — free of the `:` and `_` that would
405+/// otherwise let one client's key collide with another's by construction.
406+fn row_key<K: std::fmt::Display>(tier: &str, key: &K, epoch: i64) -> String {
407+ use sha2::{Digest, Sha256};
408+ let digest = Sha256::digest(key.to_string().as_bytes());
409+ format!("{tier}_{:x}_{epoch}", ByteSlice(&digest[..8]))
410+}
411+
412+/// Lowercase hex of a byte slice, for [`row_key`].
413+struct ByteSlice<'a>(&'a [u8]);
414+
415+impl std::fmt::LowerHex for ByteSlice<'_> {
416+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
417+ self.0.iter().try_for_each(|byte| write!(f, "{byte:02x}"))
418+ }
419+}
420+
421+/// Run a sync query under a deadline. The liveness flag catches a *known*
422+/// outage; this catches the socket that died between the last ping and now,
423+/// which the SDK would otherwise park until the database returned — wedging
424+/// the one task every tier's sharing depends on.
425+async fn with_deadline<T>(
426+ query: impl std::future::IntoFuture<Output = surrealdb::Result<T>>,
427+) -> Result<T, AppError> {
428+ tokio::time::timeout(
429+ Duration::from_secs(RATE_SYNC_TIMEOUT_SECS),
430+ query.into_future(),
431+ )
432+ .await
433+ .map_err(|_| AppError::Internal("rate-limit sync timed out".into()))?
434+ .map_err(AppError::from)
435+}
436+
190 /// Resolve the client IP a request is billed against.437 /// Resolve the client IP a request is billed against.
191 ///438 ///
192 /// With `trust_proxy`, prefer the rightmost `X-Forwarded-For` entry — appended439 /// With `trust_proxy`, prefer the rightmost `X-Forwarded-For` entry — appended
src/web/appointments.rsmodified+5 -5
@@ -386,6 +386,7 @@ async fn list_slots(
386 (slots, people)386 (slots, people)
387 };387 };
388 let total = slots.len() as i64;388 let total = slots.len() as i64;
389+ // Paged in the web layer: slots of demoted teachers are dropped above.
389 let items = paginate(&slots, limit, offset)390 let items = paginate(&slots, limit, offset)
390 .iter()391 .iter()
391 .map(|slot| SlotResponse::new(slot, &people))392 .map(|slot| SlotResponse::new(slot, &people))
@@ -547,14 +548,13 @@ async fn list_appointments(
547 Query(page): Query<PageParams>,548 Query(page): Query<PageParams>,
548 ) -> Result<Json<Page<AppointmentResponse>>, AppError> {549 ) -> Result<Json<Page<AppointmentResponse>>, AppError> {
549 let (limit, offset) = page.resolve()?;550 let (limit, offset) = page.resolve()?;
550- let rows = if user.get_role().at_least(Role::Teacher) {551+ let (rows, total) = if user.get_role().at_least(Role::Teacher) {
551- Appointment::list_for_teacher(user.get_id(), &st.db).await?552+ Appointment::list_for_teacher(user.get_id(), limit, offset, &st.db).await?
552 } else {553 } else {
553- Appointment::list_for_requester(user.get_id(), &st.db).await?554+ Appointment::list_for_requester(user.get_id(), limit, offset, &st.db).await?
554 };555 };
555- let total = rows.len() as i64;
556 // Join slots and people onto the page alone — the lookup shrinks with it.556 // Join slots and people onto the page alone — the lookup shrinks with it.
557- let items = appointment_responses(paginate(&rows, limit, offset), &st.db).await?;557+ let items = appointment_responses(&rows, &st.db).await?;
558 Ok(Json(Page::new(items, total, limit, offset)))558 Ok(Json(Page::new(items, total, limit, offset)))
559 }559 }
560 560
src/web/auth.rsmodified+5 -1
@@ -20,12 +20,16 @@ use crate::state::AppState;
20 use super::dto::Role;20 use super::dto::Role;
21 use super::{CurrentUser, UserResponse};21 use super::{CurrentUser, UserResponse};
22 22
23-pub fn routes(rate_limit: &RateLimitConfig) -> OpenApiRouter<AppState> {23+pub fn routes(state: &AppState) -> OpenApiRouter<AppState> {
24 // Strict per-IP limit on the two credential endpoints only — the24 // Strict per-IP limit on the two credential endpoints only — the
25 // brute-force and username-enumeration surface. `me` and `logout` stay25 // brute-force and username-enumeration surface. `me` and `logout` stay
26 // outside it: browser frontends poll `me` on every page load, and being26 // outside it: browser frontends poll `me` on every page load, and being
27 // over the auth limit must never block an intentional logout.27 // over the auth limit must never block an intentional logout.
28+ let rate_limit: &RateLimitConfig = &state.rate_limit;
28 let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy);29 let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy);
30+ // One budget across replicas, not one per process — the tier only means
31+ // something if a brute-forcer cannot get it twice by hitting both.
32+ limiter.share("auth", state.db.clone(), state.db_up.clone());
29 OpenApiRouter::new()33 OpenApiRouter::new()
30 .routes(routes!(register))34 .routes(routes!(register))
31 .routes(routes!(login))35 .routes(routes!(login))
src/web/bank_questions.rsmodified+92 -101
@@ -24,7 +24,7 @@ use utoipa::{IntoParams, ToSchema};
24 use utoipa_axum::router::OpenApiRouter;24 use utoipa_axum::router::OpenApiRouter;
25 use utoipa_axum::routes;25 use utoipa_axum::routes;
26 26
27-use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};27+use crate::constant::{CAS_UPDATE_RETRIES, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
28 use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility};28 use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility};
29 use crate::domain::bank_question_image::BankQuestionImage;29 use crate::domain::bank_question_image::BankQuestionImage;
30 use crate::domain::exam_question::{30 use crate::domain::exam_question::{
@@ -32,7 +32,6 @@ use crate::domain::exam_question::{
32 };32 };
33 use crate::domain::note_file::FileContentType;33 use crate::domain::note_file::FileContentType;
34 use crate::domain::role::Role;34 use crate::domain::role::Role;
35-use crate::domain::settings::Settings;
36 use crate::domain::subject::{Subject, SubjectId};35 use crate::domain::subject::{Subject, SubjectId};
37 use crate::domain::user::{User, UserId};36 use crate::domain::user::{User, UserId};
38 use crate::error::{AppError, ErrorResponse, ValidationError};37 use crate::error::{AppError, ErrorResponse, ValidationError};
@@ -42,16 +41,17 @@ use super::dto::person_map;
42 use super::exams::ChoiceResponse;41 use super::exams::ChoiceResponse;
43 use super::subjects::subject_must_exist;42 use super::subjects::subject_must_exist;
44 use super::{43 use super::{
45- ChoiceBody, Page, PageParams, RequireTeacher, UploadFileForm, blob_path, image_content_type,44+ ChoiceBody, ImageUpload, Page, PageParams, RequireTeacher, UploadFileForm, read_image_upload,
46- read_upload, remove_blob, serve_inline_blob, set_or_clear,45+ remove_blob, serve_inline_blob, set_or_clear, store_blob,
47 };46 };
48 47
49 /// Serializes bank writes that adopt a `subject` against a concurrent subject48 /// Serializes bank writes that adopt a `subject` against a concurrent subject
50-/// delete. Bank create takes the reader lease across its49+/// delete — the one invariant left here, and a **replica-local** one: it orders
51-/// subject-exists check and the write; the *update* takes the writer lease50+/// requests inside one process, and there are two. Every lease is now a
52-/// instead, because it is a read-modify-write of the whole template, so its row51+/// *reader* lease taken across a subject-exists check and the write that adopts
53-/// read must be serialized against another update and not merely against the52+/// it: bank create, bank update, and save-to-bank. (Update used to take the
54-/// delete cascade; the subject delete takes the writer53+/// writer lease for its read-modify-write; that is a compare-and-set on the row
54+/// itself now, which holds across replicas.) The subject delete takes the writer
55 /// lease across the cascade that clears `subject` off every template, so a55 /// lease across the cascade that clears `subject` off every template, so a
56 /// template can't land on a subject that vanished mid-flight (it would outlive56 /// template can't land on a subject that vanished mid-flight (it would outlive
57 /// the sweep) — the bank twin of the57 /// the sweep) — the bank twin of the
@@ -113,7 +113,7 @@ struct CreateBankQuestion {
113 correct: Option<String>,113 correct: Option<String>,
114 }114 }
115 115
116-#[derive(Deserialize, ToSchema)]116+#[derive(Clone, Deserialize, ToSchema)]
117 struct UpdateBankQuestion {117 struct UpdateBankQuestion {
118 /// Re-tag the template's origin subject. Omit to keep the current one118 /// Re-tag the template's origin subject. Omit to keep the current one
119 /// (which is `null` if that subject has since been deleted).119 /// (which is `null` if that subject has since been deleted).
@@ -392,9 +392,9 @@ async fn owned_question(st: &AppState, user: &User, bid: &str) -> Result<BankQue
392 Ok(question)392 Ok(question)
393 }393 }
394 394
395-/// The whole bank-image write tail: new blob to disk, row UPSERT (the395+/// The bank-image write tail: the slot's current row names the blob to retire,
396-/// deterministic per-slot id makes it a replace), then the replaced blob off396+/// the UPSERT replaces it (the deterministic per-slot id makes it a replace),
397-/// disk. A failed row write takes the fresh blob back out.397+/// and [`store_blob`] owns the disk ordering.
398 pub(crate) async fn store_image(398 pub(crate) async fn store_image(
399 st: &AppState,399 st: &AppState,
400 question: &BankQuestionId,400 question: &BankQuestionId,
@@ -404,22 +404,12 @@ pub(crate) async fn store_image(
404 ) -> Result<BankQuestionImage, AppError> {404 ) -> Result<BankQuestionImage, AppError> {
405 let replaced = BankQuestionImage::read_slot(question, slot, &st.db).await?;405 let replaced = BankQuestionImage::read_slot(question, slot, &st.db).await?;
406 let image = BankQuestionImage::new(question, slot, content_type, data.len() as i64);406 let image = BankQuestionImage::new(question, slot, content_type, data.len() as i64);
407- let path = blob_path(&st.files_path, image.get_file());407+ let file = image.get_file().to_string();
408- tokio::fs::write(&path, data)408+ store_blob(st, &file, data, || async {
409- .await409+ let stored = image.upsert(&st.db).await?;
410- .map_err(|err| AppError::Internal(format!("failed to store the image blob: {err}")))?;410+ Ok((stored, replaced.map(|old| old.get_file().to_string())))
411- match image.upsert(&st.db).await {411+ })
412- Ok(stored) => {412+ .await
413- if let Some(replaced) = replaced {
414- remove_blob(&st.files_path, replaced.get_file()).await;
415- }
416- Ok(stored)
417- }
418- Err(err) => {
419- let _ = tokio::fs::remove_file(&path).await;
420- Err(err)
421- }
422- }
423 }413 }
424 414
425 /// Add a template to the bank. Requires teacher+. `subject_id` is origin415 /// Add a template to the bank. Requires teacher+. `subject_id` is origin
@@ -602,8 +592,10 @@ async fn get_question(
602 Ok(Json(BankQuestionResponse::new(&question, &images)))592 Ok(Json(BankQuestionResponse::new(&question, &images)))
603 }593 }
604 594
605-/// Edit a template. Owner only (admins aside — 403 otherwise). Omitted fields595+/// Edit a template. Owner only (admins aside — 403 otherwise). Concurrent edits
606-/// keep their value; `kind`/`choices`/`correct` are re-validated as a unit, so596+/// of *different* fields merge instead of reverting each other (the save is
597+/// conditioned on the snapshot it merged over, and re-merges when it loses).
598+/// Omitted fields keep their value; `kind`/`choices`/`correct` are re-validated as a unit, so
607 /// a kind switch must bring the matching fields along. Replacing or clearing599 /// a kind switch must bring the matching fields along. Replacing or clearing
608 /// `choices` drops the old options' pictures. Bank templates never freeze —600 /// `choices` drops the old options' pictures. Bank templates never freeze —
609 /// they have no exam tie.601 /// they have no exam tie.
@@ -626,6 +618,7 @@ async fn get_question(
626 (status = 401, description = "Not authenticated", body = ErrorResponse),618 (status = 401, description = "Not authenticated", body = ErrorResponse),
627 (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse),619 (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse),
628 (status = 404, description = "No such template", body = ErrorResponse),620 (status = 404, description = "No such template", body = ErrorResponse),
621+ (status = 409, description = "The template kept changing under concurrent edits — retry", body = ErrorResponse),
629 ),622 ),
630 )]623 )]
631 async fn update_question(624 async fn update_question(
@@ -634,62 +627,71 @@ async fn update_question(
634 Path(bid): Path<String>,627 Path(bid): Path<String>,
635 Json(req): Json<UpdateBankQuestion>,628 Json(req): Json<UpdateBankQuestion>,
636 ) -> Result<Json<BankQuestionResponse>, AppError> {629 ) -> Result<Json<BankQuestionResponse>, AppError> {
637- // *Writer* lease of [`BANK_LOCK`], taken before the row is read: this is a630+ // Reader lease of [`BANK_LOCK`], exactly like the create path and for the
638- // read-modify-write, not a per-field write. Omitted fields are refilled from631+ // one thing it buys: the subject-exists check below is paired with the
639- // the snapshot below, and the kind/choices/correct trio genuinely has to be632+ // subject delete that sweeps this table (that cascade takes the writer
640- // (a text-only edit re-submits the stored options *with their ids* so every633+ // lease), so a template cannot be pinned to a subject on its way out. It is
641- // choice keeps its picture), so the read, the merge and the write must be634+ // replica-local, like every lock here. The *writer* lease this used to take
642- // one unit or a concurrent PATCH of another field is silently reverted. The635+ // was aimed at the read-modify-write below, which it only serialized inside
643- // reader lease this used to take was both shared *and* acquired after the636+ // one process — that is now a compare-and-set on the row itself.
644- // read, so it serialized nothing; it only ever covered the subject-exists637+ let _guard = BANK_LOCK.read().await;
645- // check against a subject delete, which the writer lease still covers.638+ // Read, merge and write again while the row keeps moving underneath: the
646- // Exclusive means bank writes queue behind each other — they are rare639+ // guarded write refuses on a snapshot that has gone stale, so both edits
647- // teacher edits, and the per-field alternative cannot express the640+ // land instead of the later one reverting the earlier.
648- // choice-identity merge. Still the only lock this path takes, so the641+ let mut left = CAS_UPDATE_RETRIES;
649- // documented EXAM → BANK order is unaffected.642+ let updated = loop {
650- let _guard = BANK_LOCK.write().await;643+ let question = owned_question(&st, &user, &bid).await?;
651- let question = owned_question(&st, &user, &bid).await?;644+ // Omitted keeps the stored subject — which may already be `None`, cleared
652- // Omitted keeps the stored subject — which may already be `None`, cleared645+ // by that subject's delete.
653- // by that subject's delete.646+ let subject = match req.subject_id {
654- let subject = match req.subject_id {647+ Some(ref subject_id) => Some(subject_must_exist(subject_id, &st.db).await?),
655- Some(ref subject_id) => Some(subject_must_exist(subject_id, &st.db).await?),648+ None => question.get_subject().cloned(),
656- None => question.get_subject().cloned(),649+ };
657- };650+ let text = match req.text {
658- let text = match req.text {651+ Some(ref text) => QuestionText::try_new(text)?,
659- Some(ref text) => QuestionText::try_new(text)?,652+ None => question.get_text().clone(),
660- None => question.get_text().clone(),653+ };
661- };654+ let points = match req.points {
662- let points = match req.points {655+ Some(points) => QuestionPoints::try_new(points)?,
663- Some(points) => QuestionPoints::try_new(points)?,656+ None => question.get_points(),
664- None => question.get_points(),657+ };
665- };658+ // Merge the kind-dependent fields (set / clear / keep per field), then
666- // Merge the kind-dependent fields (set / clear / keep per field), then659+ // re-validate them as a unit — a PATCH can't leave a half-question behind.
667- // re-validate them as a unit — a PATCH can't leave a half-question behind.660+ let kind = match req.kind {
668- let kind = match req.kind {661+ Some(ref kind) => QuestionKind::try_new(kind)?,
669- Some(ref kind) => QuestionKind::try_new(kind)?,662+ None => question.get_kind().clone(),
670- None => question.get_kind().clone(),663+ };
671- };664+ // Omitting `choices` re-submits the stored options *with their ids*, so a
672- // Omitting `choices` re-submits the stored options *with their ids*, so a665+ // text-only edit keeps every identity (and every picture) untouched.
673- // text-only edit keeps every identity (and every picture) untouched.666+ let choices = match req.choices.clone() {
674- let choices = match req.choices {667+ Some(update) => ChoiceBody::into_inputs(update),
675- Some(update) => ChoiceBody::into_inputs(update),668+ None => ChoiceBody::from_stored(question.get_choices()),
676- None => ChoiceBody::from_stored(question.get_choices()),669+ };
677- };670+ let correct = match req.correct.clone() {
678- let correct = match req.correct {671+ Some(update) => update,
679- Some(update) => update,672+ None => question.get_correct().map(|id| id.as_str().to_string()),
680- None => question.get_correct().map(|id| id.as_str().to_string()),673+ };
681- };674+ let stored: Vec<Choice> = question.get_choices().unwrap_or_default().to_vec();
682- let stored: Vec<Choice> = question.get_choices().unwrap_or_default().to_vec();675+ let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?;
683- let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?;676+ let visibility = match req.visibility {
684- let visibility = match req.visibility {677+ Some(ref visibility) => BankVisibility::try_new(visibility)?,
685- Some(ref visibility) => BankVisibility::try_new(visibility)?,678+ None => question.get_visibility().clone(),
686- None => question.get_visibility().clone(),679+ };
680+
681+ if let Some(updated) = question
682+ .update_if_unchanged(subject, text, points, spec, visibility, &st.db)
683+ .await?
684+ {
685+ break updated;
686+ }
687+ left -= 1;
688+ if left == 0 {
689+ return Err(AppError::Conflict(
690+ "the template kept changing underneath this update — try again",
691+ ));
692+ }
687 };693 };
688-694+ let bid = updated.get_id().clone();
689- let bid = question.get_id().clone();
690- let updated = question
691- .update(subject, text, points, spec, visibility, &st.db)
692- .await?;
693 // Only the options that are actually *gone* lose their pictures — an option695 // Only the options that are actually *gone* lose their pictures — an option
694 // that survives the edit keeps its image wherever it moved in the list.696 // that survives the edit keeps its image wherever it moved in the list.
695 let keep: Vec<ChoiceId> = updated697 let keep: Vec<ChoiceId> = updated
@@ -770,10 +772,8 @@ async fn upload_question_image(
770 mut multipart: Multipart,772 mut multipart: Multipart,
771 ) -> Result<(StatusCode, Json<BankImageMeta>), AppError> {773 ) -> Result<(StatusCode, Json<BankImageMeta>), AppError> {
772 let question = owned_question(&st, &user, &bid).await?;774 let question = owned_question(&st, &user, &bid).await?;
773- let limit = Settings::load(&st.db).await?.get_max_file_bytes();775+ let ImageUpload { content_type, data } = read_image_upload(&st, &mut multipart).await?;
774- let upload = read_upload(&mut multipart, limit).await?;776+ let stored = store_image(&st, question.get_id(), None, content_type, &data).await?;
775- let content_type = image_content_type(&upload.content_type.unwrap_or_default())?;
776- let stored = store_image(&st, question.get_id(), None, content_type, &upload.data).await?;
777 Ok((StatusCode::CREATED, Json(BankImageMeta::new(&stored))))777 Ok((StatusCode::CREATED, Json(BankImageMeta::new(&stored))))
778 }778 }
779 779
@@ -864,17 +864,8 @@ async fn upload_choice_image(
864 ) -> Result<(StatusCode, Json<BankImageMeta>), AppError> {864 ) -> Result<(StatusCode, Json<BankImageMeta>), AppError> {
865 let question = owned_question(&st, &user, &bid).await?;865 let question = owned_question(&st, &user, &bid).await?;
866 let slot = bank_choice_slot(&question, &choice_id)?;866 let slot = bank_choice_slot(&question, &choice_id)?;
867- let limit = Settings::load(&st.db).await?.get_max_file_bytes();867+ let ImageUpload { content_type, data } = read_image_upload(&st, &mut multipart).await?;
868- let upload = read_upload(&mut multipart, limit).await?;868+ let stored = store_image(&st, question.get_id(), Some(&slot), content_type, &data).await?;
869- let content_type = image_content_type(&upload.content_type.unwrap_or_default())?;
870- let stored = store_image(
871- &st,
872- question.get_id(),
873- Some(&slot),
874- content_type,
875- &upload.data,
876- )
877- .await?;
878 Ok((StatusCode::CREATED, Json(BankImageMeta::new(&stored))))869 Ok((StatusCode::CREATED, Json(BankImageMeta::new(&stored))))
879 }870 }
880 871
src/web/chatbot.rsmodified+7 -13
@@ -50,7 +50,7 @@ use crate::domain::user::UserId;
50 use crate::error::{AppError, ErrorResponse, ValidationError};50 use crate::error::{AppError, ErrorResponse, ValidationError};
51 use crate::state::AppState;51 use crate::state::AppState;
52 52
53-use super::{CurrentUser, Page, PageParams, paginate};53+use super::{CurrentUser, Page, PageParams};
54 54
55 pub fn routes() -> OpenApiRouter<AppState> {55 pub fn routes() -> OpenApiRouter<AppState> {
56 OpenApiRouter::new()56 OpenApiRouter::new()
@@ -155,12 +155,9 @@ async fn list_threads(
155 Query(page): Query<PageParams>,155 Query(page): Query<PageParams>,
156 ) -> Result<Json<Page<ChatbotThreadResponse>>, AppError> {156 ) -> Result<Json<Page<ChatbotThreadResponse>>, AppError> {
157 let (limit, offset) = page.resolve()?;157 let (limit, offset) = page.resolve()?;
158- let threads = ChatbotThread::list_for_user(user.get_id(), &st.db).await?;158+ let (threads, total) =
159- let total = threads.len() as i64;159+ ChatbotThread::list_for_user(user.get_id(), limit, offset, &st.db).await?;
160- let items = paginate(&threads, limit, offset)160+ let items = threads.iter().map(ChatbotThreadResponse::new).collect();
161- .iter()
162- .map(ChatbotThreadResponse::new)
163- .collect();
164 Ok(Json(Page::new(items, total, limit, offset)))161 Ok(Json(Page::new(items, total, limit, offset)))
165 }162 }
166 163
@@ -339,12 +336,9 @@ async fn list_messages(
339 ) -> Result<Json<Page<ChatbotMessageResponse>>, AppError> {336 ) -> Result<Json<Page<ChatbotMessageResponse>>, AppError> {
340 let (limit, offset) = page.resolve()?;337 let (limit, offset) = page.resolve()?;
341 let thread = own_thread(&id, user.get_id(), &st.db).await?;338 let thread = own_thread(&id, user.get_id(), &st.db).await?;
342- let messages = ChatbotMessage::list_for_thread(thread.get_id(), &st.db).await?;339+ let (messages, total) =
343- let total = messages.len() as i64;340+ ChatbotMessage::list_for_thread(thread.get_id(), limit, offset, &st.db).await?;
344- let items = paginate(&messages, limit, offset)341+ let items = messages.iter().map(ChatbotMessageResponse::new).collect();
345- .iter()
346- .map(ChatbotMessageResponse::new)
347- .collect();
348 Ok(Json(Page::new(items, total, limit, offset)))342 Ok(Json(Page::new(items, total, limit, offset)))
349 }343 }
350 344
src/web/courses.rsmodified+13 -18
@@ -219,7 +219,7 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Co
219 return Course::list_all(db).await;219 return Course::list_all(db).await;
220 }220 }
221 let mut courses = Course::list_for_teacher(user.get_id(), db).await?;221 let mut courses = Course::list_for_teacher(user.get_id(), db).await?;
222- for course in Course::list_enrolled(user.get_id(), db).await? {222+ for course in Course::list_enrolled(user.get_id(), None, 0, db).await?.0 {
223 if !courses223 if !courses
224 .iter()224 .iter()
225 .any(|known| known.get_id() == course.get_id())225 .any(|known| known.get_id() == course.get_id())
@@ -325,6 +325,7 @@ async fn list_courses(
325 let (limit, offset) = page.resolve()?;325 let (limit, offset) = page.resolve()?;
326 let courses = visible_courses(&user, &st.db).await?;326 let courses = visible_courses(&user, &st.db).await?;
327 let total = courses.len() as i64;327 let total = courses.len() as i64;
328+ // Paged in the web layer: the visible set is a Rust union of two lists.
328 let window = paginate(&courses, limit, offset);329 let window = paginate(&courses, limit, offset);
329 // Join creators onto the page alone — the lookup shrinks with the window.330 // Join creators onto the page alone — the lookup shrinks with the window.
330 let people = person_map(window.iter().flat_map(course_people), &st.db).await?;331 let people = person_map(window.iter().flat_map(course_people), &st.db).await?;
@@ -356,11 +357,9 @@ async fn my_courses(
356 Query(page): Query<PageParams>,357 Query(page): Query<PageParams>,
357 ) -> Result<Json<Page<CourseResponse>>, AppError> {358 ) -> Result<Json<Page<CourseResponse>>, AppError> {
358 let (limit, offset) = page.resolve()?;359 let (limit, offset) = page.resolve()?;
359- let courses = Course::list_enrolled(user.get_id(), &st.db).await?;360+ let (courses, total) = Course::list_enrolled(user.get_id(), limit, offset, &st.db).await?;
360- let total = courses.len() as i64;361+ let people = person_map(courses.iter().flat_map(course_people), &st.db).await?;
361- let window = paginate(&courses, limit, offset);362+ let items = courses
362- let people = person_map(window.iter().flat_map(course_people), &st.db).await?;
363- let items = window
364 .iter()363 .iter()
365 .map(|course| CourseResponse::new(course, &people))364 .map(|course| CourseResponse::new(course, &people))
366 .collect();365 .collect();
@@ -711,10 +710,8 @@ async fn list_roster(
711 "only the course creator, an assigned teacher, or a manager/admin can list the roster",710 "only the course creator, an assigned teacher, or a manager/admin can list the roster",
712 ));711 ));
713 }712 }
714- let enrollments = Enrollment::list_for_course(course.get_id(), &st.db).await?;713+ let (rows, total) = Enrollment::list_for_course(course.get_id(), limit, offset, &st.db).await?;
715- let total = enrollments.len() as i64;
716 // Join people onto the page alone — the lookup shrinks with the window.714 // Join people onto the page alone — the lookup shrinks with the window.
717- let rows = paginate(&enrollments, limit, offset);
718 let people = person_map(715 let people = person_map(
719 rows.iter()716 rows.iter()
720 .flat_map(|e| [e.get_user().clone(), e.get_enrolled_by().clone()]),717 .flat_map(|e| [e.get_user().clone(), e.get_enrolled_by().clone()]),
@@ -884,6 +881,7 @@ async fn list_course_exams(
884 exams.retain(|exam| !exam.is_draft());881 exams.retain(|exam| !exam.is_draft());
885 }882 }
886 let total = exams.len() as i64;883 let total = exams.len() as i64;
884+ // Paged in the web layer: the draft filter above is per-row Rust.
887 let items = paginate(&exams, limit, offset)885 let items = paginate(&exams, limit, offset)
888 .iter()886 .iter()
889 .map(ExamResponse::new)887 .map(ExamResponse::new)
@@ -976,12 +974,9 @@ async fn list_course_subjects(
976 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course",974 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course",
977 ));975 ));
978 }976 }
979- let subjects = Subject::list_for_course(course.get_id(), &st.db).await?;977+ let (subjects, total) =
980- let total = subjects.len() as i64;978+ Subject::list_for_course(course.get_id(), limit, offset, &st.db).await?;
981- let items = paginate(&subjects, limit, offset)979+ let items = subjects.iter().map(SubjectResponse::new).collect();
982- .iter()
983- .map(SubjectResponse::new)
984- .collect();
985 Ok(Json(Page::new(items, total, limit, offset)))980 Ok(Json(Page::new(items, total, limit, offset)))
986 }981 }
987 982
@@ -1115,6 +1110,7 @@ async fn list_course_homework(
1115 homework.retain(|hw| hw.student_sees(user.get_id()));1110 homework.retain(|hw| hw.student_sees(user.get_id()));
1116 }1111 }
1117 let total = homework.len() as i64;1112 let total = homework.len() as i64;
1113+ // Paged in the web layer: the audience filter above is per-row Rust.
1118 let items = paginate(&homework, limit, offset)1114 let items = paginate(&homework, limit, offset)
1119 .iter()1115 .iter()
1120 .map(HomeworkResponse::new)1116 .map(HomeworkResponse::new)
@@ -1230,10 +1226,9 @@ async fn list_course_sessions(
1230 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course",1226 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course",
1231 ));1227 ));
1232 }1228 }
1233- let sessions = CourseSession::list_for_course(course.get_id(), &st.db).await?;1229+ let (rows, total) =
1234- let total = sessions.len() as i64;1230+ CourseSession::list_for_course(course.get_id(), limit, offset, &st.db).await?;
1235 // Join teachers onto the page alone — the lookup shrinks with the window.1231 // Join teachers onto the page alone — the lookup shrinks with the window.
1236- let rows = paginate(&sessions, limit, offset);
1237 let people = person_map(rows.iter().map(|s| s.get_teacher().clone()), &st.db).await?;1232 let people = person_map(rows.iter().map(|s| s.get_teacher().clone()), &st.db).await?;
1238 let items = rows1233 let items = rows
1239 .iter()1234 .iter()
src/web/events.rsmodified+7 -17
@@ -11,9 +11,7 @@ use utoipa_axum::routes;
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::course::{Course, CourseId};13 use crate::domain::course::{Course, CourseId};
14-use crate::domain::event::{14+use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle};
15- EVENT_LOCK, Event, EventAudience, EventDescription, EventId, EventTitle,
16-};
17 use crate::domain::registration::Registration;15 use crate::domain::registration::Registration;
18 use crate::domain::role::Role;16 use crate::domain::role::Role;
19 use crate::domain::settings::Settings;17 use crate::domain::settings::Settings;
@@ -303,6 +301,7 @@ async fn list_events(
303 let (limit, offset) = page.resolve()?;301 let (limit, offset) = page.resolve()?;
304 let events = window.apply(Event::list_all(&st.db).await?)?;302 let events = window.apply(Event::list_all(&st.db).await?)?;
305 let total = events.len() as i64;303 let total = events.len() as i64;
304+ // Paged in the web layer: `WindowParams` filters and re-orders in Rust.
306 let items = paginate(&events, limit, offset)305 let items = paginate(&events, limit, offset)
307 .iter()306 .iter()
308 .map(EventResponse::new)307 .map(EventResponse::new)
@@ -368,15 +367,6 @@ async fn update_event(
368 .starts_at367 .starts_at
369 .map(|update| update.map(Timestamp::from_millis));368 .map(|update| update.map(Timestamp::from_millis));
370 let ends_at = req.ends_at.map(|update| update.map(Timestamp::from_millis));369 let ends_at = req.ends_at.map(|update| update.map(Timestamp::from_millis));
371- // Only the range check needs the stored row, and only it can race: it
372- // validates an arriving end against the other end as stored, so the read,
373- // the check and the write are held together under [`EVENT_LOCK`]. A PATCH
374- // that moves neither end pays nothing.
375- let _guard = match (starts_at, ends_at) {
376- (None, None) => None,
377- _ => Some(EVENT_LOCK.lock().await),
378- };
379-
380 let event = Event::read(&EventId::from_key(&id), &st.db)370 let event = Event::read(&EventId::from_key(&id), &st.db)
381 .await?371 .await?
382 .ok_or(AppError::NotFound)?;372 .ok_or(AppError::NotFound)?;
@@ -411,7 +401,8 @@ async fn update_event(
411 }401 }
412 // The range CHECK needs both ends: whichever the request omitted comes402 // The range CHECK needs both ends: whichever the request omitted comes
413 // from the stored row. Read for the check only — the omitted side is403 // from the stored row. Read for the check only — the omitted side is
414- // never written back.404+ // never written back. Pre-flight only: `Event::update` re-makes this check
405+ // in the UPDATE's `WHERE`, so a concurrent move of the omitted end loses.
415 check_time_range(406 check_time_range(
416 starts_at.unwrap_or_else(|| event.get_starts_at()),407 starts_at.unwrap_or_else(|| event.get_starts_at()),
417 ends_at.unwrap_or_else(|| event.get_ends_at()),408 ends_at.unwrap_or_else(|| event.get_ends_at()),
@@ -549,10 +540,8 @@ async fn list_attendance(
549 Event::read(&event_id, &st.db)540 Event::read(&event_id, &st.db)
550 .await?541 .await?
551 .ok_or(AppError::NotFound)?;542 .ok_or(AppError::NotFound)?;
552- let roster = Attendance::list_for_event(&event_id, &st.db).await?;543+ let (rows, total) = Attendance::list_for_event(&event_id, limit, offset, &st.db).await?;
553- let total = roster.len() as i64;
554 // Join people onto the page alone — the lookup shrinks with the window.544 // Join people onto the page alone — the lookup shrinks with the window.
555- let rows = paginate(&roster, limit, offset);
556 let people = person_map(545 let people = person_map(
557 rows.iter()546 rows.iter()
558 .flat_map(|a| [a.get_user().clone(), a.get_marked_by().clone()]),547 .flat_map(|a| [a.get_user().clone(), a.get_marked_by().clone()]),
@@ -646,7 +635,7 @@ async fn roster(
646 let mut members = event.get_audience().members(event.get_id(), &st.db).await?;635 let mut members = event.get_audience().members(event.get_id(), &st.db).await?;
647 // ULID keys sort by creation instant — a stable order keeps pages coherent.636 // ULID keys sort by creation instant — a stable order keeps pages coherent.
648 members.sort_by(|a, b| a.key().cmp(b.key()));637 members.sort_by(|a, b| a.key().cmp(b.key()));
649- let marks = Attendance::list_for_event(&event_id, &st.db).await?;638+ let (marks, _) = Attendance::list_for_event(&event_id, None, 0, &st.db).await?;
650 let by_user: HashMap<&str, &Attendance> = marks639 let by_user: HashMap<&str, &Attendance> = marks
651 .iter()640 .iter()
652 .map(|attendance| (attendance.get_user().key(), attendance))641 .map(|attendance| (attendance.get_user().key(), attendance))
@@ -654,6 +643,7 @@ async fn roster(
654 643
655 let total = members.len() as i64;644 let total = members.len() as i64;
656 // Join people onto the page alone — the lookup shrinks with the window.645 // Join people onto the page alone — the lookup shrinks with the window.
646+ // Paged in the web layer: the audience is resolved in Rust.
657 let window = paginate(&members, limit, offset);647 let window = paginate(&members, limit, offset);
658 let ids = window.iter().cloned().chain(window.iter().filter_map(|m| {648 let ids = window.iter().cloned().chain(window.iter().filter_map(|m| {
659 by_user649 by_user
src/web/exam_ws.rsmodified+7 -3
@@ -88,8 +88,9 @@ use crate::web::exams::{
88 /// so it never stamps. No ordering leaves a present student stamped as left —88 /// so it never stamps. No ordering leaves a present student stamped as left —
89 /// the reconnect-vs-teardown race that used to lock students out with89 /// the reconnect-vs-teardown race that used to lock students out with
90 /// `allow_rejoin` off (cleared at the door, stamped after, present forever90 /// `allow_rejoin` off (cleared at the door, stamped after, present forever
91-/// refused). This backend is the database's only writer (single91+/// refused). The count this pairs with lives in *this* process's memory
92-/// instance) — so one process-wide lock is sufficient, same as `REGISTER_LOCK`.92+/// ([`crate::state::ExamPresence`]), so process-wide is exactly the right
93+/// scope: a peer replica counts its own sockets in its own map.
93 // ponytail: global lock, per-attempt locks if room churn ever shows up in a94 // ponytail: global lock, per-attempt locks if room churn ever shows up in a
94 // profile.95 // profile.
95 static PRESENCE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());96 static PRESENCE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
@@ -337,7 +338,10 @@ async fn state_frame(
337 ExamAnswer::list_for_exam_user(exam.get_id(), attempt.get_user(), attempt.get_seq(), db)338 ExamAnswer::list_for_exam_user(exam.get_id(), attempt.get_user(), attempt.get_seq(), db)
338 .await?339 .await?
339 .len();340 .len();
340- let question_count = ExamQuestion::list_for_exam(exam.get_id(), db).await?.len();341+ let question_count = ExamQuestion::list_for_exam(exam.get_id(), None, 0, db)
342+ .await?
343+ .0
344+ .len();
341 let frame = json!({345 let frame = json!({
342 "type": "state",346 "type": "state",
343 "status": status.as_str(),347 "status": status.as_str(),
src/web/exams.rsdeleted+0 -3629

Diff too large; view file

@@ -1,3629 +0,0 @@
1-use std::collections::HashMap;
2-
3-use axum::Json;
4-use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State};
5-use axum::http::StatusCode;
6-use axum::response::Response;
7-use serde::{Deserialize, Serialize};
8-use utoipa::ToSchema;
9-use utoipa_axum::router::OpenApiRouter;
10-use utoipa_axum::routes;
11-
12-use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
13-use crate::database::Database;
14-use crate::domain::answer_image::AnswerImage;
15-use crate::domain::bank_question::{BankQuestion, BankQuestionId};
16-use crate::domain::bank_question_image::BankQuestionImage;
17-use crate::domain::course::Course;
18-use crate::domain::enrollment::Enrollment;
19-use crate::domain::exam::{
20- Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode,
21- ExamSchedule, ExamTitle,
22-};
23-use crate::domain::exam_answer::{ExamAnswer, auto_score};
24-use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt};
25-use crate::domain::exam_question::{
26- Choice, ChoiceId, ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec,
27- QuestionText,
28-};
29-use crate::domain::exam_result::{ExamResult, Mark};
30-use crate::domain::note_file::FileContentType;
31-use crate::domain::question_image::QuestionImage;
32-use crate::domain::role::Role;
33-use crate::domain::settings::Settings;
34-use crate::domain::timestamp::Timestamp;
35-use crate::domain::user::{User, UserId};
36-use crate::error::{AppError, ErrorResponse, ValidationError};
37-use crate::state::AppState;
38-
39-use super::bank_questions::BankQuestionResponse;
40-use super::courses::{can_manage_course, can_view_course, visible_courses};
41-use super::subjects::subject_in_course;
42-use super::{
43- ChoiceBody, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, Scheduled,
44- UploadFileForm, WindowParams, blob_path, check_not_past, image_content_type, paginate,
45- person_map, read_upload, remove_blob, set_or_clear,
46-};
47-
48-impl Scheduled for Exam {
49- fn starts_at_ms(&self) -> Option<i64> {
50- self.get_starts_at().map(|at| at.as_millis())
51- }
52-
53- fn ends_at_ms(&self) -> Option<i64> {
54- self.get_ends_at().map(|at| at.as_millis())
55- }
56-
57- fn order_key(&self) -> &str {
58- self.get_id().key()
59- }
60-}
61-
62-/// Serializes the exam subsystem's cross-record check-then-writes, which
63-/// `BEGIN…COMMIT` cannot (write skew) — same reasoning as `REGISTER_LOCK`.
64-/// Read side: the answer saves (REST and the exam room), holding the sheet
65-/// open from the writable-attempt gate through the upsert, and the grade
66-/// write (draft gate through the result upsert); these stay concurrent with
67-/// each other. Write side: attempt starts (the max-attempts count and the
68-/// retake's answer wipe) and the structural teacher writes whose 409 guards
69-/// read attempt, question, or result rows first — exam mode/schedule/draft
70-/// updates, question create/update/delete, subject delete. So a save can
71-/// never land on a sheet a retake just wiped, a first attempt can never
72-/// slip between a freeze-gate read and the write it was meant to freeze,
73-/// and a mark can never land on an exam mid-flight into hiding.
74-// ponytail: global RwLock, shard per-exam if save latency ever matters.
75-pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
76-
77-pub fn routes() -> OpenApiRouter<AppState> {
78- OpenApiRouter::new()
79- // Plain route: OpenApiRouter can't describe a WebSocket upgrade, so
80- // the exam room lives outside the generated spec (see the `exams` tag
81- // description and README for the protocol).
82- .route(
83- "/{id}/attempt/ws",
84- axum::routing::get(super::exam_ws::attempt_ws),
85- )
86- .routes(routes!(list_exams))
87- .routes(routes!(get_exam, update_exam, delete_exam))
88- .routes(routes!(grade, list_results))
89- .routes(routes!(my_result))
90- .routes(routes!(remove_result))
91- .routes(routes!(exam_statistics))
92- .routes(routes!(start_attempt, my_attempt))
93- .routes(routes!(finish_attempt))
94- .routes(routes!(exam_live))
95- .routes(routes!(create_question, list_questions))
96- .routes(routes!(update_question, delete_question))
97- .routes(routes!(question_from_bank))
98- .routes(routes!(question_to_bank))
99- .routes(routes!(question_refresh_from_bank))
100- .routes(routes!(attempt_questions))
101- .routes(routes!(save_answer))
102- .routes(routes!(attempt_answers))
103- .routes(routes!(student_attempts))
104- .routes(routes!(student_attempt_answers))
105- .routes(routes!(student_marks_history))
106- .routes(routes!(review_questions))
107- .routes(routes!(review_attempts))
108- .routes(routes!(review_attempt_answers))
109- // The image routes get their own HTTP body cap, like the note-file
110- // ones: the server-wide hard ceiling plus multipart framing headroom.
111- .merge(
112- OpenApiRouter::new()
113- .routes(routes!(
114- upload_question_image,
115- get_question_image,
116- delete_question_image
117- ))
118- .routes(routes!(
119- upload_choice_image,
120- get_choice_image,
121- delete_choice_image
122- ))
123- .routes(routes!(
124- upload_answer_image,
125- get_answer_image,
126- delete_answer_image
127- ))
128- .routes(routes!(get_student_answer_image))
129- .routes(routes!(student_attempt_answer_image))
130- .routes(routes!(review_attempt_answer_image))
131- .layer(DefaultBodyLimit::max(
132- MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES,
133- )),
134- )
135-}
136-
137-#[derive(Deserialize, ToSchema)]
138-struct UpdateExam {
139- #[schema(max_length = 200)]
140- title: Option<String>,
141- #[schema(max_length = 2000)]
142- description: Option<String>,
143- /// The assessment form — one of the school's exam kinds (`GET /settings`).
144- /// Changing it re-weights the exam: the course average uses the kind's
145- /// settings-configured weight.
146- kind: Option<String>,
147- /// `sync`, `async`, or `open`. Omit to keep the current mode; send `null`
148- /// to turn the exam back into an offline-graded one. Frozen once anyone
149- /// has started an attempt. Switching to `open` requires clearing
150- /// `starts_at`/`ends_at` in the same request.
151- #[serde(default, deserialize_with = "set_or_clear")]
152- #[schema(value_type = Option<String>)]
153- mode: Option<Option<String>>,
154- /// Window open, UTC unix-milliseconds. Omit to keep; `null` to clear.
155- /// A newly set value must not be in the past.
156- #[serde(default, deserialize_with = "set_or_clear")]
157- #[schema(value_type = Option<i64>)]
158- starts_at: Option<Option<i64>>,
159- /// Window close, UTC unix-milliseconds. Omit to keep; `null` to clear.
160- /// Moving it while a sync exam runs extends (or cuts) everyone's deadline;
161- /// a newly set value must not be in the past.
162- #[serde(default, deserialize_with = "set_or_clear")]
163- #[schema(value_type = Option<i64>)]
164- ends_at: Option<Option<i64>>,
165- /// Per-attempt budget, milliseconds (`async`, or optionally `open`). Omit
166- /// to keep; `null` to clear. Changing it mid-exam moves every running
167- /// attempt's deadline.
168- #[serde(default, deserialize_with = "set_or_clear")]
169- #[schema(value_type = Option<i64>, minimum = 60000, maximum = 86400000)]
170- duration_ms: Option<Option<i64>>,
171- /// Attempt limit: `1`–`100`, or `0` for unlimited. Omit to keep. Editable
172- /// live — raising it grants retakes on the spot; lowering it only blocks
173- /// future starts.
174- #[schema(minimum = 0, maximum = 100)]
175- max_attempts: Option<i64>,
176- /// Whether students who left the exam room may come back in. Omit to
177- /// keep. Editable live — the teacher's door handle for the running room.
178- allow_rejoin: Option<bool>,
179- /// Whether students may review their graded attempt once results are out.
180- /// Omit to keep. Editable live.
181- allow_review: Option<bool>,
182- /// `false` publishes a draft (students can now see and sit it); `true`
183- /// pulls a published exam back into hiding — allowed only while nobody
184- /// has attempted it and nothing is graded (`409` otherwise). Omit to keep.
185- draft: Option<bool>,
186-}
187-
188-#[derive(Deserialize, ToSchema)]
189-struct GradeResult {
190- /// The mark to record, `0`–`100`.
191- #[schema(example = 85, minimum = 0, maximum = 100)]
192- mark: i64,
193- /// The student being graded.
194- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
195- user_id: String,
196-}
197-
198-#[derive(Serialize, ToSchema)]
199-struct ExamResultResponse {
200- id: String,
201- exam: String,
202- /// The graded student.
203- user: PersonRef,
204- /// Which sitting this mark belongs to (1 = first attempt). Lets the grader
205- /// jump from a mark to that sitting's answer sheet
206- /// (`GET /exams/{id}/students/{user}/attempts/{seq}/answers`) — without it
207- /// a marked retake's answers are unreachable from the mark.
208- seq: i64,
209- mark: i64,
210- /// Who recorded the mark.
211- graded_by: PersonRef,
212-}
213-
214-impl ExamResultResponse {
215- fn new(result: &ExamResult, people: &HashMap<String, PersonRef>) -> Self {
216- Self {
217- id: result.get_id().key().to_string(),
218- exam: result.get_exam().key().to_string(),
219- user: PersonRef::resolve(people, result.get_user()),
220- seq: result.get_seq(),
221- mark: result.get_mark().as_i64(),
222- graded_by: PersonRef::resolve(people, result.get_graded_by()),
223- }
224- }
225-}
226-
227-#[derive(Serialize, ToSchema)]
228-struct ExamStatisticsResponse {
229- exam: String,
230- /// Number of graded results.
231- graded: u64,
232- /// Plain mean of the graded marks; `null` while nothing is graded.
233- average: Option<f64>,
234- min: Option<i64>,
235- max: Option<i64>,
236-}
237-
238-/// The course an exam belongs to. A dangling reference means the course-delete
239-/// cascade was violated — surface it loudly as a 500, not a user-facing 404.
240-async fn course_of(exam: &Exam, db: &Database) -> Result<Course, AppError> {
241- Course::read(exam.get_course(), db)
242- .await?
243- .ok_or_else(|| AppError::Internal("exam references a missing course".into()))
244-}
245-
246-// ---- exams --------------------------------------------------------------
247-// Exams are created inside a course: `POST /courses/{id}/exams`.
248-
249-/// List the exams visible to the caller: every exam for manager+, otherwise
250-/// the exams of the courses they created or are enrolled in — minus other
251-/// people's drafts (a draft shows only to its course's managers). Paged via
252-/// `?limit=&offset=` (omit `limit` for the full list); returns a
253-/// `{items, total, limit, offset}` envelope.
254-///
255-/// The optional `?starts_after=&ends_after=` schedule window (unix
256-/// milliseconds) applies *after* the visibility and draft filtering, narrows
257-/// the list to upcoming/unfinished exams and flips the order to ascending by
258-/// schedule — so `?ends_after=<now>&limit=20` returns the twenty *soonest*
259-/// exams rather than the twenty newest-created. Exams without a window
260-/// (no `mode`, or `open`) are excluded by either parameter.
261-#[utoipa::path(
262- get,
263- path = "/",
264- tag = "exams",
265- security(("session_cookie" = [])),
266- params(WindowParams, PageParams),
267- responses(
268- (status = 200, description = "A page of the caller's visible exams (all of them when unpaged)", body = Page<ExamResponse>),
269- (status = 400, description = "Invalid window, limit, or offset", body = ErrorResponse),
270- (status = 401, description = "Not authenticated", body = ErrorResponse),
271- ),
272-)]
273-async fn list_exams(
274- State(st): State<AppState>,
275- CurrentUser(user): CurrentUser,
276- Query(window): Query<WindowParams>,
277- Query(page): Query<PageParams>,
278-) -> Result<Json<Page<ExamResponse>>, AppError> {
279- let (limit, offset) = page.resolve()?;
280- let exams = if user.get_role().at_least(Role::Manager) {
281- Exam::list_all(&st.db).await?
282- } else {
283- let courses = visible_courses(&user, &st.db).await?;
284- let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect();
285- // Drafts show only where the caller manages the course (as its
286- // creator — the manager+ path above already saw everything).
287- let managed: Vec<&str> = courses
288- .iter()
289- .filter(|c| can_manage_course(c, &user))
290- .map(|c| c.get_id().key())
291- .collect();
292- let mut exams = Exam::list_for_courses(&ids, &st.db).await?;
293- exams.retain(|exam| !exam.is_draft() || managed.contains(&exam.get_course().key()));
294- exams
295- };
296- let exams = window.apply(exams)?;
297- let total = exams.len() as i64;
298- let items = paginate(&exams, limit, offset)
299- .iter()
300- .map(ExamResponse::new)
301- .collect();
302- Ok(Json(Page::new(items, total, limit, offset)))
303-}
304-
305-/// Fetch a single exam by id. Visible to its course's enrolled users, the
306-/// course creator, and managers/admins — except drafts, which only the
307-/// course's managers see (everyone else gets a `404`, as if the exam doesn't
308-/// exist yet — because it doesn't, officially).
309-#[utoipa::path(
310- get,
311- path = "/{id}",
312- tag = "exams",
313- security(("session_cookie" = [])),
314- params(("id" = String, Path, description = "Exam id")),
315- responses(
316- (status = 200, description = "The exam", body = ExamResponse),
317- (status = 401, description = "Not authenticated", body = ErrorResponse),
318- (status = 403, description = "Not enrolled in the exam's course, not its creator, and not a manager/admin", body = ErrorResponse),
319- (status = 404, description = "Not found (or a draft the caller may not see)", body = ErrorResponse),
320- ),
321-)]
322-async fn get_exam(
323- State(st): State<AppState>,
324- CurrentUser(user): CurrentUser,
325- Path(id): Path<String>,
326-) -> Result<Json<ExamResponse>, AppError> {
327- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
328- .await?
329- .ok_or(AppError::NotFound)?;
330- let course = course_of(&exam, &st.db).await?;
331- if !can_view_course(&course, &user, &st.db).await? {
332- return Err(AppError::Forbidden(
333- "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this exam",
334- ));
335- }
336- // A draft doesn't exist for anyone but its course's managers — 404, not
337- // 403, so its existence never leaks to the students it's hidden from.
338- if exam.is_draft() && !can_manage_course(&course, &user) {
339- return Err(AppError::NotFound);
340- }
341- Ok(Json(ExamResponse::new(&exam)))
342-}
343-
344-/// Update an exam. Requires teacher+ and management rights over the exam's
345-/// course (its creator, or manager/admin). Omitted fields keep their value; an
346-/// explicit `null` clears a schedule field; the course itself is not updatable.
347-/// The schedule must stay consistent as a whole (see the create endpoint), and
348-/// `mode` is frozen once anyone has started an attempt — times, duration,
349-/// `max_attempts`, and `allow_rejoin` stay editable so a running exam can be
350-/// extended, granted retakes, or have its rejoin door opened live.
351-/// `draft: false` publishes a draft; `draft: true` re-hides an exam, but only
352-/// while it has no attempts and no results (`409` otherwise) — students never
353-/// lose sight of an exam they've already sat or been graded on.
354-#[utoipa::path(
355- patch,
356- path = "/{id}",
357- tag = "exams",
358- security(("session_cookie" = [])),
359- params(("id" = String, Path, description = "Exam id")),
360- request_body = UpdateExam,
361- responses(
362- (status = 200, description = "Updated exam", body = ExamResponse),
363- (status = 400, description = "Invalid fields, kind, attempt limit, or schedule (malformed window, duration exceeding the window, or newly set times in the past)", body = ErrorResponse),
364- (status = 401, description = "Not authenticated", body = ErrorResponse),
365- (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
366- (status = 404, description = "Not found", body = ErrorResponse),
367- (status = 409, description = "Mode change after attempts started, or re-drafting an exam that has attempts or results", body = ErrorResponse),
368- ),
369-)]
370-async fn update_exam(
371- State(st): State<AppState>,
372- RequireTeacher(user): RequireTeacher,
373- Path(id): Path<String>,
374- Json(req): Json<UpdateExam>,
375-) -> Result<Json<ExamResponse>, AppError> {
376- // Take the writer lease before the row read: the merge defaults and the
377- // mode/draft gates below all judge this snapshot, so a publish or mode
378- // change landing between an unlocked read and the gates would be silently
379- // written back over.
380- let _guard = EXAM_LOCK.write().await;
381- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
382- .await?
383- .ok_or(AppError::NotFound)?;
384- let course = course_of(&exam, &st.db).await?;
385- if !can_manage_course(&course, &user) {
386- return Err(AppError::Forbidden(
387- "only the course creator, an assigned teacher, or a manager/admin can edit this exam",
388- ));
389- }
390-
391- let title = match req.title {
392- Some(ref title) => ExamTitle::try_new(title)?,
393- None => exam.get_title().clone(),
394- };
395- let description = match req.description {
396- Some(ref description) => ExamDescription::try_new(description)?,
397- None => exam.get_description().clone(),
398- };
399- let kind = match req.kind {
400- // Only a kind this request sets is held to the current settings list —
401- // a stored kind survives later list edits, like past times survive
402- // the no-past rule.
403- Some(ref kind) => {
404- let school = Settings::load(&st.db).await?;
405- ExamKind::try_new(kind, school.get_exam_kinds())?
406- }
407- None => exam.get_kind().clone(),
408- };
409-
410- // Merge the schedule (set / clear / keep per field), then re-validate it
411- // as a unit — a PATCH can't leave a half-schedule behind. Only values this
412- // request sets are held to the no-past rule: kept ones may legitimately be
413- // past (a running exam's `starts_at`), and rechecking them would block
414- // unrelated edits.
415- let mode = match req.mode {
416- Some(update) => update.as_deref().map(ExamMode::try_new).transpose()?,
417- None => exam.get_mode().cloned(),
418- };
419- let starts_at = match req.starts_at {
420- Some(update) => {
421- let starts_at = update.map(Timestamp::from_millis);
422- check_not_past("starts_at", starts_at)?;
423- starts_at
424- }
425- None => exam.get_starts_at(),
426- };
427- let ends_at = match req.ends_at {
428- Some(update) => {
429- let ends_at = update.map(Timestamp::from_millis);
430- check_not_past("ends_at", ends_at)?;
431- ends_at
432- }
433- None => exam.get_ends_at(),
434- };
435- let duration_ms = match req.duration_ms {
436- Some(update) => update.map(ExamDuration::try_new).transpose()?,
437- None => exam.get_duration_ms(),
438- };
439- let schedule = ExamSchedule::try_new(mode, starts_at, ends_at, duration_ms)?;
440- let max_attempts = match req.max_attempts {
441- Some(limit) => ExamAttemptLimit::try_new(limit)?,
442- None => exam.get_max_attempts(),
443- };
444- let allow_rejoin = req.allow_rejoin.unwrap_or_else(|| exam.get_allow_rejoin());
445- let allow_review = req.allow_review.unwrap_or_else(|| exam.get_allow_review());
446- let draft = req.draft.unwrap_or_else(|| exam.is_draft());
447-
448- // Switching sync <-> async <-> open (or back to unscheduled) would
449- // silently rewrite the deadline rules under students who already sat
450- // down; extending times, the attempt limit, and the rejoin door are the
451- // supported live adjustments instead. Gate read and write share the
452- // handler-wide writer lease of [`EXAM_LOCK`], so a first attempt can't
453- // land in the gap and leave a sat exam's mode flipped under it.
454- let mode_changed =
455- schedule.get_mode().map(ExamMode::as_str) != exam.get_mode().map(ExamMode::as_str);
456- if mode_changed && ExamAttempt::any_for_exam(exam.get_id(), &st.db).await? {
457- return Err(AppError::Conflict(
458- "cannot change the exam mode after attempts have started",
459- ));
460- }
461- // Re-drafting hides the exam — never out from under a student who already
462- // sat it or holds a mark on it. Same writer lease: a first attempt or an
463- // in-flight grade (readers) can't slip between this gate and the write.
464- if draft && !exam.is_draft() {
465- let sat = ExamAttempt::any_for_exam(exam.get_id(), &st.db).await?;
466- let graded = !ExamResult::list_for_exam(exam.get_id(), &st.db)
467- .await?
468- .is_empty();
469- if sat || graded {
470- return Err(AppError::Conflict(
471- "cannot turn a published exam back into a draft after attempts or results exist",
472- ));
473- }
474- }
475-
476- let updated = exam
477- .update(
478- title,
479- description,
480- kind,
481- schedule,
482- max_attempts,
483- allow_rejoin,
484- allow_review,
485- draft,
486- &st.db,
487- )
488- .await?;
489- Ok(Json(ExamResponse::new(&updated)))
490-}
491-
492-/// Delete an exam. Requires teacher+ and management rights over the exam's
493-/// course (its creator, or manager/admin). Cascades the exam's results,
494-/// attempts, questions, answers, and question + answer images (blobs included).
495-#[utoipa::path(
496- delete,
497- path = "/{id}",
498- tag = "exams",
499- security(("session_cookie" = [])),
500- params(("id" = String, Path, description = "Exam id")),
501- responses(
502- (status = 204, description = "Deleted"),
503- (status = 401, description = "Not authenticated", body = ErrorResponse),
504- (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
505- (status = 404, description = "Not found", body = ErrorResponse),
506- ),
507-)]
508-async fn delete_exam(
509- State(st): State<AppState>,
510- RequireTeacher(user): RequireTeacher,
511- Path(id): Path<String>,
512-) -> Result<StatusCode, AppError> {
513- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
514- .await?
515- .ok_or(AppError::NotFound)?;
516- let course = course_of(&exam, &st.db).await?;
517- if !can_manage_course(&course, &user) {
518- return Err(AppError::Forbidden(
519- "only the course creator, an assigned teacher, or a manager/admin can delete this exam",
520- ));
521- }
522- // Rows go first (the delete cascades them), blobs after — a crash in
523- // between strands at worst an unreachable blob.
524- let images = QuestionImage::list_for_exam(exam.get_id(), &st.db).await?;
525- let answer_images = AnswerImage::list_for_exam(exam.get_id(), &st.db).await?;
526- exam.delete(&st.db).await?;
527- for image in &images {
528- remove_blob(&st.files_path, image.get_file()).await;
529- }
530- for image in &answer_images {
531- remove_blob(&st.files_path, image.get_file()).await;
532- }
533- Ok(StatusCode::NO_CONTENT)
534-}
535-
536-// ---- results ------------------------------------------------------------
537-
538-/// Record (or overwrite) a student's mark for an exam. Requires teacher+ and
539-/// management rights over the exam's course; the target must be a student and
540-/// enrolled. Only students carry marks; students never grade — and nobody
541-/// grades themselves. A draft can't be graded (`409`) — a mark would point at
542-/// an exam its student can't see.
543-#[utoipa::path(
544- post,
545- path = "/{id}/results",
546- tag = "exams",
547- security(("session_cookie" = [])),
548- params(("id" = String, Path, description = "Exam id")),
549- request_body = GradeResult,
550- responses(
551- (status = 200, description = "Result recorded", body = ExamResultResponse),
552- (status = 400, description = "Invalid mark, unknown user, user not a student, or not enrolled", body = ErrorResponse),
553- (status = 401, description = "Not authenticated", body = ErrorResponse),
554- (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse),
555- (status = 404, description = "Exam not found", body = ErrorResponse),
556- (status = 409, description = "The exam is a draft", body = ErrorResponse),
557- ),
558-)]
559-async fn grade(
560- State(st): State<AppState>,
561- RequireTeacher(teacher): RequireTeacher,
562- Path(id): Path<String>,
563- Json(req): Json<GradeResult>,
564-) -> Result<Json<ExamResultResponse>, AppError> {
565- let exam_id = ExamId::from_key(&id);
566- // Reader lease of [`EXAM_LOCK`] from the exam read through the result
567- // write: the draft gate below must be judged against the same row the
568- // mark lands under, or a concurrent re-draft (a writer, which checks for
569- // results) could slip between them and leave a mark on a hidden exam.
570- let _guard = EXAM_LOCK.read().await;
571- // Exam must exist.
572- let exam = Exam::read(&exam_id, &st.db)
573- .await?
574- .ok_or(AppError::NotFound)?;
575- let course = course_of(&exam, &st.db).await?;
576- if !can_manage_course(&course, &teacher) {
577- return Err(AppError::Forbidden(
578- "only the course creator, an assigned teacher, or a manager/admin can grade this exam",
579- ));
580- }
581- if exam.is_draft() {
582- return Err(AppError::Conflict(
583- "this exam is a draft — publish it before grading",
584- ));
585- }
586-
587- let mark = Mark::try_new(req.mark)?;
588- let target = UserId::from_key(&req.user_id);
589-
590- // Grading never targets oneself — no grader, whatever their role, may
591- // write their own mark.
592- if &target == teacher.get_id() {
593- return Err(AppError::Forbidden("grading yourself is not allowed"));
594- }
595-
596- // Target user must exist.
597- let Some(target_user) = User::read(&target, &st.db).await? else {
598- return Err(AppError::Validation(ValidationError::Invalid {
599- field: "user_id",
600- reason: "target user does not exist",
601- }));
602- };
603-
604- // Only students carry marks — the grade system is theirs alone. A stale
605- // enrollment left behind by a promotion can't reopen grading for staff.
606- if target_user.get_role() != Role::Student {
607- return Err(AppError::Validation(ValidationError::Invalid {
608- field: "user_id",
609- reason: "only students can be graded",
610- }));
611- }
612-
613- // ... and be enrolled in the exam's course.
614- if Enrollment::read_for_user(exam.get_course(), &target, &st.db)
615- .await?
616- .is_none()
617- {
618- return Err(AppError::Validation(ValidationError::Invalid {
619- field: "user_id",
620- reason: "target user is not enrolled in this course",
621- }));
622- }
623-
624- // The mark lands on the student's current sitting; the latest seq is the
625- // grade-of-record. An offline-graded exam has no sitting — grade its base
626- // seq (1).
627- let seq = ExamAttempt::read_latest_for_user(&exam_id, &target, &st.db)
628- .await?
629- .map_or(1, |a| a.get_seq());
630- let result = ExamResult::grade(&exam_id, &target, seq, mark, teacher.get_id(), &st.db).await?;
631- let people = PersonRef::map_of(&[&target_user, &teacher]);
632- Ok(Json(ExamResultResponse::new(&result, &people)))
633-}
634-
635-/// List an exam's results, paged via `?limit=&offset=` (omit `limit` for all
636-/// of them). Requires teacher+ and management rights over the exam's course —
637-/// students read only their own via `GET /exams/{id}/result`. Returns a
638-/// `{items, total, limit, offset}` envelope.
639-#[utoipa::path(
640- get,
641- path = "/{id}/results",
642- tag = "exams",
643- security(("session_cookie" = [])),
644- params(("id" = String, Path, description = "Exam id"), PageParams),
645- responses(
646- (status = 200, description = "A page of results (all of them when unpaged)", body = Page<ExamResultResponse>),
647- (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
648- (status = 401, description = "Not authenticated", body = ErrorResponse),
649- (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
650- (status = 404, description = "Exam not found", body = ErrorResponse),
651- ),
652-)]
653-async fn list_results(
654- State(st): State<AppState>,
655- RequireTeacher(user): RequireTeacher,
656- Path(id): Path<String>,
657- Query(page): Query<PageParams>,
658-) -> Result<Json<Page<ExamResultResponse>>, AppError> {
659- let (limit, offset) = page.resolve()?;
660- // Exam must exist — a missing exam is a 404, not an empty result list.
661- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
662- .await?
663- .ok_or(AppError::NotFound)?;
664- let course = course_of(&exam, &st.db).await?;
665- if !can_manage_course(&course, &user) {
666- return Err(AppError::Forbidden(
667- "only the course creator, an assigned teacher, or a manager/admin can list results",
668- ));
669- }
670- let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?;
671- let total = results.len() as i64;
672- // Join people onto the page alone — the lookup shrinks with the window.
673- let rows = paginate(&results, limit, offset);
674- let people = person_map(
675- rows.iter()
676- .flat_map(|r| [r.get_user().clone(), r.get_graded_by().clone()]),
677- &st.db,
678- )
679- .await?;
680- let items = rows
681- .iter()
682- .map(|r| ExamResultResponse::new(r, &people))
683- .collect();
684- Ok(Json(Page::new(items, total, limit, offset)))
685-}
686-
687-/// The current user's own result for an exam. Any authenticated user may read
688-/// their own mark; `404` while ungraded (or when the exam doesn't exist).
689-#[utoipa::path(
690- get,
691- path = "/{id}/result",
692- tag = "exams",
693- security(("session_cookie" = [])),
694- params(("id" = String, Path, description = "Exam id")),
695- responses(
696- (status = 200, description = "The caller's result", body = ExamResultResponse),
697- (status = 401, description = "Not authenticated", body = ErrorResponse),
698- (status = 404, description = "No such exam, or not graded yet", body = ErrorResponse),
699- ),
700-)]
701-async fn my_result(
702- State(st): State<AppState>,
703- CurrentUser(user): CurrentUser,
704- Path(id): Path<String>,
705-) -> Result<Json<ExamResultResponse>, AppError> {
706- let result = ExamResult::read_for_user(&ExamId::from_key(&id), user.get_id(), &st.db)
707- .await?
708- .ok_or(AppError::NotFound)?;
709- let people = person_map(
710- [result.get_user().clone(), result.get_graded_by().clone()],
711- &st.db,
712- )
713- .await?;
714- Ok(Json(ExamResultResponse::new(&result, &people)))
715-}
716-
717-/// Remove a student's result from an exam. Requires teacher+ and management
718-/// rights over the exam's course.
719-#[utoipa::path(
720- delete,
721- path = "/{id}/results/{user}",
722- tag = "exams",
723- security(("session_cookie" = [])),
724- params(
725- ("id" = String, Path, description = "Exam id"),
726- ("user" = String, Path, description = "User id"),
727- ),
728- responses(
729- (status = 204, description = "Removed"),
730- (status = 401, description = "Not authenticated", body = ErrorResponse),
731- (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
732- (status = 404, description = "Not found", body = ErrorResponse),
733- ),
734-)]
735-async fn remove_result(
736- State(st): State<AppState>,
737- RequireTeacher(user): RequireTeacher,
738- Path((id, target)): Path<(String, String)>,
739-) -> Result<StatusCode, AppError> {
740- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
741- .await?
742- .ok_or(AppError::NotFound)?;
743- let course = course_of(&exam, &st.db).await?;
744- if !can_manage_course(&course, &user) {
745- return Err(AppError::Forbidden(
746- "only the course creator, an assigned teacher, or a manager/admin can remove results",
747- ));
748- }
749- let removed = ExamResult::remove(exam.get_id(), &UserId::from_key(&target), &st.db).await?;
750- if removed.is_none() {
751- return Err(AppError::NotFound);
752- }
753- Ok(StatusCode::NO_CONTENT)
754-}
755-
756-/// Summary statistics for an exam's graded results. Requires teacher+ and
757-/// management rights over the exam's course.
758-#[utoipa::path(
759- get,
760- path = "/{id}/statistics",
761- tag = "exams",
762- security(("session_cookie" = [])),
763- params(("id" = String, Path, description = "Exam id")),
764- responses(
765- (status = 200, description = "The exam's mark statistics", body = ExamStatisticsResponse),
766- (status = 401, description = "Not authenticated", body = ErrorResponse),
767- (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
768- (status = 404, description = "Exam not found", body = ErrorResponse),
769- ),
770-)]
771-async fn exam_statistics(
772- State(st): State<AppState>,
773- RequireTeacher(user): RequireTeacher,
774- Path(id): Path<String>,
775-) -> Result<Json<ExamStatisticsResponse>, AppError> {
776- // Exam must exist — a missing exam is a 404, not an empty statistic.
777- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
778- .await?
779- .ok_or(AppError::NotFound)?;
780- let course = course_of(&exam, &st.db).await?;
781- if !can_manage_course(&course, &user) {
782- return Err(AppError::Forbidden(
783- "only the course creator, an assigned teacher, or a manager/admin can view statistics",
784- ));
785- }
786- let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?;
787-
788- let marks: Vec<i64> = results.iter().map(|r| r.get_mark().as_i64()).collect();
789- let average =
790- (!marks.is_empty()).then(|| marks.iter().sum::<i64>() as f64 / marks.len() as f64);
791- Ok(Json(ExamStatisticsResponse {
792- exam: exam.get_id().key().to_string(),
793- graded: marks.len() as u64,
794- average,
795- min: marks.iter().min().copied(),
796- max: marks.iter().max().copied(),
797- }))
798-}
799-
800-// ---- attempts -------------------------------------------------------------
801-// A sittable exam (sync, async, or open mode) is *sat*: starting an attempt
802-// is the live-attendance signal, finishing is the submission. The exam's
803-// `max_attempts` (0 = unlimited) says how many sittings each student gets;
804-// re-posting resumes a running attempt and mints the next sitting once the
805-// last one is over. Deadlines are judged only by the server clock — clients
806-// sync via `GET /time`.
807-
808-/// A student's view of their (latest) attempt. `now` is echoed so clients can
809-/// render countdowns without trusting the device clock.
810-#[derive(Serialize, ToSchema)]
811-struct AttemptResponse {
812- id: String,
813- exam: String,
814- user: PersonRef,
815- /// Which sitting this is — 1 for the first attempt, counting up.
816- attempt: i64,
817- /// How many sittings the caller has used, this one included.
818- attempts_used: u64,
819- /// The exam's attempt limit; `0` means unlimited.
820- max_attempts: i64,
821- /// When the attempt started, UTC unix-milliseconds.
822- started_at: i64,
823- /// Submission instant; `null` while running (or expired unsubmitted).
824- finished_at: Option<i64>,
825- /// When the student left the exam room mid-attempt; `null` while inside
826- /// (or if they never used the room). With `allow_rejoin` off, a set
827- /// `left_at` locks further answering until the teacher reopens the door.
828- left_at: Option<i64>,
829- /// `in_progress` | `submitted` | `expired`.
830- #[schema(example = "in_progress")]
831- status: String,
832- /// When the attempt closes: the earlier of the window's `ends_at` and
833- /// `started_at + duration_ms` (whichever exists). Recomputed live from
834- /// the exam's current schedule; `null` for an open exam without a
835- /// duration — such an attempt only ends by submission.
836- deadline: Option<i64>,
837- /// `deadline - now`, floored at 0; `null` unless in progress with a
838- /// deadline.
839- remaining_ms: Option<i64>,
840- /// The caller's mark, once graded.
841- mark: Option<i64>,
842- /// How many questions the caller has answered so far.
843- answered: u64,
844- /// How many questions the exam has.
845- question_count: u64,
846- /// Server clock at response time, UTC unix-milliseconds.
847- now: i64,
848-}
849-
850-impl AttemptResponse {
851- #[expect(
852- clippy::too_many_arguments,
853- reason = "a flat view over attempt + exam + progress; a builder would obscure it"
854- )]
855- fn new(
856- attempt: &ExamAttempt,
857- exam: &Exam,
858- mark: Option<Mark>,
859- people: &HashMap<String, PersonRef>,
860- answered: u64,
861- question_count: u64,
862- attempts_used: u64,
863- now: Timestamp,
864- ) -> Self {
865- let status = attempt.status(exam, now);
866- let deadline = attempt.deadline(exam);
867- let remaining_ms = (status == AttemptStatus::InProgress)
868- .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0)))
869- .flatten();
870- Self {
871- id: attempt.get_id().key().to_string(),
872- exam: attempt.get_exam().key().to_string(),
873- user: PersonRef::resolve(people, attempt.get_user()),
874- attempt: attempt.get_seq(),
875- attempts_used,
876- max_attempts: exam.get_max_attempts().as_i64(),
877- started_at: attempt.get_started_at().as_millis(),
878- finished_at: attempt.get_finished_at().map(|t| t.as_millis()),
879- left_at: attempt.get_left_at().map(|t| t.as_millis()),
880- status: status.as_str().to_string(),
881- deadline: deadline.map(|t| t.as_millis()),
882- remaining_ms,
883- mark: mark.map(|m| m.as_i64()),
884- answered,
885- question_count,
886- now: now.as_millis(),
887- }
888- }
889-}
890-
891-/// The (answered, question_count) pair behind an attempt view — how far one
892-/// student has come through the exam's question list.
893-async fn attempt_progress(
894- exam: &ExamId,
895- user: &UserId,
896- seq: i64,
897- db: &Database,
898-) -> Result<(u64, u64), AppError> {
899- let answered = ExamAnswer::list_for_exam_user(exam, user, seq, db)
900- .await?
901- .len() as u64;
902- let question_count = ExamQuestion::list_for_exam(exam, db).await?.len() as u64;
903- Ok((answered, question_count))
904-}
905-
906-/// Rejects sitting an exam that can't be sat. A draft is a `404`, not a
907-/// `409` — sitting is a student act, drafts are invisible to students, and a
908-/// state-specific error would leak the existence this feature hides. A
909-/// modeless (offline-graded) exam is a `409`: visible, just nothing to sit.
910-/// Enrollment and window checks for the caller are the caller's own state —
911-/// also `Conflict`, not validation.
912-pub(crate) fn ensure_sittable(exam: &Exam) -> Result<(), AppError> {
913- if exam.is_draft() {
914- return Err(AppError::NotFound);
915- }
916- if exam.get_mode().is_none() {
917- return Err(AppError::Conflict(
918- "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)",
919- ));
920- }
921- Ok(())
922-}
923-
924-/// How many sittings the caller has used at this exam.
925-async fn attempts_used(exam: &ExamId, user: &UserId, db: &Database) -> Result<u64, AppError> {
926- Ok(ExamAttempt::list_for_user(exam, user, db).await?.len() as u64)
927-}
928-
929-/// Start, resume, or retake the caller's attempt. Requires the student role
930-/// (staff run exams, they don't sit them), enrollment in the exam's course, a
931-/// sittable exam (`sync`/`async`/`open` mode), and — when a window exists — the
932-/// window to be open. A still-running attempt is returned
933-/// as-is (`200` instead of `201`), so a reconnecting client gets its original
934-/// clock back — re-starting never resets the time. Once the latest attempt is
935-/// submitted or expired, re-posting starts the next sitting (`201`, blank
936-/// answer sheet) while the exam's `max_attempts` (0 = unlimited) allows it.
937-#[utoipa::path(
938- post,
939- path = "/{id}/attempt",
940- tag = "exams",
941- security(("session_cookie" = [])),
942- params(("id" = String, Path, description = "Exam id")),
943- responses(
944- (status = 201, description = "Attempt started (first sitting or a retake)", body = AttemptResponse),
945- (status = 200, description = "Running attempt resumed (unchanged)", body = AttemptResponse),
946- (status = 401, description = "Not authenticated", body = ErrorResponse),
947- (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse),
948- (status = 404, description = "Exam not found (drafts are invisible here)", body = ErrorResponse),
949- (status = 409, description = "Unscheduled (offline-graded) exam, outside the window, or no attempts remaining", body = ErrorResponse),
950- ),
951-)]
952-async fn start_attempt(
953- State(st): State<AppState>,
954- CurrentUser(user): CurrentUser,
955- Path(id): Path<String>,
956-) -> Result<(StatusCode, Json<AttemptResponse>), AppError> {
957- // Writer lease of [`EXAM_LOCK`] from the exam read through the start: the
958- // sittable/window gates must be judged against the same exam row the
959- // attempt lands under (the mirror of `update_exam`'s re-derive — without
960- // it, a mode change or re-draft at legally-zero attempts could slip
961- // between this gate and the insert, leaving an attempt on an unsittable
962- // exam). The lease
963- // also keeps the max-attempts count and the retake's wipe-and-create
964- // from interleaving with an in-flight answer save (a reader). Dropped
965- // before the response reads — they only describe the row.
966- let guard = EXAM_LOCK.write().await;
967- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
968- .await?
969- .ok_or(AppError::NotFound)?;
970- ensure_sittable(&exam)?;
971- ensure_student(&user)?;
972- ensure_enrolled(&exam, user.get_id(), &st.db).await?;
973- let now = Timestamp::now();
974- if let Some(starts_at) = exam.get_starts_at()
975- && now < starts_at
976- {
977- return Err(AppError::Conflict("the exam has not started yet"));
978- }
979- if let Some(ends_at) = exam.get_ends_at()
980- && now >= ends_at
981- {
982- return Err(AppError::Conflict("the exam has already ended"));
983- }
984-
985- // A retake no longer wipes the prior sitting — each attempt's answers,
986- // drawings, and marks stay put at their own seq (per-attempt history), so
987- // there are no orphaned blobs to GC here. The exam-delete cascade still
988- // cleans every sitting's blobs.
989- let (attempt, created) = ExamAttempt::start(&exam, user.get_id(), &st.db).await?;
990- drop(guard);
991- let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
992- .await?
993- .map(|r| r.get_mark());
994- let (answered, question_count) =
995- attempt_progress(exam.get_id(), user.get_id(), attempt.get_seq(), &st.db).await?;
996- let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?;
997- let people = PersonRef::map_of(&[&user]);
998- let status = if created {
999- StatusCode::CREATED
1000- } else {
1001- StatusCode::OK
1002- };
1003- Ok((
1004- status,
1005- Json(AttemptResponse::new(
1006- &attempt,
1007- &exam,
1008- mark,
1009- &people,
1010- answered,
1011- question_count,
1012- used,
1013- Timestamp::now(),
1014- )),
1015- ))
1016-}
1017-
1018-/// The caller's own (latest) attempt: status, deadline, remaining time, and
1019-/// mark once graded — everything a student's live exam screen needs, judged
1020-/// by the server clock. `404` until an attempt is started.
1021-#[utoipa::path(
1022- get,
1023- path = "/{id}/attempt",
1024- tag = "exams",
1025- security(("session_cookie" = [])),
1026- params(("id" = String, Path, description = "Exam id")),
1027- responses(
1028- (status = 200, description = "The caller's latest attempt", body = AttemptResponse),
1029- (status = 401, description = "Not authenticated", body = ErrorResponse),
1030- (status = 404, description = "No such exam, or no attempt yet", body = ErrorResponse),
1031- ),
1032-)]
1033-async fn my_attempt(
1034- State(st): State<AppState>,
1035- CurrentUser(user): CurrentUser,
1036- Path(id): Path<String>,
1037-) -> Result<Json<AttemptResponse>, AppError> {
1038- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
1039- .await?
1040- .ok_or(AppError::NotFound)?;
1041- let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db)
1042- .await?
1043- .ok_or(AppError::NotFound)?;
1044- let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
1045- .await?
1046- .map(|r| r.get_mark());
1047- let (answered, question_count) =
1048- attempt_progress(exam.get_id(), user.get_id(), attempt.get_seq(), &st.db).await?;
1049- let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?;
1050- let people = PersonRef::map_of(&[&user]);
1051- Ok(Json(AttemptResponse::new(
1052- &attempt,
1053- &exam,
1054- mark,
1055- &people,
1056- answered,
1057- question_count,
1058- used,
1059- Timestamp::now(),
1060- )))
1061-}
1062-
1063-/// Submit the caller's attempt. Allowed while the deadline hasn't passed;
1064-/// after it, the attempt is already `expired` (a valid terminal state — the
1065-/// student used their full time) and submitting is a `409`.
1066-#[utoipa::path(
1067- post,
1068- path = "/{id}/attempt/finish",
1069- tag = "exams",
1070- security(("session_cookie" = [])),
1071- params(("id" = String, Path, description = "Exam id")),
1072- responses(
1073- (status = 200, description = "Attempt submitted", body = AttemptResponse),
1074- (status = 401, description = "Not authenticated", body = ErrorResponse),
1075- (status = 404, description = "No such exam, or no attempt to finish", body = ErrorResponse),
1076- (status = 409, description = "Already submitted, or the deadline passed", body = ErrorResponse),
1077- ),
1078-)]
1079-async fn finish_attempt(
1080- State(st): State<AppState>,
1081- CurrentUser(user): CurrentUser,
1082- Path(id): Path<String>,
1083-) -> Result<Json<AttemptResponse>, AppError> {
1084- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
1085- .await?
1086- .ok_or(AppError::NotFound)?;
1087- let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db)
1088- .await?
1089- .ok_or(AppError::NotFound)?;
1090- if attempt.get_finished_at().is_some() {
1091- return Err(AppError::Conflict("the attempt is already submitted"));
1092- }
1093- let now = Timestamp::now();
1094- if let Some(deadline) = attempt.deadline(&exam)
1095- && now >= deadline
1096- {
1097- return Err(AppError::Conflict("time is up — the attempt has expired"));
1098- }
1099-
1100- // Deliberately no rejoin check: a student locked out of the room may
1101- // still submit what they saved — finishing answers nothing new.
1102- let finished = attempt.finish(&st.db).await?;
1103- let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
1104- .await?
1105- .map(|r| r.get_mark());
1106- let (answered, question_count) =
1107- attempt_progress(exam.get_id(), user.get_id(), finished.get_seq(), &st.db).await?;
1108- let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?;
1109- let people = PersonRef::map_of(&[&user]);
1110- Ok(Json(AttemptResponse::new(
1111- &finished,
1112- &exam,
1113- mark,
1114- &people,
1115- answered,
1116- question_count,
1117- used,
1118- Timestamp::now(),
1119- )))
1120-}
1121-
1122-// ---- live monitor ---------------------------------------------------------
1123-
1124-/// One roster row of the live exam monitor. The attempt fields describe the
1125-/// student's *latest* sitting.
1126-#[derive(Serialize, ToSchema)]
1127-struct LiveStudentResponse {
1128- user: PersonRef,
1129- /// `not_started` | `absent` | `in_progress` | `submitted` | `expired`.
1130- /// `absent` is `not_started` after the window closed: the student never
1131- /// sat and no longer can. Open exams have no window, so nobody is ever
1132- /// absent from one.
1133- #[schema(example = "in_progress")]
1134- status: String,
1135- /// Which sitting the shown attempt is (1, 2, …); `null` before the first.
1136- attempt: Option<i64>,
1137- /// How many sittings this student has used.
1138- attempts_used: u64,
1139- started_at: Option<i64>,
1140- finished_at: Option<i64>,
1141- /// When this student left the exam room mid-attempt; `null` while inside.
1142- left_at: Option<i64>,
1143- /// When this student's attempt closes (server-authoritative).
1144- deadline: Option<i64>,
1145- /// Time this student has left, floored at 0; `null` unless in progress.
1146- remaining_ms: Option<i64>,
1147- /// The student's mark, once graded.
1148- mark: Option<i64>,
1149- /// How many questions this student has answered so far.
1150- answered: u64,
1151- /// When this student last saved an answer, UTC unix-milliseconds; `null`
1152- /// before the first save.
1153- last_activity: Option<i64>,
1154-}
1155-
1156-#[derive(Serialize, ToSchema)]
1157-struct LiveCountsResponse {
1158- enrolled: u64,
1159- /// Enrolled with no attempt while the window is still open (or the exam
1160- /// has no window).
1161- not_started: u64,
1162- /// Enrolled with no attempt and the window closed — the no-shows.
1163- absent: u64,
1164- in_progress: u64,
1165- submitted: u64,
1166- expired: u64,
1167- graded: u64,
1168-}
1169-
1170-/// A live snapshot of an exam: the enrolled roster with per-student attempt
1171-/// state, remaining time, and marks, all judged by one server-clock read.
1172-#[derive(Serialize, ToSchema)]
1173-struct ExamLiveResponse {
1174- exam: ExamResponse,
1175- /// Server clock the snapshot was judged at, UTC unix-milliseconds.
1176- now: i64,
1177- /// How many questions the exam has.
1178- question_count: u64,
1179- counts: LiveCountsResponse,
1180- students: Vec<LiveStudentResponse>,
1181-}
1182-
1183-/// Build the monitor snapshot: roster ⋈ attempts ⋈ marks at one instant.
1184-/// Students unenrolled mid-exam drop off the roster view (their attempt and
1185-/// mark rows survive, exactly like the marks report).
1186-async fn live_snapshot(exam: &Exam, db: &Database) -> Result<ExamLiveResponse, AppError> {
1187- let now = Timestamp::now();
1188- let roster = Enrollment::list_for_course(exam.get_course(), db).await?;
1189- // Per student: their latest sitting (the one the monitor shows) plus how
1190- // many they've used.
1191- let mut attempts: HashMap<String, ExamAttempt> = HashMap::new();
1192- let mut used: HashMap<String, u64> = HashMap::new();
1193- for attempt in ExamAttempt::list_for_exam(exam.get_id(), db).await? {
1194- let key = attempt.get_user().key().to_string();
1195- *used.entry(key.clone()).or_insert(0) += 1;
1196- match attempts.entry(key) {
1197- std::collections::hash_map::Entry::Vacant(slot) => {
1198- slot.insert(attempt);
1199- }
1200- std::collections::hash_map::Entry::Occupied(mut slot) => {
1201- if attempt.get_seq() > slot.get().get_seq() {
1202- slot.insert(attempt);
1203- }
1204- }
1205- }
1206- }
1207- let marks: HashMap<String, i64> = ExamResult::list_for_exam(exam.get_id(), db)
1208- .await?
1209- .iter()
1210- .map(|result| {
1211- (
1212- result.get_user().key().to_string(),
1213- result.get_mark().as_i64(),
1214- )
1215- })
1216- .collect();
1217- let question_count = ExamQuestion::list_for_exam(exam.get_id(), db).await?.len() as u64;
1218- // Per-student progress: answer count and the latest save instant. The
1219- // per-exam read now returns every sitting's rows across all students, so
1220- // each answer is scoped to that student's *current* sitting — matching its
1221- // seq to their latest attempt — or a re-sitting student's count would
1222- // double up their prior attempts.
1223- let mut progress: HashMap<String, (u64, i64)> = HashMap::new();
1224- for answer in ExamAnswer::list_for_exam(exam.get_id(), db).await? {
1225- let key = answer.get_user().key().to_string();
1226- if attempts.get(&key).map(ExamAttempt::get_seq) != Some(answer.get_seq()) {
1227- continue;
1228- }
1229- let entry = progress.entry(key).or_insert((0, i64::MIN));
1230- entry.0 += 1;
1231- entry.1 = entry.1.max(answer.get_updated_at().as_millis());
1232- }
1233- let people = person_map(roster.iter().map(|e| e.get_user().clone()), db).await?;
1234-
1235- // Once the window closes the door is shut for good (starting answers
1236- // 409), so "hasn't started" hardens into "was absent". Open exams have
1237- // no window and never make that call.
1238- let window_over = exam.get_ends_at().is_some_and(|ends| now >= ends);
1239- let mut students: Vec<LiveStudentResponse> = roster
1240- .iter()
1241- .map(|enrollment| {
1242- let key = enrollment.get_user().key();
1243- let attempt = attempts.get(key);
1244- let status = attempt.map(|a| a.status(exam, now));
1245- let deadline = attempt.and_then(|a| a.deadline(exam));
1246- LiveStudentResponse {
1247- user: PersonRef::resolve(&people, enrollment.get_user()),
1248- status: match status {
1249- Some(status) => status.as_str(),
1250- None if window_over => "absent",
1251- None => "not_started",
1252- }
1253- .to_string(),
1254- attempt: attempt.map(ExamAttempt::get_seq),
1255- attempts_used: used.get(key).copied().unwrap_or(0),
1256- started_at: attempt.map(|a| a.get_started_at().as_millis()),
1257- finished_at: attempt
1258- .and_then(|a| a.get_finished_at())
1259- .map(|t| t.as_millis()),
1260- left_at: attempt.and_then(|a| a.get_left_at()).map(|t| t.as_millis()),
1261- deadline: deadline.map(|t| t.as_millis()),
1262- remaining_ms: (status == Some(AttemptStatus::InProgress))
1263- .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0)))
1264- .flatten(),
1265- mark: marks.get(key).copied(),
1266- answered: progress.get(key).map_or(0, |p| p.0),
1267- last_activity: progress.get(key).map(|p| p.1),
1268- }
1269- })
1270- .collect();
1271- students.sort_by(|a, b| a.user.username.cmp(&b.user.username));
1272-
1273- let count = |status: &str| students.iter().filter(|s| s.status == status).count() as u64;
1274- let counts = LiveCountsResponse {
1275- enrolled: students.len() as u64,
1276- not_started: count("not_started"),
1277- absent: count("absent"),
1278- in_progress: count("in_progress"),
1279- submitted: count("submitted"),
1280- expired: count("expired"),
1281- graded: students.iter().filter(|s| s.mark.is_some()).count() as u64,
1282- };
1283- Ok(ExamLiveResponse {
1284- exam: ExamResponse::new(exam),
1285- now: now.as_millis(),
1286- question_count,
1287- counts,
1288- students,
1289- })
1290-}
1291-
1292-/// A one-shot live snapshot of the exam: who's in, who's still writing (and
1293-/// on which sitting), who walked out of the room (`left_at`), who never
1294-/// showed at all (`absent`, once the window is over), time each student has
1295-/// left, and marks as they land. Requires teacher+ and management rights
1296-/// over the exam's course. Poll it to keep a monitor up to date.
1297-#[utoipa::path(
1298- get,
1299- path = "/{id}/live",
1300- tag = "exams",
1301- security(("session_cookie" = [])),
1302- params(("id" = String, Path, description = "Exam id")),
1303- responses(
1304- (status = 200, description = "Live snapshot", body = ExamLiveResponse),
1305- (status = 401, description = "Not authenticated", body = ErrorResponse),
1306- (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
1307- (status = 404, description = "Exam not found", body = ErrorResponse),
1308- ),
1309-)]
1310-async fn exam_live(
1311- State(st): State<AppState>,
1312- RequireTeacher(user): RequireTeacher,
1313- Path(id): Path<String>,
1314-) -> Result<Json<ExamLiveResponse>, AppError> {
1315- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
1316- .await?
1317- .ok_or(AppError::NotFound)?;
1318- let course = course_of(&exam, &st.db).await?;
1319- if !can_manage_course(&course, &user) {
1320- return Err(AppError::Forbidden(
1321- "only the course creator, an assigned teacher, or a manager/admin can monitor this exam",
1322- ));
1323- }
1324- Ok(Json(live_snapshot(&exam, &st.db).await?))
1325-}
1326-
1327-// ---- questions --------------------------------------------------------------
1328-// Teachers author the question list before the exam runs; it freezes the
1329-// moment anyone starts an attempt, so every student sits the same exam.
1330-
1331-#[derive(Deserialize, ToSchema)]
1332-struct CreateQuestion {
1333- /// The subject this question belongs to — one of the exam's course's
1334- /// subjects (`GET /courses/{id}/subjects`). Required.
1335- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
1336- subject_id: String,
1337- /// The question itself.
1338- #[schema(example = "What is 2 + 2?", max_length = 2000)]
1339- text: String,
1340- /// `choice` or `text`.
1341- #[schema(example = "choice")]
1342- kind: String,
1343- /// This question's share of the auto-score, `1`–`100`.
1344- #[schema(example = 10, minimum = 1, maximum = 100)]
1345- points: i64,
1346- /// The options of a `choice` question (2–10 of them); omit for `text`.
1347- /// Each carries an `id` naming it within this payload — the server mints
1348- /// the stored ids and returns them.
1349- #[schema(min_items = 2, max_items = 10)]
1350- choices: Option<Vec<ChoiceBody>>,
1351- /// The `id` of the right option, as sent in `choices`; required for
1352- /// `choice`, absent for `text`.
1353- #[schema(example = "b")]
1354- correct: Option<String>,
1355-}
1356-
1357-#[derive(Deserialize, ToSchema)]
1358-struct UpdateQuestion {
1359- /// Re-tag the question with another of the course's subjects. Omit to
1360- /// keep the current one — a question always has a subject, so there is no
1361- /// clearing it.
1362- subject_id: Option<String>,
1363- #[schema(max_length = 2000)]
1364- text: Option<String>,
1365- #[schema(minimum = 1, maximum = 100)]
1366- points: Option<i64>,
1367- /// `choice` or `text`. Switching kinds needs the other fields to follow:
1368- /// send `choices` + `correct` when moving to `choice`, explicit `null`s
1369- /// when moving to `text`.
1370- kind: Option<String>,
1371- /// Omit to keep the stored options; send `null` to drop them (text
1372- /// questions only). Send each option back with the `id` it was returned
1373- /// with to keep it — its picture rides along. Only options whose id is
1374- /// absent from the new list lose their picture, so reordering, renaming,
1375- /// and deleting one option leave the rest untouched.
1376- #[serde(default, deserialize_with = "set_or_clear")]
1377- #[schema(value_type = Option<Vec<ChoiceBody>>, min_items = 2, max_items = 10)]
1378- choices: Option<Option<Vec<ChoiceBody>>>,
1379- /// The `id` of the right option. Omit to keep; `null` to clear (text
1380- /// questions only).
1381- #[serde(default, deserialize_with = "set_or_clear")]
1382- #[schema(value_type = Option<String>)]
1383- correct: Option<Option<String>>,
1384-}
1385-
1386-/// A stored question image's metadata; the bytes come from the image
1387-/// endpoints (`GET .../image`, `GET .../choices/{choice_id}/image`).
1388-#[derive(Serialize, ToSchema)]
1389-struct ImageMetaResponse {
1390- /// MIME type as declared on upload (always one of the raster allowlist).
1391- #[schema(example = "image/png")]
1392- content_type: String,
1393- /// Image size in bytes.
1394- #[schema(example = 24_576)]
1395- size: i64,
1396-}
1397-
1398-impl ImageMetaResponse {
1399- fn new(image: &QuestionImage) -> Self {
1400- Self {
1401- content_type: image.get_content_type().as_str().to_string(),
1402- size: image.get_size(),
1403- }
1404- }
1405-
1406- fn from_answer(image: &AnswerImage) -> Self {
1407- Self {
1408- content_type: image.get_content_type().as_str().to_string(),
1409- size: image.get_size(),
1410- }
1411- }
1412-}
1413-
1414-/// The question's slot out of its image rows.
1415-fn image_meta(images: &[QuestionImage], slot: Option<&ChoiceId>) -> Option<ImageMetaResponse> {
1416- images
1417- .iter()
1418- .find(|image| image.get_slot() == slot)
1419- .map(ImageMetaResponse::new)
1420-}
1421-
1422-/// The per-choice metas, aligned position-for-position with `choices` (`None`
1423-/// entries = that option has no picture); `None` whole for text questions.
1424-/// A response-only projection: the pictures are *stored* against choice ids, so
1425-/// this alignment is rebuilt from the current list on every read and can never
1426-/// go stale.
1427-fn choice_image_metas(
1428- question: &ExamQuestion,
1429- images: &[QuestionImage],
1430-) -> Option<Vec<Option<ImageMetaResponse>>> {
1431- question.get_choices().map(|choices| {
1432- choices
1433- .iter()
1434- .map(|choice| image_meta(images, Some(choice.get_id())))
1435- .collect()
1436- })
1437-}
1438-
1439-/// `exam`'s image rows bucketed by question key — one query feeding a whole
1440-/// question list.
1441-async fn images_by_question(
1442- exam: &ExamId,
1443- db: &Database,
1444-) -> Result<HashMap<String, Vec<QuestionImage>>, AppError> {
1445- let mut buckets: HashMap<String, Vec<QuestionImage>> = HashMap::new();
1446- for image in QuestionImage::list_for_exam(exam, db).await? {
1447- buckets
1448- .entry(image.get_question().key().to_string())
1449- .or_default()
1450- .push(image);
1451- }
1452- Ok(buckets)
1453-}
1454-
1455-/// One option on the wire: its stable id and its text. Carries **no** answer
1456-/// key — `correct` is a sibling field on the question, and only on the
1457-/// author-facing DTO, so a student response cannot contain one by construction.
1458-#[derive(Serialize, ToSchema)]
1459-pub(crate) struct ChoiceResponse {
1460- /// Send this back in a PATCH to keep the option (and its picture).
1461- id: String,
1462- text: String,
1463-}
1464-
1465-impl ChoiceResponse {
1466- pub(crate) fn list(choices: Option<&[Choice]>) -> Option<Vec<Self>> {
1467- choices.map(|choices| {
1468- choices
1469- .iter()
1470- .map(|choice| Self {
1471- id: choice.get_id().as_str().to_string(),
1472- text: choice.get_text().as_str().to_string(),
1473- })
1474- .collect()
1475- })
1476- }
1477-}
1478-
1479-/// A question as its author sees it — including the `correct` option. Never
1480-/// serialized to students; they get [`AttemptQuestionResponse`].
1481-#[derive(Serialize, ToSchema)]
1482-struct QuestionResponse {
1483- id: String,
1484- exam: String,
1485- /// The subject this question belongs to (`GET /subjects/{id}`).
1486- subject: String,
1487- text: String,
1488- /// `choice` or `text`.
1489- #[schema(example = "choice")]
1490- kind: String,
1491- points: i64,
1492- /// The options with their stable ids (`choice` questions only).
1493- choices: Option<Vec<ChoiceResponse>>,
1494- /// The id of the right option (`choice` questions only).
1495- correct: Option<String>,
1496- /// The question's illustration, if one was uploaded (any kind).
1497- image: Option<ImageMetaResponse>,
1498- /// Per-option pictures, aligned with `choices` (`choice` questions only).
1499- choice_images: Option<Vec<Option<ImageMetaResponse>>>,
1500- /// The bank template this question was created from, if it was added out of
1501- /// the bank (`GET /bank-questions/{id}`).
1502- from_bank: Option<String>,
1503- /// The bank template most recently created by saving this question into the
1504- /// bank, if any — set only by `POST …/questions/{qid}/to-bank`. Null on a
1505- /// question that came *from* the bank and was never saved back.
1506- banked_as: Option<String>,
1507-}
1508-
1509-impl QuestionResponse {
1510- fn new(question: &ExamQuestion, images: &[QuestionImage]) -> Self {
1511- Self {
1512- id: question.get_id().key().to_string(),
1513- exam: question.get_exam().key().to_string(),
1514- subject: question.get_subject().key().to_string(),
1515- text: question.get_text().as_str().to_string(),
1516- kind: question.get_kind().as_str().to_string(),
1517- points: question.get_points().as_i64(),
1518- choices: ChoiceResponse::list(question.get_choices()),
1519- correct: question.get_correct().map(|id| id.as_str().to_string()),
1520- image: image_meta(images, None),
1521- choice_images: choice_image_metas(question, images),
1522- from_bank: question.get_from_bank().map(|b| b.key().to_string()),
1523- banked_as: question.get_banked_as().map(|b| b.key().to_string()),
1524- }
1525- }
1526-}
1527-
1528-/// The questions freeze once anyone has started an attempt — editing them
1529-/// under a student mid-exam would fork what "the exam" means.
1530-async fn ensure_questions_editable(exam: &ExamId, db: &Database) -> Result<(), AppError> {
1531- if ExamAttempt::any_for_exam(exam, db).await? {
1532- return Err(AppError::Conflict(
1533- "cannot change questions after attempts have started",
1534- ));
1535- }
1536- Ok(())
1537-}
1538-
1539-/// The question, provided it belongs to `exam` — a qid under someone else's
1540-/// exam is a plain 404, not a leak.
1541-async fn question_of_exam(
1542- exam: &ExamId,
1543- qid: &str,
1544- db: &Database,
1545-) -> Result<ExamQuestion, AppError> {
1546- let question = ExamQuestion::read(&ExamQuestionId::from_key(qid), db)
1547- .await?
1548- .ok_or(AppError::NotFound)?;
1549- if question.get_exam() != exam {
1550- return Err(AppError::NotFound);
1551- }
1552- Ok(question)
1553-}
1554-
1555-/// The question's option named by `choice_id` — a 400 for a text question or an
1556-/// id the question doesn't have, so an option picture can only ever be
1557-/// addressed through an option that exists.
1558-fn choice_slot(question: &ExamQuestion, choice_id: &str) -> Result<ChoiceId, AppError> {
1559- let Some(choices) = question.get_choices() else {
1560- return Err(AppError::Validation(ValidationError::Invalid {
1561- field: "choice_id",
1562- reason: "only choice questions take option pictures",
1563- }));
1564- };
1565- choices
1566- .iter()
1567- .find(|choice| choice.get_id().as_str() == choice_id)
1568- .map(|choice| choice.get_id().clone())
1569- .ok_or(AppError::Validation(ValidationError::Invalid {
1570- field: "choice_id",
1571- reason: "must name one of the choices",
1572- }))
1573-}
1574-
1575-/// Add a question to an exam. Requires teacher+ and management rights over the
1576-/// exam's course. `subject_id` must name one of the course's subjects
1577-/// (`GET /courses/{id}/subjects`) — every question belongs to a subject.
1578-/// `choice` questions carry 2–10 `choices` plus `correct` naming one of them by id; `text`
1579-/// questions carry neither. Locked once attempts exist.
1580-#[utoipa::path(
1581- post,
1582- path = "/{id}/questions",
1583- tag = "exams",
1584- security(("session_cookie" = [])),
1585- params(("id" = String, Path, description = "Exam id")),
1586- request_body = CreateQuestion,
1587- responses(
1588- (status = 201, description = "Question created", body = QuestionResponse),
1589- (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse),
1590- (status = 401, description = "Not authenticated", body = ErrorResponse),
1591- (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
1592- (status = 404, description = "Exam not found", body = ErrorResponse),
1593- (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
1594- ),
1595-)]
1596-async fn create_question(
1597- State(st): State<AppState>,
1598- RequireTeacher(user): RequireTeacher,
1599- Path(id): Path<String>,
1600- Json(req): Json<CreateQuestion>,
1601-) -> Result<(StatusCode, Json<QuestionResponse>), AppError> {
1602- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
1603- .await?
1604- .ok_or(AppError::NotFound)?;
1605- let course = course_of(&exam, &st.db).await?;
1606- if !can_manage_course(&course, &user) {
1607- return Err(AppError::Forbidden(
1608- "only the course creator, an assigned teacher, or a manager/admin can author questions",
1609- ));
1610- }
1611- // Writer lease of [`EXAM_LOCK`]: the freeze gate, the subject check, and
1612- // the create are one unit — no first attempt can slip past the gate, and
1613- // no subject delete can invalidate a subject this just validated.
1614- let _guard = EXAM_LOCK.write().await;
1615- ensure_questions_editable(exam.get_id(), &st.db).await?;
1616-
1617- let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;
1618- let text = QuestionText::try_new(&req.text)?;
1619- let points = QuestionPoints::try_new(req.points)?;
1620- // No stored choices to match against on create, so every option is new and
1621- // every id is minted here.
1622- let spec = QuestionSpec::try_new(
1623- QuestionKind::try_new(&req.kind)?,
1624- ChoiceBody::into_inputs(req.choices),
1625- req.correct,
1626- &[],
1627- )?;
1628- let question = ExamQuestion::create(exam.get_id(), subject, text, points, spec, &st.db).await?;
1629- // A question is born imageless — uploads come after, against its id.
1630- Ok((
1631- StatusCode::CREATED,
1632- Json(QuestionResponse::new(&question, &[])),
1633- ))
1634-}
1635-
1636-/// The exam's question list, `correct` choice ids included — the answer key,
1637-/// paged via `?limit=&offset=` (omit `limit` for the whole list). Requires
1638-/// teacher+ and management rights over the exam's course. Students read
1639-/// questions through `GET /exams/{id}/attempt/questions`. Returns a
1640-/// `{items, total, limit, offset}` envelope.
1641-#[utoipa::path(
1642- get,
1643- path = "/{id}/questions",
1644- tag = "exams",
1645- security(("session_cookie" = [])),
1646- params(("id" = String, Path, description = "Exam id"), PageParams),
1647- responses(
1648- (status = 200, description = "A page of the exam's questions (all of them when unpaged)", body = Page<QuestionResponse>),
1649- (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
1650- (status = 401, description = "Not authenticated", body = ErrorResponse),
1651- (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
1652- (status = 404, description = "Exam not found", body = ErrorResponse),
1653- ),
1654-)]
1655-async fn list_questions(
1656- State(st): State<AppState>,
1657- RequireTeacher(user): RequireTeacher,
1658- Path(id): Path<String>,
1659- Query(page): Query<PageParams>,
1660-) -> Result<Json<Page<QuestionResponse>>, AppError> {
1661- let (limit, offset) = page.resolve()?;
1662- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
1663- .await?
1664- .ok_or(AppError::NotFound)?;
1665- let course = course_of(&exam, &st.db).await?;
1666- if !can_manage_course(&course, &user) {
1667- return Err(AppError::Forbidden(
1668- "only the course creator, an assigned teacher, or a manager/admin can read the question list",
1669- ));
1670- }
1671- Ok(Json(question_page(&exam, limit, offset, &st.db).await?))
1672-}
1673-
1674-/// The paged answer-key list (`correct` included) shared by the teacher
1675-/// `list_questions` read and the student `review_questions` read — the two
1676-/// differ only in the access wall they run first.
1677-async fn question_page(
1678- exam: &Exam,
1679- limit: Option<i64>,
1680- offset: i64,
1681- db: &Database,
1682-) -> Result<Page<QuestionResponse>, AppError> {
1683- let questions = ExamQuestion::list_for_exam(exam.get_id(), db).await?;
1684- let images = images_by_question(exam.get_id(), db).await?;
1685- let total = questions.len() as i64;
1686- let items = paginate(&questions, limit, offset)
1687- .iter()
1688- .map(|question| {
1689- QuestionResponse::new(
1690- question,
1691- images
1692- .get(question.get_id().key())
1693- .map_or(&[][..], Vec::as_slice),
1694- )
1695- })
1696- .collect();
1697- Ok(Page::new(items, total, limit, offset))
1698-}
1699-
1700-/// Edit a question. Requires teacher+ and management rights over the exam's
1701-/// course. Omitted fields keep their value; `kind`/`choices`/`correct` are
1702-/// re-validated as a unit, so a kind switch must bring the matching fields
1703-/// along. `subject_id` re-tags within the course's subjects. Locked once
1704-/// attempts exist.
1705-#[utoipa::path(
1706- patch,
1707- path = "/{id}/questions/{qid}",
1708- tag = "exams",
1709- security(("session_cookie" = [])),
1710- params(
1711- ("id" = String, Path, description = "Exam id"),
1712- ("qid" = String, Path, description = "Question id"),
1713- ),
1714- request_body = UpdateQuestion,
1715- responses(
1716- (status = 200, description = "Updated question", body = QuestionResponse),
1717- (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse),
1718- (status = 401, description = "Not authenticated", body = ErrorResponse),
1719- (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
1720- (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse),
1721- (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
1722- ),
1723-)]
1724-async fn update_question(
1725- State(st): State<AppState>,
1726- RequireTeacher(user): RequireTeacher,
1727- Path((id, qid)): Path<(String, String)>,
1728- Json(req): Json<UpdateQuestion>,
1729-) -> Result<Json<QuestionResponse>, AppError> {
1730- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
1731- .await?
1732- .ok_or(AppError::NotFound)?;
1733- let course = course_of(&exam, &st.db).await?;
1734- if !can_manage_course(&course, &user) {
1735- return Err(AppError::Forbidden(
1736- "only the course creator, an assigned teacher, or a manager/admin can edit questions",
1737- ));
1738- }
1739- // Writer lease of [`EXAM_LOCK`]: the freeze gate, the subject check, and
1740- // the update are one unit — see `create_question`.
1741- let _guard = EXAM_LOCK.write().await;
1742- ensure_questions_editable(exam.get_id(), &st.db).await?;
1743- let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
1744-
1745- let subject = match req.subject_id {
1746- Some(ref subject_id) => subject_in_course(subject_id, course.get_id(), &st.db).await?,
1747- None => question.get_subject().clone(),
1748- };
1749- let text = match req.text {
1750- Some(ref text) => QuestionText::try_new(text)?,
1751- None => question.get_text().clone(),
1752- };
1753- let points = match req.points {
1754- Some(points) => QuestionPoints::try_new(points)?,
1755- None => question.get_points(),
1756- };
1757- // Merge the kind-dependent fields (set / clear / keep per field), then
1758- // re-validate them as a unit — a PATCH can't leave a half-question behind.
1759- let kind = match req.kind {
1760- Some(ref kind) => QuestionKind::try_new(kind)?,
1761- None => question.get_kind().clone(),
1762- };
1763- // Omitting `choices` re-submits the stored options *with their ids*, so a
1764- // text-only edit keeps every identity (and every picture) untouched.
1765- let choices = match req.choices {
1766- Some(update) => ChoiceBody::into_inputs(update),
1767- None => ChoiceBody::from_stored(question.get_choices()),
1768- };
1769- let correct = match req.correct {
1770- Some(update) => update,
1771- None => question.get_correct().map(|id| id.as_str().to_string()),
1772- };
1773- let stored: Vec<Choice> = question.get_choices().unwrap_or_default().to_vec();
1774- let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?;
1775-
1776- let updated = question.update(subject, text, points, spec, &st.db).await?;
1777- // Only the options that are actually *gone* lose their pictures: keyed by
1778- // choice id, an option that survives the edit keeps its image no matter
1779- // where it moved in the list. (This used to wipe every option picture
1780- // whenever the request so much as carried a `choices` key.)
1781- let keep: Vec<ChoiceId> = updated
1782- .get_choices()
1783- .unwrap_or_default()
1784- .iter()
1785- .map(|choice| choice.get_id().clone())
1786- .collect();
1787- for image in QuestionImage::delete_choices_not_in(updated.get_id(), &keep, &st.db).await? {
1788- remove_blob(&st.files_path, image.get_file()).await;
1789- }
1790- let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?;
1791- Ok(Json(QuestionResponse::new(&updated, &images)))
1792-}
1793-
1794-/// Remove a question (and every answer to it). Requires teacher+ and
1795-/// management rights over the exam's course. Locked once attempts exist.
1796-#[utoipa::path(
1797- delete,
1798- path = "/{id}/questions/{qid}",
1799- tag = "exams",
1800- security(("session_cookie" = [])),
1801- params(
1802- ("id" = String, Path, description = "Exam id"),
1803- ("qid" = String, Path, description = "Question id"),
1804- ),
1805- responses(
1806- (status = 204, description = "Deleted"),
1807- (status = 401, description = "Not authenticated", body = ErrorResponse),
1808- (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
1809- (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse),
1810- (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
1811- ),
1812-)]
1813-async fn delete_question(
1814- State(st): State<AppState>,
1815- RequireTeacher(user): RequireTeacher,
1816- Path((id, qid)): Path<(String, String)>,
1817-) -> Result<StatusCode, AppError> {
1818- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
1819- .await?
1820- .ok_or(AppError::NotFound)?;
1821- let course = course_of(&exam, &st.db).await?;
1822- if !can_manage_course(&course, &user) {
1823- return Err(AppError::Forbidden(
1824- "only the course creator, an assigned teacher, or a manager/admin can delete questions",
1825- ));
1826- }
1827- // Writer lease of [`EXAM_LOCK`]: freeze gate + delete are one unit — a
1828- // first attempt slipping past the gate would sit an exam whose question
1829- // list forks from what `auto_score` later judges.
1830- let _guard = EXAM_LOCK.write().await;
1831- ensure_questions_editable(exam.get_id(), &st.db).await?;
1832- let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
1833- // Rows go first (the delete cascades them), blobs after — a crash in
1834- // between strands at worst an unreachable blob.
1835- let images = QuestionImage::list_for_question(question.get_id(), &st.db).await?;
1836- question.delete(&st.db).await?;
1837- for image in &images {
1838- remove_blob(&st.files_path, image.get_file()).await;
1839- }
1840- Ok(StatusCode::NO_CONTENT)
1841-}
1842-
1843-// ---- question bank bridge ---------------------------------------------------
1844-// Two copy funnels between an exam's questions and the school-wide bank
1845-// (`web/bank_questions`): instantiate a template into this exam, or save one of
1846-// this exam's questions back into the bank. Both COPY the row and every image
1847-// blob to fresh ids/files — the source side is never touched or shared.
1848-
1849-#[derive(Deserialize, ToSchema)]
1850-struct InstantiateFromBank {
1851- /// The subject to file the new question under — one of the exam's course's
1852- /// subjects (the same-course rule the bank row itself is exempt from).
1853- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
1854- subject_id: String,
1855-}
1856-
1857-/// Instantiate a bank template into this exam as a fresh question. Requires
1858-/// teacher+, management rights over the exam's course, and a template the
1859-/// caller may see (their own, or one published to the school) — anything else
1860-/// is a 404. `subject_id` must
1861-/// name one of the course's subjects — the template's own subject is origin
1862-/// metadata and does not carry over. The template (and its blobs) stay
1863-/// untouched; a full copy — text, points, spec, illustration, and option
1864-/// pictures — lands under a new question id. Locked once attempts exist.
1865-#[utoipa::path(
1866- post,
1867- path = "/{id}/questions/from-bank/{bid}",
1868- tag = "exams",
1869- security(("session_cookie" = [])),
1870- params(
1871- ("id" = String, Path, description = "Exam id"),
1872- ("bid" = String, Path, description = "Bank question id"),
1873- ),
1874- request_body = InstantiateFromBank,
1875- responses(
1876- (status = 201, description = "Question created from the template", body = QuestionResponse),
1877- (status = 400, description = "Unknown subject, or one from another course", body = ErrorResponse),
1878- (status = 401, description = "Not authenticated", body = ErrorResponse),
1879- (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
1880- (status = 404, description = "No such exam, or no bank template the caller may see", body = ErrorResponse),
1881- (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
1882- ),
1883-)]
1884-async fn question_from_bank(
1885- State(st): State<AppState>,
1886- RequireTeacher(user): RequireTeacher,
1887- Path((id, bid)): Path<(String, String)>,
1888- Json(req): Json<InstantiateFromBank>,
1889-) -> Result<(StatusCode, Json<QuestionResponse>), AppError> {
1890- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
1891- .await?
1892- .ok_or(AppError::NotFound)?;
1893- let course = course_of(&exam, &st.db).await?;
1894- if !can_manage_course(&course, &user) {
1895- return Err(AppError::Forbidden(
1896- "only the course creator, an assigned teacher, or a manager/admin can author questions",
1897- ));
1898- }
1899- // Writer lease of [`EXAM_LOCK`]: the freeze gate, the subject check, and the
1900- // create are one unit — same reasoning as `create_question`.
1901- let _guard = EXAM_LOCK.write().await;
1902- ensure_questions_editable(exam.get_id(), &st.db).await?;
1903- let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;
1904-
1905- let template = BankQuestion::read(&BankQuestionId::from_key(&bid), &st.db)
1906- .await?
1907- .ok_or(AppError::NotFound)?;
1908- // A template the caller may not see is a 404, exactly as it is on the bank's
1909- // own routes — instantiating is a read of `correct`, and a 403 here would
1910- // confirm that someone else's private template exists under that id.
1911- if !super::bank_questions::can_see(&template, &user) {
1912- return Err(AppError::NotFound);
1913- }
1914- let question = ExamQuestion::create_from_bank(
1915- exam.get_id(),
1916- subject,
1917- template.get_text().clone(),
1918- template.get_points(),
1919- template.spec(),
1920- template.get_id().clone(),
1921- &st.db,
1922- )
1923- .await?;
1924-
1925- // Copy each of the template's image blobs to a fresh file under the new
1926- // question + same slot (file before row, via `store_image`). A missing
1927- // source blob is server-side damage, surfaced as a 500 — not silently lost.
1928- // The copy is all-or-nothing: any mid-loop failure rolls back the fresh
1929- // question row (its cascade drops the copied image rows) and the blobs
1930- // written so far, leaving the source and destination untouched.
1931- let sources = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?;
1932- let mut copied: Vec<String> = Vec::new();
1933- for source in &sources {
1934- let step = async {
1935- let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file()))
1936- .await
1937- .map_err(|err| {
1938- AppError::Internal(format!(
1939- "missing blob for bank image {}: {err}",
1940- source.get_file()
1941- ))
1942- })?;
1943- store_image(
1944- &st,
1945- &exam,
1946- &question,
1947- source.get_slot(),
1948- source.get_content_type().clone(),
1949- &bytes,
1950- )
1951- .await
1952- };
1953- match step.await {
1954- Ok(image) => copied.push(image.get_file().to_string()),
1955- Err(err) => {
1956- for file in &copied {
1957- remove_blob(&st.files_path, file).await;
1958- }
1959- let _ = question.delete(&st.db).await;
1960- return Err(err);
1961- }
1962- }
1963- }
1964- let images = QuestionImage::list_for_question(question.get_id(), &st.db).await?;
1965- Ok((
1966- StatusCode::CREATED,
1967- Json(QuestionResponse::new(&question, &images)),
1968- ))
1969-}
1970-
1971-/// Re-copy a bank template's *current* content over the exam question that was
1972-/// instantiated from it — the escape hatch for the divergence a deep copy
1973-/// creates: fixing a typo in the template does not reach the copies, so this is
1974-/// how a copy is brought back in line, explicitly and per question. Requires
1975-/// teacher+, management rights over the exam's course, and a template the
1976-/// caller may still see.
1977-///
1978-/// Replaces text, points, kind, choices, `correct`, the illustration, and the
1979-/// option pictures with the template's; the question keeps its own id, its
1980-/// exam, its `subject` (exam-course-scoped — the template's subject is
1981-/// unrelated metadata) and its provenance links. Anything edited on the exam
1982-/// copy since it was inserted is overwritten.
1983-///
1984-/// **Choice ids come from the template**, exactly as
1985-/// [`question_from_bank`] mints them — the copy adopts the template's ids, so
1986-/// its option pictures key off the same slots the template's do, and a
1987-/// re-copy after a template edit re-lands the right picture on the right
1988-/// option. A recorded `selected` can never be stranded by that: the freeze
1989-/// below refuses the whole route once *any* attempt exists, and an
1990-/// `exam_answer` only exists under an attempt — so at refresh time no answer
1991-/// points at any choice id at all.
1992-///
1993-/// - No `from_bank` (never came from the bank, or its template was deleted and
1994-/// the cascade cleared the link) → `400`; there is nothing to refresh from.
1995-/// - Template gone or not visible to the caller → `404`, never a 403.
1996-/// - Any attempt started → `409`, the same `ensure_questions_editable` freeze
1997-/// every other question mutation answers to.
1998-#[utoipa::path(
1999- post,
2000- path = "/{id}/questions/{qid}/refresh-from-bank",
src/web/exams/attempts.rsadded+1004 -0
@@ -0,0 +1,1004 @@
1+use super::*;
2+
3+// ---- attempts -------------------------------------------------------------
4+// A sittable exam (sync, async, or open mode) is *sat*: starting an attempt
5+// is the live-attendance signal, finishing is the submission. The exam's
6+// `max_attempts` (0 = unlimited) says how many sittings each student gets;
7+// re-posting resumes a running attempt and mints the next sitting once the
8+// last one is over. Deadlines are judged only by the server clock — clients
9+// sync via `GET /time`.
10+
11+/// A student's view of their (latest) attempt. `now` is echoed so clients can
12+/// render countdowns without trusting the device clock.
13+#[derive(Serialize, ToSchema)]
14+pub(crate) struct AttemptResponse {
15+ id: String,
16+ exam: String,
17+ user: PersonRef,
18+ /// Which sitting this is — 1 for the first attempt, counting up.
19+ attempt: i64,
20+ /// How many sittings the caller has used, this one included.
21+ attempts_used: u64,
22+ /// The exam's attempt limit; `0` means unlimited.
23+ max_attempts: i64,
24+ /// When the attempt started, UTC unix-milliseconds.
25+ started_at: i64,
26+ /// Submission instant; `null` while running (or expired unsubmitted).
27+ finished_at: Option<i64>,
28+ /// When the student left the exam room mid-attempt; `null` while inside
29+ /// (or if they never used the room). With `allow_rejoin` off, a set
30+ /// `left_at` locks further answering until the teacher reopens the door.
31+ left_at: Option<i64>,
32+ /// `in_progress` | `submitted` | `expired`.
33+ #[schema(example = "in_progress")]
34+ status: String,
35+ /// When the attempt closes: the earlier of the window's `ends_at` and
36+ /// `started_at + duration_ms` (whichever exists). Recomputed live from
37+ /// the exam's current schedule; `null` for an open exam without a
38+ /// duration — such an attempt only ends by submission.
39+ deadline: Option<i64>,
40+ /// `deadline - now`, floored at 0; `null` unless in progress with a
41+ /// deadline.
42+ remaining_ms: Option<i64>,
43+ /// The caller's mark, once graded.
44+ mark: Option<i64>,
45+ /// How many questions the caller has answered so far.
46+ answered: u64,
47+ /// How many questions the exam has.
48+ question_count: u64,
49+ /// Server clock at response time, UTC unix-milliseconds.
50+ now: i64,
51+}
52+
53+impl AttemptResponse {
54+ #[expect(
55+ clippy::too_many_arguments,
56+ reason = "a flat view over attempt + exam + progress; a builder would obscure it"
57+ )]
58+ pub(crate) fn new(
59+ attempt: &ExamAttempt,
60+ exam: &Exam,
61+ mark: Option<Mark>,
62+ people: &HashMap<String, PersonRef>,
63+ answered: u64,
64+ question_count: u64,
65+ attempts_used: u64,
66+ now: Timestamp,
67+ ) -> Self {
68+ let status = attempt.status(exam, now);
69+ let deadline = attempt.deadline(exam);
70+ let remaining_ms = (status == AttemptStatus::InProgress)
71+ .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0)))
72+ .flatten();
73+ Self {
74+ id: attempt.get_id().key().to_string(),
75+ exam: attempt.get_exam().key().to_string(),
76+ user: PersonRef::resolve(people, attempt.get_user()),
77+ attempt: attempt.get_seq(),
78+ attempts_used,
79+ max_attempts: exam.get_max_attempts().as_i64(),
80+ started_at: attempt.get_started_at().as_millis(),
81+ finished_at: attempt.get_finished_at().map(|t| t.as_millis()),
82+ left_at: attempt.get_left_at().map(|t| t.as_millis()),
83+ status: status.as_str().to_string(),
84+ deadline: deadline.map(|t| t.as_millis()),
85+ remaining_ms,
86+ mark: mark.map(|m| m.as_i64()),
87+ answered,
88+ question_count,
89+ now: now.as_millis(),
90+ }
91+ }
92+}
93+
94+/// The (answered, question_count) pair behind an attempt view — how far one
95+/// student has come through the exam's question list.
96+pub(crate) async fn attempt_progress(
97+ exam: &ExamId,
98+ user: &UserId,
99+ seq: i64,
100+ db: &Database,
101+) -> Result<(u64, u64), AppError> {
102+ let answered = ExamAnswer::list_for_exam_user(exam, user, seq, db)
103+ .await?
104+ .len() as u64;
105+ let question_count = ExamQuestion::list_for_exam(exam, None, 0, db)
106+ .await?
107+ .0
108+ .len() as u64;
109+ Ok((answered, question_count))
110+}
111+
112+/// Rejects sitting an exam that can't be sat. A draft is a `404`, not a
113+/// `409` — sitting is a student act, drafts are invisible to students, and a
114+/// state-specific error would leak the existence this feature hides. A
115+/// modeless (offline-graded) exam is a `409`: visible, just nothing to sit.
116+/// Enrollment and window checks for the caller are the caller's own state —
117+/// also `Conflict`, not validation.
118+pub(crate) fn ensure_sittable(exam: &Exam) -> Result<(), AppError> {
119+ if exam.is_draft() {
120+ return Err(AppError::NotFound);
121+ }
122+ if exam.get_mode().is_none() {
123+ return Err(AppError::Conflict(
124+ "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)",
125+ ));
126+ }
127+ Ok(())
128+}
129+
130+/// How many sittings the caller has used at this exam.
131+pub(crate) async fn attempts_used(
132+ exam: &ExamId,
133+ user: &UserId,
134+ db: &Database,
135+) -> Result<u64, AppError> {
136+ Ok(ExamAttempt::list_for_user(exam, user, db).await?.len() as u64)
137+}
138+
139+/// Start, resume, or retake the caller's attempt. Requires the student role
140+/// (staff run exams, they don't sit them), enrollment in the exam's course, a
141+/// sittable exam (`sync`/`async`/`open` mode), and — when a window exists — the
142+/// window to be open. A still-running attempt is returned
143+/// as-is (`200` instead of `201`), so a reconnecting client gets its original
144+/// clock back — re-starting never resets the time. Once the latest attempt is
145+/// submitted or expired, re-posting starts the next sitting (`201`, blank
146+/// answer sheet) while the exam's `max_attempts` (0 = unlimited) allows it.
147+#[utoipa::path(
148+ post,
149+ path = "/{id}/attempt",
150+ tag = "exams",
151+ security(("session_cookie" = [])),
152+ params(("id" = String, Path, description = "Exam id")),
153+ responses(
154+ (status = 201, description = "Attempt started (first sitting or a retake)", body = AttemptResponse),
155+ (status = 200, description = "Running attempt resumed (unchanged)", body = AttemptResponse),
156+ (status = 401, description = "Not authenticated", body = ErrorResponse),
157+ (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse),
158+ (status = 404, description = "Exam not found (drafts are invisible here)", body = ErrorResponse),
159+ (status = 409, description = "Unscheduled (offline-graded) exam, outside the window, or no attempts remaining", body = ErrorResponse),
160+ ),
161+)]
162+pub(crate) async fn start_attempt(
163+ State(st): State<AppState>,
164+ CurrentUser(user): CurrentUser,
165+ Path(id): Path<String>,
166+) -> Result<(StatusCode, Json<AttemptResponse>), AppError> {
167+ // Writer lease of [`EXAM_LOCK`] from the exam read through the start: the
168+ // sittable/window gates must be judged against the same exam row the
169+ // attempt lands under (the mirror of `update_exam`'s re-derive — without
170+ // it, a mode change or re-draft at legally-zero attempts could slip
171+ // between this gate and the insert, leaving an attempt on an unsittable
172+ // exam). The lease
173+ // also keeps the max-attempts count and the retake's wipe-and-create
174+ // from interleaving with an in-flight answer save (a reader). Dropped
175+ // before the response reads — they only describe the row.
176+ let guard = EXAM_LOCK.write().await;
177+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
178+ .await?
179+ .ok_or(AppError::NotFound)?;
180+ ensure_sittable(&exam)?;
181+ ensure_student(&user)?;
182+ ensure_enrolled(&exam, user.get_id(), &st.db).await?;
183+ let now = Timestamp::now();
184+ if let Some(starts_at) = exam.get_starts_at()
185+ && now < starts_at
186+ {
187+ return Err(AppError::Conflict("the exam has not started yet"));
188+ }
189+ if let Some(ends_at) = exam.get_ends_at()
190+ && now >= ends_at
191+ {
192+ return Err(AppError::Conflict("the exam has already ended"));
193+ }
194+
195+ // A retake no longer wipes the prior sitting — each attempt's answers,
196+ // drawings, and marks stay put at their own seq (per-attempt history), so
197+ // there are no orphaned blobs to GC here. The exam-delete cascade still
198+ // cleans every sitting's blobs.
199+ let (attempt, created) = ExamAttempt::start(&exam, user.get_id(), &st.db).await?;
200+ drop(guard);
201+ let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
202+ .await?
203+ .map(|r| r.get_mark());
204+ let (answered, question_count) =
205+ attempt_progress(exam.get_id(), user.get_id(), attempt.get_seq(), &st.db).await?;
206+ let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?;
207+ let people = PersonRef::map_of(&[&user]);
208+ let status = if created {
209+ StatusCode::CREATED
210+ } else {
211+ StatusCode::OK
212+ };
213+ Ok((
214+ status,
215+ Json(AttemptResponse::new(
216+ &attempt,
217+ &exam,
218+ mark,
219+ &people,
220+ answered,
221+ question_count,
222+ used,
223+ Timestamp::now(),
224+ )),
225+ ))
226+}
227+
228+/// The caller's own (latest) attempt: status, deadline, remaining time, and
229+/// mark once graded — everything a student's live exam screen needs, judged
230+/// by the server clock. `404` until an attempt is started.
231+#[utoipa::path(
232+ get,
233+ path = "/{id}/attempt",
234+ tag = "exams",
235+ security(("session_cookie" = [])),
236+ params(("id" = String, Path, description = "Exam id")),
237+ responses(
238+ (status = 200, description = "The caller's latest attempt", body = AttemptResponse),
239+ (status = 401, description = "Not authenticated", body = ErrorResponse),
240+ (status = 404, description = "No such exam, or no attempt yet", body = ErrorResponse),
241+ ),
242+)]
243+pub(crate) async fn my_attempt(
244+ State(st): State<AppState>,
245+ CurrentUser(user): CurrentUser,
246+ Path(id): Path<String>,
247+) -> Result<Json<AttemptResponse>, AppError> {
248+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
249+ .await?
250+ .ok_or(AppError::NotFound)?;
251+ let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db)
252+ .await?
253+ .ok_or(AppError::NotFound)?;
254+ let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
255+ .await?
256+ .map(|r| r.get_mark());
257+ let (answered, question_count) =
258+ attempt_progress(exam.get_id(), user.get_id(), attempt.get_seq(), &st.db).await?;
259+ let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?;
260+ let people = PersonRef::map_of(&[&user]);
261+ Ok(Json(AttemptResponse::new(
262+ &attempt,
263+ &exam,
264+ mark,
265+ &people,
266+ answered,
267+ question_count,
268+ used,
269+ Timestamp::now(),
270+ )))
271+}
272+
273+/// Submit the caller's attempt. Allowed while the deadline hasn't passed;
274+/// after it, the attempt is already `expired` (a valid terminal state — the
275+/// student used their full time) and submitting is a `409`.
276+#[utoipa::path(
277+ post,
278+ path = "/{id}/attempt/finish",
279+ tag = "exams",
280+ security(("session_cookie" = [])),
281+ params(("id" = String, Path, description = "Exam id")),
282+ responses(
283+ (status = 200, description = "Attempt submitted", body = AttemptResponse),
284+ (status = 401, description = "Not authenticated", body = ErrorResponse),
285+ (status = 404, description = "No such exam, or no attempt to finish", body = ErrorResponse),
286+ (status = 409, description = "Already submitted, or the deadline passed", body = ErrorResponse),
287+ ),
288+)]
289+pub(crate) async fn finish_attempt(
290+ State(st): State<AppState>,
291+ CurrentUser(user): CurrentUser,
292+ Path(id): Path<String>,
293+) -> Result<Json<AttemptResponse>, AppError> {
294+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
295+ .await?
296+ .ok_or(AppError::NotFound)?;
297+ let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db)
298+ .await?
299+ .ok_or(AppError::NotFound)?;
300+ if attempt.get_finished_at().is_some() {
301+ return Err(AppError::Conflict("the attempt is already submitted"));
302+ }
303+ let now = Timestamp::now();
304+ if let Some(deadline) = attempt.deadline(&exam)
305+ && now >= deadline
306+ {
307+ return Err(AppError::Conflict("time is up — the attempt has expired"));
308+ }
309+
310+ // Deliberately no rejoin check: a student locked out of the room may
311+ // still submit what they saved — finishing answers nothing new.
312+ let finished = attempt.finish(&st.db).await?;
313+ let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
314+ .await?
315+ .map(|r| r.get_mark());
316+ let (answered, question_count) =
317+ attempt_progress(exam.get_id(), user.get_id(), finished.get_seq(), &st.db).await?;
318+ let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?;
319+ let people = PersonRef::map_of(&[&user]);
320+ Ok(Json(AttemptResponse::new(
321+ &finished,
322+ &exam,
323+ mark,
324+ &people,
325+ answered,
326+ question_count,
327+ used,
328+ Timestamp::now(),
329+ )))
330+}
331+
332+// ---- live monitor ---------------------------------------------------------
333+
334+/// One roster row of the live exam monitor. The attempt fields describe the
335+/// student's *latest* sitting.
336+#[derive(Serialize, ToSchema)]
337+pub(crate) struct LiveStudentResponse {
338+ user: PersonRef,
339+ /// `not_started` | `absent` | `in_progress` | `submitted` | `expired`.
340+ /// `absent` is `not_started` after the window closed: the student never
341+ /// sat and no longer can. Open exams have no window, so nobody is ever
342+ /// absent from one.
343+ #[schema(example = "in_progress")]
344+ status: String,
345+ /// Which sitting the shown attempt is (1, 2, …); `null` before the first.
346+ attempt: Option<i64>,
347+ /// How many sittings this student has used.
348+ attempts_used: u64,
349+ started_at: Option<i64>,
350+ finished_at: Option<i64>,
351+ /// When this student left the exam room mid-attempt; `null` while inside.
352+ left_at: Option<i64>,
353+ /// When this student's attempt closes (server-authoritative).
354+ deadline: Option<i64>,
355+ /// Time this student has left, floored at 0; `null` unless in progress.
356+ remaining_ms: Option<i64>,
357+ /// The student's mark, once graded.
358+ mark: Option<i64>,
359+ /// How many questions this student has answered so far.
360+ answered: u64,
361+ /// When this student last saved an answer, UTC unix-milliseconds; `null`
362+ /// before the first save.
363+ last_activity: Option<i64>,
364+}
365+
366+#[derive(Serialize, ToSchema)]
367+pub(crate) struct LiveCountsResponse {
368+ enrolled: u64,
369+ /// Enrolled with no attempt while the window is still open (or the exam
370+ /// has no window).
371+ not_started: u64,
372+ /// Enrolled with no attempt and the window closed — the no-shows.
373+ absent: u64,
374+ in_progress: u64,
375+ submitted: u64,
376+ expired: u64,
377+ graded: u64,
378+}
379+
380+/// A live snapshot of an exam: the enrolled roster with per-student attempt
381+/// state, remaining time, and marks, all judged by one server-clock read.
382+#[derive(Serialize, ToSchema)]
383+pub(crate) struct ExamLiveResponse {
384+ exam: ExamResponse,
385+ /// Server clock the snapshot was judged at, UTC unix-milliseconds.
386+ now: i64,
387+ /// How many questions the exam has.
388+ question_count: u64,
389+ counts: LiveCountsResponse,
390+ students: Vec<LiveStudentResponse>,
391+}
392+
393+/// Build the monitor snapshot: roster ⋈ attempts ⋈ marks at one instant.
394+/// Students unenrolled mid-exam drop off the roster view (their attempt and
395+/// mark rows survive, exactly like the marks report).
396+pub(crate) async fn live_snapshot(
397+ exam: &Exam,
398+ db: &Database,
399+) -> Result<ExamLiveResponse, AppError> {
400+ let now = Timestamp::now();
401+ let (roster, _) = Enrollment::list_for_course(exam.get_course(), None, 0, db).await?;
402+ // Per student: their latest sitting (the one the monitor shows) plus how
403+ // many they've used.
404+ let mut attempts: HashMap<String, ExamAttempt> = HashMap::new();
405+ let mut used: HashMap<String, u64> = HashMap::new();
406+ for attempt in ExamAttempt::list_for_exam(exam.get_id(), db).await? {
407+ let key = attempt.get_user().key().to_string();
408+ *used.entry(key.clone()).or_insert(0) += 1;
409+ match attempts.entry(key) {
410+ std::collections::hash_map::Entry::Vacant(slot) => {
411+ slot.insert(attempt);
412+ }
413+ std::collections::hash_map::Entry::Occupied(mut slot) => {
414+ if attempt.get_seq() > slot.get().get_seq() {
415+ slot.insert(attempt);
416+ }
417+ }
418+ }
419+ }
420+ let marks: HashMap<String, i64> = ExamResult::list_for_exam(exam.get_id(), db)
421+ .await?
422+ .iter()
423+ .map(|result| {
424+ (
425+ result.get_user().key().to_string(),
426+ result.get_mark().as_i64(),
427+ )
428+ })
429+ .collect();
430+ let question_count = ExamQuestion::list_for_exam(exam.get_id(), None, 0, db)
431+ .await?
432+ .0
433+ .len() as u64;
434+ // Per-student progress: answer count and the latest save instant. The
435+ // per-exam read now returns every sitting's rows across all students, so
436+ // each answer is scoped to that student's *current* sitting — matching its
437+ // seq to their latest attempt — or a re-sitting student's count would
438+ // double up their prior attempts.
439+ let mut progress: HashMap<String, (u64, i64)> = HashMap::new();
440+ for answer in ExamAnswer::list_for_exam(exam.get_id(), db).await? {
441+ let key = answer.get_user().key().to_string();
442+ if attempts.get(&key).map(ExamAttempt::get_seq) != Some(answer.get_seq()) {
443+ continue;
444+ }
445+ let entry = progress.entry(key).or_insert((0, i64::MIN));
446+ entry.0 += 1;
447+ entry.1 = entry.1.max(answer.get_updated_at().as_millis());
448+ }
449+ let people = person_map(roster.iter().map(|e| e.get_user().clone()), db).await?;
450+
451+ // Once the window closes the door is shut for good (starting answers
452+ // 409), so "hasn't started" hardens into "was absent". Open exams have
453+ // no window and never make that call.
454+ let window_over = exam.get_ends_at().is_some_and(|ends| now >= ends);
455+ let mut students: Vec<LiveStudentResponse> = roster
456+ .iter()
457+ .map(|enrollment| {
458+ let key = enrollment.get_user().key();
459+ let attempt = attempts.get(key);
460+ let status = attempt.map(|a| a.status(exam, now));
461+ let deadline = attempt.and_then(|a| a.deadline(exam));
462+ LiveStudentResponse {
463+ user: PersonRef::resolve(&people, enrollment.get_user()),
464+ status: match status {
465+ Some(status) => status.as_str(),
466+ None if window_over => "absent",
467+ None => "not_started",
468+ }
469+ .to_string(),
470+ attempt: attempt.map(ExamAttempt::get_seq),
471+ attempts_used: used.get(key).copied().unwrap_or(0),
472+ started_at: attempt.map(|a| a.get_started_at().as_millis()),
473+ finished_at: attempt
474+ .and_then(|a| a.get_finished_at())
475+ .map(|t| t.as_millis()),
476+ left_at: attempt.and_then(|a| a.get_left_at()).map(|t| t.as_millis()),
477+ deadline: deadline.map(|t| t.as_millis()),
478+ remaining_ms: (status == Some(AttemptStatus::InProgress))
479+ .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0)))
480+ .flatten(),
481+ mark: marks.get(key).copied(),
482+ answered: progress.get(key).map_or(0, |p| p.0),
483+ last_activity: progress.get(key).map(|p| p.1),
484+ }
485+ })
486+ .collect();
487+ students.sort_by(|a, b| a.user.username.cmp(&b.user.username));
488+
489+ let count = |status: &str| students.iter().filter(|s| s.status == status).count() as u64;
490+ let counts = LiveCountsResponse {
491+ enrolled: students.len() as u64,
492+ not_started: count("not_started"),
493+ absent: count("absent"),
494+ in_progress: count("in_progress"),
495+ submitted: count("submitted"),
496+ expired: count("expired"),
497+ graded: students.iter().filter(|s| s.mark.is_some()).count() as u64,
498+ };
499+ Ok(ExamLiveResponse {
500+ exam: ExamResponse::new(exam),
501+ now: now.as_millis(),
502+ question_count,
503+ counts,
504+ students,
505+ })
506+}
507+
508+/// A one-shot live snapshot of the exam: who's in, who's still writing (and
509+/// on which sitting), who walked out of the room (`left_at`), who never
510+/// showed at all (`absent`, once the window is over), time each student has
511+/// left, and marks as they land. Requires teacher+ and management rights
512+/// over the exam's course. Poll it to keep a monitor up to date.
513+#[utoipa::path(
514+ get,
515+ path = "/{id}/live",
516+ tag = "exams",
517+ security(("session_cookie" = [])),
518+ params(("id" = String, Path, description = "Exam id")),
519+ responses(
520+ (status = 200, description = "Live snapshot", body = ExamLiveResponse),
521+ (status = 401, description = "Not authenticated", body = ErrorResponse),
522+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
523+ (status = 404, description = "Exam not found", body = ErrorResponse),
524+ ),
525+)]
526+pub(crate) async fn exam_live(
527+ State(st): State<AppState>,
528+ RequireTeacher(user): RequireTeacher,
529+ Path(id): Path<String>,
530+) -> Result<Json<ExamLiveResponse>, AppError> {
531+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
532+ .await?
533+ .ok_or(AppError::NotFound)?;
534+ let course = course_of(&exam, &st.db).await?;
535+ if !can_manage_course(&course, &user) {
536+ return Err(AppError::Forbidden(
537+ "only the course creator, an assigned teacher, or a manager/admin can monitor this exam",
538+ ));
539+ }
540+ Ok(Json(live_snapshot(&exam, &st.db).await?))
541+}
542+
543+// ---- answers ----------------------------------------------------------------
544+// Students answer inside their attempt; every save is an upsert stamped with
545+// the server clock. The WebSocket room (`/exams/{id}/attempt/ws`) drives the
546+// same paths below.
547+
548+/// A student's own saved answer, embedded in their question view.
549+#[derive(Serialize, ToSchema)]
550+pub(crate) struct AnswerStateResponse {
551+ /// The picked option's id (`choice` questions).
552+ selected: Option<String>,
553+ /// The typed answer (`text` questions).
554+ text: Option<String>,
555+ /// When this answer was last saved, UTC unix-milliseconds.
556+ updated_at: i64,
557+ /// The student's own drawn answer, if any — bytes at
558+ /// `GET /exams/{id}/attempt/answers/{qid}/image`.
559+ answer_image: Option<ImageMetaResponse>,
560+}
561+
562+impl AnswerStateResponse {
563+ pub(crate) fn new(answer: &ExamAnswer, answer_image: Option<ImageMetaResponse>) -> Self {
564+ Self {
565+ selected: answer.get_selected().map(|id| id.as_str().to_string()),
566+ text: answer.get_text().map(|t| t.as_str().to_string()),
567+ updated_at: answer.get_updated_at().as_millis(),
568+ answer_image,
569+ }
570+ }
571+}
572+
573+/// A question as the sitting student sees it: no `correct` choice id, their own
574+/// saved answer embedded.
575+#[derive(Serialize, ToSchema)]
576+pub(crate) struct AttemptQuestionResponse {
577+ id: String,
578+ /// The subject this question belongs to (`GET /subjects/{id}`).
579+ subject: String,
580+ text: String,
581+ /// `choice` or `text`.
582+ #[schema(example = "choice")]
583+ kind: String,
584+ points: i64,
585+ /// The options with their ids — and deliberately *not* `correct`: this DTO
586+ /// leaks no answer key because it has no field to carry one, and
587+ /// `ChoiceResponse` carries none either.
588+ choices: Option<Vec<ChoiceResponse>>,
589+ /// The question's illustration, if any — bytes at
590+ /// `GET /exams/{id}/questions/{qid}/image`.
591+ image: Option<ImageMetaResponse>,
592+ /// Per-option pictures aligned with `choices`, if any — bytes at
593+ /// `GET /exams/{id}/questions/{qid}/choices/{choice_id}/image`.
594+ choice_images: Option<Vec<Option<ImageMetaResponse>>>,
595+ /// The caller's saved answer; `null` while unanswered.
596+ answer: Option<AnswerStateResponse>,
597+}
598+
599+#[derive(Deserialize, ToSchema)]
600+pub(crate) struct SaveAnswer {
601+ /// The question being answered.
602+ question_id: String,
603+ /// The picked option's `id` — required for `choice` questions.
604+ selected: Option<String>,
605+ /// The typed answer — required for `text` questions (empty clears the draft).
606+ #[schema(max_length = 10000)]
607+ text: Option<String>,
608+}
609+
610+#[derive(Serialize, ToSchema)]
611+pub(crate) struct AnswerSavedResponse {
612+ question: String,
613+ /// The picked option's id.
614+ selected: Option<String>,
615+ text: Option<String>,
616+ /// Save instant by the server clock, UTC unix-milliseconds.
617+ updated_at: i64,
618+}
619+
620+/// The caller's latest attempt provided it is still writable, or the error
621+/// that says why not: no attempt yet (404 — start it first), already
622+/// submitted (409), deadline passed (409). One gate shared by REST saves and
623+/// the WebSocket room.
624+pub(crate) async fn writable_attempt(
625+ exam: &Exam,
626+ user: &UserId,
627+ db: &Database,
628+) -> Result<ExamAttempt, AppError> {
629+ let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user, db)
630+ .await?
631+ .ok_or(AppError::NotFound)?;
632+ match attempt.status(exam, Timestamp::now()) {
633+ AttemptStatus::Submitted => Err(AppError::Conflict("the attempt is already submitted")),
634+ AttemptStatus::Expired => Err(AppError::Conflict("time is up — the attempt has expired")),
635+ AttemptStatus::InProgress => Ok(attempt),
636+ }
637+}
638+
639+/// A 409 when the student has walked out of the exam room and the exam's
640+/// rejoin door is closed: no more answering (from anywhere) until the teacher
641+/// flips `allow_rejoin` back on. Finishing is deliberately exempt — see
642+/// `finish_attempt`.
643+pub(crate) fn check_rejoin(exam: &Exam, attempt: &ExamAttempt) -> Result<(), AppError> {
644+ if attempt.get_left_at().is_some() && !exam.get_allow_rejoin() {
645+ return Err(AppError::Conflict(
646+ "you left the exam and rejoin is closed — ask your teacher to reopen it",
647+ ));
648+ }
649+ Ok(())
650+}
651+
652+/// Save one answer inside the caller's in-progress attempt — the whole write
653+/// path (attempt gate, rejoin gate, question lookup, kind check, upsert). The
654+/// REST handler saves into the latest sitting via this; the WebSocket room
655+/// resolves its own sitting first and shares [`save_answer_in`], so the two
656+/// can never drift.
657+pub(crate) async fn save_answer_checked(
658+ exam: &Exam,
659+ user: &UserId,
660+ question_id: &str,
661+ selected: Option<String>,
662+ text: Option<String>,
663+ db: &Database,
664+) -> Result<ExamAnswer, AppError> {
665+ // Reader lease of [`EXAM_LOCK`]: the writable gate and the upsert are
666+ // one unit, or a retake's wipe-and-create (a writer) slips in between
667+ // and this stale save lands on the fresh blank sheet.
668+ let _guard = EXAM_LOCK.read().await;
669+ let attempt = writable_attempt(exam, user, db).await?;
670+ save_answer_in(exam, &attempt, question_id, selected, text, db).await
671+}
672+
673+/// The tail of the answer write path, given the sitting to write in: the
674+/// student wall and the enrollment wall (a promotion out of `student` or an
675+/// unenrollment closes the sheet, mid-exam included), the rejoin gate, the
676+/// question lookup, and the upsert.
677+pub(crate) async fn save_answer_in(
678+ exam: &Exam,
679+ attempt: &ExamAttempt,
680+ question_id: &str,
681+ selected: Option<String>,
682+ text: Option<String>,
683+ db: &Database,
684+) -> Result<ExamAnswer, AppError> {
685+ ensure_student_now(attempt.get_user(), db).await?;
686+ ensure_enrolled(exam, attempt.get_user(), db).await?;
687+ check_rejoin(exam, attempt)?;
688+ let question = question_of_exam(exam.get_id(), question_id, db).await?;
689+ ExamAnswer::save(
690+ &question,
691+ attempt.get_user(),
692+ attempt.get_seq(),
693+ selected,
694+ text,
695+ db,
696+ )
697+ .await
698+}
699+
700+/// A 403 unless `user` is a student. Sitting an exam is a student action —
701+/// teachers and above run exams, they never take them — so the sit paths
702+/// (start, room, save) enforce it on the *current* role. Checking the live
703+/// role, not just enrollment, closes the gap a mid-exam promotion would open
704+/// and neutralizes any stale non-student enrollment. Reading one's own attempt
705+/// and finishing stay ungated: a non-student has no attempt to read, and
706+/// finishing only submits work already saved.
707+pub(crate) fn ensure_student(user: &User) -> Result<(), AppError> {
708+ if user.get_role() != Role::Student {
709+ return Err(AppError::Forbidden("only students can sit exams"));
710+ }
711+ Ok(())
712+}
713+
714+/// The answer path's live edition of [`ensure_student`]: re-read the row and
715+/// judge the *current* role, exactly like the enrollment wall beside it. Both
716+/// save paths run through here (REST per request, the exam room per message),
717+/// so a promotion out of `student` mid-exam closes the sheet on the very next
718+/// save — the room's door check is not the last word for a socket that
719+/// outlives the role.
720+pub(crate) async fn ensure_student_now(user: &UserId, db: &Database) -> Result<(), AppError> {
721+ let user = User::read(user, db).await?.ok_or(AppError::Unauthorized)?;
722+ ensure_student(&user)
723+}
724+
725+/// A 403 unless `user` is enrolled in the exam's course — the same wall the
726+/// exam room checks at its door, re-applied to the sitting's content paths so
727+/// an unenrollment mid-exam cuts them too. Finishing stays exempt: like the
728+/// rejoin lock, submitting what's already saved writes nothing new.
729+pub(crate) async fn ensure_enrolled(
730+ exam: &Exam,
731+ user: &UserId,
732+ db: &Database,
733+) -> Result<(), AppError> {
734+ if Enrollment::read_for_user(exam.get_course(), user, db)
735+ .await?
736+ .is_none()
737+ {
738+ return Err(AppError::Forbidden(
739+ "you are not enrolled in this exam's course",
740+ ));
741+ }
742+ Ok(())
743+}
744+
745+/// The exam's questions as the sitting student sees them: `correct` stripped,
746+/// their own saved answers embedded — the latest sitting's, since a retake
747+/// starts from a blank sheet. Requires enrollment in the exam's course (the
748+/// questions are course content — leaving the course closes them) and an
749+/// attempt — start one with `POST /exams/{id}/attempt` first (404 until
750+/// then). Readable in every attempt state, so a submitted student can still
751+/// review what they wrote.
752+#[utoipa::path(
753+ get,
754+ path = "/{id}/attempt/questions",
755+ tag = "exams",
756+ security(("session_cookie" = [])),
757+ params(("id" = String, Path, description = "Exam id")),
758+ responses(
759+ (status = 200, description = "Questions with the caller's answers embedded", body = [AttemptQuestionResponse]),
760+ (status = 401, description = "Not authenticated", body = ErrorResponse),
761+ (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse),
762+ (status = 404, description = "No such exam, or no attempt yet — start the attempt first", body = ErrorResponse),
763+ ),
764+)]
765+pub(crate) async fn attempt_questions(
766+ State(st): State<AppState>,
767+ CurrentUser(user): CurrentUser,
768+ Path(id): Path<String>,
769+) -> Result<Json<Vec<AttemptQuestionResponse>>, AppError> {
770+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
771+ .await?
772+ .ok_or(AppError::NotFound)?;
773+ ensure_enrolled(&exam, user.get_id(), &st.db).await?;
774+ // The question list is for sitting students; without an attempt there is
775+ // nothing to sit behind — and no early peek at the questions. The embedded
776+ // answers are the *current* sitting's only, so the seq scopes the reads.
777+ let seq = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db)
778+ .await?
779+ .ok_or(AppError::NotFound)?
780+ .get_seq();
781+
782+ let (questions, _) = ExamQuestion::list_for_exam(exam.get_id(), None, 0, &st.db).await?;
783+ let images = images_by_question(exam.get_id(), &st.db).await?;
784+ let answers: HashMap<String, ExamAnswer> =
785+ ExamAnswer::list_for_exam_user(exam.get_id(), user.get_id(), seq, &st.db)
786+ .await?
787+ .into_iter()
788+ .map(|answer| (answer.get_question().key().to_string(), answer))
789+ .collect();
790+ let answer_images: HashMap<String, AnswerImage> =
791+ AnswerImage::list_for_exam_user(exam.get_id(), user.get_id(), seq, &st.db)
792+ .await?
793+ .into_iter()
794+ .map(|image| (image.get_question().key().to_string(), image))
795+ .collect();
796+ Ok(Json(
797+ questions
798+ .iter()
799+ .map(|question| {
800+ let question_images = images
801+ .get(question.get_id().key())
802+ .map_or(&[][..], Vec::as_slice);
803+ AttemptQuestionResponse {
804+ id: question.get_id().key().to_string(),
805+ subject: question.get_subject().key().to_string(),
806+ text: question.get_text().as_str().to_string(),
807+ kind: question.get_kind().as_str().to_string(),
808+ points: question.get_points().as_i64(),
809+ choices: ChoiceResponse::list(question.get_choices()),
810+ image: image_meta(question_images, None),
811+ choice_images: choice_image_metas(question, question_images),
812+ answer: answers.get(question.get_id().key()).map(|answer| {
813+ AnswerStateResponse::new(
814+ answer,
815+ answer_images
816+ .get(question.get_id().key())
817+ .map(ImageMetaResponse::from_answer),
818+ )
819+ }),
820+ }
821+ })
822+ .collect(),
823+ ))
824+}
825+
826+/// Save (or overwrite) one answer in the caller's in-progress attempt.
827+/// `choice` questions take `selected`; `text` questions take `text`. Requires
828+/// the student role and enrollment in the exam's course — an unenrollment (or a
829+/// promotion out of `student`) mid-exam closes the sheet. Rejected once the
830+/// attempt is submitted or its deadline has passed —
831+/// the server clock, not the client's, is the judge — and rejected while the
832+/// student has left the exam room with the exam's rejoin door closed.
833+#[utoipa::path(
834+ post,
835+ path = "/{id}/attempt/answers",
836+ tag = "exams",
837+ security(("session_cookie" = [])),
838+ params(("id" = String, Path, description = "Exam id")),
839+ request_body = SaveAnswer,
840+ responses(
841+ (status = 200, description = "Answer saved", body = AnswerSavedResponse),
842+ (status = 400, description = "Payload doesn't match the question's kind", body = ErrorResponse),
843+ (status = 401, description = "Not authenticated", body = ErrorResponse),
844+ (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse),
845+ (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse),
846+ (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse),
847+ ),
848+)]
849+pub(crate) async fn save_answer(
850+ State(st): State<AppState>,
851+ CurrentUser(user): CurrentUser,
852+ Path(id): Path<String>,
853+ Json(req): Json<SaveAnswer>,
854+) -> Result<Json<AnswerSavedResponse>, AppError> {
855+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
856+ .await?
857+ .ok_or(AppError::NotFound)?;
858+ ensure_student(&user)?;
859+ let answer = save_answer_checked(
860+ &exam,
861+ user.get_id(),
862+ &req.question_id,
863+ req.selected,
864+ req.text,
865+ &st.db,
866+ )
867+ .await?;
868+ Ok(Json(AnswerSavedResponse {
869+ question: answer.get_question().key().to_string(),
870+ selected: answer.get_selected().map(|id| id.as_str().to_string()),
871+ text: answer.get_text().map(|t| t.as_str().to_string()),
872+ updated_at: answer.get_updated_at().as_millis(),
873+ }))
874+}
875+
876+/// One student's answer sheet with correctness flags — always the *latest*
877+/// sitting's answers (a retake starts from a blank sheet). Every row carries
878+/// the saved answer plus `is_correct` (`null` for text questions — those are
879+/// the grader's call), and the machine's `auto_score` over the choice
880+/// questions is attached as a *suggestion*: the final mark stays human, via
881+/// `POST /exams/{id}/results`. Requires teacher+ and management rights over
882+/// the exam's course.
883+#[utoipa::path(
884+ get,
885+ path = "/{id}/attempts/{user}/answers",
886+ tag = "exams",
887+ security(("session_cookie" = [])),
888+ params(
889+ ("id" = String, Path, description = "Exam id"),
890+ ("user" = String, Path, description = "User id"),
891+ ),
892+ responses(
893+ (status = 200, description = "The student's answers, judged", body = AttemptAnswersResponse),
894+ (status = 401, description = "Not authenticated", body = ErrorResponse),
895+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
896+ (status = 404, description = "No such exam, or the student has no attempt", body = ErrorResponse),
897+ ),
898+)]
899+pub(crate) async fn attempt_answers(
900+ State(st): State<AppState>,
901+ RequireTeacher(user): RequireTeacher,
902+ Path((id, target)): Path<(String, String)>,
903+) -> Result<Json<AttemptAnswersResponse>, AppError> {
904+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
905+ .await?
906+ .ok_or(AppError::NotFound)?;
907+ let course = course_of(&exam, &st.db).await?;
908+ if !can_manage_course(&course, &user) {
909+ return Err(AppError::Forbidden(
910+ "only the course creator, an assigned teacher, or a manager/admin can read answer sheets",
911+ ));
912+ }
913+ let target = UserId::from_key(&target);
914+ // No attempt means no answer sheet — a 404, not an empty one. This grading
915+ // view shows the *latest* sitting; prior sittings live under the
916+ // per-attempt history endpoints.
917+ let seq = ExamAttempt::read_latest_for_user(exam.get_id(), &target, &st.db)
918+ .await?
919+ .ok_or(AppError::NotFound)?
920+ .get_seq();
921+ Ok(Json(answer_sheet(&exam, &target, seq, &st.db).await?))
922+}
923+
924+/// One sitting's judged answer sheet: the `seq`th attempt's answers, drawing
925+/// refs, correctness flags, and auto-score suggestion. Shared by the latest-
926+/// sitting grading view and the per-attempt history endpoint.
927+pub(crate) async fn answer_sheet(
928+ exam: &Exam,
929+ target: &UserId,
930+ seq: i64,
931+ db: &Database,
932+) -> Result<AttemptAnswersResponse, AppError> {
933+ let (questions, _) = ExamQuestion::list_for_exam(exam.get_id(), None, 0, db).await?;
934+ let answers = ExamAnswer::list_for_exam_user(exam.get_id(), target, seq, db).await?;
935+ let answer_images: HashMap<String, AnswerImage> =
936+ AnswerImage::list_for_exam_user(exam.get_id(), target, seq, db)
937+ .await?
938+ .into_iter()
939+ .map(|image| (image.get_question().key().to_string(), image))
940+ .collect();
941+ let by_question: HashMap<&str, &ExamQuestion> = questions
942+ .iter()
943+ .map(|question| (question.get_id().key(), question))
944+ .collect();
945+ let (earned, possible) = auto_score(&questions, &answers);
946+ let people = person_map([target.clone()], db).await?;
947+ Ok(AttemptAnswersResponse {
948+ exam: exam.get_id().key().to_string(),
949+ user: PersonRef::resolve(&people, target),
950+ answers: answers
951+ .iter()
952+ .map(|answer| StudentAnswerResponse {
953+ question: answer.get_question().key().to_string(),
954+ selected: answer.get_selected().map(|id| id.as_str().to_string()),
955+ text: answer.get_text().map(|t| t.as_str().to_string()),
956+ updated_at: answer.get_updated_at().as_millis(),
957+ is_correct: by_question
958+ .get(answer.get_question().key())
959+ .and_then(|question| answer.is_correct(question)),
960+ answer_image: answer_images
961+ .get(answer.get_question().key())
962+ .map(ImageMetaResponse::from_answer),
963+ })
964+ .collect(),
965+ auto_score: AutoScoreResponse { earned, possible },
966+ })
967+}
968+
969+/// One row of a student's answer sheet, as the grader sees it.
970+#[derive(Serialize, ToSchema)]
971+pub(crate) struct StudentAnswerResponse {
972+ question: String,
973+ /// The picked option's id.
974+ selected: Option<String>,
975+ text: Option<String>,
976+ /// When the answer was last saved, UTC unix-milliseconds.
977+ updated_at: i64,
978+ /// Whether `selected` hits the question's `correct`; `null` for text
979+ /// questions (the grader judges those).
980+ is_correct: Option<bool>,
981+ /// The student's drawn answer, if any — bytes at
982+ /// `GET /exams/{id}/attempts/{user}/answers/{qid}/image`.
983+ answer_image: Option<ImageMetaResponse>,
984+}
985+
986+/// The machine's scoring suggestion over the choice questions.
987+#[derive(Serialize, ToSchema)]
988+pub(crate) struct AutoScoreResponse {
989+ /// Points earned where `selected == correct`.
990+ earned: i64,
991+ /// Total points across the exam's choice questions.
992+ possible: i64,
993+}
994+
995+/// A student's full answer sheet for grading.
996+#[derive(Serialize, ToSchema)]
997+pub(crate) struct AttemptAnswersResponse {
998+ exam: String,
999+ /// The student whose sheet this is.
1000+ user: PersonRef,
1001+ answers: Vec<StudentAnswerResponse>,
1002+ /// The suggested score over choice questions — never the final mark.
1003+ auto_score: AutoScoreResponse,
1004+}
src/web/exams/images.rsadded+651 -0
@@ -0,0 +1,651 @@
1+use super::*;
2+
3+/// A stored question image's metadata; the bytes come from the image
4+/// endpoints (`GET .../image`, `GET .../choices/{choice_id}/image`).
5+#[derive(Serialize, ToSchema)]
6+pub(crate) struct ImageMetaResponse {
7+ /// MIME type as declared on upload (always one of the raster allowlist).
8+ #[schema(example = "image/png")]
9+ content_type: String,
10+ /// Image size in bytes.
11+ #[schema(example = 24_576)]
12+ size: i64,
13+}
14+
15+impl ImageMetaResponse {
16+ pub(crate) fn new(image: &QuestionImage) -> Self {
17+ Self {
18+ content_type: image.get_content_type().as_str().to_string(),
19+ size: image.get_size(),
20+ }
21+ }
22+
23+ pub(crate) fn from_answer(image: &AnswerImage) -> Self {
24+ Self {
25+ content_type: image.get_content_type().as_str().to_string(),
26+ size: image.get_size(),
27+ }
28+ }
29+}
30+
31+/// The question's slot out of its image rows.
32+pub(crate) fn image_meta(
33+ images: &[QuestionImage],
34+ slot: Option<&ChoiceId>,
35+) -> Option<ImageMetaResponse> {
36+ images
37+ .iter()
38+ .find(|image| image.get_slot() == slot)
39+ .map(ImageMetaResponse::new)
40+}
41+
42+/// The per-choice metas, aligned position-for-position with `choices` (`None`
43+/// entries = that option has no picture); `None` whole for text questions.
44+/// A response-only projection: the pictures are *stored* against choice ids, so
45+/// this alignment is rebuilt from the current list on every read and can never
46+/// go stale.
47+pub(crate) fn choice_image_metas(
48+ question: &ExamQuestion,
49+ images: &[QuestionImage],
50+) -> Option<Vec<Option<ImageMetaResponse>>> {
51+ question.get_choices().map(|choices| {
52+ choices
53+ .iter()
54+ .map(|choice| image_meta(images, Some(choice.get_id())))
55+ .collect()
56+ })
57+}
58+
59+/// `exam`'s image rows bucketed by question key — one query feeding a whole
60+/// question list.
61+pub(crate) async fn images_by_question(
62+ exam: &ExamId,
63+ db: &Database,
64+) -> Result<HashMap<String, Vec<QuestionImage>>, AppError> {
65+ let mut buckets: HashMap<String, Vec<QuestionImage>> = HashMap::new();
66+ for image in QuestionImage::list_for_exam(exam, db).await? {
67+ buckets
68+ .entry(image.get_question().key().to_string())
69+ .or_default()
70+ .push(image);
71+ }
72+ Ok(buckets)
73+}
74+
75+// ---- question images ----------------------------------------------------------
76+// A question may carry one illustration (any kind — the map above the prompt)
77+// and, on choice questions, one picture per option (pick the right city off
78+// the map). Uploads are teacher authoring and freeze with the rest of the
79+// question once attempts exist; metadata rides on the question DTOs, bytes
80+// flow through the GET endpoints below, whose access follows the question's
81+// own visibility (author side and sitting side alike).
82+
83+/// The exam, provided the caller may author its questions — the shared front
84+/// half of every image write.
85+pub(crate) async fn image_managed_exam(
86+ st: &AppState,
87+ user: &User,
88+ id: &str,
89+) -> Result<Exam, AppError> {
90+ let exam = Exam::read(&ExamId::from_key(id), &st.db)
91+ .await?
92+ .ok_or(AppError::NotFound)?;
93+ let course = course_of(&exam, &st.db).await?;
94+ if !can_manage_course(&course, user) {
95+ return Err(AppError::Forbidden(
96+ "only the course creator, an assigned teacher, or a manager/admin can manage question images",
97+ ));
98+ }
99+ Ok(exam)
100+}
101+
102+/// A 403/404 unless the caller may see the exam's question content: course
103+/// managers always, students through the same wall as
104+/// `GET /exams/{id}/attempt/questions` — enrollment plus a started attempt,
105+/// so there is no early peek at the pictures either.
106+pub(crate) async fn ensure_question_content_visible(
107+ st: &AppState,
108+ exam: &Exam,
109+ user: &User,
110+) -> Result<(), AppError> {
111+ let course = course_of(exam, &st.db).await?;
112+ if can_manage_course(&course, user) {
113+ return Ok(());
114+ }
115+ ensure_enrolled(exam, user.get_id(), &st.db).await?;
116+ ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db)
117+ .await?
118+ .ok_or(AppError::NotFound)?;
119+ Ok(())
120+}
121+
122+/// The image write tail, shared by both upload endpoints: the slot's current
123+/// row names the blob to retire, the UPSERT replaces it (the deterministic
124+/// per-slot id makes it a replace), and [`store_blob`] owns the disk ordering.
125+pub(crate) async fn store_image(
126+ st: &AppState,
127+ exam: &Exam,
128+ question: &ExamQuestion,
129+ slot: Option<&ChoiceId>,
130+ content_type: FileContentType,
131+ data: &[u8],
132+) -> Result<QuestionImage, AppError> {
133+ let replaced = QuestionImage::read_slot(question.get_id(), slot, &st.db).await?;
134+ let image = QuestionImage::new(
135+ exam.get_id(),
136+ question.get_id(),
137+ slot,
138+ content_type,
139+ data.len() as i64,
140+ );
141+ let file = image.get_file().to_string();
142+ store_blob(st, &file, data, || async {
143+ let stored = image.upsert(&st.db).await?;
144+ Ok((stored, replaced.map(|old| old.get_file().to_string())))
145+ })
146+ .await
147+}
148+
149+/// The stored bytes, served inline via [`crate::web::serve_inline_blob`].
150+pub(crate) async fn serve_image(
151+ st: &AppState,
152+ image: &QuestionImage,
153+) -> Result<Response, AppError> {
154+ crate::web::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await
155+}
156+
157+/// Attach (or replace) a question's illustration — any question kind may
158+/// carry one, e.g. the map the prompt asks about. `multipart/form-data` with
159+/// the image under a `file` field; the declared content type must be
160+/// `image/png`, `image/jpeg`, `image/webp`, or `image/gif` (rasters only —
161+/// no SVG), the bytes at most the school's `max_file_bytes` (settings).
162+/// Requires teacher+ and management rights over the exam's course; frozen
163+/// once attempts exist, like every other question edit.
164+#[utoipa::path(
165+ post,
166+ path = "/{id}/questions/{qid}/image",
167+ tag = "exams",
168+ security(("session_cookie" = [])),
169+ params(
170+ ("id" = String, Path, description = "Exam id"),
171+ ("qid" = String, Path, description = "Question id"),
172+ ),
173+ request_body(content = UploadFileForm, content_type = "multipart/form-data"),
174+ responses(
175+ (status = 201, description = "Image stored", body = ImageMetaResponse),
176+ (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse),
177+ (status = 401, description = "Not authenticated", body = ErrorResponse),
178+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
179+ (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse),
180+ (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
181+ (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse),
182+ ),
183+)]
184+pub(crate) async fn upload_question_image(
185+ State(st): State<AppState>,
186+ RequireTeacher(user): RequireTeacher,
187+ Path((id, qid)): Path<(String, String)>,
188+ mut multipart: Multipart,
189+) -> Result<(StatusCode, Json<ImageMetaResponse>), AppError> {
190+ let exam = image_managed_exam(&st, &user, &id).await?;
191+ // The body is consumed before the lock — a client's slow upload must not
192+ // stall the exam subsystem.
193+ let ImageUpload { content_type, data } = read_image_upload(&st, &mut multipart).await?;
194+ // No lock: the freeze gate is part of the image row's own transaction
195+ // (`QuestionImage::upsert`), and this path checks no subject. The
196+ // pre-flight below is the fast 409 and the byte-identical error.
197+ ensure_questions_editable(exam.get_id(), &st.db).await?;
198+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
199+ let stored = store_image(&st, &exam, &question, None, content_type, &data).await?;
200+ Ok((StatusCode::CREATED, Json(ImageMetaResponse::new(&stored))))
201+}
202+
203+/// The question's illustration bytes. Course managers read anytime; students
204+/// through the same wall as the sitting view — enrollment plus a started
205+/// attempt (404 before that, like the question list itself).
206+#[utoipa::path(
207+ get,
208+ path = "/{id}/questions/{qid}/image",
209+ tag = "exams",
210+ security(("session_cookie" = [])),
211+ params(
212+ ("id" = String, Path, description = "Exam id"),
213+ ("qid" = String, Path, description = "Question id"),
214+ ),
215+ responses(
216+ (status = 200, description = "The image bytes", content_type = "image/*"),
217+ (status = 401, description = "Not authenticated", body = ErrorResponse),
218+ (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse),
219+ (status = 404, description = "No such exam, question, or image — or no attempt yet", body = ErrorResponse),
220+ ),
221+)]
222+pub(crate) async fn get_question_image(
223+ State(st): State<AppState>,
224+ CurrentUser(user): CurrentUser,
225+ Path((id, qid)): Path<(String, String)>,
226+) -> Result<Response, AppError> {
227+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
228+ .await?
229+ .ok_or(AppError::NotFound)?;
230+ ensure_question_content_visible(&st, &exam, &user).await?;
231+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
232+ let image = QuestionImage::read_slot(question.get_id(), None, &st.db)
233+ .await?
234+ .ok_or(AppError::NotFound)?;
235+ serve_image(&st, &image).await
236+}
237+
238+/// Remove a question's illustration. Requires teacher+ and management rights
239+/// over the exam's course; frozen once attempts exist.
240+#[utoipa::path(
241+ delete,
242+ path = "/{id}/questions/{qid}/image",
243+ tag = "exams",
244+ security(("session_cookie" = [])),
245+ params(
246+ ("id" = String, Path, description = "Exam id"),
247+ ("qid" = String, Path, description = "Question id"),
248+ ),
249+ responses(
250+ (status = 204, description = "Deleted"),
251+ (status = 401, description = "Not authenticated", body = ErrorResponse),
252+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
253+ (status = 404, description = "No such exam, question, or image", body = ErrorResponse),
254+ (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
255+ ),
256+)]
257+pub(crate) async fn delete_question_image(
258+ State(st): State<AppState>,
259+ RequireTeacher(user): RequireTeacher,
260+ Path((id, qid)): Path<(String, String)>,
261+) -> Result<StatusCode, AppError> {
262+ let exam = image_managed_exam(&st, &user, &id).await?;
263+ ensure_questions_editable(exam.get_id(), &st.db).await?;
264+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
265+ let image = QuestionImage::read_slot(question.get_id(), None, &st.db)
266+ .await?
267+ .ok_or(AppError::NotFound)?;
268+ let image = image.delete(&st.db).await?;
269+ remove_blob(&st.files_path, image.get_file()).await;
270+ Ok(StatusCode::NO_CONTENT)
271+}
272+
273+/// Attach (or replace) one option's picture on a `choice` question — so the
274+/// options themselves can be images (four map crops, pick the right one).
275+/// Same form, limits, and rights as the question-image upload; `choice_id` is
276+/// the `id` carried on that choice, as returned in the question's `choices`
277+/// (not a position — an unknown id is a `400`). Replacing the question's
278+/// `choices` list drops all its option pictures — re-upload against the new
279+/// list.
280+#[utoipa::path(
281+ post,
282+ path = "/{id}/questions/{qid}/choices/{choice_id}/image",
283+ tag = "exams",
284+ security(("session_cookie" = [])),
285+ params(
286+ ("id" = String, Path, description = "Exam id"),
287+ ("qid" = String, Path, description = "Question id"),
288+ ("choice_id" = String, Path, description = "Choice id, as returned in the question's `choices`"),
289+ ),
290+ request_body(content = UploadFileForm, content_type = "multipart/form-data"),
291+ responses(
292+ (status = 201, description = "Image stored", body = ImageMetaResponse),
293+ (status = 400, description = "Missing file field, empty file, a content type outside the image allowlist, a text question, or an unknown choice id", body = ErrorResponse),
294+ (status = 401, description = "Not authenticated", body = ErrorResponse),
295+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
296+ (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse),
297+ (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
298+ (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse),
299+ ),
300+)]
301+pub(crate) async fn upload_choice_image(
302+ State(st): State<AppState>,
303+ RequireTeacher(user): RequireTeacher,
304+ Path((id, qid, choice_id)): Path<(String, String, String)>,
305+ mut multipart: Multipart,
306+) -> Result<(StatusCode, Json<ImageMetaResponse>), AppError> {
307+ let exam = image_managed_exam(&st, &user, &id).await?;
308+ let ImageUpload { content_type, data } = read_image_upload(&st, &mut multipart).await?;
309+ ensure_questions_editable(exam.get_id(), &st.db).await?;
310+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
311+ let slot = choice_slot(&question, &choice_id)?;
312+ let stored = store_image(&st, &exam, &question, Some(&slot), content_type, &data).await?;
313+ Ok((StatusCode::CREATED, Json(ImageMetaResponse::new(&stored))))
314+}
315+
316+/// One option's picture bytes. Same access wall as the question-image read.
317+#[utoipa::path(
318+ get,
319+ path = "/{id}/questions/{qid}/choices/{choice_id}/image",
320+ tag = "exams",
321+ security(("session_cookie" = [])),
322+ params(
323+ ("id" = String, Path, description = "Exam id"),
324+ ("qid" = String, Path, description = "Question id"),
325+ ("choice_id" = String, Path, description = "Choice id"),
326+ ),
327+ responses(
328+ (status = 200, description = "The image bytes", content_type = "image/*"),
329+ (status = 401, description = "Not authenticated", body = ErrorResponse),
330+ (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse),
331+ (status = 404, description = "No such exam, question, or image — or no attempt yet", body = ErrorResponse),
332+ ),
333+)]
334+pub(crate) async fn get_choice_image(
335+ State(st): State<AppState>,
336+ CurrentUser(user): CurrentUser,
337+ Path((id, qid, choice_id)): Path<(String, String, String)>,
338+) -> Result<Response, AppError> {
339+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
340+ .await?
341+ .ok_or(AppError::NotFound)?;
342+ ensure_question_content_visible(&st, &exam, &user).await?;
343+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
344+ let slot = choice_slot(&question, &choice_id)?;
345+ let image = QuestionImage::read_slot(question.get_id(), Some(&slot), &st.db)
346+ .await?
347+ .ok_or(AppError::NotFound)?;
348+ serve_image(&st, &image).await
349+}
350+
351+/// Remove one option's picture. Requires teacher+ and management rights over
352+/// the exam's course; frozen once attempts exist.
353+#[utoipa::path(
354+ delete,
355+ path = "/{id}/questions/{qid}/choices/{choice_id}/image",
356+ tag = "exams",
357+ security(("session_cookie" = [])),
358+ params(
359+ ("id" = String, Path, description = "Exam id"),
360+ ("qid" = String, Path, description = "Question id"),
361+ ("choice_id" = String, Path, description = "Choice id"),
362+ ),
363+ responses(
364+ (status = 204, description = "Deleted"),
365+ (status = 401, description = "Not authenticated", body = ErrorResponse),
366+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
367+ (status = 404, description = "No such exam, question, or image", body = ErrorResponse),
368+ (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
369+ ),
370+)]
371+pub(crate) async fn delete_choice_image(
372+ State(st): State<AppState>,
373+ RequireTeacher(user): RequireTeacher,
374+ Path((id, qid, choice_id)): Path<(String, String, String)>,
375+) -> Result<StatusCode, AppError> {
376+ let exam = image_managed_exam(&st, &user, &id).await?;
377+ ensure_questions_editable(exam.get_id(), &st.db).await?;
378+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
379+ let slot = choice_slot(&question, &choice_id)?;
380+ let image = QuestionImage::read_slot(question.get_id(), Some(&slot), &st.db)
381+ .await?
382+ .ok_or(AppError::NotFound)?;
383+ let image = image.delete(&st.db).await?;
384+ remove_blob(&st.files_path, image.get_file()).await;
385+ Ok(StatusCode::NO_CONTENT)
386+}
387+
388+// ---- answer images ----------------------------------------------------------
389+// A student's freehand drawing of their answer to a question — one per (exam,
390+// user, question), the answer-side mirror of the teacher's question images.
391+// It is a normal `image/png` (the frontend embeds its editable stroke JSON in a
392+// PNG `tEXt` chunk, opaque to us), so it flows through the same raster
393+// content-type wall and inline-serve path as every other exam image. The write
394+// paths ride the exact `save_answer` gate chain; the reads follow the question
395+// content's own visibility (own sitting view / teacher grading view).
396+
397+/// The answer-image write tail, mirroring [`store_image`]: the deterministic
398+/// per-(question, user, seq) id makes the UPSERT a replace, and [`store_blob`]
399+/// owns the disk ordering.
400+pub(crate) async fn store_answer_image(
401+ st: &AppState,
402+ exam: &Exam,
403+ question: &ExamQuestion,
404+ user: &UserId,
405+ seq: i64,
406+ content_type: FileContentType,
407+ data: &[u8],
408+) -> Result<AnswerImage, AppError> {
409+ let replaced = AnswerImage::read(question.get_id(), user, seq, &st.db).await?;
410+ let image = AnswerImage::new(
411+ exam.get_id(),
412+ question.get_id(),
413+ user,
414+ seq,
415+ content_type,
416+ data.len() as i64,
417+ );
418+ let file = image.get_file().to_string();
419+ store_blob(st, &file, data, || async {
420+ let stored = image.upsert(&st.db).await?;
421+ Ok((stored, replaced.map(|old| old.get_file().to_string())))
422+ })
423+ .await
424+}
425+
426+/// Attach (or replace) the caller's drawn answer to a question inside their
427+/// in-progress attempt. `multipart/form-data` with the drawing under a `file`
428+/// field; the declared content type must be `image/png`, `image/jpeg`,
429+/// `image/webp`, or `image/gif` (rasters only — no SVG), the bytes at most the
430+/// school's `max_file_bytes`. Rides the exact `POST /exams/{id}/attempt/answers`
431+/// gate chain: the student role, an in-progress attempt, current enrollment, and
432+/// the rejoin door.
433+#[utoipa::path(
434+ post,
435+ path = "/{id}/attempt/answers/{qid}/image",
436+ tag = "exams",
437+ security(("session_cookie" = [])),
438+ params(
439+ ("id" = String, Path, description = "Exam id"),
440+ ("qid" = String, Path, description = "Question id"),
441+ ),
442+ request_body(content = UploadFileForm, content_type = "multipart/form-data"),
443+ responses(
444+ (status = 201, description = "Drawing stored", body = ImageMetaResponse),
445+ (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse),
446+ (status = 401, description = "Not authenticated", body = ErrorResponse),
447+ (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse),
448+ (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse),
449+ (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse),
450+ (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse),
451+ ),
452+)]
453+pub(crate) async fn upload_answer_image(
454+ State(st): State<AppState>,
455+ CurrentUser(user): CurrentUser,
456+ Path((id, qid)): Path<(String, String)>,
457+ mut multipart: Multipart,
458+) -> Result<(StatusCode, Json<ImageMetaResponse>), AppError> {
459+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
460+ .await?
461+ .ok_or(AppError::NotFound)?;
462+ ensure_student(&user)?;
463+ // The body is consumed before the lock — a client's slow upload must not
464+ // stall the exam subsystem (mirrors the question-image upload).
465+ let ImageUpload { content_type, data } = read_image_upload(&st, &mut multipart).await?;
466+ // Reader lease of [`EXAM_LOCK`], exactly like `save_answer_checked`: the
467+ // writable gate and the write are one unit, or a retake's wipe-and-create
468+ // (a writer) slips in between and this stale drawing lands on the fresh
469+ // blank sheet.
470+ let _guard = EXAM_LOCK.read().await;
471+ let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?;
472+ ensure_student_now(attempt.get_user(), &st.db).await?;
473+ ensure_enrolled(&exam, attempt.get_user(), &st.db).await?;
474+ check_rejoin(&exam, &attempt)?;
475+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
476+ let seq = attempt.get_seq();
477+ let stored = store_answer_image(
478+ &st,
479+ &exam,
480+ &question,
481+ user.get_id(),
482+ seq,
483+ content_type,
484+ &data,
485+ )
486+ .await?;
487+ // A drawing-only answer (drew, typed nothing) still needs an ExamAnswer row,
488+ // or the drawing never surfaces in the sitting/grading views — answer_image
489+ // rides the answer payload. Create a blank text answer when absent, without
490+ // clobbering typed text. Choice questions can't hold a blank answer (and the
491+ // UI only offers drawing on text questions), so they are skipped. Removing
492+ // the drawing later grooms this blank row away (see `delete_answer_image`).
493+ if question.get_kind().as_str() != "choice"
494+ && ExamAnswer::read(question.get_id(), user.get_id(), seq, &st.db)
495+ .await?
496+ .is_none()
497+ {
498+ ExamAnswer::save(
499+ &question,
500+ user.get_id(),
501+ seq,
502+ None,
503+ Some(String::new()),
504+ &st.db,
505+ )
506+ .await?;
507+ }
508+ Ok((
509+ StatusCode::CREATED,
510+ Json(ImageMetaResponse::from_answer(&stored)),
511+ ))
512+}
513+
514+/// Clear the caller's drawn answer to a question. Same writable-attempt gate
515+/// chain as the upload.
516+#[utoipa::path(
517+ delete,
518+ path = "/{id}/attempt/answers/{qid}/image",
519+ tag = "exams",
520+ security(("session_cookie" = [])),
521+ params(
522+ ("id" = String, Path, description = "Exam id"),
523+ ("qid" = String, Path, description = "Question id"),
524+ ),
525+ responses(
526+ (status = 204, description = "Deleted"),
527+ (status = 401, description = "Not authenticated", body = ErrorResponse),
528+ (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse),
529+ (status = 404, description = "No such exam, question, attempt, or drawing", body = ErrorResponse),
530+ (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse),
531+ ),
532+)]
533+pub(crate) async fn delete_answer_image(
534+ State(st): State<AppState>,
535+ CurrentUser(user): CurrentUser,
536+ Path((id, qid)): Path<(String, String)>,
537+) -> Result<StatusCode, AppError> {
538+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
539+ .await?
540+ .ok_or(AppError::NotFound)?;
541+ ensure_student(&user)?;
542+ let _guard = EXAM_LOCK.read().await;
543+ let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?;
544+ ensure_student_now(attempt.get_user(), &st.db).await?;
545+ ensure_enrolled(&exam, attempt.get_user(), &st.db).await?;
546+ check_rejoin(&exam, &attempt)?;
547+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
548+ let seq = attempt.get_seq();
549+ let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db)
550+ .await?
551+ .ok_or(AppError::NotFound)?;
552+ let image = image.delete(&st.db).await?;
553+ remove_blob(&st.files_path, image.get_file()).await;
554+ // If the drawing was the whole answer (blank text, no choice — the row the
555+ // upload created for a drawing-only answer), drop it too so it stops counting
556+ // as answered. A typed answer keeps its row.
557+ if let Some(answer) = ExamAnswer::read(question.get_id(), user.get_id(), seq, &st.db).await? {
558+ let blank = answer.get_selected().is_none()
559+ && answer.get_text().is_none_or(|t| t.as_str().is_empty());
560+ if blank {
561+ ExamAnswer::delete(question.get_id(), user.get_id(), seq, &st.db).await?;
562+ }
563+ }
564+ Ok(StatusCode::NO_CONTENT)
565+}
566+
567+/// The caller's own drawn-answer bytes. Same visibility wall as the sitting
568+/// question view — enrollment plus a started attempt (404 before that).
569+#[utoipa::path(
570+ get,
571+ path = "/{id}/attempt/answers/{qid}/image",
572+ tag = "exams",
573+ security(("session_cookie" = [])),
574+ params(
575+ ("id" = String, Path, description = "Exam id"),
576+ ("qid" = String, Path, description = "Question id"),
577+ ),
578+ responses(
579+ (status = 200, description = "The drawing bytes", content_type = "image/*"),
580+ (status = 401, description = "Not authenticated", body = ErrorResponse),
581+ (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse),
582+ (status = 404, description = "No such exam, question, or drawing — or no attempt yet", body = ErrorResponse),
583+ ),
584+)]
585+pub(crate) async fn get_answer_image(
586+ State(st): State<AppState>,
587+ CurrentUser(user): CurrentUser,
588+ Path((id, qid)): Path<(String, String)>,
589+) -> Result<Response, AppError> {
590+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
591+ .await?
592+ .ok_or(AppError::NotFound)?;
593+ ensure_question_content_visible(&st, &exam, &user).await?;
594+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
595+ // The caller's current sitting — the drawing belongs to their latest seq.
596+ let seq = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db)
597+ .await?
598+ .ok_or(AppError::NotFound)?
599+ .get_seq();
600+ let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db)
601+ .await?
602+ .ok_or(AppError::NotFound)?;
603+ crate::web::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await
604+}
605+
606+/// One student's drawn-answer bytes, for the grader. Requires teacher+ and
607+/// management rights over the exam's course — the `attempt_answers` gate.
608+#[utoipa::path(
609+ get,
610+ path = "/{id}/attempts/{user}/answers/{qid}/image",
611+ tag = "exams",
612+ security(("session_cookie" = [])),
613+ params(
614+ ("id" = String, Path, description = "Exam id"),
615+ ("user" = String, Path, description = "User id"),
616+ ("qid" = String, Path, description = "Question id"),
617+ ),
618+ responses(
619+ (status = 200, description = "The student's drawing bytes", content_type = "image/*"),
620+ (status = 401, description = "Not authenticated", body = ErrorResponse),
621+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
622+ (status = 404, description = "No such exam, question, or drawing", body = ErrorResponse),
623+ ),
624+)]
625+pub(crate) async fn get_student_answer_image(
626+ State(st): State<AppState>,
627+ RequireTeacher(user): RequireTeacher,
628+ Path((id, target, qid)): Path<(String, String, String)>,
629+) -> Result<Response, AppError> {
630+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
631+ .await?
632+ .ok_or(AppError::NotFound)?;
633+ let course = course_of(&exam, &st.db).await?;
634+ if !can_manage_course(&course, &user) {
635+ return Err(AppError::Forbidden(
636+ "only the course creator, an assigned teacher, or a manager/admin can read answer sheets",
637+ ));
638+ }
639+ let target = UserId::from_key(&target);
640+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
641+ // The grader's default view is the latest sitting; per-attempt drawings
642+ // come from the history image endpoint.
643+ let seq = ExamAttempt::read_latest_for_user(exam.get_id(), &target, &st.db)
644+ .await?
645+ .ok_or(AppError::NotFound)?
646+ .get_seq();
647+ let image = AnswerImage::read(question.get_id(), &target, seq, &st.db)
648+ .await?
649+ .ok_or(AppError::NotFound)?;
650+ crate::web::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await
651+}
src/web/exams/mod.rsadded+842 -0
@@ -0,0 +1,842 @@
1+use std::collections::HashMap;
2+
3+use axum::Json;
4+use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State};
5+use axum::http::StatusCode;
6+use axum::response::Response;
7+use serde::{Deserialize, Serialize};
8+use utoipa::ToSchema;
9+use utoipa_axum::router::OpenApiRouter;
10+use utoipa_axum::routes;
11+
12+use crate::constant::{CAS_UPDATE_RETRIES, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
13+use crate::database::Database;
14+use crate::domain::answer_image::AnswerImage;
15+use crate::domain::bank_question::{BankQuestion, BankQuestionId};
16+use crate::domain::bank_question_image::BankQuestionImage;
17+use crate::domain::course::Course;
18+use crate::domain::enrollment::Enrollment;
19+use crate::domain::exam::{
20+ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode,
21+ ExamSchedule, ExamTitle,
22+};
23+use crate::domain::exam_answer::{ExamAnswer, auto_score};
24+use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt};
25+use crate::domain::exam_question::{
26+ Choice, ChoiceId, ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec,
27+ QuestionText,
28+};
29+use crate::domain::exam_result::{ExamResult, Mark};
30+use crate::domain::note_file::FileContentType;
31+use crate::domain::question_image::QuestionImage;
32+use crate::domain::role::Role;
33+use crate::domain::settings::Settings;
34+use crate::domain::timestamp::Timestamp;
35+use crate::domain::user::{User, UserId};
36+use crate::error::{AppError, ErrorResponse, ValidationError};
37+use crate::state::AppState;
38+
39+use super::bank_questions::BankQuestionResponse;
40+use super::courses::{can_manage_course, can_view_course, visible_courses};
41+use super::subjects::subject_in_course;
42+use super::{
43+ ChoiceBody, CurrentUser, ExamResponse, ImageUpload, Page, PageParams, PersonRef,
44+ RequireTeacher, Scheduled, UploadFileForm, WindowParams, blob_path, check_not_past, paginate,
45+ person_map, read_image_upload, remove_blob, set_or_clear, store_blob,
46+};
47+
48+pub(crate) mod attempts;
49+pub(crate) mod images;
50+pub(crate) mod questions;
51+pub(crate) mod review;
52+
53+pub(crate) use attempts::*;
54+pub(crate) use images::*;
55+pub(crate) use questions::*;
56+pub(crate) use review::*;
57+
58+impl Scheduled for Exam {
59+ fn starts_at_ms(&self) -> Option<i64> {
60+ self.get_starts_at().map(|at| at.as_millis())
61+ }
62+
63+ fn ends_at_ms(&self) -> Option<i64> {
64+ self.get_ends_at().map(|at| at.as_millis())
65+ }
66+
67+ fn order_key(&self) -> &str {
68+ self.get_id().key()
69+ }
70+}
71+
72+/// Serializes the exam subsystem's cross-record check-then-writes, which
73+/// `BEGIN…COMMIT` cannot (write skew) — the reasoning in [`crate::domain::cap`].
74+/// **Replica-local**: it orders requests inside one process only, and the
75+/// backend runs as two, so every invariant that could be moved into the
76+/// database has been. What is left needs a cross-record read and a write held
77+/// together, which no single statement expresses:
78+///
79+/// Read side — the answer saves (REST and the exam room), from the
80+/// writable-attempt gate through the upsert; the grade write (draft gate
81+/// through the result upsert); the exam PATCH, whose mode/re-draft gates count
82+/// attempts and results; and the three question writes that first check a
83+/// subject belongs to the course. These stay concurrent with each other.
84+///
85+/// Write side — attempt starts (the max-attempts count and the retake's answer
86+/// wipe) and the subject delete's cascade. So a save can never land on a sheet
87+/// a retake just wiped, a mark can never land on an exam mid-flight into
88+/// hiding, and a question can never adopt a subject being swept.
89+///
90+/// The question freeze gate is *not* on this list any more: it rides inside
91+/// each question/image write's own transaction
92+/// ([`crate::domain::exam_attempt::ExamAttempt::unfrozen`]), and the exam PATCH
93+/// no longer needs the writer lease because its save is a compare-and-set.
94+// ponytail: global RwLock, shard per-exam if save latency ever matters.
95+pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
96+
97+pub fn routes() -> OpenApiRouter<AppState> {
98+ OpenApiRouter::new()
99+ // Plain route: OpenApiRouter can't describe a WebSocket upgrade, so
100+ // the exam room lives outside the generated spec (see the `exams` tag
101+ // description and README for the protocol).
102+ .route(
103+ "/{id}/attempt/ws",
104+ axum::routing::get(super::exam_ws::attempt_ws),
105+ )
106+ .routes(routes!(list_exams))
107+ .routes(routes!(get_exam, update_exam, delete_exam))
108+ .routes(routes!(grade, list_results))
109+ .routes(routes!(my_result))
110+ .routes(routes!(remove_result))
111+ .routes(routes!(exam_statistics))
112+ .routes(routes!(start_attempt, my_attempt))
113+ .routes(routes!(finish_attempt))
114+ .routes(routes!(exam_live))
115+ .routes(routes!(create_question, list_questions))
116+ .routes(routes!(update_question, delete_question))
117+ .routes(routes!(question_from_bank))
118+ .routes(routes!(question_to_bank))
119+ .routes(routes!(question_refresh_from_bank))
120+ .routes(routes!(attempt_questions))
121+ .routes(routes!(save_answer))
122+ .routes(routes!(attempt_answers))
123+ .routes(routes!(student_attempts))
124+ .routes(routes!(student_attempt_answers))
125+ .routes(routes!(student_marks_history))
126+ .routes(routes!(review_questions))
127+ .routes(routes!(review_attempts))
128+ .routes(routes!(review_attempt_answers))
129+ // The image routes get their own HTTP body cap, like the note-file
130+ // ones: the server-wide hard ceiling plus multipart framing headroom.
131+ .merge(
132+ OpenApiRouter::new()
133+ .routes(routes!(
134+ upload_question_image,
135+ get_question_image,
136+ delete_question_image
137+ ))
138+ .routes(routes!(
139+ upload_choice_image,
140+ get_choice_image,
141+ delete_choice_image
142+ ))
143+ .routes(routes!(
144+ upload_answer_image,
145+ get_answer_image,
146+ delete_answer_image
147+ ))
148+ .routes(routes!(get_student_answer_image))
149+ .routes(routes!(student_attempt_answer_image))
150+ .routes(routes!(review_attempt_answer_image))
151+ .layer(DefaultBodyLimit::max(
152+ MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES,
153+ )),
154+ )
155+}
156+
157+#[derive(Deserialize, ToSchema)]
158+struct UpdateExam {
159+ #[schema(max_length = 200)]
160+ title: Option<String>,
161+ #[schema(max_length = 2000)]
162+ description: Option<String>,
163+ /// The assessment form — one of the school's exam kinds (`GET /settings`).
164+ /// Changing it re-weights the exam: the course average uses the kind's
165+ /// settings-configured weight.
166+ kind: Option<String>,
167+ /// `sync`, `async`, or `open`. Omit to keep the current mode; send `null`
168+ /// to turn the exam back into an offline-graded one. Frozen once anyone
169+ /// has started an attempt. Switching to `open` requires clearing
170+ /// `starts_at`/`ends_at` in the same request.
171+ #[serde(default, deserialize_with = "set_or_clear")]
172+ #[schema(value_type = Option<String>)]
173+ mode: Option<Option<String>>,
174+ /// Window open, UTC unix-milliseconds. Omit to keep; `null` to clear.
175+ /// A newly set value must not be in the past.
176+ #[serde(default, deserialize_with = "set_or_clear")]
177+ #[schema(value_type = Option<i64>)]
178+ starts_at: Option<Option<i64>>,
179+ /// Window close, UTC unix-milliseconds. Omit to keep; `null` to clear.
180+ /// Moving it while a sync exam runs extends (or cuts) everyone's deadline;
181+ /// a newly set value must not be in the past.
182+ #[serde(default, deserialize_with = "set_or_clear")]
183+ #[schema(value_type = Option<i64>)]
184+ ends_at: Option<Option<i64>>,
185+ /// Per-attempt budget, milliseconds (`async`, or optionally `open`). Omit
186+ /// to keep; `null` to clear. Changing it mid-exam moves every running
187+ /// attempt's deadline.
188+ #[serde(default, deserialize_with = "set_or_clear")]
189+ #[schema(value_type = Option<i64>, minimum = 60000, maximum = 86400000)]
190+ duration_ms: Option<Option<i64>>,
191+ /// Attempt limit: `1`–`100`, or `0` for unlimited. Omit to keep. Editable
192+ /// live — raising it grants retakes on the spot; lowering it only blocks
193+ /// future starts.
194+ #[schema(minimum = 0, maximum = 100)]
195+ max_attempts: Option<i64>,
196+ /// Whether students who left the exam room may come back in. Omit to
197+ /// keep. Editable live — the teacher's door handle for the running room.
198+ allow_rejoin: Option<bool>,
199+ /// Whether students may review their graded attempt once results are out.
200+ /// Omit to keep. Editable live.
201+ allow_review: Option<bool>,
202+ /// `false` publishes a draft (students can now see and sit it); `true`
203+ /// pulls a published exam back into hiding — allowed only while nobody
204+ /// has attempted it and nothing is graded (`409` otherwise). Omit to keep.
205+ draft: Option<bool>,
206+}
207+
208+#[derive(Deserialize, ToSchema)]
209+struct GradeResult {
210+ /// The mark to record, `0`–`100`.
211+ #[schema(example = 85, minimum = 0, maximum = 100)]
212+ mark: i64,
213+ /// The student being graded.
214+ #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
215+ user_id: String,
216+}
217+
218+#[derive(Serialize, ToSchema)]
219+pub(crate) struct ExamResultResponse {
220+ id: String,
221+ exam: String,
222+ /// The graded student.
223+ user: PersonRef,
224+ /// Which sitting this mark belongs to (1 = first attempt). Lets the grader
225+ /// jump from a mark to that sitting's answer sheet
226+ /// (`GET /exams/{id}/students/{user}/attempts/{seq}/answers`) — without it
227+ /// a marked retake's answers are unreachable from the mark.
228+ seq: i64,
229+ mark: i64,
230+ /// Who recorded the mark.
231+ graded_by: PersonRef,
232+}
233+
234+impl ExamResultResponse {
235+ fn new(result: &ExamResult, people: &HashMap<String, PersonRef>) -> Self {
236+ Self {
237+ id: result.get_id().key().to_string(),
238+ exam: result.get_exam().key().to_string(),
239+ user: PersonRef::resolve(people, result.get_user()),
240+ seq: result.get_seq(),
241+ mark: result.get_mark().as_i64(),
242+ graded_by: PersonRef::resolve(people, result.get_graded_by()),
243+ }
244+ }
245+}
246+
247+#[derive(Serialize, ToSchema)]
248+struct ExamStatisticsResponse {
249+ exam: String,
250+ /// Number of graded results.
251+ graded: u64,
252+ /// Plain mean of the graded marks; `null` while nothing is graded.
253+ average: Option<f64>,
254+ min: Option<i64>,
255+ max: Option<i64>,
256+}
257+
258+/// The course an exam belongs to. A dangling reference means the course-delete
259+/// cascade was violated — surface it loudly as a 500, not a user-facing 404.
260+async fn course_of(exam: &Exam, db: &Database) -> Result<Course, AppError> {
261+ Course::read(exam.get_course(), db)
262+ .await?
263+ .ok_or_else(|| AppError::Internal("exam references a missing course".into()))
264+}
265+
266+// ---- exams --------------------------------------------------------------
267+// Exams are created inside a course: `POST /courses/{id}/exams`.
268+
269+/// List the exams visible to the caller: every exam for manager+, otherwise
270+/// the exams of the courses they created or are enrolled in — minus other
271+/// people's drafts (a draft shows only to its course's managers). Paged via
272+/// `?limit=&offset=` (omit `limit` for the full list); returns a
273+/// `{items, total, limit, offset}` envelope.
274+///
275+/// The optional `?starts_after=&ends_after=` schedule window (unix
276+/// milliseconds) applies *after* the visibility and draft filtering, narrows
277+/// the list to upcoming/unfinished exams and flips the order to ascending by
278+/// schedule — so `?ends_after=<now>&limit=20` returns the twenty *soonest*
279+/// exams rather than the twenty newest-created. Exams without a window
280+/// (no `mode`, or `open`) are excluded by either parameter.
281+#[utoipa::path(
282+ get,
283+ path = "/",
284+ tag = "exams",
285+ security(("session_cookie" = [])),
286+ params(WindowParams, PageParams),
287+ responses(
288+ (status = 200, description = "A page of the caller's visible exams (all of them when unpaged)", body = Page<ExamResponse>),
289+ (status = 400, description = "Invalid window, limit, or offset", body = ErrorResponse),
290+ (status = 401, description = "Not authenticated", body = ErrorResponse),
291+ ),
292+)]
293+async fn list_exams(
294+ State(st): State<AppState>,
295+ CurrentUser(user): CurrentUser,
296+ Query(window): Query<WindowParams>,
297+ Query(page): Query<PageParams>,
298+) -> Result<Json<Page<ExamResponse>>, AppError> {
299+ let (limit, offset) = page.resolve()?;
300+ let exams = if user.get_role().at_least(Role::Manager) {
301+ Exam::list_all(&st.db).await?
302+ } else {
303+ let courses = visible_courses(&user, &st.db).await?;
304+ let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect();
305+ // Drafts show only where the caller manages the course (as its
306+ // creator — the manager+ path above already saw everything).
307+ let managed: Vec<&str> = courses
308+ .iter()
309+ .filter(|c| can_manage_course(c, &user))
310+ .map(|c| c.get_id().key())
311+ .collect();
312+ let mut exams = Exam::list_for_courses(&ids, &st.db).await?;
313+ exams.retain(|exam| !exam.is_draft() || managed.contains(&exam.get_course().key()));
314+ exams
315+ };
316+ let exams = window.apply(exams)?;
317+ let total = exams.len() as i64;
318+ // Paged in the web layer: the draft filter and the window are Rust.
319+ let items = paginate(&exams, limit, offset)
320+ .iter()
321+ .map(ExamResponse::new)
322+ .collect();
323+ Ok(Json(Page::new(items, total, limit, offset)))
324+}
325+
326+/// Fetch a single exam by id. Visible to its course's enrolled users, the
327+/// course creator, and managers/admins — except drafts, which only the
328+/// course's managers see (everyone else gets a `404`, as if the exam doesn't
329+/// exist yet — because it doesn't, officially).
330+#[utoipa::path(
331+ get,
332+ path = "/{id}",
333+ tag = "exams",
334+ security(("session_cookie" = [])),
335+ params(("id" = String, Path, description = "Exam id")),
336+ responses(
337+ (status = 200, description = "The exam", body = ExamResponse),
338+ (status = 401, description = "Not authenticated", body = ErrorResponse),
339+ (status = 403, description = "Not enrolled in the exam's course, not its creator, and not a manager/admin", body = ErrorResponse),
340+ (status = 404, description = "Not found (or a draft the caller may not see)", body = ErrorResponse),
341+ ),
342+)]
343+async fn get_exam(
344+ State(st): State<AppState>,
345+ CurrentUser(user): CurrentUser,
346+ Path(id): Path<String>,
347+) -> Result<Json<ExamResponse>, AppError> {
348+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
349+ .await?
350+ .ok_or(AppError::NotFound)?;
351+ let course = course_of(&exam, &st.db).await?;
352+ if !can_view_course(&course, &user, &st.db).await? {
353+ return Err(AppError::Forbidden(
354+ "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this exam",
355+ ));
356+ }
357+ // A draft doesn't exist for anyone but its course's managers — 404, not
358+ // 403, so its existence never leaks to the students it's hidden from.
359+ if exam.is_draft() && !can_manage_course(&course, &user) {
360+ return Err(AppError::NotFound);
361+ }
362+ Ok(Json(ExamResponse::new(&exam)))
363+}
364+
365+/// Update an exam. Requires teacher+ and management rights over the exam's
366+/// course (its creator, or manager/admin). Omitted fields keep their value; an
367+/// explicit `null` clears a schedule field; the course itself is not updatable.
368+/// The schedule must stay consistent as a whole (see the create endpoint), and
369+/// `mode` is frozen once anyone has started an attempt — times, duration,
370+/// `max_attempts`, and `allow_rejoin` stay editable so a running exam can be
371+/// extended, granted retakes, or have its rejoin door opened live.
372+/// `draft: false` publishes a draft; `draft: true` re-hides an exam, but only
373+/// while it has no attempts and no results (`409` otherwise) — students never
374+/// lose sight of an exam they've already sat or been graded on.
375+#[utoipa::path(
376+ patch,
377+ path = "/{id}",
378+ tag = "exams",
379+ security(("session_cookie" = [])),
380+ params(("id" = String, Path, description = "Exam id")),
381+ request_body = UpdateExam,
382+ responses(
383+ (status = 200, description = "Updated exam", body = ExamResponse),
384+ (status = 400, description = "Invalid fields, kind, attempt limit, or schedule (malformed window, duration exceeding the window, or newly set times in the past)", body = ErrorResponse),
385+ (status = 401, description = "Not authenticated", body = ErrorResponse),
386+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
387+ (status = 404, description = "Not found", body = ErrorResponse),
388+ (status = 409, description = "Mode change after attempts started, re-drafting an exam that has attempts or results, or the exam kept changing under concurrent edits", body = ErrorResponse),
389+ ),
390+)]
391+async fn update_exam(
392+ State(st): State<AppState>,
393+ RequireTeacher(user): RequireTeacher,
394+ Path(id): Path<String>,
395+ Json(req): Json<UpdateExam>,
396+) -> Result<Json<ExamResponse>, AppError> {
397+ // *Reader* lease of [`EXAM_LOCK`] for exactly one pairing: the mode gate
398+ // below reads `exam_attempt`, and an attempt start takes the *writer*
399+ // lease, so a first sitting still cannot land between that gate and the
400+ // write — replica-locally, as it always did.
401+ //
402+ // It buys nothing against grading, which is a reader too: the re-draft gate
403+ // is therefore enforced inside the update's own transaction
404+ // (`Exam::update_if_unchanged`), where it holds across replicas. The gate
405+ // below stays as the pre-flight — same error, one round trip earlier.
406+ // Concurrent PATCHes of this exam no longer queue behind each other either:
407+ // the lost update they used to cause is refused by the compare-and-set.
408+ let _guard = EXAM_LOCK.read().await;
409+ let mut left = CAS_UPDATE_RETRIES;
410+ let exam = loop {
411+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
412+ .await?
413+ .ok_or(AppError::NotFound)?;
414+ let course = course_of(&exam, &st.db).await?;
415+ if !can_manage_course(&course, &user) {
416+ return Err(AppError::Forbidden(
417+ "only the course creator, an assigned teacher, or a manager/admin can edit this exam",
418+ ));
419+ }
420+
421+ let title = match req.title {
422+ Some(ref title) => ExamTitle::try_new(title)?,
423+ None => exam.get_title().clone(),
424+ };
425+ let description = match req.description {
426+ Some(ref description) => ExamDescription::try_new(description)?,
427+ None => exam.get_description().clone(),
428+ };
429+ let kind = match req.kind {
430+ // Only a kind this request sets is held to the current settings list —
431+ // a stored kind survives later list edits, like past times survive
432+ // the no-past rule.
433+ Some(ref kind) => {
434+ let school = Settings::load(&st.db).await?;
435+ ExamKind::try_new(kind, school.get_exam_kinds())?
436+ }
437+ None => exam.get_kind().clone(),
438+ };
439+
440+ // Merge the schedule (set / clear / keep per field), then re-validate it
441+ // as a unit — a PATCH can't leave a half-schedule behind. Only values this
442+ // request sets are held to the no-past rule: kept ones may legitimately be
443+ // past (a running exam's `starts_at`), and rechecking them would block
444+ // unrelated edits.
445+ let mode = match req.mode {
446+ Some(ref update) => update.as_deref().map(ExamMode::try_new).transpose()?,
447+ None => exam.get_mode().cloned(),
448+ };
449+ let starts_at = match req.starts_at {
450+ Some(update) => {
451+ let starts_at = update.map(Timestamp::from_millis);
452+ check_not_past("starts_at", starts_at)?;
453+ starts_at
454+ }
455+ None => exam.get_starts_at(),
456+ };
457+ let ends_at = match req.ends_at {
458+ Some(update) => {
459+ let ends_at = update.map(Timestamp::from_millis);
460+ check_not_past("ends_at", ends_at)?;
461+ ends_at
462+ }
463+ None => exam.get_ends_at(),
464+ };
465+ let duration_ms = match req.duration_ms {
466+ Some(update) => update.map(ExamDuration::try_new).transpose()?,
467+ None => exam.get_duration_ms(),
468+ };
469+ let schedule = ExamSchedule::try_new(mode, starts_at, ends_at, duration_ms)?;
470+ let max_attempts = match req.max_attempts {
471+ Some(limit) => ExamAttemptLimit::try_new(limit)?,
472+ None => exam.get_max_attempts(),
473+ };
474+ let allow_rejoin = req.allow_rejoin.unwrap_or_else(|| exam.get_allow_rejoin());
475+ let allow_review = req.allow_review.unwrap_or_else(|| exam.get_allow_review());
476+ let draft = req.draft.unwrap_or_else(|| exam.is_draft());
477+
478+ // Switching sync <-> async <-> open (or back to unscheduled) would
479+ // silently rewrite the deadline rules under students who already sat
480+ // down; extending times, the attempt limit, and the rejoin door are the
481+ // supported live adjustments instead. Gate read and write share the
482+ // handler-wide writer lease of [`EXAM_LOCK`], so a first attempt can't
483+ // land in the gap and leave a sat exam's mode flipped under it.
484+ let mode_changed =
485+ schedule.get_mode().map(ExamMode::as_str) != exam.get_mode().map(ExamMode::as_str);
486+ if mode_changed && ExamAttempt::any_for_exam(exam.get_id(), &st.db).await? {
487+ return Err(AppError::Conflict(
488+ "cannot change the exam mode after attempts have started",
489+ ));
490+ }
491+ // Re-drafting hides the exam — never out from under a student who
492+ // already sat it or holds a mark on it. Pre-flight only: the write's own
493+ // transaction re-makes this check and answers with the same error, so a
494+ // grade landing after this read still cannot leave a mark on a draft.
495+ if draft && !exam.is_draft() {
496+ let sat = ExamAttempt::any_for_exam(exam.get_id(), &st.db).await?;
497+ let graded = !ExamResult::list_for_exam(exam.get_id(), &st.db)
498+ .await?
499+ .is_empty();
500+ if sat || graded {
501+ return Err(crate::domain::exam::redraft_error());
502+ }
503+ }
504+
505+ if let Some(updated) = exam
506+ .update_if_unchanged(
507+ title,
508+ description,
509+ kind,
510+ schedule,
511+ max_attempts,
512+ allow_rejoin,
513+ allow_review,
514+ draft,
515+ &st.db,
516+ )
517+ .await?
518+ {
519+ break updated;
520+ }
521+ // The row moved under the snapshot every gate above judged: re-read and
522+ // re-merge, so both edits land instead of the later reverting the earlier.
523+ left -= 1;
524+ if left == 0 {
525+ return Err(AppError::Conflict(
526+ "the exam kept changing underneath this update — try again",
527+ ));
528+ }
529+ };
530+ Ok(Json(ExamResponse::new(&exam)))
531+}
532+
533+/// Delete an exam. Requires teacher+ and management rights over the exam's
534+/// course (its creator, or manager/admin). Cascades the exam's results,
535+/// attempts, questions, answers, and question + answer images (blobs included).
536+#[utoipa::path(
537+ delete,
538+ path = "/{id}",
539+ tag = "exams",
540+ security(("session_cookie" = [])),
541+ params(("id" = String, Path, description = "Exam id")),
542+ responses(
543+ (status = 204, description = "Deleted"),
544+ (status = 401, description = "Not authenticated", body = ErrorResponse),
545+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
546+ (status = 404, description = "Not found", body = ErrorResponse),
547+ ),
548+)]
549+async fn delete_exam(
550+ State(st): State<AppState>,
551+ RequireTeacher(user): RequireTeacher,
552+ Path(id): Path<String>,
553+) -> Result<StatusCode, AppError> {
554+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
555+ .await?
556+ .ok_or(AppError::NotFound)?;
557+ let course = course_of(&exam, &st.db).await?;
558+ if !can_manage_course(&course, &user) {
559+ return Err(AppError::Forbidden(
560+ "only the course creator, an assigned teacher, or a manager/admin can delete this exam",
561+ ));
562+ }
563+ // Rows go first (the delete cascades them), blobs after — a crash in
564+ // between strands at worst an unreachable blob.
565+ let images = QuestionImage::list_for_exam(exam.get_id(), &st.db).await?;
566+ let answer_images = AnswerImage::list_for_exam(exam.get_id(), &st.db).await?;
567+ exam.delete(&st.db).await?;
568+ for image in &images {
569+ remove_blob(&st.files_path, image.get_file()).await;
570+ }
571+ for image in &answer_images {
572+ remove_blob(&st.files_path, image.get_file()).await;
573+ }
574+ Ok(StatusCode::NO_CONTENT)
575+}
576+
577+// ---- results ------------------------------------------------------------
578+
579+/// Record (or overwrite) a student's mark for an exam. Requires teacher+ and
580+/// management rights over the exam's course; the target must be a student and
581+/// enrolled. Only students carry marks; students never grade — and nobody
582+/// grades themselves. A draft can't be graded (`409`) — a mark would point at
583+/// an exam its student can't see.
584+#[utoipa::path(
585+ post,
586+ path = "/{id}/results",
587+ tag = "exams",
588+ security(("session_cookie" = [])),
589+ params(("id" = String, Path, description = "Exam id")),
590+ request_body = GradeResult,
591+ responses(
592+ (status = 200, description = "Result recorded", body = ExamResultResponse),
593+ (status = 400, description = "Invalid mark, unknown user, user not a student, or not enrolled", body = ErrorResponse),
594+ (status = 401, description = "Not authenticated", body = ErrorResponse),
595+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse),
596+ (status = 404, description = "Exam not found", body = ErrorResponse),
597+ (status = 409, description = "The exam is a draft", body = ErrorResponse),
598+ ),
599+)]
600+async fn grade(
601+ State(st): State<AppState>,
602+ RequireTeacher(teacher): RequireTeacher,
603+ Path(id): Path<String>,
604+ Json(req): Json<GradeResult>,
605+) -> Result<Json<ExamResultResponse>, AppError> {
606+ let exam_id = ExamId::from_key(&id);
607+ // Reader lease of [`EXAM_LOCK`] from the exam read through the result
608+ // write: the draft gate below must be judged against the same row the
609+ // mark lands under, or a concurrent re-draft (a writer, which checks for
610+ // results) could slip between them and leave a mark on a hidden exam.
611+ let _guard = EXAM_LOCK.read().await;
612+ // Exam must exist.
613+ let exam = Exam::read(&exam_id, &st.db)
614+ .await?
615+ .ok_or(AppError::NotFound)?;
616+ let course = course_of(&exam, &st.db).await?;
617+ if !can_manage_course(&course, &teacher) {
618+ return Err(AppError::Forbidden(
619+ "only the course creator, an assigned teacher, or a manager/admin can grade this exam",
620+ ));
621+ }
622+ // Pre-flight: `ExamResult::grade` re-makes this check inside the mark's own
623+ // transaction, so a re-draft landing after this read cannot leave a mark on
624+ // a hidden exam.
625+ if exam.is_draft() {
626+ return Err(crate::domain::exam_result::draft_error());
627+ }
628+
629+ let mark = Mark::try_new(req.mark)?;
630+ let target = UserId::from_key(&req.user_id);
631+
632+ // Grading never targets oneself — no grader, whatever their role, may
633+ // write their own mark.
634+ if &target == teacher.get_id() {
635+ return Err(AppError::Forbidden("grading yourself is not allowed"));
636+ }
637+
638+ // Target user must exist.
639+ let Some(target_user) = User::read(&target, &st.db).await? else {
640+ return Err(AppError::Validation(ValidationError::Invalid {
641+ field: "user_id",
642+ reason: "target user does not exist",
643+ }));
644+ };
645+
646+ // Only students carry marks — the grade system is theirs alone. A stale
647+ // enrollment left behind by a promotion can't reopen grading for staff.
648+ if target_user.get_role() != Role::Student {
649+ return Err(AppError::Validation(ValidationError::Invalid {
650+ field: "user_id",
651+ reason: "only students can be graded",
652+ }));
653+ }
654+
655+ // ... and be enrolled in the exam's course.
656+ if Enrollment::read_for_user(exam.get_course(), &target, &st.db)
657+ .await?
658+ .is_none()
659+ {
660+ return Err(AppError::Validation(ValidationError::Invalid {
661+ field: "user_id",
662+ reason: "target user is not enrolled in this course",
663+ }));
664+ }
665+
666+ // The mark lands on the student's current sitting; the latest seq is the
667+ // grade-of-record. An offline-graded exam has no sitting — grade its base
668+ // seq (1).
669+ let seq = ExamAttempt::read_latest_for_user(&exam_id, &target, &st.db)
670+ .await?
671+ .map_or(1, |a| a.get_seq());
672+ let result = ExamResult::grade(&exam_id, &target, seq, mark, teacher.get_id(), &st.db).await?;
673+ let people = PersonRef::map_of(&[&target_user, &teacher]);
674+ Ok(Json(ExamResultResponse::new(&result, &people)))
675+}
676+
677+/// List an exam's results, paged via `?limit=&offset=` (omit `limit` for all
678+/// of them). Requires teacher+ and management rights over the exam's course —
679+/// students read only their own via `GET /exams/{id}/result`. Returns a
680+/// `{items, total, limit, offset}` envelope.
681+#[utoipa::path(
682+ get,
683+ path = "/{id}/results",
684+ tag = "exams",
685+ security(("session_cookie" = [])),
686+ params(("id" = String, Path, description = "Exam id"), PageParams),
687+ responses(
688+ (status = 200, description = "A page of results (all of them when unpaged)", body = Page<ExamResultResponse>),
689+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
690+ (status = 401, description = "Not authenticated", body = ErrorResponse),
691+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
692+ (status = 404, description = "Exam not found", body = ErrorResponse),
693+ ),
694+)]
695+async fn list_results(
696+ State(st): State<AppState>,
697+ RequireTeacher(user): RequireTeacher,
698+ Path(id): Path<String>,
699+ Query(page): Query<PageParams>,
700+) -> Result<Json<Page<ExamResultResponse>>, AppError> {
701+ let (limit, offset) = page.resolve()?;
702+ // Exam must exist — a missing exam is a 404, not an empty result list.
703+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
704+ .await?
705+ .ok_or(AppError::NotFound)?;
706+ let course = course_of(&exam, &st.db).await?;
707+ if !can_manage_course(&course, &user) {
708+ return Err(AppError::Forbidden(
709+ "only the course creator, an assigned teacher, or a manager/admin can list results",
710+ ));
711+ }
712+ let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?;
713+ let total = results.len() as i64;
714+ // Join people onto the page alone — the lookup shrinks with the window.
715+ // Paged in the web layer: the list is deduped to the latest mark per
716+ // sitting pair in Rust.
717+ let rows = paginate(&results, limit, offset);
718+ let people = person_map(
719+ rows.iter()
720+ .flat_map(|r| [r.get_user().clone(), r.get_graded_by().clone()]),
721+ &st.db,
722+ )
723+ .await?;
724+ let items = rows
725+ .iter()
726+ .map(|r| ExamResultResponse::new(r, &people))
727+ .collect();
728+ Ok(Json(Page::new(items, total, limit, offset)))
729+}
730+
731+/// The current user's own result for an exam. Any authenticated user may read
732+/// their own mark; `404` while ungraded (or when the exam doesn't exist).
733+#[utoipa::path(
734+ get,
735+ path = "/{id}/result",
736+ tag = "exams",
737+ security(("session_cookie" = [])),
738+ params(("id" = String, Path, description = "Exam id")),
739+ responses(
740+ (status = 200, description = "The caller's result", body = ExamResultResponse),
741+ (status = 401, description = "Not authenticated", body = ErrorResponse),
742+ (status = 404, description = "No such exam, or not graded yet", body = ErrorResponse),
743+ ),
744+)]
745+async fn my_result(
746+ State(st): State<AppState>,
747+ CurrentUser(user): CurrentUser,
748+ Path(id): Path<String>,
749+) -> Result<Json<ExamResultResponse>, AppError> {
750+ let result = ExamResult::read_for_user(&ExamId::from_key(&id), user.get_id(), &st.db)
751+ .await?
752+ .ok_or(AppError::NotFound)?;
753+ let people = person_map(
754+ [result.get_user().clone(), result.get_graded_by().clone()],
755+ &st.db,
756+ )
757+ .await?;
758+ Ok(Json(ExamResultResponse::new(&result, &people)))
759+}
760+
761+/// Remove a student's result from an exam. Requires teacher+ and management
762+/// rights over the exam's course.
763+#[utoipa::path(
764+ delete,
765+ path = "/{id}/results/{user}",
766+ tag = "exams",
767+ security(("session_cookie" = [])),
768+ params(
769+ ("id" = String, Path, description = "Exam id"),
770+ ("user" = String, Path, description = "User id"),
771+ ),
772+ responses(
773+ (status = 204, description = "Removed"),
774+ (status = 401, description = "Not authenticated", body = ErrorResponse),
775+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
776+ (status = 404, description = "Not found", body = ErrorResponse),
777+ ),
778+)]
779+async fn remove_result(
780+ State(st): State<AppState>,
781+ RequireTeacher(user): RequireTeacher,
782+ Path((id, target)): Path<(String, String)>,
783+) -> Result<StatusCode, AppError> {
784+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
785+ .await?
786+ .ok_or(AppError::NotFound)?;
787+ let course = course_of(&exam, &st.db).await?;
788+ if !can_manage_course(&course, &user) {
789+ return Err(AppError::Forbidden(
790+ "only the course creator, an assigned teacher, or a manager/admin can remove results",
791+ ));
792+ }
793+ let removed = ExamResult::remove(exam.get_id(), &UserId::from_key(&target), &st.db).await?;
794+ if removed.is_none() {
795+ return Err(AppError::NotFound);
796+ }
797+ Ok(StatusCode::NO_CONTENT)
798+}
799+
800+/// Summary statistics for an exam's graded results. Requires teacher+ and
801+/// management rights over the exam's course.
802+#[utoipa::path(
803+ get,
804+ path = "/{id}/statistics",
805+ tag = "exams",
806+ security(("session_cookie" = [])),
807+ params(("id" = String, Path, description = "Exam id")),
808+ responses(
809+ (status = 200, description = "The exam's mark statistics", body = ExamStatisticsResponse),
810+ (status = 401, description = "Not authenticated", body = ErrorResponse),
811+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
812+ (status = 404, description = "Exam not found", body = ErrorResponse),
813+ ),
814+)]
815+async fn exam_statistics(
816+ State(st): State<AppState>,
817+ RequireTeacher(user): RequireTeacher,
818+ Path(id): Path<String>,
819+) -> Result<Json<ExamStatisticsResponse>, AppError> {
820+ // Exam must exist — a missing exam is a 404, not an empty statistic.
821+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
822+ .await?
823+ .ok_or(AppError::NotFound)?;
824+ let course = course_of(&exam, &st.db).await?;
825+ if !can_manage_course(&course, &user) {
826+ return Err(AppError::Forbidden(
827+ "only the course creator, an assigned teacher, or a manager/admin can view statistics",
828+ ));
829+ }
830+ let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?;
831+
832+ let marks: Vec<i64> = results.iter().map(|r| r.get_mark().as_i64()).collect();
833+ let average =
834+ (!marks.is_empty()).then(|| marks.iter().sum::<i64>() as f64 / marks.len() as f64);
835+ Ok(Json(ExamStatisticsResponse {
836+ exam: exam.get_id().key().to_string(),
837+ graded: marks.len() as u64,
838+ average,
839+ min: marks.iter().min().copied(),
840+ max: marks.iter().max().copied(),
841+ }))
842+}
src/web/exams/questions.rsadded+851 -0
@@ -0,0 +1,851 @@
1+use super::*;
2+
3+// ---- questions --------------------------------------------------------------
4+// Teachers author the question list before the exam runs; it freezes the
5+// moment anyone starts an attempt, so every student sits the same exam.
6+
7+#[derive(Deserialize, ToSchema)]
8+pub(crate) struct CreateQuestion {
9+ /// The subject this question belongs to — one of the exam's course's
10+ /// subjects (`GET /courses/{id}/subjects`). Required.
11+ #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
12+ subject_id: String,
13+ /// The question itself.
14+ #[schema(example = "What is 2 + 2?", max_length = 2000)]
15+ text: String,
16+ /// `choice` or `text`.
17+ #[schema(example = "choice")]
18+ kind: String,
19+ /// This question's share of the auto-score, `1`–`100`.
20+ #[schema(example = 10, minimum = 1, maximum = 100)]
21+ points: i64,
22+ /// The options of a `choice` question (2–10 of them); omit for `text`.
23+ /// Each carries an `id` naming it within this payload — the server mints
24+ /// the stored ids and returns them.
25+ #[schema(min_items = 2, max_items = 10)]
26+ choices: Option<Vec<ChoiceBody>>,
27+ /// The `id` of the right option, as sent in `choices`; required for
28+ /// `choice`, absent for `text`.
29+ #[schema(example = "b")]
30+ correct: Option<String>,
31+}
32+
33+#[derive(Deserialize, ToSchema)]
34+pub(crate) struct UpdateQuestion {
35+ /// Re-tag the question with another of the course's subjects. Omit to
36+ /// keep the current one — a question always has a subject, so there is no
37+ /// clearing it.
38+ subject_id: Option<String>,
39+ #[schema(max_length = 2000)]
40+ text: Option<String>,
41+ #[schema(minimum = 1, maximum = 100)]
42+ points: Option<i64>,
43+ /// `choice` or `text`. Switching kinds needs the other fields to follow:
44+ /// send `choices` + `correct` when moving to `choice`, explicit `null`s
45+ /// when moving to `text`.
46+ kind: Option<String>,
47+ /// Omit to keep the stored options; send `null` to drop them (text
48+ /// questions only). Send each option back with the `id` it was returned
49+ /// with to keep it — its picture rides along. Only options whose id is
50+ /// absent from the new list lose their picture, so reordering, renaming,
51+ /// and deleting one option leave the rest untouched.
52+ #[serde(default, deserialize_with = "set_or_clear")]
53+ #[schema(value_type = Option<Vec<ChoiceBody>>, min_items = 2, max_items = 10)]
54+ choices: Option<Option<Vec<ChoiceBody>>>,
55+ /// The `id` of the right option. Omit to keep; `null` to clear (text
56+ /// questions only).
57+ #[serde(default, deserialize_with = "set_or_clear")]
58+ #[schema(value_type = Option<String>)]
59+ correct: Option<Option<String>>,
60+}
61+
62+/// One option on the wire: its stable id and its text. Carries **no** answer
63+/// key — `correct` is a sibling field on the question, and only on the
64+/// author-facing DTO, so a student response cannot contain one by construction.
65+#[derive(Serialize, ToSchema)]
66+pub(crate) struct ChoiceResponse {
67+ /// Send this back in a PATCH to keep the option (and its picture).
68+ id: String,
69+ text: String,
70+}
71+
72+impl ChoiceResponse {
73+ pub(crate) fn list(choices: Option<&[Choice]>) -> Option<Vec<Self>> {
74+ choices.map(|choices| {
75+ choices
76+ .iter()
77+ .map(|choice| Self {
78+ id: choice.get_id().as_str().to_string(),
79+ text: choice.get_text().as_str().to_string(),
80+ })
81+ .collect()
82+ })
83+ }
84+}
85+
86+/// A question as its author sees it — including the `correct` option. Never
87+/// serialized to students; they get [`AttemptQuestionResponse`].
88+#[derive(Serialize, ToSchema)]
89+pub(crate) struct QuestionResponse {
90+ id: String,
91+ exam: String,
92+ /// The subject this question belongs to (`GET /subjects/{id}`).
93+ subject: String,
94+ text: String,
95+ /// `choice` or `text`.
96+ #[schema(example = "choice")]
97+ kind: String,
98+ points: i64,
99+ /// The options with their stable ids (`choice` questions only).
100+ choices: Option<Vec<ChoiceResponse>>,
101+ /// The id of the right option (`choice` questions only).
102+ correct: Option<String>,
103+ /// The question's illustration, if one was uploaded (any kind).
104+ image: Option<ImageMetaResponse>,
105+ /// Per-option pictures, aligned with `choices` (`choice` questions only).
106+ choice_images: Option<Vec<Option<ImageMetaResponse>>>,
107+ /// The bank template this question was created from, if it was added out of
108+ /// the bank (`GET /bank-questions/{id}`).
109+ from_bank: Option<String>,
110+ /// The bank template most recently created by saving this question into the
111+ /// bank, if any — set only by `POST …/questions/{qid}/to-bank`. Null on a
112+ /// question that came *from* the bank and was never saved back.
113+ banked_as: Option<String>,
114+}
115+
116+impl QuestionResponse {
117+ pub(crate) fn new(question: &ExamQuestion, images: &[QuestionImage]) -> Self {
118+ Self {
119+ id: question.get_id().key().to_string(),
120+ exam: question.get_exam().key().to_string(),
121+ subject: question.get_subject().key().to_string(),
122+ text: question.get_text().as_str().to_string(),
123+ kind: question.get_kind().as_str().to_string(),
124+ points: question.get_points().as_i64(),
125+ choices: ChoiceResponse::list(question.get_choices()),
126+ correct: question.get_correct().map(|id| id.as_str().to_string()),
127+ image: image_meta(images, None),
128+ choice_images: choice_image_metas(question, images),
129+ from_bank: question.get_from_bank().map(|b| b.key().to_string()),
130+ banked_as: question.get_banked_as().map(|b| b.key().to_string()),
131+ }
132+ }
133+}
134+
135+/// The questions freeze once anyone has started an attempt — editing them
136+/// under a student mid-exam would fork what "the exam" means.
137+pub(crate) async fn ensure_questions_editable(
138+ exam: &ExamId,
139+ db: &Database,
140+) -> Result<(), AppError> {
141+ if ExamAttempt::any_for_exam(exam, db).await? {
142+ return Err(AppError::Conflict(
143+ "cannot change questions after attempts have started",
144+ ));
145+ }
146+ Ok(())
147+}
148+
149+/// The question, provided it belongs to `exam` — a qid under someone else's
150+/// exam is a plain 404, not a leak.
151+pub(crate) async fn question_of_exam(
152+ exam: &ExamId,
153+ qid: &str,
154+ db: &Database,
155+) -> Result<ExamQuestion, AppError> {
156+ let question = ExamQuestion::read(&ExamQuestionId::from_key(qid), db)
157+ .await?
158+ .ok_or(AppError::NotFound)?;
159+ if question.get_exam() != exam {
160+ return Err(AppError::NotFound);
161+ }
162+ Ok(question)
163+}
164+
165+/// The question's option named by `choice_id` — a 400 for a text question or an
166+/// id the question doesn't have, so an option picture can only ever be
167+/// addressed through an option that exists.
168+pub(crate) fn choice_slot(question: &ExamQuestion, choice_id: &str) -> Result<ChoiceId, AppError> {
169+ let Some(choices) = question.get_choices() else {
170+ return Err(AppError::Validation(ValidationError::Invalid {
171+ field: "choice_id",
172+ reason: "only choice questions take option pictures",
173+ }));
174+ };
175+ choices
176+ .iter()
177+ .find(|choice| choice.get_id().as_str() == choice_id)
178+ .map(|choice| choice.get_id().clone())
179+ .ok_or(AppError::Validation(ValidationError::Invalid {
180+ field: "choice_id",
181+ reason: "must name one of the choices",
182+ }))
183+}
184+
185+/// Add a question to an exam. Requires teacher+ and management rights over the
186+/// exam's course. `subject_id` must name one of the course's subjects
187+/// (`GET /courses/{id}/subjects`) — every question belongs to a subject.
188+/// `choice` questions carry 2–10 `choices` plus `correct` naming one of them by id; `text`
189+/// questions carry neither. Locked once attempts exist.
190+#[utoipa::path(
191+ post,
192+ path = "/{id}/questions",
193+ tag = "exams",
194+ security(("session_cookie" = [])),
195+ params(("id" = String, Path, description = "Exam id")),
196+ request_body = CreateQuestion,
197+ responses(
198+ (status = 201, description = "Question created", body = QuestionResponse),
199+ (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse),
200+ (status = 401, description = "Not authenticated", 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),
203+ (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
204+ ),
205+)]
206+pub(crate) async fn create_question(
207+ State(st): State<AppState>,
208+ RequireTeacher(user): RequireTeacher,
209+ Path(id): Path<String>,
210+ Json(req): Json<CreateQuestion>,
211+) -> Result<(StatusCode, Json<QuestionResponse>), AppError> {
212+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
213+ .await?
214+ .ok_or(AppError::NotFound)?;
215+ let course = course_of(&exam, &st.db).await?;
216+ if !can_manage_course(&course, &user) {
217+ return Err(AppError::Forbidden(
218+ "only the course creator, an assigned teacher, or a manager/admin can author questions",
219+ ));
220+ }
221+ // Reader lease of [`EXAM_LOCK`], for the subject check alone: a subject
222+ // delete (which takes the writer lease) must not invalidate a subject this
223+ // just validated. Replica-local, like every lock here. The freeze gate no
224+ // longer needs the lease — it rides inside the insert's own transaction.
225+ let _guard = EXAM_LOCK.read().await;
226+ ensure_questions_editable(exam.get_id(), &st.db).await?;
227+
228+ let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;
229+ let text = QuestionText::try_new(&req.text)?;
230+ let points = QuestionPoints::try_new(req.points)?;
231+ // No stored choices to match against on create, so every option is new and
232+ // every id is minted here.
233+ let spec = QuestionSpec::try_new(
234+ QuestionKind::try_new(&req.kind)?,
235+ ChoiceBody::into_inputs(req.choices),
236+ req.correct,
237+ &[],
238+ )?;
239+ let question = ExamQuestion::create(exam.get_id(), subject, text, points, spec, &st.db).await?;
240+ // A question is born imageless — uploads come after, against its id.
241+ Ok((
242+ StatusCode::CREATED,
243+ Json(QuestionResponse::new(&question, &[])),
244+ ))
245+}
246+
247+/// The exam's question list, `correct` choice ids included — the answer key,
248+/// paged via `?limit=&offset=` (omit `limit` for the whole list). Requires
249+/// teacher+ and management rights over the exam's course. Students read
250+/// questions through `GET /exams/{id}/attempt/questions`. Returns a
251+/// `{items, total, limit, offset}` envelope.
252+#[utoipa::path(
253+ get,
254+ path = "/{id}/questions",
255+ tag = "exams",
256+ security(("session_cookie" = [])),
257+ params(("id" = String, Path, description = "Exam id"), PageParams),
258+ responses(
259+ (status = 200, description = "A page of the exam's questions (all of them when unpaged)", body = Page<QuestionResponse>),
260+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
261+ (status = 401, description = "Not authenticated", body = ErrorResponse),
262+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
263+ (status = 404, description = "Exam not found", body = ErrorResponse),
264+ ),
265+)]
266+pub(crate) async fn list_questions(
267+ State(st): State<AppState>,
268+ RequireTeacher(user): RequireTeacher,
269+ Path(id): Path<String>,
270+ Query(page): Query<PageParams>,
271+) -> Result<Json<Page<QuestionResponse>>, AppError> {
272+ let (limit, offset) = page.resolve()?;
273+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
274+ .await?
275+ .ok_or(AppError::NotFound)?;
276+ let course = course_of(&exam, &st.db).await?;
277+ if !can_manage_course(&course, &user) {
278+ return Err(AppError::Forbidden(
279+ "only the course creator, an assigned teacher, or a manager/admin can read the question list",
280+ ));
281+ }
282+ Ok(Json(question_page(&exam, limit, offset, &st.db).await?))
283+}
284+
285+/// The paged answer-key list (`correct` included) shared by the teacher
286+/// `list_questions` read and the student `review_questions` read — the two
287+/// differ only in the access wall they run first.
288+pub(crate) async fn question_page(
289+ exam: &Exam,
290+ limit: Option<i64>,
291+ offset: i64,
292+ db: &Database,
293+) -> Result<Page<QuestionResponse>, AppError> {
294+ let (questions, total) = ExamQuestion::list_for_exam(exam.get_id(), limit, offset, db).await?;
295+ let images = images_by_question(exam.get_id(), db).await?;
296+ let items = questions
297+ .iter()
298+ .map(|question| {
299+ QuestionResponse::new(
300+ question,
301+ images
302+ .get(question.get_id().key())
303+ .map_or(&[][..], Vec::as_slice),
304+ )
305+ })
306+ .collect();
307+ Ok(Page::new(items, total, limit, offset))
308+}
309+
310+/// Edit a question. Requires teacher+ and management rights over the exam's
311+/// course. Omitted fields keep their value; `kind`/`choices`/`correct` are
312+/// re-validated as a unit, so a kind switch must bring the matching fields
313+/// along. `subject_id` re-tags within the course's subjects. Locked once
314+/// attempts exist.
315+#[utoipa::path(
316+ patch,
317+ path = "/{id}/questions/{qid}",
318+ tag = "exams",
319+ security(("session_cookie" = [])),
320+ params(
321+ ("id" = String, Path, description = "Exam id"),
322+ ("qid" = String, Path, description = "Question id"),
323+ ),
324+ request_body = UpdateQuestion,
325+ responses(
326+ (status = 200, description = "Updated question", body = QuestionResponse),
327+ (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse),
328+ (status = 401, description = "Not authenticated", body = ErrorResponse),
329+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
330+ (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse),
331+ (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
332+ ),
333+)]
334+pub(crate) async fn update_question(
335+ State(st): State<AppState>,
336+ RequireTeacher(user): RequireTeacher,
337+ Path((id, qid)): Path<(String, String)>,
338+ Json(req): Json<UpdateQuestion>,
339+) -> Result<Json<QuestionResponse>, AppError> {
340+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
341+ .await?
342+ .ok_or(AppError::NotFound)?;
343+ let course = course_of(&exam, &st.db).await?;
344+ if !can_manage_course(&course, &user) {
345+ return Err(AppError::Forbidden(
346+ "only the course creator, an assigned teacher, or a manager/admin can edit questions",
347+ ));
348+ }
349+ // Reader lease of [`EXAM_LOCK`] for the subject check — see
350+ // `create_question`. The freeze gate rides in the update's transaction.
351+ let _guard = EXAM_LOCK.read().await;
352+ ensure_questions_editable(exam.get_id(), &st.db).await?;
353+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
354+
355+ let subject = match req.subject_id {
356+ Some(ref subject_id) => subject_in_course(subject_id, course.get_id(), &st.db).await?,
357+ None => question.get_subject().clone(),
358+ };
359+ let text = match req.text {
360+ Some(ref text) => QuestionText::try_new(text)?,
361+ None => question.get_text().clone(),
362+ };
363+ let points = match req.points {
364+ Some(points) => QuestionPoints::try_new(points)?,
365+ None => question.get_points(),
366+ };
367+ // Merge the kind-dependent fields (set / clear / keep per field), then
368+ // re-validate them as a unit — a PATCH can't leave a half-question behind.
369+ let kind = match req.kind {
370+ Some(ref kind) => QuestionKind::try_new(kind)?,
371+ None => question.get_kind().clone(),
372+ };
373+ // Omitting `choices` re-submits the stored options *with their ids*, so a
374+ // text-only edit keeps every identity (and every picture) untouched.
375+ let choices = match req.choices {
376+ Some(update) => ChoiceBody::into_inputs(update),
377+ None => ChoiceBody::from_stored(question.get_choices()),
378+ };
379+ let correct = match req.correct {
380+ Some(update) => update,
381+ None => question.get_correct().map(|id| id.as_str().to_string()),
382+ };
383+ let stored: Vec<Choice> = question.get_choices().unwrap_or_default().to_vec();
384+ let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?;
385+
386+ let updated = question.update(subject, text, points, spec, &st.db).await?;
387+ // Only the options that are actually *gone* lose their pictures: keyed by
388+ // choice id, an option that survives the edit keeps its image no matter
389+ // where it moved in the list. (This used to wipe every option picture
390+ // whenever the request so much as carried a `choices` key.)
391+ let keep: Vec<ChoiceId> = updated
392+ .get_choices()
393+ .unwrap_or_default()
394+ .iter()
395+ .map(|choice| choice.get_id().clone())
396+ .collect();
397+ for image in QuestionImage::delete_choices_not_in(updated.get_id(), &keep, &st.db).await? {
398+ remove_blob(&st.files_path, image.get_file()).await;
399+ }
400+ let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?;
401+ Ok(Json(QuestionResponse::new(&updated, &images)))
402+}
403+
404+/// Remove a question (and every answer to it). Requires teacher+ and
405+/// management rights over the exam's course. Locked once attempts exist.
406+#[utoipa::path(
407+ delete,
408+ path = "/{id}/questions/{qid}",
409+ tag = "exams",
410+ security(("session_cookie" = [])),
411+ params(
412+ ("id" = String, Path, description = "Exam id"),
413+ ("qid" = String, Path, description = "Question id"),
414+ ),
415+ responses(
416+ (status = 204, description = "Deleted"),
417+ (status = 401, description = "Not authenticated", body = ErrorResponse),
418+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
419+ (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse),
420+ (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
421+ ),
422+)]
423+pub(crate) async fn delete_question(
424+ State(st): State<AppState>,
425+ RequireTeacher(user): RequireTeacher,
426+ Path((id, qid)): Path<(String, String)>,
427+) -> Result<StatusCode, AppError> {
428+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
429+ .await?
430+ .ok_or(AppError::NotFound)?;
431+ let course = course_of(&exam, &st.db).await?;
432+ if !can_manage_course(&course, &user) {
433+ return Err(AppError::Forbidden(
434+ "only the course creator, an assigned teacher, or a manager/admin can delete questions",
435+ ));
436+ }
437+ // No lock: the freeze gate is part of the delete's own transaction, and
438+ // this path checks no subject. The pre-flight below is the fast 409.
439+ ensure_questions_editable(exam.get_id(), &st.db).await?;
440+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
441+ // Rows go first (the delete cascades them), blobs after — a crash in
442+ // between strands at worst an unreachable blob.
443+ let images = QuestionImage::list_for_question(question.get_id(), &st.db).await?;
444+ question.delete(&st.db).await?;
445+ for image in &images {
446+ remove_blob(&st.files_path, image.get_file()).await;
447+ }
448+ Ok(StatusCode::NO_CONTENT)
449+}
450+
451+// ---- question bank bridge ---------------------------------------------------
452+// Two copy funnels between an exam's questions and the school-wide bank
453+// (`web/bank_questions`): instantiate a template into this exam, or save one of
454+// this exam's questions back into the bank. Both COPY the row and every image
455+// blob to fresh ids/files — the source side is never touched or shared.
456+
457+#[derive(Deserialize, ToSchema)]
458+pub(crate) struct InstantiateFromBank {
459+ /// The subject to file the new question under — one of the exam's course's
460+ /// subjects (the same-course rule the bank row itself is exempt from).
461+ #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
462+ subject_id: String,
463+}
464+
465+/// Instantiate a bank template into this exam as a fresh question. Requires
466+/// teacher+, management rights over the exam's course, and a template the
467+/// caller may see (their own, or one published to the school) — anything else
468+/// is a 404. `subject_id` must
469+/// name one of the course's subjects — the template's own subject is origin
470+/// metadata and does not carry over. The template (and its blobs) stay
471+/// untouched; a full copy — text, points, spec, illustration, and option
472+/// pictures — lands under a new question id. Locked once attempts exist.
473+#[utoipa::path(
474+ post,
475+ path = "/{id}/questions/from-bank/{bid}",
476+ tag = "exams",
477+ security(("session_cookie" = [])),
478+ params(
479+ ("id" = String, Path, description = "Exam id"),
480+ ("bid" = String, Path, description = "Bank question id"),
481+ ),
482+ request_body = InstantiateFromBank,
483+ responses(
484+ (status = 201, description = "Question created from the template", body = QuestionResponse),
485+ (status = 400, description = "Unknown subject, or one from another course", body = ErrorResponse),
486+ (status = 401, description = "Not authenticated", body = ErrorResponse),
487+ (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),
489+ (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
490+ ),
491+)]
492+pub(crate) async fn question_from_bank(
493+ State(st): State<AppState>,
494+ RequireTeacher(user): RequireTeacher,
495+ Path((id, bid)): Path<(String, String)>,
496+ Json(req): Json<InstantiateFromBank>,
497+) -> Result<(StatusCode, Json<QuestionResponse>), AppError> {
498+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
499+ .await?
500+ .ok_or(AppError::NotFound)?;
501+ let course = course_of(&exam, &st.db).await?;
502+ if !can_manage_course(&course, &user) {
503+ return Err(AppError::Forbidden(
504+ "only the course creator, an assigned teacher, or a manager/admin can author questions",
505+ ));
506+ }
507+ // Reader lease of [`EXAM_LOCK`] for the subject check — same reasoning as
508+ // `create_question`. The freeze gate rides in the insert's transaction.
509+ let _guard = EXAM_LOCK.read().await;
510+ ensure_questions_editable(exam.get_id(), &st.db).await?;
511+ let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;
512+
513+ let template = BankQuestion::read(&BankQuestionId::from_key(&bid), &st.db)
514+ .await?
515+ .ok_or(AppError::NotFound)?;
516+ // A template the caller may not see is a 404, exactly as it is on the bank's
517+ // own routes — instantiating is a read of `correct`, and a 403 here would
518+ // confirm that someone else's private template exists under that id.
519+ if !crate::web::bank_questions::can_see(&template, &user) {
520+ return Err(AppError::NotFound);
521+ }
522+ let question = ExamQuestion::create_from_bank(
523+ exam.get_id(),
524+ subject,
525+ template.get_text().clone(),
526+ template.get_points(),
527+ template.spec(),
528+ template.get_id().clone(),
529+ &st.db,
530+ )
531+ .await?;
532+
533+ // Copy each of the template's image blobs to a fresh file under the new
534+ // question + same slot (file before row, via `store_image`). A missing
535+ // source blob is server-side damage, surfaced as a 500 — not silently lost.
536+ // The copy is all-or-nothing: any mid-loop failure rolls back the fresh
537+ // question row (its cascade drops the copied image rows) and the blobs
538+ // written so far, leaving the source and destination untouched.
539+ let sources = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?;
540+ let mut copied: Vec<String> = Vec::new();
541+ for source in &sources {
542+ let step = async {
543+ let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file()))
544+ .await
545+ .map_err(|err| {
546+ AppError::Internal(format!(
547+ "missing blob for bank image {}: {err}",
548+ source.get_file()
549+ ))
550+ })?;
551+ store_image(
552+ &st,
553+ &exam,
554+ &question,
555+ source.get_slot(),
556+ source.get_content_type().clone(),
557+ &bytes,
558+ )
559+ .await
560+ };
561+ match step.await {
562+ Ok(image) => copied.push(image.get_file().to_string()),
563+ Err(err) => {
564+ for file in &copied {
565+ remove_blob(&st.files_path, file).await;
566+ }
567+ let _ = question.delete(&st.db).await;
568+ return Err(err);
569+ }
570+ }
571+ }
572+ let images = QuestionImage::list_for_question(question.get_id(), &st.db).await?;
573+ Ok((
574+ StatusCode::CREATED,
575+ Json(QuestionResponse::new(&question, &images)),
576+ ))
577+}
578+
579+/// Re-copy a bank template's *current* content over the exam question that was
580+/// instantiated from it — the escape hatch for the divergence a deep copy
581+/// creates: fixing a typo in the template does not reach the copies, so this is
582+/// how a copy is brought back in line, explicitly and per question. Requires
583+/// teacher+, management rights over the exam's course, and a template the
584+/// caller may still see.
585+///
586+/// Replaces text, points, kind, choices, `correct`, the illustration, and the
587+/// option pictures with the template's; the question keeps its own id, its
588+/// exam, its `subject` (exam-course-scoped — the template's subject is
589+/// unrelated metadata) and its provenance links. Anything edited on the exam
590+/// copy since it was inserted is overwritten.
591+///
592+/// **Choice ids come from the template**, exactly as
593+/// [`question_from_bank`] mints them — the copy adopts the template's ids, so
594+/// its option pictures key off the same slots the template's do, and a
595+/// re-copy after a template edit re-lands the right picture on the right
596+/// option. A recorded `selected` can never be stranded by that: the freeze
597+/// below refuses the whole route once *any* attempt exists, and an
598+/// `exam_answer` only exists under an attempt — so at refresh time no answer
599+/// points at any choice id at all.
600+///
601+/// - No `from_bank` (never came from the bank, or its template was deleted and
602+/// the cascade cleared the link) → `400`; there is nothing to refresh from.
603+/// - Template gone or not visible to the caller → `404`, never a 403.
604+/// - Any attempt started → `409`, the same `ensure_questions_editable` freeze
605+/// every other question mutation answers to.
606+#[utoipa::path(
607+ post,
608+ path = "/{id}/questions/{qid}/refresh-from-bank",
609+ tag = "exams",
610+ security(("session_cookie" = [])),
611+ params(
612+ ("id" = String, Path, description = "Exam id"),
613+ ("qid" = String, Path, description = "Question id"),
614+ ),
615+ responses(
616+ (status = 200, description = "Question refreshed from its template", body = QuestionResponse),
617+ (status = 400, description = "The question did not come from the bank", body = ErrorResponse),
618+ (status = 401, description = "Not authenticated", body = ErrorResponse),
619+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
620+ (status = 404, description = "No such exam, no such question in it, or no bank template the caller may see", body = ErrorResponse),
621+ (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
622+ ),
623+)]
624+pub(crate) async fn question_refresh_from_bank(
625+ State(st): State<AppState>,
626+ RequireTeacher(user): RequireTeacher,
627+ Path((id, qid)): Path<(String, String)>,
628+) -> Result<Json<QuestionResponse>, AppError> {
629+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
630+ .await?
631+ .ok_or(AppError::NotFound)?;
632+ let course = course_of(&exam, &st.db).await?;
633+ if !can_manage_course(&course, &user) {
634+ return Err(AppError::Forbidden(
635+ "only the course creator, an assigned teacher, or a manager/admin can edit questions",
636+ ));
637+ }
638+ // No lock: the question keeps its own subject here, so there is nothing to
639+ // pair with a subject delete, and the freeze gate rides in the overwrite's
640+ // transaction.
641+ ensure_questions_editable(exam.get_id(), &st.db).await?;
642+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
643+
644+ let Some(source) = question.get_from_bank().cloned() else {
645+ return Err(AppError::Validation(ValidationError::Invalid {
646+ field: "question",
647+ reason: "this question did not come from a bank template",
648+ }));
649+ };
650+ let template = BankQuestion::read(&source, &st.db)
651+ .await?
652+ .ok_or(AppError::NotFound)?;
653+ if !crate::web::bank_questions::can_see(&template, &user) {
654+ return Err(AppError::NotFound);
655+ }
656+
657+ // Every source blob is read up front, *before* anything is written: a
658+ // missing one is server-side damage and must surface as a 500 with the
659+ // question untouched, since a half-applied refresh has no old content left
660+ // to roll back to. Bounded — at most one illustration plus ten option
661+ // pictures, each under the school's file cap.
662+ let sources = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?;
663+ let mut incoming: Vec<(&BankQuestionImage, Vec<u8>)> = Vec::with_capacity(sources.len());
664+ for source in &sources {
665+ let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file()))
666+ .await
667+ .map_err(|err| {
668+ AppError::Internal(format!(
669+ "missing blob for bank image {}: {err}",
670+ source.get_file()
671+ ))
672+ })?;
673+ incoming.push((source, bytes));
674+ }
675+
676+ // The question's own subject stays: it is checked against the exam's
677+ // course, and the template's is origin metadata from anywhere in school.
678+ let subject = question.get_subject().clone();
679+ // `spec()` hands over the template's stored choices *with their ids* rather
680+ // than re-minting any — the same funnel `question_from_bank` uses.
681+ let updated = question
682+ .update(
683+ subject,
684+ template.get_text().clone(),
685+ template.get_points(),
686+ template.spec(),
687+ &st.db,
688+ )
689+ .await?;
690+
691+ // Make the pictures match the template exactly: drop every slot the
692+ // template has no picture for (including the illustration, and every option
693+ // that is gone after the re-copy), then write the template's over the rest.
694+ // `store_image` upserts per slot, so a slot both sides have is replaced.
695+ let incoming_slots: Vec<Option<&ChoiceId>> =
696+ incoming.iter().map(|(image, _)| image.get_slot()).collect();
697+ for stale in QuestionImage::list_for_question(updated.get_id(), &st.db).await? {
698+ if incoming_slots.contains(&stale.get_slot()) {
699+ continue;
700+ }
701+ let file = stale.get_file().to_string();
702+ stale.delete(&st.db).await?;
703+ remove_blob(&st.files_path, &file).await;
704+ }
705+ for (source, bytes) in &incoming {
706+ store_image(
707+ &st,
708+ &exam,
709+ &updated,
710+ source.get_slot(),
711+ source.get_content_type().clone(),
712+ bytes,
713+ )
714+ .await?;
715+ }
716+
717+ let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?;
718+ Ok(Json(QuestionResponse::new(&updated, &images)))
719+}
720+
721+/// Save one of this exam's questions into the school-wide bank as a reusable
722+/// template. Requires teacher+ and management rights over the exam's course.
723+/// The caller becomes the template's owner; the question's subject rides along
724+/// as origin metadata. A full copy — text, points, spec, illustration, and
725+/// option pictures — lands under a new bank id. Provenance rides both ways: the
726+/// origin exam is recorded on the template as `source_exam`, and the exam
727+/// question's `banked_as` is pointed at the new template (a repeat save is
728+/// allowed and repoints it at the newest one). `from_bank` is left alone — it
729+/// records the other direction and a save never changes where a question came
730+/// from.
731+#[utoipa::path(
732+ post,
733+ path = "/{id}/questions/{qid}/to-bank",
734+ tag = "exams",
735+ security(("session_cookie" = [])),
736+ params(
737+ ("id" = String, Path, description = "Exam id"),
738+ ("qid" = String, Path, description = "Question id"),
739+ ),
740+ responses(
741+ (status = 201, description = "Template saved to the bank", body = BankQuestionResponse),
742+ (status = 401, description = "Not authenticated", body = ErrorResponse),
743+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
744+ (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse),
745+ ),
746+)]
747+pub(crate) async fn question_to_bank(
748+ State(st): State<AppState>,
749+ RequireTeacher(user): RequireTeacher,
750+ Path((id, qid)): Path<(String, String)>,
751+) -> Result<(StatusCode, Json<BankQuestionResponse>), AppError> {
752+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
753+ .await?
754+ .ok_or(AppError::NotFound)?;
755+ let course = course_of(&exam, &st.db).await?;
756+ if !can_manage_course(&course, &user) {
757+ return Err(AppError::Forbidden(
758+ "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank",
759+ ));
760+ }
761+ // Reader lease of [`BANK_LOCK`] across the question read and the insert: the
762+ // template adopts the question's subject, so without it a subject delete
763+ // could slip between the two and leave the fresh template pointing at a
764+ // subject its cascade had already swept (that cascade runs under BANK_LOCK's
765+ // writer lease, so holding the reader lease orders us either side of it).
766+ let _bank_guard = crate::web::bank_questions::BANK_LOCK.read().await;
767+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
768+
769+ // `create_from_exam` mints its own id and insert (the funnel), fed the
770+ // question's fields plus the origin exam it was saved off.
771+ let template = BankQuestion::create_from_exam(
772+ user.get_id().clone(),
773+ question.get_subject().clone(),
774+ question.get_text().clone(),
775+ question.get_points(),
776+ question.spec(),
777+ exam.get_id().clone(),
778+ &st.db,
779+ )
780+ .await?;
781+
782+ // Copy every image blob (illustration + option pictures) to a fresh file
783+ // under the new bank row + same slot (file before row). All-or-nothing: a
784+ // mid-loop failure rolls back the fresh bank row (cascade drops the copied
785+ // image rows) and the blobs written so far; the source exam question stays
786+ // untouched.
787+ let sources = QuestionImage::list_for_question(question.get_id(), &st.db).await?;
788+ let mut copied: Vec<String> = Vec::new();
789+ for source in &sources {
790+ let step = async {
791+ let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file()))
792+ .await
793+ .map_err(|err| {
794+ AppError::Internal(format!(
795+ "missing blob for question image {}: {err}",
796+ source.get_file()
797+ ))
798+ })?;
799+ crate::web::bank_questions::store_image(
800+ &st,
801+ template.get_id(),
802+ source.get_slot(),
803+ source.get_content_type().clone(),
804+ &bytes,
805+ )
806+ .await
807+ };
808+ match step.await {
809+ Ok(image) => copied.push(image.get_file().to_string()),
810+ Err(err) => {
811+ for file in &copied {
812+ remove_blob(&st.files_path, file).await;
813+ }
814+ let _ = template.delete(&st.db).await;
815+ return Err(err);
816+ }
817+ }
818+ }
819+ // Provenance back-link, so a client can tell this question was already
820+ // banked: the question points at the template it was saved into, and a
821+ // repeat save repoints it at the newest one (never blocked). Written only
822+ // after the all-or-nothing copy above, so a rolled-back template can never
823+ // leave a dangling link. A failure here is logged and swallowed rather than
824+ // rolling the template back: the save is the user's actual work and a
825+ // template silently vanishing over a metadata write is worse than a
826+ // template with no back-link (the next save re-links it).
827+ let question_key = question.get_id().key().to_string();
828+ // The bank lease has done its job (the template is inserted, its subject
829+ // pinned); hand it back before the link write.
830+ drop(_bank_guard);
831+ // No exam lease around the back-link any more, and none is needed: this is a
832+ // single-column `UPDATE`, and `ExamQuestion::update` no longer re-states
833+ // this column from a snapshot (it names the columns it writes), so a
834+ // question edit racing the link cannot revert it. That lease existed only to
835+ // order those two, and the ordering requirement is gone with the whole-row
836+ // save that created it.
837+ if let Err(err) = question
838+ .link_banked_as(template.get_id().clone(), &st.db)
839+ .await
840+ {
841+ tracing::warn!(
842+ "saved question {question_key} to the bank but could not link it back: {err}"
843+ );
844+ }
845+
846+ let images = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?;
847+ Ok((
848+ StatusCode::CREATED,
849+ Json(BankQuestionResponse::new(&template, &images)),
850+ ))
851+}
src/web/exams/review.rsadded+314 -0
@@ -0,0 +1,314 @@
1+use super::*;
2+
3+// ---- per-attempt history ----------------------------------------------------
4+// The grading views above show the latest sitting; these expose every prior
5+// sitting a re-taking student left behind. Same wall as grading: teacher+ who
6+// manages the exam's course. A student never reaches another student's sheet,
7+// and a student's own prior attempts are staff-visible by design.
8+
9+/// The exam plus the manage-rights check the grading and history reads share.
10+pub(crate) async fn gradable_exam(st: &AppState, user: &User, id: &str) -> Result<Exam, AppError> {
11+ let exam = Exam::read(&ExamId::from_key(id), &st.db)
12+ .await?
13+ .ok_or(AppError::NotFound)?;
14+ let course = course_of(&exam, &st.db).await?;
15+ if !can_manage_course(&course, user) {
16+ return Err(AppError::Forbidden(
17+ "only the course creator, an assigned teacher, or a manager/admin can read answer sheets",
18+ ));
19+ }
20+ Ok(exam)
21+}
22+
23+/// The sitting numbers a student has left at an exam — every seq that carries
24+/// answers or a mark, ascending. Requires teacher+ and management rights over
25+/// the exam's course. Drives the FE's attempt-by-attempt picker.
26+#[utoipa::path(
27+ get,
28+ path = "/{id}/students/{user}/attempts",
29+ tag = "exams",
30+ security(("session_cookie" = [])),
31+ params(
32+ ("id" = String, Path, description = "Exam id"),
33+ ("user" = String, Path, description = "User id"),
34+ ),
35+ responses(
36+ (status = 200, description = "The student's sitting numbers, ascending", body = [i64]),
37+ (status = 401, description = "Not authenticated", body = ErrorResponse),
38+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
39+ (status = 404, description = "Exam not found", body = ErrorResponse),
40+ ),
41+)]
42+pub(crate) async fn student_attempts(
43+ State(st): State<AppState>,
44+ RequireTeacher(user): RequireTeacher,
45+ Path((id, target)): Path<(String, String)>,
46+) -> Result<Json<Vec<i64>>, AppError> {
47+ let exam = gradable_exam(&st, &user, &id).await?;
48+ let target = UserId::from_key(&target);
49+ let mut seqs = ExamAnswer::list_seqs_for_user(exam.get_id(), &target, &st.db).await?;
50+ for result in ExamResult::list_all_for_exam_user(exam.get_id(), &target, &st.db).await? {
51+ seqs.push(result.get_seq());
52+ }
53+ seqs.sort_unstable();
54+ seqs.dedup();
55+ Ok(Json(seqs))
56+}
57+
58+/// One prior sitting's judged answer sheet — the `seq`th attempt's answers,
59+/// drawing refs, correctness flags, and auto-score suggestion. Requires
60+/// teacher+ and management rights over the exam's course. Serves an empty
61+/// sheet for a seq the student never wrote in.
62+#[utoipa::path(
63+ get,
64+ path = "/{id}/students/{user}/attempts/{seq}/answers",
65+ tag = "exams",
66+ security(("session_cookie" = [])),
67+ params(
68+ ("id" = String, Path, description = "Exam id"),
69+ ("user" = String, Path, description = "User id"),
70+ ("seq" = i64, Path, description = "Sitting number (1, 2, …)"),
71+ ),
72+ responses(
73+ (status = 200, description = "That sitting's answers, judged", body = AttemptAnswersResponse),
74+ (status = 401, description = "Not authenticated", body = ErrorResponse),
75+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
76+ (status = 404, description = "Exam not found", body = ErrorResponse),
77+ ),
78+)]
79+pub(crate) async fn student_attempt_answers(
80+ State(st): State<AppState>,
81+ RequireTeacher(user): RequireTeacher,
82+ Path((id, target, seq)): Path<(String, String, i64)>,
83+) -> Result<Json<AttemptAnswersResponse>, AppError> {
84+ let exam = gradable_exam(&st, &user, &id).await?;
85+ let target = UserId::from_key(&target);
86+ Ok(Json(answer_sheet(&exam, &target, seq, &st.db).await?))
87+}
88+
89+/// A prior sitting's drawn-answer bytes. Requires teacher+ and management
90+/// rights over the exam's course — the seq-scoped mirror of the grader's
91+/// latest-sitting drawing read.
92+#[utoipa::path(
93+ get,
94+ path = "/{id}/students/{user}/attempts/{seq}/answers/{qid}/image",
95+ tag = "exams",
96+ security(("session_cookie" = [])),
97+ params(
98+ ("id" = String, Path, description = "Exam id"),
99+ ("user" = String, Path, description = "User id"),
100+ ("seq" = i64, Path, description = "Sitting number (1, 2, …)"),
101+ ("qid" = String, Path, description = "Question id"),
102+ ),
103+ responses(
104+ (status = 200, description = "The student's drawing bytes", content_type = "image/*"),
105+ (status = 401, description = "Not authenticated", body = ErrorResponse),
106+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
107+ (status = 404, description = "No such exam, question, or drawing", body = ErrorResponse),
108+ ),
109+)]
110+pub(crate) async fn student_attempt_answer_image(
111+ State(st): State<AppState>,
112+ RequireTeacher(user): RequireTeacher,
113+ Path((id, target, seq, qid)): Path<(String, String, i64, String)>,
114+) -> Result<Response, AppError> {
115+ let exam = gradable_exam(&st, &user, &id).await?;
116+ let target = UserId::from_key(&target);
117+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
118+ let image = AnswerImage::read(question.get_id(), &target, seq, &st.db)
119+ .await?
120+ .ok_or(AppError::NotFound)?;
121+ crate::web::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await
122+}
123+
124+/// A student's full mark history at an exam — every sitting's mark, oldest
125+/// first (the grade-of-record is the latest). Requires teacher+ and management
126+/// rights over the exam's course.
127+#[utoipa::path(
128+ get,
129+ path = "/{id}/students/{user}/marks",
130+ tag = "exams",
131+ security(("session_cookie" = [])),
132+ params(
133+ ("id" = String, Path, description = "Exam id"),
134+ ("user" = String, Path, description = "User id"),
135+ ),
136+ responses(
137+ (status = 200, description = "The student's per-sitting marks, oldest first", body = [ExamResultResponse]),
138+ (status = 401, description = "Not authenticated", body = ErrorResponse),
139+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
140+ (status = 404, description = "Exam not found", body = ErrorResponse),
141+ ),
142+)]
143+pub(crate) async fn student_marks_history(
144+ State(st): State<AppState>,
145+ RequireTeacher(user): RequireTeacher,
146+ Path((id, target)): Path<(String, String)>,
147+) -> Result<Json<Vec<ExamResultResponse>>, AppError> {
148+ let exam = gradable_exam(&st, &user, &id).await?;
149+ let target = UserId::from_key(&target);
150+ let results = ExamResult::list_all_for_exam_user(exam.get_id(), &target, &st.db).await?;
151+ let people = person_map(
152+ results
153+ .iter()
154+ .flat_map(|r| [r.get_user().clone(), r.get_graded_by().clone()]),
155+ &st.db,
156+ )
157+ .await?;
158+ Ok(Json(
159+ results
160+ .iter()
161+ .map(|r| ExamResultResponse::new(r, &people))
162+ .collect(),
163+ ))
164+}
165+
166+// ---- student self-review ----------------------------------------------------
167+// The mirror of the teacher history reads above, but own-scoped: no `{user}`
168+// path param, so the target is always the caller — a student can never reach
169+// another student's sheet. Opens only once the teacher enables review AND has
170+// marked this student (an ExamResult row proves it).
171+
172+/// The exam plus the per-student review gate the three self-review reads share.
173+/// 404 if the exam is missing or still a draft, 403 if review is off for it, and
174+/// 404 until the caller has a mark on it (nothing to review yet).
175+pub(crate) async fn reviewable_exam(
176+ st: &AppState,
177+ user: &User,
178+ id: &str,
179+) -> Result<Exam, AppError> {
180+ let exam = Exam::read(&ExamId::from_key(id), &st.db)
181+ .await?
182+ .ok_or(AppError::NotFound)?;
183+ if exam.is_draft() {
184+ return Err(AppError::NotFound);
185+ }
186+ if !exam.get_allow_review() {
187+ return Err(AppError::Forbidden("review not enabled for this exam"));
188+ }
189+ ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
190+ .await?
191+ .ok_or(AppError::NotFound)?;
192+ Ok(exam)
193+}
194+
195+/// The caller's own sitting numbers at an exam — every seq that carries answers
196+/// or a mark, ascending. Own-scoped review view; opens once the teacher enables
197+/// review and has marked the caller.
198+#[utoipa::path(
199+ get,
200+ path = "/{id}/review/attempts",
201+ tag = "exams",
202+ security(("session_cookie" = [])),
203+ params(("id" = String, Path, description = "Exam id")),
204+ responses(
205+ (status = 200, description = "The caller's own sitting numbers, ascending", body = [i64]),
206+ (status = 401, description = "Not authenticated", body = ErrorResponse),
207+ (status = 403, description = "Review not enabled for this exam", body = ErrorResponse),
208+ (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse),
209+ ),
210+)]
211+pub(crate) async fn review_attempts(
212+ State(st): State<AppState>,
213+ CurrentUser(user): CurrentUser,
214+ Path(id): Path<String>,
215+) -> Result<Json<Vec<i64>>, AppError> {
216+ let exam = reviewable_exam(&st, &user, &id).await?;
217+ let target = user.get_id().clone();
218+ let mut seqs = ExamAnswer::list_seqs_for_user(exam.get_id(), &target, &st.db).await?;
219+ for result in ExamResult::list_all_for_exam_user(exam.get_id(), &target, &st.db).await? {
220+ seqs.push(result.get_seq());
221+ }
222+ seqs.sort_unstable();
223+ seqs.dedup();
224+ Ok(Json(seqs))
225+}
226+
227+/// The exam's full question list, `correct` choice ids included — the answer key
228+/// the caller reviews their own sheet against. Same review gate as the other
229+/// self-review reads; revealing `correct` is the point (the gate already proves
230+/// the caller was marked). Paged via `?limit=&offset=`.
231+#[utoipa::path(
232+ get,
233+ path = "/{id}/review/questions",
234+ tag = "exams",
235+ security(("session_cookie" = [])),
236+ params(("id" = String, Path, description = "Exam id"), PageParams),
237+ responses(
238+ (status = 200, description = "A page of the exam's questions with `correct` (all of them when unpaged)", body = Page<QuestionResponse>),
239+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
240+ (status = 401, description = "Not authenticated", body = ErrorResponse),
241+ (status = 403, description = "Review not enabled for this exam", body = ErrorResponse),
242+ (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse),
243+ ),
244+)]
245+pub(crate) async fn review_questions(
246+ State(st): State<AppState>,
247+ CurrentUser(user): CurrentUser,
248+ Path(id): Path<String>,
249+ Query(page): Query<PageParams>,
250+) -> Result<Json<Page<QuestionResponse>>, AppError> {
251+ let (limit, offset) = page.resolve()?;
252+ let exam = reviewable_exam(&st, &user, &id).await?;
253+ Ok(Json(question_page(&exam, limit, offset, &st.db).await?))
254+}
255+
256+/// One of the caller's own sittings, judged — the `seq`th attempt's answers,
257+/// drawing refs, correctness flags, and auto-score suggestion. Own-scoped
258+/// review view.
259+#[utoipa::path(
260+ get,
261+ path = "/{id}/review/attempts/{seq}/answers",
262+ tag = "exams",
263+ security(("session_cookie" = [])),
264+ params(
265+ ("id" = String, Path, description = "Exam id"),
266+ ("seq" = i64, Path, description = "Sitting number (1, 2, …)"),
267+ ),
268+ responses(
269+ (status = 200, description = "That sitting's answers, judged", body = AttemptAnswersResponse),
270+ (status = 401, description = "Not authenticated", body = ErrorResponse),
271+ (status = 403, description = "Review not enabled for this exam", body = ErrorResponse),
272+ (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse),
273+ ),
274+)]
275+pub(crate) async fn review_attempt_answers(
276+ State(st): State<AppState>,
277+ CurrentUser(user): CurrentUser,
278+ Path((id, seq)): Path<(String, i64)>,
279+) -> Result<Json<AttemptAnswersResponse>, AppError> {
280+ let exam = reviewable_exam(&st, &user, &id).await?;
281+ Ok(Json(answer_sheet(&exam, user.get_id(), seq, &st.db).await?))
282+}
283+
284+/// The caller's own drawn-answer bytes for one of their sittings — the
285+/// seq-scoped, own-scoped mirror of the grader's drawing read.
286+#[utoipa::path(
287+ get,
288+ path = "/{id}/review/attempts/{seq}/answers/{qid}/image",
289+ tag = "exams",
290+ security(("session_cookie" = [])),
291+ params(
292+ ("id" = String, Path, description = "Exam id"),
293+ ("seq" = i64, Path, description = "Sitting number (1, 2, …)"),
294+ ("qid" = String, Path, description = "Question id"),
295+ ),
296+ responses(
297+ (status = 200, description = "The caller's drawing bytes", content_type = "image/*"),
298+ (status = 401, description = "Not authenticated", body = ErrorResponse),
299+ (status = 403, description = "Review not enabled for this exam", body = ErrorResponse),
300+ (status = 404, description = "No such exam/question/drawing, a draft, or the caller has no mark on it", body = ErrorResponse),
301+ ),
302+)]
303+pub(crate) async fn review_attempt_answer_image(
304+ State(st): State<AppState>,
305+ CurrentUser(user): CurrentUser,
306+ Path((id, seq, qid)): Path<(String, i64, String)>,
307+) -> Result<Response, AppError> {
308+ let exam = reviewable_exam(&st, &user, &id).await?;
309+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
310+ let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db)
311+ .await?
312+ .ok_or(AppError::NotFound)?;
313+ crate::web::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await
314+}
src/web/homework.rsmodified+6 -2
@@ -192,6 +192,7 @@ async fn list_homework(
192 homework192 homework
193 };193 };
194 let total = homework.len() as i64;194 let total = homework.len() as i64;
195+ // Paged in the web layer: the audience filter above is per-row Rust.
195 let items = paginate(&homework, limit, offset)196 let items = paginate(&homework, limit, offset)
196 .iter()197 .iter()
197 .map(HomeworkResponse::new)198 .map(HomeworkResponse::new)
@@ -1201,8 +1202,9 @@ async fn list_homework_submissions(
1201 }1202 }
1202 let submissions = HomeworkSubmission::list_for_homework(homework.get_id(), &st.db).await?;1203 let submissions = HomeworkSubmission::list_for_homework(homework.get_id(), &st.db).await?;
1203 let results = HomeworkResult::list_for_homework(homework.get_id(), &st.db).await?;1204 let results = HomeworkResult::list_for_homework(homework.get_id(), &st.db).await?;
1204- let enrolled: Vec<String> = Enrollment::list_for_course(course.get_id(), &st.db)1205+ let enrolled: Vec<String> = Enrollment::list_for_course(course.get_id(), None, 0, &st.db)
1205 .await?1206 .await?
1207+ .0
1206 .iter()1208 .iter()
1207 .map(|enrollment| enrollment.get_user().key().to_string())1209 .map(|enrollment| enrollment.get_user().key().to_string())
1208 .collect();1210 .collect();
@@ -1232,6 +1234,7 @@ async fn list_homework_submissions(
1232 let total = users.len() as i64;1234 let total = users.len() as i64;
1233 // Join the heavy parts (the file lists) onto the page alone.1235 // Join the heavy parts (the file lists) onto the page alone.
1234 let mut items = Vec::new();1236 let mut items = Vec::new();
1237+ // Paged in the web layer: the audience is resolved in Rust.
1235 for user_key in paginate(&users, limit, offset) {1238 for user_key in paginate(&users, limit, offset) {
1236 let submission = match submissions1239 let submission = match submissions
1237 .iter()1240 .iter()
@@ -1325,7 +1328,7 @@ async fn homework_report(
1325 .ok_or(AppError::NotFound)?;1328 .ok_or(AppError::NotFound)?;
1326 // Only an exactly-teacher caller is narrowed to their managed courses;1329 // Only an exactly-teacher caller is narrowed to their managed courses;
1327 // manager+ and a linked parent read the full report (the marks idiom).1330 // manager+ and a linked parent read the full report (the marks idiom).
1328- let mut courses = Course::list_enrolled(&target, &st.db).await?;1331+ let (mut courses, _) = Course::list_enrolled(&target, None, 0, &st.db).await?;
1329 if caller.get_role() == Role::Teacher {1332 if caller.get_role() == Role::Teacher {
1330 courses.retain(|course| can_manage_course(course, &caller));1333 courses.retain(|course| can_manage_course(course, &caller));
1331 }1334 }
@@ -1336,6 +1339,7 @@ async fn homework_report(
1336 let total = rows.len() as i64;1339 let total = rows.len() as i64;
1337 // Join submissions and grades onto the page alone.1340 // Join submissions and grades onto the page alone.
1338 let mut items = Vec::new();1341 let mut items = Vec::new();
1342+ // Paged in the web layer: the rows are gathered course by course.
1339 for homework in paginate(&rows, limit, offset) {1343 for homework in paginate(&rows, limit, offset) {
1340 let submission = HomeworkSubmission::read_for(homework.get_id(), &target, &st.db).await?;1344 let submission = HomeworkSubmission::read_for(homework.get_id(), &target, &st.db).await?;
1341 let result = HomeworkResult::read_for(homework.get_id(), &target, &st.db).await?;1345 let result = HomeworkResult::read_for(homework.get_id(), &target, &st.db).await?;
src/web/image.rsadded+81 -0
@@ -0,0 +1,81 @@
1+//! The two halves every image upload shares, whatever the picture hangs on
2+//! (exam question, bank template, pool question, solution, answer sheet):
3+//! reading the `file` part under the school's size limit and the raster
4+//! allowlist, and the blob-first write dance — fresh blob to disk, then the
5+//! row, then the replaced blob off disk, with any row failure taking the fresh
6+//! blob back out. A stored row therefore always points at a real blob, and a
7+//! failed write strands nothing.
8+//!
9+//! Gates stay at the call sites (the exam freeze, the pool's approval, owner
10+//! and author rules), as do the row types: this module owns only the
11+//! format/limit rule and the rollback, once each.
12+
13+use std::future::Future;
14+
15+use axum::extract::Multipart;
16+
17+use crate::domain::note_file::FileContentType;
18+use crate::domain::settings::Settings;
19+use crate::error::AppError;
20+use crate::state::AppState;
21+
22+use super::{blob_path, image_content_type, read_upload, remove_blob};
23+
24+/// A validated image upload: an allowlisted raster content type and the bytes.
25+pub(crate) struct ImageUpload {
26+ pub content_type: FileContentType,
27+ pub data: Vec<u8>,
28+}
29+
30+impl ImageUpload {
31+ pub(crate) fn size(&self) -> i64 {
32+ self.data.len() as i64
33+ }
34+}
35+
36+/// The multipart `file` part, held to the school's `max_file_bytes` and the
37+/// raster allowlist — the one place either rule is spelled, so a format or
38+/// limit change lands on every image endpoint at once.
39+pub(crate) async fn read_image_upload(
40+ st: &AppState,
41+ multipart: &mut Multipart,
42+) -> Result<ImageUpload, AppError> {
43+ let limit = Settings::load(&st.db).await?.get_max_file_bytes();
44+ let upload = read_upload(multipart, limit).await?;
45+ let content_type = image_content_type(&upload.content_type.unwrap_or_default())?;
46+ Ok(ImageUpload {
47+ content_type,
48+ data: upload.data,
49+ })
50+}
51+
52+/// Blob first, row second: `data` lands on disk under `file`, then `write_row`
53+/// runs. It returns what it stored plus the blob name it replaced (if any),
54+/// which comes off disk only once the row is safely written; any error takes
55+/// the fresh blob back out instead.
56+pub(crate) async fn store_blob<T, Fut>(
57+ st: &AppState,
58+ file: &str,
59+ data: &[u8],
60+ write_row: impl FnOnce() -> Fut,
61+) -> Result<T, AppError>
62+where
63+ Fut: Future<Output = Result<(T, Option<String>), AppError>>,
64+{
65+ let path = blob_path(&st.files_path, file);
66+ tokio::fs::write(&path, data)
67+ .await
68+ .map_err(|err| AppError::Internal(format!("failed to store the image blob: {err}")))?;
69+ match write_row().await {
70+ Ok((stored, replaced)) => {
71+ if let Some(replaced) = replaced {
72+ remove_blob(&st.files_path, &replaced).await;
73+ }
74+ Ok(stored)
75+ }
76+ Err(err) => {
77+ let _ = tokio::fs::remove_file(&path).await;
78+ Err(err)
79+ }
80+ }
81+}
src/web/marks.rsmodified+1 -1
@@ -95,7 +95,7 @@ async fn build_report(
95 viewer: Option<&User>,95 viewer: Option<&User>,
96 db: &Database,96 db: &Database,
97 ) -> Result<MarksReport, AppError> {97 ) -> Result<MarksReport, AppError> {
98- let mut courses = Course::list_enrolled(user, db).await?;98+ let (mut courses, _) = Course::list_enrolled(user, None, 0, db).await?;
99 if let Some(viewer) = viewer {99 if let Some(viewer) = viewer {
100 courses.retain(|course| can_manage_course(course, viewer));100 courses.retain(|course| can_manage_course(course, viewer));
101 }101 }
src/web/meals.rsmodified+21 -20
@@ -35,7 +35,7 @@ use crate::state::AppState;
35 35
36 use super::{36 use super::{
37 CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireManager, RequireTeacher,37 CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireManager, RequireTeacher,
38- paginate, person_map, set_or_clear,38+ person_map, set_or_clear,
39 };39 };
40 40
41 pub fn routes() -> OpenApiRouter<AppState> {41 pub fn routes() -> OpenApiRouter<AppState> {
@@ -283,10 +283,9 @@ async fn list_menus(
283 let (limit, offset) = page.resolve()?;283 let (limit, offset) = page.resolve()?;
284 let from = range.from.as_deref().map(MenuDate::try_new).transpose()?;284 let from = range.from.as_deref().map(MenuDate::try_new).transpose()?;
285 let to = range.to.as_deref().map(MenuDate::try_new).transpose()?;285 let to = range.to.as_deref().map(MenuDate::try_new).transpose()?;
286- let menus = Menu::list(from.as_ref(), to.as_ref(), &st.db).await?;286+ let (menus, total) = Menu::list(from.as_ref(), to.as_ref(), limit, offset, &st.db).await?;
287- let total = menus.len() as i64;
288 // The dish/people join runs over the page alone, so it shrinks with it.287 // The dish/people join runs over the page alone, so it shrinks with it.
289- let items = menu_responses(paginate(&menus, limit, offset), user.get_id(), &st.db).await?;288+ let items = menu_responses(&menus, user.get_id(), &st.db).await?;
290 Ok(Json(Page::new(items, total, limit, offset)))289 Ok(Json(Page::new(items, total, limit, offset)))
291 }290 }
292 291
@@ -870,9 +869,8 @@ async fn my_bookings(
870 .map(|link| link.get_student().clone()),869 .map(|link| link.get_student().clone()),
871 );870 );
872 }871 }
873- let rows = MealBooking::list_for_students(&students, &st.db).await?;872+ let (rows, total) = MealBooking::list_for_students(&students, limit, offset, &st.db).await?;
874- let total = rows.len() as i64;873+ let items = booking_responses(&rows, &st.db).await?;
875- let items = booking_responses(paginate(&rows, limit, offset), &st.db).await?;
876 Ok(Json(Page::new(items, total, limit, offset)))874 Ok(Json(Page::new(items, total, limit, offset)))
877 }875 }
878 876
@@ -903,9 +901,8 @@ async fn list_menu_bookings(
903 let menu = Menu::read(&MenuId::from_key(&id), &st.db)901 let menu = Menu::read(&MenuId::from_key(&id), &st.db)
904 .await?902 .await?
905 .ok_or(AppError::NotFound)?;903 .ok_or(AppError::NotFound)?;
906- let rows = MealBooking::list_for_menu(menu.get_id(), &st.db).await?;904+ let (rows, total) = MealBooking::list_for_menu(menu.get_id(), limit, offset, &st.db).await?;
907- let total = rows.len() as i64;905+ let items = booking_responses(&rows, &st.db).await?;
908- let items = booking_responses(paginate(&rows, limit, offset), &st.db).await?;
909 Ok(Json(Page::new(items, total, limit, offset)))906 Ok(Json(Page::new(items, total, limit, offset)))
910 }907 }
911 908
@@ -1094,9 +1091,8 @@ async fn list_menu_attendance(
1094 let menu = Menu::read(&MenuId::from_key(&id), &st.db)1091 let menu = Menu::read(&MenuId::from_key(&id), &st.db)
1095 .await?1092 .await?
1096 .ok_or(AppError::NotFound)?;1093 .ok_or(AppError::NotFound)?;
1097- let rows = MealAttendance::list_for_menu(menu.get_id(), &st.db).await?;1094+ let (rows, total) = MealAttendance::list_for_menu(menu.get_id(), limit, offset, &st.db).await?;
1098- let total = rows.len() as i64;1095+ let items = attendance_responses(&rows, &st.db).await?;
1099- let items = attendance_responses(paginate(&rows, limit, offset), &st.db).await?;
1100 Ok(Json(Page::new(items, total, limit, offset)))1096 Ok(Json(Page::new(items, total, limit, offset)))
1101 }1097 }
1102 1098
@@ -1129,10 +1125,16 @@ async fn user_attendance(
1129 ensure_can_read_student(&caller, &target, &st.db).await?;1125 ensure_can_read_student(&caller, &target, &st.db).await?;
1130 let from = range.from.as_deref().map(MenuDate::try_new).transpose()?;1126 let from = range.from.as_deref().map(MenuDate::try_new).transpose()?;
1131 let to = range.to.as_deref().map(MenuDate::try_new).transpose()?;1127 let to = range.to.as_deref().map(MenuDate::try_new).transpose()?;
1132- let rows =1128+ let (rows, total) = MealAttendance::list_for_student(
1133- MealAttendance::list_for_student(&target, from.as_ref(), to.as_ref(), &st.db).await?;1129+ &target,
1134- let total = rows.len() as i64;1130+ from.as_ref(),
1135- let items = attendance_responses(paginate(&rows, limit, offset), &st.db).await?;1131+ to.as_ref(),
1132+ limit,
1133+ offset,
1134+ &st.db,
1135+ )
1136+ .await?;
1137+ let items = attendance_responses(&rows, &st.db).await?;
1136 Ok(Json(Page::new(items, total, limit, offset)))1138 Ok(Json(Page::new(items, total, limit, offset)))
1137 }1139 }
1138 1140
@@ -1296,9 +1298,8 @@ async fn user_ledger(
1296 let (limit, offset) = page.resolve()?;1298 let (limit, offset) = page.resolve()?;
1297 let target = UserId::from_key(&user);1299 let target = UserId::from_key(&user);
1298 ensure_can_read_student(&caller, &target, &st.db).await?;1300 ensure_can_read_student(&caller, &target, &st.db).await?;
1299- let rows = MealLedger::list_for_student(&target, &st.db).await?;1301+ let (rows, total) = MealLedger::list_for_student(&target, limit, offset, &st.db).await?;
1300- let total = rows.len() as i64;1302+ let items = ledger_responses(&rows, &st.db).await?;
1301- let items = ledger_responses(paginate(&rows, limit, offset), &st.db).await?;
1302 Ok(Json(Page::new(items, total, limit, offset)))1303 Ok(Json(Page::new(items, total, limit, offset)))
1303 }1304 }
1304 1305
src/web/messages.rsmodified+5 -6
@@ -17,7 +17,7 @@ use crate::error::{AppError, ErrorResponse, ValidationError};
17 use crate::state::AppState;17 use crate::state::AppState;
18 18
19 use super::dto::Role;19 use super::dto::Role;
20-use super::{CurrentUser, Page, PageParams, PersonRef, paginate};20+use super::{CurrentUser, Page, PageParams, PersonRef};
21 21
22 pub fn routes() -> OpenApiRouter<AppState> {22 pub fn routes() -> OpenApiRouter<AppState> {
23 OpenApiRouter::new()23 OpenApiRouter::new()
@@ -240,11 +240,10 @@ async fn list(
240 None => Folder::Inbox,240 None => Folder::Inbox,
241 };241 };
242 242
243- let messages = Message::list_folder(user.get_id(), folder, filter.read, &st.db).await?;243+ let (messages, total) =
244- let total = messages.len() as i64;244+ Message::list_folder(user.get_id(), folder, filter.read, limit, offset, &st.db).await?;
245- let slice = paginate(&messages, limit, offset);245+ let people = load_people(&messages, &st.db).await?;
246- let people = load_people(slice, &st.db).await?;246+ let items = messages
247- let items = slice
248 .iter()247 .iter()
249 .map(|message| MessageResponse::new(message, user.get_id(), &people))248 .map(|message| MessageResponse::new(message, user.get_id(), &people))
250 .collect();249 .collect();
src/web/mod.rsmodified+7 -5
@@ -31,6 +31,7 @@ pub mod work;
31 31
32 mod dto;32 mod dto;
33 mod extractor;33 mod extractor;
34+mod image;
34 mod page;35 mod page;
35 36
36 pub use dto::{37 pub use dto::{
@@ -38,6 +39,7 @@ pub use dto::{
38 UserResponse, course_people, person_map,39 UserResponse, course_people, person_map,
39 };40 };
40 pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireStudent, RequireTeacher};41 pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireStudent, RequireTeacher};
42+pub(crate) use image::{ImageUpload, read_image_upload, store_blob};
41 pub use page::{Page, PageParams, Scheduled, WindowParams, paginate};43 pub use page::{Page, PageParams, Scheduled, WindowParams, paginate};
42 44
43 use std::path::{Path as FsPath, PathBuf};45 use std::path::{Path as FsPath, PathBuf};
@@ -92,7 +94,10 @@ pub(crate) async fn ensure_can_observe(
92 }94 }
93 95
94 /// If both ends are present, `ends_at` must not precede `starts_at`. Shared by96 /// If both ends are present, `ends_at` must not precede `starts_at`. Shared by
95-/// everything that carries a time range (events, course sessions).97+/// everything that carries a time range (events, course sessions). The PATCH
98+/// paths re-check this at write time via
99+/// [`crate::domain::field_update::FieldUpdate::ordered`], which answers with the
100+/// same error — this is the pre-flight, that is the race closer.
96 pub(crate) fn check_time_range(101 pub(crate) fn check_time_range(
97 starts_at: Option<Timestamp>,102 starts_at: Option<Timestamp>,
98 ends_at: Option<Timestamp>,103 ends_at: Option<Timestamp>,
@@ -100,10 +105,7 @@ pub(crate) fn check_time_range(
100 if let (Some(starts), Some(ends)) = (starts_at, ends_at)105 if let (Some(starts), Some(ends)) = (starts_at, ends_at)
101 && ends < starts106 && ends < starts
102 {107 {
103- return Err(AppError::Validation(ValidationError::Invalid {108+ return Err(crate::domain::timestamp::range_error());
104- field: "ends_at",
105- reason: "must be at or after starts_at",
106- }));
107 }109 }
108 Ok(())110 Ok(())
109 }111 }
src/web/notes.rsmodified+6 -14
@@ -16,7 +16,7 @@ use crate::error::{AppError, ErrorResponse};
16 use crate::state::AppState;16 use crate::state::AppState;
17 17
18 use super::{18 use super::{
19- Page, PageParams, RequireStudent, UploadFileForm, blob_path, paginate, read_upload, remove_blob,19+ Page, PageParams, RequireStudent, UploadFileForm, blob_path, read_upload, remove_blob,
20 };20 };
21 21
22 pub fn routes() -> OpenApiRouter<AppState> {22 pub fn routes() -> OpenApiRouter<AppState> {
@@ -116,12 +116,8 @@ async fn list(
116 Query(page): Query<PageParams>,116 Query(page): Query<PageParams>,
117 ) -> Result<Json<Page<NoteResponse>>, AppError> {117 ) -> Result<Json<Page<NoteResponse>>, AppError> {
118 let (limit, offset) = page.resolve()?;118 let (limit, offset) = page.resolve()?;
119- let notes = Note::list_for(user.get_id(), &st.db).await?;119+ let (notes, total) = Note::list_for(user.get_id(), limit, offset, &st.db).await?;
120- let total = notes.len() as i64;120+ let items = notes.iter().map(NoteResponse::new).collect();
121- let items = paginate(&notes, limit, offset)
122- .iter()
123- .map(NoteResponse::new)
124- .collect();
125 Ok(Json(Page::new(items, total, limit, offset)))121 Ok(Json(Page::new(items, total, limit, offset)))
126 }122 }
127 123
@@ -216,7 +212,7 @@ async fn delete_one(
216 // Rows go first (the note delete cascades them), blobs after: a crash in212 // Rows go first (the note delete cascades them), blobs after: a crash in
217 // between strands at worst an unreachable blob, never a row whose blob is213 // between strands at worst an unreachable blob, never a row whose blob is
218 // already gone.214 // already gone.
219- let files = NoteFile::list_for(note.get_id(), &st.db).await?;215+ let (files, _) = NoteFile::list_for(note.get_id(), None, 0, &st.db).await?;
220 note.delete(&st.db).await?;216 note.delete(&st.db).await?;
221 for file in &files {217 for file in &files {
222 remove_blob(&st.files_path, file.get_id().key()).await;218 remove_blob(&st.files_path, file.get_id().key()).await;
@@ -331,12 +327,8 @@ async fn list_files(
331 let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)327 let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)
332 .await?328 .await?
333 .ok_or(AppError::NotFound)?;329 .ok_or(AppError::NotFound)?;
334- let files = NoteFile::list_for(note.get_id(), &st.db).await?;330+ let (files, total) = NoteFile::list_for(note.get_id(), limit, offset, &st.db).await?;
335- let total = files.len() as i64;331+ let items = files.iter().map(NoteFileResponse::new).collect();
336- let items = paginate(&files, limit, offset)
337- .iter()
338- .map(NoteFileResponse::new)
339- .collect();
340 Ok(Json(Page::new(items, total, limit, offset)))332 Ok(Json(Page::new(items, total, limit, offset)))
341 }333 }
342 334
src/web/pomodoro.rsmodified+2 -0
@@ -92,6 +92,8 @@ impl PomodoroLog {
92 })92 })
93 .sum();93 .sum();
94 Self {94 Self {
95+ // Paged in the web layer: `total_focus_ms` folds the whole log, so the
96+ // rows the page comes from are already all in hand.
95 items: paginate(sessions, limit, offset)97 items: paginate(sessions, limit, offset)
96 .iter()98 .iter()
97 .map(PomodoroResponse::new)99 .map(PomodoroResponse::new)
src/web/questions.rsmodified+43 -71
@@ -22,7 +22,6 @@ use crate::domain::pool_question::{
22 PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle,22 PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle,
23 };23 };
24 use crate::domain::role::Role;24 use crate::domain::role::Role;
25-use crate::domain::settings::Settings;
26 use crate::domain::solution::{Solution, SolutionBody, SolutionId};25 use crate::domain::solution::{Solution, SolutionBody, SolutionId};
27 use crate::domain::user::User;26 use crate::domain::user::User;
28 use crate::error::{AppError, ErrorResponse, ValidationError};27 use crate::error::{AppError, ErrorResponse, ValidationError};
@@ -30,8 +29,7 @@ use crate::state::AppState;
30 29
31 use super::{30 use super::{
32 CurrentUser, Page, PageParams, PersonRef, RequireStudent, RequireTeacher, UploadFileForm,31 CurrentUser, Page, PageParams, PersonRef, RequireStudent, RequireTeacher, UploadFileForm,
33- blob_path, image_content_type, paginate, person_map, read_upload, remove_blob,32+ paginate, person_map, read_image_upload, remove_blob, serve_inline_blob, store_blob,
34- serve_inline_blob,
35 };33 };
36 34
37 pub fn routes() -> OpenApiRouter<AppState> {35 pub fn routes() -> OpenApiRouter<AppState> {
@@ -319,6 +317,7 @@ async fn list_questions(
319 }317 }
320 318
321 let total = questions.len() as i64;319 let total = questions.len() as i64;
320+ // Paged in the web layer: the status filter above is per-row Rust.
322 let items = question_responses(paginate(&questions, limit, offset), &st).await?;321 let items = question_responses(paginate(&questions, limit, offset), &st).await?;
323 Ok(Json(Page::new(items, total, limit, offset)))322 Ok(Json(Page::new(items, total, limit, offset)))
324 }323 }
@@ -476,42 +475,29 @@ async fn upload_image(
476 ) -> Result<(StatusCode, Json<PoolImageMeta>), AppError> {475 ) -> Result<(StatusCode, Json<PoolImageMeta>), AppError> {
477 let question = question_or_404(&st, &id).await?;476 let question = question_or_404(&st, &id).await?;
478 ensure_asker_editable(&question, &user)?;477 ensure_asker_editable(&question, &user)?;
479- let limit = Settings::load(&st.db).await?.get_max_file_bytes();478+ let upload = read_image_upload(&st, &mut multipart).await?;
480- let upload = read_upload(&mut multipart, limit).await?;479+ let size = upload.size();
481- let content_type = image_content_type(&upload.content_type.unwrap_or_default())?;
482 480
483- // Blob first, row second — a stored row always points at a real blob.
484 let file = ulid::Ulid::new().to_string();481 let file = ulid::Ulid::new().to_string();
485- let path = blob_path(&st.files_path, &file);482+ store_blob(&st, &file, &upload.data, || async {
486- tokio::fs::write(&path, &upload.data)483+ match PoolQuestion::set_image(question.get_id(), &file, &upload.content_type, size, &st.db)
487- .await484+ .await?
488- .map_err(|err| AppError::Internal(format!("failed to store the image blob: {err}")))?;485+ {
489- let size = upload.data.len() as i64;486+ // The guarded UPDATE found the question still pending: point-of-truth
490- match PoolQuestion::set_image(question.get_id(), &file, &content_type, size, &st.db).await {487+ // write done; the replaced blob (if any) comes off disk.
491- // The guarded UPDATE found the question still pending: point-of-truth488+ Some(before) => Ok(((), before.get_image_file().map(str::to_string))),
492- // write done; the replaced blob (if any) comes off disk.489+ // Approved or deleted mid-upload — the fresh blob is an orphan.
493- Ok(Some(before)) => {490+ None => Err(AppError::Conflict("the question is no longer pending")),
494- if let Some(replaced) = before.get_image_file() {
495- remove_blob(&st.files_path, replaced).await;
496- }
497- Ok((
498- StatusCode::CREATED,
499- Json(PoolImageMeta {
500- content_type: content_type.as_str().to_string(),
501- size,
502- }),
503- ))
504- }
505- // Approved or deleted mid-upload — the fresh blob is an orphan.
506- Ok(None) => {
507- let _ = tokio::fs::remove_file(&path).await;
508- Err(AppError::Conflict("the question is no longer pending"))
509 }491 }
510- Err(err) => {492+ })
511- let _ = tokio::fs::remove_file(&path).await;493+ .await?;
512- Err(err)494+ Ok((
513- }495+ StatusCode::CREATED,
514- }496+ Json(PoolImageMeta {
497+ content_type: upload.content_type.as_str().to_string(),
498+ size,
499+ }),
500+ ))
515 }501 }
516 502
517 /// The question's photo bytes. Access follows the question itself: approved →503 /// The question's photo bytes. Access follows the question itself: approved →
@@ -683,9 +669,8 @@ async fn list_solutions(
683 let (limit, offset) = page.resolve()?;669 let (limit, offset) = page.resolve()?;
684 let question = question_or_404(&st, &id).await?;670 let question = question_or_404(&st, &id).await?;
685 ensure_visible(&question, &user)?;671 ensure_visible(&question, &user)?;
686- let solutions = Solution::list_for(question.get_id(), &st.db).await?;672+ let (solutions, total) = Solution::list_for(question.get_id(), limit, offset, &st.db).await?;
687- let total = solutions.len() as i64;673+ let slice = solutions.as_slice();
688- let slice = paginate(&solutions, limit, offset);
689 let people = person_map(674 let people = person_map(
690 slice.iter().map(|solution| solution.get_author().clone()),675 slice.iter().map(|solution| solution.get_author().clone()),
691 &st.db,676 &st.db,
@@ -812,41 +797,28 @@ async fn upload_solution_image(
812 mut multipart: Multipart,797 mut multipart: Multipart,
813 ) -> Result<(StatusCode, Json<PoolImageMeta>), AppError> {798 ) -> Result<(StatusCode, Json<PoolImageMeta>), AppError> {
814 let solution = author_solution(&st, &user, &id, &sid).await?;799 let solution = author_solution(&st, &user, &id, &sid).await?;
815- let limit = Settings::load(&st.db).await?.get_max_file_bytes();800+ let upload = read_image_upload(&st, &mut multipart).await?;
816- let upload = read_upload(&mut multipart, limit).await?;801+ let size = upload.size();
817- let content_type = image_content_type(&upload.content_type.unwrap_or_default())?;
818 802
819- // Blob first, row second — a stored row always points at a real blob.
820 let file = ulid::Ulid::new().to_string();803 let file = ulid::Ulid::new().to_string();
821- let path = blob_path(&st.files_path, &file);804+ store_blob(&st, &file, &upload.data, || async {
822- tokio::fs::write(&path, &upload.data)805+ match Solution::set_image(solution.get_id(), &file, &upload.content_type, size, &st.db)
823- .await806+ .await?
824- .map_err(|err| AppError::Internal(format!("failed to store the image blob: {err}")))?;807+ {
825- let size = upload.data.len() as i64;808+ // Row write done; the replaced blob (if any) comes off disk.
826- match Solution::set_image(solution.get_id(), &file, &content_type, size, &st.db).await {809+ Some(before) => Ok(((), before.get_image_file().map(str::to_string))),
827- // Row write done; the replaced blob (if any) comes off disk.810+ // Deleted mid-upload — the fresh blob is an orphan.
828- Ok(Some(before)) => {811+ None => Err(AppError::NotFound),
829- if let Some(replaced) = before.get_image_file() {
830- remove_blob(&st.files_path, replaced).await;
831- }
832- Ok((
833- StatusCode::CREATED,
834- Json(PoolImageMeta {
835- content_type: content_type.as_str().to_string(),
836- size,
837- }),
838- ))
839- }
840- // Deleted mid-upload — the fresh blob is an orphan.
841- Ok(None) => {
842- let _ = tokio::fs::remove_file(&path).await;
843- Err(AppError::NotFound)
844 }812 }
845- Err(err) => {813+ })
846- let _ = tokio::fs::remove_file(&path).await;814+ .await?;
847- Err(err)815+ Ok((
848- }816+ StatusCode::CREATED,
849- }817+ Json(PoolImageMeta {
818+ content_type: upload.content_type.as_str().to_string(),
819+ size,
820+ }),
821+ ))
850 }822 }
851 823
852 /// The solution photo's bytes. Access follows the question the solution824 /// The solution photo's bytes. Access follows the question the solution
src/web/sessions.rsmodified+6 -15
@@ -11,7 +11,7 @@ use utoipa_axum::routes;
11 use crate::database::Database;11 use crate::database::Database;
12 use crate::domain::attendance::AttendanceStatus;12 use crate::domain::attendance::AttendanceStatus;
13 use crate::domain::course::Course;13 use crate::domain::course::Course;
14-use crate::domain::course_session::{CourseSession, CourseSessionId, SESSION_LOCK, SessionTopic};14+use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic};
15 use crate::domain::enrollment::Enrollment;15 use crate::domain::enrollment::Enrollment;
16 use crate::domain::role::Role;16 use crate::domain::role::Role;
17 use crate::domain::session_attendance::SessionAttendance;17 use crate::domain::session_attendance::SessionAttendance;
@@ -24,7 +24,7 @@ use crate::state::AppState;
24 use super::courses::{can_manage_course, can_view_course};24 use super::courses::{can_manage_course, can_view_course};
25 use super::{25 use super::{
26 CurrentUser, Page, PageParams, PersonRef, RequireTeacher, SessionResponse, check_not_past,26 CurrentUser, Page, PageParams, PersonRef, RequireTeacher, SessionResponse, check_not_past,
27- check_time_range, paginate, person_map, set_or_clear,27+ check_time_range, person_map, set_or_clear,
28 };28 };
29 29
30 pub fn routes() -> OpenApiRouter<AppState> {30 pub fn routes() -> OpenApiRouter<AppState> {
@@ -197,15 +197,6 @@ async fn update_session(
197 if let Some(ends_at) = ends_at {197 if let Some(ends_at) = ends_at {
198 check_not_past("ends_at", ends_at)?;198 check_not_past("ends_at", ends_at)?;
199 }199 }
200- // Only the range check needs the stored row, and only it can race: it
201- // validates an arriving end against the other end as stored, so the read,
202- // the check and the write are held together under [`SESSION_LOCK`]. A PATCH
203- // that moves neither end pays nothing.
204- let _guard = match (starts_at, ends_at) {
205- (None, None) => None,
206- _ => Some(SESSION_LOCK.lock().await),
207- };
208-
209 let (session, course) = session_with_course(&id, &st.db).await?;200 let (session, course) = session_with_course(&id, &st.db).await?;
210 if !can_manage_course(&course, &user) {201 if !can_manage_course(&course, &user) {
211 return Err(AppError::Forbidden(202 return Err(AppError::Forbidden(
@@ -228,7 +219,8 @@ async fn update_session(
228 None => None,219 None => None,
229 };220 };
230 // The end this request left out is only *read* for the range check — it is221 // The end this request left out is only *read* for the range check — it is
231- // never written back, so a concurrent move of it survives.222+ // never written back, so a concurrent move of it survives. Pre-flight only:
223+ // `CourseSession::update` re-makes this check in the UPDATE's `WHERE`.
232 check_time_range(224 check_time_range(
233 Some(starts_at.unwrap_or_else(|| session.get_starts_at())),225 Some(starts_at.unwrap_or_else(|| session.get_starts_at())),
234 ends_at.unwrap_or_else(|| session.get_ends_at()),226 ends_at.unwrap_or_else(|| session.get_ends_at()),
@@ -383,10 +375,9 @@ async fn list_roll_call(
383 "only the session's teacher or a course manager can list the roll call",375 "only the session's teacher or a course manager can list the roll call",
384 ));376 ));
385 }377 }
386- let roster = SessionAttendance::list_for_session(session.get_id(), &st.db).await?;378+ let (rows, total) =
387- let total = roster.len() as i64;379+ SessionAttendance::list_for_session(session.get_id(), limit, offset, &st.db).await?;
388 // Join people onto the page alone — the lookup shrinks with the window.380 // Join people onto the page alone — the lookup shrinks with the window.
389- let rows = paginate(&roster, limit, offset);
390 let people = person_map(381 let people = person_map(
391 rows.iter()382 rows.iter()
392 .flat_map(|a| [a.get_user().clone(), a.get_marked_by().clone()]),383 .flat_map(|a| [a.get_user().clone(), a.get_marked_by().clone()]),
src/web/settings.rsmodified+2 -2
@@ -5,7 +5,7 @@ use utoipa::ToSchema;
5 use utoipa_axum::router::OpenApiRouter;5 use utoipa_axum::router::OpenApiRouter;
6 use utoipa_axum::routes;6 use utoipa_axum::routes;
7 7
8-use crate::constant::SETTINGS_UPDATE_RETRIES;8+use crate::constant::CAS_UPDATE_RETRIES;
9 use crate::domain::exam_result::ExamResult;9 use crate::domain::exam_result::ExamResult;
10 use crate::domain::menu::{MENU_LOCK, Menu};10 use crate::domain::menu::{MENU_LOCK, Menu};
11 use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings};11 use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings};
@@ -274,7 +274,7 @@ async fn update_settings(
274 Some(_) => Some(MENU_LOCK.lock().await),274 Some(_) => Some(MENU_LOCK.lock().await),
275 None => None,275 None => None,
276 };276 };
277- for _ in 0..SETTINGS_UPDATE_RETRIES {277+ for _ in 0..CAS_UPDATE_RETRIES {
278 let current = Settings::load(&st.db).await?;278 let current = Settings::load(&st.db).await?;
279 279
280 let exam_kinds = match &req.exam_kinds {280 let exam_kinds = match &req.exam_kinds {
src/web/terms.rsmodified+6 -14
@@ -12,7 +12,7 @@ use crate::domain::timestamp::Timestamp;
12 use crate::error::{AppError, ErrorResponse, ValidationError};12 use crate::error::{AppError, ErrorResponse, ValidationError};
13 use crate::state::AppState;13 use crate::state::AppState;
14 14
15-use super::{CurrentUser, Page, PageParams, RequireManager, check_time_range, paginate};15+use super::{CurrentUser, Page, PageParams, RequireManager, check_time_range};
16 16
17 pub fn routes() -> OpenApiRouter<AppState> {17 pub fn routes() -> OpenApiRouter<AppState> {
18 OpenApiRouter::new()18 OpenApiRouter::new()
@@ -132,12 +132,8 @@ async fn list_terms(
132 Query(page): Query<PageParams>,132 Query(page): Query<PageParams>,
133 ) -> Result<Json<Page<TermResponse>>, AppError> {133 ) -> Result<Json<Page<TermResponse>>, AppError> {
134 let (limit, offset) = page.resolve()?;134 let (limit, offset) = page.resolve()?;
135- let terms = Term::list_all(&st.db).await?;135+ let (terms, total) = Term::list_all(limit, offset, &st.db).await?;
136- let total = terms.len() as i64;136+ let items = terms.iter().map(TermResponse::new).collect();
137- let items = paginate(&terms, limit, offset)
138- .iter()
139- .map(TermResponse::new)
140- .collect();
141 Ok(Json(Page::new(items, total, limit, offset)))137 Ok(Json(Page::new(items, total, limit, offset)))
142 }138 }
143 139
@@ -192,16 +188,12 @@ async fn update_term(
192 let starts_at = req.starts_at.map(Timestamp::from_millis);188 let starts_at = req.starts_at.map(Timestamp::from_millis);
193 let ends_at = req.ends_at.map(Timestamp::from_millis);189 let ends_at = req.ends_at.map(Timestamp::from_millis);
194 190
195- // Only the range check needs the stored row, and only it can race: it
196- // validates an arriving end against the other end as stored, so the read,
197- // the check and the write are held together under [`TERM_LOCK`].
198- let _guard = match (starts_at, ends_at) {
199- (None, None) => None,
200- _ => Some(TERM_LOCK.lock().await),
201- };
202 let term = Term::read(&TermId::from_key(&id), &st.db)191 let term = Term::read(&TermId::from_key(&id), &st.db)
203 .await?192 .await?
204 .ok_or(AppError::NotFound)?;193 .ok_or(AppError::NotFound)?;
194+ // Pre-flight only: the range check is re-made inside the UPDATE's `WHERE`
195+ // (`Term::update`), so a concurrent move of the end this PATCH omits cannot
196+ // slip an inverted range past this snapshot.
205 check_time_range(197 check_time_range(
206 Some(starts_at.unwrap_or_else(|| term.get_starts_at())),198 Some(starts_at.unwrap_or_else(|| term.get_starts_at())),
207 Some(ends_at.unwrap_or_else(|| term.get_ends_at())),199 Some(ends_at.unwrap_or_else(|| term.get_ends_at())),
src/web/users.rsmodified+6 -12
@@ -182,12 +182,8 @@ async fn search_users(
182 }182 }
183 .resolve()?;183 .resolve()?;
184 let role = req.role.as_deref().map(Role::try_from_str).transpose()?;184 let role = req.role.as_deref().map(Role::try_from_str).transpose()?;
185- let users = User::search(&req.q, role, &st.db).await?;185+ let (users, total) = User::search(&req.q, role, limit, offset, &st.db).await?;
186- let total = users.len() as i64;186+ let items = users.iter().map(PersonRef::new).collect();
187- let items = paginate(&users, limit, offset)
188- .iter()
189- .map(PersonRef::new)
190- .collect();
191 Ok(Json(Page::new(items, total, limit, offset)))187 Ok(Json(Page::new(items, total, limit, offset)))
192 }188 }
193 189
@@ -214,12 +210,8 @@ async fn list_users(
214 Query(page): Query<PageParams>,210 Query(page): Query<PageParams>,
215 ) -> Result<Json<Page<UserResponse>>, AppError> {211 ) -> Result<Json<Page<UserResponse>>, AppError> {
216 let (limit, offset) = page.resolve()?;212 let (limit, offset) = page.resolve()?;
217- let users = User::list_all(&st.db).await?;213+ let (users, total) = User::list_all(limit, offset, &st.db).await?;
218- let total = users.len() as i64;214+ let items = users.iter().map(UserResponse::new).collect();
219- let items = paginate(&users, limit, offset)
220- .iter()
221- .map(UserResponse::new)
222- .collect();
223 Ok(Json(Page::new(items, total, limit, offset)))215 Ok(Json(Page::new(items, total, limit, offset)))
224 }216 }
225 217
@@ -445,6 +437,8 @@ async fn students_page(
445 let mut students = User::list_by_ids(&ids, db).await?;437 let mut students = User::list_by_ids(&ids, db).await?;
446 students.sort_by(|a, b| a.get_username().as_str().cmp(b.get_username().as_str()));438 students.sort_by(|a, b| a.get_username().as_str().cmp(b.get_username().as_str()));
447 let total = students.len() as i64;439 let total = students.len() as i64;
440+ // Paged in the web layer: the rows come from a link table and are
441+ // re-sorted by username in Rust.
448 let items = paginate(&students, limit, offset)442 let items = paginate(&students, limit, offset)
449 .iter()443 .iter()
450 .map(PersonRef::new)444 .map(PersonRef::new)
src/web/work.rsmodified+9 -28
@@ -8,11 +8,11 @@ use utoipa_axum::routes;
8 8
9 use crate::domain::timestamp::Timestamp;9 use crate::domain::timestamp::Timestamp;
10 use crate::domain::user::{User, UserId};10 use crate::domain::user::{User, UserId};
11-use crate::domain::work_entry::{WORK_ENTRY_LOCK, WorkEntry, WorkEntryId};11+use crate::domain::work_entry::{WorkEntry, WorkEntryId, out_before_in_error};
12-use crate::error::{AppError, ErrorResponse, ValidationError};12+use crate::error::{AppError, ErrorResponse};
13 use crate::state::AppState;13 use crate::state::AppState;
14 14
15-use super::{Page, PageParams, RequireManager, RequireTeacher, paginate};15+use super::{Page, PageParams, RequireManager, RequireTeacher};
16 16
17 pub fn routes() -> OpenApiRouter<AppState> {17 pub fn routes() -> OpenApiRouter<AppState> {
18 OpenApiRouter::new()18 OpenApiRouter::new()
@@ -127,12 +127,8 @@ async fn my_work(
127 Query(page): Query<PageParams>,127 Query(page): Query<PageParams>,
128 ) -> Result<Json<Page<WorkEntryResponse>>, AppError> {128 ) -> Result<Json<Page<WorkEntryResponse>>, AppError> {
129 let (limit, offset) = page.resolve()?;129 let (limit, offset) = page.resolve()?;
130- let entries = WorkEntry::list_for_user(user.get_id(), &st.db).await?;130+ let (entries, total) = WorkEntry::list_for_user(user.get_id(), limit, offset, &st.db).await?;
131- let total = entries.len() as i64;131+ let items = entries.iter().map(WorkEntryResponse::new).collect();
132- let items = paginate(&entries, limit, offset)
133- .iter()
134- .map(WorkEntryResponse::new)
135- .collect();
136 Ok(Json(Page::new(items, total, limit, offset)))132 Ok(Json(Page::new(items, total, limit, offset)))
137 }133 }
138 134
@@ -165,12 +161,8 @@ async fn user_work(
165 User::read(&target, &st.db)161 User::read(&target, &st.db)
166 .await?162 .await?
167 .ok_or(AppError::NotFound)?;163 .ok_or(AppError::NotFound)?;
168- let entries = WorkEntry::list_for_user(&target, &st.db).await?;164+ let (entries, total) = WorkEntry::list_for_user(&target, limit, offset, &st.db).await?;
169- let total = entries.len() as i64;165+ let items = entries.iter().map(WorkEntryResponse::new).collect();
170- let items = paginate(&entries, limit, offset)
171- .iter()
172- .map(WorkEntryResponse::new)
173- .collect();
174 Ok(Json(Page::new(items, total, limit, offset)))166 Ok(Json(Page::new(items, total, limit, offset)))
175 }167 }
176 168
@@ -200,15 +192,6 @@ async fn update_entry(
200 ) -> Result<Json<WorkEntryResponse>, AppError> {192 ) -> Result<Json<WorkEntryResponse>, AppError> {
201 let check_in = req.check_in.map(Timestamp::from_millis);193 let check_in = req.check_in.map(Timestamp::from_millis);
202 let check_out = req.check_out.map(Timestamp::from_millis);194 let check_out = req.check_out.map(Timestamp::from_millis);
203- // Only the ordering check needs the stored row, and only it can race: it
204- // validates an arriving instant against the other one as stored, so the
205- // read, the check and the write are held together under
206- // [`WORK_ENTRY_LOCK`]. A PATCH carrying neither instant pays nothing.
207- let _guard = match (check_in, check_out) {
208- (None, None) => None,
209- _ => Some(WORK_ENTRY_LOCK.lock().await),
210- };
211-
212 let entry = WorkEntry::read(&WorkEntryId::from_key(&id), &st.db)195 let entry = WorkEntry::read(&WorkEntryId::from_key(&id), &st.db)
213 .await?196 .await?
214 .ok_or(AppError::NotFound)?;197 .ok_or(AppError::NotFound)?;
@@ -220,11 +203,9 @@ async fn update_entry(
220 203
221 // The side the correction left out is only *read* for the ordering check —204 // The side the correction left out is only *read* for the ordering check —
222 // it is never written back, so a concurrent correction of it survives.205 // it is never written back, so a concurrent correction of it survives.
206+ // Pre-flight only: `WorkEntry::update` re-makes this in the UPDATE's `WHERE`.
223 if check_out.unwrap_or(current_out) < check_in.unwrap_or_else(|| entry.get_check_in()) {207 if check_out.unwrap_or(current_out) < check_in.unwrap_or_else(|| entry.get_check_in()) {
224- return Err(AppError::Validation(ValidationError::Invalid {208+ return Err(out_before_in_error());
225- field: "check_out",
226- reason: "must be at or after check_in",
227- }));
228 }209 }
229 210
230 let updated = entry.update(check_in, check_out, &st.db).await?;211 let updated = entry.update(check_in, check_out, &st.db).await?;
tests/integration.rsmodified+236 -11
@@ -4108,6 +4108,127 @@ async fn concurrent_placements_never_exceed_capacity() {
4108 }4108 }
4109 }4109 }
4110 4110
4111+/// The course capacity cap is a counter column on the course row now, not a
4112+/// process mutex: `UPDATE ... SET n += 1 WHERE n < capacity` is atomic per
4113+/// record, so it holds whichever replica the racing enrolls land on. Removing
4114+/// that `WHERE` (or the claim entirely) puts a third student on a capacity-2
4115+/// course and fails this. The unenroll each round proves the seat comes back —
4116+/// without the decrement the course is permanently full by round two.
4117+#[tokio::test]
4118+async fn concurrent_enrolls_never_exceed_course_capacity() {
4119+ let (app, db) = app_and_db().await;
4120+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
4121+ let mut students = Vec::new();
4122+ for name in ["ali", "veli", "ayse"] {
4123+ let cookie = login(&app, name).await;
4124+ let id = me_id(&app, &cookie).await;
4125+ students.push(id);
4126+ }
4127+ let res = send(
4128+ &app,
4129+ "POST",
4130+ "/courses",
4131+ Some(&teacher),
4132+ Some(json!({ "title": "small", "description": "", "capacity": 2 })),
4133+ )
4134+ .await;
4135+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
4136+ let course = id_of(&res.body);
4137+ let uri = format!("/courses/{course}/enrollments");
4138+
4139+ for _round in 0..8 {
4140+ for id in &students {
4141+ let _ = send(&app, "DELETE", &format!("{uri}/{id}"), Some(&teacher), None).await;
4142+ }
4143+ let mut handles = Vec::new();
4144+ for id in &students {
4145+ let (app, teacher, uri) = (app.clone(), teacher.clone(), uri.clone());
4146+ let body = json!({ "user_id": id });
4147+ handles.push(tokio::spawn(async move {
4148+ send(&app, "POST", &uri, Some(&teacher), Some(body))
4149+ .await
4150+ .status
4151+ }));
4152+ }
4153+ for handle in handles {
4154+ let status = handle.await.unwrap();
4155+ assert!(
4156+ status == StatusCode::OK || status == StatusCode::CONFLICT,
4157+ "a lost capacity race must be a 409, got {status}"
4158+ );
4159+ }
4160+ let roster = send(&app, "GET", &uri, Some(&teacher), None).await;
4161+ assert!(
4162+ common::total(&roster.body) <= 2,
4163+ "capacity 2 must never over-admit, roster={}",
4164+ roster.body
4165+ );
4166+ }
4167+}
4168+
4169+/// The same (user, course) pair enrolled concurrently must cost exactly one
4170+/// seat: the row is idempotent by its composite id, so a second enroll that
4171+/// finds the pair already there returns it *without* claiming, and a `CREATE`
4172+/// that loses the id race releases the seat it claimed before reading the
4173+/// winner's row back. Either way the counter must equal the roster — a drift
4174+/// above it is permanent (nothing recomputes the counter), so the course would
4175+/// be full forever. Stored state is the only witness: the embedded engine can
4176+/// tell two racers they both won, so the HTTP statuses prove nothing.
4177+//
4178+// ponytail: `ENROLL_LOCK` serializes the enrolls inside one process, so what
4179+// this actually drives is the already-enrolled early return; the `CREATE`-loser
4180+// release only runs when the two racers sit on different replicas. Both paths
4181+// are pinned by the same assertion below (counter == roster), which is the part
4182+// that matters.
4183+#[tokio::test]
4184+async fn concurrent_enrolls_of_one_pair_claim_one_seat() {
4185+ let (app, db) = app_and_db().await;
4186+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
4187+ let alice = login(&app, "alice").await;
4188+ let alice_id = me_id(&app, &alice).await;
4189+ let res = send(
4190+ &app,
4191+ "POST",
4192+ "/courses",
4193+ Some(&teacher),
4194+ Some(json!({ "title": "seats", "description": "", "capacity": 2 })),
4195+ )
4196+ .await;
4197+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
4198+ let course = id_of(&res.body);
4199+ let uri = format!("/courses/{course}/enrollments");
4200+
4201+ let mut handles = Vec::new();
4202+ for _ in 0..16 {
4203+ let (app, teacher, uri) = (app.clone(), teacher.clone(), uri.clone());
4204+ let body = json!({ "user_id": alice_id });
4205+ handles.push(tokio::spawn(async move {
4206+ send(&app, "POST", &uri, Some(&teacher), Some(body))
4207+ .await
4208+ .status
4209+ }));
4210+ }
4211+ for handle in handles {
4212+ let status = handle.await.unwrap();
4213+ assert_eq!(status, StatusCode::OK, "a same-pair enroll is idempotent");
4214+ }
4215+
4216+ let roster = send(&app, "GET", &uri, Some(&teacher), None).await;
4217+ assert_eq!(common::total(&roster.body), 1, "one pair, one row");
4218+ let mut counted = db
4219+ .query("SELECT VALUE enrollment_count FROM type::record('course', $c)")
4220+ .bind(("c", course.clone()))
4221+ .await
4222+ .expect("counter read")
4223+ .check()
4224+ .expect("counter read");
4225+ assert_eq!(
4226+ counted.take::<Vec<i64>>(0).expect("counter column"),
4227+ vec![1],
4228+ "one row on the roster must have cost exactly one seat"
4229+ );
4230+}
4231+
4111 /// The signup list freezes the moment the event starts — both directions.4232 /// The signup list freezes the moment the event starts — both directions.
4112 /// (The create-time no-past grace lets a just-started event exist, which is4233 /// (The create-time no-past grace lets a just-started event exist, which is
4113 /// exactly a closed list.)4234 /// exactly a closed list.)
@@ -8589,9 +8710,10 @@ async fn questions_and_answers_cascade_with_deletes() {
8589 }8710 }
8590 let exam_id = ExamId::from_key(&exam);8711 let exam_id = ExamId::from_key(&exam);
8591 assert_eq!(8712 assert_eq!(
8592- ExamQuestion::list_for_exam(&exam_id, &db)8713+ ExamQuestion::list_for_exam(&exam_id, None, 0, &db)
8593 .await8714 .await
8594 .unwrap()8715 .unwrap()
8716+ .0
8595 .len(),8717 .len(),
8596 28718 2
8597 );8719 );
@@ -8603,20 +8725,40 @@ async fn questions_and_answers_cascade_with_deletes() {
8603 28725 2
8604 );8726 );
8605 8727
8606- // Deleting one question takes its answers with it — the API freezes8728+ // Deleting one question takes its answers with it. The freeze gate now
8607- // question deletes once attempts exist, so exercise the domain cascade8729+ // lives inside `ExamQuestion::delete`'s own transaction (not in a lock the
8608- // directly (it also runs under the exam/course cascades below).8730+ // handler held), so the attempt has to go first for the cascade to be
8609- let question = ExamQuestion::list_for_exam(&exam_id, &db)8731+ // exercised at all — that refusal is asserted here before it is cleared.
8732+ let frozen = ExamQuestion::list_for_exam(&exam_id, None, 0, &db)
8610 .await8733 .await
8611 .unwrap()8734 .unwrap()
8735+ .0
8736+ .into_iter()
8737+ .next()
8738+ .unwrap();
8739+ assert!(
8740+ matches!(frozen.delete(&db).await, Err(err) if err.to_string().contains("after attempts")),
8741+ "the gate must refuse a question delete while an attempt exists"
8742+ );
8743+ db.query("DELETE exam_attempt WHERE exam = $ex")
8744+ .bind(("ex", exam_id.record()))
8745+ .await
8746+ .unwrap()
8747+ .check()
8748+ .unwrap();
8749+ let question = ExamQuestion::list_for_exam(&exam_id, None, 0, &db)
8750+ .await
8751+ .unwrap()
8752+ .0
8612 .into_iter()8753 .into_iter()
8613 .next()8754 .next()
8614 .unwrap();8755 .unwrap();
8615 question.delete(&db).await.unwrap();8756 question.delete(&db).await.unwrap();
8616 assert_eq!(8757 assert_eq!(
8617- ExamQuestion::list_for_exam(&exam_id, &db)8758+ ExamQuestion::list_for_exam(&exam_id, None, 0, &db)
8618 .await8759 .await
8619 .unwrap()8760 .unwrap()
8761+ .0
8620 .len(),8762 .len(),
8621 18763 1
8622 );8764 );
@@ -8640,9 +8782,10 @@ async fn questions_and_answers_cascade_with_deletes() {
8640 .await;8782 .await;
8641 assert_eq!(res.status, StatusCode::NO_CONTENT);8783 assert_eq!(res.status, StatusCode::NO_CONTENT);
8642 assert!(8784 assert!(
8643- ExamQuestion::list_for_exam(&exam_id, &db)8785+ ExamQuestion::list_for_exam(&exam_id, None, 0, &db)
8644 .await8786 .await
8645 .unwrap()8787 .unwrap()
8788+ .0
8646 .is_empty()8789 .is_empty()
8647 );8790 );
8648 assert!(8791 assert!(
@@ -8703,9 +8846,10 @@ async fn questions_and_answers_cascade_with_deletes() {
8703 assert_eq!(res.status, StatusCode::NO_CONTENT);8846 assert_eq!(res.status, StatusCode::NO_CONTENT);
8704 let exam2_id = ExamId::from_key(&exam2);8847 let exam2_id = ExamId::from_key(&exam2);
8705 assert!(8848 assert!(
8706- ExamQuestion::list_for_exam(&exam2_id, &db)8849+ ExamQuestion::list_for_exam(&exam2_id, None, 0, &db)
8707 .await8850 .await
8708 .unwrap()8851 .unwrap()
8852+ .0
8709 .is_empty()8853 .is_empty()
8710 );8854 );
8711 assert!(8855 assert!(
@@ -14222,6 +14366,84 @@ async fn homework_grading_gates_and_bounds() {
14222 }14366 }
14223 14367
14224 /// A stored grade freezes the submission — text, files, withdrawal — until14368 /// A stored grade freezes the submission — text, files, withdrawal — until
14369+/// The files-per-submission cap is the same counter guard as the note-file one,
14370+/// on the submission row. Nine seeded files plus four racers for the last slot:
14371+/// exactly one may win, and the delete must give the slot back or the next
14372+/// upload is refused forever.
14373+#[tokio::test]
14374+async fn concurrent_homework_uploads_never_exceed_the_file_cap() {
14375+ let (app, db) = app_and_db().await;
14376+ let w = hw_world(&app, &db).await;
14377+ let now = Timestamp::now().as_millis();
14378+ let hw = create_homework(
14379+ &app,
14380+ &w.teacher,
14381+ &w.course,
14382+ &w.subject,
14383+ "essay",
14384+ now + 3_600_000,
14385+ )
14386+ .await;
14387+ let res = submit_hw(&app, &w.ali, &hw, Some("v1")).await;
14388+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
14389+ for i in 0..9 {
14390+ let up = upload_hw_file(&app, &w.ali, &hw, &format!("f{i}.txt"), "text/plain", b"x").await;
14391+ assert_eq!(up.status, StatusCode::CREATED, "seed file {i}: {}", up.body);
14392+ }
14393+
14394+ let racers = tokio::join!(
14395+ upload_hw_file(&app, &w.ali, &hw, "r0.txt", "text/plain", b"x"),
14396+ upload_hw_file(&app, &w.ali, &hw, "r1.txt", "text/plain", b"x"),
14397+ upload_hw_file(&app, &w.ali, &hw, "r2.txt", "text/plain", b"x"),
14398+ upload_hw_file(&app, &w.ali, &hw, "r3.txt", "text/plain", b"x"),
14399+ );
14400+ let statuses = [
14401+ racers.0.status,
14402+ racers.1.status,
14403+ racers.2.status,
14404+ racers.3.status,
14405+ ];
14406+ for status in statuses {
14407+ assert!(
14408+ status == StatusCode::CREATED || status == StatusCode::CONFLICT,
14409+ "a lost cap race must be a 409, got {status}"
14410+ );
14411+ }
14412+ let list = send(
14413+ &app,
14414+ "GET",
14415+ &format!("/homework/{hw}/submission"),
14416+ Some(&w.ali),
14417+ None,
14418+ )
14419+ .await;
14420+ let files = list.body["files"].as_array().expect("files").clone();
14421+ assert_eq!(
14422+ files.len(),
14423+ 10,
14424+ "the cap must hold exactly under concurrency, statuses={statuses:?}"
14425+ );
14426+
14427+ // A deleted file frees its slot again — the counter is not a ratchet.
14428+ let fid = files[0]["id"].as_str().expect("file id").to_string();
14429+ let res = send(
14430+ &app,
14431+ "DELETE",
14432+ &format!("/homework/{hw}/submission/files/{fid}"),
14433+ Some(&w.ali),
14434+ None,
14435+ )
14436+ .await;
14437+ assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
14438+ let up = upload_hw_file(&app, &w.ali, &hw, "after.txt", "text/plain", b"x").await;
14439+ assert_eq!(
14440+ up.status,
14441+ StatusCode::CREATED,
14442+ "the freed slot must be reusable: {}",
14443+ up.body
14444+ );
14445+}
14446+
14225 /// the teacher removes it; and work never handed in can be graded `missing`,14447 /// the teacher removes it; and work never handed in can be graded `missing`,
14226 /// a verdict the student reads from `/result` despite having no submission.14448 /// a verdict the student reads from `/result` despite having no submission.
14227 #[tokio::test]14449 #[tokio::test]
@@ -19311,7 +19533,7 @@ async fn a_bank_patch_does_not_clobber_a_concurrent_write() {
19311 19533
19312 // The stale struct writes its own fields only.19534 // The stale struct writes its own fields only.
19313 let updated = stale19535 let updated = stale
19314- .update(19536+ .update_if_unchanged(
19315 None,19537 None,
19316 QuestionText::try_new("edited").unwrap(),19538 QuestionText::try_new("edited").unwrap(),
19317 QuestionPoints::try_new(7).unwrap(),19539 QuestionPoints::try_new(7).unwrap(),
@@ -19320,7 +19542,8 @@ async fn a_bank_patch_does_not_clobber_a_concurrent_write() {
19320 &db,19542 &db,
19321 )19543 )
19322 .await19544 .await
19323- .expect("update written");19545+ .expect("update ran")
19546+ .expect("update written — the exam delete touched no compared column");
19324 assert_eq!(updated.get_text().as_str(), "edited");19547 assert_eq!(updated.get_text().as_str(), "edited");
19325 assert!(19548 assert!(
19326 updated.get_source_exam().is_none(),19549 updated.get_source_exam().is_none(),
@@ -20783,7 +21006,9 @@ async fn concurrent_ledger_appends_of_one_id_write_one_line_not_a_500() {
20783 "the loser must read back the winner's line, not fail: {second:?}"21006 "the loser must read back the winner's line, not fail: {second:?}"
20784 );21007 );
20785 21008
20786- let lines = MealLedger::list_for_student(&student, &db).await.unwrap();21009+ let (lines, _) = MealLedger::list_for_student(&student, None, 0, &db)
21010+ .await
21011+ .unwrap();
20787 assert_eq!(lines.len(), 2, "one charge and exactly one reversal");21012 assert_eq!(lines.len(), 2, "one charge and exactly one reversal");
20788 assert_eq!(21013 assert_eq!(
20789 MealLedger::balance_of(&student, &db).await.unwrap(),21014 MealLedger::balance_of(&student, &db).await.unwrap(),
tests/limits_completeness.rsmodified+27 -16
@@ -36,9 +36,14 @@ const EXCLUDED: &[(&str, &str)] = &[
36 "DB_CONNECT_BACKOFF_MAX_SECS",36 "DB_CONNECT_BACKOFF_MAX_SECS",
37 "boot reconnect backoff ceiling",37 "boot reconnect backoff ceiling",
38 ),38 ),
39+ ("CAS_UPDATE_RETRIES", "internal compare-and-set retry count"),
39 (40 (
40- "SETTINGS_UPDATE_RETRIES",41+ "CAP_WRITE_TRIES",
41- "internal compare-and-set retry count",42+ "internal retry count for a contended cap counter",
43+ ),
44+ (
45+ "CAP_WRITE_BACKOFF_MS",
46+ "internal backoff between cap counter retries",
42 ),47 ),
43 (48 (
44 "UPLOAD_BODY_OVERHEAD_BYTES",49 "UPLOAD_BODY_OVERHEAD_BYTES",
@@ -114,9 +119,6 @@ const EXCLUDED: &[(&str, &str)] = &[
114 "DEFAULT_DIETARY_TAGS",119 "DEFAULT_DIETARY_TAGS",
115 "settings seed; the live list is on GET /settings",120 "settings seed; the live list is on GET /settings",
116 ),121 ),
117- // Schema and query text. `constant.rs` is the single home for every
118- // constant, so the migration batches live there too — a client never sees
119- // a byte of SurrealQL.
120 // The boot leader election. A client never sees the lock, and the timings122 // The boot leader election. A client never sees the lock, and the timings
121 // are startup mechanics between processes — publishing them would invite a123 // are startup mechanics between processes — publishing them would invite a
122 // frontend to reason about a boot it cannot observe.124 // frontend to reason about a boot it cannot observe.
@@ -136,13 +138,9 @@ const EXCLUDED: &[(&str, &str)] = &[
136 "how long a non-leader waits for the boot migration",138 "how long a non-leader waits for the boot migration",
137 ),139 ),
138 ("MIGRATION_LOCK_POLL_MS", "boot lock poll cadence"),140 ("MIGRATION_LOCK_POLL_MS", "boot lock poll cadence"),
139- (141+ // The three migration batches and their list moved to
140- "MIGRATION_BATCHES",142+ // `src/migration_sql.rs` — they are SurrealQL text, not bounds, and the
141- "the batch list the boot executes and fingerprints",143+ // numeric sweep below still catches any bound that tries to follow them.
142- ),
143- ("PRE_REPAIR", "pre-DDL data repair batch"),
144- ("MIGRATION", "SCHEMAFULL DDL batch"),
145- ("BACKFILL", "post-DDL data backfill batch"),
146 ("USAGE_COUNTS_SQL", "one-statement bank usage-count query"),144 ("USAGE_COUNTS_SQL", "one-statement bank usage-count query"),
147 // Storage-side keys and literals. Each names a row, a column value or a145 // Storage-side keys and literals. Each names a row, a column value or a
148 // fold rule the server writes; none is a number a client is held to.146 // fold rule the server writes; none is a number a client is held to.
@@ -188,6 +186,18 @@ const EXCLUDED: &[(&str, &str)] = &[
188 "ETag middleware's own buffering ceiling",186 "ETag middleware's own buffering ceiling",
189 ),187 ),
190 ("PURGE_AT", "rate-limiter bucket eviction threshold"),188 ("PURGE_AT", "rate-limiter bucket eviction threshold"),
189+ // How the tiers are kept fleet-wide. A client is held to the tier itself
190+ // (published live in /limits `rate`), never to the cadence the replicas
191+ // reconcile it at — publishing that would invite pacing against it.
192+ (
193+ "RATE_SYNC_INTERVAL_SECS",
194+ "how often a replica reconciles its counters",
195+ ),
196+ ("RATE_SYNC_TIMEOUT_SECS", "deadline on one sync round"),
197+ (
198+ "RATE_SYNC_MAX_KEYS",
199+ "client buckets one sync round carries",
200+ ),
191 (201 (
192 "MAX_ERROR_CODE_LEN",202 "MAX_ERROR_CODE_LEN",
193 "bounds a code the SERVER writes from an AI service's reply; no client sends it",203 "bounds a code the SERVER writes from an AI service's reply; no client sends it",
@@ -196,11 +206,12 @@ const EXCLUDED: &[(&str, &str)] = &[
196 ("MIN_CHUNK_CHARS", "how the SSE stream slices an answer"),206 ("MIN_CHUNK_CHARS", "how the SSE stream slices an answer"),
197 ];207 ];
198 208
199-/// A `*_TABLE` constant is a SurrealDB table name, not a bound. Listing all 37209+/// A `*_TABLE` constant is a SurrealDB table name and a `*_FIELD` one a column
200-/// by hand would bury the deliberate exclusions above in boilerplate, so the210+/// name, not a bound. Listing all 37 by hand would bury the deliberate
201-/// whole shape is excused once — the naming convention *is* the decision.211+/// exclusions above in boilerplate, so the whole shape is excused once — the
212+/// naming convention *is* the decision.
202 fn is_storage_identifier(name: &str) -> bool {213 fn is_storage_identifier(name: &str) -> bool {
203- name.ends_with("_TABLE")214+ (name.ends_with("_TABLE") || name.ends_with("_FIELD"))
204 && !["MAX_", "MIN_", "DEFAULT_"]215 && !["MAX_", "MIN_", "DEFAULT_"]
205 .iter()216 .iter()
206 .any(|prefix| name.starts_with(prefix))217 .any(|prefix| name.starts_with(prefix))
tests/partial_patch_sessions.rsmodified+2 -1
@@ -1,7 +1,8 @@
1 //! Two concurrent partial PATCHes on the same session must not revert each1 //! Two concurrent partial PATCHes on the same session must not revert each
2 //! other, and — since only the fields a request carried are written — the2 //! other, and — since only the fields a request carried are written — the
3 //! `starts_at`/`ends_at` pair must not be invertible by two one-ended PATCHes3 //! `starts_at`/`ends_at` pair must not be invertible by two one-ended PATCHes
4-//! either (that is what `SESSION_LOCK` is for).4+//! either (that is what `FieldUpdate::ordered`'s in-statement range guard is
5+//! for).
5 6
6 mod common;7 mod common;
7 8
tests/persistence.rsmodified+89 -2
@@ -952,9 +952,10 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
952 assert_eq!(reply.get_content().as_str(), "aleykum selam");952 assert_eq!(reply.get_content().as_str(), "aleykum selam");
953 assert!(reply.get_completed_at().is_some());953 assert!(reply.get_completed_at().is_some());
954 assert_eq!(954 assert_eq!(
955- ChatbotMessage::list_for_thread(&id, &db)955+ ChatbotMessage::list_for_thread(&id, None, 0, &db)
956 .await956 .await
957 .expect("thread")957 .expect("thread")
958+ .0
958 .len(),959 .len(),
959 2960 2
960 );961 );
@@ -993,9 +994,10 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
993 .is_none()994 .is_none()
994 );995 );
995 assert_eq!(996 assert_eq!(
996- ChatbotThread::list_for_user(&owner, &db)997+ ChatbotThread::list_for_user(&owner, None, 0, &db)
997 .await998 .await
998 .unwrap()999 .unwrap()
1000+ .0
999 .len(),1001 .len(),
1000 01002 0
1001 );1003 );
@@ -1177,3 +1179,88 @@ async fn settings_slots_without_a_serving_minute_still_patch() {
1177 res.body1179 res.body
1178 );1180 );
1179 }1181 }
1182+
1183+/// Rows written before the cap counters existed (2026-07-27) carry no counter
1184+/// at all, and an absent counter reads as zero — which would hand a full course
1185+/// and a full note a clean slate. The backfill seeds each parent from the
1186+/// children it actually has, so the caps keep holding across the upgrade.
1187+#[tokio::test]
1188+async fn cap_counters_are_seeded_from_the_rows_that_predate_them() {
1189+ let (app, db) = common::app_and_db().await;
1190+ let teacher = common::login_as(&app, &db, "teacher", "teacher").await;
1191+ let ali = common::login(&app, "ali").await;
1192+ let veli = common::login(&app, "veli").await;
1193+ let ayse = common::login(&app, "ayse").await;
1194+ let (ali_id, veli_id, ayse_id) = (
1195+ me_id(&app, &ali).await,
1196+ me_id(&app, &veli).await,
1197+ me_id(&app, &ayse).await,
1198+ );
1199+
1200+ let res = send(
1201+ &app,
1202+ "POST",
1203+ "/courses",
1204+ Some(&teacher),
1205+ Some(json!({ "title": "small", "description": "", "capacity": 2 })),
1206+ )
1207+ .await;
1208+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1209+ let course = common::id_of(&res.body);
1210+ enroll(&app, &teacher, &course, &ali_id).await;
1211+ enroll(&app, &teacher, &course, &veli_id).await;
1212+
1213+ let res = send(
1214+ &app,
1215+ "POST",
1216+ "/notes",
1217+ Some(&ali),
1218+ Some(json!({ "title": "full", "content": "x" })),
1219+ )
1220+ .await;
1221+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1222+ let note = common::id_of(&res.body);
1223+ for i in 0..10 {
1224+ let up = common::upload_file(&app, &ali, &note, &format!("f{i}.txt"), "", b"x").await;
1225+ assert_eq!(up.status, StatusCode::CREATED, "seed file {i}");
1226+ }
1227+
1228+ // Age both parents into the pre-counter shape.
1229+ db.query("UPDATE course UNSET enrollment_count; UPDATE note UNSET file_count;")
1230+ .await
1231+ .expect("age the rows")
1232+ .check()
1233+ .expect("age the rows");
1234+
1235+ let app = reboot(&db).await;
1236+
1237+ let mut counters = db
1238+ .query("SELECT VALUE enrollment_count FROM course; SELECT VALUE file_count FROM note;")
1239+ .await
1240+ .expect("read counters")
1241+ .check()
1242+ .expect("read counters");
1243+ assert_eq!(
1244+ counters.take::<Vec<i64>>(0).expect("enrollment_count"),
1245+ vec![2],
1246+ "the course counter must be seeded from its roster"
1247+ );
1248+ assert_eq!(
1249+ counters.take::<Vec<i64>>(1).expect("file_count"),
1250+ vec![10],
1251+ "the note counter must be seeded from its files"
1252+ );
1253+
1254+ // And the caps still bite, which a zeroed counter would not have done.
1255+ let res = send(
1256+ &app,
1257+ "POST",
1258+ &format!("/courses/{course}/enrollments"),
1259+ Some(&teacher),
1260+ Some(json!({ "user_id": ayse_id })),
1261+ )
1262+ .await;
1263+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
1264+ let up = common::upload_file(&app, &ali, &note, "eleventh.txt", "", b"x").await;
1265+ assert_eq!(up.status, StatusCode::CONFLICT, "{}", up.body);
1266+}
tests/rate_limit.rsmodified+140 -0
@@ -310,6 +310,146 @@ async fn concurrent_bursts_never_over_admit() {
310 assert_eq!((ok, limited), (5, 15));310 assert_eq!((ok, limited), (5, 15));
311 }311 }
312 312
313+// --- shared across replicas --------------------------------------------
314+//
315+// Two `UserRateLimiter`s over one database stand in for two replicas: they are
316+// separate processes' worth of in-memory buckets, sharing only the `rate_limit`
317+// table. Time is paused, so a round of the sync task is driven by advancing
318+// past `RATE_SYNC_INTERVAL_SECS` — and because the task blocks on the database
319+// (not on time) mid-round, the short sleep afterwards cannot resolve until the
320+// round has finished. Assertions are on admissions, never on which replica won
321+// a race: the embedded engine can drop one of two concurrent writes and still
322+// answer `Ok`.
323+
324+use hezarfen_backend::constant::RATE_SYNC_INTERVAL_SECS;
325+use hezarfen_backend::database::Database;
326+use hezarfen_backend::rate_limit::UserRateLimiter;
327+use hezarfen_backend::state::DbHealth;
328+use std::time::Duration;
329+
330+/// A migrated in-memory database, with the clock frozen only afterwards: the
331+/// embedded engine has internal deadlines of its own and cannot start up under
332+/// a paused clock ("Insert node failed after 5 attempts due to timeout").
333+async fn shared_db() -> Database {
334+ let db = database::init_mem().await.expect("in-memory db");
335+ tokio::time::pause();
336+ db
337+}
338+
339+/// Let the sync task run one round: fire its timer, then hand it *real* time
340+/// to finish in. The real time is not optional — a round waits on the database,
341+/// and a paused clock auto-advances straight past a virtual sleep while it
342+/// does, so the assertions would race the round they are about.
343+async fn sync_round() {
344+ // Let a freshly spawned task reach its `sleep` first: `advance` moves the
345+ // clock *before* it yields, so a timer registered after it is registered
346+ // against the new now and would sit out the whole round.
347+ tokio::task::yield_now().await;
348+ tokio::time::advance(Duration::from_secs(RATE_SYNC_INTERVAL_SECS)).await;
349+ tokio::time::resume();
350+ tokio::time::sleep(Duration::from_millis(250)).await;
351+ tokio::time::pause();
352+}
353+
354+/// Two "replicas" of one tier, sharing `db`.
355+fn two_replicas(max: u32, db: &Database) -> (UserRateLimiter, UserRateLimiter, DbHealth) {
356+ let health = DbHealth::default();
357+ let (a, b) = (
358+ UserRateLimiter::per_user_minute(max),
359+ UserRateLimiter::per_user_minute(max),
360+ );
361+ a.share("test", db.clone(), health.clone());
362+ b.share("test", db.clone(), health.clone());
363+ (a, b, health)
364+}
365+
366+/// How many of `tries` requests a limiter admits for `user`.
367+fn admits(limiter: &UserRateLimiter, user: &str, tries: usize) -> usize {
368+ (0..tries)
369+ .filter(|_| limiter.enforce_user(user).is_ok())
370+ .count()
371+}
372+
373+#[tokio::test]
374+async fn two_replicas_share_one_budget() {
375+ let db = shared_db().await;
376+ let (a, b, _health) = two_replicas(6, &db);
377+
378+ // Both replicas spend freely until their first sync — the accepted
379+ // one-interval overshoot, and the whole reason the fleet needs the shared
380+ // row at all.
381+ let spent = admits(&a, "user:a", 6) + admits(&b, "user:a", 6);
382+ assert_eq!(spent, 12, "each replica starts on its own local budget");
383+
384+ // From the first sync on, the fleet total is what binds: neither replica
385+ // admits anything more in this window, whatever the interleaving was.
386+ sync_round().await;
387+ assert_eq!(
388+ admits(&a, "user:a", 6) + admits(&b, "user:a", 6),
389+ 0,
390+ "the shared budget is spent"
391+ );
392+
393+ // And the shared row agrees with what was actually admitted.
394+ let mut rows = db
395+ .query("SELECT VALUE hits FROM rate_limit")
396+ .await
397+ .expect("read shared counters");
398+ assert_eq!(rows.take::<Vec<i64>>(0).unwrap(), vec![spent as i64]);
399+}
400+
401+#[tokio::test]
402+async fn a_replica_that_never_admitted_still_learns_the_budget_is_gone() {
403+ let db = shared_db().await;
404+ let (a, b, _health) = two_replicas(4, &db);
405+
406+ // b spends one request, so it has a bucket to sync; a spends the rest.
407+ assert_eq!(admits(&b, "user:a", 1), 1);
408+ assert_eq!(admits(&a, "user:a", 3), 3);
409+ sync_round().await;
410+
411+ assert_eq!(
412+ admits(&b, "user:a", 3),
413+ 0,
414+ "the fleet total, not b's own count, is the cap"
415+ );
416+ // Other users are untouched by a spent bucket.
417+ assert_eq!(admits(&b, "user:b", 4), 4);
418+}
419+
420+#[tokio::test]
421+async fn a_down_database_leaves_each_replica_on_its_local_budget() {
422+ let db = shared_db().await;
423+ let (a, b, health) = two_replicas(3, &db);
424+ health.set(false);
425+
426+ // Nothing is shared while the database is down — and nothing stalls: both
427+ // replicas keep serving their own budgets at full speed.
428+ for _ in 0..3 {
429+ sync_round().await;
430+ assert_eq!(admits(&a, "user:a", 1), 1);
431+ assert_eq!(admits(&b, "user:a", 1), 1);
432+ }
433+ assert_eq!(admits(&a, "user:a", 1), 0, "the local budget still binds");
434+ assert_eq!(admits(&b, "user:a", 1), 0);
435+
436+ // Nothing was written, so the row the sync would have made does not exist.
437+ let mut rows = db
438+ .query("SELECT VALUE hits FROM rate_limit")
439+ .await
440+ .expect("read shared counters");
441+ assert_eq!(rows.take::<Vec<i64>>(0).unwrap(), Vec::<i64>::new());
442+
443+ // Recovery needs no restart: the next round shares again.
444+ health.set(true);
445+ sync_round().await;
446+ let mut rows = db
447+ .query("SELECT VALUE hits FROM rate_limit")
448+ .await
449+ .expect("read shared counters");
450+ assert_eq!(rows.take::<Vec<i64>>(0).unwrap(), vec![6]);
451+}
452+
313 /// Boot the app on a real TCP port, `ConnectInfo` wired exactly like `main`.453 /// Boot the app on a real TCP port, `ConnectInfo` wired exactly like `main`.
314 async fn spawn_server(rate_limit: RateLimitConfig) -> String {454 async fn spawn_server(rate_limit: RateLimitConfig) -> String {
315 let db = database::init_mem().await.expect("in-memory db");455 let db = database::init_mem().await.expect("in-memory db");
tests/spec_bounds.rsmodified+71 -20
@@ -780,26 +780,35 @@ fn expectations_cover_every_annotation() {
780 ];780 ];
781 781
782 let mut annotated = 0;782 let mut annotated = 0;
783- for entry in std::fs::read_dir(format!("{root}/src/web")).expect("read src/web") {783+ // Walk sub-directories too: a resource split into `web/<x>/` (exams) keeps
784- let path = entry.expect("dir entry").path();784+ // its annotations, and a flat read_dir would silently stop counting them.
785- if path.extension().is_none_or(|ext| ext != "rs") {785+ let mut dirs = vec![format!("{root}/src/web")];
786- continue;786+ while let Some(dir) = dirs.pop() {
787- }787+ for entry in std::fs::read_dir(&dir).expect("read src/web") {
788- let source = std::fs::read_to_string(&path).expect("read source");788+ let path = entry.expect("dir entry").path();
789- // Scan whole attributes, not lines: rustfmt wraps a long789+ if path.is_dir() {
790- // `#[schema(example = "…", max_length = 5_000)]` across several lines,790+ dirs.push(path.to_string_lossy().into_owned());
791- // and a line-based count silently misses the wrapped keyword.791+ continue;
792- //792+ }
793- // `#[param(...)]` bounds are query parameters, covered by793+ if path.extension().is_none_or(|ext| ext != "rs") {
794- // `every_page_limit_param_matches_its_constant` instead.794+ continue;
795- for (at, _) in source.match_indices("#[schema(") {795+ }
796- let rest = &source[at..];796+ let source = std::fs::read_to_string(&path).expect("read source");
797- let end = rest.find(")]").map_or(rest.len(), |end| end + 2);797+ // Scan whole attributes, not lines: rustfmt wraps a long
798- let attribute = &rest[..end];798+ // `#[schema(example = "…", max_length = 5_000)]` across several lines,
799- annotated += keywords799+ // and a line-based count silently misses the wrapped keyword.
800- .iter()800+ //
801- .filter(|kw| attribute.contains(&format!("{kw} = ")))801+ // `#[param(...)]` bounds are query parameters, covered by
802- .count();802+ // `every_page_limit_param_matches_its_constant` instead.
803+ for (at, _) in source.match_indices("#[schema(") {
804+ let rest = &source[at..];
805+ let end = rest.find(")]").map_or(rest.len(), |end| end + 2);
806+ let attribute = &rest[..end];
807+ annotated += keywords
808+ .iter()
809+ .filter(|kw| attribute.contains(&format!("{kw} = ")))
810+ .count();
811+ }
803 }812 }
804 }813 }
805 814
@@ -812,3 +821,45 @@ fn expectations_cover_every_annotation() {
812 expectations().len()821 expectations().len()
813 );822 );
814 }823 }
824+
825+/// The three image-meta bodies — exam question images, bank template images,
826+/// and pool question/solution photos — are hand-kept copies of one shape,
827+/// `{content_type, size}`. The write half behind them is shared
828+/// (`src/web/image.rs`), but the DTOs stay three types because their *names*
829+/// are the published contract, so nothing but this comparison of the emitted
830+/// JSON stops one of them from quietly growing a field the others lack.
831+#[tokio::test]
832+async fn the_image_meta_bodies_stay_the_same_shape() {
833+ let spec = spec().await;
834+ let schemas = &spec["components"]["schemas"];
835+
836+ // Field names with their JSON type, prose (description/example) stripped —
837+ // the wording is allowed to differ per system, the shape is not.
838+ let shape = |name: &str| -> Vec<String> {
839+ let properties = schemas[name]["properties"]
840+ .as_object()
841+ .unwrap_or_else(|| panic!("{name} is not an object schema — was it renamed?"));
842+ let mut fields: Vec<String> = properties
843+ .iter()
844+ .map(|(field, spec)| format!("{field}: {}/{}", spec["type"], spec["format"]))
845+ .collect();
846+ fields.sort();
847+ let mut required: Vec<String> = schemas[name]["required"]
848+ .as_array()
849+ .map(|items| items.iter().map(|item| item.to_string()).collect())
850+ .unwrap_or_default();
851+ required.sort();
852+ fields.push(format!("required: {required:?}"));
853+ fields
854+ };
855+
856+ let want = shape("ImageMetaResponse");
857+ for other in ["BankImageMeta", "PoolImageMeta"] {
858+ assert_eq!(
859+ want,
860+ shape(other),
861+ "{other} has drifted from ImageMetaResponse — the image-meta bodies are \
862+ copies of one shape and must be changed together"
863+ );
864+ }
865+}