Bind room writes to their sitting, wall unenrolled sitters
Browse files at this commit33755655d22707a9eeba7f2ebf7b8b21f3b597f7Parent: 6eb0a28- fix
- bind room writes to their sitting, wall unenrolled sitters
9 changed files +531 -69
- README.md +22 -13
- src/constant.rs +4 -0
- src/domain/settings.rs +118 -1
- src/web/exam_ws.rs +38 -17
- src/web/exams.rs +55 -20
- src/web/settings.rs +31 -17
- src/web/work.rs +3 -1
- tests/e2e.rs +112 -0
- tests/integration.rs +148 -0
README.mdmodified+22 -13
| @@ -290,8 +290,8 @@ marks/attendance reports narrow to the courses the caller manages. | |||
| 290 | | GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) | | 290 | | GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) | |
| 291 | | PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question — the kind bundle revalidates as a unit (course manager; frozen once attempted) | | 291 | | PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question — the kind bundle revalidates as a unit (course manager; frozen once attempted) | |
| 292 | | DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) | | 292 | | DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) | |
| 293 | -| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded (requires an attempt) | | 293 | +| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded (requires enrollment + an attempt) | |
| 294 | -| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \| text?}` — autosave one answer while `in_progress` (and not locked out by a closed rejoin door) | | 294 | +| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \| text?}` — autosave one answer while enrolled and `in_progress` (and not locked out by a closed rejoin door) | |
| 295 | | GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) | | 295 | | GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) | |
| 296 | | GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room: state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") | | 296 | | GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room: state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") | |
| 297 | | GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster × latest attempts × marks + per-student progress/`left_at`/`attempts_used` + counts (course manager) | | 297 | | GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster × latest attempts × marks + per-student progress/`left_at`/`attempts_used` + counts (course manager) | |
| @@ -307,7 +307,7 @@ marks/attendance reports narrow to the courses the caller manages. | |||
| 307 | | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies | | 307 | | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies | |
| 308 | | GET | `/attendance/{user}` | teacher | A user's attendance report, narrowed to the caller's courses (manager+: full) | | 308 | | GET | `/attendance/{user}` | teacher | A user's attendance report, narrowed to the caller's courses (manager+: full) | |
| 309 | | GET | `/settings` | student | The school's policy: `exam_kinds`, `attendance_statuses`, `grade_bands` | | 309 | | GET | `/settings` | student | The school's policy: `exam_kinds`, `attendance_statuses`, `grade_bands` | |
| 310 | -| PATCH | `/settings` | manager | Replace any subset of the three lists, each wholesale (see "Per-school policy") | | 310 | +| PATCH | `/settings` | manager | Replace any subset of the three lists, each wholesale; concurrent edits merge, never silently revert each other (see "Per-school policy") | |
| 311 | | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) | | 311 | | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) | |
| 312 | | GET | `/terms` | student | List terms, newest first | | 312 | | GET | `/terms` | student | List terms, newest first | |
| 313 | | GET | `/terms/{id}` | student | Get one term | | 313 | | GET | `/terms/{id}` | student | Get one term | |
| @@ -381,9 +381,12 @@ editable `settings` singleton (`GET /settings` for any signed-in user, | |||
| 381 | can switch display scales without touching a single stored mark. | 381 | can switch display scales without touching a single stored mark. |
| 382 | 382 | ||
| 383 | A `PATCH` replaces only the fields it carries, each wholesale, and validation | 383 | A `PATCH` replaces only the fields it carries, each wholesale, and validation |
| 384 | -is all-or-nothing. Editing a list never rewrites history: an exam keeps its | 384 | +is all-or-nothing. Concurrent edits are safe: each save applies only if the |
| 385 | -retired kind, a roll-call row keeps its retired status — only **new writes** | 385 | +policy still matches the snapshot it merged from (retrying over the fresh row |
| 386 | -are held to the current lists. | 386 | +otherwise), so two managers patching different fields both land instead of |
| 387 | +the later write silently reverting the earlier one. Editing a list never | ||
| 388 | +rewrites history: an exam keeps its retired kind, a roll-call row keeps its | ||
| 389 | +retired status — only **new writes** are held to the current lists. | ||
| 387 | 390 | ||
| 388 | Academic structure is data too. **Terms** (`/terms`) model whatever calendar | 391 | Academic structure is data too. **Terms** (`/terms`) model whatever calendar |
| 389 | the school runs — semester, trimester, quarter systems are just rows with a | 392 | the school runs — semester, trimester, quarter systems are just rows with a |
| @@ -512,15 +515,18 @@ would fork what "the exam" means. Deleting a question cascades its answers. | |||
| 512 | **Answering** (student, attempt `in_progress`, deadline judged by the server | 515 | **Answering** (student, attempt `in_progress`, deadline judged by the server |
| 513 | clock on every save): | 516 | clock on every save): |
| 514 | 517 | ||
| 515 | -- `GET /exams/{id}/attempt/questions` — the sitting view. Requires an attempt | 518 | +- `GET /exams/{id}/attempt/questions` — the sitting view. Requires |
| 516 | - (`404` before `POST /exams/{id}/attempt`; also the anti-peek gate), never | 519 | + enrollment (`403` — the questions are course content, so leaving the course |
| 517 | - contains `correct`, and embeds the caller's own saved answer per question | 520 | + closes them) and an attempt (`404` before `POST /exams/{id}/attempt`; also |
| 518 | - (`{selected, text, updated_at}` or `null`). Still readable after | 521 | + the anti-peek gate), never contains `correct`, and embeds the caller's own |
| 519 | - submitting/expiry, for review. | 522 | + saved answer per question (`{selected, text, updated_at}` or `null`). Still |
| 523 | + readable after submitting/expiry, for review. | ||
| 520 | - `POST /exams/{id}/attempt/answers` `{question_id, selected? | text?}` — an | 524 | - `POST /exams/{id}/attempt/answers` `{question_id, selected? | text?}` — an |
| 521 | upsert: one row per question+user, re-answering overwrites. The payload must | 525 | upsert: one row per question+user, re-answering overwrites. The payload must |
| 522 | match the question's kind (`selected` indexing a choice, or `text` | 526 | match the question's kind (`selected` indexing a choice, or `text` |
| 523 | - ≤ 10 000 chars — empty clears the draft); mismatches are `400`s. Once the | 527 | + ≤ 10 000 chars — empty clears the draft); mismatches are `400`s. Requires |
| 528 | + enrollment (`403`): an unenrollment mid-exam closes the sheet (the exam | ||
| 529 | + room's door check, applied to every save — finishing stays open). Once the | ||
| 524 | attempt is submitted or past its deadline every save is a `409` — likewise | 530 | attempt is submitted or past its deadline every save is a `409` — likewise |
| 525 | while the student has left the exam room with `allow_rejoin` off; answers | 531 | while the student has left the exam room with `allow_rejoin` off; answers |
| 526 | saved in time survive untouched for grading (until a retake wipes the sheet | 532 | saved in time survive untouched for grading (until a retake wipes the sheet |
| @@ -551,7 +557,10 @@ rejoin is closed `409`. Then JSON text frames: | |||
| 551 | 557 | ||
| 552 | Every tick and every save re-read the exam, so a mid-exam `ends_at` extension | 558 | Every tick and every save re-read the exam, so a mid-exam `ends_at` extension |
| 553 | moves the room's countdown on the next tick, and no stale socket can write | 559 | 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. | 560 | +past its real deadline — the socket shares the exact REST write path. Each |
| 561 | +room acts only on the sitting it was opened for: once that sitting is over, | ||
| 562 | +its `answer`/`finish` are `error` frames, so a lingering socket can never | ||
| 563 | +scribble on (or instantly submit) a retake started elsewhere. | ||
| 555 | 564 | ||
| 556 | The room is also the presence signal behind the **rejoin door**: connecting | 565 | The room is also the presence signal behind the **rejoin door**: connecting |
| 557 | clears the attempt's `left_at`, and the *last* socket of the sitting to close | 566 | clears the attempt's `left_at`, and the *last* socket of the sitting to close |
src/constant.rsmodified+4 -0
| @@ -65,6 +65,10 @@ pub const MAX_SETTINGS_ITEM_LEN: usize = 50; | |||
| 65 | pub const MAX_GRADE_BANDS: usize = 20; | 65 | pub const MAX_GRADE_BANDS: usize = 20; |
| 66 | pub const MAX_GRADE_LABEL_LEN: usize = 20; | 66 | pub const MAX_GRADE_LABEL_LEN: usize = 20; |
| 67 | 67 | ||
| 68 | +/// How many times `PATCH /settings` re-merges and retries when a concurrent | ||
| 69 | +/// edit lands between its snapshot and its compare-and-set save. | ||
| 70 | +pub const SETTINGS_UPDATE_RETRIES: usize = 3; | ||
| 71 | + | ||
| 68 | pub const MAX_TERM_NAME_LEN: usize = 100; | 72 | pub const MAX_TERM_NAME_LEN: usize = 100; |
| 69 | 73 | ||
| 70 | /// The only accepted exam modes. `sync`: everyone sits the exam inside one | 74 | /// The only accepted exam modes. `sync`: everyone sits the exam inside one |
src/domain/settings.rsmodified+118 -1
| @@ -167,11 +167,53 @@ impl Settings { | |||
| 167 | Ok(found.unwrap_or_else(Self::defaults)) | 167 | Ok(found.unwrap_or_else(Self::defaults)) |
| 168 | } | 168 | } |
| 169 | 169 | ||
| 170 | - /// Persist the policy (single UPSERT on the fixed singleton id). | 170 | + /// Persist the policy (single UPSERT on the fixed singleton id), |
| 171 | + /// unconditionally — last write wins. Prefer [`Self::save_if_unchanged`] | ||
| 172 | + /// wherever the new policy was merged from a loaded snapshot. | ||
| 171 | pub async fn save(self, db: &Database) -> Result<Settings, AppError> { | 173 | pub async fn save(self, db: &Database) -> Result<Settings, AppError> { |
| 172 | let saved: Option<Settings> = db.upsert(Self::record_id()).content(self).await?; | 174 | let saved: Option<Settings> = db.upsert(Self::record_id()).content(self).await?; |
| 173 | saved.ok_or_else(|| AppError::Internal("failed to save settings".into())) | 175 | saved.ok_or_else(|| AppError::Internal("failed to save settings".into())) |
| 174 | } | 176 | } |
| 177 | + | ||
| 178 | + /// Persist the policy only while the stored row still matches `expected` | ||
| 179 | + /// — the snapshot the caller merged omitted fields from. `None` means a | ||
| 180 | + /// concurrent edit landed in between and nothing was written: reload, | ||
| 181 | + /// re-merge, retry. Without this compare-and-set, two managers patching | ||
| 182 | + /// *different* fields silently revert each other (both merge from the | ||
| 183 | + /// same snapshot; the later whole-row write restores its stale copy of | ||
| 184 | + /// the other's field). | ||
| 185 | + /// | ||
| 186 | + /// One transaction: the seed insert materializes the defaults-as-loaded | ||
| 187 | + /// state when no row exists yet (`load` reported the defaults, so the | ||
| 188 | + /// defaults are what the caller merged over), then the guarded update | ||
| 189 | + /// applies `self` only if the row (still) equals `expected`. | ||
| 190 | + pub async fn save_if_unchanged( | ||
| 191 | + self, | ||
| 192 | + expected: &Settings, | ||
| 193 | + db: &Database, | ||
| 194 | + ) -> Result<Option<Settings>, AppError> { | ||
| 195 | + let mut result = db | ||
| 196 | + .query( | ||
| 197 | + "BEGIN TRANSACTION; | ||
| 198 | + INSERT IGNORE INTO settings $expected; | ||
| 199 | + UPDATE $id CONTENT $new | ||
| 200 | + WHERE exam_kinds = $ek | ||
| 201 | + AND attendance_statuses = $st | ||
| 202 | + AND grade_bands = $gb; | ||
| 203 | + COMMIT TRANSACTION;", | ||
| 204 | + ) | ||
| 205 | + .bind(("expected", expected.clone())) | ||
| 206 | + .bind(("id", Self::record_id())) | ||
| 207 | + .bind(("new", self)) | ||
| 208 | + .bind(("ek", expected.exam_kinds.clone())) | ||
| 209 | + .bind(("st", expected.attendance_statuses.clone())) | ||
| 210 | + .bind(("gb", expected.grade_bands.clone())) | ||
| 211 | + .await? | ||
| 212 | + .check()?; | ||
| 213 | + // Statement slots count BEGIN too: the guarded UPDATE is slot 2. An | ||
| 214 | + // empty slot means the row no longer matched `expected`. | ||
| 215 | + Ok(result.take::<Vec<Settings>>(2)?.into_iter().next()) | ||
| 216 | + } | ||
| 175 | } | 217 | } |
| 176 | 218 | ||
| 177 | /// Shared rules for the editable string lists: 1–20 trimmed, non-empty, | 219 | /// Shared rules for the editable string lists: 1–20 trimmed, non-empty, |
| @@ -337,6 +379,81 @@ mod tests { | |||
| 337 | assert_eq!(rows[0].get_exam_kinds(), ["quiz"]); | 379 | assert_eq!(rows[0].get_exam_kinds(), ["quiz"]); |
| 338 | } | 380 | } |
| 339 | 381 | ||
| 382 | + #[tokio::test] | ||
| 383 | + async fn a_stale_snapshot_cannot_revert_a_newer_policy() { | ||
| 384 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 385 | + let statuses = Settings::defaults().get_attendance_statuses().to_vec(); | ||
| 386 | + | ||
| 387 | + // Editor A snapshots the policy (the defaults — no row yet)... | ||
| 388 | + let stale = Settings::load(&db).await.unwrap(); | ||
| 389 | + // ...then editor B lands a new exam-kind list first. | ||
| 390 | + Settings::try_new(kinds(&["lab"]), statuses.clone(), vec![]) | ||
| 391 | + .unwrap() | ||
| 392 | + .save(&db) | ||
| 393 | + .await | ||
| 394 | + .unwrap(); | ||
| 395 | + | ||
| 396 | + // A's merge over the stale snapshot (kinds kept "as loaded", bands | ||
| 397 | + // changed) — exactly what a concurrent PATCH /settings computes — | ||
| 398 | + // must be refused, not applied. | ||
| 399 | + let refused = Settings::try_new( | ||
| 400 | + stale.get_exam_kinds().to_vec(), | ||
| 401 | + stale.get_attendance_statuses().to_vec(), | ||
| 402 | + bands(&[(0, "F"), (50, "P")]), | ||
| 403 | + ) | ||
| 404 | + .unwrap() | ||
| 405 | + .save_if_unchanged(&stale, &db) | ||
| 406 | + .await | ||
| 407 | + .unwrap(); | ||
| 408 | + assert!(refused.is_none(), "a stale snapshot's save must not apply"); | ||
| 409 | + | ||
| 410 | + // B's edit must survive A's stale write attempt. | ||
| 411 | + let after = Settings::load(&db).await.unwrap(); | ||
| 412 | + assert_eq!( | ||
| 413 | + after.get_exam_kinds(), | ||
| 414 | + ["lab"], | ||
| 415 | + "a concurrent editor's exam kinds must not be silently reverted" | ||
| 416 | + ); | ||
| 417 | + assert!(after.get_grade_bands().is_empty()); | ||
| 418 | + | ||
| 419 | + // A's retry — reload, re-merge, save again — lands both edits. | ||
| 420 | + let fresh = Settings::load(&db).await.unwrap(); | ||
| 421 | + let saved = Settings::try_new( | ||
| 422 | + fresh.get_exam_kinds().to_vec(), | ||
| 423 | + fresh.get_attendance_statuses().to_vec(), | ||
| 424 | + bands(&[(0, "F"), (50, "P")]), | ||
| 425 | + ) | ||
| 426 | + .unwrap() | ||
| 427 | + .save_if_unchanged(&fresh, &db) | ||
| 428 | + .await | ||
| 429 | + .unwrap() | ||
| 430 | + .expect("a merge over the current row applies"); | ||
| 431 | + assert_eq!(saved.get_exam_kinds(), ["lab"]); | ||
| 432 | + assert_eq!(saved.get_grade_bands().len(), 2); | ||
| 433 | + } | ||
| 434 | + | ||
| 435 | + #[tokio::test] | ||
| 436 | + async fn save_if_unchanged_seeds_the_first_row() { | ||
| 437 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 438 | + // No row yet: `load` reports the defaults, and a save conditioned on | ||
| 439 | + // that snapshot must apply (seeding the singleton on the way). | ||
| 440 | + let current = Settings::load(&db).await.unwrap(); | ||
| 441 | + let saved = Settings::try_new( | ||
| 442 | + kinds(&["lab"]), | ||
| 443 | + current.get_attendance_statuses().to_vec(), | ||
| 444 | + vec![], | ||
| 445 | + ) | ||
| 446 | + .unwrap() | ||
| 447 | + .save_if_unchanged(¤t, &db) | ||
| 448 | + .await | ||
| 449 | + .unwrap() | ||
| 450 | + .expect("the first save applies"); | ||
| 451 | + assert_eq!(saved.get_exam_kinds(), ["lab"]); | ||
| 452 | + let mut result = db.query("SELECT * FROM settings").await.unwrap(); | ||
| 453 | + let rows: Vec<Settings> = result.take(0).unwrap(); | ||
| 454 | + assert_eq!(rows.len(), 1, "still one singleton row"); | ||
| 455 | + } | ||
| 456 | + | ||
| 340 | #[tokio::test] | 457 | #[tokio::test] |
| 341 | async fn grade_label_picks_the_greatest_min_at_or_below() { | 458 | async fn grade_label_picks_the_greatest_min_at_or_below() { |
| 342 | let defaults = Settings::defaults(); | 459 | let defaults = Settings::defaults(); |
src/web/exam_ws.rsmodified+38 -17
| @@ -36,8 +36,10 @@ | |||
| 36 | //! finishing stays allowed. | 36 | //! finishing stays allowed. |
| 37 | //! | 37 | //! |
| 38 | //! Each room is bound to the sitting it was opened for: state frames track | 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 — | 39 | +//! that attempt (not whatever is latest), a room whose sitting ends — |
| 40 | -//! submitted or expired anywhere — announces it and closes. | 40 | +//! submitted or expired anywhere — announces it and closes, and `answer` / |
| 41 | +//! `finish` refuse to touch any other sitting, so a lingering socket can | ||
| 42 | +//! never write into (or submit) a retake it never hosted. | ||
| 41 | 43 | ||
| 42 | use std::time::Duration; | 44 | use std::time::Duration; |
| 43 | 45 | ||
| @@ -49,7 +51,6 @@ use serde_json::{Value, json}; | |||
| 49 | 51 | ||
| 50 | use crate::constant::EXAM_WS_TICK_SECS; | 52 | use crate::constant::EXAM_WS_TICK_SECS; |
| 51 | use crate::database::Database; | 53 | use crate::database::Database; |
| 52 | -use crate::domain::enrollment::Enrollment; | ||
| 53 | use crate::domain::exam::{Exam, ExamId}; | 54 | use crate::domain::exam::{Exam, ExamId}; |
| 54 | use crate::domain::exam_answer::ExamAnswer; | 55 | use crate::domain::exam_answer::ExamAnswer; |
| 55 | use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId}; | 56 | use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId}; |
| @@ -59,7 +60,7 @@ use crate::domain::user::UserId; | |||
| 59 | use crate::error::AppError; | 60 | use crate::error::AppError; |
| 60 | use crate::state::AppState; | 61 | use crate::state::AppState; |
| 61 | use crate::web::CurrentUser; | 62 | use crate::web::CurrentUser; |
| 62 | -use crate::web::exams::{check_rejoin, save_answer_checked, writable_attempt}; | 63 | +use crate::web::exams::{check_rejoin, ensure_enrolled, save_answer_in, writable_attempt}; |
| 63 | 64 | ||
| 64 | /// What the client asked for, tagged by `type`. | 65 | /// What the client asked for, tagged by `type`. |
| 65 | #[derive(Deserialize)] | 66 | #[derive(Deserialize)] |
| @@ -96,14 +97,7 @@ pub async fn attempt_ws( | |||
| 96 | "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)", | 97 | "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)", |
| 97 | )); | 98 | )); |
| 98 | } | 99 | } |
| 99 | - if Enrollment::read_for_user(exam.get_course(), user.get_id(), &st.db) | 100 | + ensure_enrolled(&exam, user.get_id(), &st.db).await?; |
| 100 | - .await? | ||
| 101 | - .is_none() | ||
| 102 | - { | ||
| 103 | - return Err(AppError::Forbidden( | ||
| 104 | - "you are not enrolled in this exam's course", | ||
| 105 | - )); | ||
| 106 | - } | ||
| 107 | let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; | 101 | let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; |
| 108 | check_rejoin(&exam, &attempt)?; | 102 | check_rejoin(&exam, &attempt)?; |
| 109 | let attempt = if attempt.get_left_at().is_some() { | 103 | let attempt = if attempt.get_left_at().is_some() { |
| @@ -198,6 +192,27 @@ async fn stamp_left(exam_id: &ExamId, attempt_id: &ExamAttemptId, db: &Database) | |||
| 198 | /// terminal state and the close frame was sent. | 192 | /// terminal state and the close frame was sent. |
| 199 | struct RoomClosed; | 193 | struct RoomClosed; |
| 200 | 194 | ||
| 195 | +/// The room's own sitting, provided it is still the student's current one and | ||
| 196 | +/// writable. Messages act on the sitting the room was opened for — never on a | ||
| 197 | +/// retake started elsewhere while this socket lingered, which a stale tab | ||
| 198 | +/// could otherwise scribble on or instantly submit (burning a limited | ||
| 199 | +/// sitting). The latest-attempt read also keeps the deadline gates on the | ||
| 200 | +/// exam's current schedule, exactly like the REST path. | ||
| 201 | +async fn writable_room_attempt( | ||
| 202 | + exam: &Exam, | ||
| 203 | + attempt_id: &ExamAttemptId, | ||
| 204 | + user: &UserId, | ||
| 205 | + db: &Database, | ||
| 206 | +) -> Result<ExamAttempt, AppError> { | ||
| 207 | + let attempt = writable_attempt(exam, user, db).await?; | ||
| 208 | + if attempt.get_id() != attempt_id { | ||
| 209 | + return Err(AppError::Conflict( | ||
| 210 | + "this room's sitting is over — reconnect to continue in the new attempt", | ||
| 211 | + )); | ||
| 212 | + } | ||
| 213 | + Ok(attempt) | ||
| 214 | +} | ||
| 215 | + | ||
| 201 | async fn send(socket: &mut WebSocket, frame: Value) -> Result<(), RoomClosed> { | 216 | async fn send(socket: &mut WebSocket, frame: Value) -> Result<(), RoomClosed> { |
| 202 | socket | 217 | socket |
| 203 | .send(Message::Text(frame.to_string().into())) | 218 | .send(Message::Text(frame.to_string().into())) |
| @@ -310,11 +325,15 @@ async fn handle_message( | |||
| 310 | text, | 325 | text, |
| 311 | } => { | 326 | } => { |
| 312 | // Re-read the exam so the save is judged against the *current* | 327 | // Re-read the exam so the save is judged against the *current* |
| 313 | - // schedule, exactly like the REST path it shares. | 328 | + // schedule, exactly like the REST path it shares — but write into |
| 329 | + // the room's own sitting, never whatever is latest. | ||
| 314 | let saved = match Exam::read(exam_id, db).await { | 330 | let saved = match Exam::read(exam_id, db).await { |
| 315 | - Ok(Some(exam)) => { | 331 | + Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await { |
| 316 | - save_answer_checked(&exam, user, &question_id, selected, text, db).await | 332 | + Ok(attempt) => { |
| 317 | - } | 333 | + save_answer_in(&exam, &attempt, &question_id, selected, text, db).await |
| 334 | + } | ||
| 335 | + Err(err) => Err(err), | ||
| 336 | + }, | ||
| 318 | Ok(None) => Err(AppError::NotFound), | 337 | Ok(None) => Err(AppError::NotFound), |
| 319 | Err(err) => Err(err), | 338 | Err(err) => Err(err), |
| 320 | }; | 339 | }; |
| @@ -337,8 +356,10 @@ async fn handle_message( | |||
| 337 | } | 356 | } |
| 338 | } | 357 | } |
| 339 | ClientMessage::Finish => { | 358 | ClientMessage::Finish => { |
| 359 | + // Submit the room's own sitting — a stale room must not submit a | ||
| 360 | + // retake it never hosted. | ||
| 340 | let finished = match Exam::read(exam_id, db).await { | 361 | let finished = match Exam::read(exam_id, db).await { |
| 341 | - Ok(Some(exam)) => match writable_attempt(&exam, user, db).await { | 362 | + Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await { |
| 342 | Ok(attempt) => attempt.finish(db).await, | 363 | Ok(attempt) => attempt.finish(db).await, |
| 343 | Err(err) => Err(err), | 364 | Err(err) => Err(err), |
| 344 | }, | 365 | }, |
src/web/exams.rsmodified+55 -20
| @@ -758,14 +758,7 @@ async fn start_attempt( | |||
| 758 | .await? | 758 | .await? |
| 759 | .ok_or(AppError::NotFound)?; | 759 | .ok_or(AppError::NotFound)?; |
| 760 | ensure_sittable(&exam)?; | 760 | ensure_sittable(&exam)?; |
| 761 | - if Enrollment::read_for_user(exam.get_course(), user.get_id(), &st.db) | 761 | + ensure_enrolled(&exam, user.get_id(), &st.db).await?; |
| 762 | - .await? | ||
| 763 | - .is_none() | ||
| 764 | - { | ||
| 765 | - return Err(AppError::Forbidden( | ||
| 766 | - "you are not enrolled in this exam's course", | ||
| 767 | - )); | ||
| 768 | - } | ||
| 769 | let now = Timestamp::now(); | 762 | let now = Timestamp::now(); |
| 770 | if let Some(starts_at) = exam.get_starts_at() | 763 | if let Some(starts_at) = exam.get_starts_at() |
| 771 | && now < starts_at | 764 | && now < starts_at |
| @@ -1539,9 +1532,10 @@ pub(crate) fn check_rejoin(exam: &Exam, attempt: &ExamAttempt) -> Result<(), App | |||
| 1539 | } | 1532 | } |
| 1540 | 1533 | ||
| 1541 | /// Save one answer inside the caller's in-progress attempt — the whole write | 1534 | /// Save one answer inside the caller's in-progress attempt — the whole write |
| 1542 | -/// path (attempt gate, rejoin gate, question lookup, kind check, upsert), | 1535 | +/// path (attempt gate, rejoin gate, question lookup, kind check, upsert). The |
| 1543 | -/// shared verbatim by the REST handler and the WebSocket room so the two can | 1536 | +/// REST handler saves into the latest sitting via this; the WebSocket room |
| 1544 | -/// never drift. | 1537 | +/// resolves its own sitting first and shares [`save_answer_in`], so the two |
| 1538 | +/// can never drift. | ||
| 1545 | pub(crate) async fn save_answer_checked( | 1539 | pub(crate) async fn save_answer_checked( |
| 1546 | exam: &Exam, | 1540 | exam: &Exam, |
| 1547 | user: &UserId, | 1541 | user: &UserId, |
| @@ -1551,16 +1545,53 @@ pub(crate) async fn save_answer_checked( | |||
| 1551 | db: &Database, | 1545 | db: &Database, |
| 1552 | ) -> Result<ExamAnswer, AppError> { | 1546 | ) -> Result<ExamAnswer, AppError> { |
| 1553 | let attempt = writable_attempt(exam, user, db).await?; | 1547 | let attempt = writable_attempt(exam, user, db).await?; |
| 1554 | - check_rejoin(exam, &attempt)?; | 1548 | + save_answer_in(exam, &attempt, question_id, selected, text, db).await |
| 1549 | +} | ||
| 1550 | + | ||
| 1551 | +/// The tail of the answer write path, given the sitting to write in: the | ||
| 1552 | +/// enrollment wall (leaving the course closes the sheet, mid-exam included), | ||
| 1553 | +/// the rejoin gate, the question lookup, and the upsert. | ||
| 1554 | +pub(crate) async fn save_answer_in( | ||
| 1555 | + exam: &Exam, | ||
| 1556 | + attempt: &ExamAttempt, | ||
| 1557 | + question_id: &str, | ||
| 1558 | + selected: Option<i64>, | ||
| 1559 | + text: Option<String>, | ||
| 1560 | + db: &Database, | ||
| 1561 | +) -> Result<ExamAnswer, AppError> { | ||
| 1562 | + ensure_enrolled(exam, attempt.get_user(), db).await?; | ||
| 1563 | + check_rejoin(exam, attempt)?; | ||
| 1555 | let question = question_of_exam(exam.get_id(), question_id, db).await?; | 1564 | let question = question_of_exam(exam.get_id(), question_id, db).await?; |
| 1556 | - ExamAnswer::save(&question, user, selected, text, db).await | 1565 | + ExamAnswer::save(&question, attempt.get_user(), selected, text, db).await |
| 1566 | +} | ||
| 1567 | + | ||
| 1568 | +/// A 403 unless `user` is enrolled in the exam's course — the same wall the | ||
| 1569 | +/// exam room checks at its door, re-applied to the sitting's content paths so | ||
| 1570 | +/// an unenrollment mid-exam cuts them too. Finishing stays exempt: like the | ||
| 1571 | +/// rejoin lock, submitting what's already saved writes nothing new. | ||
| 1572 | +pub(crate) async fn ensure_enrolled( | ||
| 1573 | + exam: &Exam, | ||
| 1574 | + user: &UserId, | ||
| 1575 | + db: &Database, | ||
| 1576 | +) -> Result<(), AppError> { | ||
| 1577 | + if Enrollment::read_for_user(exam.get_course(), user, db) | ||
| 1578 | + .await? | ||
| 1579 | + .is_none() | ||
| 1580 | + { | ||
| 1581 | + return Err(AppError::Forbidden( | ||
| 1582 | + "you are not enrolled in this exam's course", | ||
| 1583 | + )); | ||
| 1584 | + } | ||
| 1585 | + Ok(()) | ||
| 1557 | } | 1586 | } |
| 1558 | 1587 | ||
| 1559 | /// The exam's questions as the sitting student sees them: `correct` stripped, | 1588 | /// The exam's questions as the sitting student sees them: `correct` stripped, |
| 1560 | /// their own saved answers embedded — the latest sitting's, since a retake | 1589 | /// their own saved answers embedded — the latest sitting's, since a retake |
| 1561 | -/// starts from a blank sheet. Requires an attempt — start one with | 1590 | +/// starts from a blank sheet. Requires enrollment in the exam's course (the |
| 1562 | -/// `POST /exams/{id}/attempt` first (404 until then). Readable in every | 1591 | +/// questions are course content — leaving the course closes them) and an |
| 1563 | -/// attempt state, so a submitted student can still review what they wrote. | 1592 | +/// attempt — start one with `POST /exams/{id}/attempt` first (404 until |
| 1593 | +/// then). Readable in every attempt state, so a submitted student can still | ||
| 1594 | +/// review what they wrote. | ||
| 1564 | #[utoipa::path( | 1595 | #[utoipa::path( |
| 1565 | get, | 1596 | get, |
| 1566 | path = "/{id}/attempt/questions", | 1597 | path = "/{id}/attempt/questions", |
| @@ -1570,6 +1601,7 @@ pub(crate) async fn save_answer_checked( | |||
| 1570 | responses( | 1601 | responses( |
| 1571 | (status = 200, description = "Questions with the caller's answers embedded", body = [AttemptQuestionResponse]), | 1602 | (status = 200, description = "Questions with the caller's answers embedded", body = [AttemptQuestionResponse]), |
| 1572 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 1603 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1604 | + (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse), | ||
| 1573 | (status = 404, description = "No such exam, or no attempt yet — start the attempt first", body = ErrorResponse), | 1605 | (status = 404, description = "No such exam, or no attempt yet — start the attempt first", body = ErrorResponse), |
| 1574 | ), | 1606 | ), |
| 1575 | )] | 1607 | )] |
| @@ -1581,6 +1613,7 @@ async fn attempt_questions( | |||
| 1581 | let exam = Exam::read(&ExamId::from_key(&id), &st.db) | 1613 | let exam = Exam::read(&ExamId::from_key(&id), &st.db) |
| 1582 | .await? | 1614 | .await? |
| 1583 | .ok_or(AppError::NotFound)?; | 1615 | .ok_or(AppError::NotFound)?; |
| 1616 | + ensure_enrolled(&exam, user.get_id(), &st.db).await?; | ||
| 1584 | // The question list is for sitting students; without an attempt there is | 1617 | // The question list is for sitting students; without an attempt there is |
| 1585 | // nothing to sit behind — and no early peek at the questions. | 1618 | // nothing to sit behind — and no early peek at the questions. |
| 1586 | ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) | 1619 | ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) |
| @@ -1614,10 +1647,11 @@ async fn attempt_questions( | |||
| 1614 | } | 1647 | } |
| 1615 | 1648 | ||
| 1616 | /// Save (or overwrite) one answer in the caller's in-progress attempt. | 1649 | /// Save (or overwrite) one answer in the caller's in-progress attempt. |
| 1617 | -/// `choice` questions take `selected`; `text` questions take `text`. Rejected | 1650 | +/// `choice` questions take `selected`; `text` questions take `text`. Requires |
| 1618 | -/// once the attempt is submitted or its deadline has passed — the server | 1651 | +/// enrollment in the exam's course — an unenrollment mid-exam closes the |
| 1619 | -/// clock, not the client's, is the judge — and rejected while the student has | 1652 | +/// sheet. Rejected once the attempt is submitted or its deadline has passed — |
| 1620 | -/// left the exam room with the exam's rejoin door closed. | 1653 | +/// the server clock, not the client's, is the judge — and rejected while the |
| 1654 | +/// student has left the exam room with the exam's rejoin door closed. | ||
| 1621 | #[utoipa::path( | 1655 | #[utoipa::path( |
| 1622 | post, | 1656 | post, |
| 1623 | path = "/{id}/attempt/answers", | 1657 | path = "/{id}/attempt/answers", |
| @@ -1629,6 +1663,7 @@ async fn attempt_questions( | |||
| 1629 | (status = 200, description = "Answer saved", body = AnswerSavedResponse), | 1663 | (status = 200, description = "Answer saved", body = AnswerSavedResponse), |
| 1630 | (status = 400, description = "Payload doesn't match the question's kind", body = ErrorResponse), | 1664 | (status = 400, description = "Payload doesn't match the question's kind", body = ErrorResponse), |
| 1631 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 1665 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1666 | + (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse), | ||
| 1632 | (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse), | 1667 | (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse), |
| 1633 | (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), | 1668 | (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), |
| 1634 | ), | 1669 | ), |
src/web/settings.rsmodified+31 -17
| @@ -5,6 +5,7 @@ use utoipa::ToSchema; | |||
| 5 | use utoipa_axum::router::OpenApiRouter; | 5 | use utoipa_axum::router::OpenApiRouter; |
| 6 | use utoipa_axum::routes; | 6 | use utoipa_axum::routes; |
| 7 | 7 | ||
| 8 | +use crate::constant::SETTINGS_UPDATE_RETRIES; | ||
| 8 | use crate::domain::settings::{GradeBand, Settings}; | 9 | use crate::domain::settings::{GradeBand, Settings}; |
| 9 | use crate::error::{AppError, ErrorResponse}; | 10 | use crate::error::{AppError, ErrorResponse}; |
| 10 | use crate::state::AppState; | 11 | use crate::state::AppState; |
| @@ -108,6 +109,7 @@ async fn get_settings( | |||
| 108 | (status = 400, description = "Invalid lists or bands", body = ErrorResponse), | 109 | (status = 400, description = "Invalid lists or bands", body = ErrorResponse), |
| 109 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 110 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 110 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 111 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 112 | + (status = 409, description = "Concurrent edits kept changing the settings mid-save", body = ErrorResponse), | ||
| 111 | ), | 113 | ), |
| 112 | )] | 114 | )] |
| 113 | async fn update_settings( | 115 | async fn update_settings( |
| @@ -115,23 +117,35 @@ async fn update_settings( | |||
| 115 | RequireManager(_user): RequireManager, | 117 | RequireManager(_user): RequireManager, |
| 116 | Json(req): Json<UpdateSettings>, | 118 | Json(req): Json<UpdateSettings>, |
| 117 | ) -> Result<Json<SettingsResponse>, AppError> { | 119 | ) -> Result<Json<SettingsResponse>, AppError> { |
| 118 | - let current = Settings::load(&st.db).await?; | 120 | + // Merge over a snapshot, then save only while the row still matches it — |
| 121 | + // otherwise a concurrent PATCH of a *different* field would be silently | ||
| 122 | + // reverted by whichever whole-row write lands second. A refused save | ||
| 123 | + // reloads and re-merges, so both edits land. | ||
| 124 | + for _ in 0..SETTINGS_UPDATE_RETRIES { | ||
| 125 | + let current = Settings::load(&st.db).await?; | ||
| 119 | 126 | ||
| 120 | - let exam_kinds = req | 127 | + let exam_kinds = req |
| 121 | - .exam_kinds | 128 | + .exam_kinds |
| 122 | - .unwrap_or_else(|| current.get_exam_kinds().to_vec()); | 129 | + .clone() |
| 123 | - let attendance_statuses = req | 130 | + .unwrap_or_else(|| current.get_exam_kinds().to_vec()); |
| 124 | - .attendance_statuses | 131 | + let attendance_statuses = req |
| 125 | - .unwrap_or_else(|| current.get_attendance_statuses().to_vec()); | 132 | + .attendance_statuses |
| 126 | - let grade_bands = match req.grade_bands { | 133 | + .clone() |
| 127 | - Some(bands) => bands | 134 | + .unwrap_or_else(|| current.get_attendance_statuses().to_vec()); |
| 128 | - .into_iter() | 135 | + let grade_bands = match &req.grade_bands { |
| 129 | - .map(|band| GradeBand::try_new(band.min, &band.label)) | 136 | + Some(bands) => bands |
| 130 | - .collect::<Result<Vec<_>, _>>()?, | 137 | + .iter() |
| 131 | - None => current.get_grade_bands().to_vec(), | 138 | + .map(|band| GradeBand::try_new(band.min, &band.label)) |
| 132 | - }; | 139 | + .collect::<Result<Vec<_>, _>>()?, |
| 140 | + None => current.get_grade_bands().to_vec(), | ||
| 141 | + }; | ||
| 133 | 142 | ||
| 134 | - let settings = Settings::try_new(exam_kinds, attendance_statuses, grade_bands)?; | 143 | + let settings = Settings::try_new(exam_kinds, attendance_statuses, grade_bands)?; |
| 135 | - let saved = settings.save(&st.db).await?; | 144 | + if let Some(saved) = settings.save_if_unchanged(¤t, &st.db).await? { |
| 136 | - Ok(Json(SettingsResponse::new(&saved))) | 145 | + return Ok(Json(SettingsResponse::new(&saved))); |
| 146 | + } | ||
| 147 | + } | ||
| 148 | + Err(AppError::Conflict( | ||
| 149 | + "the settings kept changing underneath this update — try again", | ||
| 150 | + )) | ||
| 137 | } | 151 | } |
src/web/work.rsmodified+3 -1
| @@ -53,7 +53,9 @@ impl WorkEntryResponse { | |||
| 53 | user: entry.get_user().key().to_string(), | 53 | user: entry.get_user().key().to_string(), |
| 54 | check_in, | 54 | check_in, |
| 55 | check_out, | 55 | check_out, |
| 56 | - duration_ms: check_out.map(|out| out - check_in), | 56 | + // Saturating: manager-corrected instants are arbitrary i64s, and |
| 57 | + // an absurdly wide pair must cap the duration, not overflow it. | ||
| 58 | + duration_ms: check_out.map(|out| out.saturating_sub(check_in)), | ||
| 57 | } | 59 | } |
| 58 | } | 60 | } |
| 59 | } | 61 | } |
tests/e2e.rsmodified+112 -0
| @@ -1266,6 +1266,118 @@ async fn exam_room_close_after_a_retake_leaves_the_new_sitting_alone() { | |||
| 1266 | ); | 1266 | ); |
| 1267 | } | 1267 | } |
| 1268 | 1268 | ||
| 1269 | +/// Messages through a stale room act on that room's own sitting — never on a | ||
| 1270 | +/// retake started while the old socket lingered. An `answer` or `finish` sent | ||
| 1271 | +/// through the old room after sitting #1 ended must be refused, not silently | ||
| 1272 | +/// applied to sitting #2 (which would scribble on — or instantly submit — a | ||
| 1273 | +/// fresh attempt the student opened elsewhere, burning a limited sitting). | ||
| 1274 | +#[tokio::test] | ||
| 1275 | +async fn exam_room_messages_bind_to_their_own_sitting() { | ||
| 1276 | + let room = exam_room_fixture(600_000).await; | ||
| 1277 | + | ||
| 1278 | + // An open exam with two sittings and one choice question. | ||
| 1279 | + let exam: Value = room | ||
| 1280 | + .teacher | ||
| 1281 | + .post(format!("{}/courses/{}/exams", room.base, room.course_id)) | ||
| 1282 | + .json(&json!({ | ||
| 1283 | + "title": "practice", "kind": "quiz", "weight": 1, | ||
| 1284 | + "mode": "open", "max_attempts": 2, | ||
| 1285 | + })) | ||
| 1286 | + .send() | ||
| 1287 | + .await | ||
| 1288 | + .unwrap() | ||
| 1289 | + .json() | ||
| 1290 | + .await | ||
| 1291 | + .unwrap(); | ||
| 1292 | + let exam_id = exam["id"].as_str().unwrap().to_string(); | ||
| 1293 | + let question: Value = room | ||
| 1294 | + .teacher | ||
| 1295 | + .post(format!("{}/exams/{exam_id}/questions", room.base)) | ||
| 1296 | + .json(&json!({ "text": "3 + 3?", "kind": "choice", "points": 5, | ||
| 1297 | + "choices": ["5", "6"], "correct": 1 })) | ||
| 1298 | + .send() | ||
| 1299 | + .await | ||
| 1300 | + .unwrap() | ||
| 1301 | + .json() | ||
| 1302 | + .await | ||
| 1303 | + .unwrap(); | ||
| 1304 | + let question_id = question["id"].as_str().unwrap().to_string(); | ||
| 1305 | + | ||
| 1306 | + // Sit sitting #1 and open its room. | ||
| 1307 | + let res = room | ||
| 1308 | + .student | ||
| 1309 | + .post(format!("{}/exams/{exam_id}/attempt", room.base)) | ||
| 1310 | + .send() | ||
| 1311 | + .await | ||
| 1312 | + .unwrap(); | ||
| 1313 | + assert_eq!(res.status(), StatusCode::CREATED); | ||
| 1314 | + let mut ws = ws_open(&room.base, &exam_id, Some(&room.cookie)) | ||
| 1315 | + .await | ||
| 1316 | + .expect("room for sitting #1"); | ||
| 1317 | + let state = ws_next_frame(&mut ws).await.expect("connect state"); | ||
| 1318 | + assert_eq!(state["attempt"], 1, "{state}"); | ||
| 1319 | + | ||
| 1320 | + // Finish sitting #1 and start sitting #2 over REST — the old socket is | ||
| 1321 | + // still open while the retake begins. | ||
| 1322 | + let res = room | ||
| 1323 | + .student | ||
| 1324 | + .post(format!("{}/exams/{exam_id}/attempt/finish", room.base)) | ||
| 1325 | + .send() | ||
| 1326 | + .await | ||
| 1327 | + .unwrap(); | ||
| 1328 | + assert_eq!(res.status(), StatusCode::OK); | ||
| 1329 | + let res = room | ||
| 1330 | + .student | ||
| 1331 | + .post(format!("{}/exams/{exam_id}/attempt", room.base)) | ||
| 1332 | + .send() | ||
| 1333 | + .await | ||
| 1334 | + .unwrap(); | ||
| 1335 | + assert_eq!(res.status(), StatusCode::CREATED); | ||
| 1336 | + let body: Value = res.json().await.unwrap(); | ||
| 1337 | + assert_eq!(body["attempt"], 2); | ||
| 1338 | + | ||
| 1339 | + // An answer through the stale room must be refused — not saved into the | ||
| 1340 | + // blank sheet of sitting #2. | ||
| 1341 | + ws_send( | ||
| 1342 | + &mut ws, | ||
| 1343 | + json!({ "type": "answer", "question_id": question_id, "selected": 1 }), | ||
| 1344 | + ) | ||
| 1345 | + .await; | ||
| 1346 | + let error = ws_frame_of_type(&mut ws, "error").await; | ||
| 1347 | + assert!( | ||
| 1348 | + error["message"].as_str().unwrap().contains("sitting"), | ||
| 1349 | + "{error}" | ||
| 1350 | + ); | ||
| 1351 | + | ||
| 1352 | + // A finish through the stale room must be refused — not submit sitting #2. | ||
| 1353 | + ws_send(&mut ws, json!({ "type": "finish" })).await; | ||
| 1354 | + let error = ws_frame_of_type(&mut ws, "error").await; | ||
| 1355 | + assert!( | ||
| 1356 | + error["message"].as_str().unwrap().contains("sitting"), | ||
| 1357 | + "{error}" | ||
| 1358 | + ); | ||
| 1359 | + | ||
| 1360 | + // Sitting #2 is untouched: still running, sheet still blank. | ||
| 1361 | + let attempt: Value = room | ||
| 1362 | + .student | ||
| 1363 | + .get(format!("{}/exams/{exam_id}/attempt", room.base)) | ||
| 1364 | + .send() | ||
| 1365 | + .await | ||
| 1366 | + .unwrap() | ||
| 1367 | + .json() | ||
| 1368 | + .await | ||
| 1369 | + .unwrap(); | ||
| 1370 | + assert_eq!(attempt["attempt"], 2, "{attempt}"); | ||
| 1371 | + assert_eq!( | ||
| 1372 | + attempt["status"], "in_progress", | ||
| 1373 | + "a stale room must not submit the new sitting: {attempt}" | ||
| 1374 | + ); | ||
| 1375 | + assert_eq!( | ||
| 1376 | + attempt["answered"], 0, | ||
| 1377 | + "a stale room must not write into the new sitting's sheet: {attempt}" | ||
| 1378 | + ); | ||
| 1379 | +} | ||
| 1380 | + | ||
| 1269 | /// Two sockets on the same sitting (a second tab): closing one must not count | 1381 | /// 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 | 1382 | /// 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. | 1383 | /// socket out stamps `left_at` and (with the door closed) locks answering. |
tests/integration.rsmodified+148 -0
| @@ -5247,6 +5247,122 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { | |||
| 5247 | assert_eq!(res.body[1]["answer"]["text"], "because"); | 5247 | assert_eq!(res.body[1]["answer"]["text"], "because"); |
| 5248 | } | 5248 | } |
| 5249 | 5249 | ||
| 5250 | +#[tokio::test] | ||
| 5251 | +async fn unenrollment_cuts_the_sittings_reads_and_writes() { | ||
| 5252 | + let (app, db) = app_and_db().await; | ||
| 5253 | + let teacher = login_as(&app, &db, "cut_t", "teacher").await; | ||
| 5254 | + let student = login(&app, "cansu").await; | ||
| 5255 | + let student_id = me_id(&app, &student).await; | ||
| 5256 | + let (course, exam) = open_exam_with_student(&app, &teacher, &student_id, "chem").await; | ||
| 5257 | + let question = create_question( | ||
| 5258 | + &app, | ||
| 5259 | + &teacher, | ||
| 5260 | + &exam, | ||
| 5261 | + json!({ "text": "2 + 2?", "kind": "choice", "points": 10, | ||
| 5262 | + "choices": ["3", "4"], "correct": 1 }), | ||
| 5263 | + ) | ||
| 5264 | + .await; | ||
| 5265 | + | ||
| 5266 | + // Enrolled: start the attempt, read the questions, save an answer. | ||
| 5267 | + let res = send( | ||
| 5268 | + &app, | ||
| 5269 | + "POST", | ||
| 5270 | + &format!("/exams/{exam}/attempt"), | ||
| 5271 | + Some(&student), | ||
| 5272 | + None, | ||
| 5273 | + ) | ||
| 5274 | + .await; | ||
| 5275 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 5276 | + let res = send( | ||
| 5277 | + &app, | ||
| 5278 | + "GET", | ||
| 5279 | + &format!("/exams/{exam}/attempt/questions"), | ||
| 5280 | + Some(&student), | ||
| 5281 | + None, | ||
| 5282 | + ) | ||
| 5283 | + .await; | ||
| 5284 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 5285 | + let res = send( | ||
| 5286 | + &app, | ||
| 5287 | + "POST", | ||
| 5288 | + &format!("/exams/{exam}/attempt/answers"), | ||
| 5289 | + Some(&student), | ||
| 5290 | + Some(json!({ "question_id": question, "selected": 1 })), | ||
| 5291 | + ) | ||
| 5292 | + .await; | ||
| 5293 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 5294 | + | ||
| 5295 | + // Unenrolled mid-exam: the course wall closes over the sitting too. The | ||
| 5296 | + // question list is course content (`GET /exams/{id}` is already walled), | ||
| 5297 | + // and answering from outside the course would dodge the same wall the | ||
| 5298 | + // exam room enforces on entry. | ||
| 5299 | + let res = send( | ||
| 5300 | + &app, | ||
| 5301 | + "DELETE", | ||
| 5302 | + &format!("/courses/{course}/enrollments/{student_id}"), | ||
| 5303 | + Some(&teacher), | ||
| 5304 | + None, | ||
| 5305 | + ) | ||
| 5306 | + .await; | ||
| 5307 | + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); | ||
| 5308 | + let res = send( | ||
| 5309 | + &app, | ||
| 5310 | + "GET", | ||
| 5311 | + &format!("/exams/{exam}/attempt/questions"), | ||
| 5312 | + Some(&student), | ||
| 5313 | + None, | ||
| 5314 | + ) | ||
| 5315 | + .await; | ||
| 5316 | + assert_eq!( | ||
| 5317 | + res.status, | ||
| 5318 | + StatusCode::FORBIDDEN, | ||
| 5319 | + "question list after unenrollment: {}", | ||
| 5320 | + res.body | ||
| 5321 | + ); | ||
| 5322 | + let res = send( | ||
| 5323 | + &app, | ||
| 5324 | + "POST", | ||
| 5325 | + &format!("/exams/{exam}/attempt/answers"), | ||
| 5326 | + Some(&student), | ||
| 5327 | + Some(json!({ "question_id": question, "selected": 0 })), | ||
| 5328 | + ) | ||
| 5329 | + .await; | ||
| 5330 | + assert_eq!( | ||
| 5331 | + res.status, | ||
| 5332 | + StatusCode::FORBIDDEN, | ||
| 5333 | + "answer save after unenrollment: {}", | ||
| 5334 | + res.body | ||
| 5335 | + ); | ||
| 5336 | + | ||
| 5337 | + // Their own status and submission stay theirs: like the rejoin lock, | ||
| 5338 | + // finishing submits what's already saved and writes nothing new. | ||
| 5339 | + let res = send( | ||
| 5340 | + &app, | ||
| 5341 | + "GET", | ||
| 5342 | + &format!("/exams/{exam}/attempt"), | ||
| 5343 | + Some(&student), | ||
| 5344 | + None, | ||
| 5345 | + ) | ||
| 5346 | + .await; | ||
| 5347 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 5348 | + let res = send( | ||
| 5349 | + &app, | ||
| 5350 | + "POST", | ||
| 5351 | + &format!("/exams/{exam}/attempt/finish"), | ||
| 5352 | + Some(&student), | ||
| 5353 | + None, | ||
| 5354 | + ) | ||
| 5355 | + .await; | ||
| 5356 | + assert_eq!( | ||
| 5357 | + res.status, | ||
| 5358 | + StatusCode::OK, | ||
| 5359 | + "finish stays open: {}", | ||
| 5360 | + res.body | ||
| 5361 | + ); | ||
| 5362 | + assert_eq!(res.body["status"], "submitted"); | ||
| 5363 | + assert_eq!(res.body["answered"], 1, "the enrolled-time answer survives"); | ||
| 5364 | +} | ||
| 5365 | + | ||
| 5250 | #[tokio::test] | 5366 | #[tokio::test] |
| 5251 | async fn answer_saves_stop_at_the_deadline() { | 5367 | async fn answer_saves_stop_at_the_deadline() { |
| 5252 | let (app, db) = app_and_db().await; | 5368 | let (app, db) = app_and_db().await; |
| @@ -6591,6 +6707,38 @@ async fn work_log_manager_reads_and_corrections() { | |||
| 6591 | assert_eq!(res.status, StatusCode::CREATED); | 6707 | assert_eq!(res.status, StatusCode::CREATED); |
| 6592 | } | 6708 | } |
| 6593 | 6709 | ||
| 6710 | +#[tokio::test] | ||
| 6711 | +async fn work_duration_survives_absurd_corrected_instants() { | ||
| 6712 | + let (app, db) = app_and_db().await; | ||
| 6713 | + let hoca = login_as(&app, &db, "wid_t", "teacher").await; | ||
| 6714 | + let boss = login_as(&app, &db, "wid_m", "manager").await; | ||
| 6715 | + send(&app, "POST", "/work/check-in", Some(&hoca), None).await; | ||
| 6716 | + let closed = send(&app, "POST", "/work/check-out", Some(&hoca), None).await; | ||
| 6717 | + let closed_id = id_of(&closed.body); | ||
| 6718 | + | ||
| 6719 | + // Corrected instants are arbitrary i64 millis; the widest legal pair must | ||
| 6720 | + // not overflow the `check_out - check_in` duration (a wrapped negative in | ||
| 6721 | + // release, a panicking 500 in debug) — it saturates instead. | ||
| 6722 | + let res = send( | ||
| 6723 | + &app, | ||
| 6724 | + "PATCH", | ||
| 6725 | + &format!("/work/entries/{closed_id}"), | ||
| 6726 | + Some(&boss), | ||
| 6727 | + Some(json!({ "check_in": i64::MIN, "check_out": i64::MAX })), | ||
| 6728 | + ) | ||
| 6729 | + .await; | ||
| 6730 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 6731 | + assert_eq!( | ||
| 6732 | + res.body["duration_ms"].as_i64(), | ||
| 6733 | + Some(i64::MAX), | ||
| 6734 | + "the over-wide stint saturates: {}", | ||
| 6735 | + res.body | ||
| 6736 | + ); | ||
| 6737 | + // The stored row must stay readable, not a permanent 500. | ||
| 6738 | + let res = send(&app, "GET", "/work/me", Some(&hoca), None).await; | ||
| 6739 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 6740 | +} | ||
| 6741 | + | ||
| 6594 | // --- attendance reports ------------------------------------------------------- | 6742 | // --- attendance reports ------------------------------------------------------- |
| 6595 | 6743 | ||
| 6596 | #[tokio::test] | 6744 | #[tokio::test] |