diff --git a/src/db/exam_attempt.rs b/src/db/exam_attempt.rs new file mode 100644 index 0000000..54245dc --- /dev/null +++ b/src/db/exam_attempt.rs @@ -0,0 +1,488 @@ +//! The `exam_attempt` table: sitting reads, the two field-scoped writes +//! (`finished_at`, `left_at`), and the `write_unfrozen` transaction gateway +//! that ties exam-child writes to their exam row. + +use surrealdb::types::{RecordId, SurrealValue}; + +use crate::constant::EXAM_RESULT_COUNT_FIELD; +use crate::database::{Database, transaction_with_retry}; +use crate::domain::exam::ExamId; +use crate::domain::exam_attempt::{ExamAttempt, ExamAttemptId}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// The `THROW` marker the freeze gate aborts with, and the one 409 both it and +/// the handler's pre-flight check answer with — a client cannot tell which of +/// the two refused. +const FROZEN_MARK: &str = "questions_frozen"; + +/// The `THROW` marker the exam-existence touch aborts with — the exam row this +/// write hangs off is gone, so the write is a 404 and nothing lands. +const GONE_MARK: &str = "no_exam"; + +/// The 409 the freeze gate's marker means. +fn frozen_error() -> AppError { + AppError::Conflict("cannot change questions after attempts have started") +} + +/// Stamp the submission time. The caller has already checked the deadline +/// and that the attempt isn't finished. +/// +/// Writes *only* `finished_at`, for the mirror image of +/// [`set_left`]'s reason: the submit path reads the attempt, +/// then awaits its deadline and already-finished checks before writing, and +/// the exam room stamps or clears `left_at` on the same row from a socket. +/// A whole-row write from the pre-read snapshot would carry its stale +/// `left_at` back over that stamp, erasing the recorded walk-out. +pub async fn finish(db: &Database, attempt: ExamAttempt) -> Result { + let mut result = db + .query("UPDATE $id SET finished_at = $at RETURN AFTER") + .bind(("id", attempt.id.record())) + .bind(("at", Some(Timestamp::now()))) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::NotFound) +} + +/// Stamp (or clear) the walked-out marker. The exam room sets it when the +/// student's socket closes mid-attempt and clears it when they come back. +/// +/// Writes *only* the `left_at` field (never the whole row): the room's +/// teardown reads the attempt, sees it in progress, then stamps here — and +/// a submission that lands in that gap must survive. A whole-row write from +/// the pre-read snapshot would carry its blank `finished_at` back over the +/// fresh submission, silently un-submitting the exam (and, with +/// `allow_rejoin` off, locking the student out). +pub async fn set_left( + db: &Database, + attempt: ExamAttempt, + left_at: Option, +) -> Result { + let mut result = db + .query("UPDATE $id SET left_at = $left RETURN AFTER") + .bind(("id", attempt.id.record())) + .bind(("left", left_at)) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::NotFound) +} + +/// One sitting by id — the exam room re-reads its own attempt this way, +/// so a retake started elsewhere can never be mistaken for it. +pub async fn read(db: &Database, id: &ExamAttemptId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// The student's current sitting — the highest `seq` for the pair. All +/// reads that used to mean "the attempt" mean this now. +pub async fn read_latest_for_user( + db: &Database, + exam: &ExamId, + user: &UserId, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM exam_attempt WHERE exam = $ex AND user = $usr + ORDER BY seq DESC LIMIT 1", + ) + .bind(("ex", exam.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) +} + +/// Every sitting of `user` at `exam`, newest first. +pub async fn list_for_user( + db: &Database, + exam: &ExamId, + user: &UserId, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM exam_attempt WHERE exam = $ex AND user = $usr + ORDER BY seq DESC", + ) + .bind(("ex", exam.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Every sitting of `user` nobody has submitted yet, across all exams. Only +/// the *candidates* for "in progress": a deadline comes off the exam's live +/// schedule, so the caller still judges [`ExamAttempt::status`] per exam rather +/// than re-spelling that rule in SurrealQL. +pub async fn list_unfinished_for_user( + db: &Database, + user: &UserId, +) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM exam_attempt WHERE user = $usr AND finished_at = NONE") + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM exam_attempt WHERE exam = $ex ORDER BY id DESC") + .bind(("ex", exam.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Whether anyone has started this exam — the gate that freezes `mode` +/// edits once an attempt exists. +pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result { + let mut result = db + .query("SELECT VALUE id FROM exam_attempt WHERE exam = $ex LIMIT 1") + .bind(("ex", exam.record())) + .await? + .check()?; + Ok(!result.take::>(0)?.is_empty()) +} + +/// Send `statements` wrapped in a transaction that refuses to run them at +/// all once `exam` has an attempt — the freeze gate, made atomic with the +/// write it guards instead of merely preceding it. `freeze_exam` is bound +/// here; the caller binds the rest and reads its own results from +/// [`FROZEN_SLOT`] onwards. +/// +/// The same transaction *writes* the exam row — bumping its mark counter +/// and putting it straight back — which is what ties every child written +/// through here to its exam. The freeze gate only *reads* `exam_attempt`, +/// and a read does not survive [`Exam::delete`](crate::domain::exam::Exam::delete)'s +/// window: a question or picture landing after that delete removed the exam +/// but before it committed reads a row that is still there, while the +/// cascade's `DELETE exam_question WHERE exam = $ex` ran on a snapshot +/// predating this insert — so both commit and the child outlives the exam, +/// with neither caller told anything. Writing a key the delete also writes +/// makes the two collide and the store refuses one side. It is the shape +/// [`crate::domain::exam_answer::ExamAnswer::save`] and +/// [`crate::domain::menu::bump_menu_and_write`] already use. +/// +/// An orphan here is not merely untidy: an `exam_question` that outlives +/// its exam keeps the reference it claimed on its subject (the cascade's +/// per-subject decrement counted the rows it could see), and +/// [`crate::domain::subject::Subject::delete`] is gated on that count +/// reading zero — a subject nobody can ever delete again. +/// +/// The bump is restored *by captured value*, `NONE` included, so the row is +/// byte-identical afterwards: the boot backfill still finds the rows it +/// keys on (`WHERE result_count = NONE`) and a teacher's PATCH, which pins +/// that counter, is not refused because somebody added a question. Writing +/// the same value back would not do — an `UPDATE` that leaves the document +/// unchanged is elided and never reaches the store's write set, so it +/// collides with nothing. +/// +/// This replaces a process-wide `EXAM_LOCK.write()` held across the check +/// and the write. That lock ordered the two requests but still read the +/// attempt table a round trip before it wrote; the gate checks inside the +/// writing statement, so a question edit can no longer sail past an attempt +/// that started in that gap. +/// +/// The send lives here rather than at the five call sites because a lost +/// round has to be re-sent, and only whoever owns the send can re-send: the +/// gate reads the very table its rival writes, so the two contend by design +/// and a raced edit used to answer 500. The refusal outranks the conflict — +/// `FROZEN_MARK` is a decision and stays the 409 the pre-flight check +/// answers with, and only exhausting the tries becomes a 500. See +/// [`transaction_with_retry`] for why the whole error map is scanned: an +/// aborted transaction errors *every* slot and all but one say a generic +/// "not executed". +/// +/// Returning only on an empty error map is what keeps [`FROZEN_SLOT`] +/// (and any slot counted off `num_statements`) correct — `take_errors` +/// `swap_remove`s errored slots, so a fixed slot read is meaningless once +/// anything failed. +// +// corner-cut: the count and a concurrent `CREATE exam_attempt` are still not +// serialized against each other — SurrealDB does not conflict-check a +// cross-record count (the write skew `db::cap` exists for), so an +// attempt landing in the same instant as an edit can still interleave +// either way. The mutex this replaces closed that inside one process only, +// and there are two, so nothing is lost. Closing it properly means the +// cap.rs shape: an attempt counter on the exam row, incremented by the +// attempt create, and the write conditioned on `count ?? 0 = 0`. +pub async fn write_unfrozen( + db: &Database, + exam: &ExamId, + statements: &str, + bindings: Vec<(String, surrealdb::types::Value)>, +) -> Result { + write_unfrozen_with(db, exam, statements, bindings, Vec::new()).await +} + +/// [`write_unfrozen`] for statements that carry gates of their own: +/// each `(marker, refusal)` names a `THROW` the caller's SQL aborts with and +/// the error it means. The markers are handed to [`transaction_with_retry`] +/// too, so an abort on one is a refusal rather than a round to re-send. +/// +/// The freeze still outranks every one of them: a caller folding a counter +/// claim in here is refused as frozen even when its own gate would also have +/// fired, which is the answer the pre-flight check has always given. +pub async fn write_unfrozen_with( + db: &Database, + exam: &ExamId, + statements: &str, + bindings: Vec<(String, surrealdb::types::Value)>, + refusals: Vec<(&str, AppError)>, +) -> Result { + let sql = format!( + "BEGIN TRANSACTION; + IF array::len((SELECT VALUE id FROM exam_attempt \ + WHERE exam = $freeze_exam LIMIT 1)) > 0 {{ THROW '{FROZEN_MARK}' }}; + LET $was_results = \ + (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $freeze_exam); + LET $touched = (UPDATE $freeze_exam SET {EXAM_RESULT_COUNT_FIELD} = \ + ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); + IF array::len($touched) = 0 {{ THROW '{GONE_MARK}' }}; + UPDATE $freeze_exam SET {EXAM_RESULT_COUNT_FIELD} = $was_results; + {statements} + COMMIT TRANSACTION;" + ); + let mut bound = vec![("freeze_exam".into(), exam.record().into_value())]; + bound.extend(bindings); + let mut marks = vec![FROZEN_MARK, GONE_MARK]; + marks.extend(refusals.iter().map(|(marker, _)| *marker)); + let (result, mut errors) = transaction_with_retry(db, &sql, &bound, &marks).await?; + let thrown = |marker: &str| { + errors + .values() + .any(|error| error.to_string().contains(marker)) + }; + if thrown(FROZEN_MARK) { + return Err(frozen_error()); + } + // The exam is gone: the same 404 every one of these writes' handlers + // answers a missing exam with, and it outranks the callers' own gates + // for the freeze's reason — there is nothing left to refuse *about*. + if thrown(GONE_MARK) { + return Err(AppError::NotFound); + } + for (marker, refusal) in refusals { + if thrown(marker) { + return Err(refusal); + } + } + match errors.drain().map(|(_, error)| error).next() { + Some(error) => Err(error.into()), + None => Ok(result), + } +} + +/// The first slot a [`write_unfrozen`] caller's own statements land +/// in: `BEGIN`, the freeze `IF`, and the exam touch's two `LET`s, `IF` and +/// restoring `UPDATE` take one each. +pub const FROZEN_SLOT: usize = 6; + +#[cfg(test)] +mod tests { + use super::*; + use crate::database::init_mem; + use crate::domain::exam::{ + Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, + }; + use crate::domain::exam_question::{ + ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, + }; + use crate::domain::settings::Settings; + + /// An open exam with retakes allowed, plus one choice question — enough + /// rows to exercise the attempt lifecycle without the HTTP layer. + async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) { + let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + let course = crate::domain::course::a_test_course(db).await; + let kinds = Settings::defaults().get_exam_kinds().to_vec(); + let exam = Exam::create( + &creator, + &course, + ExamTitle::try_new("practice").unwrap(), + ExamDescription::try_new("").unwrap(), + ExamKind::try_new("quiz", &kinds).unwrap(), + ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None) + .unwrap(), + ExamAttemptLimit::try_new(max_attempts).unwrap(), + true, + false, + false, + db, + ) + .await + .unwrap(); + let spec = QuestionSpec::try_new( + QuestionKind::try_new("choice").unwrap(), + Some(vec![ + ChoiceInput { + id: Some("a".into()), + text: "5".into(), + }, + ChoiceInput { + id: Some("b".into()), + text: "6".into(), + }, + ]), + Some("b".into()), + &[], + ) + .unwrap(); + // A real subject row, not a minted id: a question claims a reference on + // its subject and is refused if that subject does not exist. + let subject = crate::domain::subject::Subject::create( + &crate::domain::course::a_test_course(db).await, + crate::domain::subject::SubjectName::try_new("topic").unwrap(), + crate::domain::subject::SubjectDescription::try_new("").unwrap(), + db, + ) + .await + .unwrap(); + let question = ExamQuestion::create( + exam.get_id(), + subject.get_id().clone(), + crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(), + QuestionPoints::try_new(5).unwrap(), + spec, + db, + ) + .await + .unwrap(); + (exam, question) + } + + /// A real user row: the sitting counter lives on it, and the claim that + /// rides the attempt's create has nothing to write to without one. + async fn student(db: &Database) -> UserId { + let hash = crate::domain::user::Password::try_new("secret1") + .unwrap() + .hash_async() + .await + .unwrap(); + crate::domain::user::User::create( + crate::domain::user::Username::try_new("ogrenci").unwrap(), + hash, + db, + ) + .await + .unwrap() + .get_id() + .clone() + } + + #[tokio::test] + async fn submitting_never_reverts_a_walk_out_that_raced_it() { + let db = init_mem().await.unwrap(); + let (exam, _question) = open_exam_with_question(&db, 1).await; + let user = student(&db).await; + + let (attempt, _) = crate::service::exam_attempt::start(&db, &exam, &user) + .await + .unwrap(); + + // The REST submit path reads the attempt, then checks the deadline and + // the already-finished guard — several awaits before it writes. + let stale = read(&db, attempt.get_id()) + .await + .unwrap() + .expect("attempt exists"); + assert!(stale.get_left_at().is_none()); + + // In that gap the exam room's teardown stamps the walk-out (or a join + // clears it) — a field-scoped write to the same row. + set_left( + &db, + read(&db, attempt.get_id()) + .await + .unwrap() + .expect("attempt exists"), + Some(Timestamp::now()), + ) + .await + .unwrap(); + + // The submit now writes from its stale snapshot. It owns `finished_at` + // and nothing else: carrying the snapshot's blank `left_at` back over + // the fresh stamp erases the recorded walk-out. + let finished = finish(&db, stale).await.unwrap(); + assert!(finished.get_finished_at().is_some()); + + let after = read(&db, attempt.get_id()) + .await + .unwrap() + .expect("attempt still exists"); + assert!( + after.get_left_at().is_some(), + "submitting must not revert a walk-out stamp that raced it" + ); + assert!(after.get_finished_at().is_some(), "the submission stands"); + } + + #[tokio::test] + async fn stamping_left_never_reverts_a_submission() { + let db = init_mem().await.unwrap(); + let (exam, _question) = open_exam_with_question(&db, 1).await; + let user = student(&db).await; + + // The student is sitting the exam. + let (attempt, _) = crate::service::exam_attempt::start(&db, &exam, &user) + .await + .unwrap(); + assert_eq!(attempt.get_seq(), 1); + + // The exam-room teardown reads the attempt while it is still in + // progress (`stamp_left`'s read) — a snapshot with `finished_at` unset. + let stale = read(&db, attempt.get_id()) + .await + .unwrap() + .expect("attempt exists"); + assert!(stale.get_finished_at().is_none()); + let finished = finish( + &db, + read(&db, attempt.get_id()) + .await + .unwrap() + .expect("attempt exists"), + ) + .await + .unwrap(); + assert!(finished.get_finished_at().is_some()); + + // Now the last socket's teardown stamps `left_at` from its stale + // snapshot. Stamping the walk-out must touch only `left_at` — it must + // not carry the snapshot's blank `finished_at` back over the fresh + // submission, or the student's submitted exam silently reopens (and, + // with `allow_rejoin` off, locks them out of a room they left after + // finishing). + set_left(&db, stale, Some(Timestamp::now())).await.unwrap(); + + let after = read(&db, attempt.get_id()) + .await + .unwrap() + .expect("attempt still exists"); + assert!( + after.get_finished_at().is_some(), + "stamping left_at must not revert a submission that raced it" + ); + assert!( + after.get_left_at().is_some(), + "the walk-out is still recorded" + ); + assert_eq!( + after.status(&exam, Timestamp::now()), + crate::domain::exam_attempt::AttemptStatus::Submitted, + "the attempt stays submitted" + ); + } +} diff --git a/src/db/mod.rs b/src/db/mod.rs index 44326cb..1ad9342 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -3,6 +3,7 @@ pub mod appointment; pub mod cap; pub mod course; +pub mod exam_attempt; pub mod field_update; pub mod note; pub mod page; diff --git a/src/domain/exam.rs b/src/domain/exam.rs index c58c003..b7bca75 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -599,7 +599,7 @@ impl Exam { ) .await?; // An aborted transaction errors every slot; only the THROW's names the - // marker (the [`ExamAttempt::write_unfrozen`] treatment). + // marker (the [`crate::db::exam_attempt::write_unfrozen`] treatment). if errors .values() .any(|error| error.to_string().contains("exam_redraft")) @@ -682,7 +682,7 @@ impl Exam { /// An unscheduled published exam — the minimum any test that writes a *child* /// of an exam needs, in any module: every such write moves the exam row (see -/// [`ExamAttempt::write_unfrozen_with`](crate::domain::exam_attempt::ExamAttempt) +/// [`crate::db::exam_attempt::write_unfrozen_with`] /// and [`crate::domain::exam_answer::ExamAnswer::save`]), so a minted id whose /// row was never created is a 404 rather than a silent orphan. #[cfg(test)] @@ -1239,7 +1239,7 @@ mod tests { /// gated on that count reading zero — a subject nobody could ever delete /// again, hanging off an exam nobody could ever see. The freeze gate is a /// *read* of `exam_attempt` and never survived this window; - /// [`ExamAttempt::write_unfrozen_with`] now writes the exam row too. + /// [`crate::db::exam_attempt::write_unfrozen_with`] now writes the exam row too. /// /// Same seam, same `#[ignore]`, same reason as the answer twin above: the /// subject *is* the store's conflict detection, which the in-memory engine diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs index ce12c3d..6f8b5da 100644 --- a/src/domain/exam_attempt.rs +++ b/src/domain/exam_attempt.rs @@ -1,36 +1,20 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{EXAM_ATTEMPT_TABLE, EXAM_RESULT_COUNT_FIELD, EXAM_SAT_TOTAL_FIELD}; -use crate::database::{Database, transaction_with_retry}; +use crate::constant::EXAM_ATTEMPT_TABLE; use crate::domain::exam::Exam; use crate::domain::exam::ExamId; +use crate::domain::key; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::db::cap; -use crate::domain::{badge, key}; -use crate::error::AppError; - -/// The `THROW` marker the freeze gate aborts with, and the one 409 both it and -/// the handler's pre-flight check answer with — a client cannot tell which of -/// the two refused. -const FROZEN_MARK: &str = "questions_frozen"; - -/// The `THROW` marker the exam-existence touch aborts with — the exam row this -/// write hangs off is gone, so the write is a 404 and nothing lands. -const GONE_MARK: &str = "no_exam"; - -pub(crate) fn frozen_error() -> AppError { - AppError::Conflict("cannot change questions after attempts have started") -} +/// A deterministic id for the (exam, user, seq) triple, so sitting `seq` +/// exists at most once by construction — a concurrent double "start" races +/// on the same id and exactly one create wins. See [`key::sitting`] for the +/// key shape and why the first sitting stays bare. #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ExamAttemptId(RecordId); impl ExamAttemptId { - /// A deterministic id for the (exam, user, seq) triple, so sitting `seq` - /// exists at most once by construction — a concurrent double "start" races - /// on the same id and exactly one create wins. See [`key::sitting`] for the - /// key shape and why the first sitting stays bare. pub fn composite(exam: &ExamId, user: &UserId, seq: i64) -> Self { let key = key::sitting(exam.key(), user.key(), seq); Self(RecordId::new(EXAM_ATTEMPT_TABLE, key)) @@ -75,15 +59,19 @@ impl AttemptStatus { /// `finished_at` the submission. `seq` numbers the sittings (1, 2, …) when the /// exam allows retakes; `left_at` marks a student who walked out of the exam /// room mid-attempt. Grading stays a separate `exam_result` row. +/// +/// Fields are crate-visible: [`crate::db::exam_attempt`] reads the id to +/// target its field-scoped writes and [`crate::service::exam_attempt::start`] +/// mints the rows on create. #[derive(Debug, Clone, SurrealValue)] pub struct ExamAttempt { - id: ExamAttemptId, - exam: ExamId, - user: UserId, - seq: i64, - started_at: Timestamp, - finished_at: Option, - left_at: Option, + pub(crate) id: ExamAttemptId, + pub(crate) exam: ExamId, + pub(crate) user: UserId, + pub(crate) seq: i64, + pub(crate) started_at: Timestamp, + pub(crate) finished_at: Option, + pub(crate) left_at: Option, } impl ExamAttempt { @@ -151,754 +139,4 @@ impl ExamAttempt { _ => AttemptStatus::InProgress, } } - - /// Start (or resume) `user`'s attempt at `exam`. Returns the attempt plus - /// whether it was newly created. - /// - /// - A still-running latest attempt is returned untouched, so a - /// reconnecting client gets its original clock back instead of a reset — - /// re-"starting" can never buy more time. - /// - A terminal latest attempt (submitted or expired) starts sitting - /// `seq + 1` if the exam's `max_attempts` allows another, and is a - /// conflict otherwise. A retake preserves every prior sitting: the new - /// row is created at the new `seq` and the student's earlier answers, - /// drawings, and marks stay put at their own seq — the fresh sitting - /// simply writes into an empty higher seq. - /// - /// The composite id makes each create atomic; a concurrent double-start - /// races on the same seq, loses to the unique id, and reads the winner's - /// row. - /// - /// A created row rides [`cap::create_counting`] so the student's - /// `exam_sat_total` moves in the same transaction — but only for `seq == 1`, - /// because that counter is *exams sat*, not sittings. A retake is the same - /// exam again, and counting it made a badge a student could mint alone: an - /// open exam with unlimited attempts is a start/finish loop nobody else has - /// to touch. `seq == 1` is the whole condition and needs no extra read — - /// the first sitting's id is one deterministic key, so of every writer - /// aiming at it exactly one `CREATE` commits and the losers' increments - /// abort with their duplicates, while a retake computes its seq from a row - /// that already exists. A `SELECT` inside the transaction would be strictly - /// worse: SurrealDB 3.2.3 conflict-checks write sets, not read sets. - pub async fn start( - exam: &Exam, - user: &UserId, - db: &Database, - ) -> Result<(ExamAttempt, bool), AppError> { - let attempts = Self::list_for_user(exam.get_id(), user, db).await?; - let next_seq = match attempts.first() { - None => 1, - Some(latest) if latest.status(exam, Timestamp::now()) == AttemptStatus::InProgress => { - return Ok((latest.clone(), false)); - } - Some(latest) => { - if !exam.get_max_attempts().allows_another(attempts.len()) { - return Err(AppError::Conflict( - "no attempts remaining — this exam's attempt limit is used up", - )); - } - latest.seq + 1 - } - }; - let attempt = ExamAttempt { - id: ExamAttemptId::composite(exam.get_id(), user, next_seq), - exam: exam.get_id().clone(), - user: user.clone(), - seq: next_seq, - started_at: Timestamp::now(), - finished_at: None, - left_at: None, - }; - let id = attempt.id.record(); - let first = next_seq == 1; - match cap::create_counting( - &user.record(), - EXAM_SAT_TOTAL_FIELD, - first, - &id, - &attempt, - db, - ) - .await? - { - cap::Claimed::Made(created) => { - // Only a moved counter can have crossed a threshold. - if first && let Err(err) = badge::sync(user, db).await { - tracing::warn!("failed to sync badges for {}: {err}", user.key()); - } - Ok((created, true)) - } - // Only a still-running row proves the loss was a double-start - // collision (the winner's fresh sitting); a terminal or missing - // latest means the create genuinely failed — surface that instead - // of passing a finished sitting off as a resume. The duplicate - // aborted the transaction, so the loser's increment went with it. - cap::Claimed::Duplicate => { - match Self::read_latest_for_user(exam.get_id(), user, db).await? { - Some(existing) - if existing.status(exam, Timestamp::now()) == AttemptStatus::InProgress => - { - Ok((existing, false)) - } - _ => Err(AppError::Internal("failed to start exam attempt".into())), - } - } - // Nothing caps sittings, so the conditional write can only miss by - // finding no user row — not a state a live session can reach, and - // passing it off as a resume would hand out a sitting the counter - // never learned about. - cap::Claimed::Full => Err(AppError::Internal( - "cannot start an exam attempt: the student's account row is missing".into(), - )), - } - } - - /// Stamp the submission time. The caller has already checked the deadline - /// and that the attempt isn't finished. - /// - /// Writes *only* `finished_at`, for the mirror image of - /// [`ExamAttempt::set_left`]'s reason: the submit path reads the attempt, - /// then awaits its deadline and already-finished checks before writing, and - /// the exam room stamps or clears `left_at` on the same row from a socket. - /// A whole-row write from the pre-read snapshot would carry its stale - /// `left_at` back over that stamp, erasing the recorded walk-out. - pub async fn finish(self, db: &Database) -> Result { - let mut result = db - .query("UPDATE $id SET finished_at = $at RETURN AFTER") - .bind(("id", self.id.record())) - .bind(("at", Some(Timestamp::now()))) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) - } - - /// Stamp (or clear) the walked-out marker. The exam room sets it when the - /// student's socket closes mid-attempt and clears it when they come back. - /// - /// Writes *only* the `left_at` field (never the whole row): the room's - /// teardown reads the attempt, sees it in progress, then stamps here — and - /// a submission that lands in that gap must survive. A whole-row write from - /// the pre-read snapshot would carry its blank `finished_at` back over the - /// fresh submission, silently un-submitting the exam (and, with - /// `allow_rejoin` off, locking the student out). - pub async fn set_left( - self, - left_at: Option, - db: &Database, - ) -> Result { - let mut result = db - .query("UPDATE $id SET left_at = $left RETURN AFTER") - .bind(("id", self.id.record())) - .bind(("left", left_at)) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) - } - - /// One sitting by id — the exam room re-reads its own attempt this way, - /// so a retake started elsewhere can never be mistaken for it. - pub async fn read(id: &ExamAttemptId, db: &Database) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// The student's current sitting — the highest `seq` for the pair. All - /// reads that used to mean "the attempt" mean this now. - pub async fn read_latest_for_user( - exam: &ExamId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM exam_attempt WHERE exam = $ex AND user = $usr - ORDER BY seq DESC LIMIT 1", - ) - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) - } - - /// Every sitting of `user` at `exam`, newest first. - pub async fn list_for_user( - exam: &ExamId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM exam_attempt WHERE exam = $ex AND user = $usr - ORDER BY seq DESC", - ) - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Every sitting of `user` nobody has submitted yet, across all exams. Only - /// the *candidates* for "in progress": a deadline comes off the exam's live - /// schedule, so the caller still judges [`Self::status`] per exam rather - /// than re-spelling that rule in SurrealQL. - pub async fn list_unfinished_for_user( - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM exam_attempt WHERE user = $usr AND finished_at = NONE") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM exam_attempt WHERE exam = $ex ORDER BY id DESC") - .bind(("ex", exam.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Send `statements` wrapped in a transaction that refuses to run them at - /// all once `exam` has an attempt — the freeze gate, made atomic with the - /// write it guards instead of merely preceding it. `freeze_exam` is bound - /// here; the caller binds the rest and reads its own results from - /// [`Self::FROZEN_SLOT`] onwards. - /// - /// The same transaction *writes* the exam row — bumping its mark counter - /// and putting it straight back — which is what ties every child written - /// through here to its exam. The freeze gate only *reads* `exam_attempt`, - /// and a read does not survive [`Exam::delete`](crate::domain::exam::Exam::delete)'s - /// window: a question or picture landing after that delete removed the exam - /// but before it committed reads a row that is still there, while the - /// cascade's `DELETE exam_question WHERE exam = $ex` ran on a snapshot - /// predating this insert — so both commit and the child outlives the exam, - /// with neither caller told anything. Writing a key the delete also writes - /// makes the two collide and the store refuses one side. It is the shape - /// [`crate::domain::exam_answer::ExamAnswer::save`] and - /// [`crate::domain::menu::bump_menu_and_write`] already use. - /// - /// An orphan here is not merely untidy: an `exam_question` that outlives - /// its exam keeps the reference it claimed on its subject (the cascade's - /// per-subject decrement counted the rows it could see), and - /// [`crate::domain::subject::Subject::delete`] is gated on that count - /// reading zero — a subject nobody can ever delete again. - /// - /// The bump is restored *by captured value*, `NONE` included, so the row is - /// byte-identical afterwards: the boot backfill still finds the rows it - /// keys on (`WHERE result_count = NONE`) and a teacher's PATCH, which pins - /// that counter, is not refused because somebody added a question. Writing - /// the same value back would not do — an `UPDATE` that leaves the document - /// unchanged is elided and never reaches the store's write set, so it - /// collides with nothing. - /// - /// This replaces a process-wide `EXAM_LOCK.write()` held across the check - /// and the write. That lock ordered the two requests but still read the - /// attempt table a round trip before it wrote; the gate checks inside the - /// writing statement, so a question edit can no longer sail past an attempt - /// that started in that gap. - /// - /// The send lives here rather than at the five call sites because a lost - /// round has to be re-sent, and only whoever owns the send can re-send: the - /// gate reads the very table its rival writes, so the two contend by design - /// and a raced edit used to answer 500. The refusal outranks the conflict — - /// `FROZEN_MARK` is a decision and stays the 409 the pre-flight check - /// answers with, and only exhausting the tries becomes a 500. See - /// [`transaction_with_retry`] for why the whole error map is scanned: an - /// aborted transaction errors *every* slot and all but one say a generic - /// "not executed". - /// - /// Returning only on an empty error map is what keeps [`Self::FROZEN_SLOT`] - /// (and any slot counted off `num_statements`) correct — `take_errors` - /// `swap_remove`s errored slots, so a fixed slot read is meaningless once - /// anything failed. - // - // corner-cut: the count and a concurrent `CREATE exam_attempt` are still not - // serialized against each other — SurrealDB does not conflict-check a - // cross-record count (the write skew `db::cap` exists for), so an - // attempt landing in the same instant as an edit can still interleave - // either way. The mutex this replaces closed that inside one process only, - // and there are two, so nothing is lost. Closing it properly means the - // cap.rs shape: an attempt counter on the exam row, incremented by the - // attempt create, and the write conditioned on `count ?? 0 = 0`. - pub(crate) async fn write_unfrozen( - exam: &ExamId, - statements: &str, - bindings: Vec<(String, surrealdb::types::Value)>, - db: &Database, - ) -> Result { - Self::write_unfrozen_with(exam, statements, bindings, Vec::new(), db).await - } - - /// [`Self::write_unfrozen`] for statements that carry gates of their own: - /// each `(marker, refusal)` names a `THROW` the caller's SQL aborts with and - /// the error it means. The markers are handed to [`transaction_with_retry`] - /// too, so an abort on one is a refusal rather than a round to re-send. - /// - /// The freeze still outranks every one of them: a caller folding a counter - /// claim in here is refused as frozen even when its own gate would also have - /// fired, which is the answer the pre-flight check has always given. - pub(crate) async fn write_unfrozen_with( - exam: &ExamId, - statements: &str, - bindings: Vec<(String, surrealdb::types::Value)>, - refusals: Vec<(&str, AppError)>, - db: &Database, - ) -> Result { - let sql = format!( - "BEGIN TRANSACTION; - IF array::len((SELECT VALUE id FROM exam_attempt \ - WHERE exam = $freeze_exam LIMIT 1)) > 0 {{ THROW '{FROZEN_MARK}' }}; - LET $was_results = \ - (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $freeze_exam); - LET $touched = (UPDATE $freeze_exam SET {EXAM_RESULT_COUNT_FIELD} = \ - ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); - IF array::len($touched) = 0 {{ THROW '{GONE_MARK}' }}; - UPDATE $freeze_exam SET {EXAM_RESULT_COUNT_FIELD} = $was_results; - {statements} - COMMIT TRANSACTION;" - ); - let mut bound = vec![("freeze_exam".into(), exam.record().into_value())]; - bound.extend(bindings); - let mut marks = vec![FROZEN_MARK, GONE_MARK]; - marks.extend(refusals.iter().map(|(marker, _)| *marker)); - let (result, mut errors) = transaction_with_retry(db, &sql, &bound, &marks).await?; - let thrown = |marker: &str| { - errors - .values() - .any(|error| error.to_string().contains(marker)) - }; - if thrown(FROZEN_MARK) { - return Err(frozen_error()); - } - // The exam is gone: the same 404 every one of these writes' handlers - // answers a missing exam with, and it outranks the callers' own gates - // for the freeze's reason — there is nothing left to refuse *about*. - if thrown(GONE_MARK) { - return Err(AppError::NotFound); - } - for (marker, refusal) in refusals { - if thrown(marker) { - return Err(refusal); - } - } - match errors.drain().map(|(_, error)| error).next() { - Some(error) => Err(error.into()), - None => Ok(result), - } - } - - /// The first slot a [`Self::write_unfrozen`] caller's own statements land - /// in: `BEGIN`, the freeze `IF`, and the exam touch's two `LET`s, `IF` and - /// restoring `UPDATE` take one each. - pub(crate) const FROZEN_SLOT: usize = 6; - - /// Whether anyone has started this exam — the gate that freezes `mode` - /// edits once an attempt exists. - pub async fn any_for_exam(exam: &ExamId, db: &Database) -> Result { - let mut result = db - .query("SELECT VALUE id FROM exam_attempt WHERE exam = $ex LIMIT 1") - .bind(("ex", exam.record())) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::database::init_mem; - use crate::domain::exam::{ - ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, - }; - use crate::domain::exam_answer::ExamAnswer; - use crate::domain::exam_question::{ - ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, - }; - - /// The id of the question's second option — what these tests used to write - /// as the index `1`. - fn second_choice(question: &ExamQuestion) -> String { - question.get_choices().unwrap()[1] - .get_id() - .as_str() - .to_string() - } - use crate::domain::settings::Settings; - - /// An open exam with retakes allowed, plus one choice question — enough - /// rows to exercise the attempt lifecycle without the HTTP layer. - async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) { - let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); - let course = crate::db::course::a_test_course(db).await; - let kinds = Settings::defaults().get_exam_kinds().to_vec(); - let exam = Exam::create( - &creator, - &course, - ExamTitle::try_new("practice").unwrap(), - ExamDescription::try_new("").unwrap(), - ExamKind::try_new("quiz", &kinds).unwrap(), - ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None) - .unwrap(), - ExamAttemptLimit::try_new(max_attempts).unwrap(), - true, - false, - false, - db, - ) - .await - .unwrap(); - let spec = QuestionSpec::try_new( - QuestionKind::try_new("choice").unwrap(), - Some(vec![ - ChoiceInput { - id: Some("a".into()), - text: "5".into(), - }, - ChoiceInput { - id: Some("b".into()), - text: "6".into(), - }, - ]), - Some("b".into()), - &[], - ) - .unwrap(); - // A real subject row, not a minted id: a question claims a reference on - // its subject and is refused if that subject does not exist. - let subject = crate::domain::subject::Subject::create( - &crate::db::course::a_test_course(db).await, - crate::domain::subject::SubjectName::try_new("topic").unwrap(), - crate::domain::subject::SubjectDescription::try_new("").unwrap(), - db, - ) - .await - .unwrap(); - let question = ExamQuestion::create( - exam.get_id(), - subject.get_id().clone(), - crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(), - QuestionPoints::try_new(5).unwrap(), - spec, - db, - ) - .await - .unwrap(); - (exam, question) - } - - /// A real user row: the sitting counter lives on it, and the claim that - /// rides the attempt's create has nothing to write to without one. - async fn student(db: &Database) -> UserId { - let hash = crate::domain::user::Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(); - crate::domain::user::User::create( - crate::domain::user::Username::try_new("ogrenci").unwrap(), - hash, - db, - ) - .await - .unwrap() - .get_id() - .clone() - } - - /// The student's lifetime sitting count, absent reading as zero. - async fn sat_total(user: &UserId, db: &Database) -> i64 { - let mut result = db - .query(format!( - "SELECT VALUE ({EXAM_SAT_TOTAL_FIELD} ?? 0) FROM $usr" - )) - .bind(("usr", user.record())) - .await - .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .into_iter() - .next() - .unwrap() - } - - /// The badge counter counts *exams sat*, one per first sitting — so a start - /// moves it by exactly one and a resume, which creates nothing, leaves it - /// alone. Anything else and a seeded account and a fresh one would mean - /// different things by the same number. - #[tokio::test] - async fn starting_counts_one_sitting_and_resuming_counts_none() { - let db = init_mem().await.unwrap(); - let (exam, _question) = open_exam_with_question(&db, 2).await; - let user = student(&db).await; - assert_eq!(sat_total(&user, &db).await, 0, "a fresh row reads as zero"); - - let (_, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); - assert!(created); - assert_eq!(sat_total(&user, &db).await, 1); - - // Still in progress: this start returns the running sitting untouched. - let (_, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); - assert!(!created); - assert_eq!( - sat_total(&user, &db).await, - 1, - "a resume writes no row, so it counts nothing" - ); - } - - /// A retake is the same exam again: the row lands at the next `seq` and the - /// counter stays where it is. Counting it is the farm — an open exam with - /// unlimited attempts would mint `exam_sat_25` off one exam and no teacher. - #[tokio::test] - async fn a_retake_writes_its_row_and_counts_nothing() { - let db = init_mem().await.unwrap(); - let (exam, _question) = open_exam_with_question(&db, 3).await; - let user = student(&db).await; - - let (first, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); - first.finish(&db).await.unwrap(); - let (second, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); - assert!(created); - assert_eq!(second.get_seq(), 2); - assert_eq!(sat_total(&user, &db).await, 1); - } - - /// The lost half of a double-start race. `start` can only reach that branch - /// by interleaving with a rival, so the claim is put to the counter - /// directly — the same call `start` makes, aimed at a row that already - /// exists. The duplicate aborts the transaction and takes its increment - /// with it: a sitting is never counted twice. - #[tokio::test] - async fn a_lost_start_race_never_counts_the_sitting_twice() { - let db = init_mem().await.unwrap(); - let (exam, _question) = open_exam_with_question(&db, 1).await; - let user = student(&db).await; - - let (winner, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); - assert_eq!(sat_total(&user, &db).await, 1); - - let claimed = cap::claim_and_create( - &user.record(), - EXAM_SAT_TOTAL_FIELD, - cap::UNLIMITED, - &winner.id.record(), - &winner, - &db, - ) - .await - .unwrap(); - assert!(matches!(claimed, cap::Claimed::Duplicate)); - assert_eq!( - sat_total(&user, &db).await, - 1, - "the loser's increment rolled back with its duplicate create" - ); - } - - #[tokio::test] - async fn a_retake_preserves_the_prior_sittings_sheet() { - let db = init_mem().await.unwrap(); - let (exam, question) = open_exam_with_question(&db, 2).await; - let user = student(&db).await; - - let (first, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); - assert!(created); - assert_eq!(first.get_seq(), 1); - ExamAnswer::save( - &question, - &user, - 1, - Some(second_choice(&question)), - None, - &db, - ) - .await - .unwrap(); - first.finish(&db).await.unwrap(); - - // The retake lands as sitting #2 without touching sitting #1's answers. - let (second, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); - assert!(created); - assert_eq!(second.get_seq(), 2); - - // Sitting #1's answer is still there, read at its own seq. - let prior = ExamAnswer::read(question.get_id(), &user, 1, &db) - .await - .unwrap(); - assert!(prior.is_some(), "the retake must preserve seq 1's answer"); - // The new sitting starts blank at its own seq. - let fresh = ExamAnswer::list_for_exam_user(exam.get_id(), &user, 2, &db) - .await - .unwrap(); - assert!(fresh.is_empty(), "seq 2 starts blank"); - } - - #[tokio::test] - async fn a_lost_retake_race_cannot_touch_the_winners_sheet() { - let db = init_mem().await.unwrap(); - let (exam, question) = open_exam_with_question(&db, 3).await; - let user = student(&db).await; - - // Sitting #1 ends; the winner starts sitting #2 and saves an answer. - let (first, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); - first.finish(&db).await.unwrap(); - let (winner, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); - assert!(created); - assert_eq!(winner.get_seq(), 2); - ExamAnswer::save( - &question, - &user, - 2, - Some(second_choice(&question)), - None, - &db, - ) - .await - .unwrap(); - - // A stale double-start races on the same seq and loses to the - // composite id: the duplicate create is rejected, and with no wipe in - // the path the winner's fresh answer is untouched either way. - let loser = ExamAttempt { - id: ExamAttemptId::composite(exam.get_id(), &user, 2), - exam: exam.get_id().clone(), - user: user.clone(), - seq: 2, - started_at: Timestamp::now(), - finished_at: None, - left_at: None, - }; - let lost: Result, surrealdb::Error> = - db.create(loser.id.record()).content(loser).await; - assert!(lost.is_err(), "the duplicate-seq create must be rejected"); - let answers = ExamAnswer::list_for_exam_user(exam.get_id(), &user, 2, &db) - .await - .unwrap(); - assert_eq!( - answers.len(), - 1, - "the lost race must not disturb the winner's saved answer" - ); - - // The public path shrugs the race off: a re-start resumes the winner. - let (resumed, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); - assert!(!created); - assert_eq!(resumed.get_seq(), 2); - } - - #[tokio::test] - async fn submitting_never_reverts_a_walk_out_that_raced_it() { - let db = init_mem().await.unwrap(); - let (exam, _question) = open_exam_with_question(&db, 1).await; - let user = student(&db).await; - - let (attempt, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); - - // The REST submit path reads the attempt, then checks the deadline and - // the already-finished guard — several awaits before it writes. - let stale = ExamAttempt::read(attempt.get_id(), &db) - .await - .unwrap() - .expect("attempt exists"); - assert!(stale.get_left_at().is_none()); - - // In that gap the exam room's teardown stamps the walk-out (or a join - // clears it) — a field-scoped write to the same row. - ExamAttempt::read(attempt.get_id(), &db) - .await - .unwrap() - .expect("attempt exists") - .set_left(Some(Timestamp::now()), &db) - .await - .unwrap(); - - // The submit now writes from its stale snapshot. It owns `finished_at` - // and nothing else: carrying the snapshot's blank `left_at` back over - // the fresh stamp erases the recorded walk-out. - let finished = stale.finish(&db).await.unwrap(); - assert!(finished.get_finished_at().is_some()); - - let after = ExamAttempt::read(attempt.get_id(), &db) - .await - .unwrap() - .expect("attempt still exists"); - assert!( - after.get_left_at().is_some(), - "submitting must not revert a walk-out stamp that raced it" - ); - assert!(after.get_finished_at().is_some(), "the submission stands"); - } - - #[tokio::test] - async fn stamping_left_never_reverts_a_submission() { - let db = init_mem().await.unwrap(); - let (exam, _question) = open_exam_with_question(&db, 1).await; - let user = student(&db).await; - - // The student is sitting the exam. - let (attempt, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); - assert_eq!(attempt.get_seq(), 1); - - // The exam-room teardown reads the attempt while it is still in - // progress (`stamp_left`'s read) — a snapshot with `finished_at` unset. - let stale = ExamAttempt::read(attempt.get_id(), &db) - .await - .unwrap() - .expect("attempt exists"); - assert!(stale.get_finished_at().is_none()); - - // Before the teardown writes, the student submits (a REST finish, or a - // finish over another socket) — the submission lands. - let finished = ExamAttempt::read(attempt.get_id(), &db) - .await - .unwrap() - .expect("attempt exists") - .finish(&db) - .await - .unwrap(); - assert!(finished.get_finished_at().is_some()); - - // Now the last socket's teardown stamps `left_at` from its stale - // snapshot. Stamping the walk-out must touch only `left_at` — it must - // not carry the snapshot's blank `finished_at` back over the fresh - // submission, or the student's submitted exam silently reopens (and, - // with `allow_rejoin` off, locks them out of a room they left after - // finishing). - stale.set_left(Some(Timestamp::now()), &db).await.unwrap(); - - let after = ExamAttempt::read(attempt.get_id(), &db) - .await - .unwrap() - .expect("attempt still exists"); - assert!( - after.get_finished_at().is_some(), - "stamping left_at must not revert a submission that raced it" - ); - assert!( - after.get_left_at().is_some(), - "the walk-out is still recorded" - ); - assert_eq!( - after.status(&exam, Timestamp::now()), - AttemptStatus::Submitted, - "the attempt stays submitted" - ); - } } diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index 7b8329d..cadf182 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -8,12 +8,11 @@ use crate::constant::{ MIN_QUESTION_CHOICES, SUBJECT_QUESTION_COUNT_FIELD, }; use crate::database::Database; -use crate::domain::bank_question::BankQuestionId; use crate::db::cap; +use crate::db::page::PagedList; +use crate::domain::bank_question::BankQuestionId; use crate::domain::exam::ExamId; -use crate::domain::exam_attempt::ExamAttempt; use crate::domain::monotonic_id::next_ulid; -use crate::db::page::PagedList; use crate::domain::subject::SubjectId; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_question_kind, validate_question_points, validate_required}; @@ -444,7 +443,8 @@ impl ExamQuestion { let id = question.id.record(); // One counter write in flight at a time, like every other counter write. let _guard = cap::counter_lock().await; - let mut result = ExamAttempt::write_unfrozen_with( + let mut result = crate::db::exam_attempt::write_unfrozen_with( + db, exam, &format!( "LET $seat = (UPDATE $subject SET {SUBJECT_QUESTION_COUNT_FIELD} = \ @@ -458,7 +458,6 @@ impl ExamQuestion { ("question".into(), question.into_value()), ], vec![(SUBJECT_MARK, dead_subject())], - db, ) .await?; // Counted off the statements that actually ran rather than a fixed @@ -640,9 +639,14 @@ impl ExamQuestion { Some(_) => Some(cap::counter_lock().await), None => None, }; - let mut result = - ExamAttempt::write_unfrozen_with(&self.exam, &statements, bindings, refusals, db) - .await?; + let mut result = crate::db::exam_attempt::write_unfrozen_with( + db, + &self.exam, + &statements, + bindings, + refusals, + ) + .await?; // Read off the trailing `RETURN` rather than a fixed slot: a re-tag // arms three more statements than a plain PATCH does (and an `IF` // block is one slot whether or not it is taken). @@ -694,7 +698,8 @@ impl ExamQuestion { /// delete — and the cascade now shares that transaction too, so a failure /// mid-way can no longer strand answers whose question survived. pub async fn delete(self, db: &Database) -> Result { - let mut result = ExamAttempt::write_unfrozen( + let mut result = crate::db::exam_attempt::write_unfrozen( + db, &self.exam, &format!( "DELETE exam_answer WHERE question = $q; @@ -707,7 +712,6 @@ impl ExamQuestion { RETURN $gone;" ), vec![("q".into(), self.id.record().into_value())], - db, ) .await?; // The subject's reference is given back inside this same transaction, @@ -1197,7 +1201,7 @@ mod tests { ) .await .unwrap(); - ExamAttempt::start(&exam, student.get_id(), &db) + crate::service::exam_attempt::start(&db, &exam, student.get_id()) .await .unwrap(); diff --git a/src/domain/question_image.rs b/src/domain/question_image.rs index dee6e2a..9b7a7e3 100644 --- a/src/domain/question_image.rs +++ b/src/domain/question_image.rs @@ -16,7 +16,6 @@ use crate::constant::QUESTION_IMAGE_TABLE; use crate::database::Database; use crate::domain::course::CourseId; use crate::domain::exam::ExamId; -use crate::domain::exam_attempt::ExamAttempt; use crate::domain::exam_question::{ChoiceId, ExamQuestionId}; use crate::domain::key; use crate::domain::note_file::FileContentType; @@ -127,7 +126,8 @@ impl QuestionImage { pub async fn upsert(self, db: &Database) -> Result<(QuestionImage, Option), AppError> { // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic let (exam, id) = (self.exam.clone(), self.id.record()); - let mut result = ExamAttempt::write_unfrozen( + let mut result = crate::db::exam_attempt::write_unfrozen( + db, &exam, "LET $replaced = (SELECT VALUE file FROM $id); LET $stored = (UPSERT $id CONTENT $image); @@ -136,7 +136,6 @@ impl QuestionImage { ("id".into(), id.into_value()), ("image".into(), self.into_value()), ], - db, ) .await?; // The trailing `RETURN` is the last statement before `COMMIT`, so its @@ -235,15 +234,15 @@ impl QuestionImage { /// Refused once the exam has an attempt, in the same transaction — same /// gate, same reason as [`Self::upsert`]. pub async fn delete(self, db: &Database) -> Result { - let mut result = ExamAttempt::write_unfrozen( + let mut result = crate::db::exam_attempt::write_unfrozen( + db, &self.exam, "DELETE $id RETURN BEFORE;", vec![("id".into(), self.id.record().into_value())], - db, ) .await?; result - .take::>(ExamAttempt::FROZEN_SLOT)? + .take::>(crate::db::exam_attempt::FROZEN_SLOT)? .into_iter() .next() .ok_or(AppError::NotFound) diff --git a/src/service/exam_attempt.rs b/src/service/exam_attempt.rs new file mode 100644 index 0000000..15b9a55 --- /dev/null +++ b/src/service/exam_attempt.rs @@ -0,0 +1,765 @@ +//! The exam-sitting workflows: starting, resuming, and finishing sittings, +//! saving answers into them, and the gates (sittable, student, enrollment, +//! rejoin, archived term) every sitting path shares. The queries live in +//! [`crate::db::exam_attempt`]; the HTTP shaping stays in the web layer. + +use crate::constant::EXAM_SAT_TOTAL_FIELD; +use crate::database::Database; +use crate::db::cap; +use crate::domain::badge; +use crate::domain::course::Course; +use crate::domain::enrollment::Enrollment; +use crate::domain::exam::{Exam, ExamId}; +use crate::domain::exam_answer::ExamAnswer; +use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId}; +use crate::domain::exam_question::{ExamQuestion, ExamQuestionId}; +use crate::domain::role::Role; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::{User, UserId}; +use crate::error::AppError; + +/// Serializes the exam subsystem's cross-record check-then-writes, which +/// `BEGIN…COMMIT` cannot (write skew) — the reasoning in [`crate::db::cap`]. +/// It orders requests, but only around what it wraps — every invariant that +/// could be moved into the database itself has been, so a gap between a read +/// and its write is decided by the store. What is left here needs a +/// cross-record read and a write held together, which no single statement +/// expresses: +/// +/// Read side — the answer saves (REST and the exam room), from the +/// writable-attempt gate through the upsert; the grade write (draft gate +/// through the result upsert); and the exam PATCH, whose mode/re-draft gates +/// count attempts and results. These stay concurrent with each other. +/// +/// Write side — attempt starts alone (the max-attempts count and the retake's +/// answer wipe). So a save can never land on a sheet a retake just wiped, and a +/// mark can never land on an exam mid-flight into hiding. +/// +/// Two rules have left this list. The question freeze gate rides inside each +/// question/image write's own transaction +/// ([`crate::db::exam_attempt::write_unfrozen`]), and the exam PATCH +/// no longer needs the writer lease because its save is a compare-and-set. The +/// subject delete's cascade — the only writer outside attempt starts, paired +/// with the question writes' subject check — is now a conditional statement on +/// the subject's own reference counter +/// ([`crate::domain::subject::Subject::delete`]), which every question create, +/// re-tag and delete moves. +// corner-cut: global RwLock, shard per-exam if save latency ever matters. +pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); + +/// Rejects sitting an exam that can't be sat. A draft is a `404`, not a +/// `409` — sitting is a student act, drafts are invisible to students, and a +/// state-specific error would leak the existence this feature hides. A +/// modeless (offline-graded) exam is a `409`: visible, just nothing to sit. +/// Enrollment and window checks for the caller are the caller's own state — +/// also `Conflict`, not validation. +pub fn ensure_sittable(exam: &Exam) -> Result<(), AppError> { + if exam.is_draft() { + return Err(AppError::NotFound); + } + if exam.get_mode().is_none() { + return Err(AppError::Conflict( + "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)", + )); + } + Ok(()) +} + +/// A 403 unless `user` is a student. Sitting an exam is a student action — +/// teachers and above run exams, they never take them — so the sit paths +/// (start, room, save) enforce it on the *current* role. Checking the live +/// role, not just enrollment, closes the gap a mid-exam promotion would open +/// and neutralizes any stale non-student enrollment. Reading one's own attempt +/// and finishing stay ungated: a non-student has no attempt to read, and +/// finishing only submits work already saved. +pub fn ensure_student(user: &User) -> Result<(), AppError> { + if user.get_role() != Role::Student { + return Err(AppError::Forbidden("only students can sit exams")); + } + Ok(()) +} + +/// The answer path's live edition of [`ensure_student`]: re-read the row and +/// judge the *current* role, exactly like the enrollment wall beside it. Both +/// save paths run through here (REST per request, the exam room per message), +/// so a promotion out of `student` mid-exam closes the sheet on the very next +/// save — the room's door check is not the last word for a socket that +/// outlives the role. +pub async fn ensure_student_now(user: &UserId, db: &Database) -> Result<(), AppError> { + let user = crate::domain::user::User::read(user, db) + .await? + .ok_or(AppError::Unauthorized)?; + ensure_student(&user) +} + +/// A 403 unless `user` is enrolled in the exam's course — the same wall the +/// exam room checks at its door, re-applied to the sitting's content paths so +/// an unenrollment mid-exam cuts them too. Finishing stays exempt: like the +/// rejoin lock, submitting what's already saved writes nothing new. +pub async fn ensure_enrolled(exam: &Exam, user: &UserId, db: &Database) -> Result<(), AppError> { + if Enrollment::read_for_user(exam.get_course(), user, db) + .await? + .is_none() + { + return Err(AppError::Forbidden( + "you are not enrolled in this exam's course", + )); + } + Ok(()) +} + +/// A 409 when the student has walked out of the exam room and the exam's +/// rejoin door is closed: no more answering (from anywhere) until the teacher +/// flips `allow_rejoin` back on. Finishing is deliberately exempt — see +/// the finish workflow. +pub fn check_rejoin(exam: &Exam, attempt: &ExamAttempt) -> Result<(), AppError> { + if attempt.get_left_at().is_some() && !exam.get_allow_rejoin() { + return Err(AppError::Conflict( + "you left the exam and rejoin is closed — ask your teacher to reopen it", + )); + } + Ok(()) +} + +/// The caller's latest attempt provided it is still writable, or the error +/// that says why not: no attempt yet (404 — start it first), already +/// submitted (409), deadline passed (409). One gate shared by REST saves and +/// the WebSocket room. +pub async fn writable_attempt( + exam: &Exam, + user: &UserId, + db: &Database, +) -> Result { + let attempt = crate::db::exam_attempt::read_latest_for_user(db, exam.get_id(), user) + .await? + .ok_or(AppError::NotFound)?; + match attempt.status(exam, Timestamp::now()) { + AttemptStatus::Submitted => Err(AppError::Conflict("the attempt is already submitted")), + AttemptStatus::Expired => Err(AppError::Conflict("time is up — the attempt has expired")), + AttemptStatus::InProgress => Ok(attempt), + } +} + +/// The course an exam belongs to. A dangling reference means the course-delete +/// cascade was violated — surface it loudly as a 500, not a user-facing 404. +pub async fn course_of(exam: &Exam, db: &Database) -> Result { + crate::domain::course::Course::read(exam.get_course(), db) + .await? + .ok_or_else(|| AppError::Internal("exam references a missing course".into())) +} + +/// The question, provided it belongs to `exam` — a qid under someone else's +/// exam is a plain 404, not a leak. +pub async fn question_of_exam( + exam: &ExamId, + qid: &str, + db: &Database, +) -> Result { + let question = ExamQuestion::read(&ExamQuestionId::from_key(qid), db) + .await? + .ok_or(AppError::NotFound)?; + if question.get_exam() != exam { + return Err(AppError::NotFound); + } + Ok(question) +} + +/// Start, resume, or retake `user`'s attempt at `exam`. Returns the attempt +/// plus whether it was newly created. +/// +/// - A still-running latest attempt is returned untouched, so a +/// reconnecting client gets its original clock back instead of a reset — +/// re-"starting" can never buy more time. +/// - A terminal latest attempt (submitted or expired) starts sitting +/// `seq + 1` if the exam's `max_attempts` allows another, and is a +/// conflict otherwise. A retake preserves every prior sitting: the new +/// row is created at the new `seq` and the student's earlier answers, +/// drawings, and marks stay put at their own seq — the fresh sitting +/// simply writes into an empty higher seq. +/// +/// The composite id makes each create atomic; a concurrent double-start +/// races on the same seq, loses to the unique id, and reads the winner's +/// row. +/// +/// A created row rides [`cap::create_counting`] so the student's +/// `exam_sat_total` moves in the same transaction — but only for `seq == 1`, +/// because that counter is *exams sat*, not sittings. A retake is the same +/// exam again, and counting it made a badge a student could mint alone: an +/// open exam with unlimited attempts is a start/finish loop nobody else has +/// to touch. `seq == 1` is the whole condition and needs no extra read — +/// the first sitting's id is one deterministic key, so of every writer +/// aiming at it exactly one `CREATE` commits and the losers' increments +/// abort with their duplicates, while a retake computes its seq from a row +/// that already exists. A `SELECT` inside the transaction would be strictly +/// worse: SurrealDB 3.2.3 conflict-checks write sets, not read sets. +pub async fn start( + db: &Database, + exam: &Exam, + user: &UserId, +) -> Result<(ExamAttempt, bool), AppError> { + let attempts = crate::db::exam_attempt::list_for_user(db, exam.get_id(), user).await?; + let next_seq = match attempts.first() { + None => 1, + Some(latest) if latest.status(exam, Timestamp::now()) == AttemptStatus::InProgress => { + return Ok((latest.clone(), false)); + } + Some(latest) => { + if !exam.get_max_attempts().allows_another(attempts.len()) { + return Err(AppError::Conflict( + "no attempts remaining — this exam's attempt limit is used up", + )); + } + latest.seq + 1 + } + }; + let attempt = ExamAttempt { + id: ExamAttemptId::composite(exam.get_id(), user, next_seq), + exam: exam.get_id().clone(), + user: user.clone(), + seq: next_seq, + started_at: Timestamp::now(), + finished_at: None, + left_at: None, + }; + let id = attempt.id.record(); + let first = next_seq == 1; + match cap::create_counting( + &user.record(), + EXAM_SAT_TOTAL_FIELD, + first, + &id, + &attempt, + db, + ) + .await? + { + cap::Claimed::Made(created) => { + // Only a moved counter can have crossed a threshold. + if first && let Err(err) = badge::sync(user, db).await { + tracing::warn!("failed to sync badges for {}: {err}", user.key()); + } + Ok((created, true)) + } + // Only a still-running row proves the loss was a double-start + // collision (the winner's fresh sitting); a terminal or missing + // latest means the create genuinely failed — surface that instead + // of passing a finished sitting off as a resume. The duplicate + // aborted the transaction, so the loser's increment went with it. + cap::Claimed::Duplicate => { + match crate::db::exam_attempt::read_latest_for_user(db, exam.get_id(), user).await? { + Some(existing) + if existing.status(exam, Timestamp::now()) == AttemptStatus::InProgress => + { + Ok((existing, false)) + } + _ => Err(AppError::Internal("failed to start exam attempt".into())), + } + } + // Nothing caps sittings, so the conditional write can only miss by + // finding no user row — not a state a live session can reach, and + // passing it off as a resume would hand out a sitting the counter + // never learned about. + cap::Claimed::Full => Err(AppError::Internal( + "cannot start an exam attempt: the student's account row is missing".into(), + )), + } +} + +/// Start, resume, or retake the caller's attempt at `exam_id`. Requires the +/// student role (staff run exams, they don't sit them), enrollment in the +/// exam's course, a sittable exam (`sync`/`async`/`open` mode), and — when a +/// window exists — the window to be open. Returns the exam the gates judged +/// (the response describes that row) plus the attempt and whether it was +/// newly created. +/// +/// Writer lease of [`EXAM_LOCK`] from the exam read through the start: the +/// sittable/window gates must be judged against the same exam row the +/// attempt lands under (the mirror of `update_exam`'s re-derive — without +/// it, a mode change or re-draft at legally-zero attempts could slip +/// between this gate and the insert, leaving an attempt on an unsittable +/// exam). The lease +/// also keeps the max-attempts count and the retake's wipe-and-create +/// from interleaving with an in-flight answer save (a reader). The caller +/// drops nothing: the lease lives and dies inside this call, before the +/// response reads — they only describe the row. +/// +/// A still-running attempt comes back as-is (the handler answers `200` +/// instead of `201`), so a reconnecting client gets its original clock +/// back — re-starting never resets the time. Once the latest attempt is +/// submitted or expired, re-posting starts the next sitting while the +/// exam's `max_attempts` (0 = unlimited) allows it. +/// +/// A retake no longer wipes the prior sitting — each attempt's answers, +/// drawings, and marks stay put at their own seq (per-attempt history), so +/// there are no orphaned blobs to GC here. The exam-delete cascade still +/// cleans every sitting's blobs. +pub async fn start_attempt( + db: &Database, + exam_id: &ExamId, + user: &User, +) -> Result<(Exam, ExamAttempt, bool), AppError> { + let _guard = EXAM_LOCK.write().await; + let exam = crate::domain::exam::Exam::read(exam_id, db) + .await? + .ok_or(AppError::NotFound)?; + ensure_sittable(&exam)?; + ensure_student(user)?; + ensure_enrolled(&exam, user.get_id(), db).await?; + course_of(&exam, db).await?.require_open(db).await?; + let now = Timestamp::now(); + if let Some(starts_at) = exam.get_starts_at() + && now < starts_at + { + return Err(AppError::Conflict("the exam has not started yet")); + } + if let Some(ends_at) = exam.get_ends_at() + && now >= ends_at + { + return Err(AppError::Conflict("the exam has already ended")); + } + let (attempt, created) = start(db, &exam, user.get_id()).await?; + Ok((exam, attempt, created)) +} + +/// Submit `user`'s latest attempt at `exam`. Allowed while the deadline +/// hasn't passed; after it, the attempt is already `expired` (a valid +/// terminal state — the student used their full time) and submitting is a +/// `409`. +/// +/// Deliberately no rejoin check: a student locked out of the room may +/// still submit what they saved — finishing answers nothing new. +pub async fn finish_attempt( + db: &Database, + exam: &Exam, + user: &UserId, +) -> Result { + let attempt = crate::db::exam_attempt::read_latest_for_user(db, exam.get_id(), user) + .await? + .ok_or(AppError::NotFound)?; + if attempt.get_finished_at().is_some() { + return Err(AppError::Conflict("the attempt is already submitted")); + } + let now = Timestamp::now(); + if let Some(deadline) = attempt.deadline(exam) + && now >= deadline + { + return Err(AppError::Conflict("time is up — the attempt has expired")); + } + course_of(exam, db).await?.require_open(db).await?; + crate::db::exam_attempt::finish(db, attempt).await +} + +/// Save one answer inside the caller's in-progress attempt — the whole write +/// path (student gate, attempt gate, rejoin gate via [`save_answer_in`], +/// question lookup, kind check, upsert). The REST handler saves into the +/// latest sitting via this; the WebSocket room +/// resolves its own sitting first and shares [`save_answer_in`], so the two +/// can never drift. +pub async fn save_answer_checked( + db: &Database, + exam: &Exam, + user: &User, + question_id: &str, + selected: Option, + text: Option, +) -> Result { + ensure_student(user)?; + // Reader lease of [`EXAM_LOCK`]: the writable gate and the upsert are + // one unit, or a retake's wipe-and-create (a writer) slips in between + // and this stale save lands on the fresh blank sheet. + // + // The lease covers the gate *and* the upsert here, so a retake cannot + // interleave with this path at all. The accepted late-save race lives in + // the exam-room socket instead, which writes into the sitting it joined + // with — a value chosen before any lease is taken. See + // [`crate::web::exam_ws`]. + let _guard = EXAM_LOCK.read().await; + let attempt = writable_attempt(exam, user.get_id(), db).await?; + save_answer_in(db, exam, &attempt, question_id, selected, text).await +} + +/// The tail of the answer write path, given the sitting to write in: the +/// student wall and the enrollment wall (a promotion out of `student` or an +/// unenrollment closes the sheet, mid-exam included), the rejoin gate, the +/// archived-term gate, the question lookup, and the upsert. +/// +/// The archived-term refusal sits here because this is the single funnel every +/// answer write passes: REST `POST /exams/{id}/attempt/answers` (via +/// [`save_answer_checked`]) *and* every `answer` frame of the exam-room +/// WebSocket ([`crate::web::exam_ws`]). The answer-image writes are the only +/// answer-side writes outside it, and carry their own guard. +pub async fn save_answer_in( + db: &Database, + exam: &Exam, + attempt: &ExamAttempt, + question_id: &str, + selected: Option, + text: Option, +) -> Result { + ensure_student_now(attempt.get_user(), db).await?; + ensure_enrolled(exam, attempt.get_user(), db).await?; + check_rejoin(exam, attempt)?; + course_of(exam, db).await?.require_open(db).await?; + let question = question_of_exam(exam.get_id(), question_id, db).await?; + crate::domain::exam_answer::ExamAnswer::save( + &question, + attempt.get_user(), + attempt.get_seq(), + selected, + text, + db, + ) + .await +} + +/// One sitting by id — the exam room re-reads its own attempt this way. +pub async fn read(db: &Database, id: &ExamAttemptId) -> Result, AppError> { + crate::db::exam_attempt::read(db, id).await +} + +/// The student's current sitting — the highest `seq` for the pair. +pub async fn read_latest_for_user( + db: &Database, + exam: &ExamId, + user: &UserId, +) -> Result, AppError> { + crate::db::exam_attempt::read_latest_for_user(db, exam, user).await +} + +/// Every sitting of `user` at `exam`, newest first. +pub async fn list_for_user( + db: &Database, + exam: &ExamId, + user: &UserId, +) -> Result, AppError> { + crate::db::exam_attempt::list_for_user(db, exam, user).await +} + +/// Every sitting of `user` nobody has submitted yet, across all exams. +pub async fn list_unfinished_for_user( + db: &Database, + user: &UserId, +) -> Result, AppError> { + crate::db::exam_attempt::list_unfinished_for_user(db, user).await +} + +/// Every sitting at `exam`, newest id first. +pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result, AppError> { + crate::db::exam_attempt::list_for_exam(db, exam).await +} + +/// Whether anyone has started this exam — the gate that freezes `mode` +/// edits once an attempt exists. +pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result { + crate::db::exam_attempt::any_for_exam(db, exam).await +} + +/// How many sittings `user` has used at `exam`. +pub async fn attempts_used(db: &Database, exam: &ExamId, user: &UserId) -> Result { + Ok(crate::db::exam_attempt::list_for_user(db, exam, user) + .await? + .len() as u64) +} + +/// Stamp the submission time. The caller has already checked the deadline +/// and that the attempt isn't finished. +pub async fn finish(db: &Database, attempt: ExamAttempt) -> Result { + crate::db::exam_attempt::finish(db, attempt).await +} + +/// Stamp (or clear) the walked-out marker. The exam room sets it when the +/// student's socket closes mid-attempt and clears it when they come back. +pub async fn set_left( + db: &Database, + attempt: ExamAttempt, + left_at: Option, +) -> Result { + crate::db::exam_attempt::set_left(db, attempt, left_at).await +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database::init_mem; + use crate::domain::exam::{ + ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, + }; + use crate::domain::exam_answer::ExamAnswer; + use crate::domain::exam_question::{ + ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, + }; + use crate::domain::settings::Settings; + + /// The id of the question's second option — what these tests used to write + /// as the index `1`. + fn second_choice(question: &ExamQuestion) -> String { + question.get_choices().unwrap()[1] + .get_id() + .as_str() + .to_string() + } + + /// An open exam with retakes allowed, plus one choice question — enough + /// rows to exercise the attempt lifecycle without the HTTP layer. + async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) { + let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + let course = crate::domain::course::a_test_course(db).await; + let kinds = Settings::defaults().get_exam_kinds().to_vec(); + let exam = Exam::create( + &creator, + &course, + ExamTitle::try_new("practice").unwrap(), + ExamDescription::try_new("").unwrap(), + ExamKind::try_new("quiz", &kinds).unwrap(), + ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None) + .unwrap(), + ExamAttemptLimit::try_new(max_attempts).unwrap(), + true, + false, + false, + db, + ) + .await + .unwrap(); + let spec = QuestionSpec::try_new( + QuestionKind::try_new("choice").unwrap(), + Some(vec![ + ChoiceInput { + id: Some("a".into()), + text: "5".into(), + }, + ChoiceInput { + id: Some("b".into()), + text: "6".into(), + }, + ]), + Some("b".into()), + &[], + ) + .unwrap(); + // A real subject row, not a minted id: a question claims a reference on + // its subject and is refused if that subject does not exist. + let subject = crate::domain::subject::Subject::create( + &crate::domain::course::a_test_course(db).await, + crate::domain::subject::SubjectName::try_new("topic").unwrap(), + crate::domain::subject::SubjectDescription::try_new("").unwrap(), + db, + ) + .await + .unwrap(); + let question = ExamQuestion::create( + exam.get_id(), + subject.get_id().clone(), + crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(), + QuestionPoints::try_new(5).unwrap(), + spec, + db, + ) + .await + .unwrap(); + (exam, question) + } + + /// A real user row: the sitting counter lives on it, and the claim that + /// rides the attempt's create has nothing to write to without one. + async fn student(db: &Database) -> UserId { + let hash = crate::domain::user::Password::try_new("secret1") + .unwrap() + .hash_async() + .await + .unwrap(); + crate::domain::user::User::create( + crate::domain::user::Username::try_new("ogrenci").unwrap(), + hash, + db, + ) + .await + .unwrap() + .get_id() + .clone() + } + + /// The student's lifetime sitting count, absent reading as zero. + async fn sat_total(user: &UserId, db: &Database) -> i64 { + let mut result = db + .query(format!( + "SELECT VALUE ({EXAM_SAT_TOTAL_FIELD} ?? 0) FROM $usr" + )) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .into_iter() + .next() + .unwrap() + } + + /// The badge counter counts *exams sat*, one per first sitting — so a start + /// moves it by exactly one and a resume, which creates nothing, leaves it + /// alone. Anything else and a seeded account and a fresh one would mean + /// different things by the same number. + #[tokio::test] + async fn starting_counts_one_sitting_and_resuming_counts_none() { + let db = init_mem().await.unwrap(); + let (exam, _question) = open_exam_with_question(&db, 2).await; + let user = student(&db).await; + assert_eq!(sat_total(&user, &db).await, 0, "a fresh row reads as zero"); + + let (_, created) = start(&db, &exam, &user).await.unwrap(); + assert!(created); + assert_eq!(sat_total(&user, &db).await, 1); + + // Still in progress: this start returns the running sitting untouched. + let (_, created) = start(&db, &exam, &user).await.unwrap(); + assert!(!created); + assert_eq!( + sat_total(&user, &db).await, + 1, + "a resume writes no row, so it counts nothing" + ); + } + + /// A retake is the same exam again: the row lands at the next `seq` and the + /// counter stays where it is. Counting it is the farm — an open exam with + /// unlimited attempts would mint `exam_sat_25` off one exam and no teacher. + #[tokio::test] + async fn a_retake_writes_its_row_and_counts_nothing() { + let db = init_mem().await.unwrap(); + let (exam, _question) = open_exam_with_question(&db, 3).await; + let user = student(&db).await; + + let (first, _) = start(&db, &exam, &user).await.unwrap(); + finish(&db, first).await.unwrap(); + let (second, created) = start(&db, &exam, &user).await.unwrap(); + assert!(created); + assert_eq!(second.get_seq(), 2); + assert_eq!(sat_total(&user, &db).await, 1); + } + + /// The lost half of a double-start race. `start` can only reach that branch + /// by interleaving with a rival, so the claim is put to the counter + /// directly — the same call `start` makes, aimed at a row that already + /// exists. The duplicate aborts the transaction and takes its increment + /// with it: a sitting is never counted twice. + #[tokio::test] + async fn a_lost_start_race_never_counts_the_sitting_twice() { + let db = init_mem().await.unwrap(); + let (exam, _question) = open_exam_with_question(&db, 1).await; + let user = student(&db).await; + + let (winner, _) = start(&db, &exam, &user).await.unwrap(); + assert_eq!(sat_total(&user, &db).await, 1); + + let claimed = cap::claim_and_create( + &user.record(), + EXAM_SAT_TOTAL_FIELD, + cap::UNLIMITED, + &winner.id.record(), + &winner, + &db, + ) + .await + .unwrap(); + assert!(matches!(claimed, cap::Claimed::Duplicate)); + assert_eq!( + sat_total(&user, &db).await, + 1, + "the loser's increment rolled back with its duplicate create" + ); + } + + #[tokio::test] + async fn a_retake_preserves_the_prior_sittings_sheet() { + let db = init_mem().await.unwrap(); + let (exam, question) = open_exam_with_question(&db, 2).await; + let user = student(&db).await; + + let (first, created) = start(&db, &exam, &user).await.unwrap(); + assert!(created); + assert_eq!(first.get_seq(), 1); + ExamAnswer::save( + &question, + &user, + 1, + Some(second_choice(&question)), + None, + &db, + ) + .await + .unwrap(); + finish(&db, first).await.unwrap(); + + // The retake lands as sitting #2 without touching sitting #1's answers. + let (second, created) = start(&db, &exam, &user).await.unwrap(); + assert!(created); + assert_eq!(second.get_seq(), 2); + + // Sitting #1's answer is still there, read at its own seq. + let prior = ExamAnswer::read(question.get_id(), &user, 1, &db) + .await + .unwrap(); + assert!(prior.is_some(), "the retake must preserve seq 1's answer"); + // The new sitting starts blank at its own seq. + let fresh = ExamAnswer::list_for_exam_user(exam.get_id(), &user, 2, &db) + .await + .unwrap(); + assert!(fresh.is_empty(), "seq 2 starts blank"); + } + + #[tokio::test] + async fn a_lost_retake_race_cannot_touch_the_winners_sheet() { + let db = init_mem().await.unwrap(); + let (exam, question) = open_exam_with_question(&db, 3).await; + let user = student(&db).await; + + // Sitting #1 ends; the winner starts sitting #2 and saves an answer. + let (first, _) = start(&db, &exam, &user).await.unwrap(); + finish(&db, first).await.unwrap(); + let (winner, created) = start(&db, &exam, &user).await.unwrap(); + assert!(created); + assert_eq!(winner.get_seq(), 2); + ExamAnswer::save( + &question, + &user, + 2, + Some(second_choice(&question)), + None, + &db, + ) + .await + .unwrap(); + + // A stale double-start races on the same seq and loses to the + // composite id: the duplicate create is rejected, and with no wipe in + // the path the winner's fresh answer is untouched either way. + let loser = ExamAttempt { + id: ExamAttemptId::composite(exam.get_id(), &user, 2), + exam: exam.get_id().clone(), + user: user.clone(), + seq: 2, + started_at: Timestamp::now(), + finished_at: None, + left_at: None, + }; + let lost: Result, surrealdb::Error> = + db.create(loser.id.record()).content(loser).await; + assert!(lost.is_err(), "the duplicate-seq create must be rejected"); + let answers = ExamAnswer::list_for_exam_user(exam.get_id(), &user, 2, &db) + .await + .unwrap(); + assert_eq!( + answers.len(), + 1, + "the lost race must not disturb the winner's saved answer" + ); + + // The public path shrugs the race off: a re-start resumes the winner. + let (resumed, created) = start(&db, &exam, &user).await.unwrap(); + assert!(!created); + assert_eq!(resumed.get_seq(), 2); + } +} diff --git a/src/service/mod.rs b/src/service/mod.rs index f50a1e4..892e3cd 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -3,6 +3,7 @@ pub mod appointment; pub mod course; +pub mod exam_attempt; pub mod note; pub mod payment_ledger; pub mod session; diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 16ad239..5b29fbd 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -72,14 +72,14 @@ use crate::domain::exam_question::ExamQuestion; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; +use crate::service::exam_attempt::{ + EXAM_LOCK, check_rejoin, course_of, ensure_enrolled, ensure_sittable, ensure_student, finish, + read, save_answer_in, set_left, writable_attempt, +}; use crate::state::AppState; use crate::tenant::Slug; use crate::validate::validate_required; use crate::web::CurrentUser; -use crate::web::exams::{ - EXAM_LOCK, check_rejoin, course_of, ensure_enrolled, ensure_sittable, ensure_student, - save_answer_in, writable_attempt, -}; use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq}; /// How this room names itself in the logs [`room::public_message`] writes. @@ -152,7 +152,7 @@ pub async fn attempt_ws( 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::course::require_open(&st.db, &course_of(&exam, &st.db).await?).await?; + course_of(&exam, &st.db).await?.require_open(&st.db).await?; let user_id = user.get_id().clone(); Ok(ws.on_upgrade(move |socket| room(socket, st, slug, exam, attempt, user_id))) @@ -184,7 +184,7 @@ async fn room( { let _guard = PRESENCE_LOCK.lock().await; st.exam_presence.enter(&slug, attempt_id.key()); - if let Err(err) = attempt.set_left(None, &st.db).await { + if let Err(err) = set_left(&st.db, attempt, None).await { tracing::warn!("exam room could not clear left_at on join: {err}"); } } @@ -234,7 +234,7 @@ async fn room( /// started elsewhere can't be marked as left by an old room's teardown. async fn stamp_left(exam_id: &ExamId, attempt_id: &ExamAttemptId, db: &Database) { let attempt = match Exam::read(exam_id, db).await { - Ok(Some(exam)) => match ExamAttempt::read(attempt_id, db).await { + Ok(Some(exam)) => match read(db, attempt_id).await { Ok(Some(attempt)) if attempt.status(&exam, Timestamp::now()) == AttemptStatus::InProgress => { @@ -253,7 +253,7 @@ async fn stamp_left(exam_id: &ExamId, attempt_id: &ExamAttemptId, db: &Database) } }; if let Some(attempt) = attempt - && let Err(err) = attempt.set_left(Some(Timestamp::now()), db).await + && let Err(err) = set_left(db, attempt, Some(Timestamp::now())).await { tracing::warn!("exam room could not stamp left_at: {err}"); } @@ -329,9 +329,7 @@ async fn state_frame( db: &Database, ) -> Result<(Value, AttemptStatus, Option), AppError> { let exam = Exam::read(exam, db).await?.ok_or(AppError::NotFound)?; - let attempt = ExamAttempt::read(attempt, db) - .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); @@ -417,7 +415,7 @@ async fn handle_message( Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await { Ok(attempt) => { in_save = true; - save_answer_in(&exam, &attempt, &question_id, selected, text, db).await + save_answer_in(db, &exam, &attempt, &question_id, selected, text).await } Err(err) => Err(err), }, @@ -463,8 +461,8 @@ async fn handle_message( // same error frame as every other conflict. async { let attempt = writable_room_attempt(&exam, attempt_id, user, db).await?; - crate::service::course::require_open(db, &course_of(&exam, db).await?).await?; - attempt.finish(db).await + course_of(&exam, db).await?.require_open(db).await?; + finish(db, attempt).await } .await } diff --git a/src/web/exams/attempts.rs b/src/web/exams/attempts.rs index cadadd7..1a9068d 100644 --- a/src/web/exams/attempts.rs +++ b/src/web/exams/attempts.rs @@ -1,5 +1,8 @@ use super::*; +use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt}; +use crate::service::exam_attempt; + // ---- attempts ------------------------------------------------------------- // A sittable exam (sync, async, or open mode) is *sat*: starting an attempt // is the live-attendance signal, finishing is the submission. The exam's @@ -109,33 +112,6 @@ pub(crate) async fn attempt_progress( Ok((answered, question_count)) } -/// Rejects sitting an exam that can't be sat. A draft is a `404`, not a -/// `409` — sitting is a student act, drafts are invisible to students, and a -/// state-specific error would leak the existence this feature hides. A -/// modeless (offline-graded) exam is a `409`: visible, just nothing to sit. -/// Enrollment and window checks for the caller are the caller's own state — -/// also `Conflict`, not validation. -pub(crate) fn ensure_sittable(exam: &Exam) -> Result<(), AppError> { - if exam.is_draft() { - return Err(AppError::NotFound); - } - if exam.get_mode().is_none() { - return Err(AppError::Conflict( - "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)", - )); - } - Ok(()) -} - -/// How many sittings the caller has used at this exam. -pub(crate) async fn attempts_used( - exam: &ExamId, - user: &UserId, - db: &Database, -) -> Result { - Ok(ExamAttempt::list_for_user(exam, user, db).await?.len() as u64) -} - /// Start, resume, or retake the caller's attempt. Requires the student role /// (staff run exams, they don't sit them), enrollment in the exam's course, a /// sittable exam (`sync`/`async`/`open` mode), and — when a window exists — the @@ -164,47 +140,14 @@ pub(crate) async fn start_attempt( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result<(StatusCode, Json), AppError> { - // Writer lease of [`EXAM_LOCK`] from the exam read through the start: the - // sittable/window gates must be judged against the same exam row the - // attempt lands under (the mirror of `update_exam`'s re-derive — without - // it, a mode change or re-draft at legally-zero attempts could slip - // between this gate and the insert, leaving an attempt on an unsittable - // exam). The lease - // also keeps the max-attempts count and the retake's wipe-and-create - // from interleaving with an in-flight answer save (a reader). Dropped - // before the response reads — they only describe the row. - let guard = EXAM_LOCK.write().await; - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - ensure_sittable(&exam)?; - ensure_student(&user)?; - ensure_enrolled(&exam, user.get_id(), &st.db).await?; - crate::service::course::require_open(&st.db, &course_of(&exam, &st.db).await?).await?; - let now = Timestamp::now(); - if let Some(starts_at) = exam.get_starts_at() - && now < starts_at - { - return Err(AppError::Conflict("the exam has not started yet")); - } - if let Some(ends_at) = exam.get_ends_at() - && now >= ends_at - { - return Err(AppError::Conflict("the exam has already ended")); - } - - // A retake no longer wipes the prior sitting — each attempt's answers, - // drawings, and marks stay put at their own seq (per-attempt history), so - // there are no orphaned blobs to GC here. The exam-delete cascade still - // cleans every sitting's blobs. - let (attempt, created) = ExamAttempt::start(&exam, user.get_id(), &st.db).await?; - drop(guard); + let (exam, attempt, created) = + exam_attempt::start_attempt(&st.db, &ExamId::from_key(&id), &user).await?; let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) .await? .map(|r| r.get_mark()); let (answered, question_count) = attempt_progress(exam.get_id(), user.get_id(), attempt.get_seq(), &st.db).await?; - let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?; + let used = exam_attempt::attempts_used(&st.db, exam.get_id(), user.get_id()).await?; let people = PersonRef::map_of(&[&user]); let status = if created { StatusCode::CREATED @@ -249,7 +192,7 @@ pub(crate) async fn my_attempt( let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) + let attempt = exam_attempt::read_latest_for_user(&st.db, exam.get_id(), user.get_id()) .await? .ok_or(AppError::NotFound)?; let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) @@ -257,7 +200,7 @@ pub(crate) async fn my_attempt( .map(|r| r.get_mark()); let (answered, question_count) = attempt_progress(exam.get_id(), user.get_id(), attempt.get_seq(), &st.db).await?; - let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?; + let used = exam_attempt::attempts_used(&st.db, exam.get_id(), user.get_id()).await?; let people = PersonRef::map_of(&[&user]); Ok(Json(AttemptResponse::new( &attempt, @@ -295,29 +238,13 @@ pub(crate) async fn finish_attempt( let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) - .await? - .ok_or(AppError::NotFound)?; - if attempt.get_finished_at().is_some() { - return Err(AppError::Conflict("the attempt is already submitted")); - } - let now = Timestamp::now(); - if let Some(deadline) = attempt.deadline(&exam) - && now >= deadline - { - return Err(AppError::Conflict("time is up — the attempt has expired")); - } - crate::service::course::require_open(&st.db, &course_of(&exam, &st.db).await?).await?; - - // Deliberately no rejoin check: a student locked out of the room may - // still submit what they saved — finishing answers nothing new. - let finished = attempt.finish(&st.db).await?; + let finished = exam_attempt::finish_attempt(&st.db, &exam, user.get_id()).await?; let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) .await? .map(|r| r.get_mark()); let (answered, question_count) = attempt_progress(exam.get_id(), user.get_id(), finished.get_seq(), &st.db).await?; - let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?; + let used = exam_attempt::attempts_used(&st.db, exam.get_id(), user.get_id()).await?; let people = PersonRef::map_of(&[&user]); Ok(Json(AttemptResponse::new( &finished, @@ -405,7 +332,7 @@ pub(crate) async fn live_snapshot( // many they've used. let mut attempts: HashMap = HashMap::new(); let mut used: HashMap = HashMap::new(); - for attempt in ExamAttempt::list_for_exam(exam.get_id(), db).await? { + for attempt in exam_attempt::list_for_exam(db, exam.get_id()).await? { let key = attempt.get_user().key().to_string(); *used.entry(key.clone()).or_insert(0) += 1; match attempts.entry(key) { @@ -533,7 +460,7 @@ pub(crate) async fn exam_live( let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; + let course = exam_attempt::course_of(&exam, &st.db).await?; if !can_manage_course(&course, &user) { return Err(AppError::Forbidden( "only the course creator, an assigned teacher, or a manager/admin can monitor this exam", @@ -619,144 +546,6 @@ pub(crate) struct AnswerSavedResponse { updated_at: i64, } -/// The caller's latest attempt provided it is still writable, or the error -/// that says why not: no attempt yet (404 — start it first), already -/// submitted (409), deadline passed (409). One gate shared by REST saves and -/// the WebSocket room. -pub(crate) async fn writable_attempt( - exam: &Exam, - user: &UserId, - db: &Database, -) -> Result { - let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user, db) - .await? - .ok_or(AppError::NotFound)?; - match attempt.status(exam, Timestamp::now()) { - AttemptStatus::Submitted => Err(AppError::Conflict("the attempt is already submitted")), - AttemptStatus::Expired => Err(AppError::Conflict("time is up — the attempt has expired")), - AttemptStatus::InProgress => Ok(attempt), - } -} - -/// A 409 when the student has walked out of the exam room and the exam's -/// rejoin door is closed: no more answering (from anywhere) until the teacher -/// flips `allow_rejoin` back on. Finishing is deliberately exempt — see -/// `finish_attempt`. -pub(crate) fn check_rejoin(exam: &Exam, attempt: &ExamAttempt) -> Result<(), AppError> { - if attempt.get_left_at().is_some() && !exam.get_allow_rejoin() { - return Err(AppError::Conflict( - "you left the exam and rejoin is closed — ask your teacher to reopen it", - )); - } - Ok(()) -} - -/// Save one answer inside the caller's in-progress attempt — the whole write -/// path (attempt gate, rejoin gate, question lookup, kind check, upsert). The -/// REST handler saves into the latest sitting via this; the WebSocket room -/// resolves its own sitting first and shares [`save_answer_in`], so the two -/// can never drift. -pub(crate) async fn save_answer_checked( - exam: &Exam, - user: &UserId, - question_id: &str, - selected: Option, - text: Option, - db: &Database, -) -> Result { - // Reader lease of [`EXAM_LOCK`]: the writable gate and the upsert are - // one unit, or a retake's wipe-and-create (a writer) slips in between - // and this stale save lands on the fresh blank sheet. - // - // The lease covers the gate *and* the upsert here, so a retake cannot - // interleave with this path at all. The accepted late-save race lives in - // the exam-room socket instead, which writes into the sitting it joined - // with — a value chosen before any lease is taken. See - // [`crate::web::exam_ws`]. - let _guard = EXAM_LOCK.read().await; - let attempt = writable_attempt(exam, user, db).await?; - save_answer_in(exam, &attempt, question_id, selected, text, db).await -} - -/// The tail of the answer write path, given the sitting to write in: the -/// student wall and the enrollment wall (a promotion out of `student` or an -/// unenrollment closes the sheet, mid-exam included), the rejoin gate, the -/// archived-term gate, the question lookup, and the upsert. -/// -/// The archived-term refusal sits here because this is the single funnel every -/// answer write passes: REST `POST /exams/{id}/attempt/answers` (via -/// [`save_answer_checked`]) *and* every `answer` frame of the exam-room -/// WebSocket ([`crate::web::exam_ws`]). The answer-image writes are the only -/// answer-side writes outside it, and carry their own guard. -pub(crate) async fn save_answer_in( - exam: &Exam, - attempt: &ExamAttempt, - question_id: &str, - selected: Option, - text: Option, - db: &Database, -) -> Result { - ensure_student_now(attempt.get_user(), db).await?; - ensure_enrolled(exam, attempt.get_user(), db).await?; - check_rejoin(exam, attempt)?; - crate::service::course::require_open(db, &course_of(exam, db).await?).await?; - let question = question_of_exam(exam.get_id(), question_id, db).await?; - ExamAnswer::save( - &question, - attempt.get_user(), - attempt.get_seq(), - selected, - text, - db, - ) - .await -} - -/// A 403 unless `user` is a student. Sitting an exam is a student action — -/// teachers and above run exams, they never take them — so the sit paths -/// (start, room, save) enforce it on the *current* role. Checking the live -/// role, not just enrollment, closes the gap a mid-exam promotion would open -/// and neutralizes any stale non-student enrollment. Reading one's own attempt -/// and finishing stay ungated: a non-student has no attempt to read, and -/// finishing only submits work already saved. -pub(crate) fn ensure_student(user: &User) -> Result<(), AppError> { - if user.get_role() != Role::Student { - return Err(AppError::Forbidden("only students can sit exams")); - } - Ok(()) -} - -/// The answer path's live edition of [`ensure_student`]: re-read the row and -/// judge the *current* role, exactly like the enrollment wall beside it. Both -/// save paths run through here (REST per request, the exam room per message), -/// so a promotion out of `student` mid-exam closes the sheet on the very next -/// save — the room's door check is not the last word for a socket that -/// outlives the role. -pub(crate) async fn ensure_student_now(user: &UserId, db: &Database) -> Result<(), AppError> { - let user = User::read(user, db).await?.ok_or(AppError::Unauthorized)?; - ensure_student(&user) -} - -/// A 403 unless `user` is enrolled in the exam's course — the same wall the -/// exam room checks at its door, re-applied to the sitting's content paths so -/// an unenrollment mid-exam cuts them too. Finishing stays exempt: like the -/// rejoin lock, submitting what's already saved writes nothing new. -pub(crate) async fn ensure_enrolled( - exam: &Exam, - user: &UserId, - db: &Database, -) -> Result<(), AppError> { - if Enrollment::read_for_user(exam.get_course(), user, db) - .await? - .is_none() - { - return Err(AppError::Forbidden( - "you are not enrolled in this exam's course", - )); - } - Ok(()) -} - /// The exam's questions as the sitting student sees them: `correct` stripped, /// their own saved answers embedded — the latest sitting's, since a retake /// starts from a blank sheet. Requires enrollment in the exam's course (the @@ -785,11 +574,11 @@ pub(crate) async fn attempt_questions( let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - ensure_enrolled(&exam, user.get_id(), &st.db).await?; + exam_attempt::ensure_enrolled(&exam, user.get_id(), &st.db).await?; // The question list is for sitting students; without an attempt there is // nothing to sit behind — and no early peek at the questions. The embedded // answers are the *current* sitting's only, so the seq scopes the reads. - let seq = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) + let seq = exam_attempt::read_latest_for_user(&st.db, exam.get_id(), user.get_id()) .await? .ok_or(AppError::NotFound)? .get_seq(); @@ -844,7 +633,7 @@ pub(crate) async fn attempt_questions( /// promotion out of `student`) mid-exam closes the sheet. Rejected once the /// attempt is submitted or its deadline has passed — /// the server clock, not the client's, is the judge — and rejected while the -/// student has left the exam room with the exam's rejoin door closed. +/// student has left the exam room with the rejoin door closed. #[utoipa::path( post, path = "/{id}/attempt/answers", @@ -871,14 +660,13 @@ pub(crate) async fn save_answer( let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - ensure_student(&user)?; - let answer = save_answer_checked( + let answer = exam_attempt::save_answer_checked( + &st.db, &exam, - user.get_id(), + &user, &req.question_id, req.selected, req.text, - &st.db, ) .await?; Ok(Json(AnswerSavedResponse { @@ -920,7 +708,7 @@ pub(crate) async fn attempt_answers( let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; + let course = exam_attempt::course_of(&exam, &st.db).await?; if !can_manage_course(&course, &user) { return Err(AppError::Forbidden( "only the course creator, an assigned teacher, or a manager/admin can read answer sheets", @@ -930,7 +718,7 @@ pub(crate) async fn attempt_answers( // No attempt means no answer sheet — a 404, not an empty one. This grading // view shows the *latest* sitting; prior sittings live under the // per-attempt history endpoints. - let seq = ExamAttempt::read_latest_for_user(exam.get_id(), &target, &st.db) + let seq = exam_attempt::read_latest_for_user(&st.db, exam.get_id(), &target) .await? .ok_or(AppError::NotFound)? .get_seq(); diff --git a/src/web/exams/images.rs b/src/web/exams/images.rs index a8c161f..9faf82e 100644 --- a/src/web/exams/images.rs +++ b/src/web/exams/images.rs @@ -1,5 +1,10 @@ use super::*; +use crate::service::exam_attempt::{ + EXAM_LOCK, check_rejoin, course_of, ensure_enrolled, ensure_student, ensure_student_now, + question_of_exam, read_latest_for_user, writable_attempt, +}; + /// A stored question image's metadata; the bytes come from the image /// endpoints (`GET .../image`, `GET .../choices/{choice_id}/image`). #[derive(Serialize, ToSchema)] @@ -117,7 +122,7 @@ pub(crate) async fn ensure_question_content_visible( return Ok(()); } ensure_enrolled(exam, user.get_id(), &st.db).await?; - ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) + read_latest_for_user(&st.db, exam.get_id(), user.get_id()) .await? .ok_or(AppError::NotFound)?; Ok(()) @@ -595,7 +600,7 @@ pub(crate) async fn get_answer_image( ensure_question_content_visible(&st, &exam, &user).await?; let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; // The caller's current sitting — the drawing belongs to their latest seq. - let seq = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) + let seq = read_latest_for_user(&st.db, exam.get_id(), user.get_id()) .await? .ok_or(AppError::NotFound)? .get_seq(); @@ -642,7 +647,7 @@ pub(crate) async fn get_student_answer_image( let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; // The grader's default view is the latest sitting; per-attempt drawings // come from the history image endpoint. - let seq = ExamAttempt::read_latest_for_user(exam.get_id(), &target, &st.db) + let seq = read_latest_for_user(&st.db, exam.get_id(), &target) .await? .ok_or(AppError::NotFound)? .get_seq(); diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index ea0a0bd..a3244b5 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -16,17 +16,14 @@ use crate::domain::answer_image::AnswerImage; use crate::domain::badge; use crate::domain::bank_question::{BankQuestion, BankQuestionId}; use crate::domain::bank_question_image::BankQuestionImage; -use crate::domain::course::Course; use crate::domain::enrollment::Enrollment; use crate::domain::exam::{ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, ExamSchedule, ExamTitle, }; use crate::domain::exam_answer::{ExamAnswer, auto_score}; -use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt}; use crate::domain::exam_question::{ - Choice, ChoiceId, ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec, - QuestionText, + Choice, ChoiceId, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, }; use crate::domain::exam_result::{ExamResult, Mark}; use crate::domain::note_file::FileContentType; @@ -36,6 +33,7 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::service; +use crate::service::exam_attempt::{EXAM_LOCK, any_for_exam, course_of, read_latest_for_user}; use crate::state::AppState; use super::bank_questions::BankQuestionResponse; @@ -71,35 +69,6 @@ impl Scheduled for Exam { } } -/// Serializes the exam subsystem's cross-record check-then-writes, which -/// `BEGIN…COMMIT` cannot (write skew) — the reasoning in [`crate::db::cap`]. -/// It orders requests, but only around what it wraps — every invariant that -/// could be moved into the database itself has been, so a gap between a read -/// and its write is decided by the store. What is left here needs a -/// cross-record read and a write held together, which no single statement -/// expresses: -/// -/// Read side — the answer saves (REST and the exam room), from the -/// writable-attempt gate through the upsert; the grade write (draft gate -/// through the result upsert); and the exam PATCH, whose mode/re-draft gates -/// count attempts and results. These stay concurrent with each other. -/// -/// Write side — attempt starts alone (the max-attempts count and the retake's -/// answer wipe). So a save can never land on a sheet a retake just wiped, and a -/// mark can never land on an exam mid-flight into hiding. -/// -/// Two rules have left this list. The question freeze gate rides inside each -/// question/image write's own transaction -/// ([`crate::domain::exam_attempt::ExamAttempt::write_unfrozen`]), and the exam PATCH -/// no longer needs the writer lease because its save is a compare-and-set. The -/// subject delete's cascade — the only writer outside attempt starts, paired -/// with the question writes' subject check — is now a conditional statement on -/// the subject's own reference counter -/// ([`crate::domain::subject::Subject::delete`]), which every question create, -/// re-tag and delete moves. -// corner-cut: global RwLock, shard per-exam if save latency ever matters. -pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); - pub fn routes() -> OpenApiRouter { OpenApiRouter::new() // Plain route: OpenApiRouter can't describe a WebSocket upgrade, so @@ -263,14 +232,6 @@ struct ExamStatisticsResponse { max: Option, } -/// The course an exam belongs to. A dangling reference means the course-delete -/// cascade was violated — surface it loudly as a 500, not a user-facing 404. -pub(crate) async fn course_of(exam: &Exam, db: &Database) -> Result { - crate::service::course::read(db, exam.get_course()) - .await? - .ok_or_else(|| AppError::Internal("exam references a missing course".into())) -} - // ---- exams -------------------------------------------------------------- // Exams are created inside a course: `POST /courses/{id}/exams`. @@ -433,7 +394,7 @@ async fn update_exam( "only the course creator, an assigned teacher, or a manager/admin can edit this exam", )); } - crate::service::course::require_open(&st.db, &course).await?; + course.require_open(&st.db).await?; let title = match req.title { Some(ref title) => ExamTitle::try_new(title)?, @@ -500,7 +461,7 @@ async fn update_exam( // land in the gap and leave a sat exam's mode flipped under it. let mode_changed = schedule.get_mode().map(ExamMode::as_str) != exam.get_mode().map(ExamMode::as_str); - if mode_changed && ExamAttempt::any_for_exam(exam.get_id(), &st.db).await? { + if mode_changed && any_for_exam(&st.db, exam.get_id()).await? { return Err(AppError::Conflict( "cannot change the exam mode after attempts have started", )); @@ -510,7 +471,7 @@ async fn update_exam( // transaction re-makes this check and answers with the same error, so a // grade landing after this read still cannot leave a mark on a draft. if draft && !exam.is_draft() { - let sat = ExamAttempt::any_for_exam(exam.get_id(), &st.db).await?; + let sat = any_for_exam(&st.db, exam.get_id()).await?; let graded = !ExamResult::list_for_exam(exam.get_id(), &st.db) .await? .is_empty(); @@ -591,7 +552,7 @@ async fn delete_exam( "only the course creator, an assigned teacher, or a manager/admin can delete this exam", )); } - crate::service::course::require_open(&st.db, &course).await?; + course.require_open(&st.db).await?; // *Writer* lease of [`EXAM_LOCK`] across the whole cascade, blob names // included — the lease `delete_homework` has always held, and its absence // here is what made a sitting able to start inside this delete. Every other @@ -676,7 +637,7 @@ async fn grade( "only the course creator, an assigned teacher, or a manager/admin can grade this exam", )); } - crate::service::course::require_open(&st.db, &course).await?; + course.require_open(&st.db).await?; // Pre-flight: `ExamResult::grade` re-makes this check inside the mark's own // transaction, so a re-draft landing after this read cannot leave a mark on // a hidden exam. @@ -740,7 +701,7 @@ async fn grade( // The mark lands on the student's current sitting; the latest seq is the // grade-of-record. An offline-graded exam has no sitting — grade its base // seq (1). - let seq = ExamAttempt::read_latest_for_user(&exam_id, &target, &st.db) + let seq = read_latest_for_user(&st.db, &exam_id, &target) .await? .map_or(1, |a| a.get_seq()); let result = ExamResult::grade( @@ -883,7 +844,7 @@ async fn remove_result( "only the course creator, an assigned teacher, or a manager/admin can remove results", )); } - crate::service::course::require_open(&st.db, &course).await?; + course.require_open(&st.db).await?; let removed = ExamResult::remove( exam.get_id(), &UserId::from_key(&target), diff --git a/src/web/exams/questions.rs b/src/web/exams/questions.rs index 9515435..0294883 100644 --- a/src/web/exams/questions.rs +++ b/src/web/exams/questions.rs @@ -1,5 +1,8 @@ use super::*; +use crate::service::exam_attempt; +use crate::service::exam_attempt::question_of_exam; + // ---- questions -------------------------------------------------------------- // Teachers author the question list before the exam runs; it freezes the // moment anyone starts an attempt, so every student sits the same exam. @@ -138,7 +141,7 @@ pub(crate) async fn ensure_questions_editable( exam: &ExamId, db: &Database, ) -> Result<(), AppError> { - if ExamAttempt::any_for_exam(exam, db).await? { + if exam_attempt::any_for_exam(db, exam).await? { return Err(AppError::Conflict( "cannot change questions after attempts have started", )); @@ -146,22 +149,6 @@ pub(crate) async fn ensure_questions_editable( Ok(()) } -/// The question, provided it belongs to `exam` — a qid under someone else's -/// exam is a plain 404, not a leak. -pub(crate) async fn question_of_exam( - exam: &ExamId, - qid: &str, - db: &Database, -) -> Result { - let question = ExamQuestion::read(&ExamQuestionId::from_key(qid), db) - .await? - .ok_or(AppError::NotFound)?; - if question.get_exam() != exam { - return Err(AppError::NotFound); - } - Ok(question) -} - /// The question's option named by `choice_id` — a 400 for a text question or an /// id the question doesn't have, so an option picture can only ever be /// addressed through an option that exists. diff --git a/src/web/exams/review.rs b/src/web/exams/review.rs index c539935..a4dfe8a 100644 --- a/src/web/exams/review.rs +++ b/src/web/exams/review.rs @@ -1,5 +1,10 @@ use super::*; +use crate::domain::exam_attempt::AttemptStatus; +use crate::service::exam_attempt::{ + course_of, list_for_user, list_unfinished_for_user, question_of_exam, +}; + // ---- per-attempt history ---------------------------------------------------- // The grading views above show the latest sitting; these expose every prior // sitting a re-taking student left behind. Same wall as grading: teacher+ who @@ -210,7 +215,7 @@ pub(crate) async fn reviewable_exam( if !exam.get_allow_review() { return Err(AppError::Forbidden("review not enabled for this exam")); } - let attempts = ExamAttempt::list_for_user(exam.get_id(), user.get_id(), &st.db).await?; + let attempts = list_for_user(&st.db, exam.get_id(), user.get_id()).await?; let now = Timestamp::now(); if attempts .first() @@ -221,7 +226,7 @@ pub(crate) async fn reviewable_exam( )); } // The same three conditions `POST /exams/{id}/attempt` starts a sitting - // under (`ensure_sittable` + the window + `ExamAttempt::start`'s limit + // under (`ensure_sittable` + the window + `exam_attempt::start`'s limit // check), minus the caller's role and enrollment: those bar the sitting // without making the key any safer to hand out, and a student dropped from // the course after being marked should still read their own review back. @@ -262,7 +267,7 @@ async fn live_elsewhere( ) -> Result, AppError> { let now = Timestamp::now(); let mut live = Vec::new(); - for attempt in ExamAttempt::list_unfinished_for_user(user.get_id(), &st.db).await? { + for attempt in list_unfinished_for_user(&st.db, user.get_id()).await? { let Some(other) = Exam::read(attempt.get_exam(), &st.db).await? else { continue; }; diff --git a/src/web/homework.rs b/src/web/homework.rs index 38edeb1..dd767b3 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -46,7 +46,7 @@ use super::{ /// Serializes the homework subsystem's cross-record check-then-writes, which /// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as -/// [`crate::web::exams::EXAM_LOCK`]. Every lease below is held across the +/// [`crate::service::exam_attempt::EXAM_LOCK`]. Every lease below is held across the /// database write it guards, so within this one process it does order a full /// round trip — but the freeze no longer *rests* on that: a graded submission /// used to stay unedited only because the "no grade yet" read and the write it @@ -476,7 +476,7 @@ async fn delete_homework( } /// A 403 unless `user` is enrolled in `course` — the homework twin of the exam -/// sitting wall ([`super::exams::ensure_enrolled`], which is `Exam`-shaped). +/// sitting wall ([`crate::service::exam_attempt::ensure_enrolled`], which is `Exam`-shaped). /// Submitting is course content, so leaving the course closes it; re-checked on /// every submission and file write, so an unenrollment mid-task bites the next. async fn ensure_enrolled(course: &CourseId, user: &UserId, db: &Database) -> Result<(), AppError> { @@ -495,7 +495,7 @@ async fn ensure_enrolled(course: &CourseId, user: &UserId, db: &Database) -> Res /// 1. Exact `Student` on the *live* role. Teachers assign homework, they never /// hand it in; the `RequireStudent` extractor's ≥Student would wave a /// promoted teacher through, so this checks the role `CurrentUser` read for -/// this very request — the same reasoning as [`super::exams::ensure_student`]. +/// this very request — the same reasoning as [`crate::service::exam_attempt::ensure_student`]. /// 2. Current enrollment in the course. /// 3. The audience check: a student a subset homework does not name gets a 404, /// never a 403, so a subset assignment never leaks to those left out (the diff --git a/tests/integration.rs b/tests/integration.rs index 55ec1af..632284a 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -15,6 +15,7 @@ use hezarfen_backend::constant::{ BANK_VISIBILITY_SCHOOL, MAX_BOARD_STROKES, MAX_BOARDS_PER_CREATOR, MAX_COURSE_NOTE_FILES, MAX_EPOCH_STROKES, MAX_FEE_PLAN_ASSIGN_STUDENTS, }; +use hezarfen_backend::db::exam_attempt::any_for_exam; use hezarfen_backend::db::session; use hezarfen_backend::domain::board::{Board, BoardId}; use hezarfen_backend::domain::board_stroke::{BoardStroke, BoardStrokeId}; @@ -24,7 +25,6 @@ use hezarfen_backend::domain::course::CourseId; use hezarfen_backend::domain::course_note::CourseNoteId; use hezarfen_backend::domain::course_note_file::CourseNoteFileId; use hezarfen_backend::domain::exam::ExamId; -use hezarfen_backend::domain::exam_attempt::ExamAttempt; use hezarfen_backend::domain::rag_output::RagOutput; use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::domain::user::{Password, User, UserId, Username}; @@ -7887,11 +7887,7 @@ async fn attempts_cascade_with_exam_and_course_deletion() { ) .await; assert_eq!(res.status, StatusCode::CREATED); - assert!( - ExamAttempt::any_for_exam(&ExamId::from_key(&exam), &db) - .await - .unwrap() - ); + assert!(any_for_exam(&db, &ExamId::from_key(&exam)).await.unwrap()); let res = send( &app, "DELETE", @@ -7901,11 +7897,7 @@ async fn attempts_cascade_with_exam_and_course_deletion() { ) .await; assert_eq!(res.status, StatusCode::NO_CONTENT); - assert!( - !ExamAttempt::any_for_exam(&ExamId::from_key(&exam), &db) - .await - .unwrap() - ); + assert!(!any_for_exam(&db, &ExamId::from_key(&exam)).await.unwrap()); // Deleting the whole course cascades through its exams' attempts too. let exam = scheduled_exam(&app, &teacher, &course, schedule).await; @@ -7928,11 +7920,7 @@ async fn attempts_cascade_with_exam_and_course_deletion() { ) .await; assert_eq!(res.status, StatusCode::NO_CONTENT); - assert!( - !ExamAttempt::any_for_exam(&ExamId::from_key(&exam), &db) - .await - .unwrap() - ); + assert!(!any_for_exam(&db, &ExamId::from_key(&exam)).await.unwrap()); } /// An `open` exam is sittable anytime — no window, no deadline — and diff --git a/tests/regress_course_delete.rs b/tests/regress_course_delete.rs index 105f940..5eabdfe 100644 --- a/tests/regress_course_delete.rs +++ b/tests/regress_course_delete.rs @@ -28,9 +28,9 @@ use common::{ login_as, me_id, send, unenroll, }; use hezarfen_backend::db::course; +use hezarfen_backend::db::exam_attempt::list_for_exam; use hezarfen_backend::domain::course::CourseId; use hezarfen_backend::domain::exam::ExamId; -use hezarfen_backend::domain::exam_attempt::ExamAttempt; use serde_json::json; /// Delete `course` the way the handler would, minus its `EXAM_LOCK` lease. @@ -257,7 +257,7 @@ async fn an_attempt_started_inside_a_course_delete_never_outlives_it() { ); // Stored state is the whole verdict; a response code is not evidence. assert_eq!( - ExamAttempt::list_for_exam(&ExamId::from_key(&exam), &db) + list_for_exam(&db, &ExamId::from_key(&exam)) .await .unwrap() .len(), diff --git a/tests/regress_exam_delete.rs b/tests/regress_exam_delete.rs index 5495cee..b768e07 100644 --- a/tests/regress_exam_delete.rs +++ b/tests/regress_exam_delete.rs @@ -18,8 +18,8 @@ mod common; use axum::http::StatusCode; use common::{app_and_db, create_exam_with, enroll, id_of, login_as, me_id, send}; +use hezarfen_backend::db::exam_attempt::list_for_exam; use hezarfen_backend::domain::exam::ExamId; -use hezarfen_backend::domain::exam_attempt::ExamAttempt; use serde_json::json; /// The delete is held open for a second *after* the exam row is gone but @@ -122,7 +122,7 @@ async fn an_attempt_started_inside_a_delete_never_outlives_the_exam() { // Stored state is the whole verdict; a response code is not evidence. let id = ExamId::from_key(&exam); - sittings += ExamAttempt::list_for_exam(&id, &db).await.unwrap().len(); + sittings += list_for_exam(&db, &id).await.unwrap().len(); } assert_eq!(sittings, 0, "a sitting outlived its exam"); }