diff --git a/src/constant.rs b/src/constant.rs index 714b81f..321df28 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -69,14 +69,22 @@ pub const MAX_TERM_NAME_LEN: usize = 100; /// 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"]; +/// own `duration_ms` slice of it. `open`: no window — students sit anytime, +/// with an optional per-attempt `duration_ms` (absent = unlimited time). An +/// exam with no mode at all is an offline-graded draft and cannot be sat. +pub const EXAM_MODES: [&str; 3] = ["sync", "async", "open"]; -/// Inclusive bounds for an async exam's per-student duration, milliseconds -/// (1 minute to 24 hours). +/// Inclusive bounds for an exam's per-attempt duration, milliseconds +/// (1 minute to 24 hours). Required for `async`, optional for `open`. pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000; pub const MAX_EXAM_DURATION_MS: i64 = 24 * 60 * 60 * 1000; +/// Upper bound for an exam's attempt limit; `UNLIMITED_EXAM_ATTEMPTS` (zero) +/// is the wire-and-storage spelling of "no limit". A limit of 1 — the +/// default — is the classic single sitting. +pub const MAX_EXAM_ATTEMPTS: i64 = 100; +pub const UNLIMITED_EXAM_ATTEMPTS: i64 = 0; + /// Cadence of the live exam-monitor SSE stream (`GET /exams/{id}/live/stream`). pub const EXAM_LIVE_STREAM_INTERVAL_SECS: u64 = 2; diff --git a/src/database.rs b/src/database.rs index 88154da..7af80ab 100644 --- a/src/database.rs +++ b/src/database.rs @@ -27,7 +27,10 @@ pub const SETTINGS_TABLE: &str = "settings"; pub const TERM_TABLE: &str = "term"; /// SCHEMAFULL schema: every column is typed, references use `record<..>`. -/// Idempotent — safe to run on every boot. +/// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the +/// definitions, the backfill `UPDATE ... WHERE = NONE` lines only +/// touch rows written before their column existed, and `REMOVE ... IF EXISTS` +/// retires schema (like the single-attempt unique index) exactly once. const MIGRATION: &str = " DEFINE TABLE IF NOT EXISTS user SCHEMAFULL; DEFINE FIELD IF NOT EXISTS username ON user TYPE string; @@ -123,14 +126,22 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS starts_at ON exam TYPE option; DEFINE FIELD IF NOT EXISTS ends_at ON exam TYPE option; DEFINE FIELD IF NOT EXISTS duration_ms ON exam TYPE option; + DEFINE FIELD IF NOT EXISTS max_attempts ON exam TYPE int DEFAULT 1; + DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true; DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course; + UPDATE exam SET max_attempts = 1 WHERE max_attempts = NONE; + UPDATE exam SET allow_rejoin = true WHERE allow_rejoin = NONE; DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL; DEFINE FIELD IF NOT EXISTS exam ON exam_attempt TYPE record; DEFINE FIELD IF NOT EXISTS user ON exam_attempt TYPE record; + DEFINE FIELD IF NOT EXISTS seq ON exam_attempt TYPE int DEFAULT 1; DEFINE FIELD IF NOT EXISTS started_at ON exam_attempt TYPE int; DEFINE FIELD IF NOT EXISTS finished_at ON exam_attempt TYPE option; - DEFINE INDEX IF NOT EXISTS exam_attempt_exam_user ON exam_attempt FIELDS exam, user UNIQUE; + DEFINE FIELD IF NOT EXISTS left_at ON exam_attempt TYPE option; + UPDATE exam_attempt SET seq = 1 WHERE seq = NONE; + REMOVE INDEX IF EXISTS exam_attempt_exam_user ON TABLE exam_attempt; + DEFINE INDEX IF NOT EXISTS exam_attempt_exam_user_seq ON exam_attempt FIELDS exam, user, seq UNIQUE; DEFINE INDEX IF NOT EXISTS exam_attempt_exam ON exam_attempt FIELDS exam; DEFINE TABLE IF NOT EXISTS exam_question SCHEMAFULL; diff --git a/src/domain/exam.rs b/src/domain/exam.rs index c8a88df..9cb76be 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -1,15 +1,15 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; -use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN}; +use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS}; 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_duration, validate_exam_mode, validate_optional, validate_required, - validate_weight, + validate_attempt_limit, validate_exam_duration, validate_exam_mode, validate_optional, + validate_required, validate_weight, }; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -104,8 +104,9 @@ 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`). +/// A validated exam mode: `sync` (everyone sits inside one fixed window), +/// `async` (each student starts inside the window and gets `duration_ms`), or +/// `open` (no window — sit anytime, with an optional per-attempt duration). #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ExamMode(String); @@ -120,7 +121,8 @@ impl ExamMode { } } -/// A validated per-student time budget for an `async` exam, milliseconds. +/// A validated per-attempt time budget, milliseconds. Required for an `async` +/// exam, optional for an `open` one (absent = unlimited time). #[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] pub struct ExamDuration(i64); @@ -135,17 +137,51 @@ impl ExamDuration { } } +/// How many attempts a student gets at an exam. `0` means unlimited — the +/// same spelling on the wire and in storage; `1` (the default) is the classic +/// single sitting. Editable live: raising it mid-exam grants retakes, and +/// lowering it only blocks *future* starts (existing attempts stand). +#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] +pub struct ExamAttemptLimit(i64); + +impl ExamAttemptLimit { + pub fn try_new(value: i64) -> Result { + validate_attempt_limit(value)?; + Ok(Self(value)) + } + + /// The single-sitting default for exams created without a limit. + pub fn single() -> Self { + Self(1) + } + + pub fn as_i64(&self) -> i64 { + self.0 + } + + pub fn is_unlimited(&self) -> bool { + self.0 == UNLIMITED_EXAM_ATTEMPTS + } + + /// Whether a student who already used `used` attempts may start another. + pub fn allows_another(&self, used: usize) -> bool { + self.is_unlimited() || (used as 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), +/// - no mode → no `starts_at`/`ends_at`/`duration_ms` (an offline-graded +/// draft; 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`. +/// - `open` → no window; `duration_ms` optional (a student who starts at `t` +/// gets until `t + duration_ms`, or forever when absent), +/// - `ends_at` strictly after `starts_at` whenever the window exists. #[derive(Debug, Clone, Default)] pub struct ExamSchedule { mode: Option, @@ -167,10 +203,20 @@ impl ExamSchedule { 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)", + "starts_at, ends_at, and duration_ms require a mode (sync, async, or open)", )); } } + Some(m) if m.as_str() == "open" => { + if starts_at.is_some() || ends_at.is_some() { + return Err(invalid( + "starts_at", + "an open exam has no window — drop starts_at/ends_at or pick sync/async", + )); + } + // `duration_ms` stays optional: limited time per attempt when + // set, unlimited when absent. + } Some(m) => { if starts_at.is_none() { return Err(invalid("starts_at", "required for a scheduled exam")); @@ -186,7 +232,10 @@ impl ExamSchedule { return Err(invalid("duration_ms", "required for an async exam")); } ("sync", true) => { - return Err(invalid("duration_ms", "only async exams take a duration")); + return Err(invalid( + "duration_ms", + "only async and open exams take a duration", + )); } _ => {} } @@ -221,6 +270,10 @@ pub struct Exam { starts_at: Option, ends_at: Option, duration_ms: Option, + // Attempt policy. Rows predating these columns are backfilled by the boot + // migration (limit 1, rejoin open), so reads never see them missing. + max_attempts: ExamAttemptLimit, + allow_rejoin: bool, } impl Exam { @@ -268,6 +321,16 @@ impl Exam { self.duration_ms } + pub fn get_max_attempts(&self) -> ExamAttemptLimit { + self.max_attempts + } + + /// Whether a student who left the exam room may come back into it (and + /// keep saving answers). The teacher can flip this live. + pub fn get_allow_rejoin(&self) -> bool { + self.allow_rejoin + } + /// 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. @@ -296,6 +359,8 @@ impl Exam { kind: ExamKind, weight: ExamWeight, schedule: ExamSchedule, + max_attempts: ExamAttemptLimit, + allow_rejoin: bool, db: &Database, ) -> Result { let exam = Exam { @@ -310,6 +375,8 @@ impl Exam { starts_at: schedule.starts_at, ends_at: schedule.ends_at, duration_ms: schedule.duration_ms, + max_attempts, + allow_rejoin, }; let created: Option = db.create(exam.id.record()).content(exam).await?; created.ok_or_else(|| AppError::Internal("failed to create exam".into())) @@ -356,6 +423,10 @@ impl Exam { // `course` is deliberately not updatable — moving an exam between courses // would strand results of students not enrolled in the target course. + #[expect( + clippy::too_many_arguments, + reason = "mirrors the sibling entities' update(field, field, ..) shape" + )] pub async fn update( mut self, title: ExamTitle, @@ -363,6 +434,8 @@ impl Exam { kind: ExamKind, weight: ExamWeight, schedule: ExamSchedule, + max_attempts: ExamAttemptLimit, + allow_rejoin: bool, db: &Database, ) -> Result { self.title = title; @@ -373,6 +446,8 @@ impl Exam { self.starts_at = schedule.starts_at; self.ends_at = schedule.ends_at; self.duration_ms = schedule.duration_ms; + self.max_attempts = max_attempts; + self.allow_rejoin = allow_rejoin; let updated: Option = db.update(self.id.record()).content(self).await?; updated.ok_or(AppError::NotFound) } @@ -441,12 +516,34 @@ mod tests { #[tokio::test] async fn mode_must_be_known() { - for mode in ["sync", "async"] { + for mode in ["sync", "async", "open"] { assert_eq!(ExamMode::try_new(mode).unwrap().as_str(), mode); } assert!(ExamMode::try_new("live").is_err()); } + #[tokio::test] + async fn attempt_limit_counts_or_never_runs_out() { + let single = ExamAttemptLimit::single(); + assert_eq!(single.as_i64(), 1); + assert!(!single.is_unlimited()); + assert!(single.allows_another(0)); + assert!(!single.allows_another(1)); + + let three = ExamAttemptLimit::try_new(3).unwrap(); + assert!(three.allows_another(2)); + assert!(!three.allows_another(3)); + assert!(!three.allows_another(4)); + + let unlimited = ExamAttemptLimit::try_new(0).unwrap(); + assert!(unlimited.is_unlimited()); + assert!(unlimited.allows_another(0)); + assert!(unlimited.allows_another(10_000)); + + assert!(ExamAttemptLimit::try_new(-1).is_err()); + assert!(ExamAttemptLimit::try_new(101).is_err()); + } + #[tokio::test] async fn schedule_invariants_hold() { let mode = |m| Some(ExamMode::try_new(m).unwrap()); @@ -469,6 +566,13 @@ mod tests { 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()); + // Open: no window, duration optional (limited or unlimited time). + assert!(ExamSchedule::try_new(mode("open"), None, None, None).is_ok()); + assert!(ExamSchedule::try_new(mode("open"), None, None, dur).is_ok()); + assert!(ExamSchedule::try_new(mode("open"), at(1), None, None).is_err()); + assert!(ExamSchedule::try_new(mode("open"), None, at(2), None).is_err()); + assert!(ExamSchedule::try_new(mode("open"), at(1), at(2), dur).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 index b850133..e6506f6 100644 --- a/src/domain/exam_answer.rs +++ b/src/domain/exam_answer.rs @@ -189,6 +189,21 @@ impl ExamAnswer { .check()?; Ok(result.take::>(0)?) } + + /// Drop one student's answers across an exam — a retake starts from a + /// blank sheet. + pub async fn delete_for_exam_user( + exam: &ExamId, + user: &UserId, + db: &Database, + ) -> Result<(), AppError> { + db.query("DELETE exam_answer WHERE exam = $ex AND user = $usr") + .bind(("ex", exam.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(()) + } } /// The choice-question score suggested by the machine: `earned` points from diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs index 30e3521..c272cfb 100644 --- a/src/domain/exam_attempt.rs +++ b/src/domain/exam_attempt.rs @@ -3,6 +3,7 @@ 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::exam_answer::ExamAnswer; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -11,15 +12,20 @@ use crate::error::AppError; 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 + /// A deterministic id for the (exam, user, seq) triple. The same triple + /// always maps to the same record id, so sitting `seq` exists at most once + /// by construction — a concurrent double "start" races on the same id and + /// exactly one create wins. The first sitting keeps the historical + /// `{exam}_{user}` shape (rows written before retakes existed stay + /// addressable); later sittings append their number. ULID keys are /// alphanumeric, so `_` is an unambiguous joiner. - pub fn composite(exam: &ExamId, user: &UserId) -> Self { - Self(RecordId::new( - EXAM_ATTEMPT_TABLE, - format!("{}_{}", exam.key(), user.key()), - )) + pub fn composite(exam: &ExamId, user: &UserId, seq: i64) -> Self { + let key = if seq == 1 { + format!("{}_{}", exam.key(), user.key()) + } else { + format!("{}_{}_{}", exam.key(), user.key(), seq) + }; + Self(RecordId::new(EXAM_ATTEMPT_TABLE, key)) } pub fn record(&self) -> RecordId { @@ -57,16 +63,19 @@ impl AttemptStatus { } } -/// 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. +/// One student's sitting of an exam: starting is the live-attendance signal, +/// `finished_at` the submission. `seq` numbers the sittings (1, 2, …) when the +/// exam allows retakes; `left_at` marks a student who walked out of the exam +/// room mid-attempt. Grading stays a separate `exam_result` row. #[derive(Debug, Clone, SurrealValue)] pub struct ExamAttempt { id: ExamAttemptId, exam: ExamId, user: UserId, + seq: i64, started_at: Timestamp, finished_at: Option, + left_at: Option, } impl ExamAttempt { @@ -82,6 +91,11 @@ impl ExamAttempt { &self.user } + /// Which sitting this is — 1 for the first attempt, counting up. + pub fn get_seq(&self) -> i64 { + self.seq + } + pub fn get_started_at(&self) -> Timestamp { self.started_at } @@ -90,22 +104,33 @@ impl ExamAttempt { self.finished_at } + /// When the student left the exam room (WebSocket closed mid-attempt); + /// `None` while they're in it, or if they never used the room. Gates + /// nothing by itself — the exam's `allow_rejoin` decides what it means. + pub fn get_left_at(&self) -> Option { + self.left_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. + /// (never stored): the earlier of the window's `ends_at` and `started_at + + /// duration_ms`, whichever of the two exists. Recomputing on every read + /// means a teacher extending `ends_at` (or `duration_ms`) mid-exam moves + /// every deadline live. `None` for an open exam without a duration — such + /// an attempt only ends by submission. 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( + let by_duration = exam.get_duration_ms().map(|duration| { + Timestamp::from_millis( self.started_at .as_millis() .saturating_add(duration.as_millis()), - )), - None => ends_at, - }) + ) + }); + match (exam.get_ends_at(), by_duration) { + (Some(ends_at), Some(cap)) => Some(ends_at.min(cap)), + (Some(ends_at), None) => Some(ends_at), + (None, Some(cap)) => Some(cap), + (None, None) => None, + } } /// Status judged at `now` (one clock read per snapshot, shared across rows). @@ -120,32 +145,59 @@ impl ExamAttempt { } /// 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. + /// whether it was newly created. + /// + /// - A still-running latest attempt is returned untouched, so a + /// reconnecting client gets its original clock back instead of a reset — + /// re-"starting" can never buy more time. + /// - A terminal latest attempt (submitted or expired) starts sitting + /// `seq + 1` if the exam's `max_attempts` allows another, and is a + /// conflict otherwise. A retake begins from a blank sheet: the student's + /// previous answers are wiped first. Wiping *before* creating keeps the + /// race benign — until the new row exists, saves still hit the terminal + /// attempt and are rejected, so no fresh answer can be lost to the wipe. + /// + /// The composite id makes each create atomic; a concurrent double-start + /// races on the same seq, loses to the unique id, and reads the winner's + /// row. pub async fn start( - exam: &ExamId, + exam: &Exam, 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 attempts = Self::list_for_user(exam.get_id(), user, db).await?; + let next_seq = match attempts.first() { + None => 1, + Some(latest) if latest.status(exam, Timestamp::now()) == AttemptStatus::InProgress => { + return Ok((latest.clone(), false)); + } + Some(latest) => { + if !exam.get_max_attempts().allows_another(attempts.len()) { + return Err(AppError::Conflict( + "no attempts remaining — this exam's attempt limit is used up", + )); + } + latest.seq + 1 + } + }; + if next_seq > 1 { + ExamAnswer::delete_for_exam_user(exam.get_id(), user, db).await?; } let attempt = ExamAttempt { - id: ExamAttemptId::composite(exam, user), - exam: exam.clone(), + id: ExamAttemptId::composite(exam.get_id(), user, next_seq), + exam: exam.get_id().clone(), user: user.clone(), + seq: next_seq, started_at: Timestamp::now(), finished_at: None, + left_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? { + Err(err) => match Self::read_latest_for_user(exam.get_id(), user, db).await? { Some(existing) => Ok((existing, false)), None => Err(err.into()), }, @@ -160,14 +212,53 @@ impl ExamAttempt { updated.ok_or(AppError::NotFound) } - pub async fn read_for_user( + /// Stamp (or clear) the walked-out marker. The exam room sets it when the + /// student's socket closes mid-attempt and clears it when they come back. + pub async fn set_left( + mut self, + left_at: Option, + db: &Database, + ) -> Result { + self.left_at = left_at; + let updated: Option = db.update(self.id.record()).content(self).await?; + updated.ok_or(AppError::NotFound) + } + + /// The student's current sitting — the highest `seq` for the pair. All + /// reads that used to mean "the attempt" mean this now. + pub async fn read_latest_for_user( exam: &ExamId, user: &UserId, db: &Database, ) -> Result, AppError> { - Ok(db - .select(ExamAttemptId::composite(exam, user).record()) - .await?) + let mut result = db + .query( + "SELECT * FROM exam_attempt WHERE exam = $ex AND user = $usr + ORDER BY seq DESC LIMIT 1", + ) + .bind(("ex", exam.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } + + /// Every sitting of `user` at `exam`, newest first. + pub async fn list_for_user( + exam: &ExamId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM exam_attempt WHERE exam = $ex AND user = $usr + ORDER BY seq DESC", + ) + .bind(("ex", exam.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) } pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result, AppError> { diff --git a/src/validate.rs b/src/validate.rs index 504aa5e..796284d 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -2,10 +2,11 @@ //! the value, so an existing newtype is always valid (parse, don't validate). use crate::constant::{ - 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, USERNAME_SEPARATORS, + EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, 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, UNLIMITED_EXAM_ATTEMPTS, + USERNAME_SEPARATORS, }; use crate::error::ValidationError; @@ -63,7 +64,9 @@ pub fn validate_username(value: &str) -> Result<(), ValidationError> { let mut chars = value.chars().peekable(); while let Some(c) = chars.next() { if USERNAME_SEPARATORS.contains(&c) - && chars.peek().is_some_and(|n| USERNAME_SEPARATORS.contains(n)) + && chars + .peek() + .is_some_and(|n| USERNAME_SEPARATORS.contains(n)) { return Err(ValidationError::Invalid { field: "username", @@ -201,7 +204,18 @@ pub fn validate_exam_mode(value: &str) -> Result<(), ValidationError> { } else { Err(ValidationError::Invalid { field: "mode", - reason: "must be one of: sync, async", + reason: "must be one of: sync, async, open", + }) + } +} + +pub fn validate_attempt_limit(value: i64) -> Result<(), ValidationError> { + if value == UNLIMITED_EXAM_ATTEMPTS || (1..=MAX_EXAM_ATTEMPTS).contains(&value) { + Ok(()) + } else { + Err(ValidationError::Invalid { + field: "max_attempts", + reason: "must be between 1 and 100, or 0 for unlimited", }) } } @@ -374,13 +388,23 @@ mod tests { #[tokio::test] async fn exam_mode_rules() { - for mode in ["sync", "async"] { + for mode in ["sync", "async", "open"] { assert!(validate_exam_mode(mode).is_ok()); } assert!(validate_exam_mode("live").is_err()); assert!(validate_exam_mode("").is_err()); } + #[tokio::test] + async fn attempt_limit_rules() { + assert!(validate_attempt_limit(UNLIMITED_EXAM_ATTEMPTS).is_ok()); + for limit in [1, 2, 50, MAX_EXAM_ATTEMPTS] { + assert!(validate_attempt_limit(limit).is_ok()); + } + assert!(validate_attempt_limit(-1).is_err()); + assert!(validate_attempt_limit(MAX_EXAM_ATTEMPTS + 1).is_err()); + } + #[tokio::test] async fn exam_duration_rules() { assert!(validate_exam_duration(MIN_EXAM_DURATION_MS).is_ok()); diff --git a/src/web/courses.rs b/src/web/courses.rs index 8574abb..a62c0fb 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -13,7 +13,8 @@ use crate::domain::course::{Course, CourseDescription, CourseId, CourseTitle}; use crate::domain::course_session::{CourseSession, SessionTopic}; use crate::domain::enrollment::Enrollment; use crate::domain::exam::{ - Exam, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, ExamWeight, + Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, + ExamTitle, ExamWeight, }; use crate::domain::role::Role; use crate::domain::settings::Settings; @@ -80,22 +81,29 @@ 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. + /// `sync` (one fixed window for everyone), `async` (each student starts + /// inside the window and gets `duration_ms`), or `open` (no window — sit + /// anytime). Omit for an offline-graded draft that cannot be sat. #[schema(example = "sync")] mode: Option, - /// Window open, UTC unix-milliseconds. Required with `mode`; must not be - /// in the past. + /// Window open, UTC unix-milliseconds. Required for `sync`/`async`, + /// forbidden for `open`; must not be in the past. #[schema(example = 1_900_000_000_000_i64)] starts_at: Option, - /// Window close, UTC unix-milliseconds. Required with `mode`; must not be - /// in the past. + /// Window close, UTC unix-milliseconds. Required for `sync`/`async`, + /// forbidden for `open`; must not be in the past. ends_at: Option, - /// Per-student time budget, milliseconds — required for (and exclusive to) - /// `async` exams. + /// Per-attempt time budget, milliseconds — required for `async`, optional + /// for `open` (omit for unlimited time), forbidden for `sync`. #[schema(example = 5_400_000_i64)] duration_ms: Option, + /// How many attempts each student gets, `1`–`100`, or `0` for unlimited. + /// Defaults to `1` — the classic single sitting. + #[schema(example = 1)] + max_attempts: Option, + /// Whether a student who left the exam room may come back in and keep + /// answering. Defaults to `true`; editable live while the exam runs. + allow_rejoin: Option, } #[derive(Serialize, ToSchema)] @@ -525,6 +533,10 @@ async fn create_exam_in_course( ends_at, req.duration_ms.map(ExamDuration::try_new).transpose()?, )?; + let max_attempts = match req.max_attempts { + Some(limit) => ExamAttemptLimit::try_new(limit)?, + None => ExamAttemptLimit::single(), + }; let exam = Exam::create( user.get_id(), course.get_id(), @@ -533,6 +545,8 @@ async fn create_exam_in_course( kind, weight, schedule, + max_attempts, + req.allow_rejoin.unwrap_or(true), &st.db, ) .await?; diff --git a/src/web/dto.rs b/src/web/dto.rs index 10b9690..2c0aed0 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -198,7 +198,7 @@ impl SessionResponse { /// Public shape of an exam. Shared by `exams` (CRUD/results) and `courses` /// (in-course creation and listing). The schedule fields are all `null` for an -/// unscheduled (offline-graded) exam; see the create/update endpoints for the +/// offline-graded draft (no mode); see the create/update endpoints for the /// rules tying them together. #[derive(Serialize, ToSchema)] pub struct ExamResponse { @@ -209,15 +209,23 @@ pub struct ExamResponse { pub description: String, pub kind: String, pub weight: i64, - /// `sync` or `async`; `null` for an unscheduled exam. + /// `sync`, `async`, or `open`; `null` for an offline-graded draft + /// (not sittable). #[schema(example = "sync")] pub mode: Option, - /// Window open, UTC unix-milliseconds. + /// Window open, UTC unix-milliseconds (`sync`/`async`). pub starts_at: Option, - /// Window close, UTC unix-milliseconds. + /// Window close, UTC unix-milliseconds (`sync`/`async`). pub ends_at: Option, - /// Per-student time budget in milliseconds (async exams only). + /// Per-attempt time budget in milliseconds — required for `async`, + /// optional for `open` (`null` = unlimited time). pub duration_ms: Option, + /// How many attempts each student gets; `0` means unlimited. + #[schema(example = 1)] + pub max_attempts: i64, + /// Whether a student who left the exam room may come back in and keep + /// answering. Teachers can flip this live. + pub allow_rejoin: bool, } impl ExamResponse { @@ -234,6 +242,8 @@ impl ExamResponse { 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()), + max_attempts: exam.get_max_attempts().as_i64(), + allow_rejoin: exam.get_allow_rejoin(), } } } diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index f869974..dd89d90 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -8,7 +8,7 @@ //! Wire protocol (JSON text frames): //! //! server → client -//! - `{"type":"state", status, deadline, remaining_ms, now, answered, question_count}` +//! - `{"type":"state", status, attempt, 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"}` @@ -25,6 +25,12 @@ //! 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. +//! +//! The room is also the presence signal behind the rejoin policy: connecting +//! clears the attempt's `left_at`, and a socket that closes while the attempt +//! is still running stamps it. With the exam's `allow_rejoin` off, a stamped +//! `left_at` refuses re-entry (and any further saves, here or over REST) until +//! the teacher flips the door back open; finishing stays allowed. use std::time::Duration; @@ -46,7 +52,7 @@ 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}; +use crate::web::exams::{check_rejoin, save_answer_checked, writable_attempt}; /// What the client asked for, tagged by `type`. #[derive(Deserialize)] @@ -65,8 +71,10 @@ enum ClientMessage { /// Upgrade into the caller's exam room. All gates run *before* the upgrade so /// a rejected client gets a proper HTTP status instead of an instant close: -/// unknown exam (404), unscheduled (409), not enrolled (403), no attempt yet -/// (404 — `POST /exams/{id}/attempt` first), submitted or expired (409). +/// unknown exam (404), draft with no mode (409), not enrolled (403), no +/// attempt yet (404 — `POST /exams/{id}/attempt` first), submitted or expired +/// (409), left the room while rejoin is closed (409). Entering the room +/// clears the attempt's `left_at` — the student is back inside. pub async fn attempt_ws( State(st): State, CurrentUser(user): CurrentUser, @@ -76,9 +84,9 @@ pub async fn attempt_ws( let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - if exam.get_starts_at().is_none() { + if exam.get_mode().is_none() { return Err(AppError::Conflict( - "this exam is not scheduled — there is nothing to sit", + "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)", )); } if Enrollment::read_for_user(exam.get_course(), user.get_id(), &st.db) @@ -89,7 +97,11 @@ pub async fn attempt_ws( "you are not enrolled in this exam's course", )); } - writable_attempt(&exam, user.get_id(), &st.db).await?; + let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; + check_rejoin(&exam, &attempt)?; + if attempt.get_left_at().is_some() { + attempt.set_left(None, &st.db).await?; + } let user_id = user.get_id().clone(); Ok(ws.on_upgrade(move |socket| room(socket, st, exam, user_id))) @@ -128,6 +140,41 @@ async fn room(mut socket: WebSocket, st: AppState, exam: Exam, user: UserId) { // 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; + // The student is out of the room. If their attempt is still running, + // stamp the walk-out — with `allow_rejoin` off this is what locks further + // answering. Terminal exits (finished/expired) need no stamp. Best-effort: + // a failed stamp only means the walk-out goes unrecorded. + stamp_left(&exam_id, &user, &st.db).await; +} + +/// Stamp `left_at` on the student's latest attempt if it is still in +/// progress — re-reading both rows so a finish or expiry that raced the +/// socket close wins. +async fn stamp_left(exam_id: &ExamId, user: &UserId, db: &Database) { + let attempt = match Exam::read(exam_id, db).await { + Ok(Some(exam)) => match ExamAttempt::read_latest_for_user(exam.get_id(), user, db).await { + Ok(Some(attempt)) + if attempt.status(&exam, Timestamp::now()) == AttemptStatus::InProgress => + { + Some(attempt) + } + Ok(_) => None, + Err(err) => { + tracing::warn!("exam room could not read the attempt to stamp left_at: {err}"); + None + } + }, + Ok(None) => None, + Err(err) => { + tracing::warn!("exam room could not read the exam to stamp left_at: {err}"); + None + } + }; + if let Some(attempt) = attempt + && let Err(err) = attempt.set_left(Some(Timestamp::now()), db).await + { + tracing::warn!("exam room could not stamp left_at: {err}"); + } } /// Errors that end the room: the peer went away, or the attempt reached a @@ -189,7 +236,7 @@ async fn state_frame( 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) + let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user, db) .await? .ok_or(AppError::NotFound)?; let now = Timestamp::now(); @@ -205,6 +252,7 @@ async fn state_frame( let frame = json!({ "type": "state", "status": status.as_str(), + "attempt": attempt.get_seq(), "deadline": deadline.map(|t| t.as_millis()), "remaining_ms": remaining_ms, "now": now.as_millis(), diff --git a/src/web/exams.rs b/src/web/exams.rs index 32de503..be33838 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -17,8 +17,8 @@ use crate::database::Database; use crate::domain::course::Course; use crate::domain::enrollment::Enrollment; use crate::domain::exam::{ - Exam, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, ExamSchedule, ExamTitle, - ExamWeight, + Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, + ExamSchedule, ExamTitle, ExamWeight, }; use crate::domain::exam_answer::{ExamAnswer, auto_score}; use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt}; @@ -70,8 +70,10 @@ 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. + /// `sync`, `async`, or `open`. Omit to keep the current mode; send `null` + /// to turn the exam back into an offline draft. Frozen once anyone has + /// started an attempt. Switching to `open` requires clearing + /// `starts_at`/`ends_at` in the same request. #[serde(default, deserialize_with = "set_or_clear")] #[schema(value_type = Option)] mode: Option>, @@ -86,11 +88,19 @@ struct UpdateExam { #[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. + /// Per-attempt budget, milliseconds (`async`, or optionally `open`). Omit + /// to keep; `null` to clear. Changing it mid-exam moves every running + /// attempt's deadline. #[serde(default, deserialize_with = "set_or_clear")] #[schema(value_type = Option)] duration_ms: Option>, + /// Attempt limit: `1`–`100`, or `0` for unlimited. Omit to keep. Editable + /// live — raising it grants retakes on the spot; lowering it only blocks + /// future starts. + max_attempts: Option, + /// Whether students who left the exam room may come back in. Omit to + /// keep. Editable live — the teacher's door handle for the running room. + allow_rejoin: Option, } #[derive(Deserialize, ToSchema)] @@ -210,8 +220,9 @@ async fn get_exam( /// 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. +/// `mode` is frozen once anyone has started an attempt — times, duration, +/// `max_attempts`, and `allow_rejoin` stay editable so a running exam can be +/// extended, granted retakes, or have its rejoin door opened live. #[utoipa::path( patch, path = "/{id}", @@ -297,10 +308,16 @@ async fn update_exam( None => exam.get_duration_ms(), }; let schedule = ExamSchedule::try_new(mode, starts_at, ends_at, duration_ms)?; + let max_attempts = match req.max_attempts { + Some(limit) => ExamAttemptLimit::try_new(limit)?, + None => exam.get_max_attempts(), + }; + let allow_rejoin = req.allow_rejoin.unwrap_or_else(|| exam.get_allow_rejoin()); - // 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. + // Switching sync <-> async <-> open (or back to a draft) would silently + // rewrite the deadline rules under students who already sat down; + // extending times, the attempt limit, and the rejoin door are the + // supported live adjustments 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? { @@ -310,7 +327,16 @@ async fn update_exam( } let updated = exam - .update(title, description, kind, weight, schedule, &st.db) + .update( + title, + description, + kind, + weight, + schedule, + max_attempts, + allow_rejoin, + &st.db, + ) .await?; Ok(Json(ExamResponse::new(&updated))) } @@ -581,29 +607,44 @@ async fn exam_statistics( } // ---- 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. +// A sittable exam (sync, async, or open mode) is *sat*: starting an attempt +// is the live-attendance signal, finishing is the submission. The exam's +// `max_attempts` (0 = unlimited) says how many sittings each student gets; +// re-posting resumes a running attempt and mints the next sitting once the +// last one is over. Deadlines are judged only by the server clock — clients +// sync via `GET /time`. + +/// A student's view of their (latest) attempt. `now` is echoed so clients can +/// render countdowns without trusting the device clock. #[derive(Serialize, ToSchema)] struct AttemptResponse { id: String, exam: String, user: PersonRef, + /// Which sitting this is — 1 for the first attempt, counting up. + attempt: i64, + /// How many sittings the caller has used, this one included. + attempts_used: u64, + /// The exam's attempt limit; `0` means unlimited. + max_attempts: i64, /// When the attempt started, UTC unix-milliseconds. started_at: i64, /// Submission instant; `null` while running (or expired unsubmitted). finished_at: Option, + /// When the student left the exam room mid-attempt; `null` while inside + /// (or if they never used the room). With `allow_rejoin` off, a set + /// `left_at` locks further answering until the teacher reopens the door. + left_at: Option, /// `in_progress` | `submitted` | `expired`. #[schema(example = "in_progress")] status: String, - /// When the attempt closes: `ends_at` for sync, `min(started_at + - /// duration_ms, ends_at)` for async. Recomputed live from the exam's - /// current schedule. + /// When the attempt closes: the earlier of the window's `ends_at` and + /// `started_at + duration_ms` (whichever exists). Recomputed live from + /// the exam's current schedule; `null` for an open exam without a + /// duration — such an attempt only ends by submission. deadline: Option, - /// `deadline - now`, floored at 0; `null` unless in progress. + /// `deadline - now`, floored at 0; `null` unless in progress with a + /// deadline. remaining_ms: Option, /// The caller's mark, once graded. mark: Option, @@ -616,6 +657,10 @@ struct AttemptResponse { } impl AttemptResponse { + #[expect( + clippy::too_many_arguments, + reason = "a flat view over attempt + exam + progress; a builder would obscure it" + )] fn new( attempt: &ExamAttempt, exam: &Exam, @@ -623,6 +668,7 @@ impl AttemptResponse { people: &HashMap, answered: u64, question_count: u64, + attempts_used: u64, now: Timestamp, ) -> Self { let status = attempt.status(exam, now); @@ -634,8 +680,12 @@ impl AttemptResponse { id: attempt.get_id().key().to_string(), exam: attempt.get_exam().key().to_string(), user: PersonRef::resolve(people, attempt.get_user()), + attempt: attempt.get_seq(), + attempts_used, + max_attempts: exam.get_max_attempts().as_i64(), started_at: attempt.get_started_at().as_millis(), finished_at: attempt.get_finished_at().map(|t| t.as_millis()), + left_at: attempt.get_left_at().map(|t| t.as_millis()), status: status.as_str().to_string(), deadline: deadline.map(|t| t.as_millis()), remaining_ms, @@ -659,23 +709,31 @@ async fn attempt_progress( Ok((answered, question_count)) } -/// The exam's window, or a 409 when it isn't scheduled at all. Enrollment and +/// A 409 unless the exam can be sat at all: it needs a mode (`sync`, `async`, +/// or `open`) — a modeless exam is an offline-graded draft. Enrollment and /// window checks for the caller are the caller's own state — hence `Conflict` /// (a state problem), not validation. -fn 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", - )), +fn ensure_sittable(exam: &Exam) -> Result<(), AppError> { + if exam.get_mode().is_none() { + return Err(AppError::Conflict( + "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)", + )); } + Ok(()) +} + +/// How many sittings the caller has used at this exam. +async fn attempts_used(exam: &ExamId, user: &UserId, db: &Database) -> Result { + Ok(ExamAttempt::list_for_user(exam, user, db).await?.len() as u64) } -/// Start (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. +/// Start, resume, or retake the caller's attempt. Requires enrollment in the +/// exam's course, a sittable exam (`sync`/`async`/`open` mode), and — when a +/// window exists — the window to be open. A still-running attempt is returned +/// as-is (`200` instead of `201`), so a reconnecting client gets its original +/// clock back — re-starting never resets the time. Once the latest attempt is +/// submitted or expired, re-posting starts the next sitting (`201`, blank +/// answer sheet) while the exam's `max_attempts` (0 = unlimited) allows it. #[utoipa::path( post, path = "/{id}/attempt", @@ -683,12 +741,12 @@ fn window_of(exam: &Exam) -> Result<(Timestamp, Timestamp), AppError> { 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 = 201, description = "Attempt started (first sitting or a retake)", body = AttemptResponse), + (status = 200, description = "Running attempt resumed (unchanged)", body = AttemptResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not 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), + (status = 409, description = "Draft exam, outside the window, or no attempts remaining", body = ErrorResponse), ), )] async fn start_attempt( @@ -699,7 +757,7 @@ async fn start_attempt( let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - let (starts_at, ends_at) = window_of(&exam)?; + ensure_sittable(&exam)?; if Enrollment::read_for_user(exam.get_course(), user.get_id(), &st.db) .await? .is_none() @@ -709,18 +767,23 @@ async fn start_attempt( )); } let now = Timestamp::now(); - if now < starts_at { + if let Some(starts_at) = exam.get_starts_at() + && now < starts_at + { return Err(AppError::Conflict("the exam has not started yet")); } - if now >= ends_at { + if let Some(ends_at) = exam.get_ends_at() + && 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 (attempt, created) = ExamAttempt::start(&exam, 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 used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?; let people = PersonRef::map_of(&[&user]); let status = if created { StatusCode::CREATED @@ -736,14 +799,15 @@ async fn start_attempt( &people, answered, question_count, + used, 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. +/// The caller's own (latest) attempt: status, deadline, remaining time, and +/// mark once graded — everything a student's live exam screen needs, judged +/// by the server clock. `404` until an attempt is started. #[utoipa::path( get, path = "/{id}/attempt", @@ -751,7 +815,7 @@ async fn start_attempt( security(("session_cookie" = [])), params(("id" = String, Path, description = "Exam id")), responses( - (status = 200, description = "The caller's attempt", body = AttemptResponse), + (status = 200, description = "The caller's latest attempt", body = AttemptResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 404, description = "No such exam, or no attempt yet", body = ErrorResponse), ), @@ -764,13 +828,14 @@ async fn my_attempt( 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) + let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) .await? .ok_or(AppError::NotFound)?; let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) .await? .map(|r| r.get_mark()); let (answered, question_count) = attempt_progress(exam.get_id(), user.get_id(), &st.db).await?; + let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?; let people = PersonRef::map_of(&[&user]); Ok(Json(AttemptResponse::new( &attempt, @@ -779,6 +844,7 @@ async fn my_attempt( &people, answered, question_count, + used, Timestamp::now(), ))) } @@ -807,7 +873,7 @@ async fn finish_attempt( 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) + let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) .await? .ok_or(AppError::NotFound)?; if attempt.get_finished_at().is_some() { @@ -820,11 +886,14 @@ async fn finish_attempt( return Err(AppError::Conflict("time is up — the attempt has expired")); } + // Deliberately no rejoin check: a student locked out of the room may + // still submit what they saved — finishing answers nothing new. let finished = attempt.finish(&st.db).await?; let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) .await? .map(|r| r.get_mark()); let (answered, question_count) = attempt_progress(exam.get_id(), user.get_id(), &st.db).await?; + let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?; let people = PersonRef::map_of(&[&user]); Ok(Json(AttemptResponse::new( &finished, @@ -833,21 +902,29 @@ async fn finish_attempt( &people, answered, question_count, + used, Timestamp::now(), ))) } // ---- live monitor --------------------------------------------------------- -/// One roster row of the live exam monitor. +/// One roster row of the live exam monitor. The attempt fields describe the +/// student's *latest* sitting. #[derive(Serialize, ToSchema)] struct LiveStudentResponse { user: PersonRef, /// `not_started` | `in_progress` | `submitted` | `expired`. #[schema(example = "in_progress")] status: String, + /// Which sitting the shown attempt is (1, 2, …); `null` before the first. + attempt: Option, + /// How many sittings this student has used. + attempts_used: u64, started_at: Option, finished_at: Option, + /// When this student left the exam room mid-attempt; `null` while inside. + left_at: Option, /// When this student's attempt closes (server-authoritative). deadline: Option, /// Time this student has left, floored at 0; `null` unless in progress. @@ -890,11 +967,24 @@ struct ExamLiveResponse { 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(); + // Per student: their latest sitting (the one the monitor shows) plus how + // many they've used. + let mut attempts: HashMap = HashMap::new(); + let mut used: HashMap = HashMap::new(); + for attempt in ExamAttempt::list_for_exam(exam.get_id(), db).await? { + let key = attempt.get_user().key().to_string(); + *used.entry(key.clone()).or_insert(0) += 1; + match attempts.entry(key) { + std::collections::hash_map::Entry::Vacant(slot) => { + slot.insert(attempt); + } + std::collections::hash_map::Entry::Occupied(mut slot) => { + if attempt.get_seq() > slot.get().get_seq() { + slot.insert(attempt); + } + } + } + } let marks: HashMap = ExamResult::list_for_exam(exam.get_id(), db) .await? .iter() @@ -929,10 +1019,13 @@ async fn live_snapshot(exam: &Exam, db: &Database) -> Result Result { - let attempt = ExamAttempt::read_for_user(exam.get_id(), user, db) + let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user, db) .await? .ok_or(AppError::NotFound)?; match attempt.status(exam, Timestamp::now()) { @@ -1430,9 +1524,23 @@ pub(crate) async fn writable_attempt( } } +/// A 409 when the student has walked out of the exam room and the exam's +/// rejoin door is closed: no more answering (from anywhere) until the teacher +/// flips `allow_rejoin` back on. Finishing is deliberately exempt — see +/// `finish_attempt`. +pub(crate) fn check_rejoin(exam: &Exam, attempt: &ExamAttempt) -> Result<(), AppError> { + if attempt.get_left_at().is_some() && !exam.get_allow_rejoin() { + return Err(AppError::Conflict( + "you left the exam and rejoin is closed — ask your teacher to reopen it", + )); + } + Ok(()) +} + /// Save one answer inside the caller's in-progress attempt — the whole write -/// path (attempt gate, question lookup, kind check, upsert), shared verbatim -/// by the REST handler and the WebSocket room so the two can never drift. +/// path (attempt gate, rejoin 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, @@ -1441,7 +1549,8 @@ pub(crate) async fn save_answer_checked( text: Option, db: &Database, ) -> Result { - writable_attempt(exam, user, db).await?; + let attempt = writable_attempt(exam, user, db).await?; + check_rejoin(exam, &attempt)?; let question = question_of_exam(exam.get_id(), question_id, db).await?; ExamAnswer::save(&question, user, selected, text, db).await } @@ -1472,7 +1581,7 @@ async fn attempt_questions( .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) + ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) .await? .ok_or(AppError::NotFound)?; @@ -1505,7 +1614,8 @@ async fn attempt_questions( /// 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. +/// clock, not the client's, is the judge — and rejected while the student has +/// left the exam room with the exam's rejoin door closed. #[utoipa::path( post, path = "/{id}/attempt/answers", @@ -1518,7 +1628,7 @@ async fn attempt_questions( (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), + (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), ), )] async fn save_answer( @@ -1584,8 +1694,9 @@ async fn attempt_answers( )); } 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) + // No attempt means no answer sheet — a 404, not an empty one. Answers are + // always the latest sitting's: a retake starts from a blank sheet. + ExamAttempt::read_latest_for_user(exam.get_id(), &target, &st.db) .await? .ok_or(AppError::NotFound)?;