forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

exam_ws.rs495 lines, 21.1 KiBHistoryRawDownload
1//! The student exam room: a WebSocket at `GET /exams/{id}/attempt/ws`.
2//!
3//! REST remains the fallback (`POST /exams/{id}/attempt/answers` etc.); the
4//! socket exists so a sitting student gets autosave acks and a live,
5//! server-judged countdown without polling. The teacher monitor polls the
6//! one-shot snapshot (`GET /exams/{id}/live`) instead.
7//!
8//! Wire protocol (JSON text frames):
9//!
10//! server → client
11//! - `{"type":"state", status, attempt, deadline, remaining_ms, now, answered, question_count}`
12//! on connect, every [`EXAM_WS_TICK_SECS`], and after each save
13//! - `{"type":"saved", question_id, updated_at, client_seq?}` — an answer landed
14//! - `{"type":"pong"}`
15//! - `{"type":"finished", finished_at}` then Close — submitted (here or elsewhere)
16//! - `{"type":"expired"}` then Close — the deadline passed mid-session
17//! - `{"type":"error", message, question_id?, client_seq?}` — bad JSON, unknown type,
18//! validation, deadline. `question_id` is present only when the failure
19//! belongs to that one `answer` (its payload or its question); absent means
20//! the failure is connection- or sitting-level, so every save in flight is
21//! equally refused
22//!
23//! `client_seq` on either reply is whatever the `answer` sent, echoed verbatim: the
24//! server never reads it, never dedupes on it, and omits the key entirely when
25//! the request omitted it. `question_id` cannot serve as the correlation id —
26//! a re-save of the same question after a timeout leaves two sends
27//! outstanding for it.
28//!
29//! client → server
30//! - `{"type":"answer", question_id, selected? | text?, client_seq?}` (`selected` =
31//! choice id, `client_seq` = the client's own correlation id)
32//! - `{"type":"finish"}`
33//! - `{"type":"ping"}`
34//!
35//! Every save and every tick re-reads the exam and attempt, so the deadline
36//! stays server-authoritative: a teacher extending `ends_at` (or `duration_ms`)
37//! mid-exam moves this room's clock on the next tick, and a stale client can
38//! never write past its real deadline. Every save also re-judges the sitter —
39//! live role and enrollment — so a promotion out of `student` or an
40//! unenrollment mid-exam closes the sheet with no reconnect needed.
41//!
42//! The room is also the presence signal behind the rejoin policy: joining the
43//! room clears the attempt's `left_at`, and the *last* socket of the sitting to
44//! close while the attempt is still running stamps it — a student closing one
45//! of two tabs hasn't left, and a lingering socket from an already-finished
46//! sitting can never mark a later retake as left. With the exam's
47//! `allow_rejoin` off, a stamped `left_at` refuses re-entry (and any further
48//! saves, here or over REST) until the teacher flips the door back open;
49//! finishing stays allowed.
50//!
51//! Each room is bound to the sitting it was opened for: state frames track
52//! that attempt (not whatever is latest), a room whose sitting ends —
53//! submitted or expired anywhere — announces it and closes, and `answer` /
54//! `finish` refuse to touch any other sitting, so a lingering socket can
55//! never write into (or submit) a retake it never hosted.
56
57use std::time::Duration;
58
59use crate::web::tenant_state::{SchoolIdCookie, State};
60use axum::extract::Path;
61use axum::extract::ws::{WebSocket, WebSocketUpgrade};
62use axum::response::Response;
63use serde::Deserialize;
64use serde_json::{Value, json};
65
66use crate::constant::{EXAM_WS_TICK_SECS, MAX_QUESTION_ID_LEN};
67use crate::database::Database;
68use crate::domain::exam::{Exam, ExamId};
69use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId};
70use crate::domain::timestamp::Timestamp;
71use crate::domain::user::UserId;
72use crate::error::AppError;
73use crate::service::exam_attempt::{
74 check_rejoin, ensure_enrolled, ensure_sittable, ensure_student, finish, read, save_answer_in,
75 set_left, writable_attempt,
76};
77use crate::state::AppState;
78use crate::tenant::SchoolId;
79use crate::validate::validate_required;
80use crate::web::CurrentUser;
81use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq};
82
83/// How this room names itself in the logs [`room::public_message`] writes.
84const ROOM: &str = "exam room";
85
86/// Presence counting is in-process memory
87/// ([`crate::state::ExamPresence`], keyed per sitting), and the `left_at`
88/// writes are idempotent single statements against the sitting's own row:
89/// joining counts the socket and unconditionally clears the marker; the
90/// last socket out stamps it, but only while the row still reads
91/// not-stamped, not-submitted, and not-past-deadline — so concurrent
92/// last-outs are harmless (only the first finds `left_at IS NULL`) and a
93/// stamp can never erase a join's clear of a marker it did not make. The
94/// join's clear lands milliseconds after the door's read-only rejoin
95/// check, which no HTTP caller can observe.
96/// What the client asked for, tagged by `type`.
97#[derive(Deserialize)]
98#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
99enum ClientMessage {
100 Answer {
101 question_id: String,
102 #[serde(default)]
103 selected: Option<String>,
104 #[serde(default)]
105 text: Option<String>,
106 /// The client's own correlation id, echoed verbatim on this message's
107 /// `saved` or `error` and never read by the server. `question_id` is
108 /// not an identity — a re-save of the same question after a timeout
109 /// has two sends outstanding, and the first reply would otherwise
110 /// settle the second.
111 #[serde(default)]
112 client_seq: Option<u64>,
113 },
114 Finish,
115 Ping,
116}
117
118/// Upgrade into the caller's exam room. All gates run *before* the upgrade so
119/// a rejected client gets a proper HTTP status instead of an instant close:
120/// unknown or draft exam (404), unscheduled with no mode (409), not a student
121/// (403), not enrolled (403), no attempt yet (404 — `POST /exams/{id}/attempt`
122/// first), submitted or expired (409), left the room while rejoin is closed
123/// (409), its instance's academic year archived (409 `academic_year_archived` —
124/// a past year's room is read-only, and the room's whole purpose is writing).
125///
126/// The rejoin gate here is a read-only fast-fail for a proper 409; the
127/// authoritative clear of `left_at` happens inside the room task, paired
128/// with the presence count — milliseconds after this gate, which no HTTP
129/// caller can observe. Clearing it here instead (before the socket counts
130/// as present) is exactly the ordering that let a dying socket's teardown
131/// stamp a student who was already reconnecting.
132pub async fn attempt_ws(
133 State(st): State<AppState>,
134 SchoolIdCookie(school): SchoolIdCookie,
135 CurrentUser(user): CurrentUser,
136 Path(id): Path<String>,
137 ws: WebSocketUpgrade,
138) -> Result<Response, AppError> {
139 let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
140 .await?
141 .ok_or(AppError::NotFound)?;
142 ensure_sittable(&exam)?;
143 ensure_student(&user)?;
144 ensure_enrolled(&exam, user.get_id(), &st.db).await?;
145 let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?;
146 check_rejoin(&exam, &attempt)?;
147 crate::service::exam_attempt::require_open(&st.db, &exam).await?;
148
149 let user_id = *user.get_id();
150 Ok(ws.on_upgrade(move |socket| room(socket, st, school, exam, attempt, user_id)))
151}
152
153/// The room loop: state ticks out, answer/finish/ping in, until the socket
154/// closes or the room's sitting reaches a terminal state. The room is bound
155/// to the attempt it was opened for — `attempt` — and to no later sitting.
156async fn room(
157 mut socket: WebSocket,
158 st: AppState,
159 school: SchoolId,
160 exam: Exam,
161 attempt: ExamAttempt,
162 user: UserId,
163) {
164 let exam_id = exam.get_id().clone();
165 let attempt_id = attempt.get_id().clone();
166 // The exam, not the attempt: an attempt names one student, and telemetry
167 // never names a person.
168 let _connected = room::Connected::open(
169 &st.metrics,
170 "exam_room",
171 school.as_str(),
172 exam_id.key().as_str(),
173 );
174 // Join: this socket counts as presence in the sitting's room until it
175 // closes, and joining clears the walk-out marker — the clear is one
176 // unconditional statement against the sitting's row, so it always
177 // overwrites any stamp that landed before it. The door's snapshot may
178 // predate a stamp that raced the upgrade; clearing regardless is what
179 // keeps a reconnecting student unmarked. Best-effort — a failed clear
180 // leaves the stamp for the next join or the teacher's door.
181 st.exam_presence.enter(&school, attempt_id.key().as_str());
182 if let Err(err) = set_left(&st.db, attempt, None).await {
183 tracing::warn!("exam room could not clear left_at on join: {err}");
184 }
185 let mut tick = tokio::time::interval(Duration::from_secs(EXAM_WS_TICK_SECS));
186 loop {
187 tokio::select! {
188 // First tick fires immediately — the connect-time state frame.
189 _ = tick.tick() => {
190 if push_state(&mut socket, &exam_id, &attempt_id, &st.db).await.is_err() {
191 break;
192 }
193 }
194 incoming = socket.recv() => {
195 let text = match room::classify(incoming) {
196 Incoming::Text(text) => text,
197 Incoming::Gone => break,
198 Incoming::Ignore => continue,
199 };
200 if handle_message(&mut socket, text.as_str(), &exam_id, &attempt_id, &user, &st.db)
201 .await
202 .is_err()
203 {
204 break;
205 }
206 }
207 }
208 }
209 room::close(&mut socket).await;
210 // Leave: only the last socket out means the student actually left the
211 // room. The stamp is one conditional statement — it lands only while
212 // the row still reads unstamped, unsubmitted, and not past the exam's
213 // live deadline — so concurrent last-outs are harmless and a finished
214 // or expired sitting (and any sitting a retake superseded) is never
215 // stamped. With `allow_rejoin` off this is what locks further
216 // answering. Best-effort: a failed stamp only means it goes
217 // unrecorded.
218 if st.exam_presence.leave(&school, attempt_id.key().as_str()) {
219 crate::db::exam_attempt::stamp_left_if_running(&st.db, &attempt_id, Timestamp::now())
220 .await
221 .unwrap_or_else(|err| {
222 tracing::warn!("exam room could not stamp left_at: {err}");
223 });
224 }
225}
226
227/// The room's own sitting, provided it is still the student's current one and
228/// writable. Messages act on the sitting the room was opened for — never on a
229/// retake started elsewhere while this socket lingered, which a stale tab
230/// could otherwise scribble on or instantly submit (burning a limited
231/// sitting). The latest-attempt read also keeps the deadline gates on the
232/// exam's current schedule, exactly like the REST path.
233async fn writable_room_attempt(
234 exam: &Exam,
235 attempt_id: &ExamAttemptId,
236 user: &UserId,
237 db: &Database,
238) -> Result<ExamAttempt, AppError> {
239 let attempt = writable_attempt(exam, user, db).await?;
240 if &attempt.get_id() != attempt_id {
241 return Err(AppError::Conflict(
242 "this room's sitting is over — reconnect to continue in the new attempt",
243 ));
244 }
245 Ok(attempt)
246}
247
248/// Re-read everything, push a `state` frame, and close the room (after a
249/// `finished`/`expired` notice) once the room's sitting is no longer in
250/// progress.
251async fn push_state(
252 socket: &mut WebSocket,
253 exam: &ExamId,
254 attempt: &ExamAttemptId,
255 db: &Database,
256) -> Result<(), RoomClosed> {
257 let (frame, status, finished_at) = match state_frame(exam, attempt, db).await {
258 Ok(state) => state,
259 // The exam vanished mid-room (deleted) or the db hiccuped: nothing
260 // sensible left to serve.
261 Err(err) => {
262 tracing::warn!("exam room state failed: {err}");
263 let _ = send(
264 socket,
265 json!({ "type": "error", "message": "state unavailable" }),
266 )
267 .await;
268 return Err(RoomClosed);
269 }
270 };
271 send(socket, frame).await?;
272 match status {
273 AttemptStatus::InProgress => Ok(()),
274 AttemptStatus::Submitted => {
275 send(
276 socket,
277 json!({ "type": "finished", "finished_at": finished_at }),
278 )
279 .await?;
280 Err(RoomClosed)
281 }
282 AttemptStatus::Expired => {
283 send(socket, json!({ "type": "expired" })).await?;
284 Err(RoomClosed)
285 }
286 }
287}
288
289/// One server-judged snapshot of the room's own sitting, shaped like the REST
290/// `AttemptResponse`'s live fields.
291async fn state_frame(
292 exam: &ExamId,
293 attempt: &ExamAttemptId,
294 db: &Database,
295) -> Result<(Value, AttemptStatus, Option<i64>), AppError> {
296 let exam = crate::service::exam::read(db, exam)
297 .await?
298 .ok_or(AppError::NotFound)?;
299 let attempt = read(db, attempt).await?.ok_or(AppError::NotFound)?;
300 let now = Timestamp::now();
301 let status = attempt.status(&exam, now);
302 let deadline = attempt.deadline(&exam);
303 let remaining_ms = (status == AttemptStatus::InProgress)
304 .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0)))
305 .flatten();
306 let answered = crate::service::exam_answer::list_for_exam_user(
307 db,
308 exam.get_id(),
309 attempt.get_user(),
310 attempt.get_seq(),
311 )
312 .await?
313 .len();
314 let question_count = crate::service::exam_question::list_for_exam(db, exam.get_id(), None, 0)
315 .await?
316 .0
317 .len();
318 let frame = json!({
319 "type": "state",
320 "status": status.as_str(),
321 "attempt": attempt.get_seq(),
322 "deadline": deadline.map(|t| t.as_millis()),
323 "remaining_ms": remaining_ms,
324 "now": now.as_millis(),
325 "answered": answered,
326 "question_count": question_count,
327 });
328 Ok((
329 frame,
330 status,
331 attempt.get_finished_at().map(|t| t.as_millis()),
332 ))
333}
334
335async fn handle_message(
336 socket: &mut WebSocket,
337 text: &str,
338 exam_id: &ExamId,
339 attempt_id: &ExamAttemptId,
340 user: &UserId,
341 db: &Database,
342) -> Result<(), RoomClosed> {
343 let message = match serde_json::from_str::<ClientMessage>(text) {
344 Ok(message) => message,
345 Err(err) => {
346 return send(
347 socket,
348 json!({ "type": "error", "message": format!("unrecognized message: {err}") }),
349 )
350 .await;
351 }
352 };
353 match message {
354 ClientMessage::Ping => send(socket, json!({ "type": "pong" })).await,
355 ClientMessage::Answer {
356 question_id,
357 selected,
358 text,
359 client_seq,
360 } => {
361 // Cap the key before it can be echoed — see [`MAX_QUESTION_ID_LEN`].
362 if let Err(err) = validate_required("question_id", &question_id, MAX_QUESTION_ID_LEN) {
363 let frame = error_frame_for(&AppError::Validation(err), None, client_seq);
364 return send(socket, frame).await;
365 }
366 // Re-read the exam so the save is judged against the *current*
367 // schedule, exactly like the REST path it shares — but write into
368 // the room's own sitting, never whatever is latest. No process
369 // lease is needed around the gates and the upsert: the save is
370 // one guarded statement keyed to the sitting's own seq, and a
371 // retake writes fresh rows at a higher seq, so nothing can wipe
372 // the sheet under this save.
373 //
374 // corner-cut (accepted race, reviewed, unchanged): the room's
375 // sitting was chosen at join, so a save can land on it just
376 // after a retake made it terminal. It writes a history row for
377 // the old seq; the grade of record (latest seq) is untouched.
378 // The fix is a `current_seq` claim on every save — the hottest
379 // path here — so the cost beats the damage and it stays.
380 // Tracks how far the gates got: only once the sitting resolved can
381 // a failure possibly be about this one question rather than about
382 // the room. See [`error_frame_for`].
383 let mut in_save = false;
384 let saved = match crate::service::exam::read(db, exam_id).await {
385 Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await {
386 Ok(attempt) => {
387 in_save = true;
388 save_answer_in(db, &exam, &attempt, &question_id, selected, text).await
389 }
390 Err(err) => Err(err),
391 },
392 Ok(None) => Err(AppError::NotFound),
393 Err(err) => Err(err),
394 };
395 match saved {
396 Ok(answer) => {
397 let mut frame = json!({
398 "type": "saved",
399 "question_id": answer.get_question().key(),
400 "updated_at": answer.get_updated_at().as_millis(),
401 });
402 with_client_seq(&mut frame, client_seq);
403 send(socket, frame).await?;
404 // Progress changed — refresh the countdown/answered state
405 // right away rather than waiting out the tick.
406 push_state(socket, exam_id, attempt_id, db).await
407 }
408 Err(err) => {
409 let attributed = in_save && attributable(&err);
410 send(
411 socket,
412 error_frame_for(
413 &err,
414 attributed.then_some(question_id.as_str()),
415 client_seq,
416 ),
417 )
418 .await
419 }
420 }
421 }
422 ClientMessage::Finish => {
423 // Submit the room's own sitting — a stale room must not submit a
424 // retake it never hosted.
425 let finished = match crate::service::exam::read(db, exam_id).await {
426 Ok(Some(exam)) => {
427 // Its own archived-year gate: `finish` is the one
428 // sitting-side write that does not go through
429 // `save_answer_in`, and the refusal leaves the room by the
430 // same error frame as every other conflict.
431 async {
432 let attempt = writable_room_attempt(&exam, attempt_id, user, db).await?;
433 crate::service::exam_attempt::require_open(db, &exam).await?;
434 finish(db, attempt).await
435 }
436 .await
437 }
438 Ok(None) => Err(AppError::NotFound),
439 Err(err) => Err(err),
440 };
441 match finished {
442 Ok(attempt) => {
443 send(
444 socket,
445 json!({
446 "type": "finished",
447 "finished_at": attempt.get_finished_at().map(|t| t.as_millis()),
448 }),
449 )
450 .await?;
451 Err(RoomClosed)
452 }
453 Err(err) => send(socket, error_frame(&err)).await,
454 }
455 }
456 }
457}
458
459/// Whether a failure raised *inside* the save (past the exam and sitting
460/// gates) is about the answered question alone, so the client can fail that
461/// one save instead of every save in flight.
462///
463/// Only the two question-shaped failures qualify: [`AppError::Validation`]
464/// (the payload doesn't fit the question — wrong kind, unknown choice, too
465/// long) and [`AppError::NotFound`] (no such question in this exam). Every
466/// other variant from the save path is about the sitter or the sitting —
467/// `Unauthorized`/`Forbidden` (promoted out of `student`, unenrolled),
468/// `Conflict` (walked out with rejoin closed) — and dooms the next save just
469/// as much as this one, so it stays unattributed and keeps fail-everything.
470/// Db/Internal stay unattributed too: a database that just failed is not a
471/// per-question fact, and over-reporting there is the safe side.
472fn attributable(err: &AppError) -> bool {
473 matches!(err, AppError::Validation(_) | AppError::NotFound)
474}
475
476/// The public words for an error — the same strings the HTTP layer would use,
477/// with internals logged, never sent.
478fn error_frame(err: &AppError) -> Value {
479 error_frame_for(err, None, None)
480}
481
482/// [`error_frame`] plus the optional blame: `question_id` when the failure
483/// belongs to one `answer` message, and `client_seq` whenever the `answer` carried
484/// one — the two are independent, so an unattributable failure is still
485/// matchable to the send that caused it. Absent keeps its original meaning —
486/// an unattributed failure — so a client that ignores the fields behaves
487/// exactly as before.
488fn error_frame_for(err: &AppError, question: Option<&str>, client_seq: Option<u64>) -> Value {
489 let mut frame = json!({ "type": "error", "message": room::public_message(err, ROOM) });
490 if let Some(question) = question {
491 frame["question_id"] = json!(question);
492 }
493 with_client_seq(&mut frame, client_seq);
494 frame
495}