From ade4fedec165c7ed4be5d83d3956dfc1b438a56e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 12 Jul 2026 06:02:06 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(exams):=20scheduled=20attempts?= =?UTF-8?q?,=20live=20monitor,=20questions,=20answers,=20exam=20room?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - exam scheduling as one validated unit: mode sync|async + window (+ per-student duration_ms for async); unscheduled stays offline-graded - exam_attempt: one row per exam+user by composite id; start = attendance signal, finish = submission; status/deadline recomputed from the current schedule on every read (mode frozen once attempts exist, times extend live) - teacher live monitor: GET /exams/{id}/live snapshot + SSE /live/stream - exam_question: choice|text authored per exam, kind bundle (choices+correct) validated as a unit, frozen once attempts start, ULID order - exam_answer: upsert per question+user via composite id, kind-coherent, server-clock stamped; pure auto_score over choice questions as a grading suggestion — final mark stays human via /results - student exam room WebSocket at /exams/{id}/attempt/ws: state ticks, autosave acks, finish/expire lifecycle, gates rejected pre-upgrade with proper HTTP statuses; shares the REST write path - PersonRef embeds (id + username + display name) in people-bearing responses, plus teacher+ GET /users/search - cascades: exam/course deletes sweep attempts, questions, answers, results --- Cargo.lock | 190 +++++- Cargo.toml | 7 +- src/constant.rs | 34 + src/database.rs | 35 ++ src/domain/course.rs | 11 +- src/domain/exam.rs | 209 ++++++- src/domain/exam_answer.rs | 303 +++++++++ src/domain/exam_attempt.rs | 192 ++++++ src/domain/exam_question.rs | 381 +++++++++++ src/domain/mod.rs | 3 + src/domain/user.rs | 34 + src/lib.rs | 2 +- src/validate.rs | 90 ++- src/web/courses.rs | 61 +- src/web/dto.rs | 89 ++- src/web/events.rs | 49 +- src/web/exam_ws.rs | 315 ++++++++++ src/web/exams.rs | 1183 ++++++++++++++++++++++++++++++++++- src/web/mod.rs | 16 +- src/web/users.rs | 44 +- 20 files changed, 3156 insertions(+), 92 deletions(-) create mode 100644 src/domain/exam_answer.rs create mode 100644 src/domain/exam_attempt.rs create mode 100644 src/domain/exam_question.rs create mode 100644 src/web/exam_ws.rs diff --git a/Cargo.lock b/Cargo.lock index 23eef9f..f3f1404 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -266,6 +266,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ "axum-core", + "base64", "bytes", "form_urlencoded", "futures-util", @@ -284,8 +285,10 @@ dependencies = [ "serde_json", "serde_path_to_error", "serde_urlencoded", + "sha1 0.10.6", "sync_wrapper", "tokio", + "tokio-tungstenite 0.29.0", "tower", "tower-layer", "tower-service", @@ -409,7 +412,7 @@ version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" dependencies = [ - "digest", + "digest 0.10.7", ] [[package]] @@ -435,6 +438,15 @@ dependencies = [ "generic-array 0.14.7", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "blowfish" version = "0.9.1" @@ -577,6 +589,17 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +[[package]] +name = "chacha20" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "rand_core 0.10.1", +] + [[package]] name = "chrono" version = "0.4.45" @@ -624,7 +647,7 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "crypto-common", + "crypto-common 0.1.7", "inout", ] @@ -652,6 +675,12 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "constant_time_eq" version = "0.4.2" @@ -798,6 +827,15 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "cssparser" version = "0.37.0" @@ -818,7 +856,7 @@ dependencies = [ "cfg-if", "cpufeatures 0.2.17", "curve25519-dalek-derive", - "digest", + "digest 0.10.7", "fiat-crypto", "rustc_version", "subtle", @@ -862,7 +900,7 @@ version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ - "const-oid", + "const-oid 0.9.6", "pem-rfc7468", "zeroize", ] @@ -896,12 +934,23 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "const-oid", - "crypto-common", + "block-buffer 0.10.4", + "const-oid 0.9.6", + "crypto-common 0.1.7", "subtle", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.2", + "crypto-common 0.2.2", +] + [[package]] name = "diskann" version = "0.54.0" @@ -1034,7 +1083,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" dependencies = [ "der", - "digest", + "digest 0.10.7", "elliptic-curve", "rfc6979", "signature", @@ -1079,7 +1128,7 @@ checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" dependencies = [ "base16ct", "crypto-bigint", - "digest", + "digest 0.10.7", "ff", "generic-array 0.14.7", "group", @@ -1466,6 +1515,7 @@ dependencies = [ "cfg-if", "libc", "r-efi 6.0.0", + "rand_core 0.10.1", ] [[package]] @@ -1590,7 +1640,7 @@ dependencies = [ "http", "httpdate", "mime", - "sha1", + "sha1 0.10.6", ] [[package]] @@ -1665,6 +1715,7 @@ dependencies = [ "axum-extra", "chrono", "dotenvy", + "futures-util", "getrandom 0.3.4", "hex", "reqwest", @@ -1675,6 +1726,8 @@ dependencies = [ "thiserror", "time", "tokio", + "tokio-stream", + "tokio-tungstenite 0.30.0", "tower", "tower-http", "tracing", @@ -1700,7 +1753,7 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" dependencies = [ - "digest", + "digest 0.10.7", ] [[package]] @@ -1764,6 +1817,15 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" +[[package]] +name = "hybrid-array" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "818356c5132c1fede50f837ca96afbe78ff42413047f4abb886217845e1b6c8c" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.10.1" @@ -2244,7 +2306,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" dependencies = [ "cfg-if", - "digest", + "digest 0.10.7", ] [[package]] @@ -2577,7 +2639,7 @@ version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" dependencies = [ - "digest", + "digest 0.10.7", "hmac", "password-hash", "sha2", @@ -2928,6 +2990,17 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + [[package]] name = "rand_chacha" version = "0.3.1" @@ -2966,6 +3039,12 @@ dependencies = [ "getrandom 0.3.4", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + [[package]] name = "rand_distr" version = "0.5.1" @@ -3211,8 +3290,8 @@ version = "0.9.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" dependencies = [ - "const-oid", - "digest", + "const-oid 0.9.6", + "digest 0.10.7", "num-bigint-dig", "num-integer", "num-traits", @@ -3541,7 +3620,18 @@ checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", ] [[package]] @@ -3552,7 +3642,7 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", ] [[package]] @@ -3592,7 +3682,7 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ - "digest", + "digest 0.10.7", "rand_core 0.6.4", ] @@ -3867,7 +3957,7 @@ dependencies = [ "semver", "serde", "serde_json", - "sha1", + "sha1 0.10.6", "sha2", "storekey", "strsim", @@ -4238,7 +4328,31 @@ dependencies = [ "futures-util", "log", "tokio", - "tungstenite", + "tungstenite 0.28.0", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.29.0", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17a073bfed563fa236697a068031408a93cd9522e08abf9933ead3e73411bd71" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.30.0", ] [[package]] @@ -4255,7 +4369,7 @@ dependencies = [ "js-sys", "thiserror", "tokio", - "tokio-tungstenite", + "tokio-tungstenite 0.28.0", "wasm-bindgen", "web-sys", ] @@ -4485,11 +4599,43 @@ dependencies = [ "httparse", "log", "rand 0.9.4", - "sha1", + "sha1 0.10.6", "thiserror", "utf-8", ] +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.4", + "sha1 0.10.6", + "thiserror", +] + +[[package]] +name = "tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.10.2", + "sha1 0.11.0", + "thiserror", +] + [[package]] name = "twox-hash" version = "2.1.2" diff --git a/Cargo.toml b/Cargo.toml index 2295c25..5ad6ce1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,10 @@ disallowed_types = "deny" [dependencies] tokio = { version = "1", features = ["full"] } -axum = "0.8" +# IntervalStream for the live exam-monitor SSE tick. +tokio-stream = "0.1" +# "ws" backs the live exam room (WebSocket at /exams/{id}/attempt/ws). +axum = { version = "0.8", features = ["ws"] } axum-extra = { version = "0.10", features = ["cookie"] } tower-http = { version = "0.6", features = ["trace", "cors"] } surrealdb = { version = "3", default-features = false, features = ["kv-surrealkv", "kv-mem"] } @@ -38,3 +41,5 @@ tokio = { version = "1", features = ["full", "test-util"] } tower = { version = "0.5", features = ["util"] } reqwest = { version = "0.12", default-features = false, features = ["json", "cookies"] } tempfile = "3" +tokio-tungstenite = "0.30.0" +futures-util = "0.3.32" diff --git a/src/constant.rs b/src/constant.rs index 4b953d9..a487d8a 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -34,6 +34,40 @@ pub const ATTENDANCE_STATUSES: [&str; 4] = ["present", "absent", "late", "excuse /// the course average. pub const EXAM_KINDS: [&str; 6] = ["homework", "quiz", "midterm", "final", "project", "oral"]; +/// The only accepted exam modes. `sync`: everyone sits the exam inside one +/// fixed window. `async`: each student starts inside the window and gets their +/// own `duration_ms` slice of it. +pub const EXAM_MODES: [&str; 2] = ["sync", "async"]; + +/// Inclusive bounds for an async exam's per-student duration, milliseconds +/// (1 minute to 24 hours). +pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000; +pub const MAX_EXAM_DURATION_MS: i64 = 24 * 60 * 60 * 1000; + +/// Cadence of the live exam-monitor SSE stream (`GET /exams/{id}/live/stream`). +pub const EXAM_LIVE_STREAM_INTERVAL_SECS: u64 = 2; + +/// Cadence of the `state` ticks on the student exam-room WebSocket +/// (`GET /exams/{id}/attempt/ws`). +pub const EXAM_WS_TICK_SECS: u64 = 2; + +/// The only accepted question kinds. `choice`: pick one of the listed +/// choices, auto-scorable. `text`: free text, judged by the grader. +pub const QUESTION_KINDS: [&str; 2] = ["choice", "text"]; + +pub const MAX_QUESTION_TEXT_LEN: usize = 2_000; + +/// Inclusive bounds for a question's points (its share of the auto-score). +pub const MIN_QUESTION_POINTS: i64 = 1; +pub const MAX_QUESTION_POINTS: i64 = 100; + +/// Bounds for a choice question's option list and each option's text. +pub const MIN_QUESTION_CHOICES: usize = 2; +pub const MAX_QUESTION_CHOICES: usize = 10; +pub const MAX_CHOICE_TEXT_LEN: usize = 500; + +pub const MAX_ANSWER_TEXT_LEN: usize = 10_000; + /// Inclusive bounds for an exam mark. pub const MIN_MARK: i64 = 0; pub const MAX_MARK: i64 = 100; diff --git a/src/database.rs b/src/database.rs index 0b7e70f..86e77a0 100644 --- a/src/database.rs +++ b/src/database.rs @@ -15,6 +15,9 @@ pub const EVENT_TABLE: &str = "event"; pub const ATTENDANCE_TABLE: &str = "attendance"; pub const EXAM_TABLE: &str = "exam"; pub const EXAM_RESULT_TABLE: &str = "exam_result"; +pub const EXAM_ATTEMPT_TABLE: &str = "exam_attempt"; +pub const EXAM_QUESTION_TABLE: &str = "exam_question"; +pub const EXAM_ANSWER_TABLE: &str = "exam_answer"; pub const COURSE_TABLE: &str = "course"; pub const ENROLLMENT_TABLE: &str = "enrollment"; @@ -79,8 +82,40 @@ const MIGRATION: &str = " 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 weight ON exam TYPE int; + 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 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 started_at ON exam_attempt TYPE int; + DEFINE FIELD IF NOT EXISTS finished_at ON exam_attempt TYPE option; + DEFINE INDEX IF NOT EXISTS exam_attempt_exam_user ON exam_attempt FIELDS exam, user 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; + DEFINE FIELD IF NOT EXISTS choices ON exam_question TYPE option>; + DEFINE FIELD IF NOT EXISTS correct ON exam_question TYPE option; + DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam; + + 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; + DEFINE FIELD IF NOT EXISTS 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; + DEFINE INDEX IF NOT EXISTS exam_answer_question_user ON exam_answer FIELDS question, user 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 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; diff --git a/src/domain/course.rs b/src/domain/course.rs index 2123006..02214c2 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -145,14 +145,17 @@ impl Course { updated.ok_or(AppError::NotFound) } - /// Delete the course and cascade-remove everything inside it: results of - /// its exams, its enrollments, and the exams themselves. The children go in - /// one transaction so a crash can't leave an exam pointing at a deleted - /// course. + /// Delete the course and cascade-remove everything inside it: results and + /// attempts of its exams, its enrollments, and the exams themselves. The + /// children go in one transaction so a crash can't leave an exam pointing + /// at a deleted course. pub async fn delete(self, db: &Database) -> Result { db.query( "BEGIN TRANSACTION; DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); + DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); + DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); + DELETE exam_question WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); DELETE enrollment WHERE course = $course; DELETE exam WHERE course = $course; COMMIT TRANSACTION;", diff --git a/src/domain/exam.rs b/src/domain/exam.rs index 24112a4..a197e8c 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -4,9 +4,13 @@ use ulid::Ulid; use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN}; use crate::database::{Database, EXAM_TABLE}; use crate::domain::course::CourseId; +use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; -use crate::validate::{validate_exam_kind, validate_optional, validate_required, validate_weight}; +use crate::validate::{ + validate_exam_duration, validate_exam_kind, validate_exam_mode, validate_optional, + validate_required, validate_weight, +}; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ExamId(RecordId); @@ -93,6 +97,107 @@ impl ExamWeight { } } +/// A validated exam mode: `sync` (everyone sits inside one fixed window) or +/// `async` (each student starts inside the window and gets `duration_ms`). +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct ExamMode(String); + +impl ExamMode { + pub fn try_new(value: &str) -> Result { + validate_exam_mode(value)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// A validated per-student time budget for an `async` exam, milliseconds. +#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] +pub struct ExamDuration(i64); + +impl ExamDuration { + pub fn try_new(value: i64) -> Result { + validate_exam_duration(value)?; + Ok(Self(value)) + } + + pub fn as_millis(&self) -> i64 { + self.0 + } +} + +/// The scheduling fields of an exam, validated as a unit — they only make +/// sense together. `try_new` is the sole constructor, so an `ExamSchedule` in +/// hand always satisfies: +/// +/// - no mode → no `starts_at`/`ends_at`/`duration_ms` (an unscheduled exam is +/// graded offline; 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 +/// at `t` gets until `min(t + duration_ms, ends_at)`), +/// - `ends_at` strictly after `starts_at`. +#[derive(Debug, Clone, Default)] +pub struct ExamSchedule { + mode: Option, + starts_at: Option, + ends_at: Option, + duration_ms: Option, +} + +impl ExamSchedule { + pub fn try_new( + mode: Option, + starts_at: Option, + ends_at: Option, + duration_ms: Option, + ) -> Result { + let invalid = |field, reason| ValidationError::Invalid { field, reason }; + match &mode { + None => { + if starts_at.is_some() || ends_at.is_some() || duration_ms.is_some() { + return Err(invalid( + "mode", + "starts_at, ends_at, and duration_ms require a mode (sync or async)", + )); + } + } + Some(m) => { + if starts_at.is_none() { + return Err(invalid("starts_at", "required for a scheduled exam")); + } + if ends_at.is_none() { + return Err(invalid("ends_at", "required for a scheduled exam")); + } + if ends_at <= starts_at { + return Err(invalid("ends_at", "must be after starts_at")); + } + match (m.as_str(), duration_ms.is_some()) { + ("async", false) => { + return Err(invalid("duration_ms", "required for an async exam")); + } + ("sync", true) => { + return Err(invalid("duration_ms", "only async exams take a duration")); + } + _ => {} + } + } + } + Ok(Self { + mode, + starts_at, + ends_at, + duration_ms, + }) + } + + pub fn get_mode(&self) -> Option<&ExamMode> { + self.mode.as_ref() + } +} + #[derive(Debug, Clone, SurrealValue)] pub struct Exam { id: ExamId, @@ -102,6 +207,13 @@ pub struct Exam { description: ExamDescription, kind: ExamKind, weight: ExamWeight, + // The schedule, flattened into columns (SCHEMAFULL keeps them typed). + // Always written through an `ExamSchedule`, so the invariants above hold + // for every stored row; pre-schedule rows read back as all-`None`. + mode: Option, + starts_at: Option, + ends_at: Option, + duration_ms: Option, } impl Exam { @@ -133,10 +245,42 @@ impl Exam { self.weight } + pub fn get_mode(&self) -> Option<&ExamMode> { + self.mode.as_ref() + } + + pub fn get_starts_at(&self) -> Option { + self.starts_at + } + + pub fn get_ends_at(&self) -> Option { + self.ends_at + } + + pub fn get_duration_ms(&self) -> Option { + self.duration_ms + } + + /// 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. + pub fn schedule(&self) -> ExamSchedule { + ExamSchedule { + mode: self.mode.clone(), + starts_at: self.starts_at, + ends_at: self.ends_at, + duration_ms: self.duration_ms, + } + } + pub fn is_creator(&self, user: &UserId) -> bool { &self.creator == user } + #[expect( + clippy::too_many_arguments, + reason = "mirrors the sibling entities' create(field, field, ..) shape" + )] pub async fn create( creator: &UserId, course: &CourseId, @@ -144,6 +288,7 @@ impl Exam { description: ExamDescription, kind: ExamKind, weight: ExamWeight, + schedule: ExamSchedule, db: &Database, ) -> Result { let exam = Exam { @@ -154,6 +299,10 @@ impl Exam { description, kind, weight, + mode: schedule.mode, + starts_at: schedule.starts_at, + ends_at: schedule.ends_at, + duration_ms: schedule.duration_ms, }; let created: Option = db.create(exam.id.record()).content(exam).await?; created.ok_or_else(|| AppError::Internal("failed to create exam".into())) @@ -188,22 +337,35 @@ impl Exam { description: ExamDescription, kind: ExamKind, weight: ExamWeight, + schedule: ExamSchedule, db: &Database, ) -> Result { self.title = title; self.description = description; self.kind = kind; self.weight = weight; + self.mode = schedule.mode; + self.starts_at = schedule.starts_at; + self.ends_at = schedule.ends_at; + self.duration_ms = schedule.duration_ms; let updated: Option = db.update(self.id.record()).content(self).await?; updated.ok_or(AppError::NotFound) } - /// Delete the exam and cascade-remove its result rows. + /// Delete the exam and cascade-remove its result, attempt, question, and + /// answer rows. pub async fn delete(self, db: &Database) -> Result { - db.query("DELETE exam_result WHERE exam = $ex") - .bind(("ex", self.id.record())) - .await? - .check()?; + db.query( + "BEGIN TRANSACTION; + DELETE exam_result WHERE exam = $ex; + DELETE exam_attempt WHERE exam = $ex; + DELETE exam_answer WHERE exam = $ex; + DELETE exam_question WHERE exam = $ex; + COMMIT TRANSACTION;", + ) + .bind(("ex", self.id.record())) + .await? + .check()?; let deleted: Option = db.delete(self.id.record()).await?; deleted.ok_or(AppError::NotFound) } @@ -241,4 +403,39 @@ mod tests { assert!(ExamWeight::try_new(0).is_err()); assert!(ExamWeight::try_new(101).is_err()); } + + #[tokio::test] + async fn mode_must_be_known() { + for mode in ["sync", "async"] { + assert_eq!(ExamMode::try_new(mode).unwrap().as_str(), mode); + } + assert!(ExamMode::try_new("live").is_err()); + } + + #[tokio::test] + async fn schedule_invariants_hold() { + let mode = |m| Some(ExamMode::try_new(m).unwrap()); + let at = |ms| Some(Timestamp::from_millis(ms)); + let dur = Some(ExamDuration::try_new(90 * 60 * 1000).unwrap()); + + // Unscheduled: nothing set is fine, any time/duration without a mode is not. + assert!(ExamSchedule::try_new(None, None, None, None).is_ok()); + assert!(ExamSchedule::try_new(None, at(1), None, None).is_err()); + assert!(ExamSchedule::try_new(None, None, at(2), None).is_err()); + assert!(ExamSchedule::try_new(None, None, None, dur).is_err()); + + // Sync: fixed window, no duration. + assert!(ExamSchedule::try_new(mode("sync"), at(1), at(2), None).is_ok()); + assert!(ExamSchedule::try_new(mode("sync"), None, at(2), None).is_err()); + assert!(ExamSchedule::try_new(mode("sync"), at(1), None, None).is_err()); + assert!(ExamSchedule::try_new(mode("sync"), at(1), at(2), dur).is_err()); + + // Async: window plus a per-student duration. + assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), dur).is_ok()); + assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), None).is_err()); + + // The window must be a real interval, whatever the mode. + assert!(ExamSchedule::try_new(mode("sync"), at(2), at(2), None).is_err()); + assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err()); + } } diff --git a/src/domain/exam_answer.rs b/src/domain/exam_answer.rs new file mode 100644 index 0000000..b850133 --- /dev/null +++ b/src/domain/exam_answer.rs @@ -0,0 +1,303 @@ +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; + +use crate::constant::MAX_ANSWER_TEXT_LEN; +use crate::database::{Database, EXAM_ANSWER_TABLE}; +use crate::domain::exam::ExamId; +use crate::domain::exam_question::{ExamQuestion, ExamQuestionId}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::validate_optional; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct ExamAnswerId(RecordId); + +impl ExamAnswerId { + /// A deterministic id for the (question, user) pair — the question key is + /// its own ULID, so the pair key is unambiguous. Saving is a single atomic + /// UPSERT: re-answering overwrites the one row instead of racing the + /// unique index into a 500. ULID keys are alphanumeric, so `_` is an + /// unambiguous joiner. + pub fn composite(question: &ExamQuestionId, user: &UserId) -> Self { + Self(RecordId::new( + EXAM_ANSWER_TABLE, + format!("{}_{}", question.key(), user.key()), + )) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// A free-text answer: may be empty (a student clearing their draft is a valid +/// save), at most `MAX_ANSWER_TEXT_LEN` characters. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct AnswerText(String); + +impl AnswerText { + pub fn try_new(value: &str) -> Result { + validate_optional("text", value, MAX_ANSWER_TEXT_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// One student's answer to one question, autosaved as they type or pick. +/// `exam` is denormalized from the question so per-exam reads (live monitor, +/// cascades) don't fan out through `exam_question`. +#[derive(Debug, Clone, SurrealValue)] +pub struct ExamAnswer { + id: ExamAnswerId, + exam: ExamId, + question: ExamQuestionId, + user: UserId, + selected: Option, + text: Option, + updated_at: Timestamp, +} + +impl ExamAnswer { + pub fn get_id(&self) -> &ExamAnswerId { + &self.id + } + + pub fn get_exam(&self) -> &ExamId { + &self.exam + } + + pub fn get_question(&self) -> &ExamQuestionId { + &self.question + } + + pub fn get_user(&self) -> &UserId { + &self.user + } + + pub fn get_selected(&self) -> Option { + self.selected + } + + pub fn get_text(&self) -> Option<&AnswerText> { + self.text.as_ref() + } + + pub fn get_updated_at(&self) -> Timestamp { + self.updated_at + } + + /// Whether this answer hits the question's correct choice. `None` for a + /// text question — correctness is the grader's call, not the machine's. + pub fn is_correct(&self, question: &ExamQuestion) -> Option { + let correct = question.get_correct()?; + Some(self.selected == Some(correct)) + } + + /// Save (or overwrite) `user`'s answer to `question` — the one write path, + /// shared by the REST handler and the WebSocket room. The payload must + /// match the question's kind: a choice question takes `selected` (indexing + /// one of its choices), a text question takes `text`. The caller has + /// already checked that the attempt is in progress. + pub async fn save( + question: &ExamQuestion, + user: &UserId, + selected: Option, + text: Option, + db: &Database, + ) -> Result { + let invalid = + |field, reason| AppError::Validation(ValidationError::Invalid { field, reason }); + let (selected, text) = match question.get_kind().as_str() { + "choice" => { + if text.is_some() { + return Err(invalid( + "text", + "a choice question takes selected, not text", + )); + } + let Some(selected) = selected else { + return Err(invalid("selected", "required for a choice question")); + }; + let count = question.get_choices().map_or(0, <[_]>::len); + if !(0..count as i64).contains(&selected) { + return Err(invalid( + "selected", + "must index one of the question's choices", + )); + } + (Some(selected), None) + } + _ => { + if selected.is_some() { + return Err(invalid( + "selected", + "a text question takes text, not selected", + )); + } + let Some(text) = text else { + return Err(invalid("text", "required for a text question")); + }; + (None, Some(AnswerText::try_new(&text)?)) + } + }; + let answer = ExamAnswer { + id: ExamAnswerId::composite(question.get_id(), user), + exam: question.get_exam().clone(), + question: question.get_id().clone(), + user: user.clone(), + selected, + text, + updated_at: Timestamp::now(), + }; + let saved: Option = db.upsert(answer.id.record()).content(answer).await?; + saved.ok_or_else(|| AppError::Internal("failed to save exam answer".into())) + } + + /// One student's answers across an exam, in question (ULID) order. + pub async fn list_for_exam_user( + exam: &ExamId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM exam_answer WHERE exam = $ex AND user = $usr ORDER BY question ASC", + ) + .bind(("ex", exam.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// Every answer of an exam — the live monitor aggregates these per student. + pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM exam_answer WHERE exam = $ex ORDER BY question ASC") + .bind(("ex", exam.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } +} + +/// The choice-question score suggested by the machine: `earned` points from +/// answers hitting `correct`, out of `possible` points across all choice +/// questions. Text questions never count — the final mark stays a human call +/// (`POST /exams/{id}/results`). +pub fn auto_score(questions: &[ExamQuestion], answers: &[ExamAnswer]) -> (i64, i64) { + let mut earned = 0; + let mut possible = 0; + for question in questions { + let Some(correct) = question.get_correct() else { + continue; + }; + possible += question.get_points().as_i64(); + if answers + .iter() + .any(|a| a.get_question() == question.get_id() && a.get_selected() == Some(correct)) + { + earned += question.get_points().as_i64(); + } + } + (earned, possible) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::exam_question::{QuestionKind, QuestionSpec}; + + fn choice_question(exam: &ExamId, points: i64, correct: i64) -> ExamQuestion { + let spec = QuestionSpec::try_new( + QuestionKind::try_new("choice").unwrap(), + Some(vec!["a".into(), "b".into(), "c".into()]), + Some(correct), + ) + .unwrap(); + ExamQuestion::test_new(exam, "pick one", points, spec) + } + + fn text_question(exam: &ExamId, points: i64) -> ExamQuestion { + let spec = + QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None).unwrap(); + ExamQuestion::test_new(exam, "explain", points, spec) + } + + fn answer(question: &ExamQuestion, user: &UserId, selected: Option) -> ExamAnswer { + ExamAnswer { + id: ExamAnswerId::composite(question.get_id(), user), + exam: question.get_exam().clone(), + question: question.get_id().clone(), + user: user.clone(), + selected, + text: selected + .is_none() + .then(|| AnswerText::try_new("essay").unwrap()), + updated_at: Timestamp::from_millis(1), + } + } + + fn student() -> UserId { + UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA") + } + + #[tokio::test] + async fn answer_text_may_be_empty_but_bounded() { + assert!(AnswerText::try_new("").is_ok()); + assert!(AnswerText::try_new(&"x".repeat(10_000)).is_ok()); + assert!(AnswerText::try_new(&"x".repeat(10_001)).is_err()); + } + + #[tokio::test] + async fn auto_score_counts_correct_choices_only() { + let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA"); + let user = student(); + let q1 = choice_question(&exam, 10, 0); // answered right + let q2 = choice_question(&exam, 20, 1); // answered wrong + let q3 = choice_question(&exam, 30, 2); // unanswered + let q4 = text_question(&exam, 40); // never auto-scored + let questions = vec![q1.clone(), q2.clone(), q3, q4.clone()]; + let answers = vec![ + answer(&q1, &user, Some(0)), + answer(&q2, &user, Some(0)), + answer(&q4, &user, None), + ]; + assert_eq!(auto_score(&questions, &answers), (10, 60)); + } + + #[tokio::test] + async fn auto_score_of_nothing_is_zero() { + assert_eq!(auto_score(&[], &[]), (0, 0)); + let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA"); + let questions = vec![text_question(&exam, 50)]; + assert_eq!(auto_score(&questions, &[]), (0, 0)); + } + + #[tokio::test] + async fn is_correct_judges_choice_questions_only() { + let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA"); + let user = student(); + let choice = choice_question(&exam, 10, 1); + assert_eq!( + answer(&choice, &user, Some(1)).is_correct(&choice), + Some(true) + ); + assert_eq!( + answer(&choice, &user, Some(0)).is_correct(&choice), + Some(false) + ); + let text = text_question(&exam, 10); + assert_eq!(answer(&text, &user, None).is_correct(&text), None); + } +} diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs new file mode 100644 index 0000000..30e3521 --- /dev/null +++ b/src/domain/exam_attempt.rs @@ -0,0 +1,192 @@ +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; + +use crate::database::{Database, EXAM_ATTEMPT_TABLE}; +use crate::domain::exam::Exam; +use crate::domain::exam::ExamId; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct ExamAttemptId(RecordId); + +impl ExamAttemptId { + /// A deterministic id for the (exam, user) pair. The same pair always maps + /// to the same record id, so a student gets exactly one attempt per exam by + /// construction — a second "start" cannot mint a fresh clock. ULID keys are + /// alphanumeric, so `_` is an unambiguous joiner. + pub fn composite(exam: &ExamId, user: &UserId) -> Self { + Self(RecordId::new( + EXAM_ATTEMPT_TABLE, + format!("{}_{}", exam.key(), user.key()), + )) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// Where an attempt stands right now, judged against the server clock. Derived +/// on read — never stored, so it can't go stale. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AttemptStatus { + /// Started, not submitted, deadline not reached. + InProgress, + /// The student declared themselves done before the deadline. + Submitted, + /// The deadline passed without a submission — a valid terminal state + /// (the student used their full time), not an error. + Expired, +} + +impl AttemptStatus { + pub fn as_str(self) -> &'static str { + match self { + AttemptStatus::InProgress => "in_progress", + AttemptStatus::Submitted => "submitted", + AttemptStatus::Expired => "expired", + } + } +} + +/// One student's sitting of a scheduled exam: starting is the live-attendance +/// signal, `finished_at` the submission. Grading stays a separate +/// `exam_result` row. +#[derive(Debug, Clone, SurrealValue)] +pub struct ExamAttempt { + id: ExamAttemptId, + exam: ExamId, + user: UserId, + started_at: Timestamp, + finished_at: Option, +} + +impl ExamAttempt { + pub fn get_id(&self) -> &ExamAttemptId { + &self.id + } + + pub fn get_exam(&self) -> &ExamId { + &self.exam + } + + pub fn get_user(&self) -> &UserId { + &self.user + } + + pub fn get_started_at(&self) -> Timestamp { + self.started_at + } + + pub fn get_finished_at(&self) -> Option { + self.finished_at + } + + /// When this attempt closes, computed from the exam's *current* schedule + /// (never stored): `ends_at` for a sync exam, `min(started_at + + /// duration_ms, ends_at)` for an async one. Recomputing on every read means + /// a teacher extending `ends_at` (or an async `duration_ms`) mid-exam moves + /// every deadline live. `None` only if the exam is unscheduled, which + /// starting an attempt forbids. + pub fn deadline(&self, exam: &Exam) -> Option { + let ends_at = exam.get_ends_at()?; + Some(match exam.get_duration_ms() { + Some(duration) => ends_at.min(Timestamp::from_millis( + self.started_at + .as_millis() + .saturating_add(duration.as_millis()), + )), + None => ends_at, + }) + } + + /// Status judged at `now` (one clock read per snapshot, shared across rows). + pub fn status(&self, exam: &Exam, now: Timestamp) -> AttemptStatus { + if self.finished_at.is_some() { + return AttemptStatus::Submitted; + } + match self.deadline(exam) { + Some(deadline) if now >= deadline => AttemptStatus::Expired, + _ => AttemptStatus::InProgress, + } + } + + /// Start (or resume) `user`'s attempt at `exam`. Returns the attempt plus + /// whether it was newly created: an existing row is returned untouched, so + /// a reconnecting client gets its original clock back instead of a reset — + /// re-"starting" can never buy more time. The composite id makes the + /// create atomic; a concurrent double-start loses to the unique id and + /// reads the winner's row. + pub async fn start( + exam: &ExamId, + user: &UserId, + db: &Database, + ) -> Result<(ExamAttempt, bool), AppError> { + if let Some(existing) = Self::read_for_user(exam, user, db).await? { + return Ok((existing, false)); + } + let attempt = ExamAttempt { + id: ExamAttemptId::composite(exam, user), + exam: exam.clone(), + user: user.clone(), + started_at: Timestamp::now(), + finished_at: None, + }; + let created: Result, surrealdb::Error> = + db.create(attempt.id.record()).content(attempt).await; + match created { + Ok(Some(created)) => Ok((created, true)), + Ok(None) => Err(AppError::Internal("failed to start exam attempt".into())), + Err(err) => match Self::read_for_user(exam, user, db).await? { + Some(existing) => Ok((existing, false)), + None => Err(err.into()), + }, + } + } + + /// Stamp the submission time. The caller has already checked the deadline + /// and that the attempt isn't finished. + pub async fn finish(mut self, db: &Database) -> Result { + self.finished_at = Some(Timestamp::now()); + let updated: Option = db.update(self.id.record()).content(self).await?; + updated.ok_or(AppError::NotFound) + } + + pub async fn read_for_user( + exam: &ExamId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + Ok(db + .select(ExamAttemptId::composite(exam, user).record()) + .await?) + } + + pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM exam_attempt WHERE exam = $ex ORDER BY id DESC") + .bind(("ex", exam.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// 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 { + let mut result = db + .query("SELECT VALUE id FROM exam_attempt WHERE exam = $ex LIMIT 1") + .bind(("ex", exam.record())) + .await? + .check()?; + Ok(!result.take::>(0)?.is_empty()) + } +} diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs new file mode 100644 index 0000000..f7f3216 --- /dev/null +++ b/src/domain/exam_question.rs @@ -0,0 +1,381 @@ +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::constant::{ + MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, MIN_QUESTION_CHOICES, +}; +use crate::database::{Database, EXAM_QUESTION_TABLE}; +use crate::domain::exam::ExamId; +use crate::error::{AppError, ValidationError}; +use crate::validate::{validate_question_kind, validate_question_points, validate_required}; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct ExamQuestionId(RecordId); + +impl ExamQuestionId { + pub fn generate() -> Self { + Self(RecordId::new(EXAM_QUESTION_TABLE, Ulid::new().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(EXAM_QUESTION_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct QuestionText(String); + +impl QuestionText { + pub fn try_new(value: &str) -> Result { + validate_required("text", value, MAX_QUESTION_TEXT_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// A validated question kind: `choice` (pick one option, auto-scorable) or +/// `text` (free text, judged by the grader). +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct QuestionKind(String); + +impl QuestionKind { + pub fn try_new(value: &str) -> Result { + validate_question_kind(value)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// A validated question weight in the auto-score, held to +/// `[MIN_QUESTION_POINTS, MAX_QUESTION_POINTS]`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] +pub struct QuestionPoints(i64); + +impl QuestionPoints { + pub fn try_new(value: i64) -> Result { + validate_question_points(value)?; + Ok(Self(value)) + } + + pub fn as_i64(&self) -> i64 { + self.0 + } +} + +/// One option of a choice question: non-blank, at most `MAX_CHOICE_TEXT_LEN` +/// characters. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct ChoiceText(String); + +impl ChoiceText { + pub fn try_new(value: &str) -> Result { + validate_required("choice", value, MAX_CHOICE_TEXT_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// The kind-dependent fields of a question, validated as a unit — they only +/// make sense together. `try_new` is the sole constructor, so a `QuestionSpec` +/// in hand always satisfies: +/// +/// - `text` → no `choices`, no `correct` (the grader judges the answer), +/// - `choice` → 2–10 `choices` plus a `correct` index into them. +#[derive(Debug, Clone)] +pub struct QuestionSpec { + kind: QuestionKind, + choices: Option>, + correct: Option, +} + +impl QuestionSpec { + pub fn try_new( + kind: QuestionKind, + choices: Option>, + correct: Option, + ) -> Result { + let invalid = |field, reason| ValidationError::Invalid { field, reason }; + let choices = match (kind.as_str(), choices) { + ("text", Some(_)) => { + return Err(invalid("choices", "only choice questions take choices")); + } + ("text", None) => { + if correct.is_some() { + return Err(invalid( + "correct", + "only choice questions take a correct index", + )); + } + None + } + (_, None) => return Err(invalid("choices", "required for a choice question")), + (_, Some(choices)) => { + if !(MIN_QUESTION_CHOICES..=MAX_QUESTION_CHOICES).contains(&choices.len()) { + return Err(invalid("choices", "must list 2 to 10 choices")); + } + let Some(correct) = correct else { + return Err(invalid("correct", "required for a choice question")); + }; + if !(0..choices.len() as i64).contains(&correct) { + return Err(invalid("correct", "must index one of the choices")); + } + Some( + choices + .iter() + .map(|choice| ChoiceText::try_new(choice)) + .collect::, _>>()?, + ) + } + }; + Ok(Self { + kind, + choices, + correct, + }) + } + + pub fn get_kind(&self) -> &QuestionKind { + &self.kind + } +} + +/// One question of an exam. Order within the exam is the id's ULID order +/// (creation order); the kind-dependent columns always satisfy the +/// [`QuestionSpec`] invariants because every write goes through one. +#[derive(Debug, Clone, SurrealValue)] +pub struct ExamQuestion { + id: ExamQuestionId, + exam: ExamId, + text: QuestionText, + kind: QuestionKind, + points: QuestionPoints, + choices: Option>, + correct: Option, +} + +impl ExamQuestion { + pub fn get_id(&self) -> &ExamQuestionId { + &self.id + } + + pub fn get_exam(&self) -> &ExamId { + &self.exam + } + + pub fn get_text(&self) -> &QuestionText { + &self.text + } + + pub fn get_kind(&self) -> &QuestionKind { + &self.kind + } + + pub fn get_points(&self) -> QuestionPoints { + self.points + } + + pub fn get_choices(&self) -> Option<&[ChoiceText]> { + self.choices.as_deref() + } + + pub fn get_correct(&self) -> Option { + self.correct + } + + /// The stored kind-dependent fields as the validated bundle (for + /// merge-on-update). Bypasses `try_new`: the fields were written through a + /// `QuestionSpec`, so the invariants already hold. + pub fn spec(&self) -> QuestionSpec { + QuestionSpec { + kind: self.kind.clone(), + choices: self.choices.clone(), + correct: self.correct, + } + } + + pub async fn create( + exam: &ExamId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, + db: &Database, + ) -> Result { + let question = ExamQuestion { + id: ExamQuestionId::generate(), + exam: exam.clone(), + text, + points, + kind: spec.kind, + choices: spec.choices, + correct: spec.correct, + }; + let created: Option = + db.create(question.id.record()).content(question).await?; + created.ok_or_else(|| AppError::Internal("failed to create exam question".into())) + } + + pub async fn read( + id: &ExamQuestionId, + db: &Database, + ) -> Result, AppError> { + Ok(db.select(id.record()).await?) + } + + /// The exam's questions in presentation order (ULID ids sort by creation). + pub async fn list_for_exam( + exam: &ExamId, + 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)?) + } + + pub async fn update( + mut self, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, + db: &Database, + ) -> Result { + self.text = text; + self.points = points; + self.kind = spec.kind; + self.choices = spec.choices; + self.correct = spec.correct; + let updated: Option = db.update(self.id.record()).content(self).await?; + updated.ok_or(AppError::NotFound) + } + + /// Delete the question and cascade-remove its answers, so no answer row + /// can point at a missing question. + pub async fn delete(self, db: &Database) -> Result { + db.query("DELETE exam_answer WHERE question = $q") + .bind(("q", self.id.record())) + .await? + .check()?; + let deleted: Option = db.delete(self.id.record()).await?; + deleted.ok_or(AppError::NotFound) + } + + /// A question constructed without a database, for pure-function tests. + #[cfg(test)] + pub fn test_new(exam: &ExamId, text: &str, points: i64, spec: QuestionSpec) -> ExamQuestion { + ExamQuestion { + id: ExamQuestionId::generate(), + exam: exam.clone(), + text: QuestionText::try_new(text).unwrap(), + points: QuestionPoints::try_new(points).unwrap(), + kind: spec.kind, + choices: spec.choices, + correct: spec.correct, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn kind(value: &str) -> QuestionKind { + QuestionKind::try_new(value).unwrap() + } + + fn two_choices() -> Option> { + Some(vec!["yes".into(), "no".into()]) + } + + #[tokio::test] + async fn text_is_required() { + assert!(QuestionText::try_new("What is 2 + 2?").is_ok()); + assert!(QuestionText::try_new("").is_err()); + assert!(QuestionText::try_new(" ").is_err()); + assert!(QuestionText::try_new(&"x".repeat(2_001)).is_err()); + } + + #[tokio::test] + async fn kind_must_be_known() { + for value in ["choice", "text"] { + assert_eq!(QuestionKind::try_new(value).unwrap().as_str(), value); + } + assert!(QuestionKind::try_new("essay").is_err()); + } + + #[tokio::test] + async fn points_range_is_enforced() { + assert_eq!(QuestionPoints::try_new(1).unwrap().as_i64(), 1); + assert_eq!(QuestionPoints::try_new(100).unwrap().as_i64(), 100); + assert!(QuestionPoints::try_new(0).is_err()); + assert!(QuestionPoints::try_new(101).is_err()); + } + + #[tokio::test] + async fn choice_text_is_required() { + assert!(ChoiceText::try_new("yes").is_ok()); + assert!(ChoiceText::try_new("").is_err()); + assert!(ChoiceText::try_new(" ").is_err()); + assert!(ChoiceText::try_new(&"x".repeat(501)).is_err()); + } + + #[tokio::test] + async fn spec_invariants_hold() { + // Text questions carry neither choices nor a correct index. + assert!(QuestionSpec::try_new(kind("text"), None, None).is_ok()); + assert!(QuestionSpec::try_new(kind("text"), two_choices(), None).is_err()); + assert!(QuestionSpec::try_new(kind("text"), None, Some(0)).is_err()); + assert!(QuestionSpec::try_new(kind("text"), two_choices(), Some(0)).is_err()); + + // Choice questions need both. + assert!(QuestionSpec::try_new(kind("choice"), two_choices(), Some(0)).is_ok()); + assert!(QuestionSpec::try_new(kind("choice"), two_choices(), Some(1)).is_ok()); + assert!(QuestionSpec::try_new(kind("choice"), None, None).is_err()); + assert!(QuestionSpec::try_new(kind("choice"), None, Some(0)).is_err()); + assert!(QuestionSpec::try_new(kind("choice"), two_choices(), None).is_err()); + } + + #[tokio::test] + async fn spec_correct_must_index_a_choice() { + assert!(QuestionSpec::try_new(kind("choice"), two_choices(), Some(-1)).is_err()); + assert!(QuestionSpec::try_new(kind("choice"), two_choices(), Some(2)).is_err()); + } + + #[tokio::test] + async fn spec_choice_count_is_bounded() { + let n = |count: usize| Some(vec!["option".to_string(); count]); + assert!(QuestionSpec::try_new(kind("choice"), n(1), Some(0)).is_err()); + assert!(QuestionSpec::try_new(kind("choice"), n(2), Some(0)).is_ok()); + assert!(QuestionSpec::try_new(kind("choice"), n(10), Some(0)).is_ok()); + assert!(QuestionSpec::try_new(kind("choice"), n(11), Some(0)).is_err()); + } + + #[tokio::test] + async fn spec_rejects_blank_or_oversized_choices() { + let blank = Some(vec!["yes".to_string(), " ".to_string()]); + assert!(QuestionSpec::try_new(kind("choice"), blank, Some(0)).is_err()); + let oversized = Some(vec!["yes".to_string(), "x".repeat(501)]); + assert!(QuestionSpec::try_new(kind("choice"), oversized, Some(0)).is_err()); + } +} diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 38ca4a3..aeef724 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -7,6 +7,9 @@ pub mod course; pub mod enrollment; pub mod event; pub mod exam; +pub mod exam_answer; +pub mod exam_attempt; +pub mod exam_question; pub mod exam_result; pub mod note; pub mod profile; diff --git a/src/domain/user.rs b/src/domain/user.rs index b5b9f72..46db600 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -259,6 +259,40 @@ impl User { Ok(result.take::>(0)?) } + /// Fetch the users behind `ids` in one query. Ids with no row are simply + /// absent from the result — the caller decides how to degrade. + pub async fn list_by_ids(ids: &[UserId], db: &Database) -> Result, AppError> { + if ids.is_empty() { + return Ok(Vec::new()); + } + let records: Vec = ids.iter().map(UserId::record).collect(); + let mut result = db + .query("SELECT * FROM user WHERE id IN $ids") + .bind(("ids", records)) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// Case-insensitive fragment search over username, name, and surname — + /// backs the user pickers. Capped at 10 rows: pickers show a short list, + /// and the cap keeps an over-broad fragment from hauling the whole table. + pub async fn search(query: &str, db: &Database) -> Result, AppError> { + let needle = query.trim().to_lowercase(); + let mut result = db + .query( + "SELECT * FROM user WHERE \ + string::lowercase(username) CONTAINS $q \ + OR string::lowercase(name ?? '') CONTAINS $q \ + OR string::lowercase(surname ?? '') CONTAINS $q \ + ORDER BY username LIMIT 10", + ) + .bind(("q", needle)) + .await? + .check()?; + Ok(result.take::>(0)?) + } + /// Overwrite this user's role. The caller is responsible for authorizing it. pub async fn set_role(mut self, role: Role, db: &Database) -> Result { self.role = role; diff --git a/src/lib.rs b/src/lib.rs index 8f6e96e..3ce688b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -42,7 +42,7 @@ use crate::state::AppState; (name = "notes", description = "Per-user notes CRUD"), (name = "events", description = "Events and attendance"), (name = "courses", description = "Courses, enrollment, and course exams"), - (name = "exams", description = "Exams (per course, weighted) and student results"), + (name = "exams", description = "Exams (per course, weighted): results, sync/async scheduling, attempts, questions/answers, and live monitoring. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames, see the README's \"Taking an exam\" section for the protocol"), (name = "marks", description = "Weighted mark reports per course and overall"), ), )] diff --git a/src/validate.rs b/src/validate.rs index 2d9de5b..d14891a 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -2,9 +2,10 @@ //! the value, so an existing newtype is always valid (parse, don't validate). use crate::constant::{ - ATTENDANCE_STATUSES, EXAM_KINDS, MAX_EMAIL_LEN, MAX_EXAM_WEIGHT, MAX_MARK, MAX_PASSWORD_LEN, - MAX_PHONE_DIGITS, MAX_USERNAME_LEN, MIN_EXAM_WEIGHT, MIN_MARK, MIN_PASSWORD_LEN, - MIN_PHONE_DIGITS, MIN_USERNAME_LEN, + ATTENDANCE_STATUSES, EXAM_KINDS, EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_DURATION_MS, + MAX_EXAM_WEIGHT, MAX_MARK, MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, + MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, MIN_EXAM_WEIGHT, MIN_MARK, MIN_PASSWORD_LEN, + MIN_PHONE_DIGITS, MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS, }; use crate::error::ValidationError; @@ -179,6 +180,50 @@ pub fn validate_exam_kind(value: &str) -> Result<(), ValidationError> { } } +pub fn validate_exam_mode(value: &str) -> Result<(), ValidationError> { + if EXAM_MODES.contains(&value) { + Ok(()) + } else { + Err(ValidationError::Invalid { + field: "mode", + reason: "must be one of: sync, async", + }) + } +} + +pub fn validate_exam_duration(value: i64) -> Result<(), ValidationError> { + if (MIN_EXAM_DURATION_MS..=MAX_EXAM_DURATION_MS).contains(&value) { + Ok(()) + } else { + Err(ValidationError::Invalid { + field: "duration_ms", + reason: "must be between 60000 (1 minute) and 86400000 (24 hours) milliseconds", + }) + } +} + +pub fn validate_question_kind(value: &str) -> Result<(), ValidationError> { + if QUESTION_KINDS.contains(&value) { + Ok(()) + } else { + Err(ValidationError::Invalid { + field: "kind", + reason: "must be one of: choice, text", + }) + } +} + +pub fn validate_question_points(value: i64) -> Result<(), ValidationError> { + if (MIN_QUESTION_POINTS..=MAX_QUESTION_POINTS).contains(&value) { + Ok(()) + } else { + Err(ValidationError::Invalid { + field: "points", + reason: "must be between 1 and 100", + }) + } +} + pub fn validate_mark(value: i64) -> Result<(), ValidationError> { if (MIN_MARK..=MAX_MARK).contains(&value) { Ok(()) @@ -294,6 +339,45 @@ mod tests { assert!(validate_exam_kind("").is_err()); } + #[tokio::test] + async fn exam_mode_rules() { + for mode in ["sync", "async"] { + assert!(validate_exam_mode(mode).is_ok()); + } + assert!(validate_exam_mode("live").is_err()); + assert!(validate_exam_mode("").is_err()); + } + + #[tokio::test] + async fn exam_duration_rules() { + assert!(validate_exam_duration(MIN_EXAM_DURATION_MS).is_ok()); + assert!(validate_exam_duration(90 * 60 * 1000).is_ok()); + assert!(validate_exam_duration(MAX_EXAM_DURATION_MS).is_ok()); + assert!(validate_exam_duration(MIN_EXAM_DURATION_MS - 1).is_err()); + assert!(validate_exam_duration(MAX_EXAM_DURATION_MS + 1).is_err()); + assert!(validate_exam_duration(0).is_err()); + assert!(validate_exam_duration(-1).is_err()); + } + + #[tokio::test] + async fn question_kind_rules() { + for kind in ["choice", "text"] { + assert!(validate_question_kind(kind).is_ok()); + } + assert!(validate_question_kind("essay").is_err()); + assert!(validate_question_kind("").is_err()); + } + + #[tokio::test] + async fn question_points_rules() { + for points in [1, 50, 100] { + assert!(validate_question_points(points).is_ok()); + } + assert!(validate_question_points(0).is_err()); + assert!(validate_question_points(-1).is_err()); + assert!(validate_question_points(101).is_err()); + } + #[tokio::test] async fn mark_rules() { for mark in [0, 1, 50, 99, 100] { diff --git a/src/web/courses.rs b/src/web/courses.rs index 91677e8..1a14f87 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use axum::Json; use axum::extract::{Path, State}; use axum::http::StatusCode; @@ -8,13 +10,16 @@ use utoipa_axum::routes; use crate::domain::course::{Course, CourseDescription, CourseId, CourseTitle}; use crate::domain::enrollment::Enrollment; -use crate::domain::exam::{Exam, ExamDescription, ExamKind, ExamTitle, ExamWeight}; +use crate::domain::exam::{ + Exam, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, ExamWeight, +}; use crate::domain::role::Role; +use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; -use super::{CourseResponse, CurrentUser, ExamResponse, RequireTeacher}; +use super::{CourseResponse, CurrentUser, ExamResponse, PersonRef, RequireTeacher, person_map}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() @@ -58,23 +63,39 @@ struct CreateExamInCourse { /// How many times this exam counts into the course average, `1`–`100`. #[schema(example = 3)] weight: i64, + /// `sync` (one fixed window for everyone) or `async` (each student starts + /// inside the window and gets `duration_ms`). Omit for an unscheduled, + /// offline-graded exam. + #[schema(example = "sync")] + mode: Option, + /// Window open, UTC unix-milliseconds. Required with `mode`. + #[schema(example = 1_752_275_000_000_i64)] + starts_at: Option, + /// Window close, UTC unix-milliseconds. Required with `mode`. + ends_at: Option, + /// Per-student time budget, milliseconds — required for (and exclusive to) + /// `async` exams. + #[schema(example = 5_400_000_i64)] + duration_ms: Option, } #[derive(Serialize, ToSchema)] struct EnrollmentResponse { id: String, course: String, - user: String, - enrolled_by: String, + /// The enrolled student. + user: PersonRef, + /// Who enrolled them. + enrolled_by: PersonRef, } impl EnrollmentResponse { - fn new(enrollment: &Enrollment) -> Self { + fn new(enrollment: &Enrollment, people: &HashMap) -> Self { Self { id: enrollment.get_id().key().to_string(), course: enrollment.get_course().key().to_string(), - user: enrollment.get_user().key().to_string(), - enrolled_by: enrollment.get_enrolled_by().key().to_string(), + user: PersonRef::resolve(people, enrollment.get_user()), + enrolled_by: PersonRef::resolve(people, enrollment.get_enrolled_by()), } } } @@ -288,15 +309,16 @@ async fn enroll( } let target = UserId::from_key(&req.user_id); - if User::read(&target, &st.db).await?.is_none() { + 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", })); - } + }; let enrollment = Enrollment::enroll(course.get_id(), &target, user.get_id(), &st.db).await?; - Ok(Json(EnrollmentResponse::new(&enrollment))) + let people = PersonRef::map_of(&[&target_user, &user]); + Ok(Json(EnrollmentResponse::new(&enrollment, &people))) } /// List a course's roster. Requires teacher+ — students see their own courses @@ -325,8 +347,18 @@ async fn list_roster( .await? .ok_or(AppError::NotFound)?; let enrollments = Enrollment::list_for_course(&course_id, &st.db).await?; + let people = person_map( + enrollments + .iter() + .flat_map(|e| [e.get_user().clone(), e.get_enrolled_by().clone()]), + &st.db, + ) + .await?; Ok(Json( - enrollments.iter().map(EnrollmentResponse::new).collect(), + enrollments + .iter() + .map(|e| EnrollmentResponse::new(e, &people)) + .collect(), )) } @@ -407,6 +439,12 @@ async fn create_exam_in_course( let description = ExamDescription::try_new(&req.description.unwrap_or_default())?; let kind = ExamKind::try_new(&req.kind)?; let weight = ExamWeight::try_new(req.weight)?; + let schedule = ExamSchedule::try_new( + req.mode.as_deref().map(ExamMode::try_new).transpose()?, + req.starts_at.map(Timestamp::from_millis), + req.ends_at.map(Timestamp::from_millis), + req.duration_ms.map(ExamDuration::try_new).transpose()?, + )?; let exam = Exam::create( user.get_id(), course.get_id(), @@ -414,6 +452,7 @@ async fn create_exam_in_course( description, kind, weight, + schedule, &st.db, ) .await?; diff --git a/src/web/dto.rs b/src/web/dto.rs index 40e3463..14465d0 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -1,12 +1,16 @@ //! Response DTOs shared across more than one handler module. +use std::collections::{HashMap, HashSet}; + use serde::Serialize; use utoipa::ToSchema; +use crate::database::Database; use crate::domain::course::Course; use crate::domain::exam::Exam; use crate::domain::role::Role as DomainRole; -use crate::domain::user::User; +use crate::domain::user::{User, UserId}; +use crate::error::AppError; /// The four access roles, lowest to highest privilege. The web-facing mirror of /// [`crate::domain::role::Role`] — it carries the serde + OpenAPI derives (which @@ -32,6 +36,72 @@ impl From for Role { } } +/// How another person appears inside a response: enough to say *who* without +/// leaking contact details. Rows that reference users (enrollments, attendance, +/// exam results) embed this instead of a bare id, so no client ever has to +/// show a raw ULID to a human. +#[derive(Serialize, Clone, ToSchema)] +pub struct PersonRef { + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + pub id: String, + #[schema(example = "ada")] + pub username: String, + /// `"Name Surname"` when the profile carries either; `null` otherwise. + #[schema(example = "Ada Lovelace")] + pub display_name: Option, +} + +impl PersonRef { + pub fn new(user: &User) -> Self { + let full: Vec<&str> = [user.get_name(), user.get_surname()] + .into_iter() + .flatten() + .map(|part| part.as_str()) + .collect(); + Self { + id: user.get_id().key().to_string(), + username: user.get_username().as_str().to_string(), + display_name: (!full.is_empty()).then(|| full.join(" ")), + } + } + + /// Key already-loaded users by id — for handlers that hold the rows anyway. + pub fn map_of(users: &[&User]) -> HashMap { + users + .iter() + .map(|user| (user.get_id().key().to_string(), PersonRef::new(user))) + .collect() + } + + /// Look `id` up in `people`, degrading to the bare id when the row is gone + /// — a stale reference renders oddly instead of failing the request. + pub fn resolve(people: &HashMap, id: &UserId) -> Self { + people.get(id.key()).cloned().unwrap_or_else(|| Self { + id: id.key().to_string(), + username: id.key().to_string(), + display_name: None, + }) + } +} + +/// Load every user behind `ids` (duplicates collapsed, one query) and key +/// their `PersonRef`s by id — the join half of list endpoints that embed people. +pub async fn person_map( + ids: impl IntoIterator, + db: &Database, +) -> Result, AppError> { + let mut seen = HashSet::new(); + let unique: Vec = ids + .into_iter() + .filter(|id| seen.insert(id.key().to_string())) + .collect(); + let users = User::list_by_ids(&unique, db).await?; + Ok(users + .iter() + .map(|user| (user.get_id().key().to_string(), PersonRef::new(user))) + .collect()) +} + /// Public shape of a user: id, username, role, and the optional personal info /// (`null` until filled in). Never carries the password hash. Shared by `auth` /// (register/login/me) and `users` (listing, role and profile changes). @@ -93,7 +163,9 @@ impl CourseResponse { } /// Public shape of an exam. Shared by `exams` (CRUD/results) and `courses` -/// (in-course creation and listing). +/// (in-course creation and listing). The schedule fields are all `null` for an +/// unscheduled (offline-graded) exam; see the create/update endpoints for the +/// rules tying them together. #[derive(Serialize, ToSchema)] pub struct ExamResponse { pub id: String, @@ -103,6 +175,15 @@ pub struct ExamResponse { pub description: String, pub kind: String, pub weight: i64, + /// `sync` or `async`; `null` for an unscheduled exam. + #[schema(example = "sync")] + pub mode: Option, + /// Window open, UTC unix-milliseconds. + pub starts_at: Option, + /// Window close, UTC unix-milliseconds. + pub ends_at: Option, + /// Per-student time budget in milliseconds (async exams only). + pub duration_ms: Option, } impl ExamResponse { @@ -115,6 +196,10 @@ impl ExamResponse { description: exam.get_description().as_str().to_string(), kind: exam.get_kind().as_str().to_string(), weight: exam.get_weight().as_i64(), + mode: exam.get_mode().map(|m| m.as_str().to_string()), + starts_at: exam.get_starts_at().map(|t| t.as_millis()), + ends_at: exam.get_ends_at().map(|t| t.as_millis()), + duration_ms: exam.get_duration_ms().map(|d| d.as_millis()), } } } diff --git a/src/web/events.rs b/src/web/events.rs index 34dfbee..cebc0b4 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -1,7 +1,9 @@ +use std::collections::HashMap; + use axum::Json; use axum::extract::{Path, State}; use axum::http::StatusCode; -use serde::{Deserialize, Deserializer, Serialize}; +use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; @@ -14,7 +16,7 @@ use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; -use super::{CurrentUser, RequireTeacher}; +use super::{CurrentUser, PersonRef, RequireTeacher, person_map, set_or_clear}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() @@ -35,16 +37,6 @@ struct CreateEvent { ends_at: Option, } -/// Distinguishes an *absent* field from an explicit `null`: absent never -/// reaches the deserializer and stays `None` via `#[serde(default)]` (keep the -/// stored value); `null` or a number lands here as `Some(inner)` (clear or set). -fn set_or_clear<'de, D>(de: D) -> Result>, D::Error> -where - D: Deserializer<'de>, -{ - Option::::deserialize(de).map(Some) -} - #[derive(Deserialize, ToSchema)] struct UpdateEvent { title: Option, @@ -120,19 +112,21 @@ fn check_time_range( struct AttendanceResponse { id: String, event: String, - user: String, + /// Whose attendance this row records. + user: PersonRef, status: String, - marked_by: String, + /// Who recorded it. + marked_by: PersonRef, } impl AttendanceResponse { - fn new(attendance: &Attendance) -> Self { + fn new(attendance: &Attendance, people: &HashMap) -> Self { Self { id: attendance.get_id().key().to_string(), event: attendance.get_event().key().to_string(), - user: attendance.get_user().key().to_string(), + user: PersonRef::resolve(people, attendance.get_user()), status: attendance.get_status().as_str().to_string(), - marked_by: attendance.get_marked_by().key().to_string(), + marked_by: PersonRef::resolve(people, attendance.get_marked_by()), } } } @@ -355,15 +349,16 @@ async fn mark( } // Target user must exist. - if User::read(&target, &st.db).await?.is_none() { + 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", })); - } + }; let attendance = Attendance::mark(&event_id, &target, status, user.get_id(), &st.db).await?; - Ok(Json(AttendanceResponse::new(&attendance))) + let people = PersonRef::map_of(&[&target_user, &user]); + Ok(Json(AttendanceResponse::new(&attendance, &people))) } /// List the attendance roster for an event. @@ -390,7 +385,19 @@ async fn list_attendance( .await? .ok_or(AppError::NotFound)?; let roster = Attendance::list_for_event(&event_id, &st.db).await?; - Ok(Json(roster.iter().map(AttendanceResponse::new).collect())) + let people = person_map( + roster + .iter() + .flat_map(|a| [a.get_user().clone(), a.get_marked_by().clone()]), + &st.db, + ) + .await?; + Ok(Json( + roster + .iter() + .map(|a| AttendanceResponse::new(a, &people)) + .collect(), + )) } /// Remove a user's attendance record from an event. Requires teacher+. diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs new file mode 100644 index 0000000..f869974 --- /dev/null +++ b/src/web/exam_ws.rs @@ -0,0 +1,315 @@ +//! The student exam room: a WebSocket at `GET /exams/{id}/attempt/ws`. +//! +//! REST remains the fallback (`POST /exams/{id}/attempt/answers` etc.); the +//! socket exists so a sitting student gets autosave acks and a live, +//! server-judged countdown without polling. The teacher monitor deliberately +//! stays on SSE (`/exams/{id}/live/stream`) — it only ever flows one way. +//! +//! Wire protocol (JSON text frames): +//! +//! server → client +//! - `{"type":"state", status, deadline, remaining_ms, now, answered, question_count}` +//! on connect, every [`EXAM_WS_TICK_SECS`], and after each save +//! - `{"type":"saved", question_id, updated_at}` — an answer landed +//! - `{"type":"pong"}` +//! - `{"type":"finished", finished_at}` then Close — submitted (here or elsewhere) +//! - `{"type":"expired"}` then Close — the deadline passed mid-session +//! - `{"type":"error", message}` — bad JSON, unknown type, validation, deadline +//! +//! client → server +//! - `{"type":"answer", question_id, selected? | text?}` +//! - `{"type":"finish"}` +//! - `{"type":"ping"}` +//! +//! Every save and every tick re-reads the exam and attempt, so the deadline +//! stays server-authoritative: a teacher extending `ends_at` (or `duration_ms`) +//! mid-exam moves this room's clock on the next tick, and a stale client can +//! never write past its real deadline. + +use std::time::Duration; + +use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; +use axum::extract::{Path, State}; +use axum::response::Response; +use serde::Deserialize; +use serde_json::{Value, json}; + +use crate::constant::EXAM_WS_TICK_SECS; +use crate::database::Database; +use crate::domain::enrollment::Enrollment; +use crate::domain::exam::{Exam, ExamId}; +use crate::domain::exam_answer::ExamAnswer; +use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt}; +use crate::domain::exam_question::ExamQuestion; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; +use crate::state::AppState; +use crate::web::CurrentUser; +use crate::web::exams::{save_answer_checked, writable_attempt}; + +/// What the client asked for, tagged by `type`. +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +enum ClientMessage { + Answer { + question_id: String, + #[serde(default)] + selected: Option, + #[serde(default)] + text: Option, + }, + Finish, + Ping, +} + +/// 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), unscheduled (409), not enrolled (403), no attempt yet +/// (404 — `POST /exams/{id}/attempt` first), submitted or expired (409). +pub async fn attempt_ws( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, + ws: WebSocketUpgrade, +) -> Result { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if exam.get_starts_at().is_none() { + return Err(AppError::Conflict( + "this exam is not scheduled — there is nothing to sit", + )); + } + if Enrollment::read_for_user(exam.get_course(), user.get_id(), &st.db) + .await? + .is_none() + { + return Err(AppError::Forbidden( + "you are not enrolled in this exam's course", + )); + } + writable_attempt(&exam, user.get_id(), &st.db).await?; + + let user_id = user.get_id().clone(); + Ok(ws.on_upgrade(move |socket| room(socket, st, exam, user_id))) +} + +/// The room loop: state ticks out, answer/finish/ping in, until the socket +/// closes or the attempt reaches a terminal state. +async fn room(mut socket: WebSocket, st: AppState, exam: Exam, user: UserId) { + let exam_id = exam.get_id().clone(); + let mut tick = tokio::time::interval(Duration::from_secs(EXAM_WS_TICK_SECS)); + loop { + tokio::select! { + // First tick fires immediately — the connect-time state frame. + _ = tick.tick() => { + if push_state(&mut socket, &exam_id, &user, &st.db).await.is_err() { + break; + } + } + incoming = socket.recv() => { + let text = match incoming { + Some(Ok(Message::Text(text))) => text, + // Ping/pong frames are answered by axum itself; other + // non-text frames carry nothing for this protocol. + Some(Ok(Message::Close(_))) | Some(Err(_)) | None => break, + Some(Ok(_)) => continue, + }; + if handle_message(&mut socket, text.as_str(), &exam_id, &user, &st.db) + .await + .is_err() + { + break; + } + } + } + } + // Best-effort closing handshake — a bare TCP teardown reads as an error + // on the client; a Close frame reads as "the room is over". + let _ = socket.send(Message::Close(None)).await; +} + +/// Errors that end the room: the peer went away, or the attempt reached a +/// terminal state and the close frame was sent. +struct RoomClosed; + +async fn send(socket: &mut WebSocket, frame: Value) -> Result<(), RoomClosed> { + socket + .send(Message::Text(frame.to_string().into())) + .await + .map_err(|_| RoomClosed) +} + +/// Re-read everything, push a `state` frame, and close the room (after a +/// `finished`/`expired` notice) once the attempt is no longer in progress. +async fn push_state( + socket: &mut WebSocket, + exam: &ExamId, + user: &UserId, + db: &Database, +) -> Result<(), RoomClosed> { + let (frame, status, finished_at) = match state_frame(exam, user, db).await { + Ok(state) => state, + // The exam vanished mid-room (deleted) or the db hiccuped: nothing + // sensible left to serve. + Err(err) => { + tracing::warn!("exam room state failed: {err}"); + let _ = send( + socket, + json!({ "type": "error", "message": "state unavailable" }), + ) + .await; + return Err(RoomClosed); + } + }; + send(socket, frame).await?; + match status { + AttemptStatus::InProgress => Ok(()), + AttemptStatus::Submitted => { + send( + socket, + json!({ "type": "finished", "finished_at": finished_at }), + ) + .await?; + Err(RoomClosed) + } + AttemptStatus::Expired => { + send(socket, json!({ "type": "expired" })).await?; + Err(RoomClosed) + } + } +} + +/// One server-judged snapshot of the attempt, shaped like the REST +/// `AttemptResponse`'s live fields. +async fn state_frame( + exam: &ExamId, + user: &UserId, + db: &Database, +) -> Result<(Value, AttemptStatus, Option), AppError> { + let exam = Exam::read(exam, db).await?.ok_or(AppError::NotFound)?; + let attempt = ExamAttempt::read_for_user(exam.get_id(), user, db) + .await? + .ok_or(AppError::NotFound)?; + let now = Timestamp::now(); + 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(); + let answered = ExamAnswer::list_for_exam_user(exam.get_id(), user, db) + .await? + .len(); + let question_count = ExamQuestion::list_for_exam(exam.get_id(), db).await?.len(); + let frame = json!({ + "type": "state", + "status": status.as_str(), + "deadline": deadline.map(|t| t.as_millis()), + "remaining_ms": remaining_ms, + "now": now.as_millis(), + "answered": answered, + "question_count": question_count, + }); + Ok(( + frame, + status, + attempt.get_finished_at().map(|t| t.as_millis()), + )) +} + +async fn handle_message( + socket: &mut WebSocket, + text: &str, + exam_id: &ExamId, + user: &UserId, + db: &Database, +) -> Result<(), RoomClosed> { + let message = match serde_json::from_str::(text) { + Ok(message) => message, + Err(err) => { + return send( + socket, + json!({ "type": "error", "message": format!("unrecognized message: {err}") }), + ) + .await; + } + }; + match message { + ClientMessage::Ping => send(socket, json!({ "type": "pong" })).await, + ClientMessage::Answer { + question_id, + selected, + text, + } => { + // Re-read the exam so the save is judged against the *current* + // schedule, exactly like the REST path it shares. + let saved = match Exam::read(exam_id, db).await { + Ok(Some(exam)) => { + save_answer_checked(&exam, user, &question_id, selected, text, db).await + } + Ok(None) => Err(AppError::NotFound), + Err(err) => Err(err), + }; + match saved { + Ok(answer) => { + send( + socket, + json!({ + "type": "saved", + "question_id": answer.get_question().key(), + "updated_at": answer.get_updated_at().as_millis(), + }), + ) + .await?; + // Progress changed — refresh the countdown/answered state + // right away rather than waiting out the tick. + push_state(socket, exam_id, user, db).await + } + Err(err) => send(socket, error_frame(&err)).await, + } + } + ClientMessage::Finish => { + let finished = match Exam::read(exam_id, db).await { + Ok(Some(exam)) => match writable_attempt(&exam, user, db).await { + Ok(attempt) => attempt.finish(db).await, + Err(err) => Err(err), + }, + Ok(None) => Err(AppError::NotFound), + Err(err) => Err(err), + }; + match finished { + Ok(attempt) => { + send( + socket, + json!({ + "type": "finished", + "finished_at": attempt.get_finished_at().map(|t| t.as_millis()), + }), + ) + .await?; + Err(RoomClosed) + } + Err(err) => send(socket, error_frame(&err)).await, + } + } + } +} + +/// The public words for an error — the same strings the HTTP layer would use, +/// with internals logged, never sent. +fn error_frame(err: &AppError) -> Value { + let message = match err { + AppError::Validation(err) => err.to_string(), + AppError::NotFound => "not found".to_string(), + AppError::Unauthorized => "unauthorized".to_string(), + AppError::Forbidden(message) => (*message).to_string(), + AppError::Conflict(message) => (*message).to_string(), + AppError::TooManyRequests { .. } => "too many requests".to_string(), + AppError::Db(_) | AppError::Internal(_) => { + tracing::error!("exam room error: {err}"); + "internal server error".to_string() + } + }; + json!({ "type": "error", "message": message }) +} diff --git a/src/web/exams.rs b/src/web/exams.rs index fb67c48..36e0c99 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -1,31 +1,63 @@ +use std::collections::HashMap; +use std::time::Duration; + use axum::Json; use axum::extract::{Path, State}; use axum::http::StatusCode; +use axum::response::sse::{Event, KeepAlive, Sse}; use serde::{Deserialize, Serialize}; +use tokio_stream::wrappers::IntervalStream; +use tokio_stream::{Stream, StreamExt}; use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; +use crate::constant::EXAM_LIVE_STREAM_INTERVAL_SECS; use crate::database::Database; use crate::domain::course::Course; use crate::domain::enrollment::Enrollment; -use crate::domain::exam::{Exam, ExamDescription, ExamId, ExamKind, ExamTitle, ExamWeight}; +use crate::domain::exam::{ + Exam, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, ExamSchedule, ExamTitle, + ExamWeight, +}; +use crate::domain::exam_answer::{ExamAnswer, auto_score}; +use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt}; +use crate::domain::exam_question::{ + ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, +}; use crate::domain::exam_result::{ExamResult, Mark}; +use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; use super::courses::can_manage_course; -use super::{CurrentUser, ExamResponse, RequireTeacher}; +use super::{CurrentUser, ExamResponse, PersonRef, RequireTeacher, person_map, set_or_clear}; 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!(exam_live_stream)) + .routes(routes!(create_question, list_questions)) + .routes(routes!(update_question, delete_question)) + .routes(routes!(attempt_questions)) + .routes(routes!(save_answer)) + .routes(routes!(attempt_answers)) } #[derive(Deserialize, ToSchema)] @@ -34,6 +66,25 @@ struct UpdateExam { description: Option, kind: Option, weight: Option, + /// `sync` or `async`. Omit to keep the current mode; send `null` to + /// unschedule the exam. Frozen once anyone has started an attempt. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option)] + mode: Option>, + /// Window open, UTC unix-milliseconds. Omit to keep; `null` to clear. + #[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. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option)] + ends_at: Option>, + /// Per-student budget, milliseconds (async only). 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)] + duration_ms: Option>, } #[derive(Deserialize, ToSchema)] @@ -50,19 +101,21 @@ struct GradeResult { struct ExamResultResponse { id: String, exam: String, - user: String, + /// The graded student. + user: PersonRef, mark: i64, - graded_by: String, + /// Who recorded the mark. + graded_by: PersonRef, } impl ExamResultResponse { - fn new(result: &ExamResult) -> Self { + fn new(result: &ExamResult, people: &HashMap) -> Self { Self { id: result.get_id().key().to_string(), exam: result.get_exam().key().to_string(), - user: result.get_user().key().to_string(), + user: PersonRef::resolve(people, result.get_user()), mark: result.get_mark().as_i64(), - graded_by: result.get_graded_by().key().to_string(), + graded_by: PersonRef::resolve(people, result.get_graded_by()), } } } @@ -133,8 +186,11 @@ async fn get_exam( } /// Update an exam. Requires teacher+ and management rights over the exam's -/// course (its creator, or manager/admin). Omitted fields keep their value; the -/// course itself is not updatable. +/// 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 and duration +/// stay editable so a running exam can be extended live. #[utoipa::path( patch, path = "/{id}", @@ -144,10 +200,11 @@ async fn get_exam( request_body = UpdateExam, responses( (status = 200, description = "Updated exam", body = ExamResponse), - (status = 400, description = "Invalid fields, kind, or weight", body = ErrorResponse), + (status = 400, description = "Invalid fields, kind, weight, or schedule", body = ErrorResponse), (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), ), )] async fn update_exam( @@ -183,14 +240,46 @@ async fn update_exam( None => exam.get_weight(), }; + // Merge the schedule (set / clear / keep per field), then re-validate it + // as a unit — a PATCH can't leave a half-schedule behind. + 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) => update.map(Timestamp::from_millis), + None => exam.get_starts_at(), + }; + let ends_at = match req.ends_at { + Some(update) => update.map(Timestamp::from_millis), + 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)?; + + // Switching sync <-> async (or unscheduling) would silently rewrite the + // deadline rules under students who already sat down; extending times is + // the supported live adjustment instead. + 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", + )); + } + let updated = exam - .update(title, description, kind, weight, &st.db) + .update(title, description, kind, weight, schedule, &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 result rows. +/// course (its creator, or manager/admin). Cascades the exam's result and +/// attempt rows. #[utoipa::path( delete, path = "/{id}", @@ -270,12 +359,12 @@ async fn grade( } // Target user must exist. - if User::read(&target, &st.db).await?.is_none() { + 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", })); - } + }; // ... and be enrolled in the exam's course. if Enrollment::read_for_user(exam.get_course(), &target, &st.db) @@ -289,7 +378,8 @@ async fn grade( } let result = ExamResult::grade(&exam_id, &target, mark, teacher.get_id(), &st.db).await?; - Ok(Json(ExamResultResponse::new(&result))) + let people = PersonRef::map_of(&[&target_user, &teacher]); + Ok(Json(ExamResultResponse::new(&result, &people))) } /// List every result for an exam. Requires teacher+ — students read only their @@ -318,7 +408,19 @@ async fn list_results( .await? .ok_or(AppError::NotFound)?; let results = ExamResult::list_for_exam(&exam_id, &st.db).await?; - Ok(Json(results.iter().map(ExamResultResponse::new).collect())) + 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(), + )) } /// The current user's own result for an exam. Any authenticated user may read @@ -343,7 +445,12 @@ async fn my_result( let result = ExamResult::read_for_user(&ExamId::from_key(&id), user.get_id(), &st.db) .await? .ok_or(AppError::NotFound)?; - Ok(Json(ExamResultResponse::new(&result))) + 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 @@ -422,3 +529,1045 @@ async fn exam_statistics( max: marks.iter().max().copied(), })) } + +// ---- attempts ------------------------------------------------------------- +// A scheduled exam is *sat*: starting an attempt is the live-attendance +// signal, finishing is the submission. Deadlines are judged only by the +// server clock — clients sync via `GET /time`. + +/// A student's view of their 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, + /// When the attempt started, UTC unix-milliseconds. + started_at: i64, + /// Submission instant; `null` while running (or expired unsubmitted). + finished_at: Option, + /// `in_progress` | `submitted` | `expired`. + #[schema(example = "in_progress")] + status: String, + /// When the attempt closes: `ends_at` for sync, `min(started_at + + /// duration_ms, ends_at)` for async. Recomputed live from the exam's + /// current schedule. + deadline: Option, + /// `deadline - now`, floored at 0; `null` unless in progress. + 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 { + fn new( + attempt: &ExamAttempt, + exam: &Exam, + mark: Option, + people: &HashMap, + answered: u64, + question_count: 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()), + started_at: attempt.get_started_at().as_millis(), + finished_at: attempt.get_finished_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, + db: &Database, +) -> Result<(u64, u64), AppError> { + let answered = ExamAnswer::list_for_exam_user(exam, user, db).await?.len() as u64; + let question_count = ExamQuestion::list_for_exam(exam, db).await?.len() as u64; + Ok((answered, question_count)) +} + +/// The exam's window, or a 409 when it isn't scheduled at all. Enrollment and +/// window checks for the caller are the caller's own state — hence `Conflict` +/// (a state problem), not validation. +fn window_of(exam: &Exam) -> Result<(Timestamp, Timestamp), AppError> { + match (exam.get_starts_at(), exam.get_ends_at()) { + (Some(starts), Some(ends)) => Ok((starts, ends)), + _ => Err(AppError::Conflict( + "this exam is not scheduled — there is nothing to sit", + )), + } +} + +/// Start (or resume) the caller's attempt at a scheduled exam. Requires +/// enrollment in the exam's course and the window to be open. Idempotent in +/// the useful direction: if an attempt already exists it is returned as-is +/// (`200` instead of `201`), so a reconnecting client gets its original clock +/// back — re-starting never resets the time. +#[utoipa::path( + post, + path = "/{id}/attempt", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 201, description = "Attempt started", body = AttemptResponse), + (status = 200, description = "Attempt already existed (unchanged)", body = AttemptResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse), + (status = 404, description = "Exam not found", body = ErrorResponse), + (status = 409, description = "Unscheduled exam, or outside the window", body = ErrorResponse), + ), +)] +async fn start_attempt( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result<(StatusCode, Json), AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let (starts_at, ends_at) = window_of(&exam)?; + if Enrollment::read_for_user(exam.get_course(), user.get_id(), &st.db) + .await? + .is_none() + { + return Err(AppError::Forbidden( + "you are not enrolled in this exam's course", + )); + } + let now = Timestamp::now(); + if now < starts_at { + return Err(AppError::Conflict("the exam has not started yet")); + } + if now >= ends_at { + return Err(AppError::Conflict("the exam has already ended")); + } + + let (attempt, created) = ExamAttempt::start(exam.get_id(), user.get_id(), &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(), &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, + Timestamp::now(), + )), + )) +} + +/// The caller's own attempt: status, deadline, remaining time, and mark once +/// graded — everything a student's live exam screen needs, judged by the +/// server clock. `404` until the 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 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_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(), &st.db).await?; + let people = PersonRef::map_of(&[&user]); + Ok(Json(AttemptResponse::new( + &attempt, + &exam, + mark, + &people, + answered, + question_count, + 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_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")); + } + + 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(), &st.db).await?; + let people = PersonRef::map_of(&[&user]); + Ok(Json(AttemptResponse::new( + &finished, + &exam, + mark, + &people, + answered, + question_count, + Timestamp::now(), + ))) +} + +// ---- live monitor --------------------------------------------------------- + +/// One roster row of the live exam monitor. +#[derive(Serialize, ToSchema)] +struct LiveStudentResponse { + user: PersonRef, + /// `not_started` | `in_progress` | `submitted` | `expired`. + #[schema(example = "in_progress")] + status: String, + started_at: Option, + finished_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, + not_started: 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?; + let attempts: HashMap = ExamAttempt::list_for_exam(exam.get_id(), db) + .await? + .into_iter() + .map(|attempt| (attempt.get_user().key().to_string(), attempt)) + .collect(); + 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. + let mut progress: HashMap = HashMap::new(); + for answer in ExamAnswer::list_for_exam(exam.get_id(), db).await? { + let entry = progress + .entry(answer.get_user().key().to_string()) + .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?; + + 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: status + .map_or("not_started", AttemptStatus::as_str) + .to_string(), + 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()), + 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"), + 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, time +/// each student has left, and marks as they land. Requires teacher+. For a +/// self-updating feed of the same shape, see `GET /exams/{id}/live/stream`. +#[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 = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "Exam not found", body = ErrorResponse), + ), +)] +async fn exam_live( + State(st): State, + _teacher: RequireTeacher, + Path(id): Path, +) -> Result, AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + Ok(Json(live_snapshot(&exam, &st.db).await?)) +} + +/// The live snapshot as a Server-Sent-Events stream: one `snapshot` event +/// (the `ExamLiveResponse` JSON) immediately on connect and then every couple +/// of seconds, so attendance, remaining time, submissions, and marks update +/// without polling. Requires teacher+. Consume with `EventSource` (cookies +/// ride along on same-site / credentialed requests). If the exam disappears +/// mid-stream an `error` event is sent instead. +#[utoipa::path( + get, + path = "/{id}/live/stream", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 200, description = "SSE feed of `snapshot` events (`ExamLiveResponse` as JSON)", content_type = "text/event-stream"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "Exam not found", body = ErrorResponse), + ), +)] +async fn exam_live_stream( + State(st): State, + _teacher: RequireTeacher, + Path(id): Path, +) -> Result>>, AppError> { + let exam_id = ExamId::from_key(&id); + // A missing exam is a 404 up front; after this the response is a stream. + Exam::read(&exam_id, &st.db) + .await? + .ok_or(AppError::NotFound)?; + + // First tick fires immediately, so the monitor paints on connect. The + // exam is re-read every tick: schedule edits (deadline extensions) show + // up mid-stream. + let interval = tokio::time::interval(Duration::from_secs(EXAM_LIVE_STREAM_INTERVAL_SECS)); + let stream = IntervalStream::new(interval).then(move |_| { + let db = st.db.clone(); + let exam_id = exam_id.clone(); + async move { + let snapshot = match Exam::read(&exam_id, &db).await { + Ok(Some(exam)) => live_snapshot(&exam, &db).await, + Ok(None) => Err(AppError::NotFound), + Err(err) => Err(err), + }; + match snapshot { + Ok(snapshot) => Event::default().event("snapshot").json_data(&snapshot), + // Exam deleted mid-stream or a db hiccup: say so without + // leaking internals and keep the stream alive — the client + // decides whether to hang on or close. + Err(err) => { + tracing::warn!("live exam stream snapshot failed: {err}"); + Event::default() + .event("error") + .json_data(serde_json::json!({ "error": "live snapshot unavailable" })) + } + } + } + }); + Ok(Sse::new(stream).keep_alive(KeepAlive::default())) +} + +// ---- 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 question itself. + #[schema(example = "What is 2 + 2?")] + text: String, + /// `choice` or `text`. + #[schema(example = "choice")] + kind: String, + /// This question's share of the auto-score, `1`–`100`. + #[schema(example = 10)] + points: i64, + /// The options of a `choice` question (2–10 of them); omit for `text`. + choices: Option>, + /// Zero-based index of the right option; required for `choice`, absent + /// for `text`. + #[schema(example = 1)] + correct: Option, +} + +#[derive(Deserialize, ToSchema)] +struct UpdateQuestion { + text: Option, + 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). + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option>)] + choices: Option>>, + /// Omit to keep; `null` to clear (text questions only). + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option)] + correct: Option>, +} + +/// A question as its author sees it — including the `correct` index. Never +/// serialized to students; they get [`AttemptQuestionResponse`]. +#[derive(Serialize, ToSchema)] +struct QuestionResponse { + id: String, + exam: String, + text: String, + /// `choice` or `text`. + #[schema(example = "choice")] + kind: String, + points: i64, + choices: Option>, + /// Zero-based index of the right option (`choice` questions only). + correct: Option, +} + +impl QuestionResponse { + fn new(question: &ExamQuestion) -> Self { + Self { + id: question.get_id().key().to_string(), + exam: question.get_exam().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: question + .get_choices() + .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()), + correct: question.get_correct(), + } + } +} + +/// 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) +} + +/// Add a question to an exam. Requires teacher+ and management rights over the +/// exam's course. `choice` questions carry 2–10 `choices` plus the `correct` +/// index; `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", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator (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 or a manager/admin can author questions", + )); + } + ensure_questions_editable(exam.get_id(), &st.db).await?; + + let text = QuestionText::try_new(&req.text)?; + let points = QuestionPoints::try_new(req.points)?; + let spec = QuestionSpec::try_new(QuestionKind::try_new(&req.kind)?, req.choices, req.correct)?; + let question = ExamQuestion::create(exam.get_id(), text, points, spec, &st.db).await?; + Ok((StatusCode::CREATED, Json(QuestionResponse::new(&question)))) +} + +/// The exam's full question list, `correct` indexes included. Requires +/// teacher+. Students read questions through `GET /exams/{id}/attempt/questions`. +#[utoipa::path( + get, + path = "/{id}/questions", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 200, description = "The exam's questions", body = [QuestionResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "Exam not found", body = ErrorResponse), + ), +)] +async fn list_questions( + State(st): State, + _teacher: RequireTeacher, + Path(id): Path, +) -> Result>, AppError> { + let exam_id = ExamId::from_key(&id); + Exam::read(&exam_id, &st.db) + .await? + .ok_or(AppError::NotFound)?; + let questions = ExamQuestion::list_for_exam(&exam_id, &st.db).await?; + Ok(Json(questions.iter().map(QuestionResponse::new).collect())) +} + +/// 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. 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", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator (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 or a manager/admin can edit questions", + )); + } + ensure_questions_editable(exam.get_id(), &st.db).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + + 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(), + }; + let choices = match req.choices { + Some(update) => update, + None => question + .get_choices() + .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()), + }; + let correct = match req.correct { + Some(update) => update, + None => question.get_correct(), + }; + let spec = QuestionSpec::try_new(kind, choices, correct)?; + + let updated = question.update(text, points, spec, &st.db).await?; + Ok(Json(QuestionResponse::new(&updated))) +} + +/// 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 (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 or a manager/admin can delete questions", + )); + } + ensure_questions_editable(exam.get_id(), &st.db).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + question.delete(&st.db).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 zero-based index (`choice` questions). + selected: Option, + /// The typed answer (`text` questions). + text: Option, + /// When this answer was last saved, UTC unix-milliseconds. + updated_at: i64, +} + +impl AnswerStateResponse { + fn new(answer: &ExamAnswer) -> Self { + Self { + selected: answer.get_selected(), + text: answer.get_text().map(|t| t.as_str().to_string()), + updated_at: answer.get_updated_at().as_millis(), + } + } +} + +/// A question as the sitting student sees it: no `correct` index, their own +/// saved answer embedded. +#[derive(Serialize, ToSchema)] +struct AttemptQuestionResponse { + id: String, + text: String, + /// `choice` or `text`. + #[schema(example = "choice")] + kind: String, + points: i64, + choices: 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 zero-based index — required for `choice` questions. + selected: Option, + /// The typed answer — required for `text` questions (empty clears the draft). + text: Option, +} + +#[derive(Serialize, ToSchema)] +struct AnswerSavedResponse { + question: String, + selected: Option, + text: Option, + /// Save instant by the server clock, UTC unix-milliseconds. + updated_at: i64, +} + +/// The caller's 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_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), + } +} + +/// Save one answer inside the caller's in-progress attempt — the whole write +/// path (attempt gate, question lookup, kind check, upsert), shared verbatim +/// by the REST handler and the WebSocket room 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 { + writable_attempt(exam, user, db).await?; + let question = question_of_exam(exam.get_id(), question_id, db).await?; + ExamAnswer::save(&question, user, selected, text, db).await +} + +/// The exam's questions as the sitting student sees them: `correct` stripped, +/// their own saved answers embedded. Requires 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 = 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)?; + // The question list is for sitting students; without an attempt there is + // nothing to sit behind — and no early peek at the questions. + ExamAttempt::read_for_user(exam.get_id(), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + + let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?; + let answers: HashMap = + ExamAnswer::list_for_exam_user(exam.get_id(), user.get_id(), &st.db) + .await? + .into_iter() + .map(|answer| (answer.get_question().key().to_string(), answer)) + .collect(); + Ok(Json( + questions + .iter() + .map(|question| AttemptQuestionResponse { + id: question.get_id().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: question + .get_choices() + .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()), + answer: answers + .get(question.get_id().key()) + .map(AnswerStateResponse::new), + }) + .collect(), + )) +} + +/// Save (or overwrite) one answer in the caller's in-progress attempt. +/// `choice` questions take `selected`; `text` questions take `text`. Rejected +/// once the attempt is submitted or its deadline has passed — the server +/// clock, not the client's, is the judge. +#[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 = 404, description = "No such exam, question, or attempt", body = ErrorResponse), + (status = 409, description = "Attempt already submitted, or time is up", 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)?; + 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(), + 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. 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+. +#[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 = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "No such exam, or the student has no attempt", body = ErrorResponse), + ), +)] +async fn attempt_answers( + State(st): State, + _teacher: 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 target = UserId::from_key(&target); + // No attempt means no answer sheet — a 404, not an empty one. + ExamAttempt::read_for_user(exam.get_id(), &target, &st.db) + .await? + .ok_or(AppError::NotFound)?; + + let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?; + let answers = ExamAnswer::list_for_exam_user(exam.get_id(), &target, &st.db).await?; + 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()], &st.db).await?; + Ok(Json(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(), + 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)), + }) + .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, + 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 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, +} diff --git a/src/web/mod.rs b/src/web/mod.rs index 1c22d3d..1698587 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -6,6 +6,7 @@ pub mod auth; pub mod courses; pub mod events; +pub mod exam_ws; pub mod exams; pub mod marks; pub mod notes; @@ -14,5 +15,18 @@ pub mod users; mod dto; mod extractor; -pub use dto::{CourseResponse, ExamResponse, UserResponse}; +pub use dto::{CourseResponse, ExamResponse, PersonRef, UserResponse, person_map}; pub use extractor::{CurrentUser, RequireAdmin, RequireTeacher}; + +use serde::{Deserialize, Deserializer}; + +/// Distinguishes an *absent* PATCH field from an explicit `null`: absent never +/// reaches the deserializer and stays `None` via `#[serde(default)]` (keep the +/// stored value); `null` or a value lands here as `Some(inner)` (clear or set). +pub(crate) fn set_or_clear<'de, D, T>(de: D) -> Result>, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + Option::::deserialize(de).map(Some) +} diff --git a/src/web/users.rs b/src/web/users.rs index 1538ad4..e456cbe 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -1,7 +1,7 @@ use axum::Json; -use axum::extract::{Path, State}; +use axum::extract::{Path, Query, State}; use serde::Deserialize; -use utoipa::ToSchema; +use utoipa::{IntoParams, ToSchema}; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; @@ -13,12 +13,13 @@ use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; use super::dto::Role as RoleSchema; -use super::{CurrentUser, RequireAdmin, UserResponse}; +use super::{CurrentUser, PersonRef, RequireAdmin, RequireTeacher, UserResponse}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() .routes(routes!(list_users)) .routes(routes!(update_my_profile)) + .routes(routes!(search_users)) .routes(routes!(get_user)) .routes(routes!(set_role)) .routes(routes!(update_user_profile)) @@ -90,6 +91,43 @@ async fn apply_profile( Ok(UserResponse::new(&updated)) } +#[derive(Deserialize, IntoParams)] +struct SearchUsers { + /// Case-insensitive fragment of a username, name, or surname. + q: String, +} + +/// Find users by username or name — backs the pickers (enroll, grade, mark +/// attendance). Requires teacher+. Returns at most 10 matches, and only +/// id/username/display name — no contact details. +#[utoipa::path( + get, + path = "/search", + tag = "users", + security(("session_cookie" = [])), + params(SearchUsers), + responses( + (status = 200, description = "Matching users, at most 10", body = [PersonRef]), + (status = 400, description = "Empty query", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + ), +)] +async fn search_users( + State(st): State, + _teacher: RequireTeacher, + Query(req): Query, +) -> Result>, AppError> { + if req.q.trim().is_empty() { + return Err(AppError::Validation(ValidationError::Invalid { + field: "q", + reason: "must not be empty", + })); + } + let users = User::search(&req.q, &st.db).await?; + Ok(Json(users.iter().map(PersonRef::new).collect())) +} + /// List every user with their role. Admin only. #[utoipa::path( get,