From 606085def8a5309407f089f779e97446fd0eac52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 11 Sep 2026 09:58:33 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=B9=20chore:=20split=20exam=20into=20d?= =?UTF-8?q?omain/db/service=20layers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/db/course.rs | 2 +- src/db/exam.rs | 1109 ++++++++++++++++++++++++ src/db/exam_attempt.rs | 6 +- src/db/mod.rs | 1 + src/domain/answer_image.rs | 7 +- src/domain/bank_question.rs | 10 +- src/domain/course_session.rs | 2 +- src/domain/exam.rs | 1145 +------------------------ src/domain/exam_answer.rs | 14 +- src/domain/exam_question.rs | 4 +- src/domain/homework.rs | 4 +- src/domain/question_image.rs | 5 +- src/domain/subject.rs | 19 +- src/service/course.rs | 5 +- src/service/exam.rs | 287 +++++++ src/service/exam_attempt.rs | 6 +- src/service/mod.rs | 1 + src/web/courses.rs | 28 +- src/web/exam_ws.rs | 15 +- src/web/exams/attempts.rs | 12 +- src/web/exams/images.rs | 14 +- src/web/exams/mod.rs | 281 ++---- src/web/exams/questions.rs | 14 +- src/web/exams/review.rs | 6 +- src/web/marks.rs | 2 +- tests/regress_course_child_orphans.rs | 20 +- 26 files changed, 1606 insertions(+), 1413 deletions(-) create mode 100644 src/db/exam.rs create mode 100644 src/service/exam.rs diff --git a/src/db/course.rs b/src/db/course.rs index 4c08f7e..979c459 100644 --- a/src/db/course.rs +++ b/src/db/course.rs @@ -261,7 +261,7 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App /// **Bank templates** survive it — they are a separate, reusable library /// spanning every course — so their `source_exam` and `subject` links are /// cleared instead, in this same transaction, exactly as -/// [`crate::domain::exam::Exam::delete`] and +/// [`crate::db::exam::delete`] and /// [`crate::domain::subject::Subject::delete`] clear them one level down. /// Deleting a course must leave the bank where deleting each of its exams /// and subjects by hand would have left it, or a template is left pointing diff --git a/src/db/exam.rs b/src/db/exam.rs new file mode 100644 index 0000000..e82f70e --- /dev/null +++ b/src/db/exam.rs @@ -0,0 +1,1109 @@ +//! The `exam` table: row reads and listings, the count-and-create that pins +//! the exam to a live course row, the compare-and-set every PATCH writes +//! through, and the cascading delete. The PATCH re-derive and the delete's +//! blob-key collection live in [`crate::service::exam`]. + +use surrealdb::types::{RecordId, SurrealValue}; + +use crate::constant::ENROLLMENT_COUNT_FIELD; +use crate::database::{Database, transaction_with_retry}; +use crate::db::cap; +use crate::domain::course::CourseId; +use crate::domain::exam::{ + Exam, ExamAttemptLimit, ExamDescription, ExamId, ExamKind, ExamSchedule, ExamTitle, + redraft_error, +}; +use crate::domain::user::UserId; +use crate::error::AppError; + +#[expect( + clippy::too_many_arguments, + reason = "mirrors the sibling entities' create(field, field, ..) shape" +)] +pub async fn create( + db: &Database, + creator: &UserId, + course: &CourseId, + title: ExamTitle, + description: ExamDescription, + kind: ExamKind, + schedule: ExamSchedule, + max_attempts: ExamAttemptLimit, + allow_rejoin: bool, + allow_review: bool, + draft: bool, +) -> Result { + let exam = Exam { + id: ExamId::generate(), + creator: creator.clone(), + course: course.clone(), + title, + description, + kind, + mode: schedule.mode, + starts_at: schedule.starts_at, + ends_at: schedule.ends_at, + duration_ms: schedule.duration_ms, + max_attempts, + allow_rejoin, + allow_review, + draft, + result_count: None, + }; + // The course row is *written* (bumped and put back), not read: a plain + // read does not survive `Course::delete`'s window, and an exam that + // outlives its course is unreachable for good — every route to one goes + // through `course_of`, which answers a 500 no delete can clear, while + // `GET /exams` still lists it. See [`cap::touch_and_create`]. + cap::touch_and_create( + &course.record(), + ENROLLMENT_COUNT_FIELD, + &exam.id.record(), + &exam, + db, + ) + .await? + .ok_or(AppError::NotFound) +} + +pub async fn read(db: &Database, id: &ExamId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +pub async fn list_all(db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM exam ORDER BY id DESC") + .await? + .check()?; + Ok(result.take::>(0)?) +} + +pub async fn list_for_course(db: &Database, course: &CourseId) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM exam WHERE course = $course ORDER BY id DESC") + .bind(("course", course.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Every exam of every course in `courses` (one query) — the catalog as one +/// user sees it. +pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result, AppError> { + if courses.is_empty() { + return Ok(Vec::new()); + } + let records: Vec = courses.iter().map(CourseId::record).collect(); + let mut result = db + .query("SELECT * FROM exam WHERE course IN $courses ORDER BY id DESC") + .bind(("courses", records)) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +// `course` is deliberately not updatable — moving an exam between courses +// would strand results of students not enrolled in the target course. +#[expect( + clippy::too_many_arguments, + reason = "mirrors the sibling entities' update(field, field, ..) shape" +)] +/// Save the merged exam, but only while the row still reads as the +/// snapshot the caller merged over — `None` means a concurrent PATCH +/// landed in between and nothing was written: re-read, re-merge, retry. +/// +/// Every column this write replaces is in the guard, which is what makes +/// the whole-row `CONTENT` save safe without a lock held across the +/// handler's read: the compare-and-set refuses precisely when that save +/// would have reverted somebody. `course`/`creator` are not editable and +/// ride along unchanged. Same shape as +/// [`crate::db::settings::save_if_unchanged`]. +pub async fn update_if_unchanged( + db: &Database, + mut expected: Exam, + title: ExamTitle, + description: ExamDescription, + kind: ExamKind, + schedule: ExamSchedule, + max_attempts: ExamAttemptLimit, + allow_rejoin: bool, + allow_review: bool, + draft: bool, +) -> Result, AppError> { + // Re-drafting hides an exam: it must be refused while any sitting or + // mark exists, and that check has to be *in this transaction*. Holding + // it under a lock outside would only order the two writers inside one + // process — and it did not even do that, since grading takes the reader + // lease this write does. + let redraft = draft && !expected.draft; + let was = ( + expected.title.clone(), + expected.description.clone(), + expected.kind.clone(), + expected.mode.clone(), + expected.starts_at, + expected.ends_at, + expected.duration_ms, + expected.max_attempts, + expected.allow_rejoin, + expected.allow_review, + expected.draft, + ); + expected.title = title; + expected.description = description; + expected.kind = kind; + expected.mode = schedule.mode; + expected.starts_at = schedule.starts_at; + expected.ends_at = schedule.ends_at; + expected.duration_ms = schedule.duration_ms; + expected.max_attempts = max_attempts; + expected.allow_rejoin = allow_rejoin; + expected.allow_review = allow_review; + expected.draft = draft; + // whole-row-save-ok: the WHERE below pins every column this replaces to + // the caller's snapshot, so no concurrent write can be reverted + // + // Sent through the retry loop, not a bare `query`: this row now has a + // hot writer. Every answer save touches it to tie itself to the exam + // ([`crate::domain::exam_answer::ExamAnswer::save`]), so a teacher + // flipping `allow_rejoin` mid-exam can lose a round to a student + // typing — and a lost round is a re-send, never the 500 a bare `?` on + // the conflict would have answered. Re-sending is sound because the + // statement is a compare-and-set: the second pass carries the same + // pinned snapshot, so it lands only if the row is still what the caller + // read, and a rival that really moved it is refused as it was before. + // Admissible for the loop — an `UPDATE`, an `IF`/`THROW` and a `SELECT` + // can never answer "already exists". + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; + IF $redraft AND ( + array::len((SELECT VALUE id FROM exam_attempt WHERE exam = $id LIMIT 1)) > 0 + OR array::len((SELECT VALUE id FROM exam_result WHERE exam = $id LIMIT 1)) > 0 + ) { THROW 'exam_redraft' }; + UPDATE $id CONTENT $new + WHERE title = $was_title AND description = $was_description + AND kind = $was_kind AND mode = $was_mode + AND starts_at = $was_starts AND ends_at = $was_ends + AND duration_ms = $was_duration + AND max_attempts = $was_max_attempts + AND allow_rejoin = $was_allow_rejoin + AND allow_review = $was_allow_review + AND draft = $was_draft + AND (result_count ?? 0) = $was_results + RETURN AFTER; + COMMIT TRANSACTION;", + &[ + ("redraft".into(), redraft.into_value()), + ("id".into(), expected.id.record().into_value()), + ("was_title".into(), was.0.into_value()), + ("was_description".into(), was.1.into_value()), + ("was_kind".into(), was.2.into_value()), + ("was_mode".into(), was.3.into_value()), + ("was_starts".into(), was.4.into_value()), + ("was_ends".into(), was.5.into_value()), + ("was_duration".into(), was.6.into_value()), + ("was_max_attempts".into(), was.7.into_value()), + ("was_allow_rejoin".into(), was.8.into_value()), + ("was_allow_review".into(), was.9.into_value()), + ("was_draft".into(), was.10.into_value()), + // The mark counter is pinned like every other column this write + // replaces, and for a sharper reason: a grade increments it, so + // pinning it is what makes "this exam had no marks" — the gate + // the handler refuses a kind change on — true at *write* time + // and not merely at read time. A mark landing in between + // refuses the save. + ( + "was_results".into(), + expected.result_count.unwrap_or(0).into_value(), + ), + ("new".into(), expected.into_value()), + ], + &["exam_redraft"], + ) + .await?; + // An aborted transaction errors every slot; only the THROW's names the + // marker (the [`crate::db::exam_attempt::write_unfrozen`] treatment). + if errors + .values() + .any(|error| error.to_string().contains("exam_redraft")) + { + return Err(redraft_error()); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // BEGIN and the IF take a slot each. + Ok(result.take::>(2)?.into_iter().next()) +} + +/// Delete the exam and cascade-remove its result, attempt, question, +/// answer, question-image, and answer-image rows — all in one transaction, +/// so a failure can't leave an emptied-out exam shell behind. The image +/// *blobs* (question and answer) are the web layer's to remove — it collects +/// their names before calling this. +/// +/// Bank templates saved out of this exam survive it — they are a separate, +/// reusable library — so only their `source_exam` provenance link is cleared, +/// in the same transaction, never left pointing at a dead exam. +/// +/// The questions about to be cascaded each hold a reference on their +/// subject, which is what keeps that subject from being deleted under them. +/// They are given back in this same transaction, counted per subject, so +/// deleting an exam frees its subjects for deletion and nothing else does. +/// The marks give their *kind* references back the same way, and it has to +/// be the same way: counted outside the transaction, a mark deleted by a +/// concurrent `remove_result` in the gap would be released twice — once by +/// each — which on a kind another exam still uses reads as one mark too +/// few, and that is a kind wrongly free to leave the settings. +pub async fn delete(db: &Database, target: Exam) -> Result { + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; + FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result + WHERE exam = $ex GROUP BY kind) ?? []) { + UPDATE type::record('kind_ref', $row.kind) SET count = + math::max([(count ?? 0) - $row.n, 0]) + }; + DELETE exam_result WHERE exam = $ex; + DELETE exam_attempt WHERE exam = $ex; + DELETE exam_answer WHERE exam = $ex; + DELETE answer_image WHERE exam = $ex; + DELETE question_image WHERE exam = $ex; + FOR $row IN ((SELECT subject, count() AS n FROM exam_question + WHERE exam = $ex GROUP BY subject) ?? []) { + UPDATE $row.subject SET exam_question_count = + math::max([(exam_question_count ?? 0) - $row.n, 0]) + }; + DELETE exam_question WHERE exam = $ex; + UPDATE bank_question SET source_exam = NONE WHERE source_exam = $ex; + LET $before = (DELETE $ex RETURN BEFORE); + RETURN $before; + COMMIT TRANSACTION;", + &[("ex".into(), target.id.record().into_value())], + // No THROW of its own: an unconditional cascade, so the only error + // worth telling apart is a lost round, and `check()` — which took + // the *first* error in the batch — could not. It reported a + // sibling's "not executed" and made a retryable round a 500. + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The deleted row comes back through the transaction's trailing + // `RETURN`, never a hand-counted slot: the old `take(8)` turned a + // successful delete into a 404 the moment a cascade statement was + // inserted above it (it already had to be bumped once). `RETURN` is + // always the last statement before `COMMIT`, so its slot is derived + // from the statement count and every insertion above it shifts it + // along. `num_statements` counts BEGIN and COMMIT too, hence -2. + let slot = result.num_statements().saturating_sub(2); + let deleted: Option = result.take::>(slot)?.into_iter().next(); + deleted.ok_or(AppError::NotFound) +} +#[cfg(test)] +use crate::domain::settings::ExamKindDef; + +/// 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 +/// [`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)] +pub(crate) async fn published_exam(db: &Database) -> Exam { + let allowed: Vec = crate::domain::settings::Settings::defaults() + .get_exam_kinds() + .to_vec(); + create( + db, + &UserId::generate(), + &crate::db::course::a_test_course(db).await, + ExamTitle::try_new("midterm").unwrap(), + ExamDescription::try_new("").unwrap(), + ExamKind::try_new("midterm", &allowed).unwrap(), + ExamSchedule::try_new(None, None, None, None).unwrap(), + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + false, + ) + .await + .unwrap() +} + +#[cfg(test)] +mod tests { + use super::*; + + use super::published_exam as published; + + use crate::constant::EXAM_TABLE; + use crate::domain::exam::{ExamDuration, ExamMode}; + use crate::domain::settings::ExamKindDef; + use crate::domain::timestamp::Timestamp; + use crate::error::ValidationError; + + /// An exam must not outlive the course it belongs to. It is the worst of + /// the three children `Course::delete` used to leave behind: every exam + /// route funnels through `course_of`, which answers + /// `Internal("exam references a missing course")`, so an orphan **500s + /// forever** on `GET`/`PATCH`/`DELETE /exams/{id}` — undeletable — while + /// [`crate::db::exam::list_all`] still hands it to every manager+ on `GET /exams`. + /// + /// [`create`] therefore *writes* the course row rather than reading + /// it ([`cap::touch_and_create`]); the harness and the window it races in + /// are documented on + /// [`crate::db::course::assert_no_child_outlives_a_course_delete`]. + /// Mutation-tested: with the bare `db.create` this shipped with, all four + /// rounds orphan. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn an_exam_never_outlives_its_course() { + fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle> { + tokio::spawn(async move { + let kinds = crate::domain::settings::Settings::defaults() + .get_exam_kinds() + .to_vec(); + create( + &db, + &UserId::generate(), + &course, + ExamTitle::try_new("quiz").unwrap(), + ExamDescription::try_new("").unwrap(), + ExamKind::try_new("quiz", &kinds).unwrap(), + ExamSchedule::try_new(None, None, None, None).unwrap(), + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + false, + ) + .await + .map(|_| ()) + }) + } + crate::db::course::assert_no_child_outlives_a_course_delete( + "exam_orphan_race", + EXAM_TABLE, + make, + ) + .await; + } + + fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) { + ( + exam.get_title().clone(), + exam.get_description().clone(), + exam.get_kind().clone(), + ExamSchedule::try_new(None, None, None, None).unwrap(), + ) + } + + /// The bite test for the compare-and-set that replaced the writer lease on + /// `PATCH /exams/{id}`: a merge built on a snapshot the row has moved past + /// must be refused (the handler then re-reads and re-merges), never + /// written over somebody else's edit. Asserts the *stored* row. + #[tokio::test] + async fn a_merge_built_on_a_stale_snapshot_is_refused() { + let db = crate::database::init_mem().await.unwrap(); + let stale = published(&db).await; + let (_, description, kind, schedule) = edit(&stale); + let landed = update_if_unchanged( + &db, + stale.clone(), + ExamTitle::try_new("theirs").unwrap(), + description, + kind, + schedule, + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + false, + ) + .await + .unwrap(); + assert!(landed.is_some(), "the first write is on a fresh snapshot"); + + let (_, description, kind, schedule) = edit(&stale); + let refused = update_if_unchanged( + &db, + stale, + ExamTitle::try_new("mine").unwrap(), + description, + kind, + schedule, + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + false, + ) + .await + .unwrap(); + assert!(refused.is_none(), "a stale merge must not be written"); + let stored = read(&db, landed.unwrap().get_id()).await.unwrap().unwrap(); + assert_eq!(stored.get_title().as_str(), "theirs"); + } + + /// The bite test for the re-draft guard now living *inside* the update's + /// transaction: a mark that lands after the handler's pre-flight gate (the + /// grade path is a lock reader, exactly like this one) must still stop the + /// exam from being hidden. + #[tokio::test] + async fn re_drafting_is_refused_by_the_write_itself_once_a_mark_exists() { + use crate::domain::exam_result::{ExamResult, Mark}; + let db = crate::database::init_mem().await.unwrap(); + let exam = published(&db).await; + let student = UserId::generate(); + ExamResult::grade( + exam.get_id(), + &student, + 1, + Mark::try_new(80).unwrap(), + &UserId::generate(), + exam.get_kind().as_str(), + &db, + ) + .await + .unwrap(); + + let (title, description, kind, schedule) = edit(&exam); + let refused = update_if_unchanged( + &db, + exam.clone(), + title, + description, + kind, + schedule, + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + true, + ) + .await + .expect_err("a graded exam cannot be re-drafted"); + assert!(refused.to_string().contains("back into a draft")); + let stored = read(&db, exam.get_id()).await.unwrap().unwrap(); + assert!(!stored.is_draft(), "nothing may have been written"); + } + + #[tokio::test] + async fn title_is_required() { + assert!(ExamTitle::try_new("midterm").is_ok()); + assert!(ExamTitle::try_new("").is_err()); + assert!(ExamTitle::try_new(" ").is_err()); + } + + #[tokio::test] + async fn description_is_optional() { + assert!(ExamDescription::try_new("").is_ok()); + } + + #[tokio::test] + async fn kind_must_be_in_the_allowed_list() { + let allowed: Vec = crate::domain::settings::Settings::defaults() + .get_exam_kinds() + .to_vec(); + for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] { + assert_eq!(ExamKind::try_new(kind, &allowed).unwrap().as_str(), kind); + } + assert!(ExamKind::try_new("essay", &allowed).is_err()); + assert!(ExamKind::try_new("", &allowed).is_err()); + // A school-defined list swaps the acceptance set wholesale. + let custom = vec![ExamKindDef::try_new("lab", 2).unwrap()]; + assert!(ExamKind::try_new("lab", &custom).is_ok()); + assert!(ExamKind::try_new("midterm", &custom).is_err()); + // Matching is exact, case included — the settings list is the wire + // truth, not a case-folded suggestion. + assert!(ExamKind::try_new("Lab", &custom).is_err()); + } + + #[tokio::test] + async fn mode_must_be_known() { + for mode in ["sync", "async", "open"] { + assert_eq!(ExamMode::try_new(mode).unwrap().as_str(), mode); + } + assert!(ExamMode::try_new("live").is_err()); + } + + #[tokio::test] + async fn attempt_limit_counts_or_never_runs_out() { + let single = ExamAttemptLimit::single(); + assert_eq!(single.as_i64(), 1); + assert!(!single.is_unlimited()); + assert!(single.allows_another(0)); + assert!(!single.allows_another(1)); + + let three = ExamAttemptLimit::try_new(3).unwrap(); + assert!(three.allows_another(2)); + assert!(!three.allows_another(3)); + assert!(!three.allows_another(4)); + + let unlimited = ExamAttemptLimit::try_new(0).unwrap(); + assert!(unlimited.is_unlimited()); + assert!(unlimited.allows_another(0)); + assert!(unlimited.allows_another(10_000)); + + assert!(ExamAttemptLimit::try_new(-1).is_err()); + assert!(ExamAttemptLimit::try_new(101).is_err()); + } + + #[tokio::test] + async fn schedule_invariants_hold() { + let mode = |m| Some(ExamMode::try_new(m).unwrap()); + let at = |ms| Some(Timestamp::from_millis(ms)); + let dur = Some(ExamDuration::try_new(90 * 60 * 1000).unwrap()); + + // Unscheduled: nothing set is fine, any time/duration without a mode is not. + assert!(ExamSchedule::try_new(None, None, None, None).is_ok()); + assert!(ExamSchedule::try_new(None, at(1), None, None).is_err()); + assert!(ExamSchedule::try_new(None, None, at(2), None).is_err()); + assert!(ExamSchedule::try_new(None, None, None, dur).is_err()); + + // Sync: fixed window, no duration. + assert!(ExamSchedule::try_new(mode("sync"), at(1), at(2), None).is_ok()); + assert!(ExamSchedule::try_new(mode("sync"), None, at(2), None).is_err()); + assert!(ExamSchedule::try_new(mode("sync"), at(1), None, None).is_err()); + // Over-long `dur` in a 1ms window, but the root cause is that sync + // takes no duration at all — that message wins over the window one. + assert!(matches!( + ExamSchedule::try_new(mode("sync"), at(1), at(2), dur), + Err(ValidationError::Invalid { + reason: "only async and open exams take a duration", + .. + }) + )); + + // Async: window plus a per-student duration, which must fit inside it + // (equal to the window is fine; the window `at(1), at(2)` above is + // too narrow for `dur`, so give it one exactly `dur` wide instead). + assert!(ExamSchedule::try_new(mode("async"), at(1), at(1 + 90 * 60 * 1000), dur).is_ok()); + assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), dur).is_err()); + assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), None).is_err()); + + // Open: no window, duration optional (limited or unlimited time). + assert!(ExamSchedule::try_new(mode("open"), None, None, None).is_ok()); + assert!(ExamSchedule::try_new(mode("open"), None, None, dur).is_ok()); + assert!(ExamSchedule::try_new(mode("open"), at(1), None, None).is_err()); + assert!(ExamSchedule::try_new(mode("open"), None, at(2), None).is_err()); + assert!(ExamSchedule::try_new(mode("open"), at(1), at(2), dur).is_err()); + + // The window must be a real interval, whatever the mode. + assert!(ExamSchedule::try_new(mode("sync"), at(2), at(2), None).is_err()); + assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err()); + } + + /// GUARD, not a retry measurement — read the last paragraph before + /// trusting this test with the retry. See + /// [`crate::db::course::delete`]'s race test for why the rate is + /// counted rather than asserted per round. + /// + /// This site has no `THROW` marker at all: it ends `.check()?`, which + /// returns the *first* error in the batch, and an aborted transaction + /// errors every slot — most of them with a generic "not executed". So a + /// genuine conflict can be masked by a sibling, and either way there is no + /// [`crate::database::lost_the_race`] check and no retry. + /// + /// The racer is a mark: [`ExamResult::grade`] claims the exam's own + /// `result_count` (and the kind's reference) before writing, so it contends + /// with the `DELETE $ex` and with the kind_ref decrement inside the same + /// transaction. A round where *some* of the six grades 404 and the rest + /// succeed is the witness that the delete landed inside the burst: the 404 + /// comes from `write_mark`'s existence gate, so it can only be answered by a + /// grade that reached the store after the row was gone, and its siblings' + /// success says the same burst also had grades that got there first. Stored + /// state cannot say this any more — the gate is what stops a mark outliving + /// its exam, so the sweep now finds nothing to leave behind in *every* + /// round, which is asserted below as a fact rather than read as a signal. + /// + /// It does not prove the retry either: measured at 0 conflicts in 100 raced + /// rounds, and green with + /// [`crate::database::transaction_with_retry`]'s loop cut to a single + /// attempt — the grades serialize behind `cap`'s claim lock, so they mostly + /// queue rather than collide. So this guards the status codes and the + /// cascade (marks either survive whole or are swept whole, never a 500). + /// The retry is measured on [`crate::db::course::delete`]. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_delete_racing_a_mark_never_answers_500() { + use crate::domain::exam_result::{ExamResult, Mark}; + let (db, _serialized) = crate::database::init_test_server("exam_delete_race").await; + let (mut delete_500, mut grade_500) = (0, 0); + let (mut split, mut swept) = (0, 0); + let (mut last_delete, mut last_grade) = (String::new(), String::new()); + for round in 0..20 { + let exam = published(&db).await; + let kind = exam.get_kind().as_str().to_string(); + + // A burst of marks and a delete held back by a sweeping beat: this + // site has no guard to lose to, so a single racer released with it + // simply finishes on one side of it. Same recipe as + // [`crate::db::course::delete`]'s race test. + let drop_it = { + let (exam, db) = (exam.clone(), db.clone()); + // A wide sweep, not the 0-3ms the other three use: each grade + // takes two counter writes serialized behind `cap`'s claim + // lock, so the burst runs tens of milliseconds and a short beat + // always puts the delete in front of all six. + let beat = std::time::Duration::from_millis(round * 2); + tokio::spawn(async move { + tokio::time::sleep(beat).await; + delete(&db, exam).await + }) + }; + let marks: Vec<_> = (0..6) + .map(|seat| { + let (id, db, kind) = (exam.get_id().clone(), db.clone(), kind.clone()); + let student = UserId::from_key(&format!("stu{round}_{seat}")); + tokio::spawn(async move { + ExamResult::grade( + &id, + &student, + 1, + Mark::try_new(50).unwrap(), + &UserId::from_key("teacher"), + &kind, + &db, + ) + .await + }) + }) + .collect(); + let drop_it = drop_it.await.unwrap(); + if matches!(drop_it, Err(AppError::Db(_))) { + delete_500 += 1; + last_delete = format!("{drop_it:?}"); + } + let mut refused = 0; + for mark in marks { + let mark = mark.await.unwrap(); + match mark { + // The existence gate: this grade reached the store after + // the row was gone. + Err(AppError::NotFound) => refused += 1, + Err(AppError::Db(_)) => { + grade_500 += 1; + last_grade = format!("{mark:?}"); + } + _ => {} + } + } + // Neither end of the burst: some grades beat the delete and some + // lost to it, so the delete landed *between* them. A round that is + // all-refused or all-through is one where it landed outside. + if (1..6).contains(&refused) { + split += 1; + } + if ExamResult::list_for_exam(exam.get_id(), &db) + .await + .unwrap() + .is_empty() + { + swept += 1; + } + } + eprintln!( + "Exam::delete raced: {delete_500}/20 delete 500s, {grade_500} grade 500s, \ + {split} rounds split by the delete / {swept} swept clean" + ); + assert!( + split > 0, + "the delete never landed inside the burst (0/20 rounds split)" + ); + // Not a race signal, an invariant: the gate refuses a mark for an exam + // that is gone, so no round can leave one behind for the next reader. + assert_eq!( + swept, + 20, + "a mark outlived its exam in {} rounds", + 20 - swept + ); + assert_eq!( + delete_500, 0, + "a raced delete must not 500: {delete_500}/20 rounds, last {last_delete}" + ); + assert_eq!( + grade_500, 0, + "a raced grade must retry, not 500: {grade_500}/20 rounds, last {last_grade}" + ); + } + + /// One choice question on `exam`, with a real subject row behind it — a + /// question claims a reference on its subject and is refused without one. + async fn question_on(exam: &Exam, db: &Database) -> crate::domain::exam_question::ExamQuestion { + use crate::domain::exam_question::{ + ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, + }; + 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(); + 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(); + ExamQuestion::create( + exam.get_id(), + subject.get_id().clone(), + QuestionText::try_new("3 + 3?").unwrap(), + QuestionPoints::try_new(5).unwrap(), + spec, + db, + ) + .await + .unwrap() + } + + /// The `Menu::delete` defect, one domain over: a student's answer must not + /// outlive the exam it belongs to. Guarding the save by *reading* the exam + /// would not do it — the read sees a row [`crate::db::exam::delete`] has removed but + /// not committed, while its `DELETE exam_answer WHERE exam = $ex` swept a + /// snapshot predating the save, so both commit and the answer is left + /// pointing at an exam that is gone. [`ExamAnswer::save`] writes the exam + /// row instead (its `result_count`, back unchanged), so the two transactions + /// touch one key and the store refuses one of them. + /// + /// The window is opened by the database, not by a lucky interleaving: a + /// `DEFINE EVENT` on `exam` fires *inside* the delete's own transaction the + /// instant the row goes, so the `SLEEP` lands exactly between the delete and + /// its cascade every time. Nothing in `src/` knows about it; the seam is the + /// schema. + /// + /// One child per round, deliberately — in the menu twin, two children in one + /// round hid the bug: the first writer made the delete lose and re-send, and + /// the re-sent sweep removed the other's row. + /// + /// Real server, and `#[ignore]`d for it: the subject *is* the store's + /// conflict detection, which `init_mem`'s embedded engine does not have — it + /// commits both writes and answers `Ok` to each, so this passes there on + /// broken code. Mutation-tested: putting the bare + /// `db.upsert(id).content(answer)` back turns it red (the exact output is in + /// the commit that added it). + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn an_answer_written_inside_a_delete_never_outlives_the_exam() { + use crate::domain::exam_answer::ExamAnswer; + let (db, _serialized) = crate::database::init_test_server("exam_answer_race").await; + // Hold the delete open for a full second after the row is gone, while + // its cascade still has to run. + db.query( + "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let (mut answers, mut swept) = (0, 0); + for round in 0..4 { + let exam = published(&db).await; + let question = question_on(&exam, &db).await; + let id = exam.get_id().clone(); + let student = UserId::from_key(&format!("stu{round}")); + // The stored choice ids are minted by the create, not the ones the + // spec asked for — an answer must name one of *those*. + let pick = question.get_choices().unwrap()[1] + .get_id() + .as_str() + .to_string(); + + let drop_it = { + let db = db.clone(); + tokio::spawn(async move { delete(&db, exam).await }) + }; + // The save starts inside the held window — the exam row is gone but + // uncommitted, which is exactly what an exam read believes. + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let child = { + let (db, question, student) = (db.clone(), question.clone(), student.clone()); + tokio::spawn(async move { + ExamAnswer::save(&question, &student, 1, Some(pick), None, &db).await + }) + }; + let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); + // A 404 for the save, or a NotFound for the delete, is a correct + // answer — the only defect is stored state. + assert!( + !matches!(child, Err(AppError::Db(_))), + "round {round}: a raced save must be answered, not 500: {child:?}" + ); + + // Stored state is the whole verdict; a return value is not evidence. + if read(&db, &id).await.unwrap().is_none() { + swept += 1; + answers += ExamAnswer::list_for_exam(&id, &db).await.unwrap().len(); + } else if drop_it.is_ok() { + panic!("round {round}: the delete reported success but the exam is still there"); + } + } + eprintln!("Exam::delete raced by an answer save: {swept}/4 rounds deleted the exam"); + assert!( + swept > 0, + "no round ever deleted the exam, so the window was never reached" + ); + assert_eq!(answers, 0, "an answer outlived its exam"); + } + + /// The same defect on the teacher's side of the sheet, and a worse one: a + /// question written inside the delete window kept the reference it claimed + /// on its subject (the cascade's per-subject decrement counted only the + /// rows it could see), and [`crate::domain::subject::Subject::delete`] is + /// 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; + /// [`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 + /// does not have. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_question_written_inside_a_delete_never_outlives_the_exam() { + use crate::domain::exam_question::{ + ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, + }; + use crate::domain::subject::Subject; + let (db, _serialized) = crate::database::init_test_server("exam_question_race").await; + db.query( + "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let (mut questions, mut swept, mut stuck) = (0, 0, 0); + for round in 0..4 { + let exam = published(&db).await; + let id = exam.get_id().clone(); + let 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 drop_it = { + let db = db.clone(); + tokio::spawn(async move { delete(&db, exam).await }) + }; + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let child = { + let (db, exam_id, on) = (db.clone(), id.clone(), subject.get_id().clone()); + tokio::spawn(async move { + 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(); + ExamQuestion::create( + &exam_id, + on, + QuestionText::try_new("3 + 3?").unwrap(), + QuestionPoints::try_new(5).unwrap(), + spec, + &db, + ) + .await + }) + }; + let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); + assert!( + !matches!(child, Err(AppError::Db(_))), + "round {round}: a raced question write must be answered, not 500: {child:?}" + ); + + if read(&db, &id).await.unwrap().is_none() { + swept += 1; + questions += ExamQuestion::list_for_exam(&id, None, 0, &db) + .await + .unwrap() + .0 + .len(); + // The subject has to be free again: a stranded reference is the + // half of this bug a row count alone would not catch. + if Subject::read(subject.get_id(), &db) + .await + .unwrap() + .unwrap() + .delete(&db) + .await + .is_err() + { + stuck += 1; + } + } else if drop_it.is_ok() { + panic!("round {round}: the delete reported success but the exam is still there"); + } + } + eprintln!("Exam::delete raced by a question write: {swept}/4 rounds deleted the exam"); + assert!( + swept > 0, + "no round ever deleted the exam, so the window was never reached" + ); + assert_eq!(questions, 0, "a question outlived its exam"); + assert_eq!(stuck, 0, "an orphan question left its subject undeletable"); + } + + /// The student's half of the same picture problem: a drawing is a bare + /// `UPSERT` — the exact pre-fix shape of [`ExamAnswer::save`] — so it kept + /// the hole the text answer just lost, blob and all. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_drawing_written_inside_a_delete_never_outlives_the_exam() { + use crate::domain::answer_image::AnswerImage; + use crate::domain::note_file::FileContentType; + let (db, _serialized) = crate::database::init_test_server("answer_image_race").await; + db.query( + "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let (mut drawings, mut swept) = (0, 0); + for round in 0..4 { + let exam = published(&db).await; + let question = question_on(&exam, &db).await; + let id = exam.get_id().clone(); + let student = UserId::from_key(&format!("stu{round}")); + + let drop_it = { + let db = db.clone(); + tokio::spawn(async move { delete(&db, exam).await }) + }; + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let child = { + let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone()); + tokio::spawn(async move { + AnswerImage::new( + &exam_id, + &on, + &student, + 1, + FileContentType::try_new("image/png").unwrap(), + 3, + ) + .upsert(&db) + .await + }) + }; + let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); + assert!( + !matches!(child, Err(AppError::Db(_))), + "round {round}: a raced drawing write must be answered, not 500: {child:?}" + ); + + if read(&db, &id).await.unwrap().is_none() { + swept += 1; + drawings += AnswerImage::list_for_exam(&id, &db).await.unwrap().len(); + } else if drop_it.is_ok() { + panic!("round {round}: the delete reported success but the exam is still there"); + } + } + eprintln!("Exam::delete raced by a drawing write: {swept}/4 rounds deleted the exam"); + assert!( + swept > 0, + "no round ever deleted the exam, so the window was never reached" + ); + assert_eq!(drawings, 0, "a drawing outlived its exam"); + } + + /// A picture is written through the same freeze gate as the question it + /// hangs on, so it had the same hole — and one the row count does not even + /// show: `delete_exam` collects the blob names to unlink *before* it calls + /// [\`crate::db::exam::delete\`], so an image row landing after that snapshot strands + /// its bytes on disk forever as well. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_picture_written_inside_a_delete_never_outlives_the_exam() { + use crate::domain::note_file::FileContentType; + use crate::domain::question_image::QuestionImage; + let (db, _serialized) = crate::database::init_test_server("question_image_race").await; + db.query( + "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let (mut images, mut swept) = (0, 0); + for round in 0..4 { + let exam = published(&db).await; + let question = question_on(&exam, &db).await; + let id = exam.get_id().clone(); + + let drop_it = { + let db = db.clone(); + tokio::spawn(async move { delete(&db, exam).await }) + }; + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let child = { + let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone()); + tokio::spawn(async move { + QuestionImage::new( + &exam_id, + &on, + None, + FileContentType::try_new("image/png").unwrap(), + 3, + ) + .upsert(&db) + .await + }) + }; + let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); + assert!( + !matches!(child, Err(AppError::Db(_))), + "round {round}: a raced picture write must be answered, not 500: {child:?}" + ); + + if read(&db, &id).await.unwrap().is_none() { + swept += 1; + images += QuestionImage::list_for_exam(&id, &db).await.unwrap().len(); + } else if drop_it.is_ok() { + panic!("round {round}: the delete reported success but the exam is still there"); + } + } + eprintln!("Exam::delete raced by a picture write: {swept}/4 rounds deleted the exam"); + assert!( + swept > 0, + "no round ever deleted the exam, so the window was never reached" + ); + assert_eq!(images, 0, "a picture outlived its exam"); + } +} diff --git a/src/db/exam_attempt.rs b/src/db/exam_attempt.rs index 0c938d2..5383cfd 100644 --- a/src/db/exam_attempt.rs +++ b/src/db/exam_attempt.rs @@ -164,7 +164,7 @@ pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result ExamId { - crate::domain::exam::published_exam(db) - .await - .get_id() - .clone() + crate::db::exam::published_exam(db).await.get_id().clone() } fn student() -> UserId { diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs index e9e567c..3d2ee48 100644 --- a/src/domain/bank_question.rs +++ b/src/domain/bank_question.rs @@ -835,14 +835,8 @@ mod tests { // Real exam rows: instantiating a template moves the exam's counter // (what keeps a question from outliving its exam), so a minted id // nothing wrote is a 404. - let exam = crate::domain::exam::published_exam(&db) - .await - .get_id() - .clone(); - let other_exam = crate::domain::exam::published_exam(&db) - .await - .get_id() - .clone(); + let exam = crate::db::exam::published_exam(&db).await.get_id().clone(); + let other_exam = crate::db::exam::published_exam(&db).await.get_id().clone(); // A real subject row: an exam question claims a reference on its // subject, so a minted id it never wrote would be refused. let subject = crate::domain::subject::Subject::create( diff --git a/src/domain/course_session.rs b/src/domain/course_session.rs index 813c6fc..21b371b 100644 --- a/src/domain/course_session.rs +++ b/src/domain/course_session.rs @@ -196,7 +196,7 @@ impl CourseSession { &[("s".into(), self.id.record().into_value())], // No THROW of its own — an unconditional cascade, so the only // error worth telling apart is a lost round (see - // [`crate::domain::exam::Exam::delete`]). + // [`crate::db::exam::delete`]). &[], ) .await?; diff --git a/src/domain/exam.rs b/src/domain/exam.rs index b7bca75..ed55c84 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -1,11 +1,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ - ENROLLMENT_COUNT_FIELD, EXAM_TABLE, MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, - UNLIMITED_EXAM_ATTEMPTS, + EXAM_TABLE, MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS, }; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; use crate::domain::course::CourseId; use crate::domain::monotonic_id::next_ulid; use crate::domain::settings::ExamKindDef; @@ -13,9 +10,10 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; -/// The one spelling of the re-draft refusal, shared by the handler's -/// pre-flight gate and the in-transaction guard that re-makes it at write -/// time — a client cannot tell which of the two refused. +/// The one spelling of the re-draft refusal, shared by the update workflow's +/// pre-flight gate ([`crate::service::exam::update`]) and the in-transaction +/// guard that re-makes it at write time — a client cannot tell which of the +/// two refused. pub(crate) fn redraft_error() -> AppError { AppError::Conflict( "cannot turn a published exam back into a draft after attempts or results exist", @@ -31,7 +29,7 @@ pub struct ExamId(RecordId); impl ExamId { /// Minted from the process-wide monotonic generator, not `Ulid::new()`: - /// exams list `id DESC` (newest first, [`Exam::list_all`]), + /// exams list `id DESC` (newest first, [`crate::db::exam::list_all`]), /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { Self(RecordId::new(EXAM_TABLE, next_ulid().to_string())) @@ -186,10 +184,10 @@ impl ExamAttemptLimit { /// - `ends_at` strictly after `starts_at` whenever the window exists. #[derive(Debug, Clone, Default)] pub struct ExamSchedule { - mode: Option, - starts_at: Option, - ends_at: Option, - duration_ms: Option, + pub(crate) mode: Option, + pub(crate) starts_at: Option, + pub(crate) ends_at: Option, + pub(crate) duration_ms: Option, } impl ExamSchedule { @@ -273,36 +271,37 @@ impl ExamSchedule { #[derive(Debug, Clone, SurrealValue)] pub struct Exam { - id: ExamId, - creator: UserId, - course: CourseId, - title: ExamTitle, - description: ExamDescription, - kind: ExamKind, + pub(crate) id: ExamId, + pub(crate) creator: UserId, + pub(crate) course: CourseId, + pub(crate) title: ExamTitle, + pub(crate) description: ExamDescription, + pub(crate) kind: ExamKind, // The schedule, flattened into columns (SCHEMAFULL keeps them typed). // Always written through an `ExamSchedule`, so the invariants above hold // for every stored row; pre-schedule rows read back as all-`None`. - mode: Option, - starts_at: Option, - ends_at: Option, - duration_ms: Option, + pub(crate) mode: Option, + pub(crate) starts_at: Option, + pub(crate) ends_at: Option, + pub(crate) duration_ms: Option, // Attempt policy. Rows predating these columns are backfilled by the boot // migration (limit 1, rejoin open), so reads never see them missing. - max_attempts: ExamAttemptLimit, - allow_rejoin: bool, - allow_review: bool, + pub(crate) max_attempts: ExamAttemptLimit, + pub(crate) allow_rejoin: bool, + pub(crate) allow_review: bool, // Work-in-progress marker: a draft is visible only to its course's // managers, cannot be sat, and cannot be graded. Rows predating the // column are backfilled published (`false`). - draft: bool, - /// How many marks the exam carries — a cap-style counter ([`cap::claim`] + pub(crate) draft: bool, + /// How many marks the exam carries — a cap-style counter + /// ([`crate::db::cap::claim`] /// from the grade, decremented by every delete of a mark), absent meaning /// zero. Unlike every other counter it is carried *in the struct*, because /// the save below is a whole-row `CONTENT` write: a column this type did /// not know about would be wiped by the next exam PATCH. Being in the row /// is also what makes it useful — the save pins it, so a grade landing /// mid-PATCH refuses the save instead of slipping past its gates. - result_count: Option, + pub(crate) result_count: Option, } impl Exam { @@ -388,1094 +387,4 @@ impl Exam { pub fn is_creator(&self, user: &UserId) -> bool { &self.creator == user } - - #[expect( - clippy::too_many_arguments, - reason = "mirrors the sibling entities' create(field, field, ..) shape" - )] - pub async fn create( - creator: &UserId, - course: &CourseId, - title: ExamTitle, - description: ExamDescription, - kind: ExamKind, - schedule: ExamSchedule, - max_attempts: ExamAttemptLimit, - allow_rejoin: bool, - allow_review: bool, - draft: bool, - db: &Database, - ) -> Result { - let exam = Exam { - id: ExamId::generate(), - creator: creator.clone(), - course: course.clone(), - title, - description, - kind, - mode: schedule.mode, - starts_at: schedule.starts_at, - ends_at: schedule.ends_at, - duration_ms: schedule.duration_ms, - max_attempts, - allow_rejoin, - allow_review, - draft, - result_count: None, - }; - // The course row is *written* (bumped and put back), not read: a plain - // read does not survive `Course::delete`'s window, and an exam that - // outlives its course is unreachable for good — every route to one goes - // through `course_of`, which answers a 500 no delete can clear, while - // `GET /exams` still lists it. See [`cap::touch_and_create`]. - cap::touch_and_create( - &course.record(), - ENROLLMENT_COUNT_FIELD, - &exam.id.record(), - &exam, - db, - ) - .await? - .ok_or(AppError::NotFound) - } - - pub async fn read(id: &ExamId, db: &Database) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - pub async fn list_all(db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM exam ORDER BY id DESC") - .await? - .check()?; - Ok(result.take::>(0)?) - } - - pub async fn list_for_course(course: &CourseId, db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM exam WHERE course = $course ORDER BY id DESC") - .bind(("course", course.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Every exam of every course in `courses` (one query) — the catalog as one - /// user sees it. - pub async fn list_for_courses( - courses: &[CourseId], - db: &Database, - ) -> Result, AppError> { - if courses.is_empty() { - return Ok(Vec::new()); - } - let records: Vec = courses.iter().map(CourseId::record).collect(); - let mut result = db - .query("SELECT * FROM exam WHERE course IN $courses ORDER BY id DESC") - .bind(("courses", records)) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - // `course` is deliberately not updatable — moving an exam between courses - // would strand results of students not enrolled in the target course. - #[expect( - clippy::too_many_arguments, - reason = "mirrors the sibling entities' update(field, field, ..) shape" - )] - /// Save the merged exam, but only while the row still reads as the - /// snapshot the caller merged over — `None` means a concurrent PATCH - /// landed in between and nothing was written: re-read, re-merge, retry. - /// - /// Every column this write replaces is in the guard, which is what makes - /// the whole-row `CONTENT` save safe without a lock held across the - /// handler's read: the compare-and-set refuses precisely when that save - /// would have reverted somebody. `course`/`creator` are not editable and - /// ride along unchanged. Same shape as - /// [`crate::db::settings::save_if_unchanged`]. - pub async fn update_if_unchanged( - mut self, - title: ExamTitle, - description: ExamDescription, - kind: ExamKind, - schedule: ExamSchedule, - max_attempts: ExamAttemptLimit, - allow_rejoin: bool, - allow_review: bool, - draft: bool, - db: &Database, - ) -> Result, AppError> { - // Re-drafting hides an exam: it must be refused while any sitting or - // mark exists, and that check has to be *in this transaction*. Holding - // it under a lock outside would only order the two writers inside one - // process — and it did not even do that, since grading takes the reader - // lease this write does. - let redraft = draft && !self.draft; - let was = ( - self.title.clone(), - self.description.clone(), - self.kind.clone(), - self.mode.clone(), - self.starts_at, - self.ends_at, - self.duration_ms, - self.max_attempts, - self.allow_rejoin, - self.allow_review, - self.draft, - ); - self.title = title; - self.description = description; - self.kind = kind; - self.mode = schedule.mode; - self.starts_at = schedule.starts_at; - self.ends_at = schedule.ends_at; - self.duration_ms = schedule.duration_ms; - self.max_attempts = max_attempts; - self.allow_rejoin = allow_rejoin; - self.allow_review = allow_review; - self.draft = draft; - // whole-row-save-ok: the WHERE below pins every column this replaces to - // the caller's snapshot, so no concurrent write can be reverted - // - // Sent through the retry loop, not a bare `query`: this row now has a - // hot writer. Every answer save touches it to tie itself to the exam - // ([`crate::domain::exam_answer::ExamAnswer::save`]), so a teacher - // flipping `allow_rejoin` mid-exam can lose a round to a student - // typing — and a lost round is a re-send, never the 500 a bare `?` on - // the conflict would have answered. Re-sending is sound because the - // statement is a compare-and-set: the second pass carries the same - // pinned snapshot, so it lands only if the row is still what the caller - // read, and a rival that really moved it is refused as it was before. - // Admissible for the loop — an `UPDATE`, an `IF`/`THROW` and a `SELECT` - // can never answer "already exists". - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - IF $redraft AND ( - array::len((SELECT VALUE id FROM exam_attempt WHERE exam = $id LIMIT 1)) > 0 - OR array::len((SELECT VALUE id FROM exam_result WHERE exam = $id LIMIT 1)) > 0 - ) { THROW 'exam_redraft' }; - UPDATE $id CONTENT $new - WHERE title = $was_title AND description = $was_description - AND kind = $was_kind AND mode = $was_mode - AND starts_at = $was_starts AND ends_at = $was_ends - AND duration_ms = $was_duration - AND max_attempts = $was_max_attempts - AND allow_rejoin = $was_allow_rejoin - AND allow_review = $was_allow_review - AND draft = $was_draft - AND (result_count ?? 0) = $was_results - RETURN AFTER; - COMMIT TRANSACTION;", - &[ - ("redraft".into(), redraft.into_value()), - ("id".into(), self.id.record().into_value()), - ("was_title".into(), was.0.into_value()), - ("was_description".into(), was.1.into_value()), - ("was_kind".into(), was.2.into_value()), - ("was_mode".into(), was.3.into_value()), - ("was_starts".into(), was.4.into_value()), - ("was_ends".into(), was.5.into_value()), - ("was_duration".into(), was.6.into_value()), - ("was_max_attempts".into(), was.7.into_value()), - ("was_allow_rejoin".into(), was.8.into_value()), - ("was_allow_review".into(), was.9.into_value()), - ("was_draft".into(), was.10.into_value()), - // The mark counter is pinned like every other column this write - // replaces, and for a sharper reason: a grade increments it, so - // pinning it is what makes "this exam had no marks" — the gate - // the handler refuses a kind change on — true at *write* time - // and not merely at read time. A mark landing in between - // refuses the save. - ( - "was_results".into(), - self.result_count.unwrap_or(0).into_value(), - ), - ("new".into(), self.into_value()), - ], - &["exam_redraft"], - ) - .await?; - // An aborted transaction errors every slot; only the THROW's names the - // marker (the [`crate::db::exam_attempt::write_unfrozen`] treatment). - if errors - .values() - .any(|error| error.to_string().contains("exam_redraft")) - { - return Err(redraft_error()); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // BEGIN and the IF take a slot each. - Ok(result.take::>(2)?.into_iter().next()) - } - - /// Delete the exam and cascade-remove its result, attempt, question, - /// answer, question-image, and answer-image rows — all in one transaction, - /// so a failure can't leave an emptied-out exam shell behind. The image - /// *blobs* (question and answer) are the web layer's to remove — it collects - /// their names before calling this. - /// - /// Bank templates saved out of this exam survive it — they are a separate, - /// reusable library — so only their `source_exam` provenance link is cleared, - /// in the same transaction, never left pointing at a dead exam. - /// - /// The questions about to be cascaded each hold a reference on their - /// subject, which is what keeps that subject from being deleted under them. - /// They are given back in this same transaction, counted per subject, so - /// deleting an exam frees its subjects for deletion and nothing else does. - /// The marks give their *kind* references back the same way, and it has to - /// be the same way: counted outside the transaction, a mark deleted by a - /// concurrent `remove_result` in the gap would be released twice — once by - /// each — which on a kind another exam still uses reads as one mark too - /// few, and that is a kind wrongly free to leave the settings. - pub async fn delete(self, db: &Database) -> Result { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result - WHERE exam = $ex GROUP BY kind) ?? []) { - UPDATE type::record('kind_ref', $row.kind) SET count = - math::max([(count ?? 0) - $row.n, 0]) - }; - DELETE exam_result WHERE exam = $ex; - DELETE exam_attempt WHERE exam = $ex; - DELETE exam_answer WHERE exam = $ex; - DELETE answer_image WHERE exam = $ex; - DELETE question_image WHERE exam = $ex; - FOR $row IN ((SELECT subject, count() AS n FROM exam_question - WHERE exam = $ex GROUP BY subject) ?? []) { - UPDATE $row.subject SET exam_question_count = - math::max([(exam_question_count ?? 0) - $row.n, 0]) - }; - DELETE exam_question WHERE exam = $ex; - UPDATE bank_question SET source_exam = NONE WHERE source_exam = $ex; - LET $before = (DELETE $ex RETURN BEFORE); - RETURN $before; - COMMIT TRANSACTION;", - &[("ex".into(), self.id.record().into_value())], - // No THROW of its own: an unconditional cascade, so the only error - // worth telling apart is a lost round, and `check()` — which took - // the *first* error in the batch — could not. It reported a - // sibling's "not executed" and made a retryable round a 500. - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The deleted row comes back through the transaction's trailing - // `RETURN`, never a hand-counted slot: the old `take(8)` turned a - // successful delete into a 404 the moment a cascade statement was - // inserted above it (it already had to be bumped once). `RETURN` is - // always the last statement before `COMMIT`, so its slot is derived - // from the statement count and every insertion above it shifts it - // along. `num_statements` counts BEGIN and COMMIT too, hence -2. - let slot = result.num_statements().saturating_sub(2); - let deleted: Option = result.take::>(slot)?.into_iter().next(); - deleted.ok_or(AppError::NotFound) - } -} - -/// 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 -/// [`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)] -pub(crate) async fn published_exam(db: &Database) -> Exam { - let allowed: Vec = crate::domain::settings::Settings::defaults() - .get_exam_kinds() - .to_vec(); - Exam::create( - &UserId::generate(), - &crate::db::course::a_test_course(db).await, - ExamTitle::try_new("midterm").unwrap(), - ExamDescription::try_new("").unwrap(), - ExamKind::try_new("midterm", &allowed).unwrap(), - ExamSchedule::try_new(None, None, None, None).unwrap(), - ExamAttemptLimit::try_new(1).unwrap(), - true, - false, - false, - db, - ) - .await - .unwrap() -} - -#[cfg(test)] -mod tests { - use super::*; - - use crate::domain::exam::published_exam as published; - - /// An exam must not outlive the course it belongs to. It is the worst of - /// the three children `Course::delete` used to leave behind: every exam - /// route funnels through `course_of`, which answers - /// `Internal("exam references a missing course")`, so an orphan **500s - /// forever** on `GET`/`PATCH`/`DELETE /exams/{id}` — undeletable — while - /// `Exam::list_all` still hands it to every manager+ on `GET /exams`. - /// - /// [`Exam::create`] therefore *writes* the course row rather than reading - /// it ([`cap::touch_and_create`]); the harness and the window it races in - /// are documented on - /// [`crate::db::course::assert_no_child_outlives_a_course_delete`]. - /// Mutation-tested: with the bare `db.create` this shipped with, all four - /// rounds orphan. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn an_exam_never_outlives_its_course() { - fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle> { - tokio::spawn(async move { - let kinds = crate::domain::settings::Settings::defaults() - .get_exam_kinds() - .to_vec(); - Exam::create( - &UserId::generate(), - &course, - ExamTitle::try_new("quiz").unwrap(), - ExamDescription::try_new("").unwrap(), - ExamKind::try_new("quiz", &kinds).unwrap(), - ExamSchedule::try_new(None, None, None, None).unwrap(), - ExamAttemptLimit::try_new(1).unwrap(), - true, - false, - false, - &db, - ) - .await - .map(|_| ()) - }) - } - crate::db::course::assert_no_child_outlives_a_course_delete("exam_orphan_race", - EXAM_TABLE, - make,) - .await; - } - - fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) { - ( - exam.get_title().clone(), - exam.get_description().clone(), - exam.get_kind().clone(), - ExamSchedule::try_new(None, None, None, None).unwrap(), - ) - } - - /// The bite test for the compare-and-set that replaced the writer lease on - /// `PATCH /exams/{id}`: a merge built on a snapshot the row has moved past - /// must be refused (the handler then re-reads and re-merges), never - /// written over somebody else's edit. Asserts the *stored* row. - #[tokio::test] - async fn a_merge_built_on_a_stale_snapshot_is_refused() { - let db = crate::database::init_mem().await.unwrap(); - let stale = published(&db).await; - let (_, description, kind, schedule) = edit(&stale); - let landed = stale - .clone() - .update_if_unchanged( - ExamTitle::try_new("theirs").unwrap(), - description, - kind, - schedule, - ExamAttemptLimit::try_new(1).unwrap(), - true, - false, - false, - &db, - ) - .await - .unwrap(); - assert!(landed.is_some(), "the first write is on a fresh snapshot"); - - let (_, description, kind, schedule) = edit(&stale); - let refused = stale - .update_if_unchanged( - ExamTitle::try_new("mine").unwrap(), - description, - kind, - schedule, - ExamAttemptLimit::try_new(1).unwrap(), - true, - false, - false, - &db, - ) - .await - .unwrap(); - assert!(refused.is_none(), "a stale merge must not be written"); - let stored = Exam::read(landed.unwrap().get_id(), &db) - .await - .unwrap() - .unwrap(); - assert_eq!(stored.get_title().as_str(), "theirs"); - } - - /// The bite test for the re-draft guard now living *inside* the update's - /// transaction: a mark that lands after the handler's pre-flight gate (the - /// grade path is a lock reader, exactly like this one) must still stop the - /// exam from being hidden. - #[tokio::test] - async fn re_drafting_is_refused_by_the_write_itself_once_a_mark_exists() { - use crate::domain::exam_result::{ExamResult, Mark}; - let db = crate::database::init_mem().await.unwrap(); - let exam = published(&db).await; - let student = UserId::generate(); - ExamResult::grade( - exam.get_id(), - &student, - 1, - Mark::try_new(80).unwrap(), - &UserId::generate(), - exam.get_kind().as_str(), - &db, - ) - .await - .unwrap(); - - let (title, description, kind, schedule) = edit(&exam); - let refused = exam - .clone() - .update_if_unchanged( - title, - description, - kind, - schedule, - ExamAttemptLimit::try_new(1).unwrap(), - true, - false, - true, - &db, - ) - .await - .expect_err("a graded exam cannot be re-drafted"); - assert!(refused.to_string().contains("back into a draft")); - let stored = Exam::read(exam.get_id(), &db).await.unwrap().unwrap(); - assert!(!stored.is_draft(), "nothing may have been written"); - } - - #[tokio::test] - async fn title_is_required() { - assert!(ExamTitle::try_new("midterm").is_ok()); - assert!(ExamTitle::try_new("").is_err()); - assert!(ExamTitle::try_new(" ").is_err()); - } - - #[tokio::test] - async fn description_is_optional() { - assert!(ExamDescription::try_new("").is_ok()); - } - - #[tokio::test] - async fn kind_must_be_in_the_allowed_list() { - let allowed: Vec = crate::domain::settings::Settings::defaults() - .get_exam_kinds() - .to_vec(); - for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] { - assert_eq!(ExamKind::try_new(kind, &allowed).unwrap().as_str(), kind); - } - assert!(ExamKind::try_new("essay", &allowed).is_err()); - assert!(ExamKind::try_new("", &allowed).is_err()); - // A school-defined list swaps the acceptance set wholesale. - let custom = vec![ExamKindDef::try_new("lab", 2).unwrap()]; - assert!(ExamKind::try_new("lab", &custom).is_ok()); - assert!(ExamKind::try_new("midterm", &custom).is_err()); - // Matching is exact, case included — the settings list is the wire - // truth, not a case-folded suggestion. - assert!(ExamKind::try_new("Lab", &custom).is_err()); - } - - #[tokio::test] - async fn mode_must_be_known() { - for mode in ["sync", "async", "open"] { - assert_eq!(ExamMode::try_new(mode).unwrap().as_str(), mode); - } - assert!(ExamMode::try_new("live").is_err()); - } - - #[tokio::test] - async fn attempt_limit_counts_or_never_runs_out() { - let single = ExamAttemptLimit::single(); - assert_eq!(single.as_i64(), 1); - assert!(!single.is_unlimited()); - assert!(single.allows_another(0)); - assert!(!single.allows_another(1)); - - let three = ExamAttemptLimit::try_new(3).unwrap(); - assert!(three.allows_another(2)); - assert!(!three.allows_another(3)); - assert!(!three.allows_another(4)); - - let unlimited = ExamAttemptLimit::try_new(0).unwrap(); - assert!(unlimited.is_unlimited()); - assert!(unlimited.allows_another(0)); - assert!(unlimited.allows_another(10_000)); - - assert!(ExamAttemptLimit::try_new(-1).is_err()); - assert!(ExamAttemptLimit::try_new(101).is_err()); - } - - #[tokio::test] - async fn schedule_invariants_hold() { - let mode = |m| Some(ExamMode::try_new(m).unwrap()); - let at = |ms| Some(Timestamp::from_millis(ms)); - let dur = Some(ExamDuration::try_new(90 * 60 * 1000).unwrap()); - - // Unscheduled: nothing set is fine, any time/duration without a mode is not. - assert!(ExamSchedule::try_new(None, None, None, None).is_ok()); - assert!(ExamSchedule::try_new(None, at(1), None, None).is_err()); - assert!(ExamSchedule::try_new(None, None, at(2), None).is_err()); - assert!(ExamSchedule::try_new(None, None, None, dur).is_err()); - - // Sync: fixed window, no duration. - assert!(ExamSchedule::try_new(mode("sync"), at(1), at(2), None).is_ok()); - assert!(ExamSchedule::try_new(mode("sync"), None, at(2), None).is_err()); - assert!(ExamSchedule::try_new(mode("sync"), at(1), None, None).is_err()); - // Over-long `dur` in a 1ms window, but the root cause is that sync - // takes no duration at all — that message wins over the window one. - assert!(matches!( - ExamSchedule::try_new(mode("sync"), at(1), at(2), dur), - Err(ValidationError::Invalid { - reason: "only async and open exams take a duration", - .. - }) - )); - - // Async: window plus a per-student duration, which must fit inside it - // (equal to the window is fine; the window `at(1), at(2)` above is - // too narrow for `dur`, so give it one exactly `dur` wide instead). - assert!(ExamSchedule::try_new(mode("async"), at(1), at(1 + 90 * 60 * 1000), dur).is_ok()); - assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), dur).is_err()); - assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), None).is_err()); - - // Open: no window, duration optional (limited or unlimited time). - assert!(ExamSchedule::try_new(mode("open"), None, None, None).is_ok()); - assert!(ExamSchedule::try_new(mode("open"), None, None, dur).is_ok()); - assert!(ExamSchedule::try_new(mode("open"), at(1), None, None).is_err()); - assert!(ExamSchedule::try_new(mode("open"), None, at(2), None).is_err()); - assert!(ExamSchedule::try_new(mode("open"), at(1), at(2), dur).is_err()); - - // The window must be a real interval, whatever the mode. - assert!(ExamSchedule::try_new(mode("sync"), at(2), at(2), None).is_err()); - assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err()); - } - - /// GUARD, not a retry measurement — read the last paragraph before - /// trusting this test with the retry. See - /// [`crate::db::course::delete`]'s race test for why the rate is - /// counted rather than asserted per round. - /// - /// This site has no `THROW` marker at all: it ends `.check()?`, which - /// returns the *first* error in the batch, and an aborted transaction - /// errors every slot — most of them with a generic "not executed". So a - /// genuine conflict can be masked by a sibling, and either way there is no - /// [`crate::database::lost_the_race`] check and no retry. - /// - /// The racer is a mark: [`ExamResult::grade`] claims the exam's own - /// `result_count` (and the kind's reference) before writing, so it contends - /// with the `DELETE $ex` and with the kind_ref decrement inside the same - /// transaction. A round where *some* of the six grades 404 and the rest - /// succeed is the witness that the delete landed inside the burst: the 404 - /// comes from `write_mark`'s existence gate, so it can only be answered by a - /// grade that reached the store after the row was gone, and its siblings' - /// success says the same burst also had grades that got there first. Stored - /// state cannot say this any more — the gate is what stops a mark outliving - /// its exam, so the sweep now finds nothing to leave behind in *every* - /// round, which is asserted below as a fact rather than read as a signal. - /// - /// It does not prove the retry either: measured at 0 conflicts in 100 raced - /// rounds, and green with - /// [`crate::database::transaction_with_retry`]'s loop cut to a single - /// attempt — the grades serialize behind `cap`'s claim lock, so they mostly - /// queue rather than collide. So this guards the status codes and the - /// cascade (marks either survive whole or are swept whole, never a 500). - /// The retry is measured on [`crate::db::course::delete`]. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_delete_racing_a_mark_never_answers_500() { - use crate::domain::exam_result::{ExamResult, Mark}; - let (db, _serialized) = crate::database::init_test_server("exam_delete_race").await; - let (mut delete_500, mut grade_500) = (0, 0); - let (mut split, mut swept) = (0, 0); - let (mut last_delete, mut last_grade) = (String::new(), String::new()); - for round in 0..20 { - let exam = published(&db).await; - let kind = exam.get_kind().as_str().to_string(); - - // A burst of marks and a delete held back by a sweeping beat: this - // site has no guard to lose to, so a single racer released with it - // simply finishes on one side of it. Same recipe as - // [`crate::db::course::delete`]'s race test. - let drop_it = { - let (exam, db) = (exam.clone(), db.clone()); - // A wide sweep, not the 0-3ms the other three use: each grade - // takes two counter writes serialized behind `cap`'s claim - // lock, so the burst runs tens of milliseconds and a short beat - // always puts the delete in front of all six. - let beat = std::time::Duration::from_millis(round * 2); - tokio::spawn(async move { - tokio::time::sleep(beat).await; - exam.delete(&db).await - }) - }; - let marks: Vec<_> = (0..6) - .map(|seat| { - let (id, db, kind) = (exam.get_id().clone(), db.clone(), kind.clone()); - let student = UserId::from_key(&format!("stu{round}_{seat}")); - tokio::spawn(async move { - ExamResult::grade( - &id, - &student, - 1, - Mark::try_new(50).unwrap(), - &UserId::from_key("teacher"), - &kind, - &db, - ) - .await - }) - }) - .collect(); - let drop_it = drop_it.await.unwrap(); - if matches!(drop_it, Err(AppError::Db(_))) { - delete_500 += 1; - last_delete = format!("{drop_it:?}"); - } - let mut refused = 0; - for mark in marks { - let mark = mark.await.unwrap(); - match mark { - // The existence gate: this grade reached the store after - // the row was gone. - Err(AppError::NotFound) => refused += 1, - Err(AppError::Db(_)) => { - grade_500 += 1; - last_grade = format!("{mark:?}"); - } - _ => {} - } - } - // Neither end of the burst: some grades beat the delete and some - // lost to it, so the delete landed *between* them. A round that is - // all-refused or all-through is one where it landed outside. - if (1..6).contains(&refused) { - split += 1; - } - if ExamResult::list_for_exam(exam.get_id(), &db) - .await - .unwrap() - .is_empty() - { - swept += 1; - } - } - eprintln!( - "Exam::delete raced: {delete_500}/20 delete 500s, {grade_500} grade 500s, \ - {split} rounds split by the delete / {swept} swept clean" - ); - assert!( - split > 0, - "the delete never landed inside the burst (0/20 rounds split)" - ); - // Not a race signal, an invariant: the gate refuses a mark for an exam - // that is gone, so no round can leave one behind for the next reader. - assert_eq!( - swept, - 20, - "a mark outlived its exam in {} rounds", - 20 - swept - ); - assert_eq!( - delete_500, 0, - "a raced delete must not 500: {delete_500}/20 rounds, last {last_delete}" - ); - assert_eq!( - grade_500, 0, - "a raced grade must retry, not 500: {grade_500}/20 rounds, last {last_grade}" - ); - } - - /// One choice question on `exam`, with a real subject row behind it — a - /// question claims a reference on its subject and is refused without one. - async fn question_on(exam: &Exam, db: &Database) -> crate::domain::exam_question::ExamQuestion { - use crate::domain::exam_question::{ - ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, - }; - 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(); - 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(); - ExamQuestion::create( - exam.get_id(), - subject.get_id().clone(), - QuestionText::try_new("3 + 3?").unwrap(), - QuestionPoints::try_new(5).unwrap(), - spec, - db, - ) - .await - .unwrap() - } - - /// The `Menu::delete` defect, one domain over: a student's answer must not - /// outlive the exam it belongs to. Guarding the save by *reading* the exam - /// would not do it — the read sees a row [`Exam::delete`] has removed but - /// not committed, while its `DELETE exam_answer WHERE exam = $ex` swept a - /// snapshot predating the save, so both commit and the answer is left - /// pointing at an exam that is gone. [`ExamAnswer::save`] writes the exam - /// row instead (its `result_count`, back unchanged), so the two transactions - /// touch one key and the store refuses one of them. - /// - /// The window is opened by the database, not by a lucky interleaving: a - /// `DEFINE EVENT` on `exam` fires *inside* the delete's own transaction the - /// instant the row goes, so the `SLEEP` lands exactly between the delete and - /// its cascade every time. Nothing in `src/` knows about it; the seam is the - /// schema. - /// - /// One child per round, deliberately — in the menu twin, two children in one - /// round hid the bug: the first writer made the delete lose and re-send, and - /// the re-sent sweep removed the other's row. - /// - /// Real server, and `#[ignore]`d for it: the subject *is* the store's - /// conflict detection, which `init_mem`'s embedded engine does not have — it - /// commits both writes and answers `Ok` to each, so this passes there on - /// broken code. Mutation-tested: putting the bare - /// `db.upsert(id).content(answer)` back turns it red (the exact output is in - /// the commit that added it). - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn an_answer_written_inside_a_delete_never_outlives_the_exam() { - use crate::domain::exam_answer::ExamAnswer; - let (db, _serialized) = crate::database::init_test_server("exam_answer_race").await; - // Hold the delete open for a full second after the row is gone, while - // its cascade still has to run. - db.query( - "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); - - let (mut answers, mut swept) = (0, 0); - for round in 0..4 { - let exam = published(&db).await; - let question = question_on(&exam, &db).await; - let id = exam.get_id().clone(); - let student = UserId::from_key(&format!("stu{round}")); - // The stored choice ids are minted by the create, not the ones the - // spec asked for — an answer must name one of *those*. - let pick = question.get_choices().unwrap()[1] - .get_id() - .as_str() - .to_string(); - - let drop_it = { - let db = db.clone(); - tokio::spawn(async move { exam.delete(&db).await }) - }; - // The save starts inside the held window — the exam row is gone but - // uncommitted, which is exactly what an exam read believes. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - let child = { - let (db, question, student) = (db.clone(), question.clone(), student.clone()); - tokio::spawn(async move { - ExamAnswer::save(&question, &student, 1, Some(pick), None, &db).await - }) - }; - let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); - // A 404 for the save, or a NotFound for the delete, is a correct - // answer — the only defect is stored state. - assert!( - !matches!(child, Err(AppError::Db(_))), - "round {round}: a raced save must be answered, not 500: {child:?}" - ); - - // Stored state is the whole verdict; a return value is not evidence. - if Exam::read(&id, &db).await.unwrap().is_none() { - swept += 1; - answers += ExamAnswer::list_for_exam(&id, &db).await.unwrap().len(); - } else if drop_it.is_ok() { - panic!("round {round}: the delete reported success but the exam is still there"); - } - } - eprintln!("Exam::delete raced by an answer save: {swept}/4 rounds deleted the exam"); - assert!( - swept > 0, - "no round ever deleted the exam, so the window was never reached" - ); - assert_eq!(answers, 0, "an answer outlived its exam"); - } - - /// The same defect on the teacher's side of the sheet, and a worse one: a - /// question written inside the delete window kept the reference it claimed - /// on its subject (the cascade's per-subject decrement counted only the - /// rows it could see), and [`crate::domain::subject::Subject::delete`] is - /// 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; - /// [`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 - /// does not have. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_question_written_inside_a_delete_never_outlives_the_exam() { - use crate::domain::exam_question::{ - ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, - }; - use crate::domain::subject::Subject; - let (db, _serialized) = crate::database::init_test_server("exam_question_race").await; - db.query( - "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); - - let (mut questions, mut swept, mut stuck) = (0, 0, 0); - for round in 0..4 { - let exam = published(&db).await; - let id = exam.get_id().clone(); - let 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 drop_it = { - let db = db.clone(); - tokio::spawn(async move { exam.delete(&db).await }) - }; - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - let child = { - let (db, exam_id, on) = (db.clone(), id.clone(), subject.get_id().clone()); - tokio::spawn(async move { - 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(); - ExamQuestion::create( - &exam_id, - on, - QuestionText::try_new("3 + 3?").unwrap(), - QuestionPoints::try_new(5).unwrap(), - spec, - &db, - ) - .await - }) - }; - let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); - assert!( - !matches!(child, Err(AppError::Db(_))), - "round {round}: a raced question write must be answered, not 500: {child:?}" - ); - - if Exam::read(&id, &db).await.unwrap().is_none() { - swept += 1; - questions += ExamQuestion::list_for_exam(&id, None, 0, &db) - .await - .unwrap() - .0 - .len(); - // The subject has to be free again: a stranded reference is the - // half of this bug a row count alone would not catch. - if Subject::read(subject.get_id(), &db) - .await - .unwrap() - .unwrap() - .delete(&db) - .await - .is_err() - { - stuck += 1; - } - } else if drop_it.is_ok() { - panic!("round {round}: the delete reported success but the exam is still there"); - } - } - eprintln!("Exam::delete raced by a question write: {swept}/4 rounds deleted the exam"); - assert!( - swept > 0, - "no round ever deleted the exam, so the window was never reached" - ); - assert_eq!(questions, 0, "a question outlived its exam"); - assert_eq!(stuck, 0, "an orphan question left its subject undeletable"); - } - - /// The student's half of the same picture problem: a drawing is a bare - /// `UPSERT` — the exact pre-fix shape of [`ExamAnswer::save`] — so it kept - /// the hole the text answer just lost, blob and all. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_drawing_written_inside_a_delete_never_outlives_the_exam() { - use crate::domain::answer_image::AnswerImage; - use crate::domain::note_file::FileContentType; - let (db, _serialized) = crate::database::init_test_server("answer_image_race").await; - db.query( - "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); - - let (mut drawings, mut swept) = (0, 0); - for round in 0..4 { - let exam = published(&db).await; - let question = question_on(&exam, &db).await; - let id = exam.get_id().clone(); - let student = UserId::from_key(&format!("stu{round}")); - - let drop_it = { - let db = db.clone(); - tokio::spawn(async move { exam.delete(&db).await }) - }; - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - let child = { - let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone()); - tokio::spawn(async move { - AnswerImage::new( - &exam_id, - &on, - &student, - 1, - FileContentType::try_new("image/png").unwrap(), - 3, - ) - .upsert(&db) - .await - }) - }; - let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); - assert!( - !matches!(child, Err(AppError::Db(_))), - "round {round}: a raced drawing write must be answered, not 500: {child:?}" - ); - - if Exam::read(&id, &db).await.unwrap().is_none() { - swept += 1; - drawings += AnswerImage::list_for_exam(&id, &db).await.unwrap().len(); - } else if drop_it.is_ok() { - panic!("round {round}: the delete reported success but the exam is still there"); - } - } - eprintln!("Exam::delete raced by a drawing write: {swept}/4 rounds deleted the exam"); - assert!( - swept > 0, - "no round ever deleted the exam, so the window was never reached" - ); - assert_eq!(drawings, 0, "a drawing outlived its exam"); - } - - /// A picture is written through the same freeze gate as the question it - /// hangs on, so it had the same hole — and one the row count does not even - /// show: `delete_exam` collects the blob names to unlink *before* it calls - /// [`Exam::delete`], so an image row landing after that snapshot strands - /// its bytes on disk forever as well. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_picture_written_inside_a_delete_never_outlives_the_exam() { - use crate::domain::note_file::FileContentType; - use crate::domain::question_image::QuestionImage; - let (db, _serialized) = crate::database::init_test_server("question_image_race").await; - db.query( - "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); - - let (mut images, mut swept) = (0, 0); - for round in 0..4 { - let exam = published(&db).await; - let question = question_on(&exam, &db).await; - let id = exam.get_id().clone(); - - let drop_it = { - let db = db.clone(); - tokio::spawn(async move { exam.delete(&db).await }) - }; - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - let child = { - let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone()); - tokio::spawn(async move { - QuestionImage::new( - &exam_id, - &on, - None, - FileContentType::try_new("image/png").unwrap(), - 3, - ) - .upsert(&db) - .await - }) - }; - let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); - assert!( - !matches!(child, Err(AppError::Db(_))), - "round {round}: a raced picture write must be answered, not 500: {child:?}" - ); - - if Exam::read(&id, &db).await.unwrap().is_none() { - swept += 1; - images += QuestionImage::list_for_exam(&id, &db).await.unwrap().len(); - } else if drop_it.is_ok() { - panic!("round {round}: the delete reported success but the exam is still there"); - } - } - eprintln!("Exam::delete raced by a picture write: {swept}/4 rounds deleted the exam"); - assert!( - swept > 0, - "no round ever deleted the exam, so the window was never reached" - ); - assert_eq!(images, 0, "a picture outlived its exam"); - } } diff --git a/src/domain/exam_answer.rs b/src/domain/exam_answer.rs index 2689522..e3ff797 100644 --- a/src/domain/exam_answer.rs +++ b/src/domain/exam_answer.rs @@ -173,7 +173,7 @@ impl ExamAnswer { }; // The save writes the *exam row* as well as the answer, in one // transaction, and that is what ties the answer's fate to its exam: - // reading the exam does not survive [`crate::domain::exam::Exam::delete`]'s + // reading the exam does not survive [`crate::db::exam::delete`]'s // window — a save landing after its `DELETE exam_answer WHERE exam = $ex` // but before the commit reads an exam that is still there (uncommitted) // while the sweep ran on a snapshot predating this row, so both commit @@ -240,7 +240,7 @@ impl ExamAnswer { } // The trailing `RETURN` is the last statement before `COMMIT`, so its // slot follows the statement count rather than a hand-kept number (the - // `Exam::delete` treatment); `num_statements` counts BEGIN and COMMIT. + // `db::exam::delete` treatment); `num_statements` counts BEGIN and COMMIT. let slot = result.num_statements().saturating_sub(2); result .take::>(slot)? @@ -491,22 +491,23 @@ mod tests { } /// The bite test for the exam-row touch in [`ExamAnswer::save`]: it exists - /// to collide with [`crate::domain::exam::Exam::delete`], so it must leave + /// to collide with [`crate::db::exam::delete`], so it must leave /// the counter it borrows exactly where it found it — absent stays absent /// (the boot backfill keys on `result_count = NONE`), and a real count is /// not moved by a student typing. The race half is - /// `domain::exam::tests::an_answer_written_inside_a_delete_never_outlives_the_exam`, + /// `db::exam::tests::an_answer_written_inside_a_delete_never_outlives_the_exam`, /// which needs a real server; this half is the arithmetic and runs anywhere. #[tokio::test] async fn a_save_puts_the_exams_mark_counter_back_exactly() { use crate::domain::exam::{ - Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle, + ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle, }; let db = crate::database::init_mem().await.unwrap(); let kinds = crate::domain::settings::Settings::defaults() .get_exam_kinds() .to_vec(); - let exam = Exam::create( + let exam = crate::db::exam::create( + &db, &student(), &crate::db::course::a_test_course(&db).await, ExamTitle::try_new("quiz").unwrap(), @@ -517,7 +518,6 @@ mod tests { true, false, false, - &db, ) .await .unwrap(); diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index cadf182..9706598 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -1096,7 +1096,8 @@ mod tests { async fn an_exam(db: &Database) -> Exam { let kinds = Settings::defaults().get_exam_kinds().to_vec(); - Exam::create( + crate::db::exam::create( + db, &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), &crate::db::course::a_test_course(db).await, ExamTitle::try_new("practice").unwrap(), @@ -1108,7 +1109,6 @@ mod tests { true, false, false, - db, ) .await .unwrap() diff --git a/src/domain/homework.rs b/src/domain/homework.rs index f3b3d19..5a323ac 100644 --- a/src/domain/homework.rs +++ b/src/domain/homework.rs @@ -18,8 +18,8 @@ use crate::constant::{ }; use crate::database::Database; use crate::db::cap; -use crate::domain::course::CourseId; use crate::db::field_update::FieldUpdate; +use crate::domain::course::CourseId; use crate::domain::monotonic_id::next_ulid; use crate::domain::subject::SubjectId; use crate::domain::timestamp::Timestamp; @@ -370,7 +370,7 @@ impl Homework { .check()?; // The subject's reference is given back in this same transaction, off // what the delete actually removed. Read through the trailing `RETURN`, - // not a hand-counted slot — see [`crate::domain::exam::Exam::delete`]. + // not a hand-counted slot — see [`crate::db::exam::delete`]. let slot = result.num_statements().saturating_sub(2); let deleted: Option = result.take::>(slot)?.into_iter().next(); deleted.ok_or(AppError::NotFound) diff --git a/src/domain/question_image.rs b/src/domain/question_image.rs index 9b7a7e3..1c1ae18 100644 --- a/src/domain/question_image.rs +++ b/src/domain/question_image.rs @@ -258,10 +258,7 @@ mod tests { /// keeps a picture from outliving its exam), so a minted id nothing wrote /// is a 404. async fn exam_row(db: &Database) -> ExamId { - crate::domain::exam::published_exam(db) - .await - .get_id() - .clone() + crate::db::exam::published_exam(db).await.get_id().clone() } fn png() -> FileContentType { diff --git a/src/domain/subject.rs b/src/domain/subject.rs index 16337e6..55f9a0c 100644 --- a/src/domain/subject.rs +++ b/src/domain/subject.rs @@ -5,10 +5,10 @@ use crate::constant::{ }; use crate::database::{Database, transaction_with_retry}; use crate::db::cap; -use crate::domain::course::CourseId; use crate::db::field_update::FieldUpdate; -use crate::domain::monotonic_id::next_ulid; use crate::db::page::PagedList; +use crate::domain::course::CourseId; +use crate::domain::monotonic_id::next_ulid; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_optional, validate_required}; @@ -244,7 +244,7 @@ impl Subject { return Err(error.into()); } // Read through the trailing `RETURN`, not a counted slot — see - // [`crate::domain::exam::Exam::delete`]. + // [`crate::db::exam::delete`]. let slot = result.num_statements().saturating_sub(2); let deleted: Option = result.take::>(slot)?.into_iter().next(); deleted.ok_or(AppError::NotFound) @@ -281,9 +281,11 @@ mod tests { .map(|_| ()) }) } - crate::db::course::assert_no_child_outlives_a_course_delete("subject_orphan_race", - SUBJECT_TABLE, - make,) + crate::db::course::assert_no_child_outlives_a_course_delete( + "subject_orphan_race", + SUBJECT_TABLE, + make, + ) .await; } @@ -356,10 +358,7 @@ mod tests { // A real exam row per round: a question write moves its exam's // counter, so a minted id nothing wrote is a 404 and no round would // reach the subject race this test is about. - let exam = crate::domain::exam::published_exam(&db) - .await - .get_id() - .clone(); + let exam = crate::db::exam::published_exam(&db).await.get_id().clone(); let subject = Subject::create( &course, SubjectName::try_new("Limits").unwrap(), diff --git a/src/service/course.rs b/src/service/course.rs index 31018fe..e6be111 100644 --- a/src/service/course.rs +++ b/src/service/course.rs @@ -11,8 +11,8 @@ use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, Cou use crate::domain::course_note_file::CourseNoteFile; use crate::domain::homework_file::HomeworkFile; use crate::domain::question_image::QuestionImage; -use crate::domain::term::{self, TermId}; use crate::domain::role::Role; +use crate::domain::term::{self, TermId}; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ValidationError}; @@ -138,8 +138,7 @@ pub struct DeleteOutcome { /// Delete the course: collect the image/homework/note-file blob keys, then /// run the cascading delete. /// -/// Writer lease of [`crate::web::exams::EXAM_LOCK`] (moving to -/// `crate::service::exam_attempt` with the exam lane's split), for +/// Writer lease of [`crate::service::exam_attempt::EXAM_LOCK`], for /// `delete_exam`'s reason: this cascade sweeps the course's exams *and their /// attempts*, and an attempt is the one exam child whose write cannot /// collide with the sweep (its claim lands on the student's row, never the diff --git a/src/service/exam.rs b/src/service/exam.rs new file mode 100644 index 0000000..dc09c45 --- /dev/null +++ b/src/service/exam.rs @@ -0,0 +1,287 @@ +//! Exam workflows: the PATCH re-derive — the merge (set / clear / keep per +//! field) re-judged against a fresh read every retry round, and the +//! mode-freeze, re-draft, and kind gates that guard it — and the delete that +//! collects the image blob keys under the writer lease before the cascade. +//! The queries live in [`crate::db::exam`]; the sitting workflows next door +//! in [`crate::service::exam_attempt`], whose [`EXAM_LOCK`] every path here +//! leases. + +use crate::constant::CAS_UPDATE_RETRIES; +use crate::database::Database; +use crate::db::exam; +use crate::domain::answer_image::AnswerImage; +use crate::domain::course::CourseId; +use crate::domain::exam::{ + Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, + ExamSchedule, ExamTitle, redraft_error, +}; +use crate::domain::exam_result::ExamResult; +use crate::domain::question_image::QuestionImage; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; +use crate::service::course::require_open; +use crate::service::exam_attempt::{EXAM_LOCK, any_for_exam, course_of}; + +pub async fn create( + db: &Database, + creator: &UserId, + course: &CourseId, + title: ExamTitle, + description: ExamDescription, + kind: ExamKind, + schedule: ExamSchedule, + max_attempts: ExamAttemptLimit, + allow_rejoin: bool, + allow_review: bool, + draft: bool, +) -> Result { + exam::create( + db, + creator, + course, + title, + description, + kind, + schedule, + max_attempts, + allow_rejoin, + allow_review, + draft, + ) + .await +} + +/// The exam row, for callers that only inspect it — the web layer's gates +/// read through here. +pub async fn read(db: &Database, id: &ExamId) -> Result, AppError> { + exam::read(db, id).await +} + +pub async fn list_all(db: &Database) -> Result, AppError> { + exam::list_all(db).await +} + +pub async fn list_for_course(db: &Database, course: &CourseId) -> Result, AppError> { + exam::list_for_course(db, course).await +} + +/// Every exam of every course in `courses` (one query) — the catalog as one +/// user sees it. +pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result, AppError> { + exam::list_for_courses(db, courses).await +} + +/// A `PATCH /exams/{id}` request after field validation: every value the +/// request *set* is already validated (title, description, mode, duration, +/// and attempt limit by their newtypes; the kind against the school's +/// current list; newly set window ends by the web layer's no-past grace). +/// What is *kept* — and whether the merged whole is a legal schedule — are +/// the update's own decisions, re-derived against a fresh read every retry +/// round, so they live here and not in the web layer. A `None` field keeps +/// the stored value; the `Option>` schedule fields carry the +/// web DTO's set-or-clear spelling (`Some(None)` = explicit `null`). +pub struct ExamPatch { + pub title: Option, + pub description: Option, + pub kind: Option, + pub mode: Option>, + pub starts_at: Option>, + pub ends_at: Option>, + pub duration_ms: Option>, + pub max_attempts: Option, + pub allow_rejoin: Option, + pub allow_review: Option, + pub draft: Option, +} + +/// Re-derive and save the exam: merge the patch over a fresh read, re-validate +/// the schedule as a unit, judge every business gate against that same row, +/// and land the whole merge with the compare-and-set — retried while the row +/// keeps moving under the snapshot. +/// +/// *Reader* lease of [`EXAM_LOCK`] for exactly one pairing: the mode gate +/// below reads `exam_attempt`, and an attempt start takes the *writer* +/// lease, so a first sitting still cannot land between that gate and the +/// write, as it always did. +/// +/// It buys nothing against grading, which is a reader too: the re-draft gate +/// is therefore enforced inside the update's own transaction +/// ([`exam::update_if_unchanged`]), where the store decides it. The gate +/// below stays as the pre-flight — same error, one round trip earlier. +/// Concurrent PATCHes of this exam no longer queue behind each other either: +/// the lost update they used to cause is refused by the compare-and-set. +pub async fn update(db: &Database, id: &ExamId, patch: &ExamPatch) -> Result { + let _guard = EXAM_LOCK.read().await; + let mut left = CAS_UPDATE_RETRIES; + loop { + let current = exam::read(db, id).await?.ok_or(AppError::NotFound)?; + let course = course_of(¤t, db).await?; + require_open(db, &course).await?; + + let title = patch + .title + .clone() + .unwrap_or_else(|| current.get_title().clone()); + let description = patch + .description + .clone() + .unwrap_or_else(|| current.get_description().clone()); + let kind = patch + .kind + .clone() + .unwrap_or_else(|| current.get_kind().clone()); + + // Merge the schedule (set / clear / keep per field), then re-validate it + // as a unit — a PATCH can't leave a half-schedule behind. Only values this + // request sets are held to the no-past rule: kept ones may legitimately be + // past (a running exam's `starts_at`), and rechecking them would block + // unrelated edits. + let mode = match &patch.mode { + Some(update) => update.clone(), + None => current.get_mode().cloned(), + }; + let starts_at = match patch.starts_at { + Some(update) => update, + None => current.get_starts_at(), + }; + let ends_at = match patch.ends_at { + Some(update) => update, + None => current.get_ends_at(), + }; + let duration_ms = match patch.duration_ms { + Some(update) => update, + None => current.get_duration_ms(), + }; + let schedule = ExamSchedule::try_new(mode, starts_at, ends_at, duration_ms)?; + let max_attempts = patch + .max_attempts + .unwrap_or_else(|| current.get_max_attempts()); + let allow_rejoin = patch + .allow_rejoin + .unwrap_or_else(|| current.get_allow_rejoin()); + let allow_review = patch + .allow_review + .unwrap_or_else(|| current.get_allow_review()); + let draft = patch.draft.unwrap_or(current.is_draft()); + + // Switching sync <-> async <-> open (or back to unscheduled) would + // silently rewrite the deadline rules under students who already sat + // down; extending times, the attempt limit, and the rejoin door are the + // supported live adjustments instead. Gate read and write share the + // call-wide reader lease of [`EXAM_LOCK`], so a first attempt can't + // land in the gap and leave a sat exam's mode flipped under it. + let mode_changed = + schedule.get_mode().map(ExamMode::as_str) != current.get_mode().map(ExamMode::as_str); + if mode_changed && any_for_exam(db, current.get_id()).await? { + return Err(AppError::Conflict( + "cannot change the exam mode after attempts have started", + )); + } + // Re-drafting hides the exam — never out from under a student who + // already sat it or holds a mark on it. Pre-flight only: the write's own + // 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 && !current.is_draft() { + let sat = any_for_exam(db, current.get_id()).await?; + let graded = !ExamResult::list_for_exam(current.get_id(), db) + .await? + .is_empty(); + if sat || graded { + return Err(redraft_error()); + } + } + + // A graded exam keeps its kind. Moving it re-weights every mark it + // already carries — the same silent re-weighting the settings' removal + // guard refuses — and it would strand those marks' references on the + // kind they were counted under, freeing the kind the exam now claims to + // be. Marks are counted on the exam row, and the save below *pins* that + // counter, so a grade landing between this read and the write refuses + // the save (the loop then re-reads and answers the 409 below). + if kind.as_str() != current.get_kind().as_str() && current.get_result_count() > 0 { + return Err(AppError::Conflict( + "cannot change the kind of an exam that already has marks", + )); + } + + if let Some(updated) = exam::update_if_unchanged( + db, + current, + title, + description, + kind, + schedule, + max_attempts, + allow_rejoin, + allow_review, + draft, + ) + .await? + { + return Ok(updated); + } + // The row moved under the snapshot every gate above judged: re-read and + // re-merge, so both edits land instead of the later reverting the earlier. + left -= 1; + if left == 0 { + return Err(AppError::Conflict( + "the exam kept changing underneath this update — try again", + )); + } + } +} + +/// What [`delete`] did: the blob keys of the image rows the cascade removed — +/// exactly whose files the web layer may unlink. +#[derive(Debug)] +pub struct DeleteOutcome { + pub image_files: Vec, + pub answer_image_files: Vec, +} + +/// Delete the exam: collect the question/answer image blob keys, then run the +/// cascading delete. +/// +/// 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 +/// child of an exam now writes the exam row in its own transaction, so the +/// store refuses the pair; an attempt cannot, because its claim lands on the +/// *student's* row (`exam_sat_total`) and touches nothing this delete +/// writes. `start_attempt` already takes the writer lease from its exam read +/// through the insert, so this one lease is the whole ordering: a start +/// either finishes before the sweep (which then takes its row) or reads no +/// exam at all and is a 404. Left orphaned, that attempt kept a sitting on +/// the student's lifetime counter and could mint a badge — awards are +/// add-only and never revoked — for an exam that never existed. +/// +/// It spans the blob names too: they are collected *before* the rows go, so +/// an image row written after that snapshot would strand its bytes on disk +/// even though the row itself is now refused. +/// +/// corner-cut: process-local, so it holds because the deployment runs one +/// process by contract with stop-the-world deploys (two overlapping +/// binaries would +/// reopen it). Closing it in the store means the `cap` shape the counter +/// work already sketched: `claim_and_create` gaining a second record to +/// touch, so the attempt writes the exam key as every other child does. +pub async fn delete(db: &Database, target: &Exam) -> Result { + require_open(db, &course_of(target, db).await?).await?; + let _guard = EXAM_LOCK.write().await; + // Rows go first (the delete cascades them), blobs after — a crash in + // between strands at worst an unreachable blob. + let images = QuestionImage::list_for_exam(target.get_id(), db).await?; + let answer_images = AnswerImage::list_for_exam(target.get_id(), db).await?; + exam::delete(db, target.clone()).await?; + Ok(DeleteOutcome { + image_files: images + .iter() + .map(|image| image.get_file().to_string()) + .collect(), + answer_image_files: answer_images + .iter() + .map(|image| image.get_file().to_string()) + .collect(), + }) +} diff --git a/src/service/exam_attempt.rs b/src/service/exam_attempt.rs index 70c965d..9314ce8 100644 --- a/src/service/exam_attempt.rs +++ b/src/service/exam_attempt.rs @@ -299,7 +299,7 @@ pub async fn start_attempt( user: &User, ) -> Result<(Exam, ExamAttempt, bool), AppError> { let _guard = EXAM_LOCK.write().await; - let exam = crate::domain::exam::Exam::read(exam_id, db) + let exam = crate::db::exam::read(db, exam_id) .await? .ok_or(AppError::NotFound)?; ensure_sittable(&exam)?; @@ -505,7 +505,8 @@ mod tests { 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( + let exam = crate::db::exam::create( + db, &creator, &course, ExamTitle::try_new("practice").unwrap(), @@ -517,7 +518,6 @@ mod tests { true, false, false, - db, ) .await .unwrap(); diff --git a/src/service/mod.rs b/src/service/mod.rs index 892e3cd..d7236d6 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -3,6 +3,7 @@ pub mod appointment; pub mod course; +pub mod exam; pub mod exam_attempt; pub mod note; pub mod payment_ledger; diff --git a/src/web/courses.rs b/src/web/courses.rs index 9a52348..af717c7 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -14,8 +14,7 @@ use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, Cou use crate::domain::course_session::{CourseSession, SessionTopic}; use crate::domain::enrollment::Enrollment; use crate::domain::exam::{ - Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, - ExamTitle, + ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, }; use crate::domain::homework::{Homework, HomeworkTitle}; use crate::domain::role::Role; @@ -265,7 +264,10 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let (courses, total) = service::course::list_enrolled(&st.db, user.get_id(), limit, offset).await?; + let (courses, total) = + service::course::list_enrolled(&st.db, user.get_id(), limit, offset).await?; let people = person_map(courses.iter().flat_map(course_people), &st.db).await?; let items = courses .iter() @@ -865,7 +868,8 @@ async fn create_exam_in_course( Some(limit) => ExamAttemptLimit::try_new(limit)?, None => ExamAttemptLimit::single(), }; - let exam = Exam::create( + let exam = crate::service::exam::create( + &st.db, user.get_id(), course.get_id(), title, @@ -876,7 +880,6 @@ async fn create_exam_in_course( req.allow_rejoin.unwrap_or(true), req.allow_review.unwrap_or(false), req.draft.unwrap_or(false), - &st.db, ) .await?; Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam)))) @@ -916,7 +919,7 @@ async fn list_course_exams( "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course", )); } - let mut exams = Exam::list_for_course(course.get_id(), &st.db).await?; + let mut exams = crate::service::exam::list_for_course(&st.db, course.get_id()).await?; // Drafts are the managers' workbench — enrolled students don't see them. if !can_manage_course(&course, &user) { exams.retain(|exam| !exam.is_draft()); @@ -1359,13 +1362,10 @@ mod tests { let db = init_mem().await.unwrap(); let creator = user("creator", Role::Teacher, &db).await; let assigned = user("assigned", Role::Teacher, &db).await; - let course = service::course::assign_teacher( - &db, - &course(&creator, &db).await, - assigned.get_id(), - ) - .await - .unwrap(); + let course = + service::course::assign_teacher(&db, &course(&creator, &db).await, assigned.get_id()) + .await + .unwrap(); // Still teacher+: untouched by the floor. assert!(can_manage_course(&course, &assigned)); // ...but never an owner, assigned or not. diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 2a0c68e..35aec3f 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -144,7 +144,7 @@ pub async fn attempt_ws( Path(id): Path, ws: WebSocketUpgrade, ) -> Result { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; ensure_sittable(&exam)?; @@ -233,7 +233,7 @@ async fn room( /// wins. Targeting the sitting by id (never "the latest") means a retake /// 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 { + let attempt = match crate::service::exam::read(db, exam_id).await { Ok(Some(exam)) => match read(db, attempt_id).await { Ok(Some(attempt)) if attempt.status(&exam, Timestamp::now()) == AttemptStatus::InProgress => @@ -328,7 +328,9 @@ async fn state_frame( attempt: &ExamAttemptId, db: &Database, ) -> Result<(Value, AttemptStatus, Option), AppError> { - let exam = Exam::read(exam, db).await?.ok_or(AppError::NotFound)?; + let exam = crate::service::exam::read(db, exam) + .await? + .ok_or(AppError::NotFound)?; let attempt = read(db, attempt).await?.ok_or(AppError::NotFound)?; let now = Timestamp::now(); let status = attempt.status(&exam, now); @@ -411,7 +413,7 @@ async fn handle_message( // a failure possibly be about this one question rather than about // the room. See [`error_frame_for`]. let mut in_save = false; - let saved = match Exam::read(exam_id, db).await { + let saved = match crate::service::exam::read(db, exam_id).await { Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await { Ok(attempt) => { in_save = true; @@ -453,7 +455,7 @@ async fn handle_message( ClientMessage::Finish => { // Submit the room's own sitting — a stale room must not submit a // retake it never hosted. - let finished = match Exam::read(exam_id, db).await { + let finished = match crate::service::exam::read(db, exam_id).await { Ok(Some(exam)) => { // Its own archived-term gate: `finish` is the one // sitting-side write that does not go through @@ -461,7 +463,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?; + crate::service::course::require_open(db, &course_of(&exam, db).await?) + .await?; finish(db, attempt).await } .await diff --git a/src/web/exams/attempts.rs b/src/web/exams/attempts.rs index 1a9068d..cfbf29d 100644 --- a/src/web/exams/attempts.rs +++ b/src/web/exams/attempts.rs @@ -189,7 +189,7 @@ pub(crate) async fn my_attempt( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let attempt = exam_attempt::read_latest_for_user(&st.db, exam.get_id(), user.get_id()) @@ -235,7 +235,7 @@ pub(crate) async fn finish_attempt( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let finished = exam_attempt::finish_attempt(&st.db, &exam, user.get_id()).await?; @@ -457,7 +457,7 @@ pub(crate) async fn exam_live( RequireTeacher(user): RequireTeacher, Path(id): Path, ) -> Result, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let course = exam_attempt::course_of(&exam, &st.db).await?; @@ -571,7 +571,7 @@ pub(crate) async fn attempt_questions( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result>, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; exam_attempt::ensure_enrolled(&exam, user.get_id(), &st.db).await?; @@ -657,7 +657,7 @@ pub(crate) async fn save_answer( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let answer = exam_attempt::save_answer_checked( @@ -705,7 +705,7 @@ pub(crate) async fn attempt_answers( RequireTeacher(user): RequireTeacher, Path((id, target)): Path<(String, String)>, ) -> Result, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let course = exam_attempt::course_of(&exam, &st.db).await?; diff --git a/src/web/exams/images.rs b/src/web/exams/images.rs index 9faf82e..43c15db 100644 --- a/src/web/exams/images.rs +++ b/src/web/exams/images.rs @@ -95,7 +95,7 @@ pub(crate) async fn image_managed_exam( user: &User, id: &str, ) -> Result { - let exam = Exam::read(&ExamId::from_key(id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(id)) .await? .ok_or(AppError::NotFound)?; let course = course_of(&exam, &st.db).await?; @@ -231,7 +231,7 @@ pub(crate) async fn get_question_image( CurrentUser(user): CurrentUser, Path((id, qid)): Path<(String, String)>, ) -> Result { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; ensure_question_content_visible(&st, &exam, &user).await?; @@ -343,7 +343,7 @@ pub(crate) async fn get_choice_image( CurrentUser(user): CurrentUser, Path((id, qid, choice_id)): Path<(String, String, String)>, ) -> Result { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; ensure_question_content_visible(&st, &exam, &user).await?; @@ -459,7 +459,7 @@ pub(crate) async fn upload_answer_image( Path((id, qid)): Path<(String, String)>, mut multipart: Multipart, ) -> Result<(StatusCode, Json), AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; ensure_student(&user)?; @@ -541,7 +541,7 @@ pub(crate) async fn delete_answer_image( CurrentUser(user): CurrentUser, Path((id, qid)): Path<(String, String)>, ) -> Result { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; ensure_student(&user)?; @@ -594,7 +594,7 @@ pub(crate) async fn get_answer_image( CurrentUser(user): CurrentUser, Path((id, qid)): Path<(String, String)>, ) -> Result { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; ensure_question_content_visible(&st, &exam, &user).await?; @@ -634,7 +634,7 @@ pub(crate) async fn get_student_answer_image( RequireTeacher(user): RequireTeacher, Path((id, target, qid)): Path<(String, String, String)>, ) -> Result { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let course = course_of(&exam, &st.db).await?; diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index 0011dff..676113d 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -10,7 +10,7 @@ use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; -use crate::constant::{CAS_UPDATE_RETRIES, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; +use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; use crate::database::Database; use crate::domain::answer_image::AnswerImage; use crate::domain::badge; @@ -18,8 +18,7 @@ use crate::domain::bank_question::{BankQuestion, BankQuestionId}; use crate::domain::bank_question_image::BankQuestionImage; use crate::domain::enrollment::Enrollment; use crate::domain::exam::{ - Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, - ExamSchedule, ExamTitle, + Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, ExamTitle, }; use crate::domain::exam_answer::{ExamAnswer, auto_score}; use crate::domain::exam_question::{ @@ -33,7 +32,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::service::exam_attempt::{EXAM_LOCK, course_of, read_latest_for_user}; use crate::state::AppState; use super::bank_questions::BankQuestionResponse; @@ -267,7 +266,7 @@ async fn list_exams( ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; let exams = if user.get_role().at_least(Role::Manager) { - Exam::list_all(&st.db).await? + service::exam::list_all(&st.db).await? } else { let courses = visible_courses(&user, &st.db).await?; let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect(); @@ -278,7 +277,7 @@ async fn list_exams( .filter(|c| can_manage_course(c, &user)) .map(|c| c.get_id().key()) .collect(); - let mut exams = Exam::list_for_courses(&ids, &st.db).await?; + let mut exams = service::exam::list_for_courses(&st.db, &ids).await?; exams.retain(|exam| !exam.is_draft() || managed.contains(&exam.get_course().key())); exams }; @@ -321,7 +320,7 @@ async fn get_exam( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let course = course_of(&exam, &st.db).await?; @@ -371,153 +370,82 @@ async fn update_exam( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - // *Reader* lease of [`EXAM_LOCK`] for exactly one pairing: the mode gate - // below reads `exam_attempt`, and an attempt start takes the *writer* - // lease, so a first sitting still cannot land between that gate and the - // write, as it always did. - // - // It buys nothing against grading, which is a reader too: the re-draft gate - // is therefore enforced inside the update's own transaction - // (`Exam::update_if_unchanged`), where the store decides it. The gate - // below stays as the pre-flight — same error, one round trip earlier. - // Concurrent PATCHes of this exam no longer queue behind each other either: - // the lost update they used to cause is refused by the compare-and-set. - let _guard = EXAM_LOCK.read().await; - let mut left = CAS_UPDATE_RETRIES; - let exam = loop { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = 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 edit this exam", - )); - } - crate::service::course::require_open(&st.db, &course).await?; - - let title = match req.title { - Some(ref title) => ExamTitle::try_new(title)?, - None => exam.get_title().clone(), - }; - let description = match req.description { - Some(ref description) => ExamDescription::try_new(description)?, - None => exam.get_description().clone(), - }; - let kind = match req.kind { - // Only a kind this request sets is held to the current settings list — - // a stored kind survives later list edits, like past times survive - // the no-past rule. - Some(ref kind) => { - let school = service::settings::load(&st.db).await?; - ExamKind::try_new(kind, school.get_exam_kinds())? - } - None => exam.get_kind().clone(), - }; - - // Merge the schedule (set / clear / keep per field), then re-validate it - // as a unit — a PATCH can't leave a half-schedule behind. Only values this - // request sets are held to the no-past rule: kept ones may legitimately be - // past (a running exam's `starts_at`), and rechecking them would block - // unrelated edits. - let mode = match req.mode { - Some(ref update) => update.as_deref().map(ExamMode::try_new).transpose()?, - None => exam.get_mode().cloned(), - }; - let starts_at = match req.starts_at { - Some(update) => { - let starts_at = update.map(Timestamp::from_millis); - check_not_past("starts_at", starts_at)?; - starts_at - } - None => exam.get_starts_at(), - }; - let ends_at = match req.ends_at { - Some(update) => { - let ends_at = update.map(Timestamp::from_millis); - check_not_past("ends_at", ends_at)?; - ends_at - } - None => exam.get_ends_at(), - }; - let duration_ms = match req.duration_ms { - Some(update) => update.map(ExamDuration::try_new).transpose()?, - None => exam.get_duration_ms(), - }; - let schedule = ExamSchedule::try_new(mode, starts_at, ends_at, duration_ms)?; - let max_attempts = match req.max_attempts { - Some(limit) => ExamAttemptLimit::try_new(limit)?, - None => exam.get_max_attempts(), - }; - let allow_rejoin = req.allow_rejoin.unwrap_or_else(|| exam.get_allow_rejoin()); - let allow_review = req.allow_review.unwrap_or_else(|| exam.get_allow_review()); - let draft = req.draft.unwrap_or_else(|| exam.is_draft()); - - // Switching sync <-> async <-> open (or back to unscheduled) would - // silently rewrite the deadline rules under students who already sat - // down; extending times, the attempt limit, and the rejoin door are the - // supported live adjustments instead. Gate read and write share the - // handler-wide writer lease of [`EXAM_LOCK`], so a first attempt can't - // 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 && any_for_exam(&st.db, exam.get_id()).await? { - return Err(AppError::Conflict( - "cannot change the exam mode after attempts have started", - )); - } - // Re-drafting hides the exam — never out from under a student who - // already sat it or holds a mark on it. Pre-flight only: the write's own - // 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 = any_for_exam(&st.db, exam.get_id()).await?; - let graded = !ExamResult::list_for_exam(exam.get_id(), &st.db) - .await? - .is_empty(); - if sat || graded { - return Err(crate::domain::exam::redraft_error()); - } - } - - // A graded exam keeps its kind. Moving it re-weights every mark it - // already carries — the same silent re-weighting the settings' removal - // guard refuses — and it would strand those marks' references on the - // kind they were counted under, freeing the kind the exam now claims to - // be. Marks are counted on the exam row, and the save below *pins* that - // counter, so a grade landing between this read and the write refuses - // the save (the loop then re-reads and answers the 409 below). - if kind.as_str() != exam.get_kind().as_str() && exam.get_result_count() > 0 { - return Err(AppError::Conflict( - "cannot change the kind of an exam that already has marks", - )); - } + let exam = service::exam::read(&st.db, &ExamId::from_key(&id)) + .await? + .ok_or(AppError::NotFound)?; + let course = 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 edit this exam", + )); + } + crate::service::course::require_open(&st.db, &course).await?; - if let Some(updated) = exam - .update_if_unchanged( - title, - description, - kind, - schedule, - max_attempts, - allow_rejoin, - allow_review, - draft, - &st.db, - ) - .await? - { - break updated; + // Field validation, in the order the request is judged — only values this + // request sets are held to the rules (a stored kind survives list edits, + // kept times may legitimately be past). The merge against the stored row, + // the schedule re-validation as a unit, and the mode-freeze / re-draft / + // kind gates are the workflow's own steps: + // [`crate::service::exam::update`] re-derives them per retry round behind + // the compare-and-set. + let title = req.title.as_deref().map(ExamTitle::try_new).transpose()?; + let description = req + .description + .as_deref() + .map(ExamDescription::try_new) + .transpose()?; + let kind = match &req.kind { + // Only a kind this request sets is held to the current settings list — + // a stored kind survives later list edits, like past times survive + // the no-past rule. + Some(kind) => Some(ExamKind::try_new( + kind, + service::settings::load(&st.db).await?.get_exam_kinds(), + )?), + None => None, + }; + let mode = match &req.mode { + Some(update) => Some(update.as_deref().map(ExamMode::try_new).transpose()?), + None => None, + }; + let starts_at = match req.starts_at { + Some(update) => { + let starts_at = update.map(Timestamp::from_millis); + check_not_past("starts_at", starts_at)?; + Some(starts_at) } - // The row moved under the snapshot every gate above judged: re-read and - // re-merge, so both edits land instead of the later reverting the earlier. - left -= 1; - if left == 0 { - return Err(AppError::Conflict( - "the exam kept changing underneath this update — try again", - )); + None => None, + }; + let ends_at = match req.ends_at { + Some(update) => { + let ends_at = update.map(Timestamp::from_millis); + check_not_past("ends_at", ends_at)?; + Some(ends_at) } + None => None, + }; + let duration_ms = match req.duration_ms { + Some(update) => Some(update.map(ExamDuration::try_new).transpose()?), + None => None, }; + let max_attempts = req + .max_attempts + .map(ExamAttemptLimit::try_new) + .transpose()?; + let patch = service::exam::ExamPatch { + title, + description, + kind, + mode, + starts_at, + ends_at, + duration_ms, + max_attempts, + allow_rejoin: req.allow_rejoin, + allow_review: req.allow_review, + draft: req.draft, + }; + let exam = service::exam::update(&st.db, exam.get_id(), &patch).await?; Ok(Json(ExamResponse::new(&exam))) } @@ -543,7 +471,7 @@ async fn delete_exam( RequireTeacher(user): RequireTeacher, Path(id): Path, ) -> Result { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let course = course_of(&exam, &st.db).await?; @@ -552,41 +480,16 @@ 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?; - // *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 - // child of an exam now writes the exam row in its own transaction, so the - // store refuses the pair; an attempt cannot, because its claim lands on the - // *student's* row (`exam_sat_total`) and touches nothing this delete - // writes. `start_attempt` already takes the writer lease from its exam read - // through the insert, so this one lease is the whole ordering: a start - // either finishes before the sweep (which then takes its row) or reads no - // exam at all and is a 404. Left orphaned, that attempt kept a sitting on - // the student's lifetime counter and could mint a badge — awards are - // add-only and never revoked — for an exam that never existed. - // - // It spans the blob names too: they are collected *before* the rows go, so - // an image row written after that snapshot would strand its bytes on disk - // even though the row itself is now refused. - // - // corner-cut: process-local, so it holds because the deployment runs one - // process by contract with stop-the-world deploys (two overlapping - // binaries would - // reopen it). Closing it in the store means the `cap` shape the counter - // work already sketched: `claim_and_create` gaining a second record to - // touch, so the attempt writes the exam key as every other child does. - let _guard = EXAM_LOCK.write().await; - // Rows go first (the delete cascades them), blobs after — a crash in - // between strands at worst an unreachable blob. - let images = QuestionImage::list_for_exam(exam.get_id(), &st.db).await?; - let answer_images = AnswerImage::list_for_exam(exam.get_id(), &st.db).await?; - exam.delete(&st.db).await?; - for image in &images { - remove_blob(&st.files_path, image.get_file()).await; + // The workflow — the archived-term gate, the *writer* lease of + // [`EXAM_LOCK`] across the cascade, blob-key collection, the delete — is + // [`crate::service::exam::delete`]'s. Blob unlinking stays here because + // only the web layer knows `files_path`. + let outcome = service::exam::delete(&st.db, &exam).await?; + for file in &outcome.image_files { + remove_blob(&st.files_path, file).await; } - for image in &answer_images { - remove_blob(&st.files_path, image.get_file()).await; + for file in &outcome.answer_image_files { + remove_blob(&st.files_path, file).await; } Ok(StatusCode::NO_CONTENT) } @@ -628,7 +531,7 @@ async fn grade( // results) could slip between them and leave a mark on a hidden exam. let _guard = EXAM_LOCK.read().await; // Exam must exist. - let exam = Exam::read(&exam_id, &st.db) + let exam = service::exam::read(&st.db, &exam_id) .await? .ok_or(AppError::NotFound)?; let course = course_of(&exam, &st.db).await?; @@ -753,7 +656,7 @@ async fn list_results( ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; // Exam must exist — a missing exam is a 404, not an empty result list. - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let course = course_of(&exam, &st.db).await?; @@ -835,7 +738,7 @@ async fn remove_result( RequireTeacher(user): RequireTeacher, Path((id, target)): Path<(String, String)>, ) -> Result { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let course = course_of(&exam, &st.db).await?; @@ -879,7 +782,7 @@ async fn exam_statistics( Path(id): Path, ) -> Result, AppError> { // Exam must exist — a missing exam is a 404, not an empty statistic. - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let course = course_of(&exam, &st.db).await?; diff --git a/src/web/exams/questions.rs b/src/web/exams/questions.rs index 0294883..b195a72 100644 --- a/src/web/exams/questions.rs +++ b/src/web/exams/questions.rs @@ -197,7 +197,7 @@ pub(crate) async fn create_question( Path(id): Path, Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let course = course_of(&exam, &st.db).await?; @@ -258,7 +258,7 @@ pub(crate) async fn list_questions( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let course = course_of(&exam, &st.db).await?; @@ -336,7 +336,7 @@ pub(crate) async fn update_question( Path((id, qid)): Path<(String, String)>, Json(req): Json, ) -> Result, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let course = course_of(&exam, &st.db).await?; @@ -424,7 +424,7 @@ pub(crate) async fn delete_question( RequireTeacher(user): RequireTeacher, Path((id, qid)): Path<(String, String)>, ) -> Result { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let course = course_of(&exam, &st.db).await?; @@ -496,7 +496,7 @@ pub(crate) async fn question_from_bank( Path((id, bid)): Path<(String, String)>, Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let course = course_of(&exam, &st.db).await?; @@ -627,7 +627,7 @@ pub(crate) async fn question_refresh_from_bank( RequireTeacher(user): RequireTeacher, Path((id, qid)): Path<(String, String)>, ) -> Result, AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let course = course_of(&exam, &st.db).await?; @@ -752,7 +752,7 @@ pub(crate) async fn question_to_bank( RequireTeacher(user): RequireTeacher, Path((id, qid)): Path<(String, String)>, ) -> Result<(StatusCode, Json), AppError> { - let exam = Exam::read(&ExamId::from_key(&id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let course = course_of(&exam, &st.db).await?; diff --git a/src/web/exams/review.rs b/src/web/exams/review.rs index a4dfe8a..c21268f 100644 --- a/src/web/exams/review.rs +++ b/src/web/exams/review.rs @@ -13,7 +13,7 @@ use crate::service::exam_attempt::{ /// The exam plus the manage-rights check the grading and history reads share. pub(crate) async fn gradable_exam(st: &AppState, user: &User, id: &str) -> Result { - let exam = Exam::read(&ExamId::from_key(id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(id)) .await? .ok_or(AppError::NotFound)?; let course = course_of(&exam, &st.db).await?; @@ -203,7 +203,7 @@ pub(crate) async fn reviewable_exam( user: &User, id: &str, ) -> Result { - let exam = Exam::read(&ExamId::from_key(id), &st.db) + let exam = crate::service::exam::read(&st.db, &ExamId::from_key(id)) .await? .ok_or(AppError::NotFound)?; if exam.is_draft() { @@ -268,7 +268,7 @@ async fn live_elsewhere( let now = Timestamp::now(); let mut live = Vec::new(); 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 { + let Some(other) = crate::service::exam::read(&st.db, attempt.get_exam()).await? else { continue; }; if attempt.status(&other, now) == AttemptStatus::InProgress { diff --git a/src/web/marks.rs b/src/web/marks.rs index 5ea9970..401f789 100644 --- a/src/web/marks.rs +++ b/src/web/marks.rs @@ -107,7 +107,7 @@ async fn build_report( let mut blocks = Vec::with_capacity(courses.len()); for course in &courses { - let exams = Exam::list_for_course(course.get_id(), db).await?; + let exams = crate::service::exam::list_for_course(db, course.get_id()).await?; let by_key: HashMap<&str, &Exam> = exams.iter().map(|e| (e.get_id().key(), e)).collect(); let results = ExamResult::list_for_user_in_course(course.get_id(), user, db).await?; diff --git a/tests/regress_course_child_orphans.rs b/tests/regress_course_child_orphans.rs index a7fa258..0a9100a 100644 --- a/tests/regress_course_child_orphans.rs +++ b/tests/regress_course_child_orphans.rs @@ -31,7 +31,7 @@ //! //! The **race** half drives the real interleaving and lives in-crate, one pin //! per child beside the create it pins — -//! `domain::exam::tests::an_exam_never_outlives_its_course`, +//! `db::exam::tests::an_exam_never_outlives_its_course`, //! `domain::course_session::tests::a_session_never_outlives_its_course`, //! `domain::subject::tests::a_subject_never_outlives_its_course` — over the //! shared harness `domain::course::assert_no_child_outlives_a_course_delete`. @@ -54,7 +54,7 @@ use hezarfen_backend::domain::course_note::{CourseNote, CourseNoteContent, Cours use hezarfen_backend::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; use hezarfen_backend::domain::course_session::{CourseSession, SessionTopic}; use hezarfen_backend::domain::exam::{ - Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle, + ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle, }; use hezarfen_backend::domain::settings::Settings; use hezarfen_backend::domain::subject::{Subject, SubjectDescription, SubjectName}; @@ -102,7 +102,8 @@ async fn drop_course(course: &CourseId, db: &Database) -> Result fn make_exam(course: CourseId, db: Database) -> JoinHandle> { tokio::spawn(async move { let kinds = Settings::defaults().get_exam_kinds().to_vec(); - Exam::create( + hezarfen_backend::db::exam::create( + &db, &teacher(), &course, ExamTitle::try_new("quiz").unwrap(), @@ -113,7 +114,6 @@ fn make_exam(course: CourseId, db: Database) -> JoinHandle> true, false, false, - &db, ) .await .map(|_| ()) @@ -325,15 +325,9 @@ async fn a_course_note_file_under_a_deleted_note_is_refused() { .await .unwrap(); assert!( - course::delete( - &db, - course::read(&db, &course) - .await - .unwrap() - .unwrap() - ) - .await - .unwrap(), + course::delete(&db, course::read(&db, &course).await.unwrap().unwrap()) + .await + .unwrap(), "the course, and its note with it, goes" );