From d8fdbf0513a6b37ad98d8df259b42620e3d48e4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 19 Jul 2026 17:39:06 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(exams):=20draft=20exams=20hidd?= =?UTF-8?q?en=20until=20published?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Exam prep is long work: draft: true keeps an exam private to its course's managers while it's written. Students get 404s (not 403/409 — existence must not leak) on get/attempt/ws and filtered lists; sitting and grading are blocked. Publish via PATCH draft: false; re-drafting is 409 once attempts or results exist. grade now holds an EXAM_LOCK read lease so a mark can't race a re-draft. Modeless exams renamed offline-graded/unscheduled everywhere — "draft" now means only this. Old rows backfill published at boot. --- README.md | 48 ++++++++----- src/database.rs | 5 ++ src/domain/exam.rs | 16 ++++- src/domain/exam_attempt.rs | 1 + src/lib.rs | 2 +- src/web/courses.rs | 22 ++++-- src/web/dto.rs | 8 ++- src/web/exam_ws.rs | 16 ++--- src/web/exams.rs | 112 ++++++++++++++++++++++------- tests/integration.rs | 141 +++++++++++++++++++++++++++++++++++++ tests/persistence.rs | 82 +++++++++++++++++++++ 11 files changed, 392 insertions(+), 61 deletions(-) diff --git a/README.md b/README.md index b1ed3c4..0971db7 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,9 @@ fixed window), **async** (start anytime inside the window, with a personal time budget), or **open** (sit anytime, optionally timed per attempt); students *sit* them via attempts — retakes metered by a per-exam limit (`0` = unlimited), leaving the exam room governed by a teacher-controlled -rejoin door. Questions can carry **images**: any question may hold one +rejoin door. Writing an exam takes a while, so it can be saved as a +**draft** — invisible to students, unsittable, ungradable — and published +when it's ready. Questions can carry **images**: any question may hold one illustration (a map above the prompt), and each option of a choice question may be a picture of its own (pick the right city off the map) — raster uploads capped by the same `max_file_bytes` policy as note files. Teachers @@ -203,7 +205,7 @@ effect on the user's very next call (no re-login). | View **any** user's pomodoro log | teacher | Study oversight — same shape as `/pomodoro/me`, incl. the unpaged `total_focus_ms` | | Read **own** attendance report | student | | | Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all | -| View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created; `manager`+: all) | +| View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created; `manager`+: all); exam **drafts** show only to the course's managers | | Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | **Students only** — staff never sit; must be enrolled; window (where one exists) and `max_attempts` enforced by the server | | Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off | | Author an exam's questions (add/edit/delete, incl. question + option images) | teacher | Course-management rights; frozen once anyone has an attempt | @@ -344,13 +346,13 @@ their existing shapes: the student exam-room reads | POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` — roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ | | GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) · paged | | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) | -| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?}` — add an exam (course manager); its weight comes from the kind | -| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, or manager+) · paged | -| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all) · paged | -| GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+) | -| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin` (course manager; `course` immutable, `mode` frozen once attempted — the rest stays live) | +| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, draft?}` — add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written | +| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, 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 | +| 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`, `draft` (course manager; `course` immutable, `mode` frozen once attempted, re-drafting frozen once attempts/results exist — the rest stays live) | | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question images (course manager) | -| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled student** (upsert; course manager; students only) | +| 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 | | GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) | | DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) | @@ -535,10 +537,21 @@ keeps every school's data physically isolated. ## Exam modes, attempts, retakes, rejoin & live monitoring -An exam is a **draft** by default (all schedule fields `null`) — graded -offline; attempts on it are a `409` ("nothing to sit"). Making it sittable -means giving it a `mode`, as one consistent unit (validated together on -create and after every `PATCH` merge): +Preparing an exam is slow work, so an exam can be created as a **draft** +(`draft: true`): only the course's managers see it (to students it's a `404` +that might as well not exist — lists, direct reads, and attempts all hide +it), nobody can sit it, and grading it is a `409`. The teacher builds the +questions in peace and publishes with `PATCH /exams/{id}` `{"draft": false}`. +An exam can go back into hiding the same way — but only while it has **no +attempts and no results**; after that, re-drafting is a `409` (students never +lose sight of an exam they've sat or been graded on). Existing exams (and +those created without the flag) are published from the start. + +Separately from drafts, a published exam without a `mode` (all schedule +fields `null`) is **offline-graded** — a paper exam whose marks are entered +by hand; students see it and their marks, but attempts on it are a `409` +("nothing to sit"). Making an exam sittable means giving it a `mode`, as one +consistent unit (validated together on create and after every `PATCH` merge): - `mode: "sync"` + `starts_at` + `ends_at` — everyone sits inside one window; every attempt's deadline is `ends_at`. @@ -587,8 +600,8 @@ construction): Deadlines are **recomputed from the exam's current schedule on every read**, never stored: a teacher who `PATCH`es `ends_at` (or a `duration_ms`) while the exam runs moves every running deadline instantly. What's frozen once -anyone has started is only `mode` (including back to a draft) — swapping the -deadline rules mid-sitting would be a different exam (`409`). +anyone has started is only `mode` (including back to unscheduled) — swapping +the deadline rules mid-sitting would be a different exam (`409`). The course's manager (its creator, or manager+) watches it all live: `GET /exams/{id}/live` returns one snapshot — @@ -707,9 +720,10 @@ suggestion to read while grading, never written anywhere. **The exam room (WebSocket)** — `GET /exams/{id}/attempt/ws`, cookie-authed like everything else; REST above remains the full fallback. Gates run before -the upgrade: unknown exam `404`, draft with no mode `409`, not a student `403`, -not enrolled `403`, no attempt yet `404` (start it first), submitted/expired -`409`, left while rejoin is closed `409`. Then JSON text frames: +the upgrade: unknown or draft exam `404`, unscheduled (no mode) `409`, not a +student `403`, not enrolled `403`, no attempt yet `404` (start it first), +submitted/expired `409`, left while rejoin is closed `409`. Then JSON text +frames: | direction | frame | |-----------|-------| diff --git a/src/database.rs b/src/database.rs index f58dbb5..d952f75 100644 --- a/src/database.rs +++ b/src/database.rs @@ -169,6 +169,7 @@ const MIGRATION: &str = " 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 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; @@ -240,6 +241,10 @@ const BACKFILL: &str = " UPDATE course SET kind = 'course' WHERE kind = 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; + UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {}; -- Questions written before subjects existed (2026-07-17) are destroyed, not diff --git a/src/domain/exam.rs b/src/domain/exam.rs index 20c75dd..ac2e5d7 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -159,7 +159,7 @@ impl ExamAttemptLimit { /// hand always satisfies: /// /// - no mode → no `starts_at`/`ends_at`/`duration_ms` (an offline-graded -/// draft; attempts are rejected), +/// exam; attempts are rejected), /// - `sync` → `starts_at` + `ends_at`, no duration (everyone's deadline is /// `ends_at`), /// - `async` → `starts_at` + `ends_at` + `duration_ms` (a student who starts @@ -258,6 +258,10 @@ pub struct Exam { // migration (limit 1, rejoin open), so reads never see them missing. max_attempts: ExamAttemptLimit, allow_rejoin: bool, + // Work-in-progress marker: a draft is visible only to its course's + // managers, cannot be sat, and cannot be graded. Rows predating the + // column are backfilled published (`false`). + draft: bool, } impl Exam { @@ -311,6 +315,12 @@ impl Exam { self.allow_rejoin } + /// Whether the exam is still being prepared — hidden from students, not + /// sittable, not gradable, until published. + pub fn is_draft(&self) -> bool { + self.draft + } + /// The stored schedule as the validated bundle (for merge-on-update). /// Bypasses `try_new`: the fields were written through an `ExamSchedule`, /// so the invariants already hold. @@ -340,6 +350,7 @@ impl Exam { schedule: ExamSchedule, max_attempts: ExamAttemptLimit, allow_rejoin: bool, + draft: bool, db: &Database, ) -> Result { let exam = Exam { @@ -355,6 +366,7 @@ impl Exam { duration_ms: schedule.duration_ms, max_attempts, allow_rejoin, + draft, }; let created: Option = db.create(exam.id.record()).content(exam).await?; created.ok_or_else(|| AppError::Internal("failed to create exam".into())) @@ -413,6 +425,7 @@ impl Exam { schedule: ExamSchedule, max_attempts: ExamAttemptLimit, allow_rejoin: bool, + draft: bool, db: &Database, ) -> Result { self.title = title; @@ -424,6 +437,7 @@ impl Exam { self.duration_ms = schedule.duration_ms; self.max_attempts = max_attempts; self.allow_rejoin = allow_rejoin; + self.draft = draft; let updated: Option = db.update(self.id.record()).content(self).await?; updated.ok_or(AppError::NotFound) } diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs index ff8c393..7a0ce74 100644 --- a/src/domain/exam_attempt.rs +++ b/src/domain/exam_attempt.rs @@ -366,6 +366,7 @@ mod tests { .unwrap(), ExamAttemptLimit::try_new(max_attempts).unwrap(), true, + false, db, ) .await diff --git a/src/lib.rs b/src/lib.rs index f41443d..0f830e4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -46,7 +46,7 @@ use crate::state::AppState; (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"), (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"), - (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. A modeless exam is an offline-graded draft — attempts on it are a 409. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"), + (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"), (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings)"), (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). Read: any authenticated user; edit: manager+"), (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, manager+); edit follows course management rights"), diff --git a/src/web/courses.rs b/src/web/courses.rs index 55bfb1d..f10d635 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -91,7 +91,7 @@ struct CreateExamInCourse { kind: String, /// `sync` (one fixed window for everyone), `async` (each student starts /// inside the window and gets `duration_ms`), or `open` (no window — sit - /// anytime). Omit for an offline-graded draft that cannot be sat. + /// anytime). Omit for an offline-graded exam that cannot be sat. #[schema(example = "sync")] mode: Option, /// Window open, UTC unix-milliseconds. Required for `sync`/`async`, @@ -112,6 +112,10 @@ struct CreateExamInCourse { /// Whether a student who left the exam room may come back in and keep /// answering. Defaults to `true`; editable live while the exam runs. allow_rejoin: Option, + /// Save as a work-in-progress draft: visible only to the course's + /// managers, not sittable, not gradable, until published via + /// `PATCH /exams/{id}` with `draft: false`. Defaults to `false`. + draft: Option, } #[derive(Serialize, ToSchema)] @@ -555,12 +559,14 @@ async fn unenroll( /// Create an exam inside a course. Requires teacher+ and course management /// rights; the exam's marks count into the course average with its kind's -/// weight (`GET /settings`). Omit `mode` for an offline-graded draft nobody +/// weight (`GET /settings`). Omit `mode` for an offline-graded exam nobody /// can sit; `sync`/`async` take a window (async also `duration_ms`), `open` /// is sittable anytime with an optional per-attempt `duration_ms`. /// `max_attempts` (default 1, `0` = unlimited) meters retakes and /// `allow_rejoin` (default `true`) is the exam-room door — both stay editable -/// while the exam runs. +/// while the exam runs. Send `draft: true` to keep the exam private while +/// it's still being written: only the course's managers see it, and sitting +/// and grading are blocked until it's published (`PATCH` `draft: false`). #[utoipa::path( post, path = "/{id}/exams", @@ -618,6 +624,7 @@ async fn create_exam_in_course( schedule, max_attempts, req.allow_rejoin.unwrap_or(true), + req.draft.unwrap_or(false), &st.db, ) .await?; @@ -626,7 +633,8 @@ async fn create_exam_in_course( /// List a course's exams, paged via `?limit=&offset=` (omit `limit` for all of /// them). Visible to the course's enrolled users, its creator, and -/// managers/admins. Returns a `{items, total, limit, offset}` envelope. +/// managers/admins — but drafts appear only to the course's managers. +/// Returns a `{items, total, limit, offset}` envelope. #[utoipa::path( get, path = "/{id}/exams", @@ -657,7 +665,11 @@ async fn list_course_exams( "only enrolled users, the course creator, or a manager/admin can view this course", )); } - let exams = Exam::list_for_course(course.get_id(), &st.db).await?; + let mut exams = Exam::list_for_course(course.get_id(), &st.db).await?; + // Drafts are the managers' workbench — enrolled students don't see them. + if !can_manage_course(&course, &user) { + exams.retain(|exam| !exam.is_draft()); + } let total = exams.len() as i64; let items = paginate(&exams, limit, offset) .iter() diff --git a/src/web/dto.rs b/src/web/dto.rs index 33e02f4..6a701b3 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -239,7 +239,7 @@ impl SessionResponse { /// Public shape of an exam. Shared by `exams` (CRUD/results) and `courses` /// (in-course creation and listing). The schedule fields are all `null` for an -/// offline-graded draft (no mode); see the create/update endpoints for the +/// offline-graded exam (no mode); see the create/update endpoints for the /// rules tying them together. #[derive(Serialize, ToSchema)] pub struct ExamResponse { @@ -251,7 +251,7 @@ pub struct ExamResponse { /// The assessment form. Its weight in the course average is school policy: /// `GET /settings` maps each kind to a weight. pub kind: String, - /// `sync`, `async`, or `open`; `null` for an offline-graded draft + /// `sync`, `async`, or `open`; `null` for an offline-graded exam /// (not sittable). #[schema(example = "sync")] pub mode: Option, @@ -268,6 +268,9 @@ pub struct ExamResponse { /// Whether a student who left the exam room may come back in and keep /// answering. Teachers can flip this live. pub allow_rejoin: bool, + /// Still being prepared: visible only to the course's managers, not + /// sittable, not gradable. Publish by `PATCH`ing `draft: false`. + pub draft: bool, } impl ExamResponse { @@ -285,6 +288,7 @@ impl ExamResponse { duration_ms: exam.get_duration_ms().map(|d| d.as_millis()), max_attempts: exam.get_max_attempts().as_i64(), allow_rejoin: exam.get_allow_rejoin(), + draft: exam.is_draft(), } } } diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 1a65561..9346535 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -63,7 +63,8 @@ use crate::error::AppError; use crate::state::AppState; use crate::web::CurrentUser; use crate::web::exams::{ - EXAM_LOCK, check_rejoin, ensure_enrolled, ensure_student, save_answer_in, writable_attempt, + EXAM_LOCK, check_rejoin, ensure_enrolled, ensure_sittable, ensure_student, save_answer_in, + writable_attempt, }; /// Serializes every presence transition with its matching `left_at` write: @@ -98,9 +99,10 @@ enum ClientMessage { /// Upgrade into the caller's exam room. All gates run *before* the upgrade so /// a rejected client gets a proper HTTP status instead of an instant close: -/// unknown exam (404), draft with no mode (409), not a student (403), not -/// enrolled (403), no attempt yet (404 — `POST /exams/{id}/attempt` first), -/// submitted or expired (409), left the room while rejoin is closed (409). +/// unknown or draft exam (404), unscheduled with no mode (409), not a student +/// (403), not enrolled (403), no attempt yet (404 — `POST /exams/{id}/attempt` +/// first), submitted or expired (409), left the room while rejoin is closed +/// (409). /// /// The rejoin gate here is a read-only fast-fail for a proper 409; the /// authoritative clear of `left_at` happens inside the room task, under @@ -117,11 +119,7 @@ pub async fn attempt_ws( let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(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)", - )); - } + ensure_sittable(&exam)?; ensure_student(&user)?; ensure_enrolled(&exam, user.get_id(), &st.db).await?; let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; diff --git a/src/web/exams.rs b/src/web/exams.rs index 0fc1186..98419f4 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -50,13 +50,15 @@ use super::{ /// 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; saves 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 or question rows first — exam mode/schedule +/// 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, and a first attempt can never -/// slip between a freeze-gate read and the write it was meant to freeze. +/// 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(()); @@ -113,8 +115,8 @@ struct UpdateExam { /// 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 draft. Frozen once anyone has - /// started an attempt. Switching to `open` requires clearing + /// 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)] @@ -143,6 +145,10 @@ struct UpdateExam { /// 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, + /// `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)] @@ -201,7 +207,8 @@ async fn course_of(exam: &Exam, db: &Database) -> Result { // 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. Paged via +/// 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. #[utoipa::path( @@ -227,7 +234,16 @@ async fn list_exams( } else { let courses = visible_courses(&user, &st.db).await?; let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect(); - Exam::list_for_courses(&ids, &st.db).await? + // 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 total = exams.len() as i64; let items = paginate(&exams, limit, offset) @@ -238,7 +254,9 @@ async fn list_exams( } /// Fetch a single exam by id. Visible to its course's enrolled users, the -/// course creator, and managers/admins. +/// 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}", @@ -249,7 +267,7 @@ async fn list_exams( (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", body = ErrorResponse), + (status = 404, description = "Not found (or a draft the caller may not see)", body = ErrorResponse), ), )] async fn get_exam( @@ -266,6 +284,11 @@ async fn get_exam( "only enrolled users, the course creator, 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))) } @@ -276,6 +299,9 @@ async fn get_exam( /// `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}", @@ -289,7 +315,7 @@ async fn get_exam( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), - (status = 409, description = "Mode change after attempts started", 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( @@ -362,10 +388,11 @@ async fn update_exam( None => exam.get_max_attempts(), }; let allow_rejoin = req.allow_rejoin.unwrap_or_else(|| exam.get_allow_rejoin()); + let draft = req.draft.unwrap_or_else(|| exam.is_draft()); - // Switching sync <-> async <-> open (or back to a draft) would silently - // rewrite the deadline rules under students who already sat down; - // extending times, the attempt limit, and the rejoin door are the + // 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 one // 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. @@ -377,6 +404,20 @@ async fn update_exam( "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( @@ -386,6 +427,7 @@ async fn update_exam( schedule, max_attempts, allow_rejoin, + draft, &st.db, ) .await?; @@ -437,7 +479,8 @@ async fn delete_exam( /// 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. +/// 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", @@ -451,6 +494,7 @@ async fn delete_exam( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator (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( @@ -460,6 +504,11 @@ async fn grade( 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? @@ -470,6 +519,11 @@ async fn grade( "only the course creator 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); @@ -781,11 +835,16 @@ async fn attempt_progress( Ok((answered, question_count)) } -/// A 409 unless the exam can be sat at all: it needs a mode (`sync`, `async`, -/// or `open`) — a modeless exam is an offline-graded draft. Enrollment and -/// window checks for the caller are the caller's own state — hence `Conflict` -/// (a state problem), not validation. -fn ensure_sittable(exam: &Exam) -> Result<(), AppError> { +/// 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)", @@ -818,8 +877,8 @@ async fn attempts_used(exam: &ExamId, user: &UserId, db: &Database) -> Result