diff --git a/README.md b/README.md
index 231543c..fbcc1d8 100644
--- a/README.md
+++ b/README.md
@@ -554,9 +554,11 @@ moves the room's countdown on the next tick, and no stale socket can write
past its real deadline — the socket shares the exact REST write path.
The room is also the presence signal behind the **rejoin door**: connecting
-clears the attempt's `left_at`, and a socket that closes while the sitting is
-still running stamps it (visible on the live monitor — "left the room three
-minutes ago" at a glance). With the exam's `allow_rejoin` off, a stamped
+clears the attempt's `left_at`, and the *last* socket of the sitting to close
+while it is still running stamps it (visible on the live monitor — "left the
+room three minutes ago" at a glance). Closing one of two tabs is not leaving,
+and a lingering socket from an already-finished sitting never marks a later
+retake as left — each room is bound to the sitting it was opened for. With the exam's `allow_rejoin` off, a stamped
`left_at` refuses re-entry *and* any further saves, over the socket or REST,
until the teacher flips the door back open (`PATCH /exams/{id}
{"allow_rejoin": true}` — live, like the times). Finishing stays allowed: a
diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs
index c272cfb..bf0097d 100644
--- a/src/domain/exam_attempt.rs
+++ b/src/domain/exam_attempt.rs
@@ -3,7 +3,6 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
use crate::database::{Database, EXAM_ATTEMPT_TABLE};
use crate::domain::exam::Exam;
use crate::domain::exam::ExamId;
-use crate::domain::exam_answer::ExamAnswer;
use crate::domain::timestamp::Timestamp;
use crate::domain::user::UserId;
use crate::error::AppError;
@@ -153,9 +152,10 @@ impl ExamAttempt {
/// - A terminal latest attempt (submitted or expired) starts sitting
/// `seq + 1` if the exam's `max_attempts` allows another, and is a
/// conflict otherwise. A retake begins from a blank sheet: the student's
- /// previous answers are wiped first. Wiping *before* creating keeps the
- /// race benign — until the new row exists, saves still hit the terminal
- /// attempt and are rejected, so no fresh answer can be lost to the wipe.
+ /// previous answers are wiped in the same transaction that creates the
+ /// new row ([`Self::wipe_and_create`]), so a lost race (or a failed
+ /// create) rolls the wipe back — no answer sheet is ever destroyed
+ /// without its retake existing.
///
/// The composite id makes each create atomic; a concurrent double-start
/// races on the same seq, loses to the unique id, and reads the winner's
@@ -180,9 +180,6 @@ impl ExamAttempt {
latest.seq + 1
}
};
- if next_seq > 1 {
- ExamAnswer::delete_for_exam_user(exam.get_id(), user, db).await?;
- }
let attempt = ExamAttempt {
id: ExamAttemptId::composite(exam.get_id(), user, next_seq),
exam: exam.get_id().clone(),
@@ -192,8 +189,11 @@ impl ExamAttempt {
finished_at: None,
left_at: None,
};
- let created: Result, surrealdb::Error> =
- db.create(attempt.id.record()).content(attempt).await;
+ let created: Result , surrealdb::Error> = if next_seq == 1 {
+ db.create(attempt.id.record()).content(attempt).await
+ } else {
+ Self::wipe_and_create(attempt, db).await
+ };
match created {
Ok(Some(created)) => Ok((created, true)),
Ok(None) => Err(AppError::Internal("failed to start exam attempt".into())),
@@ -204,6 +204,33 @@ impl ExamAttempt {
}
}
+ /// Wipe the student's previous answers and create the retake row in one
+ /// transaction. Atomicity is the point: a create that fails (a concurrent
+ /// double-start lost the race on the composite id, or the database
+ /// hiccuped) cancels the whole transaction, wipe included — otherwise a
+ /// stale loser could delete answers freshly saved into the winner's
+ /// sitting, or destroy a graded sheet without a retake ever existing.
+ async fn wipe_and_create(
+ attempt: ExamAttempt,
+ db: &Database,
+ ) -> Result , surrealdb::Error> {
+ let mut result = db
+ .query(
+ "BEGIN TRANSACTION;
+ DELETE exam_answer WHERE exam = $ex AND user = $usr;
+ CREATE $id CONTENT $attempt;
+ COMMIT TRANSACTION;",
+ )
+ .bind(("ex", attempt.exam.record()))
+ .bind(("usr", attempt.user.record()))
+ .bind(("id", attempt.id.record()))
+ .bind(("attempt", attempt))
+ .await?
+ .check()?;
+ // Statement slots count BEGIN and COMMIT too: the CREATE is slot 2.
+ Ok(result.take::>(2)?.into_iter().next())
+ }
+
/// Stamp the submission time. The caller has already checked the deadline
/// and that the attempt isn't finished.
pub async fn finish(mut self, db: &Database) -> Result {
@@ -224,6 +251,12 @@ impl ExamAttempt {
updated.ok_or(AppError::NotFound)
}
+ /// One sitting by id — the exam room re-reads its own attempt this way,
+ /// so a retake started elsewhere can never be mistaken for it.
+ pub async fn read(id: &ExamAttemptId, db: &Database) -> Result, AppError> {
+ Ok(db.select(id.record()).await?)
+ }
+
/// The student's current sitting — the highest `seq` for the pair. All
/// reads that used to mean "the attempt" mean this now.
pub async fn read_latest_for_user(
@@ -281,3 +314,129 @@ impl ExamAttempt {
Ok(!result.take::>(0)?.is_empty())
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::database::init_mem;
+ use crate::domain::course::CourseId;
+ use crate::domain::exam::{
+ ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, ExamWeight,
+ };
+ use crate::domain::exam_answer::ExamAnswer;
+ use crate::domain::exam_question::{ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec};
+ use crate::domain::settings::Settings;
+
+ /// An open exam with retakes allowed, plus one choice question — enough
+ /// rows to exercise the attempt lifecycle without the HTTP layer.
+ async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) {
+ let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
+ let course = CourseId::from_key("01TESTCOURSEAAAAAAAAAAAAAA");
+ let kinds = Settings::defaults().get_exam_kinds().to_vec();
+ let exam = Exam::create(
+ &creator,
+ &course,
+ ExamTitle::try_new("practice").unwrap(),
+ ExamDescription::try_new("").unwrap(),
+ ExamKind::try_new("quiz", &kinds).unwrap(),
+ ExamWeight::try_new(1).unwrap(),
+ ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None)
+ .unwrap(),
+ ExamAttemptLimit::try_new(max_attempts).unwrap(),
+ true,
+ db,
+ )
+ .await
+ .unwrap();
+ let spec = QuestionSpec::try_new(
+ QuestionKind::try_new("choice").unwrap(),
+ Some(vec!["5".into(), "6".into()]),
+ Some(1),
+ )
+ .unwrap();
+ let question = ExamQuestion::create(
+ exam.get_id(),
+ crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(),
+ QuestionPoints::try_new(5).unwrap(),
+ spec,
+ db,
+ )
+ .await
+ .unwrap();
+ (exam, question)
+ }
+
+ fn student() -> UserId {
+ UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA")
+ }
+
+ #[tokio::test]
+ async fn a_retake_starts_from_a_blank_sheet() {
+ let db = init_mem().await.unwrap();
+ let (exam, question) = open_exam_with_question(&db, 2).await;
+ let user = student();
+
+ let (first, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
+ assert!(created);
+ assert_eq!(first.get_seq(), 1);
+ ExamAnswer::save(&question, &user, Some(1), None, &db)
+ .await
+ .unwrap();
+ first.finish(&db).await.unwrap();
+
+ // The retake lands as sitting #2 with the sheet wiped in the same
+ // transaction that created it.
+ let (second, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
+ assert!(created);
+ assert_eq!(second.get_seq(), 2);
+ let answers = ExamAnswer::list_for_exam_user(exam.get_id(), &user, &db)
+ .await
+ .unwrap();
+ assert!(answers.is_empty(), "a retake starts blank");
+ }
+
+ #[tokio::test]
+ async fn a_lost_retake_race_cannot_wipe_the_winners_sheet() {
+ let db = init_mem().await.unwrap();
+ let (exam, question) = open_exam_with_question(&db, 3).await;
+ let user = student();
+
+ // Sitting #1 ends; the winner starts sitting #2 and saves an answer.
+ let (first, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
+ first.finish(&db).await.unwrap();
+ let (winner, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
+ assert!(created);
+ assert_eq!(winner.get_seq(), 2);
+ ExamAnswer::save(&question, &user, Some(1), None, &db)
+ .await
+ .unwrap();
+
+ // A stale double-start races on the same seq and loses to the
+ // composite id — and the aborted transaction must roll its wipe back,
+ // leaving the winner's fresh answer untouched.
+ let loser = ExamAttempt {
+ id: ExamAttemptId::composite(exam.get_id(), &user, 2),
+ exam: exam.get_id().clone(),
+ user: user.clone(),
+ seq: 2,
+ started_at: Timestamp::now(),
+ finished_at: None,
+ left_at: None,
+ };
+ let lost = ExamAttempt::wipe_and_create(loser, &db).await;
+ assert!(lost.is_err(), "the duplicate create must fail");
+ let answers = ExamAnswer::list_for_exam_user(exam.get_id(), &user, &db)
+ .await
+ .unwrap();
+ assert_eq!(
+ answers.len(),
+ 1,
+ "the lost race must not wipe the winner's saved answer"
+ );
+
+ // The public path shrugs the race off: a re-start resumes the winner.
+ let (resumed, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
+ assert!(!created);
+ assert_eq!(resumed.get_seq(), 2);
+ }
+}
diff --git a/src/main.rs b/src/main.rs
index 20e4487..8594372 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -22,6 +22,7 @@ async fn main() -> anyhow::Result<()> {
db,
cookie_secure: cfg.cookie_secure,
rate_limit: cfg.rate_limit.clone(),
+ exam_presence: Default::default(),
});
let addr = format!("{}:{}", cfg.host, cfg.port);
diff --git a/src/state.rs b/src/state.rs
index f1c7de6..0c685d2 100644
--- a/src/state.rs
+++ b/src/state.rs
@@ -1,3 +1,6 @@
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+
use crate::database::Database;
use crate::rate_limit::RateLimitConfig;
@@ -11,4 +14,64 @@ pub struct AppState {
/// Per-IP request limits (from [`crate::config::Config::rate_limit`]).
/// Read once by [`crate::build_router`] when the limiters are built.
pub rate_limit: RateLimitConfig,
+ /// Who is inside which exam room right now (see [`ExamPresence`]).
+ pub exam_presence: ExamPresence,
+}
+
+/// How many exam-room sockets each attempt has open right now, keyed by the
+/// attempt's record key. The room counts itself in on entry and out on exit,
+/// and only the last socket out stamps the walk-out (`left_at`) — a student
+/// closing one of two tabs never counts as having left the exam.
+#[derive(Clone, Default)]
+pub struct ExamPresence(Arc>>);
+
+impl ExamPresence {
+ /// Count one socket into `attempt`'s room.
+ pub fn enter(&self, attempt: &str) {
+ let mut rooms = self.0.lock().expect("exam presence lock");
+ *rooms.entry(attempt.to_string()).or_insert(0) += 1;
+ }
+
+ /// Count one socket out of `attempt`'s room; `true` when it was the last
+ /// one — the student has actually left.
+ pub fn leave(&self, attempt: &str) -> bool {
+ let mut rooms = self.0.lock().expect("exam presence lock");
+ match rooms.get_mut(attempt) {
+ Some(count) if *count > 1 => {
+ *count -= 1;
+ false
+ }
+ Some(_) => {
+ rooms.remove(attempt);
+ true
+ }
+ // Unbalanced (an enter was lost) — treat the close as a real exit
+ // rather than leaving the walk-out unrecorded forever.
+ None => true,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn only_the_last_socket_out_is_a_real_exit() {
+ let presence = ExamPresence::default();
+ presence.enter("attempt-a");
+ presence.enter("attempt-a");
+ assert!(
+ !presence.leave("attempt-a"),
+ "one tab of two is not an exit"
+ );
+ assert!(presence.leave("attempt-a"), "the last tab out is");
+ // Rooms are independent, and a fresh key starts over.
+ presence.enter("attempt-b");
+ presence.enter("attempt-a");
+ assert!(presence.leave("attempt-b"));
+ assert!(presence.leave("attempt-a"));
+ // Unbalanced leaves degrade to "really left", never to a stuck room.
+ assert!(presence.leave("attempt-a"));
+ }
}
diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs
index dd89d90..53f5ea9 100644
--- a/src/web/exam_ws.rs
+++ b/src/web/exam_ws.rs
@@ -27,10 +27,17 @@
//! never write past its real deadline.
//!
//! The room is also the presence signal behind the rejoin policy: connecting
-//! clears the attempt's `left_at`, and a socket that closes while the attempt
-//! is still running stamps it. With the exam's `allow_rejoin` off, a stamped
-//! `left_at` refuses re-entry (and any further saves, here or over REST) until
-//! the teacher flips the door back open; finishing stays allowed.
+//! clears the attempt's `left_at`, and the *last* socket of the sitting to
+//! close while the attempt is still running stamps it — a student closing one
+//! of two tabs hasn't left, and a lingering socket from an already-finished
+//! sitting can never mark a later retake as left. With the exam's
+//! `allow_rejoin` off, a stamped `left_at` refuses re-entry (and any further
+//! saves, here or over REST) until the teacher flips the door back open;
+//! finishing stays allowed.
+//!
+//! Each room is bound to the sitting it was opened for: state frames track
+//! that attempt (not whatever is latest), so a room whose sitting ends —
+//! submitted or expired anywhere — announces it and closes.
use std::time::Duration;
@@ -45,7 +52,7 @@ use crate::database::Database;
use crate::domain::enrollment::Enrollment;
use crate::domain::exam::{Exam, ExamId};
use crate::domain::exam_answer::ExamAnswer;
-use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt};
+use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId};
use crate::domain::exam_question::ExamQuestion;
use crate::domain::timestamp::Timestamp;
use crate::domain::user::UserId;
@@ -99,24 +106,30 @@ pub async fn attempt_ws(
}
let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?;
check_rejoin(&exam, &attempt)?;
- if attempt.get_left_at().is_some() {
- attempt.set_left(None, &st.db).await?;
- }
+ let attempt = if attempt.get_left_at().is_some() {
+ attempt.set_left(None, &st.db).await?
+ } else {
+ attempt
+ };
let user_id = user.get_id().clone();
- Ok(ws.on_upgrade(move |socket| room(socket, st, exam, user_id)))
+ Ok(ws.on_upgrade(move |socket| room(socket, st, exam, attempt, user_id)))
}
/// The room loop: state ticks out, answer/finish/ping in, until the socket
-/// closes or the attempt reaches a terminal state.
-async fn room(mut socket: WebSocket, st: AppState, exam: Exam, user: UserId) {
+/// closes or the room's sitting reaches a terminal state. The room is bound
+/// to the attempt it was opened for — `attempt` — and to no later sitting.
+async fn room(mut socket: WebSocket, st: AppState, exam: Exam, attempt: ExamAttempt, user: UserId) {
let exam_id = exam.get_id().clone();
+ let attempt_id = attempt.get_id().clone();
+ // This socket counts as presence in the sitting's room until it closes.
+ st.exam_presence.enter(attempt_id.key());
let mut tick = tokio::time::interval(Duration::from_secs(EXAM_WS_TICK_SECS));
loop {
tokio::select! {
// First tick fires immediately — the connect-time state frame.
_ = tick.tick() => {
- if push_state(&mut socket, &exam_id, &user, &st.db).await.is_err() {
+ if push_state(&mut socket, &exam_id, &attempt_id, &st.db).await.is_err() {
break;
}
}
@@ -128,7 +141,7 @@ async fn room(mut socket: WebSocket, st: AppState, exam: Exam, user: UserId) {
Some(Ok(Message::Close(_))) | Some(Err(_)) | None => break,
Some(Ok(_)) => continue,
};
- if handle_message(&mut socket, text.as_str(), &exam_id, &user, &st.db)
+ if handle_message(&mut socket, text.as_str(), &exam_id, &attempt_id, &user, &st.db)
.await
.is_err()
{
@@ -140,19 +153,23 @@ async fn room(mut socket: WebSocket, st: AppState, exam: Exam, user: UserId) {
// Best-effort closing handshake — a bare TCP teardown reads as an error
// on the client; a Close frame reads as "the room is over".
let _ = socket.send(Message::Close(None)).await;
- // The student is out of the room. If their attempt is still running,
- // stamp the walk-out — with `allow_rejoin` off this is what locks further
- // answering. Terminal exits (finished/expired) need no stamp. Best-effort:
- // a failed stamp only means the walk-out goes unrecorded.
- stamp_left(&exam_id, &user, &st.db).await;
+ // Only the last socket out means the student actually left the room. If
+ // this sitting is still running, stamp the walk-out — with `allow_rejoin`
+ // off this is what locks further answering. Terminal exits (finished or
+ // expired, and any sitting superseded by a retake is terminal) need no
+ // stamp. Best-effort: a failed stamp only means it goes unrecorded.
+ if st.exam_presence.leave(attempt_id.key()) {
+ stamp_left(&exam_id, &attempt_id, &st.db).await;
+ }
}
-/// Stamp `left_at` on the student's latest attempt if it is still in
-/// progress — re-reading both rows so a finish or expiry that raced the
-/// socket close wins.
-async fn stamp_left(exam_id: &ExamId, user: &UserId, db: &Database) {
+/// Stamp `left_at` on the room's own sitting if it is still in progress —
+/// re-reading both rows so a finish or expiry that raced the socket close
+/// wins. Targeting the sitting by id (never "the latest") means a retake
+/// started elsewhere can't be marked as left by an old room's teardown.
+async fn stamp_left(exam_id: &ExamId, attempt_id: &ExamAttemptId, db: &Database) {
let attempt = match Exam::read(exam_id, db).await {
- Ok(Some(exam)) => match ExamAttempt::read_latest_for_user(exam.get_id(), user, db).await {
+ Ok(Some(exam)) => match ExamAttempt::read(attempt_id, db).await {
Ok(Some(attempt))
if attempt.status(&exam, Timestamp::now()) == AttemptStatus::InProgress =>
{
@@ -189,14 +206,15 @@ async fn send(socket: &mut WebSocket, frame: Value) -> Result<(), RoomClosed> {
}
/// Re-read everything, push a `state` frame, and close the room (after a
-/// `finished`/`expired` notice) once the attempt is no longer in progress.
+/// `finished`/`expired` notice) once the room's sitting is no longer in
+/// progress.
async fn push_state(
socket: &mut WebSocket,
exam: &ExamId,
- user: &UserId,
+ attempt: &ExamAttemptId,
db: &Database,
) -> Result<(), RoomClosed> {
- let (frame, status, finished_at) = match state_frame(exam, user, db).await {
+ let (frame, status, finished_at) = match state_frame(exam, attempt, db).await {
Ok(state) => state,
// The exam vanished mid-room (deleted) or the db hiccuped: nothing
// sensible left to serve.
@@ -228,15 +246,15 @@ async fn push_state(
}
}
-/// One server-judged snapshot of the attempt, shaped like the REST
+/// One server-judged snapshot of the room's own sitting, shaped like the REST
/// `AttemptResponse`'s live fields.
async fn state_frame(
exam: &ExamId,
- user: &UserId,
+ attempt: &ExamAttemptId,
db: &Database,
) -> Result<(Value, AttemptStatus, Option), AppError> {
let exam = Exam::read(exam, db).await?.ok_or(AppError::NotFound)?;
- let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user, db)
+ let attempt = ExamAttempt::read(attempt, db)
.await?
.ok_or(AppError::NotFound)?;
let now = Timestamp::now();
@@ -245,7 +263,7 @@ async fn state_frame(
let remaining_ms = (status == AttemptStatus::InProgress)
.then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0)))
.flatten();
- let answered = ExamAnswer::list_for_exam_user(exam.get_id(), user, db)
+ let answered = ExamAnswer::list_for_exam_user(exam.get_id(), attempt.get_user(), db)
.await?
.len();
let question_count = ExamQuestion::list_for_exam(exam.get_id(), db).await?.len();
@@ -270,6 +288,7 @@ async fn handle_message(
socket: &mut WebSocket,
text: &str,
exam_id: &ExamId,
+ attempt_id: &ExamAttemptId,
user: &UserId,
db: &Database,
) -> Result<(), RoomClosed> {
@@ -312,7 +331,7 @@ async fn handle_message(
.await?;
// Progress changed — refresh the countdown/answered state
// right away rather than waiting out the tick.
- push_state(socket, exam_id, user, db).await
+ push_state(socket, exam_id, attempt_id, db).await
}
Err(err) => send(socket, error_frame(&err)).await,
}
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 03a64e0..7eabbe5 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -30,6 +30,7 @@ pub async fn app_and_db() -> (Router, Database) {
// Off, so suites hammering the API never trip a limit; the dedicated
// `rate_limit` test binary opts into tight configs on purpose.
rate_limit: RateLimitConfig::unlimited(),
+ exam_presence: Default::default(),
});
(app, db)
}
diff --git a/tests/e2e.rs b/tests/e2e.rs
index 36ec359..cc6e37c 100644
--- a/tests/e2e.rs
+++ b/tests/e2e.rs
@@ -19,6 +19,7 @@ async fn spawn_server() -> (String, Database) {
// Every request here comes from 127.0.0.1, so per-IP limits would
// meter the whole suite as one client. Off; `rate_limit.rs` covers it.
rate_limit: RateLimitConfig::unlimited(),
+ exam_presence: Default::default(),
});
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
@@ -1161,6 +1162,185 @@ async fn exam_room_rejoin_door_is_the_teachers_call() {
assert_eq!(res.status(), StatusCode::OK, "finish is exempt from rejoin");
}
+/// A walk-out stamp belongs to the sitting the room was opened for — never to
+/// a retake started while the old socket lingered. Closing the stale room of a
+/// finished sitting must not mark the *new* sitting as left (with the door
+/// closed, that stamp would lock the student out of an exam room they never
+/// entered).
+#[tokio::test]
+async fn exam_room_close_after_a_retake_leaves_the_new_sitting_alone() {
+ let room = exam_room_fixture(600_000).await;
+
+ // An open exam with two sittings and the rejoin door closed.
+ let exam: Value = room
+ .teacher
+ .post(format!("{}/courses/{}/exams", room.base, room.course_id))
+ .json(&json!({
+ "title": "practice", "kind": "quiz", "weight": 1,
+ "mode": "open", "max_attempts": 2, "allow_rejoin": false,
+ }))
+ .send()
+ .await
+ .unwrap()
+ .json()
+ .await
+ .unwrap();
+ let exam_id = exam["id"].as_str().unwrap().to_string();
+ let question: Value = room
+ .teacher
+ .post(format!("{}/exams/{exam_id}/questions", room.base))
+ .json(&json!({ "text": "3 + 3?", "kind": "choice", "points": 5,
+ "choices": ["5", "6"], "correct": 1 }))
+ .send()
+ .await
+ .unwrap()
+ .json()
+ .await
+ .unwrap();
+ let question_id = question["id"].as_str().unwrap().to_string();
+
+ // Sit sitting #1 and open its room.
+ let res = room
+ .student
+ .post(format!("{}/exams/{exam_id}/attempt", room.base))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(res.status(), StatusCode::CREATED);
+ let mut ws = ws_open(&room.base, &exam_id, Some(&room.cookie))
+ .await
+ .expect("room for sitting #1");
+ let state = ws_next_frame(&mut ws).await.expect("connect state");
+ assert_eq!(state["attempt"], 1, "{state}");
+
+ // Finish sitting #1 and start sitting #2 over REST — the old socket is
+ // still open while the retake begins.
+ let res = room
+ .student
+ .post(format!("{}/exams/{exam_id}/attempt/finish", room.base))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(res.status(), StatusCode::OK);
+ let res = room
+ .student
+ .post(format!("{}/exams/{exam_id}/attempt", room.base))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(res.status(), StatusCode::CREATED);
+ let body: Value = res.json().await.unwrap();
+ assert_eq!(body["attempt"], 2);
+
+ // Now walk out of the stale sitting-#1 room and give the teardown time.
+ ws.close(None).await.unwrap();
+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
+
+ // Sitting #2 was never entered, so it was never left: no stamp, and
+ // answering it works despite the closed door.
+ let attempt: Value = room
+ .student
+ .get(format!("{}/exams/{exam_id}/attempt", room.base))
+ .send()
+ .await
+ .unwrap()
+ .json()
+ .await
+ .unwrap();
+ assert_eq!(attempt["attempt"], 2, "{attempt}");
+ assert!(
+ attempt["left_at"].is_null(),
+ "closing the old sitting's room must not stamp the new sitting: {attempt}"
+ );
+ let res = room
+ .student
+ .post(format!("{}/exams/{exam_id}/attempt/answers", room.base))
+ .json(&json!({ "question_id": question_id, "selected": 1 }))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(
+ res.status(),
+ StatusCode::OK,
+ "sitting #2 is writable — the student never left it"
+ );
+}
+
+/// Two sockets on the same sitting (a second tab): closing one must not count
+/// as leaving the exam room while the other is still connected — only the last
+/// socket out stamps `left_at` and (with the door closed) locks answering.
+#[tokio::test]
+async fn exam_room_second_tab_keeps_the_student_present() {
+ let room = exam_room_fixture(600_000).await;
+
+ // Close the door before anyone sits, so a false stamp locks immediately.
+ let res = room
+ .teacher
+ .patch(format!("{}/exams/{}", room.base, room.exam_id))
+ .json(&json!({ "allow_rejoin": false }))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(res.status(), StatusCode::OK);
+ let res = room
+ .student
+ .post(format!("{}/exams/{}/attempt", room.base, room.exam_id))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(res.status(), StatusCode::CREATED);
+
+ // Two tabs in the same room.
+ let mut ws1 = ws_open(&room.base, &room.exam_id, Some(&room.cookie))
+ .await
+ .expect("first tab");
+ ws_next_frame(&mut ws1).await.expect("state on tab one");
+ let mut ws2 = ws_open(&room.base, &room.exam_id, Some(&room.cookie))
+ .await
+ .expect("second tab");
+ ws_next_frame(&mut ws2).await.expect("state on tab two");
+
+ // Closing one tab is not leaving: the student is still in the room.
+ ws1.close(None).await.unwrap();
+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
+ let attempt = my_attempt(&room).await;
+ assert!(
+ attempt["left_at"].is_null(),
+ "one closed tab of two must not stamp a walk-out: {attempt}"
+ );
+ let res = room
+ .student
+ .post(format!(
+ "{}/exams/{}/attempt/answers",
+ room.base, room.exam_id
+ ))
+ .json(&json!({ "question_id": room.question_id, "selected": 1 }))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(
+ res.status(),
+ StatusCode::OK,
+ "still present via the second tab, so saves land"
+ );
+
+ // The last tab closing is the real walk-out: stamped, and the closed door
+ // now locks further saves.
+ ws2.close(None).await.unwrap();
+ wait_for_left_at(&room).await;
+ let res = room
+ .student
+ .post(format!(
+ "{}/exams/{}/attempt/answers",
+ room.base, room.exam_id
+ ))
+ .json(&json!({ "question_id": room.question_id, "selected": 0 }))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(res.status(), StatusCode::CONFLICT);
+}
+
/// An `open`-mode exam room: no deadline in the state frames, and a retake
/// (attempt #2) enters the room with a blank sheet after the first sitting is
/// submitted.
diff --git a/tests/integration.rs b/tests/integration.rs
index 6de09a8..cb25ce1 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -3188,6 +3188,7 @@ async fn session_cookie_secure_attribute_follows_config() {
db,
cookie_secure: true,
rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
+ exam_presence: Default::default(),
});
let secure = login_set_cookie(&app).await;
assert!(
diff --git a/tests/persistence.rs b/tests/persistence.rs
index 0fbfbfe..822be76 100644
--- a/tests/persistence.rs
+++ b/tests/persistence.rs
@@ -48,6 +48,7 @@ fn state(db: Database) -> AppState {
db,
cookie_secure: false,
rate_limit: RateLimitConfig::unlimited(),
+ exam_presence: Default::default(),
}
}
diff --git a/tests/rate_limit.rs b/tests/rate_limit.rs
index 6e49ba7..4e22fba 100644
--- a/tests/rate_limit.rs
+++ b/tests/rate_limit.rs
@@ -23,6 +23,7 @@ async fn app_with(rate_limit: RateLimitConfig) -> Router {
db,
cookie_secure: false,
rate_limit,
+ exam_presence: Default::default(),
})
}
@@ -312,6 +313,7 @@ async fn spawn_server(rate_limit: RateLimitConfig) -> String {
db,
cookie_secure: false,
rate_limit,
+ exam_presence: Default::default(),
});
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();