Make room presence atomic with left_at writes
Browse files at this commit2aed950052af1881fc6a679491234f96636c86ffParent: 6faa816- fix
- make room presence atomic with left_at writes
2 changed files +54 -16
- src/state.rs +6 -0
- src/web/exam_ws.rs +48 -16
src/state.rsmodified+6 -0
| @@ -27,6 +27,12 @@ pub struct AppState { | |||
| 27 | /// attempt's record key. The room counts itself in on entry and out on exit, | 27 | /// attempt's record key. The room counts itself in on entry and out on exit, |
| 28 | /// and only the last socket out stamps the walk-out (`left_at`) — a student | 28 | /// and only the last socket out stamps the walk-out (`left_at`) — a student |
| 29 | /// closing one of two tabs never counts as having left the exam. | 29 | /// closing one of two tabs never counts as having left the exam. |
| 30 | +/// | ||
| 31 | +/// The inner mutex only guards the map (never held across an await — keep it | ||
| 32 | +/// that way). Each count transition and its matching `left_at` DB write are | ||
| 33 | +/// serialized as one critical section by the exam room's `PRESENCE_LOCK` | ||
| 34 | +/// (see `web::exam_ws`), so "clear on join" and "stamp on last-out" stay | ||
| 35 | +/// atomic with the counts they depend on. | ||
| 30 | #[derive(Clone, Default)] | 36 | #[derive(Clone, Default)] |
| 31 | pub struct ExamPresence(Arc<Mutex<HashMap<String, usize>>>); | 37 | pub struct ExamPresence(Arc<Mutex<HashMap<String, usize>>>); |
| 32 | 38 | ||
src/web/exam_ws.rsmodified+48 -16
| @@ -28,8 +28,8 @@ | |||
| 28 | //! live role and enrollment — so a promotion out of `student` or an | 28 | //! live role and enrollment — so a promotion out of `student` or an |
| 29 | //! unenrollment mid-exam closes the sheet with no reconnect needed. | 29 | //! unenrollment mid-exam closes the sheet with no reconnect needed. |
| 30 | //! | 30 | //! |
| 31 | -//! The room is also the presence signal behind the rejoin policy: connecting | 31 | +//! The room is also the presence signal behind the rejoin policy: joining the |
| 32 | -//! clears the attempt's `left_at`, and the *last* socket of the sitting to | 32 | +//! room clears the attempt's `left_at`, and the *last* socket of the sitting to |
| 33 | //! close while the attempt is still running stamps it — a student closing one | 33 | //! close while the attempt is still running stamps it — a student closing one |
| 34 | //! of two tabs hasn't left, and a lingering socket from an already-finished | 34 | //! of two tabs hasn't left, and a lingering socket from an already-finished |
| 35 | //! sitting can never mark a later retake as left. With the exam's | 35 | //! sitting can never mark a later retake as left. With the exam's |
| @@ -66,6 +66,21 @@ use crate::web::exams::{ | |||
| 66 | check_rejoin, ensure_enrolled, ensure_student, save_answer_in, writable_attempt, | 66 | check_rejoin, ensure_enrolled, ensure_student, save_answer_in, writable_attempt, |
| 67 | }; | 67 | }; |
| 68 | 68 | ||
| 69 | +/// Serializes every presence transition with its matching `left_at` write: | ||
| 70 | +/// `enter` + clear at room start and `leave` + maybe-stamp at room teardown | ||
| 71 | +/// are each one critical section, so any join and any teardown run wholly | ||
| 72 | +/// before or wholly after each other. Teardown first: its stamp lands, then | ||
| 73 | +/// the join's clear overwrites it — the student is present and unmarked. | ||
| 74 | +/// Join first: the teardown's `leave` sees the joiner's socket still counted, | ||
| 75 | +/// so it never stamps. No ordering leaves a present student stamped as left — | ||
| 76 | +/// the reconnect-vs-teardown race that used to lock students out with | ||
| 77 | +/// `allow_rejoin` off (cleared at the door, stamped after, present forever | ||
| 78 | +/// refused). The database is embedded — this process is the only writer — so | ||
| 79 | +/// one process-wide lock is sufficient, same as `REGISTER_LOCK`. | ||
| 80 | +// ponytail: global lock, per-attempt locks if room churn ever shows up in a | ||
| 81 | +// profile. | ||
| 82 | +static PRESENCE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); | ||
| 83 | + | ||
| 69 | /// What the client asked for, tagged by `type`. | 84 | /// What the client asked for, tagged by `type`. |
| 70 | #[derive(Deserialize)] | 85 | #[derive(Deserialize)] |
| 71 | #[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] | 86 | #[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] |
| @@ -86,8 +101,13 @@ enum ClientMessage { | |||
| 86 | /// unknown exam (404), draft with no mode (409), not a student (403), not | 101 | /// unknown exam (404), draft with no mode (409), not a student (403), not |
| 87 | /// enrolled (403), no attempt yet (404 — `POST /exams/{id}/attempt` first), | 102 | /// enrolled (403), no attempt yet (404 — `POST /exams/{id}/attempt` first), |
| 88 | /// submitted or expired (409), left the room while rejoin is closed (409). | 103 | /// submitted or expired (409), left the room while rejoin is closed (409). |
| 89 | -/// Entering the room clears the attempt's `left_at` — the student is back | 104 | +/// |
| 90 | -/// inside. | 105 | +/// The rejoin gate here is a read-only fast-fail for a proper 409; the |
| 106 | +/// authoritative clear of `left_at` happens inside the room task, under | ||
| 107 | +/// [`PRESENCE_LOCK`], atomically with the presence count — milliseconds after | ||
| 108 | +/// this gate, which no HTTP caller can observe. Clearing it here instead | ||
| 109 | +/// (before the socket counts as present) is exactly the ordering that let a | ||
| 110 | +/// dying socket's teardown stamp a student who was already reconnecting. | ||
| 91 | pub async fn attempt_ws( | 111 | pub async fn attempt_ws( |
| 92 | State(st): State<AppState>, | 112 | State(st): State<AppState>, |
| 93 | CurrentUser(user): CurrentUser, | 113 | CurrentUser(user): CurrentUser, |
| @@ -106,11 +126,6 @@ pub async fn attempt_ws( | |||
| 106 | ensure_enrolled(&exam, user.get_id(), &st.db).await?; | 126 | ensure_enrolled(&exam, user.get_id(), &st.db).await?; |
| 107 | let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; | 127 | let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; |
| 108 | check_rejoin(&exam, &attempt)?; | 128 | check_rejoin(&exam, &attempt)?; |
| 109 | - let attempt = if attempt.get_left_at().is_some() { | ||
| 110 | - attempt.set_left(None, &st.db).await? | ||
| 111 | - } else { | ||
| 112 | - attempt | ||
| 113 | - }; | ||
| 114 | 129 | ||
| 115 | let user_id = user.get_id().clone(); | 130 | let user_id = user.get_id().clone(); |
| 116 | Ok(ws.on_upgrade(move |socket| room(socket, st, exam, attempt, user_id))) | 131 | Ok(ws.on_upgrade(move |socket| room(socket, st, exam, attempt, user_id))) |
| @@ -122,8 +137,20 @@ pub async fn attempt_ws( | |||
| 122 | async fn room(mut socket: WebSocket, st: AppState, exam: Exam, attempt: ExamAttempt, user: UserId) { | 137 | async fn room(mut socket: WebSocket, st: AppState, exam: Exam, attempt: ExamAttempt, user: UserId) { |
| 123 | let exam_id = exam.get_id().clone(); | 138 | let exam_id = exam.get_id().clone(); |
| 124 | let attempt_id = attempt.get_id().clone(); | 139 | let attempt_id = attempt.get_id().clone(); |
| 125 | - // This socket counts as presence in the sitting's room until it closes. | 140 | + // Join critical section: this socket counts as presence in the sitting's |
| 126 | - st.exam_presence.enter(attempt_id.key()); | 141 | + // room until it closes, and joining clears the walk-out marker — one |
| 142 | + // atomic step under PRESENCE_LOCK, so a dying socket's teardown either | ||
| 143 | + // stamps before this (and the clear overwrites it) or sees this socket | ||
| 144 | + // counted (and never stamps). The clear is unconditional: the door's | ||
| 145 | + // snapshot may predate a stamp that raced the upgrade. Best-effort — a | ||
| 146 | + // failed clear leaves the stamp for the next join or the teacher's door. | ||
| 147 | + { | ||
| 148 | + let _guard = PRESENCE_LOCK.lock().await; | ||
| 149 | + st.exam_presence.enter(attempt_id.key()); | ||
| 150 | + if let Err(err) = attempt.set_left(None, &st.db).await { | ||
| 151 | + tracing::warn!("exam room could not clear left_at on join: {err}"); | ||
| 152 | + } | ||
| 153 | + } | ||
| 127 | let mut tick = tokio::time::interval(Duration::from_secs(EXAM_WS_TICK_SECS)); | 154 | let mut tick = tokio::time::interval(Duration::from_secs(EXAM_WS_TICK_SECS)); |
| 128 | loop { | 155 | loop { |
| 129 | tokio::select! { | 156 | tokio::select! { |
| @@ -153,11 +180,16 @@ async fn room(mut socket: WebSocket, st: AppState, exam: Exam, attempt: ExamAtte | |||
| 153 | // Best-effort closing handshake — a bare TCP teardown reads as an error | 180 | // Best-effort closing handshake — a bare TCP teardown reads as an error |
| 154 | // on the client; a Close frame reads as "the room is over". | 181 | // on the client; a Close frame reads as "the room is over". |
| 155 | let _ = socket.send(Message::Close(None)).await; | 182 | let _ = socket.send(Message::Close(None)).await; |
| 156 | - // Only the last socket out means the student actually left the room. If | 183 | + // Leave critical section: only the last socket out means the student |
| 157 | - // this sitting is still running, stamp the walk-out — with `allow_rejoin` | 184 | + // actually left the room, and the count-down and its stamp are one atomic |
| 158 | - // off this is what locks further answering. Terminal exits (finished or | 185 | + // step under PRESENCE_LOCK (a join racing this either lands wholly before |
| 159 | - // expired, and any sitting superseded by a retake is terminal) need no | 186 | + // — its socket keeps the count up, no stamp — or wholly after, clearing |
| 160 | - // stamp. Best-effort: a failed stamp only means it goes unrecorded. | 187 | + // whatever this stamps). If this sitting is still running, stamp the |
| 188 | + // walk-out — with `allow_rejoin` off this is what locks further | ||
| 189 | + // answering. Terminal exits (finished or expired, and any sitting | ||
| 190 | + // superseded by a retake is terminal) need no stamp. Best-effort: a | ||
| 191 | + // failed stamp only means it goes unrecorded. | ||
| 192 | + let _guard = PRESENCE_LOCK.lock().await; | ||
| 161 | if st.exam_presence.leave(attempt_id.key()) { | 193 | if st.exam_presence.leave(attempt_id.key()) { |
| 162 | stamp_left(&exam_id, &attempt_id, &st.db).await; | 194 | stamp_left(&exam_id, &attempt_id, &st.db).await; |
| 163 | } | 195 | } |