//! The student exam room: a WebSocket at `GET /exams/{id}/attempt/ws`. //! //! REST remains the fallback (`POST /exams/{id}/attempt/answers` etc.); the //! socket exists so a sitting student gets autosave acks and a live, //! server-judged countdown without polling. The teacher monitor polls the //! one-shot snapshot (`GET /exams/{id}/live`) instead. //! //! Wire protocol (JSON text frames): //! //! server → client //! - `{"type":"state", status, attempt, deadline, remaining_ms, now, answered, question_count}` //! on connect, every [`EXAM_WS_TICK_SECS`], and after each save //! - `{"type":"saved", question_id, updated_at, client_seq?}` — an answer landed //! - `{"type":"pong"}` //! - `{"type":"finished", finished_at}` then Close — submitted (here or elsewhere) //! - `{"type":"expired"}` then Close — the deadline passed mid-session //! - `{"type":"error", message, question_id?, client_seq?}` — bad JSON, unknown type, //! validation, deadline. `question_id` is present only when the failure //! belongs to that one `answer` (its payload or its question); absent means //! the failure is connection- or sitting-level, so every save in flight is //! equally refused //! //! `client_seq` on either reply is whatever the `answer` sent, echoed verbatim: the //! server never reads it, never dedupes on it, and omits the key entirely when //! the request omitted it. `question_id` cannot serve as the correlation id — //! a re-save of the same question after a timeout leaves two sends //! outstanding for it. //! //! client → server //! - `{"type":"answer", question_id, selected? | text?, client_seq?}` (`selected` = //! choice id, `client_seq` = the client's own correlation id) //! - `{"type":"finish"}` //! - `{"type":"ping"}` //! //! Every save and every tick re-reads the exam and attempt, so the deadline //! stays server-authoritative: a teacher extending `ends_at` (or `duration_ms`) //! mid-exam moves this room's clock on the next tick, and a stale client can //! never write past its real deadline. Every save also re-judges the sitter — //! live role and enrollment — so a promotion out of `student` or an //! unenrollment mid-exam closes the sheet with no reconnect needed. //! //! The room is also the presence signal behind the rejoin policy: joining the //! room 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), a room whose sitting ends — //! submitted or expired anywhere — announces it and closes, and `answer` / //! `finish` refuse to touch any other sitting, so a lingering socket can //! never write into (or submit) a retake it never hosted. use std::time::Duration; use crate::web::tenant_state::{SchoolIdCookie, State}; use axum::extract::Path; use axum::extract::ws::{WebSocket, WebSocketUpgrade}; use axum::response::Response; use serde::Deserialize; use serde_json::{Value, json}; use crate::constant::{EXAM_WS_TICK_SECS, MAX_QUESTION_ID_LEN}; use crate::database::Database; use crate::domain::exam::{Exam, ExamId}; use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; use crate::service::exam_attempt::{ check_rejoin, ensure_enrolled, ensure_sittable, ensure_student, finish, read, save_answer_in, set_left, writable_attempt, }; use crate::state::AppState; use crate::tenant::SchoolId; use crate::validate::validate_required; use crate::web::CurrentUser; use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq}; /// How this room names itself in the logs [`room::public_message`] writes. const ROOM: &str = "exam room"; /// Presence counting is in-process memory /// ([`crate::state::ExamPresence`], keyed per sitting), and the `left_at` /// writes are idempotent single statements against the sitting's own row: /// joining counts the socket and unconditionally clears the marker; the /// last socket out stamps it, but only while the row still reads /// not-stamped, not-submitted, and not-past-deadline — so concurrent /// last-outs are harmless (only the first finds `left_at IS NULL`) and a /// stamp can never erase a join's clear of a marker it did not make. The /// join's clear lands milliseconds after the door's read-only rejoin /// check, which no HTTP caller can observe. /// What the client asked for, tagged by `type`. #[derive(Deserialize)] #[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] enum ClientMessage { Answer { question_id: String, #[serde(default)] selected: Option, #[serde(default)] text: Option, /// The client's own correlation id, echoed verbatim on this message's /// `saved` or `error` and never read by the server. `question_id` is /// not an identity — a re-save of the same question after a timeout /// has two sends outstanding, and the first reply would otherwise /// settle the second. #[serde(default)] client_seq: Option, }, Finish, Ping, } /// Upgrade into the caller's exam room. All gates run *before* the upgrade so /// a rejected client gets a proper HTTP status instead of an instant close: /// unknown or draft exam (404), unscheduled with no mode (409), not a student /// (403), not enrolled (403), no attempt yet (404 — `POST /exams/{id}/attempt` /// first), submitted or expired (409), left the room while rejoin is closed /// (409), its instance's academic year archived (409 `academic_year_archived` — /// a past year's room is read-only, and the room's whole purpose is writing). /// /// The rejoin gate here is a read-only fast-fail for a proper 409; the /// authoritative clear of `left_at` happens inside the room task, paired /// with the presence count — milliseconds after this gate, which no HTTP /// caller can observe. Clearing it here instead (before the socket counts /// as present) is exactly the ordering that let a dying socket's teardown /// stamp a student who was already reconnecting. pub async fn attempt_ws( State(st): State, SchoolIdCookie(school): SchoolIdCookie, CurrentUser(user): CurrentUser, Path(id): Path, ws: WebSocketUpgrade, ) -> Result { let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; ensure_sittable(&exam)?; ensure_student(&user)?; ensure_enrolled(&exam, user.get_id(), &st.db).await?; let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; check_rejoin(&exam, &attempt)?; crate::service::exam_attempt::require_open(&st.db, &exam).await?; let user_id = *user.get_id(); Ok(ws.on_upgrade(move |socket| room(socket, st, school, exam, attempt, user_id))) } /// The room loop: state ticks out, answer/finish/ping in, until the socket /// 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, school: SchoolId, exam: Exam, attempt: ExamAttempt, user: UserId, ) { let exam_id = exam.get_id().clone(); let attempt_id = attempt.get_id().clone(); // The exam, not the attempt: an attempt names one student, and telemetry // never names a person. let _connected = room::Connected::open( &st.metrics, "exam_room", school.as_str(), exam_id.key().as_str(), ); // Join: this socket counts as presence in the sitting's room until it // closes, and joining clears the walk-out marker — the clear is one // unconditional statement against the sitting's row, so it always // overwrites any stamp that landed before it. The door's snapshot may // predate a stamp that raced the upgrade; clearing regardless is what // keeps a reconnecting student unmarked. Best-effort — a failed clear // leaves the stamp for the next join or the teacher's door. st.exam_presence.enter(&school, attempt_id.key().as_str()); if let Err(err) = set_left(&st.db, attempt, None).await { tracing::warn!("exam room could not clear left_at on join: {err}"); } 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, &attempt_id, &st.db).await.is_err() { break; } } incoming = socket.recv() => { let text = match room::classify(incoming) { Incoming::Text(text) => text, Incoming::Gone => break, Incoming::Ignore => continue, }; if handle_message(&mut socket, text.as_str(), &exam_id, &attempt_id, &user, &st.db) .await .is_err() { break; } } } } room::close(&mut socket).await; // Leave: only the last socket out means the student actually left the // room. The stamp is one conditional statement — it lands only while // the row still reads unstamped, unsubmitted, and not past the exam's // live deadline — so concurrent last-outs are harmless and a finished // or expired sitting (and any sitting a retake superseded) is never // stamped. With `allow_rejoin` off this is what locks further // answering. Best-effort: a failed stamp only means it goes // unrecorded. if st.exam_presence.leave(&school, attempt_id.key().as_str()) { crate::db::exam_attempt::stamp_left_if_running(&st.db, &attempt_id, Timestamp::now()) .await .unwrap_or_else(|err| { tracing::warn!("exam room could not stamp left_at: {err}"); }); } } /// The room's own sitting, provided it is still the student's current one and /// writable. Messages act on the sitting the room was opened for — never on a /// retake started elsewhere while this socket lingered, which a stale tab /// could otherwise scribble on or instantly submit (burning a limited /// sitting). The latest-attempt read also keeps the deadline gates on the /// exam's current schedule, exactly like the REST path. async fn writable_room_attempt( exam: &Exam, attempt_id: &ExamAttemptId, user: &UserId, db: &Database, ) -> Result { let attempt = writable_attempt(exam, user, db).await?; if &attempt.get_id() != attempt_id { return Err(AppError::Conflict( "this room's sitting is over — reconnect to continue in the new attempt", )); } Ok(attempt) } /// Re-read everything, push a `state` frame, and close the room (after a /// `finished`/`expired` notice) once the room's sitting is no longer in /// progress. async fn push_state( socket: &mut WebSocket, exam: &ExamId, attempt: &ExamAttemptId, db: &Database, ) -> Result<(), RoomClosed> { 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. Err(err) => { tracing::warn!("exam room state failed: {err}"); let _ = send( socket, json!({ "type": "error", "message": "state unavailable" }), ) .await; return Err(RoomClosed); } }; send(socket, frame).await?; match status { AttemptStatus::InProgress => Ok(()), AttemptStatus::Submitted => { send( socket, json!({ "type": "finished", "finished_at": finished_at }), ) .await?; Err(RoomClosed) } AttemptStatus::Expired => { send(socket, json!({ "type": "expired" })).await?; Err(RoomClosed) } } } /// One server-judged snapshot of the room's own sitting, shaped like the REST /// `AttemptResponse`'s live fields. async fn state_frame( exam: &ExamId, attempt: &ExamAttemptId, db: &Database, ) -> Result<(Value, AttemptStatus, Option), AppError> { let exam = crate::service::exam::read(db, exam) .await? .ok_or(AppError::NotFound)?; let attempt = read(db, attempt).await?.ok_or(AppError::NotFound)?; let now = Timestamp::now(); let status = attempt.status(&exam, now); let deadline = attempt.deadline(&exam); let remaining_ms = (status == AttemptStatus::InProgress) .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0))) .flatten(); let answered = crate::service::exam_answer::list_for_exam_user( db, exam.get_id(), attempt.get_user(), attempt.get_seq(), ) .await? .len(); let question_count = crate::service::exam_question::list_for_exam(db, exam.get_id(), None, 0) .await? .0 .len(); let frame = json!({ "type": "state", "status": status.as_str(), "attempt": attempt.get_seq(), "deadline": deadline.map(|t| t.as_millis()), "remaining_ms": remaining_ms, "now": now.as_millis(), "answered": answered, "question_count": question_count, }); Ok(( frame, status, attempt.get_finished_at().map(|t| t.as_millis()), )) } async fn handle_message( socket: &mut WebSocket, text: &str, exam_id: &ExamId, attempt_id: &ExamAttemptId, user: &UserId, db: &Database, ) -> Result<(), RoomClosed> { let message = match serde_json::from_str::(text) { Ok(message) => message, Err(err) => { return send( socket, json!({ "type": "error", "message": format!("unrecognized message: {err}") }), ) .await; } }; match message { ClientMessage::Ping => send(socket, json!({ "type": "pong" })).await, ClientMessage::Answer { question_id, selected, text, client_seq, } => { // Cap the key before it can be echoed — see [`MAX_QUESTION_ID_LEN`]. if let Err(err) = validate_required("question_id", &question_id, MAX_QUESTION_ID_LEN) { let frame = error_frame_for(&AppError::Validation(err), None, client_seq); return send(socket, frame).await; } // Re-read the exam so the save is judged against the *current* // schedule, exactly like the REST path it shares — but write into // the room's own sitting, never whatever is latest. No process // lease is needed around the gates and the upsert: the save is // one guarded statement keyed to the sitting's own seq, and a // retake writes fresh rows at a higher seq, so nothing can wipe // the sheet under this save. // // corner-cut (accepted race, reviewed, unchanged): the room's // sitting was chosen at join, so a save can land on it just // after a retake made it terminal. It writes a history row for // the old seq; the grade of record (latest seq) is untouched. // The fix is a `current_seq` claim on every save — the hottest // path here — so the cost beats the damage and it stays. // Tracks how far the gates got: only once the sitting resolved can // a failure possibly be about this one question rather than about // the room. See [`error_frame_for`]. let mut in_save = false; let saved = match crate::service::exam::read(db, exam_id).await { Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await { Ok(attempt) => { in_save = true; save_answer_in(db, &exam, &attempt, &question_id, selected, text).await } Err(err) => Err(err), }, Ok(None) => Err(AppError::NotFound), Err(err) => Err(err), }; match saved { Ok(answer) => { let mut frame = json!({ "type": "saved", "question_id": answer.get_question().key(), "updated_at": answer.get_updated_at().as_millis(), }); with_client_seq(&mut frame, client_seq); send(socket, frame).await?; // Progress changed — refresh the countdown/answered state // right away rather than waiting out the tick. push_state(socket, exam_id, attempt_id, db).await } Err(err) => { let attributed = in_save && attributable(&err); send( socket, error_frame_for( &err, attributed.then_some(question_id.as_str()), client_seq, ), ) .await } } } ClientMessage::Finish => { // Submit the room's own sitting — a stale room must not submit a // retake it never hosted. let finished = match crate::service::exam::read(db, exam_id).await { Ok(Some(exam)) => { // Its own archived-year gate: `finish` is the one // sitting-side write that does not go through // `save_answer_in`, and the refusal leaves the room by the // same error frame as every other conflict. async { let attempt = writable_room_attempt(&exam, attempt_id, user, db).await?; crate::service::exam_attempt::require_open(db, &exam).await?; finish(db, attempt).await } .await } Ok(None) => Err(AppError::NotFound), Err(err) => Err(err), }; match finished { Ok(attempt) => { send( socket, json!({ "type": "finished", "finished_at": attempt.get_finished_at().map(|t| t.as_millis()), }), ) .await?; Err(RoomClosed) } Err(err) => send(socket, error_frame(&err)).await, } } } } /// Whether a failure raised *inside* the save (past the exam and sitting /// gates) is about the answered question alone, so the client can fail that /// one save instead of every save in flight. /// /// Only the two question-shaped failures qualify: [`AppError::Validation`] /// (the payload doesn't fit the question — wrong kind, unknown choice, too /// long) and [`AppError::NotFound`] (no such question in this exam). Every /// other variant from the save path is about the sitter or the sitting — /// `Unauthorized`/`Forbidden` (promoted out of `student`, unenrolled), /// `Conflict` (walked out with rejoin closed) — and dooms the next save just /// as much as this one, so it stays unattributed and keeps fail-everything. /// Db/Internal stay unattributed too: a database that just failed is not a /// per-question fact, and over-reporting there is the safe side. fn attributable(err: &AppError) -> bool { matches!(err, AppError::Validation(_) | AppError::NotFound) } /// The public words for an error — the same strings the HTTP layer would use, /// with internals logged, never sent. fn error_frame(err: &AppError) -> Value { error_frame_for(err, None, None) } /// [`error_frame`] plus the optional blame: `question_id` when the failure /// belongs to one `answer` message, and `client_seq` whenever the `answer` carried /// one — the two are independent, so an unattributable failure is still /// matchable to the send that caused it. Absent keeps its original meaning — /// an unattributed failure — so a client that ignores the fields behaves /// exactly as before. fn error_frame_for(err: &AppError, question: Option<&str>, client_seq: Option) -> Value { let mut frame = json!({ "type": "error", "message": room::public_message(err, ROOM) }); if let Some(question) = question { frame["question_id"] = json!(question); } with_client_seq(&mut frame, client_seq); frame }