From c192f7e540b456b0f7674ea17183c81e4a73517e 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:51:08 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=B9=20chore:=20split=20exam=5Fquestion?= =?UTF-8?q?=20into=20domain/db/service=20layers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/db/exam_attempt.rs | 4 +- src/db/exam_question.rs | 722 ++++++++++++++++++++++++++++++++++ src/db/mod.rs | 1 + src/domain/bank_question.rs | 10 +- src/domain/exam.rs | 22 +- src/domain/exam_question.rs | 740 +---------------------------------- src/domain/subject.rs | 22 +- src/service/exam_attempt.rs | 24 +- src/service/exam_question.rs | 134 +++++++ src/service/mod.rs | 1 + src/web/exam_ws.rs | 6 +- src/web/exams/attempts.rs | 10 +- src/web/exams/images.rs | 3 +- src/web/exams/questions.rs | 95 ++--- src/web/exams/review.rs | 13 +- tests/integration.rs | 32 +- 16 files changed, 973 insertions(+), 866 deletions(-) create mode 100644 src/db/exam_question.rs create mode 100644 src/service/exam_question.rs diff --git a/src/db/exam_attempt.rs b/src/db/exam_attempt.rs index 0c938d2..4ea6550 100644 --- a/src/db/exam_attempt.rs +++ b/src/db/exam_attempt.rs @@ -349,13 +349,13 @@ mod tests { ) .await .unwrap(); - let question = ExamQuestion::create( + let question = crate::db::exam_question::create( + db, exam.get_id(), subject.get_id().clone(), crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(), QuestionPoints::try_new(5).unwrap(), spec, - db, ) .await .unwrap(); diff --git a/src/db/exam_question.rs b/src/db/exam_question.rs new file mode 100644 index 0000000..dda75ea --- /dev/null +++ b/src/db/exam_question.rs @@ -0,0 +1,722 @@ +//! The `exam_question` table: row reads and listings, the answer-key join +//! behind review hiding, and the field-scoped writes that tie the freeze gate +//! and the subject's reference counter into their own transaction. The +//! workflows and the freeze pre-flight live in +//! [`crate::service::exam_question`]. + +use std::collections::HashSet; + +use surrealdb::types::{RecordId, SurrealValue}; + +use crate::constant::SUBJECT_QUESTION_COUNT_FIELD; +use crate::database::Database; +use crate::db::cap; +use crate::db::page::PagedList; +use crate::domain::bank_question::BankQuestionId; +use crate::domain::exam::ExamId; +use crate::domain::exam_question::{ + ExamQuestion, ExamQuestionId, QuestionPoints, QuestionSpec, QuestionText, +}; +use crate::domain::subject::SubjectId; +use crate::error::{AppError, ValidationError}; + +/// The `THROW` markers the folded counter moves abort with: the subject the +/// reference was to be claimed on is gone, the question being patched is gone, +/// and the subject this move started from is no longer the one the handler +/// read. File-local like every other marker set (`cap`'s, `subject`'s). +const SUBJECT_MARK: &str = "question_subject_gone"; +const ROW_MARK: &str = "question_row_gone"; +const STALE_MARK: &str = "question_stale_move"; + +/// The one answer for a subject that isn't there — a claim missing it and the +/// web layer's pre-flight lookup missing it are the same 400. +fn dead_subject() -> AppError { + AppError::Validation(ValidationError::Invalid { + field: "subject_id", + reason: "subject does not exist", + }) +} + +pub async fn create( + db: &Database, + exam: &ExamId, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, +) -> Result { + insert(db, exam, subject, text, points, spec, None).await +} + +/// Like [`create`], but records the bank template this question was +/// instantiated from (`POST …/questions/from-bank/{bid}`). +pub async fn create_from_bank( + db: &Database, + exam: &ExamId, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, + source: BankQuestionId, +) -> Result { + insert(db, exam, subject, text, points, spec, Some(source)).await +} + +#[allow(clippy::too_many_arguments)] +async fn insert( + db: &Database, + exam: &ExamId, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, + from_bank: Option, +) -> Result { + let counted = subject.record(); + let question = ExamQuestion { + id: ExamQuestionId::generate(), + exam: exam.clone(), + subject, + text, + points, + kind: spec.kind, + choices: spec.choices, + correct: spec.correct, + from_bank, + // An insert never banks anything: only a to-bank save writes this. + banked_as: None, + }; + // The freeze gate and the subject's reference ride in the same + // transaction as the insert: a question cannot appear under an exam + // somebody has already started, and the claim that accounts for it + // cannot outlive a row that never landed. Claiming in its own query + // (with a release on failure, as this did) leaves a window where a + // crash strands the count — and the subject delete is conditioned on + // that count reading zero, so a stranded one makes the subject + // undeletable forever. A missed claim means the subject is already gone + // — the same 400 the web layer's pre-flight check answers with. + // + // Re-sendable despite the `CREATE`: a lost round aborts having written + // nothing and `$id` is a ULID minted once per call, so the re-send + // cannot answer "already exists" (there is no UNIQUE index on + // `exam_question`) — the one thing the retry cannot survive. + let id = question.id.record(); + // One counter write in flight at a time, like every other counter write. + let _guard = cap::counter_lock().await; + let mut result = crate::db::exam_attempt::write_unfrozen_with( + db, + exam, + &format!( + "LET $seat = (UPDATE $subject SET {SUBJECT_QUESTION_COUNT_FIELD} = \ + ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); + IF array::len($seat) = 0 {{ THROW '{SUBJECT_MARK}' }}; + CREATE $id CONTENT $question;" + ), + vec![ + ("subject".into(), counted.into_value()), + ("id".into(), id.into_value()), + ("question".into(), question.into_value()), + ], + vec![(SUBJECT_MARK, dead_subject())], + ) + .await?; + // Counted off the statements that actually ran rather than a fixed + // slot, so folding another gate in above can never mis-read the row. + let slot = result.num_statements().saturating_sub(2); + result + .take::>(slot)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to create exam question".into())) +} + +pub async fn read(db: &Database, id: &ExamQuestionId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// The exam's questions in presentation order (ULID ids sort by creation). +pub async fn list_for_exam( + db: &Database, + exam: &ExamId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new("exam_question WHERE exam = $ex", "ORDER BY id ASC") + .bind("ex", exam.record()) + .run(limit, offset, db) + .await +} + +/// The ids of `exam`'s questions that share a bank template with a question +/// under one of `live` — the questions two exams hold identical `correct` +/// for, because the bank copies the key into every instantiation. Keyed on +/// the template, never on the exam, so only the overlapping questions are +/// named. Empty when `live` is empty. +/// +/// A question links to a template through *either* column and both must be +/// read, on both sides of the join: `from_bank` is the template it was +/// instantiated from, `banked_as` the template minted by saving it into the +/// bank ([`link_banked_as`]). A question authored by hand in exam A +/// and then saved to the bank holds only `banked_as`, while its copy in +/// exam B holds only `from_bank` — matching `from_bank` to `from_bank` saw +/// neither and leaked A's key while B was live. A single coalesced key per +/// row is not enough either: a question instantiated from one template and +/// re-saved as another carries *both*, and only the second one may be the +/// shared link. +/// +/// So: collect every template id reachable from a live exam by either +/// column, then name any of `exam`'s questions pointing at one by either +/// column. `$shared` is built from `!= NONE` filters, so it never holds a +/// `NONE` for an unlinked question's absent column to match against. +pub async fn list_shared_with( + db: &Database, + exam: &ExamId, + live: &[ExamId], +) -> Result, AppError> { + if live.is_empty() { + return Ok(HashSet::new()); + } + let mut result = db + .query( + "LET $shared = array::union( + (SELECT VALUE from_bank FROM exam_question + WHERE exam IN $live AND from_bank != NONE), + (SELECT VALUE banked_as FROM exam_question + WHERE exam IN $live AND banked_as != NONE)); + SELECT VALUE id FROM exam_question + WHERE exam = $ex AND (from_bank IN $shared OR banked_as IN $shared)", + ) + .bind(("ex", exam.record())) + .bind(( + "live", + live.iter().map(ExamId::record).collect::>(), + )) + .await? + .check()?; + Ok(result + .take::>(1)? + .iter() + .map(|id| id.key().to_string()) + .collect()) +} + +/// Write the editable fields, refused outright once the exam has an +/// attempt — the freeze gate is part of this transaction, not a check the +/// caller made a moment earlier under a lock. +/// +/// Field-scoped, no longer a whole-row save. The row also carries +/// `from_bank`/`banked_as`, which [`link_banked_as`] writes from a +/// *different* request: re-stating this snapshot's copy of them would +/// revert a to-bank save that landed in between. That is exactly what the +/// caller's `EXAM_LOCK.write()` used to order (inside one process), and +/// naming the columns removes the need for any ordering at all. +pub async fn update( + db: &Database, + question: ExamQuestion, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, +) -> Result { + // A re-tag moves a reference, and the move rides the very transaction + // that moves the link: the old subject's release, the new one's claim + // and the row write commit together or not at all, so no crash can + // strand a count on a subject nothing points at (which would make it + // undeletable forever). + // + // The two are armed on *different* conditions, which is the whole of + // the rule ([`crate::db::field_update::FieldUpdate::refcount`] states + // it the same way): the counter statements only when the link actually + // changes, but the CAS whenever this write *carries* the link — and it + // always does, because the handler fills an omitted `subject_id` from + // the row it read (`web::exams::questions`), so `subject` is in the + // `SET` of every one of these updates. Arming the CAS on "changed" + // instead would leave the re-stater through: a PATCH carrying the + // subject its own stale snapshot held, sent while a rival's move + // already landed, writes that stale subject straight back over the + // winner — a revert with the counters left pointing at the move. + let retag = + (subject != question.subject).then(|| (subject.record(), question.subject.record())); + let write = "UPDATE $id SET subject = $subject, text = $text, points = $points, + kind = $kind, choices = $choices, correct = $correct"; + let mut bindings = vec![ + ("id".into(), question.id.record().into_value()), + ("subject".into(), subject.record().into_value()), + ("text".into(), text.into_value()), + ("points".into(), points.into_value()), + ("kind".into(), spec.kind.into_value()), + ("choices".into(), spec.choices.into_value()), + ("correct".into(), spec.correct.into_value()), + ]; + let mut statements: Vec = Vec::new(); + let mut refusals: Vec<(&str, AppError)> = Vec::new(); + if let Some((next, previous)) = &retag { + statements.push(format!( + "UPDATE $ref_release SET {SUBJECT_QUESTION_COUNT_FIELD} = \ + math::max([({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) - 1, 0])" + )); + statements.push(format!( + "LET $seat = (UPDATE $ref_claim SET {SUBJECT_QUESTION_COUNT_FIELD} = \ + ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id)" + )); + statements.push(format!( + "IF array::len($seat) = 0 {{ THROW '{SUBJECT_MARK}' }}" + )); + bindings.push(("ref_claim".into(), next.clone().into_value())); + bindings.push(("ref_release".into(), previous.clone().into_value())); + refusals.push((SUBJECT_MARK, dead_subject())); + } + // The CAS: the row write matches only while the question still sits on + // the subject this handler read. A genuine no-op re-state passes it + // trivially (the row holds exactly what is expected); a stale one — + // whether it moves the link or restates it — matches nothing, aborts + // the whole transaction, and so claims nothing and answers 409. + bindings.push(( + "ref_expected".into(), + question.subject.record().into_value(), + )); + statements.push(format!( + "LET $row = ({write} WHERE subject = $ref_expected RETURN AFTER)" + )); + statements.push(format!( + "IF array::len($row) = 0 {{ \ + LET $live = (UPDATE $id WHERE subject != $ref_expected RETURN VALUE id); \ + IF array::len($live) = 0 {{ THROW '{ROW_MARK}' }} \ + ELSE {{ THROW '{STALE_MARK}' }} }}" + )); + statements.push("RETURN $row".into()); + refusals.push(( + STALE_MARK, + AppError::Conflict( + "the subject this question was read on changed since; re-read and retry", + ), + )); + // The row is gone: the same 404 an empty write answers with, so the + // deleted-row case is unchanged. + refusals.push((ROW_MARK, AppError::NotFound)); + let statements = format!("{};", statements.join("; ")); + // One counter write in flight at a time — only a move writes one. + let _guard = match &retag { + Some(_) => Some(cap::counter_lock().await), + None => None, + }; + let mut result = crate::db::exam_attempt::write_unfrozen_with( + db, + &question.exam, + &statements, + bindings, + refusals, + ) + .await?; + // Read off the trailing `RETURN` rather than a fixed slot: a re-tag + // arms three more statements than a plain PATCH does (and an `IF` + // block is one slot whether or not it is taken). + let slot = result.num_statements().saturating_sub(2); + result + .take::>(slot)? + .into_iter() + .next() + .ok_or(AppError::NotFound) +} + +/// Point the question's `banked_as` at the bank template it was just saved +/// into (`POST …/questions/{qid}/to-bank`). The mirror direction of the +/// `from_bank` [`create_from_bank`] writes, and deliberately a +/// *different* column: a question inserted from the bank has not been saved +/// to it, and one field for both would make the client claim it was. +/// Overwrites any earlier link: repeat saves mint a new template and the +/// newest one wins. +/// +/// Field-scoped write, unlike [`update`]: the caller awaits a bank +/// insert plus the whole blob-copy loop between reading this row and +/// linking it, so the row it holds is long stale by now — a whole-row save +/// would silently revert whatever landed in that window. (The caller takes +/// `EXAM_LOCK.read()` around this call, which is what keeps +/// [`update`]'s whole-row save from clobbering the link in the other +/// direction; the lease guards the ordering, not the staleness.) +pub async fn link_banked_as( + db: &Database, + question: ExamQuestion, + template: BankQuestionId, +) -> Result { + let mut result = db + .query("UPDATE $id SET banked_as = $bank RETURN AFTER") + .bind(("id", question.id.record())) + .bind(("bank", template.record())) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::NotFound) +} + +/// Delete the question and cascade-remove its answers and image rows, so +/// neither can point at a missing question. The image *blobs* are the web +/// layer's to remove — it collects their names before calling this. +/// Refused once the exam has an attempt, in the same transaction as the +/// delete — and the cascade now shares that transaction too, so a failure +/// mid-way can no longer strand answers whose question survived. +pub async fn delete(db: &Database, question: ExamQuestion) -> Result { + let mut result = crate::db::exam_attempt::write_unfrozen( + db, + &question.exam, + &format!( + "DELETE exam_answer WHERE question = $q; + DELETE question_image WHERE question = $q; + LET $gone = (DELETE $q RETURN BEFORE); + FOR $sub IN ($gone.subject ?? []) {{ + UPDATE $sub SET {SUBJECT_QUESTION_COUNT_FIELD} = + math::max([({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) - 1, 0]) + }}; + RETURN $gone;" + ), + vec![("q".into(), question.id.record().into_value())], + ) + .await?; + // The subject's reference is given back inside this same transaction, + // driven off what the delete actually removed — a question that wasn't + // there decrements nothing. Read through the trailing `RETURN` rather + // than a hand-counted slot, so inserting a cascade statement above can + // never turn a delete into a 404 (see [`crate::domain::exam::Exam`]). + let slot = result.num_statements().saturating_sub(2); + result + .take::>(slot)? + .into_iter() + .next() + .ok_or(AppError::NotFound) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::exam_question::QuestionKind; + + fn kind(value: &str) -> QuestionKind { + QuestionKind::try_new(value).unwrap() + } + + /// The subject reference counter, which is what the subject's delete guard + /// reads: every one of these asserts *stored* state, because a claim that + /// outlives the row it accounts for makes its subject undeletable forever. + mod counters { + use super::*; + use crate::database::init_mem; + use crate::domain::exam::{ + Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, + }; + use crate::domain::settings::Settings; + use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; + use crate::domain::user::UserId; + + async fn an_exam(db: &Database) -> Exam { + let kinds = Settings::defaults().get_exam_kinds().to_vec(); + Exam::create( + &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), + &crate::db::course::a_test_course(db).await, + ExamTitle::try_new("practice").unwrap(), + ExamDescription::try_new("").unwrap(), + ExamKind::try_new("quiz", &kinds).unwrap(), + ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None) + .unwrap(), + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + false, + db, + ) + .await + .unwrap() + } + + async fn a_subject(db: &Database) -> Subject { + Subject::create( + &crate::db::course::a_test_course(db).await, + SubjectName::try_new("topic").unwrap(), + SubjectDescription::try_new("").unwrap(), + db, + ) + .await + .unwrap() + } + + /// The editable payload, fresh per call (each one is consumed). + fn body() -> (QuestionText, QuestionPoints, QuestionSpec) { + ( + QuestionText::try_new("3 + 3?").unwrap(), + QuestionPoints::try_new(5).unwrap(), + QuestionSpec::try_new(kind("text"), None, None, &[]).unwrap(), + ) + } + + async fn a_question(exam: &Exam, on: &SubjectId, db: &Database) -> ExamQuestion { + let (text, points, spec) = body(); + create(db, exam.get_id(), on.clone(), text, points, spec) + .await + .unwrap() + } + + async fn moved( + question: ExamQuestion, + to: &SubjectId, + db: &Database, + ) -> Result { + let (text, points, spec) = body(); + update(db, question, to.clone(), text, points, spec).await + } + + /// The stored `exam_question_count` on one subject, absent = zero. + async fn count_on(subject: &SubjectId, db: &Database) -> i64 { + let mut result = db + .query(format!( + "SELECT VALUE ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) FROM $sub" + )) + .bind(("sub", subject.record())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .first() + .copied() + .unwrap_or(0) + } + + async fn rows(sql: &str, db: &Database) -> usize { + let mut result = db.query(sql).await.unwrap().check().unwrap(); + result.take::>(0).unwrap().len() + } + + /// The freeze outranks the counter move, on both paths — and because + /// the claim now rides the refused transaction, "outranks" has to mean + /// the counters read as if nothing ran. + #[tokio::test] + async fn a_frozen_exam_leaves_the_subject_counters_untouched() { + let db = init_mem().await.unwrap(); + let exam = an_exam(&db).await; + let (from, to) = (a_subject(&db).await, a_subject(&db).await); + let (from, to) = (from.get_id().clone(), to.get_id().clone()); + let question = a_question(&exam, &from, &db).await; + assert_eq!(count_on(&from, &db).await, 1); + + // A real user row: starting a sitting moves that student's badge + // counter in the same transaction, and an `UPDATE` has nothing to + // write to without one. + let hash = crate::domain::user::Password::try_new("secret1") + .unwrap() + .hash_async() + .await + .unwrap(); + let student = crate::domain::user::User::create( + crate::domain::user::Username::try_new("ogrenci").unwrap(), + hash, + &db, + ) + .await + .unwrap(); + crate::service::exam_attempt::start(&db, &exam, student.get_id()) + .await + .unwrap(); + + let (text, points, spec) = body(); + let error = create(&db, exam.get_id(), to.clone(), text, points, spec) + .await + .expect_err("a started exam takes no new questions"); + assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); + assert_eq!(count_on(&to, &db).await, 0, "the refused claim rolled back"); + + let error = moved(question, &to, &db) + .await + .expect_err("a started exam takes no re-tag either"); + assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); + assert_eq!(count_on(&from, &db).await, 1, "the release rolled back too"); + assert_eq!(count_on(&to, &db).await, 0); + } + + /// The create-path invariant: a refused create writes neither the row + /// nor a count — least of all on a subject it would have to invent. + #[tokio::test] + async fn a_create_on_a_dead_subject_writes_neither_row_nor_count() { + let db = init_mem().await.unwrap(); + let exam = an_exam(&db).await; + let subject = a_subject(&db).await; + let id = subject.get_id().clone(); + subject.delete(&db).await.unwrap(); + + let (text, points, spec) = body(); + let error = create(&db, exam.get_id(), id, text, points, spec) + .await + .expect_err("a subject that is gone must not be taggable"); + assert!(error.to_string().contains("subject does not exist")); + assert_eq!( + rows("SELECT VALUE id FROM exam_question", &db).await, + 0, + "a refused create may write no row" + ); + assert_eq!( + rows("SELECT VALUE id FROM subject", &db).await, + 0, + "…and least of all a count on a subject it just brought back" + ); + } + + #[tokio::test] + async fn a_subject_move_moves_the_count() { + let db = init_mem().await.unwrap(); + let exam = an_exam(&db).await; + let (from, to) = (a_subject(&db).await, a_subject(&db).await); + let (from, to) = (from.get_id().clone(), to.get_id().clone()); + let question = a_question(&exam, &from, &db).await; + + let after = moved(question, &to, &db).await.unwrap(); + assert_eq!(after.get_subject(), &to); + assert_eq!(count_on(&from, &db).await, 0, "the old subject is free"); + assert_eq!(count_on(&to, &db).await, 1, "the new one is not"); + } + + #[tokio::test] + async fn a_move_to_a_dead_subject_leaves_everything_untouched() { + let db = init_mem().await.unwrap(); + let exam = an_exam(&db).await; + let from = a_subject(&db).await.get_id().clone(); + let dead = a_subject(&db).await; + let gone = dead.get_id().clone(); + dead.delete(&db).await.unwrap(); + let question = a_question(&exam, &from, &db).await; + + let error = moved(question.clone(), &gone, &db) + .await + .expect_err("a subject that is gone must not be taggable"); + assert!(error.to_string().contains("subject does not exist")); + let stored = read(&db, question.get_id()).await.unwrap().unwrap(); + assert_eq!(stored.get_subject(), &from, "the link never moved"); + assert_eq!( + count_on(&from, &db).await, + 1, + "the release rolled back with the claim" + ); + assert_eq!(rows("SELECT VALUE id FROM subject", &db).await, 1); + } + + /// The double-claim guard. Both movers compute their claim and release + /// from the row as *they* read it, so two PATCHes re-tagging the same + /// question both release the old subject and both claim their own + /// target — two counts for one link, and the loser's target is + /// undeletable forever. The second call here runs on the struct read + /// before the first one landed: it must be refused outright, and the + /// counts must read as if it never ran. + /// + /// Drop `AND subject = $ref_expected` from the row write in + /// [`update`] and this goes red on the very first + /// assertion — the stale mover is happily applied. + #[tokio::test] + async fn a_stale_mover_is_refused_and_claims_nothing() { + let db = init_mem().await.unwrap(); + let exam = an_exam(&db).await; + let from = a_subject(&db).await.get_id().clone(); + let to = a_subject(&db).await.get_id().clone(); + let other = a_subject(&db).await.get_id().clone(); + let question = a_question(&exam, &from, &db).await; + let stale = question.clone(); + + moved(question, &to, &db).await.unwrap(); + let error = moved(stale.clone(), &other, &db) + .await + .expect_err("a mover that read a subject it no longer holds must be refused"); + assert!( + matches!(error, AppError::Conflict(_)), + "a lost CAS is a conflict, not a 404 or a 500: {error:?}" + ); + + let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); + assert_eq!(stored.get_subject(), &to, "the winner's link"); + assert_eq!(count_on(&from, &db).await, 0, "released once, not twice"); + assert_eq!(count_on(&to, &db).await, 1, "claimed once"); + assert_eq!(count_on(&other, &db).await, 0, "never claimed"); + } + + /// The other half of the same race, and the one arming on "the subject + /// changed" lets through: this PATCH carries the subject its snapshot + /// already held, so it moves no counter — but a rival's move landed + /// first, and writing that stale subject back would revert the winner + /// while both counters still describe the move. The handler fills an + /// omitted `subject_id` from the row it read, so this is also every + /// text-only PATCH sent from a stale snapshot. + /// + /// Arm the CAS on the re-tag instead of on the write and this goes red + /// on the first assertion — the re-state lands 200. + #[tokio::test] + async fn a_stale_re_stater_is_refused_and_reverts_nothing() { + let db = init_mem().await.unwrap(); + let exam = an_exam(&db).await; + let from = a_subject(&db).await.get_id().clone(); + let to = a_subject(&db).await.get_id().clone(); + let question = a_question(&exam, &from, &db).await; + let stale = question.clone(); + + moved(question, &to, &db).await.unwrap(); + let error = moved(stale.clone(), &from, &db) + .await + .expect_err("re-stating a subject a rival moved off must be refused"); + assert!( + matches!(error, AppError::Conflict(_)), + "a lost CAS is a conflict, not a silent revert: {error:?}" + ); + + let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); + assert_eq!(stored.get_subject(), &to, "the winner's link stands"); + assert_eq!( + count_on(&from, &db).await, + 0, + "released once, and stayed so" + ); + assert_eq!(count_on(&to, &db).await, 1, "claimed once, and stayed so"); + } + + /// …and the price of arming the CAS on every write is nothing: a PATCH + /// re-stating the subject the row really holds passes it trivially. + #[tokio::test] + async fn a_no_op_re_state_still_lands() { + let db = init_mem().await.unwrap(); + let exam = an_exam(&db).await; + let on = a_subject(&db).await.get_id().clone(); + let question = a_question(&exam, &on, &db).await; + + let (_, points, spec) = body(); + let after = update( + &db, + question, + on.clone(), + QuestionText::try_new("4 + 4?").unwrap(), + points, + spec, + ) + .await + .expect("re-stating the subject the row holds is not a conflict"); + assert_eq!(after.get_text().as_str(), "4 + 4?"); + assert_eq!(after.get_subject(), &on); + assert_eq!(count_on(&on, &db).await, 1, "no counter moved"); + } + + /// A re-tag of a question whose row is gone is still the 404 it was, + /// not the stale-mover 409 — the two empty-`$row` cases stay apart. + #[tokio::test] + async fn a_move_of_a_deleted_question_is_still_a_404() { + let db = init_mem().await.unwrap(); + let exam = an_exam(&db).await; + let from = a_subject(&db).await.get_id().clone(); + let to = a_subject(&db).await.get_id().clone(); + let question = a_question(&exam, &from, &db).await; + delete(&db, question.clone()).await.unwrap(); + + let error = moved(question, &to, &db) + .await + .expect_err("a deleted question cannot be re-tagged"); + assert!(matches!(error, AppError::NotFound), "{error:?}"); + assert_eq!(count_on(&to, &db).await, 0, "and nothing was claimed"); + } + } +} diff --git a/src/db/mod.rs b/src/db/mod.rs index 1ad9342..cb1f7e5 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -4,6 +4,7 @@ pub mod appointment; pub mod cap; pub mod course; pub mod exam_attempt; +pub mod exam_question; pub mod field_update; pub mod note; pub mod page; diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs index e9e567c..4c28e84 100644 --- a/src/domain/bank_question.rs +++ b/src/domain/bank_question.rs @@ -807,8 +807,6 @@ mod tests { /// "0"), and questions authored by hand never counted. #[tokio::test] async fn usage_counts_tallies_a_page_in_one_statement() { - use crate::domain::exam_question::ExamQuestion; - // One statement, so a page costs one round trip — a `;` here would mean // the per-row N+1 crept back in. assert!( @@ -859,14 +857,14 @@ mod tests { source: &BankQuestion, db: &Database, ) { - ExamQuestion::create_from_bank( + crate::db::exam_question::create_from_bank( + db, exam, subject.clone(), source.get_text().clone(), source.get_points(), source.spec(), source.get_id().clone(), - db, ) .await .unwrap(); @@ -876,13 +874,13 @@ mod tests { instantiate(&other_exam, subject.get_id(), &used_twice, &db).await; instantiate(&exam, subject.get_id(), &used_once, &db).await; // A hand-authored question has no `from_bank` and must not be tallied. - ExamQuestion::create( + crate::db::exam_question::create( + &db, &exam, subject.get_id().clone(), QuestionText::try_new("mine").unwrap(), QuestionPoints::try_new(1).unwrap(), spec(), - &db, ) .await .unwrap(); diff --git a/src/domain/exam.rs b/src/domain/exam.rs index b7bca75..4f28f88 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -751,9 +751,11 @@ mod tests { .map(|_| ()) }) } - crate::db::course::assert_no_child_outlives_a_course_delete("exam_orphan_race", - EXAM_TABLE, - make,) + crate::db::course::assert_no_child_outlives_a_course_delete( + "exam_orphan_race", + EXAM_TABLE, + make, + ) .await; } @@ -1103,7 +1105,7 @@ mod tests { /// 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, + ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, }; let spec = QuestionSpec::try_new( QuestionKind::try_new("choice").unwrap(), @@ -1129,13 +1131,13 @@ mod tests { ) .await .unwrap(); - ExamQuestion::create( + crate::db::exam_question::create( + db, exam.get_id(), subject.get_id().clone(), QuestionText::try_new("3 + 3?").unwrap(), QuestionPoints::try_new(5).unwrap(), spec, - db, ) .await .unwrap() @@ -1248,7 +1250,7 @@ mod tests { #[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, + ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, }; use crate::domain::subject::Subject; let (db, _serialized) = crate::database::init_test_server("exam_question_race").await; @@ -1298,13 +1300,13 @@ mod tests { &[], ) .unwrap(); - ExamQuestion::create( + crate::db::exam_question::create( + &db, &exam_id, on, QuestionText::try_new("3 + 3?").unwrap(), QuestionPoints::try_new(5).unwrap(), spec, - &db, ) .await }) @@ -1317,7 +1319,7 @@ mod tests { if Exam::read(&id, &db).await.unwrap().is_none() { swept += 1; - questions += ExamQuestion::list_for_exam(&id, None, 0, &db) + questions += crate::db::exam_question::list_for_exam(&db, &id, None, 0) .await .unwrap() .0 diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index cadf182..0e1fc75 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -1,45 +1,24 @@ -use std::collections::HashSet; - use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; use crate::constant::{ EXAM_QUESTION_TABLE, MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, - MIN_QUESTION_CHOICES, SUBJECT_QUESTION_COUNT_FIELD, + MIN_QUESTION_CHOICES, }; -use crate::database::Database; -use crate::db::cap; -use crate::db::page::PagedList; use crate::domain::bank_question::BankQuestionId; use crate::domain::exam::ExamId; use crate::domain::monotonic_id::next_ulid; use crate::domain::subject::SubjectId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::{validate_question_kind, validate_question_points, validate_required}; -/// The `THROW` markers the folded counter moves abort with: the subject the -/// reference was to be claimed on is gone, the question being patched is gone, -/// and the subject this move started from is no longer the one the handler -/// read. File-local like every other marker set (`cap`'s, `subject`'s). -const SUBJECT_MARK: &str = "question_subject_gone"; -const ROW_MARK: &str = "question_row_gone"; -const STALE_MARK: &str = "question_stale_move"; - -/// The one answer for a subject that isn't there — a claim missing it and the -/// web layer's pre-flight lookup missing it are the same 400. -fn dead_subject() -> AppError { - AppError::Validation(ValidationError::Invalid { - field: "subject_id", - reason: "subject does not exist", - }) -} - #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ExamQuestionId(RecordId); impl ExamQuestionId { /// Minted from the process-wide monotonic generator, not `Ulid::new()`: the - /// id *is* the question's presentation order ([`ExamQuestion::list_for_exam`] + /// id *is* the question's presentation order + /// ([`crate::db::exam_question::list_for_exam`] /// sorts `id ASC`), and a random low half scrambles a burst of saves that /// lands inside one millisecond. pub fn generate() -> Self { @@ -181,9 +160,9 @@ pub struct ChoiceInput { /// - `choice` → 2–10 `choices` plus a `correct` naming one of them. #[derive(Debug, Clone)] pub struct QuestionSpec { - kind: QuestionKind, - choices: Option>, - correct: Option, + pub(crate) kind: QuestionKind, + pub(crate) choices: Option>, + pub(crate) correct: Option, } impl QuestionSpec { @@ -305,25 +284,26 @@ impl QuestionSpec { /// subject's course matches before any write. #[derive(Debug, Clone, SurrealValue)] pub struct ExamQuestion { - id: ExamQuestionId, - exam: ExamId, - subject: SubjectId, - text: QuestionText, - kind: QuestionKind, - points: QuestionPoints, - choices: Option>, - correct: Option, + pub(crate) id: ExamQuestionId, + pub(crate) exam: ExamId, + pub(crate) subject: SubjectId, + pub(crate) text: QuestionText, + pub(crate) kind: QuestionKind, + pub(crate) points: QuestionPoints, + pub(crate) choices: Option>, + pub(crate) correct: Option, /// The bank template this question was created *from*, if it was inserted /// out of the bank. Written once, at insert. #[surreal(default)] - from_bank: Option, + pub(crate) from_bank: Option, /// The bank template most recently created *by saving this question* into - /// the bank, if any. Written by [`Self::link_banked_as`], repointed by every + /// the bank, if any. Written by + /// [`crate::db::exam_question::link_banked_as`], repointed by every /// repeat save. Never set by an insert-from-bank: the two directions are /// separate columns precisely so "came from the bank" can't be misread as /// "already saved to the bank". #[surreal(default)] - banked_as: Option, + pub(crate) banked_as: Option, } impl ExamQuestion { @@ -377,356 +357,6 @@ impl ExamQuestion { ) } - pub async fn create( - exam: &ExamId, - subject: SubjectId, - text: QuestionText, - points: QuestionPoints, - spec: QuestionSpec, - db: &Database, - ) -> Result { - Self::insert(exam, subject, text, points, spec, None, db).await - } - - /// Like [`Self::create`], but records the bank template this question was - /// instantiated from (`POST …/questions/from-bank/{bid}`). - pub async fn create_from_bank( - exam: &ExamId, - subject: SubjectId, - text: QuestionText, - points: QuestionPoints, - spec: QuestionSpec, - source: BankQuestionId, - db: &Database, - ) -> Result { - Self::insert(exam, subject, text, points, spec, Some(source), db).await - } - - #[allow(clippy::too_many_arguments)] - async fn insert( - exam: &ExamId, - subject: SubjectId, - text: QuestionText, - points: QuestionPoints, - spec: QuestionSpec, - from_bank: Option, - db: &Database, - ) -> Result { - let counted = subject.record(); - let question = ExamQuestion { - id: ExamQuestionId::generate(), - exam: exam.clone(), - subject, - text, - points, - kind: spec.kind, - choices: spec.choices, - correct: spec.correct, - from_bank, - // An insert never banks anything: only a to-bank save writes this. - banked_as: None, - }; - // The freeze gate and the subject's reference ride in the same - // transaction as the insert: a question cannot appear under an exam - // somebody has already started, and the claim that accounts for it - // cannot outlive a row that never landed. Claiming in its own query - // (with a release on failure, as this did) leaves a window where a - // crash strands the count — and the subject delete is conditioned on - // that count reading zero, so a stranded one makes the subject - // undeletable forever. A missed claim means the subject is already gone - // — the same 400 the web layer's pre-flight check answers with. - // - // Re-sendable despite the `CREATE`: a lost round aborts having written - // nothing and `$id` is a ULID minted once per call, so the re-send - // cannot answer "already exists" (there is no UNIQUE index on - // `exam_question`) — the one thing the retry cannot survive. - let id = question.id.record(); - // One counter write in flight at a time, like every other counter write. - let _guard = cap::counter_lock().await; - let mut result = crate::db::exam_attempt::write_unfrozen_with( - db, - exam, - &format!( - "LET $seat = (UPDATE $subject SET {SUBJECT_QUESTION_COUNT_FIELD} = \ - ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); - IF array::len($seat) = 0 {{ THROW '{SUBJECT_MARK}' }}; - CREATE $id CONTENT $question;" - ), - vec![ - ("subject".into(), counted.into_value()), - ("id".into(), id.into_value()), - ("question".into(), question.into_value()), - ], - vec![(SUBJECT_MARK, dead_subject())], - ) - .await?; - // Counted off the statements that actually ran rather than a fixed - // slot, so folding another gate in above can never mis-read the row. - let slot = result.num_statements().saturating_sub(2); - result - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to create exam question".into())) - } - - pub async fn read( - id: &ExamQuestionId, - db: &Database, - ) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// The exam's questions in presentation order (ULID ids sort by creation). - pub async fn list_for_exam( - exam: &ExamId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new("exam_question WHERE exam = $ex", "ORDER BY id ASC") - .bind("ex", exam.record()) - .run(limit, offset, db) - .await - } - - /// The ids of `exam`'s questions that share a bank template with a question - /// under one of `live` — the questions two exams hold identical `correct` - /// for, because the bank copies the key into every instantiation. Keyed on - /// the template, never on the exam, so only the overlapping questions are - /// named. Empty when `live` is empty. - /// - /// A question links to a template through *either* column and both must be - /// read, on both sides of the join: `from_bank` is the template it was - /// instantiated from, `banked_as` the template minted by saving it into the - /// bank ([`Self::link_banked_as`]). A question authored by hand in exam A - /// and then saved to the bank holds only `banked_as`, while its copy in - /// exam B holds only `from_bank` — matching `from_bank` to `from_bank` saw - /// neither and leaked A's key while B was live. A single coalesced key per - /// row is not enough either: a question instantiated from one template and - /// re-saved as another carries *both*, and only the second one may be the - /// shared link. - /// - /// So: collect every template id reachable from a live exam by either - /// column, then name any of `exam`'s questions pointing at one by either - /// column. `$shared` is built from `!= NONE` filters, so it never holds a - /// `NONE` for an unlinked question's absent column to match against. - pub async fn list_shared_with( - exam: &ExamId, - live: &[ExamId], - db: &Database, - ) -> Result, AppError> { - if live.is_empty() { - return Ok(HashSet::new()); - } - let mut result = db - .query( - "LET $shared = array::union( - (SELECT VALUE from_bank FROM exam_question - WHERE exam IN $live AND from_bank != NONE), - (SELECT VALUE banked_as FROM exam_question - WHERE exam IN $live AND banked_as != NONE)); - SELECT VALUE id FROM exam_question - WHERE exam = $ex AND (from_bank IN $shared OR banked_as IN $shared)", - ) - .bind(("ex", exam.record())) - .bind(( - "live", - live.iter().map(ExamId::record).collect::>(), - )) - .await? - .check()?; - Ok(result - .take::>(1)? - .iter() - .map(|id| id.key().to_string()) - .collect()) - } - - /// Write the editable fields, refused outright once the exam has an - /// attempt — the freeze gate is part of this transaction, not a check the - /// caller made a moment earlier under a lock. - /// - /// Field-scoped, no longer a whole-row save. The row also carries - /// `from_bank`/`banked_as`, which [`Self::link_banked_as`] writes from a - /// *different* request: re-stating this snapshot's copy of them would - /// revert a to-bank save that landed in between. That is exactly what the - /// caller's `EXAM_LOCK.write()` used to order (inside one process), and - /// naming the columns removes the need for any ordering at all. - pub async fn update( - self, - subject: SubjectId, - text: QuestionText, - points: QuestionPoints, - spec: QuestionSpec, - db: &Database, - ) -> Result { - // A re-tag moves a reference, and the move rides the very transaction - // that moves the link: the old subject's release, the new one's claim - // and the row write commit together or not at all, so no crash can - // strand a count on a subject nothing points at (which would make it - // undeletable forever). - // - // The two are armed on *different* conditions, which is the whole of - // the rule ([`crate::db::field_update::FieldUpdate::refcount`] states - // it the same way): the counter statements only when the link actually - // changes, but the CAS whenever this write *carries* the link — and it - // always does, because the handler fills an omitted `subject_id` from - // the row it read (`web::exams::questions`), so `subject` is in the - // `SET` of every one of these updates. Arming the CAS on "changed" - // instead would leave the re-stater through: a PATCH carrying the - // subject its own stale snapshot held, sent while a rival's move - // already landed, writes that stale subject straight back over the - // winner — a revert with the counters left pointing at the move. - let retag = (subject != self.subject).then(|| (subject.record(), self.subject.record())); - let write = "UPDATE $id SET subject = $subject, text = $text, points = $points, - kind = $kind, choices = $choices, correct = $correct"; - let mut bindings = vec![ - ("id".into(), self.id.record().into_value()), - ("subject".into(), subject.record().into_value()), - ("text".into(), text.into_value()), - ("points".into(), points.into_value()), - ("kind".into(), spec.kind.into_value()), - ("choices".into(), spec.choices.into_value()), - ("correct".into(), spec.correct.into_value()), - ]; - let mut statements: Vec = Vec::new(); - let mut refusals: Vec<(&str, AppError)> = Vec::new(); - if let Some((next, previous)) = &retag { - statements.push(format!( - "UPDATE $ref_release SET {SUBJECT_QUESTION_COUNT_FIELD} = \ - math::max([({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) - 1, 0])" - )); - statements.push(format!( - "LET $seat = (UPDATE $ref_claim SET {SUBJECT_QUESTION_COUNT_FIELD} = \ - ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id)" - )); - statements.push(format!( - "IF array::len($seat) = 0 {{ THROW '{SUBJECT_MARK}' }}" - )); - bindings.push(("ref_claim".into(), next.clone().into_value())); - bindings.push(("ref_release".into(), previous.clone().into_value())); - refusals.push((SUBJECT_MARK, dead_subject())); - } - // The CAS: the row write matches only while the question still sits on - // the subject this handler read. A genuine no-op re-state passes it - // trivially (the row holds exactly what is expected); a stale one — - // whether it moves the link or restates it — matches nothing, aborts - // the whole transaction, and so claims nothing and answers 409. - bindings.push(("ref_expected".into(), self.subject.record().into_value())); - statements.push(format!( - "LET $row = ({write} WHERE subject = $ref_expected RETURN AFTER)" - )); - statements.push(format!( - "IF array::len($row) = 0 {{ \ - LET $live = (UPDATE $id WHERE subject != $ref_expected RETURN VALUE id); \ - IF array::len($live) = 0 {{ THROW '{ROW_MARK}' }} \ - ELSE {{ THROW '{STALE_MARK}' }} }}" - )); - statements.push("RETURN $row".into()); - refusals.push(( - STALE_MARK, - AppError::Conflict( - "the subject this question was read on changed since; re-read and retry", - ), - )); - // The row is gone: the same 404 an empty write answers with, so the - // deleted-row case is unchanged. - refusals.push((ROW_MARK, AppError::NotFound)); - let statements = format!("{};", statements.join("; ")); - // One counter write in flight at a time — only a move writes one. - let _guard = match &retag { - Some(_) => Some(cap::counter_lock().await), - None => None, - }; - let mut result = crate::db::exam_attempt::write_unfrozen_with( - db, - &self.exam, - &statements, - bindings, - refusals, - ) - .await?; - // Read off the trailing `RETURN` rather than a fixed slot: a re-tag - // arms three more statements than a plain PATCH does (and an `IF` - // block is one slot whether or not it is taken). - let slot = result.num_statements().saturating_sub(2); - result - .take::>(slot)? - .into_iter() - .next() - .ok_or(AppError::NotFound) - } - - /// Point the question's `banked_as` at the bank template it was just saved - /// into (`POST …/questions/{qid}/to-bank`). The mirror direction of the - /// `from_bank` [`Self::create_from_bank`] writes, and deliberately a - /// *different* column: a question inserted from the bank has not been saved - /// to it, and one field for both would make the client claim it was. - /// Overwrites any earlier link: repeat saves mint a new template and the - /// newest one wins. - /// - /// Field-scoped write, unlike [`Self::update`]: the caller awaits a bank - /// insert plus the whole blob-copy loop between reading this row and - /// linking it, so the row it holds is long stale by now — a whole-row save - /// would silently revert whatever landed in that window. (The caller takes - /// `EXAM_LOCK.read()` around this call, which is what keeps - /// [`Self::update`]'s whole-row save from clobbering the link in the other - /// direction; the lease guards the ordering, not the staleness.) - pub async fn link_banked_as( - self, - template: BankQuestionId, - db: &Database, - ) -> Result { - let mut result = db - .query("UPDATE $id SET banked_as = $bank RETURN AFTER") - .bind(("id", self.id.record())) - .bind(("bank", template.record())) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) - } - - /// Delete the question and cascade-remove its answers and image rows, so - /// neither can point at a missing question. The image *blobs* are the web - /// layer's to remove — it collects their names before calling this. - /// Refused once the exam has an attempt, in the same transaction as the - /// delete — and the cascade now shares that transaction too, so a failure - /// mid-way can no longer strand answers whose question survived. - pub async fn delete(self, db: &Database) -> Result { - let mut result = crate::db::exam_attempt::write_unfrozen( - db, - &self.exam, - &format!( - "DELETE exam_answer WHERE question = $q; - DELETE question_image WHERE question = $q; - LET $gone = (DELETE $q RETURN BEFORE); - FOR $sub IN ($gone.subject ?? []) {{ - UPDATE $sub SET {SUBJECT_QUESTION_COUNT_FIELD} = - math::max([({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) - 1, 0]) - }}; - RETURN $gone;" - ), - vec![("q".into(), self.id.record().into_value())], - ) - .await?; - // The subject's reference is given back inside this same transaction, - // driven off what the delete actually removed — a question that wasn't - // there decrements nothing. Read through the trailing `RETURN` rather - // than a hand-counted slot, so inserting a cascade statement above can - // never turn a delete into a 404 (see [`crate::domain::exam::Exam`]). - let slot = result.num_statements().saturating_sub(2); - result - .take::>(slot)? - .into_iter() - .next() - .ok_or(AppError::NotFound) - } - /// A question constructed without a database, for pure-function tests. #[cfg(test)] pub fn test_new(exam: &ExamId, text: &str, points: i64, spec: QuestionSpec) -> ExamQuestion { @@ -1081,338 +711,6 @@ mod tests { } } - /// The subject reference counter, which is what the subject's delete guard - /// reads: every one of these asserts *stored* state, because a claim that - /// outlives the row it accounts for makes its subject undeletable forever. - mod counters { - use super::*; - use crate::database::init_mem; - use crate::domain::exam::{ - Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, - }; - use crate::domain::settings::Settings; - use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; - use crate::domain::user::UserId; - - async fn an_exam(db: &Database) -> Exam { - let kinds = Settings::defaults().get_exam_kinds().to_vec(); - Exam::create( - &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), - &crate::db::course::a_test_course(db).await, - ExamTitle::try_new("practice").unwrap(), - ExamDescription::try_new("").unwrap(), - ExamKind::try_new("quiz", &kinds).unwrap(), - ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None) - .unwrap(), - ExamAttemptLimit::try_new(1).unwrap(), - true, - false, - false, - db, - ) - .await - .unwrap() - } - - async fn a_subject(db: &Database) -> Subject { - Subject::create( - &crate::db::course::a_test_course(db).await, - SubjectName::try_new("topic").unwrap(), - SubjectDescription::try_new("").unwrap(), - db, - ) - .await - .unwrap() - } - - /// The editable payload, fresh per call (each one is consumed). - fn body() -> (QuestionText, QuestionPoints, QuestionSpec) { - ( - QuestionText::try_new("3 + 3?").unwrap(), - QuestionPoints::try_new(5).unwrap(), - QuestionSpec::try_new(kind("text"), None, None, &[]).unwrap(), - ) - } - - async fn a_question(exam: &Exam, on: &SubjectId, db: &Database) -> ExamQuestion { - let (text, points, spec) = body(); - ExamQuestion::create(exam.get_id(), on.clone(), text, points, spec, db) - .await - .unwrap() - } - - async fn moved( - question: ExamQuestion, - to: &SubjectId, - db: &Database, - ) -> Result { - let (text, points, spec) = body(); - question.update(to.clone(), text, points, spec, db).await - } - - /// The stored `exam_question_count` on one subject, absent = zero. - async fn count_on(subject: &SubjectId, db: &Database) -> i64 { - let mut result = db - .query(format!( - "SELECT VALUE ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) FROM $sub" - )) - .bind(("sub", subject.record())) - .await - .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .first() - .copied() - .unwrap_or(0) - } - - async fn rows(sql: &str, db: &Database) -> usize { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result.take::>(0).unwrap().len() - } - - /// The freeze outranks the counter move, on both paths — and because - /// the claim now rides the refused transaction, "outranks" has to mean - /// the counters read as if nothing ran. - #[tokio::test] - async fn a_frozen_exam_leaves_the_subject_counters_untouched() { - let db = init_mem().await.unwrap(); - let exam = an_exam(&db).await; - let (from, to) = (a_subject(&db).await, a_subject(&db).await); - let (from, to) = (from.get_id().clone(), to.get_id().clone()); - let question = a_question(&exam, &from, &db).await; - assert_eq!(count_on(&from, &db).await, 1); - - // A real user row: starting a sitting moves that student's badge - // counter in the same transaction, and an `UPDATE` has nothing to - // write to without one. - let hash = crate::domain::user::Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(); - let student = crate::domain::user::User::create( - crate::domain::user::Username::try_new("ogrenci").unwrap(), - hash, - &db, - ) - .await - .unwrap(); - crate::service::exam_attempt::start(&db, &exam, student.get_id()) - .await - .unwrap(); - - let (text, points, spec) = body(); - let error = ExamQuestion::create(exam.get_id(), to.clone(), text, points, spec, &db) - .await - .expect_err("a started exam takes no new questions"); - assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); - assert_eq!(count_on(&to, &db).await, 0, "the refused claim rolled back"); - - let error = moved(question, &to, &db) - .await - .expect_err("a started exam takes no re-tag either"); - assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); - assert_eq!(count_on(&from, &db).await, 1, "the release rolled back too"); - assert_eq!(count_on(&to, &db).await, 0); - } - - /// The create-path invariant: a refused create writes neither the row - /// nor a count — least of all on a subject it would have to invent. - #[tokio::test] - async fn a_create_on_a_dead_subject_writes_neither_row_nor_count() { - let db = init_mem().await.unwrap(); - let exam = an_exam(&db).await; - let subject = a_subject(&db).await; - let id = subject.get_id().clone(); - subject.delete(&db).await.unwrap(); - - let (text, points, spec) = body(); - let error = ExamQuestion::create(exam.get_id(), id, text, points, spec, &db) - .await - .expect_err("a subject that is gone must not be taggable"); - assert!(error.to_string().contains("subject does not exist")); - assert_eq!( - rows("SELECT VALUE id FROM exam_question", &db).await, - 0, - "a refused create may write no row" - ); - assert_eq!( - rows("SELECT VALUE id FROM subject", &db).await, - 0, - "…and least of all a count on a subject it just brought back" - ); - } - - #[tokio::test] - async fn a_subject_move_moves_the_count() { - let db = init_mem().await.unwrap(); - let exam = an_exam(&db).await; - let (from, to) = (a_subject(&db).await, a_subject(&db).await); - let (from, to) = (from.get_id().clone(), to.get_id().clone()); - let question = a_question(&exam, &from, &db).await; - - let after = moved(question, &to, &db).await.unwrap(); - assert_eq!(after.get_subject(), &to); - assert_eq!(count_on(&from, &db).await, 0, "the old subject is free"); - assert_eq!(count_on(&to, &db).await, 1, "the new one is not"); - } - - #[tokio::test] - async fn a_move_to_a_dead_subject_leaves_everything_untouched() { - let db = init_mem().await.unwrap(); - let exam = an_exam(&db).await; - let from = a_subject(&db).await.get_id().clone(); - let dead = a_subject(&db).await; - let gone = dead.get_id().clone(); - dead.delete(&db).await.unwrap(); - let question = a_question(&exam, &from, &db).await; - - let error = moved(question.clone(), &gone, &db) - .await - .expect_err("a subject that is gone must not be taggable"); - assert!(error.to_string().contains("subject does not exist")); - let stored = ExamQuestion::read(question.get_id(), &db) - .await - .unwrap() - .unwrap(); - assert_eq!(stored.get_subject(), &from, "the link never moved"); - assert_eq!( - count_on(&from, &db).await, - 1, - "the release rolled back with the claim" - ); - assert_eq!(rows("SELECT VALUE id FROM subject", &db).await, 1); - } - - /// The double-claim guard. Both movers compute their claim and release - /// from the row as *they* read it, so two PATCHes re-tagging the same - /// question both release the old subject and both claim their own - /// target — two counts for one link, and the loser's target is - /// undeletable forever. The second call here runs on the struct read - /// before the first one landed: it must be refused outright, and the - /// counts must read as if it never ran. - /// - /// Drop `AND subject = $ref_expected` from the row write in - /// [`ExamQuestion::update`] and this goes red on the very first - /// assertion — the stale mover is happily applied. - #[tokio::test] - async fn a_stale_mover_is_refused_and_claims_nothing() { - let db = init_mem().await.unwrap(); - let exam = an_exam(&db).await; - let from = a_subject(&db).await.get_id().clone(); - let to = a_subject(&db).await.get_id().clone(); - let other = a_subject(&db).await.get_id().clone(); - let question = a_question(&exam, &from, &db).await; - let stale = question.clone(); - - moved(question, &to, &db).await.unwrap(); - let error = moved(stale.clone(), &other, &db) - .await - .expect_err("a mover that read a subject it no longer holds must be refused"); - assert!( - matches!(error, AppError::Conflict(_)), - "a lost CAS is a conflict, not a 404 or a 500: {error:?}" - ); - - let stored = ExamQuestion::read(stale.get_id(), &db) - .await - .unwrap() - .unwrap(); - assert_eq!(stored.get_subject(), &to, "the winner's link"); - assert_eq!(count_on(&from, &db).await, 0, "released once, not twice"); - assert_eq!(count_on(&to, &db).await, 1, "claimed once"); - assert_eq!(count_on(&other, &db).await, 0, "never claimed"); - } - - /// The other half of the same race, and the one arming on "the subject - /// changed" lets through: this PATCH carries the subject its snapshot - /// already held, so it moves no counter — but a rival's move landed - /// first, and writing that stale subject back would revert the winner - /// while both counters still describe the move. The handler fills an - /// omitted `subject_id` from the row it read, so this is also every - /// text-only PATCH sent from a stale snapshot. - /// - /// Arm the CAS on the re-tag instead of on the write and this goes red - /// on the first assertion — the re-state lands 200. - #[tokio::test] - async fn a_stale_re_stater_is_refused_and_reverts_nothing() { - let db = init_mem().await.unwrap(); - let exam = an_exam(&db).await; - let from = a_subject(&db).await.get_id().clone(); - let to = a_subject(&db).await.get_id().clone(); - let question = a_question(&exam, &from, &db).await; - let stale = question.clone(); - - moved(question, &to, &db).await.unwrap(); - let error = moved(stale.clone(), &from, &db) - .await - .expect_err("re-stating a subject a rival moved off must be refused"); - assert!( - matches!(error, AppError::Conflict(_)), - "a lost CAS is a conflict, not a silent revert: {error:?}" - ); - - let stored = ExamQuestion::read(stale.get_id(), &db) - .await - .unwrap() - .unwrap(); - assert_eq!(stored.get_subject(), &to, "the winner's link stands"); - assert_eq!( - count_on(&from, &db).await, - 0, - "released once, and stayed so" - ); - assert_eq!(count_on(&to, &db).await, 1, "claimed once, and stayed so"); - } - - /// …and the price of arming the CAS on every write is nothing: a PATCH - /// re-stating the subject the row really holds passes it trivially. - #[tokio::test] - async fn a_no_op_re_state_still_lands() { - let db = init_mem().await.unwrap(); - let exam = an_exam(&db).await; - let on = a_subject(&db).await.get_id().clone(); - let question = a_question(&exam, &on, &db).await; - - let (_, points, spec) = body(); - let after = question - .update( - on.clone(), - QuestionText::try_new("4 + 4?").unwrap(), - points, - spec, - &db, - ) - .await - .expect("re-stating the subject the row holds is not a conflict"); - assert_eq!(after.get_text().as_str(), "4 + 4?"); - assert_eq!(after.get_subject(), &on); - assert_eq!(count_on(&on, &db).await, 1, "no counter moved"); - } - - /// A re-tag of a question whose row is gone is still the 404 it was, - /// not the stale-mover 409 — the two empty-`$row` cases stay apart. - #[tokio::test] - async fn a_move_of_a_deleted_question_is_still_a_404() { - let db = init_mem().await.unwrap(); - let exam = an_exam(&db).await; - let from = a_subject(&db).await.get_id().clone(); - let to = a_subject(&db).await.get_id().clone(); - let question = a_question(&exam, &from, &db).await; - question.clone().delete(&db).await.unwrap(); - - let error = moved(question, &to, &db) - .await - .expect_err("a deleted question cannot be re-tagged"); - assert!(matches!(error, AppError::NotFound), "{error:?}"); - assert_eq!(count_on(&to, &db).await, 0, "and nothing was claimed"); - } - } - #[tokio::test] async fn spec_rejects_blank_or_oversized_choices() { let with = |text: String| { diff --git a/src/domain/subject.rs b/src/domain/subject.rs index 16337e6..eb10618 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}; @@ -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; } @@ -322,7 +324,7 @@ mod tests { /// is counted rather than asserted per round, and why this needs the real /// server and a multi-threaded runtime. /// - /// The racer is [`ExamQuestion::create`], which claims the subject's + /// The racer is [`crate::db::exam_question::create`], which claims the subject's /// question reference *before* it writes the row — a conditional write on /// the same record the delete's `WHERE` reads. `Err(Conflict)` (still /// referenced), `Err(NotFound)` and the claim's `Validation` miss are all @@ -345,7 +347,7 @@ mod tests { #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_delete_racing_a_question_never_answers_500() { use crate::domain::exam_question::{ - ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, + QuestionKind, QuestionPoints, QuestionSpec, QuestionText, }; let (db, _serialized) = crate::database::init_test_server("subject_delete_race").await; let (mut delete_500, mut question_500) = (0, 0); @@ -398,7 +400,8 @@ mod tests { }; tokio::spawn(async move { tokio::time::sleep(head_start).await; - ExamQuestion::create( + crate::db::exam_question::create( + &db, &exam, id, QuestionText::try_new("why").unwrap(), @@ -410,7 +413,6 @@ mod tests { &[], ) .unwrap(), - &db, ) .await }) @@ -438,7 +440,7 @@ mod tests { { wiped += 1; } - if !ExamQuestion::list_for_exam(&exam, None, 0, &db) + if !crate::db::exam_question::list_for_exam(&db, &exam, None, 0) .await .unwrap() .0 diff --git a/src/service/exam_attempt.rs b/src/service/exam_attempt.rs index 70c965d..479c31f 100644 --- a/src/service/exam_attempt.rs +++ b/src/service/exam_attempt.rs @@ -12,7 +12,6 @@ use crate::domain::enrollment::Enrollment; use crate::domain::exam::{Exam, ExamId}; use crate::domain::exam_answer::ExamAnswer; use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId}; -use crate::domain::exam_question::{ExamQuestion, ExamQuestionId}; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; @@ -148,22 +147,6 @@ pub async fn course_of(exam: &Exam, db: &Database) -> Result { .ok_or_else(|| AppError::Internal("exam references a missing course".into())) } -/// The question, provided it belongs to `exam` — a qid under someone else's -/// exam is a plain 404, not a leak. -pub async fn question_of_exam( - exam: &ExamId, - qid: &str, - db: &Database, -) -> Result { - let question = ExamQuestion::read(&ExamQuestionId::from_key(qid), db) - .await? - .ok_or(AppError::NotFound)?; - if question.get_exam() != exam { - return Err(AppError::NotFound); - } - Ok(question) -} - /// Start, resume, or retake `user`'s attempt at `exam`. Returns the attempt /// plus whether it was newly created. /// @@ -400,7 +383,8 @@ pub async fn save_answer_in( ensure_enrolled(exam, attempt.get_user(), db).await?; check_rejoin(exam, attempt)?; crate::service::course::require_open(db, &course_of(exam, db).await?).await?; - let question = question_of_exam(exam.get_id(), question_id, db).await?; + let question = + crate::service::exam_question::question_of_exam(exam.get_id(), question_id, db).await?; crate::domain::exam_answer::ExamAnswer::save( &question, attempt.get_user(), @@ -547,13 +531,13 @@ mod tests { ) .await .unwrap(); - let question = ExamQuestion::create( + let question = crate::db::exam_question::create( + db, exam.get_id(), subject.get_id().clone(), crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(), QuestionPoints::try_new(5).unwrap(), spec, - db, ) .await .unwrap(); diff --git a/src/service/exam_question.rs b/src/service/exam_question.rs new file mode 100644 index 0000000..4eba7ff --- /dev/null +++ b/src/service/exam_question.rs @@ -0,0 +1,134 @@ +//! Exam-question authoring rules: the freeze pre-flight every authoring path +//! runs, the question-lookup and option-addressing gates, and the read and +//! write funnels the web layer goes through. The queries and their +//! transactions live in [`crate::db::exam_question`]; the HTTP shaping stays +//! in the web layer. + +use crate::database::Database; +use crate::domain::bank_question::BankQuestionId; +use crate::domain::exam::ExamId; +use crate::domain::exam_question::{ + ChoiceId, ExamQuestion, ExamQuestionId, QuestionPoints, QuestionSpec, QuestionText, +}; +use crate::domain::subject::SubjectId; +use crate::error::{AppError, ValidationError}; + +/// The questions freeze once anyone has started an attempt — editing them +/// under a student mid-exam would fork what "the exam" means. +pub async fn ensure_questions_editable(exam: &ExamId, db: &Database) -> Result<(), AppError> { + if crate::service::exam_attempt::any_for_exam(db, exam).await? { + return Err(AppError::Conflict( + "cannot change questions after attempts have started", + )); + } + Ok(()) +} + +/// The question's option named by `choice_id` — a 400 for a text question or an +/// id the question doesn't have, so an option picture can only ever be +/// addressed through an option that exists. +pub fn choice_slot(question: &ExamQuestion, choice_id: &str) -> Result { + let Some(choices) = question.get_choices() else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "choice_id", + reason: "only choice questions take option pictures", + })); + }; + choices + .iter() + .find(|choice| choice.get_id().as_str() == choice_id) + .map(|choice| choice.get_id().clone()) + .ok_or(AppError::Validation(ValidationError::Invalid { + field: "choice_id", + reason: "must name one of the choices", + })) +} + +/// The question, provided it belongs to `exam` — a qid under someone else's +/// exam is a plain 404, not a leak. +pub async fn question_of_exam( + exam: &ExamId, + qid: &str, + db: &Database, +) -> Result { + let question = crate::db::exam_question::read(db, &ExamQuestionId::from_key(qid)) + .await? + .ok_or(AppError::NotFound)?; + if question.get_exam() != exam { + return Err(AppError::NotFound); + } + Ok(question) +} + +/// Add a question to an exam. The freeze gate and the subject's reference +/// counter ride in the write's own transaction. +pub async fn create( + db: &Database, + exam: &ExamId, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, +) -> Result { + crate::db::exam_question::create(db, exam, subject, text, points, spec).await +} + +/// Like [`create`], but records the bank template the question was +/// instantiated from. +pub async fn create_from_bank( + db: &Database, + exam: &ExamId, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, + source: BankQuestionId, +) -> Result { + crate::db::exam_question::create_from_bank(db, exam, subject, text, points, spec, source).await +} + +/// The exam's questions in presentation order — the web layer's paging read. +pub async fn list_for_exam( + db: &Database, + exam: &ExamId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + crate::db::exam_question::list_for_exam(db, exam, limit, offset).await +} + +/// The question ids of `exam` sharing a bank template with a question under +/// one of `live` — the review hiding key. +pub async fn list_shared_with( + db: &Database, + exam: &ExamId, + live: &[ExamId], +) -> Result, AppError> { + crate::db::exam_question::list_shared_with(db, exam, live).await +} + +/// Write the editable fields; a stale read is a 409, nothing was written. +pub async fn update( + db: &Database, + question: ExamQuestion, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, +) -> Result { + crate::db::exam_question::update(db, question, subject, text, points, spec).await +} + +/// Delete the question and cascade its answers and image rows. +pub async fn delete(db: &Database, question: ExamQuestion) -> Result { + crate::db::exam_question::delete(db, question).await +} + +/// Point the question's `banked_as` at the bank template it was saved into. +pub async fn link_banked_as( + db: &Database, + question: ExamQuestion, + template: BankQuestionId, +) -> Result { + crate::db::exam_question::link_banked_as(db, question, template).await +} diff --git a/src/service/mod.rs b/src/service/mod.rs index 892e3cd..c0fa118 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -4,6 +4,7 @@ pub mod appointment; pub mod course; pub mod exam_attempt; +pub mod exam_question; pub mod note; pub mod payment_ledger; pub mod session; diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 2a0c68e..30579cc 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -68,7 +68,6 @@ use crate::database::Database; use crate::domain::exam::{Exam, ExamId}; use crate::domain::exam_answer::ExamAnswer; use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId}; -use crate::domain::exam_question::ExamQuestion; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -340,7 +339,7 @@ async fn state_frame( ExamAnswer::list_for_exam_user(exam.get_id(), attempt.get_user(), attempt.get_seq(), db) .await? .len(); - let question_count = ExamQuestion::list_for_exam(exam.get_id(), None, 0, db) + let question_count = crate::service::exam_question::list_for_exam(db, exam.get_id(), None, 0) .await? .0 .len(); @@ -461,7 +460,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..4824133 100644 --- a/src/web/exams/attempts.rs +++ b/src/web/exams/attempts.rs @@ -105,7 +105,7 @@ pub(crate) async fn attempt_progress( let answered = ExamAnswer::list_for_exam_user(exam, user, seq, db) .await? .len() as u64; - let question_count = ExamQuestion::list_for_exam(exam, None, 0, db) + let question_count = crate::service::exam_question::list_for_exam(db, exam, None, 0) .await? .0 .len() as u64; @@ -356,7 +356,7 @@ pub(crate) async fn live_snapshot( ) }) .collect(); - let question_count = ExamQuestion::list_for_exam(exam.get_id(), None, 0, db) + let question_count = crate::service::exam_question::list_for_exam(db, exam.get_id(), None, 0) .await? .0 .len() as u64; @@ -583,7 +583,8 @@ pub(crate) async fn attempt_questions( .ok_or(AppError::NotFound)? .get_seq(); - let (questions, _) = ExamQuestion::list_for_exam(exam.get_id(), None, 0, &st.db).await?; + let (questions, _) = + crate::service::exam_question::list_for_exam(&st.db, exam.get_id(), None, 0).await?; let images = images_by_question(exam.get_id(), &st.db).await?; let answers: HashMap = ExamAnswer::list_for_exam_user(exam.get_id(), user.get_id(), seq, &st.db) @@ -743,7 +744,8 @@ pub(crate) async fn answer_sheet( hidden: &HashSet, db: &Database, ) -> Result { - let (mut questions, _) = ExamQuestion::list_for_exam(exam.get_id(), None, 0, db).await?; + let (mut questions, _) = + crate::service::exam_question::list_for_exam(db, exam.get_id(), None, 0).await?; questions.retain(|question| !hidden.contains(question.get_id().key())); let answers = ExamAnswer::list_for_exam_user(exam.get_id(), target, seq, db).await?; let answer_images: HashMap = diff --git a/src/web/exams/images.rs b/src/web/exams/images.rs index 9faf82e..b3efee3 100644 --- a/src/web/exams/images.rs +++ b/src/web/exams/images.rs @@ -2,8 +2,9 @@ use super::*; use crate::service::exam_attempt::{ EXAM_LOCK, check_rejoin, course_of, ensure_enrolled, ensure_student, ensure_student_now, - question_of_exam, read_latest_for_user, writable_attempt, + read_latest_for_user, writable_attempt, }; +use crate::service::exam_question::{choice_slot, ensure_questions_editable, question_of_exam}; /// A stored question image's metadata; the bytes come from the image /// endpoints (`GET .../image`, `GET .../choices/{choice_id}/image`). diff --git a/src/web/exams/questions.rs b/src/web/exams/questions.rs index 0294883..27c0f08 100644 --- a/src/web/exams/questions.rs +++ b/src/web/exams/questions.rs @@ -1,7 +1,6 @@ use super::*; -use crate::service::exam_attempt; -use crate::service::exam_attempt::question_of_exam; +use crate::service::exam_question; // ---- questions -------------------------------------------------------------- // Teachers author the question list before the exam runs; it freezes the @@ -135,40 +134,6 @@ impl QuestionResponse { } } -/// The questions freeze once anyone has started an attempt — editing them -/// under a student mid-exam would fork what "the exam" means. -pub(crate) async fn ensure_questions_editable( - exam: &ExamId, - db: &Database, -) -> Result<(), AppError> { - if exam_attempt::any_for_exam(db, exam).await? { - return Err(AppError::Conflict( - "cannot change questions after attempts have started", - )); - } - Ok(()) -} - -/// The question's option named by `choice_id` — a 400 for a text question or an -/// id the question doesn't have, so an option picture can only ever be -/// addressed through an option that exists. -pub(crate) fn choice_slot(question: &ExamQuestion, choice_id: &str) -> Result { - let Some(choices) = question.get_choices() else { - return Err(AppError::Validation(ValidationError::Invalid { - field: "choice_id", - reason: "only choice questions take option pictures", - })); - }; - choices - .iter() - .find(|choice| choice.get_id().as_str() == choice_id) - .map(|choice| choice.get_id().clone()) - .ok_or(AppError::Validation(ValidationError::Invalid { - field: "choice_id", - reason: "must name one of the choices", - })) -} - /// Add a question to an exam. Requires teacher+ and management rights over the /// exam's course. `subject_id` must name one of the course's subjects /// (`GET /courses/{id}/subjects`) — every question belongs to a subject. @@ -211,7 +176,7 @@ pub(crate) async fn create_question( // and the insert takes the subject's reference counter in the same breath — // a subject delete lands either wholly before it (400) or is refused. The // freeze gate rides inside the insert's own transaction. - ensure_questions_editable(exam.get_id(), &st.db).await?; + exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; let text = QuestionText::try_new(&req.text)?; @@ -224,7 +189,8 @@ pub(crate) async fn create_question( req.correct, &[], )?; - let question = ExamQuestion::create(exam.get_id(), subject, text, points, spec, &st.db).await?; + let question = + exam_question::create(&st.db, exam.get_id(), subject, text, points, spec).await?; // A question is born imageless — uploads come after, against its id. Ok(( StatusCode::CREATED, @@ -283,7 +249,7 @@ pub(crate) async fn question_page( hidden: &HashSet, db: &Database, ) -> Result, AppError> { - let (questions, total) = ExamQuestion::list_for_exam(exam.get_id(), limit, offset, db).await?; + let (questions, total) = exam_question::list_for_exam(db, exam.get_id(), limit, offset).await?; let images = images_by_question(exam.get_id(), db).await?; let items = questions .iter() @@ -348,8 +314,8 @@ pub(crate) async fn update_question( crate::service::course::require_open(&st.db, &course).await?; // No lease — see `create_question`; a re-tag moves the subject's reference // counter, and the freeze gate rides in the update's transaction. - ensure_questions_editable(exam.get_id(), &st.db).await?; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; + let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; let subject = match req.subject_id { Some(ref subject_id) => subject_in_course(subject_id, course.get_id(), &st.db).await?, @@ -382,7 +348,7 @@ pub(crate) async fn update_question( let stored: Vec = question.get_choices().unwrap_or_default().to_vec(); let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?; - let updated = question.update(subject, text, points, spec, &st.db).await?; + let updated = exam_question::update(&st.db, question, subject, text, points, spec).await?; // Only the options that are actually *gone* lose their pictures: keyed by // choice id, an option that survives the edit keeps its image no matter // where it moved in the list. (This used to wipe every option picture @@ -436,12 +402,12 @@ pub(crate) async fn delete_question( crate::service::course::require_open(&st.db, &course).await?; // No lock: the freeze gate is part of the delete's own transaction, and // this path checks no subject. The pre-flight below is the fast 409. - ensure_questions_editable(exam.get_id(), &st.db).await?; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; + let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).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_question(question.get_id(), &st.db).await?; - question.delete(&st.db).await?; + exam_question::delete(&st.db, question).await?; for image in &images { remove_blob(&st.files_path, image.get_file()).await; } @@ -508,7 +474,7 @@ pub(crate) async fn question_from_bank( crate::service::course::require_open(&st.db, &course).await?; // No lease — same reasoning as `create_question`. The freeze gate rides in // the insert's transaction. - ensure_questions_editable(exam.get_id(), &st.db).await?; + exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; let template = BankQuestion::read(&BankQuestionId::from_key(&bid), &st.db) @@ -520,14 +486,14 @@ pub(crate) async fn question_from_bank( if !crate::web::bank_questions::can_see(&template, &user) { return Err(AppError::NotFound); } - let question = ExamQuestion::create_from_bank( + let question = exam_question::create_from_bank( + &st.db, exam.get_id(), subject, template.get_text().clone(), template.get_points(), template.spec(), template.get_id().clone(), - &st.db, ) .await?; @@ -565,7 +531,7 @@ pub(crate) async fn question_from_bank( for file in &copied { remove_blob(&st.files_path, file).await; } - let _ = question.delete(&st.db).await; + let _ = exam_question::delete(&st.db, question).await; return Err(err); } } @@ -640,8 +606,8 @@ pub(crate) async fn question_refresh_from_bank( // No lock: the question keeps its own subject here, so there is nothing to // pair with a subject delete, and the freeze gate rides in the overwrite's // transaction. - ensure_questions_editable(exam.get_id(), &st.db).await?; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; + let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; let Some(source) = question.get_from_bank().cloned() else { return Err(AppError::Validation(ValidationError::Invalid { @@ -680,15 +646,15 @@ pub(crate) async fn question_refresh_from_bank( let subject = question.get_subject().clone(); // `spec()` hands over the template's stored choices *with their ids* rather // than re-minting any — the same funnel `question_from_bank` uses. - let updated = question - .update( - subject, - template.get_text().clone(), - template.get_points(), - template.spec(), - &st.db, - ) - .await?; + let updated = exam_question::update( + &st.db, + question, + subject, + template.get_text().clone(), + template.get_points(), + template.spec(), + ) + .await?; // Make the pictures match the template exactly: drop every slot the // template has no picture for (including the illustration, and every option @@ -765,7 +731,7 @@ pub(crate) async fn question_to_bank( // No lease: `BANK_LOCK` is gone with the subject delete's writer lease, and // a template left holding a deleted subject reads as an empty // `subject_name` either way (see [`crate::web::bank_questions`]). - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; // `create_from_exam` mints its own id and insert (the funnel), fed the // question's fields plus the origin exam it was saved off. @@ -827,14 +793,13 @@ pub(crate) async fn question_to_bank( // template with no back-link (the next save re-links it). let question_key = question.get_id().key().to_string(); // No exam lease around the back-link any more, and none is needed: this is a - // single-column `UPDATE`, and `ExamQuestion::update` no longer re-states + // single-column `UPDATE`, and the question row `UPDATE` no longer re-states // this column from a snapshot (it names the columns it writes), so a // question edit racing the link cannot revert it. That lease existed only to // order those two, and the ordering requirement is gone with the whole-row // save that created it. - if let Err(err) = question - .link_banked_as(template.get_id().clone(), &st.db) - .await + if let Err(err) = + exam_question::link_banked_as(&st.db, question, template.get_id().clone()).await { tracing::warn!( "saved question {question_key} to the bank but could not link it back: {err}" diff --git a/src/web/exams/review.rs b/src/web/exams/review.rs index a4dfe8a..c3c3251 100644 --- a/src/web/exams/review.rs +++ b/src/web/exams/review.rs @@ -1,9 +1,8 @@ use super::*; use crate::domain::exam_attempt::AttemptStatus; -use crate::service::exam_attempt::{ - course_of, list_for_user, list_unfinished_for_user, question_of_exam, -}; +use crate::service::exam_attempt::{course_of, list_for_user, list_unfinished_for_user}; +use crate::service::exam_question; // ---- per-attempt history ---------------------------------------------------- // The grading views above show the latest sitting; these expose every prior @@ -121,7 +120,7 @@ pub(crate) async fn student_attempt_answer_image( ) -> Result { let exam = gradable_exam(&st, &user, &id).await?; let target = UserId::from_key(&target); - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; let image = AnswerImage::read(question.get_id(), &target, seq, &st.db) .await? .ok_or(AppError::NotFound)?; @@ -253,7 +252,7 @@ pub(crate) async fn reviewable_exam( /// count — a question authored by hand and *saved* to the bank shares its key /// with every later instantiation just as an instantiated one does, so only a /// question with no bank link at all is never hidden -/// ([`ExamQuestion::list_shared_with`]). +/// ([`crate::service::exam_question::list_shared_with`]). /// /// The open sittings are read whole and judged here rather than filtered in /// SurrealQL, because "in progress" is [`ExamAttempt::status`]'s call off the @@ -275,7 +274,7 @@ async fn live_elsewhere( live.push(other.get_id().clone()); } } - ExamQuestion::list_shared_with(exam.get_id(), &live, &st.db).await + exam_question::list_shared_with(&st.db, exam.get_id(), &live).await } /// The caller's own sitting numbers at an exam — every seq that carries answers @@ -417,7 +416,7 @@ pub(crate) async fn review_attempt_answer_image( Path((id, seq, qid)): Path<(String, i64, String)>, ) -> Result { let exam = reviewable_exam(&st, &user, &id).await?; - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db) .await? .ok_or(AppError::NotFound)?; diff --git a/tests/integration.rs b/tests/integration.rs index 632284a..36b80bd 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -9625,8 +9625,8 @@ async fn live_monitor_tracks_answer_progress() { #[tokio::test] async fn questions_and_answers_cascade_with_deletes() { + use hezarfen_backend::db::exam_question; use hezarfen_backend::domain::exam_answer::ExamAnswer; - use hezarfen_backend::domain::exam_question::ExamQuestion; let (app, db) = app_and_db().await; let teacher = login_as(&app, &db, "qc_t", "teacher").await; @@ -9677,7 +9677,7 @@ async fn questions_and_answers_cascade_with_deletes() { } let exam_id = ExamId::from_key(&exam); assert_eq!( - ExamQuestion::list_for_exam(&exam_id, None, 0, &db) + exam_question::list_for_exam(&db, &exam_id, None, 0) .await .unwrap() .0 @@ -9693,10 +9693,10 @@ async fn questions_and_answers_cascade_with_deletes() { ); // Deleting one question takes its answers with it. The freeze gate now - // lives inside `ExamQuestion::delete`'s own transaction (not in a lock the + // lives inside `db::exam_question::delete`'s own transaction (not in a lock the // handler held), so the attempt has to go first for the cascade to be // exercised at all — that refusal is asserted here before it is cleared. - let frozen = ExamQuestion::list_for_exam(&exam_id, None, 0, &db) + let frozen = exam_question::list_for_exam(&db, &exam_id, None, 0) .await .unwrap() .0 @@ -9704,7 +9704,7 @@ async fn questions_and_answers_cascade_with_deletes() { .next() .unwrap(); assert!( - matches!(frozen.delete(&db).await, Err(err) if err.to_string().contains("after attempts")), + matches!(exam_question::delete(&db, frozen).await, Err(err) if err.to_string().contains("after attempts")), "the gate must refuse a question delete while an attempt exists" ); db.query("DELETE exam_attempt WHERE exam = $ex") @@ -9713,16 +9713,16 @@ async fn questions_and_answers_cascade_with_deletes() { .unwrap() .check() .unwrap(); - let question = ExamQuestion::list_for_exam(&exam_id, None, 0, &db) + let question = exam_question::list_for_exam(&db, &exam_id, None, 0) .await .unwrap() .0 .into_iter() .next() .unwrap(); - question.delete(&db).await.unwrap(); + exam_question::delete(&db, question).await.unwrap(); assert_eq!( - ExamQuestion::list_for_exam(&exam_id, None, 0, &db) + exam_question::list_for_exam(&db, &exam_id, None, 0) .await .unwrap() .0 @@ -9749,7 +9749,7 @@ async fn questions_and_answers_cascade_with_deletes() { .await; assert_eq!(res.status, StatusCode::NO_CONTENT); assert!( - ExamQuestion::list_for_exam(&exam_id, None, 0, &db) + exam_question::list_for_exam(&db, &exam_id, None, 0) .await .unwrap() .0 @@ -9813,7 +9813,7 @@ async fn questions_and_answers_cascade_with_deletes() { assert_eq!(res.status, StatusCode::NO_CONTENT); let exam2_id = ExamId::from_key(&exam2); assert!( - ExamQuestion::list_for_exam(&exam2_id, None, 0, &db) + exam_question::list_for_exam(&db, &exam2_id, None, 0) .await .unwrap() .0 @@ -20592,8 +20592,9 @@ async fn to_bank_links_the_question_at_the_new_template() { /// domain level: HTTP offers no way to interleave inside the handler. #[tokio::test] async fn linking_the_banked_template_does_not_clobber_a_concurrent_edit() { + use hezarfen_backend::db::exam_question; use hezarfen_backend::domain::bank_question::BankQuestionId; - use hezarfen_backend::domain::exam_question::{ExamQuestion, ExamQuestionId}; + use hezarfen_backend::domain::exam_question::ExamQuestionId; let (app, db) = app_and_db().await; let teacher = login_as(&app, &db, "bclob_t", "teacher").await; @@ -20619,7 +20620,7 @@ async fn linking_the_banked_template_does_not_clobber_a_concurrent_edit() { let bid = id_of(&res.body); // The handler's read, then someone else's edit lands mid-window. - let stale = ExamQuestion::read(&ExamQuestionId::from_key(&qid), &db) + let stale = exam_question::read(&db, &ExamQuestionId::from_key(&qid)) .await .unwrap() .expect("question exists"); @@ -20633,8 +20634,7 @@ async fn linking_the_banked_template_does_not_clobber_a_concurrent_edit() { .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - stale - .link_banked_as(BankQuestionId::from_key(&bid), &db) + exam_question::link_banked_as(&db, stale, BankQuestionId::from_key(&bid)) .await .expect("link written"); @@ -21287,9 +21287,7 @@ async fn refreshing_a_question_recopies_its_template() { #[tokio::test] async fn a_course_patch_does_not_clobber_a_concurrent_teacher_assignment() { use hezarfen_backend::db::course; - use hezarfen_backend::domain::course::{ - CourseDescription, CourseId, CourseKind, CourseTitle, - }; + use hezarfen_backend::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; let (app, db) = app_and_db().await; let owner = login_as(&app, &db, "cclob_o", "teacher").await;