forge
Explore
Log in

Don't you dare go Hollow

Stamp walk-outs per sitting, wipe retakes atomically

Browse files at this commit

6eb0a28eb3aa2bba065e59b8ce0c9d5f14719791Ahmet Kaan GümüşParent: 7341f2f
  • fix
    • stamp walk-outs per sitting, wipe retakes atomically
Show full message
🐛 fix(exams): stamp walk-outs per sitting, wipe retakes atomically

Three bugs in the attempts/rejoin build, each a wrongful lockout or
data loss once allow_rejoin is off:

- A room's teardown stamped left_at on the *latest* attempt, so a
  stale socket from a finished sitting marked a fresh retake as left,
  locking the student out of a room they never entered. Rooms now
  bind to the sitting they were opened for: state frames and the
  walk-out stamp re-read that attempt by id, never "latest", so a
  superseded room announces its own terminal state and closes.
- Closing one of two tabs counted as leaving while the student was
  still connected. ExamPresence (AppState) counts sockets per
  attempt; only the last socket out stamps the walk-out.
- The retake answer-wipe ran before the attempt create, so a lost
  double-start race could delete answers freshly saved into the
  winner's sitting — or destroy a graded sheet with no retake ever
  created. Wipe + create now run in one transaction and a failed
  create rolls the wipe back. (SurrealDB counts BEGIN/COMMIT as
  response slots: the CREATE result is slot 2.)

Regression tests: e2e rooms for the retake stamp and the second tab,
domain tests for the atomic wipe and the lost race (verified red
against the old ordering), presence unit test. README rejoin
paragraph aligned with the per-sitting semantics.
README.mdmodified+5 -3
@@ -554,9 +554,11 @@ moves the room's countdown on the next tick, and no stale socket can write
554 past its real deadline — the socket shares the exact REST write path.554 past its real deadline — the socket shares the exact REST write path.
555 555
556 The room is also the presence signal behind the **rejoin door**: connecting556 The room is also the presence signal behind the **rejoin door**: connecting
557-clears the attempt's `left_at`, and a socket that closes while the sitting is557+clears the attempt's `left_at`, and the *last* socket of the sitting to close
558-still running stamps it (visible on the live monitor — "left the room three558+while it is still running stamps it (visible on the live monitor — "left the
559-minutes ago" at a glance). With the exam's `allow_rejoin` off, a stamped559+room three minutes ago" at a glance). Closing one of two tabs is not leaving,
560+and a lingering socket from an already-finished sitting never marks a later
561+retake as left — each room is bound to the sitting it was opened for. With the exam's `allow_rejoin` off, a stamped
560 `left_at` refuses re-entry *and* any further saves, over the socket or REST,562 `left_at` refuses re-entry *and* any further saves, over the socket or REST,
561 until the teacher flips the door back open (`PATCH /exams/{id}563 until the teacher flips the door back open (`PATCH /exams/{id}
562 {"allow_rejoin": true}` — live, like the times). Finishing stays allowed: a564 {"allow_rejoin": true}` — live, like the times). Finishing stays allowed: a
src/domain/exam_attempt.rsmodified+168 -9
@@ -3,7 +3,6 @@ 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;
7 use crate::domain::timestamp::Timestamp;6 use crate::domain::timestamp::Timestamp;
8 use crate::domain::user::UserId;7 use crate::domain::user::UserId;
9 use crate::error::AppError;8 use crate::error::AppError;
@@ -153,9 +152,10 @@ impl ExamAttempt {
153 /// - A terminal latest attempt (submitted or expired) starts sitting152 /// - A terminal latest attempt (submitted or expired) starts sitting
154 /// `seq + 1` if the exam's `max_attempts` allows another, and is a153 /// `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's154 /// conflict otherwise. A retake begins from a blank sheet: the student's
156- /// previous answers are wiped first. Wiping *before* creating keeps the155+ /// previous answers are wiped in the same transaction that creates the
157- /// race benign — until the new row exists, saves still hit the terminal156+ /// new row ([`Self::wipe_and_create`]), so a lost race (or a failed
158- /// attempt and are rejected, so no fresh answer can be lost to the wipe.157+ /// create) rolls the wipe back — no answer sheet is ever destroyed
158+ /// without its retake existing.
159 ///159 ///
160 /// The composite id makes each create atomic; a concurrent double-start160 /// 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's161 /// races on the same seq, loses to the unique id, and reads the winner's
@@ -180,9 +180,6 @@ impl ExamAttempt {
180 latest.seq + 1180 latest.seq + 1
181 }181 }
182 };182 };
183- if next_seq > 1 {
184- ExamAnswer::delete_for_exam_user(exam.get_id(), user, db).await?;
185- }
186 let attempt = ExamAttempt {183 let attempt = ExamAttempt {
187 id: ExamAttemptId::composite(exam.get_id(), user, next_seq),184 id: ExamAttemptId::composite(exam.get_id(), user, next_seq),
188 exam: exam.get_id().clone(),185 exam: exam.get_id().clone(),
@@ -192,8 +189,11 @@ impl ExamAttempt {
192 finished_at: None,189 finished_at: None,
193 left_at: None,190 left_at: None,
194 };191 };
195- let created: Result<Option<ExamAttempt>, surrealdb::Error> =192+ let created: Result<Option<ExamAttempt>, surrealdb::Error> = if next_seq == 1 {
196- db.create(attempt.id.record()).content(attempt).await;193+ db.create(attempt.id.record()).content(attempt).await
194+ } else {
195+ Self::wipe_and_create(attempt, db).await
196+ };
197 match created {197 match created {
198 Ok(Some(created)) => Ok((created, true)),198 Ok(Some(created)) => Ok((created, true)),
199 Ok(None) => Err(AppError::Internal("failed to start exam attempt".into())),199 Ok(None) => Err(AppError::Internal("failed to start exam attempt".into())),
@@ -204,6 +204,33 @@ impl ExamAttempt {
204 }204 }
205 }205 }
206 206
207+ /// Wipe the student's previous answers and create the retake row in one
208+ /// transaction. Atomicity is the point: a create that fails (a concurrent
209+ /// double-start lost the race on the composite id, or the database
210+ /// hiccuped) cancels the whole transaction, wipe included — otherwise a
211+ /// stale loser could delete answers freshly saved into the winner's
212+ /// sitting, or destroy a graded sheet without a retake ever existing.
213+ async fn wipe_and_create(
214+ attempt: ExamAttempt,
215+ db: &Database,
216+ ) -> Result<Option<ExamAttempt>, surrealdb::Error> {
217+ let mut result = db
218+ .query(
219+ "BEGIN TRANSACTION;
220+ DELETE exam_answer WHERE exam = $ex AND user = $usr;
221+ CREATE $id CONTENT $attempt;
222+ COMMIT TRANSACTION;",
223+ )
224+ .bind(("ex", attempt.exam.record()))
225+ .bind(("usr", attempt.user.record()))
226+ .bind(("id", attempt.id.record()))
227+ .bind(("attempt", attempt))
228+ .await?
229+ .check()?;
230+ // Statement slots count BEGIN and COMMIT too: the CREATE is slot 2.
231+ Ok(result.take::<Vec<ExamAttempt>>(2)?.into_iter().next())
232+ }
233+
207 /// Stamp the submission time. The caller has already checked the deadline234 /// Stamp the submission time. The caller has already checked the deadline
208 /// and that the attempt isn't finished.235 /// and that the attempt isn't finished.
209 pub async fn finish(mut self, db: &Database) -> Result<ExamAttempt, AppError> {236 pub async fn finish(mut self, db: &Database) -> Result<ExamAttempt, AppError> {
@@ -224,6 +251,12 @@ impl ExamAttempt {
224 updated.ok_or(AppError::NotFound)251 updated.ok_or(AppError::NotFound)
225 }252 }
226 253
254+ /// One sitting by id — the exam room re-reads its own attempt this way,
255+ /// so a retake started elsewhere can never be mistaken for it.
256+ pub async fn read(id: &ExamAttemptId, db: &Database) -> Result<Option<ExamAttempt>, AppError> {
257+ Ok(db.select(id.record()).await?)
258+ }
259+
227 /// The student's current sitting — the highest `seq` for the pair. All260 /// The student's current sitting — the highest `seq` for the pair. All
228 /// reads that used to mean "the attempt" mean this now.261 /// reads that used to mean "the attempt" mean this now.
229 pub async fn read_latest_for_user(262 pub async fn read_latest_for_user(
@@ -281,3 +314,129 @@ impl ExamAttempt {
281 Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())314 Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
282 }315 }
283 }316 }
317+
318+#[cfg(test)]
319+mod tests {
320+ use super::*;
321+ use crate::database::init_mem;
322+ use crate::domain::course::CourseId;
323+ use crate::domain::exam::{
324+ ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, ExamWeight,
325+ };
326+ use crate::domain::exam_answer::ExamAnswer;
327+ use crate::domain::exam_question::{ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec};
328+ use crate::domain::settings::Settings;
329+
330+ /// An open exam with retakes allowed, plus one choice question — enough
331+ /// rows to exercise the attempt lifecycle without the HTTP layer.
332+ async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) {
333+ let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
334+ let course = CourseId::from_key("01TESTCOURSEAAAAAAAAAAAAAA");
335+ let kinds = Settings::defaults().get_exam_kinds().to_vec();
336+ let exam = Exam::create(
337+ &creator,
338+ &course,
339+ ExamTitle::try_new("practice").unwrap(),
340+ ExamDescription::try_new("").unwrap(),
341+ ExamKind::try_new("quiz", &kinds).unwrap(),
342+ ExamWeight::try_new(1).unwrap(),
343+ ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None)
344+ .unwrap(),
345+ ExamAttemptLimit::try_new(max_attempts).unwrap(),
346+ true,
347+ db,
348+ )
349+ .await
350+ .unwrap();
351+ let spec = QuestionSpec::try_new(
352+ QuestionKind::try_new("choice").unwrap(),
353+ Some(vec!["5".into(), "6".into()]),
354+ Some(1),
355+ )
356+ .unwrap();
357+ let question = ExamQuestion::create(
358+ exam.get_id(),
359+ crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(),
360+ QuestionPoints::try_new(5).unwrap(),
361+ spec,
362+ db,
363+ )
364+ .await
365+ .unwrap();
366+ (exam, question)
367+ }
368+
369+ fn student() -> UserId {
370+ UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA")
371+ }
372+
373+ #[tokio::test]
374+ async fn a_retake_starts_from_a_blank_sheet() {
375+ let db = init_mem().await.unwrap();
376+ let (exam, question) = open_exam_with_question(&db, 2).await;
377+ let user = student();
378+
379+ let (first, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
380+ assert!(created);
381+ assert_eq!(first.get_seq(), 1);
382+ ExamAnswer::save(&question, &user, Some(1), None, &db)
383+ .await
384+ .unwrap();
385+ first.finish(&db).await.unwrap();
386+
387+ // The retake lands as sitting #2 with the sheet wiped in the same
388+ // transaction that created it.
389+ let (second, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
390+ assert!(created);
391+ assert_eq!(second.get_seq(), 2);
392+ let answers = ExamAnswer::list_for_exam_user(exam.get_id(), &user, &db)
393+ .await
394+ .unwrap();
395+ assert!(answers.is_empty(), "a retake starts blank");
396+ }
397+
398+ #[tokio::test]
399+ async fn a_lost_retake_race_cannot_wipe_the_winners_sheet() {
400+ let db = init_mem().await.unwrap();
401+ let (exam, question) = open_exam_with_question(&db, 3).await;
402+ let user = student();
403+
404+ // Sitting #1 ends; the winner starts sitting #2 and saves an answer.
405+ let (first, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
406+ first.finish(&db).await.unwrap();
407+ let (winner, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
408+ assert!(created);
409+ assert_eq!(winner.get_seq(), 2);
410+ ExamAnswer::save(&question, &user, Some(1), None, &db)
411+ .await
412+ .unwrap();
413+
414+ // A stale double-start races on the same seq and loses to the
415+ // composite id — and the aborted transaction must roll its wipe back,
416+ // leaving the winner's fresh answer untouched.
417+ let loser = ExamAttempt {
418+ id: ExamAttemptId::composite(exam.get_id(), &user, 2),
419+ exam: exam.get_id().clone(),
420+ user: user.clone(),
421+ seq: 2,
422+ started_at: Timestamp::now(),
423+ finished_at: None,
424+ left_at: None,
425+ };
426+ let lost = ExamAttempt::wipe_and_create(loser, &db).await;
427+ assert!(lost.is_err(), "the duplicate create must fail");
428+ let answers = ExamAnswer::list_for_exam_user(exam.get_id(), &user, &db)
429+ .await
430+ .unwrap();
431+ assert_eq!(
432+ answers.len(),
433+ 1,
434+ "the lost race must not wipe the winner's saved answer"
435+ );
436+
437+ // The public path shrugs the race off: a re-start resumes the winner.
438+ let (resumed, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
439+ assert!(!created);
440+ assert_eq!(resumed.get_seq(), 2);
441+ }
442+}
src/main.rsmodified+1 -0
@@ -22,6 +22,7 @@ async fn main() -> anyhow::Result<()> {
22 db,22 db,
23 cookie_secure: cfg.cookie_secure,23 cookie_secure: cfg.cookie_secure,
24 rate_limit: cfg.rate_limit.clone(),24 rate_limit: cfg.rate_limit.clone(),
25+ exam_presence: Default::default(),
25 });26 });
26 27
27 let addr = format!("{}:{}", cfg.host, cfg.port);28 let addr = format!("{}:{}", cfg.host, cfg.port);
src/state.rsmodified+63 -0
@@ -1,3 +1,6 @@
1+use std::collections::HashMap;
2+use std::sync::{Arc, Mutex};
3+
1 use crate::database::Database;4 use crate::database::Database;
2 use crate::rate_limit::RateLimitConfig;5 use crate::rate_limit::RateLimitConfig;
3 6
@@ -11,4 +14,64 @@ pub struct AppState {
11 /// Per-IP request limits (from [`crate::config::Config::rate_limit`]).14 /// Per-IP request limits (from [`crate::config::Config::rate_limit`]).
12 /// Read once by [`crate::build_router`] when the limiters are built.15 /// Read once by [`crate::build_router`] when the limiters are built.
13 pub rate_limit: RateLimitConfig,16 pub rate_limit: RateLimitConfig,
17+ /// Who is inside which exam room right now (see [`ExamPresence`]).
18+ pub exam_presence: ExamPresence,
19+}
20+
21+/// How many exam-room sockets each attempt has open right now, keyed by the
22+/// attempt's record key. The room counts itself in on entry and out on exit,
23+/// and only the last socket out stamps the walk-out (`left_at`) — a student
24+/// closing one of two tabs never counts as having left the exam.
25+#[derive(Clone, Default)]
26+pub struct ExamPresence(Arc<Mutex<HashMap<String, usize>>>);
27+
28+impl ExamPresence {
29+ /// Count one socket into `attempt`'s room.
30+ pub fn enter(&self, attempt: &str) {
31+ let mut rooms = self.0.lock().expect("exam presence lock");
32+ *rooms.entry(attempt.to_string()).or_insert(0) += 1;
33+ }
34+
35+ /// Count one socket out of `attempt`'s room; `true` when it was the last
36+ /// one — the student has actually left.
37+ pub fn leave(&self, attempt: &str) -> bool {
38+ let mut rooms = self.0.lock().expect("exam presence lock");
39+ match rooms.get_mut(attempt) {
40+ Some(count) if *count > 1 => {
41+ *count -= 1;
42+ false
43+ }
44+ Some(_) => {
45+ rooms.remove(attempt);
46+ true
47+ }
48+ // Unbalanced (an enter was lost) — treat the close as a real exit
49+ // rather than leaving the walk-out unrecorded forever.
50+ None => true,
51+ }
52+ }
53+}
54+
55+#[cfg(test)]
56+mod tests {
57+ use super::*;
58+
59+ #[tokio::test]
60+ async fn only_the_last_socket_out_is_a_real_exit() {
61+ let presence = ExamPresence::default();
62+ presence.enter("attempt-a");
63+ presence.enter("attempt-a");
64+ assert!(
65+ !presence.leave("attempt-a"),
66+ "one tab of two is not an exit"
67+ );
68+ assert!(presence.leave("attempt-a"), "the last tab out is");
69+ // Rooms are independent, and a fresh key starts over.
70+ presence.enter("attempt-b");
71+ presence.enter("attempt-a");
72+ assert!(presence.leave("attempt-b"));
73+ assert!(presence.leave("attempt-a"));
74+ // Unbalanced leaves degrade to "really left", never to a stuck room.
75+ assert!(presence.leave("attempt-a"));
76+ }
14 }77 }
src/web/exam_ws.rsmodified+50 -31
@@ -27,10 +27,17 @@
27 //! never write past its real deadline.27 //! never write past its real deadline.
28 //!28 //!
29 //! The room is also the presence signal behind the rejoin policy: connecting29 //! 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 attempt30+//! clears the attempt's `left_at`, and the *last* socket of the sitting to
31-//! is still running stamps it. With the exam's `allow_rejoin` off, a stamped31+//! close while the attempt is still running stamps it — a student closing one
32-//! `left_at` refuses re-entry (and any further saves, here or over REST) until32+//! of two tabs hasn't left, and a lingering socket from an already-finished
33-//! the teacher flips the door back open; finishing stays allowed.33+//! sitting can never mark a later retake as left. With the exam's
34+//! `allow_rejoin` off, a stamped `left_at` refuses re-entry (and any further
35+//! saves, here or over REST) until the teacher flips the door back open;
36+//! finishing stays allowed.
37+//!
38+//! Each room is bound to the sitting it was opened for: state frames track
39+//! that attempt (not whatever is latest), so a room whose sitting ends —
40+//! submitted or expired anywhere — announces it and closes.
34 41
35 use std::time::Duration;42 use std::time::Duration;
36 43
@@ -45,7 +52,7 @@ use crate::database::Database;
45 use crate::domain::enrollment::Enrollment;52 use crate::domain::enrollment::Enrollment;
46 use crate::domain::exam::{Exam, ExamId};53 use crate::domain::exam::{Exam, ExamId};
47 use crate::domain::exam_answer::ExamAnswer;54 use crate::domain::exam_answer::ExamAnswer;
48-use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt};55+use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId};
49 use crate::domain::exam_question::ExamQuestion;56 use crate::domain::exam_question::ExamQuestion;
50 use crate::domain::timestamp::Timestamp;57 use crate::domain::timestamp::Timestamp;
51 use crate::domain::user::UserId;58 use crate::domain::user::UserId;
@@ -99,24 +106,30 @@ pub async fn attempt_ws(
99 }106 }
100 let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?;107 let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?;
101 check_rejoin(&exam, &attempt)?;108 check_rejoin(&exam, &attempt)?;
102- if attempt.get_left_at().is_some() {109+ let attempt = if attempt.get_left_at().is_some() {
103- attempt.set_left(None, &st.db).await?;110+ attempt.set_left(None, &st.db).await?
104- }111+ } else {
112+ attempt
113+ };
105 114
106 let user_id = user.get_id().clone();115 let user_id = user.get_id().clone();
107- Ok(ws.on_upgrade(move |socket| room(socket, st, exam, user_id)))116+ Ok(ws.on_upgrade(move |socket| room(socket, st, exam, attempt, user_id)))
108 }117 }
109 118
110 /// The room loop: state ticks out, answer/finish/ping in, until the socket119 /// The room loop: state ticks out, answer/finish/ping in, until the socket
111-/// closes or the attempt reaches a terminal state.120+/// closes or the room's sitting reaches a terminal state. The room is bound
112-async fn room(mut socket: WebSocket, st: AppState, exam: Exam, user: UserId) {121+/// to the attempt it was opened for — `attempt` — and to no later sitting.
122+async fn room(mut socket: WebSocket, st: AppState, exam: Exam, attempt: ExamAttempt, user: UserId) {
113 let exam_id = exam.get_id().clone();123 let exam_id = exam.get_id().clone();
124+ let attempt_id = attempt.get_id().clone();
125+ // This socket counts as presence in the sitting's room until it closes.
126+ st.exam_presence.enter(attempt_id.key());
114 let mut tick = tokio::time::interval(Duration::from_secs(EXAM_WS_TICK_SECS));127 let mut tick = tokio::time::interval(Duration::from_secs(EXAM_WS_TICK_SECS));
115 loop {128 loop {
116 tokio::select! {129 tokio::select! {
117 // First tick fires immediately — the connect-time state frame.130 // First tick fires immediately — the connect-time state frame.
118 _ = tick.tick() => {131 _ = tick.tick() => {
119- if push_state(&mut socket, &exam_id, &user, &st.db).await.is_err() {132+ if push_state(&mut socket, &exam_id, &attempt_id, &st.db).await.is_err() {
120 break;133 break;
121 }134 }
122 }135 }
@@ -128,7 +141,7 @@ async fn room(mut socket: WebSocket, st: AppState, exam: Exam, user: UserId) {
128 Some(Ok(Message::Close(_))) | Some(Err(_)) | None => break,141 Some(Ok(Message::Close(_))) | Some(Err(_)) | None => break,
129 Some(Ok(_)) => continue,142 Some(Ok(_)) => continue,
130 };143 };
131- if handle_message(&mut socket, text.as_str(), &exam_id, &user, &st.db)144+ if handle_message(&mut socket, text.as_str(), &exam_id, &attempt_id, &user, &st.db)
132 .await145 .await
133 .is_err()146 .is_err()
134 {147 {
@@ -140,19 +153,23 @@ async fn room(mut socket: WebSocket, st: AppState, exam: Exam, user: UserId) {
140 // Best-effort closing handshake — a bare TCP teardown reads as an error153 // Best-effort closing handshake — a bare TCP teardown reads as an error
141 // on the client; a Close frame reads as "the room is over".154 // on the client; a Close frame reads as "the room is over".
142 let _ = socket.send(Message::Close(None)).await;155 let _ = socket.send(Message::Close(None)).await;
143- // The student is out of the room. If their attempt is still running,156+ // Only the last socket out means the student actually left the room. If
144- // stamp the walk-out — with `allow_rejoin` off this is what locks further157+ // this sitting is still running, stamp the walk-out — with `allow_rejoin`
145- // answering. Terminal exits (finished/expired) need no stamp. Best-effort:158+ // off this is what locks further answering. Terminal exits (finished or
146- // a failed stamp only means the walk-out goes unrecorded.159+ // expired, and any sitting superseded by a retake is terminal) need no
147- stamp_left(&exam_id, &user, &st.db).await;160+ // stamp. Best-effort: a failed stamp only means it goes unrecorded.
161+ if st.exam_presence.leave(attempt_id.key()) {
162+ stamp_left(&exam_id, &attempt_id, &st.db).await;
163+ }
148 }164 }
149 165
150-/// Stamp `left_at` on the student's latest attempt if it is still in166+/// Stamp `left_at` on the room's own sitting if it is still in progress —
151-/// progress — re-reading both rows so a finish or expiry that raced the167+/// re-reading both rows so a finish or expiry that raced the socket close
152-/// socket close wins.168+/// wins. Targeting the sitting by id (never "the latest") means a retake
153-async fn stamp_left(exam_id: &ExamId, user: &UserId, db: &Database) {169+/// started elsewhere can't be marked as left by an old room's teardown.
170+async fn stamp_left(exam_id: &ExamId, attempt_id: &ExamAttemptId, db: &Database) {
154 let attempt = match Exam::read(exam_id, db).await {171 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 {172+ Ok(Some(exam)) => match ExamAttempt::read(attempt_id, db).await {
156 Ok(Some(attempt))173 Ok(Some(attempt))
157 if attempt.status(&exam, Timestamp::now()) == AttemptStatus::InProgress =>174 if attempt.status(&exam, Timestamp::now()) == AttemptStatus::InProgress =>
158 {175 {
@@ -189,14 +206,15 @@ async fn send(socket: &mut WebSocket, frame: Value) -> Result<(), RoomClosed> {
189 }206 }
190 207
191 /// Re-read everything, push a `state` frame, and close the room (after a208 /// Re-read everything, push a `state` frame, and close the room (after a
192-/// `finished`/`expired` notice) once the attempt is no longer in progress.209+/// `finished`/`expired` notice) once the room's sitting is no longer in
210+/// progress.
193 async fn push_state(211 async fn push_state(
194 socket: &mut WebSocket,212 socket: &mut WebSocket,
195 exam: &ExamId,213 exam: &ExamId,
196- user: &UserId,214+ attempt: &ExamAttemptId,
197 db: &Database,215 db: &Database,
198 ) -> Result<(), RoomClosed> {216 ) -> Result<(), RoomClosed> {
199- let (frame, status, finished_at) = match state_frame(exam, user, db).await {217+ let (frame, status, finished_at) = match state_frame(exam, attempt, db).await {
200 Ok(state) => state,218 Ok(state) => state,
201 // The exam vanished mid-room (deleted) or the db hiccuped: nothing219 // The exam vanished mid-room (deleted) or the db hiccuped: nothing
202 // sensible left to serve.220 // sensible left to serve.
@@ -228,15 +246,15 @@ async fn push_state(
228 }246 }
229 }247 }
230 248
231-/// One server-judged snapshot of the attempt, shaped like the REST249+/// One server-judged snapshot of the room's own sitting, shaped like the REST
232 /// `AttemptResponse`'s live fields.250 /// `AttemptResponse`'s live fields.
233 async fn state_frame(251 async fn state_frame(
234 exam: &ExamId,252 exam: &ExamId,
235- user: &UserId,253+ attempt: &ExamAttemptId,
236 db: &Database,254 db: &Database,
237 ) -> Result<(Value, AttemptStatus, Option<i64>), AppError> {255 ) -> Result<(Value, AttemptStatus, Option<i64>), AppError> {
238 let exam = Exam::read(exam, db).await?.ok_or(AppError::NotFound)?;256 let exam = Exam::read(exam, db).await?.ok_or(AppError::NotFound)?;
239- let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user, db)257+ let attempt = ExamAttempt::read(attempt, db)
240 .await?258 .await?
241 .ok_or(AppError::NotFound)?;259 .ok_or(AppError::NotFound)?;
242 let now = Timestamp::now();260 let now = Timestamp::now();
@@ -245,7 +263,7 @@ async fn state_frame(
245 let remaining_ms = (status == AttemptStatus::InProgress)263 let remaining_ms = (status == AttemptStatus::InProgress)
246 .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0)))264 .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0)))
247 .flatten();265 .flatten();
248- let answered = ExamAnswer::list_for_exam_user(exam.get_id(), user, db)266+ let answered = ExamAnswer::list_for_exam_user(exam.get_id(), attempt.get_user(), db)
249 .await?267 .await?
250 .len();268 .len();
251 let question_count = ExamQuestion::list_for_exam(exam.get_id(), db).await?.len();269 let question_count = ExamQuestion::list_for_exam(exam.get_id(), db).await?.len();
@@ -270,6 +288,7 @@ async fn handle_message(
270 socket: &mut WebSocket,288 socket: &mut WebSocket,
271 text: &str,289 text: &str,
272 exam_id: &ExamId,290 exam_id: &ExamId,
291+ attempt_id: &ExamAttemptId,
273 user: &UserId,292 user: &UserId,
274 db: &Database,293 db: &Database,
275 ) -> Result<(), RoomClosed> {294 ) -> Result<(), RoomClosed> {
@@ -312,7 +331,7 @@ async fn handle_message(
312 .await?;331 .await?;
313 // Progress changed — refresh the countdown/answered state332 // Progress changed — refresh the countdown/answered state
314 // right away rather than waiting out the tick.333 // right away rather than waiting out the tick.
315- push_state(socket, exam_id, user, db).await334+ push_state(socket, exam_id, attempt_id, db).await
316 }335 }
317 Err(err) => send(socket, error_frame(&err)).await,336 Err(err) => send(socket, error_frame(&err)).await,
318 }337 }
tests/common/mod.rsmodified+1 -0
@@ -30,6 +30,7 @@ pub async fn app_and_db() -> (Router, Database) {
30 // Off, so suites hammering the API never trip a limit; the dedicated30 // Off, so suites hammering the API never trip a limit; the dedicated
31 // `rate_limit` test binary opts into tight configs on purpose.31 // `rate_limit` test binary opts into tight configs on purpose.
32 rate_limit: RateLimitConfig::unlimited(),32 rate_limit: RateLimitConfig::unlimited(),
33+ exam_presence: Default::default(),
33 });34 });
34 (app, db)35 (app, db)
35 }36 }
tests/e2e.rsmodified+180 -0
@@ -19,6 +19,7 @@ async fn spawn_server() -> (String, Database) {
19 // Every request here comes from 127.0.0.1, so per-IP limits would19 // Every request here comes from 127.0.0.1, so per-IP limits would
20 // meter the whole suite as one client. Off; `rate_limit.rs` covers it.20 // meter the whole suite as one client. Off; `rate_limit.rs` covers it.
21 rate_limit: RateLimitConfig::unlimited(),21 rate_limit: RateLimitConfig::unlimited(),
22+ exam_presence: Default::default(),
22 });23 });
23 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();24 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
24 let addr = listener.local_addr().unwrap();25 let addr = listener.local_addr().unwrap();
@@ -1161,6 +1162,185 @@ async fn exam_room_rejoin_door_is_the_teachers_call() {
1161 assert_eq!(res.status(), StatusCode::OK, "finish is exempt from rejoin");1162 assert_eq!(res.status(), StatusCode::OK, "finish is exempt from rejoin");
1162 }1163 }
1163 1164
1165+/// A walk-out stamp belongs to the sitting the room was opened for — never to
1166+/// a retake started while the old socket lingered. Closing the stale room of a
1167+/// finished sitting must not mark the *new* sitting as left (with the door
1168+/// closed, that stamp would lock the student out of an exam room they never
1169+/// entered).
1170+#[tokio::test]
1171+async fn exam_room_close_after_a_retake_leaves_the_new_sitting_alone() {
1172+ let room = exam_room_fixture(600_000).await;
1173+
1174+ // An open exam with two sittings and the rejoin door closed.
1175+ let exam: Value = room
1176+ .teacher
1177+ .post(format!("{}/courses/{}/exams", room.base, room.course_id))
1178+ .json(&json!({
1179+ "title": "practice", "kind": "quiz", "weight": 1,
1180+ "mode": "open", "max_attempts": 2, "allow_rejoin": false,
1181+ }))
1182+ .send()
1183+ .await
1184+ .unwrap()
1185+ .json()
1186+ .await
1187+ .unwrap();
1188+ let exam_id = exam["id"].as_str().unwrap().to_string();
1189+ let question: Value = room
1190+ .teacher
1191+ .post(format!("{}/exams/{exam_id}/questions", room.base))
1192+ .json(&json!({ "text": "3 + 3?", "kind": "choice", "points": 5,
1193+ "choices": ["5", "6"], "correct": 1 }))
1194+ .send()
1195+ .await
1196+ .unwrap()
1197+ .json()
1198+ .await
1199+ .unwrap();
1200+ let question_id = question["id"].as_str().unwrap().to_string();
1201+
1202+ // Sit sitting #1 and open its room.
1203+ let res = room
1204+ .student
1205+ .post(format!("{}/exams/{exam_id}/attempt", room.base))
1206+ .send()
1207+ .await
1208+ .unwrap();
1209+ assert_eq!(res.status(), StatusCode::CREATED);
1210+ let mut ws = ws_open(&room.base, &exam_id, Some(&room.cookie))
1211+ .await
1212+ .expect("room for sitting #1");
1213+ let state = ws_next_frame(&mut ws).await.expect("connect state");
1214+ assert_eq!(state["attempt"], 1, "{state}");
1215+
1216+ // Finish sitting #1 and start sitting #2 over REST — the old socket is
1217+ // still open while the retake begins.
1218+ let res = room
1219+ .student
1220+ .post(format!("{}/exams/{exam_id}/attempt/finish", room.base))
1221+ .send()
1222+ .await
1223+ .unwrap();
1224+ assert_eq!(res.status(), StatusCode::OK);
1225+ let res = room
1226+ .student
1227+ .post(format!("{}/exams/{exam_id}/attempt", room.base))
1228+ .send()
1229+ .await
1230+ .unwrap();
1231+ assert_eq!(res.status(), StatusCode::CREATED);
1232+ let body: Value = res.json().await.unwrap();
1233+ assert_eq!(body["attempt"], 2);
1234+
1235+ // Now walk out of the stale sitting-#1 room and give the teardown time.
1236+ ws.close(None).await.unwrap();
1237+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
1238+
1239+ // Sitting #2 was never entered, so it was never left: no stamp, and
1240+ // answering it works despite the closed door.
1241+ let attempt: Value = room
1242+ .student
1243+ .get(format!("{}/exams/{exam_id}/attempt", room.base))
1244+ .send()
1245+ .await
1246+ .unwrap()
1247+ .json()
1248+ .await
1249+ .unwrap();
1250+ assert_eq!(attempt["attempt"], 2, "{attempt}");
1251+ assert!(
1252+ attempt["left_at"].is_null(),
1253+ "closing the old sitting's room must not stamp the new sitting: {attempt}"
1254+ );
1255+ let res = room
1256+ .student
1257+ .post(format!("{}/exams/{exam_id}/attempt/answers", room.base))
1258+ .json(&json!({ "question_id": question_id, "selected": 1 }))
1259+ .send()
1260+ .await
1261+ .unwrap();
1262+ assert_eq!(
1263+ res.status(),
1264+ StatusCode::OK,
1265+ "sitting #2 is writable — the student never left it"
1266+ );
1267+}
1268+
1269+/// Two sockets on the same sitting (a second tab): closing one must not count
1270+/// as leaving the exam room while the other is still connected — only the last
1271+/// socket out stamps `left_at` and (with the door closed) locks answering.
1272+#[tokio::test]
1273+async fn exam_room_second_tab_keeps_the_student_present() {
1274+ let room = exam_room_fixture(600_000).await;
1275+
1276+ // Close the door before anyone sits, so a false stamp locks immediately.
1277+ let res = room
1278+ .teacher
1279+ .patch(format!("{}/exams/{}", room.base, room.exam_id))
1280+ .json(&json!({ "allow_rejoin": false }))
1281+ .send()
1282+ .await
1283+ .unwrap();
1284+ assert_eq!(res.status(), StatusCode::OK);
1285+ let res = room
1286+ .student
1287+ .post(format!("{}/exams/{}/attempt", room.base, room.exam_id))
1288+ .send()
1289+ .await
1290+ .unwrap();
1291+ assert_eq!(res.status(), StatusCode::CREATED);
1292+
1293+ // Two tabs in the same room.
1294+ let mut ws1 = ws_open(&room.base, &room.exam_id, Some(&room.cookie))
1295+ .await
1296+ .expect("first tab");
1297+ ws_next_frame(&mut ws1).await.expect("state on tab one");
1298+ let mut ws2 = ws_open(&room.base, &room.exam_id, Some(&room.cookie))
1299+ .await
1300+ .expect("second tab");
1301+ ws_next_frame(&mut ws2).await.expect("state on tab two");
1302+
1303+ // Closing one tab is not leaving: the student is still in the room.
1304+ ws1.close(None).await.unwrap();
1305+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
1306+ let attempt = my_attempt(&room).await;
1307+ assert!(
1308+ attempt["left_at"].is_null(),
1309+ "one closed tab of two must not stamp a walk-out: {attempt}"
1310+ );
1311+ let res = room
1312+ .student
1313+ .post(format!(
1314+ "{}/exams/{}/attempt/answers",
1315+ room.base, room.exam_id
1316+ ))
1317+ .json(&json!({ "question_id": room.question_id, "selected": 1 }))
1318+ .send()
1319+ .await
1320+ .unwrap();
1321+ assert_eq!(
1322+ res.status(),
1323+ StatusCode::OK,
1324+ "still present via the second tab, so saves land"
1325+ );
1326+
1327+ // The last tab closing is the real walk-out: stamped, and the closed door
1328+ // now locks further saves.
1329+ ws2.close(None).await.unwrap();
1330+ wait_for_left_at(&room).await;
1331+ let res = room
1332+ .student
1333+ .post(format!(
1334+ "{}/exams/{}/attempt/answers",
1335+ room.base, room.exam_id
1336+ ))
1337+ .json(&json!({ "question_id": room.question_id, "selected": 0 }))
1338+ .send()
1339+ .await
1340+ .unwrap();
1341+ assert_eq!(res.status(), StatusCode::CONFLICT);
1342+}
1343+
1164 /// An `open`-mode exam room: no deadline in the state frames, and a retake1344 /// An `open`-mode exam room: no deadline in the state frames, and a retake
1165 /// (attempt #2) enters the room with a blank sheet after the first sitting is1345 /// (attempt #2) enters the room with a blank sheet after the first sitting is
1166 /// submitted.1346 /// submitted.
tests/integration.rsmodified+1 -0
@@ -3188,6 +3188,7 @@ async fn session_cookie_secure_attribute_follows_config() {
3188 db,3188 db,
3189 cookie_secure: true,3189 cookie_secure: true,
3190 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),3190 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
3191+ exam_presence: Default::default(),
3191 });3192 });
3192 let secure = login_set_cookie(&app).await;3193 let secure = login_set_cookie(&app).await;
3193 assert!(3194 assert!(
tests/persistence.rsmodified+1 -0
@@ -48,6 +48,7 @@ fn state(db: Database) -> AppState {
48 db,48 db,
49 cookie_secure: false,49 cookie_secure: false,
50 rate_limit: RateLimitConfig::unlimited(),50 rate_limit: RateLimitConfig::unlimited(),
51+ exam_presence: Default::default(),
51 }52 }
52 }53 }
53 54
tests/rate_limit.rsmodified+2 -0
@@ -23,6 +23,7 @@ async fn app_with(rate_limit: RateLimitConfig) -> Router {
23 db,23 db,
24 cookie_secure: false,24 cookie_secure: false,
25 rate_limit,25 rate_limit,
26+ exam_presence: Default::default(),
26 })27 })
27 }28 }
28 29
@@ -312,6 +313,7 @@ async fn spawn_server(rate_limit: RateLimitConfig) -> String {
312 db,313 db,
313 cookie_secure: false,314 cookie_secure: false,
314 rate_limit,315 rate_limit,
316+ exam_presence: Default::default(),
315 });317 });
316 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();318 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
317 let addr = listener.local_addr().unwrap();319 let addr = listener.local_addr().unwrap();