forge
Explore
Log in

Don't you dare go Hollow

Open mode, attempt limits, retakes, rejoin door

Browse files at this commit

9835fe704cd38f56b8ea262b192708b32e255250Ahmet Kaan GümüşParent: 9d57d6a
  • feat
    • open mode, attempt limits, retakes, rejoin door
Show full message
✨ feat(exams): open mode, attempt limits, retakes, rejoin door

Unscheduled exams were dead ends: attempts answered 409 "nothing to
sit", and every exam was hard-wired to a single sitting.

- mode "open": sittable anytime, no window; duration_ms optional per
  attempt (absent = unlimited time). Modeless exams stay offline
  drafts — still 409, so a student can't freeze a draft's questions.
- max_attempts (0 = unlimited, default 1): terminal attempts can be
  followed by numbered retakes that start from a blank answer sheet;
  the previous sitting's answers are wiped on the next start.
- allow_rejoin: live teacher toggle. Leaving the exam room (WS close
  mid-attempt) stamps left_at; with the door closed, re-entry and all
  saves 409 until reopened. Finish stays allowed either way.
- Attempt deadline generalized to min(ends_at, started_at + duration),
  either side optional; none = ends only by submission.

Boot migration backfills max_attempts/allow_rejoin/seq on existing
rows and replaces the single-attempt unique index (exam, user) with
(exam, user, seq) via REMOVE INDEX IF EXISTS. Sitting #1 keeps the
legacy {exam}_{user} record id, so pre-upgrade attempts stay valid.
src/constant.rsmodified+12 -4
@@ -69,14 +69,22 @@ pub const MAX_TERM_NAME_LEN: usize = 100;
69 69
70 /// The only accepted exam modes. `sync`: everyone sits the exam inside one70 /// The only accepted exam modes. `sync`: everyone sits the exam inside one
71 /// fixed window. `async`: each student starts inside the window and gets their71 /// fixed window. `async`: each student starts inside the window and gets their
72-/// own `duration_ms` slice of it.72+/// own `duration_ms` slice of it. `open`: no window — students sit anytime,
73-pub const EXAM_MODES: [&str; 2] = ["sync", "async"];73+/// with an optional per-attempt `duration_ms` (absent = unlimited time). An
74+/// exam with no mode at all is an offline-graded draft and cannot be sat.
75+pub const EXAM_MODES: [&str; 3] = ["sync", "async", "open"];
74 76
75-/// Inclusive bounds for an async exam's per-student duration, milliseconds77+/// Inclusive bounds for an exam's per-attempt duration, milliseconds
76-/// (1 minute to 24 hours).78+/// (1 minute to 24 hours). Required for `async`, optional for `open`.
77 pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000;79 pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000;
78 pub const MAX_EXAM_DURATION_MS: i64 = 24 * 60 * 60 * 1000;80 pub const MAX_EXAM_DURATION_MS: i64 = 24 * 60 * 60 * 1000;
79 81
82+/// Upper bound for an exam's attempt limit; `UNLIMITED_EXAM_ATTEMPTS` (zero)
83+/// is the wire-and-storage spelling of "no limit". A limit of 1 — the
84+/// default — is the classic single sitting.
85+pub const MAX_EXAM_ATTEMPTS: i64 = 100;
86+pub const UNLIMITED_EXAM_ATTEMPTS: i64 = 0;
87+
80 /// Cadence of the live exam-monitor SSE stream (`GET /exams/{id}/live/stream`).88 /// Cadence of the live exam-monitor SSE stream (`GET /exams/{id}/live/stream`).
81 pub const EXAM_LIVE_STREAM_INTERVAL_SECS: u64 = 2;89 pub const EXAM_LIVE_STREAM_INTERVAL_SECS: u64 = 2;
82 90
src/database.rsmodified+13 -2
@@ -27,7 +27,10 @@ pub const SETTINGS_TABLE: &str = "settings";
27 pub const TERM_TABLE: &str = "term";27 pub const TERM_TABLE: &str = "term";
28 28
29 /// SCHEMAFULL schema: every column is typed, references use `record<..>`.29 /// SCHEMAFULL schema: every column is typed, references use `record<..>`.
30-/// Idempotent — safe to run on every boot.30+/// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the
31+/// definitions, the backfill `UPDATE ... WHERE <field> = NONE` lines only
32+/// touch rows written before their column existed, and `REMOVE ... IF EXISTS`
33+/// retires schema (like the single-attempt unique index) exactly once.
31 const MIGRATION: &str = "34 const MIGRATION: &str = "
32 DEFINE TABLE IF NOT EXISTS user SCHEMAFULL;35 DEFINE TABLE IF NOT EXISTS user SCHEMAFULL;
33 DEFINE FIELD IF NOT EXISTS username ON user TYPE string;36 DEFINE FIELD IF NOT EXISTS username ON user TYPE string;
@@ -123,14 +126,22 @@ const MIGRATION: &str = "
123 DEFINE FIELD IF NOT EXISTS starts_at ON exam TYPE option<int>;126 DEFINE FIELD IF NOT EXISTS starts_at ON exam TYPE option<int>;
124 DEFINE FIELD IF NOT EXISTS ends_at ON exam TYPE option<int>;127 DEFINE FIELD IF NOT EXISTS ends_at ON exam TYPE option<int>;
125 DEFINE FIELD IF NOT EXISTS duration_ms ON exam TYPE option<int>;128 DEFINE FIELD IF NOT EXISTS duration_ms ON exam TYPE option<int>;
129+ DEFINE FIELD IF NOT EXISTS max_attempts ON exam TYPE int DEFAULT 1;
130+ DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true;
126 DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course;131 DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course;
132+ UPDATE exam SET max_attempts = 1 WHERE max_attempts = NONE;
133+ UPDATE exam SET allow_rejoin = true WHERE allow_rejoin = NONE;
127 134
128 DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL;135 DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL;
129 DEFINE FIELD IF NOT EXISTS exam ON exam_attempt TYPE record<exam>;136 DEFINE FIELD IF NOT EXISTS exam ON exam_attempt TYPE record<exam>;
130 DEFINE FIELD IF NOT EXISTS user ON exam_attempt TYPE record<user>;137 DEFINE FIELD IF NOT EXISTS user ON exam_attempt TYPE record<user>;
138+ DEFINE FIELD IF NOT EXISTS seq ON exam_attempt TYPE int DEFAULT 1;
131 DEFINE FIELD IF NOT EXISTS started_at ON exam_attempt TYPE int;139 DEFINE FIELD IF NOT EXISTS started_at ON exam_attempt TYPE int;
132 DEFINE FIELD IF NOT EXISTS finished_at ON exam_attempt TYPE option<int>;140 DEFINE FIELD IF NOT EXISTS finished_at ON exam_attempt TYPE option<int>;
133- DEFINE INDEX IF NOT EXISTS exam_attempt_exam_user ON exam_attempt FIELDS exam, user UNIQUE;141+ DEFINE FIELD IF NOT EXISTS left_at ON exam_attempt TYPE option<int>;
142+ UPDATE exam_attempt SET seq = 1 WHERE seq = NONE;
143+ REMOVE INDEX IF EXISTS exam_attempt_exam_user ON TABLE exam_attempt;
144+ DEFINE INDEX IF NOT EXISTS exam_attempt_exam_user_seq ON exam_attempt FIELDS exam, user, seq UNIQUE;
134 DEFINE INDEX IF NOT EXISTS exam_attempt_exam ON exam_attempt FIELDS exam;145 DEFINE INDEX IF NOT EXISTS exam_attempt_exam ON exam_attempt FIELDS exam;
135 146
136 DEFINE TABLE IF NOT EXISTS exam_question SCHEMAFULL;147 DEFINE TABLE IF NOT EXISTS exam_question SCHEMAFULL;
src/domain/exam.rsmodified+116 -12
@@ -1,15 +1,15 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 use ulid::Ulid;2 use ulid::Ulid;
3 3
4-use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN};4+use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS};
5 use crate::database::{Database, EXAM_TABLE};5 use crate::database::{Database, EXAM_TABLE};
6 use crate::domain::course::CourseId;6 use crate::domain::course::CourseId;
7 use crate::domain::timestamp::Timestamp;7 use crate::domain::timestamp::Timestamp;
8 use crate::domain::user::UserId;8 use crate::domain::user::UserId;
9 use crate::error::{AppError, ValidationError};9 use crate::error::{AppError, ValidationError};
10 use crate::validate::{10 use crate::validate::{
11- validate_exam_duration, validate_exam_mode, validate_optional, validate_required,11+ validate_attempt_limit, validate_exam_duration, validate_exam_mode, validate_optional,
12- validate_weight,12+ validate_required, validate_weight,
13 };13 };
14 14
15 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]15 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
@@ -104,8 +104,9 @@ impl ExamWeight {
104 }104 }
105 }105 }
106 106
107-/// A validated exam mode: `sync` (everyone sits inside one fixed window) or107+/// A validated exam mode: `sync` (everyone sits inside one fixed window),
108-/// `async` (each student starts inside the window and gets `duration_ms`).108+/// `async` (each student starts inside the window and gets `duration_ms`), or
109+/// `open` (no window — sit anytime, with an optional per-attempt duration).
109 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]110 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
110 pub struct ExamMode(String);111 pub struct ExamMode(String);
111 112
@@ -120,7 +121,8 @@ impl ExamMode {
120 }121 }
121 }122 }
122 123
123-/// A validated per-student time budget for an `async` exam, milliseconds.124+/// A validated per-attempt time budget, milliseconds. Required for an `async`
125+/// exam, optional for an `open` one (absent = unlimited time).
124 #[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)]126 #[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)]
125 pub struct ExamDuration(i64);127 pub struct ExamDuration(i64);
126 128
@@ -135,17 +137,51 @@ impl ExamDuration {
135 }137 }
136 }138 }
137 139
140+/// How many attempts a student gets at an exam. `0` means unlimited — the
141+/// same spelling on the wire and in storage; `1` (the default) is the classic
142+/// single sitting. Editable live: raising it mid-exam grants retakes, and
143+/// lowering it only blocks *future* starts (existing attempts stand).
144+#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)]
145+pub struct ExamAttemptLimit(i64);
146+
147+impl ExamAttemptLimit {
148+ pub fn try_new(value: i64) -> Result<Self, ValidationError> {
149+ validate_attempt_limit(value)?;
150+ Ok(Self(value))
151+ }
152+
153+ /// The single-sitting default for exams created without a limit.
154+ pub fn single() -> Self {
155+ Self(1)
156+ }
157+
158+ pub fn as_i64(&self) -> i64 {
159+ self.0
160+ }
161+
162+ pub fn is_unlimited(&self) -> bool {
163+ self.0 == UNLIMITED_EXAM_ATTEMPTS
164+ }
165+
166+ /// Whether a student who already used `used` attempts may start another.
167+ pub fn allows_another(&self, used: usize) -> bool {
168+ self.is_unlimited() || (used as i64) < self.0
169+ }
170+}
171+
138 /// The scheduling fields of an exam, validated as a unit — they only make172 /// The scheduling fields of an exam, validated as a unit — they only make
139 /// sense together. `try_new` is the sole constructor, so an `ExamSchedule` in173 /// sense together. `try_new` is the sole constructor, so an `ExamSchedule` in
140 /// hand always satisfies:174 /// hand always satisfies:
141 ///175 ///
142-/// - no mode → no `starts_at`/`ends_at`/`duration_ms` (an unscheduled exam is176+/// - no mode → no `starts_at`/`ends_at`/`duration_ms` (an offline-graded
143-/// graded offline; attempts are rejected),177+/// draft; attempts are rejected),
144 /// - `sync` → `starts_at` + `ends_at`, no duration (everyone's deadline is178 /// - `sync` → `starts_at` + `ends_at`, no duration (everyone's deadline is
145 /// `ends_at`),179 /// `ends_at`),
146 /// - `async` → `starts_at` + `ends_at` + `duration_ms` (a student who starts180 /// - `async` → `starts_at` + `ends_at` + `duration_ms` (a student who starts
147 /// at `t` gets until `min(t + duration_ms, ends_at)`),181 /// at `t` gets until `min(t + duration_ms, ends_at)`),
148-/// - `ends_at` strictly after `starts_at`.182+/// - `open` → no window; `duration_ms` optional (a student who starts at `t`
183+/// gets until `t + duration_ms`, or forever when absent),
184+/// - `ends_at` strictly after `starts_at` whenever the window exists.
149 #[derive(Debug, Clone, Default)]185 #[derive(Debug, Clone, Default)]
150 pub struct ExamSchedule {186 pub struct ExamSchedule {
151 mode: Option<ExamMode>,187 mode: Option<ExamMode>,
@@ -167,10 +203,20 @@ impl ExamSchedule {
167 if starts_at.is_some() || ends_at.is_some() || duration_ms.is_some() {203 if starts_at.is_some() || ends_at.is_some() || duration_ms.is_some() {
168 return Err(invalid(204 return Err(invalid(
169 "mode",205 "mode",
170- "starts_at, ends_at, and duration_ms require a mode (sync or async)",206+ "starts_at, ends_at, and duration_ms require a mode (sync, async, or open)",
171 ));207 ));
172 }208 }
173 }209 }
210+ Some(m) if m.as_str() == "open" => {
211+ if starts_at.is_some() || ends_at.is_some() {
212+ return Err(invalid(
213+ "starts_at",
214+ "an open exam has no window — drop starts_at/ends_at or pick sync/async",
215+ ));
216+ }
217+ // `duration_ms` stays optional: limited time per attempt when
218+ // set, unlimited when absent.
219+ }
174 Some(m) => {220 Some(m) => {
175 if starts_at.is_none() {221 if starts_at.is_none() {
176 return Err(invalid("starts_at", "required for a scheduled exam"));222 return Err(invalid("starts_at", "required for a scheduled exam"));
@@ -186,7 +232,10 @@ impl ExamSchedule {
186 return Err(invalid("duration_ms", "required for an async exam"));232 return Err(invalid("duration_ms", "required for an async exam"));
187 }233 }
188 ("sync", true) => {234 ("sync", true) => {
189- return Err(invalid("duration_ms", "only async exams take a duration"));235+ return Err(invalid(
236+ "duration_ms",
237+ "only async and open exams take a duration",
238+ ));
190 }239 }
191 _ => {}240 _ => {}
192 }241 }
@@ -221,6 +270,10 @@ pub struct Exam {
221 starts_at: Option<Timestamp>,270 starts_at: Option<Timestamp>,
222 ends_at: Option<Timestamp>,271 ends_at: Option<Timestamp>,
223 duration_ms: Option<ExamDuration>,272 duration_ms: Option<ExamDuration>,
273+ // Attempt policy. Rows predating these columns are backfilled by the boot
274+ // migration (limit 1, rejoin open), so reads never see them missing.
275+ max_attempts: ExamAttemptLimit,
276+ allow_rejoin: bool,
224 }277 }
225 278
226 impl Exam {279 impl Exam {
@@ -268,6 +321,16 @@ impl Exam {
268 self.duration_ms321 self.duration_ms
269 }322 }
270 323
324+ pub fn get_max_attempts(&self) -> ExamAttemptLimit {
325+ self.max_attempts
326+ }
327+
328+ /// Whether a student who left the exam room may come back into it (and
329+ /// keep saving answers). The teacher can flip this live.
330+ pub fn get_allow_rejoin(&self) -> bool {
331+ self.allow_rejoin
332+ }
333+
271 /// The stored schedule as the validated bundle (for merge-on-update).334 /// The stored schedule as the validated bundle (for merge-on-update).
272 /// Bypasses `try_new`: the fields were written through an `ExamSchedule`,335 /// Bypasses `try_new`: the fields were written through an `ExamSchedule`,
273 /// so the invariants already hold.336 /// so the invariants already hold.
@@ -296,6 +359,8 @@ impl Exam {
296 kind: ExamKind,359 kind: ExamKind,
297 weight: ExamWeight,360 weight: ExamWeight,
298 schedule: ExamSchedule,361 schedule: ExamSchedule,
362+ max_attempts: ExamAttemptLimit,
363+ allow_rejoin: bool,
299 db: &Database,364 db: &Database,
300 ) -> Result<Exam, AppError> {365 ) -> Result<Exam, AppError> {
301 let exam = Exam {366 let exam = Exam {
@@ -310,6 +375,8 @@ impl Exam {
310 starts_at: schedule.starts_at,375 starts_at: schedule.starts_at,
311 ends_at: schedule.ends_at,376 ends_at: schedule.ends_at,
312 duration_ms: schedule.duration_ms,377 duration_ms: schedule.duration_ms,
378+ max_attempts,
379+ allow_rejoin,
313 };380 };
314 let created: Option<Exam> = db.create(exam.id.record()).content(exam).await?;381 let created: Option<Exam> = db.create(exam.id.record()).content(exam).await?;
315 created.ok_or_else(|| AppError::Internal("failed to create exam".into()))382 created.ok_or_else(|| AppError::Internal("failed to create exam".into()))
@@ -356,6 +423,10 @@ impl Exam {
356 423
357 // `course` is deliberately not updatable — moving an exam between courses424 // `course` is deliberately not updatable — moving an exam between courses
358 // would strand results of students not enrolled in the target course.425 // would strand results of students not enrolled in the target course.
426+ #[expect(
427+ clippy::too_many_arguments,
428+ reason = "mirrors the sibling entities' update(field, field, ..) shape"
429+ )]
359 pub async fn update(430 pub async fn update(
360 mut self,431 mut self,
361 title: ExamTitle,432 title: ExamTitle,
@@ -363,6 +434,8 @@ impl Exam {
363 kind: ExamKind,434 kind: ExamKind,
364 weight: ExamWeight,435 weight: ExamWeight,
365 schedule: ExamSchedule,436 schedule: ExamSchedule,
437+ max_attempts: ExamAttemptLimit,
438+ allow_rejoin: bool,
366 db: &Database,439 db: &Database,
367 ) -> Result<Exam, AppError> {440 ) -> Result<Exam, AppError> {
368 self.title = title;441 self.title = title;
@@ -373,6 +446,8 @@ impl Exam {
373 self.starts_at = schedule.starts_at;446 self.starts_at = schedule.starts_at;
374 self.ends_at = schedule.ends_at;447 self.ends_at = schedule.ends_at;
375 self.duration_ms = schedule.duration_ms;448 self.duration_ms = schedule.duration_ms;
449+ self.max_attempts = max_attempts;
450+ self.allow_rejoin = allow_rejoin;
376 let updated: Option<Exam> = db.update(self.id.record()).content(self).await?;451 let updated: Option<Exam> = db.update(self.id.record()).content(self).await?;
377 updated.ok_or(AppError::NotFound)452 updated.ok_or(AppError::NotFound)
378 }453 }
@@ -441,12 +516,34 @@ mod tests {
441 516
442 #[tokio::test]517 #[tokio::test]
443 async fn mode_must_be_known() {518 async fn mode_must_be_known() {
444- for mode in ["sync", "async"] {519+ for mode in ["sync", "async", "open"] {
445 assert_eq!(ExamMode::try_new(mode).unwrap().as_str(), mode);520 assert_eq!(ExamMode::try_new(mode).unwrap().as_str(), mode);
446 }521 }
447 assert!(ExamMode::try_new("live").is_err());522 assert!(ExamMode::try_new("live").is_err());
448 }523 }
449 524
525+ #[tokio::test]
526+ async fn attempt_limit_counts_or_never_runs_out() {
527+ let single = ExamAttemptLimit::single();
528+ assert_eq!(single.as_i64(), 1);
529+ assert!(!single.is_unlimited());
530+ assert!(single.allows_another(0));
531+ assert!(!single.allows_another(1));
532+
533+ let three = ExamAttemptLimit::try_new(3).unwrap();
534+ assert!(three.allows_another(2));
535+ assert!(!three.allows_another(3));
536+ assert!(!three.allows_another(4));
537+
538+ let unlimited = ExamAttemptLimit::try_new(0).unwrap();
539+ assert!(unlimited.is_unlimited());
540+ assert!(unlimited.allows_another(0));
541+ assert!(unlimited.allows_another(10_000));
542+
543+ assert!(ExamAttemptLimit::try_new(-1).is_err());
544+ assert!(ExamAttemptLimit::try_new(101).is_err());
545+ }
546+
450 #[tokio::test]547 #[tokio::test]
451 async fn schedule_invariants_hold() {548 async fn schedule_invariants_hold() {
452 let mode = |m| Some(ExamMode::try_new(m).unwrap());549 let mode = |m| Some(ExamMode::try_new(m).unwrap());
@@ -469,6 +566,13 @@ mod tests {
469 assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), dur).is_ok());566 assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), dur).is_ok());
470 assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), None).is_err());567 assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), None).is_err());
471 568
569+ // Open: no window, duration optional (limited or unlimited time).
570+ assert!(ExamSchedule::try_new(mode("open"), None, None, None).is_ok());
571+ assert!(ExamSchedule::try_new(mode("open"), None, None, dur).is_ok());
572+ assert!(ExamSchedule::try_new(mode("open"), at(1), None, None).is_err());
573+ assert!(ExamSchedule::try_new(mode("open"), None, at(2), None).is_err());
574+ assert!(ExamSchedule::try_new(mode("open"), at(1), at(2), dur).is_err());
575+
472 // The window must be a real interval, whatever the mode.576 // The window must be a real interval, whatever the mode.
473 assert!(ExamSchedule::try_new(mode("sync"), at(2), at(2), None).is_err());577 assert!(ExamSchedule::try_new(mode("sync"), at(2), at(2), None).is_err());
474 assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err());578 assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err());
src/domain/exam_answer.rsmodified+15 -0
@@ -189,6 +189,21 @@ impl ExamAnswer {
189 .check()?;189 .check()?;
190 Ok(result.take::<Vec<ExamAnswer>>(0)?)190 Ok(result.take::<Vec<ExamAnswer>>(0)?)
191 }191 }
192+
193+ /// Drop one student's answers across an exam — a retake starts from a
194+ /// blank sheet.
195+ pub async fn delete_for_exam_user(
196+ exam: &ExamId,
197+ user: &UserId,
198+ db: &Database,
199+ ) -> Result<(), AppError> {
200+ db.query("DELETE exam_answer WHERE exam = $ex AND user = $usr")
201+ .bind(("ex", exam.record()))
202+ .bind(("usr", user.record()))
203+ .await?
204+ .check()?;
205+ Ok(())
206+ }
192 }207 }
193 208
194 /// The choice-question score suggested by the machine: `earned` points from209 /// The choice-question score suggested by the machine: `earned` points from
src/domain/exam_attempt.rsmodified+128 -37
@@ -3,6 +3,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
3 use crate::database::{Database, EXAM_ATTEMPT_TABLE};3 use crate::database::{Database, EXAM_ATTEMPT_TABLE};
4 use crate::domain::exam::Exam;4 use crate::domain::exam::Exam;
5 use crate::domain::exam::ExamId;5 use crate::domain::exam::ExamId;
6+use crate::domain::exam_answer::ExamAnswer;
6 use crate::domain::timestamp::Timestamp;7 use crate::domain::timestamp::Timestamp;
7 use crate::domain::user::UserId;8 use crate::domain::user::UserId;
8 use crate::error::AppError;9 use crate::error::AppError;
@@ -11,15 +12,20 @@ use crate::error::AppError;
11 pub struct ExamAttemptId(RecordId);12 pub struct ExamAttemptId(RecordId);
12 13
13 impl ExamAttemptId {14 impl ExamAttemptId {
14- /// A deterministic id for the (exam, user) pair. The same pair always maps15+ /// A deterministic id for the (exam, user, seq) triple. The same triple
15- /// to the same record id, so a student gets exactly one attempt per exam by16+ /// always maps to the same record id, so sitting `seq` exists at most once
16- /// construction — a second "start" cannot mint a fresh clock. ULID keys are17+ /// by construction — a concurrent double "start" races on the same id and
18+ /// exactly one create wins. The first sitting keeps the historical
19+ /// `{exam}_{user}` shape (rows written before retakes existed stay
20+ /// addressable); later sittings append their number. ULID keys are
17 /// alphanumeric, so `_` is an unambiguous joiner.21 /// alphanumeric, so `_` is an unambiguous joiner.
18- pub fn composite(exam: &ExamId, user: &UserId) -> Self {22+ pub fn composite(exam: &ExamId, user: &UserId, seq: i64) -> Self {
19- Self(RecordId::new(23+ let key = if seq == 1 {
20- EXAM_ATTEMPT_TABLE,24+ format!("{}_{}", exam.key(), user.key())
21- format!("{}_{}", exam.key(), user.key()),25+ } else {
22- ))26+ format!("{}_{}_{}", exam.key(), user.key(), seq)
27+ };
28+ Self(RecordId::new(EXAM_ATTEMPT_TABLE, key))
23 }29 }
24 30
25 pub fn record(&self) -> RecordId {31 pub fn record(&self) -> RecordId {
@@ -57,16 +63,19 @@ impl AttemptStatus {
57 }63 }
58 }64 }
59 65
60-/// One student's sitting of a scheduled exam: starting is the live-attendance66+/// One student's sitting of an exam: starting is the live-attendance signal,
61-/// signal, `finished_at` the submission. Grading stays a separate67+/// `finished_at` the submission. `seq` numbers the sittings (1, 2, …) when the
62-/// `exam_result` row.68+/// exam allows retakes; `left_at` marks a student who walked out of the exam
69+/// room mid-attempt. Grading stays a separate `exam_result` row.
63 #[derive(Debug, Clone, SurrealValue)]70 #[derive(Debug, Clone, SurrealValue)]
64 pub struct ExamAttempt {71 pub struct ExamAttempt {
65 id: ExamAttemptId,72 id: ExamAttemptId,
66 exam: ExamId,73 exam: ExamId,
67 user: UserId,74 user: UserId,
75+ seq: i64,
68 started_at: Timestamp,76 started_at: Timestamp,
69 finished_at: Option<Timestamp>,77 finished_at: Option<Timestamp>,
78+ left_at: Option<Timestamp>,
70 }79 }
71 80
72 impl ExamAttempt {81 impl ExamAttempt {
@@ -82,6 +91,11 @@ impl ExamAttempt {
82 &self.user91 &self.user
83 }92 }
84 93
94+ /// Which sitting this is — 1 for the first attempt, counting up.
95+ pub fn get_seq(&self) -> i64 {
96+ self.seq
97+ }
98+
85 pub fn get_started_at(&self) -> Timestamp {99 pub fn get_started_at(&self) -> Timestamp {
86 self.started_at100 self.started_at
87 }101 }
@@ -90,22 +104,33 @@ impl ExamAttempt {
90 self.finished_at104 self.finished_at
91 }105 }
92 106
107+ /// When the student left the exam room (WebSocket closed mid-attempt);
108+ /// `None` while they're in it, or if they never used the room. Gates
109+ /// nothing by itself — the exam's `allow_rejoin` decides what it means.
110+ pub fn get_left_at(&self) -> Option<Timestamp> {
111+ self.left_at
112+ }
113+
93 /// When this attempt closes, computed from the exam's *current* schedule114 /// When this attempt closes, computed from the exam's *current* schedule
94- /// (never stored): `ends_at` for a sync exam, `min(started_at +115+ /// (never stored): the earlier of the window's `ends_at` and `started_at +
95- /// duration_ms, ends_at)` for an async one. Recomputing on every read means116+ /// duration_ms`, whichever of the two exists. Recomputing on every read
96- /// a teacher extending `ends_at` (or an async `duration_ms`) mid-exam moves117+ /// means a teacher extending `ends_at` (or `duration_ms`) mid-exam moves
97- /// every deadline live. `None` only if the exam is unscheduled, which118+ /// every deadline live. `None` for an open exam without a duration — such
98- /// starting an attempt forbids.119+ /// an attempt only ends by submission.
99 pub fn deadline(&self, exam: &Exam) -> Option<Timestamp> {120 pub fn deadline(&self, exam: &Exam) -> Option<Timestamp> {
100- let ends_at = exam.get_ends_at()?;121+ let by_duration = exam.get_duration_ms().map(|duration| {
101- Some(match exam.get_duration_ms() {122+ Timestamp::from_millis(
102- Some(duration) => ends_at.min(Timestamp::from_millis(
103 self.started_at123 self.started_at
104 .as_millis()124 .as_millis()
105 .saturating_add(duration.as_millis()),125 .saturating_add(duration.as_millis()),
106- )),126+ )
107- None => ends_at,127+ });
108- })128+ match (exam.get_ends_at(), by_duration) {
129+ (Some(ends_at), Some(cap)) => Some(ends_at.min(cap)),
130+ (Some(ends_at), None) => Some(ends_at),
131+ (None, Some(cap)) => Some(cap),
132+ (None, None) => None,
133+ }
109 }134 }
110 135
111 /// Status judged at `now` (one clock read per snapshot, shared across rows).136 /// Status judged at `now` (one clock read per snapshot, shared across rows).
@@ -120,32 +145,59 @@ impl ExamAttempt {
120 }145 }
121 146
122 /// Start (or resume) `user`'s attempt at `exam`. Returns the attempt plus147 /// Start (or resume) `user`'s attempt at `exam`. Returns the attempt plus
123- /// whether it was newly created: an existing row is returned untouched, so148+ /// whether it was newly created.
124- /// a reconnecting client gets its original clock back instead of a reset —149+ ///
125- /// re-"starting" can never buy more time. The composite id makes the150+ /// - A still-running latest attempt is returned untouched, so a
126- /// create atomic; a concurrent double-start loses to the unique id and151+ /// reconnecting client gets its original clock back instead of a reset —
127- /// reads the winner's row.152+ /// re-"starting" can never buy more time.
153+ /// - A terminal latest attempt (submitted or expired) starts sitting
154+ /// `seq + 1` if the exam's `max_attempts` allows another, and is a
155+ /// conflict otherwise. A retake begins from a blank sheet: the student's
156+ /// previous answers are wiped first. Wiping *before* creating keeps the
157+ /// race benign — until the new row exists, saves still hit the terminal
158+ /// attempt and are rejected, so no fresh answer can be lost to the wipe.
159+ ///
160+ /// The composite id makes each create atomic; a concurrent double-start
161+ /// races on the same seq, loses to the unique id, and reads the winner's
162+ /// row.
128 pub async fn start(163 pub async fn start(
129- exam: &ExamId,164+ exam: &Exam,
130 user: &UserId,165 user: &UserId,
131 db: &Database,166 db: &Database,
132 ) -> Result<(ExamAttempt, bool), AppError> {167 ) -> Result<(ExamAttempt, bool), AppError> {
133- if let Some(existing) = Self::read_for_user(exam, user, db).await? {168+ let attempts = Self::list_for_user(exam.get_id(), user, db).await?;
134- return Ok((existing, false));169+ let next_seq = match attempts.first() {
170+ None => 1,
171+ Some(latest) if latest.status(exam, Timestamp::now()) == AttemptStatus::InProgress => {
172+ return Ok((latest.clone(), false));
173+ }
174+ Some(latest) => {
175+ if !exam.get_max_attempts().allows_another(attempts.len()) {
176+ return Err(AppError::Conflict(
177+ "no attempts remaining — this exam's attempt limit is used up",
178+ ));
179+ }
180+ latest.seq + 1
181+ }
182+ };
183+ if next_seq > 1 {
184+ ExamAnswer::delete_for_exam_user(exam.get_id(), user, db).await?;
135 }185 }
136 let attempt = ExamAttempt {186 let attempt = ExamAttempt {
137- id: ExamAttemptId::composite(exam, user),187+ id: ExamAttemptId::composite(exam.get_id(), user, next_seq),
138- exam: exam.clone(),188+ exam: exam.get_id().clone(),
139 user: user.clone(),189 user: user.clone(),
190+ seq: next_seq,
140 started_at: Timestamp::now(),191 started_at: Timestamp::now(),
141 finished_at: None,192 finished_at: None,
193+ left_at: None,
142 };194 };
143 let created: Result<Option<ExamAttempt>, surrealdb::Error> =195 let created: Result<Option<ExamAttempt>, surrealdb::Error> =
144 db.create(attempt.id.record()).content(attempt).await;196 db.create(attempt.id.record()).content(attempt).await;
145 match created {197 match created {
146 Ok(Some(created)) => Ok((created, true)),198 Ok(Some(created)) => Ok((created, true)),
147 Ok(None) => Err(AppError::Internal("failed to start exam attempt".into())),199 Ok(None) => Err(AppError::Internal("failed to start exam attempt".into())),
148- Err(err) => match Self::read_for_user(exam, user, db).await? {200+ Err(err) => match Self::read_latest_for_user(exam.get_id(), user, db).await? {
149 Some(existing) => Ok((existing, false)),201 Some(existing) => Ok((existing, false)),
150 None => Err(err.into()),202 None => Err(err.into()),
151 },203 },
@@ -160,14 +212,53 @@ impl ExamAttempt {
160 updated.ok_or(AppError::NotFound)212 updated.ok_or(AppError::NotFound)
161 }213 }
162 214
163- pub async fn read_for_user(215+ /// Stamp (or clear) the walked-out marker. The exam room sets it when the
216+ /// student's socket closes mid-attempt and clears it when they come back.
217+ pub async fn set_left(
218+ mut self,
219+ left_at: Option<Timestamp>,
220+ db: &Database,
221+ ) -> Result<ExamAttempt, AppError> {
222+ self.left_at = left_at;
223+ let updated: Option<ExamAttempt> = db.update(self.id.record()).content(self).await?;
224+ updated.ok_or(AppError::NotFound)
225+ }
226+
227+ /// The student's current sitting — the highest `seq` for the pair. All
228+ /// reads that used to mean "the attempt" mean this now.
229+ pub async fn read_latest_for_user(
164 exam: &ExamId,230 exam: &ExamId,
165 user: &UserId,231 user: &UserId,
166 db: &Database,232 db: &Database,
167 ) -> Result<Option<ExamAttempt>, AppError> {233 ) -> Result<Option<ExamAttempt>, AppError> {
168- Ok(db234+ let mut result = db
169- .select(ExamAttemptId::composite(exam, user).record())235+ .query(
170- .await?)236+ "SELECT * FROM exam_attempt WHERE exam = $ex AND user = $usr
237+ ORDER BY seq DESC LIMIT 1",
238+ )
239+ .bind(("ex", exam.record()))
240+ .bind(("usr", user.record()))
241+ .await?
242+ .check()?;
243+ Ok(result.take::<Vec<ExamAttempt>>(0)?.into_iter().next())
244+ }
245+
246+ /// Every sitting of `user` at `exam`, newest first.
247+ pub async fn list_for_user(
248+ exam: &ExamId,
249+ user: &UserId,
250+ db: &Database,
251+ ) -> Result<Vec<ExamAttempt>, AppError> {
252+ let mut result = db
253+ .query(
254+ "SELECT * FROM exam_attempt WHERE exam = $ex AND user = $usr
255+ ORDER BY seq DESC",
256+ )
257+ .bind(("ex", exam.record()))
258+ .bind(("usr", user.record()))
259+ .await?
260+ .check()?;
261+ Ok(result.take::<Vec<ExamAttempt>>(0)?)
171 }262 }
172 263
173 pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<ExamAttempt>, AppError> {264 pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<ExamAttempt>, AppError> {
src/validate.rsmodified+31 -7
@@ -2,10 +2,11 @@
2 //! the value, so an existing newtype is always valid (parse, don't validate).2 //! the value, so an existing newtype is always valid (parse, don't validate).
3 3
4 use crate::constant::{4 use crate::constant::{
5- EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_DURATION_MS, MAX_EXAM_WEIGHT, MAX_MARK, MAX_PASSWORD_LEN,5+ EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, MAX_EXAM_DURATION_MS, MAX_EXAM_WEIGHT, MAX_MARK,
6- MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS,6+ MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, MAX_USERNAME_LEN,
7- MIN_EXAM_WEIGHT, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_QUESTION_POINTS,7+ MIN_EXAM_DURATION_MS, MIN_EXAM_WEIGHT, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS,
8- MIN_USERNAME_LEN, QUESTION_KINDS, USERNAME_SEPARATORS,8+ MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS, UNLIMITED_EXAM_ATTEMPTS,
9+ USERNAME_SEPARATORS,
9 };10 };
10 use crate::error::ValidationError;11 use crate::error::ValidationError;
11 12
@@ -63,7 +64,9 @@ pub fn validate_username(value: &str) -> Result<(), ValidationError> {
63 let mut chars = value.chars().peekable();64 let mut chars = value.chars().peekable();
64 while let Some(c) = chars.next() {65 while let Some(c) = chars.next() {
65 if USERNAME_SEPARATORS.contains(&c)66 if USERNAME_SEPARATORS.contains(&c)
66- && chars.peek().is_some_and(|n| USERNAME_SEPARATORS.contains(n))67+ && chars
68+ .peek()
69+ .is_some_and(|n| USERNAME_SEPARATORS.contains(n))
67 {70 {
68 return Err(ValidationError::Invalid {71 return Err(ValidationError::Invalid {
69 field: "username",72 field: "username",
@@ -201,7 +204,18 @@ pub fn validate_exam_mode(value: &str) -> Result<(), ValidationError> {
201 } else {204 } else {
202 Err(ValidationError::Invalid {205 Err(ValidationError::Invalid {
203 field: "mode",206 field: "mode",
204- reason: "must be one of: sync, async",207+ reason: "must be one of: sync, async, open",
208+ })
209+ }
210+}
211+
212+pub fn validate_attempt_limit(value: i64) -> Result<(), ValidationError> {
213+ if value == UNLIMITED_EXAM_ATTEMPTS || (1..=MAX_EXAM_ATTEMPTS).contains(&value) {
214+ Ok(())
215+ } else {
216+ Err(ValidationError::Invalid {
217+ field: "max_attempts",
218+ reason: "must be between 1 and 100, or 0 for unlimited",
205 })219 })
206 }220 }
207 }221 }
@@ -374,13 +388,23 @@ mod tests {
374 388
375 #[tokio::test]389 #[tokio::test]
376 async fn exam_mode_rules() {390 async fn exam_mode_rules() {
377- for mode in ["sync", "async"] {391+ for mode in ["sync", "async", "open"] {
378 assert!(validate_exam_mode(mode).is_ok());392 assert!(validate_exam_mode(mode).is_ok());
379 }393 }
380 assert!(validate_exam_mode("live").is_err());394 assert!(validate_exam_mode("live").is_err());
381 assert!(validate_exam_mode("").is_err());395 assert!(validate_exam_mode("").is_err());
382 }396 }
383 397
398+ #[tokio::test]
399+ async fn attempt_limit_rules() {
400+ assert!(validate_attempt_limit(UNLIMITED_EXAM_ATTEMPTS).is_ok());
401+ for limit in [1, 2, 50, MAX_EXAM_ATTEMPTS] {
402+ assert!(validate_attempt_limit(limit).is_ok());
403+ }
404+ assert!(validate_attempt_limit(-1).is_err());
405+ assert!(validate_attempt_limit(MAX_EXAM_ATTEMPTS + 1).is_err());
406+ }
407+
384 #[tokio::test]408 #[tokio::test]
385 async fn exam_duration_rules() {409 async fn exam_duration_rules() {
386 assert!(validate_exam_duration(MIN_EXAM_DURATION_MS).is_ok());410 assert!(validate_exam_duration(MIN_EXAM_DURATION_MS).is_ok());
src/web/courses.rsmodified+24 -10
@@ -13,7 +13,8 @@ use crate::domain::course::{Course, CourseDescription, CourseId, CourseTitle};
13 use crate::domain::course_session::{CourseSession, SessionTopic};13 use crate::domain::course_session::{CourseSession, SessionTopic};
14 use crate::domain::enrollment::Enrollment;14 use crate::domain::enrollment::Enrollment;
15 use crate::domain::exam::{15 use crate::domain::exam::{
16- Exam, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, ExamWeight,16+ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule,
17+ ExamTitle, ExamWeight,
17 };18 };
18 use crate::domain::role::Role;19 use crate::domain::role::Role;
19 use crate::domain::settings::Settings;20 use crate::domain::settings::Settings;
@@ -80,22 +81,29 @@ struct CreateExamInCourse {
80 /// How many times this exam counts into the course average, `1`–`100`.81 /// How many times this exam counts into the course average, `1`–`100`.
81 #[schema(example = 3)]82 #[schema(example = 3)]
82 weight: i64,83 weight: i64,
83- /// `sync` (one fixed window for everyone) or `async` (each student starts84+ /// `sync` (one fixed window for everyone), `async` (each student starts
84- /// inside the window and gets `duration_ms`). Omit for an unscheduled,85+ /// inside the window and gets `duration_ms`), or `open` (no window — sit
85- /// offline-graded exam.86+ /// anytime). Omit for an offline-graded draft that cannot be sat.
86 #[schema(example = "sync")]87 #[schema(example = "sync")]
87 mode: Option<String>,88 mode: Option<String>,
88- /// Window open, UTC unix-milliseconds. Required with `mode`; must not be89+ /// Window open, UTC unix-milliseconds. Required for `sync`/`async`,
89- /// in the past.90+ /// forbidden for `open`; must not be in the past.
90 #[schema(example = 1_900_000_000_000_i64)]91 #[schema(example = 1_900_000_000_000_i64)]
91 starts_at: Option<i64>,92 starts_at: Option<i64>,
92- /// Window close, UTC unix-milliseconds. Required with `mode`; must not be93+ /// Window close, UTC unix-milliseconds. Required for `sync`/`async`,
93- /// in the past.94+ /// forbidden for `open`; must not be in the past.
94 ends_at: Option<i64>,95 ends_at: Option<i64>,
95- /// Per-student time budget, milliseconds — required for (and exclusive to)96+ /// Per-attempt time budget, milliseconds — required for `async`, optional
96- /// `async` exams.97+ /// for `open` (omit for unlimited time), forbidden for `sync`.
97 #[schema(example = 5_400_000_i64)]98 #[schema(example = 5_400_000_i64)]
98 duration_ms: Option<i64>,99 duration_ms: Option<i64>,
100+ /// How many attempts each student gets, `1`–`100`, or `0` for unlimited.
101+ /// Defaults to `1` — the classic single sitting.
102+ #[schema(example = 1)]
103+ max_attempts: Option<i64>,
104+ /// Whether a student who left the exam room may come back in and keep
105+ /// answering. Defaults to `true`; editable live while the exam runs.
106+ allow_rejoin: Option<bool>,
99 }107 }
100 108
101 #[derive(Serialize, ToSchema)]109 #[derive(Serialize, ToSchema)]
@@ -525,6 +533,10 @@ async fn create_exam_in_course(
525 ends_at,533 ends_at,
526 req.duration_ms.map(ExamDuration::try_new).transpose()?,534 req.duration_ms.map(ExamDuration::try_new).transpose()?,
527 )?;535 )?;
536+ let max_attempts = match req.max_attempts {
537+ Some(limit) => ExamAttemptLimit::try_new(limit)?,
538+ None => ExamAttemptLimit::single(),
539+ };
528 let exam = Exam::create(540 let exam = Exam::create(
529 user.get_id(),541 user.get_id(),
530 course.get_id(),542 course.get_id(),
@@ -533,6 +545,8 @@ async fn create_exam_in_course(
533 kind,545 kind,
534 weight,546 weight,
535 schedule,547 schedule,
548+ max_attempts,
549+ req.allow_rejoin.unwrap_or(true),
536 &st.db,550 &st.db,
537 )551 )
538 .await?;552 .await?;
src/web/dto.rsmodified+15 -5
@@ -198,7 +198,7 @@ impl SessionResponse {
198 198
199 /// Public shape of an exam. Shared by `exams` (CRUD/results) and `courses`199 /// Public shape of an exam. Shared by `exams` (CRUD/results) and `courses`
200 /// (in-course creation and listing). The schedule fields are all `null` for an200 /// (in-course creation and listing). The schedule fields are all `null` for an
201-/// unscheduled (offline-graded) exam; see the create/update endpoints for the201+/// offline-graded draft (no mode); see the create/update endpoints for the
202 /// rules tying them together.202 /// rules tying them together.
203 #[derive(Serialize, ToSchema)]203 #[derive(Serialize, ToSchema)]
204 pub struct ExamResponse {204 pub struct ExamResponse {
@@ -209,15 +209,23 @@ pub struct ExamResponse {
209 pub description: String,209 pub description: String,
210 pub kind: String,210 pub kind: String,
211 pub weight: i64,211 pub weight: i64,
212- /// `sync` or `async`; `null` for an unscheduled exam.212+ /// `sync`, `async`, or `open`; `null` for an offline-graded draft
213+ /// (not sittable).
213 #[schema(example = "sync")]214 #[schema(example = "sync")]
214 pub mode: Option<String>,215 pub mode: Option<String>,
215- /// Window open, UTC unix-milliseconds.216+ /// Window open, UTC unix-milliseconds (`sync`/`async`).
216 pub starts_at: Option<i64>,217 pub starts_at: Option<i64>,
217- /// Window close, UTC unix-milliseconds.218+ /// Window close, UTC unix-milliseconds (`sync`/`async`).
218 pub ends_at: Option<i64>,219 pub ends_at: Option<i64>,
219- /// Per-student time budget in milliseconds (async exams only).220+ /// Per-attempt time budget in milliseconds — required for `async`,
221+ /// optional for `open` (`null` = unlimited time).
220 pub duration_ms: Option<i64>,222 pub duration_ms: Option<i64>,
223+ /// How many attempts each student gets; `0` means unlimited.
224+ #[schema(example = 1)]
225+ pub max_attempts: i64,
226+ /// Whether a student who left the exam room may come back in and keep
227+ /// answering. Teachers can flip this live.
228+ pub allow_rejoin: bool,
221 }229 }
222 230
223 impl ExamResponse {231 impl ExamResponse {
@@ -234,6 +242,8 @@ impl ExamResponse {
234 starts_at: exam.get_starts_at().map(|t| t.as_millis()),242 starts_at: exam.get_starts_at().map(|t| t.as_millis()),
235 ends_at: exam.get_ends_at().map(|t| t.as_millis()),243 ends_at: exam.get_ends_at().map(|t| t.as_millis()),
236 duration_ms: exam.get_duration_ms().map(|d| d.as_millis()),244 duration_ms: exam.get_duration_ms().map(|d| d.as_millis()),
245+ max_attempts: exam.get_max_attempts().as_i64(),
246+ allow_rejoin: exam.get_allow_rejoin(),
237 }247 }
238 }248 }
239 }249 }
src/web/exam_ws.rsmodified+56 -8
@@ -8,7 +8,7 @@
8 //! Wire protocol (JSON text frames):8 //! Wire protocol (JSON text frames):
9 //!9 //!
10 //! server → client10 //! server → client
11-//! - `{"type":"state", status, deadline, remaining_ms, now, answered, question_count}`11+//! - `{"type":"state", status, attempt, deadline, remaining_ms, now, answered, question_count}`
12 //! on connect, every [`EXAM_WS_TICK_SECS`], and after each save12 //! on connect, every [`EXAM_WS_TICK_SECS`], and after each save
13 //! - `{"type":"saved", question_id, updated_at}` — an answer landed13 //! - `{"type":"saved", question_id, updated_at}` — an answer landed
14 //! - `{"type":"pong"}`14 //! - `{"type":"pong"}`
@@ -25,6 +25,12 @@
25 //! stays server-authoritative: a teacher extending `ends_at` (or `duration_ms`)25 //! stays server-authoritative: a teacher extending `ends_at` (or `duration_ms`)
26 //! mid-exam moves this room's clock on the next tick, and a stale client can26 //! mid-exam moves this room's clock on the next tick, and a stale client can
27 //! never write past its real deadline.27 //! never write past its real deadline.
28+//!
29+//! The room is also the presence signal behind the rejoin policy: connecting
30+//! clears the attempt's `left_at`, and a socket that closes while the attempt
31+//! is still running stamps it. With the exam's `allow_rejoin` off, a stamped
32+//! `left_at` refuses re-entry (and any further saves, here or over REST) until
33+//! the teacher flips the door back open; finishing stays allowed.
28 34
29 use std::time::Duration;35 use std::time::Duration;
30 36
@@ -46,7 +52,7 @@ use crate::domain::user::UserId;
46 use crate::error::AppError;52 use crate::error::AppError;
47 use crate::state::AppState;53 use crate::state::AppState;
48 use crate::web::CurrentUser;54 use crate::web::CurrentUser;
49-use crate::web::exams::{save_answer_checked, writable_attempt};55+use crate::web::exams::{check_rejoin, save_answer_checked, writable_attempt};
50 56
51 /// What the client asked for, tagged by `type`.57 /// What the client asked for, tagged by `type`.
52 #[derive(Deserialize)]58 #[derive(Deserialize)]
@@ -65,8 +71,10 @@ enum ClientMessage {
65 71
66 /// Upgrade into the caller's exam room. All gates run *before* the upgrade so72 /// Upgrade into the caller's exam room. All gates run *before* the upgrade so
67 /// a rejected client gets a proper HTTP status instead of an instant close:73 /// a rejected client gets a proper HTTP status instead of an instant close:
68-/// unknown exam (404), unscheduled (409), not enrolled (403), no attempt yet74+/// unknown exam (404), draft with no mode (409), not enrolled (403), no
69-/// (404 — `POST /exams/{id}/attempt` first), submitted or expired (409).75+/// attempt yet (404 — `POST /exams/{id}/attempt` first), submitted or expired
76+/// (409), left the room while rejoin is closed (409). Entering the room
77+/// clears the attempt's `left_at` — the student is back inside.
70 pub async fn attempt_ws(78 pub async fn attempt_ws(
71 State(st): State<AppState>,79 State(st): State<AppState>,
72 CurrentUser(user): CurrentUser,80 CurrentUser(user): CurrentUser,
@@ -76,9 +84,9 @@ pub async fn attempt_ws(
76 let exam = Exam::read(&ExamId::from_key(&id), &st.db)84 let exam = Exam::read(&ExamId::from_key(&id), &st.db)
77 .await?85 .await?
78 .ok_or(AppError::NotFound)?;86 .ok_or(AppError::NotFound)?;
79- if exam.get_starts_at().is_none() {87+ if exam.get_mode().is_none() {
80 return Err(AppError::Conflict(88 return Err(AppError::Conflict(
81- "this exam is not scheduled — there is nothing to sit",89+ "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)",
82 ));90 ));
83 }91 }
84 if Enrollment::read_for_user(exam.get_course(), user.get_id(), &st.db)92 if Enrollment::read_for_user(exam.get_course(), user.get_id(), &st.db)
@@ -89,7 +97,11 @@ pub async fn attempt_ws(
89 "you are not enrolled in this exam's course",97 "you are not enrolled in this exam's course",
90 ));98 ));
91 }99 }
92- writable_attempt(&exam, user.get_id(), &st.db).await?;100+ let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?;
101+ check_rejoin(&exam, &attempt)?;
102+ if attempt.get_left_at().is_some() {
103+ attempt.set_left(None, &st.db).await?;
104+ }
93 105
94 let user_id = user.get_id().clone();106 let user_id = user.get_id().clone();
95 Ok(ws.on_upgrade(move |socket| room(socket, st, exam, user_id)))107 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) {
128 // Best-effort closing handshake — a bare TCP teardown reads as an error140 // Best-effort closing handshake — a bare TCP teardown reads as an error
129 // on the client; a Close frame reads as "the room is over".141 // on the client; a Close frame reads as "the room is over".
130 let _ = socket.send(Message::Close(None)).await;142 let _ = socket.send(Message::Close(None)).await;
143+ // The student is out of the room. If their attempt is still running,
144+ // stamp the walk-out — with `allow_rejoin` off this is what locks further
145+ // answering. Terminal exits (finished/expired) need no stamp. Best-effort:
146+ // a failed stamp only means the walk-out goes unrecorded.
147+ stamp_left(&exam_id, &user, &st.db).await;
148+}
149+
150+/// Stamp `left_at` on the student's latest attempt if it is still in
151+/// progress — re-reading both rows so a finish or expiry that raced the
152+/// socket close wins.
153+async fn stamp_left(exam_id: &ExamId, user: &UserId, db: &Database) {
154+ let attempt = match Exam::read(exam_id, db).await {
155+ Ok(Some(exam)) => match ExamAttempt::read_latest_for_user(exam.get_id(), user, db).await {
156+ Ok(Some(attempt))
157+ if attempt.status(&exam, Timestamp::now()) == AttemptStatus::InProgress =>
158+ {
159+ Some(attempt)
160+ }
161+ Ok(_) => None,
162+ Err(err) => {
163+ tracing::warn!("exam room could not read the attempt to stamp left_at: {err}");
164+ None
165+ }
166+ },
167+ Ok(None) => None,
168+ Err(err) => {
169+ tracing::warn!("exam room could not read the exam to stamp left_at: {err}");
170+ None
171+ }
172+ };
173+ if let Some(attempt) = attempt
174+ && let Err(err) = attempt.set_left(Some(Timestamp::now()), db).await
175+ {
176+ tracing::warn!("exam room could not stamp left_at: {err}");
177+ }
131 }178 }
132 179
133 /// Errors that end the room: the peer went away, or the attempt reached a180 /// Errors that end the room: the peer went away, or the attempt reached a
@@ -189,7 +236,7 @@ async fn state_frame(
189 db: &Database,236 db: &Database,
190 ) -> Result<(Value, AttemptStatus, Option<i64>), AppError> {237 ) -> Result<(Value, AttemptStatus, Option<i64>), AppError> {
191 let exam = Exam::read(exam, db).await?.ok_or(AppError::NotFound)?;238 let exam = Exam::read(exam, db).await?.ok_or(AppError::NotFound)?;
192- let attempt = ExamAttempt::read_for_user(exam.get_id(), user, db)239+ let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user, db)
193 .await?240 .await?
194 .ok_or(AppError::NotFound)?;241 .ok_or(AppError::NotFound)?;
195 let now = Timestamp::now();242 let now = Timestamp::now();
@@ -205,6 +252,7 @@ async fn state_frame(
205 let frame = json!({252 let frame = json!({
206 "type": "state",253 "type": "state",
207 "status": status.as_str(),254 "status": status.as_str(),
255+ "attempt": attempt.get_seq(),
208 "deadline": deadline.map(|t| t.as_millis()),256 "deadline": deadline.map(|t| t.as_millis()),
209 "remaining_ms": remaining_ms,257 "remaining_ms": remaining_ms,
210 "now": now.as_millis(),258 "now": now.as_millis(),
src/web/exams.rsmodified+176 -65
@@ -17,8 +17,8 @@ use crate::database::Database;
17 use crate::domain::course::Course;17 use crate::domain::course::Course;
18 use crate::domain::enrollment::Enrollment;18 use crate::domain::enrollment::Enrollment;
19 use crate::domain::exam::{19 use crate::domain::exam::{
20- Exam, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, ExamSchedule, ExamTitle,20+ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode,
21- ExamWeight,21+ ExamSchedule, ExamTitle, ExamWeight,
22 };22 };
23 use crate::domain::exam_answer::{ExamAnswer, auto_score};23 use crate::domain::exam_answer::{ExamAnswer, auto_score};
24 use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt};24 use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt};
@@ -70,8 +70,10 @@ struct UpdateExam {
70 description: Option<String>,70 description: Option<String>,
71 kind: Option<String>,71 kind: Option<String>,
72 weight: Option<i64>,72 weight: Option<i64>,
73- /// `sync` or `async`. Omit to keep the current mode; send `null` to73+ /// `sync`, `async`, or `open`. Omit to keep the current mode; send `null`
74- /// unschedule the exam. Frozen once anyone has started an attempt.74+ /// to turn the exam back into an offline draft. Frozen once anyone has
75+ /// started an attempt. Switching to `open` requires clearing
76+ /// `starts_at`/`ends_at` in the same request.
75 #[serde(default, deserialize_with = "set_or_clear")]77 #[serde(default, deserialize_with = "set_or_clear")]
76 #[schema(value_type = Option<String>)]78 #[schema(value_type = Option<String>)]
77 mode: Option<Option<String>>,79 mode: Option<Option<String>>,
@@ -86,11 +88,19 @@ struct UpdateExam {
86 #[serde(default, deserialize_with = "set_or_clear")]88 #[serde(default, deserialize_with = "set_or_clear")]
87 #[schema(value_type = Option<i64>)]89 #[schema(value_type = Option<i64>)]
88 ends_at: Option<Option<i64>>,90 ends_at: Option<Option<i64>>,
89- /// Per-student budget, milliseconds (async only). Omit to keep; `null` to91+ /// Per-attempt budget, milliseconds (`async`, or optionally `open`). Omit
90- /// clear. Changing it mid-exam moves every running attempt's deadline.92+ /// to keep; `null` to clear. Changing it mid-exam moves every running
93+ /// attempt's deadline.
91 #[serde(default, deserialize_with = "set_or_clear")]94 #[serde(default, deserialize_with = "set_or_clear")]
92 #[schema(value_type = Option<i64>)]95 #[schema(value_type = Option<i64>)]
93 duration_ms: Option<Option<i64>>,96 duration_ms: Option<Option<i64>>,
97+ /// Attempt limit: `1`–`100`, or `0` for unlimited. Omit to keep. Editable
98+ /// live — raising it grants retakes on the spot; lowering it only blocks
99+ /// future starts.
100+ max_attempts: Option<i64>,
101+ /// Whether students who left the exam room may come back in. Omit to
102+ /// keep. Editable live — the teacher's door handle for the running room.
103+ allow_rejoin: Option<bool>,
94 }104 }
95 105
96 #[derive(Deserialize, ToSchema)]106 #[derive(Deserialize, ToSchema)]
@@ -210,8 +220,9 @@ async fn get_exam(
210 /// course (its creator, or manager/admin). Omitted fields keep their value; an220 /// course (its creator, or manager/admin). Omitted fields keep their value; an
211 /// explicit `null` clears a schedule field; the course itself is not updatable.221 /// explicit `null` clears a schedule field; the course itself is not updatable.
212 /// The schedule must stay consistent as a whole (see the create endpoint), and222 /// The schedule must stay consistent as a whole (see the create endpoint), and
213-/// `mode` is frozen once anyone has started an attempt — times and duration223+/// `mode` is frozen once anyone has started an attempt — times, duration,
214-/// stay editable so a running exam can be extended live.224+/// `max_attempts`, and `allow_rejoin` stay editable so a running exam can be
225+/// extended, granted retakes, or have its rejoin door opened live.
215 #[utoipa::path(226 #[utoipa::path(
216 patch,227 patch,
217 path = "/{id}",228 path = "/{id}",
@@ -297,10 +308,16 @@ async fn update_exam(
297 None => exam.get_duration_ms(),308 None => exam.get_duration_ms(),
298 };309 };
299 let schedule = ExamSchedule::try_new(mode, starts_at, ends_at, duration_ms)?;310 let schedule = ExamSchedule::try_new(mode, starts_at, ends_at, duration_ms)?;
311+ let max_attempts = match req.max_attempts {
312+ Some(limit) => ExamAttemptLimit::try_new(limit)?,
313+ None => exam.get_max_attempts(),
314+ };
315+ let allow_rejoin = req.allow_rejoin.unwrap_or_else(|| exam.get_allow_rejoin());
300 316
301- // Switching sync <-> async (or unscheduling) would silently rewrite the317+ // Switching sync <-> async <-> open (or back to a draft) would silently
302- // deadline rules under students who already sat down; extending times is318+ // rewrite the deadline rules under students who already sat down;
303- // the supported live adjustment instead.319+ // extending times, the attempt limit, and the rejoin door are the
320+ // supported live adjustments instead.
304 let mode_changed =321 let mode_changed =
305 schedule.get_mode().map(ExamMode::as_str) != exam.get_mode().map(ExamMode::as_str);322 schedule.get_mode().map(ExamMode::as_str) != exam.get_mode().map(ExamMode::as_str);
306 if mode_changed && ExamAttempt::any_for_exam(exam.get_id(), &st.db).await? {323 if mode_changed && ExamAttempt::any_for_exam(exam.get_id(), &st.db).await? {
@@ -310,7 +327,16 @@ async fn update_exam(
310 }327 }
311 328
312 let updated = exam329 let updated = exam
313- .update(title, description, kind, weight, schedule, &st.db)330+ .update(
331+ title,
332+ description,
333+ kind,
334+ weight,
335+ schedule,
336+ max_attempts,
337+ allow_rejoin,
338+ &st.db,
339+ )
314 .await?;340 .await?;
315 Ok(Json(ExamResponse::new(&updated)))341 Ok(Json(ExamResponse::new(&updated)))
316 }342 }
@@ -581,29 +607,44 @@ async fn exam_statistics(
581 }607 }
582 608
583 // ---- attempts -------------------------------------------------------------609 // ---- attempts -------------------------------------------------------------
584-// A scheduled exam is *sat*: starting an attempt is the live-attendance610+// A sittable exam (sync, async, or open mode) is *sat*: starting an attempt
585-// signal, finishing is the submission. Deadlines are judged only by the611+// is the live-attendance signal, finishing is the submission. The exam's
586-// server clock — clients sync via `GET /time`.612+// `max_attempts` (0 = unlimited) says how many sittings each student gets;
587-613+// re-posting resumes a running attempt and mints the next sitting once the
588-/// A student's view of their attempt. `now` is echoed so clients can render614+// last one is over. Deadlines are judged only by the server clock — clients
589-/// countdowns without trusting the device clock.615+// sync via `GET /time`.
616+
617+/// A student's view of their (latest) attempt. `now` is echoed so clients can
618+/// render countdowns without trusting the device clock.
590 #[derive(Serialize, ToSchema)]619 #[derive(Serialize, ToSchema)]
591 struct AttemptResponse {620 struct AttemptResponse {
592 id: String,621 id: String,
593 exam: String,622 exam: String,
594 user: PersonRef,623 user: PersonRef,
624+ /// Which sitting this is — 1 for the first attempt, counting up.
625+ attempt: i64,
626+ /// How many sittings the caller has used, this one included.
627+ attempts_used: u64,
628+ /// The exam's attempt limit; `0` means unlimited.
629+ max_attempts: i64,
595 /// When the attempt started, UTC unix-milliseconds.630 /// When the attempt started, UTC unix-milliseconds.
596 started_at: i64,631 started_at: i64,
597 /// Submission instant; `null` while running (or expired unsubmitted).632 /// Submission instant; `null` while running (or expired unsubmitted).
598 finished_at: Option<i64>,633 finished_at: Option<i64>,
634+ /// When the student left the exam room mid-attempt; `null` while inside
635+ /// (or if they never used the room). With `allow_rejoin` off, a set
636+ /// `left_at` locks further answering until the teacher reopens the door.
637+ left_at: Option<i64>,
599 /// `in_progress` | `submitted` | `expired`.638 /// `in_progress` | `submitted` | `expired`.
600 #[schema(example = "in_progress")]639 #[schema(example = "in_progress")]
601 status: String,640 status: String,
602- /// When the attempt closes: `ends_at` for sync, `min(started_at +641+ /// When the attempt closes: the earlier of the window's `ends_at` and
603- /// duration_ms, ends_at)` for async. Recomputed live from the exam's642+ /// `started_at + duration_ms` (whichever exists). Recomputed live from
604- /// current schedule.643+ /// the exam's current schedule; `null` for an open exam without a
644+ /// duration — such an attempt only ends by submission.
605 deadline: Option<i64>,645 deadline: Option<i64>,
606- /// `deadline - now`, floored at 0; `null` unless in progress.646+ /// `deadline - now`, floored at 0; `null` unless in progress with a
647+ /// deadline.
607 remaining_ms: Option<i64>,648 remaining_ms: Option<i64>,
608 /// The caller's mark, once graded.649 /// The caller's mark, once graded.
609 mark: Option<i64>,650 mark: Option<i64>,
@@ -616,6 +657,10 @@ struct AttemptResponse {
616 }657 }
617 658
618 impl AttemptResponse {659 impl AttemptResponse {
660+ #[expect(
661+ clippy::too_many_arguments,
662+ reason = "a flat view over attempt + exam + progress; a builder would obscure it"
663+ )]
619 fn new(664 fn new(
620 attempt: &ExamAttempt,665 attempt: &ExamAttempt,
621 exam: &Exam,666 exam: &Exam,
@@ -623,6 +668,7 @@ impl AttemptResponse {
623 people: &HashMap<String, PersonRef>,668 people: &HashMap<String, PersonRef>,
624 answered: u64,669 answered: u64,
625 question_count: u64,670 question_count: u64,
671+ attempts_used: u64,
626 now: Timestamp,672 now: Timestamp,
627 ) -> Self {673 ) -> Self {
628 let status = attempt.status(exam, now);674 let status = attempt.status(exam, now);
@@ -634,8 +680,12 @@ impl AttemptResponse {
634 id: attempt.get_id().key().to_string(),680 id: attempt.get_id().key().to_string(),
635 exam: attempt.get_exam().key().to_string(),681 exam: attempt.get_exam().key().to_string(),
636 user: PersonRef::resolve(people, attempt.get_user()),682 user: PersonRef::resolve(people, attempt.get_user()),
683+ attempt: attempt.get_seq(),
684+ attempts_used,
685+ max_attempts: exam.get_max_attempts().as_i64(),
637 started_at: attempt.get_started_at().as_millis(),686 started_at: attempt.get_started_at().as_millis(),
638 finished_at: attempt.get_finished_at().map(|t| t.as_millis()),687 finished_at: attempt.get_finished_at().map(|t| t.as_millis()),
688+ left_at: attempt.get_left_at().map(|t| t.as_millis()),
639 status: status.as_str().to_string(),689 status: status.as_str().to_string(),
640 deadline: deadline.map(|t| t.as_millis()),690 deadline: deadline.map(|t| t.as_millis()),
641 remaining_ms,691 remaining_ms,
@@ -659,23 +709,31 @@ async fn attempt_progress(
659 Ok((answered, question_count))709 Ok((answered, question_count))
660 }710 }
661 711
662-/// The exam's window, or a 409 when it isn't scheduled at all. Enrollment and712+/// A 409 unless the exam can be sat at all: it needs a mode (`sync`, `async`,
713+/// or `open`) — a modeless exam is an offline-graded draft. Enrollment and
663 /// window checks for the caller are the caller's own state — hence `Conflict`714 /// window checks for the caller are the caller's own state — hence `Conflict`
664 /// (a state problem), not validation.715 /// (a state problem), not validation.
665-fn window_of(exam: &Exam) -> Result<(Timestamp, Timestamp), AppError> {716+fn ensure_sittable(exam: &Exam) -> Result<(), AppError> {
666- match (exam.get_starts_at(), exam.get_ends_at()) {717+ if exam.get_mode().is_none() {
667- (Some(starts), Some(ends)) => Ok((starts, ends)),718+ return Err(AppError::Conflict(
668- _ => Err(AppError::Conflict(719+ "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)",
669- "this exam is not scheduled — there is nothing to sit",720+ ));
670- )),
671 }721 }
722+ Ok(())
723+}
724+
725+/// How many sittings the caller has used at this exam.
726+async fn attempts_used(exam: &ExamId, user: &UserId, db: &Database) -> Result<u64, AppError> {
727+ Ok(ExamAttempt::list_for_user(exam, user, db).await?.len() as u64)
672 }728 }
673 729
674-/// Start (or resume) the caller's attempt at a scheduled exam. Requires730+/// Start, resume, or retake the caller's attempt. Requires enrollment in the
675-/// enrollment in the exam's course and the window to be open. Idempotent in731+/// exam's course, a sittable exam (`sync`/`async`/`open` mode), and — when a
676-/// the useful direction: if an attempt already exists it is returned as-is732+/// window exists — the window to be open. A still-running attempt is returned
677-/// (`200` instead of `201`), so a reconnecting client gets its original clock733+/// as-is (`200` instead of `201`), so a reconnecting client gets its original
678-/// back — re-starting never resets the time.734+/// clock back — re-starting never resets the time. Once the latest attempt is
735+/// submitted or expired, re-posting starts the next sitting (`201`, blank
736+/// answer sheet) while the exam's `max_attempts` (0 = unlimited) allows it.
679 #[utoipa::path(737 #[utoipa::path(
680 post,738 post,
681 path = "/{id}/attempt",739 path = "/{id}/attempt",
@@ -683,12 +741,12 @@ fn window_of(exam: &Exam) -> Result<(Timestamp, Timestamp), AppError> {
683 security(("session_cookie" = [])),741 security(("session_cookie" = [])),
684 params(("id" = String, Path, description = "Exam id")),742 params(("id" = String, Path, description = "Exam id")),
685 responses(743 responses(
686- (status = 201, description = "Attempt started", body = AttemptResponse),744+ (status = 201, description = "Attempt started (first sitting or a retake)", body = AttemptResponse),
687- (status = 200, description = "Attempt already existed (unchanged)", body = AttemptResponse),745+ (status = 200, description = "Running attempt resumed (unchanged)", body = AttemptResponse),
688 (status = 401, description = "Not authenticated", body = ErrorResponse),746 (status = 401, description = "Not authenticated", body = ErrorResponse),
689 (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse),747 (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse),
690 (status = 404, description = "Exam not found", body = ErrorResponse),748 (status = 404, description = "Exam not found", body = ErrorResponse),
691- (status = 409, description = "Unscheduled exam, or outside the window", body = ErrorResponse),749+ (status = 409, description = "Draft exam, outside the window, or no attempts remaining", body = ErrorResponse),
692 ),750 ),
693 )]751 )]
694 async fn start_attempt(752 async fn start_attempt(
@@ -699,7 +757,7 @@ async fn start_attempt(
699 let exam = Exam::read(&ExamId::from_key(&id), &st.db)757 let exam = Exam::read(&ExamId::from_key(&id), &st.db)
700 .await?758 .await?
701 .ok_or(AppError::NotFound)?;759 .ok_or(AppError::NotFound)?;
702- let (starts_at, ends_at) = window_of(&exam)?;760+ ensure_sittable(&exam)?;
703 if Enrollment::read_for_user(exam.get_course(), user.get_id(), &st.db)761 if Enrollment::read_for_user(exam.get_course(), user.get_id(), &st.db)
704 .await?762 .await?
705 .is_none()763 .is_none()
@@ -709,18 +767,23 @@ async fn start_attempt(
709 ));767 ));
710 }768 }
711 let now = Timestamp::now();769 let now = Timestamp::now();
712- if now < starts_at {770+ if let Some(starts_at) = exam.get_starts_at()
771+ && now < starts_at
772+ {
713 return Err(AppError::Conflict("the exam has not started yet"));773 return Err(AppError::Conflict("the exam has not started yet"));
714 }774 }
715- if now >= ends_at {775+ if let Some(ends_at) = exam.get_ends_at()
776+ && now >= ends_at
777+ {
716 return Err(AppError::Conflict("the exam has already ended"));778 return Err(AppError::Conflict("the exam has already ended"));
717 }779 }
718 780
719- let (attempt, created) = ExamAttempt::start(exam.get_id(), user.get_id(), &st.db).await?;781+ let (attempt, created) = ExamAttempt::start(&exam, user.get_id(), &st.db).await?;
720 let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)782 let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
721 .await?783 .await?
722 .map(|r| r.get_mark());784 .map(|r| r.get_mark());
723 let (answered, question_count) = attempt_progress(exam.get_id(), user.get_id(), &st.db).await?;785 let (answered, question_count) = attempt_progress(exam.get_id(), user.get_id(), &st.db).await?;
786+ let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?;
724 let people = PersonRef::map_of(&[&user]);787 let people = PersonRef::map_of(&[&user]);
725 let status = if created {788 let status = if created {
726 StatusCode::CREATED789 StatusCode::CREATED
@@ -736,14 +799,15 @@ async fn start_attempt(
736 &people,799 &people,
737 answered,800 answered,
738 question_count,801 question_count,
802+ used,
739 Timestamp::now(),803 Timestamp::now(),
740 )),804 )),
741 ))805 ))
742 }806 }
743 807
744-/// The caller's own attempt: status, deadline, remaining time, and mark once808+/// The caller's own (latest) attempt: status, deadline, remaining time, and
745-/// graded — everything a student's live exam screen needs, judged by the809+/// mark once graded — everything a student's live exam screen needs, judged
746-/// server clock. `404` until the attempt is started.810+/// by the server clock. `404` until an attempt is started.
747 #[utoipa::path(811 #[utoipa::path(
748 get,812 get,
749 path = "/{id}/attempt",813 path = "/{id}/attempt",
@@ -751,7 +815,7 @@ async fn start_attempt(
751 security(("session_cookie" = [])),815 security(("session_cookie" = [])),
752 params(("id" = String, Path, description = "Exam id")),816 params(("id" = String, Path, description = "Exam id")),
753 responses(817 responses(
754- (status = 200, description = "The caller's attempt", body = AttemptResponse),818+ (status = 200, description = "The caller's latest attempt", body = AttemptResponse),
755 (status = 401, description = "Not authenticated", body = ErrorResponse),819 (status = 401, description = "Not authenticated", body = ErrorResponse),
756 (status = 404, description = "No such exam, or no attempt yet", body = ErrorResponse),820 (status = 404, description = "No such exam, or no attempt yet", body = ErrorResponse),
757 ),821 ),
@@ -764,13 +828,14 @@ async fn my_attempt(
764 let exam = Exam::read(&ExamId::from_key(&id), &st.db)828 let exam = Exam::read(&ExamId::from_key(&id), &st.db)
765 .await?829 .await?
766 .ok_or(AppError::NotFound)?;830 .ok_or(AppError::NotFound)?;
767- let attempt = ExamAttempt::read_for_user(exam.get_id(), user.get_id(), &st.db)831+ let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db)
768 .await?832 .await?
769 .ok_or(AppError::NotFound)?;833 .ok_or(AppError::NotFound)?;
770 let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)834 let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
771 .await?835 .await?
772 .map(|r| r.get_mark());836 .map(|r| r.get_mark());
773 let (answered, question_count) = attempt_progress(exam.get_id(), user.get_id(), &st.db).await?;837 let (answered, question_count) = attempt_progress(exam.get_id(), user.get_id(), &st.db).await?;
838+ let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?;
774 let people = PersonRef::map_of(&[&user]);839 let people = PersonRef::map_of(&[&user]);
775 Ok(Json(AttemptResponse::new(840 Ok(Json(AttemptResponse::new(
776 &attempt,841 &attempt,
@@ -779,6 +844,7 @@ async fn my_attempt(
779 &people,844 &people,
780 answered,845 answered,
781 question_count,846 question_count,
847+ used,
782 Timestamp::now(),848 Timestamp::now(),
783 )))849 )))
784 }850 }
@@ -807,7 +873,7 @@ async fn finish_attempt(
807 let exam = Exam::read(&ExamId::from_key(&id), &st.db)873 let exam = Exam::read(&ExamId::from_key(&id), &st.db)
808 .await?874 .await?
809 .ok_or(AppError::NotFound)?;875 .ok_or(AppError::NotFound)?;
810- let attempt = ExamAttempt::read_for_user(exam.get_id(), user.get_id(), &st.db)876+ let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db)
811 .await?877 .await?
812 .ok_or(AppError::NotFound)?;878 .ok_or(AppError::NotFound)?;
813 if attempt.get_finished_at().is_some() {879 if attempt.get_finished_at().is_some() {
@@ -820,11 +886,14 @@ async fn finish_attempt(
820 return Err(AppError::Conflict("time is up — the attempt has expired"));886 return Err(AppError::Conflict("time is up — the attempt has expired"));
821 }887 }
822 888
889+ // Deliberately no rejoin check: a student locked out of the room may
890+ // still submit what they saved — finishing answers nothing new.
823 let finished = attempt.finish(&st.db).await?;891 let finished = attempt.finish(&st.db).await?;
824 let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)892 let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
825 .await?893 .await?
826 .map(|r| r.get_mark());894 .map(|r| r.get_mark());
827 let (answered, question_count) = attempt_progress(exam.get_id(), user.get_id(), &st.db).await?;895 let (answered, question_count) = attempt_progress(exam.get_id(), user.get_id(), &st.db).await?;
896+ let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?;
828 let people = PersonRef::map_of(&[&user]);897 let people = PersonRef::map_of(&[&user]);
829 Ok(Json(AttemptResponse::new(898 Ok(Json(AttemptResponse::new(
830 &finished,899 &finished,
@@ -833,21 +902,29 @@ async fn finish_attempt(
833 &people,902 &people,
834 answered,903 answered,
835 question_count,904 question_count,
905+ used,
836 Timestamp::now(),906 Timestamp::now(),
837 )))907 )))
838 }908 }
839 909
840 // ---- live monitor ---------------------------------------------------------910 // ---- live monitor ---------------------------------------------------------
841 911
842-/// One roster row of the live exam monitor.912+/// One roster row of the live exam monitor. The attempt fields describe the
913+/// student's *latest* sitting.
843 #[derive(Serialize, ToSchema)]914 #[derive(Serialize, ToSchema)]
844 struct LiveStudentResponse {915 struct LiveStudentResponse {
845 user: PersonRef,916 user: PersonRef,
846 /// `not_started` | `in_progress` | `submitted` | `expired`.917 /// `not_started` | `in_progress` | `submitted` | `expired`.
847 #[schema(example = "in_progress")]918 #[schema(example = "in_progress")]
848 status: String,919 status: String,
920+ /// Which sitting the shown attempt is (1, 2, …); `null` before the first.
921+ attempt: Option<i64>,
922+ /// How many sittings this student has used.
923+ attempts_used: u64,
849 started_at: Option<i64>,924 started_at: Option<i64>,
850 finished_at: Option<i64>,925 finished_at: Option<i64>,
926+ /// When this student left the exam room mid-attempt; `null` while inside.
927+ left_at: Option<i64>,
851 /// When this student's attempt closes (server-authoritative).928 /// When this student's attempt closes (server-authoritative).
852 deadline: Option<i64>,929 deadline: Option<i64>,
853 /// Time this student has left, floored at 0; `null` unless in progress.930 /// Time this student has left, floored at 0; `null` unless in progress.
@@ -890,11 +967,24 @@ struct ExamLiveResponse {
890 async fn live_snapshot(exam: &Exam, db: &Database) -> Result<ExamLiveResponse, AppError> {967 async fn live_snapshot(exam: &Exam, db: &Database) -> Result<ExamLiveResponse, AppError> {
891 let now = Timestamp::now();968 let now = Timestamp::now();
892 let roster = Enrollment::list_for_course(exam.get_course(), db).await?;969 let roster = Enrollment::list_for_course(exam.get_course(), db).await?;
893- let attempts: HashMap<String, ExamAttempt> = ExamAttempt::list_for_exam(exam.get_id(), db)970+ // Per student: their latest sitting (the one the monitor shows) plus how
894- .await?971+ // many they've used.
895- .into_iter()972+ let mut attempts: HashMap<String, ExamAttempt> = HashMap::new();
896- .map(|attempt| (attempt.get_user().key().to_string(), attempt))973+ let mut used: HashMap<String, u64> = HashMap::new();
897- .collect();974+ for attempt in ExamAttempt::list_for_exam(exam.get_id(), db).await? {
975+ let key = attempt.get_user().key().to_string();
976+ *used.entry(key.clone()).or_insert(0) += 1;
977+ match attempts.entry(key) {
978+ std::collections::hash_map::Entry::Vacant(slot) => {
979+ slot.insert(attempt);
980+ }
981+ std::collections::hash_map::Entry::Occupied(mut slot) => {
982+ if attempt.get_seq() > slot.get().get_seq() {
983+ slot.insert(attempt);
984+ }
985+ }
986+ }
987+ }
898 let marks: HashMap<String, i64> = ExamResult::list_for_exam(exam.get_id(), db)988 let marks: HashMap<String, i64> = ExamResult::list_for_exam(exam.get_id(), db)
899 .await?989 .await?
900 .iter()990 .iter()
@@ -929,10 +1019,13 @@ async fn live_snapshot(exam: &Exam, db: &Database) -> Result<ExamLiveResponse, A
929 status: status1019 status: status
930 .map_or("not_started", AttemptStatus::as_str)1020 .map_or("not_started", AttemptStatus::as_str)
931 .to_string(),1021 .to_string(),
1022+ attempt: attempt.map(ExamAttempt::get_seq),
1023+ attempts_used: used.get(key).copied().unwrap_or(0),
932 started_at: attempt.map(|a| a.get_started_at().as_millis()),1024 started_at: attempt.map(|a| a.get_started_at().as_millis()),
933 finished_at: attempt1025 finished_at: attempt
934 .and_then(|a| a.get_finished_at())1026 .and_then(|a| a.get_finished_at())
935 .map(|t| t.as_millis()),1027 .map(|t| t.as_millis()),
1028+ left_at: attempt.and_then(|a| a.get_left_at()).map(|t| t.as_millis()),
936 deadline: deadline.map(|t| t.as_millis()),1029 deadline: deadline.map(|t| t.as_millis()),
937 remaining_ms: (status == Some(AttemptStatus::InProgress))1030 remaining_ms: (status == Some(AttemptStatus::InProgress))
938 .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0)))1031 .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0)))
@@ -1412,15 +1505,16 @@ struct AnswerSavedResponse {
1412 updated_at: i64,1505 updated_at: i64,
1413 }1506 }
1414 1507
1415-/// The caller's attempt provided it is still writable, or the error that says1508+/// The caller's latest attempt provided it is still writable, or the error
1416-/// why not: no attempt yet (404 — start it first), already submitted (409),1509+/// that says why not: no attempt yet (404 — start it first), already
1417-/// deadline passed (409). One gate shared by REST saves and the WebSocket room.1510+/// submitted (409), deadline passed (409). One gate shared by REST saves and
1511+/// the WebSocket room.
1418 pub(crate) async fn writable_attempt(1512 pub(crate) async fn writable_attempt(
1419 exam: &Exam,1513 exam: &Exam,
1420 user: &UserId,1514 user: &UserId,
1421 db: &Database,1515 db: &Database,
1422 ) -> Result<ExamAttempt, AppError> {1516 ) -> Result<ExamAttempt, AppError> {
1423- let attempt = ExamAttempt::read_for_user(exam.get_id(), user, db)1517+ let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user, db)
1424 .await?1518 .await?
1425 .ok_or(AppError::NotFound)?;1519 .ok_or(AppError::NotFound)?;
1426 match attempt.status(exam, Timestamp::now()) {1520 match attempt.status(exam, Timestamp::now()) {
@@ -1430,9 +1524,23 @@ pub(crate) async fn writable_attempt(
1430 }1524 }
1431 }1525 }
1432 1526
1527+/// A 409 when the student has walked out of the exam room and the exam's
1528+/// rejoin door is closed: no more answering (from anywhere) until the teacher
1529+/// flips `allow_rejoin` back on. Finishing is deliberately exempt — see
1530+/// `finish_attempt`.
1531+pub(crate) fn check_rejoin(exam: &Exam, attempt: &ExamAttempt) -> Result<(), AppError> {
1532+ if attempt.get_left_at().is_some() && !exam.get_allow_rejoin() {
1533+ return Err(AppError::Conflict(
1534+ "you left the exam and rejoin is closed — ask your teacher to reopen it",
1535+ ));
1536+ }
1537+ Ok(())
1538+}
1539+
1433 /// Save one answer inside the caller's in-progress attempt — the whole write1540 /// Save one answer inside the caller's in-progress attempt — the whole write
1434-/// path (attempt gate, question lookup, kind check, upsert), shared verbatim1541+/// path (attempt gate, rejoin gate, question lookup, kind check, upsert),
1435-/// by the REST handler and the WebSocket room so the two can never drift.1542+/// shared verbatim by the REST handler and the WebSocket room so the two can
1543+/// never drift.
1436 pub(crate) async fn save_answer_checked(1544 pub(crate) async fn save_answer_checked(
1437 exam: &Exam,1545 exam: &Exam,
1438 user: &UserId,1546 user: &UserId,
@@ -1441,7 +1549,8 @@ pub(crate) async fn save_answer_checked(
1441 text: Option<String>,1549 text: Option<String>,
1442 db: &Database,1550 db: &Database,
1443 ) -> Result<ExamAnswer, AppError> {1551 ) -> Result<ExamAnswer, AppError> {
1444- writable_attempt(exam, user, db).await?;1552+ let attempt = writable_attempt(exam, user, db).await?;
1553+ check_rejoin(exam, &attempt)?;
1445 let question = question_of_exam(exam.get_id(), question_id, db).await?;1554 let question = question_of_exam(exam.get_id(), question_id, db).await?;
1446 ExamAnswer::save(&question, user, selected, text, db).await1555 ExamAnswer::save(&question, user, selected, text, db).await
1447 }1556 }
@@ -1472,7 +1581,7 @@ async fn attempt_questions(
1472 .ok_or(AppError::NotFound)?;1581 .ok_or(AppError::NotFound)?;
1473 // The question list is for sitting students; without an attempt there is1582 // The question list is for sitting students; without an attempt there is
1474 // nothing to sit behind — and no early peek at the questions.1583 // nothing to sit behind — and no early peek at the questions.
1475- ExamAttempt::read_for_user(exam.get_id(), user.get_id(), &st.db)1584+ ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db)
1476 .await?1585 .await?
1477 .ok_or(AppError::NotFound)?;1586 .ok_or(AppError::NotFound)?;
1478 1587
@@ -1505,7 +1614,8 @@ async fn attempt_questions(
1505 /// Save (or overwrite) one answer in the caller's in-progress attempt.1614 /// Save (or overwrite) one answer in the caller's in-progress attempt.
1506 /// `choice` questions take `selected`; `text` questions take `text`. Rejected1615 /// `choice` questions take `selected`; `text` questions take `text`. Rejected
1507 /// once the attempt is submitted or its deadline has passed — the server1616 /// once the attempt is submitted or its deadline has passed — the server
1508-/// clock, not the client's, is the judge.1617+/// clock, not the client's, is the judge — and rejected while the student has
1618+/// left the exam room with the exam's rejoin door closed.
1509 #[utoipa::path(1619 #[utoipa::path(
1510 post,1620 post,
1511 path = "/{id}/attempt/answers",1621 path = "/{id}/attempt/answers",
@@ -1518,7 +1628,7 @@ async fn attempt_questions(
1518 (status = 400, description = "Payload doesn't match the question's kind", body = ErrorResponse),1628 (status = 400, description = "Payload doesn't match the question's kind", body = ErrorResponse),
1519 (status = 401, description = "Not authenticated", body = ErrorResponse),1629 (status = 401, description = "Not authenticated", body = ErrorResponse),
1520 (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse),1630 (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse),
1521- (status = 409, description = "Attempt already submitted, or time is up", body = ErrorResponse),1631+ (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse),
1522 ),1632 ),
1523 )]1633 )]
1524 async fn save_answer(1634 async fn save_answer(
@@ -1584,8 +1694,9 @@ async fn attempt_answers(
1584 ));1694 ));
1585 }1695 }
1586 let target = UserId::from_key(&target);1696 let target = UserId::from_key(&target);
1587- // No attempt means no answer sheet — a 404, not an empty one.1697+ // No attempt means no answer sheet — a 404, not an empty one. Answers are
1588- ExamAttempt::read_for_user(exam.get_id(), &target, &st.db)1698+ // always the latest sitting's: a retake starts from a blank sheet.
1699+ ExamAttempt::read_latest_for_user(exam.get_id(), &target, &st.db)
1589 .await?1700 .await?
1590 .ok_or(AppError::NotFound)?;1701 .ok_or(AppError::NotFound)?;
1591 1702