From 6c87ecad6de69b1f38d7a3696d447e33e52cd1a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 27 Jul 2026 05:39:40 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=AA=A2=20guard=20writes=20in=20the?= =?UTF-8?q?=20database,=20not=20the=20process?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- README.md | 24 +- src/constant.rs | 781 +------ src/database.rs | 12 +- src/domain/answer_image.rs | 17 +- src/domain/appointment.rs | 341 ++- src/domain/attendance.rs | 15 +- src/domain/bank_question.rs | 104 +- src/domain/bank_question_image.rs | 15 +- src/domain/cap.rs | 133 ++ src/domain/chatbot_message.rs | 33 +- src/domain/chatbot_thread.rs | 63 +- src/domain/course.rs | 25 +- src/domain/course_session.rs | 44 +- src/domain/enrollment.rs | 112 +- src/domain/event.rs | 34 +- src/domain/exam.rs | 217 +- src/domain/exam_answer.rs | 16 +- src/domain/exam_attempt.rs | 78 +- src/domain/exam_question.rs | 103 +- src/domain/exam_result.rs | 56 +- src/domain/field_update.rs | 55 +- src/domain/homework_file.rs | 71 +- src/domain/key.rs | 54 + src/domain/meal_attendance.rs | 49 +- src/domain/meal_booking.rs | 50 +- src/domain/meal_ledger.rs | 24 +- src/domain/menu.rs | 24 +- src/domain/message.rs | 24 +- src/domain/mod.rs | 3 + src/domain/note.rs | 18 +- src/domain/note_file.rs | 103 +- src/domain/page.rs | 205 ++ src/domain/pool_question.rs | 3 +- src/domain/question_image.rs | 49 +- src/domain/registration.rs | 69 +- src/domain/session_attendance.rs | 15 +- src/domain/solution.rs | 32 +- src/domain/subject.rs | 15 +- src/domain/term.rs | 60 +- src/domain/timestamp.rs | 11 + src/domain/user.rs | 31 +- src/domain/work_entry.rs | 53 +- src/lib.rs | 10 +- src/migration_sql.rs | 787 +++++++ src/rate_limit.rs | 265 ++- src/web/appointments.rs | 10 +- src/web/auth.rs | 6 +- src/web/bank_questions.rs | 193 +- src/web/chatbot.rs | 20 +- src/web/courses.rs | 31 +- src/web/events.rs | 24 +- src/web/exam_ws.rs | 10 +- src/web/exams.rs | 3629 ----------------------------- src/web/exams/attempts.rs | 1004 ++++++++ src/web/exams/images.rs | 651 ++++++ src/web/exams/mod.rs | 842 +++++++ src/web/exams/questions.rs | 851 +++++++ src/web/exams/review.rs | 314 +++ src/web/homework.rs | 8 +- src/web/image.rs | 81 + src/web/marks.rs | 2 +- src/web/meals.rs | 41 +- src/web/messages.rs | 11 +- src/web/mod.rs | 12 +- src/web/notes.rs | 20 +- src/web/pomodoro.rs | 2 + src/web/questions.rs | 114 +- src/web/sessions.rs | 21 +- src/web/settings.rs | 4 +- src/web/terms.rs | 20 +- src/web/users.rs | 18 +- src/web/work.rs | 37 +- tests/integration.rs | 247 +- tests/limits_completeness.rs | 43 +- tests/partial_patch_sessions.rs | 3 +- tests/persistence.rs | 91 +- tests/rate_limit.rs | 140 ++ tests/spec_bounds.rs | 91 +- 78 files changed, 7515 insertions(+), 5379 deletions(-) create mode 100644 src/domain/cap.rs create mode 100644 src/domain/key.rs create mode 100644 src/domain/page.rs create mode 100644 src/migration_sql.rs delete mode 100644 src/web/exams.rs create mode 100644 src/web/exams/attempts.rs create mode 100644 src/web/exams/images.rs create mode 100644 src/web/exams/mod.rs create mode 100644 src/web/exams/questions.rs create mode 100644 src/web/exams/review.rs create mode 100644 src/web/image.rs diff --git a/README.md b/README.md index cee080d..ae1aa25 100644 --- a/README.md +++ b/README.md @@ -390,6 +390,15 @@ student's budget on another's. `0` disables it like the other two. It is charged before anything is written, so a `429` leaves no trace (see "Chatbot"). +All three tiers are **fleet-wide, not per replica**. Admission stays in memory +(no request ever waits on the database to be let in), and a background task in +each replica folds its new admits into one shared `rate_limit` row per tier + +client + minute every 2 seconds, then caps itself by the total that comes back. +Two replicas therefore enforce one budget, with one caveat: within a single +2-second interval a client that reaches both can spend up to the tier's budget +on each before the shared total tightens them. If the database is down the +tiers simply fall back to their own local budgets — nobody is refused for it. + Behind a reverse proxy every connection carries the proxy's address, so also set `TRUST_PROXY=true` to key clients by the rightmost `X-Forwarded-For` entry (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. | GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) · paged | | 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) | | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) | -| 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) | +| 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) | | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) | | POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled student** (upsert; course manager; students only; drafts can't be graded, `409`) | | 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. | GET | `/bank-questions` | teacher | The school-wide question bank — `?subject=` filters by origin subject, `?owner=` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) · paged | | 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) | | GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) | -| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question — the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze) | +| 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) | | DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) | | 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) | | GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) | @@ -2276,6 +2285,8 @@ src/ validate.rs field validators (used by every newtype's try_new) error.rs ValidationError + AppError -> HTTP responses database.rs SurrealDB server connect (ws) + SCHEMAFULL migration + migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR, + MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier state.rs AppState { db, files_path, cookie_secure, rate_limit, ai } ai/ QUIC bridge to the out-of-process AI services @@ -2294,6 +2305,12 @@ src/ PATCH actually carried (an omitted field is never written) monotonic_id.rs next_ulid: ids that sort in write order — one process-wide Generator, so same-millisecond rows never scramble + key.rs sitting(): the deterministic per-sitting record key shared by + attempts, answers, answer images and results (seq 1 stays bare) + cap.rs claim()/release(): the cross-replica count caps — an atomic + `UPDATE parent SET n += 1 WHERE n < cap` on a counter column + of the parent row, replacing the per-process mutexes that + only held while one instance owned the database text_fold.rs case- and diacritic-insensitive folding for search, shared by the Rust needle and the SurrealQL column (Turkish İ/ı, ü, ö…) session.rs SessionId · SessionToken · Session (7-day expiry) @@ -2393,7 +2410,8 @@ src/ Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory db), rate-limit (both tiers, proxy-header and peer-address keying, shipped -limits over every route), e2e (real TCP + reqwest cookie jar), persistence +limits over every route, two "replicas" sharing one budget over one db), e2e +(real TCP + reqwest cookie jar), persistence (tempfile file engine, including close + reopen), ai-bridge (real QUIC on loopback against a fake AI service), ai-protocol (the `hab/1` wire contract, driven by a client that shares no code with the backend). diff --git a/src/constant.rs b/src/constant.rs index 650c8d7..0584713 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -131,9 +131,12 @@ pub const MAX_SETTINGS_ITEM_LEN: usize = 50; pub const MAX_GRADE_BANDS: usize = 20; pub const MAX_GRADE_LABEL_LEN: usize = 20; -/// How many times `PATCH /settings` re-merges and retries when a concurrent -/// edit lands between its snapshot and its compare-and-set save. -pub const SETTINGS_UPDATE_RETRIES: usize = 3; +/// How many times a read-then-compare-and-set path (`PATCH /settings`, `PATCH +/// /bank/{bid}`, every appointment decision) re-reads and retries when a +/// concurrent edit lands between its snapshot and its save. A miss normally +/// re-validates into a `409`, so this only covers a write racing a legal +/// transition. +pub const CAS_UPDATE_RETRIES: usize = 3; pub const MAX_TERM_NAME_LEN: usize = 100; @@ -574,6 +577,27 @@ pub const DEFAULT_CHATBOT_RATE_LIMIT: u32 = 20; /// swept out on the next check. Keeps memory bounded without a reaper task. pub const PURGE_AT: usize = 10_000; +/// The shared counter every replica folds its local admits into, so N replicas +/// enforce one budget instead of N (see [`crate::rate_limit`]). +pub const RATE_LIMIT_TABLE: &str = "rate_limit"; + +/// How often a limiter pushes its admits and reads the fleet's total back. +/// The knob that decides the worst case: within one interval a replica can +/// admit up to its full local budget before the shared total tightens it, so +/// short enough to matter and long enough to stay one query per tier per tick. +pub const RATE_SYNC_INTERVAL_SECS: u64 = 2; + +/// How long one sync round may wait on the database. The SDK *parks* a query +/// while the socket is down instead of failing it, so the liveness flag alone +/// cannot stop a round wedging the task forever — this is the backstop that +/// keeps the limiter purely local through an outage instead of stalled. +pub const RATE_SYNC_TIMEOUT_SECS: u64 = 5; + +/// How many client buckets one round syncs. A round is a single query holding +/// one statement per bucket, so this bounds both its size and the write volume +/// a burst of distinct clients can put on the database. +pub const RATE_SYNC_MAX_KEYS: usize = 512; + // --- time spans -------------------------------------------------------- pub const MILLIS_PER_DAY: i64 = 24 * 60 * 60 * 1000; @@ -719,6 +743,30 @@ pub const MEAL_BOOKING_TABLE: &str = "meal_booking"; pub const MEAL_ATTENDANCE_TABLE: &str = "meal_attendance"; pub const MEAL_LEDGER_TABLE: &str = "meal_ledger"; +// --- cross-replica cap counters ---------------------------------------- + +/// The counter columns behind the count caps (see [`crate::domain::cap`]). +/// Each one lives on the *parent* row, because a single-record conditional +/// `UPDATE` is the only guard that holds when the writers are in different +/// processes. Spelled here rather than at the call site so the field a claim +/// increments and the field a delete decrements cannot drift apart; the +/// definitions themselves are in `MIGRATION`, and a typo there is caught by +/// SCHEMAFULL refusing the write. +pub const ENROLLMENT_COUNT_FIELD: &str = "enrollment_count"; +pub const REGISTRATION_COUNT_FIELD: &str = "registration_count"; +pub const NOTE_FILE_COUNT_FIELD: &str = "file_count"; +pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count"; +pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count"; + +/// How hard a counter write tries before giving up, and the first backoff step +/// it sleeps between attempts (doubling, plus jitter). Contention on one record +/// is the guard working as designed, and SurrealDB answers it by aborting the +/// loser's transaction — so these two numbers are what turn "retry the +/// transaction" into a queue. Sized for one HTTP burst of racers on a single +/// parent: seven doublings from 2ms is a quarter of a second of patience. +pub const CAP_WRITE_TRIES: usize = 8; +pub const CAP_WRITE_BACKOFF_MS: u64 = 2; + // --- boot leader election ---------------------------------------------- /// The lock row every booting process races for (see @@ -799,730 +847,3 @@ pub const MIGRATION_LOCK_HEARTBEAT_SECS: u64 = 5; /// serving on a schema nobody confirmed — is worse. pub const MIGRATION_LOCK_WAIT_SECS: u64 = 180; pub const MIGRATION_LOCK_POLL_MS: u64 = 200; - -// --- schema migration SQL ---------------------------------------------- - -/// Repairs that must run *before* the DDL batch, because the DDL is what makes -/// them impossible. -/// -/// `MIGRATION` retires `exam_question.source_bank` with `REMOVE FIELD`, and -/// once the column is gone SCHEMAFULL rejects every write to a row that still -/// stores it ("Found field 'source_bank', but no such field exists") — an -/// UNSET included. So the value has to go while its definition is still -/// standing. Runs as its own query for the usual reason (see `MIGRATION`). -/// -/// The table-exists guard is load-bearing: on a fresh database `MIGRATION` has -/// not run yet, and an UPDATE against an undefined table is an error, not an -/// empty result. On a database that has the table but never had the column the -/// `WHERE` simply matches nothing. -pub const PRE_REPAIR: &str = " - IF 'exam_question' IN object::keys((INFO FOR DB).tables) { - UPDATE exam_question UNSET source_bank WHERE source_bank != NONE - }; -"; - -/// SCHEMAFULL schema: every column is typed, references use `record<..>`. -/// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the -/// definitions and `REMOVE ... IF EXISTS` retires schema (like the -/// single-attempt unique index) exactly once. DDL only — data backfills live -/// in `BACKFILL`, which runs as a *separate* query: statements inside one -/// batch see the schema as it stood when the batch started, so an UPDATE next -/// to a fresh `DEFINE FIELD audience.*` writes against the old field set and -/// SCHEMAFULL silently strips the very keys being backfilled. -pub const MIGRATION: &str = " - DEFINE TABLE IF NOT EXISTS user SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS username ON user TYPE string; - DEFINE FIELD IF NOT EXISTS password_hash ON user TYPE string; - DEFINE FIELD IF NOT EXISTS role ON user TYPE string DEFAULT 'student'; - DEFINE FIELD IF NOT EXISTS name ON user TYPE option; - DEFINE FIELD IF NOT EXISTS surname ON user TYPE option; - DEFINE FIELD IF NOT EXISTS email ON user TYPE option; - DEFINE FIELD IF NOT EXISTS phone ON user TYPE option; - DEFINE FIELD IF NOT EXISTS birth_date ON user TYPE option; - DEFINE FIELD IF NOT EXISTS theme ON user TYPE option; - DEFINE FIELD IF NOT EXISTS language ON user TYPE option; - DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; - - DEFINE TABLE IF NOT EXISTS session SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS user ON session TYPE record; - DEFINE FIELD IF NOT EXISTS token ON session TYPE string; - DEFINE FIELD IF NOT EXISTS expires_at ON session TYPE int; - DEFINE INDEX IF NOT EXISTS session_token ON session FIELDS token UNIQUE; - DEFINE INDEX IF NOT EXISTS session_expires ON session FIELDS expires_at; - - DEFINE TABLE IF NOT EXISTS note SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS user ON note TYPE record; - DEFINE FIELD IF NOT EXISTS title ON note TYPE string; - DEFINE FIELD IF NOT EXISTS content ON note TYPE string; - DEFINE INDEX IF NOT EXISTS note_user ON note FIELDS user; - - DEFINE TABLE IF NOT EXISTS message SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS sender ON message TYPE record; - DEFINE FIELD IF NOT EXISTS recipient ON message TYPE record; - DEFINE FIELD IF NOT EXISTS subject ON message TYPE string; - DEFINE FIELD IF NOT EXISTS body ON message TYPE string; - DEFINE FIELD IF NOT EXISTS label ON message TYPE option; - DEFINE FIELD IF NOT EXISTS sent_at ON message TYPE int; - DEFINE FIELD IF NOT EXISTS read ON message TYPE bool DEFAULT false; - DEFINE FIELD IF NOT EXISTS sender_folder ON message TYPE string DEFAULT 'sent'; - DEFINE FIELD IF NOT EXISTS recipient_folder ON message TYPE string DEFAULT 'inbox'; - -- Where each side's copy sat before it was filed into archive/trash, so a - -- restore lands where it came from. NONE while the copy is in its home - -- folder — and on rows filed before this field existed (2026-07-23), which - -- restore to the home folder just as they always did. - DEFINE FIELD IF NOT EXISTS sender_origin ON message TYPE option; - DEFINE FIELD IF NOT EXISTS recipient_origin ON message TYPE option; - DEFINE INDEX IF NOT EXISTS message_sender ON message FIELDS sender; - DEFINE INDEX IF NOT EXISTS message_recipient ON message FIELDS recipient; - - DEFINE TABLE IF NOT EXISTS note_file SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS note ON note_file TYPE record; - DEFINE FIELD IF NOT EXISTS name ON note_file TYPE string; - DEFINE FIELD IF NOT EXISTS content_type ON note_file TYPE string; - DEFINE FIELD IF NOT EXISTS size ON note_file TYPE int; - DEFINE INDEX IF NOT EXISTS note_file_note ON note_file FIELDS note; - - -- Chatbot relay (2026-07-23): a `thread` groups the turns, one - -- `chatbot_message` is one turn. `user_id` rides on the message too so an - -- ownership check needs no join. An assistant turn is born `pending` and - -- is completed (or failed) by the task holding the AI-bridge stream — - -- hence the BACKFILL sweep, since that task dies with the process. - DEFINE TABLE IF NOT EXISTS chatbot_thread SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS user_id ON chatbot_thread TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS title ON chatbot_thread TYPE option; - DEFINE FIELD IF NOT EXISTS created_at ON chatbot_thread TYPE int READONLY; - DEFINE FIELD IF NOT EXISTS updated_at ON chatbot_thread TYPE int; - DEFINE INDEX IF NOT EXISTS chatbot_thread_user_updated ON chatbot_thread FIELDS user_id, updated_at; - - DEFINE TABLE IF NOT EXISTS chatbot_message SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS thread_id ON chatbot_message TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS user_id ON chatbot_message TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS role ON chatbot_message TYPE string READONLY; - DEFINE FIELD IF NOT EXISTS content ON chatbot_message TYPE string; - DEFINE FIELD IF NOT EXISTS status ON chatbot_message TYPE string; - DEFINE FIELD IF NOT EXISTS truncated ON chatbot_message TYPE bool DEFAULT false; - DEFINE FIELD IF NOT EXISTS error_code ON chatbot_message TYPE option; - DEFINE FIELD IF NOT EXISTS created_at ON chatbot_message TYPE int READONLY; - DEFINE FIELD IF NOT EXISTS completed_at ON chatbot_message TYPE option; - -- The claim (2026-07-27): which replica's claim loop owes this turn an - -- answer, and when it said so. Absent = nobody has taken it yet; a claim - -- older than CHATBOT_CLAIM_RECLAIM_SECS is a dead claimer and the turn is - -- taken back (see `CHATBOT_CLAIM`). - DEFINE FIELD IF NOT EXISTS claimed_by ON chatbot_message TYPE option; - DEFINE FIELD IF NOT EXISTS claimed_at ON chatbot_message TYPE option; - DEFINE INDEX IF NOT EXISTS chatbot_message_thread_created ON chatbot_message FIELDS thread_id, created_at; - DEFINE INDEX IF NOT EXISTS chatbot_message_user ON chatbot_message FIELDS user_id; - -- The claim loop's sweep: every poll asks for pending rows by age. - DEFINE INDEX IF NOT EXISTS chatbot_message_status_created ON chatbot_message FIELDS status, created_at; - - -- Which AI workers are connected to *any* replica (2026-07-27). The GATE - -- and nothing else: a row only says a socket existed somewhere at - -- `seen_at`, so it may spare a user a 503 but must never pick who answers - -- — that is the in-process registry's call. Heartbeated by the replica - -- owning the connection; a stale row is ignored by the read and swept. - DEFINE TABLE IF NOT EXISTS ai_worker SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS service ON ai_worker TYPE string; - DEFINE FIELD IF NOT EXISTS capabilities ON ai_worker TYPE array; - DEFINE FIELD IF NOT EXISTS seen_at ON ai_worker TYPE int; - - DEFINE TABLE IF NOT EXISTS event SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS creator ON event TYPE record; - DEFINE FIELD IF NOT EXISTS title ON event TYPE string; - DEFINE FIELD IF NOT EXISTS description ON event TYPE string; - DEFINE FIELD IF NOT EXISTS audience ON event TYPE object; - DEFINE FIELD IF NOT EXISTS audience.kind ON event TYPE string; - DEFINE FIELD IF NOT EXISTS audience.role ON event TYPE option; - DEFINE FIELD IF NOT EXISTS audience.course ON event TYPE option>; - DEFINE FIELD IF NOT EXISTS audience.capacity ON event TYPE option; - REMOVE FIELD IF EXISTS audience.users ON TABLE event; - DEFINE FIELD IF NOT EXISTS starts_at ON event TYPE option; - DEFINE FIELD IF NOT EXISTS ends_at ON event TYPE option; - - DEFINE TABLE IF NOT EXISTS attendance SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS event ON attendance TYPE record; - DEFINE FIELD IF NOT EXISTS user ON attendance TYPE record; - DEFINE FIELD IF NOT EXISTS status ON attendance TYPE string; - DEFINE FIELD IF NOT EXISTS marked_by ON attendance TYPE record; - DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE; - DEFINE INDEX IF NOT EXISTS attendance_user ON attendance FIELDS user; - - DEFINE TABLE IF NOT EXISTS registration SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS event ON registration TYPE record; - DEFINE FIELD IF NOT EXISTS user ON registration TYPE record; - DEFINE FIELD IF NOT EXISTS registered_by ON registration TYPE record; - DEFINE INDEX IF NOT EXISTS registration_event_user ON registration FIELDS event, user UNIQUE; - DEFINE INDEX IF NOT EXISTS registration_event ON registration FIELDS event; - - DEFINE TABLE IF NOT EXISTS term SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS name ON term TYPE string; - DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int; - DEFINE FIELD IF NOT EXISTS ends_at ON term TYPE int; - - DEFINE TABLE IF NOT EXISTS course SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS creator ON course TYPE record; - DEFINE FIELD IF NOT EXISTS teachers ON course TYPE array> DEFAULT []; - DEFINE FIELD IF NOT EXISTS teachers[*] ON course TYPE record; - DEFINE FIELD IF NOT EXISTS title ON course TYPE string; - DEFINE FIELD IF NOT EXISTS description ON course TYPE string; - DEFINE FIELD IF NOT EXISTS kind ON course TYPE string DEFAULT 'course'; - DEFINE FIELD IF NOT EXISTS term ON course TYPE option>; - DEFINE FIELD IF NOT EXISTS capacity ON course TYPE option; - - DEFINE TABLE IF NOT EXISTS subject SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS course ON subject TYPE record; - DEFINE FIELD IF NOT EXISTS name ON subject TYPE string; - DEFINE FIELD IF NOT EXISTS description ON subject TYPE string; - DEFINE INDEX IF NOT EXISTS subject_course ON subject FIELDS course; - - DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS course ON enrollment TYPE record; - DEFINE FIELD IF NOT EXISTS user ON enrollment TYPE record; - DEFINE FIELD IF NOT EXISTS enrolled_by ON enrollment TYPE record; - DEFINE INDEX IF NOT EXISTS enrollment_course_user ON enrollment FIELDS course, user UNIQUE; - DEFINE INDEX IF NOT EXISTS enrollment_user ON enrollment FIELDS user; - - DEFINE TABLE IF NOT EXISTS parent_link SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS parent ON parent_link TYPE record; - DEFINE FIELD IF NOT EXISTS student ON parent_link TYPE record; - DEFINE FIELD IF NOT EXISTS linked_by ON parent_link TYPE record; - DEFINE INDEX IF NOT EXISTS parent_link_parent_student ON parent_link FIELDS parent, student UNIQUE; - DEFINE INDEX IF NOT EXISTS parent_link_parent ON parent_link FIELDS parent; - DEFINE INDEX IF NOT EXISTS parent_link_student ON parent_link FIELDS student; - - DEFINE TABLE IF NOT EXISTS course_session SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS course ON course_session TYPE record; - DEFINE FIELD IF NOT EXISTS teacher ON course_session TYPE record; - DEFINE FIELD IF NOT EXISTS topic ON course_session TYPE string; - DEFINE FIELD IF NOT EXISTS starts_at ON course_session TYPE int; - DEFINE FIELD IF NOT EXISTS ends_at ON course_session TYPE option; - DEFINE INDEX IF NOT EXISTS course_session_course ON course_session FIELDS course; - - DEFINE TABLE IF NOT EXISTS session_attendance SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS session ON session_attendance TYPE record; - DEFINE FIELD IF NOT EXISTS course ON session_attendance TYPE record; - DEFINE FIELD IF NOT EXISTS user ON session_attendance TYPE record; - DEFINE FIELD IF NOT EXISTS status ON session_attendance TYPE string; - DEFINE FIELD IF NOT EXISTS marked_by ON session_attendance TYPE record; - DEFINE INDEX IF NOT EXISTS session_attendance_session_user ON session_attendance FIELDS session, user UNIQUE; - DEFINE INDEX IF NOT EXISTS session_attendance_session ON session_attendance FIELDS session; - DEFINE INDEX IF NOT EXISTS session_attendance_user ON session_attendance FIELDS user; - DEFINE INDEX IF NOT EXISTS session_attendance_course ON session_attendance FIELDS course; - - DEFINE TABLE IF NOT EXISTS work_entry SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS user ON work_entry TYPE record; - DEFINE FIELD IF NOT EXISTS check_in ON work_entry TYPE int; - DEFINE FIELD IF NOT EXISTS check_out ON work_entry TYPE option; - DEFINE INDEX IF NOT EXISTS work_entry_user ON work_entry FIELDS user; - - DEFINE TABLE IF NOT EXISTS pomodoro_session SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS user ON pomodoro_session TYPE record; - DEFINE FIELD IF NOT EXISTS started_at ON pomodoro_session TYPE int; - DEFINE FIELD IF NOT EXISTS finished_at ON pomodoro_session TYPE option; - DEFINE INDEX IF NOT EXISTS pomodoro_session_user ON pomodoro_session FIELDS user; - - DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS creator ON exam TYPE record; - DEFINE FIELD IF NOT EXISTS course ON exam TYPE record; - DEFINE FIELD IF NOT EXISTS title ON exam TYPE string; - DEFINE FIELD IF NOT EXISTS description ON exam TYPE string; - DEFINE FIELD IF NOT EXISTS kind ON exam TYPE string; - DEFINE FIELD IF NOT EXISTS mode ON exam TYPE option; - DEFINE FIELD IF NOT EXISTS starts_at ON exam TYPE option; - DEFINE FIELD IF NOT EXISTS ends_at ON exam TYPE option; - DEFINE FIELD IF NOT EXISTS duration_ms ON exam TYPE option; - DEFINE FIELD IF NOT EXISTS max_attempts ON exam TYPE int DEFAULT 1; - DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true; - DEFINE FIELD IF NOT EXISTS allow_review ON exam TYPE bool DEFAULT false; - DEFINE FIELD IF NOT EXISTS draft ON exam TYPE bool DEFAULT false; - DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course; - - DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS exam ON exam_attempt TYPE record; - DEFINE FIELD IF NOT EXISTS user ON exam_attempt TYPE record; - DEFINE FIELD IF NOT EXISTS seq ON exam_attempt TYPE int DEFAULT 1; - DEFINE FIELD IF NOT EXISTS started_at ON exam_attempt TYPE int; - DEFINE FIELD IF NOT EXISTS finished_at ON exam_attempt TYPE option; - DEFINE FIELD IF NOT EXISTS left_at ON exam_attempt TYPE option; - DEFINE INDEX IF NOT EXISTS exam_attempt_exam_user_seq ON exam_attempt FIELDS exam, user, seq UNIQUE; - DEFINE INDEX IF NOT EXISTS exam_attempt_exam ON exam_attempt FIELDS exam; - - DEFINE TABLE IF NOT EXISTS exam_question SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS exam ON exam_question TYPE record; - DEFINE FIELD IF NOT EXISTS text ON exam_question TYPE string; - DEFINE FIELD IF NOT EXISTS kind ON exam_question TYPE string; - DEFINE FIELD IF NOT EXISTS points ON exam_question TYPE int; - -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices - -- gained stable ids (`array`/`int` -> `array`/`string`), - -- and IF NOT EXISTS would leave an existing database on the old types. - DEFINE FIELD OVERWRITE choices ON exam_question TYPE option>; - -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice - -- object's own fields are declared too (same shape as `settings.exam_kinds`). - DEFINE FIELD OVERWRITE choices.*.id ON exam_question TYPE string; - DEFINE FIELD OVERWRITE choices.*.text ON exam_question TYPE string; - DEFINE FIELD OVERWRITE correct ON exam_question TYPE option; - DEFINE FIELD IF NOT EXISTS subject ON exam_question TYPE record; - -- Provenance, one column per direction: `from_bank` is the template this - -- question was inserted from, `banked_as` the template most recently minted - -- by saving it into the bank. They replace the single `source_bank`, which - -- both directions wrote — so a question inserted from the bank read as - -- already-saved. OVERWRITE (not IF NOT EXISTS): the old column has to - -- actually go on an existing database, or SCHEMAFULL keeps accepting it - -- while the struct no longer writes it. - DEFINE FIELD OVERWRITE from_bank ON exam_question TYPE option>; - DEFINE FIELD OVERWRITE banked_as ON exam_question TYPE option>; - REMOVE FIELD IF EXISTS source_bank ON TABLE exam_question; - DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam; - DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject; - - DEFINE TABLE IF NOT EXISTS question_image SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS exam ON question_image TYPE record; - DEFINE FIELD IF NOT EXISTS question ON question_image TYPE record; - -- OVERWRITE: `slot` is now the choice's id, not its position. - DEFINE FIELD OVERWRITE slot ON question_image TYPE option; - DEFINE FIELD IF NOT EXISTS file ON question_image TYPE string; - DEFINE FIELD IF NOT EXISTS content_type ON question_image TYPE string; - DEFINE FIELD IF NOT EXISTS size ON question_image TYPE int; - DEFINE INDEX IF NOT EXISTS question_image_exam ON question_image FIELDS exam; - DEFINE INDEX IF NOT EXISTS question_image_question ON question_image FIELDS question; - - DEFINE TABLE IF NOT EXISTS bank_question SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS owner ON bank_question TYPE record; - -- OVERWRITE, not IF NOT EXISTS: the field started life as a required - -- `record` and has to actually change type on an existing database, - -- otherwise the subject-delete cascade (`SET subject = NONE`) is rejected. - DEFINE FIELD OVERWRITE subject ON bank_question TYPE option>; - DEFINE FIELD IF NOT EXISTS text ON bank_question TYPE string; - DEFINE FIELD IF NOT EXISTS kind ON bank_question TYPE string; - DEFINE FIELD IF NOT EXISTS points ON bank_question TYPE int; - -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices - -- gained stable ids (`array`/`int` -> `array`/`string`), - -- and IF NOT EXISTS would leave an existing database on the old types. - DEFINE FIELD OVERWRITE choices ON bank_question TYPE option>; - -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice - -- object's own fields are declared too (same shape as `settings.exam_kinds`). - DEFINE FIELD OVERWRITE choices.*.id ON bank_question TYPE string; - DEFINE FIELD OVERWRITE choices.*.text ON bank_question TYPE string; - DEFINE FIELD OVERWRITE correct ON bank_question TYPE option; - DEFINE FIELD IF NOT EXISTS source_exam ON bank_question TYPE option>; - -- 'private' | 'school'. DEFAULT so a row that predates the field (or any - -- partial write) can never come out published: the answer key stays the - -- owner's until they publish it. - DEFINE FIELD IF NOT EXISTS visibility ON bank_question TYPE string DEFAULT 'private'; - DEFINE FIELD IF NOT EXISTS created_at ON bank_question TYPE int READONLY; - DEFINE INDEX IF NOT EXISTS bank_question_owner ON bank_question FIELDS owner; - DEFINE INDEX IF NOT EXISTS bank_question_subject ON bank_question FIELDS subject; - - DEFINE TABLE IF NOT EXISTS bank_question_image SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS bank_question ON bank_question_image TYPE record; - -- OVERWRITE: `slot` is now the choice's id, not its position. - DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option; - DEFINE FIELD IF NOT EXISTS file ON bank_question_image TYPE string; - DEFINE FIELD IF NOT EXISTS content_type ON bank_question_image TYPE string; - DEFINE FIELD IF NOT EXISTS size ON bank_question_image TYPE int; - DEFINE INDEX IF NOT EXISTS bank_question_image_question ON bank_question_image FIELDS bank_question; - - DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record; - DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record; - DEFINE FIELD IF NOT EXISTS user ON exam_answer TYPE record; - -- OVERWRITE: `selected` now names the picked option by id. - DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option; - DEFINE FIELD IF NOT EXISTS text ON exam_answer TYPE option; - DEFINE FIELD IF NOT EXISTS updated_at ON exam_answer TYPE int; - -- `seq` numbers the sitting an answer belongs to (1, 2, …), mirroring - -- exam_attempt. It rides the record key too, so a retake's answer is a new - -- row, not an overwrite of the prior sitting. - DEFINE FIELD IF NOT EXISTS seq ON exam_answer TYPE int DEFAULT 1; - -- Retire the pre-history unique index: (question, user) is no longer unique - -- once a student re-sits; (question, user, seq) is. - REMOVE INDEX IF EXISTS exam_answer_question_user ON exam_answer; - DEFINE INDEX IF NOT EXISTS exam_answer_question_user_seq ON exam_answer FIELDS question, user, seq UNIQUE; - DEFINE INDEX IF NOT EXISTS exam_answer_exam_user ON exam_answer FIELDS exam, user; - DEFINE INDEX IF NOT EXISTS exam_answer_exam ON exam_answer FIELDS exam; - - DEFINE TABLE IF NOT EXISTS answer_image SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS exam ON answer_image TYPE record; - DEFINE FIELD IF NOT EXISTS question ON answer_image TYPE record; - DEFINE FIELD IF NOT EXISTS user ON answer_image TYPE record; - DEFINE FIELD IF NOT EXISTS file ON answer_image TYPE string; - DEFINE FIELD IF NOT EXISTS content_type ON answer_image TYPE string; - DEFINE FIELD IF NOT EXISTS size ON answer_image TYPE int; - -- `seq` numbers the sitting this drawing belongs to; it rides the record - -- key so a retake's image never overwrites the prior sitting's. - DEFINE FIELD IF NOT EXISTS seq ON answer_image TYPE int DEFAULT 1; - DEFINE INDEX IF NOT EXISTS answer_image_exam ON answer_image FIELDS exam; - DEFINE INDEX IF NOT EXISTS answer_image_user ON answer_image FIELDS user; - - DEFINE TABLE IF NOT EXISTS exam_result SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS exam ON exam_result TYPE record; - DEFINE FIELD IF NOT EXISTS user ON exam_result TYPE record; - DEFINE FIELD IF NOT EXISTS mark ON exam_result TYPE int; - DEFINE FIELD IF NOT EXISTS graded_by ON exam_result TYPE record; - -- `seq` numbers the sitting a mark belongs to; a retake earns its own mark - -- row, and the latest seq is the student's standing. - DEFINE FIELD IF NOT EXISTS seq ON exam_result TYPE int DEFAULT 1; - REMOVE INDEX IF EXISTS exam_result_exam_user ON exam_result; - DEFINE INDEX IF NOT EXISTS exam_result_exam_user_seq ON exam_result FIELDS exam, user, seq UNIQUE; - - DEFINE TABLE IF NOT EXISTS pool_question SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS asker ON pool_question TYPE record; - DEFINE FIELD IF NOT EXISTS title ON pool_question TYPE string; - DEFINE FIELD IF NOT EXISTS body ON pool_question TYPE string; - DEFINE FIELD IF NOT EXISTS status ON pool_question TYPE string DEFAULT 'pending'; - DEFINE FIELD IF NOT EXISTS asked_at ON pool_question TYPE int; - DEFINE FIELD IF NOT EXISTS approved_by ON pool_question TYPE option>; - DEFINE FIELD IF NOT EXISTS image_file ON pool_question TYPE option; - DEFINE FIELD IF NOT EXISTS image_content_type ON pool_question TYPE option; - DEFINE FIELD IF NOT EXISTS image_size ON pool_question TYPE option; - DEFINE INDEX IF NOT EXISTS pool_question_status ON pool_question FIELDS status; - DEFINE INDEX IF NOT EXISTS pool_question_asker ON pool_question FIELDS asker; - - DEFINE TABLE IF NOT EXISTS solution SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS question ON solution TYPE record; - DEFINE FIELD IF NOT EXISTS author ON solution TYPE record; - DEFINE FIELD IF NOT EXISTS body ON solution TYPE string; - DEFINE FIELD IF NOT EXISTS offered_at ON solution TYPE int; - DEFINE FIELD IF NOT EXISTS image_file ON solution TYPE option; - DEFINE FIELD IF NOT EXISTS image_content_type ON solution TYPE option; - DEFINE FIELD IF NOT EXISTS image_size ON solution TYPE option; - DEFINE INDEX IF NOT EXISTS solution_question ON solution FIELDS question; - - DEFINE TABLE IF NOT EXISTS settings SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS exam_kinds ON settings TYPE array; - DEFINE FIELD IF NOT EXISTS exam_kinds.*.name ON settings TYPE string; - DEFINE FIELD IF NOT EXISTS exam_kinds.*.weight ON settings TYPE int; - DEFINE FIELD IF NOT EXISTS attendance_statuses ON settings TYPE array; - DEFINE FIELD IF NOT EXISTS grade_bands ON settings TYPE array; - DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int; - DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string; - DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option; - DEFINE FIELD IF NOT EXISTS chatbot_history_turns ON settings TYPE option; - DEFINE FIELD IF NOT EXISTS max_chatbot_threads ON settings TYPE option; - DEFINE FIELD IF NOT EXISTS max_chatbot_message_len ON settings TYPE option; - -- Food program (2026-07-26). `meal_slots` mirrors the `exam_kinds` shape — - -- a named list a menu snapshots from — and `dietary_tags` mirrors - -- `attendance_statuses`. `meal_cancel_cutoff_minutes` is ONE knob for both - -- the booking and the cancel deadline; absent means no cutoff at all. All - -- three are `option<>`, exactly like `max_file_bytes`: NOT `DEFAULT []`. - -- `DEFAULT` fires on create only, and `PATCH /settings` writes the whole - -- row with `UPDATE ... CONTENT`, so a required-with-default field a writer - -- omits coerces to NONE and fails every settings write until the domain - -- struct carries it. `option<>` also means the existing singleton reads - -- fine, which is why the food program needs no BACKFILL anywhere. - DEFINE FIELD IF NOT EXISTS meal_slots ON settings TYPE option>; - DEFINE FIELD IF NOT EXISTS meal_slots.*.name ON settings TYPE string; - -- Minutes past midnight UTC at which the slot is served (2026-07-26). - -- `option` for the same reason the list itself is: slots written - -- before the field existed simply have no key, and read back as NONE -> - -- the booking cutoff falls back to midnight UTC, its old meaning. No - -- BACKFILL, and no DEFAULT — see the note above. - DEFINE FIELD IF NOT EXISTS meal_slots.*.serving_minute ON settings TYPE option; - DEFINE FIELD IF NOT EXISTS dietary_tags ON settings TYPE option>; - DEFINE FIELD IF NOT EXISTS meal_cancel_cutoff_minutes ON settings TYPE option; - - -- Homework (greenfield, 2026-07-22): a teacher assigns per course, students - -- submit files + optional text, a teacher grades a status + optional mark. - -- `course`/`created_by`/`created_at` are READONLY (a homework never moves - -- course, and stamps never rewrite); `subject` is NOT — it is re-taggable - -- via PATCH. `assigned` NONE/empty means the whole course. No BACKFILL: the - -- tables are new, so the whole migration stays additive and idempotent. - DEFINE TABLE IF NOT EXISTS homework SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS course ON homework TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS subject ON homework TYPE record; - DEFINE FIELD IF NOT EXISTS title ON homework TYPE string; - DEFINE FIELD IF NOT EXISTS description ON homework TYPE option; - DEFINE FIELD IF NOT EXISTS due_at ON homework TYPE int; - DEFINE FIELD IF NOT EXISTS assigned ON homework TYPE option>>; - DEFINE FIELD IF NOT EXISTS assigned[*] ON homework TYPE record; - DEFINE FIELD IF NOT EXISTS created_by ON homework TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS created_at ON homework TYPE int READONLY; - DEFINE INDEX IF NOT EXISTS homework_course ON homework FIELDS course; - - DEFINE TABLE IF NOT EXISTS homework_submission SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS homework ON homework_submission TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS user ON homework_submission TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS text ON homework_submission TYPE option; - DEFINE FIELD IF NOT EXISTS submitted_at ON homework_submission TYPE int READONLY; - DEFINE FIELD IF NOT EXISTS updated_at ON homework_submission TYPE int; - DEFINE INDEX IF NOT EXISTS homework_submission_homework ON homework_submission FIELDS homework; - - DEFINE TABLE IF NOT EXISTS homework_file SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS submission ON homework_file TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS name ON homework_file TYPE string; - DEFINE FIELD IF NOT EXISTS content_type ON homework_file TYPE string; - DEFINE FIELD IF NOT EXISTS size ON homework_file TYPE int; - DEFINE FIELD IF NOT EXISTS file ON homework_file TYPE string READONLY; - DEFINE FIELD IF NOT EXISTS created_at ON homework_file TYPE int READONLY; - DEFINE INDEX IF NOT EXISTS homework_file_submission ON homework_file FIELDS submission; - - DEFINE TABLE IF NOT EXISTS homework_result SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS homework ON homework_result TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS user ON homework_result TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS status ON homework_result TYPE string; - DEFINE FIELD IF NOT EXISTS mark ON homework_result TYPE option; - DEFINE FIELD IF NOT EXISTS graded_by ON homework_result TYPE record; - DEFINE FIELD IF NOT EXISTS created_at ON homework_result TYPE int; - DEFINE INDEX IF NOT EXISTS homework_result_homework ON homework_result FIELDS homework; - - -- Appointments (greenfield, 2026-07-23): a teacher publishes availability - -- slots, a student or parent books one. `series` groups the occurrences a - -- weekly repeat expanded into, so one cancel deletes one row and a series - -- delete finds the rest. A booking's live/dead state is the `status` - -- string; occupancy is derived from it under the appointment lock rather - -- than stored, so a rejected or cancelled booking frees its slot again. - -- The `proposed_*` fields carry a teacher's counter-proposal on the same - -- row until the requester accepts. No BACKFILL: both tables are new. - DEFINE TABLE IF NOT EXISTS appointment_slot SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS teacher ON appointment_slot TYPE record; - DEFINE FIELD IF NOT EXISTS starts_at ON appointment_slot TYPE int; - DEFINE FIELD IF NOT EXISTS ends_at ON appointment_slot TYPE int; - DEFINE FIELD IF NOT EXISTS note ON appointment_slot TYPE option; - DEFINE FIELD IF NOT EXISTS series ON appointment_slot TYPE option; - DEFINE FIELD IF NOT EXISTS created_at ON appointment_slot TYPE int; - DEFINE INDEX IF NOT EXISTS appointment_slot_teacher_starts ON appointment_slot FIELDS teacher, starts_at; - DEFINE INDEX IF NOT EXISTS appointment_slot_series ON appointment_slot FIELDS series; - - DEFINE TABLE IF NOT EXISTS appointment SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS slot ON appointment TYPE record; - DEFINE FIELD IF NOT EXISTS requester ON appointment TYPE record; - DEFINE FIELD IF NOT EXISTS status ON appointment TYPE string DEFAULT 'pending'; - DEFINE FIELD IF NOT EXISTS reason ON appointment TYPE string; - DEFINE FIELD IF NOT EXISTS proposed_starts_at ON appointment TYPE option; - DEFINE FIELD IF NOT EXISTS proposed_ends_at ON appointment TYPE option; - DEFINE FIELD IF NOT EXISTS proposed_by ON appointment TYPE option>; - DEFINE FIELD IF NOT EXISTS decided_by ON appointment TYPE option>; - DEFINE FIELD IF NOT EXISTS cancelled_by ON appointment TYPE option>; - DEFINE FIELD IF NOT EXISTS cancel_reason ON appointment TYPE option; - DEFINE FIELD IF NOT EXISTS reject_reason ON appointment TYPE option; - DEFINE FIELD IF NOT EXISTS created_at ON appointment TYPE int; - DEFINE INDEX IF NOT EXISTS appointment_slot_ref ON appointment FIELDS slot; - DEFINE INDEX IF NOT EXISTS appointment_requester ON appointment FIELDS requester; - DEFINE INDEX IF NOT EXISTS appointment_status ON appointment FIELDS status; - - -- Food program (greenfield, 2026-07-26): a published menu per day+slot, - -- dishes on it, a dietary profile per student, bookings against a menu's - -- capacity, who actually ate, and the money that moved. `date` is a - -- calendar day as `YYYY-MM-DD` text, not a timestamp: the unique index is - -- an equality test and a midnight-in-millis day is only unique for one - -- timezone. `slot` is snapshotted text, not a link, so retiring a slot in - -- settings never rewrites a past menu. Stamps stay `int` millis like the - -- rest of the schema. No BACKFILL: all six tables are new. - DEFINE TABLE IF NOT EXISTS menu SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS date ON menu TYPE string READONLY; - DEFINE FIELD IF NOT EXISTS slot ON menu TYPE string READONLY; - DEFINE FIELD IF NOT EXISTS capacity ON menu TYPE option; - DEFINE FIELD IF NOT EXISTS created_by ON menu TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS created_at ON menu TYPE int READONLY; - DEFINE INDEX IF NOT EXISTS menu_date_slot ON menu FIELDS date, slot UNIQUE; - - DEFINE TABLE IF NOT EXISTS menu_dish SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS menu ON menu_dish TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS name ON menu_dish TYPE string; - DEFINE FIELD IF NOT EXISTS description ON menu_dish TYPE option; - -- Money is minor units (kuruş) as an integer, everywhere. Never decimal. - DEFINE FIELD IF NOT EXISTS price_minor ON menu_dish TYPE int; - DEFINE FIELD IF NOT EXISTS tags ON menu_dish TYPE array DEFAULT []; - DEFINE FIELD IF NOT EXISTS tags[*] ON menu_dish TYPE string; - DEFINE FIELD IF NOT EXISTS created_at ON menu_dish TYPE int READONLY; - DEFINE INDEX IF NOT EXISTS menu_dish_menu ON menu_dish FIELDS menu; - - DEFINE TABLE IF NOT EXISTS dietary_profile SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS student ON dietary_profile TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS tags ON dietary_profile TYPE array DEFAULT []; - DEFINE FIELD IF NOT EXISTS tags[*] ON dietary_profile TYPE string; - DEFINE FIELD IF NOT EXISTS note ON dietary_profile TYPE option; - DEFINE FIELD IF NOT EXISTS updated_by ON dietary_profile TYPE record; - DEFINE FIELD IF NOT EXISTS updated_at ON dietary_profile TYPE int; - DEFINE INDEX IF NOT EXISTS dietary_profile_student ON dietary_profile FIELDS student UNIQUE; - - -- A cancel flips `status` and stamps `cancelled_at`; the row stays so the - -- freed seat is still auditable against the ledger line it charged. - DEFINE TABLE IF NOT EXISTS meal_booking SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS menu ON meal_booking TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS student ON meal_booking TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS booked_by ON meal_booking TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS status ON meal_booking TYPE string DEFAULT 'booked'; - -- How many times this seat has been taken, and what it cost when the - -- *current* attempt took it (NONE = the menu was free then). Together they - -- key the attempt's ledger lines, which is what makes billing idempotent - -- by identity rather than by scanning for an outstanding charge. - DEFINE FIELD IF NOT EXISTS attempt ON meal_booking TYPE int DEFAULT 1; - DEFINE FIELD IF NOT EXISTS price_minor ON meal_booking TYPE option; - DEFINE FIELD IF NOT EXISTS cancelled_at ON meal_booking TYPE option; - DEFINE FIELD IF NOT EXISTS created_at ON meal_booking TYPE int READONLY; - DEFINE INDEX IF NOT EXISTS meal_booking_menu ON meal_booking FIELDS menu; - DEFINE INDEX IF NOT EXISTS meal_booking_student ON meal_booking FIELDS student; - - DEFINE TABLE IF NOT EXISTS meal_attendance SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS menu ON meal_attendance TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS student ON meal_attendance TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS status ON meal_attendance TYPE string; - DEFINE FIELD IF NOT EXISTS marked_by ON meal_attendance TYPE record; - DEFINE FIELD IF NOT EXISTS marked_at ON meal_attendance TYPE int; - DEFINE INDEX IF NOT EXISTS meal_attendance_menu_student ON meal_attendance FIELDS menu, student UNIQUE; - - -- APPEND-ONLY by design: a mistake is corrected with an opposing - -- `reversal` line, never by editing or deleting one. Hence every field is - -- READONLY. `source` is untyped on purpose — a charge points at the - -- booking that caused it, a reversal at the line it undoes. - DEFINE TABLE IF NOT EXISTS meal_ledger SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS student ON meal_ledger TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS kind ON meal_ledger TYPE string READONLY; - DEFINE FIELD IF NOT EXISTS amount_minor ON meal_ledger TYPE int READONLY; - DEFINE FIELD IF NOT EXISTS source ON meal_ledger TYPE option READONLY; - DEFINE FIELD IF NOT EXISTS method ON meal_ledger TYPE option READONLY; - DEFINE FIELD IF NOT EXISTS note ON meal_ledger TYPE option READONLY; - DEFINE FIELD IF NOT EXISTS recorded_by ON meal_ledger TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS created_at ON meal_ledger TYPE int READONLY; - DEFINE INDEX IF NOT EXISTS meal_ledger_student ON meal_ledger FIELDS student; -"; - -/// Data backfills for rows written by older binaries. Runs *after* (and apart -/// from) the DDL batch so every statement sees the freshly defined schema — -/// see the `MIGRATION` doc for why sharing the batch corrupts the writes. -/// Idempotent: each backfill's `WHERE` only matches unconverted rows. -pub const BACKFILL: &str = " - UPDATE user SET role = 'student' WHERE role = NONE; - - UPDATE course SET kind = 'course' WHERE kind = NONE; - - -- Courses predate assignable teachers (2026-07-21): every existing course - -- was run by its creator alone, so it starts with nobody else assigned. - UPDATE course SET teachers = [] WHERE teachers = NONE; - - -- Exams predate the draft flag (2026-07-19): everything already out there - -- was live for its course, so it stays published. - UPDATE exam SET draft = false WHERE draft = NONE; - - -- Exams predate the review toggle (2026-07-24): default it closed (opt-in). - UPDATE exam SET allow_review = false WHERE allow_review = NONE; - - UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {}; - - -- Questions written before subjects existed (2026-07-17) are destroyed, not - -- backfilled: a subject is mandatory and there is nothing truthful to - -- assign. Their answers go first so no answer row outlives its question. - DELETE exam_answer WHERE question IN (SELECT VALUE id FROM exam_question WHERE subject = NONE); - DELETE exam_question WHERE subject = NONE; - - -- The hand-picked `users` audience retired into `registration` (2026-07-16): - -- each listed user becomes a signup row credited to the event's creator, and - -- the event becomes an uncapped registration list. Runs once — converted - -- events no longer match the `kind = 'users'` filter. (`?? []`: an empty - -- statement-subquery evaluates to NONE, which FOR refuses to iterate.) - FOR $ev IN ((SELECT id, creator, audience FROM event WHERE audience.kind = 'users') ?? []) { - FOR $usr IN ($ev.audience.users ?? []) { - UPSERT type::record('registration', string::concat(record::id($ev.id), '_', record::id($usr))) CONTENT { - event: $ev.id, - user: $usr, - registered_by: $ev.creator, - }; - }; - UPDATE $ev.id SET audience = { kind: 'registration' }; - }; - - -- Turns written before the clipped-answer flag existed (2026-07-23): the - -- clip was silent then, so nothing can be recovered — they read as whole, - -- which is what they were presented as all along. - UPDATE chatbot_message SET truncated = false WHERE truncated = NONE; - - -- An assistant turn is answered by a claim loop in some replica's process, - -- so a restart can leave its row `pending` with nobody left to complete it. - -- Only rows past the stale horizon ($stale_ms, from - -- `CHATBOT_PENDING_STALE_SECS`) are certainly abandoned though: a young one - -- may still be being answered on the other side of the AI bridge, and a - -- deploy must not shoot down a turn dispatched seconds ago. Nothing is lost - -- by waiting — a reader already presents an over-age `pending` row as - -- failed, and the next boot sweeps for real whatever crossed the horizon in - -- the meantime. - -- - -- Claim-aware since 2026-07-27, because the sweep is no longer school-wide - -- truth: under N replicas the row may belong to a *live peer's* claim loop, - -- and failing it here would shoot down another process's in-flight turn. - -- So a claim restamped within the window is left alone. Both disjuncts - -- matter — `claimed_by = NONE` alone would strand every row whose claimer - -- died, which is the one case the sweep exists for. - -- - -- The claim age is measured against $stale_ms rather than - -- CHATBOT_CLAIM_RECLAIM_SECS only because the boot binds one horizon (see - -- `database::migration_binds`); erring long is the safe direction — the - -- cost is that a row claimed just before it aged out waits one more boot - -- for its durable stamp, while readers have shown it failed all along. - UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted', - completed_at = time::unix(time::now()) * 1000 - WHERE status = 'pending' AND created_at < time::unix(time::now()) * 1000 - $stale_ms - AND (claimed_by = NONE - OR claimed_at < time::unix(time::now()) * 1000 - $stale_ms); - - -- Promotion out of student now deletes the user's enrollments (2026-07-18); - -- this sweeps rows promoted before that fix. A deleted user reads as - -- `user.role = NONE`, which is also != 'student' — those rows go too. - DELETE enrollment WHERE user.role != 'student'; - - -- Choices gained stable ids (2026-07-24): `choices` held bare strings and - -- `correct`/`selected`/`slot` held the option's *position*. The DDL above - -- retypes those columns, which leaves every old-shaped row readable but - -- unwritable ('Expected `none | array` but found `[..]`'), so this - -- conversion is repair, not cosmetics. - -- - -- Ids are minted in array order, so the id at position i *is* the id for - -- old index i — that identity is what keeps a stored answer, and an option - -- picture, pointing at the option the student actually saw. Hence the - -- dependent rows are remapped inside the loop that mints `$new`, against - -- that same array: once the ids are stored the positions are still - -- recoverable, but nothing guarantees a later pass would look them up the - -- same way. `WHERE choices[0] != NONE AND type::is_string(choices[0])` - -- matches only unconverted rows, so a second boot re-mints nothing; an - -- empty or absent `choices` needs no conversion at all. A question-level - -- picture (`slot = NONE`) is not an index and is left alone. - -- - -- Runs *before* every other backfill that writes these rows (the `seq` - -- stamps below): a write coerces the whole record, so touching a row for - -- any reason fails while its choices are still positional. For the same - -- reason the answer's remap stamps `seq` itself — the two legacy gaps sit - -- on the same row, and a write that fixes only one of them is rejected for - -- the other. `seq ?? 1` leaves an already-numbered sitting alone (DEFAULT - -- fills a CREATE, not an UPDATE of a row that predates the column). - FOR $q IN ((SELECT id, choices, correct FROM exam_question - WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) { - LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c }); - UPDATE $q.id SET choices = $new, - correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id }; - FOR $img IN ((SELECT id, slot FROM question_image - WHERE question = $q.id AND type::is_int(slot)) ?? []) { - UPDATE $img.id SET slot = $new[$img.slot].id; - }; - FOR $ans IN ((SELECT id, selected FROM exam_answer - WHERE question = $q.id AND type::is_int(selected)) ?? []) { - UPDATE $ans.id SET selected = $new[$ans.selected].id, seq = seq ?? 1; - }; - }; - - FOR $q IN ((SELECT id, choices, correct FROM bank_question - WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) { - LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c }); - UPDATE $q.id SET choices = $new, - correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id }; - FOR $img IN ((SELECT id, slot FROM bank_question_image - WHERE bank_question = $q.id AND type::is_int(slot)) ?? []) { - UPDATE $img.id SET slot = $new[$img.slot].id; - }; - }; - - -- Per-attempt history (2026-07-24): answers, drawings, and marks written - -- before retakes stopped wiping belong to the student's first sitting. - -- They already use the bare (seq==1) record key, so only the denormalized - -- `seq` field needs stamping. - UPDATE exam_answer SET seq = 1 WHERE seq = NONE; - UPDATE answer_image SET seq = 1 WHERE seq = NONE; - UPDATE exam_result SET seq = 1 WHERE seq = NONE; -"; - -/// The migration batches, in the order a boot applies them — and the *only* -/// list of them. [`crate::database::migrate`] runs exactly these and -/// [`crate::database::migration_fingerprint`] hashes exactly these, so a fourth -/// batch cannot be executed without changing the fingerprint that decides -/// whether a peer's schema is ours. They stay three separate queries: statements -/// in one batch see the schema as it stood when the batch started (see -/// `MIGRATION`). -pub const MIGRATION_BATCHES: [&str; 3] = [PRE_REPAIR, MIGRATION, BACKFILL]; diff --git a/src/database.rs b/src/database.rs index d606a6a..d00c193 100644 --- a/src/database.rs +++ b/src/database.rs @@ -7,13 +7,13 @@ use surrealdb::types::SurrealValue; use crate::config::Config; use crate::constant::{ - CHATBOT_PENDING_STALE_SECS, MIGRATION_BATCHES, MIGRATION_LOCK_CLAIM, MIGRATION_LOCK_DDL, - MIGRATION_LOCK_HEARTBEAT, MIGRATION_LOCK_HEARTBEAT_SECS, MIGRATION_LOCK_LEASE_SECS, - MIGRATION_LOCK_POLL_MS, MIGRATION_LOCK_STAMP, MIGRATION_LOCK_STATE, MIGRATION_LOCK_TAKEOVER, - MIGRATION_LOCK_WAIT_SECS, + CHATBOT_PENDING_STALE_SECS, MIGRATION_LOCK_CLAIM, MIGRATION_LOCK_DDL, MIGRATION_LOCK_HEARTBEAT, + MIGRATION_LOCK_HEARTBEAT_SECS, MIGRATION_LOCK_LEASE_SECS, MIGRATION_LOCK_POLL_MS, + MIGRATION_LOCK_STAMP, MIGRATION_LOCK_STATE, MIGRATION_LOCK_TAKEOVER, MIGRATION_LOCK_WAIT_SECS, }; use crate::domain::user::{Password, User, Username}; use crate::error::AppError; +use crate::migration_sql::MIGRATION_BATCHES; /// The shared database handle. /// @@ -259,7 +259,7 @@ async fn claim(db: &Database, sql: &str, me: &str, lease_ms: i64) -> Result bool { +pub(crate) fn lost_the_race(err: &surrealdb::Error) -> bool { use surrealdb::types::{ErrorDetails, QueryError}; if err.is_already_exists() || matches!( @@ -685,7 +685,7 @@ mod tests { } hex::encode(hasher.finalize()) }; - let batches: Vec = crate::constant::MIGRATION_BATCHES + let batches: Vec = crate::migration_sql::MIGRATION_BATCHES .iter() .map(|sql| (*sql).to_string()) .collect(); diff --git a/src/domain/answer_image.rs b/src/domain/answer_image.rs index 5303cce..05a4a8e 100644 --- a/src/domain/answer_image.rs +++ b/src/domain/answer_image.rs @@ -20,6 +20,7 @@ use crate::database::Database; use crate::domain::course::CourseId; use crate::domain::exam::ExamId; use crate::domain::exam_question::ExamQuestionId; +use crate::domain::key; use crate::domain::note_file::FileContentType; use crate::domain::user::UserId; use crate::error::AppError; @@ -28,19 +29,11 @@ use crate::error::AppError; pub struct AnswerImageId(RecordId); impl AnswerImageId { - /// The one id a (question, user, seq) triple can have — the same - /// deterministic shape as [`crate::domain::exam_attempt::ExamAttemptId::composite`], - /// so "one drawing per student per question per sitting" needs no index. - /// The first sitting keeps the historical `{question}_{user}` shape (rows - /// written before per-attempt history existed stay addressable); later - /// sittings append their number. ULID keys are alphanumeric, so `_` is an - /// unambiguous joiner. + /// The one id a (question, user, seq) triple can have, so "one drawing per + /// student per question per sitting" needs no index. See [`key::sitting`] + /// for the key shape and why the first sitting stays bare. pub fn composite(question: &ExamQuestionId, user: &UserId, seq: i64) -> Self { - let key = if seq == 1 { - format!("{}_{}", question.key(), user.key()) - } else { - format!("{}_{}_{}", question.key(), user.key(), seq) - }; + let key = key::sitting(question.key(), user.key(), seq); Self(RecordId::new(ANSWER_IMAGE_TABLE, key)) } diff --git a/src/domain/appointment.rs b/src/domain/appointment.rs index 22e96df..ea37d35 100644 --- a/src/domain/appointment.rs +++ b/src/domain/appointment.rs @@ -2,8 +2,8 @@ //! for the meeting with a reason; the teacher approves, rejects, or //! counter-proposes another time. //! -//! Two invariants live here, and both are guarded by [`APPOINTMENT_LOCK`] -//! rather than by the database: +//! Two *cross-record* invariants live here, and both are guarded by +//! [`APPOINTMENT_LOCK`] rather than by the database: //! //! - **One live booking per slot.** Occupancy is counted from the rows, not //! stored — so rejecting or cancelling frees the slot with nothing to reset. @@ -12,8 +12,18 @@ //! //! Both are count-then-write checks across records, which a `BEGIN…COMMIT` //! does not serialize in SurrealDB (write-skew: two racing bookings each see a -//! free slot). This backend is the database's only writer, so one process-wide -//! lock closes it, exactly as `REGISTER_LOCK` does for event seats. +//! free slot). +//! +//! The *single-row* invariant — a decision must be written onto the state it +//! was validated against — is **not** the lock's job, and never was: the lock +//! is process-local, so two replicas each take their own copy of it and a +//! whole-row save would silently drop the other's decision. That one is a +//! compare-and-set ([`Appointment::save_if_unchanged`]), which holds across +//! replicas. The lock stays for the two counts above, which no per-row +//! conditional write can cover. +// ponytail: with more than one replica those two counts are only +// replica-local. Closing them needs a stored occupancy counter (`domain::cap`) +// rather than a lock — deliberately not built here. use std::sync::LazyLock; @@ -21,9 +31,10 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use tokio::sync::Mutex; use ulid::Generator; -use crate::constant::{APPOINTMENT_TABLE, MAX_APPOINTMENT_REASON_LEN}; -use crate::database::Database; +use crate::constant::{APPOINTMENT_TABLE, CAS_UPDATE_RETRIES, MAX_APPOINTMENT_REASON_LEN}; +use crate::database::{Database, lost_the_race}; use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId}; +use crate::domain::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -34,7 +45,7 @@ use crate::validate::validate_required; /// conflict-check a cross-record `count()` against a concurrent insert. /// /// Lock order: no path ever holds this together with `ENROLL_LOCK`, -/// `TERM_LOCK`, `REGISTER_LOCK`, `EXAM_LOCK`, or `PRESENCE_LOCK` — appointments +/// `TERM_LOCK`, `EXAM_LOCK`, or `PRESENCE_LOCK` — appointments /// touch no roster, term, event seat, or exam room, and none of those touch /// appointments — so they cannot deadlock. Should a future path ever need two, /// take this one *last*. @@ -407,28 +418,34 @@ impl Appointment { pub async fn list_for_requester( requester: &UserId, + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM appointment WHERE requester = $requester ORDER BY id DESC") - .bind(("requester", requester.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + ) -> Result<(Vec, i64), AppError> { + PagedList::new( + "appointment WHERE requester = $requester", + "ORDER BY id DESC", + ) + .bind("requester", requester.record()) + .run(limit, offset, db) + .await } /// Every booking aimed at `teacher`, across all their slots — the teacher's /// request inbox. pub async fn list_for_teacher( teacher: &UserId, + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM appointment WHERE slot.teacher = $teacher ORDER BY id DESC") - .bind(("teacher", teacher.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + ) -> Result<(Vec, i64), AppError> { + PagedList::new( + "appointment WHERE slot.teacher = $teacher", + "ORDER BY id DESC", + ) + .bind("teacher", teacher.record()) + .run(limit, offset, db) + .await } pub async fn list_for_slot( @@ -454,36 +471,42 @@ impl Appointment { db: &Database, ) -> Result { let _guard = APPOINTMENT_LOCK.lock().await; - let mut appointment = Self::read_pending(id, db).await?; - let slot = AppointmentSlot::read(&appointment.slot, db) + for _ in 0..CAS_UPDATE_RETRIES { + let expected = Self::read_pending(id, db).await?; + let slot = AppointmentSlot::read(&expected.slot, db) + .await? + .ok_or(AppError::NotFound)?; + let (starts_at, ends_at) = expected.window(&slot); + // The effective window — the proposal's when one stands — must still + // be ahead. Mutual agreement does not help: `cancel` refuses a + // meeting that started, so committing to a passed window would mint + // a booking nobody can ever undo. Refused, the row stays `pending` + // and the teacher can propose a time that can actually happen. + if starts_at.as_millis() <= Timestamp::now().as_millis() { + return Err(AppError::Conflict("that time has already started")); + } + if Self::conflicts( + slot.get_teacher(), + &expected.requester, + starts_at, + ends_at, + Some(id), + db, + ) .await? - .ok_or(AppError::NotFound)?; - let (starts_at, ends_at) = appointment.window(&slot); - // The effective window — the proposal's when one stands — must still be - // ahead. Mutual agreement does not help: `cancel` refuses a meeting - // that started, so committing to a passed window would mint a booking - // nobody can ever undo. Refused, the row stays `pending` and the - // teacher can propose a time that can actually happen. - if starts_at.as_millis() <= Timestamp::now().as_millis() { - return Err(AppError::Conflict("that time has already started")); - } - if Self::conflicts( - slot.get_teacher(), - &appointment.requester, - starts_at, - ends_at, - Some(id), - db, - ) - .await? - { - return Err(AppError::Conflict( - "that time collides with another approved appointment", - )); + { + return Err(AppError::Conflict( + "that time collides with another approved appointment", + )); + } + let mut approved = expected.clone(); + approved.status = AppointmentStatus::Approved; + approved.decided_by = Some(decided_by.clone()); + if let Some(saved) = approved.save_if_unchanged(&expected, db).await? { + return Ok(saved); + } } - appointment.status = AppointmentStatus::Approved; - appointment.decided_by = Some(decided_by.clone()); - Self::save(appointment, db).await + Err(contended()) } /// Turn the request down. Frees the slot: occupancy counts live rows only. @@ -494,11 +517,17 @@ impl Appointment { db: &Database, ) -> Result { let _guard = APPOINTMENT_LOCK.lock().await; - let mut appointment = Self::read_pending(id, db).await?; - appointment.status = AppointmentStatus::Rejected; - appointment.decided_by = Some(decided_by.clone()); - appointment.reject_reason = reason; - Self::save(appointment, db).await + for _ in 0..CAS_UPDATE_RETRIES { + let expected = Self::read_pending(id, db).await?; + let mut rejected = expected.clone(); + rejected.status = AppointmentStatus::Rejected; + rejected.decided_by = Some(decided_by.clone()); + rejected.reject_reason = reason.clone(); + if let Some(saved) = rejected.save_if_unchanged(&expected, db).await? { + return Ok(saved); + } + } + Err(contended()) } /// Call the meeting off. Legal from either live state, so an approved @@ -519,20 +548,26 @@ impl Appointment { db: &Database, ) -> Result { let _guard = APPOINTMENT_LOCK.lock().await; - let mut appointment = Self::read(id, db).await?.ok_or(AppError::NotFound)?; - if !appointment.status.is_live() { - return Err(AppError::Conflict("the appointment is already settled")); - } - let slot = AppointmentSlot::read(&appointment.slot, db) - .await? - .ok_or(AppError::NotFound)?; - if appointment.window(&slot).0.as_millis() <= Timestamp::now().as_millis() { - return Err(AppError::Conflict("the appointment has already started")); + for _ in 0..CAS_UPDATE_RETRIES { + let expected = Self::read(id, db).await?.ok_or(AppError::NotFound)?; + if !expected.status.is_live() { + return Err(AppError::Conflict("the appointment is already settled")); + } + let slot = AppointmentSlot::read(&expected.slot, db) + .await? + .ok_or(AppError::NotFound)?; + if expected.window(&slot).0.as_millis() <= Timestamp::now().as_millis() { + return Err(AppError::Conflict("the appointment has already started")); + } + let mut cancelled = expected.clone(); + cancelled.status = AppointmentStatus::Cancelled; + cancelled.cancelled_by = Some(cancelled_by.clone()); + cancelled.cancel_reason = reason.clone(); + if let Some(saved) = cancelled.save_if_unchanged(&expected, db).await? { + return Ok(saved); + } } - appointment.status = AppointmentStatus::Cancelled; - appointment.cancelled_by = Some(cancelled_by.clone()); - appointment.cancel_reason = reason; - Self::save(appointment, db).await + Err(contended()) } /// Counter-propose another time on the same booking (no second row, so the @@ -561,19 +596,25 @@ impl Appointment { .into()); } let _guard = APPOINTMENT_LOCK.lock().await; - let mut appointment = Self::read(id, db).await?.ok_or(AppError::NotFound)?; - if !appointment.status.is_live() { - return Err(AppError::Conflict("the appointment is already settled")); - } - if starts_at.as_millis() <= Timestamp::now().as_millis() { - return Err(AppError::Conflict("that time has already started")); + for _ in 0..CAS_UPDATE_RETRIES { + let expected = Self::read(id, db).await?.ok_or(AppError::NotFound)?; + if !expected.status.is_live() { + return Err(AppError::Conflict("the appointment is already settled")); + } + if starts_at.as_millis() <= Timestamp::now().as_millis() { + return Err(AppError::Conflict("that time has already started")); + } + let mut proposed = expected.clone(); + proposed.status = AppointmentStatus::Pending; + proposed.decided_by = None; + proposed.proposed_starts_at = Some(starts_at); + proposed.proposed_ends_at = Some(ends_at); + proposed.proposed_by = Some(proposed_by.clone()); + if let Some(saved) = proposed.save_if_unchanged(&expected, db).await? { + return Ok(saved); + } } - appointment.status = AppointmentStatus::Pending; - appointment.decided_by = None; - appointment.proposed_starts_at = Some(starts_at); - appointment.proposed_ends_at = Some(ends_at); - appointment.proposed_by = Some(proposed_by.clone()); - Self::save(appointment, db).await + Err(contended()) } /// Accept the standing proposal — approval at the proposed time. The @@ -603,15 +644,66 @@ impl Appointment { Ok(appointment) } - async fn save(appointment: Appointment, db: &Database) -> Result { - let updated: Option = db - .update(appointment.id.record()) - .content(appointment) - .await?; - updated.ok_or(AppError::NotFound) + /// Write the decision only while the stored row still carries the state it + /// was validated against. `None` means it does not: another decision landed + /// between the read and the write, so reload, re-validate, and try again. + /// + /// Four columns discriminate every write, and `status` alone would not: + /// `propose` leaves a pending booking pending, so an approval built from a + /// snapshot taken *before* that proposal would sail through a status-only + /// guard and confirm the meeting at the old, superseded time. With the + /// proposed window and `decided_by` alongside it, every mutator moves at + /// least one of the four. The fields only a terminal transition writes + /// (`cancelled_by`, `cancel_reason`, `reject_reason`) need no compare of + /// their own: they always travel with a `status` change into a state no + /// later decision is allowed from. All four are top-level columns, so an + /// absent one reads back as `NONE` and `NONE = NONE` holds — the object-key + /// dropping that forces `settings` to compare a rebuilt projection cannot + /// bite here. + /// + /// A store-level write conflict is reported the same way as a miss: it + /// means a concurrent write committed on this row, which is exactly the + /// "reload and re-decide" case. + async fn save_if_unchanged( + self, + expected: &Appointment, + db: &Database, + ) -> Result, AppError> { + let attempted = async { + let mut result = db + .query( + "UPDATE $id CONTENT $new \ + WHERE status = $status \ + AND proposed_starts_at = $proposed_starts_at \ + AND proposed_ends_at = $proposed_ends_at \ + AND decided_by = $decided_by", + ) + .bind(("id", expected.id.record())) + .bind(("status", expected.status)) + .bind(("proposed_starts_at", expected.proposed_starts_at)) + .bind(("proposed_ends_at", expected.proposed_ends_at)) + .bind(("decided_by", expected.decided_by.clone())) + .bind(("new", self)) + .await? + .check()?; + result.take::>(0) + } + .await; + match attempted { + Ok(rows) => Ok(rows.into_iter().next()), + Err(err) if lost_the_race(&err) => Ok(None), + Err(err) => Err(err.into()), + } } } +/// Every retry lost the row to another decision. A 409 rather than a 500: the +/// caller's request was refused, nothing was half-applied, and re-reading the +/// booking shows what happened to it. +fn contended() -> AppError { + AppError::Conflict("the appointment is being decided elsewhere") +} + #[cfg(test)] mod tests { use super::*; @@ -749,13 +841,18 @@ mod tests { // And approval judges the effective window again, for a proposal whose // time simply passed while it stood: forced onto the row directly, // since `propose` no longer mints one. - let mut standing = Appointment::read(booking.get_id(), &db) + let current = Appointment::read(booking.get_id(), &db) .await .unwrap() .unwrap(); + let mut standing = current.clone(); standing.proposed_starts_at = Some(soon(-30_000)); standing.proposed_ends_at = Some(soon(30_000)); - Appointment::save(standing, &db).await.unwrap(); + standing + .save_if_unchanged(¤t, &db) + .await + .unwrap() + .unwrap(); assert!(matches!( Appointment::accept_proposal(booking.get_id(), &student, &db).await, Err(AppError::Conflict("that time has already started")) @@ -773,6 +870,76 @@ mod tests { assert_eq!(accepted.get_status(), AppointmentStatus::Approved); } + /// The compare-and-set every decision writes through. `APPOINTMENT_LOCK` is + /// process-local, so with two replicas serving, nothing else stands between + /// an approval and a counter-proposal landing on the same booking — and the + /// interleaving that matters is the one a status-only guard would miss, + /// since `propose` leaves a pending booking pending. + /// + /// Deliberately sequential: the mem engine answers `Ok` to a write it then + /// drops, so a `join!` of two decisions proves nothing. This drives the + /// primitive itself with the exact snapshot a second replica would hold. + #[tokio::test] + async fn a_decision_built_on_a_stale_snapshot_never_lands() { + let db = crate::database::init_mem().await.unwrap(); + let teacher = UserId::from_key("t1"); + let student = UserId::from_key("s1"); + let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) + .await + .unwrap(); + let booking = Appointment::book( + slot.get_id(), + &student, + AppointmentReason::try_new("görüşme").unwrap(), + &db, + ) + .await + .unwrap(); + + // Replica A counter-proposes. Replica B is still holding the snapshot + // it read before that — same id, same `pending` status. + let stale = booking.clone(); + let (proposed_starts_at, proposed_ends_at) = (soon(180_000), soon(240_000)); + Appointment::propose( + booking.get_id(), + proposed_starts_at, + proposed_ends_at, + &teacher, + &db, + ) + .await + .unwrap(); + + let mut late = stale.clone(); + late.status = AppointmentStatus::Approved; + late.decided_by = Some(teacher.clone()); + assert!(late.save_if_unchanged(&stale, &db).await.unwrap().is_none()); + + // The proposal survived: the row was not confirmed at the slot's old + // window behind the requester's back. + let after = Appointment::read(booking.get_id(), &db) + .await + .unwrap() + .unwrap(); + assert_eq!(after.get_status(), AppointmentStatus::Pending); + assert_eq!(after.get_proposed_starts_at(), Some(proposed_starts_at)); + assert_eq!(after.get_proposed_ends_at(), Some(proposed_ends_at)); + assert_eq!(after.get_decided_by(), None); + + // And the same decision, re-validated against the row as it now + // stands, does land — a miss is a retry signal, not a wall. + let mut fresh = after.clone(); + fresh.status = AppointmentStatus::Approved; + fresh.decided_by = Some(teacher.clone()); + let saved = fresh + .save_if_unchanged(&after, &db) + .await + .unwrap() + .expect("a current snapshot must write"); + assert_eq!(saved.get_status(), AppointmentStatus::Approved); + assert_eq!(saved.get_proposed_starts_at(), Some(proposed_starts_at)); + } + /// Occupancy is derived, so a rejected booking must hand the slot back. #[tokio::test] async fn rejecting_frees_the_slot_for_re_booking() { diff --git a/src/domain/attendance.rs b/src/domain/attendance.rs index 069c2a3..161d3f3 100644 --- a/src/domain/attendance.rs +++ b/src/domain/attendance.rs @@ -3,6 +3,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::ATTENDANCE_TABLE; use crate::database::Database; use crate::domain::event::EventId; +use crate::domain::page::PagedList; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -113,14 +114,14 @@ impl Attendance { pub async fn list_for_event( event: &EventId, + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM attendance WHERE event = $ev ORDER BY id DESC") - .bind(("ev", event.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + ) -> Result<(Vec, i64), AppError> { + PagedList::new("attendance WHERE event = $ev", "ORDER BY id DESC") + .bind("ev", event.record()) + .run(limit, offset, db) + .await } /// Every event-attendance row recorded for `user` — the events half of the diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs index 34f6b50..30d9d1e 100644 --- a/src/domain/bank_question.rs +++ b/src/domain/bank_question.rs @@ -379,15 +379,22 @@ impl BankQuestion { .collect()) } - /// Write the editable fields of the template. + /// Write the editable fields of the template, but only while the row still + /// reads as the snapshot `self` was loaded from — `None` means a concurrent + /// edit (or the subject-delete cascade that clears `subject`) landed inside + /// the handler's read-merge window, so nothing was written: reload, + /// re-merge, retry. This is a genuine read-modify-write — every editable + /// field is re-stated from the snapshot, and the kind/choices/correct trio + /// has to be (a text-only edit re-submits the stored options *with their + /// ids* so each keeps its picture) — so without the compare-and-set the + /// later writer silently reverts the earlier one. An in-process `RwLock` + /// only stopped that between requests of *one* replica. /// - /// Field-scoped, never a whole-row content-replace save: the handler reads - /// the row, then awaits an ownership check and a subject lookup before - /// getting here, so a concurrent PATCH (or the subject-delete cascade that - /// clears `subject`) can land inside that window — a whole-row save would - /// silently revert it. Same shape, same reason as - /// [`crate::domain::exam_question::ExamQuestion::link_banked_as`]. - pub async fn update( + /// Every field the merge re-states is in the guard, which is the same list + /// the `SET` writes. `choices` is compared whole: its objects carry two + /// required string keys, so none is ever dropped for being `NONE` (the trap + /// [`crate::domain::settings::Settings::save_if_unchanged`] works around). + pub async fn update_if_unchanged( self, subject: Option, text: QuestionText, @@ -395,14 +402,26 @@ impl BankQuestion { spec: QuestionSpec, visibility: BankVisibility, db: &Database, - ) -> Result { + ) -> Result, AppError> { let (kind, choices, correct) = spec.into_parts(); let mut result = db .query( "UPDATE $id SET subject = $subject, text = $text, points = $points, kind = $kind, choices = $choices, correct = $correct, - visibility = $visibility RETURN AFTER", + visibility = $visibility + WHERE subject = $was_subject AND text = $was_text + AND points = $was_points AND kind = $was_kind + AND choices = $was_choices AND correct = $was_correct + AND visibility = $was_visibility + RETURN AFTER", ) + .bind(("was_subject", self.subject.clone().map(|s| s.record()))) + .bind(("was_text", self.text.clone())) + .bind(("was_points", self.points)) + .bind(("was_kind", self.kind.clone())) + .bind(("was_choices", self.choices.clone())) + .bind(("was_correct", self.correct.clone())) + .bind(("was_visibility", self.visibility.clone())) .bind(("id", self.id.record())) .bind(("subject", subject.map(|s| s.record()))) .bind(("text", text)) @@ -413,11 +432,7 @@ impl BankQuestion { .bind(("visibility", visibility)) .await? .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + Ok(result.take::>(0)?.into_iter().next()) } /// Delete the template and cascade-remove its bank images, so none points @@ -556,7 +571,7 @@ mod tests { .unwrap(); let subject = published.get_subject().cloned(); published - .update( + .update_if_unchanged( subject, QuestionText::try_new("shared").unwrap(), QuestionPoints::try_new(1).unwrap(), @@ -591,6 +606,61 @@ mod tests { assert_eq!(private.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); } + /// The bite test for the compare-and-set that replaced the writer lease of + /// `BANK_LOCK` on the PATCH path: a merge built on a snapshot the row has + /// since moved past must be refused, not written — otherwise it reverts + /// whatever landed in between. Asserts the *stored* row, never a race + /// outcome: the in-memory engine can drop one of two concurrent writes and + /// still answer `Ok`. + #[tokio::test] + async fn a_merge_built_on_a_stale_snapshot_is_refused() { + let db = crate::database::init_mem().await.unwrap(); + let owner = UserId::generate(); + let stale = BankQuestion::create( + owner, + SubjectId::generate(), + QuestionText::try_new("first").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + &db, + ) + .await + .unwrap(); + // Somebody else's edit lands on the row this snapshot came from. + let landed = stale + .clone() + .update_if_unchanged( + None, + QuestionText::try_new("theirs").unwrap(), + QuestionPoints::try_new(2).unwrap(), + spec(), + BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(), + &db, + ) + .await + .unwrap(); + assert!(landed.is_some(), "the first write is on a fresh snapshot"); + + let refused = stale + .update_if_unchanged( + None, + QuestionText::try_new("mine").unwrap(), + QuestionPoints::try_new(3).unwrap(), + spec(), + BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(), + &db, + ) + .await + .unwrap(); + assert!(refused.is_none(), "a stale merge must not be written"); + let stored = BankQuestion::read(landed.unwrap().get_id(), &db) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.get_text().as_str(), "theirs"); + assert_eq!(stored.get_points().as_i64(), 2); + } + /// The `visibility` filter ANDs onto the security gate, so it narrows and /// never widens: a stranger asking for `school` still can't see a private /// row, and `private` means "my own drafts" for everyone but an admin. @@ -613,7 +683,7 @@ mod tests { let published = mine("shared").await.unwrap(); let subject = published.get_subject().cloned(); published - .update( + .update_if_unchanged( subject, QuestionText::try_new("shared").unwrap(), QuestionPoints::try_new(1).unwrap(), diff --git a/src/domain/bank_question_image.rs b/src/domain/bank_question_image.rs index c2b8bd6..f81ba99 100644 --- a/src/domain/bank_question_image.rs +++ b/src/domain/bank_question_image.rs @@ -17,6 +17,7 @@ use crate::constant::BANK_QUESTION_IMAGE_TABLE; use crate::database::Database; use crate::domain::bank_question::BankQuestionId; use crate::domain::exam_question::ChoiceId; +use crate::domain::key; use crate::domain::note_file::FileContentType; use crate::error::AppError; @@ -24,20 +25,12 @@ use crate::error::AppError; pub struct BankQuestionImageId(RecordId); impl BankQuestionImageId { - /// The one id a (question, slot) pair can have: `{bid}_q` for the - /// question's own image, `{bid}_{choice id}` for one option's picture — - /// uniqueness per slot needs no index this way. Keyed by the option's - /// *stable id*, so reordering the choice list moves no picture. + /// The one id a (question, slot) pair can have — see [`key::slot`] for the + /// key shape and why the two forms can never collide. pub fn for_slot(question: &BankQuestionId, slot: Option<&ChoiceId>) -> Self { - // `_` is not in Crockford base32 and a ULID is never `"q"`, so - // `{qid}_{cid}` and `{qid}_q` can never collide. - let suffix = match slot { - None => "q", - Some(id) => id.as_str(), - }; Self(RecordId::new( BANK_QUESTION_IMAGE_TABLE, - format!("{}_{suffix}", question.key()), + key::slot(question.key(), slot.map(|id| id.as_str())), )) } diff --git a/src/domain/cap.rs b/src/domain/cap.rs new file mode 100644 index 0000000..19f0ce5 --- /dev/null +++ b/src/domain/cap.rs @@ -0,0 +1,133 @@ +//! Count caps that hold across replicas. +//! +//! Every "at most N children per parent" rule used to be a count-then-write +//! under a process-wide `Mutex`, because a `BEGIN…COMMIT` cannot enforce it: +//! SurrealDB does not conflict-check a cross-record `count()` against a +//! concurrent insert (write-skew), so two racing writers both saw a free slot. +//! A mutex only serializes the writers *inside one process*, and the backend +//! now runs as two replicas against one database — so every one of those caps +//! was open again. +//! +//! The guard that does survive is a single-record conditional write: an +//! `UPDATE … SET n += 1 WHERE n < cap` on the *parent* row is atomic, so of N +//! concurrent claimers exactly `cap` get a non-empty result and the rest are +//! refused, whatever process they run in. The counter is therefore the +//! authority on how many slots are taken, and the child rows follow it: +//! [`claim`] before the insert, [`release`] if the insert then fails, and a +//! decrement in the *same transaction* as every delete of a child row. +//! +//! The counters are `option` columns on the parent table, absent meaning +//! zero, so no Rust struct carries them and no whole-row save can clobber one +//! (every parent's `.content()` write is a create of a fresh row). +// +// ponytail: a counter can only drift if a future delete path forgets its +// decrement, and the boot backfill seeds counters once rather than recomputing +// them (recomputing on every boot would clobber a live peer's increments). If +// drift is ever observed, the repair is the same GROUP BY count the backfill +// runs, issued by hand with the field's `= NONE` guard dropped. + +use surrealdb::types::RecordId; +use tokio::sync::Mutex; + +use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES}; +use crate::database::{Database, lost_the_race}; +use crate::domain::timestamp::Timestamp; +use crate::error::AppError; + +/// One writer per process at a time, over every counter. +/// +/// Not the cap — the `WHERE` clause is the cap, and it holds with or without +/// this. What the lock buys is that a replica sends its counter writes one at a +/// time, so the only contention the database ever sees on a parent row is +/// between replicas: at most as many concurrent writers as there are processes, +/// instead of as many as there are in-flight requests. That keeps the optimistic +/// retry loop below to a beat or two rather than a storm. +/// +/// It is also what keeps the test suite deterministic. The embedded in-memory +/// engine the tests run on does *not* have the real server's conflict +/// detection: under two concurrent writes to one record it can drop one and +/// still answer `Ok` (probed — the stored counter stays correct, but ~13% of a +/// 16-racer round had one more caller told it had won than the counter agreed +/// to). The real ws server never did this in 150 rounds of the same probe. +// +// ponytail: one lock for every cap. Per-parent locks (a keyed map) if unrelated +// caps ever contend measurably — the counters are already independent, this is +// only about how many writes a process has in flight. +static CLAIM_LOCK: Mutex<()> = Mutex::const_new(()); + +/// "No cap" as a number, so the guard stays one comparison instead of a +/// nullable branch: `NONE`/`NULL` bind ambiguity is a worse trade than a +/// sentinel no roster will ever reach. +pub(crate) const UNLIMITED: i64 = i64::MAX; + +/// Take one slot on `parent`'s `field` counter. `false` means the cap is full +/// (or the parent row is gone) and the caller must refuse — nothing was +/// written. `field` is always an in-crate constant, never user input. +pub(crate) async fn claim( + parent: &RecordId, + field: &str, + cap: i64, + db: &Database, +) -> Result { + let sql = format!( + "UPDATE $parent SET {field} = ({field} ?? 0) + 1 \ + WHERE ({field} ?? 0) < $cap RETURN VALUE id" + ); + Ok(!write(&sql, parent, cap, db).await?.is_empty()) +} + +/// Give a claimed slot back, for the insert that never landed. Clamped at zero +/// so a double release can never push a counter negative and open the cap. +pub(crate) async fn release(parent: &RecordId, field: &str, db: &Database) -> Result<(), AppError> { + let sql = + format!("UPDATE $parent SET {field} = math::max([({field} ?? 0) - 1, 0]) RETURN VALUE id"); + write(&sql, parent, UNLIMITED, db).await?; + Ok(()) +} + +/// Run one conditional counter write, retrying while the store reports a write +/// conflict. +/// +/// Claimers contend on a single record by design — that contention *is* the +/// guard — and SurrealDB resolves it optimistically: the loser's transaction is +/// aborted with "can be retried" rather than queued, which the old mutex hid by +/// never letting two writers reach the database at once. So the queueing has to +/// happen here. Backoff is exponential with jitter, because racers arrive in +/// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them. +async fn write( + sql: &str, + parent: &RecordId, + cap: i64, + db: &Database, +) -> Result, AppError> { + let _guard = CLAIM_LOCK.lock().await; + let mut last = None; + for attempt in 0..CAP_WRITE_TRIES { + if attempt > 0 { + let step = CAP_WRITE_BACKOFF_MS << (attempt - 1); + let jitter = Timestamp::now().as_millis().unsigned_abs() % step.max(1); + tokio::time::sleep(std::time::Duration::from_millis(step + jitter)).await; + } + let attempted = async { + let mut result = db + .query(sql) + .bind(("parent", parent.clone())) + .bind(("cap", cap)) + .await? + .check()?; + result.take::>(0) + } + .await; + match attempted { + Ok(hit) => return Ok(hit), + // `lost_the_race` also matches "already exists", which an UPDATE + // cannot produce — what is being reused here is its transaction + // conflict detection, typed details first and wording second. + Err(err) if lost_the_race(&err) => last = Some(err), + Err(err) => return Err(err.into()), + } + } + Err(last + .map(AppError::from) + .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) +} diff --git a/src/domain/chatbot_message.rs b/src/domain/chatbot_message.rs index e2c793c..e48f860 100644 --- a/src/domain/chatbot_message.rs +++ b/src/domain/chatbot_message.rs @@ -21,6 +21,7 @@ use crate::constant::{ }; use crate::database::Database; use crate::domain::chatbot_thread::ChatbotThreadId; +use crate::domain::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -283,21 +284,21 @@ impl ChatbotMessage { /// history payload read in. pub async fn list_for_thread( thread: &ChatbotThreadId, + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM chatbot_message WHERE thread_id = $conv \ - ORDER BY created_at ASC, id ASC", - ) - .bind(("conv", thread.record())) - .await? - .check()?; - Ok(result - .take::>(0)? - .into_iter() - .map(ChatbotMessage::projected) - .collect()) + ) -> Result<(Vec, i64), AppError> { + let (rows, total) = PagedList::new( + "chatbot_message WHERE thread_id = $conv", + "ORDER BY created_at ASC, id ASC", + ) + .bind("conv", thread.record()) + .run::(limit, offset, db) + .await?; + Ok(( + rows.into_iter().map(ChatbotMessage::projected).collect(), + total, + )) } /// The last `limit` turns, still oldest-first — the tail replayed to the @@ -549,7 +550,9 @@ mod tests { .unwrap(); } - let whole = ChatbotMessage::list_for_thread(&thread, &db).await.unwrap(); + let (whole, _) = ChatbotMessage::list_for_thread(&thread, None, 0, &db) + .await + .unwrap(); let tail = ChatbotMessage::list_tail(&thread, TURNS * 2, &db) .await .unwrap(); diff --git a/src/domain/chatbot_thread.rs b/src/domain/chatbot_thread.rs index 0ca6515..915232a 100644 --- a/src/domain/chatbot_thread.rs +++ b/src/domain/chatbot_thread.rs @@ -4,23 +4,20 @@ //! [`crate::domain::chatbot_message`], and deleting a thread cascades them. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use tokio::sync::Mutex; use ulid::Ulid; -use crate::constant::{CHATBOT_THREAD_TABLE, MAX_CHATBOT_THREAD_TITLE_LEN}; +use crate::constant::{ + CHATBOT_THREAD_COUNT_FIELD, CHATBOT_THREAD_TABLE, MAX_CHATBOT_THREAD_TITLE_LEN, +}; use crate::database::Database; +use crate::domain::cap; +use crate::domain::page::PagedList; use crate::domain::settings::Settings; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::validate_required; -/// Serializes thread creation so the `max_chatbot_threads` check (count, -/// then write) can't over-admit under concurrency — the database's optimistic -/// transactions don't serialize cross-record counts against concurrent -/// inserts. Same reasoning, and the same shape, as `ENROLL_LOCK`. -static CHATBOT_THREAD_LOCK: Mutex<()> = Mutex::const_new(()); - #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ChatbotThreadId(RecordId); @@ -109,37 +106,46 @@ impl ChatbotThread { } /// Start a thread unless `user` is already at the school's - /// `max_chatbot_threads`. The whole check-then-write runs under - /// [`CHATBOT_THREAD_LOCK`], and the cap is re-read inside it, since neither - /// the transaction model nor a caller-supplied number survives a concurrent - /// settings PATCH. + /// `max_chatbot_threads`. The slot is taken by [`cap::claim`] on the user + /// row — an atomic single-record write, so two replicas racing the same + /// user's last slot cannot both win, and the cap is read fresh so a + /// concurrent settings PATCH is respected. pub async fn create_capped( user: &UserId, title: Option, db: &Database, ) -> Result { - let _guard = CHATBOT_THREAD_LOCK.lock().await; - let cap = Settings::load(db).await?.get_max_chatbot_threads(); - if Self::count_for_user(user, db).await? as i64 >= cap { + let limit = Settings::load(db).await?.get_max_chatbot_threads(); + let owner = user.record(); + if !cap::claim(&owner, CHATBOT_THREAD_COUNT_FIELD, limit, db).await? { return Err(AppError::Conflict( "you have reached the school's limit on saved threads — delete one first", )); } - Self::create(user, title, db).await + match Self::create(user, title, db).await { + Ok(thread) => Ok(thread), + Err(err) => { + cap::release(&owner, CHATBOT_THREAD_COUNT_FIELD, db).await?; + Err(err) + } + } } /// A user's threads, most recently active first — the sort the /// `chatbot_thread_user_updated` index exists for. pub async fn list_for_user( user: &UserId, + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM chatbot_thread WHERE user_id = $usr ORDER BY updated_at DESC") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + ) -> Result<(Vec, i64), AppError> { + PagedList::new( + "chatbot_thread WHERE user_id = $usr", + "ORDER BY updated_at DESC", + ) + .bind("usr", user.record()) + .run(limit, offset, db) + .await } /// How many threads `user` keeps — the `max_chatbot_threads` cap check. @@ -207,21 +213,24 @@ impl ChatbotThread { } /// Delete the thread and every turn in it — one transaction, so a crash - /// can't orphan messages under a vanished thread. + /// can't orphan messages under a vanished thread. The owner's slot comes + /// back in that same transaction, or the cap would ratchet shut. pub async fn delete(self, db: &Database) -> Result { let mut result = db .query( "BEGIN TRANSACTION; DELETE chatbot_message WHERE thread_id = $conv; - DELETE $conv RETURN BEFORE; + LET $gone = (DELETE $conv RETURN BEFORE); + UPDATE $usr SET chatbot_thread_count = math::max([(chatbot_thread_count ?? 0) - array::len($gone), 0]); + RETURN $gone; COMMIT TRANSACTION;", ) .bind(("conv", self.id.record())) + .bind(("usr", self.user_id.record())) .await? .check()?; - // BEGIN is slot 0; the thread's own DELETE is slot 2. let deleted: Option = - result.take::>(2)?.into_iter().next(); + result.take::>(4)?.into_iter().next(); deleted.ok_or(AppError::NotFound) } } diff --git a/src/domain/course.rs b/src/domain/course.rs index d6db468..08440c3 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -4,6 +4,7 @@ use ulid::Ulid; use crate::constant::{COURSE_TABLE, MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN}; use crate::database::Database; use crate::domain::field_update::FieldUpdate; +use crate::domain::page::PagedList; use crate::domain::term::TermId; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -189,17 +190,19 @@ impl Course { /// The courses `user` is enrolled in — the spine of `/courses/me` and the /// marks report. - pub async fn list_enrolled(user: &UserId, db: &Database) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM course - WHERE id IN (SELECT VALUE course FROM enrollment WHERE user = $usr) - ORDER BY id DESC", - ) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + pub async fn list_enrolled( + user: &UserId, + limit: Option, + offset: i64, + db: &Database, + ) -> Result<(Vec, i64), AppError> { + PagedList::new( + "course WHERE id IN (SELECT VALUE course FROM enrollment WHERE user = $usr)", + "ORDER BY id DESC", + ) + .bind("usr", user.record()) + .run(limit, offset, db) + .await } /// The courses `user` runs — the ones they created plus the ones a manager diff --git a/src/domain/course_session.rs b/src/domain/course_session.rs index 10b13bf..658424e 100644 --- a/src/domain/course_session.rs +++ b/src/domain/course_session.rs @@ -1,30 +1,16 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use tokio::sync::Mutex; use ulid::Ulid; use crate::constant::{COURSE_SESSION_TABLE, MAX_SESSION_TOPIC_LEN}; use crate::database::Database; use crate::domain::course::CourseId; use crate::domain::field_update::FieldUpdate; -use crate::domain::timestamp::Timestamp; +use crate::domain::page::PagedList; +use crate::domain::timestamp::{Timestamp, range_error}; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::validate_optional; -/// Serializes a lesson's time-range check against the write it guards, exactly -/// as [`crate::domain::event::EVENT_LOCK`] does for events: `starts_at <= -/// ends_at` is a cross-field check, so a PATCH carrying one end validates it -/// against the *stored* other end — two such PATCHes, each fine on its own -/// snapshot, would otherwise commit an inverted lesson between them. A PATCH -/// that moves neither end checks nothing cross-field and stays lock-free. -/// -/// Lock order: this is a leaf — the only path that takes it (`PATCH -/// /sessions/{id}`) takes no other lock, and no path holding `EXAM_LOCK`, -/// `BANK_LOCK`, `HOMEWORK_LOCK`, `ENROLL_LOCK` or any other takes this one, so -/// it cannot sit in a cycle. Should a future path need both, take the other -/// lock first and this one innermost. -pub(crate) static SESSION_LOCK: Mutex<()> = Mutex::const_new(()); - #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct CourseSessionId(RecordId); @@ -140,18 +126,21 @@ impl CourseSession { /// the row was created. pub async fn list_for_course( course: &CourseId, + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM course_session WHERE course = $course ORDER BY starts_at DESC") - .bind(("course", course.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Request-scoped: the handler holds no lock across its read and this write - /// unless a schedule end arrives ([`SESSION_LOCK`]), so a field the request + ) -> Result<(Vec, i64), AppError> { + PagedList::new( + "course_session WHERE course = $course", + "ORDER BY starts_at DESC", + ) + .bind("course", course.record()) + .run(limit, offset, db) + .await + } + + /// Request-scoped: the handler holds nothing across its read and this + /// write — the range check rides in the `WHERE` — so a field the request /// omitted (`None`) is not written at all. Re-sending the snapshot's value /// instead would revert a concurrent PATCH of that field — scoping the /// `SET` alone does not stop that, the values have to come from the @@ -170,6 +159,7 @@ impl CourseSession { .set("topic", topic) .set("starts_at", starts_at) .set("ends_at", ends_at) + .ordered("starts_at", "ends_at", range_error()) .run::(db) .await } diff --git a/src/domain/enrollment.rs b/src/domain/enrollment.rs index d99d71a..369d683 100644 --- a/src/domain/enrollment.rs +++ b/src/domain/enrollment.rs @@ -1,17 +1,22 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use tokio::sync::Mutex; -use crate::constant::ENROLLMENT_TABLE; -use crate::database::Database; +use crate::constant::{ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE}; +use crate::database::{Database, lost_the_race}; +use crate::domain::cap; use crate::domain::course::{Course, CourseId}; +use crate::domain::page::PagedList; use crate::domain::user::UserId; use crate::error::AppError; -/// Serializes enrolls so the capacity check (count, then write) can't -/// over-admit under concurrency — the database's optimistic transactions -/// don't serialize cross-record counts against concurrent inserts. -/// It also serializes the roster check of a course delete against a concurrent -/// enroll, so a student can't join a course that is already on its way out. +/// Serializes the roster check of a course delete against a concurrent enroll, +/// so a student can't join a course that is already on its way out. +// +// ponytail: process-local, so with two replicas the delete-vs-enroll window is +// only narrowed, not closed — a student can still land on a course another +// replica is deleting, and the cascade then leaves nothing behind but a 404 on +// the next read. Closing it needs the same treatment the capacity cap got: a +// deleting flag on the course row that the enroll's conditional UPDATE checks. pub(crate) static ENROLL_LOCK: Mutex<()> = Mutex::const_new(()); #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -69,14 +74,14 @@ impl Enrollment { } /// Enroll (idempotently) `user` into `course`. One row per (course, user), - /// keyed by a deterministic composite id so this is a single atomic UPSERT — - /// concurrent enrolls for the same pair converge on one row instead of - /// racing the unique index into a 500. When the course carries a capacity, - /// a full roster refuses new members (409) — the whole check-then-write - /// runs under [`ENROLL_LOCK`], and the cap is re-derived from a fresh - /// course read inside it, since neither the transaction model nor a - /// caller-supplied course survives a concurrent capacity PATCH. An already - /// enrolled user is returned as-is even when the roster is full. + /// keyed by a deterministic composite id, so concurrent enrolls of the same + /// pair converge on one row instead of racing the unique index into a 500: + /// the loser of the `CREATE` reads the winner's row back and returns it. + /// When the course carries a capacity, a full roster refuses new members + /// (409) — the seat is taken by [`cap::claim`] on the course row, an atomic + /// single-record conditional write, so the cap holds across replicas and + /// against a concurrent capacity PATCH alike. An already enrolled user is + /// returned as-is even when the roster is full, and never charged a seat. pub async fn enroll( course: &CourseId, user: &UserId, @@ -91,8 +96,14 @@ impl Enrollment { .await? .ok_or(AppError::NotFound)? .get_capacity(); - if let Some(capacity) = capacity - && Self::list_for_course(course, db).await?.len() as i64 >= capacity + let seats = course.record(); + if !cap::claim( + &seats, + ENROLLMENT_COUNT_FIELD, + capacity.unwrap_or(cap::UNLIMITED), + db, + ) + .await? { return Err(AppError::Conflict("the course is full")); } @@ -102,11 +113,27 @@ impl Enrollment { user: user.clone(), enrolled_by: enrolled_by.clone(), }; - let saved: Option = db - .upsert(enrollment.id.record()) - .content(enrollment) - .await?; - saved.ok_or_else(|| AppError::Internal("failed to enroll user".into())) + // CREATE, not UPSERT: a duplicate has to be *seen*, or the pair's second + // writer would silently keep the seat it claimed for a row that already + // existed and the counter would drift above the roster forever. + let saved: Result, _> = + db.create(enrollment.id.record()).content(enrollment).await; + match saved { + Ok(Some(saved)) => Ok(saved), + Ok(None) => { + cap::release(&seats, ENROLLMENT_COUNT_FIELD, db).await?; + Err(AppError::Internal("failed to enroll user".into())) + } + Err(err) => { + cap::release(&seats, ENROLLMENT_COUNT_FIELD, db).await?; + if !lost_the_race(&err) { + return Err(err.into()); + } + Self::read_for_user(course, user, db) + .await? + .ok_or_else(|| AppError::Internal("failed to enroll user".into())) + } + } } /// Some(_) iff `user` is enrolled in `course` — the grading gate. @@ -136,23 +163,30 @@ impl Enrollment { pub async fn list_for_course( course: &CourseId, + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM enrollment WHERE course = $course ORDER BY id DESC") - .bind(("course", course.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + ) -> Result<(Vec, i64), AppError> { + PagedList::new("enrollment WHERE course = $course", "ORDER BY id DESC") + .bind("course", course.record()) + .run(limit, offset, db) + .await } /// Drop every enrollment `user` holds, across all courses. Only students /// enroll, so promotion out of `student` calls this to clear the rosters. pub async fn delete_for_user(user: &UserId, db: &Database) -> Result<(), AppError> { - db.query("DELETE enrollment WHERE user = $usr") - .bind(("usr", user.record())) - .await? - .check()?; + db.query( + "BEGIN TRANSACTION; + LET $gone = (DELETE enrollment WHERE user = $usr RETURN BEFORE); + FOR $row IN ($gone ?? []) { + UPDATE $row.course SET enrollment_count = math::max([(enrollment_count ?? 0) - 1, 0]); + }; + COMMIT TRANSACTION;", + ) + .bind(("usr", user.record())) + .await? + .check()?; Ok(()) } @@ -161,12 +195,20 @@ impl Enrollment { user: &UserId, db: &Database, ) -> Result, AppError> { + // The seat comes back in the same transaction as the row that held it, + // so nothing but a lost transaction can drift the counter. let mut result = db - .query("DELETE enrollment WHERE course = $course AND user = $usr RETURN BEFORE") + .query( + "BEGIN TRANSACTION; + LET $gone = (DELETE enrollment WHERE course = $course AND user = $usr RETURN BEFORE); + UPDATE $course SET enrollment_count = math::max([(enrollment_count ?? 0) - array::len($gone), 0]); + RETURN $gone; + COMMIT TRANSACTION;", + ) .bind(("course", course.record())) .bind(("usr", user.record())) .await? .check()?; - Ok(result.take::>(0)?.into_iter().next()) + Ok(result.take::>(3)?.into_iter().next()) } } diff --git a/src/domain/event.rs b/src/domain/event.rs index 27ce711..bb11b85 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -1,7 +1,6 @@ // `Value` looks unused but is load-bearing: the `SurrealValue` derive on the // tagged `EventAudience` enum expands to code that names `Value` unqualified. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; -use tokio::sync::Mutex; use ulid::Ulid; use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; @@ -11,25 +10,11 @@ use crate::domain::enrollment::Enrollment; use crate::domain::field_update::FieldUpdate; use crate::domain::registration::Registration; use crate::domain::role::Role; -use crate::domain::timestamp::Timestamp; +use crate::domain::timestamp::{Timestamp, range_error}; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_optional, validate_required}; -/// Serializes the schedule-range check against the write it guards, exactly as -/// `TERM_LOCK` does for terms: `starts_at <= ends_at` is a cross-field check, -/// so a partial PATCH validates the end it carries against the *stored* other -/// end — two such PATCHes, each fine on its own snapshot, would otherwise -/// commit an inverted range between them. A PATCH that moves neither end -/// checks nothing cross-field and stays lock-free. -/// -/// Lock order: this is a leaf — the only path that takes it (`PATCH -/// /events/{id}`) takes no other lock, and no path that holds `REGISTER_LOCK`, -/// `ENROLL_LOCK`, `TERM_LOCK`, `EXAM_LOCK` or any other takes this one, so it -/// cannot sit in a cycle. Should a future path need both, take the other lock -/// first and this one innermost. -pub(crate) static EVENT_LOCK: Mutex<()> = Mutex::const_new(()); - #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct EventId(RecordId); @@ -140,8 +125,9 @@ impl EventAudience { /// are kept; the caller degrades their display like any stale reference. pub async fn members(&self, event: &EventId, db: &Database) -> Result, AppError> { match self { - EventAudience::School => Ok(User::list_all(db) + EventAudience::School => Ok(User::list_all(None, 0, db) .await? + .0 .iter() .map(|user| user.get_id().clone()) .collect()), @@ -150,11 +136,14 @@ impl EventAudience { .iter() .map(|user| user.get_id().clone()) .collect()), - EventAudience::Course { course } => Ok(Enrollment::list_for_course(course, db) - .await? - .iter() - .map(|enrollment| enrollment.get_user().clone()) - .collect()), + EventAudience::Course { course } => { + Ok(Enrollment::list_for_course(course, None, 0, db) + .await? + .0 + .iter() + .map(|enrollment| enrollment.get_user().clone()) + .collect()) + } EventAudience::Registration { .. } => Ok(Registration::list_for_event(event, db) .await? .iter() @@ -287,6 +276,7 @@ impl Event { .set("audience", audience) .set("starts_at", starts_at) .set("ends_at", ends_at) + .ordered("starts_at", "ends_at", range_error()) .run::(db) .await } diff --git a/src/domain/exam.rs b/src/domain/exam.rs index 5679dfd..aced7cb 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -10,6 +10,15 @@ use crate::domain::settings::ExamKindDef; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; + +/// The one spelling of the re-draft refusal, shared by the handler's +/// pre-flight gate and the in-transaction guard that re-makes it at write +/// time — a client cannot tell which of the two refused. +pub(crate) fn redraft_error() -> AppError { + AppError::Conflict( + "cannot turn a published exam back into a draft after attempts or results exist", + ) +} use crate::validate::{ validate_attempt_limit, validate_exam_duration, validate_exam_mode, validate_optional, validate_required, @@ -444,7 +453,17 @@ impl Exam { clippy::too_many_arguments, reason = "mirrors the sibling entities' update(field, field, ..) shape" )] - pub async fn update( + /// Save the merged exam, but only while the row still reads as the + /// snapshot the caller merged over — `None` means a concurrent PATCH + /// landed in between and nothing was written: re-read, re-merge, retry. + /// + /// Every column this write replaces is in the guard, which is what makes + /// the whole-row `CONTENT` save safe without a lock held across the + /// handler's read: the compare-and-set refuses precisely when that save + /// would have reverted somebody. `course`/`creator` are not editable and + /// ride along unchanged. Same shape as + /// [`crate::domain::settings::Settings::save_if_unchanged`]. + pub async fn update_if_unchanged( mut self, title: ExamTitle, description: ExamDescription, @@ -455,7 +474,26 @@ impl Exam { allow_review: bool, draft: bool, db: &Database, - ) -> Result { + ) -> Result, AppError> { + // Re-drafting hides an exam: it must be refused while any sitting or + // mark exists, and that check has to be *in this transaction*. Holding + // it under a lock outside would only order the two writers inside one + // process — and it did not even do that, since grading takes the reader + // lease this write does. + let redraft = draft && !self.draft; + let was = ( + self.title.clone(), + self.description.clone(), + self.kind.clone(), + self.mode.clone(), + self.starts_at, + self.ends_at, + self.duration_ms, + self.max_attempts, + self.allow_rejoin, + self.allow_review, + self.draft, + ); self.title = title; self.description = description; self.kind = kind; @@ -467,9 +505,56 @@ impl Exam { self.allow_rejoin = allow_rejoin; self.allow_review = allow_review; self.draft = draft; - // whole-row-save-ok: the only caller takes EXAM_LOCK.write() before the row read (web/exams.rs:354) - let updated: Option = db.update(self.id.record()).content(self).await?; - updated.ok_or(AppError::NotFound) + // whole-row-save-ok: the WHERE below pins every column this replaces to + // the caller's snapshot, so no concurrent write can be reverted + let mut result = db + .query( + "BEGIN TRANSACTION; + IF $redraft AND ( + array::len((SELECT VALUE id FROM exam_attempt WHERE exam = $id LIMIT 1)) > 0 + OR array::len((SELECT VALUE id FROM exam_result WHERE exam = $id LIMIT 1)) > 0 + ) { THROW 'exam_redraft' }; + UPDATE $id CONTENT $new + WHERE title = $was_title AND description = $was_description + AND kind = $was_kind AND mode = $was_mode + AND starts_at = $was_starts AND ends_at = $was_ends + AND duration_ms = $was_duration + AND max_attempts = $was_max_attempts + AND allow_rejoin = $was_allow_rejoin + AND allow_review = $was_allow_review + AND draft = $was_draft + RETURN AFTER; + COMMIT TRANSACTION;", + ) + .bind(("redraft", redraft)) + .bind(("id", self.id.record())) + .bind(("was_title", was.0)) + .bind(("was_description", was.1)) + .bind(("was_kind", was.2)) + .bind(("was_mode", was.3)) + .bind(("was_starts", was.4)) + .bind(("was_ends", was.5)) + .bind(("was_duration", was.6)) + .bind(("was_max_attempts", was.7)) + .bind(("was_allow_rejoin", was.8)) + .bind(("was_allow_review", was.9)) + .bind(("was_draft", was.10)) + .bind(("new", self)) + .await?; + // An aborted transaction errors every slot; only the THROW's names the + // marker (the `frozen_check` treatment). + let mut errors = result.take_errors(); + if errors + .values() + .any(|error| error.to_string().contains("exam_redraft")) + { + return Err(redraft_error()); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // BEGIN and the IF take a slot each. + Ok(result.take::>(2)?.into_iter().next()) } /// Delete the exam and cascade-remove its result, attempt, question, @@ -516,6 +601,128 @@ impl Exam { mod tests { use super::*; + /// An unscheduled published exam, the minimum this file's write tests need. + async fn published(db: &Database) -> Exam { + let allowed: Vec = crate::domain::settings::Settings::defaults() + .get_exam_kinds() + .to_vec(); + Exam::create( + &UserId::generate(), + &CourseId::generate(), + ExamTitle::try_new("midterm").unwrap(), + ExamDescription::try_new("").unwrap(), + ExamKind::try_new("midterm", &allowed).unwrap(), + ExamSchedule::try_new(None, None, None, None).unwrap(), + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + false, + db, + ) + .await + .unwrap() + } + + fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) { + ( + exam.get_title().clone(), + exam.get_description().clone(), + exam.get_kind().clone(), + ExamSchedule::try_new(None, None, None, None).unwrap(), + ) + } + + /// The bite test for the compare-and-set that replaced the writer lease on + /// `PATCH /exams/{id}`: a merge built on a snapshot the row has moved past + /// must be refused (the handler then re-reads and re-merges), never + /// written over somebody else's edit. Asserts the *stored* row. + #[tokio::test] + async fn a_merge_built_on_a_stale_snapshot_is_refused() { + let db = crate::database::init_mem().await.unwrap(); + let stale = published(&db).await; + let (_, description, kind, schedule) = edit(&stale); + let landed = stale + .clone() + .update_if_unchanged( + ExamTitle::try_new("theirs").unwrap(), + description, + kind, + schedule, + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + false, + &db, + ) + .await + .unwrap(); + assert!(landed.is_some(), "the first write is on a fresh snapshot"); + + let (_, description, kind, schedule) = edit(&stale); + let refused = stale + .update_if_unchanged( + ExamTitle::try_new("mine").unwrap(), + description, + kind, + schedule, + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + false, + &db, + ) + .await + .unwrap(); + assert!(refused.is_none(), "a stale merge must not be written"); + let stored = Exam::read(landed.unwrap().get_id(), &db) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.get_title().as_str(), "theirs"); + } + + /// The bite test for the re-draft guard now living *inside* the update's + /// transaction: a mark that lands after the handler's pre-flight gate (the + /// grade path is a lock reader, exactly like this one) must still stop the + /// exam from being hidden. + #[tokio::test] + async fn re_drafting_is_refused_by_the_write_itself_once_a_mark_exists() { + use crate::domain::exam_result::{ExamResult, Mark}; + let db = crate::database::init_mem().await.unwrap(); + let exam = published(&db).await; + let student = UserId::generate(); + ExamResult::grade( + exam.get_id(), + &student, + 1, + Mark::try_new(80).unwrap(), + &UserId::generate(), + &db, + ) + .await + .unwrap(); + + let (title, description, kind, schedule) = edit(&exam); + let refused = exam + .clone() + .update_if_unchanged( + title, + description, + kind, + schedule, + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + true, + &db, + ) + .await + .expect_err("a graded exam cannot be re-drafted"); + assert!(refused.to_string().contains("back into a draft")); + let stored = Exam::read(exam.get_id(), &db).await.unwrap().unwrap(); + assert!(!stored.is_draft(), "nothing may have been written"); + } + #[tokio::test] async fn title_is_required() { assert!(ExamTitle::try_new("midterm").is_ok()); diff --git a/src/domain/exam_answer.rs b/src/domain/exam_answer.rs index f1d3af8..dcaa0bb 100644 --- a/src/domain/exam_answer.rs +++ b/src/domain/exam_answer.rs @@ -4,6 +4,7 @@ use crate::constant::{EXAM_ANSWER_TABLE, MAX_ANSWER_TEXT_LEN}; use crate::database::Database; use crate::domain::exam::ExamId; use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId}; +use crate::domain::key; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -13,20 +14,13 @@ use crate::validate::validate_optional; pub struct ExamAnswerId(RecordId); impl ExamAnswerId { - /// A deterministic id for the (question, user, seq) triple — the question - /// key is its own ULID, so the triple key is unambiguous. Saving is a + /// A deterministic id for the (question, user, seq) triple. Saving is a /// single atomic UPSERT keyed by seq: re-answering *within a sitting* /// overwrites its one row, but a retake's `seq` writes a new row, so every - /// sitting keeps its own answer history. The first sitting keeps the - /// historical `{question}_{user}` shape (rows written before history - /// existed stay addressable); later sittings append their number. ULID - /// keys are alphanumeric, so `_` is an unambiguous joiner. + /// sitting keeps its own answer history. See [`key::sitting`] for the key + /// shape and why the first sitting stays bare. pub fn composite(question: &ExamQuestionId, user: &UserId, seq: i64) -> Self { - let key = if seq == 1 { - format!("{}_{}", question.key(), user.key()) - } else { - format!("{}_{}_{}", question.key(), user.key(), seq) - }; + let key = key::sitting(question.key(), user.key(), seq); Self(RecordId::new(EXAM_ANSWER_TABLE, key)) } diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs index df41529..da6293b 100644 --- a/src/domain/exam_attempt.rs +++ b/src/domain/exam_attempt.rs @@ -4,27 +4,30 @@ use crate::constant::EXAM_ATTEMPT_TABLE; use crate::database::Database; use crate::domain::exam::Exam; use crate::domain::exam::ExamId; +use crate::domain::key; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; +/// The `THROW` marker the freeze gate aborts with, and the one 409 both it and +/// the handler's pre-flight check answer with — a client cannot tell which of +/// the two refused. +const FROZEN_MARK: &str = "questions_frozen"; + +pub(crate) fn frozen_error() -> AppError { + AppError::Conflict("cannot change questions after attempts have started") +} + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ExamAttemptId(RecordId); impl ExamAttemptId { - /// A deterministic id for the (exam, user, seq) triple. The same triple - /// always maps to the same record id, so sitting `seq` exists at most once - /// by construction — a concurrent double "start" races on the same id and - /// exactly one create wins. The first sitting keeps the historical - /// `{exam}_{user}` shape (rows written before retakes existed stay - /// addressable); later sittings append their number. ULID keys are - /// alphanumeric, so `_` is an unambiguous joiner. + /// A deterministic id for the (exam, user, seq) triple, so sitting `seq` + /// exists at most once by construction — a concurrent double "start" races + /// on the same id and exactly one create wins. See [`key::sitting`] for the + /// key shape and why the first sitting stays bare. pub fn composite(exam: &ExamId, user: &UserId, seq: i64) -> Self { - let key = if seq == 1 { - format!("{}_{}", exam.key(), user.key()) - } else { - format!("{}_{}_{}", exam.key(), user.key(), seq) - }; + let key = key::sitting(exam.key(), user.key(), seq); Self(RecordId::new(EXAM_ATTEMPT_TABLE, key)) } @@ -311,6 +314,57 @@ impl ExamAttempt { Ok(result.take::>(0)?) } + /// Wrap `statements` in a transaction that refuses to run them at all once + /// `$freeze_exam` has an attempt — the freeze gate, made atomic with the + /// write it guards instead of merely preceding it. Callers bind + /// `freeze_exam` and read their own results from + /// [`Self::FROZEN_SLOT`] onwards (`BEGIN` and the `IF` take a slot each). + /// + /// This replaces a process-wide `EXAM_LOCK.write()` held across the check + /// and the write. That lock served one process; the gate serves the + /// database, so a question edit on replica A can no longer sail past an + /// attempt started on replica B. + // + // ponytail: the count and a concurrent `CREATE exam_attempt` are still not + // serialized against each other — SurrealDB does not conflict-check a + // cross-record count (the write skew `domain::cap` exists for), so an + // attempt landing in the same instant as an edit can still interleave + // either way. The mutex this replaces closed that inside one process only, + // and there are two, so nothing is lost. Closing it properly means the + // cap.rs shape: an attempt counter on the exam row, incremented by the + // attempt create, and the write conditioned on `count ?? 0 = 0`. + pub(crate) fn unfrozen(statements: &str) -> String { + format!( + "BEGIN TRANSACTION; + IF array::len((SELECT VALUE id FROM exam_attempt \ + WHERE exam = $freeze_exam LIMIT 1)) > 0 {{ THROW '{FROZEN_MARK}' }}; + {statements} + COMMIT TRANSACTION;" + ) + } + + /// The first slot a [`Self::unfrozen`] caller's own statements land in. + pub(crate) const FROZEN_SLOT: usize = 2; + + /// Turn a gate abort into the 409 the pre-flight check answers with, so + /// losing the race and failing the check read identically to a client. + /// An aborted transaction errors *every* slot with a generic "not + /// executed" — only the `THROW`'s own slot names the marker, so every slot + /// is scanned. + pub(crate) fn frozen_check(result: &mut surrealdb::IndexedResults) -> Result<(), AppError> { + let mut errors = result.take_errors(); + if errors + .values() + .any(|error| error.to_string().contains(FROZEN_MARK)) + { + return Err(frozen_error()); + } + match errors.drain().map(|(_, error)| error).next() { + Some(error) => Err(error.into()), + None => Ok(()), + } + } + /// Whether anyone has started this exam — the gate that freezes `mode` /// edits once an attempt exists. pub async fn any_for_exam(exam: &ExamId, db: &Database) -> Result { diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index de19575..448c423 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -8,7 +8,9 @@ use crate::constant::{ use crate::database::Database; use crate::domain::bank_question::BankQuestionId; use crate::domain::exam::ExamId; +use crate::domain::exam_attempt::ExamAttempt; use crate::domain::monotonic_id::next_ulid; +use crate::domain::page::PagedList; use crate::domain::subject::SubjectId; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_question_kind, validate_question_points, validate_required}; @@ -404,9 +406,21 @@ impl ExamQuestion { // An insert never banks anything: only a to-bank save writes this. banked_as: None, }; - let created: Option = - db.create(question.id.record()).content(question).await?; - created.ok_or_else(|| AppError::Internal("failed to create exam question".into())) + // The freeze gate rides in the same transaction as the insert: a + // question cannot appear under an exam somebody has already started, + // whichever replica the two requests hit. + let mut result = db + .query(ExamAttempt::unfrozen("CREATE $id CONTENT $question;")) + .bind(("freeze_exam", exam.record())) + .bind(("id", question.id.record())) + .bind(("question", question)) + .await?; + ExamAttempt::frozen_check(&mut result)?; + result + .take::>(ExamAttempt::FROZEN_SLOT)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to create exam question".into())) } pub async fn read( @@ -419,14 +433,14 @@ impl ExamQuestion { /// The exam's questions in presentation order (ULID ids sort by creation). pub async fn list_for_exam( exam: &ExamId, + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM exam_question WHERE exam = $ex ORDER BY id ASC") - .bind(("ex", exam.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + ) -> Result<(Vec, i64), AppError> { + PagedList::new("exam_question WHERE exam = $ex", "ORDER BY id ASC") + .bind("ex", exam.record()) + .run(limit, offset, db) + .await } /// Whether any question anywhere references `subject` — the gate that @@ -440,23 +454,44 @@ impl ExamQuestion { Ok(!result.take::>(0)?.is_empty()) } + /// Write the editable fields, refused outright once the exam has an + /// attempt — the freeze gate is part of this transaction, not a check the + /// caller made a moment earlier under a lock. + /// + /// Field-scoped, no longer a whole-row save. The row also carries + /// `from_bank`/`banked_as`, which [`Self::link_banked_as`] writes from a + /// *different* request: re-stating this snapshot's copy of them would + /// revert a to-bank save that landed in between. That is exactly what the + /// caller's `EXAM_LOCK.write()` used to order (inside one process), and + /// naming the columns removes the need for any ordering at all. pub async fn update( - mut self, + self, subject: SubjectId, text: QuestionText, points: QuestionPoints, spec: QuestionSpec, db: &Database, ) -> Result { - self.subject = subject; - self.text = text; - self.points = points; - self.kind = spec.kind; - self.choices = spec.choices; - self.correct = spec.correct; - // whole-row-save-ok: callers hold EXAM_LOCK.write() across the read and this write - let updated: Option = db.update(self.id.record()).content(self).await?; - updated.ok_or(AppError::NotFound) + let mut result = db + .query(ExamAttempt::unfrozen( + "UPDATE $id SET subject = $subject, text = $text, points = $points, + kind = $kind, choices = $choices, correct = $correct RETURN AFTER;", + )) + .bind(("freeze_exam", self.exam.record())) + .bind(("id", self.id.record())) + .bind(("subject", subject.record())) + .bind(("text", text)) + .bind(("points", points)) + .bind(("kind", spec.kind)) + .bind(("choices", spec.choices)) + .bind(("correct", spec.correct)) + .await?; + ExamAttempt::frozen_check(&mut result)?; + result + .take::>(ExamAttempt::FROZEN_SLOT)? + .into_iter() + .next() + .ok_or(AppError::NotFound) } /// Point the question's `banked_as` at the bank template it was just saved @@ -495,16 +530,26 @@ impl ExamQuestion { /// Delete the question and cascade-remove its answers and image rows, so /// neither can point at a missing question. The image *blobs* are the web /// layer's to remove — it collects their names before calling this. + /// Refused once the exam has an attempt, in the same transaction as the + /// delete — and the cascade now shares that transaction too, so a failure + /// mid-way can no longer strand answers whose question survived. pub async fn delete(self, db: &Database) -> Result { - db.query( - "DELETE exam_answer WHERE question = $q; - DELETE question_image WHERE question = $q;", - ) - .bind(("q", self.id.record())) - .await? - .check()?; - let deleted: Option = db.delete(self.id.record()).await?; - deleted.ok_or(AppError::NotFound) + let mut result = db + .query(ExamAttempt::unfrozen( + "DELETE exam_answer WHERE question = $q; + DELETE question_image WHERE question = $q; + DELETE $q RETURN BEFORE;", + )) + .bind(("freeze_exam", self.exam.record())) + .bind(("q", self.id.record())) + .await?; + ExamAttempt::frozen_check(&mut result)?; + // Two cascade statements ahead of the delete itself. + result + .take::>(ExamAttempt::FROZEN_SLOT + 2)? + .into_iter() + .next() + .ok_or(AppError::NotFound) } /// A question constructed without a database, for pure-function tests. diff --git a/src/domain/exam_result.rs b/src/domain/exam_result.rs index 06b31b5..ef54122 100644 --- a/src/domain/exam_result.rs +++ b/src/domain/exam_result.rs @@ -6,27 +6,27 @@ use crate::constant::EXAM_RESULT_TABLE; use crate::database::Database; use crate::domain::course::CourseId; use crate::domain::exam::ExamId; +use crate::domain::key; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::validate_mark; +/// The one spelling of "this exam is hidden", shared by the grade handler's +/// pre-flight gate and the in-transaction guard on the mark write. +pub(crate) fn draft_error() -> AppError { + AppError::Conflict("this exam is a draft — publish it before grading") +} + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ExamResultId(RecordId); impl ExamResultId { /// A deterministic id for the (exam, user, seq) triple — one mark row per - /// sitting. The same triple always maps to the same record id, so grading a - /// sitting is a single atomic UPSERT with no find-then-insert race. The - /// first sitting keeps the historical `{exam}_{user}` shape (marks written - /// before per-attempt history existed stay addressable unchanged); later - /// sittings append their number. ULID keys are alphanumeric, so `_` is an - /// unambiguous joiner. + /// sitting, so grading is a single atomic UPSERT with no find-then-insert + /// race. See [`key::sitting`] for the key shape and why the first sitting + /// stays bare. pub fn composite(exam: &ExamId, user: &UserId, seq: i64) -> Self { - let key = if seq == 1 { - format!("{}_{}", exam.key(), user.key()) - } else { - format!("{}_{}_{}", exam.key(), user.key(), seq) - }; + let key = key::sitting(exam.key(), user.key(), seq); Self(RecordId::new(EXAM_RESULT_TABLE, key)) } @@ -171,8 +171,38 @@ impl ExamResult { mark, graded_by: graded_by.clone(), }; - let saved: Option = db.upsert(result.id.record()).content(result).await?; - saved.ok_or_else(|| AppError::Internal("failed to record exam result".into())) + // The "not a draft" gate rides in the same transaction as the mark, the + // mirror of the re-draft gate on `Exam::update_if_unchanged`: between + // them, a mark and a re-draft racing each other can only ever leave one + // of the two applied, whichever process either ran in. The caller's + // pre-flight check answers the same 409 one round trip earlier. + let mut written = db + .query( + "BEGIN TRANSACTION; + IF (SELECT VALUE draft FROM ONLY $exam) { THROW 'exam_draft' }; + UPSERT $id CONTENT $result RETURN AFTER; + COMMIT TRANSACTION;", + ) + .bind(("exam", exam.record())) + .bind(("id", result.id.record())) + .bind(("result", result)) + .await?; + let mut errors = written.take_errors(); + if errors + .values() + .any(|error| error.to_string().contains("exam_draft")) + { + return Err(draft_error()); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // BEGIN and the IF take a slot each. + written + .take::>(2)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to record exam result".into())) } /// The user's graded results restricted to one course's exams — the raw diff --git a/src/domain/field_update.rs b/src/domain/field_update.rs index 8c0b228..37256aa 100644 --- a/src/domain/field_update.rs +++ b/src/domain/field_update.rs @@ -32,6 +32,8 @@ pub struct FieldUpdate { /// `field = $field` fragments, in the order they were set. assignments: Vec, bindings: Vec<(String, Value)>, + /// `(low, high, refusal)` for [`FieldUpdate::ordered`]. + ordered: Option<(&'static str, &'static str, AppError)>, } impl FieldUpdate { @@ -40,6 +42,7 @@ impl FieldUpdate { id, assignments: Vec::new(), bindings: Vec::new(), + ordered: None, } } @@ -54,25 +57,71 @@ impl FieldUpdate { self } + /// Refuse the write unless `low <= high` still holds on the *merged* row — + /// the new value for an end this PATCH carries, the stored column for one it + /// omits. Emitted as a `WHERE` on the same `UPDATE`, so the comparison the + /// handler made against its snapshot is re-made by the database at write + /// time, against the row as it is *then*: two PATCHes each moving one end, + /// each fine on its own, cannot commit an inverted range between them. That + /// is what an in-process `Mutex` used to buy, and this holds across replicas. + /// + /// Call it after the `.set()`s of both fields. A PATCH that moves neither + /// end emits no guard at all (nothing to race), matching the lock window it + /// replaces — so a pre-existing inverted row stays editable field by field. + /// `NONE` on either side passes, exactly like + /// [`crate::web::check_time_range`] skipping an absent end. + #[must_use] + pub fn ordered(mut self, low: &'static str, high: &'static str, refused: AppError) -> Self { + self.ordered = Some((low, high, refused)); + self + } + /// Run the update and return the stored row. An empty request writes /// nothing at all and reads the row back unchanged. - pub async fn run(self, db: &Database) -> Result { + pub async fn run(mut self, db: &Database) -> Result { if self.assignments.is_empty() { let row: Option = db.select(self.id).await?; return row.ok_or(AppError::NotFound); } + let (guard, mut refused) = match self.ordered.take() { + // Both ends stored: name the bound variable for an end this request + // set, the column for one it left alone. + Some((low, high, err)) if self.is_set(low) || self.is_set(high) => { + let side = |field: &str, set| { + if set { + format!("${field}") + } else { + field.into() + } + }; + let low = side(low, self.is_set(low)); + let high = side(high, self.is_set(high)); + ( + format!(" WHERE ({low} = NONE OR {high} = NONE OR {low} <= {high})"), + Some(err), + ) + } + _ => (String::new(), None), + }; let sets = self.assignments.join(", "); let mut query = db - .query(format!("UPDATE $id SET {sets} RETURN AFTER")) + .query(format!("UPDATE $id SET {sets}{guard} RETURN AFTER")) .bind(("id", self.id)); for (name, value) in self.bindings { query = query.bind((name, value)); } let mut result = query.await?.check()?; + // No row back means the guard bit (or, in the window after the handler's + // read, the row was deleted — the guard cannot tell the two apart, and + // reports the refusal it was given). result .take::>(0)? .into_iter() .next() - .ok_or(AppError::NotFound) + .ok_or_else(|| refused.take().unwrap_or(AppError::NotFound)) + } + + fn is_set(&self, field: &str) -> bool { + self.bindings.iter().any(|(name, _)| name == field) } } diff --git a/src/domain/homework_file.rs b/src/domain/homework_file.rs index 43d7fb7..02bc85f 100644 --- a/src/domain/homework_file.rs +++ b/src/domain/homework_file.rs @@ -9,11 +9,13 @@ //! upload, row before blob on delete); this module owns the rows. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use tokio::sync::Mutex; use ulid::Ulid; -use crate::constant::{HOMEWORK_FILE_TABLE, MAX_HOMEWORK_FILES_PER_SUBMISSION}; +use crate::constant::{ + HOMEWORK_FILE_TABLE, MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD, +}; use crate::database::Database; +use crate::domain::cap; use crate::domain::course::CourseId; use crate::domain::homework::HomeworkId; use crate::domain::homework_submission::HomeworkSubmissionId; @@ -21,14 +23,6 @@ use crate::domain::note_file::{FileContentType, FileName}; use crate::domain::timestamp::Timestamp; use crate::error::AppError; -/// Serializes the files-per-submission cap check against the insert (see -/// [`HomeworkFile::insert`]). Its own lock, not note files' `FILE_CAP_LOCK`: -/// the two caps are independent counts and must not needlessly contend on one -/// mutex. This backend is the database's only writer, so one process-wide lock -/// suffices. -// ponytail: global lock, per-submission locks if uploads ever see real contention. -static SUBMISSION_FILE_LOCK: Mutex<()> = Mutex::const_new(()); - #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct HomeworkFileId(RecordId); @@ -117,23 +111,38 @@ impl HomeworkFile { } /// Persist the row assembled by [`Self::new`], refusing once its submission - /// already holds [`MAX_HOMEWORK_FILES_PER_SUBMISSION`]. The - /// count-then-create runs under [`SUBMISSION_FILE_LOCK`]: a `BEGIN…COMMIT` - /// can't enforce the cap because SurrealDB doesn't conflict-check a - /// cross-record count against a concurrent insert (write-skew), the same - /// story as `NoteFile::insert`. + /// already holds [`MAX_HOMEWORK_FILES_PER_SUBMISSION`]. The slot is taken by + /// [`cap::claim`] on the submission row — a conditional single-record write, + /// the only guard that holds when the racing uploads are in two replicas, + /// the same story as `NoteFile::insert`. pub async fn insert(self, db: &Database) -> Result { - let _guard = SUBMISSION_FILE_LOCK.lock().await; - if Self::count_for_submission(&self.submission, db).await? - >= MAX_HOMEWORK_FILES_PER_SUBMISSION + let submission = self.submission.record(); + if !cap::claim( + &submission, + SUBMISSION_FILE_COUNT_FIELD, + MAX_HOMEWORK_FILES_PER_SUBMISSION as i64, + db, + ) + .await? { return Err(AppError::Conflict( "the submission already holds the maximum of 10 files — delete one first", )); } // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber - let created: Option = db.create(self.id.record()).content(self).await?; - created.ok_or_else(|| AppError::Internal("failed to create homework file".into())) + let created: Result, _> = + db.create(self.id.record()).content(self).await; + match created { + Ok(Some(created)) => Ok(created), + Ok(None) => { + cap::release(&submission, SUBMISSION_FILE_COUNT_FIELD, db).await?; + Err(AppError::Internal("failed to create homework file".into())) + } + Err(err) => { + cap::release(&submission, SUBMISSION_FILE_COUNT_FIELD, db).await?; + Err(err.into()) + } + } } /// Read a file's row only if it belongs to `submission` — callers have @@ -230,9 +239,27 @@ impl HomeworkFile { Ok(result.take::>(0)?) } + /// Delete the row and give its slot back in the same transaction. The + /// submission survives, so its counter has to be corrected; the cascades + /// that delete the submission itself take the counter with it. pub async fn delete(self, db: &Database) -> Result { - let deleted: Option = db.delete(self.id.record()).await?; - deleted.ok_or(AppError::NotFound) + let mut result = db + .query( + "BEGIN TRANSACTION; + LET $gone = (DELETE $id RETURN BEFORE); + UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); + RETURN $gone; + COMMIT TRANSACTION;", + ) + .bind(("id", self.id.record())) + .bind(("sub", self.submission.record())) + .await? + .check()?; + result + .take::>(3)? + .into_iter() + .next() + .ok_or(AppError::NotFound) } } diff --git a/src/domain/key.rs b/src/domain/key.rs new file mode 100644 index 0000000..1d6ef6b --- /dev/null +++ b/src/domain/key.rs @@ -0,0 +1,54 @@ +//! Deterministic record keys shared by the per-sitting exam tables and the +//! image-slot tables. + +/// The key for a `(scope, user, seq)` triple, where `scope` is whatever the row +/// hangs off — an exam for attempts and results, a question for answers and +/// drawings. The same triple always maps to the same key, so "one row per +/// student per sitting" holds by construction: a concurrent double write races +/// on one id instead of creating two rows, and no unique index is needed. +/// +/// The first sitting keeps the historical `{scope}_{user}` shape — rows written +/// before per-attempt history existed stay addressable, unchanged, forever — so +/// only later sittings carry their number. That bare-`seq == 1` case is +/// migration law, not a style choice: change it and every pre-history row +/// becomes unreachable. ULID keys are alphanumeric, so `_` is an unambiguous +/// joiner. +pub fn sitting(scope: &str, user: &str, seq: i64) -> String { + if seq == 1 { + format!("{scope}_{user}") + } else { + format!("{scope}_{user}_{seq}") + } +} + +/// The key for one image slot on `owner` — `{owner}_q` for the thing's own +/// illustration, `{owner}_{choice id}` for one option's picture. Uniqueness per +/// slot needs no index this way, and keying by the option's *stable id* means +/// reordering the choice list moves no picture. `_` is not in Crockford base32 +/// and a ULID is never `"q"`, so the two shapes can never collide — the rule +/// behind every image table's ids, spelled once. +pub fn slot(owner: &str, slot: Option<&str>) -> String { + format!("{owner}_{}", slot.unwrap_or("q")) +} + +#[cfg(test)] +mod tests { + use super::{sitting, slot}; + + #[test] + fn a_slot_key_never_collides_with_the_illustration() { + assert_eq!(slot("Q", None), "Q_q"); + assert_eq!(slot("Q", Some("01J8XZ")), "Q_01J8XZ"); + // A choice id is a ULID, so it can never be the literal "q". + assert_ne!(slot("Q", Some("01J8XZ")), slot("Q", None)); + } + + #[test] + fn the_first_sitting_stays_bare_and_later_ones_are_numbered() { + // Byte-for-byte the shape the four exam id types wrote before this + // helper existed; a pre-history row is keyed by the bare pair. + assert_eq!(sitting("EXAM", "USER", 1), "EXAM_USER"); + assert_eq!(sitting("EXAM", "USER", 2), "EXAM_USER_2"); + assert_eq!(sitting("Q", "U", 11), "Q_U_11"); + } +} diff --git a/src/domain/meal_attendance.rs b/src/domain/meal_attendance.rs index 623f3c3..75f4bbc 100644 --- a/src/domain/meal_attendance.rs +++ b/src/domain/meal_attendance.rs @@ -20,6 +20,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{MEAL_ATTENDANCE_STATUSES, MEAL_ATTENDANCE_TABLE}; use crate::database::Database; use crate::domain::menu::{MenuDate, MenuId}; +use crate::domain::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -131,17 +132,17 @@ impl MealAttendance { /// The kitchen's list for one menu. pub async fn list_for_menu( menu: &MenuId, + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM meal_attendance WHERE menu = $menu \ - ORDER BY marked_at DESC, id DESC", - ) - .bind(("menu", menu.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + ) -> Result<(Vec, i64), AppError> { + PagedList::new( + "meal_attendance WHERE menu = $menu", + "ORDER BY marked_at DESC, id DESC", + ) + .bind("menu", menu.record()) + .run(limit, offset, db) + .await } /// One student's marks, newest first. `from`/`to` are inclusive @@ -153,21 +154,21 @@ impl MealAttendance { student: &UserId, from: Option<&MenuDate>, to: Option<&MenuDate>, + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM meal_attendance WHERE student = $usr \ - AND ($from = NONE OR menu.date >= $from) \ - AND ($to = NONE OR menu.date <= $to) \ - ORDER BY marked_at DESC, id DESC", - ) - .bind(("usr", student.record())) - .bind(("from", from.map(|date| date.as_str().to_string()))) - .bind(("to", to.map(|date| date.as_str().to_string()))) - .await? - .check()?; - Ok(result.take::>(0)?) + ) -> Result<(Vec, i64), AppError> { + PagedList::new( + "meal_attendance WHERE student = $usr \ + AND ($from = NONE OR menu.date >= $from) \ + AND ($to = NONE OR menu.date <= $to)", + "ORDER BY marked_at DESC, id DESC", + ) + .bind("usr", student.record()) + .bind("from", from.map(|date| date.as_str().to_string())) + .bind("to", to.map(|date| date.as_str().to_string())) + .run(limit, offset, db) + .await } } diff --git a/src/domain/meal_booking.rs b/src/domain/meal_booking.rs index e4feac6..c821d6b 100644 --- a/src/domain/meal_booking.rs +++ b/src/domain/meal_booking.rs @@ -25,6 +25,7 @@ use crate::constant::MEAL_BOOKING_TABLE; use crate::database::Database; use crate::domain::meal_ledger::{LedgerAmount, MealLedger}; use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId, MenuSlot}; +use crate::domain::page::PagedList; use crate::domain::settings::{MealSlotDef, Settings}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -266,16 +267,19 @@ impl MealBooking { } /// Every booking on a menu, cancelled ones included — the kitchen's list. - pub async fn list_for_menu(menu: &MenuId, db: &Database) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM meal_booking WHERE menu = $menu \ - ORDER BY created_at DESC, id DESC", - ) - .bind(("menu", menu.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + pub async fn list_for_menu( + menu: &MenuId, + limit: Option, + offset: i64, + db: &Database, + ) -> Result<(Vec, i64), AppError> { + PagedList::new( + "meal_booking WHERE menu = $menu", + "ORDER BY created_at DESC, id DESC", + ) + .bind("menu", menu.record()) + .run(limit, offset, db) + .await } /// The seats actually held — the capacity count. @@ -318,20 +322,20 @@ impl MealBooking { /// dies with the link. pub async fn list_for_students( students: &[UserId], + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM meal_booking WHERE student IN $students \ - ORDER BY created_at DESC, id DESC", - ) - .bind(( - "students", - students.iter().map(UserId::record).collect::>(), - )) - .await? - .check()?; - Ok(result.take::>(0)?) + ) -> Result<(Vec, i64), AppError> { + PagedList::new( + "meal_booking WHERE student IN $students", + "ORDER BY created_at DESC, id DESC", + ) + .bind( + "students", + students.iter().map(UserId::record).collect::>(), + ) + .run(limit, offset, db) + .await } } diff --git a/src/domain/meal_ledger.rs b/src/domain/meal_ledger.rs index 0bb87ce..1102c09 100644 --- a/src/domain/meal_ledger.rs +++ b/src/domain/meal_ledger.rs @@ -52,6 +52,7 @@ use crate::database::Database; use crate::domain::meal_booking::{MealBooking, MealBookingId}; use crate::domain::menu::MenuId; use crate::domain::menu_dish::MenuDish; +use crate::domain::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -436,17 +437,17 @@ impl MealLedger { /// A student's whole statement, newest first. pub async fn list_for_student( student: &UserId, + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM meal_ledger WHERE student = $student \ - ORDER BY created_at DESC, id DESC", - ) - .bind(("student", student.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + ) -> Result<(Vec, i64), AppError> { + PagedList::new( + "meal_ledger WHERE student = $student", + "ORDER BY created_at DESC, id DESC", + ) + .bind("student", student.record()) + .run(limit, offset, db) + .await } /// The derived balance: `credits + reversals - charges`, in minor units. @@ -454,8 +455,9 @@ impl MealLedger { // ponytail: folds the student's lines in-process (a few hundred a year); // push it into a `math::sum` aggregate if a statement ever gets long. pub async fn balance_of(student: &UserId, db: &Database) -> Result { - Ok(Self::list_for_student(student, db) + Ok(Self::list_for_student(student, None, 0, db) .await? + .0 .iter() .fold(0i64, |sum, line| { sum + line.kind.sign() * line.amount_minor.as_minor() diff --git a/src/domain/menu.rs b/src/domain/menu.rs index 5f209cc..a0be645 100644 --- a/src/domain/menu.rs +++ b/src/domain/menu.rs @@ -20,6 +20,7 @@ use crate::constant::{MAX_MENU_CAPACITY, MENU_TABLE}; use crate::database::Database; use crate::domain::field_update::FieldUpdate; use crate::domain::menu_dish::MenuDish; +use crate::domain::page::PagedList; use crate::domain::settings::MealSlotDef; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -237,19 +238,18 @@ impl Menu { pub async fn list( from: Option<&MenuDate>, to: Option<&MenuDate>, + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM menu \ - WHERE ($from = NONE OR date >= $from) AND ($to = NONE OR date <= $to) \ - ORDER BY date DESC, slot ASC, id DESC", - ) - .bind(("from", from.map(|date| date.as_str().to_string()))) - .bind(("to", to.map(|date| date.as_str().to_string()))) - .await? - .check()?; - Ok(result.take::>(0)?) + ) -> Result<(Vec, i64), AppError> { + PagedList::new( + "menu WHERE ($from = NONE OR date >= $from) AND ($to = NONE OR date <= $to)", + "ORDER BY date DESC, slot ASC, id DESC", + ) + .bind("from", from.map(|date| date.as_str().to_string())) + .bind("to", to.map(|date| date.as_str().to_string())) + .run(limit, offset, db) + .await } /// Only `capacity` is writable: `date` and `slot` are `READONLY` columns, diff --git a/src/domain/message.rs b/src/domain/message.rs index 585b1a7..02a0e1c 100644 --- a/src/domain/message.rs +++ b/src/domain/message.rs @@ -14,6 +14,7 @@ use crate::constant::{ RECIPIENT_FOLDERS, SENDER_FOLDERS, }; use crate::database::Database; +use crate::domain::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -276,8 +277,10 @@ impl Message { user: &UserId, folder: Folder, read: Option, + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { + ) -> Result<(Vec, i64), AppError> { let condition = match folder { Folder::Sent => "sender = $usr AND sender_folder = 'sent'", Folder::Archive => { @@ -295,16 +298,15 @@ impl Message { } else { "" }; - let mut result = db - .query(format!( - "SELECT * FROM message WHERE ({condition}){read_clause} ORDER BY id DESC" - )) - .bind(("usr", user.record())) - .bind(("folder", folder.as_str().to_string())) - .bind(("read", read.unwrap_or_default())) - .await? - .check()?; - Ok(result.take::>(0)?) + PagedList::new( + format!("message WHERE ({condition}){read_clause}"), + "ORDER BY id DESC", + ) + .bind("usr", user.record()) + .bind("folder", folder.as_str().to_string()) + .bind("read", read.unwrap_or_default()) + .run(limit, offset, db) + .await } /// Read a message only if `user` is its sender or recipient and their diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 385095a..90f7485 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -8,6 +8,7 @@ pub mod appointment_slot; pub mod attendance; pub mod bank_question; pub mod bank_question_image; +pub mod cap; pub mod chatbot_message; pub mod chatbot_thread; pub mod course; @@ -25,6 +26,7 @@ pub mod homework; pub mod homework_file; pub mod homework_result; pub mod homework_submission; +pub mod key; pub mod meal_attendance; pub mod meal_booking; pub mod meal_ledger; @@ -34,6 +36,7 @@ pub mod message; pub mod monotonic_id; pub mod note; pub mod note_file; +pub mod page; pub mod parent_link; pub mod pomodoro; pub mod pool_question; diff --git a/src/domain/note.rs b/src/domain/note.rs index cd9f7d0..3aded84 100644 --- a/src/domain/note.rs +++ b/src/domain/note.rs @@ -4,6 +4,7 @@ use ulid::Ulid; use crate::constant::{MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN, NOTE_TABLE}; use crate::database::Database; use crate::domain::field_update::FieldUpdate; +use crate::domain::page::PagedList; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_optional, validate_required}; @@ -107,13 +108,16 @@ impl Note { Ok(note.filter(|note| ¬e.user == owner)) } - pub async fn list_for(owner: &UserId, db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM note WHERE user = $usr ORDER BY id DESC") - .bind(("usr", owner.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + pub async fn list_for( + owner: &UserId, + limit: Option, + offset: i64, + db: &Database, + ) -> Result<(Vec, i64), AppError> { + PagedList::new("note WHERE user = $usr", "ORDER BY id DESC") + .bind("usr", owner.record()) + .run(limit, offset, db) + .await } /// Request-scoped: no lock spans the handler's read and this write, so an diff --git a/src/domain/note_file.rs b/src/domain/note_file.rs index c6fe2f4..6d8fe98 100644 --- a/src/domain/note_file.rs +++ b/src/domain/note_file.rs @@ -6,22 +6,18 @@ //! before blob on delete); this module owns the rows. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use tokio::sync::Mutex; use ulid::Ulid; use crate::constant::{ - MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN, MAX_NOTE_FILES, NOTE_FILE_TABLE, + MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN, MAX_NOTE_FILES, NOTE_FILE_COUNT_FIELD, + NOTE_FILE_TABLE, }; use crate::database::Database; +use crate::domain::cap; use crate::domain::note::NoteId; +use crate::domain::page::PagedList; use crate::error::{AppError, ValidationError}; -/// Serializes the files-per-note cap check against the insert (see -/// [`NoteFile::insert`]). This backend is the database's only -/// writer (single instance) — so one process-wide lock is sufficient. -// ponytail: global lock, per-note locks if uploads ever see real contention. -static FILE_CAP_LOCK: Mutex<()> = Mutex::const_new(()); - #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct NoteFileId(RecordId); @@ -158,21 +154,31 @@ impl NoteFile { } /// Persist the row assembled by [`Self::new`], refusing once its note - /// already holds [`MAX_NOTE_FILES`]. The count-then-create runs under - /// [`FILE_CAP_LOCK`] — a `BEGIN…COMMIT` can't enforce the cap because - /// SurrealDB doesn't conflict-check a cross-record count against a - /// concurrent insert (write-skew), the same story as - /// `Registration::register`. + /// already holds [`MAX_NOTE_FILES`]. The slot is taken by [`cap::claim`] on + /// the note row: a `BEGIN…COMMIT` around a count can't enforce the cap + /// (SurrealDB doesn't conflict-check a cross-record count against a + /// concurrent insert) and a process-wide mutex can't either once the + /// backend runs as two replicas — a conditional single-record write can. pub async fn insert(self, db: &Database) -> Result { - let _guard = FILE_CAP_LOCK.lock().await; - if Self::list_for(&self.note, db).await?.len() >= MAX_NOTE_FILES { + let note = self.note.record(); + if !cap::claim(¬e, NOTE_FILE_COUNT_FIELD, MAX_NOTE_FILES as i64, db).await? { return Err(AppError::Conflict( "the note already holds the maximum of 10 files — delete one first", )); } // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber - let created: Option = db.create(self.id.record()).content(self).await?; - created.ok_or_else(|| AppError::Internal("failed to create note file".into())) + let created: Result, _> = db.create(self.id.record()).content(self).await; + match created { + Ok(Some(created)) => Ok(created), + Ok(None) => { + cap::release(¬e, NOTE_FILE_COUNT_FIELD, db).await?; + Err(AppError::Internal("failed to create note file".into())) + } + Err(err) => { + cap::release(¬e, NOTE_FILE_COUNT_FIELD, db).await?; + Err(err.into()) + } + } } /// Read a file's row only if it belongs to `note` — callers have already @@ -187,18 +193,39 @@ impl NoteFile { } /// All of `note`'s attachment rows, newest first. - pub async fn list_for(note: &NoteId, db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM note_file WHERE note = $note ORDER BY id DESC") - .bind(("note", note.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + pub async fn list_for( + note: &NoteId, + limit: Option, + offset: i64, + db: &Database, + ) -> Result<(Vec, i64), AppError> { + PagedList::new("note_file WHERE note = $note", "ORDER BY id DESC") + .bind("note", note.record()) + .run(limit, offset, db) + .await } + /// Delete the row and give its slot back in the same transaction — the note + /// itself is untouched, so unlike the note-delete cascade this one has a + /// counter to correct. (Deleting a *note* takes its counter with it.) pub async fn delete(self, db: &Database) -> Result { - let deleted: Option = db.delete(self.id.record()).await?; - deleted.ok_or(AppError::NotFound) + let mut result = db + .query( + "BEGIN TRANSACTION; + LET $gone = (DELETE $id RETURN BEFORE); + UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); + RETURN $gone; + COMMIT TRANSACTION;", + ) + .bind(("id", self.id.record())) + .bind(("note", self.note.record())) + .await? + .check()?; + result + .take::>(3)? + .into_iter() + .next() + .ok_or(AppError::NotFound) } } @@ -243,8 +270,21 @@ mod tests { #[tokio::test] async fn rows_scope_to_their_note() { let db = crate::database::init_mem().await.unwrap(); - let note_a = NoteId::generate(); - let note_b = NoteId::generate(); + // Real note rows: the cap counter lives on the note, so an insert whose + // note does not exist has no slot to take (a 409, like a full note). + let owner = crate::domain::user::UserId::generate(); + let note_of = async |title: &str| { + crate::domain::note::Note::create( + &owner, + crate::domain::note::NoteTitle::try_new(title).unwrap(), + crate::domain::note::NoteContent::try_new("body").unwrap(), + &db, + ) + .await + .unwrap() + }; + let note_a = note_of("a").await.get_id().clone(); + let note_b = note_of("b").await.get_id().clone(); let file = NoteFile::new( ¬e_a, FileName::try_new("plan.pdf").unwrap(), @@ -267,10 +307,11 @@ mod tests { .is_none() ); - assert_eq!(NoteFile::list_for(¬e_a, &db).await.unwrap().len(), 1); - assert!(NoteFile::list_for(¬e_b, &db).await.unwrap().is_empty()); + let listed = async |note: &NoteId| NoteFile::list_for(note, None, 0, &db).await.unwrap().0; + assert_eq!(listed(¬e_a).await.len(), 1); + assert!(listed(¬e_b).await.is_empty()); file.delete(&db).await.unwrap(); - assert!(NoteFile::list_for(¬e_a, &db).await.unwrap().is_empty()); + assert!(listed(¬e_a).await.is_empty()); } } diff --git a/src/domain/page.rs b/src/domain/page.rs new file mode 100644 index 0000000..f209f6f --- /dev/null +++ b/src/domain/page.rs @@ -0,0 +1,205 @@ +//! One paged `SELECT` — the window and the `total` that goes with it, both +//! done by the database. +//! +//! WHY: `?limit=10` used to run an unbounded `SELECT *`, hand the whole table +//! to the web layer and slice ten rows off it. The scan (and the decode of +//! every row) grew with the table no matter how small the page was. Here the +//! window is `LIMIT/START` in SQL, and `total` is a `count()` over the *same* +//! `WHERE`, so a page can never disagree with the count that pages it. +//! +//! ```ignore +//! PagedList::new("note WHERE user = $usr", "ORDER BY id DESC") +//! .bind("usr", owner.record()) +//! .run::(limit, offset, db) +//! .await +//! ``` +//! +//! Paging stays opt-in: `limit = None, offset = 0` is the unpaged read, and it +//! emits exactly one statement (no count — the rows in hand *are* the total), +//! so internal callers that just want the list pay nothing. +//! +//! Only for lists the database can express whole. A handler that filters rows +//! in Rust after the read (visibility, audience resolution, a schedule window) +//! must keep slicing in the web layer: a DB `LIMIT` in front of a Rust filter +//! silently returns a short page. + +use surrealdb::types::{SurrealValue, Value}; + +use crate::database::Database; +use crate::error::AppError; + +pub struct PagedList { + /// Everything after `FROM`, e.g. `note WHERE user = $usr`. Shared verbatim + /// by the page and the count. + from_where: String, + /// The full `ORDER BY ...`, applied to the page only. + order: &'static str, + bindings: Vec<(String, Value)>, +} + +impl PagedList { + /// `from_where` is a whole-table read (`"term"`) or a filtered one + /// (`"note WHERE user = $usr"`). + pub fn new(from_where: impl Into, order: &'static str) -> Self { + let from_where = from_where.into(); + Self { + // A *bare* `SELECT VALUE count() FROM t GROUP ALL` comes back as an + // object rather than the projected int ("Expected int, got object") + // — the whole-table read takes a path that drops the `VALUE`. Any + // `WHERE`, even a trivial one, keeps it an int, so an unfiltered + // list gets one. Cheaper than special-casing the take. + from_where: match from_where.contains(" WHERE ") { + true => from_where, + false => format!("{from_where} WHERE true"), + }, + order, + bindings: Vec::new(), + } + } + + /// Bind one variable of the `WHERE`. `limit` and `offset` are the two names + /// a caller must not use. + #[must_use] + pub fn bind(mut self, name: &'static str, value: T) -> Self { + self.bindings.push((name.to_string(), value.into_value())); + self + } + + /// The statements to run, and whether the second one (the count) is among + /// them. Split out so a test can read the SQL: the whole point of this type + /// is that `LIMIT`/`START` reach the database instead of a `Vec` slice. + fn statements(&self, limit: Option, offset: i64) -> (String, bool) { + let from_where = &self.from_where; + let window = match limit { + Some(_) => "LIMIT $limit START $offset", + None => "START $offset", + }; + let mut sql = format!("SELECT * FROM {from_where} {} {window};", self.order); + // A window that can hide rows needs the count; an unpaged read from row + // zero already holds every row, so it stays a single statement. + let counted = limit.is_some() || offset > 0; + if counted { + sql.push_str(&format!( + "SELECT VALUE count() FROM {from_where} GROUP ALL;" + )); + } + (sql, counted) + } + + /// The page plus the full row count. `limit = None` runs from `offset` to + /// the end, matching the unpaged envelope. + pub async fn run( + self, + limit: Option, + offset: i64, + db: &Database, + ) -> Result<(Vec, i64), AppError> { + let (sql, counted) = self.statements(limit, offset); + let mut query = db + .query(sql) + .bind(("offset", offset)) + .bind(("limit", limit.unwrap_or(0))); + for (name, value) in self.bindings { + query = query.bind((name, value)); + } + let mut result = query.await?.check()?; + let rows = result.take::>(0)?; + let total = if counted { + // `GROUP ALL` yields no row at all when nothing matched. + result.take::>(1)?.first().copied().unwrap_or(0) + } else { + rows.len() as i64 + }; + Ok((rows, total)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database; + use crate::domain::note::{Note, NoteContent, NoteTitle}; + use crate::domain::user::UserId; + use ulid::Ulid; + + fn list() -> PagedList { + PagedList::new("note WHERE user = $usr", "ORDER BY id DESC") + } + + /// The window has to be SQL — a `Vec` slice would leave the scan unbounded, + /// which is the whole reason this type exists. + #[test] + fn a_paged_read_windows_and_counts_in_sql() { + let (sql, counted) = list().statements(Some(10), 20); + assert!(sql.contains("ORDER BY id DESC LIMIT $limit START $offset;")); + assert!(sql.contains("SELECT VALUE count() FROM note WHERE user = $usr GROUP ALL;")); + assert!(counted); + } + + /// A whole-table read still gets a `WHERE`, or its count comes back as an + /// object instead of an int. + #[test] + fn an_unfiltered_list_still_counts_as_an_int() { + let (sql, _) = PagedList::new("term", "ORDER BY starts_at DESC").statements(Some(5), 0); + assert!(sql.contains("SELECT VALUE count() FROM term WHERE true GROUP ALL;")); + } + + /// Unpaged from row zero: the rows in hand are the total, so no count runs. + #[test] + fn an_unpaged_read_stays_one_statement() { + let (sql, counted) = list().statements(None, 0); + assert!(sql.ends_with("ORDER BY id DESC START $offset;")); + assert!(!sql.contains("count()")); + assert!(!counted); + // An offset without a limit still hides rows, so it needs the count. + assert!(list().statements(None, 3).1); + } + + #[tokio::test] + async fn the_window_walks_the_rows_and_total_stays_the_whole_list() { + let db = database::init_mem().await.unwrap(); + let user = UserId::from_key(&Ulid::new().to_string()); + for i in 0..5 { + Note::create( + &user, + NoteTitle::try_new(&format!("n{i}")).unwrap(), + NoteContent::try_new("x").unwrap(), + &db, + ) + .await + .unwrap(); + } + + // Every page is `limit` long and `total` ignores the window. + let (page, total) = Note::list_for(&user, Some(2), 0, &db).await.unwrap(); + assert_eq!((page.len(), total), (2, 5)); + let (tail, total) = Note::list_for(&user, Some(2), 4, &db).await.unwrap(); + assert_eq!((tail.len(), total), (1, 5)); + // Offset past the end is an empty page, not an error. + assert_eq!( + Note::list_for(&user, Some(2), 9, &db) + .await + .unwrap() + .0 + .len(), + 0 + ); + // Unpaged, and unpaged-from-an-offset: the count still covers everything. + let (all, total) = Note::list_for(&user, None, 0, &db).await.unwrap(); + assert_eq!((all.len(), total), (5, 5)); + let (rest, total) = Note::list_for(&user, None, 3, &db).await.unwrap(); + assert_eq!((rest.len(), total), (2, 5)); + + // The pages are consecutive slices of the unpaged list — page + // boundaries match the order the ORDER BY already produced. + let keys: Vec<&str> = all.iter().map(|note| note.get_id().key()).collect(); + assert_eq!( + page.iter().map(|n| n.get_id().key()).collect::>(), + keys[..2] + ); + assert_eq!( + tail.iter().map(|n| n.get_id().key()).collect::>(), + keys[4..] + ); + } +} diff --git a/src/domain/pool_question.rs b/src/domain/pool_question.rs index 05c07d2..54fff54 100644 --- a/src/domain/pool_question.rs +++ b/src/domain/pool_question.rs @@ -459,9 +459,10 @@ mod tests { assert_eq!(swept[0].get_id(), offered.get_id()); assert!(PoolQuestion::read(q.get_id(), &db).await.unwrap().is_none()); assert!( - Solution::list_for(q.get_id(), &db) + Solution::list_for(q.get_id(), None, 0, &db) .await .unwrap() + .0 .is_empty() ); diff --git a/src/domain/question_image.rs b/src/domain/question_image.rs index 27659ee..8273684 100644 --- a/src/domain/question_image.rs +++ b/src/domain/question_image.rs @@ -16,7 +16,9 @@ use crate::constant::QUESTION_IMAGE_TABLE; use crate::database::Database; use crate::domain::course::CourseId; use crate::domain::exam::ExamId; +use crate::domain::exam_attempt::ExamAttempt; use crate::domain::exam_question::{ChoiceId, ExamQuestionId}; +use crate::domain::key; use crate::domain::note_file::FileContentType; use crate::error::AppError; @@ -24,20 +26,12 @@ use crate::error::AppError; pub struct QuestionImageId(RecordId); impl QuestionImageId { - /// The one id a (question, slot) pair can have: `{qid}_q` for the - /// question's own image, `{qid}_{choice id}` for one option's picture — - /// uniqueness per slot needs no index this way. Keyed by the option's - /// *stable id*, so reordering the choice list moves no picture. + /// The one id a (question, slot) pair can have — see [`key::slot`] for the + /// key shape and why the two forms can never collide. pub fn for_slot(question: &ExamQuestionId, slot: Option<&ChoiceId>) -> Self { - // `_` is not in Crockford base32 and a ULID is never `"q"`, so - // `{qid}_{cid}` and `{qid}_q` can never collide. - let suffix = match slot { - None => "q", - Some(id) => id.as_str(), - }; Self(RecordId::new( QUESTION_IMAGE_TABLE, - format!("{}_{suffix}", question.key()), + key::slot(question.key(), slot.map(|id| id.as_str())), )) } @@ -110,11 +104,23 @@ impl QuestionImage { } /// Create or replace the slot's image row — the deterministic id makes - /// this the whole "one image per slot" story. + /// this the whole "one image per slot" story. Refused once the exam has an + /// attempt: pictures are part of the question, so they freeze with it, and + /// the gate is in this transaction rather than in a lock the caller held. pub async fn upsert(self, db: &Database) -> Result { // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic - let written: Option = db.upsert(self.id.record()).content(self).await?; - written.ok_or_else(|| AppError::Internal("failed to store question image".into())) + let mut result = db + .query(ExamAttempt::unfrozen("UPSERT $id CONTENT $image;")) + .bind(("freeze_exam", self.exam.record())) + .bind(("id", self.id.record())) + .bind(("image", self)) + .await?; + ExamAttempt::frozen_check(&mut result)?; + result + .take::>(ExamAttempt::FROZEN_SLOT)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to store question image".into())) } pub async fn read_slot( @@ -196,9 +202,20 @@ impl QuestionImage { Ok(result.take::>(0)?) } + /// Refused once the exam has an attempt, in the same transaction — same + /// gate, same reason as [`Self::upsert`]. pub async fn delete(self, db: &Database) -> Result { - let deleted: Option = db.delete(self.id.record()).await?; - deleted.ok_or(AppError::NotFound) + let mut result = db + .query(ExamAttempt::unfrozen("DELETE $id RETURN BEFORE;")) + .bind(("freeze_exam", self.exam.record())) + .bind(("id", self.id.record())) + .await?; + ExamAttempt::frozen_check(&mut result)?; + result + .take::>(ExamAttempt::FROZEN_SLOT)? + .into_iter() + .next() + .ok_or(AppError::NotFound) } } diff --git a/src/domain/registration.rs b/src/domain/registration.rs index f2c819d..045146f 100644 --- a/src/domain/registration.rs +++ b/src/domain/registration.rs @@ -1,21 +1,12 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use tokio::sync::Mutex; -use crate::constant::REGISTRATION_TABLE; -use crate::database::Database; +use crate::constant::{REGISTRATION_COUNT_FIELD, REGISTRATION_TABLE}; +use crate::database::{Database, lost_the_race}; +use crate::domain::cap; use crate::domain::event::{Event, EventId}; use crate::domain::user::UserId; use crate::error::AppError; -/// Serializes seat-taking. A `BEGIN…COMMIT` around the count can't do this: -/// SurrealDB transactions don't conflict-check a cross-record `count()` -/// against a concurrent insert (write-skew), so two racing registrations both -/// saw a free seat and a full event over-admitted. This backend is the database's only -/// writer (single instance) — so one process-wide lock is sufficient. -// ponytail: global lock, per-event locks (or DB-side serialization) if -// registration ever sees real contention. -static REGISTER_LOCK: Mutex<()> = Mutex::const_new(()); - #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct RegistrationId(RecordId); @@ -75,17 +66,16 @@ impl Registration { /// Register (idempotently) `user` onto `event`, refusing when a capacity /// cap is set and every seat is taken. Someone already listed gets their /// existing row back untouched — a true no-op that never counts against - /// the cap and never rewrites who placed them. The whole check-then-write - /// runs under [`REGISTER_LOCK`], and the gate + cap are re-derived from a - /// fresh event read under that lock, so neither a racing registration nor - /// a concurrent capacity/audience/schedule PATCH can over-admit. + /// the cap and never rewrites who placed them. The seat is taken by + /// [`cap::claim`] on the event row — an atomic single-record conditional + /// write, so neither a racing registration in another replica nor a + /// concurrent capacity/audience/schedule PATCH can over-admit. pub async fn register( event: &EventId, user: &UserId, registered_by: &UserId, db: &Database, ) -> Result { - let _guard = REGISTER_LOCK.lock().await; if let Some(existing) = Self::read_for_user(event, user, db).await? { return Ok(existing); } @@ -93,8 +83,14 @@ impl Registration { .await? .ok_or(AppError::NotFound)? .registration_capacity()?; - if let Some(capacity) = capacity - && Self::list_for_event(event, db).await?.len() as i64 >= capacity + let seats = event.record(); + if !cap::claim( + &seats, + REGISTRATION_COUNT_FIELD, + capacity.unwrap_or(cap::UNLIMITED), + db, + ) + .await? { return Err(AppError::Conflict("the event is full")); } @@ -104,11 +100,29 @@ impl Registration { user: user.clone(), registered_by: registered_by.clone(), }; - let created: Option = db + let created: Result, _> = db .create(registration.id.record()) .content(registration) - .await?; - created.ok_or_else(|| AppError::Internal("failed to register user".into())) + .await; + match created { + Ok(Some(created)) => Ok(created), + Ok(None) => { + cap::release(&seats, REGISTRATION_COUNT_FIELD, db).await?; + Err(AppError::Internal("failed to register user".into())) + } + // A concurrent placement of the same pair got there first: give the + // seat back and hand its row over, the same no-op the early return + // above would have made. + Err(err) => { + cap::release(&seats, REGISTRATION_COUNT_FIELD, db).await?; + if !lost_the_race(&err) { + return Err(err.into()); + } + Self::read_for_user(event, user, db) + .await? + .ok_or_else(|| AppError::Internal("failed to register user".into())) + } + } } /// Some(_) iff `user` holds a seat on `event` — the audience point check. @@ -143,12 +157,19 @@ impl Registration { user: &UserId, db: &Database, ) -> Result, AppError> { + // The seat comes back in the same transaction as the row that held it. let mut result = db - .query("DELETE registration WHERE event = $ev AND user = $usr RETURN BEFORE") + .query( + "BEGIN TRANSACTION; + LET $gone = (DELETE registration WHERE event = $ev AND user = $usr RETURN BEFORE); + UPDATE $ev SET registration_count = math::max([(registration_count ?? 0) - array::len($gone), 0]); + RETURN $gone; + COMMIT TRANSACTION;", + ) .bind(("ev", event.record())) .bind(("usr", user.record())) .await? .check()?; - Ok(result.take::>(0)?.into_iter().next()) + Ok(result.take::>(3)?.into_iter().next()) } } diff --git a/src/domain/session_attendance.rs b/src/domain/session_attendance.rs index f531fd7..f6452bb 100644 --- a/src/domain/session_attendance.rs +++ b/src/domain/session_attendance.rs @@ -5,6 +5,7 @@ use crate::database::Database; use crate::domain::attendance::AttendanceStatus; use crate::domain::course::CourseId; use crate::domain::course_session::{CourseSession, CourseSessionId}; +use crate::domain::page::PagedList; use crate::domain::user::UserId; use crate::error::AppError; @@ -100,14 +101,14 @@ impl SessionAttendance { pub async fn list_for_session( session: &CourseSessionId, + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM session_attendance WHERE session = $s ORDER BY id DESC") - .bind(("s", session.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + ) -> Result<(Vec, i64), AppError> { + PagedList::new("session_attendance WHERE session = $s", "ORDER BY id DESC") + .bind("s", session.record()) + .run(limit, offset, db) + .await } /// Every roll-call row ever recorded for `user` — the session half of the diff --git a/src/domain/solution.rs b/src/domain/solution.rs index 03a9286..4cfabf0 100644 --- a/src/domain/solution.rs +++ b/src/domain/solution.rs @@ -15,6 +15,7 @@ use ulid::Ulid; use crate::constant::{MAX_SOLUTION_BODY_LEN, SOLUTION_TABLE}; use crate::database::Database; use crate::domain::note_file::FileContentType; +use crate::domain::page::PagedList; use crate::domain::pool_question::PoolQuestionId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -149,14 +150,17 @@ impl Solution { /// are random within a millisecond, so same-ms order is arbitrary). pub async fn list_for( question: &PoolQuestionId, + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM solution WHERE question = $q ORDER BY offered_at ASC, id ASC") - .bind(("q", question.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + ) -> Result<(Vec, i64), AppError> { + PagedList::new( + "solution WHERE question = $q", + "ORDER BY offered_at ASC, id ASC", + ) + .bind("q", question.record()) + .run(limit, offset, db) + .await } /// Per-question solution tallies for a page of questions, in one grouped @@ -273,14 +277,15 @@ mod tests { second.offered_at = Timestamp::from_millis(2); let second = second.insert(&db).await.unwrap(); - let listed = Solution::list_for(&question_a, &db).await.unwrap(); + let (listed, _) = Solution::list_for(&question_a, None, 0, &db).await.unwrap(); assert_eq!(listed.len(), 2); assert_eq!(listed[0].get_id(), first.get_id()); assert_eq!(listed[1].get_id(), second.get_id()); assert!( - Solution::list_for(&question_b, &db) + Solution::list_for(&question_b, None, 0, &db) .await .unwrap() + .0 .is_empty() ); @@ -299,7 +304,14 @@ mod tests { ); first.delete(&db).await.unwrap(); - assert_eq!(Solution::list_for(&question_a, &db).await.unwrap().len(), 1); + assert_eq!( + Solution::list_for(&question_a, None, 0, &db) + .await + .unwrap() + .0 + .len(), + 1 + ); } #[tokio::test] diff --git a/src/domain/subject.rs b/src/domain/subject.rs index a0ef2e6..35beb02 100644 --- a/src/domain/subject.rs +++ b/src/domain/subject.rs @@ -5,6 +5,7 @@ use crate::database::Database; use crate::domain::course::CourseId; use crate::domain::field_update::FieldUpdate; use crate::domain::monotonic_id::next_ulid; +use crate::domain::page::PagedList; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_optional, validate_required}; @@ -131,14 +132,14 @@ impl Subject { /// The course's subjects in curriculum order (ULID ids sort by creation). pub async fn list_for_course( course: &CourseId, + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM subject WHERE course = $course ORDER BY id ASC") - .bind(("course", course.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + ) -> Result<(Vec, i64), AppError> { + PagedList::new("subject WHERE course = $course", "ORDER BY id ASC") + .bind("course", course.record()) + .run(limit, offset, db) + .await } /// Request-scoped: no lock spans the handler's read and this write, so an diff --git a/src/domain/term.rs b/src/domain/term.rs index b87df16..33322a7 100644 --- a/src/domain/term.rs +++ b/src/domain/term.rs @@ -13,7 +13,8 @@ use ulid::Ulid; use crate::constant::{MAX_TERM_NAME_LEN, TERM_TABLE}; use crate::database::Database; use crate::domain::field_update::FieldUpdate; -use crate::domain::timestamp::Timestamp; +use crate::domain::page::PagedList; +use crate::domain::timestamp::{Timestamp, range_error}; use crate::error::{AppError, ValidationError}; use crate::validate::validate_required; @@ -22,12 +23,12 @@ use crate::validate::validate_required; /// is already on its way out. Course writes take it only when they actually /// link a term. /// -/// A PATCH that moves either end of the range takes it too: `starts_at <= -/// ends_at` is a cross-field check, so a partial PATCH validates the value it -/// carries against the *stored* other end — two such PATCHes, each fine on its -/// own, would otherwise commit an inverted range between them. Holding this -/// across read-check-write serializes them; name-only PATCHes check nothing -/// cross-field and stay lock-free. +/// Two leases remain, both cross-record and both replica-*local*: the delete +/// guard in `web::terms::delete_term`, and the term lookup in +/// `web::courses`' create/update. The range check a PATCH makes is no longer +/// one of them — it is a `WHERE` on the update itself +/// ([`crate::domain::field_update::FieldUpdate::ordered`]), which holds across +/// replicas as this mutex never did. /// /// Lock order: no path ever holds this and `ENROLL_LOCK` at the same time — the /// course writes that take this one touch no roster, and the course delete that @@ -121,12 +122,14 @@ impl Term { } /// Every term, newest first — the school calendar is small by nature. - pub async fn list_all(db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM term ORDER BY starts_at DESC") - .await? - .check()?; - Ok(result.take::>(0)?) + pub async fn list_all( + limit: Option, + offset: i64, + db: &Database, + ) -> Result<(Vec, i64), AppError> { + PagedList::new("term", "ORDER BY starts_at DESC") + .run(limit, offset, db) + .await } /// Write only the fields the PATCH carried — `None` means the request @@ -144,6 +147,7 @@ impl Term { .set("name", name) .set("starts_at", starts_at) .set("ends_at", ends_at) + .ordered("starts_at", "ends_at", range_error()) .run::(db) .await } @@ -171,6 +175,36 @@ impl Term { mod tests { use super::*; + /// The bite test for the `WHERE` guard that replaced `TERM_LOCK` on the + /// PATCH path: the handler's pre-flight check is not in play here, so only + /// the guard can refuse a moved end that inverts the range — and it must + /// refuse it with the same error, having written nothing. + #[tokio::test] + async fn a_moved_end_is_refused_against_the_stored_other_end() { + let db = crate::database::init_mem().await.unwrap(); + let at = Timestamp::from_millis; + let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db) + .await + .unwrap(); + + let refused = term + .clone() + .update(None, None, Some(at(50)), &db) + .await + .expect_err("an end before the stored start must be refused"); + assert!(refused.to_string().contains("at or after starts_at")); + let stored = Term::read(term.get_id(), &db).await.unwrap().unwrap(); + assert_eq!( + stored.get_ends_at(), + at(200), + "nothing may have been written" + ); + + // A move that keeps the range ordered still lands, guard and all. + let moved = term.update(None, None, Some(at(300)), &db).await.unwrap(); + assert_eq!(moved.get_ends_at(), at(300)); + } + #[tokio::test] async fn name_is_required_and_bounded() { assert!(TermName::try_new("2026 Fall").is_ok()); diff --git a/src/domain/timestamp.rs b/src/domain/timestamp.rs index 336ef44..62672be 100644 --- a/src/domain/timestamp.rs +++ b/src/domain/timestamp.rs @@ -14,6 +14,17 @@ use surrealdb::types::SurrealValue; use crate::constant::MILLIS_PER_DAY; +use crate::error::{AppError, ValidationError}; + +/// The one spelling of "this range is inverted", so the pre-flight check +/// ([`crate::web::check_time_range`]) and the write-time `WHERE` guard that +/// re-makes it against the stored row answer a client identically. +pub(crate) fn range_error() -> AppError { + AppError::Validation(ValidationError::Invalid { + field: "ends_at", + reason: "must be at or after starts_at", + }) +} /// A unix-millisecond instant (UTC by construction). Stored as an `int`. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, SurrealValue)] diff --git a/src/domain/user.rs b/src/domain/user.rs index 25d131d..6014a9b 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -8,6 +8,7 @@ use ulid::Ulid; use crate::constant::{DECOY_PASSWORD, USER_TABLE}; use crate::database::Database; use crate::domain::field_update::FieldUpdate; +use crate::domain::page::PagedList; use crate::domain::preferences::{Language, Theme}; use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; use crate::domain::role::Role; @@ -355,12 +356,14 @@ impl User { Ok(db.select(id.record()).await?) } - pub async fn list_all(db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM user ORDER BY id DESC") - .await? - .check()?; - Ok(result.take::>(0)?) + pub async fn list_all( + limit: Option, + offset: i64, + db: &Database, + ) -> Result<(Vec, i64), AppError> { + PagedList::new("user", "ORDER BY id DESC") + .run(limit, offset, db) + .await } /// Fetch the users behind `ids` in one query. Ids with no row are simply @@ -402,8 +405,10 @@ impl User { pub async fn search( query: &str, role: Option, + limit: Option, + offset: i64, db: &Database, - ) -> Result, AppError> { + ) -> Result<(Vec, i64), AppError> { let needle = search_fold(query.trim()); let text_clause = format!( "({} CONTAINS $q OR {} CONTAINS $q OR {} CONTAINS $q)", @@ -423,16 +428,12 @@ impl User { } else { clauses.join(" AND ") }; - let mut query = db - .query(format!( - "SELECT * FROM user WHERE {where_clause} ORDER BY username" - )) - .bind(("q", needle)); + let mut list = PagedList::new(format!("user WHERE {where_clause}"), "ORDER BY username") + .bind("q", needle); if let Some(role) = role { - query = query.bind(("role", role)); + list = list.bind("role", role); } - let mut result = query.await?.check()?; - Ok(result.take::>(0)?) + list.run(limit, offset, db).await } /// Overwrite this user's role. The caller is responsible for authorizing it. diff --git a/src/domain/work_entry.rs b/src/domain/work_entry.rs index 9561e6b..ebcecb4 100644 --- a/src/domain/work_entry.rs +++ b/src/domain/work_entry.rs @@ -1,27 +1,23 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use tokio::sync::Mutex; use ulid::Ulid; use crate::constant::WORK_ENTRY_TABLE; use crate::database::Database; use crate::domain::field_update::FieldUpdate; +use crate::domain::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::AppError; - -/// Serializes a stint correction's ordering check against the write it guards, -/// exactly as `TERM_LOCK` does for terms: `check_in <= check_out` is a -/// cross-field check, so a correction of one instant validates against the -/// *stored* other one — two such corrections, each fine on its own snapshot, -/// would otherwise commit an inverted stint between them. Check-in/check-out -/// themselves stay lock-free (they are atomic single-row writes), and a PATCH -/// carrying neither instant checks nothing cross-field. -/// -/// Lock order: this is a leaf — the only path that takes it (`PATCH -/// /work/entries/{id}`) takes no other lock, and no path holding another lock -/// takes this one, so it cannot sit in a cycle. Should a future path need -/// both, take the other lock first and this one innermost. -pub(crate) static WORK_ENTRY_LOCK: Mutex<()> = Mutex::const_new(()); +use crate::error::{AppError, ValidationError}; + +/// The one spelling of "this stint is inverted", shared by the handler's +/// pre-flight check and the write-time `WHERE` guard that re-makes it against +/// the stored row. +pub(crate) fn out_before_in_error() -> AppError { + AppError::Validation(ValidationError::Invalid { + field: "check_out", + reason: "must be at or after check_in", + }) +} #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct WorkEntryId(RecordId); @@ -163,13 +159,16 @@ impl WorkEntry { /// Every stint of `user`, newest first — the open one (if any) included. /// Ordered by `check_in`: the open entry's `open_` key doesn't sort with /// the ULIDs, so id order would misplace it. - pub async fn list_for_user(user: &UserId, db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM work_entry WHERE user = $usr ORDER BY check_in DESC") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + pub async fn list_for_user( + user: &UserId, + limit: Option, + offset: i64, + db: &Database, + ) -> Result<(Vec, i64), AppError> { + PagedList::new("work_entry WHERE user = $usr", "ORDER BY check_in DESC") + .bind("usr", user.record()) + .run(limit, offset, db) + .await } /// Persist corrected instants (manager fix-ups on closed entries; the web @@ -188,6 +187,10 @@ impl WorkEntry { FieldUpdate::new(self.id.record()) .set("check_in", check_in) .set("check_out", check_out) + // Same race closer as the schedule ranges, with this table's own + // field names and message: a correction of one instant is only + // written while it still orders against the other as *stored*. + .ordered("check_in", "check_out", out_before_in_error()) .run::(db) .await } @@ -216,7 +219,7 @@ mod tests { // Second check-in must not create a second stint or reset the clock. let dup = WorkEntry::check_in(&user, &db).await; assert!(matches!(dup, Err(AppError::Conflict(_)))); - let entries = WorkEntry::list_for_user(&user, &db).await.unwrap(); + let (entries, _) = WorkEntry::list_for_user(&user, None, 0, &db).await.unwrap(); assert_eq!(entries.len(), 1); assert_eq!(entries[0].get_check_in(), open.get_check_in()); @@ -230,7 +233,7 @@ mod tests { Err(AppError::Conflict(_)) )); WorkEntry::check_in(&user, &db).await.unwrap(); - let entries = WorkEntry::list_for_user(&user, &db).await.unwrap(); + let (entries, _) = WorkEntry::list_for_user(&user, None, 0, &db).await.unwrap(); assert_eq!(entries.len(), 2); } } diff --git a/src/lib.rs b/src/lib.rs index e09d18c..3fc2274 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,6 +4,7 @@ pub mod constant; pub mod database; pub mod domain; pub mod error; +pub mod migration_sql; pub mod rate_limit; pub mod state; pub mod validate; @@ -103,7 +104,7 @@ pub fn build_router(state: AppState) -> Router { .routes(routes!(server_time)) .merge(web::limits::routes()) .nest("/ai", web::ai::routes()) - .nest("/auth", web::auth::routes(&state.rate_limit)) + .nest("/auth", web::auth::routes(&state)) .nest("/chatbot", web::chatbot::routes()) .nest("/users", web::users::routes()) .nest("/notes", web::notes::routes()) @@ -133,6 +134,13 @@ pub fn build_router(state: AppState) -> Router { state.rate_limit.api_per_minute, state.rate_limit.trust_proxy, ); + // Every tier's budget is fleet-wide, not per process (see + // [`rate_limit::RateLimiter::share`]). The chatbot tier is shared here too + // rather than in `main`, so it holds in every process that serves it. + api_limiter.share("api", state.db.clone(), state.db_up.clone()); + state + .chatbot_limit + .share("chatbot", state.db.clone(), state.db_up.clone()); let db_up = state.db_up.clone(); diff --git a/src/migration_sql.rs b/src/migration_sql.rs new file mode 100644 index 0000000..c12070d --- /dev/null +++ b/src/migration_sql.rs @@ -0,0 +1,787 @@ +//! The boot migration, as SurrealQL text. +//! +//! Split out of [`crate::constant`] purely for size: these three batches are +//! ~700 lines of schema, and left in the constants file they buried the +//! validation bounds that file exists to hold. Nothing else changed — they are +//! still `pub const`, still the only migration text, and +//! [`crate::database::migrate`] and [`crate::database::migration_fingerprint`] +//! still both read [`MIGRATION_BATCHES`] and nothing else. +//! +//! Numbers stay in `constant.rs`: `tests/limits_completeness.rs` sweeps `src/` +//! for stray bounds, and a bound hidden here would reach neither `GET /limits` +//! nor the OpenAPI spec. Only SurrealQL strings live in this file. + +/// Repairs that must run *before* the DDL batch, because the DDL is what makes +/// them impossible. +/// +/// `MIGRATION` retires `exam_question.source_bank` with `REMOVE FIELD`, and +/// once the column is gone SCHEMAFULL rejects every write to a row that still +/// stores it ("Found field 'source_bank', but no such field exists") — an +/// UNSET included. So the value has to go while its definition is still +/// standing. Runs as its own query for the usual reason (see `MIGRATION`). +/// +/// The table-exists guard is load-bearing: on a fresh database `MIGRATION` has +/// not run yet, and an UPDATE against an undefined table is an error, not an +/// empty result. On a database that has the table but never had the column the +/// `WHERE` simply matches nothing. +pub const PRE_REPAIR: &str = " + IF 'exam_question' IN object::keys((INFO FOR DB).tables) { + UPDATE exam_question UNSET source_bank WHERE source_bank != NONE + }; +"; + +/// SCHEMAFULL schema: every column is typed, references use `record<..>`. +/// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the +/// definitions and `REMOVE ... IF EXISTS` retires schema (like the +/// single-attempt unique index) exactly once. DDL only — data backfills live +/// in `BACKFILL`, which runs as a *separate* query: statements inside one +/// batch see the schema as it stood when the batch started, so an UPDATE next +/// to a fresh `DEFINE FIELD audience.*` writes against the old field set and +/// SCHEMAFULL silently strips the very keys being backfilled. +pub const MIGRATION: &str = " + DEFINE TABLE IF NOT EXISTS user SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS username ON user TYPE string; + DEFINE FIELD IF NOT EXISTS password_hash ON user TYPE string; + DEFINE FIELD IF NOT EXISTS role ON user TYPE string DEFAULT 'student'; + DEFINE FIELD IF NOT EXISTS name ON user TYPE option; + DEFINE FIELD IF NOT EXISTS surname ON user TYPE option; + DEFINE FIELD IF NOT EXISTS email ON user TYPE option; + DEFINE FIELD IF NOT EXISTS phone ON user TYPE option; + DEFINE FIELD IF NOT EXISTS birth_date ON user TYPE option; + DEFINE FIELD IF NOT EXISTS theme ON user TYPE option; + DEFINE FIELD IF NOT EXISTS language ON user TYPE option; + DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option; + DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; + + DEFINE TABLE IF NOT EXISTS session SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS user ON session TYPE record; + DEFINE FIELD IF NOT EXISTS token ON session TYPE string; + DEFINE FIELD IF NOT EXISTS expires_at ON session TYPE int; + DEFINE INDEX IF NOT EXISTS session_token ON session FIELDS token UNIQUE; + DEFINE INDEX IF NOT EXISTS session_expires ON session FIELDS expires_at; + + DEFINE TABLE IF NOT EXISTS note SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS user ON note TYPE record; + DEFINE FIELD IF NOT EXISTS title ON note TYPE string; + DEFINE FIELD IF NOT EXISTS content ON note TYPE string; + DEFINE FIELD IF NOT EXISTS file_count ON note TYPE option; + DEFINE INDEX IF NOT EXISTS note_user ON note FIELDS user; + + DEFINE TABLE IF NOT EXISTS message SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS sender ON message TYPE record; + DEFINE FIELD IF NOT EXISTS recipient ON message TYPE record; + DEFINE FIELD IF NOT EXISTS subject ON message TYPE string; + DEFINE FIELD IF NOT EXISTS body ON message TYPE string; + DEFINE FIELD IF NOT EXISTS label ON message TYPE option; + DEFINE FIELD IF NOT EXISTS sent_at ON message TYPE int; + DEFINE FIELD IF NOT EXISTS read ON message TYPE bool DEFAULT false; + DEFINE FIELD IF NOT EXISTS sender_folder ON message TYPE string DEFAULT 'sent'; + DEFINE FIELD IF NOT EXISTS recipient_folder ON message TYPE string DEFAULT 'inbox'; + -- Where each side's copy sat before it was filed into archive/trash, so a + -- restore lands where it came from. NONE while the copy is in its home + -- folder — and on rows filed before this field existed (2026-07-23), which + -- restore to the home folder just as they always did. + DEFINE FIELD IF NOT EXISTS sender_origin ON message TYPE option; + DEFINE FIELD IF NOT EXISTS recipient_origin ON message TYPE option; + DEFINE INDEX IF NOT EXISTS message_sender ON message FIELDS sender; + DEFINE INDEX IF NOT EXISTS message_recipient ON message FIELDS recipient; + + DEFINE TABLE IF NOT EXISTS note_file SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS note ON note_file TYPE record; + DEFINE FIELD IF NOT EXISTS name ON note_file TYPE string; + DEFINE FIELD IF NOT EXISTS content_type ON note_file TYPE string; + DEFINE FIELD IF NOT EXISTS size ON note_file TYPE int; + DEFINE INDEX IF NOT EXISTS note_file_note ON note_file FIELDS note; + + -- Chatbot relay (2026-07-23): a `thread` groups the turns, one + -- `chatbot_message` is one turn. `user_id` rides on the message too so an + -- ownership check needs no join. An assistant turn is born `pending` and + -- is completed (or failed) by the task holding the AI-bridge stream — + -- hence the BACKFILL sweep, since that task dies with the process. + DEFINE TABLE IF NOT EXISTS chatbot_thread SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS user_id ON chatbot_thread TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS title ON chatbot_thread TYPE option; + DEFINE FIELD IF NOT EXISTS created_at ON chatbot_thread TYPE int READONLY; + DEFINE FIELD IF NOT EXISTS updated_at ON chatbot_thread TYPE int; + DEFINE INDEX IF NOT EXISTS chatbot_thread_user_updated ON chatbot_thread FIELDS user_id, updated_at; + + DEFINE TABLE IF NOT EXISTS chatbot_message SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS thread_id ON chatbot_message TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS user_id ON chatbot_message TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS role ON chatbot_message TYPE string READONLY; + DEFINE FIELD IF NOT EXISTS content ON chatbot_message TYPE string; + DEFINE FIELD IF NOT EXISTS status ON chatbot_message TYPE string; + DEFINE FIELD IF NOT EXISTS truncated ON chatbot_message TYPE bool DEFAULT false; + DEFINE FIELD IF NOT EXISTS error_code ON chatbot_message TYPE option; + DEFINE FIELD IF NOT EXISTS created_at ON chatbot_message TYPE int READONLY; + DEFINE FIELD IF NOT EXISTS completed_at ON chatbot_message TYPE option; + -- The claim (2026-07-27): which replica's claim loop owes this turn an + -- answer, and when it said so. Absent = nobody has taken it yet; a claim + -- older than CHATBOT_CLAIM_RECLAIM_SECS is a dead claimer and the turn is + -- taken back (see `CHATBOT_CLAIM`). + DEFINE FIELD IF NOT EXISTS claimed_by ON chatbot_message TYPE option; + DEFINE FIELD IF NOT EXISTS claimed_at ON chatbot_message TYPE option; + DEFINE INDEX IF NOT EXISTS chatbot_message_thread_created ON chatbot_message FIELDS thread_id, created_at; + DEFINE INDEX IF NOT EXISTS chatbot_message_user ON chatbot_message FIELDS user_id; + -- The claim loop's sweep: every poll asks for pending rows by age. + DEFINE INDEX IF NOT EXISTS chatbot_message_status_created ON chatbot_message FIELDS status, created_at; + + -- Which AI workers are connected to *any* replica (2026-07-27). The GATE + -- and nothing else: a row only says a socket existed somewhere at + -- `seen_at`, so it may spare a user a 503 but must never pick who answers + -- — that is the in-process registry's call. Heartbeated by the replica + -- owning the connection; a stale row is ignored by the read and swept. + DEFINE TABLE IF NOT EXISTS ai_worker SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS service ON ai_worker TYPE string; + DEFINE FIELD IF NOT EXISTS capabilities ON ai_worker TYPE array; + DEFINE FIELD IF NOT EXISTS seen_at ON ai_worker TYPE int; + + -- How much of a rate-limit budget the whole fleet has spent in one wall + -- window (2026-07-27). One row per tier+client+window, id-keyed so every + -- replica lands on the same record; `hits` is the cross-replica total each + -- replica folds its local admits into (see `crate::rate_limit`). Rows are + -- swept by the same task once their window is past. + DEFINE TABLE IF NOT EXISTS rate_limit SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS hits ON rate_limit TYPE int DEFAULT 0; + DEFINE FIELD IF NOT EXISTS window_start ON rate_limit TYPE int; + + DEFINE TABLE IF NOT EXISTS event SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS creator ON event TYPE record; + DEFINE FIELD IF NOT EXISTS title ON event TYPE string; + DEFINE FIELD IF NOT EXISTS description ON event TYPE string; + DEFINE FIELD IF NOT EXISTS audience ON event TYPE object; + DEFINE FIELD IF NOT EXISTS audience.kind ON event TYPE string; + DEFINE FIELD IF NOT EXISTS audience.role ON event TYPE option; + DEFINE FIELD IF NOT EXISTS audience.course ON event TYPE option>; + DEFINE FIELD IF NOT EXISTS audience.capacity ON event TYPE option; + -- Seats taken on the signup list, the cross-replica capacity guard (see + -- `crate::domain::cap`). Absent reads as zero, so no Rust struct needs it. + DEFINE FIELD IF NOT EXISTS registration_count ON event TYPE option; + REMOVE FIELD IF EXISTS audience.users ON TABLE event; + DEFINE FIELD IF NOT EXISTS starts_at ON event TYPE option; + DEFINE FIELD IF NOT EXISTS ends_at ON event TYPE option; + + DEFINE TABLE IF NOT EXISTS attendance SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS event ON attendance TYPE record; + DEFINE FIELD IF NOT EXISTS user ON attendance TYPE record; + DEFINE FIELD IF NOT EXISTS status ON attendance TYPE string; + DEFINE FIELD IF NOT EXISTS marked_by ON attendance TYPE record; + DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE; + DEFINE INDEX IF NOT EXISTS attendance_user ON attendance FIELDS user; + + DEFINE TABLE IF NOT EXISTS registration SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS event ON registration TYPE record; + DEFINE FIELD IF NOT EXISTS user ON registration TYPE record; + DEFINE FIELD IF NOT EXISTS registered_by ON registration TYPE record; + DEFINE INDEX IF NOT EXISTS registration_event_user ON registration FIELDS event, user UNIQUE; + DEFINE INDEX IF NOT EXISTS registration_event ON registration FIELDS event; + + DEFINE TABLE IF NOT EXISTS term SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS name ON term TYPE string; + DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int; + DEFINE FIELD IF NOT EXISTS ends_at ON term TYPE int; + + DEFINE TABLE IF NOT EXISTS course SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS creator ON course TYPE record; + DEFINE FIELD IF NOT EXISTS teachers ON course TYPE array> DEFAULT []; + DEFINE FIELD IF NOT EXISTS teachers[*] ON course TYPE record; + DEFINE FIELD IF NOT EXISTS title ON course TYPE string; + DEFINE FIELD IF NOT EXISTS description ON course TYPE string; + DEFINE FIELD IF NOT EXISTS kind ON course TYPE string DEFAULT 'course'; + DEFINE FIELD IF NOT EXISTS term ON course TYPE option>; + DEFINE FIELD IF NOT EXISTS capacity ON course TYPE option; + DEFINE FIELD IF NOT EXISTS enrollment_count ON course TYPE option; + + DEFINE TABLE IF NOT EXISTS subject SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS course ON subject TYPE record; + DEFINE FIELD IF NOT EXISTS name ON subject TYPE string; + DEFINE FIELD IF NOT EXISTS description ON subject TYPE string; + DEFINE INDEX IF NOT EXISTS subject_course ON subject FIELDS course; + + DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS course ON enrollment TYPE record; + DEFINE FIELD IF NOT EXISTS user ON enrollment TYPE record; + DEFINE FIELD IF NOT EXISTS enrolled_by ON enrollment TYPE record; + DEFINE INDEX IF NOT EXISTS enrollment_course_user ON enrollment FIELDS course, user UNIQUE; + DEFINE INDEX IF NOT EXISTS enrollment_user ON enrollment FIELDS user; + + DEFINE TABLE IF NOT EXISTS parent_link SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS parent ON parent_link TYPE record; + DEFINE FIELD IF NOT EXISTS student ON parent_link TYPE record; + DEFINE FIELD IF NOT EXISTS linked_by ON parent_link TYPE record; + DEFINE INDEX IF NOT EXISTS parent_link_parent_student ON parent_link FIELDS parent, student UNIQUE; + DEFINE INDEX IF NOT EXISTS parent_link_parent ON parent_link FIELDS parent; + DEFINE INDEX IF NOT EXISTS parent_link_student ON parent_link FIELDS student; + + DEFINE TABLE IF NOT EXISTS course_session SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS course ON course_session TYPE record; + DEFINE FIELD IF NOT EXISTS teacher ON course_session TYPE record; + DEFINE FIELD IF NOT EXISTS topic ON course_session TYPE string; + DEFINE FIELD IF NOT EXISTS starts_at ON course_session TYPE int; + DEFINE FIELD IF NOT EXISTS ends_at ON course_session TYPE option; + DEFINE INDEX IF NOT EXISTS course_session_course ON course_session FIELDS course; + + DEFINE TABLE IF NOT EXISTS session_attendance SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS session ON session_attendance TYPE record; + DEFINE FIELD IF NOT EXISTS course ON session_attendance TYPE record; + DEFINE FIELD IF NOT EXISTS user ON session_attendance TYPE record; + DEFINE FIELD IF NOT EXISTS status ON session_attendance TYPE string; + DEFINE FIELD IF NOT EXISTS marked_by ON session_attendance TYPE record; + DEFINE INDEX IF NOT EXISTS session_attendance_session_user ON session_attendance FIELDS session, user UNIQUE; + DEFINE INDEX IF NOT EXISTS session_attendance_session ON session_attendance FIELDS session; + DEFINE INDEX IF NOT EXISTS session_attendance_user ON session_attendance FIELDS user; + DEFINE INDEX IF NOT EXISTS session_attendance_course ON session_attendance FIELDS course; + + DEFINE TABLE IF NOT EXISTS work_entry SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS user ON work_entry TYPE record; + DEFINE FIELD IF NOT EXISTS check_in ON work_entry TYPE int; + DEFINE FIELD IF NOT EXISTS check_out ON work_entry TYPE option; + DEFINE INDEX IF NOT EXISTS work_entry_user ON work_entry FIELDS user; + + DEFINE TABLE IF NOT EXISTS pomodoro_session SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS user ON pomodoro_session TYPE record; + DEFINE FIELD IF NOT EXISTS started_at ON pomodoro_session TYPE int; + DEFINE FIELD IF NOT EXISTS finished_at ON pomodoro_session TYPE option; + DEFINE INDEX IF NOT EXISTS pomodoro_session_user ON pomodoro_session FIELDS user; + + DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS creator ON exam TYPE record; + DEFINE FIELD IF NOT EXISTS course ON exam TYPE record; + DEFINE FIELD IF NOT EXISTS title ON exam TYPE string; + DEFINE FIELD IF NOT EXISTS description ON exam TYPE string; + DEFINE FIELD IF NOT EXISTS kind ON exam TYPE string; + DEFINE FIELD IF NOT EXISTS mode ON exam TYPE option; + DEFINE FIELD IF NOT EXISTS starts_at ON exam TYPE option; + DEFINE FIELD IF NOT EXISTS ends_at ON exam TYPE option; + DEFINE FIELD IF NOT EXISTS duration_ms ON exam TYPE option; + DEFINE FIELD IF NOT EXISTS max_attempts ON exam TYPE int DEFAULT 1; + DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true; + DEFINE FIELD IF NOT EXISTS allow_review ON exam TYPE bool DEFAULT false; + DEFINE FIELD IF NOT EXISTS draft ON exam TYPE bool DEFAULT false; + DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course; + + DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS exam ON exam_attempt TYPE record; + DEFINE FIELD IF NOT EXISTS user ON exam_attempt TYPE record; + DEFINE FIELD IF NOT EXISTS seq ON exam_attempt TYPE int DEFAULT 1; + DEFINE FIELD IF NOT EXISTS started_at ON exam_attempt TYPE int; + DEFINE FIELD IF NOT EXISTS finished_at ON exam_attempt TYPE option; + DEFINE FIELD IF NOT EXISTS left_at ON exam_attempt TYPE option; + DEFINE INDEX IF NOT EXISTS exam_attempt_exam_user_seq ON exam_attempt FIELDS exam, user, seq UNIQUE; + DEFINE INDEX IF NOT EXISTS exam_attempt_exam ON exam_attempt FIELDS exam; + + DEFINE TABLE IF NOT EXISTS exam_question SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS exam ON exam_question TYPE record; + DEFINE FIELD IF NOT EXISTS text ON exam_question TYPE string; + DEFINE FIELD IF NOT EXISTS kind ON exam_question TYPE string; + DEFINE FIELD IF NOT EXISTS points ON exam_question TYPE int; + -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices + -- gained stable ids (`array`/`int` -> `array`/`string`), + -- and IF NOT EXISTS would leave an existing database on the old types. + DEFINE FIELD OVERWRITE choices ON exam_question TYPE option>; + -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice + -- object's own fields are declared too (same shape as `settings.exam_kinds`). + DEFINE FIELD OVERWRITE choices.*.id ON exam_question TYPE string; + DEFINE FIELD OVERWRITE choices.*.text ON exam_question TYPE string; + DEFINE FIELD OVERWRITE correct ON exam_question TYPE option; + DEFINE FIELD IF NOT EXISTS subject ON exam_question TYPE record; + -- Provenance, one column per direction: `from_bank` is the template this + -- question was inserted from, `banked_as` the template most recently minted + -- by saving it into the bank. They replace the single `source_bank`, which + -- both directions wrote — so a question inserted from the bank read as + -- already-saved. OVERWRITE (not IF NOT EXISTS): the old column has to + -- actually go on an existing database, or SCHEMAFULL keeps accepting it + -- while the struct no longer writes it. + DEFINE FIELD OVERWRITE from_bank ON exam_question TYPE option>; + DEFINE FIELD OVERWRITE banked_as ON exam_question TYPE option>; + REMOVE FIELD IF EXISTS source_bank ON TABLE exam_question; + DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam; + DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject; + + DEFINE TABLE IF NOT EXISTS question_image SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS exam ON question_image TYPE record; + DEFINE FIELD IF NOT EXISTS question ON question_image TYPE record; + -- OVERWRITE: `slot` is now the choice's id, not its position. + DEFINE FIELD OVERWRITE slot ON question_image TYPE option; + DEFINE FIELD IF NOT EXISTS file ON question_image TYPE string; + DEFINE FIELD IF NOT EXISTS content_type ON question_image TYPE string; + DEFINE FIELD IF NOT EXISTS size ON question_image TYPE int; + DEFINE INDEX IF NOT EXISTS question_image_exam ON question_image FIELDS exam; + DEFINE INDEX IF NOT EXISTS question_image_question ON question_image FIELDS question; + + DEFINE TABLE IF NOT EXISTS bank_question SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS owner ON bank_question TYPE record; + -- OVERWRITE, not IF NOT EXISTS: the field started life as a required + -- `record` and has to actually change type on an existing database, + -- otherwise the subject-delete cascade (`SET subject = NONE`) is rejected. + DEFINE FIELD OVERWRITE subject ON bank_question TYPE option>; + DEFINE FIELD IF NOT EXISTS text ON bank_question TYPE string; + DEFINE FIELD IF NOT EXISTS kind ON bank_question TYPE string; + DEFINE FIELD IF NOT EXISTS points ON bank_question TYPE int; + -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices + -- gained stable ids (`array`/`int` -> `array`/`string`), + -- and IF NOT EXISTS would leave an existing database on the old types. + DEFINE FIELD OVERWRITE choices ON bank_question TYPE option>; + -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice + -- object's own fields are declared too (same shape as `settings.exam_kinds`). + DEFINE FIELD OVERWRITE choices.*.id ON bank_question TYPE string; + DEFINE FIELD OVERWRITE choices.*.text ON bank_question TYPE string; + DEFINE FIELD OVERWRITE correct ON bank_question TYPE option; + DEFINE FIELD IF NOT EXISTS source_exam ON bank_question TYPE option>; + -- 'private' | 'school'. DEFAULT so a row that predates the field (or any + -- partial write) can never come out published: the answer key stays the + -- owner's until they publish it. + DEFINE FIELD IF NOT EXISTS visibility ON bank_question TYPE string DEFAULT 'private'; + DEFINE FIELD IF NOT EXISTS created_at ON bank_question TYPE int READONLY; + DEFINE INDEX IF NOT EXISTS bank_question_owner ON bank_question FIELDS owner; + DEFINE INDEX IF NOT EXISTS bank_question_subject ON bank_question FIELDS subject; + + DEFINE TABLE IF NOT EXISTS bank_question_image SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS bank_question ON bank_question_image TYPE record; + -- OVERWRITE: `slot` is now the choice's id, not its position. + DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option; + DEFINE FIELD IF NOT EXISTS file ON bank_question_image TYPE string; + DEFINE FIELD IF NOT EXISTS content_type ON bank_question_image TYPE string; + DEFINE FIELD IF NOT EXISTS size ON bank_question_image TYPE int; + DEFINE INDEX IF NOT EXISTS bank_question_image_question ON bank_question_image FIELDS bank_question; + + DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record; + DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record; + DEFINE FIELD IF NOT EXISTS user ON exam_answer TYPE record; + -- OVERWRITE: `selected` now names the picked option by id. + DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option; + DEFINE FIELD IF NOT EXISTS text ON exam_answer TYPE option; + DEFINE FIELD IF NOT EXISTS updated_at ON exam_answer TYPE int; + -- `seq` numbers the sitting an answer belongs to (1, 2, …), mirroring + -- exam_attempt. It rides the record key too, so a retake's answer is a new + -- row, not an overwrite of the prior sitting. + DEFINE FIELD IF NOT EXISTS seq ON exam_answer TYPE int DEFAULT 1; + -- Retire the pre-history unique index: (question, user) is no longer unique + -- once a student re-sits; (question, user, seq) is. + REMOVE INDEX IF EXISTS exam_answer_question_user ON exam_answer; + DEFINE INDEX IF NOT EXISTS exam_answer_question_user_seq ON exam_answer FIELDS question, user, seq UNIQUE; + DEFINE INDEX IF NOT EXISTS exam_answer_exam_user ON exam_answer FIELDS exam, user; + DEFINE INDEX IF NOT EXISTS exam_answer_exam ON exam_answer FIELDS exam; + + DEFINE TABLE IF NOT EXISTS answer_image SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS exam ON answer_image TYPE record; + DEFINE FIELD IF NOT EXISTS question ON answer_image TYPE record; + DEFINE FIELD IF NOT EXISTS user ON answer_image TYPE record; + DEFINE FIELD IF NOT EXISTS file ON answer_image TYPE string; + DEFINE FIELD IF NOT EXISTS content_type ON answer_image TYPE string; + DEFINE FIELD IF NOT EXISTS size ON answer_image TYPE int; + -- `seq` numbers the sitting this drawing belongs to; it rides the record + -- key so a retake's image never overwrites the prior sitting's. + DEFINE FIELD IF NOT EXISTS seq ON answer_image TYPE int DEFAULT 1; + DEFINE INDEX IF NOT EXISTS answer_image_exam ON answer_image FIELDS exam; + DEFINE INDEX IF NOT EXISTS answer_image_user ON answer_image FIELDS user; + + DEFINE TABLE IF NOT EXISTS exam_result SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS exam ON exam_result TYPE record; + DEFINE FIELD IF NOT EXISTS user ON exam_result TYPE record; + DEFINE FIELD IF NOT EXISTS mark ON exam_result TYPE int; + DEFINE FIELD IF NOT EXISTS graded_by ON exam_result TYPE record; + -- `seq` numbers the sitting a mark belongs to; a retake earns its own mark + -- row, and the latest seq is the student's standing. + DEFINE FIELD IF NOT EXISTS seq ON exam_result TYPE int DEFAULT 1; + REMOVE INDEX IF EXISTS exam_result_exam_user ON exam_result; + DEFINE INDEX IF NOT EXISTS exam_result_exam_user_seq ON exam_result FIELDS exam, user, seq UNIQUE; + + DEFINE TABLE IF NOT EXISTS pool_question SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS asker ON pool_question TYPE record; + DEFINE FIELD IF NOT EXISTS title ON pool_question TYPE string; + DEFINE FIELD IF NOT EXISTS body ON pool_question TYPE string; + DEFINE FIELD IF NOT EXISTS status ON pool_question TYPE string DEFAULT 'pending'; + DEFINE FIELD IF NOT EXISTS asked_at ON pool_question TYPE int; + DEFINE FIELD IF NOT EXISTS approved_by ON pool_question TYPE option>; + DEFINE FIELD IF NOT EXISTS image_file ON pool_question TYPE option; + DEFINE FIELD IF NOT EXISTS image_content_type ON pool_question TYPE option; + DEFINE FIELD IF NOT EXISTS image_size ON pool_question TYPE option; + DEFINE INDEX IF NOT EXISTS pool_question_status ON pool_question FIELDS status; + DEFINE INDEX IF NOT EXISTS pool_question_asker ON pool_question FIELDS asker; + + DEFINE TABLE IF NOT EXISTS solution SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS question ON solution TYPE record; + DEFINE FIELD IF NOT EXISTS author ON solution TYPE record; + DEFINE FIELD IF NOT EXISTS body ON solution TYPE string; + DEFINE FIELD IF NOT EXISTS offered_at ON solution TYPE int; + DEFINE FIELD IF NOT EXISTS image_file ON solution TYPE option; + DEFINE FIELD IF NOT EXISTS image_content_type ON solution TYPE option; + DEFINE FIELD IF NOT EXISTS image_size ON solution TYPE option; + DEFINE INDEX IF NOT EXISTS solution_question ON solution FIELDS question; + + DEFINE TABLE IF NOT EXISTS settings SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS exam_kinds ON settings TYPE array; + DEFINE FIELD IF NOT EXISTS exam_kinds.*.name ON settings TYPE string; + DEFINE FIELD IF NOT EXISTS exam_kinds.*.weight ON settings TYPE int; + DEFINE FIELD IF NOT EXISTS attendance_statuses ON settings TYPE array; + DEFINE FIELD IF NOT EXISTS grade_bands ON settings TYPE array; + DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int; + DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string; + DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option; + DEFINE FIELD IF NOT EXISTS chatbot_history_turns ON settings TYPE option; + DEFINE FIELD IF NOT EXISTS max_chatbot_threads ON settings TYPE option; + DEFINE FIELD IF NOT EXISTS max_chatbot_message_len ON settings TYPE option; + -- Food program (2026-07-26). `meal_slots` mirrors the `exam_kinds` shape — + -- a named list a menu snapshots from — and `dietary_tags` mirrors + -- `attendance_statuses`. `meal_cancel_cutoff_minutes` is ONE knob for both + -- the booking and the cancel deadline; absent means no cutoff at all. All + -- three are `option<>`, exactly like `max_file_bytes`: NOT `DEFAULT []`. + -- `DEFAULT` fires on create only, and `PATCH /settings` writes the whole + -- row with `UPDATE ... CONTENT`, so a required-with-default field a writer + -- omits coerces to NONE and fails every settings write until the domain + -- struct carries it. `option<>` also means the existing singleton reads + -- fine, which is why the food program needs no BACKFILL anywhere. + DEFINE FIELD IF NOT EXISTS meal_slots ON settings TYPE option>; + DEFINE FIELD IF NOT EXISTS meal_slots.*.name ON settings TYPE string; + -- Minutes past midnight UTC at which the slot is served (2026-07-26). + -- `option` for the same reason the list itself is: slots written + -- before the field existed simply have no key, and read back as NONE -> + -- the booking cutoff falls back to midnight UTC, its old meaning. No + -- BACKFILL, and no DEFAULT — see the note above. + DEFINE FIELD IF NOT EXISTS meal_slots.*.serving_minute ON settings TYPE option; + DEFINE FIELD IF NOT EXISTS dietary_tags ON settings TYPE option>; + DEFINE FIELD IF NOT EXISTS meal_cancel_cutoff_minutes ON settings TYPE option; + + -- Homework (greenfield, 2026-07-22): a teacher assigns per course, students + -- submit files + optional text, a teacher grades a status + optional mark. + -- `course`/`created_by`/`created_at` are READONLY (a homework never moves + -- course, and stamps never rewrite); `subject` is NOT — it is re-taggable + -- via PATCH. `assigned` NONE/empty means the whole course. No BACKFILL: the + -- tables are new, so the whole migration stays additive and idempotent. + DEFINE TABLE IF NOT EXISTS homework SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS course ON homework TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS subject ON homework TYPE record; + DEFINE FIELD IF NOT EXISTS title ON homework TYPE string; + DEFINE FIELD IF NOT EXISTS description ON homework TYPE option; + DEFINE FIELD IF NOT EXISTS due_at ON homework TYPE int; + DEFINE FIELD IF NOT EXISTS assigned ON homework TYPE option>>; + DEFINE FIELD IF NOT EXISTS assigned[*] ON homework TYPE record; + DEFINE FIELD IF NOT EXISTS created_by ON homework TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS created_at ON homework TYPE int READONLY; + DEFINE INDEX IF NOT EXISTS homework_course ON homework FIELDS course; + + DEFINE TABLE IF NOT EXISTS homework_submission SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS homework ON homework_submission TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS user ON homework_submission TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS text ON homework_submission TYPE option; + DEFINE FIELD IF NOT EXISTS submitted_at ON homework_submission TYPE int READONLY; + DEFINE FIELD IF NOT EXISTS updated_at ON homework_submission TYPE int; + DEFINE FIELD IF NOT EXISTS file_count ON homework_submission TYPE option; + DEFINE INDEX IF NOT EXISTS homework_submission_homework ON homework_submission FIELDS homework; + + DEFINE TABLE IF NOT EXISTS homework_file SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS submission ON homework_file TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS name ON homework_file TYPE string; + DEFINE FIELD IF NOT EXISTS content_type ON homework_file TYPE string; + DEFINE FIELD IF NOT EXISTS size ON homework_file TYPE int; + DEFINE FIELD IF NOT EXISTS file ON homework_file TYPE string READONLY; + DEFINE FIELD IF NOT EXISTS created_at ON homework_file TYPE int READONLY; + DEFINE INDEX IF NOT EXISTS homework_file_submission ON homework_file FIELDS submission; + + DEFINE TABLE IF NOT EXISTS homework_result SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS homework ON homework_result TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS user ON homework_result TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS status ON homework_result TYPE string; + DEFINE FIELD IF NOT EXISTS mark ON homework_result TYPE option; + DEFINE FIELD IF NOT EXISTS graded_by ON homework_result TYPE record; + DEFINE FIELD IF NOT EXISTS created_at ON homework_result TYPE int; + DEFINE INDEX IF NOT EXISTS homework_result_homework ON homework_result FIELDS homework; + + -- Appointments (greenfield, 2026-07-23): a teacher publishes availability + -- slots, a student or parent books one. `series` groups the occurrences a + -- weekly repeat expanded into, so one cancel deletes one row and a series + -- delete finds the rest. A booking's live/dead state is the `status` + -- string; occupancy is derived from it under the appointment lock rather + -- than stored, so a rejected or cancelled booking frees its slot again. + -- The `proposed_*` fields carry a teacher's counter-proposal on the same + -- row until the requester accepts. No BACKFILL: both tables are new. + DEFINE TABLE IF NOT EXISTS appointment_slot SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS teacher ON appointment_slot TYPE record; + DEFINE FIELD IF NOT EXISTS starts_at ON appointment_slot TYPE int; + DEFINE FIELD IF NOT EXISTS ends_at ON appointment_slot TYPE int; + DEFINE FIELD IF NOT EXISTS note ON appointment_slot TYPE option; + DEFINE FIELD IF NOT EXISTS series ON appointment_slot TYPE option; + DEFINE FIELD IF NOT EXISTS created_at ON appointment_slot TYPE int; + DEFINE INDEX IF NOT EXISTS appointment_slot_teacher_starts ON appointment_slot FIELDS teacher, starts_at; + DEFINE INDEX IF NOT EXISTS appointment_slot_series ON appointment_slot FIELDS series; + + DEFINE TABLE IF NOT EXISTS appointment SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS slot ON appointment TYPE record; + DEFINE FIELD IF NOT EXISTS requester ON appointment TYPE record; + DEFINE FIELD IF NOT EXISTS status ON appointment TYPE string DEFAULT 'pending'; + DEFINE FIELD IF NOT EXISTS reason ON appointment TYPE string; + DEFINE FIELD IF NOT EXISTS proposed_starts_at ON appointment TYPE option; + DEFINE FIELD IF NOT EXISTS proposed_ends_at ON appointment TYPE option; + DEFINE FIELD IF NOT EXISTS proposed_by ON appointment TYPE option>; + DEFINE FIELD IF NOT EXISTS decided_by ON appointment TYPE option>; + DEFINE FIELD IF NOT EXISTS cancelled_by ON appointment TYPE option>; + DEFINE FIELD IF NOT EXISTS cancel_reason ON appointment TYPE option; + DEFINE FIELD IF NOT EXISTS reject_reason ON appointment TYPE option; + DEFINE FIELD IF NOT EXISTS created_at ON appointment TYPE int; + DEFINE INDEX IF NOT EXISTS appointment_slot_ref ON appointment FIELDS slot; + DEFINE INDEX IF NOT EXISTS appointment_requester ON appointment FIELDS requester; + DEFINE INDEX IF NOT EXISTS appointment_status ON appointment FIELDS status; + + -- Food program (greenfield, 2026-07-26): a published menu per day+slot, + -- dishes on it, a dietary profile per student, bookings against a menu's + -- capacity, who actually ate, and the money that moved. `date` is a + -- calendar day as `YYYY-MM-DD` text, not a timestamp: the unique index is + -- an equality test and a midnight-in-millis day is only unique for one + -- timezone. `slot` is snapshotted text, not a link, so retiring a slot in + -- settings never rewrites a past menu. Stamps stay `int` millis like the + -- rest of the schema. No BACKFILL: all six tables are new. + DEFINE TABLE IF NOT EXISTS menu SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS date ON menu TYPE string READONLY; + DEFINE FIELD IF NOT EXISTS slot ON menu TYPE string READONLY; + DEFINE FIELD IF NOT EXISTS capacity ON menu TYPE option; + DEFINE FIELD IF NOT EXISTS created_by ON menu TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS created_at ON menu TYPE int READONLY; + DEFINE INDEX IF NOT EXISTS menu_date_slot ON menu FIELDS date, slot UNIQUE; + + DEFINE TABLE IF NOT EXISTS menu_dish SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS menu ON menu_dish TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS name ON menu_dish TYPE string; + DEFINE FIELD IF NOT EXISTS description ON menu_dish TYPE option; + -- Money is minor units (kuruş) as an integer, everywhere. Never decimal. + DEFINE FIELD IF NOT EXISTS price_minor ON menu_dish TYPE int; + DEFINE FIELD IF NOT EXISTS tags ON menu_dish TYPE array DEFAULT []; + DEFINE FIELD IF NOT EXISTS tags[*] ON menu_dish TYPE string; + DEFINE FIELD IF NOT EXISTS created_at ON menu_dish TYPE int READONLY; + DEFINE INDEX IF NOT EXISTS menu_dish_menu ON menu_dish FIELDS menu; + + DEFINE TABLE IF NOT EXISTS dietary_profile SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS student ON dietary_profile TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS tags ON dietary_profile TYPE array DEFAULT []; + DEFINE FIELD IF NOT EXISTS tags[*] ON dietary_profile TYPE string; + DEFINE FIELD IF NOT EXISTS note ON dietary_profile TYPE option; + DEFINE FIELD IF NOT EXISTS updated_by ON dietary_profile TYPE record; + DEFINE FIELD IF NOT EXISTS updated_at ON dietary_profile TYPE int; + DEFINE INDEX IF NOT EXISTS dietary_profile_student ON dietary_profile FIELDS student UNIQUE; + + -- A cancel flips `status` and stamps `cancelled_at`; the row stays so the + -- freed seat is still auditable against the ledger line it charged. + DEFINE TABLE IF NOT EXISTS meal_booking SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS menu ON meal_booking TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS student ON meal_booking TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS booked_by ON meal_booking TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS status ON meal_booking TYPE string DEFAULT 'booked'; + -- How many times this seat has been taken, and what it cost when the + -- *current* attempt took it (NONE = the menu was free then). Together they + -- key the attempt's ledger lines, which is what makes billing idempotent + -- by identity rather than by scanning for an outstanding charge. + DEFINE FIELD IF NOT EXISTS attempt ON meal_booking TYPE int DEFAULT 1; + DEFINE FIELD IF NOT EXISTS price_minor ON meal_booking TYPE option; + DEFINE FIELD IF NOT EXISTS cancelled_at ON meal_booking TYPE option; + DEFINE FIELD IF NOT EXISTS created_at ON meal_booking TYPE int READONLY; + DEFINE INDEX IF NOT EXISTS meal_booking_menu ON meal_booking FIELDS menu; + DEFINE INDEX IF NOT EXISTS meal_booking_student ON meal_booking FIELDS student; + + DEFINE TABLE IF NOT EXISTS meal_attendance SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS menu ON meal_attendance TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS student ON meal_attendance TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS status ON meal_attendance TYPE string; + DEFINE FIELD IF NOT EXISTS marked_by ON meal_attendance TYPE record; + DEFINE FIELD IF NOT EXISTS marked_at ON meal_attendance TYPE int; + DEFINE INDEX IF NOT EXISTS meal_attendance_menu_student ON meal_attendance FIELDS menu, student UNIQUE; + + -- APPEND-ONLY by design: a mistake is corrected with an opposing + -- `reversal` line, never by editing or deleting one. Hence every field is + -- READONLY. `source` is untyped on purpose — a charge points at the + -- booking that caused it, a reversal at the line it undoes. + DEFINE TABLE IF NOT EXISTS meal_ledger SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS student ON meal_ledger TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS kind ON meal_ledger TYPE string READONLY; + DEFINE FIELD IF NOT EXISTS amount_minor ON meal_ledger TYPE int READONLY; + DEFINE FIELD IF NOT EXISTS source ON meal_ledger TYPE option READONLY; + DEFINE FIELD IF NOT EXISTS method ON meal_ledger TYPE option READONLY; + DEFINE FIELD IF NOT EXISTS note ON meal_ledger TYPE option READONLY; + DEFINE FIELD IF NOT EXISTS recorded_by ON meal_ledger TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS created_at ON meal_ledger TYPE int READONLY; + DEFINE INDEX IF NOT EXISTS meal_ledger_student ON meal_ledger FIELDS student; +"; + +/// Data backfills for rows written by older binaries. Runs *after* (and apart +/// from) the DDL batch so every statement sees the freshly defined schema — +/// see the `MIGRATION` doc for why sharing the batch corrupts the writes. +/// Idempotent: each backfill's `WHERE` only matches unconverted rows. +pub const BACKFILL: &str = " + UPDATE user SET role = 'student' WHERE role = NONE; + + UPDATE course SET kind = 'course' WHERE kind = NONE; + + -- Courses predate assignable teachers (2026-07-21): every existing course + -- was run by its creator alone, so it starts with nobody else assigned. + UPDATE course SET teachers = [] WHERE teachers = NONE; + + -- Exams predate the draft flag (2026-07-19): everything already out there + -- was live for its course, so it stays published. + UPDATE exam SET draft = false WHERE draft = NONE; + + -- Exams predate the review toggle (2026-07-24): default it closed (opt-in). + UPDATE exam SET allow_review = false WHERE allow_review = NONE; + + UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {}; + + -- Questions written before subjects existed (2026-07-17) are destroyed, not + -- backfilled: a subject is mandatory and there is nothing truthful to + -- assign. Their answers go first so no answer row outlives its question. + DELETE exam_answer WHERE question IN (SELECT VALUE id FROM exam_question WHERE subject = NONE); + DELETE exam_question WHERE subject = NONE; + + -- The hand-picked `users` audience retired into `registration` (2026-07-16): + -- each listed user becomes a signup row credited to the event's creator, and + -- the event becomes an uncapped registration list. Runs once — converted + -- events no longer match the `kind = 'users'` filter. (`?? []`: an empty + -- statement-subquery evaluates to NONE, which FOR refuses to iterate.) + FOR $ev IN ((SELECT id, creator, audience FROM event WHERE audience.kind = 'users') ?? []) { + FOR $usr IN ($ev.audience.users ?? []) { + UPSERT type::record('registration', string::concat(record::id($ev.id), '_', record::id($usr))) CONTENT { + event: $ev.id, + user: $usr, + registered_by: $ev.creator, + }; + }; + UPDATE $ev.id SET audience = { kind: 'registration' }; + }; + + -- Turns written before the clipped-answer flag existed (2026-07-23): the + -- clip was silent then, so nothing can be recovered — they read as whole, + -- which is what they were presented as all along. + UPDATE chatbot_message SET truncated = false WHERE truncated = NONE; + + -- An assistant turn is answered by a claim loop in some replica's process, + -- so a restart can leave its row `pending` with nobody left to complete it. + -- Only rows past the stale horizon ($stale_ms, from + -- `CHATBOT_PENDING_STALE_SECS`) are certainly abandoned though: a young one + -- may still be being answered on the other side of the AI bridge, and a + -- deploy must not shoot down a turn dispatched seconds ago. Nothing is lost + -- by waiting — a reader already presents an over-age `pending` row as + -- failed, and the next boot sweeps for real whatever crossed the horizon in + -- the meantime. + -- + -- Claim-aware since 2026-07-27, because the sweep is no longer school-wide + -- truth: under N replicas the row may belong to a *live peer's* claim loop, + -- and failing it here would shoot down another process's in-flight turn. + -- So a claim restamped within the window is left alone. Both disjuncts + -- matter — `claimed_by = NONE` alone would strand every row whose claimer + -- died, which is the one case the sweep exists for. + -- + -- The claim age is measured against $stale_ms rather than + -- CHATBOT_CLAIM_RECLAIM_SECS only because the boot binds one horizon (see + -- `database::migration_binds`); erring long is the safe direction — the + -- cost is that a row claimed just before it aged out waits one more boot + -- for its durable stamp, while readers have shown it failed all along. + UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted', + completed_at = time::unix(time::now()) * 1000 + WHERE status = 'pending' AND created_at < time::unix(time::now()) * 1000 - $stale_ms + AND (claimed_by = NONE + OR claimed_at < time::unix(time::now()) * 1000 - $stale_ms); + + -- Promotion out of student now deletes the user's enrollments (2026-07-18); + -- this sweeps rows promoted before that fix. A deleted user reads as + -- `user.role = NONE`, which is also != 'student' — those rows go too. + DELETE enrollment WHERE user.role != 'student'; + + -- Choices gained stable ids (2026-07-24): `choices` held bare strings and + -- `correct`/`selected`/`slot` held the option's *position*. The DDL above + -- retypes those columns, which leaves every old-shaped row readable but + -- unwritable ('Expected `none | array` but found `[..]`'), so this + -- conversion is repair, not cosmetics. + -- + -- Ids are minted in array order, so the id at position i *is* the id for + -- old index i — that identity is what keeps a stored answer, and an option + -- picture, pointing at the option the student actually saw. Hence the + -- dependent rows are remapped inside the loop that mints `$new`, against + -- that same array: once the ids are stored the positions are still + -- recoverable, but nothing guarantees a later pass would look them up the + -- same way. `WHERE choices[0] != NONE AND type::is_string(choices[0])` + -- matches only unconverted rows, so a second boot re-mints nothing; an + -- empty or absent `choices` needs no conversion at all. A question-level + -- picture (`slot = NONE`) is not an index and is left alone. + -- + -- Runs *before* every other backfill that writes these rows (the `seq` + -- stamps below): a write coerces the whole record, so touching a row for + -- any reason fails while its choices are still positional. For the same + -- reason the answer's remap stamps `seq` itself — the two legacy gaps sit + -- on the same row, and a write that fixes only one of them is rejected for + -- the other. `seq ?? 1` leaves an already-numbered sitting alone (DEFAULT + -- fills a CREATE, not an UPDATE of a row that predates the column). + FOR $q IN ((SELECT id, choices, correct FROM exam_question + WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) { + LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c }); + UPDATE $q.id SET choices = $new, + correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id }; + FOR $img IN ((SELECT id, slot FROM question_image + WHERE question = $q.id AND type::is_int(slot)) ?? []) { + UPDATE $img.id SET slot = $new[$img.slot].id; + }; + FOR $ans IN ((SELECT id, selected FROM exam_answer + WHERE question = $q.id AND type::is_int(selected)) ?? []) { + UPDATE $ans.id SET selected = $new[$ans.selected].id, seq = seq ?? 1; + }; + }; + + FOR $q IN ((SELECT id, choices, correct FROM bank_question + WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) { + LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c }); + UPDATE $q.id SET choices = $new, + correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id }; + FOR $img IN ((SELECT id, slot FROM bank_question_image + WHERE bank_question = $q.id AND type::is_int(slot)) ?? []) { + UPDATE $img.id SET slot = $new[$img.slot].id; + }; + }; + + -- Per-attempt history (2026-07-24): answers, drawings, and marks written + -- before retakes stopped wiping belong to the student's first sitting. + -- They already use the bare (seq==1) record key, so only the denormalized + -- `seq` field needs stamping. + UPDATE exam_answer SET seq = 1 WHERE seq = NONE; + UPDATE answer_image SET seq = 1 WHERE seq = NONE; + UPDATE exam_result SET seq = 1 WHERE seq = NONE; + + -- Count caps became cross-replica (2026-07-27): the authority moved from a + -- process-wide mutex to a counter column on the parent row, so every parent + -- that predates the column is seeded from the children it actually has. + -- Runs LAST, after the sweeps above have deleted whatever they delete. + -- + -- Deliberately one-time (`= NONE` guards every write): a peer replica is + -- serving while this boots, and recomputing a counter it is concurrently + -- incrementing would hand back a seat that is already taken. An absent + -- counter reads as zero, so the group pass runs before the zero pass. + FOR $row IN ((SELECT course, count() AS n FROM enrollment GROUP BY course) ?? []) { + UPDATE $row.course SET enrollment_count = $row.n WHERE enrollment_count = NONE; + }; + UPDATE course SET enrollment_count = 0 WHERE enrollment_count = NONE; + + FOR $row IN ((SELECT event, count() AS n FROM registration GROUP BY event) ?? []) { + UPDATE $row.event SET registration_count = $row.n WHERE registration_count = NONE; + }; + UPDATE event SET registration_count = 0 WHERE registration_count = NONE; + + FOR $row IN ((SELECT note, count() AS n FROM note_file GROUP BY note) ?? []) { + UPDATE $row.note SET file_count = $row.n WHERE file_count = NONE; + }; + UPDATE note SET file_count = 0 WHERE file_count = NONE; + + FOR $row IN ((SELECT submission, count() AS n FROM homework_file GROUP BY submission) ?? []) { + UPDATE $row.submission SET file_count = $row.n WHERE file_count = NONE; + }; + UPDATE homework_submission SET file_count = 0 WHERE file_count = NONE; + + FOR $row IN ((SELECT user_id, count() AS n FROM chatbot_thread GROUP BY user_id) ?? []) { + UPDATE $row.user_id SET chatbot_thread_count = $row.n WHERE chatbot_thread_count = NONE; + }; + UPDATE user SET chatbot_thread_count = 0 WHERE chatbot_thread_count = NONE; +"; + +/// The migration batches, in the order a boot applies them — and the *only* +/// list of them. [`crate::database::migrate`] runs exactly these and +/// [`crate::database::migration_fingerprint`] hashes exactly these, so a fourth +/// batch cannot be executed without changing the fingerprint that decides +/// whether a peer's schema is ours. They stay three separate queries: statements +/// in one batch see the schema as it stood when the batch started (see +/// `MIGRATION`). +pub const MIGRATION_BATCHES: [&str; 3] = [PRE_REPAIR, MIGRATION, BACKFILL]; diff --git a/src/rate_limit.rs b/src/rate_limit.rs index 801237c..cf66ad3 100644 --- a/src/rate_limit.rs +++ b/src/rate_limit.rs @@ -1,5 +1,6 @@ //! Rate limiting, hand-rolled on a fixed 60-second window — no extra crates, -//! no background tasks. The counter is keyed generically: by client IP for the +//! and nothing on the request path but a mutex (the one background task below +//! only shares counters). The counter is keyed generically: by client IP for the //! middleware tiers below, by user id for the per-user chatbot tier //! ([`UserRateLimiter`]), which cannot be middleware because the caller is only //! known once `CurrentUser` has run. @@ -23,6 +24,24 @@ //! Fixed windows admit up to a 2× burst straddling a window boundary. That is //! an accepted trade-off for an implementation simple enough to read in one //! sitting; argon2 keeps each allowed login attempt expensive anyway. +//! +//! # Across replicas +//! +//! The counters above are per process, and the backend runs as two replicas — +//! so a client hitting both got twice its budget. [`RateLimiter::share`] closes +//! that: a background task folds each bucket's new admits into one shared row +//! per tier + client + wall window (`rate_limit`, see +//! [`crate::constant::RATE_LIMIT_TABLE`]) every +//! [`crate::constant::RATE_SYNC_INTERVAL_SECS`], and the fleet-wide total that +//! comes back caps what the local bucket admits for the rest of that window. +//! +//! Admission itself stays in memory and stays synchronous — no request ever +//! waits on the database to be let in, and a database that is down or slow +//! costs nothing but the sharing (the tiers fall back to their local budgets +//! rather than failing anyone). The cost is a lag: within one interval a +//! replica can spend up to its own full budget before the shared total tells +//! it to stop, so the fleet's worst case is `replicas × max` for one interval +//! and `max` from then on. use std::collections::HashMap; use std::hash::Hash; @@ -33,13 +52,19 @@ use std::time::Duration; use axum::extract::{ConnectInfo, Request}; use axum::middleware::Next; use axum::response::Response; +use surrealdb::types::RecordId; // tokio's `Instant` wraps `std::time::Instant` in production but obeys // `tokio::time::pause`/`advance` under `start_paused` tests, which makes the // window arithmetic below testable without sleeping. use tokio::time::Instant; -use crate::constant::PURGE_AT; +use crate::constant::{ + PURGE_AT, RATE_LIMIT_TABLE, RATE_SYNC_INTERVAL_SECS, RATE_SYNC_MAX_KEYS, RATE_SYNC_TIMEOUT_SECS, +}; +use crate::database::Database; +use crate::domain::timestamp::Timestamp; use crate::error::AppError; +use crate::state::DbHealth; /// Per-IP rate-limit knobs, sourced from the environment (see `.env.example`) and /// carried in [`crate::state::AppState`]. A `0` limit disables that tier. @@ -80,7 +105,40 @@ pub struct RateLimiter { struct Bucket { window_start: Instant, + /// Requests this process admitted in the current local window. count: u32, + /// How many of `count` the sync task has already folded into the shared + /// row. Never above `count`, so `count - pushed` is what is still ours to + /// report. + pushed: u32, + /// The fleet-wide total the last sync read back — everyone's admits, + /// `pushed` included. Zero until a sync lands, which is what makes an + /// unshared limiter behave exactly like the local-only one it replaced. + remote: u32, + /// The wall window (`RATE_LIMIT_TABLE` row) `pushed`/`remote` describe. + /// The local window rolls per client while the shared one is aligned to the + /// clock, so this says which shared row those two numbers came from. + epoch: i64, +} + +impl Bucket { + /// A fresh window: nothing admitted, nothing shared, nothing known. + fn opened_at(now: Instant) -> Self { + Self { + window_start: now, + count: 0, + pushed: 0, + remote: 0, + epoch: 0, + } + } + + /// Requests the whole fleet has spent in this window as far as this process + /// can tell: what every replica had reported at the last sync, plus our own + /// admits since. Equals `count` until a sync lands. + fn spent(&self) -> u32 { + self.remote.saturating_add(self.count - self.pushed) + } } impl RateLimiter { @@ -168,16 +226,15 @@ impl RateLimiter { buckets.retain(|_, b| now.duration_since(b.window_start) < self.window); } - let bucket = buckets.entry(key).or_insert(Bucket { - window_start: now, - count: 0, - }); + let bucket = buckets.entry(key).or_insert_with(|| Bucket::opened_at(now)); if now.duration_since(bucket.window_start) >= self.window { - bucket.window_start = now; - bucket.count = 0; + // A fresh window starts owing nothing and knowing nothing: keeping + // the old total would hold the client at a budget it no longer + // spent. The next sync re-reads what the fleet has spent since. + *bucket = Bucket::opened_at(now); } - if bucket.count < self.max { + if bucket.spent() < self.max { bucket.count += 1; Ok(()) } else { @@ -187,6 +244,196 @@ impl RateLimiter { } } +/// One bucket's report, taken while the map was locked so the round can run +/// its query without holding it. `counted` is the `count` the delta was read +/// from — a request admitted mid-round bumps `count` past it and is simply +/// carried into the next round. +struct Pending { + key: K, + delta: u32, + counted: u32, + window_start: Instant, +} + +impl RateLimiter +where + K: Eq + Hash + Clone + std::fmt::Display + Send + Sync + 'static, +{ + /// Make this tier's budget fleet-wide: every + /// [`RATE_SYNC_INTERVAL_SECS`] a background task reports what this replica + /// has admitted and reads back what everyone has, which caps further local + /// admits in the same window (see the module docs). + /// + /// `tier` names the counter's namespace in the shared table — two limiters + /// sharing a name share a budget, which is exactly what the two processes + /// running the same tier want and what `auth` and `api` must avoid. + /// + /// The task holds a *weak* reference to the buckets, so it stops with the + /// limiter rather than keeping a dropped one alive (test suites build + /// dozens). + pub fn share(&self, tier: &'static str, db: Database, db_up: DbHealth) { + if self.max == 0 { + // The tier is off: `check` records nothing, so there is nothing to + // share and no reason to hold a task or a table row. + return; + } + let buckets = Arc::downgrade(&self.buckets); + let window = self.window; + tokio::spawn(async move { + let mut swept = 0; + loop { + tokio::time::sleep(Duration::from_secs(RATE_SYNC_INTERVAL_SECS)).await; + let Some(buckets) = buckets.upgrade() else { + return; + }; + // Never queue work on a database that is down: the SDK parks a + // query instead of failing it, so this task would sit on a + // round for the whole outage and then apply a stale total. + if !db_up.is_up() { + continue; + } + let epoch = current_epoch(window); + sync_once(tier, &buckets, window, epoch, &db).await; + // Piggybacked cleanup, once per window: rows for a window that + // has passed can never be read again. + if swept != epoch { + swept = epoch; + let sql = format!("DELETE {RATE_LIMIT_TABLE} WHERE window_start < $cutoff"); + if let Err(err) = with_deadline(db.query(sql).bind(("cutoff", epoch))).await { + tracing::warn!(%err, "rate-limit sweep failed; retrying next window"); + } + } + } + }); + } +} + +/// Fold every live bucket's new admits into its shared row and take the +/// fleet-wide total back. +/// +/// One statement per bucket in one query, and each statement is its own +/// transaction — so a statement that loses a write race fails alone. Its bucket +/// simply keeps the delta unreported and the next round (2s later) carries it, +/// which is why no retry loop is needed here: retrying the *query* would +/// double-apply the statements that did land, since `hits` accumulates. +async fn sync_once( + tier: &str, + buckets: &Mutex>, + window: Duration, + epoch: i64, + db: &Database, +) { + let now = Instant::now(); + let pending: Vec> = { + let mut guard = buckets.lock().expect("rate limiter mutex poisoned"); + guard + .iter_mut() + .filter(|(_, b)| b.count > 0 && now.duration_since(b.window_start) < window) + .take(RATE_SYNC_MAX_KEYS) + .map(|(key, b)| { + if b.epoch != epoch { + // The shared window rolled: the row this bucket is about to + // write knows nothing of us, so the whole local count is + // the delta and the previous total describes a dead row. + b.epoch = epoch; + b.pushed = 0; + b.remote = 0; + } + Pending { + key: key.clone(), + delta: b.count - b.pushed, + counted: b.count, + window_start: b.window_start, + } + }) + .collect() + }; + if pending.is_empty() { + return; + } + + let sql: String = (0..pending.len()) + .map(|i| { + format!("UPSERT $id{i} SET hits = (hits ?? 0) + $delta{i}, window_start = $window RETURN VALUE hits;") + }) + .collect(); + let mut query = db.query(sql).bind(("window", epoch)); + for (i, p) in pending.iter().enumerate() { + let id = RecordId::new(RATE_LIMIT_TABLE, row_key(tier, &p.key, epoch)); + query = query + .bind((format!("id{i}"), id)) + .bind((format!("delta{i}"), i64::from(p.delta))); + } + let mut response = match with_deadline(query).await { + Ok(response) => response, + Err(err) => { + tracing::warn!(%err, "rate-limit sync failed; counting locally until it recovers"); + return; + } + }; + + let mut guard = buckets.lock().expect("rate limiter mutex poisoned"); + for (i, p) in pending.iter().enumerate() { + // A statement that failed (a lost write race) leaves its bucket + // untouched: the delta stays unreported and the next round carries it. + let Ok(total) = response.take::>(i) else { + continue; + }; + let (Some(total), Some(bucket)) = (total.first(), guard.get_mut(&p.key)) else { + continue; + }; + // The window may have rolled while the query was in flight, in which + // case this total is about a bucket that no longer exists. + if bucket.epoch != epoch || bucket.window_start != p.window_start { + continue; + } + bucket.pushed = p.counted; + bucket.remote = (*total).clamp(0, u32::MAX.into()) as u32; + } +} + +/// The wall-clock window a shared row is keyed by, aligned so every replica +/// agrees on it — the local windows cannot be used for this, since each one +/// starts whenever that client's first request happened to land. +fn current_epoch(window: Duration) -> i64 { + let ms = i64::try_from(window.as_millis()).unwrap_or(i64::MAX).max(1); + Timestamp::now().as_millis().div_euclid(ms) * ms +} + +/// The shared row's key: tier, client, window. The client part is hashed +/// because it is a raw IP or user id — free of the `:` and `_` that would +/// otherwise let one client's key collide with another's by construction. +fn row_key(tier: &str, key: &K, epoch: i64) -> String { + use sha2::{Digest, Sha256}; + let digest = Sha256::digest(key.to_string().as_bytes()); + format!("{tier}_{:x}_{epoch}", ByteSlice(&digest[..8])) +} + +/// Lowercase hex of a byte slice, for [`row_key`]. +struct ByteSlice<'a>(&'a [u8]); + +impl std::fmt::LowerHex for ByteSlice<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.iter().try_for_each(|byte| write!(f, "{byte:02x}")) + } +} + +/// Run a sync query under a deadline. The liveness flag catches a *known* +/// outage; this catches the socket that died between the last ping and now, +/// which the SDK would otherwise park until the database returned — wedging +/// the one task every tier's sharing depends on. +async fn with_deadline( + query: impl std::future::IntoFuture>, +) -> Result { + tokio::time::timeout( + Duration::from_secs(RATE_SYNC_TIMEOUT_SECS), + query.into_future(), + ) + .await + .map_err(|_| AppError::Internal("rate-limit sync timed out".into()))? + .map_err(AppError::from) +} + /// Resolve the client IP a request is billed against. /// /// With `trust_proxy`, prefer the rightmost `X-Forwarded-For` entry — appended diff --git a/src/web/appointments.rs b/src/web/appointments.rs index b9627f5..0ade674 100644 --- a/src/web/appointments.rs +++ b/src/web/appointments.rs @@ -386,6 +386,7 @@ async fn list_slots( (slots, people) }; let total = slots.len() as i64; + // Paged in the web layer: slots of demoted teachers are dropped above. let items = paginate(&slots, limit, offset) .iter() .map(|slot| SlotResponse::new(slot, &people)) @@ -547,14 +548,13 @@ async fn list_appointments( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let rows = if user.get_role().at_least(Role::Teacher) { - Appointment::list_for_teacher(user.get_id(), &st.db).await? + let (rows, total) = if user.get_role().at_least(Role::Teacher) { + Appointment::list_for_teacher(user.get_id(), limit, offset, &st.db).await? } else { - Appointment::list_for_requester(user.get_id(), &st.db).await? + Appointment::list_for_requester(user.get_id(), limit, offset, &st.db).await? }; - let total = rows.len() as i64; // Join slots and people onto the page alone — the lookup shrinks with it. - let items = appointment_responses(paginate(&rows, limit, offset), &st.db).await?; + let items = appointment_responses(&rows, &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) } diff --git a/src/web/auth.rs b/src/web/auth.rs index 299a4cf..4c9d985 100644 --- a/src/web/auth.rs +++ b/src/web/auth.rs @@ -20,12 +20,16 @@ use crate::state::AppState; use super::dto::Role; use super::{CurrentUser, UserResponse}; -pub fn routes(rate_limit: &RateLimitConfig) -> OpenApiRouter { +pub fn routes(state: &AppState) -> OpenApiRouter { // Strict per-IP limit on the two credential endpoints only — the // brute-force and username-enumeration surface. `me` and `logout` stay // outside it: browser frontends poll `me` on every page load, and being // over the auth limit must never block an intentional logout. + let rate_limit: &RateLimitConfig = &state.rate_limit; let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy); + // One budget across replicas, not one per process — the tier only means + // something if a brute-forcer cannot get it twice by hitting both. + limiter.share("auth", state.db.clone(), state.db_up.clone()); OpenApiRouter::new() .routes(routes!(register)) .routes(routes!(login)) diff --git a/src/web/bank_questions.rs b/src/web/bank_questions.rs index 400f7a1..b203ae0 100644 --- a/src/web/bank_questions.rs +++ b/src/web/bank_questions.rs @@ -24,7 +24,7 @@ use utoipa::{IntoParams, ToSchema}; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; -use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; +use crate::constant::{CAS_UPDATE_RETRIES, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; use crate::domain::bank_question_image::BankQuestionImage; use crate::domain::exam_question::{ @@ -32,7 +32,6 @@ use crate::domain::exam_question::{ }; use crate::domain::note_file::FileContentType; use crate::domain::role::Role; -use crate::domain::settings::Settings; use crate::domain::subject::{Subject, SubjectId}; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; @@ -42,16 +41,17 @@ use super::dto::person_map; use super::exams::ChoiceResponse; use super::subjects::subject_must_exist; use super::{ - ChoiceBody, Page, PageParams, RequireTeacher, UploadFileForm, blob_path, image_content_type, - read_upload, remove_blob, serve_inline_blob, set_or_clear, + ChoiceBody, ImageUpload, Page, PageParams, RequireTeacher, UploadFileForm, read_image_upload, + remove_blob, serve_inline_blob, set_or_clear, store_blob, }; /// Serializes bank writes that adopt a `subject` against a concurrent subject -/// delete. Bank create takes the reader lease across its -/// subject-exists check and the write; the *update* takes the writer lease -/// instead, because it is a read-modify-write of the whole template, so its row -/// read must be serialized against another update and not merely against the -/// delete cascade; the subject delete takes the writer +/// delete — the one invariant left here, and a **replica-local** one: it orders +/// requests inside one process, and there are two. Every lease is now a +/// *reader* lease taken across a subject-exists check and the write that adopts +/// it: bank create, bank update, and save-to-bank. (Update used to take the +/// writer lease for its read-modify-write; that is a compare-and-set on the row +/// itself now, which holds across replicas.) The subject delete takes the writer /// lease across the cascade that clears `subject` off every template, so a /// template can't land on a subject that vanished mid-flight (it would outlive /// the sweep) — the bank twin of the @@ -113,7 +113,7 @@ struct CreateBankQuestion { correct: Option, } -#[derive(Deserialize, ToSchema)] +#[derive(Clone, Deserialize, ToSchema)] struct UpdateBankQuestion { /// Re-tag the template's origin subject. Omit to keep the current one /// (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 Result { let replaced = BankQuestionImage::read_slot(question, slot, &st.db).await?; let image = BankQuestionImage::new(question, slot, content_type, data.len() as i64); - let path = blob_path(&st.files_path, image.get_file()); - tokio::fs::write(&path, data) - .await - .map_err(|err| AppError::Internal(format!("failed to store the image blob: {err}")))?; - match image.upsert(&st.db).await { - Ok(stored) => { - if let Some(replaced) = replaced { - remove_blob(&st.files_path, replaced.get_file()).await; - } - Ok(stored) - } - Err(err) => { - let _ = tokio::fs::remove_file(&path).await; - Err(err) - } - } + let file = image.get_file().to_string(); + store_blob(st, &file, data, || async { + let stored = image.upsert(&st.db).await?; + Ok((stored, replaced.map(|old| old.get_file().to_string()))) + }) + .await } /// Add a template to the bank. Requires teacher+. `subject_id` is origin @@ -602,8 +592,10 @@ async fn get_question( Ok(Json(BankQuestionResponse::new(&question, &images))) } -/// Edit a template. Owner only (admins aside — 403 otherwise). Omitted fields -/// keep their value; `kind`/`choices`/`correct` are re-validated as a unit, so +/// Edit a template. Owner only (admins aside — 403 otherwise). Concurrent edits +/// of *different* fields merge instead of reverting each other (the save is +/// conditioned on the snapshot it merged over, and re-merges when it loses). +/// Omitted fields keep their value; `kind`/`choices`/`correct` are re-validated as a unit, so /// a kind switch must bring the matching fields along. Replacing or clearing /// `choices` drops the old options' pictures. Bank templates never freeze — /// they have no exam tie. @@ -626,6 +618,7 @@ async fn get_question( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse), (status = 404, description = "No such template", body = ErrorResponse), + (status = 409, description = "The template kept changing under concurrent edits — retry", body = ErrorResponse), ), )] async fn update_question( @@ -634,62 +627,71 @@ async fn update_question( Path(bid): Path, Json(req): Json, ) -> Result, AppError> { - // *Writer* lease of [`BANK_LOCK`], taken before the row is read: this is a - // read-modify-write, not a per-field write. Omitted fields are refilled from - // the snapshot below, and the kind/choices/correct trio genuinely has to be - // (a text-only edit re-submits the stored options *with their ids* so every - // choice keeps its picture), so the read, the merge and the write must be - // one unit or a concurrent PATCH of another field is silently reverted. The - // reader lease this used to take was both shared *and* acquired after the - // read, so it serialized nothing; it only ever covered the subject-exists - // check against a subject delete, which the writer lease still covers. - // Exclusive means bank writes queue behind each other — they are rare - // teacher edits, and the per-field alternative cannot express the - // choice-identity merge. Still the only lock this path takes, so the - // documented EXAM → BANK order is unaffected. - let _guard = BANK_LOCK.write().await; - let question = owned_question(&st, &user, &bid).await?; - // Omitted keeps the stored subject — which may already be `None`, cleared - // by that subject's delete. - let subject = match req.subject_id { - Some(ref subject_id) => Some(subject_must_exist(subject_id, &st.db).await?), - None => question.get_subject().cloned(), - }; - let text = match req.text { - Some(ref text) => QuestionText::try_new(text)?, - None => question.get_text().clone(), - }; - let points = match req.points { - Some(points) => QuestionPoints::try_new(points)?, - None => question.get_points(), - }; - // Merge the kind-dependent fields (set / clear / keep per field), then - // re-validate them as a unit — a PATCH can't leave a half-question behind. - let kind = match req.kind { - Some(ref kind) => QuestionKind::try_new(kind)?, - None => question.get_kind().clone(), - }; - // Omitting `choices` re-submits the stored options *with their ids*, so a - // text-only edit keeps every identity (and every picture) untouched. - let choices = match req.choices { - Some(update) => ChoiceBody::into_inputs(update), - None => ChoiceBody::from_stored(question.get_choices()), - }; - let correct = match req.correct { - Some(update) => update, - None => question.get_correct().map(|id| id.as_str().to_string()), - }; - let stored: Vec = question.get_choices().unwrap_or_default().to_vec(); - let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?; - let visibility = match req.visibility { - Some(ref visibility) => BankVisibility::try_new(visibility)?, - None => question.get_visibility().clone(), + // Reader lease of [`BANK_LOCK`], exactly like the create path and for the + // one thing it buys: the subject-exists check below is paired with the + // subject delete that sweeps this table (that cascade takes the writer + // lease), so a template cannot be pinned to a subject on its way out. It is + // replica-local, like every lock here. The *writer* lease this used to take + // was aimed at the read-modify-write below, which it only serialized inside + // one process — that is now a compare-and-set on the row itself. + let _guard = BANK_LOCK.read().await; + // Read, merge and write again while the row keeps moving underneath: the + // guarded write refuses on a snapshot that has gone stale, so both edits + // land instead of the later one reverting the earlier. + let mut left = CAS_UPDATE_RETRIES; + let updated = loop { + let question = owned_question(&st, &user, &bid).await?; + // Omitted keeps the stored subject — which may already be `None`, cleared + // by that subject's delete. + let subject = match req.subject_id { + Some(ref subject_id) => Some(subject_must_exist(subject_id, &st.db).await?), + None => question.get_subject().cloned(), + }; + let text = match req.text { + Some(ref text) => QuestionText::try_new(text)?, + None => question.get_text().clone(), + }; + let points = match req.points { + Some(points) => QuestionPoints::try_new(points)?, + None => question.get_points(), + }; + // Merge the kind-dependent fields (set / clear / keep per field), then + // re-validate them as a unit — a PATCH can't leave a half-question behind. + let kind = match req.kind { + Some(ref kind) => QuestionKind::try_new(kind)?, + None => question.get_kind().clone(), + }; + // Omitting `choices` re-submits the stored options *with their ids*, so a + // text-only edit keeps every identity (and every picture) untouched. + let choices = match req.choices.clone() { + Some(update) => ChoiceBody::into_inputs(update), + None => ChoiceBody::from_stored(question.get_choices()), + }; + let correct = match req.correct.clone() { + Some(update) => update, + None => question.get_correct().map(|id| id.as_str().to_string()), + }; + let stored: Vec = question.get_choices().unwrap_or_default().to_vec(); + let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?; + let visibility = match req.visibility { + Some(ref visibility) => BankVisibility::try_new(visibility)?, + None => question.get_visibility().clone(), + }; + + if let Some(updated) = question + .update_if_unchanged(subject, text, points, spec, visibility, &st.db) + .await? + { + break updated; + } + left -= 1; + if left == 0 { + return Err(AppError::Conflict( + "the template kept changing underneath this update — try again", + )); + } }; - - let bid = question.get_id().clone(); - let updated = question - .update(subject, text, points, spec, visibility, &st.db) - .await?; + let bid = updated.get_id().clone(); // Only the options that are actually *gone* lose their pictures — an option // that survives the edit keeps its image wherever it moved in the list. let keep: Vec = updated @@ -770,10 +772,8 @@ async fn upload_question_image( mut multipart: Multipart, ) -> Result<(StatusCode, Json), AppError> { let question = owned_question(&st, &user, &bid).await?; - let limit = Settings::load(&st.db).await?.get_max_file_bytes(); - let upload = read_upload(&mut multipart, limit).await?; - let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; - let stored = store_image(&st, question.get_id(), None, content_type, &upload.data).await?; + let ImageUpload { content_type, data } = read_image_upload(&st, &mut multipart).await?; + let stored = store_image(&st, question.get_id(), None, content_type, &data).await?; Ok((StatusCode::CREATED, Json(BankImageMeta::new(&stored)))) } @@ -864,17 +864,8 @@ async fn upload_choice_image( ) -> Result<(StatusCode, Json), AppError> { let question = owned_question(&st, &user, &bid).await?; let slot = bank_choice_slot(&question, &choice_id)?; - let limit = Settings::load(&st.db).await?.get_max_file_bytes(); - let upload = read_upload(&mut multipart, limit).await?; - let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; - let stored = store_image( - &st, - question.get_id(), - Some(&slot), - content_type, - &upload.data, - ) - .await?; + let ImageUpload { content_type, data } = read_image_upload(&st, &mut multipart).await?; + let stored = store_image(&st, question.get_id(), Some(&slot), content_type, &data).await?; Ok((StatusCode::CREATED, Json(BankImageMeta::new(&stored)))) } diff --git a/src/web/chatbot.rs b/src/web/chatbot.rs index 3436bac..0f7d093 100644 --- a/src/web/chatbot.rs +++ b/src/web/chatbot.rs @@ -50,7 +50,7 @@ use crate::domain::user::UserId; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; -use super::{CurrentUser, Page, PageParams, paginate}; +use super::{CurrentUser, Page, PageParams}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() @@ -155,12 +155,9 @@ async fn list_threads( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let threads = ChatbotThread::list_for_user(user.get_id(), &st.db).await?; - let total = threads.len() as i64; - let items = paginate(&threads, limit, offset) - .iter() - .map(ChatbotThreadResponse::new) - .collect(); + let (threads, total) = + ChatbotThread::list_for_user(user.get_id(), limit, offset, &st.db).await?; + let items = threads.iter().map(ChatbotThreadResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -339,12 +336,9 @@ async fn list_messages( ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; let thread = own_thread(&id, user.get_id(), &st.db).await?; - let messages = ChatbotMessage::list_for_thread(thread.get_id(), &st.db).await?; - let total = messages.len() as i64; - let items = paginate(&messages, limit, offset) - .iter() - .map(ChatbotMessageResponse::new) - .collect(); + let (messages, total) = + ChatbotMessage::list_for_thread(thread.get_id(), limit, offset, &st.db).await?; + let items = messages.iter().map(ChatbotMessageResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } diff --git a/src/web/courses.rs b/src/web/courses.rs index 13ab171..c613db4 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -219,7 +219,7 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let courses = Course::list_enrolled(user.get_id(), &st.db).await?; - let total = courses.len() as i64; - let window = paginate(&courses, limit, offset); - let people = person_map(window.iter().flat_map(course_people), &st.db).await?; - let items = window + let (courses, total) = Course::list_enrolled(user.get_id(), limit, offset, &st.db).await?; + let people = person_map(courses.iter().flat_map(course_people), &st.db).await?; + let items = courses .iter() .map(|course| CourseResponse::new(course, &people)) .collect(); @@ -711,10 +710,8 @@ async fn list_roster( "only the course creator, an assigned teacher, or a manager/admin can list the roster", )); } - let enrollments = Enrollment::list_for_course(course.get_id(), &st.db).await?; - let total = enrollments.len() as i64; + let (rows, total) = Enrollment::list_for_course(course.get_id(), limit, offset, &st.db).await?; // Join people onto the page alone — the lookup shrinks with the window. - let rows = paginate(&enrollments, limit, offset); let people = person_map( rows.iter() .flat_map(|e| [e.get_user().clone(), e.get_enrolled_by().clone()]), @@ -884,6 +881,7 @@ async fn list_course_exams( exams.retain(|exam| !exam.is_draft()); } let total = exams.len() as i64; + // Paged in the web layer: the draft filter above is per-row Rust. let items = paginate(&exams, limit, offset) .iter() .map(ExamResponse::new) @@ -976,12 +974,9 @@ async fn list_course_subjects( "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course", )); } - let subjects = Subject::list_for_course(course.get_id(), &st.db).await?; - let total = subjects.len() as i64; - let items = paginate(&subjects, limit, offset) - .iter() - .map(SubjectResponse::new) - .collect(); + let (subjects, total) = + Subject::list_for_course(course.get_id(), limit, offset, &st.db).await?; + let items = subjects.iter().map(SubjectResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -1115,6 +1110,7 @@ async fn list_course_homework( homework.retain(|hw| hw.student_sees(user.get_id())); } let total = homework.len() as i64; + // Paged in the web layer: the audience filter above is per-row Rust. let items = paginate(&homework, limit, offset) .iter() .map(HomeworkResponse::new) @@ -1230,10 +1226,9 @@ async fn list_course_sessions( "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course", )); } - let sessions = CourseSession::list_for_course(course.get_id(), &st.db).await?; - let total = sessions.len() as i64; + let (rows, total) = + CourseSession::list_for_course(course.get_id(), limit, offset, &st.db).await?; // Join teachers onto the page alone — the lookup shrinks with the window. - let rows = paginate(&sessions, limit, offset); let people = person_map(rows.iter().map(|s| s.get_teacher().clone()), &st.db).await?; let items = rows .iter() diff --git a/src/web/events.rs b/src/web/events.rs index 588aab5..30ff176 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -11,9 +11,7 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::attendance::{Attendance, AttendanceStatus}; use crate::domain::course::{Course, CourseId}; -use crate::domain::event::{ - EVENT_LOCK, Event, EventAudience, EventDescription, EventId, EventTitle, -}; +use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle}; use crate::domain::registration::Registration; use crate::domain::role::Role; use crate::domain::settings::Settings; @@ -303,6 +301,7 @@ async fn list_events( let (limit, offset) = page.resolve()?; let events = window.apply(Event::list_all(&st.db).await?)?; let total = events.len() as i64; + // Paged in the web layer: `WindowParams` filters and re-orders in Rust. let items = paginate(&events, limit, offset) .iter() .map(EventResponse::new) @@ -368,15 +367,6 @@ async fn update_event( .starts_at .map(|update| update.map(Timestamp::from_millis)); let ends_at = req.ends_at.map(|update| update.map(Timestamp::from_millis)); - // Only the range check needs the stored row, and only it can race: it - // validates an arriving end against the other end as stored, so the read, - // the check and the write are held together under [`EVENT_LOCK`]. A PATCH - // that moves neither end pays nothing. - let _guard = match (starts_at, ends_at) { - (None, None) => None, - _ => Some(EVENT_LOCK.lock().await), - }; - let event = Event::read(&EventId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; @@ -411,7 +401,8 @@ async fn update_event( } // The range CHECK needs both ends: whichever the request omitted comes // from the stored row. Read for the check only — the omitted side is - // never written back. + // never written back. Pre-flight only: `Event::update` re-makes this check + // in the UPDATE's `WHERE`, so a concurrent move of the omitted end loses. check_time_range( starts_at.unwrap_or_else(|| event.get_starts_at()), ends_at.unwrap_or_else(|| event.get_ends_at()), @@ -549,10 +540,8 @@ async fn list_attendance( Event::read(&event_id, &st.db) .await? .ok_or(AppError::NotFound)?; - let roster = Attendance::list_for_event(&event_id, &st.db).await?; - let total = roster.len() as i64; + let (rows, total) = Attendance::list_for_event(&event_id, limit, offset, &st.db).await?; // Join people onto the page alone — the lookup shrinks with the window. - let rows = paginate(&roster, limit, offset); let people = person_map( rows.iter() .flat_map(|a| [a.get_user().clone(), a.get_marked_by().clone()]), @@ -646,7 +635,7 @@ async fn roster( let mut members = event.get_audience().members(event.get_id(), &st.db).await?; // ULID keys sort by creation instant — a stable order keeps pages coherent. members.sort_by(|a, b| a.key().cmp(b.key())); - let marks = Attendance::list_for_event(&event_id, &st.db).await?; + let (marks, _) = Attendance::list_for_event(&event_id, None, 0, &st.db).await?; let by_user: HashMap<&str, &Attendance> = marks .iter() .map(|attendance| (attendance.get_user().key(), attendance)) @@ -654,6 +643,7 @@ async fn roster( let total = members.len() as i64; // Join people onto the page alone — the lookup shrinks with the window. + // Paged in the web layer: the audience is resolved in Rust. let window = paginate(&members, limit, offset); let ids = window.iter().cloned().chain(window.iter().filter_map(|m| { by_user diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index d0ff4d4..6bae209 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -88,8 +88,9 @@ use crate::web::exams::{ /// so it never stamps. No ordering leaves a present student stamped as left — /// the reconnect-vs-teardown race that used to lock students out with /// `allow_rejoin` off (cleared at the door, stamped after, present forever -/// refused). This backend is the database's only writer (single -/// instance) — so one process-wide lock is sufficient, same as `REGISTER_LOCK`. +/// refused). The count this pairs with lives in *this* process's memory +/// ([`crate::state::ExamPresence`]), so process-wide is exactly the right +/// scope: a peer replica counts its own sockets in its own map. // ponytail: global lock, per-attempt locks if room churn ever shows up in a // profile. static PRESENCE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); @@ -337,7 +338,10 @@ async fn state_frame( ExamAnswer::list_for_exam_user(exam.get_id(), attempt.get_user(), attempt.get_seq(), db) .await? .len(); - let question_count = ExamQuestion::list_for_exam(exam.get_id(), db).await?.len(); + let question_count = ExamQuestion::list_for_exam(exam.get_id(), None, 0, db) + .await? + .0 + .len(); let frame = json!({ "type": "state", "status": status.as_str(), diff --git a/src/web/exams.rs b/src/web/exams.rs deleted file mode 100644 index 0ddb9f9..0000000 --- a/src/web/exams.rs +++ /dev/null @@ -1,3629 +0,0 @@ -use std::collections::HashMap; - -use axum::Json; -use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; -use axum::http::StatusCode; -use axum::response::Response; -use serde::{Deserialize, Serialize}; -use utoipa::ToSchema; -use utoipa_axum::router::OpenApiRouter; -use utoipa_axum::routes; - -use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; -use crate::database::Database; -use crate::domain::answer_image::AnswerImage; -use crate::domain::bank_question::{BankQuestion, BankQuestionId}; -use crate::domain::bank_question_image::BankQuestionImage; -use crate::domain::course::Course; -use crate::domain::enrollment::Enrollment; -use crate::domain::exam::{ - Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, - ExamSchedule, ExamTitle, -}; -use crate::domain::exam_answer::{ExamAnswer, auto_score}; -use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt}; -use crate::domain::exam_question::{ - Choice, ChoiceId, ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec, - QuestionText, -}; -use crate::domain::exam_result::{ExamResult, Mark}; -use crate::domain::note_file::FileContentType; -use crate::domain::question_image::QuestionImage; -use crate::domain::role::Role; -use crate::domain::settings::Settings; -use crate::domain::timestamp::Timestamp; -use crate::domain::user::{User, UserId}; -use crate::error::{AppError, ErrorResponse, ValidationError}; -use crate::state::AppState; - -use super::bank_questions::BankQuestionResponse; -use super::courses::{can_manage_course, can_view_course, visible_courses}; -use super::subjects::subject_in_course; -use super::{ - ChoiceBody, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, Scheduled, - UploadFileForm, WindowParams, blob_path, check_not_past, image_content_type, paginate, - person_map, read_upload, remove_blob, set_or_clear, -}; - -impl Scheduled for Exam { - fn starts_at_ms(&self) -> Option { - self.get_starts_at().map(|at| at.as_millis()) - } - - fn ends_at_ms(&self) -> Option { - self.get_ends_at().map(|at| at.as_millis()) - } - - fn order_key(&self) -> &str { - self.get_id().key() - } -} - -/// Serializes the exam subsystem's cross-record check-then-writes, which -/// `BEGIN…COMMIT` cannot (write skew) — same reasoning as `REGISTER_LOCK`. -/// Read side: the answer saves (REST and the exam room), holding the sheet -/// open from the writable-attempt gate through the upsert, and the grade -/// write (draft gate through the result upsert); these stay concurrent with -/// each other. Write side: attempt starts (the max-attempts count and the -/// retake's answer wipe) and the structural teacher writes whose 409 guards -/// read attempt, question, or result rows first — exam mode/schedule/draft -/// updates, question create/update/delete, subject delete. So a save can -/// never land on a sheet a retake just wiped, a first attempt can never -/// slip between a freeze-gate read and the write it was meant to freeze, -/// and a mark can never land on an exam mid-flight into hiding. -// ponytail: global RwLock, shard per-exam if save latency ever matters. -pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); - -pub fn routes() -> OpenApiRouter { - OpenApiRouter::new() - // Plain route: OpenApiRouter can't describe a WebSocket upgrade, so - // the exam room lives outside the generated spec (see the `exams` tag - // description and README for the protocol). - .route( - "/{id}/attempt/ws", - axum::routing::get(super::exam_ws::attempt_ws), - ) - .routes(routes!(list_exams)) - .routes(routes!(get_exam, update_exam, delete_exam)) - .routes(routes!(grade, list_results)) - .routes(routes!(my_result)) - .routes(routes!(remove_result)) - .routes(routes!(exam_statistics)) - .routes(routes!(start_attempt, my_attempt)) - .routes(routes!(finish_attempt)) - .routes(routes!(exam_live)) - .routes(routes!(create_question, list_questions)) - .routes(routes!(update_question, delete_question)) - .routes(routes!(question_from_bank)) - .routes(routes!(question_to_bank)) - .routes(routes!(question_refresh_from_bank)) - .routes(routes!(attempt_questions)) - .routes(routes!(save_answer)) - .routes(routes!(attempt_answers)) - .routes(routes!(student_attempts)) - .routes(routes!(student_attempt_answers)) - .routes(routes!(student_marks_history)) - .routes(routes!(review_questions)) - .routes(routes!(review_attempts)) - .routes(routes!(review_attempt_answers)) - // The image routes get their own HTTP body cap, like the note-file - // ones: the server-wide hard ceiling plus multipart framing headroom. - .merge( - OpenApiRouter::new() - .routes(routes!( - upload_question_image, - get_question_image, - delete_question_image - )) - .routes(routes!( - upload_choice_image, - get_choice_image, - delete_choice_image - )) - .routes(routes!( - upload_answer_image, - get_answer_image, - delete_answer_image - )) - .routes(routes!(get_student_answer_image)) - .routes(routes!(student_attempt_answer_image)) - .routes(routes!(review_attempt_answer_image)) - .layer(DefaultBodyLimit::max( - MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES, - )), - ) -} - -#[derive(Deserialize, ToSchema)] -struct UpdateExam { - #[schema(max_length = 200)] - title: Option, - #[schema(max_length = 2000)] - description: Option, - /// The assessment form — one of the school's exam kinds (`GET /settings`). - /// Changing it re-weights the exam: the course average uses the kind's - /// settings-configured weight. - kind: Option, - /// `sync`, `async`, or `open`. Omit to keep the current mode; send `null` - /// to turn the exam back into an offline-graded one. Frozen once anyone - /// has started an attempt. Switching to `open` requires clearing - /// `starts_at`/`ends_at` in the same request. - #[serde(default, deserialize_with = "set_or_clear")] - #[schema(value_type = Option)] - mode: Option>, - /// Window open, UTC unix-milliseconds. Omit to keep; `null` to clear. - /// A newly set value must not be in the past. - #[serde(default, deserialize_with = "set_or_clear")] - #[schema(value_type = Option)] - starts_at: Option>, - /// Window close, UTC unix-milliseconds. Omit to keep; `null` to clear. - /// Moving it while a sync exam runs extends (or cuts) everyone's deadline; - /// a newly set value must not be in the past. - #[serde(default, deserialize_with = "set_or_clear")] - #[schema(value_type = Option)] - ends_at: Option>, - /// Per-attempt budget, milliseconds (`async`, or optionally `open`). Omit - /// to keep; `null` to clear. Changing it mid-exam moves every running - /// attempt's deadline. - #[serde(default, deserialize_with = "set_or_clear")] - #[schema(value_type = Option, minimum = 60000, maximum = 86400000)] - duration_ms: Option>, - /// Attempt limit: `1`–`100`, or `0` for unlimited. Omit to keep. Editable - /// live — raising it grants retakes on the spot; lowering it only blocks - /// future starts. - #[schema(minimum = 0, maximum = 100)] - max_attempts: Option, - /// Whether students who left the exam room may come back in. Omit to - /// keep. Editable live — the teacher's door handle for the running room. - allow_rejoin: Option, - /// Whether students may review their graded attempt once results are out. - /// Omit to keep. Editable live. - allow_review: Option, - /// `false` publishes a draft (students can now see and sit it); `true` - /// pulls a published exam back into hiding — allowed only while nobody - /// has attempted it and nothing is graded (`409` otherwise). Omit to keep. - draft: Option, -} - -#[derive(Deserialize, ToSchema)] -struct GradeResult { - /// The mark to record, `0`–`100`. - #[schema(example = 85, minimum = 0, maximum = 100)] - mark: i64, - /// The student being graded. - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] - user_id: String, -} - -#[derive(Serialize, ToSchema)] -struct ExamResultResponse { - id: String, - exam: String, - /// The graded student. - user: PersonRef, - /// Which sitting this mark belongs to (1 = first attempt). Lets the grader - /// jump from a mark to that sitting's answer sheet - /// (`GET /exams/{id}/students/{user}/attempts/{seq}/answers`) — without it - /// a marked retake's answers are unreachable from the mark. - seq: i64, - mark: i64, - /// Who recorded the mark. - graded_by: PersonRef, -} - -impl ExamResultResponse { - fn new(result: &ExamResult, people: &HashMap) -> Self { - Self { - id: result.get_id().key().to_string(), - exam: result.get_exam().key().to_string(), - user: PersonRef::resolve(people, result.get_user()), - seq: result.get_seq(), - mark: result.get_mark().as_i64(), - graded_by: PersonRef::resolve(people, result.get_graded_by()), - } - } -} - -#[derive(Serialize, ToSchema)] -struct ExamStatisticsResponse { - exam: String, - /// Number of graded results. - graded: u64, - /// Plain mean of the graded marks; `null` while nothing is graded. - average: Option, - min: Option, - max: Option, -} - -/// The course an exam belongs to. A dangling reference means the course-delete -/// cascade was violated — surface it loudly as a 500, not a user-facing 404. -async fn course_of(exam: &Exam, db: &Database) -> Result { - Course::read(exam.get_course(), db) - .await? - .ok_or_else(|| AppError::Internal("exam references a missing course".into())) -} - -// ---- exams -------------------------------------------------------------- -// Exams are created inside a course: `POST /courses/{id}/exams`. - -/// List the exams visible to the caller: every exam for manager+, otherwise -/// the exams of the courses they created or are enrolled in — minus other -/// people's drafts (a draft shows only to its course's managers). Paged via -/// `?limit=&offset=` (omit `limit` for the full list); returns a -/// `{items, total, limit, offset}` envelope. -/// -/// The optional `?starts_after=&ends_after=` schedule window (unix -/// milliseconds) applies *after* the visibility and draft filtering, narrows -/// the list to upcoming/unfinished exams and flips the order to ascending by -/// schedule — so `?ends_after=&limit=20` returns the twenty *soonest* -/// exams rather than the twenty newest-created. Exams without a window -/// (no `mode`, or `open`) are excluded by either parameter. -#[utoipa::path( - get, - path = "/", - tag = "exams", - security(("session_cookie" = [])), - params(WindowParams, PageParams), - responses( - (status = 200, description = "A page of the caller's visible exams (all of them when unpaged)", body = Page), - (status = 400, description = "Invalid window, limit, or offset", body = ErrorResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - ), -)] -async fn list_exams( - State(st): State, - CurrentUser(user): CurrentUser, - Query(window): Query, - Query(page): Query, -) -> Result>, AppError> { - let (limit, offset) = page.resolve()?; - let exams = if user.get_role().at_least(Role::Manager) { - Exam::list_all(&st.db).await? - } else { - let courses = visible_courses(&user, &st.db).await?; - let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect(); - // Drafts show only where the caller manages the course (as its - // creator — the manager+ path above already saw everything). - let managed: Vec<&str> = courses - .iter() - .filter(|c| can_manage_course(c, &user)) - .map(|c| c.get_id().key()) - .collect(); - let mut exams = Exam::list_for_courses(&ids, &st.db).await?; - exams.retain(|exam| !exam.is_draft() || managed.contains(&exam.get_course().key())); - exams - }; - let exams = window.apply(exams)?; - let total = exams.len() as i64; - let items = paginate(&exams, limit, offset) - .iter() - .map(ExamResponse::new) - .collect(); - Ok(Json(Page::new(items, total, limit, offset))) -} - -/// Fetch a single exam by id. Visible to its course's enrolled users, the -/// course creator, and managers/admins — except drafts, which only the -/// course's managers see (everyone else gets a `404`, as if the exam doesn't -/// exist yet — because it doesn't, officially). -#[utoipa::path( - get, - path = "/{id}", - tag = "exams", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id")), - responses( - (status = 200, description = "The exam", body = ExamResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not enrolled in the exam's course, not its creator, and not a manager/admin", body = ErrorResponse), - (status = 404, description = "Not found (or a draft the caller may not see)", body = ErrorResponse), - ), -)] -async fn get_exam( - State(st): State, - CurrentUser(user): CurrentUser, - Path(id): Path, -) -> Result, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_view_course(&course, &user, &st.db).await? { - return Err(AppError::Forbidden( - "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this exam", - )); - } - // A draft doesn't exist for anyone but its course's managers — 404, not - // 403, so its existence never leaks to the students it's hidden from. - if exam.is_draft() && !can_manage_course(&course, &user) { - return Err(AppError::NotFound); - } - Ok(Json(ExamResponse::new(&exam))) -} - -/// Update an exam. Requires teacher+ and management rights over the exam's -/// course (its creator, or manager/admin). Omitted fields keep their value; an -/// explicit `null` clears a schedule field; the course itself is not updatable. -/// The schedule must stay consistent as a whole (see the create endpoint), and -/// `mode` is frozen once anyone has started an attempt — times, duration, -/// `max_attempts`, and `allow_rejoin` stay editable so a running exam can be -/// extended, granted retakes, or have its rejoin door opened live. -/// `draft: false` publishes a draft; `draft: true` re-hides an exam, but only -/// while it has no attempts and no results (`409` otherwise) — students never -/// lose sight of an exam they've already sat or been graded on. -#[utoipa::path( - patch, - path = "/{id}", - tag = "exams", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id")), - request_body = UpdateExam, - responses( - (status = 200, description = "Updated exam", body = ExamResponse), - (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), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "Not found", body = ErrorResponse), - (status = 409, description = "Mode change after attempts started, or re-drafting an exam that has attempts or results", body = ErrorResponse), - ), -)] -async fn update_exam( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path(id): Path, - Json(req): Json, -) -> Result, AppError> { - // Take the writer lease before the row read: the merge defaults and the - // mode/draft gates below all judge this snapshot, so a publish or mode - // change landing between an unlocked read and the gates would be silently - // written back over. - let _guard = EXAM_LOCK.write().await; - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, &user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can edit this exam", - )); - } - - let title = match req.title { - Some(ref title) => ExamTitle::try_new(title)?, - None => exam.get_title().clone(), - }; - let description = match req.description { - Some(ref description) => ExamDescription::try_new(description)?, - None => exam.get_description().clone(), - }; - let kind = match req.kind { - // Only a kind this request sets is held to the current settings list — - // a stored kind survives later list edits, like past times survive - // the no-past rule. - Some(ref kind) => { - let school = Settings::load(&st.db).await?; - ExamKind::try_new(kind, school.get_exam_kinds())? - } - None => exam.get_kind().clone(), - }; - - // Merge the schedule (set / clear / keep per field), then re-validate it - // as a unit — a PATCH can't leave a half-schedule behind. Only values this - // request sets are held to the no-past rule: kept ones may legitimately be - // past (a running exam's `starts_at`), and rechecking them would block - // unrelated edits. - let mode = match req.mode { - Some(update) => update.as_deref().map(ExamMode::try_new).transpose()?, - None => exam.get_mode().cloned(), - }; - let starts_at = match req.starts_at { - Some(update) => { - let starts_at = update.map(Timestamp::from_millis); - check_not_past("starts_at", starts_at)?; - starts_at - } - None => exam.get_starts_at(), - }; - let ends_at = match req.ends_at { - Some(update) => { - let ends_at = update.map(Timestamp::from_millis); - check_not_past("ends_at", ends_at)?; - ends_at - } - None => exam.get_ends_at(), - }; - let duration_ms = match req.duration_ms { - Some(update) => update.map(ExamDuration::try_new).transpose()?, - None => exam.get_duration_ms(), - }; - let schedule = ExamSchedule::try_new(mode, starts_at, ends_at, duration_ms)?; - let max_attempts = match req.max_attempts { - Some(limit) => ExamAttemptLimit::try_new(limit)?, - None => exam.get_max_attempts(), - }; - let allow_rejoin = req.allow_rejoin.unwrap_or_else(|| exam.get_allow_rejoin()); - let allow_review = req.allow_review.unwrap_or_else(|| exam.get_allow_review()); - let draft = req.draft.unwrap_or_else(|| exam.is_draft()); - - // Switching sync <-> async <-> open (or back to unscheduled) would - // silently rewrite the deadline rules under students who already sat - // down; extending times, the attempt limit, and the rejoin door are the - // supported live adjustments instead. Gate read and write share the - // handler-wide writer lease of [`EXAM_LOCK`], so a first attempt can't - // land in the gap and leave a sat exam's mode flipped under it. - let mode_changed = - schedule.get_mode().map(ExamMode::as_str) != exam.get_mode().map(ExamMode::as_str); - if mode_changed && ExamAttempt::any_for_exam(exam.get_id(), &st.db).await? { - return Err(AppError::Conflict( - "cannot change the exam mode after attempts have started", - )); - } - // Re-drafting hides the exam — never out from under a student who already - // sat it or holds a mark on it. Same writer lease: a first attempt or an - // in-flight grade (readers) can't slip between this gate and the write. - if draft && !exam.is_draft() { - let sat = ExamAttempt::any_for_exam(exam.get_id(), &st.db).await?; - let graded = !ExamResult::list_for_exam(exam.get_id(), &st.db) - .await? - .is_empty(); - if sat || graded { - return Err(AppError::Conflict( - "cannot turn a published exam back into a draft after attempts or results exist", - )); - } - } - - let updated = exam - .update( - title, - description, - kind, - schedule, - max_attempts, - allow_rejoin, - allow_review, - draft, - &st.db, - ) - .await?; - Ok(Json(ExamResponse::new(&updated))) -} - -/// Delete an exam. Requires teacher+ and management rights over the exam's -/// course (its creator, or manager/admin). Cascades the exam's results, -/// attempts, questions, answers, and question + answer images (blobs included). -#[utoipa::path( - delete, - path = "/{id}", - tag = "exams", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id")), - responses( - (status = 204, description = "Deleted"), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "Not found", body = ErrorResponse), - ), -)] -async fn delete_exam( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path(id): Path, -) -> Result { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, &user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can delete this exam", - )); - } - // Rows go first (the delete cascades them), blobs after — a crash in - // between strands at worst an unreachable blob. - let images = QuestionImage::list_for_exam(exam.get_id(), &st.db).await?; - let answer_images = AnswerImage::list_for_exam(exam.get_id(), &st.db).await?; - exam.delete(&st.db).await?; - for image in &images { - remove_blob(&st.files_path, image.get_file()).await; - } - for image in &answer_images { - remove_blob(&st.files_path, image.get_file()).await; - } - Ok(StatusCode::NO_CONTENT) -} - -// ---- results ------------------------------------------------------------ - -/// Record (or overwrite) a student's mark for an exam. Requires teacher+ and -/// management rights over the exam's course; the target must be a student and -/// enrolled. Only students carry marks; students never grade — and nobody -/// grades themselves. A draft can't be graded (`409`) — a mark would point at -/// an exam its student can't see. -#[utoipa::path( - post, - path = "/{id}/results", - tag = "exams", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id")), - request_body = GradeResult, - responses( - (status = 200, description = "Result recorded", body = ExamResultResponse), - (status = 400, description = "Invalid mark, unknown user, user not a student, or not enrolled", body = ErrorResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse), - (status = 404, description = "Exam not found", body = ErrorResponse), - (status = 409, description = "The exam is a draft", body = ErrorResponse), - ), -)] -async fn grade( - State(st): State, - RequireTeacher(teacher): RequireTeacher, - Path(id): Path, - Json(req): Json, -) -> Result, AppError> { - let exam_id = ExamId::from_key(&id); - // Reader lease of [`EXAM_LOCK`] from the exam read through the result - // write: the draft gate below must be judged against the same row the - // mark lands under, or a concurrent re-draft (a writer, which checks for - // results) could slip between them and leave a mark on a hidden exam. - let _guard = EXAM_LOCK.read().await; - // Exam must exist. - let exam = Exam::read(&exam_id, &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, &teacher) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can grade this exam", - )); - } - if exam.is_draft() { - return Err(AppError::Conflict( - "this exam is a draft — publish it before grading", - )); - } - - let mark = Mark::try_new(req.mark)?; - let target = UserId::from_key(&req.user_id); - - // Grading never targets oneself — no grader, whatever their role, may - // write their own mark. - if &target == teacher.get_id() { - return Err(AppError::Forbidden("grading yourself is not allowed")); - } - - // Target user must exist. - let Some(target_user) = User::read(&target, &st.db).await? else { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user_id", - reason: "target user does not exist", - })); - }; - - // Only students carry marks — the grade system is theirs alone. A stale - // enrollment left behind by a promotion can't reopen grading for staff. - if target_user.get_role() != Role::Student { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user_id", - reason: "only students can be graded", - })); - } - - // ... and be enrolled in the exam's course. - if Enrollment::read_for_user(exam.get_course(), &target, &st.db) - .await? - .is_none() - { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user_id", - reason: "target user is not enrolled in this course", - })); - } - - // The mark lands on the student's current sitting; the latest seq is the - // grade-of-record. An offline-graded exam has no sitting — grade its base - // seq (1). - let seq = ExamAttempt::read_latest_for_user(&exam_id, &target, &st.db) - .await? - .map_or(1, |a| a.get_seq()); - let result = ExamResult::grade(&exam_id, &target, seq, mark, teacher.get_id(), &st.db).await?; - let people = PersonRef::map_of(&[&target_user, &teacher]); - Ok(Json(ExamResultResponse::new(&result, &people))) -} - -/// List an exam's results, paged via `?limit=&offset=` (omit `limit` for all -/// of them). Requires teacher+ and management rights over the exam's course — -/// students read only their own via `GET /exams/{id}/result`. Returns a -/// `{items, total, limit, offset}` envelope. -#[utoipa::path( - get, - path = "/{id}/results", - tag = "exams", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id"), PageParams), - responses( - (status = 200, description = "A page of results (all of them when unpaged)", body = Page), - (status = 400, description = "Invalid limit or offset", body = ErrorResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "Exam not found", body = ErrorResponse), - ), -)] -async fn list_results( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path(id): Path, - Query(page): Query, -) -> Result>, AppError> { - let (limit, offset) = page.resolve()?; - // Exam must exist — a missing exam is a 404, not an empty result list. - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, &user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can list results", - )); - } - let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?; - let total = results.len() as i64; - // Join people onto the page alone — the lookup shrinks with the window. - let rows = paginate(&results, limit, offset); - let people = person_map( - rows.iter() - .flat_map(|r| [r.get_user().clone(), r.get_graded_by().clone()]), - &st.db, - ) - .await?; - let items = rows - .iter() - .map(|r| ExamResultResponse::new(r, &people)) - .collect(); - Ok(Json(Page::new(items, total, limit, offset))) -} - -/// The current user's own result for an exam. Any authenticated user may read -/// their own mark; `404` while ungraded (or when the exam doesn't exist). -#[utoipa::path( - get, - path = "/{id}/result", - tag = "exams", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id")), - responses( - (status = 200, description = "The caller's result", body = ExamResultResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 404, description = "No such exam, or not graded yet", body = ErrorResponse), - ), -)] -async fn my_result( - State(st): State, - CurrentUser(user): CurrentUser, - Path(id): Path, -) -> Result, AppError> { - let result = ExamResult::read_for_user(&ExamId::from_key(&id), user.get_id(), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let people = person_map( - [result.get_user().clone(), result.get_graded_by().clone()], - &st.db, - ) - .await?; - Ok(Json(ExamResultResponse::new(&result, &people))) -} - -/// Remove a student's result from an exam. Requires teacher+ and management -/// rights over the exam's course. -#[utoipa::path( - delete, - path = "/{id}/results/{user}", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("user" = String, Path, description = "User id"), - ), - responses( - (status = 204, description = "Removed"), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "Not found", body = ErrorResponse), - ), -)] -async fn remove_result( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path((id, target)): Path<(String, String)>, -) -> Result { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, &user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can remove results", - )); - } - let removed = ExamResult::remove(exam.get_id(), &UserId::from_key(&target), &st.db).await?; - if removed.is_none() { - return Err(AppError::NotFound); - } - Ok(StatusCode::NO_CONTENT) -} - -/// Summary statistics for an exam's graded results. Requires teacher+ and -/// management rights over the exam's course. -#[utoipa::path( - get, - path = "/{id}/statistics", - tag = "exams", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id")), - responses( - (status = 200, description = "The exam's mark statistics", body = ExamStatisticsResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "Exam not found", body = ErrorResponse), - ), -)] -async fn exam_statistics( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path(id): Path, -) -> Result, AppError> { - // Exam must exist — a missing exam is a 404, not an empty statistic. - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, &user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can view statistics", - )); - } - let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?; - - let marks: Vec = results.iter().map(|r| r.get_mark().as_i64()).collect(); - let average = - (!marks.is_empty()).then(|| marks.iter().sum::() as f64 / marks.len() as f64); - Ok(Json(ExamStatisticsResponse { - exam: exam.get_id().key().to_string(), - graded: marks.len() as u64, - average, - min: marks.iter().min().copied(), - max: marks.iter().max().copied(), - })) -} - -// ---- attempts ------------------------------------------------------------- -// A sittable exam (sync, async, or open mode) is *sat*: starting an attempt -// is the live-attendance signal, finishing is the submission. The exam's -// `max_attempts` (0 = unlimited) says how many sittings each student gets; -// re-posting resumes a running attempt and mints the next sitting once the -// last one is over. Deadlines are judged only by the server clock — clients -// sync via `GET /time`. - -/// A student's view of their (latest) attempt. `now` is echoed so clients can -/// render countdowns without trusting the device clock. -#[derive(Serialize, ToSchema)] -struct AttemptResponse { - id: String, - exam: String, - user: PersonRef, - /// Which sitting this is — 1 for the first attempt, counting up. - attempt: i64, - /// How many sittings the caller has used, this one included. - attempts_used: u64, - /// The exam's attempt limit; `0` means unlimited. - max_attempts: i64, - /// When the attempt started, UTC unix-milliseconds. - started_at: i64, - /// Submission instant; `null` while running (or expired unsubmitted). - finished_at: Option, - /// When the student left the exam room mid-attempt; `null` while inside - /// (or if they never used the room). With `allow_rejoin` off, a set - /// `left_at` locks further answering until the teacher reopens the door. - left_at: Option, - /// `in_progress` | `submitted` | `expired`. - #[schema(example = "in_progress")] - status: String, - /// When the attempt closes: the earlier of the window's `ends_at` and - /// `started_at + duration_ms` (whichever exists). Recomputed live from - /// the exam's current schedule; `null` for an open exam without a - /// duration — such an attempt only ends by submission. - deadline: Option, - /// `deadline - now`, floored at 0; `null` unless in progress with a - /// deadline. - remaining_ms: Option, - /// The caller's mark, once graded. - mark: Option, - /// How many questions the caller has answered so far. - answered: u64, - /// How many questions the exam has. - question_count: u64, - /// Server clock at response time, UTC unix-milliseconds. - now: i64, -} - -impl AttemptResponse { - #[expect( - clippy::too_many_arguments, - reason = "a flat view over attempt + exam + progress; a builder would obscure it" - )] - fn new( - attempt: &ExamAttempt, - exam: &Exam, - mark: Option, - people: &HashMap, - answered: u64, - question_count: u64, - attempts_used: u64, - now: Timestamp, - ) -> Self { - let status = attempt.status(exam, now); - let deadline = attempt.deadline(exam); - let remaining_ms = (status == AttemptStatus::InProgress) - .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0))) - .flatten(); - Self { - id: attempt.get_id().key().to_string(), - exam: attempt.get_exam().key().to_string(), - user: PersonRef::resolve(people, attempt.get_user()), - attempt: attempt.get_seq(), - attempts_used, - max_attempts: exam.get_max_attempts().as_i64(), - started_at: attempt.get_started_at().as_millis(), - finished_at: attempt.get_finished_at().map(|t| t.as_millis()), - left_at: attempt.get_left_at().map(|t| t.as_millis()), - status: status.as_str().to_string(), - deadline: deadline.map(|t| t.as_millis()), - remaining_ms, - mark: mark.map(|m| m.as_i64()), - answered, - question_count, - now: now.as_millis(), - } - } -} - -/// The (answered, question_count) pair behind an attempt view — how far one -/// student has come through the exam's question list. -async fn attempt_progress( - exam: &ExamId, - user: &UserId, - seq: i64, - db: &Database, -) -> Result<(u64, u64), AppError> { - let answered = ExamAnswer::list_for_exam_user(exam, user, seq, db) - .await? - .len() as u64; - let question_count = ExamQuestion::list_for_exam(exam, db).await?.len() as u64; - Ok((answered, question_count)) -} - -/// Rejects sitting an exam that can't be sat. A draft is a `404`, not a -/// `409` — sitting is a student act, drafts are invisible to students, and a -/// state-specific error would leak the existence this feature hides. A -/// modeless (offline-graded) exam is a `409`: visible, just nothing to sit. -/// Enrollment and window checks for the caller are the caller's own state — -/// also `Conflict`, not validation. -pub(crate) fn ensure_sittable(exam: &Exam) -> Result<(), AppError> { - if exam.is_draft() { - return Err(AppError::NotFound); - } - if exam.get_mode().is_none() { - return Err(AppError::Conflict( - "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)", - )); - } - Ok(()) -} - -/// How many sittings the caller has used at this exam. -async fn attempts_used(exam: &ExamId, user: &UserId, db: &Database) -> Result { - Ok(ExamAttempt::list_for_user(exam, user, db).await?.len() as u64) -} - -/// Start, resume, or retake the caller's attempt. Requires the student role -/// (staff run exams, they don't sit them), enrollment in the exam's course, a -/// sittable exam (`sync`/`async`/`open` mode), and — when a window exists — the -/// window to be open. A still-running attempt is returned -/// as-is (`200` instead of `201`), so a reconnecting client gets its original -/// clock back — re-starting never resets the time. Once the latest attempt is -/// submitted or expired, re-posting starts the next sitting (`201`, blank -/// answer sheet) while the exam's `max_attempts` (0 = unlimited) allows it. -#[utoipa::path( - post, - path = "/{id}/attempt", - tag = "exams", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id")), - responses( - (status = 201, description = "Attempt started (first sitting or a retake)", body = AttemptResponse), - (status = 200, description = "Running attempt resumed (unchanged)", body = AttemptResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), - (status = 404, description = "Exam not found (drafts are invisible here)", body = ErrorResponse), - (status = 409, description = "Unscheduled (offline-graded) exam, outside the window, or no attempts remaining", body = ErrorResponse), - ), -)] -async fn start_attempt( - State(st): State, - CurrentUser(user): CurrentUser, - Path(id): Path, -) -> Result<(StatusCode, Json), AppError> { - // Writer lease of [`EXAM_LOCK`] from the exam read through the start: the - // sittable/window gates must be judged against the same exam row the - // attempt lands under (the mirror of `update_exam`'s re-derive — without - // it, a mode change or re-draft at legally-zero attempts could slip - // between this gate and the insert, leaving an attempt on an unsittable - // exam). The lease - // also keeps the max-attempts count and the retake's wipe-and-create - // from interleaving with an in-flight answer save (a reader). Dropped - // before the response reads — they only describe the row. - let guard = EXAM_LOCK.write().await; - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - ensure_sittable(&exam)?; - ensure_student(&user)?; - ensure_enrolled(&exam, user.get_id(), &st.db).await?; - let now = Timestamp::now(); - if let Some(starts_at) = exam.get_starts_at() - && now < starts_at - { - return Err(AppError::Conflict("the exam has not started yet")); - } - if let Some(ends_at) = exam.get_ends_at() - && now >= ends_at - { - return Err(AppError::Conflict("the exam has already ended")); - } - - // A retake no longer wipes the prior sitting — each attempt's answers, - // drawings, and marks stay put at their own seq (per-attempt history), so - // there are no orphaned blobs to GC here. The exam-delete cascade still - // cleans every sitting's blobs. - let (attempt, created) = ExamAttempt::start(&exam, user.get_id(), &st.db).await?; - drop(guard); - let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) - .await? - .map(|r| r.get_mark()); - let (answered, question_count) = - attempt_progress(exam.get_id(), user.get_id(), attempt.get_seq(), &st.db).await?; - let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?; - let people = PersonRef::map_of(&[&user]); - let status = if created { - StatusCode::CREATED - } else { - StatusCode::OK - }; - Ok(( - status, - Json(AttemptResponse::new( - &attempt, - &exam, - mark, - &people, - answered, - question_count, - used, - Timestamp::now(), - )), - )) -} - -/// The caller's own (latest) attempt: status, deadline, remaining time, and -/// mark once graded — everything a student's live exam screen needs, judged -/// by the server clock. `404` until an attempt is started. -#[utoipa::path( - get, - path = "/{id}/attempt", - tag = "exams", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id")), - responses( - (status = 200, description = "The caller's latest attempt", body = AttemptResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 404, description = "No such exam, or no attempt yet", body = ErrorResponse), - ), -)] -async fn my_attempt( - State(st): State, - CurrentUser(user): CurrentUser, - Path(id): Path, -) -> Result, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) - .await? - .map(|r| r.get_mark()); - let (answered, question_count) = - attempt_progress(exam.get_id(), user.get_id(), attempt.get_seq(), &st.db).await?; - let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?; - let people = PersonRef::map_of(&[&user]); - Ok(Json(AttemptResponse::new( - &attempt, - &exam, - mark, - &people, - answered, - question_count, - used, - Timestamp::now(), - ))) -} - -/// Submit the caller's attempt. Allowed while the deadline hasn't passed; -/// after it, the attempt is already `expired` (a valid terminal state — the -/// student used their full time) and submitting is a `409`. -#[utoipa::path( - post, - path = "/{id}/attempt/finish", - tag = "exams", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id")), - responses( - (status = 200, description = "Attempt submitted", body = AttemptResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 404, description = "No such exam, or no attempt to finish", body = ErrorResponse), - (status = 409, description = "Already submitted, or the deadline passed", body = ErrorResponse), - ), -)] -async fn finish_attempt( - State(st): State, - CurrentUser(user): CurrentUser, - Path(id): Path, -) -> Result, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) - .await? - .ok_or(AppError::NotFound)?; - if attempt.get_finished_at().is_some() { - return Err(AppError::Conflict("the attempt is already submitted")); - } - let now = Timestamp::now(); - if let Some(deadline) = attempt.deadline(&exam) - && now >= deadline - { - return Err(AppError::Conflict("time is up — the attempt has expired")); - } - - // Deliberately no rejoin check: a student locked out of the room may - // still submit what they saved — finishing answers nothing new. - let finished = attempt.finish(&st.db).await?; - let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) - .await? - .map(|r| r.get_mark()); - let (answered, question_count) = - attempt_progress(exam.get_id(), user.get_id(), finished.get_seq(), &st.db).await?; - let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?; - let people = PersonRef::map_of(&[&user]); - Ok(Json(AttemptResponse::new( - &finished, - &exam, - mark, - &people, - answered, - question_count, - used, - Timestamp::now(), - ))) -} - -// ---- live monitor --------------------------------------------------------- - -/// One roster row of the live exam monitor. The attempt fields describe the -/// student's *latest* sitting. -#[derive(Serialize, ToSchema)] -struct LiveStudentResponse { - user: PersonRef, - /// `not_started` | `absent` | `in_progress` | `submitted` | `expired`. - /// `absent` is `not_started` after the window closed: the student never - /// sat and no longer can. Open exams have no window, so nobody is ever - /// absent from one. - #[schema(example = "in_progress")] - status: String, - /// Which sitting the shown attempt is (1, 2, …); `null` before the first. - attempt: Option, - /// How many sittings this student has used. - attempts_used: u64, - started_at: Option, - finished_at: Option, - /// When this student left the exam room mid-attempt; `null` while inside. - left_at: Option, - /// When this student's attempt closes (server-authoritative). - deadline: Option, - /// Time this student has left, floored at 0; `null` unless in progress. - remaining_ms: Option, - /// The student's mark, once graded. - mark: Option, - /// How many questions this student has answered so far. - answered: u64, - /// When this student last saved an answer, UTC unix-milliseconds; `null` - /// before the first save. - last_activity: Option, -} - -#[derive(Serialize, ToSchema)] -struct LiveCountsResponse { - enrolled: u64, - /// Enrolled with no attempt while the window is still open (or the exam - /// has no window). - not_started: u64, - /// Enrolled with no attempt and the window closed — the no-shows. - absent: u64, - in_progress: u64, - submitted: u64, - expired: u64, - graded: u64, -} - -/// A live snapshot of an exam: the enrolled roster with per-student attempt -/// state, remaining time, and marks, all judged by one server-clock read. -#[derive(Serialize, ToSchema)] -struct ExamLiveResponse { - exam: ExamResponse, - /// Server clock the snapshot was judged at, UTC unix-milliseconds. - now: i64, - /// How many questions the exam has. - question_count: u64, - counts: LiveCountsResponse, - students: Vec, -} - -/// Build the monitor snapshot: roster ⋈ attempts ⋈ marks at one instant. -/// Students unenrolled mid-exam drop off the roster view (their attempt and -/// mark rows survive, exactly like the marks report). -async fn live_snapshot(exam: &Exam, db: &Database) -> Result { - let now = Timestamp::now(); - let roster = Enrollment::list_for_course(exam.get_course(), db).await?; - // Per student: their latest sitting (the one the monitor shows) plus how - // many they've used. - let mut attempts: HashMap = HashMap::new(); - let mut used: HashMap = HashMap::new(); - for attempt in ExamAttempt::list_for_exam(exam.get_id(), db).await? { - let key = attempt.get_user().key().to_string(); - *used.entry(key.clone()).or_insert(0) += 1; - match attempts.entry(key) { - std::collections::hash_map::Entry::Vacant(slot) => { - slot.insert(attempt); - } - std::collections::hash_map::Entry::Occupied(mut slot) => { - if attempt.get_seq() > slot.get().get_seq() { - slot.insert(attempt); - } - } - } - } - let marks: HashMap = ExamResult::list_for_exam(exam.get_id(), db) - .await? - .iter() - .map(|result| { - ( - result.get_user().key().to_string(), - result.get_mark().as_i64(), - ) - }) - .collect(); - let question_count = ExamQuestion::list_for_exam(exam.get_id(), db).await?.len() as u64; - // Per-student progress: answer count and the latest save instant. The - // per-exam read now returns every sitting's rows across all students, so - // each answer is scoped to that student's *current* sitting — matching its - // seq to their latest attempt — or a re-sitting student's count would - // double up their prior attempts. - let mut progress: HashMap = HashMap::new(); - for answer in ExamAnswer::list_for_exam(exam.get_id(), db).await? { - let key = answer.get_user().key().to_string(); - if attempts.get(&key).map(ExamAttempt::get_seq) != Some(answer.get_seq()) { - continue; - } - let entry = progress.entry(key).or_insert((0, i64::MIN)); - entry.0 += 1; - entry.1 = entry.1.max(answer.get_updated_at().as_millis()); - } - let people = person_map(roster.iter().map(|e| e.get_user().clone()), db).await?; - - // Once the window closes the door is shut for good (starting answers - // 409), so "hasn't started" hardens into "was absent". Open exams have - // no window and never make that call. - let window_over = exam.get_ends_at().is_some_and(|ends| now >= ends); - let mut students: Vec = roster - .iter() - .map(|enrollment| { - let key = enrollment.get_user().key(); - let attempt = attempts.get(key); - let status = attempt.map(|a| a.status(exam, now)); - let deadline = attempt.and_then(|a| a.deadline(exam)); - LiveStudentResponse { - user: PersonRef::resolve(&people, enrollment.get_user()), - status: match status { - Some(status) => status.as_str(), - None if window_over => "absent", - None => "not_started", - } - .to_string(), - attempt: attempt.map(ExamAttempt::get_seq), - attempts_used: used.get(key).copied().unwrap_or(0), - started_at: attempt.map(|a| a.get_started_at().as_millis()), - finished_at: attempt - .and_then(|a| a.get_finished_at()) - .map(|t| t.as_millis()), - left_at: attempt.and_then(|a| a.get_left_at()).map(|t| t.as_millis()), - deadline: deadline.map(|t| t.as_millis()), - remaining_ms: (status == Some(AttemptStatus::InProgress)) - .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0))) - .flatten(), - mark: marks.get(key).copied(), - answered: progress.get(key).map_or(0, |p| p.0), - last_activity: progress.get(key).map(|p| p.1), - } - }) - .collect(); - students.sort_by(|a, b| a.user.username.cmp(&b.user.username)); - - let count = |status: &str| students.iter().filter(|s| s.status == status).count() as u64; - let counts = LiveCountsResponse { - enrolled: students.len() as u64, - not_started: count("not_started"), - absent: count("absent"), - in_progress: count("in_progress"), - submitted: count("submitted"), - expired: count("expired"), - graded: students.iter().filter(|s| s.mark.is_some()).count() as u64, - }; - Ok(ExamLiveResponse { - exam: ExamResponse::new(exam), - now: now.as_millis(), - question_count, - counts, - students, - }) -} - -/// A one-shot live snapshot of the exam: who's in, who's still writing (and -/// on which sitting), who walked out of the room (`left_at`), who never -/// showed at all (`absent`, once the window is over), time each student has -/// left, and marks as they land. Requires teacher+ and management rights -/// over the exam's course. Poll it to keep a monitor up to date. -#[utoipa::path( - get, - path = "/{id}/live", - tag = "exams", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id")), - responses( - (status = 200, description = "Live snapshot", body = ExamLiveResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "Exam not found", body = ErrorResponse), - ), -)] -async fn exam_live( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path(id): Path, -) -> Result, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, &user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can monitor this exam", - )); - } - Ok(Json(live_snapshot(&exam, &st.db).await?)) -} - -// ---- questions -------------------------------------------------------------- -// Teachers author the question list before the exam runs; it freezes the -// moment anyone starts an attempt, so every student sits the same exam. - -#[derive(Deserialize, ToSchema)] -struct CreateQuestion { - /// The subject this question belongs to — one of the exam's course's - /// subjects (`GET /courses/{id}/subjects`). Required. - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] - subject_id: String, - /// The question itself. - #[schema(example = "What is 2 + 2?", max_length = 2000)] - text: String, - /// `choice` or `text`. - #[schema(example = "choice")] - kind: String, - /// This question's share of the auto-score, `1`–`100`. - #[schema(example = 10, minimum = 1, maximum = 100)] - points: i64, - /// The options of a `choice` question (2–10 of them); omit for `text`. - /// Each carries an `id` naming it within this payload — the server mints - /// the stored ids and returns them. - #[schema(min_items = 2, max_items = 10)] - choices: Option>, - /// The `id` of the right option, as sent in `choices`; required for - /// `choice`, absent for `text`. - #[schema(example = "b")] - correct: Option, -} - -#[derive(Deserialize, ToSchema)] -struct UpdateQuestion { - /// Re-tag the question with another of the course's subjects. Omit to - /// keep the current one — a question always has a subject, so there is no - /// clearing it. - subject_id: Option, - #[schema(max_length = 2000)] - text: Option, - #[schema(minimum = 1, maximum = 100)] - points: Option, - /// `choice` or `text`. Switching kinds needs the other fields to follow: - /// send `choices` + `correct` when moving to `choice`, explicit `null`s - /// when moving to `text`. - kind: Option, - /// Omit to keep the stored options; send `null` to drop them (text - /// questions only). Send each option back with the `id` it was returned - /// with to keep it — its picture rides along. Only options whose id is - /// absent from the new list lose their picture, so reordering, renaming, - /// and deleting one option leave the rest untouched. - #[serde(default, deserialize_with = "set_or_clear")] - #[schema(value_type = Option>, min_items = 2, max_items = 10)] - choices: Option>>, - /// The `id` of the right option. Omit to keep; `null` to clear (text - /// questions only). - #[serde(default, deserialize_with = "set_or_clear")] - #[schema(value_type = Option)] - correct: Option>, -} - -/// A stored question image's metadata; the bytes come from the image -/// endpoints (`GET .../image`, `GET .../choices/{choice_id}/image`). -#[derive(Serialize, ToSchema)] -struct ImageMetaResponse { - /// MIME type as declared on upload (always one of the raster allowlist). - #[schema(example = "image/png")] - content_type: String, - /// Image size in bytes. - #[schema(example = 24_576)] - size: i64, -} - -impl ImageMetaResponse { - fn new(image: &QuestionImage) -> Self { - Self { - content_type: image.get_content_type().as_str().to_string(), - size: image.get_size(), - } - } - - fn from_answer(image: &AnswerImage) -> Self { - Self { - content_type: image.get_content_type().as_str().to_string(), - size: image.get_size(), - } - } -} - -/// The question's slot out of its image rows. -fn image_meta(images: &[QuestionImage], slot: Option<&ChoiceId>) -> Option { - images - .iter() - .find(|image| image.get_slot() == slot) - .map(ImageMetaResponse::new) -} - -/// The per-choice metas, aligned position-for-position with `choices` (`None` -/// entries = that option has no picture); `None` whole for text questions. -/// A response-only projection: the pictures are *stored* against choice ids, so -/// this alignment is rebuilt from the current list on every read and can never -/// go stale. -fn choice_image_metas( - question: &ExamQuestion, - images: &[QuestionImage], -) -> Option>> { - question.get_choices().map(|choices| { - choices - .iter() - .map(|choice| image_meta(images, Some(choice.get_id()))) - .collect() - }) -} - -/// `exam`'s image rows bucketed by question key — one query feeding a whole -/// question list. -async fn images_by_question( - exam: &ExamId, - db: &Database, -) -> Result>, AppError> { - let mut buckets: HashMap> = HashMap::new(); - for image in QuestionImage::list_for_exam(exam, db).await? { - buckets - .entry(image.get_question().key().to_string()) - .or_default() - .push(image); - } - Ok(buckets) -} - -/// One option on the wire: its stable id and its text. Carries **no** answer -/// key — `correct` is a sibling field on the question, and only on the -/// author-facing DTO, so a student response cannot contain one by construction. -#[derive(Serialize, ToSchema)] -pub(crate) struct ChoiceResponse { - /// Send this back in a PATCH to keep the option (and its picture). - id: String, - text: String, -} - -impl ChoiceResponse { - pub(crate) fn list(choices: Option<&[Choice]>) -> Option> { - choices.map(|choices| { - choices - .iter() - .map(|choice| Self { - id: choice.get_id().as_str().to_string(), - text: choice.get_text().as_str().to_string(), - }) - .collect() - }) - } -} - -/// A question as its author sees it — including the `correct` option. Never -/// serialized to students; they get [`AttemptQuestionResponse`]. -#[derive(Serialize, ToSchema)] -struct QuestionResponse { - id: String, - exam: String, - /// The subject this question belongs to (`GET /subjects/{id}`). - subject: String, - text: String, - /// `choice` or `text`. - #[schema(example = "choice")] - kind: String, - points: i64, - /// The options with their stable ids (`choice` questions only). - choices: Option>, - /// The id of the right option (`choice` questions only). - correct: Option, - /// The question's illustration, if one was uploaded (any kind). - image: Option, - /// Per-option pictures, aligned with `choices` (`choice` questions only). - choice_images: Option>>, - /// The bank template this question was created from, if it was added out of - /// the bank (`GET /bank-questions/{id}`). - from_bank: Option, - /// The bank template most recently created by saving this question into the - /// bank, if any — set only by `POST …/questions/{qid}/to-bank`. Null on a - /// question that came *from* the bank and was never saved back. - banked_as: Option, -} - -impl QuestionResponse { - fn new(question: &ExamQuestion, images: &[QuestionImage]) -> Self { - Self { - id: question.get_id().key().to_string(), - exam: question.get_exam().key().to_string(), - subject: question.get_subject().key().to_string(), - text: question.get_text().as_str().to_string(), - kind: question.get_kind().as_str().to_string(), - points: question.get_points().as_i64(), - choices: ChoiceResponse::list(question.get_choices()), - correct: question.get_correct().map(|id| id.as_str().to_string()), - image: image_meta(images, None), - choice_images: choice_image_metas(question, images), - from_bank: question.get_from_bank().map(|b| b.key().to_string()), - banked_as: question.get_banked_as().map(|b| b.key().to_string()), - } - } -} - -/// The questions freeze once anyone has started an attempt — editing them -/// under a student mid-exam would fork what "the exam" means. -async fn ensure_questions_editable(exam: &ExamId, db: &Database) -> Result<(), AppError> { - if ExamAttempt::any_for_exam(exam, db).await? { - return Err(AppError::Conflict( - "cannot change questions after attempts have started", - )); - } - Ok(()) -} - -/// The question, provided it belongs to `exam` — a qid under someone else's -/// exam is a plain 404, not a leak. -async fn question_of_exam( - exam: &ExamId, - qid: &str, - db: &Database, -) -> Result { - let question = ExamQuestion::read(&ExamQuestionId::from_key(qid), db) - .await? - .ok_or(AppError::NotFound)?; - if question.get_exam() != exam { - return Err(AppError::NotFound); - } - Ok(question) -} - -/// The question's option named by `choice_id` — a 400 for a text question or an -/// id the question doesn't have, so an option picture can only ever be -/// addressed through an option that exists. -fn choice_slot(question: &ExamQuestion, choice_id: &str) -> Result { - let Some(choices) = question.get_choices() else { - return Err(AppError::Validation(ValidationError::Invalid { - field: "choice_id", - reason: "only choice questions take option pictures", - })); - }; - choices - .iter() - .find(|choice| choice.get_id().as_str() == choice_id) - .map(|choice| choice.get_id().clone()) - .ok_or(AppError::Validation(ValidationError::Invalid { - field: "choice_id", - reason: "must name one of the choices", - })) -} - -/// Add a question to an exam. Requires teacher+ and management rights over the -/// exam's course. `subject_id` must name one of the course's subjects -/// (`GET /courses/{id}/subjects`) — every question belongs to a subject. -/// `choice` questions carry 2–10 `choices` plus `correct` naming one of them by id; `text` -/// questions carry neither. Locked once attempts exist. -#[utoipa::path( - post, - path = "/{id}/questions", - tag = "exams", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id")), - request_body = CreateQuestion, - responses( - (status = 201, description = "Question created", body = QuestionResponse), - (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "Exam not found", body = ErrorResponse), - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), - ), -)] -async fn create_question( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path(id): Path, - Json(req): Json, -) -> Result<(StatusCode, Json), AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, &user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can author questions", - )); - } - // Writer lease of [`EXAM_LOCK`]: the freeze gate, the subject check, and - // the create are one unit — no first attempt can slip past the gate, and - // no subject delete can invalidate a subject this just validated. - let _guard = EXAM_LOCK.write().await; - ensure_questions_editable(exam.get_id(), &st.db).await?; - - let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; - let text = QuestionText::try_new(&req.text)?; - let points = QuestionPoints::try_new(req.points)?; - // No stored choices to match against on create, so every option is new and - // every id is minted here. - let spec = QuestionSpec::try_new( - QuestionKind::try_new(&req.kind)?, - ChoiceBody::into_inputs(req.choices), - req.correct, - &[], - )?; - let question = ExamQuestion::create(exam.get_id(), subject, text, points, spec, &st.db).await?; - // A question is born imageless — uploads come after, against its id. - Ok(( - StatusCode::CREATED, - Json(QuestionResponse::new(&question, &[])), - )) -} - -/// The exam's question list, `correct` choice ids included — the answer key, -/// paged via `?limit=&offset=` (omit `limit` for the whole list). Requires -/// teacher+ and management rights over the exam's course. Students read -/// questions through `GET /exams/{id}/attempt/questions`. Returns a -/// `{items, total, limit, offset}` envelope. -#[utoipa::path( - get, - path = "/{id}/questions", - tag = "exams", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id"), PageParams), - responses( - (status = 200, description = "A page of the exam's questions (all of them when unpaged)", body = Page), - (status = 400, description = "Invalid limit or offset", body = ErrorResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "Exam not found", body = ErrorResponse), - ), -)] -async fn list_questions( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path(id): Path, - Query(page): Query, -) -> Result>, AppError> { - let (limit, offset) = page.resolve()?; - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, &user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can read the question list", - )); - } - Ok(Json(question_page(&exam, limit, offset, &st.db).await?)) -} - -/// The paged answer-key list (`correct` included) shared by the teacher -/// `list_questions` read and the student `review_questions` read — the two -/// differ only in the access wall they run first. -async fn question_page( - exam: &Exam, - limit: Option, - offset: i64, - db: &Database, -) -> Result, AppError> { - let questions = ExamQuestion::list_for_exam(exam.get_id(), db).await?; - let images = images_by_question(exam.get_id(), db).await?; - let total = questions.len() as i64; - let items = paginate(&questions, limit, offset) - .iter() - .map(|question| { - QuestionResponse::new( - question, - images - .get(question.get_id().key()) - .map_or(&[][..], Vec::as_slice), - ) - }) - .collect(); - Ok(Page::new(items, total, limit, offset)) -} - -/// Edit a question. Requires teacher+ and management rights over the exam's -/// course. Omitted fields keep their value; `kind`/`choices`/`correct` are -/// re-validated as a unit, so a kind switch must bring the matching fields -/// along. `subject_id` re-tags within the course's subjects. Locked once -/// attempts exist. -#[utoipa::path( - patch, - path = "/{id}/questions/{qid}", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("qid" = String, Path, description = "Question id"), - ), - request_body = UpdateQuestion, - responses( - (status = 200, description = "Updated question", body = QuestionResponse), - (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), - ), -)] -async fn update_question( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path((id, qid)): Path<(String, String)>, - Json(req): Json, -) -> Result, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, &user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can edit questions", - )); - } - // Writer lease of [`EXAM_LOCK`]: the freeze gate, the subject check, and - // the update are one unit — see `create_question`. - let _guard = EXAM_LOCK.write().await; - ensure_questions_editable(exam.get_id(), &st.db).await?; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - - let subject = match req.subject_id { - Some(ref subject_id) => subject_in_course(subject_id, course.get_id(), &st.db).await?, - None => question.get_subject().clone(), - }; - let text = match req.text { - Some(ref text) => QuestionText::try_new(text)?, - None => question.get_text().clone(), - }; - let points = match req.points { - Some(points) => QuestionPoints::try_new(points)?, - None => question.get_points(), - }; - // Merge the kind-dependent fields (set / clear / keep per field), then - // re-validate them as a unit — a PATCH can't leave a half-question behind. - let kind = match req.kind { - Some(ref kind) => QuestionKind::try_new(kind)?, - None => question.get_kind().clone(), - }; - // Omitting `choices` re-submits the stored options *with their ids*, so a - // text-only edit keeps every identity (and every picture) untouched. - let choices = match req.choices { - Some(update) => ChoiceBody::into_inputs(update), - None => ChoiceBody::from_stored(question.get_choices()), - }; - let correct = match req.correct { - Some(update) => update, - None => question.get_correct().map(|id| id.as_str().to_string()), - }; - let stored: Vec = question.get_choices().unwrap_or_default().to_vec(); - let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?; - - let updated = question.update(subject, text, points, spec, &st.db).await?; - // Only the options that are actually *gone* lose their pictures: keyed by - // choice id, an option that survives the edit keeps its image no matter - // where it moved in the list. (This used to wipe every option picture - // whenever the request so much as carried a `choices` key.) - let keep: Vec = updated - .get_choices() - .unwrap_or_default() - .iter() - .map(|choice| choice.get_id().clone()) - .collect(); - for image in QuestionImage::delete_choices_not_in(updated.get_id(), &keep, &st.db).await? { - remove_blob(&st.files_path, image.get_file()).await; - } - let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?; - Ok(Json(QuestionResponse::new(&updated, &images))) -} - -/// Remove a question (and every answer to it). Requires teacher+ and -/// management rights over the exam's course. Locked once attempts exist. -#[utoipa::path( - delete, - path = "/{id}/questions/{qid}", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("qid" = String, Path, description = "Question id"), - ), - responses( - (status = 204, description = "Deleted"), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), - ), -)] -async fn delete_question( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path((id, qid)): Path<(String, String)>, -) -> Result { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, &user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can delete questions", - )); - } - // Writer lease of [`EXAM_LOCK`]: freeze gate + delete are one unit — a - // first attempt slipping past the gate would sit an exam whose question - // list forks from what `auto_score` later judges. - let _guard = EXAM_LOCK.write().await; - ensure_questions_editable(exam.get_id(), &st.db).await?; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - // Rows go first (the delete cascades them), blobs after — a crash in - // between strands at worst an unreachable blob. - let images = QuestionImage::list_for_question(question.get_id(), &st.db).await?; - question.delete(&st.db).await?; - for image in &images { - remove_blob(&st.files_path, image.get_file()).await; - } - Ok(StatusCode::NO_CONTENT) -} - -// ---- question bank bridge --------------------------------------------------- -// Two copy funnels between an exam's questions and the school-wide bank -// (`web/bank_questions`): instantiate a template into this exam, or save one of -// this exam's questions back into the bank. Both COPY the row and every image -// blob to fresh ids/files — the source side is never touched or shared. - -#[derive(Deserialize, ToSchema)] -struct InstantiateFromBank { - /// The subject to file the new question under — one of the exam's course's - /// subjects (the same-course rule the bank row itself is exempt from). - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] - subject_id: String, -} - -/// Instantiate a bank template into this exam as a fresh question. Requires -/// teacher+, management rights over the exam's course, and a template the -/// caller may see (their own, or one published to the school) — anything else -/// is a 404. `subject_id` must -/// name one of the course's subjects — the template's own subject is origin -/// metadata and does not carry over. The template (and its blobs) stay -/// untouched; a full copy — text, points, spec, illustration, and option -/// pictures — lands under a new question id. Locked once attempts exist. -#[utoipa::path( - post, - path = "/{id}/questions/from-bank/{bid}", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("bid" = String, Path, description = "Bank question id"), - ), - request_body = InstantiateFromBank, - responses( - (status = 201, description = "Question created from the template", body = QuestionResponse), - (status = 400, description = "Unknown subject, or one from another course", body = ErrorResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "No such exam, or no bank template the caller may see", body = ErrorResponse), - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), - ), -)] -async fn question_from_bank( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path((id, bid)): Path<(String, String)>, - Json(req): Json, -) -> Result<(StatusCode, Json), AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, &user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can author questions", - )); - } - // Writer lease of [`EXAM_LOCK`]: the freeze gate, the subject check, and the - // create are one unit — same reasoning as `create_question`. - let _guard = EXAM_LOCK.write().await; - ensure_questions_editable(exam.get_id(), &st.db).await?; - let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; - - let template = BankQuestion::read(&BankQuestionId::from_key(&bid), &st.db) - .await? - .ok_or(AppError::NotFound)?; - // A template the caller may not see is a 404, exactly as it is on the bank's - // own routes — instantiating is a read of `correct`, and a 403 here would - // confirm that someone else's private template exists under that id. - if !super::bank_questions::can_see(&template, &user) { - return Err(AppError::NotFound); - } - let question = ExamQuestion::create_from_bank( - exam.get_id(), - subject, - template.get_text().clone(), - template.get_points(), - template.spec(), - template.get_id().clone(), - &st.db, - ) - .await?; - - // Copy each of the template's image blobs to a fresh file under the new - // question + same slot (file before row, via `store_image`). A missing - // source blob is server-side damage, surfaced as a 500 — not silently lost. - // The copy is all-or-nothing: any mid-loop failure rolls back the fresh - // question row (its cascade drops the copied image rows) and the blobs - // written so far, leaving the source and destination untouched. - let sources = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; - let mut copied: Vec = Vec::new(); - for source in &sources { - let step = async { - let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file())) - .await - .map_err(|err| { - AppError::Internal(format!( - "missing blob for bank image {}: {err}", - source.get_file() - )) - })?; - store_image( - &st, - &exam, - &question, - source.get_slot(), - source.get_content_type().clone(), - &bytes, - ) - .await - }; - match step.await { - Ok(image) => copied.push(image.get_file().to_string()), - Err(err) => { - for file in &copied { - remove_blob(&st.files_path, file).await; - } - let _ = question.delete(&st.db).await; - return Err(err); - } - } - } - let images = QuestionImage::list_for_question(question.get_id(), &st.db).await?; - Ok(( - StatusCode::CREATED, - Json(QuestionResponse::new(&question, &images)), - )) -} - -/// Re-copy a bank template's *current* content over the exam question that was -/// instantiated from it — the escape hatch for the divergence a deep copy -/// creates: fixing a typo in the template does not reach the copies, so this is -/// how a copy is brought back in line, explicitly and per question. Requires -/// teacher+, management rights over the exam's course, and a template the -/// caller may still see. -/// -/// Replaces text, points, kind, choices, `correct`, the illustration, and the -/// option pictures with the template's; the question keeps its own id, its -/// exam, its `subject` (exam-course-scoped — the template's subject is -/// unrelated metadata) and its provenance links. Anything edited on the exam -/// copy since it was inserted is overwritten. -/// -/// **Choice ids come from the template**, exactly as -/// [`question_from_bank`] mints them — the copy adopts the template's ids, so -/// its option pictures key off the same slots the template's do, and a -/// re-copy after a template edit re-lands the right picture on the right -/// option. A recorded `selected` can never be stranded by that: the freeze -/// below refuses the whole route once *any* attempt exists, and an -/// `exam_answer` only exists under an attempt — so at refresh time no answer -/// points at any choice id at all. -/// -/// - No `from_bank` (never came from the bank, or its template was deleted and -/// the cascade cleared the link) → `400`; there is nothing to refresh from. -/// - Template gone or not visible to the caller → `404`, never a 403. -/// - Any attempt started → `409`, the same `ensure_questions_editable` freeze -/// every other question mutation answers to. -#[utoipa::path( - post, - path = "/{id}/questions/{qid}/refresh-from-bank", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("qid" = String, Path, description = "Question id"), - ), - responses( - (status = 200, description = "Question refreshed from its template", body = QuestionResponse), - (status = 400, description = "The question did not come from the bank", body = ErrorResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "No such exam, no such question in it, or no bank template the caller may see", body = ErrorResponse), - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), - ), -)] -async fn question_refresh_from_bank( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path((id, qid)): Path<(String, String)>, -) -> Result, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, &user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can edit questions", - )); - } - // Writer lease of [`EXAM_LOCK`]: the freeze gate, the read, and the - // overwrite are one unit — same reasoning as `update_question`, which this - // is a canned variant of. - let _guard = EXAM_LOCK.write().await; - ensure_questions_editable(exam.get_id(), &st.db).await?; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - - let Some(source) = question.get_from_bank().cloned() else { - return Err(AppError::Validation(ValidationError::Invalid { - field: "question", - reason: "this question did not come from a bank template", - })); - }; - let template = BankQuestion::read(&source, &st.db) - .await? - .ok_or(AppError::NotFound)?; - if !super::bank_questions::can_see(&template, &user) { - return Err(AppError::NotFound); - } - - // Every source blob is read up front, *before* anything is written: a - // missing one is server-side damage and must surface as a 500 with the - // question untouched, since a half-applied refresh has no old content left - // to roll back to. Bounded — at most one illustration plus ten option - // pictures, each under the school's file cap. - let sources = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; - let mut incoming: Vec<(&BankQuestionImage, Vec)> = Vec::with_capacity(sources.len()); - for source in &sources { - let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file())) - .await - .map_err(|err| { - AppError::Internal(format!( - "missing blob for bank image {}: {err}", - source.get_file() - )) - })?; - incoming.push((source, bytes)); - } - - // The question's own subject stays: it is checked against the exam's - // course, and the template's is origin metadata from anywhere in school. - let subject = question.get_subject().clone(); - // `spec()` hands over the template's stored choices *with their ids* rather - // than re-minting any — the same funnel `question_from_bank` uses. - let updated = question - .update( - subject, - template.get_text().clone(), - template.get_points(), - template.spec(), - &st.db, - ) - .await?; - - // Make the pictures match the template exactly: drop every slot the - // template has no picture for (including the illustration, and every option - // that is gone after the re-copy), then write the template's over the rest. - // `store_image` upserts per slot, so a slot both sides have is replaced. - let incoming_slots: Vec> = - incoming.iter().map(|(image, _)| image.get_slot()).collect(); - for stale in QuestionImage::list_for_question(updated.get_id(), &st.db).await? { - if incoming_slots.contains(&stale.get_slot()) { - continue; - } - let file = stale.get_file().to_string(); - stale.delete(&st.db).await?; - remove_blob(&st.files_path, &file).await; - } - for (source, bytes) in &incoming { - store_image( - &st, - &exam, - &updated, - source.get_slot(), - source.get_content_type().clone(), - bytes, - ) - .await?; - } - - let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?; - Ok(Json(QuestionResponse::new(&updated, &images))) -} - -/// Save one of this exam's questions into the school-wide bank as a reusable -/// template. Requires teacher+ and management rights over the exam's course. -/// The caller becomes the template's owner; the question's subject rides along -/// as origin metadata. A full copy — text, points, spec, illustration, and -/// option pictures — lands under a new bank id. Provenance rides both ways: the -/// origin exam is recorded on the template as `source_exam`, and the exam -/// question's `banked_as` is pointed at the new template (a repeat save is -/// allowed and repoints it at the newest one). `from_bank` is left alone — it -/// records the other direction and a save never changes where a question came -/// from. -#[utoipa::path( - post, - path = "/{id}/questions/{qid}/to-bank", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("qid" = String, Path, description = "Question id"), - ), - responses( - (status = 201, description = "Template saved to the bank", body = BankQuestionResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), - ), -)] -async fn question_to_bank( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path((id, qid)): Path<(String, String)>, -) -> Result<(StatusCode, Json), AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, &user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank", - )); - } - // Reader lease of [`BANK_LOCK`] across the question read and the insert: the - // template adopts the question's subject, so without it a subject delete - // could slip between the two and leave the fresh template pointing at a - // subject its cascade had already swept (that cascade runs under BANK_LOCK's - // writer lease, so holding the reader lease orders us either side of it). - let _bank_guard = super::bank_questions::BANK_LOCK.read().await; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - - // `create_from_exam` mints its own id and insert (the funnel), fed the - // question's fields plus the origin exam it was saved off. - let template = BankQuestion::create_from_exam( - user.get_id().clone(), - question.get_subject().clone(), - question.get_text().clone(), - question.get_points(), - question.spec(), - exam.get_id().clone(), - &st.db, - ) - .await?; - - // Copy every image blob (illustration + option pictures) to a fresh file - // under the new bank row + same slot (file before row). All-or-nothing: a - // mid-loop failure rolls back the fresh bank row (cascade drops the copied - // image rows) and the blobs written so far; the source exam question stays - // untouched. - let sources = QuestionImage::list_for_question(question.get_id(), &st.db).await?; - let mut copied: Vec = Vec::new(); - for source in &sources { - let step = async { - let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file())) - .await - .map_err(|err| { - AppError::Internal(format!( - "missing blob for question image {}: {err}", - source.get_file() - )) - })?; - super::bank_questions::store_image( - &st, - template.get_id(), - source.get_slot(), - source.get_content_type().clone(), - &bytes, - ) - .await - }; - match step.await { - Ok(image) => copied.push(image.get_file().to_string()), - Err(err) => { - for file in &copied { - remove_blob(&st.files_path, file).await; - } - let _ = template.delete(&st.db).await; - return Err(err); - } - } - } - // Provenance back-link, so a client can tell this question was already - // banked: the question points at the template it was saved into, and a - // repeat save repoints it at the newest one (never blocked). Written only - // after the all-or-nothing copy above, so a rolled-back template can never - // leave a dangling link. A failure here is logged and swallowed rather than - // rolling the template back: the save is the user's actual work and a - // template silently vanishing over a metadata write is worse than a - // template with no back-link (the next save re-links it). - let question_key = question.get_id().key().to_string(); - // The bank lease has done its job (the template is inserted, its subject - // pinned); hand it back *before* taking the exam one, so this handler never - // holds both — the subject delete goes EXAM_LOCK then BANK_LOCK, and taking - // them the other way round here would be a deadlock. - drop(_bank_guard); - // Reader lease of [`EXAM_LOCK`] around the back-link, the one write this - // handler makes to `exam_question`. `ExamQuestion::update` is a whole-row - // save taken under `EXAM_LOCK.write()`; without this lease the link could - // land between that handler's read and its write, and the pre-link snapshot - // would be written straight back over it — the provenance silently lost. - // Held around the link alone, never across the blob copy above. - let _exam_guard = EXAM_LOCK.read().await; - if let Err(err) = question - .link_banked_as(template.get_id().clone(), &st.db) - .await - { - tracing::warn!( - "saved question {question_key} to the bank but could not link it back: {err}" - ); - } - - let images = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; - Ok(( - StatusCode::CREATED, - Json(BankQuestionResponse::new(&template, &images)), - )) -} - -// ---- question images ---------------------------------------------------------- -// A question may carry one illustration (any kind — the map above the prompt) -// and, on choice questions, one picture per option (pick the right city off -// the map). Uploads are teacher authoring and freeze with the rest of the -// question once attempts exist; metadata rides on the question DTOs, bytes -// flow through the GET endpoints below, whose access follows the question's -// own visibility (author side and sitting side alike). - -/// The exam, provided the caller may author its questions — the shared front -/// half of every image write. -async fn image_managed_exam(st: &AppState, user: &User, id: &str) -> Result { - let exam = Exam::read(&ExamId::from_key(id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can manage question images", - )); - } - Ok(exam) -} - -/// A 403/404 unless the caller may see the exam's question content: course -/// managers always, students through the same wall as -/// `GET /exams/{id}/attempt/questions` — enrollment plus a started attempt, -/// so there is no early peek at the pictures either. -async fn ensure_question_content_visible( - st: &AppState, - exam: &Exam, - user: &User, -) -> Result<(), AppError> { - let course = course_of(exam, &st.db).await?; - if can_manage_course(&course, user) { - return Ok(()); - } - ensure_enrolled(exam, user.get_id(), &st.db).await?; - ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) - .await? - .ok_or(AppError::NotFound)?; - Ok(()) -} - -/// The whole image write tail, shared by both upload endpoints: new blob to -/// disk, row UPSERT (the deterministic per-slot id makes it a replace), then -/// the replaced blob off disk. A failed row write takes the fresh blob back -/// out; a stored row always points at a real blob. -async fn store_image( - st: &AppState, - exam: &Exam, - question: &ExamQuestion, - slot: Option<&ChoiceId>, - content_type: FileContentType, - data: &[u8], -) -> Result { - let replaced = QuestionImage::read_slot(question.get_id(), slot, &st.db).await?; - let image = QuestionImage::new( - exam.get_id(), - question.get_id(), - slot, - content_type, - data.len() as i64, - ); - let path = blob_path(&st.files_path, image.get_file()); - tokio::fs::write(&path, data) - .await - .map_err(|err| AppError::Internal(format!("failed to store the image blob: {err}")))?; - match image.upsert(&st.db).await { - Ok(stored) => { - if let Some(replaced) = replaced { - remove_blob(&st.files_path, replaced.get_file()).await; - } - Ok(stored) - } - Err(err) => { - let _ = tokio::fs::remove_file(&path).await; - Err(err) - } - } -} - -/// The stored bytes, served inline via [`super::serve_inline_blob`]. -async fn serve_image(st: &AppState, image: &QuestionImage) -> Result { - super::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await -} - -/// Attach (or replace) a question's illustration — any question kind may -/// carry one, e.g. the map the prompt asks about. `multipart/form-data` with -/// the image under a `file` field; the declared content type must be -/// `image/png`, `image/jpeg`, `image/webp`, or `image/gif` (rasters only — -/// no SVG), the bytes at most the school's `max_file_bytes` (settings). -/// Requires teacher+ and management rights over the exam's course; frozen -/// once attempts exist, like every other question edit. -#[utoipa::path( - post, - path = "/{id}/questions/{qid}/image", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("qid" = String, Path, description = "Question id"), - ), - request_body(content = UploadFileForm, content_type = "multipart/form-data"), - responses( - (status = 201, description = "Image stored", body = ImageMetaResponse), - (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), - (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), - ), -)] -async fn upload_question_image( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path((id, qid)): Path<(String, String)>, - mut multipart: Multipart, -) -> Result<(StatusCode, Json), AppError> { - let exam = image_managed_exam(&st, &user, &id).await?; - let limit = Settings::load(&st.db).await?.get_max_file_bytes(); - // The body is consumed before the lock — a client's slow upload must not - // stall the exam subsystem. - let upload = read_upload(&mut multipart, limit).await?; - let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; - // Writer lease of [`EXAM_LOCK`]: freeze gate + write are one unit, like - // every other question edit — see `create_question`. - let _guard = EXAM_LOCK.write().await; - ensure_questions_editable(exam.get_id(), &st.db).await?; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - let stored = store_image(&st, &exam, &question, None, content_type, &upload.data).await?; - Ok((StatusCode::CREATED, Json(ImageMetaResponse::new(&stored)))) -} - -/// The question's illustration bytes. Course managers read anytime; students -/// through the same wall as the sitting view — enrollment plus a started -/// attempt (404 before that, like the question list itself). -#[utoipa::path( - get, - path = "/{id}/questions/{qid}/image", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("qid" = String, Path, description = "Question id"), - ), - responses( - (status = 200, description = "The image bytes", content_type = "image/*"), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse), - (status = 404, description = "No such exam, question, or image — or no attempt yet", body = ErrorResponse), - ), -)] -async fn get_question_image( - State(st): State, - CurrentUser(user): CurrentUser, - Path((id, qid)): Path<(String, String)>, -) -> Result { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - ensure_question_content_visible(&st, &exam, &user).await?; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - let image = QuestionImage::read_slot(question.get_id(), None, &st.db) - .await? - .ok_or(AppError::NotFound)?; - serve_image(&st, &image).await -} - -/// Remove a question's illustration. Requires teacher+ and management rights -/// over the exam's course; frozen once attempts exist. -#[utoipa::path( - delete, - path = "/{id}/questions/{qid}/image", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("qid" = String, Path, description = "Question id"), - ), - responses( - (status = 204, description = "Deleted"), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "No such exam, question, or image", body = ErrorResponse), - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), - ), -)] -async fn delete_question_image( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path((id, qid)): Path<(String, String)>, -) -> Result { - let exam = image_managed_exam(&st, &user, &id).await?; - let _guard = EXAM_LOCK.write().await; - ensure_questions_editable(exam.get_id(), &st.db).await?; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - let image = QuestionImage::read_slot(question.get_id(), None, &st.db) - .await? - .ok_or(AppError::NotFound)?; - let image = image.delete(&st.db).await?; - remove_blob(&st.files_path, image.get_file()).await; - Ok(StatusCode::NO_CONTENT) -} - -/// Attach (or replace) one option's picture on a `choice` question — so the -/// options themselves can be images (four map crops, pick the right one). -/// Same form, limits, and rights as the question-image upload; `choice_id` is -/// the `id` carried on that choice, as returned in the question's `choices` -/// (not a position — an unknown id is a `400`). Replacing the question's -/// `choices` list drops all its option pictures — re-upload against the new -/// list. -#[utoipa::path( - post, - path = "/{id}/questions/{qid}/choices/{choice_id}/image", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("qid" = String, Path, description = "Question id"), - ("choice_id" = String, Path, description = "Choice id, as returned in the question's `choices`"), - ), - request_body(content = UploadFileForm, content_type = "multipart/form-data"), - responses( - (status = 201, description = "Image stored", body = ImageMetaResponse), - (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), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), - (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), - ), -)] -async fn upload_choice_image( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path((id, qid, choice_id)): Path<(String, String, String)>, - mut multipart: Multipart, -) -> Result<(StatusCode, Json), AppError> { - let exam = image_managed_exam(&st, &user, &id).await?; - let limit = Settings::load(&st.db).await?.get_max_file_bytes(); - let upload = read_upload(&mut multipart, limit).await?; - let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; - let _guard = EXAM_LOCK.write().await; - ensure_questions_editable(exam.get_id(), &st.db).await?; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - let slot = choice_slot(&question, &choice_id)?; - let stored = store_image( - &st, - &exam, - &question, - Some(&slot), - content_type, - &upload.data, - ) - .await?; - Ok((StatusCode::CREATED, Json(ImageMetaResponse::new(&stored)))) -} - -/// One option's picture bytes. Same access wall as the question-image read. -#[utoipa::path( - get, - path = "/{id}/questions/{qid}/choices/{choice_id}/image", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("qid" = String, Path, description = "Question id"), - ("choice_id" = String, Path, description = "Choice id"), - ), - responses( - (status = 200, description = "The image bytes", content_type = "image/*"), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse), - (status = 404, description = "No such exam, question, or image — or no attempt yet", body = ErrorResponse), - ), -)] -async fn get_choice_image( - State(st): State, - CurrentUser(user): CurrentUser, - Path((id, qid, choice_id)): Path<(String, String, String)>, -) -> Result { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - ensure_question_content_visible(&st, &exam, &user).await?; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - let slot = choice_slot(&question, &choice_id)?; - let image = QuestionImage::read_slot(question.get_id(), Some(&slot), &st.db) - .await? - .ok_or(AppError::NotFound)?; - serve_image(&st, &image).await -} - -/// Remove one option's picture. Requires teacher+ and management rights over -/// the exam's course; frozen once attempts exist. -#[utoipa::path( - delete, - path = "/{id}/questions/{qid}/choices/{choice_id}/image", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("qid" = String, Path, description = "Question id"), - ("choice_id" = String, Path, description = "Choice id"), - ), - responses( - (status = 204, description = "Deleted"), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "No such exam, question, or image", body = ErrorResponse), - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), - ), -)] -async fn delete_choice_image( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path((id, qid, choice_id)): Path<(String, String, String)>, -) -> Result { - let exam = image_managed_exam(&st, &user, &id).await?; - let _guard = EXAM_LOCK.write().await; - ensure_questions_editable(exam.get_id(), &st.db).await?; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - let slot = choice_slot(&question, &choice_id)?; - let image = QuestionImage::read_slot(question.get_id(), Some(&slot), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let image = image.delete(&st.db).await?; - remove_blob(&st.files_path, image.get_file()).await; - Ok(StatusCode::NO_CONTENT) -} - -// ---- answers ---------------------------------------------------------------- -// Students answer inside their attempt; every save is an upsert stamped with -// the server clock. The WebSocket room (`/exams/{id}/attempt/ws`) drives the -// same paths below. - -/// A student's own saved answer, embedded in their question view. -#[derive(Serialize, ToSchema)] -struct AnswerStateResponse { - /// The picked option's id (`choice` questions). - selected: Option, - /// The typed answer (`text` questions). - text: Option, - /// When this answer was last saved, UTC unix-milliseconds. - updated_at: i64, - /// The student's own drawn answer, if any — bytes at - /// `GET /exams/{id}/attempt/answers/{qid}/image`. - answer_image: Option, -} - -impl AnswerStateResponse { - fn new(answer: &ExamAnswer, answer_image: Option) -> Self { - Self { - selected: answer.get_selected().map(|id| id.as_str().to_string()), - text: answer.get_text().map(|t| t.as_str().to_string()), - updated_at: answer.get_updated_at().as_millis(), - answer_image, - } - } -} - -/// A question as the sitting student sees it: no `correct` choice id, their own -/// saved answer embedded. -#[derive(Serialize, ToSchema)] -struct AttemptQuestionResponse { - id: String, - /// The subject this question belongs to (`GET /subjects/{id}`). - subject: String, - text: String, - /// `choice` or `text`. - #[schema(example = "choice")] - kind: String, - points: i64, - /// The options with their ids — and deliberately *not* `correct`: this DTO - /// leaks no answer key because it has no field to carry one, and - /// `ChoiceResponse` carries none either. - choices: Option>, - /// The question's illustration, if any — bytes at - /// `GET /exams/{id}/questions/{qid}/image`. - image: Option, - /// Per-option pictures aligned with `choices`, if any — bytes at - /// `GET /exams/{id}/questions/{qid}/choices/{choice_id}/image`. - choice_images: Option>>, - /// The caller's saved answer; `null` while unanswered. - answer: Option, -} - -#[derive(Deserialize, ToSchema)] -struct SaveAnswer { - /// The question being answered. - question_id: String, - /// The picked option's `id` — required for `choice` questions. - selected: Option, - /// The typed answer — required for `text` questions (empty clears the draft). - #[schema(max_length = 10000)] - text: Option, -} - -#[derive(Serialize, ToSchema)] -struct AnswerSavedResponse { - question: String, - /// The picked option's id. - selected: Option, - text: Option, - /// Save instant by the server clock, UTC unix-milliseconds. - updated_at: i64, -} - -/// The caller's latest attempt provided it is still writable, or the error -/// that says why not: no attempt yet (404 — start it first), already -/// submitted (409), deadline passed (409). One gate shared by REST saves and -/// the WebSocket room. -pub(crate) async fn writable_attempt( - exam: &Exam, - user: &UserId, - db: &Database, -) -> Result { - let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user, db) - .await? - .ok_or(AppError::NotFound)?; - match attempt.status(exam, Timestamp::now()) { - AttemptStatus::Submitted => Err(AppError::Conflict("the attempt is already submitted")), - AttemptStatus::Expired => Err(AppError::Conflict("time is up — the attempt has expired")), - AttemptStatus::InProgress => Ok(attempt), - } -} - -/// A 409 when the student has walked out of the exam room and the exam's -/// rejoin door is closed: no more answering (from anywhere) until the teacher -/// flips `allow_rejoin` back on. Finishing is deliberately exempt — see -/// `finish_attempt`. -pub(crate) fn check_rejoin(exam: &Exam, attempt: &ExamAttempt) -> Result<(), AppError> { - if attempt.get_left_at().is_some() && !exam.get_allow_rejoin() { - return Err(AppError::Conflict( - "you left the exam and rejoin is closed — ask your teacher to reopen it", - )); - } - Ok(()) -} - -/// Save one answer inside the caller's in-progress attempt — the whole write -/// path (attempt gate, rejoin gate, question lookup, kind check, upsert). The -/// REST handler saves into the latest sitting via this; the WebSocket room -/// resolves its own sitting first and shares [`save_answer_in`], so the two -/// can never drift. -pub(crate) async fn save_answer_checked( - exam: &Exam, - user: &UserId, - question_id: &str, - selected: Option, - text: Option, - db: &Database, -) -> Result { - // Reader lease of [`EXAM_LOCK`]: the writable gate and the upsert are - // one unit, or a retake's wipe-and-create (a writer) slips in between - // and this stale save lands on the fresh blank sheet. - let _guard = EXAM_LOCK.read().await; - let attempt = writable_attempt(exam, user, db).await?; - save_answer_in(exam, &attempt, question_id, selected, text, db).await -} - -/// The tail of the answer write path, given the sitting to write in: the -/// student wall and the enrollment wall (a promotion out of `student` or an -/// unenrollment closes the sheet, mid-exam included), the rejoin gate, the -/// question lookup, and the upsert. -pub(crate) async fn save_answer_in( - exam: &Exam, - attempt: &ExamAttempt, - question_id: &str, - selected: Option, - text: Option, - db: &Database, -) -> Result { - ensure_student_now(attempt.get_user(), db).await?; - ensure_enrolled(exam, attempt.get_user(), db).await?; - check_rejoin(exam, attempt)?; - let question = question_of_exam(exam.get_id(), question_id, db).await?; - ExamAnswer::save( - &question, - attempt.get_user(), - attempt.get_seq(), - selected, - text, - db, - ) - .await -} - -/// A 403 unless `user` is a student. Sitting an exam is a student action — -/// teachers and above run exams, they never take them — so the sit paths -/// (start, room, save) enforce it on the *current* role. Checking the live -/// role, not just enrollment, closes the gap a mid-exam promotion would open -/// and neutralizes any stale non-student enrollment. Reading one's own attempt -/// and finishing stay ungated: a non-student has no attempt to read, and -/// finishing only submits work already saved. -pub(crate) fn ensure_student(user: &User) -> Result<(), AppError> { - if user.get_role() != Role::Student { - return Err(AppError::Forbidden("only students can sit exams")); - } - Ok(()) -} - -/// The answer path's live edition of [`ensure_student`]: re-read the row and -/// judge the *current* role, exactly like the enrollment wall beside it. Both -/// save paths run through here (REST per request, the exam room per message), -/// so a promotion out of `student` mid-exam closes the sheet on the very next -/// save — the room's door check is not the last word for a socket that -/// outlives the role. -pub(crate) async fn ensure_student_now(user: &UserId, db: &Database) -> Result<(), AppError> { - let user = User::read(user, db).await?.ok_or(AppError::Unauthorized)?; - ensure_student(&user) -} - -/// A 403 unless `user` is enrolled in the exam's course — the same wall the -/// exam room checks at its door, re-applied to the sitting's content paths so -/// an unenrollment mid-exam cuts them too. Finishing stays exempt: like the -/// rejoin lock, submitting what's already saved writes nothing new. -pub(crate) async fn ensure_enrolled( - exam: &Exam, - user: &UserId, - db: &Database, -) -> Result<(), AppError> { - if Enrollment::read_for_user(exam.get_course(), user, db) - .await? - .is_none() - { - return Err(AppError::Forbidden( - "you are not enrolled in this exam's course", - )); - } - Ok(()) -} - -/// The exam's questions as the sitting student sees them: `correct` stripped, -/// their own saved answers embedded — the latest sitting's, since a retake -/// starts from a blank sheet. Requires enrollment in the exam's course (the -/// questions are course content — leaving the course closes them) and an -/// attempt — start one with `POST /exams/{id}/attempt` first (404 until -/// then). Readable in every attempt state, so a submitted student can still -/// review what they wrote. -#[utoipa::path( - get, - path = "/{id}/attempt/questions", - tag = "exams", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id")), - responses( - (status = 200, description = "Questions with the caller's answers embedded", body = [AttemptQuestionResponse]), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse), - (status = 404, description = "No such exam, or no attempt yet — start the attempt first", body = ErrorResponse), - ), -)] -async fn attempt_questions( - State(st): State, - CurrentUser(user): CurrentUser, - Path(id): Path, -) -> Result>, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - ensure_enrolled(&exam, user.get_id(), &st.db).await?; - // The question list is for sitting students; without an attempt there is - // nothing to sit behind — and no early peek at the questions. The embedded - // answers are the *current* sitting's only, so the seq scopes the reads. - let seq = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) - .await? - .ok_or(AppError::NotFound)? - .get_seq(); - - let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?; - let images = images_by_question(exam.get_id(), &st.db).await?; - let answers: HashMap = - ExamAnswer::list_for_exam_user(exam.get_id(), user.get_id(), seq, &st.db) - .await? - .into_iter() - .map(|answer| (answer.get_question().key().to_string(), answer)) - .collect(); - let answer_images: HashMap = - AnswerImage::list_for_exam_user(exam.get_id(), user.get_id(), seq, &st.db) - .await? - .into_iter() - .map(|image| (image.get_question().key().to_string(), image)) - .collect(); - Ok(Json( - questions - .iter() - .map(|question| { - let question_images = images - .get(question.get_id().key()) - .map_or(&[][..], Vec::as_slice); - AttemptQuestionResponse { - id: question.get_id().key().to_string(), - subject: question.get_subject().key().to_string(), - text: question.get_text().as_str().to_string(), - kind: question.get_kind().as_str().to_string(), - points: question.get_points().as_i64(), - choices: ChoiceResponse::list(question.get_choices()), - image: image_meta(question_images, None), - choice_images: choice_image_metas(question, question_images), - answer: answers.get(question.get_id().key()).map(|answer| { - AnswerStateResponse::new( - answer, - answer_images - .get(question.get_id().key()) - .map(ImageMetaResponse::from_answer), - ) - }), - } - }) - .collect(), - )) -} - -/// Save (or overwrite) one answer in the caller's in-progress attempt. -/// `choice` questions take `selected`; `text` questions take `text`. Requires -/// the student role and enrollment in the exam's course — an unenrollment (or a -/// promotion out of `student`) mid-exam closes the sheet. Rejected once the -/// attempt is submitted or its deadline has passed — -/// the server clock, not the client's, is the judge — and rejected while the -/// student has left the exam room with the exam's rejoin door closed. -#[utoipa::path( - post, - path = "/{id}/attempt/answers", - tag = "exams", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id")), - request_body = SaveAnswer, - responses( - (status = 200, description = "Answer saved", body = AnswerSavedResponse), - (status = 400, description = "Payload doesn't match the question's kind", body = ErrorResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), - (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse), - (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), - ), -)] -async fn save_answer( - State(st): State, - CurrentUser(user): CurrentUser, - Path(id): Path, - Json(req): Json, -) -> Result, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - ensure_student(&user)?; - let answer = save_answer_checked( - &exam, - user.get_id(), - &req.question_id, - req.selected, - req.text, - &st.db, - ) - .await?; - Ok(Json(AnswerSavedResponse { - question: answer.get_question().key().to_string(), - selected: answer.get_selected().map(|id| id.as_str().to_string()), - text: answer.get_text().map(|t| t.as_str().to_string()), - updated_at: answer.get_updated_at().as_millis(), - })) -} - -/// One student's answer sheet with correctness flags — always the *latest* -/// sitting's answers (a retake starts from a blank sheet). Every row carries -/// the saved answer plus `is_correct` (`null` for text questions — those are -/// the grader's call), and the machine's `auto_score` over the choice -/// questions is attached as a *suggestion*: the final mark stays human, via -/// `POST /exams/{id}/results`. Requires teacher+ and management rights over -/// the exam's course. -#[utoipa::path( - get, - path = "/{id}/attempts/{user}/answers", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("user" = String, Path, description = "User id"), - ), - responses( - (status = 200, description = "The student's answers, judged", body = AttemptAnswersResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "No such exam, or the student has no attempt", body = ErrorResponse), - ), -)] -async fn attempt_answers( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path((id, target)): Path<(String, String)>, -) -> Result, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, &user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can read answer sheets", - )); - } - let target = UserId::from_key(&target); - // No attempt means no answer sheet — a 404, not an empty one. This grading - // view shows the *latest* sitting; prior sittings live under the - // per-attempt history endpoints. - let seq = ExamAttempt::read_latest_for_user(exam.get_id(), &target, &st.db) - .await? - .ok_or(AppError::NotFound)? - .get_seq(); - Ok(Json(answer_sheet(&exam, &target, seq, &st.db).await?)) -} - -/// One sitting's judged answer sheet: the `seq`th attempt's answers, drawing -/// refs, correctness flags, and auto-score suggestion. Shared by the latest- -/// sitting grading view and the per-attempt history endpoint. -async fn answer_sheet( - exam: &Exam, - target: &UserId, - seq: i64, - db: &Database, -) -> Result { - let questions = ExamQuestion::list_for_exam(exam.get_id(), db).await?; - let answers = ExamAnswer::list_for_exam_user(exam.get_id(), target, seq, db).await?; - let answer_images: HashMap = - AnswerImage::list_for_exam_user(exam.get_id(), target, seq, db) - .await? - .into_iter() - .map(|image| (image.get_question().key().to_string(), image)) - .collect(); - let by_question: HashMap<&str, &ExamQuestion> = questions - .iter() - .map(|question| (question.get_id().key(), question)) - .collect(); - let (earned, possible) = auto_score(&questions, &answers); - let people = person_map([target.clone()], db).await?; - Ok(AttemptAnswersResponse { - exam: exam.get_id().key().to_string(), - user: PersonRef::resolve(&people, target), - answers: answers - .iter() - .map(|answer| StudentAnswerResponse { - question: answer.get_question().key().to_string(), - selected: answer.get_selected().map(|id| id.as_str().to_string()), - text: answer.get_text().map(|t| t.as_str().to_string()), - updated_at: answer.get_updated_at().as_millis(), - is_correct: by_question - .get(answer.get_question().key()) - .and_then(|question| answer.is_correct(question)), - answer_image: answer_images - .get(answer.get_question().key()) - .map(ImageMetaResponse::from_answer), - }) - .collect(), - auto_score: AutoScoreResponse { earned, possible }, - }) -} - -/// One row of a student's answer sheet, as the grader sees it. -#[derive(Serialize, ToSchema)] -struct StudentAnswerResponse { - question: String, - /// The picked option's id. - selected: Option, - text: Option, - /// When the answer was last saved, UTC unix-milliseconds. - updated_at: i64, - /// Whether `selected` hits the question's `correct`; `null` for text - /// questions (the grader judges those). - is_correct: Option, - /// The student's drawn answer, if any — bytes at - /// `GET /exams/{id}/attempts/{user}/answers/{qid}/image`. - answer_image: Option, -} - -/// The machine's scoring suggestion over the choice questions. -#[derive(Serialize, ToSchema)] -struct AutoScoreResponse { - /// Points earned where `selected == correct`. - earned: i64, - /// Total points across the exam's choice questions. - possible: i64, -} - -/// A student's full answer sheet for grading. -#[derive(Serialize, ToSchema)] -struct AttemptAnswersResponse { - exam: String, - /// The student whose sheet this is. - user: PersonRef, - answers: Vec, - /// The suggested score over choice questions — never the final mark. - auto_score: AutoScoreResponse, -} - -// ---- answer images ---------------------------------------------------------- -// A student's freehand drawing of their answer to a question — one per (exam, -// user, question), the answer-side mirror of the teacher's question images. -// It is a normal `image/png` (the frontend embeds its editable stroke JSON in a -// PNG `tEXt` chunk, opaque to us), so it flows through the same raster -// content-type wall and inline-serve path as every other exam image. The write -// paths ride the exact `save_answer` gate chain; the reads follow the question -// content's own visibility (own sitting view / teacher grading view). - -/// The answer-image write tail, mirroring [`store_image`]: new blob to disk, -/// row UPSERT (the deterministic per-(question, user) id makes it a replace), -/// then the replaced blob off disk. A failed row write takes the fresh blob -/// back out; a stored row always points at a real blob. -async fn store_answer_image( - st: &AppState, - exam: &Exam, - question: &ExamQuestion, - user: &UserId, - seq: i64, - content_type: FileContentType, - data: &[u8], -) -> Result { - let replaced = AnswerImage::read(question.get_id(), user, seq, &st.db).await?; - let image = AnswerImage::new( - exam.get_id(), - question.get_id(), - user, - seq, - content_type, - data.len() as i64, - ); - let path = blob_path(&st.files_path, image.get_file()); - tokio::fs::write(&path, data).await.map_err(|err| { - AppError::Internal(format!("failed to store the answer image blob: {err}")) - })?; - match image.upsert(&st.db).await { - Ok(stored) => { - if let Some(replaced) = replaced { - remove_blob(&st.files_path, replaced.get_file()).await; - } - Ok(stored) - } - Err(err) => { - let _ = tokio::fs::remove_file(&path).await; - Err(err) - } - } -} - -/// Attach (or replace) the caller's drawn answer to a question inside their -/// in-progress attempt. `multipart/form-data` with the drawing under a `file` -/// field; the declared content type must be `image/png`, `image/jpeg`, -/// `image/webp`, or `image/gif` (rasters only — no SVG), the bytes at most the -/// school's `max_file_bytes`. Rides the exact `POST /exams/{id}/attempt/answers` -/// gate chain: the student role, an in-progress attempt, current enrollment, and -/// the rejoin door. -#[utoipa::path( - post, - path = "/{id}/attempt/answers/{qid}/image", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("qid" = String, Path, description = "Question id"), - ), - request_body(content = UploadFileForm, content_type = "multipart/form-data"), - responses( - (status = 201, description = "Drawing stored", body = ImageMetaResponse), - (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), - (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse), - (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), - (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), - ), -)] -async fn upload_answer_image( - State(st): State, - CurrentUser(user): CurrentUser, - Path((id, qid)): Path<(String, String)>, - mut multipart: Multipart, -) -> Result<(StatusCode, Json), AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - ensure_student(&user)?; - let limit = Settings::load(&st.db).await?.get_max_file_bytes(); - // The body is consumed before the lock — a client's slow upload must not - // stall the exam subsystem (mirrors the question-image upload). - let upload = read_upload(&mut multipart, limit).await?; - let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; - // Reader lease of [`EXAM_LOCK`], exactly like `save_answer_checked`: the - // writable gate and the write are one unit, or a retake's wipe-and-create - // (a writer) slips in between and this stale drawing lands on the fresh - // blank sheet. - let _guard = EXAM_LOCK.read().await; - let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; - ensure_student_now(attempt.get_user(), &st.db).await?; - ensure_enrolled(&exam, attempt.get_user(), &st.db).await?; - check_rejoin(&exam, &attempt)?; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - let seq = attempt.get_seq(); - let stored = store_answer_image( - &st, - &exam, - &question, - user.get_id(), - seq, - content_type, - &upload.data, - ) - .await?; - // A drawing-only answer (drew, typed nothing) still needs an ExamAnswer row, - // or the drawing never surfaces in the sitting/grading views — answer_image - // rides the answer payload. Create a blank text answer when absent, without - // clobbering typed text. Choice questions can't hold a blank answer (and the - // UI only offers drawing on text questions), so they are skipped. Removing - // the drawing later grooms this blank row away (see `delete_answer_image`). - if question.get_kind().as_str() != "choice" - && ExamAnswer::read(question.get_id(), user.get_id(), seq, &st.db) - .await? - .is_none() - { - ExamAnswer::save( - &question, - user.get_id(), - seq, - None, - Some(String::new()), - &st.db, - ) - .await?; - } - Ok(( - StatusCode::CREATED, - Json(ImageMetaResponse::from_answer(&stored)), - )) -} - -/// Clear the caller's drawn answer to a question. Same writable-attempt gate -/// chain as the upload. -#[utoipa::path( - delete, - path = "/{id}/attempt/answers/{qid}/image", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("qid" = String, Path, description = "Question id"), - ), - responses( - (status = 204, description = "Deleted"), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), - (status = 404, description = "No such exam, question, attempt, or drawing", body = ErrorResponse), - (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), - ), -)] -async fn delete_answer_image( - State(st): State, - CurrentUser(user): CurrentUser, - Path((id, qid)): Path<(String, String)>, -) -> Result { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - ensure_student(&user)?; - let _guard = EXAM_LOCK.read().await; - let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; - ensure_student_now(attempt.get_user(), &st.db).await?; - ensure_enrolled(&exam, attempt.get_user(), &st.db).await?; - check_rejoin(&exam, &attempt)?; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - let seq = attempt.get_seq(); - let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db) - .await? - .ok_or(AppError::NotFound)?; - let image = image.delete(&st.db).await?; - remove_blob(&st.files_path, image.get_file()).await; - // If the drawing was the whole answer (blank text, no choice — the row the - // upload created for a drawing-only answer), drop it too so it stops counting - // as answered. A typed answer keeps its row. - if let Some(answer) = ExamAnswer::read(question.get_id(), user.get_id(), seq, &st.db).await? { - let blank = answer.get_selected().is_none() - && answer.get_text().is_none_or(|t| t.as_str().is_empty()); - if blank { - ExamAnswer::delete(question.get_id(), user.get_id(), seq, &st.db).await?; - } - } - Ok(StatusCode::NO_CONTENT) -} - -/// The caller's own drawn-answer bytes. Same visibility wall as the sitting -/// question view — enrollment plus a started attempt (404 before that). -#[utoipa::path( - get, - path = "/{id}/attempt/answers/{qid}/image", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("qid" = String, Path, description = "Question id"), - ), - responses( - (status = 200, description = "The drawing bytes", content_type = "image/*"), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse), - (status = 404, description = "No such exam, question, or drawing — or no attempt yet", body = ErrorResponse), - ), -)] -async fn get_answer_image( - State(st): State, - CurrentUser(user): CurrentUser, - Path((id, qid)): Path<(String, String)>, -) -> Result { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - ensure_question_content_visible(&st, &exam, &user).await?; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - // The caller's current sitting — the drawing belongs to their latest seq. - let seq = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) - .await? - .ok_or(AppError::NotFound)? - .get_seq(); - let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db) - .await? - .ok_or(AppError::NotFound)?; - super::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await -} - -/// One student's drawn-answer bytes, for the grader. Requires teacher+ and -/// management rights over the exam's course — the `attempt_answers` gate. -#[utoipa::path( - get, - path = "/{id}/attempts/{user}/answers/{qid}/image", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("user" = String, Path, description = "User id"), - ("qid" = String, Path, description = "Question id"), - ), - responses( - (status = 200, description = "The student's drawing bytes", content_type = "image/*"), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "No such exam, question, or drawing", body = ErrorResponse), - ), -)] -async fn get_student_answer_image( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path((id, target, qid)): Path<(String, String, String)>, -) -> Result { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, &user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can read answer sheets", - )); - } - let target = UserId::from_key(&target); - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - // The grader's default view is the latest sitting; per-attempt drawings - // come from the history image endpoint. - let seq = ExamAttempt::read_latest_for_user(exam.get_id(), &target, &st.db) - .await? - .ok_or(AppError::NotFound)? - .get_seq(); - let image = AnswerImage::read(question.get_id(), &target, seq, &st.db) - .await? - .ok_or(AppError::NotFound)?; - super::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await -} - -// ---- per-attempt history ---------------------------------------------------- -// The grading views above show the latest sitting; these expose every prior -// sitting a re-taking student left behind. Same wall as grading: teacher+ who -// manages the exam's course. A student never reaches another student's sheet, -// and a student's own prior attempts are staff-visible by design. - -/// The exam plus the manage-rights check the grading and history reads share. -async fn gradable_exam(st: &AppState, user: &User, id: &str) -> Result { - let exam = Exam::read(&ExamId::from_key(id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can read answer sheets", - )); - } - Ok(exam) -} - -/// The sitting numbers a student has left at an exam — every seq that carries -/// answers or a mark, ascending. Requires teacher+ and management rights over -/// the exam's course. Drives the FE's attempt-by-attempt picker. -#[utoipa::path( - get, - path = "/{id}/students/{user}/attempts", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("user" = String, Path, description = "User id"), - ), - responses( - (status = 200, description = "The student's sitting numbers, ascending", body = [i64]), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "Exam not found", body = ErrorResponse), - ), -)] -async fn student_attempts( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path((id, target)): Path<(String, String)>, -) -> Result>, AppError> { - let exam = gradable_exam(&st, &user, &id).await?; - let target = UserId::from_key(&target); - let mut seqs = ExamAnswer::list_seqs_for_user(exam.get_id(), &target, &st.db).await?; - for result in ExamResult::list_all_for_exam_user(exam.get_id(), &target, &st.db).await? { - seqs.push(result.get_seq()); - } - seqs.sort_unstable(); - seqs.dedup(); - Ok(Json(seqs)) -} - -/// One prior sitting's judged answer sheet — the `seq`th attempt's answers, -/// drawing refs, correctness flags, and auto-score suggestion. Requires -/// teacher+ and management rights over the exam's course. Serves an empty -/// sheet for a seq the student never wrote in. -#[utoipa::path( - get, - path = "/{id}/students/{user}/attempts/{seq}/answers", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("user" = String, Path, description = "User id"), - ("seq" = i64, Path, description = "Sitting number (1, 2, …)"), - ), - responses( - (status = 200, description = "That sitting's answers, judged", body = AttemptAnswersResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "Exam not found", body = ErrorResponse), - ), -)] -async fn student_attempt_answers( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path((id, target, seq)): Path<(String, String, i64)>, -) -> Result, AppError> { - let exam = gradable_exam(&st, &user, &id).await?; - let target = UserId::from_key(&target); - Ok(Json(answer_sheet(&exam, &target, seq, &st.db).await?)) -} - -/// A prior sitting's drawn-answer bytes. Requires teacher+ and management -/// rights over the exam's course — the seq-scoped mirror of the grader's -/// latest-sitting drawing read. -#[utoipa::path( - get, - path = "/{id}/students/{user}/attempts/{seq}/answers/{qid}/image", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("user" = String, Path, description = "User id"), - ("seq" = i64, Path, description = "Sitting number (1, 2, …)"), - ("qid" = String, Path, description = "Question id"), - ), - responses( - (status = 200, description = "The student's drawing bytes", content_type = "image/*"), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "No such exam, question, or drawing", body = ErrorResponse), - ), -)] -async fn student_attempt_answer_image( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path((id, target, seq, qid)): Path<(String, String, i64, String)>, -) -> Result { - let exam = gradable_exam(&st, &user, &id).await?; - let target = UserId::from_key(&target); - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - let image = AnswerImage::read(question.get_id(), &target, seq, &st.db) - .await? - .ok_or(AppError::NotFound)?; - super::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await -} - -/// A student's full mark history at an exam — every sitting's mark, oldest -/// first (the grade-of-record is the latest). Requires teacher+ and management -/// rights over the exam's course. -#[utoipa::path( - get, - path = "/{id}/students/{user}/marks", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("user" = String, Path, description = "User id"), - ), - responses( - (status = 200, description = "The student's per-sitting marks, oldest first", body = [ExamResultResponse]), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "Exam not found", body = ErrorResponse), - ), -)] -async fn student_marks_history( - State(st): State, - RequireTeacher(user): RequireTeacher, - Path((id, target)): Path<(String, String)>, -) -> Result>, AppError> { - let exam = gradable_exam(&st, &user, &id).await?; - let target = UserId::from_key(&target); - let results = ExamResult::list_all_for_exam_user(exam.get_id(), &target, &st.db).await?; - let people = person_map( - results - .iter() - .flat_map(|r| [r.get_user().clone(), r.get_graded_by().clone()]), - &st.db, - ) - .await?; - Ok(Json( - results - .iter() - .map(|r| ExamResultResponse::new(r, &people)) - .collect(), - )) -} - -// ---- student self-review ---------------------------------------------------- -// The mirror of the teacher history reads above, but own-scoped: no `{user}` -// path param, so the target is always the caller — a student can never reach -// another student's sheet. Opens only once the teacher enables review AND has -// marked this student (an ExamResult row proves it). - -/// The exam plus the per-student review gate the three self-review reads share. -/// 404 if the exam is missing or still a draft, 403 if review is off for it, and -/// 404 until the caller has a mark on it (nothing to review yet). -async fn reviewable_exam(st: &AppState, user: &User, id: &str) -> Result { - let exam = Exam::read(&ExamId::from_key(id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - if exam.is_draft() { - return Err(AppError::NotFound); - } - if !exam.get_allow_review() { - return Err(AppError::Forbidden("review not enabled for this exam")); - } - ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) - .await? - .ok_or(AppError::NotFound)?; - Ok(exam) -} - -/// The caller's own sitting numbers at an exam — every seq that carries answers -/// or a mark, ascending. Own-scoped review view; opens once the teacher enables -/// review and has marked the caller. -#[utoipa::path( - get, - path = "/{id}/review/attempts", - tag = "exams", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id")), - responses( - (status = 200, description = "The caller's own sitting numbers, ascending", body = [i64]), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), - (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse), - ), -)] -async fn review_attempts( - State(st): State, - CurrentUser(user): CurrentUser, - Path(id): Path, -) -> Result>, AppError> { - let exam = reviewable_exam(&st, &user, &id).await?; - let target = user.get_id().clone(); - let mut seqs = ExamAnswer::list_seqs_for_user(exam.get_id(), &target, &st.db).await?; - for result in ExamResult::list_all_for_exam_user(exam.get_id(), &target, &st.db).await? { - seqs.push(result.get_seq()); - } - seqs.sort_unstable(); - seqs.dedup(); - Ok(Json(seqs)) -} - -/// The exam's full question list, `correct` choice ids included — the answer key -/// the caller reviews their own sheet against. Same review gate as the other -/// self-review reads; revealing `correct` is the point (the gate already proves -/// the caller was marked). Paged via `?limit=&offset=`. -#[utoipa::path( - get, - path = "/{id}/review/questions", - tag = "exams", - security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id"), PageParams), - responses( - (status = 200, description = "A page of the exam's questions with `correct` (all of them when unpaged)", body = Page), - (status = 400, description = "Invalid limit or offset", body = ErrorResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), - (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse), - ), -)] -async fn review_questions( - State(st): State, - CurrentUser(user): CurrentUser, - Path(id): Path, - Query(page): Query, -) -> Result>, AppError> { - let (limit, offset) = page.resolve()?; - let exam = reviewable_exam(&st, &user, &id).await?; - Ok(Json(question_page(&exam, limit, offset, &st.db).await?)) -} - -/// One of the caller's own sittings, judged — the `seq`th attempt's answers, -/// drawing refs, correctness flags, and auto-score suggestion. Own-scoped -/// review view. -#[utoipa::path( - get, - path = "/{id}/review/attempts/{seq}/answers", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("seq" = i64, Path, description = "Sitting number (1, 2, …)"), - ), - responses( - (status = 200, description = "That sitting's answers, judged", body = AttemptAnswersResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), - (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse), - ), -)] -async fn review_attempt_answers( - State(st): State, - CurrentUser(user): CurrentUser, - Path((id, seq)): Path<(String, i64)>, -) -> Result, AppError> { - let exam = reviewable_exam(&st, &user, &id).await?; - Ok(Json(answer_sheet(&exam, user.get_id(), seq, &st.db).await?)) -} - -/// The caller's own drawn-answer bytes for one of their sittings — the -/// seq-scoped, own-scoped mirror of the grader's drawing read. -#[utoipa::path( - get, - path = "/{id}/review/attempts/{seq}/answers/{qid}/image", - tag = "exams", - security(("session_cookie" = [])), - params( - ("id" = String, Path, description = "Exam id"), - ("seq" = i64, Path, description = "Sitting number (1, 2, …)"), - ("qid" = String, Path, description = "Question id"), - ), - responses( - (status = 200, description = "The caller's drawing bytes", content_type = "image/*"), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), - (status = 404, description = "No such exam/question/drawing, a draft, or the caller has no mark on it", body = ErrorResponse), - ), -)] -async fn review_attempt_answer_image( - State(st): State, - CurrentUser(user): CurrentUser, - Path((id, seq, qid)): Path<(String, i64, String)>, -) -> Result { - let exam = reviewable_exam(&st, &user, &id).await?; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db) - .await? - .ok_or(AppError::NotFound)?; - super::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await -} diff --git a/src/web/exams/attempts.rs b/src/web/exams/attempts.rs new file mode 100644 index 0000000..7a577bd --- /dev/null +++ b/src/web/exams/attempts.rs @@ -0,0 +1,1004 @@ +use super::*; + +// ---- attempts ------------------------------------------------------------- +// A sittable exam (sync, async, or open mode) is *sat*: starting an attempt +// is the live-attendance signal, finishing is the submission. The exam's +// `max_attempts` (0 = unlimited) says how many sittings each student gets; +// re-posting resumes a running attempt and mints the next sitting once the +// last one is over. Deadlines are judged only by the server clock — clients +// sync via `GET /time`. + +/// A student's view of their (latest) attempt. `now` is echoed so clients can +/// render countdowns without trusting the device clock. +#[derive(Serialize, ToSchema)] +pub(crate) struct AttemptResponse { + id: String, + exam: String, + user: PersonRef, + /// Which sitting this is — 1 for the first attempt, counting up. + attempt: i64, + /// How many sittings the caller has used, this one included. + attempts_used: u64, + /// The exam's attempt limit; `0` means unlimited. + max_attempts: i64, + /// When the attempt started, UTC unix-milliseconds. + started_at: i64, + /// Submission instant; `null` while running (or expired unsubmitted). + finished_at: Option, + /// When the student left the exam room mid-attempt; `null` while inside + /// (or if they never used the room). With `allow_rejoin` off, a set + /// `left_at` locks further answering until the teacher reopens the door. + left_at: Option, + /// `in_progress` | `submitted` | `expired`. + #[schema(example = "in_progress")] + status: String, + /// When the attempt closes: the earlier of the window's `ends_at` and + /// `started_at + duration_ms` (whichever exists). Recomputed live from + /// the exam's current schedule; `null` for an open exam without a + /// duration — such an attempt only ends by submission. + deadline: Option, + /// `deadline - now`, floored at 0; `null` unless in progress with a + /// deadline. + remaining_ms: Option, + /// The caller's mark, once graded. + mark: Option, + /// How many questions the caller has answered so far. + answered: u64, + /// How many questions the exam has. + question_count: u64, + /// Server clock at response time, UTC unix-milliseconds. + now: i64, +} + +impl AttemptResponse { + #[expect( + clippy::too_many_arguments, + reason = "a flat view over attempt + exam + progress; a builder would obscure it" + )] + pub(crate) fn new( + attempt: &ExamAttempt, + exam: &Exam, + mark: Option, + people: &HashMap, + answered: u64, + question_count: u64, + attempts_used: u64, + now: Timestamp, + ) -> Self { + let status = attempt.status(exam, now); + let deadline = attempt.deadline(exam); + let remaining_ms = (status == AttemptStatus::InProgress) + .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0))) + .flatten(); + Self { + id: attempt.get_id().key().to_string(), + exam: attempt.get_exam().key().to_string(), + user: PersonRef::resolve(people, attempt.get_user()), + attempt: attempt.get_seq(), + attempts_used, + max_attempts: exam.get_max_attempts().as_i64(), + started_at: attempt.get_started_at().as_millis(), + finished_at: attempt.get_finished_at().map(|t| t.as_millis()), + left_at: attempt.get_left_at().map(|t| t.as_millis()), + status: status.as_str().to_string(), + deadline: deadline.map(|t| t.as_millis()), + remaining_ms, + mark: mark.map(|m| m.as_i64()), + answered, + question_count, + now: now.as_millis(), + } + } +} + +/// The (answered, question_count) pair behind an attempt view — how far one +/// student has come through the exam's question list. +pub(crate) async fn attempt_progress( + exam: &ExamId, + user: &UserId, + seq: i64, + db: &Database, +) -> Result<(u64, u64), AppError> { + let answered = ExamAnswer::list_for_exam_user(exam, user, seq, db) + .await? + .len() as u64; + let question_count = ExamQuestion::list_for_exam(exam, None, 0, db) + .await? + .0 + .len() as u64; + Ok((answered, question_count)) +} + +/// Rejects sitting an exam that can't be sat. A draft is a `404`, not a +/// `409` — sitting is a student act, drafts are invisible to students, and a +/// state-specific error would leak the existence this feature hides. A +/// modeless (offline-graded) exam is a `409`: visible, just nothing to sit. +/// Enrollment and window checks for the caller are the caller's own state — +/// also `Conflict`, not validation. +pub(crate) fn ensure_sittable(exam: &Exam) -> Result<(), AppError> { + if exam.is_draft() { + return Err(AppError::NotFound); + } + if exam.get_mode().is_none() { + return Err(AppError::Conflict( + "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)", + )); + } + Ok(()) +} + +/// How many sittings the caller has used at this exam. +pub(crate) async fn attempts_used( + exam: &ExamId, + user: &UserId, + db: &Database, +) -> Result { + Ok(ExamAttempt::list_for_user(exam, user, db).await?.len() as u64) +} + +/// Start, resume, or retake the caller's attempt. Requires the student role +/// (staff run exams, they don't sit them), enrollment in the exam's course, a +/// sittable exam (`sync`/`async`/`open` mode), and — when a window exists — the +/// window to be open. A still-running attempt is returned +/// as-is (`200` instead of `201`), so a reconnecting client gets its original +/// clock back — re-starting never resets the time. Once the latest attempt is +/// submitted or expired, re-posting starts the next sitting (`201`, blank +/// answer sheet) while the exam's `max_attempts` (0 = unlimited) allows it. +#[utoipa::path( + post, + path = "/{id}/attempt", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 201, description = "Attempt started (first sitting or a retake)", body = AttemptResponse), + (status = 200, description = "Running attempt resumed (unchanged)", body = AttemptResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), + (status = 404, description = "Exam not found (drafts are invisible here)", body = ErrorResponse), + (status = 409, description = "Unscheduled (offline-graded) exam, outside the window, or no attempts remaining", body = ErrorResponse), + ), +)] +pub(crate) async fn start_attempt( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result<(StatusCode, Json), AppError> { + // Writer lease of [`EXAM_LOCK`] from the exam read through the start: the + // sittable/window gates must be judged against the same exam row the + // attempt lands under (the mirror of `update_exam`'s re-derive — without + // it, a mode change or re-draft at legally-zero attempts could slip + // between this gate and the insert, leaving an attempt on an unsittable + // exam). The lease + // also keeps the max-attempts count and the retake's wipe-and-create + // from interleaving with an in-flight answer save (a reader). Dropped + // before the response reads — they only describe the row. + let guard = EXAM_LOCK.write().await; + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + ensure_sittable(&exam)?; + ensure_student(&user)?; + ensure_enrolled(&exam, user.get_id(), &st.db).await?; + let now = Timestamp::now(); + if let Some(starts_at) = exam.get_starts_at() + && now < starts_at + { + return Err(AppError::Conflict("the exam has not started yet")); + } + if let Some(ends_at) = exam.get_ends_at() + && now >= ends_at + { + return Err(AppError::Conflict("the exam has already ended")); + } + + // A retake no longer wipes the prior sitting — each attempt's answers, + // drawings, and marks stay put at their own seq (per-attempt history), so + // there are no orphaned blobs to GC here. The exam-delete cascade still + // cleans every sitting's blobs. + let (attempt, created) = ExamAttempt::start(&exam, user.get_id(), &st.db).await?; + drop(guard); + let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) + .await? + .map(|r| r.get_mark()); + let (answered, question_count) = + attempt_progress(exam.get_id(), user.get_id(), attempt.get_seq(), &st.db).await?; + let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?; + let people = PersonRef::map_of(&[&user]); + let status = if created { + StatusCode::CREATED + } else { + StatusCode::OK + }; + Ok(( + status, + Json(AttemptResponse::new( + &attempt, + &exam, + mark, + &people, + answered, + question_count, + used, + Timestamp::now(), + )), + )) +} + +/// The caller's own (latest) attempt: status, deadline, remaining time, and +/// mark once graded — everything a student's live exam screen needs, judged +/// by the server clock. `404` until an attempt is started. +#[utoipa::path( + get, + path = "/{id}/attempt", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 200, description = "The caller's latest attempt", body = AttemptResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "No such exam, or no attempt yet", body = ErrorResponse), + ), +)] +pub(crate) async fn my_attempt( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) + .await? + .map(|r| r.get_mark()); + let (answered, question_count) = + attempt_progress(exam.get_id(), user.get_id(), attempt.get_seq(), &st.db).await?; + let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?; + let people = PersonRef::map_of(&[&user]); + Ok(Json(AttemptResponse::new( + &attempt, + &exam, + mark, + &people, + answered, + question_count, + used, + Timestamp::now(), + ))) +} + +/// Submit the caller's attempt. Allowed while the deadline hasn't passed; +/// after it, the attempt is already `expired` (a valid terminal state — the +/// student used their full time) and submitting is a `409`. +#[utoipa::path( + post, + path = "/{id}/attempt/finish", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 200, description = "Attempt submitted", body = AttemptResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "No such exam, or no attempt to finish", body = ErrorResponse), + (status = 409, description = "Already submitted, or the deadline passed", body = ErrorResponse), + ), +)] +pub(crate) async fn finish_attempt( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if attempt.get_finished_at().is_some() { + return Err(AppError::Conflict("the attempt is already submitted")); + } + let now = Timestamp::now(); + if let Some(deadline) = attempt.deadline(&exam) + && now >= deadline + { + return Err(AppError::Conflict("time is up — the attempt has expired")); + } + + // Deliberately no rejoin check: a student locked out of the room may + // still submit what they saved — finishing answers nothing new. + let finished = attempt.finish(&st.db).await?; + let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) + .await? + .map(|r| r.get_mark()); + let (answered, question_count) = + attempt_progress(exam.get_id(), user.get_id(), finished.get_seq(), &st.db).await?; + let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?; + let people = PersonRef::map_of(&[&user]); + Ok(Json(AttemptResponse::new( + &finished, + &exam, + mark, + &people, + answered, + question_count, + used, + Timestamp::now(), + ))) +} + +// ---- live monitor --------------------------------------------------------- + +/// One roster row of the live exam monitor. The attempt fields describe the +/// student's *latest* sitting. +#[derive(Serialize, ToSchema)] +pub(crate) struct LiveStudentResponse { + user: PersonRef, + /// `not_started` | `absent` | `in_progress` | `submitted` | `expired`. + /// `absent` is `not_started` after the window closed: the student never + /// sat and no longer can. Open exams have no window, so nobody is ever + /// absent from one. + #[schema(example = "in_progress")] + status: String, + /// Which sitting the shown attempt is (1, 2, …); `null` before the first. + attempt: Option, + /// How many sittings this student has used. + attempts_used: u64, + started_at: Option, + finished_at: Option, + /// When this student left the exam room mid-attempt; `null` while inside. + left_at: Option, + /// When this student's attempt closes (server-authoritative). + deadline: Option, + /// Time this student has left, floored at 0; `null` unless in progress. + remaining_ms: Option, + /// The student's mark, once graded. + mark: Option, + /// How many questions this student has answered so far. + answered: u64, + /// When this student last saved an answer, UTC unix-milliseconds; `null` + /// before the first save. + last_activity: Option, +} + +#[derive(Serialize, ToSchema)] +pub(crate) struct LiveCountsResponse { + enrolled: u64, + /// Enrolled with no attempt while the window is still open (or the exam + /// has no window). + not_started: u64, + /// Enrolled with no attempt and the window closed — the no-shows. + absent: u64, + in_progress: u64, + submitted: u64, + expired: u64, + graded: u64, +} + +/// A live snapshot of an exam: the enrolled roster with per-student attempt +/// state, remaining time, and marks, all judged by one server-clock read. +#[derive(Serialize, ToSchema)] +pub(crate) struct ExamLiveResponse { + exam: ExamResponse, + /// Server clock the snapshot was judged at, UTC unix-milliseconds. + now: i64, + /// How many questions the exam has. + question_count: u64, + counts: LiveCountsResponse, + students: Vec, +} + +/// Build the monitor snapshot: roster ⋈ attempts ⋈ marks at one instant. +/// Students unenrolled mid-exam drop off the roster view (their attempt and +/// mark rows survive, exactly like the marks report). +pub(crate) async fn live_snapshot( + exam: &Exam, + db: &Database, +) -> Result { + let now = Timestamp::now(); + let (roster, _) = Enrollment::list_for_course(exam.get_course(), None, 0, db).await?; + // Per student: their latest sitting (the one the monitor shows) plus how + // many they've used. + let mut attempts: HashMap = HashMap::new(); + let mut used: HashMap = HashMap::new(); + for attempt in ExamAttempt::list_for_exam(exam.get_id(), db).await? { + let key = attempt.get_user().key().to_string(); + *used.entry(key.clone()).or_insert(0) += 1; + match attempts.entry(key) { + std::collections::hash_map::Entry::Vacant(slot) => { + slot.insert(attempt); + } + std::collections::hash_map::Entry::Occupied(mut slot) => { + if attempt.get_seq() > slot.get().get_seq() { + slot.insert(attempt); + } + } + } + } + let marks: HashMap = ExamResult::list_for_exam(exam.get_id(), db) + .await? + .iter() + .map(|result| { + ( + result.get_user().key().to_string(), + result.get_mark().as_i64(), + ) + }) + .collect(); + let question_count = ExamQuestion::list_for_exam(exam.get_id(), None, 0, db) + .await? + .0 + .len() as u64; + // Per-student progress: answer count and the latest save instant. The + // per-exam read now returns every sitting's rows across all students, so + // each answer is scoped to that student's *current* sitting — matching its + // seq to their latest attempt — or a re-sitting student's count would + // double up their prior attempts. + let mut progress: HashMap = HashMap::new(); + for answer in ExamAnswer::list_for_exam(exam.get_id(), db).await? { + let key = answer.get_user().key().to_string(); + if attempts.get(&key).map(ExamAttempt::get_seq) != Some(answer.get_seq()) { + continue; + } + let entry = progress.entry(key).or_insert((0, i64::MIN)); + entry.0 += 1; + entry.1 = entry.1.max(answer.get_updated_at().as_millis()); + } + let people = person_map(roster.iter().map(|e| e.get_user().clone()), db).await?; + + // Once the window closes the door is shut for good (starting answers + // 409), so "hasn't started" hardens into "was absent". Open exams have + // no window and never make that call. + let window_over = exam.get_ends_at().is_some_and(|ends| now >= ends); + let mut students: Vec = roster + .iter() + .map(|enrollment| { + let key = enrollment.get_user().key(); + let attempt = attempts.get(key); + let status = attempt.map(|a| a.status(exam, now)); + let deadline = attempt.and_then(|a| a.deadline(exam)); + LiveStudentResponse { + user: PersonRef::resolve(&people, enrollment.get_user()), + status: match status { + Some(status) => status.as_str(), + None if window_over => "absent", + None => "not_started", + } + .to_string(), + attempt: attempt.map(ExamAttempt::get_seq), + attempts_used: used.get(key).copied().unwrap_or(0), + started_at: attempt.map(|a| a.get_started_at().as_millis()), + finished_at: attempt + .and_then(|a| a.get_finished_at()) + .map(|t| t.as_millis()), + left_at: attempt.and_then(|a| a.get_left_at()).map(|t| t.as_millis()), + deadline: deadline.map(|t| t.as_millis()), + remaining_ms: (status == Some(AttemptStatus::InProgress)) + .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0))) + .flatten(), + mark: marks.get(key).copied(), + answered: progress.get(key).map_or(0, |p| p.0), + last_activity: progress.get(key).map(|p| p.1), + } + }) + .collect(); + students.sort_by(|a, b| a.user.username.cmp(&b.user.username)); + + let count = |status: &str| students.iter().filter(|s| s.status == status).count() as u64; + let counts = LiveCountsResponse { + enrolled: students.len() as u64, + not_started: count("not_started"), + absent: count("absent"), + in_progress: count("in_progress"), + submitted: count("submitted"), + expired: count("expired"), + graded: students.iter().filter(|s| s.mark.is_some()).count() as u64, + }; + Ok(ExamLiveResponse { + exam: ExamResponse::new(exam), + now: now.as_millis(), + question_count, + counts, + students, + }) +} + +/// A one-shot live snapshot of the exam: who's in, who's still writing (and +/// on which sitting), who walked out of the room (`left_at`), who never +/// showed at all (`absent`, once the window is over), time each student has +/// left, and marks as they land. Requires teacher+ and management rights +/// over the exam's course. Poll it to keep a monitor up to date. +#[utoipa::path( + get, + path = "/{id}/live", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 200, description = "Live snapshot", body = ExamLiveResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Exam not found", body = ErrorResponse), + ), +)] +pub(crate) async fn exam_live( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, +) -> Result, AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can monitor this exam", + )); + } + Ok(Json(live_snapshot(&exam, &st.db).await?)) +} + +// ---- answers ---------------------------------------------------------------- +// Students answer inside their attempt; every save is an upsert stamped with +// the server clock. The WebSocket room (`/exams/{id}/attempt/ws`) drives the +// same paths below. + +/// A student's own saved answer, embedded in their question view. +#[derive(Serialize, ToSchema)] +pub(crate) struct AnswerStateResponse { + /// The picked option's id (`choice` questions). + selected: Option, + /// The typed answer (`text` questions). + text: Option, + /// When this answer was last saved, UTC unix-milliseconds. + updated_at: i64, + /// The student's own drawn answer, if any — bytes at + /// `GET /exams/{id}/attempt/answers/{qid}/image`. + answer_image: Option, +} + +impl AnswerStateResponse { + pub(crate) fn new(answer: &ExamAnswer, answer_image: Option) -> Self { + Self { + selected: answer.get_selected().map(|id| id.as_str().to_string()), + text: answer.get_text().map(|t| t.as_str().to_string()), + updated_at: answer.get_updated_at().as_millis(), + answer_image, + } + } +} + +/// A question as the sitting student sees it: no `correct` choice id, their own +/// saved answer embedded. +#[derive(Serialize, ToSchema)] +pub(crate) struct AttemptQuestionResponse { + id: String, + /// The subject this question belongs to (`GET /subjects/{id}`). + subject: String, + text: String, + /// `choice` or `text`. + #[schema(example = "choice")] + kind: String, + points: i64, + /// The options with their ids — and deliberately *not* `correct`: this DTO + /// leaks no answer key because it has no field to carry one, and + /// `ChoiceResponse` carries none either. + choices: Option>, + /// The question's illustration, if any — bytes at + /// `GET /exams/{id}/questions/{qid}/image`. + image: Option, + /// Per-option pictures aligned with `choices`, if any — bytes at + /// `GET /exams/{id}/questions/{qid}/choices/{choice_id}/image`. + choice_images: Option>>, + /// The caller's saved answer; `null` while unanswered. + answer: Option, +} + +#[derive(Deserialize, ToSchema)] +pub(crate) struct SaveAnswer { + /// The question being answered. + question_id: String, + /// The picked option's `id` — required for `choice` questions. + selected: Option, + /// The typed answer — required for `text` questions (empty clears the draft). + #[schema(max_length = 10000)] + text: Option, +} + +#[derive(Serialize, ToSchema)] +pub(crate) struct AnswerSavedResponse { + question: String, + /// The picked option's id. + selected: Option, + text: Option, + /// Save instant by the server clock, UTC unix-milliseconds. + updated_at: i64, +} + +/// The caller's latest attempt provided it is still writable, or the error +/// that says why not: no attempt yet (404 — start it first), already +/// submitted (409), deadline passed (409). One gate shared by REST saves and +/// the WebSocket room. +pub(crate) async fn writable_attempt( + exam: &Exam, + user: &UserId, + db: &Database, +) -> Result { + let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user, db) + .await? + .ok_or(AppError::NotFound)?; + match attempt.status(exam, Timestamp::now()) { + AttemptStatus::Submitted => Err(AppError::Conflict("the attempt is already submitted")), + AttemptStatus::Expired => Err(AppError::Conflict("time is up — the attempt has expired")), + AttemptStatus::InProgress => Ok(attempt), + } +} + +/// A 409 when the student has walked out of the exam room and the exam's +/// rejoin door is closed: no more answering (from anywhere) until the teacher +/// flips `allow_rejoin` back on. Finishing is deliberately exempt — see +/// `finish_attempt`. +pub(crate) fn check_rejoin(exam: &Exam, attempt: &ExamAttempt) -> Result<(), AppError> { + if attempt.get_left_at().is_some() && !exam.get_allow_rejoin() { + return Err(AppError::Conflict( + "you left the exam and rejoin is closed — ask your teacher to reopen it", + )); + } + Ok(()) +} + +/// Save one answer inside the caller's in-progress attempt — the whole write +/// path (attempt gate, rejoin gate, question lookup, kind check, upsert). The +/// REST handler saves into the latest sitting via this; the WebSocket room +/// resolves its own sitting first and shares [`save_answer_in`], so the two +/// can never drift. +pub(crate) async fn save_answer_checked( + exam: &Exam, + user: &UserId, + question_id: &str, + selected: Option, + text: Option, + db: &Database, +) -> Result { + // Reader lease of [`EXAM_LOCK`]: the writable gate and the upsert are + // one unit, or a retake's wipe-and-create (a writer) slips in between + // and this stale save lands on the fresh blank sheet. + let _guard = EXAM_LOCK.read().await; + let attempt = writable_attempt(exam, user, db).await?; + save_answer_in(exam, &attempt, question_id, selected, text, db).await +} + +/// The tail of the answer write path, given the sitting to write in: the +/// student wall and the enrollment wall (a promotion out of `student` or an +/// unenrollment closes the sheet, mid-exam included), the rejoin gate, the +/// question lookup, and the upsert. +pub(crate) async fn save_answer_in( + exam: &Exam, + attempt: &ExamAttempt, + question_id: &str, + selected: Option, + text: Option, + db: &Database, +) -> Result { + ensure_student_now(attempt.get_user(), db).await?; + ensure_enrolled(exam, attempt.get_user(), db).await?; + check_rejoin(exam, attempt)?; + let question = question_of_exam(exam.get_id(), question_id, db).await?; + ExamAnswer::save( + &question, + attempt.get_user(), + attempt.get_seq(), + selected, + text, + db, + ) + .await +} + +/// A 403 unless `user` is a student. Sitting an exam is a student action — +/// teachers and above run exams, they never take them — so the sit paths +/// (start, room, save) enforce it on the *current* role. Checking the live +/// role, not just enrollment, closes the gap a mid-exam promotion would open +/// and neutralizes any stale non-student enrollment. Reading one's own attempt +/// and finishing stay ungated: a non-student has no attempt to read, and +/// finishing only submits work already saved. +pub(crate) fn ensure_student(user: &User) -> Result<(), AppError> { + if user.get_role() != Role::Student { + return Err(AppError::Forbidden("only students can sit exams")); + } + Ok(()) +} + +/// The answer path's live edition of [`ensure_student`]: re-read the row and +/// judge the *current* role, exactly like the enrollment wall beside it. Both +/// save paths run through here (REST per request, the exam room per message), +/// so a promotion out of `student` mid-exam closes the sheet on the very next +/// save — the room's door check is not the last word for a socket that +/// outlives the role. +pub(crate) async fn ensure_student_now(user: &UserId, db: &Database) -> Result<(), AppError> { + let user = User::read(user, db).await?.ok_or(AppError::Unauthorized)?; + ensure_student(&user) +} + +/// A 403 unless `user` is enrolled in the exam's course — the same wall the +/// exam room checks at its door, re-applied to the sitting's content paths so +/// an unenrollment mid-exam cuts them too. Finishing stays exempt: like the +/// rejoin lock, submitting what's already saved writes nothing new. +pub(crate) async fn ensure_enrolled( + exam: &Exam, + user: &UserId, + db: &Database, +) -> Result<(), AppError> { + if Enrollment::read_for_user(exam.get_course(), user, db) + .await? + .is_none() + { + return Err(AppError::Forbidden( + "you are not enrolled in this exam's course", + )); + } + Ok(()) +} + +/// The exam's questions as the sitting student sees them: `correct` stripped, +/// their own saved answers embedded — the latest sitting's, since a retake +/// starts from a blank sheet. Requires enrollment in the exam's course (the +/// questions are course content — leaving the course closes them) and an +/// attempt — start one with `POST /exams/{id}/attempt` first (404 until +/// then). Readable in every attempt state, so a submitted student can still +/// review what they wrote. +#[utoipa::path( + get, + path = "/{id}/attempt/questions", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 200, description = "Questions with the caller's answers embedded", body = [AttemptQuestionResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse), + (status = 404, description = "No such exam, or no attempt yet — start the attempt first", body = ErrorResponse), + ), +)] +pub(crate) async fn attempt_questions( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result>, AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + ensure_enrolled(&exam, user.get_id(), &st.db).await?; + // The question list is for sitting students; without an attempt there is + // nothing to sit behind — and no early peek at the questions. The embedded + // answers are the *current* sitting's only, so the seq scopes the reads. + let seq = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)? + .get_seq(); + + let (questions, _) = ExamQuestion::list_for_exam(exam.get_id(), None, 0, &st.db).await?; + let images = images_by_question(exam.get_id(), &st.db).await?; + let answers: HashMap = + ExamAnswer::list_for_exam_user(exam.get_id(), user.get_id(), seq, &st.db) + .await? + .into_iter() + .map(|answer| (answer.get_question().key().to_string(), answer)) + .collect(); + let answer_images: HashMap = + AnswerImage::list_for_exam_user(exam.get_id(), user.get_id(), seq, &st.db) + .await? + .into_iter() + .map(|image| (image.get_question().key().to_string(), image)) + .collect(); + Ok(Json( + questions + .iter() + .map(|question| { + let question_images = images + .get(question.get_id().key()) + .map_or(&[][..], Vec::as_slice); + AttemptQuestionResponse { + id: question.get_id().key().to_string(), + subject: question.get_subject().key().to_string(), + text: question.get_text().as_str().to_string(), + kind: question.get_kind().as_str().to_string(), + points: question.get_points().as_i64(), + choices: ChoiceResponse::list(question.get_choices()), + image: image_meta(question_images, None), + choice_images: choice_image_metas(question, question_images), + answer: answers.get(question.get_id().key()).map(|answer| { + AnswerStateResponse::new( + answer, + answer_images + .get(question.get_id().key()) + .map(ImageMetaResponse::from_answer), + ) + }), + } + }) + .collect(), + )) +} + +/// Save (or overwrite) one answer in the caller's in-progress attempt. +/// `choice` questions take `selected`; `text` questions take `text`. Requires +/// the student role and enrollment in the exam's course — an unenrollment (or a +/// promotion out of `student`) mid-exam closes the sheet. Rejected once the +/// attempt is submitted or its deadline has passed — +/// the server clock, not the client's, is the judge — and rejected while the +/// student has left the exam room with the exam's rejoin door closed. +#[utoipa::path( + post, + path = "/{id}/attempt/answers", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + request_body = SaveAnswer, + responses( + (status = 200, description = "Answer saved", body = AnswerSavedResponse), + (status = 400, description = "Payload doesn't match the question's kind", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), + (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse), + (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), + ), +)] +pub(crate) async fn save_answer( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + ensure_student(&user)?; + let answer = save_answer_checked( + &exam, + user.get_id(), + &req.question_id, + req.selected, + req.text, + &st.db, + ) + .await?; + Ok(Json(AnswerSavedResponse { + question: answer.get_question().key().to_string(), + selected: answer.get_selected().map(|id| id.as_str().to_string()), + text: answer.get_text().map(|t| t.as_str().to_string()), + updated_at: answer.get_updated_at().as_millis(), + })) +} + +/// One student's answer sheet with correctness flags — always the *latest* +/// sitting's answers (a retake starts from a blank sheet). Every row carries +/// the saved answer plus `is_correct` (`null` for text questions — those are +/// the grader's call), and the machine's `auto_score` over the choice +/// questions is attached as a *suggestion*: the final mark stays human, via +/// `POST /exams/{id}/results`. Requires teacher+ and management rights over +/// the exam's course. +#[utoipa::path( + get, + path = "/{id}/attempts/{user}/answers", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("user" = String, Path, description = "User id"), + ), + responses( + (status = 200, description = "The student's answers, judged", body = AttemptAnswersResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, or the student has no attempt", body = ErrorResponse), + ), +)] +pub(crate) async fn attempt_answers( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, target)): Path<(String, String)>, +) -> Result, AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can read answer sheets", + )); + } + let target = UserId::from_key(&target); + // No attempt means no answer sheet — a 404, not an empty one. This grading + // view shows the *latest* sitting; prior sittings live under the + // per-attempt history endpoints. + let seq = ExamAttempt::read_latest_for_user(exam.get_id(), &target, &st.db) + .await? + .ok_or(AppError::NotFound)? + .get_seq(); + Ok(Json(answer_sheet(&exam, &target, seq, &st.db).await?)) +} + +/// One sitting's judged answer sheet: the `seq`th attempt's answers, drawing +/// refs, correctness flags, and auto-score suggestion. Shared by the latest- +/// sitting grading view and the per-attempt history endpoint. +pub(crate) async fn answer_sheet( + exam: &Exam, + target: &UserId, + seq: i64, + db: &Database, +) -> Result { + let (questions, _) = ExamQuestion::list_for_exam(exam.get_id(), None, 0, db).await?; + let answers = ExamAnswer::list_for_exam_user(exam.get_id(), target, seq, db).await?; + let answer_images: HashMap = + AnswerImage::list_for_exam_user(exam.get_id(), target, seq, db) + .await? + .into_iter() + .map(|image| (image.get_question().key().to_string(), image)) + .collect(); + let by_question: HashMap<&str, &ExamQuestion> = questions + .iter() + .map(|question| (question.get_id().key(), question)) + .collect(); + let (earned, possible) = auto_score(&questions, &answers); + let people = person_map([target.clone()], db).await?; + Ok(AttemptAnswersResponse { + exam: exam.get_id().key().to_string(), + user: PersonRef::resolve(&people, target), + answers: answers + .iter() + .map(|answer| StudentAnswerResponse { + question: answer.get_question().key().to_string(), + selected: answer.get_selected().map(|id| id.as_str().to_string()), + text: answer.get_text().map(|t| t.as_str().to_string()), + updated_at: answer.get_updated_at().as_millis(), + is_correct: by_question + .get(answer.get_question().key()) + .and_then(|question| answer.is_correct(question)), + answer_image: answer_images + .get(answer.get_question().key()) + .map(ImageMetaResponse::from_answer), + }) + .collect(), + auto_score: AutoScoreResponse { earned, possible }, + }) +} + +/// One row of a student's answer sheet, as the grader sees it. +#[derive(Serialize, ToSchema)] +pub(crate) struct StudentAnswerResponse { + question: String, + /// The picked option's id. + selected: Option, + text: Option, + /// When the answer was last saved, UTC unix-milliseconds. + updated_at: i64, + /// Whether `selected` hits the question's `correct`; `null` for text + /// questions (the grader judges those). + is_correct: Option, + /// The student's drawn answer, if any — bytes at + /// `GET /exams/{id}/attempts/{user}/answers/{qid}/image`. + answer_image: Option, +} + +/// The machine's scoring suggestion over the choice questions. +#[derive(Serialize, ToSchema)] +pub(crate) struct AutoScoreResponse { + /// Points earned where `selected == correct`. + earned: i64, + /// Total points across the exam's choice questions. + possible: i64, +} + +/// A student's full answer sheet for grading. +#[derive(Serialize, ToSchema)] +pub(crate) struct AttemptAnswersResponse { + exam: String, + /// The student whose sheet this is. + user: PersonRef, + answers: Vec, + /// The suggested score over choice questions — never the final mark. + auto_score: AutoScoreResponse, +} diff --git a/src/web/exams/images.rs b/src/web/exams/images.rs new file mode 100644 index 0000000..7b8d1d1 --- /dev/null +++ b/src/web/exams/images.rs @@ -0,0 +1,651 @@ +use super::*; + +/// A stored question image's metadata; the bytes come from the image +/// endpoints (`GET .../image`, `GET .../choices/{choice_id}/image`). +#[derive(Serialize, ToSchema)] +pub(crate) struct ImageMetaResponse { + /// MIME type as declared on upload (always one of the raster allowlist). + #[schema(example = "image/png")] + content_type: String, + /// Image size in bytes. + #[schema(example = 24_576)] + size: i64, +} + +impl ImageMetaResponse { + pub(crate) fn new(image: &QuestionImage) -> Self { + Self { + content_type: image.get_content_type().as_str().to_string(), + size: image.get_size(), + } + } + + pub(crate) fn from_answer(image: &AnswerImage) -> Self { + Self { + content_type: image.get_content_type().as_str().to_string(), + size: image.get_size(), + } + } +} + +/// The question's slot out of its image rows. +pub(crate) fn image_meta( + images: &[QuestionImage], + slot: Option<&ChoiceId>, +) -> Option { + images + .iter() + .find(|image| image.get_slot() == slot) + .map(ImageMetaResponse::new) +} + +/// The per-choice metas, aligned position-for-position with `choices` (`None` +/// entries = that option has no picture); `None` whole for text questions. +/// A response-only projection: the pictures are *stored* against choice ids, so +/// this alignment is rebuilt from the current list on every read and can never +/// go stale. +pub(crate) fn choice_image_metas( + question: &ExamQuestion, + images: &[QuestionImage], +) -> Option>> { + question.get_choices().map(|choices| { + choices + .iter() + .map(|choice| image_meta(images, Some(choice.get_id()))) + .collect() + }) +} + +/// `exam`'s image rows bucketed by question key — one query feeding a whole +/// question list. +pub(crate) async fn images_by_question( + exam: &ExamId, + db: &Database, +) -> Result>, AppError> { + let mut buckets: HashMap> = HashMap::new(); + for image in QuestionImage::list_for_exam(exam, db).await? { + buckets + .entry(image.get_question().key().to_string()) + .or_default() + .push(image); + } + Ok(buckets) +} + +// ---- question images ---------------------------------------------------------- +// A question may carry one illustration (any kind — the map above the prompt) +// and, on choice questions, one picture per option (pick the right city off +// the map). Uploads are teacher authoring and freeze with the rest of the +// question once attempts exist; metadata rides on the question DTOs, bytes +// flow through the GET endpoints below, whose access follows the question's +// own visibility (author side and sitting side alike). + +/// The exam, provided the caller may author its questions — the shared front +/// half of every image write. +pub(crate) async fn image_managed_exam( + st: &AppState, + user: &User, + id: &str, +) -> Result { + let exam = Exam::read(&ExamId::from_key(id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can manage question images", + )); + } + Ok(exam) +} + +/// A 403/404 unless the caller may see the exam's question content: course +/// managers always, students through the same wall as +/// `GET /exams/{id}/attempt/questions` — enrollment plus a started attempt, +/// so there is no early peek at the pictures either. +pub(crate) async fn ensure_question_content_visible( + st: &AppState, + exam: &Exam, + user: &User, +) -> Result<(), AppError> { + let course = course_of(exam, &st.db).await?; + if can_manage_course(&course, user) { + return Ok(()); + } + ensure_enrolled(exam, user.get_id(), &st.db).await?; + ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + Ok(()) +} + +/// The image write tail, shared by both upload endpoints: the slot's current +/// row names the blob to retire, the UPSERT replaces it (the deterministic +/// per-slot id makes it a replace), and [`store_blob`] owns the disk ordering. +pub(crate) async fn store_image( + st: &AppState, + exam: &Exam, + question: &ExamQuestion, + slot: Option<&ChoiceId>, + content_type: FileContentType, + data: &[u8], +) -> Result { + let replaced = QuestionImage::read_slot(question.get_id(), slot, &st.db).await?; + let image = QuestionImage::new( + exam.get_id(), + question.get_id(), + slot, + content_type, + data.len() as i64, + ); + let file = image.get_file().to_string(); + store_blob(st, &file, data, || async { + let stored = image.upsert(&st.db).await?; + Ok((stored, replaced.map(|old| old.get_file().to_string()))) + }) + .await +} + +/// The stored bytes, served inline via [`crate::web::serve_inline_blob`]. +pub(crate) async fn serve_image( + st: &AppState, + image: &QuestionImage, +) -> Result { + crate::web::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await +} + +/// Attach (or replace) a question's illustration — any question kind may +/// carry one, e.g. the map the prompt asks about. `multipart/form-data` with +/// the image under a `file` field; the declared content type must be +/// `image/png`, `image/jpeg`, `image/webp`, or `image/gif` (rasters only — +/// no SVG), the bytes at most the school's `max_file_bytes` (settings). +/// Requires teacher+ and management rights over the exam's course; frozen +/// once attempts exist, like every other question edit. +#[utoipa::path( + post, + path = "/{id}/questions/{qid}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ), + request_body(content = UploadFileForm, content_type = "multipart/form-data"), + responses( + (status = 201, description = "Image stored", body = ImageMetaResponse), + (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), + ), +)] +pub(crate) async fn upload_question_image( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, qid)): Path<(String, String)>, + mut multipart: Multipart, +) -> Result<(StatusCode, Json), AppError> { + let exam = image_managed_exam(&st, &user, &id).await?; + // The body is consumed before the lock — a client's slow upload must not + // stall the exam subsystem. + let ImageUpload { content_type, data } = read_image_upload(&st, &mut multipart).await?; + // No lock: the freeze gate is part of the image row's own transaction + // (`QuestionImage::upsert`), and this path checks no subject. The + // pre-flight below is the fast 409 and the byte-identical error. + ensure_questions_editable(exam.get_id(), &st.db).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let stored = store_image(&st, &exam, &question, None, content_type, &data).await?; + Ok((StatusCode::CREATED, Json(ImageMetaResponse::new(&stored)))) +} + +/// The question's illustration bytes. Course managers read anytime; students +/// through the same wall as the sitting view — enrollment plus a started +/// attempt (404 before that, like the question list itself). +#[utoipa::path( + get, + path = "/{id}/questions/{qid}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ), + responses( + (status = 200, description = "The image bytes", content_type = "image/*"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse), + (status = 404, description = "No such exam, question, or image — or no attempt yet", body = ErrorResponse), + ), +)] +pub(crate) async fn get_question_image( + State(st): State, + CurrentUser(user): CurrentUser, + Path((id, qid)): Path<(String, String)>, +) -> Result { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + ensure_question_content_visible(&st, &exam, &user).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let image = QuestionImage::read_slot(question.get_id(), None, &st.db) + .await? + .ok_or(AppError::NotFound)?; + serve_image(&st, &image).await +} + +/// Remove a question's illustration. Requires teacher+ and management rights +/// over the exam's course; frozen once attempts exist. +#[utoipa::path( + delete, + path = "/{id}/questions/{qid}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, question, or image", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + ), +)] +pub(crate) async fn delete_question_image( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, qid)): Path<(String, String)>, +) -> Result { + let exam = image_managed_exam(&st, &user, &id).await?; + ensure_questions_editable(exam.get_id(), &st.db).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let image = QuestionImage::read_slot(question.get_id(), None, &st.db) + .await? + .ok_or(AppError::NotFound)?; + let image = image.delete(&st.db).await?; + remove_blob(&st.files_path, image.get_file()).await; + Ok(StatusCode::NO_CONTENT) +} + +/// Attach (or replace) one option's picture on a `choice` question — so the +/// options themselves can be images (four map crops, pick the right one). +/// Same form, limits, and rights as the question-image upload; `choice_id` is +/// the `id` carried on that choice, as returned in the question's `choices` +/// (not a position — an unknown id is a `400`). Replacing the question's +/// `choices` list drops all its option pictures — re-upload against the new +/// list. +#[utoipa::path( + post, + path = "/{id}/questions/{qid}/choices/{choice_id}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ("choice_id" = String, Path, description = "Choice id, as returned in the question's `choices`"), + ), + request_body(content = UploadFileForm, content_type = "multipart/form-data"), + responses( + (status = 201, description = "Image stored", body = ImageMetaResponse), + (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), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), + ), +)] +pub(crate) async fn upload_choice_image( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, qid, choice_id)): Path<(String, String, String)>, + mut multipart: Multipart, +) -> Result<(StatusCode, Json), AppError> { + let exam = image_managed_exam(&st, &user, &id).await?; + let ImageUpload { content_type, data } = read_image_upload(&st, &mut multipart).await?; + ensure_questions_editable(exam.get_id(), &st.db).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let slot = choice_slot(&question, &choice_id)?; + let stored = store_image(&st, &exam, &question, Some(&slot), content_type, &data).await?; + Ok((StatusCode::CREATED, Json(ImageMetaResponse::new(&stored)))) +} + +/// One option's picture bytes. Same access wall as the question-image read. +#[utoipa::path( + get, + path = "/{id}/questions/{qid}/choices/{choice_id}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ("choice_id" = String, Path, description = "Choice id"), + ), + responses( + (status = 200, description = "The image bytes", content_type = "image/*"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse), + (status = 404, description = "No such exam, question, or image — or no attempt yet", body = ErrorResponse), + ), +)] +pub(crate) async fn get_choice_image( + State(st): State, + CurrentUser(user): CurrentUser, + Path((id, qid, choice_id)): Path<(String, String, String)>, +) -> Result { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + ensure_question_content_visible(&st, &exam, &user).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let slot = choice_slot(&question, &choice_id)?; + let image = QuestionImage::read_slot(question.get_id(), Some(&slot), &st.db) + .await? + .ok_or(AppError::NotFound)?; + serve_image(&st, &image).await +} + +/// Remove one option's picture. Requires teacher+ and management rights over +/// the exam's course; frozen once attempts exist. +#[utoipa::path( + delete, + path = "/{id}/questions/{qid}/choices/{choice_id}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ("choice_id" = String, Path, description = "Choice id"), + ), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, question, or image", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + ), +)] +pub(crate) async fn delete_choice_image( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, qid, choice_id)): Path<(String, String, String)>, +) -> Result { + let exam = image_managed_exam(&st, &user, &id).await?; + ensure_questions_editable(exam.get_id(), &st.db).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let slot = choice_slot(&question, &choice_id)?; + let image = QuestionImage::read_slot(question.get_id(), Some(&slot), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let image = image.delete(&st.db).await?; + remove_blob(&st.files_path, image.get_file()).await; + Ok(StatusCode::NO_CONTENT) +} + +// ---- answer images ---------------------------------------------------------- +// A student's freehand drawing of their answer to a question — one per (exam, +// user, question), the answer-side mirror of the teacher's question images. +// It is a normal `image/png` (the frontend embeds its editable stroke JSON in a +// PNG `tEXt` chunk, opaque to us), so it flows through the same raster +// content-type wall and inline-serve path as every other exam image. The write +// paths ride the exact `save_answer` gate chain; the reads follow the question +// content's own visibility (own sitting view / teacher grading view). + +/// The answer-image write tail, mirroring [`store_image`]: the deterministic +/// per-(question, user, seq) id makes the UPSERT a replace, and [`store_blob`] +/// owns the disk ordering. +pub(crate) async fn store_answer_image( + st: &AppState, + exam: &Exam, + question: &ExamQuestion, + user: &UserId, + seq: i64, + content_type: FileContentType, + data: &[u8], +) -> Result { + let replaced = AnswerImage::read(question.get_id(), user, seq, &st.db).await?; + let image = AnswerImage::new( + exam.get_id(), + question.get_id(), + user, + seq, + content_type, + data.len() as i64, + ); + let file = image.get_file().to_string(); + store_blob(st, &file, data, || async { + let stored = image.upsert(&st.db).await?; + Ok((stored, replaced.map(|old| old.get_file().to_string()))) + }) + .await +} + +/// Attach (or replace) the caller's drawn answer to a question inside their +/// in-progress attempt. `multipart/form-data` with the drawing under a `file` +/// field; the declared content type must be `image/png`, `image/jpeg`, +/// `image/webp`, or `image/gif` (rasters only — no SVG), the bytes at most the +/// school's `max_file_bytes`. Rides the exact `POST /exams/{id}/attempt/answers` +/// gate chain: the student role, an in-progress attempt, current enrollment, and +/// the rejoin door. +#[utoipa::path( + post, + path = "/{id}/attempt/answers/{qid}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ), + request_body(content = UploadFileForm, content_type = "multipart/form-data"), + responses( + (status = 201, description = "Drawing stored", body = ImageMetaResponse), + (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), + (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse), + (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), + (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), + ), +)] +pub(crate) async fn upload_answer_image( + State(st): State, + CurrentUser(user): CurrentUser, + Path((id, qid)): Path<(String, String)>, + mut multipart: Multipart, +) -> Result<(StatusCode, Json), AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + ensure_student(&user)?; + // The body is consumed before the lock — a client's slow upload must not + // stall the exam subsystem (mirrors the question-image upload). + let ImageUpload { content_type, data } = read_image_upload(&st, &mut multipart).await?; + // Reader lease of [`EXAM_LOCK`], exactly like `save_answer_checked`: the + // writable gate and the write are one unit, or a retake's wipe-and-create + // (a writer) slips in between and this stale drawing lands on the fresh + // blank sheet. + let _guard = EXAM_LOCK.read().await; + let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; + ensure_student_now(attempt.get_user(), &st.db).await?; + ensure_enrolled(&exam, attempt.get_user(), &st.db).await?; + check_rejoin(&exam, &attempt)?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let seq = attempt.get_seq(); + let stored = store_answer_image( + &st, + &exam, + &question, + user.get_id(), + seq, + content_type, + &data, + ) + .await?; + // A drawing-only answer (drew, typed nothing) still needs an ExamAnswer row, + // or the drawing never surfaces in the sitting/grading views — answer_image + // rides the answer payload. Create a blank text answer when absent, without + // clobbering typed text. Choice questions can't hold a blank answer (and the + // UI only offers drawing on text questions), so they are skipped. Removing + // the drawing later grooms this blank row away (see `delete_answer_image`). + if question.get_kind().as_str() != "choice" + && ExamAnswer::read(question.get_id(), user.get_id(), seq, &st.db) + .await? + .is_none() + { + ExamAnswer::save( + &question, + user.get_id(), + seq, + None, + Some(String::new()), + &st.db, + ) + .await?; + } + Ok(( + StatusCode::CREATED, + Json(ImageMetaResponse::from_answer(&stored)), + )) +} + +/// Clear the caller's drawn answer to a question. Same writable-attempt gate +/// chain as the upload. +#[utoipa::path( + delete, + path = "/{id}/attempt/answers/{qid}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), + (status = 404, description = "No such exam, question, attempt, or drawing", body = ErrorResponse), + (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), + ), +)] +pub(crate) async fn delete_answer_image( + State(st): State, + CurrentUser(user): CurrentUser, + Path((id, qid)): Path<(String, String)>, +) -> Result { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + ensure_student(&user)?; + let _guard = EXAM_LOCK.read().await; + let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; + ensure_student_now(attempt.get_user(), &st.db).await?; + ensure_enrolled(&exam, attempt.get_user(), &st.db).await?; + check_rejoin(&exam, &attempt)?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let seq = attempt.get_seq(); + let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db) + .await? + .ok_or(AppError::NotFound)?; + let image = image.delete(&st.db).await?; + remove_blob(&st.files_path, image.get_file()).await; + // If the drawing was the whole answer (blank text, no choice — the row the + // upload created for a drawing-only answer), drop it too so it stops counting + // as answered. A typed answer keeps its row. + if let Some(answer) = ExamAnswer::read(question.get_id(), user.get_id(), seq, &st.db).await? { + let blank = answer.get_selected().is_none() + && answer.get_text().is_none_or(|t| t.as_str().is_empty()); + if blank { + ExamAnswer::delete(question.get_id(), user.get_id(), seq, &st.db).await?; + } + } + Ok(StatusCode::NO_CONTENT) +} + +/// The caller's own drawn-answer bytes. Same visibility wall as the sitting +/// question view — enrollment plus a started attempt (404 before that). +#[utoipa::path( + get, + path = "/{id}/attempt/answers/{qid}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ), + responses( + (status = 200, description = "The drawing bytes", content_type = "image/*"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse), + (status = 404, description = "No such exam, question, or drawing — or no attempt yet", body = ErrorResponse), + ), +)] +pub(crate) async fn get_answer_image( + State(st): State, + CurrentUser(user): CurrentUser, + Path((id, qid)): Path<(String, String)>, +) -> Result { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + ensure_question_content_visible(&st, &exam, &user).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + // The caller's current sitting — the drawing belongs to their latest seq. + let seq = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)? + .get_seq(); + let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db) + .await? + .ok_or(AppError::NotFound)?; + crate::web::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await +} + +/// One student's drawn-answer bytes, for the grader. Requires teacher+ and +/// management rights over the exam's course — the `attempt_answers` gate. +#[utoipa::path( + get, + path = "/{id}/attempts/{user}/answers/{qid}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("user" = String, Path, description = "User id"), + ("qid" = String, Path, description = "Question id"), + ), + responses( + (status = 200, description = "The student's drawing bytes", content_type = "image/*"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, question, or drawing", body = ErrorResponse), + ), +)] +pub(crate) async fn get_student_answer_image( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, target, qid)): Path<(String, String, String)>, +) -> Result { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can read answer sheets", + )); + } + let target = UserId::from_key(&target); + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + // The grader's default view is the latest sitting; per-attempt drawings + // come from the history image endpoint. + let seq = ExamAttempt::read_latest_for_user(exam.get_id(), &target, &st.db) + .await? + .ok_or(AppError::NotFound)? + .get_seq(); + let image = AnswerImage::read(question.get_id(), &target, seq, &st.db) + .await? + .ok_or(AppError::NotFound)?; + crate::web::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await +} diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs new file mode 100644 index 0000000..96fb081 --- /dev/null +++ b/src/web/exams/mod.rs @@ -0,0 +1,842 @@ +use std::collections::HashMap; + +use axum::Json; +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; +use axum::http::StatusCode; +use axum::response::Response; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::constant::{CAS_UPDATE_RETRIES, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; +use crate::database::Database; +use crate::domain::answer_image::AnswerImage; +use crate::domain::bank_question::{BankQuestion, BankQuestionId}; +use crate::domain::bank_question_image::BankQuestionImage; +use crate::domain::course::Course; +use crate::domain::enrollment::Enrollment; +use crate::domain::exam::{ + Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, + ExamSchedule, ExamTitle, +}; +use crate::domain::exam_answer::{ExamAnswer, auto_score}; +use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt}; +use crate::domain::exam_question::{ + Choice, ChoiceId, ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec, + QuestionText, +}; +use crate::domain::exam_result::{ExamResult, Mark}; +use crate::domain::note_file::FileContentType; +use crate::domain::question_image::QuestionImage; +use crate::domain::role::Role; +use crate::domain::settings::Settings; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::state::AppState; + +use super::bank_questions::BankQuestionResponse; +use super::courses::{can_manage_course, can_view_course, visible_courses}; +use super::subjects::subject_in_course; +use super::{ + ChoiceBody, CurrentUser, ExamResponse, ImageUpload, Page, PageParams, PersonRef, + RequireTeacher, Scheduled, UploadFileForm, WindowParams, blob_path, check_not_past, paginate, + person_map, read_image_upload, remove_blob, set_or_clear, store_blob, +}; + +pub(crate) mod attempts; +pub(crate) mod images; +pub(crate) mod questions; +pub(crate) mod review; + +pub(crate) use attempts::*; +pub(crate) use images::*; +pub(crate) use questions::*; +pub(crate) use review::*; + +impl Scheduled for Exam { + fn starts_at_ms(&self) -> Option { + self.get_starts_at().map(|at| at.as_millis()) + } + + fn ends_at_ms(&self) -> Option { + self.get_ends_at().map(|at| at.as_millis()) + } + + fn order_key(&self) -> &str { + self.get_id().key() + } +} + +/// Serializes the exam subsystem's cross-record check-then-writes, which +/// `BEGIN…COMMIT` cannot (write skew) — the reasoning in [`crate::domain::cap`]. +/// **Replica-local**: it orders requests inside one process only, and the +/// backend runs as two, so every invariant that could be moved into the +/// database has been. What is left needs a cross-record read and a write held +/// together, which no single statement expresses: +/// +/// Read side — the answer saves (REST and the exam room), from the +/// writable-attempt gate through the upsert; the grade write (draft gate +/// through the result upsert); the exam PATCH, whose mode/re-draft gates count +/// attempts and results; and the three question writes that first check a +/// subject belongs to the course. These stay concurrent with each other. +/// +/// Write side — attempt starts (the max-attempts count and the retake's answer +/// wipe) and the subject delete's cascade. So a save can never land on a sheet +/// a retake just wiped, a mark can never land on an exam mid-flight into +/// hiding, and a question can never adopt a subject being swept. +/// +/// The question freeze gate is *not* on this list any more: it rides inside +/// each question/image write's own transaction +/// ([`crate::domain::exam_attempt::ExamAttempt::unfrozen`]), and the exam PATCH +/// no longer needs the writer lease because its save is a compare-and-set. +// ponytail: global RwLock, shard per-exam if save latency ever matters. +pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + // Plain route: OpenApiRouter can't describe a WebSocket upgrade, so + // the exam room lives outside the generated spec (see the `exams` tag + // description and README for the protocol). + .route( + "/{id}/attempt/ws", + axum::routing::get(super::exam_ws::attempt_ws), + ) + .routes(routes!(list_exams)) + .routes(routes!(get_exam, update_exam, delete_exam)) + .routes(routes!(grade, list_results)) + .routes(routes!(my_result)) + .routes(routes!(remove_result)) + .routes(routes!(exam_statistics)) + .routes(routes!(start_attempt, my_attempt)) + .routes(routes!(finish_attempt)) + .routes(routes!(exam_live)) + .routes(routes!(create_question, list_questions)) + .routes(routes!(update_question, delete_question)) + .routes(routes!(question_from_bank)) + .routes(routes!(question_to_bank)) + .routes(routes!(question_refresh_from_bank)) + .routes(routes!(attempt_questions)) + .routes(routes!(save_answer)) + .routes(routes!(attempt_answers)) + .routes(routes!(student_attempts)) + .routes(routes!(student_attempt_answers)) + .routes(routes!(student_marks_history)) + .routes(routes!(review_questions)) + .routes(routes!(review_attempts)) + .routes(routes!(review_attempt_answers)) + // The image routes get their own HTTP body cap, like the note-file + // ones: the server-wide hard ceiling plus multipart framing headroom. + .merge( + OpenApiRouter::new() + .routes(routes!( + upload_question_image, + get_question_image, + delete_question_image + )) + .routes(routes!( + upload_choice_image, + get_choice_image, + delete_choice_image + )) + .routes(routes!( + upload_answer_image, + get_answer_image, + delete_answer_image + )) + .routes(routes!(get_student_answer_image)) + .routes(routes!(student_attempt_answer_image)) + .routes(routes!(review_attempt_answer_image)) + .layer(DefaultBodyLimit::max( + MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES, + )), + ) +} + +#[derive(Deserialize, ToSchema)] +struct UpdateExam { + #[schema(max_length = 200)] + title: Option, + #[schema(max_length = 2000)] + description: Option, + /// The assessment form — one of the school's exam kinds (`GET /settings`). + /// Changing it re-weights the exam: the course average uses the kind's + /// settings-configured weight. + kind: Option, + /// `sync`, `async`, or `open`. Omit to keep the current mode; send `null` + /// to turn the exam back into an offline-graded one. Frozen once anyone + /// has started an attempt. Switching to `open` requires clearing + /// `starts_at`/`ends_at` in the same request. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option)] + mode: Option>, + /// Window open, UTC unix-milliseconds. Omit to keep; `null` to clear. + /// A newly set value must not be in the past. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option)] + starts_at: Option>, + /// Window close, UTC unix-milliseconds. Omit to keep; `null` to clear. + /// Moving it while a sync exam runs extends (or cuts) everyone's deadline; + /// a newly set value must not be in the past. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option)] + ends_at: Option>, + /// Per-attempt budget, milliseconds (`async`, or optionally `open`). Omit + /// to keep; `null` to clear. Changing it mid-exam moves every running + /// attempt's deadline. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option, minimum = 60000, maximum = 86400000)] + duration_ms: Option>, + /// Attempt limit: `1`–`100`, or `0` for unlimited. Omit to keep. Editable + /// live — raising it grants retakes on the spot; lowering it only blocks + /// future starts. + #[schema(minimum = 0, maximum = 100)] + max_attempts: Option, + /// Whether students who left the exam room may come back in. Omit to + /// keep. Editable live — the teacher's door handle for the running room. + allow_rejoin: Option, + /// Whether students may review their graded attempt once results are out. + /// Omit to keep. Editable live. + allow_review: Option, + /// `false` publishes a draft (students can now see and sit it); `true` + /// pulls a published exam back into hiding — allowed only while nobody + /// has attempted it and nothing is graded (`409` otherwise). Omit to keep. + draft: Option, +} + +#[derive(Deserialize, ToSchema)] +struct GradeResult { + /// The mark to record, `0`–`100`. + #[schema(example = 85, minimum = 0, maximum = 100)] + mark: i64, + /// The student being graded. + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + user_id: String, +} + +#[derive(Serialize, ToSchema)] +pub(crate) struct ExamResultResponse { + id: String, + exam: String, + /// The graded student. + user: PersonRef, + /// Which sitting this mark belongs to (1 = first attempt). Lets the grader + /// jump from a mark to that sitting's answer sheet + /// (`GET /exams/{id}/students/{user}/attempts/{seq}/answers`) — without it + /// a marked retake's answers are unreachable from the mark. + seq: i64, + mark: i64, + /// Who recorded the mark. + graded_by: PersonRef, +} + +impl ExamResultResponse { + fn new(result: &ExamResult, people: &HashMap) -> Self { + Self { + id: result.get_id().key().to_string(), + exam: result.get_exam().key().to_string(), + user: PersonRef::resolve(people, result.get_user()), + seq: result.get_seq(), + mark: result.get_mark().as_i64(), + graded_by: PersonRef::resolve(people, result.get_graded_by()), + } + } +} + +#[derive(Serialize, ToSchema)] +struct ExamStatisticsResponse { + exam: String, + /// Number of graded results. + graded: u64, + /// Plain mean of the graded marks; `null` while nothing is graded. + average: Option, + min: Option, + max: Option, +} + +/// The course an exam belongs to. A dangling reference means the course-delete +/// cascade was violated — surface it loudly as a 500, not a user-facing 404. +async fn course_of(exam: &Exam, db: &Database) -> Result { + Course::read(exam.get_course(), db) + .await? + .ok_or_else(|| AppError::Internal("exam references a missing course".into())) +} + +// ---- exams -------------------------------------------------------------- +// Exams are created inside a course: `POST /courses/{id}/exams`. + +/// List the exams visible to the caller: every exam for manager+, otherwise +/// the exams of the courses they created or are enrolled in — minus other +/// people's drafts (a draft shows only to its course's managers). Paged via +/// `?limit=&offset=` (omit `limit` for the full list); returns a +/// `{items, total, limit, offset}` envelope. +/// +/// The optional `?starts_after=&ends_after=` schedule window (unix +/// milliseconds) applies *after* the visibility and draft filtering, narrows +/// the list to upcoming/unfinished exams and flips the order to ascending by +/// schedule — so `?ends_after=&limit=20` returns the twenty *soonest* +/// exams rather than the twenty newest-created. Exams without a window +/// (no `mode`, or `open`) are excluded by either parameter. +#[utoipa::path( + get, + path = "/", + tag = "exams", + security(("session_cookie" = [])), + params(WindowParams, PageParams), + responses( + (status = 200, description = "A page of the caller's visible exams (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid window, limit, or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn list_exams( + State(st): State, + CurrentUser(user): CurrentUser, + Query(window): Query, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let exams = if user.get_role().at_least(Role::Manager) { + Exam::list_all(&st.db).await? + } else { + let courses = visible_courses(&user, &st.db).await?; + let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect(); + // Drafts show only where the caller manages the course (as its + // creator — the manager+ path above already saw everything). + let managed: Vec<&str> = courses + .iter() + .filter(|c| can_manage_course(c, &user)) + .map(|c| c.get_id().key()) + .collect(); + let mut exams = Exam::list_for_courses(&ids, &st.db).await?; + exams.retain(|exam| !exam.is_draft() || managed.contains(&exam.get_course().key())); + exams + }; + let exams = window.apply(exams)?; + let total = exams.len() as i64; + // Paged in the web layer: the draft filter and the window are Rust. + let items = paginate(&exams, limit, offset) + .iter() + .map(ExamResponse::new) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// Fetch a single exam by id. Visible to its course's enrolled users, the +/// course creator, and managers/admins — except drafts, which only the +/// course's managers see (everyone else gets a `404`, as if the exam doesn't +/// exist yet — because it doesn't, officially). +#[utoipa::path( + get, + path = "/{id}", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 200, description = "The exam", body = ExamResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled in the exam's course, not its creator, and not a manager/admin", body = ErrorResponse), + (status = 404, description = "Not found (or a draft the caller may not see)", body = ErrorResponse), + ), +)] +async fn get_exam( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_view_course(&course, &user, &st.db).await? { + return Err(AppError::Forbidden( + "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this exam", + )); + } + // A draft doesn't exist for anyone but its course's managers — 404, not + // 403, so its existence never leaks to the students it's hidden from. + if exam.is_draft() && !can_manage_course(&course, &user) { + return Err(AppError::NotFound); + } + Ok(Json(ExamResponse::new(&exam))) +} + +/// Update an exam. Requires teacher+ and management rights over the exam's +/// course (its creator, or manager/admin). Omitted fields keep their value; an +/// explicit `null` clears a schedule field; the course itself is not updatable. +/// The schedule must stay consistent as a whole (see the create endpoint), and +/// `mode` is frozen once anyone has started an attempt — times, duration, +/// `max_attempts`, and `allow_rejoin` stay editable so a running exam can be +/// extended, granted retakes, or have its rejoin door opened live. +/// `draft: false` publishes a draft; `draft: true` re-hides an exam, but only +/// while it has no attempts and no results (`409` otherwise) — students never +/// lose sight of an exam they've already sat or been graded on. +#[utoipa::path( + patch, + path = "/{id}", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + request_body = UpdateExam, + responses( + (status = 200, description = "Updated exam", body = ExamResponse), + (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), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + (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), + ), +)] +async fn update_exam( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + // *Reader* lease of [`EXAM_LOCK`] for exactly one pairing: the mode gate + // below reads `exam_attempt`, and an attempt start takes the *writer* + // lease, so a first sitting still cannot land between that gate and the + // write — replica-locally, as it always did. + // + // It buys nothing against grading, which is a reader too: the re-draft gate + // is therefore enforced inside the update's own transaction + // (`Exam::update_if_unchanged`), where it holds across replicas. The gate + // below stays as the pre-flight — same error, one round trip earlier. + // Concurrent PATCHes of this exam no longer queue behind each other either: + // the lost update they used to cause is refused by the compare-and-set. + let _guard = EXAM_LOCK.read().await; + let mut left = CAS_UPDATE_RETRIES; + let exam = loop { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can edit this exam", + )); + } + + let title = match req.title { + Some(ref title) => ExamTitle::try_new(title)?, + None => exam.get_title().clone(), + }; + let description = match req.description { + Some(ref description) => ExamDescription::try_new(description)?, + None => exam.get_description().clone(), + }; + let kind = match req.kind { + // Only a kind this request sets is held to the current settings list — + // a stored kind survives later list edits, like past times survive + // the no-past rule. + Some(ref kind) => { + let school = Settings::load(&st.db).await?; + ExamKind::try_new(kind, school.get_exam_kinds())? + } + None => exam.get_kind().clone(), + }; + + // Merge the schedule (set / clear / keep per field), then re-validate it + // as a unit — a PATCH can't leave a half-schedule behind. Only values this + // request sets are held to the no-past rule: kept ones may legitimately be + // past (a running exam's `starts_at`), and rechecking them would block + // unrelated edits. + let mode = match req.mode { + Some(ref update) => update.as_deref().map(ExamMode::try_new).transpose()?, + None => exam.get_mode().cloned(), + }; + let starts_at = match req.starts_at { + Some(update) => { + let starts_at = update.map(Timestamp::from_millis); + check_not_past("starts_at", starts_at)?; + starts_at + } + None => exam.get_starts_at(), + }; + let ends_at = match req.ends_at { + Some(update) => { + let ends_at = update.map(Timestamp::from_millis); + check_not_past("ends_at", ends_at)?; + ends_at + } + None => exam.get_ends_at(), + }; + let duration_ms = match req.duration_ms { + Some(update) => update.map(ExamDuration::try_new).transpose()?, + None => exam.get_duration_ms(), + }; + let schedule = ExamSchedule::try_new(mode, starts_at, ends_at, duration_ms)?; + let max_attempts = match req.max_attempts { + Some(limit) => ExamAttemptLimit::try_new(limit)?, + None => exam.get_max_attempts(), + }; + let allow_rejoin = req.allow_rejoin.unwrap_or_else(|| exam.get_allow_rejoin()); + let allow_review = req.allow_review.unwrap_or_else(|| exam.get_allow_review()); + let draft = req.draft.unwrap_or_else(|| exam.is_draft()); + + // Switching sync <-> async <-> open (or back to unscheduled) would + // silently rewrite the deadline rules under students who already sat + // down; extending times, the attempt limit, and the rejoin door are the + // supported live adjustments instead. Gate read and write share the + // handler-wide writer lease of [`EXAM_LOCK`], so a first attempt can't + // land in the gap and leave a sat exam's mode flipped under it. + let mode_changed = + schedule.get_mode().map(ExamMode::as_str) != exam.get_mode().map(ExamMode::as_str); + if mode_changed && ExamAttempt::any_for_exam(exam.get_id(), &st.db).await? { + return Err(AppError::Conflict( + "cannot change the exam mode after attempts have started", + )); + } + // Re-drafting hides the exam — never out from under a student who + // already sat it or holds a mark on it. Pre-flight only: the write's own + // transaction re-makes this check and answers with the same error, so a + // grade landing after this read still cannot leave a mark on a draft. + if draft && !exam.is_draft() { + let sat = ExamAttempt::any_for_exam(exam.get_id(), &st.db).await?; + let graded = !ExamResult::list_for_exam(exam.get_id(), &st.db) + .await? + .is_empty(); + if sat || graded { + return Err(crate::domain::exam::redraft_error()); + } + } + + if let Some(updated) = exam + .update_if_unchanged( + title, + description, + kind, + schedule, + max_attempts, + allow_rejoin, + allow_review, + draft, + &st.db, + ) + .await? + { + break updated; + } + // The row moved under the snapshot every gate above judged: re-read and + // re-merge, so both edits land instead of the later reverting the earlier. + left -= 1; + if left == 0 { + return Err(AppError::Conflict( + "the exam kept changing underneath this update — try again", + )); + } + }; + Ok(Json(ExamResponse::new(&exam))) +} + +/// Delete an exam. Requires teacher+ and management rights over the exam's +/// course (its creator, or manager/admin). Cascades the exam's results, +/// attempts, questions, answers, and question + answer images (blobs included). +#[utoipa::path( + delete, + path = "/{id}", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn delete_exam( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, +) -> Result { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can delete this exam", + )); + } + // Rows go first (the delete cascades them), blobs after — a crash in + // between strands at worst an unreachable blob. + let images = QuestionImage::list_for_exam(exam.get_id(), &st.db).await?; + let answer_images = AnswerImage::list_for_exam(exam.get_id(), &st.db).await?; + exam.delete(&st.db).await?; + for image in &images { + remove_blob(&st.files_path, image.get_file()).await; + } + for image in &answer_images { + remove_blob(&st.files_path, image.get_file()).await; + } + Ok(StatusCode::NO_CONTENT) +} + +// ---- results ------------------------------------------------------------ + +/// Record (or overwrite) a student's mark for an exam. Requires teacher+ and +/// management rights over the exam's course; the target must be a student and +/// enrolled. Only students carry marks; students never grade — and nobody +/// grades themselves. A draft can't be graded (`409`) — a mark would point at +/// an exam its student can't see. +#[utoipa::path( + post, + path = "/{id}/results", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + request_body = GradeResult, + responses( + (status = 200, description = "Result recorded", body = ExamResultResponse), + (status = 400, description = "Invalid mark, unknown user, user not a student, or not enrolled", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse), + (status = 404, description = "Exam not found", body = ErrorResponse), + (status = 409, description = "The exam is a draft", body = ErrorResponse), + ), +)] +async fn grade( + State(st): State, + RequireTeacher(teacher): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let exam_id = ExamId::from_key(&id); + // Reader lease of [`EXAM_LOCK`] from the exam read through the result + // write: the draft gate below must be judged against the same row the + // mark lands under, or a concurrent re-draft (a writer, which checks for + // results) could slip between them and leave a mark on a hidden exam. + let _guard = EXAM_LOCK.read().await; + // Exam must exist. + let exam = Exam::read(&exam_id, &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &teacher) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can grade this exam", + )); + } + // Pre-flight: `ExamResult::grade` re-makes this check inside the mark's own + // transaction, so a re-draft landing after this read cannot leave a mark on + // a hidden exam. + if exam.is_draft() { + return Err(crate::domain::exam_result::draft_error()); + } + + let mark = Mark::try_new(req.mark)?; + let target = UserId::from_key(&req.user_id); + + // Grading never targets oneself — no grader, whatever their role, may + // write their own mark. + if &target == teacher.get_id() { + return Err(AppError::Forbidden("grading yourself is not allowed")); + } + + // Target user must exist. + let Some(target_user) = User::read(&target, &st.db).await? else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user does not exist", + })); + }; + + // Only students carry marks — the grade system is theirs alone. A stale + // enrollment left behind by a promotion can't reopen grading for staff. + if target_user.get_role() != Role::Student { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "only students can be graded", + })); + } + + // ... and be enrolled in the exam's course. + if Enrollment::read_for_user(exam.get_course(), &target, &st.db) + .await? + .is_none() + { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user is not enrolled in this course", + })); + } + + // The mark lands on the student's current sitting; the latest seq is the + // grade-of-record. An offline-graded exam has no sitting — grade its base + // seq (1). + let seq = ExamAttempt::read_latest_for_user(&exam_id, &target, &st.db) + .await? + .map_or(1, |a| a.get_seq()); + let result = ExamResult::grade(&exam_id, &target, seq, mark, teacher.get_id(), &st.db).await?; + let people = PersonRef::map_of(&[&target_user, &teacher]); + Ok(Json(ExamResultResponse::new(&result, &people))) +} + +/// List an exam's results, paged via `?limit=&offset=` (omit `limit` for all +/// of them). Requires teacher+ and management rights over the exam's course — +/// students read only their own via `GET /exams/{id}/result`. Returns a +/// `{items, total, limit, offset}` envelope. +#[utoipa::path( + get, + path = "/{id}/results", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id"), PageParams), + responses( + (status = 200, description = "A page of results (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Exam not found", body = ErrorResponse), + ), +)] +async fn list_results( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + // Exam must exist — a missing exam is a 404, not an empty result list. + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can list results", + )); + } + let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?; + let total = results.len() as i64; + // Join people onto the page alone — the lookup shrinks with the window. + // Paged in the web layer: the list is deduped to the latest mark per + // sitting pair in Rust. + let rows = paginate(&results, limit, offset); + let people = person_map( + rows.iter() + .flat_map(|r| [r.get_user().clone(), r.get_graded_by().clone()]), + &st.db, + ) + .await?; + let items = rows + .iter() + .map(|r| ExamResultResponse::new(r, &people)) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// The current user's own result for an exam. Any authenticated user may read +/// their own mark; `404` while ungraded (or when the exam doesn't exist). +#[utoipa::path( + get, + path = "/{id}/result", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 200, description = "The caller's result", body = ExamResultResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "No such exam, or not graded yet", body = ErrorResponse), + ), +)] +async fn my_result( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let result = ExamResult::read_for_user(&ExamId::from_key(&id), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let people = person_map( + [result.get_user().clone(), result.get_graded_by().clone()], + &st.db, + ) + .await?; + Ok(Json(ExamResultResponse::new(&result, &people))) +} + +/// Remove a student's result from an exam. Requires teacher+ and management +/// rights over the exam's course. +#[utoipa::path( + delete, + path = "/{id}/results/{user}", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("user" = String, Path, description = "User id"), + ), + responses( + (status = 204, description = "Removed"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn remove_result( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, target)): Path<(String, String)>, +) -> Result { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can remove results", + )); + } + let removed = ExamResult::remove(exam.get_id(), &UserId::from_key(&target), &st.db).await?; + if removed.is_none() { + return Err(AppError::NotFound); + } + Ok(StatusCode::NO_CONTENT) +} + +/// Summary statistics for an exam's graded results. Requires teacher+ and +/// management rights over the exam's course. +#[utoipa::path( + get, + path = "/{id}/statistics", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 200, description = "The exam's mark statistics", body = ExamStatisticsResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Exam not found", body = ErrorResponse), + ), +)] +async fn exam_statistics( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, +) -> Result, AppError> { + // Exam must exist — a missing exam is a 404, not an empty statistic. + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can view statistics", + )); + } + let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?; + + let marks: Vec = results.iter().map(|r| r.get_mark().as_i64()).collect(); + let average = + (!marks.is_empty()).then(|| marks.iter().sum::() as f64 / marks.len() as f64); + Ok(Json(ExamStatisticsResponse { + exam: exam.get_id().key().to_string(), + graded: marks.len() as u64, + average, + min: marks.iter().min().copied(), + max: marks.iter().max().copied(), + })) +} diff --git a/src/web/exams/questions.rs b/src/web/exams/questions.rs new file mode 100644 index 0000000..fe6f488 --- /dev/null +++ b/src/web/exams/questions.rs @@ -0,0 +1,851 @@ +use super::*; + +// ---- questions -------------------------------------------------------------- +// Teachers author the question list before the exam runs; it freezes the +// moment anyone starts an attempt, so every student sits the same exam. + +#[derive(Deserialize, ToSchema)] +pub(crate) struct CreateQuestion { + /// The subject this question belongs to — one of the exam's course's + /// subjects (`GET /courses/{id}/subjects`). Required. + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + subject_id: String, + /// The question itself. + #[schema(example = "What is 2 + 2?", max_length = 2000)] + text: String, + /// `choice` or `text`. + #[schema(example = "choice")] + kind: String, + /// This question's share of the auto-score, `1`–`100`. + #[schema(example = 10, minimum = 1, maximum = 100)] + points: i64, + /// The options of a `choice` question (2–10 of them); omit for `text`. + /// Each carries an `id` naming it within this payload — the server mints + /// the stored ids and returns them. + #[schema(min_items = 2, max_items = 10)] + choices: Option>, + /// The `id` of the right option, as sent in `choices`; required for + /// `choice`, absent for `text`. + #[schema(example = "b")] + correct: Option, +} + +#[derive(Deserialize, ToSchema)] +pub(crate) struct UpdateQuestion { + /// Re-tag the question with another of the course's subjects. Omit to + /// keep the current one — a question always has a subject, so there is no + /// clearing it. + subject_id: Option, + #[schema(max_length = 2000)] + text: Option, + #[schema(minimum = 1, maximum = 100)] + points: Option, + /// `choice` or `text`. Switching kinds needs the other fields to follow: + /// send `choices` + `correct` when moving to `choice`, explicit `null`s + /// when moving to `text`. + kind: Option, + /// Omit to keep the stored options; send `null` to drop them (text + /// questions only). Send each option back with the `id` it was returned + /// with to keep it — its picture rides along. Only options whose id is + /// absent from the new list lose their picture, so reordering, renaming, + /// and deleting one option leave the rest untouched. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option>, min_items = 2, max_items = 10)] + choices: Option>>, + /// The `id` of the right option. Omit to keep; `null` to clear (text + /// questions only). + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option)] + correct: Option>, +} + +/// One option on the wire: its stable id and its text. Carries **no** answer +/// key — `correct` is a sibling field on the question, and only on the +/// author-facing DTO, so a student response cannot contain one by construction. +#[derive(Serialize, ToSchema)] +pub(crate) struct ChoiceResponse { + /// Send this back in a PATCH to keep the option (and its picture). + id: String, + text: String, +} + +impl ChoiceResponse { + pub(crate) fn list(choices: Option<&[Choice]>) -> Option> { + choices.map(|choices| { + choices + .iter() + .map(|choice| Self { + id: choice.get_id().as_str().to_string(), + text: choice.get_text().as_str().to_string(), + }) + .collect() + }) + } +} + +/// A question as its author sees it — including the `correct` option. Never +/// serialized to students; they get [`AttemptQuestionResponse`]. +#[derive(Serialize, ToSchema)] +pub(crate) struct QuestionResponse { + id: String, + exam: String, + /// The subject this question belongs to (`GET /subjects/{id}`). + subject: String, + text: String, + /// `choice` or `text`. + #[schema(example = "choice")] + kind: String, + points: i64, + /// The options with their stable ids (`choice` questions only). + choices: Option>, + /// The id of the right option (`choice` questions only). + correct: Option, + /// The question's illustration, if one was uploaded (any kind). + image: Option, + /// Per-option pictures, aligned with `choices` (`choice` questions only). + choice_images: Option>>, + /// The bank template this question was created from, if it was added out of + /// the bank (`GET /bank-questions/{id}`). + from_bank: Option, + /// The bank template most recently created by saving this question into the + /// bank, if any — set only by `POST …/questions/{qid}/to-bank`. Null on a + /// question that came *from* the bank and was never saved back. + banked_as: Option, +} + +impl QuestionResponse { + pub(crate) fn new(question: &ExamQuestion, images: &[QuestionImage]) -> Self { + Self { + id: question.get_id().key().to_string(), + exam: question.get_exam().key().to_string(), + subject: question.get_subject().key().to_string(), + text: question.get_text().as_str().to_string(), + kind: question.get_kind().as_str().to_string(), + points: question.get_points().as_i64(), + choices: ChoiceResponse::list(question.get_choices()), + correct: question.get_correct().map(|id| id.as_str().to_string()), + image: image_meta(images, None), + choice_images: choice_image_metas(question, images), + from_bank: question.get_from_bank().map(|b| b.key().to_string()), + banked_as: question.get_banked_as().map(|b| b.key().to_string()), + } + } +} + +/// The questions freeze once anyone has started an attempt — editing them +/// under a student mid-exam would fork what "the exam" means. +pub(crate) async fn ensure_questions_editable( + exam: &ExamId, + db: &Database, +) -> Result<(), AppError> { + if ExamAttempt::any_for_exam(exam, db).await? { + return Err(AppError::Conflict( + "cannot change questions after attempts have started", + )); + } + Ok(()) +} + +/// The question, provided it belongs to `exam` — a qid under someone else's +/// exam is a plain 404, not a leak. +pub(crate) async fn question_of_exam( + exam: &ExamId, + qid: &str, + db: &Database, +) -> Result { + let question = ExamQuestion::read(&ExamQuestionId::from_key(qid), db) + .await? + .ok_or(AppError::NotFound)?; + if question.get_exam() != exam { + return Err(AppError::NotFound); + } + Ok(question) +} + +/// The question's option named by `choice_id` — a 400 for a text question or an +/// id the question doesn't have, so an option picture can only ever be +/// addressed through an option that exists. +pub(crate) fn choice_slot(question: &ExamQuestion, choice_id: &str) -> Result { + let Some(choices) = question.get_choices() else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "choice_id", + reason: "only choice questions take option pictures", + })); + }; + choices + .iter() + .find(|choice| choice.get_id().as_str() == choice_id) + .map(|choice| choice.get_id().clone()) + .ok_or(AppError::Validation(ValidationError::Invalid { + field: "choice_id", + reason: "must name one of the choices", + })) +} + +/// Add a question to an exam. Requires teacher+ and management rights over the +/// exam's course. `subject_id` must name one of the course's subjects +/// (`GET /courses/{id}/subjects`) — every question belongs to a subject. +/// `choice` questions carry 2–10 `choices` plus `correct` naming one of them by id; `text` +/// questions carry neither. Locked once attempts exist. +#[utoipa::path( + post, + path = "/{id}/questions", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + request_body = CreateQuestion, + responses( + (status = 201, description = "Question created", body = QuestionResponse), + (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Exam not found", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + ), +)] +pub(crate) async fn create_question( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can author questions", + )); + } + // Reader lease of [`EXAM_LOCK`], for the subject check alone: a subject + // delete (which takes the writer lease) must not invalidate a subject this + // just validated. Replica-local, like every lock here. The freeze gate no + // longer needs the lease — it rides inside the insert's own transaction. + let _guard = EXAM_LOCK.read().await; + ensure_questions_editable(exam.get_id(), &st.db).await?; + + let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; + let text = QuestionText::try_new(&req.text)?; + let points = QuestionPoints::try_new(req.points)?; + // No stored choices to match against on create, so every option is new and + // every id is minted here. + let spec = QuestionSpec::try_new( + QuestionKind::try_new(&req.kind)?, + ChoiceBody::into_inputs(req.choices), + req.correct, + &[], + )?; + let question = ExamQuestion::create(exam.get_id(), subject, text, points, spec, &st.db).await?; + // A question is born imageless — uploads come after, against its id. + Ok(( + StatusCode::CREATED, + Json(QuestionResponse::new(&question, &[])), + )) +} + +/// The exam's question list, `correct` choice ids included — the answer key, +/// paged via `?limit=&offset=` (omit `limit` for the whole list). Requires +/// teacher+ and management rights over the exam's course. Students read +/// questions through `GET /exams/{id}/attempt/questions`. Returns a +/// `{items, total, limit, offset}` envelope. +#[utoipa::path( + get, + path = "/{id}/questions", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id"), PageParams), + responses( + (status = 200, description = "A page of the exam's questions (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Exam not found", body = ErrorResponse), + ), +)] +pub(crate) async fn list_questions( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can read the question list", + )); + } + Ok(Json(question_page(&exam, limit, offset, &st.db).await?)) +} + +/// The paged answer-key list (`correct` included) shared by the teacher +/// `list_questions` read and the student `review_questions` read — the two +/// differ only in the access wall they run first. +pub(crate) async fn question_page( + exam: &Exam, + limit: Option, + offset: i64, + db: &Database, +) -> Result, AppError> { + let (questions, total) = ExamQuestion::list_for_exam(exam.get_id(), limit, offset, db).await?; + let images = images_by_question(exam.get_id(), db).await?; + let items = questions + .iter() + .map(|question| { + QuestionResponse::new( + question, + images + .get(question.get_id().key()) + .map_or(&[][..], Vec::as_slice), + ) + }) + .collect(); + Ok(Page::new(items, total, limit, offset)) +} + +/// Edit a question. Requires teacher+ and management rights over the exam's +/// course. Omitted fields keep their value; `kind`/`choices`/`correct` are +/// re-validated as a unit, so a kind switch must bring the matching fields +/// along. `subject_id` re-tags within the course's subjects. Locked once +/// attempts exist. +#[utoipa::path( + patch, + path = "/{id}/questions/{qid}", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ), + request_body = UpdateQuestion, + responses( + (status = 200, description = "Updated question", body = QuestionResponse), + (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + ), +)] +pub(crate) async fn update_question( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, qid)): Path<(String, String)>, + Json(req): Json, +) -> Result, AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can edit questions", + )); + } + // Reader lease of [`EXAM_LOCK`] for the subject check — see + // `create_question`. The freeze gate rides in the update's transaction. + let _guard = EXAM_LOCK.read().await; + ensure_questions_editable(exam.get_id(), &st.db).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + + let subject = match req.subject_id { + Some(ref subject_id) => subject_in_course(subject_id, course.get_id(), &st.db).await?, + None => question.get_subject().clone(), + }; + let text = match req.text { + Some(ref text) => QuestionText::try_new(text)?, + None => question.get_text().clone(), + }; + let points = match req.points { + Some(points) => QuestionPoints::try_new(points)?, + None => question.get_points(), + }; + // Merge the kind-dependent fields (set / clear / keep per field), then + // re-validate them as a unit — a PATCH can't leave a half-question behind. + let kind = match req.kind { + Some(ref kind) => QuestionKind::try_new(kind)?, + None => question.get_kind().clone(), + }; + // Omitting `choices` re-submits the stored options *with their ids*, so a + // text-only edit keeps every identity (and every picture) untouched. + let choices = match req.choices { + Some(update) => ChoiceBody::into_inputs(update), + None => ChoiceBody::from_stored(question.get_choices()), + }; + let correct = match req.correct { + Some(update) => update, + None => question.get_correct().map(|id| id.as_str().to_string()), + }; + let stored: Vec = question.get_choices().unwrap_or_default().to_vec(); + let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?; + + let updated = question.update(subject, text, points, spec, &st.db).await?; + // Only the options that are actually *gone* lose their pictures: keyed by + // choice id, an option that survives the edit keeps its image no matter + // where it moved in the list. (This used to wipe every option picture + // whenever the request so much as carried a `choices` key.) + let keep: Vec = updated + .get_choices() + .unwrap_or_default() + .iter() + .map(|choice| choice.get_id().clone()) + .collect(); + for image in QuestionImage::delete_choices_not_in(updated.get_id(), &keep, &st.db).await? { + remove_blob(&st.files_path, image.get_file()).await; + } + let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?; + Ok(Json(QuestionResponse::new(&updated, &images))) +} + +/// Remove a question (and every answer to it). Requires teacher+ and +/// management rights over the exam's course. Locked once attempts exist. +#[utoipa::path( + delete, + path = "/{id}/questions/{qid}", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + ), +)] +pub(crate) async fn delete_question( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, qid)): Path<(String, String)>, +) -> Result { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can delete questions", + )); + } + // No lock: the freeze gate is part of the delete's own transaction, and + // this path checks no subject. The pre-flight below is the fast 409. + ensure_questions_editable(exam.get_id(), &st.db).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + // Rows go first (the delete cascades them), blobs after — a crash in + // between strands at worst an unreachable blob. + let images = QuestionImage::list_for_question(question.get_id(), &st.db).await?; + question.delete(&st.db).await?; + for image in &images { + remove_blob(&st.files_path, image.get_file()).await; + } + Ok(StatusCode::NO_CONTENT) +} + +// ---- question bank bridge --------------------------------------------------- +// Two copy funnels between an exam's questions and the school-wide bank +// (`web/bank_questions`): instantiate a template into this exam, or save one of +// this exam's questions back into the bank. Both COPY the row and every image +// blob to fresh ids/files — the source side is never touched or shared. + +#[derive(Deserialize, ToSchema)] +pub(crate) struct InstantiateFromBank { + /// The subject to file the new question under — one of the exam's course's + /// subjects (the same-course rule the bank row itself is exempt from). + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + subject_id: String, +} + +/// Instantiate a bank template into this exam as a fresh question. Requires +/// teacher+, management rights over the exam's course, and a template the +/// caller may see (their own, or one published to the school) — anything else +/// is a 404. `subject_id` must +/// name one of the course's subjects — the template's own subject is origin +/// metadata and does not carry over. The template (and its blobs) stay +/// untouched; a full copy — text, points, spec, illustration, and option +/// pictures — lands under a new question id. Locked once attempts exist. +#[utoipa::path( + post, + path = "/{id}/questions/from-bank/{bid}", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("bid" = String, Path, description = "Bank question id"), + ), + request_body = InstantiateFromBank, + responses( + (status = 201, description = "Question created from the template", body = QuestionResponse), + (status = 400, description = "Unknown subject, or one from another course", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, or no bank template the caller may see", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + ), +)] +pub(crate) async fn question_from_bank( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, bid)): Path<(String, String)>, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can author questions", + )); + } + // Reader lease of [`EXAM_LOCK`] for the subject check — same reasoning as + // `create_question`. The freeze gate rides in the insert's transaction. + let _guard = EXAM_LOCK.read().await; + ensure_questions_editable(exam.get_id(), &st.db).await?; + let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; + + let template = BankQuestion::read(&BankQuestionId::from_key(&bid), &st.db) + .await? + .ok_or(AppError::NotFound)?; + // A template the caller may not see is a 404, exactly as it is on the bank's + // own routes — instantiating is a read of `correct`, and a 403 here would + // confirm that someone else's private template exists under that id. + if !crate::web::bank_questions::can_see(&template, &user) { + return Err(AppError::NotFound); + } + let question = ExamQuestion::create_from_bank( + exam.get_id(), + subject, + template.get_text().clone(), + template.get_points(), + template.spec(), + template.get_id().clone(), + &st.db, + ) + .await?; + + // Copy each of the template's image blobs to a fresh file under the new + // question + same slot (file before row, via `store_image`). A missing + // source blob is server-side damage, surfaced as a 500 — not silently lost. + // The copy is all-or-nothing: any mid-loop failure rolls back the fresh + // question row (its cascade drops the copied image rows) and the blobs + // written so far, leaving the source and destination untouched. + let sources = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; + let mut copied: Vec = Vec::new(); + for source in &sources { + let step = async { + let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file())) + .await + .map_err(|err| { + AppError::Internal(format!( + "missing blob for bank image {}: {err}", + source.get_file() + )) + })?; + store_image( + &st, + &exam, + &question, + source.get_slot(), + source.get_content_type().clone(), + &bytes, + ) + .await + }; + match step.await { + Ok(image) => copied.push(image.get_file().to_string()), + Err(err) => { + for file in &copied { + remove_blob(&st.files_path, file).await; + } + let _ = question.delete(&st.db).await; + return Err(err); + } + } + } + let images = QuestionImage::list_for_question(question.get_id(), &st.db).await?; + Ok(( + StatusCode::CREATED, + Json(QuestionResponse::new(&question, &images)), + )) +} + +/// Re-copy a bank template's *current* content over the exam question that was +/// instantiated from it — the escape hatch for the divergence a deep copy +/// creates: fixing a typo in the template does not reach the copies, so this is +/// how a copy is brought back in line, explicitly and per question. Requires +/// teacher+, management rights over the exam's course, and a template the +/// caller may still see. +/// +/// Replaces text, points, kind, choices, `correct`, the illustration, and the +/// option pictures with the template's; the question keeps its own id, its +/// exam, its `subject` (exam-course-scoped — the template's subject is +/// unrelated metadata) and its provenance links. Anything edited on the exam +/// copy since it was inserted is overwritten. +/// +/// **Choice ids come from the template**, exactly as +/// [`question_from_bank`] mints them — the copy adopts the template's ids, so +/// its option pictures key off the same slots the template's do, and a +/// re-copy after a template edit re-lands the right picture on the right +/// option. A recorded `selected` can never be stranded by that: the freeze +/// below refuses the whole route once *any* attempt exists, and an +/// `exam_answer` only exists under an attempt — so at refresh time no answer +/// points at any choice id at all. +/// +/// - No `from_bank` (never came from the bank, or its template was deleted and +/// the cascade cleared the link) → `400`; there is nothing to refresh from. +/// - Template gone or not visible to the caller → `404`, never a 403. +/// - Any attempt started → `409`, the same `ensure_questions_editable` freeze +/// every other question mutation answers to. +#[utoipa::path( + post, + path = "/{id}/questions/{qid}/refresh-from-bank", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ), + responses( + (status = 200, description = "Question refreshed from its template", body = QuestionResponse), + (status = 400, description = "The question did not come from the bank", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, no such question in it, or no bank template the caller may see", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + ), +)] +pub(crate) async fn question_refresh_from_bank( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, qid)): Path<(String, String)>, +) -> Result, AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can edit questions", + )); + } + // No lock: the question keeps its own subject here, so there is nothing to + // pair with a subject delete, and the freeze gate rides in the overwrite's + // transaction. + ensure_questions_editable(exam.get_id(), &st.db).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + + let Some(source) = question.get_from_bank().cloned() else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "question", + reason: "this question did not come from a bank template", + })); + }; + let template = BankQuestion::read(&source, &st.db) + .await? + .ok_or(AppError::NotFound)?; + if !crate::web::bank_questions::can_see(&template, &user) { + return Err(AppError::NotFound); + } + + // Every source blob is read up front, *before* anything is written: a + // missing one is server-side damage and must surface as a 500 with the + // question untouched, since a half-applied refresh has no old content left + // to roll back to. Bounded — at most one illustration plus ten option + // pictures, each under the school's file cap. + let sources = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; + let mut incoming: Vec<(&BankQuestionImage, Vec)> = Vec::with_capacity(sources.len()); + for source in &sources { + let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file())) + .await + .map_err(|err| { + AppError::Internal(format!( + "missing blob for bank image {}: {err}", + source.get_file() + )) + })?; + incoming.push((source, bytes)); + } + + // The question's own subject stays: it is checked against the exam's + // course, and the template's is origin metadata from anywhere in school. + let subject = question.get_subject().clone(); + // `spec()` hands over the template's stored choices *with their ids* rather + // than re-minting any — the same funnel `question_from_bank` uses. + let updated = question + .update( + subject, + template.get_text().clone(), + template.get_points(), + template.spec(), + &st.db, + ) + .await?; + + // Make the pictures match the template exactly: drop every slot the + // template has no picture for (including the illustration, and every option + // that is gone after the re-copy), then write the template's over the rest. + // `store_image` upserts per slot, so a slot both sides have is replaced. + let incoming_slots: Vec> = + incoming.iter().map(|(image, _)| image.get_slot()).collect(); + for stale in QuestionImage::list_for_question(updated.get_id(), &st.db).await? { + if incoming_slots.contains(&stale.get_slot()) { + continue; + } + let file = stale.get_file().to_string(); + stale.delete(&st.db).await?; + remove_blob(&st.files_path, &file).await; + } + for (source, bytes) in &incoming { + store_image( + &st, + &exam, + &updated, + source.get_slot(), + source.get_content_type().clone(), + bytes, + ) + .await?; + } + + let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?; + Ok(Json(QuestionResponse::new(&updated, &images))) +} + +/// Save one of this exam's questions into the school-wide bank as a reusable +/// template. Requires teacher+ and management rights over the exam's course. +/// The caller becomes the template's owner; the question's subject rides along +/// as origin metadata. A full copy — text, points, spec, illustration, and +/// option pictures — lands under a new bank id. Provenance rides both ways: the +/// origin exam is recorded on the template as `source_exam`, and the exam +/// question's `banked_as` is pointed at the new template (a repeat save is +/// allowed and repoints it at the newest one). `from_bank` is left alone — it +/// records the other direction and a save never changes where a question came +/// from. +#[utoipa::path( + post, + path = "/{id}/questions/{qid}/to-bank", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ), + responses( + (status = 201, description = "Template saved to the bank", body = BankQuestionResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), + ), +)] +pub(crate) async fn question_to_bank( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, qid)): Path<(String, String)>, +) -> Result<(StatusCode, Json), AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank", + )); + } + // Reader lease of [`BANK_LOCK`] across the question read and the insert: the + // template adopts the question's subject, so without it a subject delete + // could slip between the two and leave the fresh template pointing at a + // subject its cascade had already swept (that cascade runs under BANK_LOCK's + // writer lease, so holding the reader lease orders us either side of it). + let _bank_guard = crate::web::bank_questions::BANK_LOCK.read().await; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + + // `create_from_exam` mints its own id and insert (the funnel), fed the + // question's fields plus the origin exam it was saved off. + let template = BankQuestion::create_from_exam( + user.get_id().clone(), + question.get_subject().clone(), + question.get_text().clone(), + question.get_points(), + question.spec(), + exam.get_id().clone(), + &st.db, + ) + .await?; + + // Copy every image blob (illustration + option pictures) to a fresh file + // under the new bank row + same slot (file before row). All-or-nothing: a + // mid-loop failure rolls back the fresh bank row (cascade drops the copied + // image rows) and the blobs written so far; the source exam question stays + // untouched. + let sources = QuestionImage::list_for_question(question.get_id(), &st.db).await?; + let mut copied: Vec = Vec::new(); + for source in &sources { + let step = async { + let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file())) + .await + .map_err(|err| { + AppError::Internal(format!( + "missing blob for question image {}: {err}", + source.get_file() + )) + })?; + crate::web::bank_questions::store_image( + &st, + template.get_id(), + source.get_slot(), + source.get_content_type().clone(), + &bytes, + ) + .await + }; + match step.await { + Ok(image) => copied.push(image.get_file().to_string()), + Err(err) => { + for file in &copied { + remove_blob(&st.files_path, file).await; + } + let _ = template.delete(&st.db).await; + return Err(err); + } + } + } + // Provenance back-link, so a client can tell this question was already + // banked: the question points at the template it was saved into, and a + // repeat save repoints it at the newest one (never blocked). Written only + // after the all-or-nothing copy above, so a rolled-back template can never + // leave a dangling link. A failure here is logged and swallowed rather than + // rolling the template back: the save is the user's actual work and a + // template silently vanishing over a metadata write is worse than a + // template with no back-link (the next save re-links it). + let question_key = question.get_id().key().to_string(); + // The bank lease has done its job (the template is inserted, its subject + // pinned); hand it back before the link write. + drop(_bank_guard); + // No exam lease around the back-link any more, and none is needed: this is a + // single-column `UPDATE`, and `ExamQuestion::update` no longer re-states + // this column from a snapshot (it names the columns it writes), so a + // question edit racing the link cannot revert it. That lease existed only to + // order those two, and the ordering requirement is gone with the whole-row + // save that created it. + if let Err(err) = question + .link_banked_as(template.get_id().clone(), &st.db) + .await + { + tracing::warn!( + "saved question {question_key} to the bank but could not link it back: {err}" + ); + } + + let images = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; + Ok(( + StatusCode::CREATED, + Json(BankQuestionResponse::new(&template, &images)), + )) +} diff --git a/src/web/exams/review.rs b/src/web/exams/review.rs new file mode 100644 index 0000000..3296512 --- /dev/null +++ b/src/web/exams/review.rs @@ -0,0 +1,314 @@ +use super::*; + +// ---- per-attempt history ---------------------------------------------------- +// The grading views above show the latest sitting; these expose every prior +// sitting a re-taking student left behind. Same wall as grading: teacher+ who +// manages the exam's course. A student never reaches another student's sheet, +// and a student's own prior attempts are staff-visible by design. + +/// The exam plus the manage-rights check the grading and history reads share. +pub(crate) async fn gradable_exam(st: &AppState, user: &User, id: &str) -> Result { + let exam = Exam::read(&ExamId::from_key(id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can read answer sheets", + )); + } + Ok(exam) +} + +/// The sitting numbers a student has left at an exam — every seq that carries +/// answers or a mark, ascending. Requires teacher+ and management rights over +/// the exam's course. Drives the FE's attempt-by-attempt picker. +#[utoipa::path( + get, + path = "/{id}/students/{user}/attempts", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("user" = String, Path, description = "User id"), + ), + responses( + (status = 200, description = "The student's sitting numbers, ascending", body = [i64]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Exam not found", body = ErrorResponse), + ), +)] +pub(crate) async fn student_attempts( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, target)): Path<(String, String)>, +) -> Result>, AppError> { + let exam = gradable_exam(&st, &user, &id).await?; + let target = UserId::from_key(&target); + let mut seqs = ExamAnswer::list_seqs_for_user(exam.get_id(), &target, &st.db).await?; + for result in ExamResult::list_all_for_exam_user(exam.get_id(), &target, &st.db).await? { + seqs.push(result.get_seq()); + } + seqs.sort_unstable(); + seqs.dedup(); + Ok(Json(seqs)) +} + +/// One prior sitting's judged answer sheet — the `seq`th attempt's answers, +/// drawing refs, correctness flags, and auto-score suggestion. Requires +/// teacher+ and management rights over the exam's course. Serves an empty +/// sheet for a seq the student never wrote in. +#[utoipa::path( + get, + path = "/{id}/students/{user}/attempts/{seq}/answers", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("user" = String, Path, description = "User id"), + ("seq" = i64, Path, description = "Sitting number (1, 2, …)"), + ), + responses( + (status = 200, description = "That sitting's answers, judged", body = AttemptAnswersResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Exam not found", body = ErrorResponse), + ), +)] +pub(crate) async fn student_attempt_answers( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, target, seq)): Path<(String, String, i64)>, +) -> Result, AppError> { + let exam = gradable_exam(&st, &user, &id).await?; + let target = UserId::from_key(&target); + Ok(Json(answer_sheet(&exam, &target, seq, &st.db).await?)) +} + +/// A prior sitting's drawn-answer bytes. Requires teacher+ and management +/// rights over the exam's course — the seq-scoped mirror of the grader's +/// latest-sitting drawing read. +#[utoipa::path( + get, + path = "/{id}/students/{user}/attempts/{seq}/answers/{qid}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("user" = String, Path, description = "User id"), + ("seq" = i64, Path, description = "Sitting number (1, 2, …)"), + ("qid" = String, Path, description = "Question id"), + ), + responses( + (status = 200, description = "The student's drawing bytes", content_type = "image/*"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, question, or drawing", body = ErrorResponse), + ), +)] +pub(crate) async fn student_attempt_answer_image( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, target, seq, qid)): Path<(String, String, i64, String)>, +) -> Result { + let exam = gradable_exam(&st, &user, &id).await?; + let target = UserId::from_key(&target); + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let image = AnswerImage::read(question.get_id(), &target, seq, &st.db) + .await? + .ok_or(AppError::NotFound)?; + crate::web::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await +} + +/// A student's full mark history at an exam — every sitting's mark, oldest +/// first (the grade-of-record is the latest). Requires teacher+ and management +/// rights over the exam's course. +#[utoipa::path( + get, + path = "/{id}/students/{user}/marks", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("user" = String, Path, description = "User id"), + ), + responses( + (status = 200, description = "The student's per-sitting marks, oldest first", body = [ExamResultResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Exam not found", body = ErrorResponse), + ), +)] +pub(crate) async fn student_marks_history( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, target)): Path<(String, String)>, +) -> Result>, AppError> { + let exam = gradable_exam(&st, &user, &id).await?; + let target = UserId::from_key(&target); + let results = ExamResult::list_all_for_exam_user(exam.get_id(), &target, &st.db).await?; + let people = person_map( + results + .iter() + .flat_map(|r| [r.get_user().clone(), r.get_graded_by().clone()]), + &st.db, + ) + .await?; + Ok(Json( + results + .iter() + .map(|r| ExamResultResponse::new(r, &people)) + .collect(), + )) +} + +// ---- student self-review ---------------------------------------------------- +// The mirror of the teacher history reads above, but own-scoped: no `{user}` +// path param, so the target is always the caller — a student can never reach +// another student's sheet. Opens only once the teacher enables review AND has +// marked this student (an ExamResult row proves it). + +/// The exam plus the per-student review gate the three self-review reads share. +/// 404 if the exam is missing or still a draft, 403 if review is off for it, and +/// 404 until the caller has a mark on it (nothing to review yet). +pub(crate) async fn reviewable_exam( + st: &AppState, + user: &User, + id: &str, +) -> Result { + let exam = Exam::read(&ExamId::from_key(id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if exam.is_draft() { + return Err(AppError::NotFound); + } + if !exam.get_allow_review() { + return Err(AppError::Forbidden("review not enabled for this exam")); + } + ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + Ok(exam) +} + +/// The caller's own sitting numbers at an exam — every seq that carries answers +/// or a mark, ascending. Own-scoped review view; opens once the teacher enables +/// review and has marked the caller. +#[utoipa::path( + get, + path = "/{id}/review/attempts", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 200, description = "The caller's own sitting numbers, ascending", body = [i64]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), + (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse), + ), +)] +pub(crate) async fn review_attempts( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result>, AppError> { + let exam = reviewable_exam(&st, &user, &id).await?; + let target = user.get_id().clone(); + let mut seqs = ExamAnswer::list_seqs_for_user(exam.get_id(), &target, &st.db).await?; + for result in ExamResult::list_all_for_exam_user(exam.get_id(), &target, &st.db).await? { + seqs.push(result.get_seq()); + } + seqs.sort_unstable(); + seqs.dedup(); + Ok(Json(seqs)) +} + +/// The exam's full question list, `correct` choice ids included — the answer key +/// the caller reviews their own sheet against. Same review gate as the other +/// self-review reads; revealing `correct` is the point (the gate already proves +/// the caller was marked). Paged via `?limit=&offset=`. +#[utoipa::path( + get, + path = "/{id}/review/questions", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id"), PageParams), + responses( + (status = 200, description = "A page of the exam's questions with `correct` (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), + (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse), + ), +)] +pub(crate) async fn review_questions( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let exam = reviewable_exam(&st, &user, &id).await?; + Ok(Json(question_page(&exam, limit, offset, &st.db).await?)) +} + +/// One of the caller's own sittings, judged — the `seq`th attempt's answers, +/// drawing refs, correctness flags, and auto-score suggestion. Own-scoped +/// review view. +#[utoipa::path( + get, + path = "/{id}/review/attempts/{seq}/answers", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("seq" = i64, Path, description = "Sitting number (1, 2, …)"), + ), + responses( + (status = 200, description = "That sitting's answers, judged", body = AttemptAnswersResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), + (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse), + ), +)] +pub(crate) async fn review_attempt_answers( + State(st): State, + CurrentUser(user): CurrentUser, + Path((id, seq)): Path<(String, i64)>, +) -> Result, AppError> { + let exam = reviewable_exam(&st, &user, &id).await?; + Ok(Json(answer_sheet(&exam, user.get_id(), seq, &st.db).await?)) +} + +/// The caller's own drawn-answer bytes for one of their sittings — the +/// seq-scoped, own-scoped mirror of the grader's drawing read. +#[utoipa::path( + get, + path = "/{id}/review/attempts/{seq}/answers/{qid}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("seq" = i64, Path, description = "Sitting number (1, 2, …)"), + ("qid" = String, Path, description = "Question id"), + ), + responses( + (status = 200, description = "The caller's drawing bytes", content_type = "image/*"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), + (status = 404, description = "No such exam/question/drawing, a draft, or the caller has no mark on it", body = ErrorResponse), + ), +)] +pub(crate) async fn review_attempt_answer_image( + State(st): State, + CurrentUser(user): CurrentUser, + Path((id, seq, qid)): Path<(String, i64, String)>, +) -> Result { + let exam = reviewable_exam(&st, &user, &id).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db) + .await? + .ok_or(AppError::NotFound)?; + crate::web::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await +} diff --git a/src/web/homework.rs b/src/web/homework.rs index 282baee..4d779e3 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -192,6 +192,7 @@ async fn list_homework( homework }; let total = homework.len() as i64; + // Paged in the web layer: the audience filter above is per-row Rust. let items = paginate(&homework, limit, offset) .iter() .map(HomeworkResponse::new) @@ -1201,8 +1202,9 @@ async fn list_homework_submissions( } let submissions = HomeworkSubmission::list_for_homework(homework.get_id(), &st.db).await?; let results = HomeworkResult::list_for_homework(homework.get_id(), &st.db).await?; - let enrolled: Vec = Enrollment::list_for_course(course.get_id(), &st.db) + let enrolled: Vec = Enrollment::list_for_course(course.get_id(), None, 0, &st.db) .await? + .0 .iter() .map(|enrollment| enrollment.get_user().key().to_string()) .collect(); @@ -1232,6 +1234,7 @@ async fn list_homework_submissions( let total = users.len() as i64; // Join the heavy parts (the file lists) onto the page alone. let mut items = Vec::new(); + // Paged in the web layer: the audience is resolved in Rust. for user_key in paginate(&users, limit, offset) { let submission = match submissions .iter() @@ -1325,7 +1328,7 @@ async fn homework_report( .ok_or(AppError::NotFound)?; // Only an exactly-teacher caller is narrowed to their managed courses; // manager+ and a linked parent read the full report (the marks idiom). - let mut courses = Course::list_enrolled(&target, &st.db).await?; + let (mut courses, _) = Course::list_enrolled(&target, None, 0, &st.db).await?; if caller.get_role() == Role::Teacher { courses.retain(|course| can_manage_course(course, &caller)); } @@ -1336,6 +1339,7 @@ async fn homework_report( let total = rows.len() as i64; // Join submissions and grades onto the page alone. let mut items = Vec::new(); + // Paged in the web layer: the rows are gathered course by course. for homework in paginate(&rows, limit, offset) { let submission = HomeworkSubmission::read_for(homework.get_id(), &target, &st.db).await?; let result = HomeworkResult::read_for(homework.get_id(), &target, &st.db).await?; diff --git a/src/web/image.rs b/src/web/image.rs new file mode 100644 index 0000000..5402a41 --- /dev/null +++ b/src/web/image.rs @@ -0,0 +1,81 @@ +//! The two halves every image upload shares, whatever the picture hangs on +//! (exam question, bank template, pool question, solution, answer sheet): +//! reading the `file` part under the school's size limit and the raster +//! allowlist, and the blob-first write dance — fresh blob to disk, then the +//! row, then the replaced blob off disk, with any row failure taking the fresh +//! blob back out. A stored row therefore always points at a real blob, and a +//! failed write strands nothing. +//! +//! Gates stay at the call sites (the exam freeze, the pool's approval, owner +//! and author rules), as do the row types: this module owns only the +//! format/limit rule and the rollback, once each. + +use std::future::Future; + +use axum::extract::Multipart; + +use crate::domain::note_file::FileContentType; +use crate::domain::settings::Settings; +use crate::error::AppError; +use crate::state::AppState; + +use super::{blob_path, image_content_type, read_upload, remove_blob}; + +/// A validated image upload: an allowlisted raster content type and the bytes. +pub(crate) struct ImageUpload { + pub content_type: FileContentType, + pub data: Vec, +} + +impl ImageUpload { + pub(crate) fn size(&self) -> i64 { + self.data.len() as i64 + } +} + +/// The multipart `file` part, held to the school's `max_file_bytes` and the +/// raster allowlist — the one place either rule is spelled, so a format or +/// limit change lands on every image endpoint at once. +pub(crate) async fn read_image_upload( + st: &AppState, + multipart: &mut Multipart, +) -> Result { + let limit = Settings::load(&st.db).await?.get_max_file_bytes(); + let upload = read_upload(multipart, limit).await?; + let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; + Ok(ImageUpload { + content_type, + data: upload.data, + }) +} + +/// Blob first, row second: `data` lands on disk under `file`, then `write_row` +/// runs. It returns what it stored plus the blob name it replaced (if any), +/// which comes off disk only once the row is safely written; any error takes +/// the fresh blob back out instead. +pub(crate) async fn store_blob( + st: &AppState, + file: &str, + data: &[u8], + write_row: impl FnOnce() -> Fut, +) -> Result +where + Fut: Future), AppError>>, +{ + let path = blob_path(&st.files_path, file); + tokio::fs::write(&path, data) + .await + .map_err(|err| AppError::Internal(format!("failed to store the image blob: {err}")))?; + match write_row().await { + Ok((stored, replaced)) => { + if let Some(replaced) = replaced { + remove_blob(&st.files_path, &replaced).await; + } + Ok(stored) + } + Err(err) => { + let _ = tokio::fs::remove_file(&path).await; + Err(err) + } + } +} diff --git a/src/web/marks.rs b/src/web/marks.rs index 3804baa..24c9fb5 100644 --- a/src/web/marks.rs +++ b/src/web/marks.rs @@ -95,7 +95,7 @@ async fn build_report( viewer: Option<&User>, db: &Database, ) -> Result { - let mut courses = Course::list_enrolled(user, db).await?; + let (mut courses, _) = Course::list_enrolled(user, None, 0, db).await?; if let Some(viewer) = viewer { courses.retain(|course| can_manage_course(course, viewer)); } diff --git a/src/web/meals.rs b/src/web/meals.rs index 4d8a9d1..cf10f5d 100644 --- a/src/web/meals.rs +++ b/src/web/meals.rs @@ -35,7 +35,7 @@ use crate::state::AppState; use super::{ CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireManager, RequireTeacher, - paginate, person_map, set_or_clear, + person_map, set_or_clear, }; pub fn routes() -> OpenApiRouter { @@ -283,10 +283,9 @@ async fn list_menus( let (limit, offset) = page.resolve()?; let from = range.from.as_deref().map(MenuDate::try_new).transpose()?; let to = range.to.as_deref().map(MenuDate::try_new).transpose()?; - let menus = Menu::list(from.as_ref(), to.as_ref(), &st.db).await?; - let total = menus.len() as i64; + let (menus, total) = Menu::list(from.as_ref(), to.as_ref(), limit, offset, &st.db).await?; // The dish/people join runs over the page alone, so it shrinks with it. - let items = menu_responses(paginate(&menus, limit, offset), user.get_id(), &st.db).await?; + let items = menu_responses(&menus, user.get_id(), &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) } @@ -870,9 +869,8 @@ async fn my_bookings( .map(|link| link.get_student().clone()), ); } - let rows = MealBooking::list_for_students(&students, &st.db).await?; - let total = rows.len() as i64; - let items = booking_responses(paginate(&rows, limit, offset), &st.db).await?; + let (rows, total) = MealBooking::list_for_students(&students, limit, offset, &st.db).await?; + let items = booking_responses(&rows, &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) } @@ -903,9 +901,8 @@ async fn list_menu_bookings( let menu = Menu::read(&MenuId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - let rows = MealBooking::list_for_menu(menu.get_id(), &st.db).await?; - let total = rows.len() as i64; - let items = booking_responses(paginate(&rows, limit, offset), &st.db).await?; + let (rows, total) = MealBooking::list_for_menu(menu.get_id(), limit, offset, &st.db).await?; + let items = booking_responses(&rows, &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) } @@ -1094,9 +1091,8 @@ async fn list_menu_attendance( let menu = Menu::read(&MenuId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - let rows = MealAttendance::list_for_menu(menu.get_id(), &st.db).await?; - let total = rows.len() as i64; - let items = attendance_responses(paginate(&rows, limit, offset), &st.db).await?; + let (rows, total) = MealAttendance::list_for_menu(menu.get_id(), limit, offset, &st.db).await?; + let items = attendance_responses(&rows, &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) } @@ -1129,10 +1125,16 @@ async fn user_attendance( ensure_can_read_student(&caller, &target, &st.db).await?; let from = range.from.as_deref().map(MenuDate::try_new).transpose()?; let to = range.to.as_deref().map(MenuDate::try_new).transpose()?; - let rows = - MealAttendance::list_for_student(&target, from.as_ref(), to.as_ref(), &st.db).await?; - let total = rows.len() as i64; - let items = attendance_responses(paginate(&rows, limit, offset), &st.db).await?; + let (rows, total) = MealAttendance::list_for_student( + &target, + from.as_ref(), + to.as_ref(), + limit, + offset, + &st.db, + ) + .await?; + let items = attendance_responses(&rows, &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) } @@ -1296,9 +1298,8 @@ async fn user_ledger( let (limit, offset) = page.resolve()?; let target = UserId::from_key(&user); ensure_can_read_student(&caller, &target, &st.db).await?; - let rows = MealLedger::list_for_student(&target, &st.db).await?; - let total = rows.len() as i64; - let items = ledger_responses(paginate(&rows, limit, offset), &st.db).await?; + let (rows, total) = MealLedger::list_for_student(&target, limit, offset, &st.db).await?; + let items = ledger_responses(&rows, &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) } diff --git a/src/web/messages.rs b/src/web/messages.rs index eca02c9..8d05d12 100644 --- a/src/web/messages.rs +++ b/src/web/messages.rs @@ -17,7 +17,7 @@ use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; use super::dto::Role; -use super::{CurrentUser, Page, PageParams, PersonRef, paginate}; +use super::{CurrentUser, Page, PageParams, PersonRef}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() @@ -240,11 +240,10 @@ async fn list( None => Folder::Inbox, }; - let messages = Message::list_folder(user.get_id(), folder, filter.read, &st.db).await?; - let total = messages.len() as i64; - let slice = paginate(&messages, limit, offset); - let people = load_people(slice, &st.db).await?; - let items = slice + let (messages, total) = + Message::list_folder(user.get_id(), folder, filter.read, limit, offset, &st.db).await?; + let people = load_people(&messages, &st.db).await?; + let items = messages .iter() .map(|message| MessageResponse::new(message, user.get_id(), &people)) .collect(); diff --git a/src/web/mod.rs b/src/web/mod.rs index 444e850..215dc1b 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -31,6 +31,7 @@ pub mod work; mod dto; mod extractor; +mod image; mod page; pub use dto::{ @@ -38,6 +39,7 @@ pub use dto::{ UserResponse, course_people, person_map, }; pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireStudent, RequireTeacher}; +pub(crate) use image::{ImageUpload, read_image_upload, store_blob}; pub use page::{Page, PageParams, Scheduled, WindowParams, paginate}; use std::path::{Path as FsPath, PathBuf}; @@ -92,7 +94,10 @@ pub(crate) async fn ensure_can_observe( } /// If both ends are present, `ends_at` must not precede `starts_at`. Shared by -/// everything that carries a time range (events, course sessions). +/// everything that carries a time range (events, course sessions). The PATCH +/// paths re-check this at write time via +/// [`crate::domain::field_update::FieldUpdate::ordered`], which answers with the +/// same error — this is the pre-flight, that is the race closer. pub(crate) fn check_time_range( starts_at: Option, ends_at: Option, @@ -100,10 +105,7 @@ pub(crate) fn check_time_range( if let (Some(starts), Some(ends)) = (starts_at, ends_at) && ends < starts { - return Err(AppError::Validation(ValidationError::Invalid { - field: "ends_at", - reason: "must be at or after starts_at", - })); + return Err(crate::domain::timestamp::range_error()); } Ok(()) } diff --git a/src/web/notes.rs b/src/web/notes.rs index 43635a5..c2dd50a 100644 --- a/src/web/notes.rs +++ b/src/web/notes.rs @@ -16,7 +16,7 @@ use crate::error::{AppError, ErrorResponse}; use crate::state::AppState; use super::{ - Page, PageParams, RequireStudent, UploadFileForm, blob_path, paginate, read_upload, remove_blob, + Page, PageParams, RequireStudent, UploadFileForm, blob_path, read_upload, remove_blob, }; pub fn routes() -> OpenApiRouter { @@ -116,12 +116,8 @@ async fn list( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let notes = Note::list_for(user.get_id(), &st.db).await?; - let total = notes.len() as i64; - let items = paginate(¬es, limit, offset) - .iter() - .map(NoteResponse::new) - .collect(); + let (notes, total) = Note::list_for(user.get_id(), limit, offset, &st.db).await?; + let items = notes.iter().map(NoteResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -216,7 +212,7 @@ async fn delete_one( // Rows go first (the note delete cascades them), blobs after: a crash in // between strands at worst an unreachable blob, never a row whose blob is // already gone. - let files = NoteFile::list_for(note.get_id(), &st.db).await?; + let (files, _) = NoteFile::list_for(note.get_id(), None, 0, &st.db).await?; note.delete(&st.db).await?; for file in &files { remove_blob(&st.files_path, file.get_id().key()).await; @@ -331,12 +327,8 @@ async fn list_files( let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) .await? .ok_or(AppError::NotFound)?; - let files = NoteFile::list_for(note.get_id(), &st.db).await?; - let total = files.len() as i64; - let items = paginate(&files, limit, offset) - .iter() - .map(NoteFileResponse::new) - .collect(); + let (files, total) = NoteFile::list_for(note.get_id(), limit, offset, &st.db).await?; + let items = files.iter().map(NoteFileResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } diff --git a/src/web/pomodoro.rs b/src/web/pomodoro.rs index 12c1f5f..ee66696 100644 --- a/src/web/pomodoro.rs +++ b/src/web/pomodoro.rs @@ -92,6 +92,8 @@ impl PomodoroLog { }) .sum(); Self { + // Paged in the web layer: `total_focus_ms` folds the whole log, so the + // rows the page comes from are already all in hand. items: paginate(sessions, limit, offset) .iter() .map(PomodoroResponse::new) diff --git a/src/web/questions.rs b/src/web/questions.rs index 2d6a123..a2c421c 100644 --- a/src/web/questions.rs +++ b/src/web/questions.rs @@ -22,7 +22,6 @@ use crate::domain::pool_question::{ PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle, }; use crate::domain::role::Role; -use crate::domain::settings::Settings; use crate::domain::solution::{Solution, SolutionBody, SolutionId}; use crate::domain::user::User; use crate::error::{AppError, ErrorResponse, ValidationError}; @@ -30,8 +29,7 @@ use crate::state::AppState; use super::{ CurrentUser, Page, PageParams, PersonRef, RequireStudent, RequireTeacher, UploadFileForm, - blob_path, image_content_type, paginate, person_map, read_upload, remove_blob, - serve_inline_blob, + paginate, person_map, read_image_upload, remove_blob, serve_inline_blob, store_blob, }; pub fn routes() -> OpenApiRouter { @@ -319,6 +317,7 @@ async fn list_questions( } let total = questions.len() as i64; + // Paged in the web layer: the status filter above is per-row Rust. let items = question_responses(paginate(&questions, limit, offset), &st).await?; Ok(Json(Page::new(items, total, limit, offset))) } @@ -476,42 +475,29 @@ async fn upload_image( ) -> Result<(StatusCode, Json), AppError> { let question = question_or_404(&st, &id).await?; ensure_asker_editable(&question, &user)?; - let limit = Settings::load(&st.db).await?.get_max_file_bytes(); - let upload = read_upload(&mut multipart, limit).await?; - let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; + let upload = read_image_upload(&st, &mut multipart).await?; + let size = upload.size(); - // Blob first, row second — a stored row always points at a real blob. let file = ulid::Ulid::new().to_string(); - let path = blob_path(&st.files_path, &file); - tokio::fs::write(&path, &upload.data) - .await - .map_err(|err| AppError::Internal(format!("failed to store the image blob: {err}")))?; - let size = upload.data.len() as i64; - match PoolQuestion::set_image(question.get_id(), &file, &content_type, size, &st.db).await { - // The guarded UPDATE found the question still pending: point-of-truth - // write done; the replaced blob (if any) comes off disk. - Ok(Some(before)) => { - if let Some(replaced) = before.get_image_file() { - remove_blob(&st.files_path, replaced).await; - } - Ok(( - StatusCode::CREATED, - Json(PoolImageMeta { - content_type: content_type.as_str().to_string(), - size, - }), - )) - } - // Approved or deleted mid-upload — the fresh blob is an orphan. - Ok(None) => { - let _ = tokio::fs::remove_file(&path).await; - Err(AppError::Conflict("the question is no longer pending")) + store_blob(&st, &file, &upload.data, || async { + match PoolQuestion::set_image(question.get_id(), &file, &upload.content_type, size, &st.db) + .await? + { + // The guarded UPDATE found the question still pending: point-of-truth + // write done; the replaced blob (if any) comes off disk. + Some(before) => Ok(((), before.get_image_file().map(str::to_string))), + // Approved or deleted mid-upload — the fresh blob is an orphan. + None => Err(AppError::Conflict("the question is no longer pending")), } - Err(err) => { - let _ = tokio::fs::remove_file(&path).await; - Err(err) - } - } + }) + .await?; + Ok(( + StatusCode::CREATED, + Json(PoolImageMeta { + content_type: upload.content_type.as_str().to_string(), + size, + }), + )) } /// The question's photo bytes. Access follows the question itself: approved → @@ -683,9 +669,8 @@ async fn list_solutions( let (limit, offset) = page.resolve()?; let question = question_or_404(&st, &id).await?; ensure_visible(&question, &user)?; - let solutions = Solution::list_for(question.get_id(), &st.db).await?; - let total = solutions.len() as i64; - let slice = paginate(&solutions, limit, offset); + let (solutions, total) = Solution::list_for(question.get_id(), limit, offset, &st.db).await?; + let slice = solutions.as_slice(); let people = person_map( slice.iter().map(|solution| solution.get_author().clone()), &st.db, @@ -812,41 +797,28 @@ async fn upload_solution_image( mut multipart: Multipart, ) -> Result<(StatusCode, Json), AppError> { let solution = author_solution(&st, &user, &id, &sid).await?; - let limit = Settings::load(&st.db).await?.get_max_file_bytes(); - let upload = read_upload(&mut multipart, limit).await?; - let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; + let upload = read_image_upload(&st, &mut multipart).await?; + let size = upload.size(); - // Blob first, row second — a stored row always points at a real blob. let file = ulid::Ulid::new().to_string(); - let path = blob_path(&st.files_path, &file); - tokio::fs::write(&path, &upload.data) - .await - .map_err(|err| AppError::Internal(format!("failed to store the image blob: {err}")))?; - let size = upload.data.len() as i64; - match Solution::set_image(solution.get_id(), &file, &content_type, size, &st.db).await { - // Row write done; the replaced blob (if any) comes off disk. - Ok(Some(before)) => { - if let Some(replaced) = before.get_image_file() { - remove_blob(&st.files_path, replaced).await; - } - Ok(( - StatusCode::CREATED, - Json(PoolImageMeta { - content_type: content_type.as_str().to_string(), - size, - }), - )) - } - // Deleted mid-upload — the fresh blob is an orphan. - Ok(None) => { - let _ = tokio::fs::remove_file(&path).await; - Err(AppError::NotFound) + store_blob(&st, &file, &upload.data, || async { + match Solution::set_image(solution.get_id(), &file, &upload.content_type, size, &st.db) + .await? + { + // Row write done; the replaced blob (if any) comes off disk. + Some(before) => Ok(((), before.get_image_file().map(str::to_string))), + // Deleted mid-upload — the fresh blob is an orphan. + None => Err(AppError::NotFound), } - Err(err) => { - let _ = tokio::fs::remove_file(&path).await; - Err(err) - } - } + }) + .await?; + Ok(( + StatusCode::CREATED, + Json(PoolImageMeta { + content_type: upload.content_type.as_str().to_string(), + size, + }), + )) } /// The solution photo's bytes. Access follows the question the solution diff --git a/src/web/sessions.rs b/src/web/sessions.rs index 969c23e..63e4236 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -11,7 +11,7 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::attendance::AttendanceStatus; use crate::domain::course::Course; -use crate::domain::course_session::{CourseSession, CourseSessionId, SESSION_LOCK, SessionTopic}; +use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; use crate::domain::enrollment::Enrollment; use crate::domain::role::Role; use crate::domain::session_attendance::SessionAttendance; @@ -24,7 +24,7 @@ use crate::state::AppState; use super::courses::{can_manage_course, can_view_course}; use super::{ CurrentUser, Page, PageParams, PersonRef, RequireTeacher, SessionResponse, check_not_past, - check_time_range, paginate, person_map, set_or_clear, + check_time_range, person_map, set_or_clear, }; pub fn routes() -> OpenApiRouter { @@ -197,15 +197,6 @@ async fn update_session( if let Some(ends_at) = ends_at { check_not_past("ends_at", ends_at)?; } - // Only the range check needs the stored row, and only it can race: it - // validates an arriving end against the other end as stored, so the read, - // the check and the write are held together under [`SESSION_LOCK`]. A PATCH - // that moves neither end pays nothing. - let _guard = match (starts_at, ends_at) { - (None, None) => None, - _ => Some(SESSION_LOCK.lock().await), - }; - let (session, course) = session_with_course(&id, &st.db).await?; if !can_manage_course(&course, &user) { return Err(AppError::Forbidden( @@ -228,7 +219,8 @@ async fn update_session( None => None, }; // The end this request left out is only *read* for the range check — it is - // never written back, so a concurrent move of it survives. + // never written back, so a concurrent move of it survives. Pre-flight only: + // `CourseSession::update` re-makes this check in the UPDATE's `WHERE`. check_time_range( Some(starts_at.unwrap_or_else(|| session.get_starts_at())), ends_at.unwrap_or_else(|| session.get_ends_at()), @@ -383,10 +375,9 @@ async fn list_roll_call( "only the session's teacher or a course manager can list the roll call", )); } - let roster = SessionAttendance::list_for_session(session.get_id(), &st.db).await?; - let total = roster.len() as i64; + let (rows, total) = + SessionAttendance::list_for_session(session.get_id(), limit, offset, &st.db).await?; // Join people onto the page alone — the lookup shrinks with the window. - let rows = paginate(&roster, limit, offset); let people = person_map( rows.iter() .flat_map(|a| [a.get_user().clone(), a.get_marked_by().clone()]), diff --git a/src/web/settings.rs b/src/web/settings.rs index 94cead6..2d32920 100644 --- a/src/web/settings.rs +++ b/src/web/settings.rs @@ -5,7 +5,7 @@ use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; -use crate::constant::SETTINGS_UPDATE_RETRIES; +use crate::constant::CAS_UPDATE_RETRIES; use crate::domain::exam_result::ExamResult; use crate::domain::menu::{MENU_LOCK, Menu}; use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings}; @@ -274,7 +274,7 @@ async fn update_settings( Some(_) => Some(MENU_LOCK.lock().await), None => None, }; - for _ in 0..SETTINGS_UPDATE_RETRIES { + for _ in 0..CAS_UPDATE_RETRIES { let current = Settings::load(&st.db).await?; let exam_kinds = match &req.exam_kinds { diff --git a/src/web/terms.rs b/src/web/terms.rs index faf22fd..91186cd 100644 --- a/src/web/terms.rs +++ b/src/web/terms.rs @@ -12,7 +12,7 @@ use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; -use super::{CurrentUser, Page, PageParams, RequireManager, check_time_range, paginate}; +use super::{CurrentUser, Page, PageParams, RequireManager, check_time_range}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() @@ -132,12 +132,8 @@ async fn list_terms( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let terms = Term::list_all(&st.db).await?; - let total = terms.len() as i64; - let items = paginate(&terms, limit, offset) - .iter() - .map(TermResponse::new) - .collect(); + let (terms, total) = Term::list_all(limit, offset, &st.db).await?; + let items = terms.iter().map(TermResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -192,16 +188,12 @@ async fn update_term( let starts_at = req.starts_at.map(Timestamp::from_millis); let ends_at = req.ends_at.map(Timestamp::from_millis); - // Only the range check needs the stored row, and only it can race: it - // validates an arriving end against the other end as stored, so the read, - // the check and the write are held together under [`TERM_LOCK`]. - let _guard = match (starts_at, ends_at) { - (None, None) => None, - _ => Some(TERM_LOCK.lock().await), - }; let term = Term::read(&TermId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; + // Pre-flight only: the range check is re-made inside the UPDATE's `WHERE` + // (`Term::update`), so a concurrent move of the end this PATCH omits cannot + // slip an inverted range past this snapshot. check_time_range( Some(starts_at.unwrap_or_else(|| term.get_starts_at())), Some(ends_at.unwrap_or_else(|| term.get_ends_at())), diff --git a/src/web/users.rs b/src/web/users.rs index cf3ce0d..a213c50 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -182,12 +182,8 @@ async fn search_users( } .resolve()?; let role = req.role.as_deref().map(Role::try_from_str).transpose()?; - let users = User::search(&req.q, role, &st.db).await?; - let total = users.len() as i64; - let items = paginate(&users, limit, offset) - .iter() - .map(PersonRef::new) - .collect(); + let (users, total) = User::search(&req.q, role, limit, offset, &st.db).await?; + let items = users.iter().map(PersonRef::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -214,12 +210,8 @@ async fn list_users( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let users = User::list_all(&st.db).await?; - let total = users.len() as i64; - let items = paginate(&users, limit, offset) - .iter() - .map(UserResponse::new) - .collect(); + let (users, total) = User::list_all(limit, offset, &st.db).await?; + let items = users.iter().map(UserResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -445,6 +437,8 @@ async fn students_page( let mut students = User::list_by_ids(&ids, db).await?; students.sort_by(|a, b| a.get_username().as_str().cmp(b.get_username().as_str())); let total = students.len() as i64; + // Paged in the web layer: the rows come from a link table and are + // re-sorted by username in Rust. let items = paginate(&students, limit, offset) .iter() .map(PersonRef::new) diff --git a/src/web/work.rs b/src/web/work.rs index c48e021..a663bd9 100644 --- a/src/web/work.rs +++ b/src/web/work.rs @@ -8,11 +8,11 @@ use utoipa_axum::routes; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; -use crate::domain::work_entry::{WORK_ENTRY_LOCK, WorkEntry, WorkEntryId}; -use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::domain::work_entry::{WorkEntry, WorkEntryId, out_before_in_error}; +use crate::error::{AppError, ErrorResponse}; use crate::state::AppState; -use super::{Page, PageParams, RequireManager, RequireTeacher, paginate}; +use super::{Page, PageParams, RequireManager, RequireTeacher}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() @@ -127,12 +127,8 @@ async fn my_work( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let entries = WorkEntry::list_for_user(user.get_id(), &st.db).await?; - let total = entries.len() as i64; - let items = paginate(&entries, limit, offset) - .iter() - .map(WorkEntryResponse::new) - .collect(); + let (entries, total) = WorkEntry::list_for_user(user.get_id(), limit, offset, &st.db).await?; + let items = entries.iter().map(WorkEntryResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -165,12 +161,8 @@ async fn user_work( User::read(&target, &st.db) .await? .ok_or(AppError::NotFound)?; - let entries = WorkEntry::list_for_user(&target, &st.db).await?; - let total = entries.len() as i64; - let items = paginate(&entries, limit, offset) - .iter() - .map(WorkEntryResponse::new) - .collect(); + let (entries, total) = WorkEntry::list_for_user(&target, limit, offset, &st.db).await?; + let items = entries.iter().map(WorkEntryResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -200,15 +192,6 @@ async fn update_entry( ) -> Result, AppError> { let check_in = req.check_in.map(Timestamp::from_millis); let check_out = req.check_out.map(Timestamp::from_millis); - // Only the ordering check needs the stored row, and only it can race: it - // validates an arriving instant against the other one as stored, so the - // read, the check and the write are held together under - // [`WORK_ENTRY_LOCK`]. A PATCH carrying neither instant pays nothing. - let _guard = match (check_in, check_out) { - (None, None) => None, - _ => Some(WORK_ENTRY_LOCK.lock().await), - }; - let entry = WorkEntry::read(&WorkEntryId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; @@ -220,11 +203,9 @@ async fn update_entry( // The side the correction left out is only *read* for the ordering check — // it is never written back, so a concurrent correction of it survives. + // Pre-flight only: `WorkEntry::update` re-makes this in the UPDATE's `WHERE`. if check_out.unwrap_or(current_out) < check_in.unwrap_or_else(|| entry.get_check_in()) { - return Err(AppError::Validation(ValidationError::Invalid { - field: "check_out", - reason: "must be at or after check_in", - })); + return Err(out_before_in_error()); } let updated = entry.update(check_in, check_out, &st.db).await?; diff --git a/tests/integration.rs b/tests/integration.rs index 16f6cf7..b3302f5 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -4108,6 +4108,127 @@ async fn concurrent_placements_never_exceed_capacity() { } } +/// The course capacity cap is a counter column on the course row now, not a +/// process mutex: `UPDATE ... SET n += 1 WHERE n < capacity` is atomic per +/// record, so it holds whichever replica the racing enrolls land on. Removing +/// that `WHERE` (or the claim entirely) puts a third student on a capacity-2 +/// course and fails this. The unenroll each round proves the seat comes back — +/// without the decrement the course is permanently full by round two. +#[tokio::test] +async fn concurrent_enrolls_never_exceed_course_capacity() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let mut students = Vec::new(); + for name in ["ali", "veli", "ayse"] { + let cookie = login(&app, name).await; + let id = me_id(&app, &cookie).await; + students.push(id); + } + let res = send( + &app, + "POST", + "/courses", + Some(&teacher), + Some(json!({ "title": "small", "description": "", "capacity": 2 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let course = id_of(&res.body); + let uri = format!("/courses/{course}/enrollments"); + + for _round in 0..8 { + for id in &students { + let _ = send(&app, "DELETE", &format!("{uri}/{id}"), Some(&teacher), None).await; + } + let mut handles = Vec::new(); + for id in &students { + let (app, teacher, uri) = (app.clone(), teacher.clone(), uri.clone()); + let body = json!({ "user_id": id }); + handles.push(tokio::spawn(async move { + send(&app, "POST", &uri, Some(&teacher), Some(body)) + .await + .status + })); + } + for handle in handles { + let status = handle.await.unwrap(); + assert!( + status == StatusCode::OK || status == StatusCode::CONFLICT, + "a lost capacity race must be a 409, got {status}" + ); + } + let roster = send(&app, "GET", &uri, Some(&teacher), None).await; + assert!( + common::total(&roster.body) <= 2, + "capacity 2 must never over-admit, roster={}", + roster.body + ); + } +} + +/// The same (user, course) pair enrolled concurrently must cost exactly one +/// seat: the row is idempotent by its composite id, so a second enroll that +/// finds the pair already there returns it *without* claiming, and a `CREATE` +/// that loses the id race releases the seat it claimed before reading the +/// winner's row back. Either way the counter must equal the roster — a drift +/// above it is permanent (nothing recomputes the counter), so the course would +/// be full forever. Stored state is the only witness: the embedded engine can +/// tell two racers they both won, so the HTTP statuses prove nothing. +// +// ponytail: `ENROLL_LOCK` serializes the enrolls inside one process, so what +// this actually drives is the already-enrolled early return; the `CREATE`-loser +// release only runs when the two racers sit on different replicas. Both paths +// are pinned by the same assertion below (counter == roster), which is the part +// that matters. +#[tokio::test] +async fn concurrent_enrolls_of_one_pair_claim_one_seat() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let alice = login(&app, "alice").await; + let alice_id = me_id(&app, &alice).await; + let res = send( + &app, + "POST", + "/courses", + Some(&teacher), + Some(json!({ "title": "seats", "description": "", "capacity": 2 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let course = id_of(&res.body); + let uri = format!("/courses/{course}/enrollments"); + + let mut handles = Vec::new(); + for _ in 0..16 { + let (app, teacher, uri) = (app.clone(), teacher.clone(), uri.clone()); + let body = json!({ "user_id": alice_id }); + handles.push(tokio::spawn(async move { + send(&app, "POST", &uri, Some(&teacher), Some(body)) + .await + .status + })); + } + for handle in handles { + let status = handle.await.unwrap(); + assert_eq!(status, StatusCode::OK, "a same-pair enroll is idempotent"); + } + + let roster = send(&app, "GET", &uri, Some(&teacher), None).await; + assert_eq!(common::total(&roster.body), 1, "one pair, one row"); + let mut counted = db + .query("SELECT VALUE enrollment_count FROM type::record('course', $c)") + .bind(("c", course.clone())) + .await + .expect("counter read") + .check() + .expect("counter read"); + assert_eq!( + counted.take::>(0).expect("counter column"), + vec![1], + "one row on the roster must have cost exactly one seat" + ); +} + /// The signup list freezes the moment the event starts — both directions. /// (The create-time no-past grace lets a just-started event exist, which is /// exactly a closed list.) @@ -8589,9 +8710,10 @@ async fn questions_and_answers_cascade_with_deletes() { } let exam_id = ExamId::from_key(&exam); assert_eq!( - ExamQuestion::list_for_exam(&exam_id, &db) + ExamQuestion::list_for_exam(&exam_id, None, 0, &db) .await .unwrap() + .0 .len(), 2 ); @@ -8603,20 +8725,40 @@ async fn questions_and_answers_cascade_with_deletes() { 2 ); - // Deleting one question takes its answers with it — the API freezes - // question deletes once attempts exist, so exercise the domain cascade - // directly (it also runs under the exam/course cascades below). - let question = ExamQuestion::list_for_exam(&exam_id, &db) + // Deleting one question takes its answers with it. The freeze gate now + // lives inside `ExamQuestion::delete`'s own transaction (not in a lock the + // handler held), so the attempt has to go first for the cascade to be + // exercised at all — that refusal is asserted here before it is cleared. + let frozen = ExamQuestion::list_for_exam(&exam_id, None, 0, &db) .await .unwrap() + .0 + .into_iter() + .next() + .unwrap(); + assert!( + matches!(frozen.delete(&db).await, Err(err) if err.to_string().contains("after attempts")), + "the gate must refuse a question delete while an attempt exists" + ); + db.query("DELETE exam_attempt WHERE exam = $ex") + .bind(("ex", exam_id.record())) + .await + .unwrap() + .check() + .unwrap(); + let question = ExamQuestion::list_for_exam(&exam_id, None, 0, &db) + .await + .unwrap() + .0 .into_iter() .next() .unwrap(); question.delete(&db).await.unwrap(); assert_eq!( - ExamQuestion::list_for_exam(&exam_id, &db) + ExamQuestion::list_for_exam(&exam_id, None, 0, &db) .await .unwrap() + .0 .len(), 1 ); @@ -8640,9 +8782,10 @@ async fn questions_and_answers_cascade_with_deletes() { .await; assert_eq!(res.status, StatusCode::NO_CONTENT); assert!( - ExamQuestion::list_for_exam(&exam_id, &db) + ExamQuestion::list_for_exam(&exam_id, None, 0, &db) .await .unwrap() + .0 .is_empty() ); assert!( @@ -8703,9 +8846,10 @@ async fn questions_and_answers_cascade_with_deletes() { assert_eq!(res.status, StatusCode::NO_CONTENT); let exam2_id = ExamId::from_key(&exam2); assert!( - ExamQuestion::list_for_exam(&exam2_id, &db) + ExamQuestion::list_for_exam(&exam2_id, None, 0, &db) .await .unwrap() + .0 .is_empty() ); assert!( @@ -14222,6 +14366,84 @@ async fn homework_grading_gates_and_bounds() { } /// A stored grade freezes the submission — text, files, withdrawal — until +/// The files-per-submission cap is the same counter guard as the note-file one, +/// on the submission row. Nine seeded files plus four racers for the last slot: +/// exactly one may win, and the delete must give the slot back or the next +/// upload is refused forever. +#[tokio::test] +async fn concurrent_homework_uploads_never_exceed_the_file_cap() { + let (app, db) = app_and_db().await; + let w = hw_world(&app, &db).await; + let now = Timestamp::now().as_millis(); + let hw = create_homework( + &app, + &w.teacher, + &w.course, + &w.subject, + "essay", + now + 3_600_000, + ) + .await; + let res = submit_hw(&app, &w.ali, &hw, Some("v1")).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + for i in 0..9 { + let up = upload_hw_file(&app, &w.ali, &hw, &format!("f{i}.txt"), "text/plain", b"x").await; + assert_eq!(up.status, StatusCode::CREATED, "seed file {i}: {}", up.body); + } + + let racers = tokio::join!( + upload_hw_file(&app, &w.ali, &hw, "r0.txt", "text/plain", b"x"), + upload_hw_file(&app, &w.ali, &hw, "r1.txt", "text/plain", b"x"), + upload_hw_file(&app, &w.ali, &hw, "r2.txt", "text/plain", b"x"), + upload_hw_file(&app, &w.ali, &hw, "r3.txt", "text/plain", b"x"), + ); + let statuses = [ + racers.0.status, + racers.1.status, + racers.2.status, + racers.3.status, + ]; + for status in statuses { + assert!( + status == StatusCode::CREATED || status == StatusCode::CONFLICT, + "a lost cap race must be a 409, got {status}" + ); + } + let list = send( + &app, + "GET", + &format!("/homework/{hw}/submission"), + Some(&w.ali), + None, + ) + .await; + let files = list.body["files"].as_array().expect("files").clone(); + assert_eq!( + files.len(), + 10, + "the cap must hold exactly under concurrency, statuses={statuses:?}" + ); + + // A deleted file frees its slot again — the counter is not a ratchet. + let fid = files[0]["id"].as_str().expect("file id").to_string(); + let res = send( + &app, + "DELETE", + &format!("/homework/{hw}/submission/files/{fid}"), + Some(&w.ali), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + let up = upload_hw_file(&app, &w.ali, &hw, "after.txt", "text/plain", b"x").await; + assert_eq!( + up.status, + StatusCode::CREATED, + "the freed slot must be reusable: {}", + up.body + ); +} + /// the teacher removes it; and work never handed in can be graded `missing`, /// a verdict the student reads from `/result` despite having no submission. #[tokio::test] @@ -19311,7 +19533,7 @@ async fn a_bank_patch_does_not_clobber_a_concurrent_write() { // The stale struct writes its own fields only. let updated = stale - .update( + .update_if_unchanged( None, QuestionText::try_new("edited").unwrap(), QuestionPoints::try_new(7).unwrap(), @@ -19320,7 +19542,8 @@ async fn a_bank_patch_does_not_clobber_a_concurrent_write() { &db, ) .await - .expect("update written"); + .expect("update ran") + .expect("update written — the exam delete touched no compared column"); assert_eq!(updated.get_text().as_str(), "edited"); assert!( updated.get_source_exam().is_none(), @@ -20783,7 +21006,9 @@ async fn concurrent_ledger_appends_of_one_id_write_one_line_not_a_500() { "the loser must read back the winner's line, not fail: {second:?}" ); - let lines = MealLedger::list_for_student(&student, &db).await.unwrap(); + let (lines, _) = MealLedger::list_for_student(&student, None, 0, &db) + .await + .unwrap(); assert_eq!(lines.len(), 2, "one charge and exactly one reversal"); assert_eq!( MealLedger::balance_of(&student, &db).await.unwrap(), diff --git a/tests/limits_completeness.rs b/tests/limits_completeness.rs index 9ba4ff5..c208620 100644 --- a/tests/limits_completeness.rs +++ b/tests/limits_completeness.rs @@ -36,9 +36,14 @@ const EXCLUDED: &[(&str, &str)] = &[ "DB_CONNECT_BACKOFF_MAX_SECS", "boot reconnect backoff ceiling", ), + ("CAS_UPDATE_RETRIES", "internal compare-and-set retry count"), ( - "SETTINGS_UPDATE_RETRIES", - "internal compare-and-set retry count", + "CAP_WRITE_TRIES", + "internal retry count for a contended cap counter", + ), + ( + "CAP_WRITE_BACKOFF_MS", + "internal backoff between cap counter retries", ), ( "UPLOAD_BODY_OVERHEAD_BYTES", @@ -114,9 +119,6 @@ const EXCLUDED: &[(&str, &str)] = &[ "DEFAULT_DIETARY_TAGS", "settings seed; the live list is on GET /settings", ), - // Schema and query text. `constant.rs` is the single home for every - // constant, so the migration batches live there too — a client never sees - // a byte of SurrealQL. // The boot leader election. A client never sees the lock, and the timings // are startup mechanics between processes — publishing them would invite a // frontend to reason about a boot it cannot observe. @@ -136,13 +138,9 @@ const EXCLUDED: &[(&str, &str)] = &[ "how long a non-leader waits for the boot migration", ), ("MIGRATION_LOCK_POLL_MS", "boot lock poll cadence"), - ( - "MIGRATION_BATCHES", - "the batch list the boot executes and fingerprints", - ), - ("PRE_REPAIR", "pre-DDL data repair batch"), - ("MIGRATION", "SCHEMAFULL DDL batch"), - ("BACKFILL", "post-DDL data backfill batch"), + // The three migration batches and their list moved to + // `src/migration_sql.rs` — they are SurrealQL text, not bounds, and the + // numeric sweep below still catches any bound that tries to follow them. ("USAGE_COUNTS_SQL", "one-statement bank usage-count query"), // Storage-side keys and literals. Each names a row, a column value or a // fold rule the server writes; none is a number a client is held to. @@ -188,6 +186,18 @@ const EXCLUDED: &[(&str, &str)] = &[ "ETag middleware's own buffering ceiling", ), ("PURGE_AT", "rate-limiter bucket eviction threshold"), + // How the tiers are kept fleet-wide. A client is held to the tier itself + // (published live in /limits `rate`), never to the cadence the replicas + // reconcile it at — publishing that would invite pacing against it. + ( + "RATE_SYNC_INTERVAL_SECS", + "how often a replica reconciles its counters", + ), + ("RATE_SYNC_TIMEOUT_SECS", "deadline on one sync round"), + ( + "RATE_SYNC_MAX_KEYS", + "client buckets one sync round carries", + ), ( "MAX_ERROR_CODE_LEN", "bounds a code the SERVER writes from an AI service's reply; no client sends it", @@ -196,11 +206,12 @@ const EXCLUDED: &[(&str, &str)] = &[ ("MIN_CHUNK_CHARS", "how the SSE stream slices an answer"), ]; -/// A `*_TABLE` constant is a SurrealDB table name, not a bound. Listing all 37 -/// by hand would bury the deliberate exclusions above in boilerplate, so the -/// whole shape is excused once — the naming convention *is* the decision. +/// A `*_TABLE` constant is a SurrealDB table name and a `*_FIELD` one a column +/// name, not a bound. Listing all 37 by hand would bury the deliberate +/// exclusions above in boilerplate, so the whole shape is excused once — the +/// naming convention *is* the decision. fn is_storage_identifier(name: &str) -> bool { - name.ends_with("_TABLE") + (name.ends_with("_TABLE") || name.ends_with("_FIELD")) && !["MAX_", "MIN_", "DEFAULT_"] .iter() .any(|prefix| name.starts_with(prefix)) diff --git a/tests/partial_patch_sessions.rs b/tests/partial_patch_sessions.rs index 1d3dc3a..b99ec70 100644 --- a/tests/partial_patch_sessions.rs +++ b/tests/partial_patch_sessions.rs @@ -1,7 +1,8 @@ //! Two concurrent partial PATCHes on the same session must not revert each //! other, and — since only the fields a request carried are written — the //! `starts_at`/`ends_at` pair must not be invertible by two one-ended PATCHes -//! either (that is what `SESSION_LOCK` is for). +//! either (that is what `FieldUpdate::ordered`'s in-statement range guard is +//! for). mod common; diff --git a/tests/persistence.rs b/tests/persistence.rs index 5c7dc15..9fec108 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -952,9 +952,10 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() { assert_eq!(reply.get_content().as_str(), "aleykum selam"); assert!(reply.get_completed_at().is_some()); assert_eq!( - ChatbotMessage::list_for_thread(&id, &db) + ChatbotMessage::list_for_thread(&id, None, 0, &db) .await .expect("thread") + .0 .len(), 2 ); @@ -993,9 +994,10 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() { .is_none() ); assert_eq!( - ChatbotThread::list_for_user(&owner, &db) + ChatbotThread::list_for_user(&owner, None, 0, &db) .await .unwrap() + .0 .len(), 0 ); @@ -1177,3 +1179,88 @@ async fn settings_slots_without_a_serving_minute_still_patch() { res.body ); } + +/// Rows written before the cap counters existed (2026-07-27) carry no counter +/// at all, and an absent counter reads as zero — which would hand a full course +/// and a full note a clean slate. The backfill seeds each parent from the +/// children it actually has, so the caps keep holding across the upgrade. +#[tokio::test] +async fn cap_counters_are_seeded_from_the_rows_that_predate_them() { + let (app, db) = common::app_and_db().await; + let teacher = common::login_as(&app, &db, "teacher", "teacher").await; + let ali = common::login(&app, "ali").await; + let veli = common::login(&app, "veli").await; + let ayse = common::login(&app, "ayse").await; + let (ali_id, veli_id, ayse_id) = ( + me_id(&app, &ali).await, + me_id(&app, &veli).await, + me_id(&app, &ayse).await, + ); + + let res = send( + &app, + "POST", + "/courses", + Some(&teacher), + Some(json!({ "title": "small", "description": "", "capacity": 2 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let course = common::id_of(&res.body); + enroll(&app, &teacher, &course, &ali_id).await; + enroll(&app, &teacher, &course, &veli_id).await; + + let res = send( + &app, + "POST", + "/notes", + Some(&ali), + Some(json!({ "title": "full", "content": "x" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let note = common::id_of(&res.body); + for i in 0..10 { + let up = common::upload_file(&app, &ali, ¬e, &format!("f{i}.txt"), "", b"x").await; + assert_eq!(up.status, StatusCode::CREATED, "seed file {i}"); + } + + // Age both parents into the pre-counter shape. + db.query("UPDATE course UNSET enrollment_count; UPDATE note UNSET file_count;") + .await + .expect("age the rows") + .check() + .expect("age the rows"); + + let app = reboot(&db).await; + + let mut counters = db + .query("SELECT VALUE enrollment_count FROM course; SELECT VALUE file_count FROM note;") + .await + .expect("read counters") + .check() + .expect("read counters"); + assert_eq!( + counters.take::>(0).expect("enrollment_count"), + vec![2], + "the course counter must be seeded from its roster" + ); + assert_eq!( + counters.take::>(1).expect("file_count"), + vec![10], + "the note counter must be seeded from its files" + ); + + // And the caps still bite, which a zeroed counter would not have done. + let res = send( + &app, + "POST", + &format!("/courses/{course}/enrollments"), + Some(&teacher), + Some(json!({ "user_id": ayse_id })), + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + let up = common::upload_file(&app, &ali, ¬e, "eleventh.txt", "", b"x").await; + assert_eq!(up.status, StatusCode::CONFLICT, "{}", up.body); +} diff --git a/tests/rate_limit.rs b/tests/rate_limit.rs index 8e24a5e..6e2c3ee 100644 --- a/tests/rate_limit.rs +++ b/tests/rate_limit.rs @@ -310,6 +310,146 @@ async fn concurrent_bursts_never_over_admit() { assert_eq!((ok, limited), (5, 15)); } +// --- shared across replicas -------------------------------------------- +// +// Two `UserRateLimiter`s over one database stand in for two replicas: they are +// separate processes' worth of in-memory buckets, sharing only the `rate_limit` +// table. Time is paused, so a round of the sync task is driven by advancing +// past `RATE_SYNC_INTERVAL_SECS` — and because the task blocks on the database +// (not on time) mid-round, the short sleep afterwards cannot resolve until the +// round has finished. Assertions are on admissions, never on which replica won +// a race: the embedded engine can drop one of two concurrent writes and still +// answer `Ok`. + +use hezarfen_backend::constant::RATE_SYNC_INTERVAL_SECS; +use hezarfen_backend::database::Database; +use hezarfen_backend::rate_limit::UserRateLimiter; +use hezarfen_backend::state::DbHealth; +use std::time::Duration; + +/// A migrated in-memory database, with the clock frozen only afterwards: the +/// embedded engine has internal deadlines of its own and cannot start up under +/// a paused clock ("Insert node failed after 5 attempts due to timeout"). +async fn shared_db() -> Database { + let db = database::init_mem().await.expect("in-memory db"); + tokio::time::pause(); + db +} + +/// Let the sync task run one round: fire its timer, then hand it *real* time +/// to finish in. The real time is not optional — a round waits on the database, +/// and a paused clock auto-advances straight past a virtual sleep while it +/// does, so the assertions would race the round they are about. +async fn sync_round() { + // Let a freshly spawned task reach its `sleep` first: `advance` moves the + // clock *before* it yields, so a timer registered after it is registered + // against the new now and would sit out the whole round. + tokio::task::yield_now().await; + tokio::time::advance(Duration::from_secs(RATE_SYNC_INTERVAL_SECS)).await; + tokio::time::resume(); + tokio::time::sleep(Duration::from_millis(250)).await; + tokio::time::pause(); +} + +/// Two "replicas" of one tier, sharing `db`. +fn two_replicas(max: u32, db: &Database) -> (UserRateLimiter, UserRateLimiter, DbHealth) { + let health = DbHealth::default(); + let (a, b) = ( + UserRateLimiter::per_user_minute(max), + UserRateLimiter::per_user_minute(max), + ); + a.share("test", db.clone(), health.clone()); + b.share("test", db.clone(), health.clone()); + (a, b, health) +} + +/// How many of `tries` requests a limiter admits for `user`. +fn admits(limiter: &UserRateLimiter, user: &str, tries: usize) -> usize { + (0..tries) + .filter(|_| limiter.enforce_user(user).is_ok()) + .count() +} + +#[tokio::test] +async fn two_replicas_share_one_budget() { + let db = shared_db().await; + let (a, b, _health) = two_replicas(6, &db); + + // Both replicas spend freely until their first sync — the accepted + // one-interval overshoot, and the whole reason the fleet needs the shared + // row at all. + let spent = admits(&a, "user:a", 6) + admits(&b, "user:a", 6); + assert_eq!(spent, 12, "each replica starts on its own local budget"); + + // From the first sync on, the fleet total is what binds: neither replica + // admits anything more in this window, whatever the interleaving was. + sync_round().await; + assert_eq!( + admits(&a, "user:a", 6) + admits(&b, "user:a", 6), + 0, + "the shared budget is spent" + ); + + // And the shared row agrees with what was actually admitted. + let mut rows = db + .query("SELECT VALUE hits FROM rate_limit") + .await + .expect("read shared counters"); + assert_eq!(rows.take::>(0).unwrap(), vec![spent as i64]); +} + +#[tokio::test] +async fn a_replica_that_never_admitted_still_learns_the_budget_is_gone() { + let db = shared_db().await; + let (a, b, _health) = two_replicas(4, &db); + + // b spends one request, so it has a bucket to sync; a spends the rest. + assert_eq!(admits(&b, "user:a", 1), 1); + assert_eq!(admits(&a, "user:a", 3), 3); + sync_round().await; + + assert_eq!( + admits(&b, "user:a", 3), + 0, + "the fleet total, not b's own count, is the cap" + ); + // Other users are untouched by a spent bucket. + assert_eq!(admits(&b, "user:b", 4), 4); +} + +#[tokio::test] +async fn a_down_database_leaves_each_replica_on_its_local_budget() { + let db = shared_db().await; + let (a, b, health) = two_replicas(3, &db); + health.set(false); + + // Nothing is shared while the database is down — and nothing stalls: both + // replicas keep serving their own budgets at full speed. + for _ in 0..3 { + sync_round().await; + assert_eq!(admits(&a, "user:a", 1), 1); + assert_eq!(admits(&b, "user:a", 1), 1); + } + assert_eq!(admits(&a, "user:a", 1), 0, "the local budget still binds"); + assert_eq!(admits(&b, "user:a", 1), 0); + + // Nothing was written, so the row the sync would have made does not exist. + let mut rows = db + .query("SELECT VALUE hits FROM rate_limit") + .await + .expect("read shared counters"); + assert_eq!(rows.take::>(0).unwrap(), Vec::::new()); + + // Recovery needs no restart: the next round shares again. + health.set(true); + sync_round().await; + let mut rows = db + .query("SELECT VALUE hits FROM rate_limit") + .await + .expect("read shared counters"); + assert_eq!(rows.take::>(0).unwrap(), vec![6]); +} + /// Boot the app on a real TCP port, `ConnectInfo` wired exactly like `main`. async fn spawn_server(rate_limit: RateLimitConfig) -> String { let db = database::init_mem().await.expect("in-memory db"); diff --git a/tests/spec_bounds.rs b/tests/spec_bounds.rs index 5396630..395298f 100644 --- a/tests/spec_bounds.rs +++ b/tests/spec_bounds.rs @@ -780,26 +780,35 @@ fn expectations_cover_every_annotation() { ]; let mut annotated = 0; - for entry in std::fs::read_dir(format!("{root}/src/web")).expect("read src/web") { - let path = entry.expect("dir entry").path(); - if path.extension().is_none_or(|ext| ext != "rs") { - continue; - } - let source = std::fs::read_to_string(&path).expect("read source"); - // Scan whole attributes, not lines: rustfmt wraps a long - // `#[schema(example = "…", max_length = 5_000)]` across several lines, - // and a line-based count silently misses the wrapped keyword. - // - // `#[param(...)]` bounds are query parameters, covered by - // `every_page_limit_param_matches_its_constant` instead. - for (at, _) in source.match_indices("#[schema(") { - let rest = &source[at..]; - let end = rest.find(")]").map_or(rest.len(), |end| end + 2); - let attribute = &rest[..end]; - annotated += keywords - .iter() - .filter(|kw| attribute.contains(&format!("{kw} = "))) - .count(); + // Walk sub-directories too: a resource split into `web//` (exams) keeps + // its annotations, and a flat read_dir would silently stop counting them. + let mut dirs = vec![format!("{root}/src/web")]; + while let Some(dir) = dirs.pop() { + for entry in std::fs::read_dir(&dir).expect("read src/web") { + let path = entry.expect("dir entry").path(); + if path.is_dir() { + dirs.push(path.to_string_lossy().into_owned()); + continue; + } + if path.extension().is_none_or(|ext| ext != "rs") { + continue; + } + let source = std::fs::read_to_string(&path).expect("read source"); + // Scan whole attributes, not lines: rustfmt wraps a long + // `#[schema(example = "…", max_length = 5_000)]` across several lines, + // and a line-based count silently misses the wrapped keyword. + // + // `#[param(...)]` bounds are query parameters, covered by + // `every_page_limit_param_matches_its_constant` instead. + for (at, _) in source.match_indices("#[schema(") { + let rest = &source[at..]; + let end = rest.find(")]").map_or(rest.len(), |end| end + 2); + let attribute = &rest[..end]; + annotated += keywords + .iter() + .filter(|kw| attribute.contains(&format!("{kw} = "))) + .count(); + } } } @@ -812,3 +821,45 @@ fn expectations_cover_every_annotation() { expectations().len() ); } + +/// The three image-meta bodies — exam question images, bank template images, +/// and pool question/solution photos — are hand-kept copies of one shape, +/// `{content_type, size}`. The write half behind them is shared +/// (`src/web/image.rs`), but the DTOs stay three types because their *names* +/// are the published contract, so nothing but this comparison of the emitted +/// JSON stops one of them from quietly growing a field the others lack. +#[tokio::test] +async fn the_image_meta_bodies_stay_the_same_shape() { + let spec = spec().await; + let schemas = &spec["components"]["schemas"]; + + // Field names with their JSON type, prose (description/example) stripped — + // the wording is allowed to differ per system, the shape is not. + let shape = |name: &str| -> Vec { + let properties = schemas[name]["properties"] + .as_object() + .unwrap_or_else(|| panic!("{name} is not an object schema — was it renamed?")); + let mut fields: Vec = properties + .iter() + .map(|(field, spec)| format!("{field}: {}/{}", spec["type"], spec["format"])) + .collect(); + fields.sort(); + let mut required: Vec = schemas[name]["required"] + .as_array() + .map(|items| items.iter().map(|item| item.to_string()).collect()) + .unwrap_or_default(); + required.sort(); + fields.push(format!("required: {required:?}")); + fields + }; + + let want = shape("ImageMetaResponse"); + for other in ["BankImageMeta", "PoolImageMeta"] { + assert_eq!( + want, + shape(other), + "{other} has drifted from ImageMetaResponse — the image-meta bodies are \ + copies of one shape and must be changed together" + ); + } +}