From 61990de60876b283f046a54ae2106a6c57d5e4c7 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 14:48:39 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=B9=20chore:=20split=20exam=5Fanswer/e?= =?UTF-8?q?xam=5Fresult/answer=5Fimage/question=5Fimage=20into=20domain/db?= =?UTF-8?q?/service=20layers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/db/answer_image.rs | 320 +++++++++++ src/db/cap.rs | 2 +- src/db/exam.rs | 56 +- src/db/exam_answer.rs | 362 +++++++++++++ src/db/exam_attempt.rs | 2 +- src/db/exam_result.rs | 802 +++++++++++++++++++++++++++ src/db/mod.rs | 4 + src/db/question_image.rs | 332 ++++++++++++ src/domain/answer_image.rs | 355 +----------- src/domain/attendance.rs | 4 +- src/domain/chatbot_thread.rs | 2 +- src/domain/class_pump.rs | 2 +- src/domain/exam_answer.rs | 332 +----------- src/domain/exam_result.rs | 862 ++---------------------------- src/domain/homework_submission.rs | 4 +- src/domain/pool_question.rs | 2 +- src/domain/question_image.rs | 372 +------------ src/domain/session_attendance.rs | 4 +- src/service/answer_image.rs | 46 ++ src/service/course.rs | 7 +- src/service/exam.rs | 12 +- src/service/exam_answer.rs | 71 +++ src/service/exam_attempt.rs | 20 +- src/service/exam_result.rs | 167 ++++++ src/service/mod.rs | 4 + src/service/question_image.rs | 58 ++ src/web/exam_ws.rs | 13 +- src/web/exams/attempts.rs | 21 +- src/web/exams/images.rs | 45 +- src/web/exams/mod.rs | 121 +---- src/web/exams/questions.rs | 25 +- src/web/exams/review.rs | 23 +- src/web/marks.rs | 4 +- tests/integration.rs | 10 +- 34 files changed, 2402 insertions(+), 2064 deletions(-) create mode 100644 src/db/answer_image.rs create mode 100644 src/db/exam_answer.rs create mode 100644 src/db/exam_result.rs create mode 100644 src/db/question_image.rs create mode 100644 src/service/answer_image.rs create mode 100644 src/service/exam_answer.rs create mode 100644 src/service/exam_result.rs create mode 100644 src/service/question_image.rs diff --git a/src/db/answer_image.rs b/src/db/answer_image.rs new file mode 100644 index 0000000..324e868 --- /dev/null +++ b/src/db/answer_image.rs @@ -0,0 +1,320 @@ +//! The `answer_image` table: the drawing upsert that names the blob it +//! replaces from inside its own transaction, the per-sitting and per-exam +//! reads, and the sweeps the retake and cascades use. The row's pure half — +//! ids and the fresh-blob-name constructor — lives in +//! [`crate::domain::answer_image`]; the blob bytes stay the web layer's. + +use surrealdb::types::SurrealValue; + +use crate::constant::EXAM_RESULT_COUNT_FIELD; +use crate::database::{Database, transaction_with_retry}; +use crate::domain::answer_image::{AnswerImage, AnswerImageId}; +use crate::domain::course::CourseId; +use crate::domain::exam::ExamId; +use crate::domain::exam_question::ExamQuestionId; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// What one [`upsert`] transaction returns: the row it stored and +/// the blob name it replaced. Both are arrays because SurrealDB drops an object +/// key valued `NONE` on the way out, while an empty array survives — "nothing +/// was replaced" has to be readable, not missing. +#[derive(SurrealValue)] +struct UpsertOutcome { + stored: Vec, + replaced: Vec, +} + +/// Create or replace the student's drawing for the question — the +/// deterministic id makes this the whole "one drawing per student per +/// question" story — handing back what it stored plus the blob name it +/// replaced, for the caller to take off disk. +/// +/// The replaced name is read *here*, inside this transaction, not by the +/// caller in front of it: two uploads to one (question, user, seq) both +/// write this row, so they contend and the loser re-reads the winner's blob +/// name, where two pre-reads both saw the *old* blob and left the loser's +/// fresh one on disk with nothing pointing at it. Same shape as +/// [`crate::db::question_image::upsert`]. +/// +/// `NotFound` = the exam is gone, and the drawing was *not* written. The +/// write moves the exam's mark counter and puts it straight back, in this +/// one transaction, so the exam's existence is something this write +/// *writes* rather than something a gate read a moment earlier: a bare +/// upsert landing after [`delete`](crate::db::exam::delete) +/// removed the exam but before it committed was swept by nothing — its +/// `DELETE answer_image WHERE exam = $ex` ran on a snapshot predating this +/// row — and both sides reported success. That stranded the blob as well as +/// the row: `delete_exam` collects the names to unlink *before* it calls +/// the delete, so bytes written after that snapshot stay on disk forever. +/// This is the shape [`crate::db::exam_answer::save`] takes +/// for the text half of the same answer sheet, and for the same reason. +/// +/// The restore is by captured value, `NONE` included, so the row is +/// byte-identical afterwards and a teacher's PATCH — which pins that +/// counter — is not refused because a student drew. Writing the same value +/// back would buy nothing: an `UPDATE` that leaves the document unchanged +/// is elided and never reaches the store's write set. +/// +/// Admissible for [`transaction_with_retry`]: the `UPDATE`s, `SELECT`, +/// `IF`/`THROW` and `RETURN` can never answer "already exists", and the +/// `UPSERT`'s id is bijective with the (question, user, seq) triple this +/// table keys — a lost round wrote nothing, and re-sending resolves onto +/// the same row rather than colliding with it. +pub async fn upsert( + db: &Database, + image: AnswerImage, +) -> Result<(AnswerImage, Option), AppError> { + // whole-row-save-ok: image is built in place from the request, never read back, and the (question, user, seq) id is deterministic — replacing the row *is* the operation + let (exam, id) = (image.exam.record(), image.id.record()); + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $was = (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $ex); + LET $touched = (UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = \ + ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); + IF array::len($touched) = 0 {{ THROW 'no_exam' }}; + UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = $was; + LET $replaced = (SELECT VALUE file FROM $id); + LET $row = (UPSERT $id CONTENT $image RETURN AFTER); + RETURN {{ stored: $row, replaced: $replaced }}; + COMMIT TRANSACTION;" + ), + &[ + ("ex".into(), exam.into_value()), + ("id".into(), id.into_value()), + ("image".into(), image.into_value()), + ], + &["no_exam"], + ) + .await?; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the THROW's own slot names the reason. + if errors + .values() + .any(|error| error.to_string().contains("no_exam")) + { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is the last statement before `COMMIT`, so its + // slot follows the statement count rather than a hand-kept number; + // `num_statements` counts BEGIN and COMMIT. + let slot = result.num_statements().saturating_sub(2); + let failed = || AppError::Internal("failed to store answer image".into()); + let outcome = result + .take::>(slot)? + .into_iter() + .next() + .ok_or_else(failed)?; + let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; + Ok((stored, outcome.replaced.into_iter().next())) +} + +/// The student's drawing for one question in one sitting, if any. +pub async fn read( + db: &Database, + question: &ExamQuestionId, + user: &UserId, + seq: i64, +) -> Result, AppError> { + Ok(db + .select(AnswerImageId::composite(question, user, seq).record()) + .await?) +} + +/// Every answer drawing of the exam — one query for the exam-delete cascade. +pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM answer_image WHERE exam = $ex") + .bind(("ex", exam.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// One student's answer drawings for a single sitting — the parallel to +/// [`crate::db::exam_answer::list_for_exam_user`], feeding +/// the sitting/grading answer-image maps for that attempt's `seq`. +pub async fn list_for_exam_user( + db: &Database, + exam: &ExamId, + user: &UserId, + seq: i64, +) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM answer_image WHERE exam = $ex AND user = $usr AND seq = $seq") + .bind(("ex", exam.record())) + .bind(("usr", user.record())) + .bind(("seq", seq)) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// The distinct sittings (`seq`, ascending) this student has any answer +/// drawing for at this exam — the history index behind a per-attempt view. +pub async fn list_seqs_for_user( + db: &Database, + exam: &ExamId, + user: &UserId, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT VALUE seq FROM answer_image \ + WHERE exam = $ex AND user = $usr ORDER BY seq", + ) + .bind(("ex", exam.record())) + .bind(("usr", user.record())) + .await? + .check()?; + let mut seqs = result.take::>(0)?; + seqs.dedup(); + Ok(seqs) +} + +/// The blob names behind every answer drawing of every exam of `course` — +/// collected *before* the course-delete cascade wipes the rows. +pub async fn file_keys_for_course( + db: &Database, + course: &CourseId, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT VALUE file FROM answer_image \ + WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)", + ) + .bind(("course", course.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +pub async fn delete(db: &Database, image: AnswerImage) -> Result { + let deleted: Option = db.delete(image.id.record()).await?; + deleted.ok_or(AppError::NotFound) +} + +/// Drop one student's answer drawings across an exam — a retake starts from +/// a blank sheet. Rows only; the caller GCs the blobs. The retake path itself +/// wipes rows inside `ExamAttempt::wipe_and_create`'s transaction; this is +/// the standalone mirror of [`crate::db::exam_answer::delete_for_exam_user`]. +pub async fn delete_for_exam_user( + db: &Database, + exam: &ExamId, + user: &UserId, +) -> Result<(), AppError> { + db.query("DELETE answer_image WHERE exam = $ex AND user = $usr") + .bind(("ex", exam.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::note_file::FileContentType; + + fn png() -> FileContentType { + FileContentType::try_new("image/png").unwrap() + } + + /// A real exam row: a drawing's write moves its exam's counter (that is + /// what keeps it from outliving the exam), so a minted id nothing wrote is + /// a 404. + async fn exam_row(db: &Database) -> ExamId { + crate::db::exam::published_exam(db).await.get_id().clone() + } + + fn student() -> UserId { + UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA") + } + + #[tokio::test] + async fn upsert_replaces_within_a_sitting_but_not_across_them() { + let db = crate::database::init_mem().await.unwrap(); + let exam = exam_row(&db).await; + let question = ExamQuestionId::generate(); + let user = student(); + + let (first, retired) = upsert(&db, AnswerImage::new(&exam, &question, &user, 1, png(), 3)) + .await + .unwrap(); + assert_eq!(retired, None, "a first upload retires no blob"); + let (second, retired) = upsert(&db, AnswerImage::new(&exam, &question, &user, 1, png(), 5)) + .await + .unwrap(); + // Same (question, user, seq), same row — the replace swapped the blob, + // and the write itself names the blob the caller must unlink. + assert_ne!(first.get_file(), second.get_file()); + assert_eq!(retired.as_deref(), Some(first.get_file())); + let rows = list_for_exam_user(&db, &exam, &user, 1).await.unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].get_size(), 5); + + // A retake (seq 2) accumulates: it is its own row, not an overwrite. + upsert(&db, AnswerImage::new(&exam, &question, &user, 2, png(), 9)) + .await + .unwrap(); + assert_eq!( + list_for_exam_user(&db, &exam, &user, 1) + .await + .unwrap() + .len(), + 1, + "the seq-2 image must not overwrite seq-1" + ); + assert_eq!( + list_for_exam_user(&db, &exam, &user, 2).await.unwrap()[0].get_size(), + 9 + ); + assert_eq!( + list_seqs_for_user(&db, &exam, &user).await.unwrap(), + vec![1, 2] + ); + + // Another student's drawing for the same question/sitting is its own row. + let other = UserId::from_key("01TESTSTUDENTBBBBBBBBBBBBB"); + upsert(&db, AnswerImage::new(&exam, &question, &other, 1, png(), 7)) + .await + .unwrap(); + assert_eq!(list_for_exam(&db, &exam).await.unwrap().len(), 3); + assert!(read(&db, &question, &user, 2).await.unwrap().is_some()); + } + + #[tokio::test] + async fn listing_scopes_by_exam_and_user() { + let db = crate::database::init_mem().await.unwrap(); + let exam_a = exam_row(&db).await; + let exam_b = exam_row(&db).await; + let user = student(); + upsert( + &db, + AnswerImage::new(&exam_a, &ExamQuestionId::generate(), &user, 1, png(), 1), + ) + .await + .unwrap(); + assert_eq!( + list_for_exam_user(&db, &exam_a, &user, 1) + .await + .unwrap() + .len(), + 1 + ); + assert!(list_for_exam(&db, &exam_b).await.unwrap().is_empty()); + + // delete_for_exam_user clears the student's sheet across all sittings. + delete_for_exam_user(&db, &exam_a, &user).await.unwrap(); + assert!( + list_for_exam_user(&db, &exam_a, &user, 1) + .await + .unwrap() + .is_empty() + ); + } +} diff --git a/src/db/cap.rs b/src/db/cap.rs index 117322c..8201c26 100644 --- a/src/db/cap.rs +++ b/src/db/cap.rs @@ -387,7 +387,7 @@ const GONE_MARK: &str = "cap_gone"; /// write set: `SET x = x` sits on no key at all and collides with nothing /// (measured on 3.2.3, and the reason /// [`crate::domain::class_pump::Axis::pivot_claim`] and -/// [`crate::domain::exam_answer::ExamAnswer::save`] have the same shape). Both +/// [`crate::db::exam_answer::save`] have the same shape). Both /// statements are inside the transaction, so an abort between them cannot leave /// the counter up. /// diff --git a/src/db/exam.rs b/src/db/exam.rs index f8d639a..005ff06 100644 --- a/src/db/exam.rs +++ b/src/db/exam.rs @@ -165,7 +165,7 @@ pub async fn update_if_unchanged( // // 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 + // ([`crate::db::exam_answer::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 @@ -308,7 +308,7 @@ 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 +/// and [`crate::db::exam_answer::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 { @@ -450,18 +450,19 @@ mod tests { /// 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}; + use crate::db::exam_result; + use crate::domain::exam_result::Mark; let db = crate::database::init_mem().await.unwrap(); let exam = published(&db).await; let student = UserId::generate(); - ExamResult::grade( + exam_result::grade( + &db, exam.get_id(), &student, 1, Mark::try_new(80).unwrap(), &UserId::generate(), exam.get_kind().as_str(), - &db, ) .await .unwrap(); @@ -603,7 +604,7 @@ mod tests { /// 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 + /// The racer is a mark: [`crate::db::exam_result::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 @@ -625,7 +626,8 @@ mod tests { #[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}; + use crate::db::exam_result; + use crate::domain::exam_result::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); @@ -655,14 +657,14 @@ mod tests { 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( + exam_result::grade( + &db, &id, &student, 1, Mark::try_new(50).unwrap(), &UserId::from_key("teacher"), &kind, - &db, ) .await }) @@ -693,7 +695,7 @@ mod tests { if (1..6).contains(&refused) { split += 1; } - if ExamResult::list_for_exam(exam.get_id(), &db) + if exam_result::list_for_exam(&db, exam.get_id()) .await .unwrap() .is_empty() @@ -774,7 +776,7 @@ mod tests { /// 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 + /// pointing at an exam that is gone. [`crate::db::exam_answer::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. /// @@ -797,7 +799,7 @@ mod tests { #[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; + use crate::db::exam_answer; 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. @@ -833,7 +835,7 @@ mod tests { 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 + exam_answer::save(&db, &question, &student, 1, Some(pick), None).await }) }; let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); @@ -847,7 +849,7 @@ mod tests { // 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(); + answers += exam_answer::list_for_exam(&db, &id).await.unwrap().len(); } else if drop_it.is_ok() { panic!("round {round}: the delete reported success but the exam is still there"); } @@ -976,7 +978,7 @@ mod tests { } /// 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 + /// `UPSERT` — the exact pre-fix shape of [`crate::db::exam_answer::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"] @@ -1008,16 +1010,15 @@ mod tests { let child = { let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone()); tokio::spawn(async move { - AnswerImage::new( + let image = AnswerImage::new( &exam_id, &on, &student, 1, FileContentType::try_new("image/png").unwrap(), 3, - ) - .upsert(&db) - .await + ); + crate::db::answer_image::upsert(&db, image).await }) }; let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); @@ -1028,7 +1029,10 @@ mod tests { if read(&db, &id).await.unwrap().is_none() { swept += 1; - drawings += AnswerImage::list_for_exam(&id, &db).await.unwrap().len(); + drawings += crate::db::answer_image::list_for_exam(&db, &id) + .await + .unwrap() + .len(); } else if drop_it.is_ok() { panic!("round {round}: the delete reported success but the exam is still there"); } @@ -1075,15 +1079,14 @@ mod tests { let child = { let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone()); tokio::spawn(async move { - QuestionImage::new( + let image = QuestionImage::new( &exam_id, &on, None, FileContentType::try_new("image/png").unwrap(), 3, - ) - .upsert(&db) - .await + ); + crate::db::question_image::upsert(&db, image).await }) }; let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); @@ -1094,7 +1097,10 @@ mod tests { if read(&db, &id).await.unwrap().is_none() { swept += 1; - images += QuestionImage::list_for_exam(&id, &db).await.unwrap().len(); + images += crate::db::question_image::list_for_exam(&db, &id) + .await + .unwrap() + .len(); } else if drop_it.is_ok() { panic!("round {round}: the delete reported success but the exam is still there"); } diff --git a/src/db/exam_answer.rs b/src/db/exam_answer.rs new file mode 100644 index 0000000..e7ab1a8 --- /dev/null +++ b/src/db/exam_answer.rs @@ -0,0 +1,362 @@ +//! The `exam_answer` table: the autosave upsert keyed by the (question, user, +//! seq) sitting triple, the per-sitting and per-exam reads, and the sweeps a +//! retake and the cascades use. The sitting key shape and the payload +//! validation's pure half live in [`crate::domain::exam_answer`]. + +use surrealdb::types::SurrealValue; + +use crate::constant::EXAM_RESULT_COUNT_FIELD; +use crate::database::{Database, transaction_with_retry}; +use crate::domain::exam::ExamId; +use crate::domain::exam_answer::{AnswerText, ExamAnswer, ExamAnswerId}; +use crate::domain::exam_question::{ExamQuestion, ExamQuestionId}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; + +/// Save (or overwrite) `user`'s answer to `question` for sitting `seq` — +/// the one write path, shared by the REST handler and the WebSocket room. +/// The payload must match the question's kind: a choice question takes +/// `selected` (the id of one of its choices), a text question takes `text`. +/// The caller has already checked that the attempt is in progress. Keyed +/// by `seq`, so a retake's save is a new row, not an overwrite of an +/// earlier sitting's answer. +pub async fn save( + db: &Database, + question: &ExamQuestion, + user: &UserId, + seq: i64, + selected: Option, + text: Option, +) -> Result { + let invalid = |field, reason| AppError::Validation(ValidationError::Invalid { field, reason }); + let (selected, text) = match question.get_kind().as_str() { + "choice" => { + if text.is_some() { + return Err(invalid( + "text", + "a choice question takes selected, not text", + )); + } + let Some(selected) = selected else { + return Err(invalid("selected", "required for a choice question")); + }; + // Membership, not a range: `selected` names an option by its + // stable id, so a reorder of the list can never repoint it. + let picked = question + .get_choices() + .unwrap_or_default() + .iter() + .find(|choice| choice.get_id().as_str() == selected) + .ok_or_else(|| invalid("selected", "must name one of the question's choices"))?; + (Some(picked.get_id().clone()), None) + } + _ => { + if selected.is_some() { + return Err(invalid( + "selected", + "a text question takes text, not selected", + )); + } + let Some(text) = text else { + return Err(invalid("text", "required for a text question")); + }; + (None, Some(AnswerText::try_new(&text)?)) + } + }; + let answer = ExamAnswer { + id: ExamAnswerId::composite(question.get_id(), user, seq), + exam: question.get_exam().clone(), + question: question.get_id().clone(), + user: user.clone(), + seq, + selected, + text, + updated_at: Timestamp::now(), + }; + // 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::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 + // and the answer outlives the exam (measured 4 of 4 raced rounds). + // Writing the key the delete removes makes the two collide, and the + // store refuses one of them. It is the shape + // [`crate::domain::menu::bump_menu_and_write`] uses, and the one a mark + // already uses on this very row + // ([`crate::db::exam_result::grade`]). + // + // The bump-and-restore is not a flourish, it is the whole instrument. + // The exam carries no revision to bump and must not grow one — its save + // is a whole-row `CONTENT` write, so a column this struct did not know + // about would be wiped by the next PATCH — so this touches the one + // counter it already has and puts it back. Writing the *same* value is + // not enough: an `UPDATE` that leaves the document unchanged is elided + // and never reaches the store's write set, which the race test proved + // (green on the raced delete, red the moment the value moves for real). + // The restore is by captured value, `NONE` included, so the row is + // byte-identical afterwards: the boot backfill still finds the rows it + // keys on (`WHERE result_count = NONE`), the PATCH's + // `(result_count ?? 0) = $was_results` still passes, and no teacher's + // edit is refused because a student typed. Both statements are inside + // the transaction, so a crash between them cannot leave the counter up. + // No `cap::counter_lock` either: no counter moves here, and the hottest + // write path in the app should not queue behind one. + // + // Admissible for `transaction_with_retry`: the `UPDATE`s, `SELECT`, + // `IF`/`THROW` and `RETURN` can never answer "already exists", and the + // `UPSERT`'s id is bijective with the (question, user, seq) triple + // `exam_answer` keys — a lost round wrote nothing, and re-sending + // resolves onto the same row rather than colliding with it. + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $was = (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $ex); + LET $touched = (UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = \ + ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); + IF array::len($touched) = 0 {{ THROW 'no_exam' }}; + UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = $was; + LET $row = (UPSERT $id CONTENT $answer RETURN AFTER); + RETURN $row[0]; + COMMIT TRANSACTION;" + ), + &[ + ("ex".into(), answer.exam.record().into_value()), + ("id".into(), answer.id.record().into_value()), + ("answer".into(), answer.into_value()), + ], + &["no_exam"], + ) + .await?; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the THROW's own slot names the reason. + if errors + .values() + .any(|error| error.to_string().contains("no_exam")) + { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is the last statement before `COMMIT`, so its + // slot follows the statement count rather than a hand-kept number (the + // `db::exam::delete` treatment); `num_statements` counts BEGIN and COMMIT. + let slot = result.num_statements().saturating_sub(2); + result + .take::>(slot)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to save exam answer".into())) +} + +/// One student's stored answer for a question in sitting `seq`, if any. +pub async fn read( + db: &Database, + question: &ExamQuestionId, + user: &UserId, + seq: i64, +) -> Result, AppError> { + Ok(db + .select(ExamAnswerId::composite(question, user, seq).record()) + .await?) +} + +/// Drop one student's answer to a single question in sitting `seq`. +pub async fn delete( + db: &Database, + question: &ExamQuestionId, + user: &UserId, + seq: i64, +) -> Result<(), AppError> { + let _: Option = db + .delete(ExamAnswerId::composite(question, user, seq).record()) + .await?; + Ok(()) +} + +/// One student's answers for a single sitting (`seq`) across an exam, in +/// question (ULID) order — the live-sitting read-back and, for a past +/// `seq`, that attempt's answer sheet. +pub async fn list_for_exam_user( + db: &Database, + exam: &ExamId, + user: &UserId, + seq: i64, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM exam_answer WHERE exam = $ex AND user = $usr AND seq = $seq + ORDER BY question ASC", + ) + .bind(("ex", exam.record())) + .bind(("usr", user.record())) + .bind(("seq", seq)) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// The distinct sittings a student has any answer for at `exam`, ascending +/// — the index a history view lists attempts from. +pub async fn list_seqs_for_user( + db: &Database, + exam: &ExamId, + user: &UserId, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT VALUE seq FROM exam_answer WHERE exam = $ex AND user = $usr + ORDER BY seq ASC", + ) + .bind(("ex", exam.record())) + .bind(("usr", user.record())) + .await? + .check()?; + let mut seqs = result.take::>(0)?; + seqs.dedup(); + Ok(seqs) +} + +/// Every answer of an exam — the live monitor aggregates these per student. +pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM exam_answer WHERE exam = $ex ORDER BY question ASC") + .bind(("ex", exam.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Drop one student's answers across an exam — a retake starts from a +/// blank sheet. +pub async fn delete_for_exam_user( + db: &Database, + exam: &ExamId, + user: &UserId, +) -> Result<(), AppError> { + db.query("DELETE exam_answer WHERE exam = $ex AND user = $usr") + .bind(("ex", exam.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::exam::ExamId; + use crate::domain::exam_question::{ChoiceId, ChoiceInput, QuestionKind, QuestionSpec}; + + /// A three-option question whose `correct` is the option at `correct`. + /// Positions are a *test* convenience only — the ids are minted, and every + /// assertion below goes through `choice_id`. + fn choice_question(exam: &ExamId, points: i64, correct: usize) -> ExamQuestion { + let labels = ["a", "b", "c"]; + let spec = QuestionSpec::try_new( + QuestionKind::try_new("choice").unwrap(), + Some( + labels + .iter() + .map(|l| ChoiceInput { + id: Some((*l).into()), + text: (*l).into(), + }) + .collect(), + ), + Some(labels[correct].into()), + &[], + ) + .unwrap(); + ExamQuestion::test_new(exam, "pick one", points, spec) + } + + /// The minted id of the question's option at `index`. + fn choice_id(question: &ExamQuestion, index: usize) -> ChoiceId { + question.get_choices().unwrap()[index].get_id().clone() + } + + fn student() -> UserId { + UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA") + } + + /// The bite test for the exam-row touch in [`save`]: it exists + /// 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 + /// `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::{ + 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 = crate::db::exam::create( + &db, + &student(), + &crate::db::course::a_test_course(&db).await, + 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 + .unwrap(); + let stored = async |db: &Database| -> Option { + let mut result = db + .query("SELECT VALUE result_count FROM ONLY $ex") + .bind(("ex", exam.get_id().record())) + .await + .unwrap() + .check() + .unwrap(); + result.take::>(0).unwrap() + }; + let question = choice_question(exam.get_id(), 10, 1); + let pick = choice_id(&question, 1).as_str().to_string(); + + // A fresh exam carries no counter at all, and must still not after a save. + assert_eq!(stored(&db).await, None, "the fixture must start absent"); + save(&db, &question, &student(), 1, Some(pick.clone()), None) + .await + .unwrap(); + assert_eq!( + stored(&db).await, + None, + "the touch left the counter set — the backfill keys on NONE" + ); + + // …and a counter that marks have moved is put back at its own value. + db.query("UPDATE $ex SET result_count = 7") + .bind(("ex", exam.get_id().record())) + .await + .unwrap() + .check() + .unwrap(); + save(&db, &question, &student(), 2, Some(pick), None) + .await + .unwrap(); + assert_eq!(stored(&db).await, Some(7), "the touch moved a real count"); + + // The gate that makes the touch worth having: no exam, no answer. + let orphan = choice_question(&ExamId::from_key("01NOSUCHEXAMAAAAAAAAAAAAAA"), 10, 0); + let pick = choice_id(&orphan, 0).as_str().to_string(); + let refused = save(&db, &orphan, &student(), 1, Some(pick), None).await; + assert!( + matches!(refused, Err(AppError::NotFound)), + "a save into a missing exam must 404, got {refused:?}" + ); + } +} diff --git a/src/db/exam_attempt.rs b/src/db/exam_attempt.rs index 0e07a1b..1e2ed50 100644 --- a/src/db/exam_attempt.rs +++ b/src/db/exam_attempt.rs @@ -171,7 +171,7 @@ pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result Result, AppError> { + // Grade-of-record is the latest sitting's mark: the highest seq wins. + let mut result = db + .query( + "SELECT * FROM exam_result WHERE exam = $ex AND user = $usr + ORDER BY seq DESC LIMIT 1", + ) + .bind(("ex", exam.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) +} + +/// Record (or overwrite) `user`'s mark for the `seq`th sitting of `exam`. +/// One row per (exam, user, seq), keyed by a deterministic composite id so +/// this is a single atomic UPSERT — concurrent grades for the same sitting +/// converge on one row instead of racing the unique index into a 500. +/// Grading a retake writes a fresh mark at the current seq and never touches +/// prior sittings' marks; the latest seq is the grade-of-record. +/// +/// `kind` is the exam's kind, and this is where a mark takes its reference +/// on it — claimed *inside the mark's own transaction*, and only on the +/// branch that is about to add a row. A kind the school has retired refuses +/// the claim, which is the same invariant the settings guard enforces from +/// the other side. Claimed before the write and released after, the pair had +/// two crash windows either side of the write that leaked a reference (a +/// kind frozen out of the settings for good) and an exam's `result_count`; +/// riding the transaction, both counters land exactly when the row does. +/// +/// The exam's own `result_count` is claimed in the same breath, and it is +/// what a kind change is refused against: the exam PATCH pins that counter, +/// so a mark landing while it decides cannot slip past its gate and leave +/// itself counted under a kind its exam no longer carries. +/// +/// An overwrite (a regrade of a sitting already marked) claims *nothing*: +/// one mark, one reference, so the branch that finds a row simply leaves +/// both counters where they are — there is no claim to give back, and so no +/// window in which a crash could fail to give it. +/// +/// The grader's `marks_given_total` rides that same first-time branch: a +/// regrade of a sitting moves it however often it is run, while a retake, +/// being a distinct `seq` and so a distinct row, counts on its own. +/// +/// The student's `high_mark_total` cannot ride it, because it is not a +/// count of rows but a count of rows *at or above* [`HIGH_MARK_MIN`], and a +/// regrade moves a mark across that line without adding or removing a row. +/// It moves by the difference between the mark about to be stored and the +/// one already there — `+1` crossing up, `-1` crossing down, nothing at all +/// when both sides sit on the same side of the line, so an overwrite still +/// costs the student's row no write unless the answer actually changed. +/// Decided on the first branch alone it drifted upward without bound: 95 +/// credited, regraded to 40 (no row added, so no move), then deleted, whose +/// refund reads the *stored* mark and so found nothing to give back — a +/// counter of one over zero stored high marks, looped into a permanent +/// badge. Both counters are written field-scoped: a user row also carries +/// admin-owned data (`role`) that a whole-row save would revert. +pub async fn grade( + db: &Database, + exam: &ExamId, + user: &UserId, + seq: i64, + mark: Mark, + graded_by: &UserId, + kind: &str, +) -> Result { + let result = ExamResult { + id: ExamResultId::composite(exam, user, seq), + exam: exam.clone(), + user: user.clone(), + seq, + mark, + graded_by: graded_by.clone(), + }; + // The "exists" and "not a draft" gates ride in the same transaction as + // the mark, the mirror of the re-draft gate on + // `crate::db::exam::update_if_unchanged`: between them, a mark and a + // re-draft racing each other can only ever leave one of the two applied, + // whichever process either ran in. The existence gate is not + // redundant with the draft one — a deleted exam reads NONE, which is + // *falsy*, so the draft gate alone waved a mark onto an exam that no + // longer existed. The caller's pre-flight check answers the same 409 + // one round trip earlier. It is also what makes a separate "did the + // exam survive my claim?" check moot: the claim now sits behind this + // gate instead of in front of it. + // + // `$before` is the sitting's *previous mark*, and it answers both + // questions off one read: `mark` is a mandatory column on a schemafull + // row, so `NONE` there means no row at all — the claim branch — while a + // number is what the student's counter takes its difference against. + // Read one statement before the counters inside the same transaction: + // read anywhere else it would be a guess about a row two graders may be + // writing at once, and the difference would be taken against a mark + // some other round had already replaced. + // + // Re-sent while the store answers "conflict, retry": the gates read a + // column an exam PATCH writes, and the counters are the ones a + // concurrent delete gives back, so this contends on three records by + // design. Sound to re-send because no statement in it can legitimately + // answer "already exists": the counter writes are `UPDATE`/`UPSERT` on + // ids no rival can collide *into*, and the mark's own UPSERT is on a + // deterministic id bijective with the `exam_result_exam_user_seq` + // unique tuple — `key::sitting(exam, user, seq)` *is* that tuple, so + // the index entry can only ever point at the row the id already names + // and the write resolves onto it. A lost round aborts having written + // nothing, counters included. + let _guard = cap::counter_lock().await; + let (mut written, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + IF (SELECT VALUE id FROM ONLY $exam) IS NONE {{ THROW 'exam_missing' }}; + IF (SELECT VALUE draft FROM ONLY $exam) {{ THROW 'exam_draft' }}; + LET $before = (SELECT VALUE mark FROM ONLY $id); + IF $before = NONE {{ + LET $kind = (UPSERT $kref SET {REF_COUNT_FIELD} = ({REF_COUNT_FIELD} ?? 0) + 1 + WHERE {REF_RETIRED_FIELD} != true RETURN VALUE id); + IF array::len($kind) = 0 {{ THROW '{RETIRED_MARK}' }}; + UPDATE $exam SET {EXAM_RESULT_COUNT_FIELD} = + ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1; + UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = + ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1; + }}; + LET $high = (IF $result.mark >= {HIGH_MARK_MIN} {{ 1 }} ELSE {{ 0 }}) + - (IF ($before ?? -1) >= {HIGH_MARK_MIN} {{ 1 }} ELSE {{ 0 }}); + IF $high != 0 {{ + UPDATE $student SET {HIGH_MARK_TOTAL_FIELD} = + math::max([({HIGH_MARK_TOTAL_FIELD} ?? 0) + $high, 0]) + }}; + LET $after = (UPSERT $id CONTENT $result RETURN AFTER); + RETURN $after[0]; + COMMIT TRANSACTION;" + ), + &[ + ("exam".into(), exam.record().into_value()), + ("id".into(), result.id.record().into_value()), + ("kref".into(), kind_ref(kind).into_value()), + ("grader".into(), graded_by.record().into_value()), + ("student".into(), user.record().into_value()), + ("result".into(), result.into_value()), + ], + &["exam_missing", "exam_draft", RETIRED_MARK], + ) + .await?; + // An aborted transaction errors every slot and only the THROW's own + // slot names the marker, so a refusal is read by marker while a lost + // round was already re-sent — never reported as a 500. + let thrown = |marker: &str| { + errors + .values() + .any(|error| error.to_string().contains(marker)) + }; + if thrown("exam_missing") { + return Err(AppError::NotFound); + } + if thrown("exam_draft") { + return Err(draft_error()); + } + if thrown(RETIRED_MARK) { + return Err(retired_kind_error(kind)); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is always the last statement before `COMMIT`, + // so its slot follows the statement count instead of a hand-kept + // number — see `db::exam::delete` for the bug the hand-kept one caused. + // Probed on crate 3.2.3: an `IF { … }` block occupies exactly one slot + // however many statements it holds, and one whether or not it is taken. + let slot = written.num_statements().saturating_sub(2); + written + .take::>(slot)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to record exam result".into())) +} + +/// The user's graded results restricted to one course's exams — the raw +/// rows behind the per-course block of the marks report. +pub async fn list_for_user_in_course( + db: &Database, + course: &CourseId, + user: &UserId, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM exam_result WHERE user = $usr + AND exam IN (SELECT VALUE id FROM exam WHERE course = $course) + ORDER BY id DESC", + ) + .bind(("usr", user.record())) + .bind(("course", course.record())) + .await? + .check()?; + Ok(latest_per_pair(result.take::>(0)?)) +} + +pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC") + .bind(("ex", exam.record())) + .await? + .check()?; + Ok(latest_per_pair(result.take::>(0)?)) +} + +/// Every sitting's mark for one (exam, user) pair, oldest first — the +/// per-attempt grade history behind the FE's attempt-by-attempt view. +pub async fn list_all_for_exam_user( + db: &Database, + exam: &ExamId, + user: &UserId, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM exam_result WHERE exam = $ex AND user = $usr + ORDER BY seq ASC", + ) + .bind(("ex", exam.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// A single user's result for an exam, if graded. +pub async fn read_for_user( + db: &Database, + exam: &ExamId, + user: &UserId, +) -> Result, AppError> { + find(db, exam, user).await +} + +/// Delete every sitting's mark for one (exam, user) pair. `kind` is the +/// exam's: the marks give their references back, so a kind nothing is +/// graded under any more can leave the settings again. +/// +/// The two badge counters come back the same way, and for a reason the +/// other counters do not need: [`grade`] credits them on the +/// branch that finds no row, and a deleted row *is* no row. Left standing, +/// ungrade-then-regrade credited a second time off one stored mark, and +/// looped it minted a badge from a single exam — permanently, since an +/// award is never revoked. Each is given back off the rows this statement +/// actually deleted: `marks_given_total` to each row's *own* grader (two +/// teachers can hold two sittings of the same pair), and `high_mark_total` +/// once per removed row that cleared [`HIGH_MARK_MIN`], read off the +/// `BEFORE` image rather than re-derived. That last one is why +/// [`grade`] has to move the student's counter on a *regrade* +/// too: this end reads the stored mark, so the other end must be decided by +/// the stored mark as well, or a mark walked across the line between the +/// two leaves a credit no delete can find to give back. +pub async fn remove( + db: &Database, + exam: &ExamId, + user: &UserId, + kind: &str, +) -> Result, AppError> { + // Both counters go back *inside* the delete's own transaction, driven + // off the rows this statement actually deleted. Counted outside it, a + // cascade (exam or course delete) taking the same rows in the gap would + // release them a second time, and on a kind another exam still grades + // under, one release too many reads as one mark too few — a kind + // wrongly free to leave the settings. + // + // Re-sent while the store answers "conflict, retry": the counters this + // touches are the ones a concurrent grade claims, so a lost round is + // routine and aborts having written nothing. `check()` cannot be used + // to read the outcome — it takes the *lowest*-slot error, and an + // aborted transaction's generic "not executed" sibling masked the real + // conflict, the exact defect deleted from `db::exam::delete`. No THROW + // of its own, and only `DELETE`/`UPDATE` inside, so nothing here can + // answer "already exists" and make a retry unsound. + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $gone = (DELETE exam_result WHERE exam = $ex AND user = $usr RETURN BEFORE); + IF array::len($gone) > 0 {{ + UPDATE type::record('kind_ref', $kind) SET {REF_COUNT_FIELD} = + math::max([({REF_COUNT_FIELD} ?? 0) - array::len($gone), 0]); + UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = + math::max([({EXAM_RESULT_COUNT_FIELD} ?? 0) - array::len($gone), 0]); + LET $high = array::len($gone[WHERE mark >= {HIGH_MARK_MIN}]); + IF $high > 0 {{ + UPDATE $usr SET {HIGH_MARK_TOTAL_FIELD} = + math::max([({HIGH_MARK_TOTAL_FIELD} ?? 0) - $high, 0]) + }}; + FOR $row IN $gone {{ + LET $grader = $row.graded_by; + UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = + math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0]) + }}; + }}; + RETURN $gone; + COMMIT TRANSACTION;" + ), + &[ + ("ex".into(), exam.record().into_value()), + ("usr".into(), user.record().into_value()), + ("kind".into(), kind.to_string().into_value()), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // `RETURN` is the last statement before `COMMIT`; its slot follows the + // statement count, as in `db::exam::delete`. + let slot = result.num_statements().saturating_sub(2); + let removed = result.take::>(slot)?; + Ok(removed.into_iter().next()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database::init_mem; + + #[tokio::test] + async fn retakes_keep_a_mark_per_sitting_with_the_latest_as_grade_of_record() { + let db = init_mem().await.unwrap(); + let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA"); + let user = UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"); + let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + // The exam has to be real: a mark is refused on one that isn't. + db.query( + "CREATE $ex SET creator = $t, course = course:c, title = 't', + description = '', kind = 'midterm'", + ) + .bind(("ex", exam.record())) + .bind(("t", teacher.record())) + .await + .unwrap() + .check() + .unwrap(); + + // Grade sitting #1, then a retake as sitting #2 — two rows, not one. + super::grade( + &db, + &exam, + &user, + 1, + Mark::try_new(40).unwrap(), + &teacher, + "midterm", + ) + .await + .unwrap(); + let second = super::grade( + &db, + &exam, + &user, + 2, + Mark::try_new(90).unwrap(), + &teacher, + "midterm", + ) + .await + .unwrap(); + assert_eq!(second.get_seq(), 2); + + // Grade-of-record is the latest sitting's mark. + let latest = read_for_user(&db, &exam, &user) + .await + .unwrap() + .expect("graded"); + assert_eq!(latest.get_mark().as_i64(), 90); + assert_eq!(latest.get_seq(), 2); + + // The roster yields exactly one row per pair — the latest. + let roster = list_for_exam(&db, &exam).await.unwrap(); + assert_eq!(roster.len(), 1); + assert_eq!(roster[0].get_mark().as_i64(), 90); + + // History keeps both sittings, oldest first. + let history = list_all_for_exam_user(&db, &exam, &user).await.unwrap(); + assert_eq!( + history + .iter() + .map(|r| r.get_mark().as_i64()) + .collect::>(), + vec![40, 90] + ); + + // Deleting the pair removes every sitting. + remove(&db, &exam, &user, "midterm").await.unwrap(); + assert!( + list_all_for_exam_user(&db, &exam, &user) + .await + .unwrap() + .is_empty() + ); + } + + /// A deleted exam reads NONE, and NONE is falsy — the draft gate alone let + /// a mark land on an exam that no longer existed. + #[tokio::test] + async fn a_mark_is_refused_on_an_exam_that_no_longer_exists() { + let db = init_mem().await.unwrap(); + let exam = ExamId::from_key("01TESTGONEEXAMAAAAAAAAAAAA"); + let user = UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"); + let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + + let refused = super::grade( + &db, + &exam, + &user, + 1, + Mark::try_new(40).unwrap(), + &teacher, + "midterm", + ) + .await; + assert!(matches!(refused, Err(AppError::NotFound)), "{refused:?}"); + assert!( + list_all_for_exam_user(&db, &exam, &user) + .await + .unwrap() + .is_empty() + ); + assert_eq!(counters(&db, "midterm").await, (0, 0)); + } + + /// The two counters, re-read out of the store — never off a return value, + /// which the in-memory engine forges wins on (see `cap::CLAIM_LOCK`). A + /// missing `kind_ref` row is a zero, which is exactly how the backfill + /// treats it (`tests/persistence.rs` — no zero pass, deliberately). + async fn counters(db: &Database, kind: &str) -> (i64, i64) { + let mut result = db + .query( + "SELECT VALUE count ?? 0 FROM kind_ref WHERE record::id(id) = $kind; + SELECT VALUE result_count ?? 0 FROM exam;", + ) + .bind(("kind", kind.to_string())) + .await + .unwrap() + .check() + .unwrap(); + let kinds: Vec = result.take(0).unwrap(); + let exams: Vec = result.take(1).unwrap(); + ( + kinds.into_iter().next().unwrap_or(0), + exams.into_iter().next().unwrap_or(0), + ) + } + + async fn an_exam(db: &Database, exam: &ExamId, kind: &str) { + db.query( + "CREATE $ex SET creator = user:t, course = course:c, title = 't', + description = '', kind = $kind", + ) + .bind(("ex", exam.record())) + .bind(("kind", kind.to_string())) + .await + .unwrap() + .check() + .unwrap(); + } + + const STUDENT: &str = "01TESTSTUDENTAAAAAAAAAAAAA"; + const TEACHER: &str = "01TESTTEACHERAAAAAAAAAAAAA"; + + /// The tests' handle on [`super::grade`] with the grader and target + /// pinned to the two test people. + async fn grade( + db: &Database, + exam: &ExamId, + seq: i64, + mark: i64, + kind: &str, + ) -> Result { + super::grade( + db, + exam, + &UserId::from_key(STUDENT), + seq, + Mark::try_new(mark).unwrap(), + &UserId::from_key(TEACHER), + kind, + ) + .await + } + + /// Both counters ride the mark's own transaction: a new mark claims each + /// exactly once, and a *regrade* of the same sitting claims neither — one + /// mark, one reference. Claimed-then-released around the write, a regrade + /// drifted them upward and froze the kind out of the settings for good. + #[tokio::test] + async fn a_new_mark_moves_both_counters_and_a_regrade_moves_neither() { + let db = init_mem().await.unwrap(); + let exam = ExamId::from_key("01TESTEXAMCOUNTAAAAAAAAAAA"); + an_exam(&db, &exam, "midterm").await; + + grade(&db, &exam, 1, 40, "midterm").await.unwrap(); + assert_eq!(counters(&db, "midterm").await, (1, 1)); + + // Same sitting, new mark: an overwrite, so neither counter moves. + let regraded = grade(&db, &exam, 1, 90, "midterm").await.unwrap(); + assert_eq!(regraded.get_mark().as_i64(), 90); + assert_eq!(counters(&db, "midterm").await, (1, 1)); + + // A retake is a second row, so it does claim. + grade(&db, &exam, 2, 70, "midterm").await.unwrap(); + assert_eq!(counters(&db, "midterm").await, (2, 2)); + } + + /// The two badge counters, re-read out of the store: the grader's marks + /// given and the student's high marks. + async fn badge_counters(db: &Database) -> (i64, i64) { + let mut result = db + .query(format!( + "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $grader; + SELECT VALUE ({HIGH_MARK_TOTAL_FIELD} ?? 0) FROM $student;" + )) + .bind(("grader", UserId::from_key(TEACHER).record())) + .bind(("student", UserId::from_key(STUDENT).record())) + .await + .unwrap() + .check() + .unwrap(); + let given: Vec = result.take(0).unwrap(); + let high: Vec = result.take(1).unwrap(); + ( + given.into_iter().next().unwrap_or(0), + high.into_iter().next().unwrap_or(0), + ) + } + + /// The rows a counter needs to land on — `UPDATE` writes nothing to a user + /// that does not exist, so the badge tests must make both real. + async fn the_two_people(db: &Database) { + for key in [TEACHER, STUDENT] { + db.query("CREATE $usr SET username = $name, password_hash = 'x'") + .bind(("usr", UserId::from_key(key).record())) + .bind(("name", key.to_string())) + .await + .unwrap() + .check() + .unwrap(); + } + } + + /// A first grade credits the grader once and the student only when the mark + /// clears the line; a regrade of the same sitting credits neither again, + /// while a retake — a distinct seq, so a distinct row — counts on its own. + #[tokio::test] + async fn a_grade_credits_the_grader_once_and_a_high_mark_the_student() { + let db = init_mem().await.unwrap(); + let exam = ExamId::from_key("01TESTEXAMBADGEAAAAAAAAAAA"); + an_exam(&db, &exam, "midterm").await; + the_two_people(&db).await; + + grade(&db, &exam, 1, 90, "midterm").await.unwrap(); + assert_eq!(badge_counters(&db).await, (1, 1), "at the line earns it"); + + // Same sitting graded again: neither counter may move, however high. + grade(&db, &exam, 1, 100, "midterm").await.unwrap(); + assert_eq!(badge_counters(&db).await, (1, 1), "a regrade moves nothing"); + + // A retake below the line: the grader is credited, the student is not. + grade(&db, &exam, 2, 89, "midterm").await.unwrap(); + assert_eq!(badge_counters(&db).await, (2, 1), "89 is under the line"); + + // …and a high-scoring retake counts as its own sitting. + grade(&db, &exam, 3, 95, "midterm").await.unwrap(); + assert_eq!(badge_counters(&db).await, (3, 2)); + } + + /// Ungrading gives both badge counters back, so grade → ungrade → regrade + /// nets to one credit however often it is run. Crediting the grade without + /// refunding the delete let that loop mint a badge off a single exam — and + /// an award, once earned, is never taken back. + #[tokio::test] + async fn ungrading_gives_the_badge_counters_back() { + let db = init_mem().await.unwrap(); + let exam = ExamId::from_key("01TESTEXAMUNGRADEAAAAAAAAA"); + an_exam(&db, &exam, "midterm").await; + the_two_people(&db).await; + let student = UserId::from_key(STUDENT); + + for _ in 0..3 { + grade(&db, &exam, 1, 95, "midterm").await.unwrap(); + assert_eq!(badge_counters(&db).await, (1, 1)); + remove(&db, &exam, &student, "midterm") + .await + .unwrap() + .expect("the mark was there"); + assert_eq!(badge_counters(&db).await, (0, 0), "the loop kept a credit"); + // The kind's reference and the exam's count come back as before. + assert_eq!(counters(&db, "midterm").await, (0, 0)); + } + + // Every removed sitting is refunded, and only the ones that took: the + // grader gets both back, the student only the mark that cleared the line. + grade(&db, &exam, 1, 40, "midterm").await.unwrap(); + grade(&db, &exam, 2, 95, "midterm").await.unwrap(); + assert_eq!(badge_counters(&db).await, (2, 1)); + remove(&db, &exam, &student, "midterm") + .await + .unwrap() + .expect("both sittings were there"); + assert_eq!(badge_counters(&db).await, (0, 0)); + + // Nothing to remove is nothing to give back — the floor holds. + assert!( + remove(&db, &exam, &student, "midterm") + .await + .unwrap() + .is_none() + ); + assert_eq!(badge_counters(&db).await, (0, 0)); + } + + /// A regrade walks the *same* sitting across [`HIGH_MARK_MIN`], and the + /// student's counter has to walk with it — the delete refunds off the mark + /// it finds stored, so a credit decided by a mark that is no longer there + /// is a credit nothing can give back. Left on the first-write branch alone, + /// grade-high → regrade-low → delete kept a phantom high mark every round + /// and looped it into a permanent badge. + #[tokio::test] + async fn a_regrade_across_the_line_moves_the_student_counter_with_it() { + let db = init_mem().await.unwrap(); + let exam = ExamId::from_key("01TESTEXAMREGRADEAAAAAAAAA"); + an_exam(&db, &exam, "midterm").await; + the_two_people(&db).await; + let student = UserId::from_key(STUDENT); + + // Up across the line: no row is added, but a high mark now exists. + grade(&db, &exam, 1, 40, "midterm").await.unwrap(); + assert_eq!(badge_counters(&db).await, (1, 0), "40 is under the line"); + grade(&db, &exam, 1, 95, "midterm").await.unwrap(); + assert_eq!(badge_counters(&db).await, (1, 1), "the regrade crossed up"); + remove(&db, &exam, &student, "midterm") + .await + .unwrap() + .expect("the mark was there"); + assert_eq!(badge_counters(&db).await, (0, 0)); + + // Down across it: the credit goes back the moment the mark does, so + // the delete has nothing left to refund and the counter still lands + // on zero rather than under it. + grade(&db, &exam, 1, 95, "midterm").await.unwrap(); + assert_eq!(badge_counters(&db).await, (1, 1)); + grade(&db, &exam, 1, 40, "midterm").await.unwrap(); + assert_eq!( + badge_counters(&db).await, + (1, 0), + "the regrade crossed down" + ); + remove(&db, &exam, &student, "midterm") + .await + .unwrap() + .expect("the mark was there"); + assert_eq!(badge_counters(&db).await, (0, 0)); + + // Both sides of a regrade above the line: nothing crosses, nothing moves. + grade(&db, &exam, 1, 90, "midterm").await.unwrap(); + grade(&db, &exam, 1, 100, "midterm").await.unwrap(); + assert_eq!(badge_counters(&db).await, (1, 1), "90 → 100 stays one"); + + // The loop that minted the badge: three rounds of high → low → delete + // must leave the counter exactly where it started. + for _ in 0..3 { + grade(&db, &exam, 1, 95, "midterm").await.unwrap(); + grade(&db, &exam, 1, 40, "midterm").await.unwrap(); + remove(&db, &exam, &student, "midterm") + .await + .unwrap() + .expect("the mark was there"); + } + assert_eq!( + badge_counters(&db).await, + (0, 0), + "the loop kept a high mark with no high mark stored" + ); + } + + /// The other half of the same asymmetry: a refund read off a stored mark + /// that was never credited eats a credit earned somewhere else. One exam + /// holds a genuine high mark while a second is graded low, regraded high + /// and deleted — the first exam's credit must still be standing. + #[tokio::test] + async fn one_exams_regrade_never_eats_another_exams_high_mark() { + let db = init_mem().await.unwrap(); + let first = ExamId::from_key("01TESTEXAMSTEALONEAAAAAAAA"); + let second = ExamId::from_key("01TESTEXAMSTEALTWOAAAAAAAA"); + an_exam(&db, &first, "midterm").await; + an_exam(&db, &second, "midterm").await; + the_two_people(&db).await; + let student = UserId::from_key(STUDENT); + + grade(&db, &first, 1, 95, "midterm").await.unwrap(); + assert_eq!( + badge_counters(&db).await, + (1, 1), + "earned on the first exam" + ); + + grade(&db, &second, 1, 40, "midterm").await.unwrap(); + grade(&db, &second, 1, 95, "midterm").await.unwrap(); + assert_eq!(badge_counters(&db).await, (2, 2)); + remove(&db, &second, &student, "midterm") + .await + .unwrap() + .expect("the mark was there"); + assert_eq!( + badge_counters(&db).await, + (1, 1), + "the first exam's high mark was eaten" + ); + } + + /// A refused mark leaves the badge counters where the other two are left. + #[tokio::test] + async fn a_refused_mark_credits_nobody() { + let db = init_mem().await.unwrap(); + let exam = ExamId::from_key("01TESTEXAMBADGEDRAFTAAAAAA"); + an_exam(&db, &exam, "midterm").await; + the_two_people(&db).await; + db.query("UPDATE $ex SET draft = true") + .bind(("ex", exam.record())) + .await + .unwrap() + .check() + .unwrap(); + + assert!(grade(&db, &exam, 1, 100, "midterm").await.is_err()); + assert_eq!(badge_counters(&db).await, (0, 0)); + } + + /// A retired kind refuses the claim from inside the transaction, which + /// takes the mark and the exam's counter down with it — the settings guard + /// enforcing the same invariant from the other side. + #[tokio::test] + async fn a_retired_kind_refuses_the_mark_and_leaves_both_counters_alone() { + let db = init_mem().await.unwrap(); + let exam = ExamId::from_key("01TESTEXAMRETIREDAAAAAAAAA"); + an_exam(&db, &exam, "midterm").await; + assert!(cap::retire(&kind_ref("midterm"), &db).await.unwrap()); + + let refused = grade(&db, &exam, 1, 40, "midterm").await; + assert!( + matches!(&refused, Err(AppError::ConflictOwned(message)) + if message.contains("has been removed from the school's settings")), + "{refused:?}" + ); + assert!( + list_for_exam(&db, &exam).await.unwrap().is_empty(), + "the mark must not have landed" + ); + assert_eq!(counters(&db, "midterm").await, (0, 0)); + } + + /// A draft exam refuses the mark, and the counters stay put — the gate + /// runs before the claim now, so there is nothing to give back. + #[tokio::test] + async fn a_draft_exam_refuses_the_mark_and_leaves_both_counters_alone() { + let db = init_mem().await.unwrap(); + let exam = ExamId::from_key("01TESTEXAMDRAFTAAAAAAAAAAA"); + an_exam(&db, &exam, "midterm").await; + db.query("UPDATE $ex SET draft = true") + .bind(("ex", exam.record())) + .await + .unwrap() + .check() + .unwrap(); + + let refused = grade(&db, &exam, 1, 40, "midterm").await; + assert!(matches!(refused, Err(AppError::Conflict(_))), "{refused:?}"); + assert!(list_for_exam(&db, &exam).await.unwrap().is_empty()); + assert_eq!(counters(&db, "midterm").await, (0, 0)); + } +} diff --git a/src/db/mod.rs b/src/db/mod.rs index e164f1b..a01fcdf 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -1,5 +1,6 @@ //! The only layer that executes queries. +pub mod answer_image; pub mod appointment; pub mod appointment_slot; pub mod cap; @@ -8,13 +9,16 @@ pub mod course; pub mod course_session; pub mod enrollment; pub mod exam; +pub mod exam_answer; pub mod exam_attempt; pub mod exam_question; +pub mod exam_result; pub mod field_update; pub mod meal_booking; pub mod note; pub mod page; pub mod payment_ledger; +pub mod question_image; pub mod session; pub mod settings; pub mod user; diff --git a/src/db/question_image.rs b/src/db/question_image.rs new file mode 100644 index 0000000..f48f094 --- /dev/null +++ b/src/db/question_image.rs @@ -0,0 +1,332 @@ +//! The `question_image` table: the slot-keyed upsert (and delete) behind the +//! question-freeze gate, the listing reads, and the choice-cleanup sweep a +//! question PATCH drives. The row's pure half — ids and the fresh-blob-name +//! constructor — lives in [`crate::domain::question_image`]; the blob bytes +//! stay the web layer's. + +use surrealdb::types::SurrealValue; + +use crate::database::Database; +use crate::domain::course::CourseId; +use crate::domain::exam::ExamId; +use crate::domain::exam_question::{ChoiceId, ExamQuestionId}; +use crate::domain::question_image::{QuestionImage, QuestionImageId}; +use crate::error::AppError; + +/// What one [`upsert`] transaction returns: the row it stored +/// and the blob name it replaced. Both are arrays because SurrealDB drops an object +/// key valued `NONE` on the way out, while an empty array survives — "nothing +/// was replaced" has to be readable, not missing. +#[derive(SurrealValue)] +struct UpsertOutcome { + stored: Vec, + replaced: Vec, +} + +/// Create or replace the slot's image row — the deterministic id makes +/// this the whole "one image per slot" story — handing back what it stored +/// plus the blob name it replaced, for the caller to take off disk. Refused +/// once the exam has an attempt: pictures are part of the question, so they +/// freeze with it, and the gate is in this transaction rather than in a lock +/// the caller held. +/// +/// The replaced name is read *here*, not by the caller before it: two +/// uploads to one slot both write this row, so they contend and the loser +/// re-reads the winner's blob name, where two pre-reads both saw the *old* +/// blob and left the loser's fresh one orphaned on disk. +pub async fn upsert( + db: &Database, + image: QuestionImage, +) -> Result<(QuestionImage, Option), AppError> { + // whole-row-save-ok: image is built in place, never read back, and the slot id is deterministic + let (exam, id) = (image.exam.clone(), image.id.record()); + let mut result = crate::db::exam_attempt::write_unfrozen( + db, + &exam, + "LET $replaced = (SELECT VALUE file FROM $id); + LET $stored = (UPSERT $id CONTENT $image); + RETURN { stored: $stored, replaced: $replaced };", + vec![ + ("id".into(), id.into_value()), + ("image".into(), image.into_value()), + ], + ) + .await?; + // The trailing `RETURN` is the last statement before `COMMIT`, so its + // slot follows the statement count rather than a hand-kept number; + // `num_statements` counts BEGIN and COMMIT. + let slot = result.num_statements().saturating_sub(2); + let failed = || AppError::Internal("failed to store question image".into()); + let outcome = result + .take::>(slot)? + .into_iter() + .next() + .ok_or_else(failed)?; + let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; + Ok((stored, outcome.replaced.into_iter().next())) +} + +pub async fn read_slot( + db: &Database, + question: &ExamQuestionId, + slot: Option<&ChoiceId>, +) -> Result, AppError> { + Ok(db + .select(QuestionImageId::for_slot(question, slot).record()) + .await?) +} + +/// Every image of the exam's questions — one query for the list views. +pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM question_image WHERE exam = $ex") + .bind(("ex", exam.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +pub async fn list_for_question( + db: &Database, + question: &ExamQuestionId, +) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM question_image WHERE question = $q") + .bind(("q", question.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Drop the option pictures whose choice is gone — every choice image of +/// the question whose `slot` is *not* in `keep` (the question's own +/// illustration always stays), returning the removed rows so the caller can +/// take their blobs off disk. +/// +/// This is what makes an edit non-destructive: a PATCH that reorders, +/// renames, or drops options passes the surviving choice ids as `keep`, so +/// only the pictures of genuinely removed options go. `keep = &[]` (a text +/// question, or an all-new choice list) still clears the lot. +pub async fn delete_choices_not_in( + db: &Database, + question: &ExamQuestionId, + keep: &[ChoiceId], +) -> Result, AppError> { + let keep: Vec = keep.iter().map(|id| id.as_str().to_string()).collect(); + let mut result = db + .query( + "DELETE question_image \ + WHERE question = $q AND slot != NONE AND slot NOT IN $keep RETURN BEFORE", + ) + .bind(("q", question.record())) + .bind(("keep", keep)) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// The blob names behind every image of every exam of `course` — collected +/// *before* the course-delete cascade wipes the rows. +pub async fn file_keys_for_course( + db: &Database, + course: &CourseId, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT VALUE file FROM question_image \ + WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)", + ) + .bind(("course", course.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Refused once the exam has an attempt, in the same transaction — same +/// gate, same reason as [`upsert`]. +pub async fn delete(db: &Database, image: QuestionImage) -> Result { + let mut result = crate::db::exam_attempt::write_unfrozen( + db, + &image.exam, + "DELETE $id RETURN BEFORE;", + vec![("id".into(), image.id.record().into_value())], + ) + .await?; + result + .take::>(crate::db::exam_attempt::FROZEN_SLOT)? + .into_iter() + .next() + .ok_or(AppError::NotFound) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec}; + use crate::domain::note_file::FileContentType; + + /// A real exam row: an image write moves its exam's counter (that is what + /// keeps a picture from outliving its exam), so a minted id nothing wrote + /// is a 404. + async fn exam_row(db: &Database) -> ExamId { + crate::db::exam::published_exam(db).await.get_id().clone() + } + + fn png() -> FileContentType { + FileContentType::try_new("image/png").unwrap() + } + + /// Three minted choice ids to slot pictures against. + fn choice_ids() -> Vec { + QuestionSpec::try_new( + QuestionKind::try_new("choice").unwrap(), + Some( + ["a", "b", "c"] + .iter() + .map(|l| ChoiceInput { + id: Some((*l).into()), + text: (*l).into(), + }) + .collect(), + ), + Some("a".into()), + &[], + ) + .unwrap() + .into_parts() + .1 + .unwrap() + .iter() + .map(|c| c.get_id().clone()) + .collect() + } + + #[tokio::test] + async fn upsert_replaces_per_slot() { + let db = crate::database::init_mem().await.unwrap(); + let exam = exam_row(&db).await; + let question = ExamQuestionId::generate(); + let ids = choice_ids(); + + let (first, retired) = upsert(&db, QuestionImage::new(&exam, &question, None, png(), 3)) + .await + .unwrap(); + assert_eq!(retired, None, "a first upload retires no blob"); + let (second, retired) = upsert(&db, QuestionImage::new(&exam, &question, None, png(), 5)) + .await + .unwrap(); + // Same slot, same row — the replace swapped the blob pointer, and the + // write itself names the blob the caller must unlink. + assert_ne!(first.get_file(), second.get_file()); + assert_eq!(retired.as_deref(), Some(first.get_file())); + let rows = list_for_question(&db, &question).await.unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].get_size(), 5); + + // A choice slot is its own row, keyed by the option's id. + upsert( + &db, + QuestionImage::new(&exam, &question, Some(&ids[0]), png(), 7), + ) + .await + .unwrap(); + assert_eq!(list_for_question(&db, &question).await.unwrap().len(), 2); + let choice = read_slot(&db, &question, Some(&ids[0])) + .await + .unwrap() + .unwrap(); + assert_eq!(choice.get_slot(), Some(&ids[0])); + assert!( + read_slot(&db, &question, Some(&ids[1])) + .await + .unwrap() + .is_none() + ); + } + + /// The behaviour the whole remodel exists for: an edit that keeps some + /// options keeps exactly their pictures, and drops only the removed one's. + #[tokio::test] + async fn only_the_dropped_options_lose_their_pictures() { + let db = crate::database::init_mem().await.unwrap(); + let exam = exam_row(&db).await; + let question = ExamQuestionId::generate(); + let ids = choice_ids(); + upsert(&db, QuestionImage::new(&exam, &question, None, png(), 1)) + .await + .unwrap(); + for id in &ids { + upsert( + &db, + QuestionImage::new(&exam, &question, Some(id), png(), 1), + ) + .await + .unwrap(); + } + + // Keep the first and last option (reordered — order is irrelevant now). + let keep = vec![ids[2].clone(), ids[0].clone()]; + let dropped = delete_choices_not_in(&db, &question, &keep).await.unwrap(); + assert_eq!(dropped.len(), 1); + assert_eq!(dropped[0].get_slot(), Some(&ids[1])); + + let left = list_for_question(&db, &question).await.unwrap(); + // The question illustration plus the two surviving option pictures. + assert_eq!(left.len(), 3); + assert!( + read_slot(&db, &question, Some(&ids[0])) + .await + .unwrap() + .is_some() + ); + assert!( + read_slot(&db, &question, Some(&ids[2])) + .await + .unwrap() + .is_some() + ); + assert!(read_slot(&db, &question, None).await.unwrap().is_some()); + } + + #[tokio::test] + async fn an_empty_keep_set_clears_every_option_picture_but_not_the_illustration() { + let db = crate::database::init_mem().await.unwrap(); + let exam = exam_row(&db).await; + let question = ExamQuestionId::generate(); + let ids = choice_ids(); + upsert(&db, QuestionImage::new(&exam, &question, None, png(), 1)) + .await + .unwrap(); + for id in &ids[..2] { + upsert( + &db, + QuestionImage::new(&exam, &question, Some(id), png(), 1), + ) + .await + .unwrap(); + } + + let dropped = delete_choices_not_in(&db, &question, &[]).await.unwrap(); + assert_eq!(dropped.len(), 2); + assert!(dropped.iter().all(|image| image.get_slot().is_some())); + + let left = list_for_question(&db, &question).await.unwrap(); + assert_eq!(left.len(), 1); + assert_eq!(left[0].get_slot(), None); + } + + #[tokio::test] + async fn exam_listing_scopes_by_exam() { + let db = crate::database::init_mem().await.unwrap(); + let exam_a = exam_row(&db).await; + let exam_b = exam_row(&db).await; + upsert( + &db, + QuestionImage::new(&exam_a, &ExamQuestionId::generate(), None, png(), 1), + ) + .await + .unwrap(); + assert_eq!(list_for_exam(&db, &exam_a).await.unwrap().len(), 1); + assert!(list_for_exam(&db, &exam_b).await.unwrap().is_empty()); + } +} diff --git a/src/domain/answer_image.rs b/src/domain/answer_image.rs index 8656958..9522340 100644 --- a/src/domain/answer_image.rs +++ b/src/domain/answer_image.rs @@ -8,22 +8,20 @@ //! shape as [`crate::domain::exam_attempt::ExamAttemptId::composite`] — so "one //! drawing per student per question per sitting" holds by construction and a //! replace within a sitting is a plain UPSERT, while a retake (`seq + 1`) -//! accumulates its own rows instead of overwriting. The web layer owns the -//! blob I/O and its ordering (new blob before row, row before old blob); this -//! module owns the rows. +//! accumulates its own rows instead of overwriting. The queries and +//! transactions over these rows live in [`crate::db::answer_image`]; the web +//! layer owns the blob I/O and its ordering (new blob before row, row before +//! old blob). use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; -use crate::constant::{ANSWER_IMAGE_TABLE, EXAM_RESULT_COUNT_FIELD}; -use crate::database::{Database, transaction_with_retry}; -use crate::domain::course::CourseId; +use crate::constant::ANSWER_IMAGE_TABLE; use crate::domain::exam::ExamId; use crate::domain::exam_question::ExamQuestionId; use crate::domain::key; use crate::domain::note_file::FileContentType; use crate::domain::user::UserId; -use crate::error::AppError; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct AnswerImageId(RecordId); @@ -55,33 +53,24 @@ impl AnswerImageId { /// through `exam_question`. #[derive(Debug, Clone, SurrealValue)] pub struct AnswerImage { - id: AnswerImageId, - exam: ExamId, - question: ExamQuestionId, - user: UserId, + pub(crate) id: AnswerImageId, + pub(crate) exam: ExamId, + pub(crate) question: ExamQuestionId, + pub(crate) user: UserId, /// Which sitting this drawing belongs to — 1 for the first attempt, /// counting up, so retakes accumulate instead of overwriting. - seq: i64, + pub(crate) seq: i64, /// The blob's on-disk name — a fresh ULID every upload. - file: String, - content_type: FileContentType, - size: i64, -} - -/// What one [`AnswerImage::upsert`] transaction returns: the row it stored and -/// the blob name it replaced. Both are arrays because SurrealDB drops an object -/// key valued `NONE` on the way out, while an empty array survives — "nothing -/// was replaced" has to be readable, not missing. -#[derive(SurrealValue)] -struct UpsertOutcome { - stored: Vec, - replaced: Vec, + pub(crate) file: String, + pub(crate) content_type: FileContentType, + pub(crate) size: i64, } impl AnswerImage { /// Assemble a row (fresh blob name generated here) without persisting it. /// The caller writes the blob under [`Self::get_file`] first, then calls - /// [`Self::upsert`] — so a stored row always points at a real blob. + /// [`crate::db::answer_image::upsert`] — so a stored row always points at + /// a real blob. pub fn new( exam: &ExamId, question: &ExamQuestionId, @@ -122,318 +111,4 @@ impl AnswerImage { pub fn get_size(&self) -> i64 { self.size } - - /// Create or replace the student's drawing for the question — the - /// deterministic id makes this the whole "one drawing per student per - /// question" story — handing back what it stored plus the blob name it - /// replaced, for the caller to take off disk. - /// - /// The replaced name is read *here*, inside this transaction, not by the - /// caller in front of it: two uploads to one (question, user, seq) both - /// write this row, so they contend and the loser re-reads the winner's blob - /// name, where two pre-reads both saw the *old* blob and left the loser's - /// fresh one on disk with nothing pointing at it. Same shape as - /// [`crate::domain::question_image::QuestionImage::upsert`]. - /// - /// `NotFound` = the exam is gone, and the drawing was *not* written. The - /// write moves the exam's mark counter and puts it straight back, in this - /// one transaction, so the exam's existence is something this write - /// *writes* rather than something a gate read a moment earlier: a bare - /// upsert landing after [`delete`](crate::db::exam::delete) - /// removed the exam but before it committed was swept by nothing — its - /// `DELETE answer_image WHERE exam = $ex` ran on a snapshot predating this - /// row — and both sides reported success. That stranded the blob as well as - /// the row: `delete_exam` collects the names to unlink *before* it calls - /// the delete, so bytes written after that snapshot stay on disk forever. - /// This is the shape [`crate::domain::exam_answer::ExamAnswer::save`] takes - /// for the text half of the same answer sheet, and for the same reason. - /// - /// The restore is by captured value, `NONE` included, so the row is - /// byte-identical afterwards and a teacher's PATCH — which pins that - /// counter — is not refused because a student drew. Writing the same value - /// back would buy nothing: an `UPDATE` that leaves the document unchanged - /// is elided and never reaches the store's write set. - /// - /// Admissible for [`transaction_with_retry`]: the `UPDATE`s, `SELECT`, - /// `IF`/`THROW` and `RETURN` can never answer "already exists", and the - /// `UPSERT`'s id is bijective with the (question, user, seq) triple this - /// table keys — a lost round wrote nothing, and re-sending resolves onto - /// the same row rather than colliding with it. - pub async fn upsert(self, db: &Database) -> Result<(AnswerImage, Option), AppError> { - // whole-row-save-ok: self is built in place from the request, never read back, and the (question, user, seq) id is deterministic — replacing the row *is* the operation - let (exam, id) = (self.exam.record(), self.id.record()); - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $was = (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $ex); - LET $touched = (UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = \ - ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); - IF array::len($touched) = 0 {{ THROW 'no_exam' }}; - UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = $was; - LET $replaced = (SELECT VALUE file FROM $id); - LET $row = (UPSERT $id CONTENT $image RETURN AFTER); - RETURN {{ stored: $row, replaced: $replaced }}; - COMMIT TRANSACTION;" - ), - &[ - ("ex".into(), exam.into_value()), - ("id".into(), id.into_value()), - ("image".into(), self.into_value()), - ], - &["no_exam"], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_exam")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is the last statement before `COMMIT`, so its - // slot follows the statement count rather than a hand-kept number; - // `num_statements` counts BEGIN and COMMIT. - let slot = result.num_statements().saturating_sub(2); - let failed = || AppError::Internal("failed to store answer image".into()); - let outcome = result - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(failed)?; - let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; - Ok((stored, outcome.replaced.into_iter().next())) - } - - /// The student's drawing for one question in one sitting, if any. - pub async fn read( - question: &ExamQuestionId, - user: &UserId, - seq: i64, - db: &Database, - ) -> Result, AppError> { - Ok(db - .select(AnswerImageId::composite(question, user, seq).record()) - .await?) - } - - /// Every answer drawing of the exam — one query for the exam-delete cascade. - pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM answer_image WHERE exam = $ex") - .bind(("ex", exam.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// One student's answer drawings for a single sitting — the parallel to - /// [`crate::domain::exam_answer::ExamAnswer::list_for_exam_user`], feeding - /// the sitting/grading answer-image maps for that attempt's `seq`. - pub async fn list_for_exam_user( - exam: &ExamId, - user: &UserId, - seq: i64, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM answer_image WHERE exam = $ex AND user = $usr AND seq = $seq") - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .bind(("seq", seq)) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// The distinct sittings (`seq`, ascending) this student has any answer - /// drawing for at this exam — the history index behind a per-attempt view. - pub async fn list_seqs_for_user( - exam: &ExamId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT VALUE seq FROM answer_image \ - WHERE exam = $ex AND user = $usr ORDER BY seq", - ) - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .await? - .check()?; - let mut seqs = result.take::>(0)?; - seqs.dedup(); - Ok(seqs) - } - - /// The blob names behind every answer drawing of every exam of `course` — - /// collected *before* the course-delete cascade wipes the rows. - pub async fn file_keys_for_course( - course: &CourseId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT VALUE file FROM answer_image \ - WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)", - ) - .bind(("course", course.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - pub async fn delete(self, db: &Database) -> Result { - let deleted: Option = db.delete(self.id.record()).await?; - deleted.ok_or(AppError::NotFound) - } - - /// Drop one student's answer drawings across an exam — a retake starts from - /// a blank sheet. Rows only; the caller GCs the blobs. The retake path itself - /// wipes rows inside `ExamAttempt::wipe_and_create`'s transaction; this is - /// the standalone mirror of [`crate::domain::exam_answer::ExamAnswer::delete_for_exam_user`]. - pub async fn delete_for_exam_user( - exam: &ExamId, - user: &UserId, - db: &Database, - ) -> Result<(), AppError> { - db.query("DELETE answer_image WHERE exam = $ex AND user = $usr") - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn png() -> FileContentType { - FileContentType::try_new("image/png").unwrap() - } - - /// A real exam row: a drawing's write moves its exam's counter (that is - /// what keeps it from outliving the exam), so a minted id nothing wrote is - /// a 404. - async fn exam_row(db: &Database) -> ExamId { - crate::db::exam::published_exam(db).await.get_id().clone() - } - - fn student() -> UserId { - UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA") - } - - #[tokio::test] - async fn upsert_replaces_within_a_sitting_but_not_across_them() { - let db = crate::database::init_mem().await.unwrap(); - let exam = exam_row(&db).await; - let question = ExamQuestionId::generate(); - let user = student(); - - let (first, retired) = AnswerImage::new(&exam, &question, &user, 1, png(), 3) - .upsert(&db) - .await - .unwrap(); - assert_eq!(retired, None, "a first upload retires no blob"); - let (second, retired) = AnswerImage::new(&exam, &question, &user, 1, png(), 5) - .upsert(&db) - .await - .unwrap(); - // Same (question, user, seq), same row — the replace swapped the blob, - // and the write itself names the blob the caller must unlink. - assert_ne!(first.get_file(), second.get_file()); - assert_eq!(retired.as_deref(), Some(first.get_file())); - let rows = AnswerImage::list_for_exam_user(&exam, &user, 1, &db) - .await - .unwrap(); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].get_size(), 5); - - // A retake (seq 2) accumulates: it is its own row, not an overwrite. - AnswerImage::new(&exam, &question, &user, 2, png(), 9) - .upsert(&db) - .await - .unwrap(); - assert_eq!( - AnswerImage::list_for_exam_user(&exam, &user, 1, &db) - .await - .unwrap() - .len(), - 1, - "the seq-2 image must not overwrite seq-1" - ); - assert_eq!( - AnswerImage::list_for_exam_user(&exam, &user, 2, &db) - .await - .unwrap()[0] - .get_size(), - 9 - ); - assert_eq!( - AnswerImage::list_seqs_for_user(&exam, &user, &db) - .await - .unwrap(), - vec![1, 2] - ); - - // Another student's drawing for the same question/sitting is its own row. - let other = UserId::from_key("01TESTSTUDENTBBBBBBBBBBBBB"); - AnswerImage::new(&exam, &question, &other, 1, png(), 7) - .upsert(&db) - .await - .unwrap(); - assert_eq!( - AnswerImage::list_for_exam(&exam, &db).await.unwrap().len(), - 3 - ); - assert!( - AnswerImage::read(&question, &user, 2, &db) - .await - .unwrap() - .is_some() - ); - } - - #[tokio::test] - async fn listing_scopes_by_exam_and_user() { - let db = crate::database::init_mem().await.unwrap(); - let exam_a = exam_row(&db).await; - let exam_b = exam_row(&db).await; - let user = student(); - AnswerImage::new(&exam_a, &ExamQuestionId::generate(), &user, 1, png(), 1) - .upsert(&db) - .await - .unwrap(); - assert_eq!( - AnswerImage::list_for_exam_user(&exam_a, &user, 1, &db) - .await - .unwrap() - .len(), - 1 - ); - assert!( - AnswerImage::list_for_exam(&exam_b, &db) - .await - .unwrap() - .is_empty() - ); - - // delete_for_exam_user clears the student's sheet across all sittings. - AnswerImage::delete_for_exam_user(&exam_a, &user, &db) - .await - .unwrap(); - assert!( - AnswerImage::list_for_exam_user(&exam_a, &user, 1, &db) - .await - .unwrap() - .is_empty() - ); - } } diff --git a/src/domain/attendance.rs b/src/domain/attendance.rs index 9950f5a..55bbdd2 100644 --- a/src/domain/attendance.rs +++ b/src/domain/attendance.rs @@ -2,8 +2,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ATTENDANCE_TABLE, REGISTRATION_COUNT_FIELD}; use crate::database::{Database, transaction_with_retry}; -use crate::domain::event::EventId; use crate::db::page::PagedList; +use crate::domain::event::EventId; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -101,7 +101,7 @@ impl Attendance { /// Reading the event here would not have closed it either: SurrealDB 3.2.3 /// conflict-checks write sets, not read sets, so the proof has to *move* a /// value on the event row. It is the bump-and-restore of - /// [`crate::domain::exam_answer::ExamAnswer::save`], on the counter the + /// [`crate::db::exam_answer::save`], on the counter the /// event already carries: matching nothing is the existence gate, writing /// the key the delete removes is the collision, and the restore is by /// captured value (`NONE` included) so no seat is spent or freed. diff --git a/src/domain/chatbot_thread.rs b/src/domain/chatbot_thread.rs index 7cbc018..66974f8 100644 --- a/src/domain/chatbot_thread.rs +++ b/src/domain/chatbot_thread.rs @@ -60,7 +60,7 @@ impl ChatbotThreadId { /// Reads do not conflict; only a write that *moves* a value on a key the delete /// also writes does. That is the shape /// [`bump_menu_and_write`](crate::domain::menu::bump_menu_and_write) and -/// [`ExamAnswer::save`](crate::domain::exam_answer::ExamAnswer::save) already +/// [`ExamAnswer::save`](crate::db::exam_answer::save) already /// use, and the sweep's ordering inside the delete stops mattering once it is /// in place. /// diff --git a/src/domain/class_pump.rs b/src/domain/class_pump.rs index 567131d..7ca5a32 100644 --- a/src/domain/class_pump.rs +++ b/src/domain/class_pump.rs @@ -233,7 +233,7 @@ impl Axis { /// and never enters the write set, so `count = count` sat on no key at all /// and a concurrent `DELETE /courses/{id}` committed beside it with both /// callers told OK (measured on 3.2.3, counter present and absent alike). - /// Same shape as [`crate::domain::exam_answer::ExamAnswer::save`]: the + /// Same shape as [`crate::db::exam_answer::save`]: the /// restore is by captured value, `NONE` included, so the row is /// byte-identical afterwards and the boot backfill still sees the `NONE` it /// seeds off. Both statements are inside the transaction, so an abort diff --git a/src/domain/exam_answer.rs b/src/domain/exam_answer.rs index e3ff797..dabaa10 100644 --- a/src/domain/exam_answer.rs +++ b/src/domain/exam_answer.rs @@ -1,13 +1,12 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{EXAM_ANSWER_TABLE, EXAM_RESULT_COUNT_FIELD, MAX_ANSWER_TEXT_LEN}; -use crate::database::{Database, transaction_with_retry}; +use crate::constant::{EXAM_ANSWER_TABLE, MAX_ANSWER_TEXT_LEN}; use crate::domain::exam::ExamId; use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId}; use crate::domain::key; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::validate_optional; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -57,14 +56,14 @@ impl AnswerText { /// cascades) don't fan out through `exam_question`. #[derive(Debug, Clone, SurrealValue)] pub struct ExamAnswer { - id: ExamAnswerId, - exam: ExamId, - question: ExamQuestionId, - user: UserId, - seq: i64, - selected: Option, - text: Option, - updated_at: Timestamp, + pub(crate) id: ExamAnswerId, + pub(crate) exam: ExamId, + pub(crate) question: ExamQuestionId, + pub(crate) user: UserId, + pub(crate) seq: i64, + pub(crate) selected: Option, + pub(crate) text: Option, + pub(crate) updated_at: Timestamp, } impl ExamAnswer { @@ -107,240 +106,6 @@ impl ExamAnswer { let correct = question.get_correct()?; Some(self.selected.as_ref() == Some(correct)) } - - /// Save (or overwrite) `user`'s answer to `question` for sitting `seq` — - /// the one write path, shared by the REST handler and the WebSocket room. - /// The payload must match the question's kind: a choice question takes - /// `selected` (the id of one of its choices), a text question takes `text`. - /// The caller has already checked that the attempt is in progress. Keyed - /// by `seq`, so a retake's save is a new row, not an overwrite of an - /// earlier sitting's answer. - pub async fn save( - question: &ExamQuestion, - user: &UserId, - seq: i64, - selected: Option, - text: Option, - db: &Database, - ) -> Result { - let invalid = - |field, reason| AppError::Validation(ValidationError::Invalid { field, reason }); - let (selected, text) = match question.get_kind().as_str() { - "choice" => { - if text.is_some() { - return Err(invalid( - "text", - "a choice question takes selected, not text", - )); - } - let Some(selected) = selected else { - return Err(invalid("selected", "required for a choice question")); - }; - // Membership, not a range: `selected` names an option by its - // stable id, so a reorder of the list can never repoint it. - let picked = question - .get_choices() - .unwrap_or_default() - .iter() - .find(|choice| choice.get_id().as_str() == selected) - .ok_or_else(|| { - invalid("selected", "must name one of the question's choices") - })?; - (Some(picked.get_id().clone()), None) - } - _ => { - if selected.is_some() { - return Err(invalid( - "selected", - "a text question takes text, not selected", - )); - } - let Some(text) = text else { - return Err(invalid("text", "required for a text question")); - }; - (None, Some(AnswerText::try_new(&text)?)) - } - }; - let answer = ExamAnswer { - id: ExamAnswerId::composite(question.get_id(), user, seq), - exam: question.get_exam().clone(), - question: question.get_id().clone(), - user: user.clone(), - seq, - selected, - text, - updated_at: Timestamp::now(), - }; - // 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::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 - // and the answer outlives the exam (measured 4 of 4 raced rounds). - // Writing the key the delete removes makes the two collide, and the - // store refuses one of them. It is the shape - // [`crate::domain::menu::bump_menu_and_write`] uses, and the one a mark - // already uses on this very row - // ([`crate::domain::exam_result::ExamResult::grade`]). - // - // The bump-and-restore is not a flourish, it is the whole instrument. - // The exam carries no revision to bump and must not grow one — its save - // is a whole-row `CONTENT` write, so a column this struct did not know - // about would be wiped by the next PATCH — so this touches the one - // counter it already has and puts it back. Writing the *same* value is - // not enough: an `UPDATE` that leaves the document unchanged is elided - // and never reaches the store's write set, which the race test proved - // (green on the raced delete, red the moment the value moves for real). - // The restore is by captured value, `NONE` included, so the row is - // byte-identical afterwards: the boot backfill still finds the rows it - // keys on (`WHERE result_count = NONE`), the PATCH's - // `(result_count ?? 0) = $was_results` still passes, and no teacher's - // edit is refused because a student typed. Both statements are inside - // the transaction, so a crash between them cannot leave the counter up. - // No `cap::counter_lock` either: no counter moves here, and the hottest - // write path in the app should not queue behind one. - // - // Admissible for `transaction_with_retry`: the `UPDATE`s, `SELECT`, - // `IF`/`THROW` and `RETURN` can never answer "already exists", and the - // `UPSERT`'s id is bijective with the (question, user, seq) triple - // `exam_answer` keys — a lost round wrote nothing, and re-sending - // resolves onto the same row rather than colliding with it. - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $was = (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $ex); - LET $touched = (UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = \ - ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); - IF array::len($touched) = 0 {{ THROW 'no_exam' }}; - UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = $was; - LET $row = (UPSERT $id CONTENT $answer RETURN AFTER); - RETURN $row[0]; - COMMIT TRANSACTION;" - ), - &[ - ("ex".into(), answer.exam.record().into_value()), - ("id".into(), answer.id.record().into_value()), - ("answer".into(), answer.into_value()), - ], - &["no_exam"], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_exam")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is the last statement before `COMMIT`, so its - // slot follows the statement count rather than a hand-kept number (the - // `db::exam::delete` treatment); `num_statements` counts BEGIN and COMMIT. - let slot = result.num_statements().saturating_sub(2); - result - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to save exam answer".into())) - } - - /// One student's stored answer for a question in sitting `seq`, if any. - pub async fn read( - question: &ExamQuestionId, - user: &UserId, - seq: i64, - db: &Database, - ) -> Result, AppError> { - Ok(db - .select(ExamAnswerId::composite(question, user, seq).record()) - .await?) - } - - /// Drop one student's answer to a single question in sitting `seq`. - pub async fn delete( - question: &ExamQuestionId, - user: &UserId, - seq: i64, - db: &Database, - ) -> Result<(), AppError> { - let _: Option = db - .delete(ExamAnswerId::composite(question, user, seq).record()) - .await?; - Ok(()) - } - - /// One student's answers for a single sitting (`seq`) across an exam, in - /// question (ULID) order — the live-sitting read-back and, for a past - /// `seq`, that attempt's answer sheet. - pub async fn list_for_exam_user( - exam: &ExamId, - user: &UserId, - seq: i64, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM exam_answer WHERE exam = $ex AND user = $usr AND seq = $seq - ORDER BY question ASC", - ) - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .bind(("seq", seq)) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// The distinct sittings a student has any answer for at `exam`, ascending - /// — the index a history view lists attempts from. - pub async fn list_seqs_for_user( - exam: &ExamId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT VALUE seq FROM exam_answer WHERE exam = $ex AND user = $usr - ORDER BY seq ASC", - ) - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .await? - .check()?; - let mut seqs = result.take::>(0)?; - seqs.dedup(); - Ok(seqs) - } - - /// Every answer of an exam — the live monitor aggregates these per student. - pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM exam_answer WHERE exam = $ex ORDER BY question ASC") - .bind(("ex", exam.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Drop one student's answers across an exam — a retake starts from a - /// blank sheet. - pub async fn delete_for_exam_user( - exam: &ExamId, - user: &UserId, - db: &Database, - ) -> Result<(), AppError> { - db.query("DELETE exam_answer WHERE exam = $ex AND user = $usr") - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(()) - } } /// The choice-question score suggested by the machine: `earned` points from @@ -489,81 +254,4 @@ mod tests { let text = text_question(&exam, 10); assert_eq!(answer(&text, &user, None).is_correct(&text), None); } - - /// The bite test for the exam-row touch in [`ExamAnswer::save`]: it exists - /// 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 - /// `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::{ - 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 = crate::db::exam::create( - &db, - &student(), - &crate::db::course::a_test_course(&db).await, - 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 - .unwrap(); - let stored = async |db: &Database| -> Option { - let mut result = db - .query("SELECT VALUE result_count FROM ONLY $ex") - .bind(("ex", exam.get_id().record())) - .await - .unwrap() - .check() - .unwrap(); - result.take::>(0).unwrap() - }; - let question = choice_question(exam.get_id(), 10, 1); - let pick = choice_id(&question, 1).as_str().to_string(); - - // A fresh exam carries no counter at all, and must still not after a save. - assert_eq!(stored(&db).await, None, "the fixture must start absent"); - ExamAnswer::save(&question, &student(), 1, Some(pick.clone()), None, &db) - .await - .unwrap(); - assert_eq!( - stored(&db).await, - None, - "the touch left the counter set — the backfill keys on NONE" - ); - - // …and a counter that marks have moved is put back at its own value. - db.query("UPDATE $ex SET result_count = 7") - .bind(("ex", exam.get_id().record())) - .await - .unwrap() - .check() - .unwrap(); - ExamAnswer::save(&question, &student(), 2, Some(pick), None, &db) - .await - .unwrap(); - assert_eq!(stored(&db).await, Some(7), "the touch moved a real count"); - - // The gate that makes the touch worth having: no exam, no answer. - let orphan = choice_question(&ExamId::from_key("01NOSUCHEXAMAAAAAAAAAAAAAA"), 10, 0); - let pick = choice_id(&orphan, 0).as_str().to_string(); - let refused = ExamAnswer::save(&orphan, &student(), 1, Some(pick), None, &db).await; - assert!( - matches!(refused, Err(AppError::NotFound)), - "a save into a missing exam must 404, got {refused:?}" - ); - } } diff --git a/src/domain/exam_result.rs b/src/domain/exam_result.rs index cbd5a98..c2b3512 100644 --- a/src/domain/exam_result.rs +++ b/src/domain/exam_result.rs @@ -2,21 +2,16 @@ use std::collections::HashMap; use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ - EXAM_RESULT_COUNT_FIELD, EXAM_RESULT_TABLE, HIGH_MARK_MIN, HIGH_MARK_TOTAL_FIELD, - KIND_REF_TABLE, MARKS_GIVEN_TOTAL_FIELD, REF_COUNT_FIELD, REF_RETIRED_FIELD, -}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; -use crate::domain::course::CourseId; +use crate::constant::{EXAM_RESULT_TABLE, KIND_REF_TABLE}; use crate::domain::exam::ExamId; use crate::domain::key; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::validate_mark; -/// The one spelling of "this exam is hidden", shared by the grade handler's -/// pre-flight gate and the in-transaction guard on the mark write. +/// The one spelling of "this exam is hidden", shared by the grading +/// pre-flight gate ([`crate::service::exam_result::grade`]) and the +/// in-transaction guard on the mark write. pub(crate) fn draft_error() -> AppError { AppError::Conflict("this exam is a draft — publish it before grading") } @@ -82,18 +77,14 @@ impl Mark { } } -/// The `THROW` marker the in-transaction kind claim aborts with — the mark's -/// own transaction refusing a name the school has retired. -const RETIRED_MARK: &str = "kind_retired"; - #[derive(Debug, Clone, SurrealValue)] pub struct ExamResult { - id: ExamResultId, - exam: ExamId, - user: UserId, - seq: i64, - mark: Mark, - graded_by: UserId, + pub(crate) id: ExamResultId, + pub(crate) exam: ExamId, + pub(crate) user: UserId, + pub(crate) seq: i64, + pub(crate) mark: Mark, + pub(crate) graded_by: UserId, } impl ExamResult { @@ -121,359 +112,39 @@ impl ExamResult { pub fn get_graded_by(&self) -> &UserId { &self.graded_by } +} - async fn find( - exam: &ExamId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - // Grade-of-record is the latest sitting's mark: the highest seq wins. - let mut result = db - .query( - "SELECT * FROM exam_result WHERE exam = $ex AND user = $usr - ORDER BY seq DESC LIMIT 1", - ) - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) - } - - /// The latest-seq mark per (exam, user) pair, preserving the outer list's - /// row order (first appearance of each pair). Grade-of-record is the latest - /// attempt's mark, so a pair with retakes collapses to its highest seq. Done - /// in Rust rather than SQL: SurrealDB's `GROUP BY` can't return the whole - /// row that carries the max, and id-order can't stand in for seq-order once - /// seq reaches two digits. - fn latest_per_pair(rows: Vec) -> Vec { - let mut order: Vec<(String, String)> = Vec::new(); - let mut best: HashMap<(String, String), ExamResult> = HashMap::new(); - for row in rows { - let key = (row.exam.key().to_string(), row.user.key().to_string()); - match best.get(&key) { - Some(existing) if existing.seq >= row.seq => {} - Some(_) => { - best.insert(key, row); - } - None => { - order.push(key.clone()); - best.insert(key, row); - } +/// The latest-seq mark per (exam, user) pair, preserving the outer list's +/// row order (first appearance of each pair). Grade-of-record is the latest +/// attempt's mark, so a pair with retakes collapses to its highest seq. Done +/// in Rust rather than SQL: SurrealDB's `GROUP BY` can't return the whole +/// row that carries the max, and id-order can't stand in for seq-order once +/// seq reaches two digits. +pub(crate) fn latest_per_pair(rows: Vec) -> Vec { + let mut order: Vec<(String, String)> = Vec::new(); + let mut best: HashMap<(String, String), ExamResult> = HashMap::new(); + for row in rows { + let key = (row.exam.key().to_string(), row.user.key().to_string()); + match best.get(&key) { + Some(existing) if existing.seq >= row.seq => {} + Some(_) => { + best.insert(key, row); + } + None => { + order.push(key.clone()); + best.insert(key, row); } } - order - .into_iter() - .map(|key| best.remove(&key).expect("key was recorded on insert")) - .collect() - } - - /// A single user's result for an exam, if graded. - pub async fn read_for_user( - exam: &ExamId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - Self::find(exam, user, db).await - } - - /// Record (or overwrite) `user`'s mark for the `seq`th sitting of `exam`. - /// One row per (exam, user, seq), keyed by a deterministic composite id so - /// this is a single atomic UPSERT — concurrent grades for the same sitting - /// converge on one row instead of racing the unique index into a 500. - /// Grading a retake writes a fresh mark at the current seq and never touches - /// prior sittings' marks; the latest seq is the grade-of-record. - /// - /// `kind` is the exam's kind, and this is where a mark takes its reference - /// on it — claimed *inside the mark's own transaction*, and only on the - /// branch that is about to add a row. A kind the school has retired refuses - /// the claim, which is the same invariant the settings guard enforces from - /// the other side. Claimed before the write and released after, the pair had - /// two crash windows either side of the write that leaked a reference (a - /// kind frozen out of the settings for good) and an exam's `result_count`; - /// riding the transaction, both counters land exactly when the row does. - /// - /// The exam's own `result_count` is claimed in the same breath, and it is - /// what a kind change is refused against: the exam PATCH pins that counter, - /// so a mark landing while it decides cannot slip past its gate and leave - /// itself counted under a kind its exam no longer carries. - /// - /// An overwrite (a regrade of a sitting already marked) claims *nothing*: - /// one mark, one reference, so the branch that finds a row simply leaves - /// both counters where they are — there is no claim to give back, and so no - /// window in which a crash could fail to give it. - /// - /// The grader's `marks_given_total` rides that same first-time branch: a - /// regrade of a sitting moves it however often it is run, while a retake, - /// being a distinct `seq` and so a distinct row, counts on its own. - /// - /// The student's `high_mark_total` cannot ride it, because it is not a - /// count of rows but a count of rows *at or above* [`HIGH_MARK_MIN`], and a - /// regrade moves a mark across that line without adding or removing a row. - /// It moves by the difference between the mark about to be stored and the - /// one already there — `+1` crossing up, `-1` crossing down, nothing at all - /// when both sides sit on the same side of the line, so an overwrite still - /// costs the student's row no write unless the answer actually changed. - /// Decided on the first branch alone it drifted upward without bound: 95 - /// credited, regraded to 40 (no row added, so no move), then deleted, whose - /// refund reads the *stored* mark and so found nothing to give back — a - /// counter of one over zero stored high marks, looped into a permanent - /// badge. Both counters are written field-scoped: a user row also carries - /// admin-owned data (`role`) that a whole-row save would revert. - pub async fn grade( - exam: &ExamId, - user: &UserId, - seq: i64, - mark: Mark, - graded_by: &UserId, - kind: &str, - db: &Database, - ) -> Result { - let result = ExamResult { - id: ExamResultId::composite(exam, user, seq), - exam: exam.clone(), - user: user.clone(), - seq, - mark, - graded_by: graded_by.clone(), - }; - // The "exists" and "not a draft" gates ride in the same transaction as - // the mark, the mirror of the re-draft gate on - // `Exam::update_if_unchanged`: between them, a mark and a re-draft - // racing each other can only ever leave one of the two applied, - // whichever process either ran in. The existence gate is not - // redundant with the draft one — a deleted exam reads NONE, which is - // *falsy*, so the draft gate alone waved a mark onto an exam that no - // longer existed. The caller's pre-flight check answers the same 409 - // one round trip earlier. It is also what makes a separate "did the - // exam survive my claim?" check moot: the claim now sits behind this - // gate instead of in front of it. - // - // `$before` is the sitting's *previous mark*, and it answers both - // questions off one read: `mark` is a mandatory column on a schemafull - // row, so `NONE` there means no row at all — the claim branch — while a - // number is what the student's counter takes its difference against. - // Read one statement before the counters inside the same transaction: - // read anywhere else it would be a guess about a row two graders may be - // writing at once, and the difference would be taken against a mark - // some other round had already replaced. - // - // Re-sent while the store answers "conflict, retry": the gates read a - // column an exam PATCH writes, and the counters are the ones a - // concurrent delete gives back, so this contends on three records by - // design. Sound to re-send because no statement in it can legitimately - // answer "already exists": the counter writes are `UPDATE`/`UPSERT` on - // ids no rival can collide *into*, and the mark's own UPSERT is on a - // deterministic id bijective with the `exam_result_exam_user_seq` - // unique tuple — `key::sitting(exam, user, seq)` *is* that tuple, so - // the index entry can only ever point at the row the id already names - // and the write resolves onto it. A lost round aborts having written - // nothing, counters included. - let _guard = cap::counter_lock().await; - let (mut written, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - IF (SELECT VALUE id FROM ONLY $exam) IS NONE {{ THROW 'exam_missing' }}; - IF (SELECT VALUE draft FROM ONLY $exam) {{ THROW 'exam_draft' }}; - LET $before = (SELECT VALUE mark FROM ONLY $id); - IF $before = NONE {{ - LET $kind = (UPSERT $kref SET {REF_COUNT_FIELD} = ({REF_COUNT_FIELD} ?? 0) + 1 - WHERE {REF_RETIRED_FIELD} != true RETURN VALUE id); - IF array::len($kind) = 0 {{ THROW '{RETIRED_MARK}' }}; - UPDATE $exam SET {EXAM_RESULT_COUNT_FIELD} = - ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1; - UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = - ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1; - }}; - LET $high = (IF $result.mark >= {HIGH_MARK_MIN} {{ 1 }} ELSE {{ 0 }}) - - (IF ($before ?? -1) >= {HIGH_MARK_MIN} {{ 1 }} ELSE {{ 0 }}); - IF $high != 0 {{ - UPDATE $student SET {HIGH_MARK_TOTAL_FIELD} = - math::max([({HIGH_MARK_TOTAL_FIELD} ?? 0) + $high, 0]) - }}; - LET $after = (UPSERT $id CONTENT $result RETURN AFTER); - RETURN $after[0]; - COMMIT TRANSACTION;" - ), - &[ - ("exam".into(), exam.record().into_value()), - ("id".into(), result.id.record().into_value()), - ("kref".into(), kind_ref(kind).into_value()), - ("grader".into(), graded_by.record().into_value()), - ("student".into(), user.record().into_value()), - ("result".into(), result.into_value()), - ], - &["exam_missing", "exam_draft", RETIRED_MARK], - ) - .await?; - // An aborted transaction errors every slot and only the THROW's own - // slot names the marker, so a refusal is read by marker while a lost - // round was already re-sent — never reported as a 500. - let thrown = |marker: &str| { - errors - .values() - .any(|error| error.to_string().contains(marker)) - }; - if thrown("exam_missing") { - return Err(AppError::NotFound); - } - if thrown("exam_draft") { - return Err(draft_error()); - } - if thrown(RETIRED_MARK) { - return Err(retired_kind_error(kind)); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`, - // so its slot follows the statement count instead of a hand-kept - // number — see `Exam::delete` for the bug the hand-kept one caused. - // Probed on crate 3.2.3: an `IF { … }` block occupies exactly one slot - // however many statements it holds, and one whether or not it is taken. - let slot = written.num_statements().saturating_sub(2); - written - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to record exam result".into())) - } - - /// The user's graded results restricted to one course's exams — the raw - /// rows behind the per-course block of the marks report. - pub async fn list_for_user_in_course( - course: &CourseId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM exam_result WHERE user = $usr - AND exam IN (SELECT VALUE id FROM exam WHERE course = $course) - ORDER BY id DESC", - ) - .bind(("usr", user.record())) - .bind(("course", course.record())) - .await? - .check()?; - Ok(Self::latest_per_pair(result.take::>(0)?)) - } - - pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC") - .bind(("ex", exam.record())) - .await? - .check()?; - Ok(Self::latest_per_pair(result.take::>(0)?)) - } - - /// Every sitting's mark for one (exam, user) pair, oldest first — the - /// per-attempt grade history behind the FE's attempt-by-attempt view. - pub async fn list_all_for_exam_user( - exam: &ExamId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM exam_result WHERE exam = $ex AND user = $usr - ORDER BY seq ASC", - ) - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Delete every sitting's mark for one (exam, user) pair. `kind` is the - /// exam's: the marks give their references back, so a kind nothing is - /// graded under any more can leave the settings again. - /// - /// The two badge counters come back the same way, and for a reason the - /// other counters do not need: [`grade`](Self::grade) credits them on the - /// branch that finds no row, and a deleted row *is* no row. Left standing, - /// ungrade-then-regrade credited a second time off one stored mark, and - /// looped it minted a badge from a single exam — permanently, since an - /// award is never revoked. Each is given back off the rows this statement - /// actually deleted: `marks_given_total` to each row's *own* grader (two - /// teachers can hold two sittings of the same pair), and `high_mark_total` - /// once per removed row that cleared [`HIGH_MARK_MIN`], read off the - /// `BEFORE` image rather than re-derived. That last one is why - /// [`grade`](Self::grade) has to move the student's counter on a *regrade* - /// too: this end reads the stored mark, so the other end must be decided by - /// the stored mark as well, or a mark walked across the line between the - /// two leaves a credit no delete can find to give back. - pub async fn remove( - exam: &ExamId, - user: &UserId, - kind: &str, - db: &Database, - ) -> Result, AppError> { - // Both counters go back *inside* the delete's own transaction, driven - // off the rows this statement actually deleted. Counted outside it, a - // cascade (exam or course delete) taking the same rows in the gap would - // release them a second time, and on a kind another exam still grades - // under, one release too many reads as one mark too few — a kind - // wrongly free to leave the settings. - // - // Re-sent while the store answers "conflict, retry": the counters this - // touches are the ones a concurrent grade claims, so a lost round is - // routine and aborts having written nothing. `check()` cannot be used - // to read the outcome — it takes the *lowest*-slot error, and an - // aborted transaction's generic "not executed" sibling masked the real - // conflict, the exact defect deleted from `Exam::delete`. No THROW of - // its own, and only `DELETE`/`UPDATE` inside, so nothing here can - // answer "already exists" and make a retry unsound. - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $gone = (DELETE exam_result WHERE exam = $ex AND user = $usr RETURN BEFORE); - IF array::len($gone) > 0 {{ - UPDATE type::record('kind_ref', $kind) SET {REF_COUNT_FIELD} = - math::max([({REF_COUNT_FIELD} ?? 0) - array::len($gone), 0]); - UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = - math::max([({EXAM_RESULT_COUNT_FIELD} ?? 0) - array::len($gone), 0]); - LET $high = array::len($gone[WHERE mark >= {HIGH_MARK_MIN}]); - IF $high > 0 {{ - UPDATE $usr SET {HIGH_MARK_TOTAL_FIELD} = - math::max([({HIGH_MARK_TOTAL_FIELD} ?? 0) - $high, 0]) - }}; - FOR $row IN $gone {{ - LET $grader = $row.graded_by; - UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = - math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0]) - }}; - }}; - RETURN $gone; - COMMIT TRANSACTION;" - ), - &[ - ("ex".into(), exam.record().into_value()), - ("usr".into(), user.record().into_value()), - ("kind".into(), kind.to_string().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // `RETURN` is the last statement before `COMMIT`; its slot follows the - // statement count, as in `Exam::delete`. - let slot = result.num_statements().saturating_sub(2); - let removed = result.take::>(slot)?; - Ok(removed.into_iter().next()) } + order + .into_iter() + .map(|key| best.remove(&key).expect("key was recorded on insert")) + .collect() } #[cfg(test)] mod tests { use super::*; - use crate::database::init_mem; #[tokio::test] async fn mark_range_is_enforced() { @@ -482,469 +153,4 @@ mod tests { assert!(Mark::try_new(-1).is_err()); assert!(Mark::try_new(101).is_err()); } - - #[tokio::test] - async fn retakes_keep_a_mark_per_sitting_with_the_latest_as_grade_of_record() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA"); - let user = UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"); - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); - // The exam has to be real: a mark is refused on one that isn't. - db.query( - "CREATE $ex SET creator = $t, course = course:c, title = 't', - description = '', kind = 'midterm'", - ) - .bind(("ex", exam.record())) - .bind(("t", teacher.record())) - .await - .unwrap() - .check() - .unwrap(); - - // Grade sitting #1, then a retake as sitting #2 — two rows, not one. - ExamResult::grade( - &exam, - &user, - 1, - Mark::try_new(40).unwrap(), - &teacher, - "midterm", - &db, - ) - .await - .unwrap(); - let second = ExamResult::grade( - &exam, - &user, - 2, - Mark::try_new(90).unwrap(), - &teacher, - "midterm", - &db, - ) - .await - .unwrap(); - assert_eq!(second.get_seq(), 2); - - // Grade-of-record is the latest sitting's mark. - let latest = ExamResult::read_for_user(&exam, &user, &db) - .await - .unwrap() - .expect("graded"); - assert_eq!(latest.get_mark().as_i64(), 90); - assert_eq!(latest.get_seq(), 2); - - // The roster yields exactly one row per pair — the latest. - let roster = ExamResult::list_for_exam(&exam, &db).await.unwrap(); - assert_eq!(roster.len(), 1); - assert_eq!(roster[0].get_mark().as_i64(), 90); - - // History keeps both sittings, oldest first. - let history = ExamResult::list_all_for_exam_user(&exam, &user, &db) - .await - .unwrap(); - assert_eq!( - history - .iter() - .map(|r| r.get_mark().as_i64()) - .collect::>(), - vec![40, 90] - ); - - // Deleting the pair removes every sitting. - ExamResult::remove(&exam, &user, "midterm", &db) - .await - .unwrap(); - assert!( - ExamResult::list_all_for_exam_user(&exam, &user, &db) - .await - .unwrap() - .is_empty() - ); - } - - /// A deleted exam reads NONE, and NONE is falsy — the draft gate alone let - /// a mark land on an exam that no longer existed. - #[tokio::test] - async fn a_mark_is_refused_on_an_exam_that_no_longer_exists() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTGONEEXAMAAAAAAAAAAAA"); - let user = UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"); - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); - - let refused = ExamResult::grade( - &exam, - &user, - 1, - Mark::try_new(40).unwrap(), - &teacher, - "midterm", - &db, - ) - .await; - assert!(matches!(refused, Err(AppError::NotFound)), "{refused:?}"); - assert!( - ExamResult::list_all_for_exam_user(&exam, &user, &db) - .await - .unwrap() - .is_empty() - ); - assert_eq!(counters(&db, "midterm").await, (0, 0)); - } - - /// The two counters, re-read out of the store — never off a return value, - /// which the in-memory engine forges wins on (see `cap::CLAIM_LOCK`). A - /// missing `kind_ref` row is a zero, which is exactly how the backfill - /// treats it (`tests/persistence.rs` — no zero pass, deliberately). - async fn counters(db: &Database, kind: &str) -> (i64, i64) { - let mut result = db - .query( - "SELECT VALUE count ?? 0 FROM kind_ref WHERE record::id(id) = $kind; - SELECT VALUE result_count ?? 0 FROM exam;", - ) - .bind(("kind", kind.to_string())) - .await - .unwrap() - .check() - .unwrap(); - let kinds: Vec = result.take(0).unwrap(); - let exams: Vec = result.take(1).unwrap(); - ( - kinds.into_iter().next().unwrap_or(0), - exams.into_iter().next().unwrap_or(0), - ) - } - - async fn an_exam(db: &Database, exam: &ExamId, kind: &str) { - db.query( - "CREATE $ex SET creator = user:t, course = course:c, title = 't', - description = '', kind = $kind", - ) - .bind(("ex", exam.record())) - .bind(("kind", kind.to_string())) - .await - .unwrap() - .check() - .unwrap(); - } - - const STUDENT: &str = "01TESTSTUDENTAAAAAAAAAAAAA"; - const TEACHER: &str = "01TESTTEACHERAAAAAAAAAAAAA"; - - async fn grade( - db: &Database, - exam: &ExamId, - seq: i64, - mark: i64, - kind: &str, - ) -> Result { - ExamResult::grade( - exam, - &UserId::from_key(STUDENT), - seq, - Mark::try_new(mark).unwrap(), - &UserId::from_key(TEACHER), - kind, - db, - ) - .await - } - - /// Both counters ride the mark's own transaction: a new mark claims each - /// exactly once, and a *regrade* of the same sitting claims neither — one - /// mark, one reference. Claimed-then-released around the write, a regrade - /// drifted them upward and froze the kind out of the settings for good. - #[tokio::test] - async fn a_new_mark_moves_both_counters_and_a_regrade_moves_neither() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTEXAMCOUNTAAAAAAAAAAA"); - an_exam(&db, &exam, "midterm").await; - - grade(&db, &exam, 1, 40, "midterm").await.unwrap(); - assert_eq!(counters(&db, "midterm").await, (1, 1)); - - // Same sitting, new mark: an overwrite, so neither counter moves. - let regraded = grade(&db, &exam, 1, 90, "midterm").await.unwrap(); - assert_eq!(regraded.get_mark().as_i64(), 90); - assert_eq!(counters(&db, "midterm").await, (1, 1)); - - // A retake is a second row, so it does claim. - grade(&db, &exam, 2, 70, "midterm").await.unwrap(); - assert_eq!(counters(&db, "midterm").await, (2, 2)); - } - - /// The two badge counters, re-read out of the store: the grader's marks - /// given and the student's high marks. - async fn badge_counters(db: &Database) -> (i64, i64) { - let mut result = db - .query(format!( - "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $grader; - SELECT VALUE ({HIGH_MARK_TOTAL_FIELD} ?? 0) FROM $student;" - )) - .bind(("grader", UserId::from_key(TEACHER).record())) - .bind(("student", UserId::from_key(STUDENT).record())) - .await - .unwrap() - .check() - .unwrap(); - let given: Vec = result.take(0).unwrap(); - let high: Vec = result.take(1).unwrap(); - ( - given.into_iter().next().unwrap_or(0), - high.into_iter().next().unwrap_or(0), - ) - } - - /// The rows a counter needs to land on — `UPDATE` writes nothing to a user - /// that does not exist, so the badge tests must make both real. - async fn the_two_people(db: &Database) { - for key in [TEACHER, STUDENT] { - db.query("CREATE $usr SET username = $name, password_hash = 'x'") - .bind(("usr", UserId::from_key(key).record())) - .bind(("name", key.to_string())) - .await - .unwrap() - .check() - .unwrap(); - } - } - - /// A first grade credits the grader once and the student only when the mark - /// clears the line; a regrade of the same sitting credits neither again, - /// while a retake — a distinct seq, so a distinct row — counts on its own. - #[tokio::test] - async fn a_grade_credits_the_grader_once_and_a_high_mark_the_student() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTEXAMBADGEAAAAAAAAAAA"); - an_exam(&db, &exam, "midterm").await; - the_two_people(&db).await; - - grade(&db, &exam, 1, 90, "midterm").await.unwrap(); - assert_eq!(badge_counters(&db).await, (1, 1), "at the line earns it"); - - // Same sitting graded again: neither counter may move, however high. - grade(&db, &exam, 1, 100, "midterm").await.unwrap(); - assert_eq!(badge_counters(&db).await, (1, 1), "a regrade moves nothing"); - - // A retake below the line: the grader is credited, the student is not. - grade(&db, &exam, 2, 89, "midterm").await.unwrap(); - assert_eq!(badge_counters(&db).await, (2, 1), "89 is under the line"); - - // …and a high-scoring retake counts as its own sitting. - grade(&db, &exam, 3, 95, "midterm").await.unwrap(); - assert_eq!(badge_counters(&db).await, (3, 2)); - } - - /// Ungrading gives both badge counters back, so grade → ungrade → regrade - /// nets to one credit however often it is run. Crediting the grade without - /// refunding the delete let that loop mint a badge off a single exam — and - /// an award, once earned, is never taken back. - #[tokio::test] - async fn ungrading_gives_the_badge_counters_back() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTEXAMUNGRADEAAAAAAAAA"); - an_exam(&db, &exam, "midterm").await; - the_two_people(&db).await; - let student = UserId::from_key(STUDENT); - - for _ in 0..3 { - grade(&db, &exam, 1, 95, "midterm").await.unwrap(); - assert_eq!(badge_counters(&db).await, (1, 1)); - ExamResult::remove(&exam, &student, "midterm", &db) - .await - .unwrap() - .expect("the mark was there"); - assert_eq!(badge_counters(&db).await, (0, 0), "the loop kept a credit"); - // The kind's reference and the exam's count come back as before. - assert_eq!(counters(&db, "midterm").await, (0, 0)); - } - - // Every removed sitting is refunded, and only the ones that took: the - // grader gets both back, the student only the mark that cleared the line. - grade(&db, &exam, 1, 40, "midterm").await.unwrap(); - grade(&db, &exam, 2, 95, "midterm").await.unwrap(); - assert_eq!(badge_counters(&db).await, (2, 1)); - ExamResult::remove(&exam, &student, "midterm", &db) - .await - .unwrap() - .expect("both sittings were there"); - assert_eq!(badge_counters(&db).await, (0, 0)); - - // Nothing to remove is nothing to give back — the floor holds. - assert!( - ExamResult::remove(&exam, &student, "midterm", &db) - .await - .unwrap() - .is_none() - ); - assert_eq!(badge_counters(&db).await, (0, 0)); - } - - /// A regrade walks the *same* sitting across [`HIGH_MARK_MIN`], and the - /// student's counter has to walk with it — the delete refunds off the mark - /// it finds stored, so a credit decided by a mark that is no longer there - /// is a credit nothing can give back. Left on the first-write branch alone, - /// grade-high → regrade-low → delete kept a phantom high mark every round - /// and looped it into a permanent badge. - #[tokio::test] - async fn a_regrade_across_the_line_moves_the_student_counter_with_it() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTEXAMREGRADEAAAAAAAAA"); - an_exam(&db, &exam, "midterm").await; - the_two_people(&db).await; - let student = UserId::from_key(STUDENT); - - // Up across the line: no row is added, but a high mark now exists. - grade(&db, &exam, 1, 40, "midterm").await.unwrap(); - assert_eq!(badge_counters(&db).await, (1, 0), "40 is under the line"); - grade(&db, &exam, 1, 95, "midterm").await.unwrap(); - assert_eq!(badge_counters(&db).await, (1, 1), "the regrade crossed up"); - ExamResult::remove(&exam, &student, "midterm", &db) - .await - .unwrap() - .expect("the mark was there"); - assert_eq!(badge_counters(&db).await, (0, 0)); - - // Down across it: the credit goes back the moment the mark does, so - // the delete has nothing left to refund and the counter still lands - // on zero rather than under it. - grade(&db, &exam, 1, 95, "midterm").await.unwrap(); - assert_eq!(badge_counters(&db).await, (1, 1)); - grade(&db, &exam, 1, 40, "midterm").await.unwrap(); - assert_eq!( - badge_counters(&db).await, - (1, 0), - "the regrade crossed down" - ); - ExamResult::remove(&exam, &student, "midterm", &db) - .await - .unwrap() - .expect("the mark was there"); - assert_eq!(badge_counters(&db).await, (0, 0)); - - // Both sides of a regrade above the line: nothing crosses, nothing moves. - grade(&db, &exam, 1, 90, "midterm").await.unwrap(); - grade(&db, &exam, 1, 100, "midterm").await.unwrap(); - assert_eq!(badge_counters(&db).await, (1, 1), "90 → 100 stays one"); - - // The loop that minted the badge: three rounds of high → low → delete - // must leave the counter exactly where it started. - for _ in 0..3 { - grade(&db, &exam, 1, 95, "midterm").await.unwrap(); - grade(&db, &exam, 1, 40, "midterm").await.unwrap(); - ExamResult::remove(&exam, &student, "midterm", &db) - .await - .unwrap() - .expect("the mark was there"); - } - assert_eq!( - badge_counters(&db).await, - (0, 0), - "the loop kept a high mark with no high mark stored" - ); - } - - /// The other half of the same asymmetry: a refund read off a stored mark - /// that was never credited eats a credit earned somewhere else. One exam - /// holds a genuine high mark while a second is graded low, regraded high - /// and deleted — the first exam's credit must still be standing. - #[tokio::test] - async fn one_exams_regrade_never_eats_another_exams_high_mark() { - let db = init_mem().await.unwrap(); - let first = ExamId::from_key("01TESTEXAMSTEALONEAAAAAAAA"); - let second = ExamId::from_key("01TESTEXAMSTEALTWOAAAAAAAA"); - an_exam(&db, &first, "midterm").await; - an_exam(&db, &second, "midterm").await; - the_two_people(&db).await; - let student = UserId::from_key(STUDENT); - - grade(&db, &first, 1, 95, "midterm").await.unwrap(); - assert_eq!( - badge_counters(&db).await, - (1, 1), - "earned on the first exam" - ); - - grade(&db, &second, 1, 40, "midterm").await.unwrap(); - grade(&db, &second, 1, 95, "midterm").await.unwrap(); - assert_eq!(badge_counters(&db).await, (2, 2)); - ExamResult::remove(&second, &student, "midterm", &db) - .await - .unwrap() - .expect("the mark was there"); - assert_eq!( - badge_counters(&db).await, - (1, 1), - "the first exam's high mark was eaten" - ); - } - - /// A refused mark leaves the badge counters where the other two are left. - #[tokio::test] - async fn a_refused_mark_credits_nobody() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTEXAMBADGEDRAFTAAAAAA"); - an_exam(&db, &exam, "midterm").await; - the_two_people(&db).await; - db.query("UPDATE $ex SET draft = true") - .bind(("ex", exam.record())) - .await - .unwrap() - .check() - .unwrap(); - - assert!(grade(&db, &exam, 1, 100, "midterm").await.is_err()); - assert_eq!(badge_counters(&db).await, (0, 0)); - } - - /// A retired kind refuses the claim from inside the transaction, which - /// takes the mark and the exam's counter down with it — the settings guard - /// enforcing the same invariant from the other side. - #[tokio::test] - async fn a_retired_kind_refuses_the_mark_and_leaves_both_counters_alone() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTEXAMRETIREDAAAAAAAAA"); - an_exam(&db, &exam, "midterm").await; - assert!(cap::retire(&kind_ref("midterm"), &db).await.unwrap()); - - let refused = grade(&db, &exam, 1, 40, "midterm").await; - assert!( - matches!(&refused, Err(AppError::ConflictOwned(message)) - if message.contains("has been removed from the school's settings")), - "{refused:?}" - ); - assert!( - ExamResult::list_for_exam(&exam, &db) - .await - .unwrap() - .is_empty(), - "the mark must not have landed" - ); - assert_eq!(counters(&db, "midterm").await, (0, 0)); - } - - /// A draft exam refuses the mark, and the counters stay put — the gate - /// runs before the claim now, so there is nothing to give back. - #[tokio::test] - async fn a_draft_exam_refuses_the_mark_and_leaves_both_counters_alone() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTEXAMDRAFTAAAAAAAAAAA"); - an_exam(&db, &exam, "midterm").await; - db.query("UPDATE $ex SET draft = true") - .bind(("ex", exam.record())) - .await - .unwrap() - .check() - .unwrap(); - - let refused = grade(&db, &exam, 1, 40, "midterm").await; - assert!(matches!(refused, Err(AppError::Conflict(_))), "{refused:?}"); - assert!( - ExamResult::list_for_exam(&exam, &db) - .await - .unwrap() - .is_empty() - ); - assert_eq!(counters(&db, "midterm").await, (0, 0)); - } } diff --git a/src/domain/homework_submission.rs b/src/domain/homework_submission.rs index ffd65f3..47878dc 100644 --- a/src/domain/homework_submission.rs +++ b/src/domain/homework_submission.rs @@ -124,7 +124,7 @@ impl HomeworkSubmission { /// transaction, and the order is load-bearing: the increment sits *after* /// the UPSERT and is conditional on it having matched a row, because a /// frozen row makes that `WHERE` match nothing **silently** (unlike - /// [`crate::domain::exam_result::ExamResult::grade`], which `THROW`s) — put + /// [`crate::db::exam_result::grade`], which `THROW`s) — put /// first, it would count a submission the freeze refused. `$before = NONE` /// keeps it to a genuine first create, so an edit moves neither counter, /// which is what makes the live count mean the same thing the one-time @@ -160,7 +160,7 @@ impl HomeworkSubmission { /// homework row — `due_at` up by one and straight back to the captured /// value, so the row is byte-identical afterwards — because only a write /// collides, and `SET x = x` is elided and never reaches the write set. It - /// is [`crate::domain::exam_answer::ExamAnswer::save`]'s shape exactly. + /// is [`crate::db::exam_answer::save`]'s shape exactly. /// `Err(NotFound)` means the homework is gone, which is the 404 the web /// layer's own lookup would have answered. pub async fn upsert( diff --git a/src/domain/pool_question.rs b/src/domain/pool_question.rs index 8b63202..b1121ed 100644 --- a/src/domain/pool_question.rs +++ b/src/domain/pool_question.rs @@ -717,7 +717,7 @@ mod tests { ); } - /// The [`crate::domain::exam_answer::ExamAnswer::save`] defect, one domain + /// The [`crate::db::exam_answer::save`] defect, one domain /// over: a solution offered inside its question's delete window must not /// outlive it. Guarding the offer by *reading* the question does not do it /// — the read sees a row [`PoolQuestion::delete`] has removed but not diff --git a/src/domain/question_image.rs b/src/domain/question_image.rs index 1c1ae18..7c21f60 100644 --- a/src/domain/question_image.rs +++ b/src/domain/question_image.rs @@ -5,21 +5,19 @@ //! `file` — a fresh server-generated ULID per upload, so no user input ever //! shapes a disk path and a replace never overwrites bytes in place. The row //! id is *deterministic* per (question, slot), so "one image per slot" holds -//! by construction and a replace is a plain UPSERT. The web layer owns the -//! blob I/O and its ordering (new blob before row, row before old blob); -//! this module owns the rows. +//! by construction and a replace is a plain UPSERT. The queries and +//! transactions over these rows live in [`crate::db::question_image`]; the web +//! layer owns the blob I/O and its ordering (new blob before row, row before +//! old blob). use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; use crate::constant::QUESTION_IMAGE_TABLE; -use crate::database::Database; -use crate::domain::course::CourseId; use crate::domain::exam::ExamId; use crate::domain::exam_question::{ChoiceId, ExamQuestionId}; use crate::domain::key; use crate::domain::note_file::FileContentType; -use crate::error::AppError; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct QuestionImageId(RecordId); @@ -48,32 +46,23 @@ impl QuestionImageId { #[derive(Debug, Clone, SurrealValue)] pub struct QuestionImage { - id: QuestionImageId, - exam: ExamId, - question: ExamQuestionId, + pub(crate) id: QuestionImageId, + pub(crate) exam: ExamId, + pub(crate) question: ExamQuestionId, /// `NONE` = the question's illustration; otherwise the id of the option /// this picture belongs to. - slot: Option, + pub(crate) slot: Option, /// The blob's on-disk name — a fresh ULID every upload. - file: String, - content_type: FileContentType, - size: i64, -} - -/// What one [`QuestionImage::upsert`] transaction returns: the row it stored -/// and the blob name it replaced. Both are arrays because SurrealDB drops an -/// object key valued `NONE` on the way out, while an empty array survives — -/// "nothing was replaced" has to be readable, not missing. -#[derive(SurrealValue)] -struct UpsertOutcome { - stored: Vec, - replaced: Vec, + pub(crate) file: String, + pub(crate) content_type: FileContentType, + pub(crate) size: i64, } impl QuestionImage { /// Assemble a row (fresh blob name generated here) without persisting it. /// The caller writes the blob under [`Self::get_file`] first, then calls - /// [`Self::upsert`] — so a stored row always points at a real blob. + /// [`crate::db::question_image::upsert`] — so a stored row always points + /// at a real blob. pub fn new( exam: &ExamId, question: &ExamQuestionId, @@ -111,339 +100,4 @@ impl QuestionImage { pub fn get_size(&self) -> i64 { self.size } - - /// Create or replace the slot's image row — the deterministic id makes - /// this the whole "one image per slot" story — handing back what it stored - /// plus the blob name it replaced, for the caller to take off disk. Refused - /// once the exam has an attempt: pictures are part of the question, so they - /// freeze with it, and the gate is in this transaction rather than in a lock - /// the caller held. - /// - /// The replaced name is read *here*, not by the caller before it: two - /// uploads to one slot both write this row, so they contend and the loser - /// re-reads the winner's blob name, where two pre-reads both saw the *old* - /// blob and left the loser's fresh one orphaned on disk. - pub async fn upsert(self, db: &Database) -> Result<(QuestionImage, Option), AppError> { - // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic - let (exam, id) = (self.exam.clone(), self.id.record()); - let mut result = crate::db::exam_attempt::write_unfrozen( - db, - &exam, - "LET $replaced = (SELECT VALUE file FROM $id); - LET $stored = (UPSERT $id CONTENT $image); - RETURN { stored: $stored, replaced: $replaced };", - vec![ - ("id".into(), id.into_value()), - ("image".into(), self.into_value()), - ], - ) - .await?; - // The trailing `RETURN` is the last statement before `COMMIT`, so its - // slot follows the statement count rather than a hand-kept number; - // `num_statements` counts BEGIN and COMMIT. - let slot = result.num_statements().saturating_sub(2); - let failed = || AppError::Internal("failed to store question image".into()); - let outcome = result - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(failed)?; - let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; - Ok((stored, outcome.replaced.into_iter().next())) - } - - pub async fn read_slot( - question: &ExamQuestionId, - slot: Option<&ChoiceId>, - db: &Database, - ) -> Result, AppError> { - Ok(db - .select(QuestionImageId::for_slot(question, slot).record()) - .await?) - } - - /// Every image of the exam's questions — one query for the list views. - pub async fn list_for_exam( - exam: &ExamId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM question_image WHERE exam = $ex") - .bind(("ex", exam.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - pub async fn list_for_question( - question: &ExamQuestionId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM question_image WHERE question = $q") - .bind(("q", question.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Drop the option pictures whose choice is gone — every choice image of - /// the question whose `slot` is *not* in `keep` (the question's own - /// illustration always stays), returning the removed rows so the caller can - /// take their blobs off disk. - /// - /// This is what makes an edit non-destructive: a PATCH that reorders, - /// renames, or drops options passes the surviving choice ids as `keep`, so - /// only the pictures of genuinely removed options go. `keep = &[]` (a text - /// question, or an all-new choice list) still clears the lot. - pub async fn delete_choices_not_in( - question: &ExamQuestionId, - keep: &[ChoiceId], - db: &Database, - ) -> Result, AppError> { - let keep: Vec = keep.iter().map(|id| id.as_str().to_string()).collect(); - let mut result = db - .query( - "DELETE question_image \ - WHERE question = $q AND slot != NONE AND slot NOT IN $keep RETURN BEFORE", - ) - .bind(("q", question.record())) - .bind(("keep", keep)) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// The blob names behind every image of every exam of `course` — collected - /// *before* the course-delete cascade wipes the rows. - pub async fn file_keys_for_course( - course: &CourseId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT VALUE file FROM question_image \ - WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)", - ) - .bind(("course", course.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Refused once the exam has an attempt, in the same transaction — same - /// gate, same reason as [`Self::upsert`]. - pub async fn delete(self, db: &Database) -> Result { - let mut result = crate::db::exam_attempt::write_unfrozen( - db, - &self.exam, - "DELETE $id RETURN BEFORE;", - vec![("id".into(), self.id.record().into_value())], - ) - .await?; - result - .take::>(crate::db::exam_attempt::FROZEN_SLOT)? - .into_iter() - .next() - .ok_or(AppError::NotFound) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec}; - - /// A real exam row: an image write moves its exam's counter (that is what - /// keeps a picture from outliving its exam), so a minted id nothing wrote - /// is a 404. - async fn exam_row(db: &Database) -> ExamId { - crate::db::exam::published_exam(db).await.get_id().clone() - } - - fn png() -> FileContentType { - FileContentType::try_new("image/png").unwrap() - } - - /// Three minted choice ids to slot pictures against. - fn choice_ids() -> Vec { - QuestionSpec::try_new( - QuestionKind::try_new("choice").unwrap(), - Some( - ["a", "b", "c"] - .iter() - .map(|l| ChoiceInput { - id: Some((*l).into()), - text: (*l).into(), - }) - .collect(), - ), - Some("a".into()), - &[], - ) - .unwrap() - .into_parts() - .1 - .unwrap() - .iter() - .map(|c| c.get_id().clone()) - .collect() - } - - #[tokio::test] - async fn upsert_replaces_per_slot() { - let db = crate::database::init_mem().await.unwrap(); - let exam = exam_row(&db).await; - let question = ExamQuestionId::generate(); - let ids = choice_ids(); - - let (first, retired) = QuestionImage::new(&exam, &question, None, png(), 3) - .upsert(&db) - .await - .unwrap(); - assert_eq!(retired, None, "a first upload retires no blob"); - let (second, retired) = QuestionImage::new(&exam, &question, None, png(), 5) - .upsert(&db) - .await - .unwrap(); - // Same slot, same row — the replace swapped the blob pointer, and the - // write itself names the blob the caller must unlink. - assert_ne!(first.get_file(), second.get_file()); - assert_eq!(retired.as_deref(), Some(first.get_file())); - let rows = QuestionImage::list_for_question(&question, &db) - .await - .unwrap(); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].get_size(), 5); - - // A choice slot is its own row, keyed by the option's id. - QuestionImage::new(&exam, &question, Some(&ids[0]), png(), 7) - .upsert(&db) - .await - .unwrap(); - assert_eq!( - QuestionImage::list_for_question(&question, &db) - .await - .unwrap() - .len(), - 2 - ); - let choice = QuestionImage::read_slot(&question, Some(&ids[0]), &db) - .await - .unwrap() - .unwrap(); - assert_eq!(choice.get_slot(), Some(&ids[0])); - assert!( - QuestionImage::read_slot(&question, Some(&ids[1]), &db) - .await - .unwrap() - .is_none() - ); - } - - /// The behaviour the whole remodel exists for: an edit that keeps some - /// options keeps exactly their pictures, and drops only the removed one's. - #[tokio::test] - async fn only_the_dropped_options_lose_their_pictures() { - let db = crate::database::init_mem().await.unwrap(); - let exam = exam_row(&db).await; - let question = ExamQuestionId::generate(); - let ids = choice_ids(); - QuestionImage::new(&exam, &question, None, png(), 1) - .upsert(&db) - .await - .unwrap(); - for id in &ids { - QuestionImage::new(&exam, &question, Some(id), png(), 1) - .upsert(&db) - .await - .unwrap(); - } - - // Keep the first and last option (reordered — order is irrelevant now). - let keep = vec![ids[2].clone(), ids[0].clone()]; - let dropped = QuestionImage::delete_choices_not_in(&question, &keep, &db) - .await - .unwrap(); - assert_eq!(dropped.len(), 1); - assert_eq!(dropped[0].get_slot(), Some(&ids[1])); - - let left = QuestionImage::list_for_question(&question, &db) - .await - .unwrap(); - // The question illustration plus the two surviving option pictures. - assert_eq!(left.len(), 3); - assert!( - QuestionImage::read_slot(&question, Some(&ids[0]), &db) - .await - .unwrap() - .is_some() - ); - assert!( - QuestionImage::read_slot(&question, Some(&ids[2]), &db) - .await - .unwrap() - .is_some() - ); - assert!( - QuestionImage::read_slot(&question, None, &db) - .await - .unwrap() - .is_some() - ); - } - - #[tokio::test] - async fn an_empty_keep_set_clears_every_option_picture_but_not_the_illustration() { - let db = crate::database::init_mem().await.unwrap(); - let exam = exam_row(&db).await; - let question = ExamQuestionId::generate(); - let ids = choice_ids(); - QuestionImage::new(&exam, &question, None, png(), 1) - .upsert(&db) - .await - .unwrap(); - for id in &ids[..2] { - QuestionImage::new(&exam, &question, Some(id), png(), 1) - .upsert(&db) - .await - .unwrap(); - } - - let dropped = QuestionImage::delete_choices_not_in(&question, &[], &db) - .await - .unwrap(); - assert_eq!(dropped.len(), 2); - assert!(dropped.iter().all(|image| image.get_slot().is_some())); - - let left = QuestionImage::list_for_question(&question, &db) - .await - .unwrap(); - assert_eq!(left.len(), 1); - assert_eq!(left[0].get_slot(), None); - } - - #[tokio::test] - async fn exam_listing_scopes_by_exam() { - let db = crate::database::init_mem().await.unwrap(); - let exam_a = exam_row(&db).await; - let exam_b = exam_row(&db).await; - QuestionImage::new(&exam_a, &ExamQuestionId::generate(), None, png(), 1) - .upsert(&db) - .await - .unwrap(); - assert_eq!( - QuestionImage::list_for_exam(&exam_a, &db) - .await - .unwrap() - .len(), - 1 - ); - assert!( - QuestionImage::list_for_exam(&exam_b, &db) - .await - .unwrap() - .is_empty() - ); - } } diff --git a/src/domain/session_attendance.rs b/src/domain/session_attendance.rs index 57ced1c..12eec10 100644 --- a/src/domain/session_attendance.rs +++ b/src/domain/session_attendance.rs @@ -106,7 +106,7 @@ impl SessionAttendance { /// route 404ing on the vanished session while the attendance report went /// on counting it. A deleted session reads NONE, which is falsy, so the /// gate is written as an explicit `IS NONE` (see - /// [`crate::domain::exam_result::ExamResult::grade`]). It reads the + /// [`crate::db::exam_result::grade`]). It reads the /// session's `teacher` — required on every row, so NONE means "no row" just /// as `id` did — because the counter below needs that teacher anyway, and /// one read serves both. @@ -115,7 +115,7 @@ impl SessionAttendance { /// sets, not read sets, so that gate alone only closes the *sequential* /// order (delete committed, then the mark arrives). To make the two really /// collide, this transaction also *writes* the session row, unconditionally - /// — the bump-and-restore of [`crate::domain::exam_answer::ExamAnswer::save`] + /// — the bump-and-restore of [`crate::db::exam_answer::save`] /// on the one column this write already owns, [`LESSON_COUNTED_AT_FIELD`]. /// Unconditional is the whole point: the credit branch below writes that /// column already, but it fires only for the first roll call of a lesson diff --git a/src/service/answer_image.rs b/src/service/answer_image.rs new file mode 100644 index 0000000..f0a3fde --- /dev/null +++ b/src/service/answer_image.rs @@ -0,0 +1,46 @@ +//! The drawn-answer workflows: the doors the web layer takes for every +//! answer-image read and write. The blob I/O and its disk ordering stay in +//! the web layer; the row transactions live in [`crate::db::answer_image`]. + +use crate::database::Database; +use crate::db; +use crate::domain::answer_image::AnswerImage; +use crate::domain::exam::ExamId; +use crate::domain::exam_question::ExamQuestionId; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Create or replace the student's drawing for the question, handing back +/// what it stored plus the blob name it replaced, for the caller to take +/// off disk. +pub async fn upsert( + db: &Database, + image: AnswerImage, +) -> Result<(AnswerImage, Option), AppError> { + db::answer_image::upsert(db, image).await +} + +/// The student's drawing for one question in one sitting, if any. +pub async fn read( + db: &Database, + question: &ExamQuestionId, + user: &UserId, + seq: i64, +) -> Result, AppError> { + db::answer_image::read(db, question, user, seq).await +} + +/// Drop one drawing — the returned row names the blob to unlink. +pub async fn delete(db: &Database, image: AnswerImage) -> Result { + db::answer_image::delete(db, image).await +} + +/// One student's answer drawings for a single sitting. +pub async fn list_for_exam_user( + db: &Database, + exam: &ExamId, + user: &UserId, + seq: i64, +) -> Result, AppError> { + db::answer_image::list_for_exam_user(db, exam, user, seq).await +} diff --git a/src/service/course.rs b/src/service/course.rs index df515be..5784626 100644 --- a/src/service/course.rs +++ b/src/service/course.rs @@ -6,11 +6,9 @@ use crate::database::Database; use crate::db::course; -use crate::domain::answer_image::AnswerImage; use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; use crate::domain::course_note_file::CourseNoteFile; use crate::domain::homework_file::HomeworkFile; -use crate::domain::question_image::QuestionImage; use crate::domain::role::Role; use crate::domain::term::{self, TermId}; use crate::domain::user::UserId; @@ -165,8 +163,9 @@ pub async fn delete(db: &Database, course: &Course) -> Result Result Result, + text: Option, +) -> Result { + db::exam_answer::save(db, question, user, seq, selected, text).await +} + +/// One student's stored answer for a question in sitting `seq`, if any. +pub async fn read( + db: &Database, + question: &ExamQuestionId, + user: &UserId, + seq: i64, +) -> Result, AppError> { + db::exam_answer::read(db, question, user, seq).await +} + +/// Drop one student's answer to a single question in sitting `seq`. +pub async fn delete( + db: &Database, + question: &ExamQuestionId, + user: &UserId, + seq: i64, +) -> Result<(), AppError> { + db::exam_answer::delete(db, question, user, seq).await +} + +/// One student's answers for a single sitting (`seq`) across an exam. +pub async fn list_for_exam_user( + db: &Database, + exam: &ExamId, + user: &UserId, + seq: i64, +) -> Result, AppError> { + db::exam_answer::list_for_exam_user(db, exam, user, seq).await +} + +/// Every answer of an exam — the live monitor aggregates these per student. +pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result, AppError> { + db::exam_answer::list_for_exam(db, exam).await +} + +/// The distinct sittings a student has any answer for at `exam`, ascending +/// — the index a history view lists attempts from. +pub async fn list_seqs_for_user( + db: &Database, + exam: &ExamId, + user: &UserId, +) -> Result, AppError> { + db::exam_answer::list_seqs_for_user(db, exam, user).await +} diff --git a/src/service/exam_attempt.rs b/src/service/exam_attempt.rs index 604bd41..6e4c25e 100644 --- a/src/service/exam_attempt.rs +++ b/src/service/exam_attempt.rs @@ -385,13 +385,13 @@ pub async fn save_answer_in( crate::service::course::require_open(db, &course_of(exam, db).await?).await?; let question = crate::service::exam_question::question_of_exam(exam.get_id(), question_id, db).await?; - crate::domain::exam_answer::ExamAnswer::save( + crate::db::exam_answer::save( + db, &question, attempt.get_user(), attempt.get_seq(), selected, text, - db, ) .await } @@ -465,10 +465,10 @@ pub async fn set_left( mod tests { use super::*; use crate::database::init_mem; + use crate::db::exam_answer; use crate::domain::exam::{ ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, }; - use crate::domain::exam_answer::ExamAnswer; use crate::domain::exam_question::{ ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, }; @@ -665,13 +665,13 @@ mod tests { let (first, created) = start(&db, &exam, &user).await.unwrap(); assert!(created); assert_eq!(first.get_seq(), 1); - ExamAnswer::save( + exam_answer::save( + &db, &question, &user, 1, Some(second_choice(&question)), None, - &db, ) .await .unwrap(); @@ -683,12 +683,12 @@ mod tests { assert_eq!(second.get_seq(), 2); // Sitting #1's answer is still there, read at its own seq. - let prior = ExamAnswer::read(question.get_id(), &user, 1, &db) + let prior = exam_answer::read(&db, question.get_id(), &user, 1) .await .unwrap(); assert!(prior.is_some(), "the retake must preserve seq 1's answer"); // The new sitting starts blank at its own seq. - let fresh = ExamAnswer::list_for_exam_user(exam.get_id(), &user, 2, &db) + let fresh = exam_answer::list_for_exam_user(&db, exam.get_id(), &user, 2) .await .unwrap(); assert!(fresh.is_empty(), "seq 2 starts blank"); @@ -706,13 +706,13 @@ mod tests { let (winner, created) = start(&db, &exam, &user).await.unwrap(); assert!(created); assert_eq!(winner.get_seq(), 2); - ExamAnswer::save( + exam_answer::save( + &db, &question, &user, 2, Some(second_choice(&question)), None, - &db, ) .await .unwrap(); @@ -732,7 +732,7 @@ mod tests { let lost: Result, surrealdb::Error> = db.create(loser.id.record()).content(loser).await; assert!(lost.is_err(), "the duplicate-seq create must be rejected"); - let answers = ExamAnswer::list_for_exam_user(exam.get_id(), &user, 2, &db) + let answers = exam_answer::list_for_exam_user(&db, exam.get_id(), &user, 2) .await .unwrap(); assert_eq!( diff --git a/src/service/exam_result.rs b/src/service/exam_result.rs new file mode 100644 index 0000000..a826ff9 --- /dev/null +++ b/src/service/exam_result.rs @@ -0,0 +1,167 @@ +//! Exam-mark workflows: the grading gate chain under the exam subsystem's +//! reader lease, ungrading behind the archived-term gate, and the read doors +//! the web layer takes. The mark's own claim-riding transaction lives in +//! [`crate::db::exam_result`]. + +use crate::database::Database; +use crate::db; +use crate::domain::badge; +use crate::domain::course::CourseId; +use crate::domain::exam::{Exam, ExamId}; +use crate::domain::exam_result::{ExamResult, Mark}; +use crate::domain::role::Role; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::service::exam_attempt::{EXAM_LOCK, course_of, read_latest_for_user}; + +/// Grade a student's current sitting: every wall the handler used to run +/// (draft, retired kind, self-grade, target existence/role/enrollment), then +/// the mark's own transaction. +/// +/// *Reader* lease of [`EXAM_LOCK`] from the exam read through the result +/// write: the draft gate below must be judged against the same row the +/// mark lands under, or a concurrent re-draft (a writer, which checks for +/// results) could slip between them and leave a mark on a hidden exam. The +/// mark's transaction re-makes the draft check inside the store, so the +/// pre-flight here answers the same `409` one round trip earlier. +/// +/// The kind gate is the settings-list twin of the counter's retired bit: +/// `kind_ref`'s bit is what actually refuses the mark inside +/// [`db::exam_result::grade`], and it is a *different record* from the +/// list — a settings PATCH moves both, so anything that leaves them +/// disagreeing (a rolled-back retirement, a hand edit) would otherwise +/// reopen grading under a kind nobody lists, which is also a mark that +/// averages at weight 1 forever. Both gates, same answer; this one is a +/// read, the counter's is the one that survives a race. +/// +/// `mark` arrives raw because its range check is deliberately sequenced +/// *after* the draft and kind gates — validation order is observable. +/// +/// Both sides of the grade moved a counter — the grader's `marks_given`, +/// the student's `high_mark` — so both are brought up to date. A badge is a +/// decoration on top of the mark: losing one to a transient database error +/// must never fail the grading, and the next counter move heals it. +pub async fn grade( + db: &Database, + exam_id: &ExamId, + grader: &UserId, + target: &UserId, + mark: i64, +) -> Result { + // Reader lease of [`EXAM_LOCK`] — see above. + let _guard = EXAM_LOCK.read().await; + // Exam must exist. + let exam = crate::service::exam::read(db, exam_id) + .await? + .ok_or(AppError::NotFound)?; + crate::service::course::require_open(db, &course_of(&exam, db).await?).await?; + // Pre-flight: `db::exam_result::grade` re-makes this check inside the + // mark's own transaction, so a re-draft landing after this read cannot + // leave a mark on a hidden exam. + if exam.is_draft() { + return Err(crate::domain::exam_result::draft_error()); + } + let kind = exam.get_kind().as_str(); + if !crate::service::settings::load(db) + .await? + .get_exam_kinds() + .iter() + .any(|offered| offered.get_name() == kind) + { + return Err(crate::domain::exam_result::retired_kind_error(kind)); + } + + let mark = Mark::try_new(mark)?; + + // Grading never targets oneself — no grader, whatever their role, may + // write their own mark. + if target == grader { + return Err(AppError::Forbidden("grading yourself is not allowed")); + } + + // Target user must exist. + let Some(target_user) = crate::service::user::read(db, target).await? else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user does not exist", + })); + }; + + // Only students carry marks — the grade system is theirs alone. A stale + // enrollment left behind by a promotion can't reopen grading for staff. + if target_user.get_role() != Role::Student { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "only students can be graded", + })); + } + + // ... and be enrolled in the exam's course. + if crate::service::enrollment::read_for_user(db, exam.get_course(), target) + .await? + .is_none() + { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user is not enrolled in this course", + })); + } + + // The mark lands on the student's current sitting; the latest seq is the + // grade-of-record. An offline-graded exam has no sitting — grade its base + // seq (1). + let seq = read_latest_for_user(db, exam_id, target) + .await? + .map_or(1, |a| a.get_seq()); + let result = db::exam_result::grade(db, exam_id, target, seq, mark, grader, kind).await?; + for person in [grader, target] { + if let Err(err) = badge::sync(person, db).await { + tracing::warn!("failed to sync badges for {}: {err}", person.key()); + } + } + Ok(result) +} + +/// Remove a student's results from an exam — every sitting's marks at once, +/// behind the archived-term gate. `NotFound` mapping stays with the caller. +pub async fn remove( + db: &Database, + exam: &Exam, + target: &UserId, +) -> Result, AppError> { + crate::service::course::require_open(db, &course_of(exam, db).await?).await?; + db::exam_result::remove(db, exam.get_id(), target, exam.get_kind().as_str()).await +} + +/// A single user's result for an exam, if graded. +pub async fn read_for_user( + db: &Database, + exam: &ExamId, + user: &UserId, +) -> Result, AppError> { + db::exam_result::read_for_user(db, exam, user).await +} + +/// An exam's graded results, deduped to the latest mark per (exam, user). +pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result, AppError> { + db::exam_result::list_for_exam(db, exam).await +} + +/// Every sitting's mark for one (exam, user) pair, oldest first. +pub async fn list_all_for_exam_user( + db: &Database, + exam: &ExamId, + user: &UserId, +) -> Result, AppError> { + db::exam_result::list_all_for_exam_user(db, exam, user).await +} + +/// The user's graded results restricted to one course's exams — the raw +/// rows behind the per-course block of the marks report. +pub async fn list_for_user_in_course( + db: &Database, + course: &CourseId, + user: &UserId, +) -> Result, AppError> { + db::exam_result::list_for_user_in_course(db, course, user).await +} diff --git a/src/service/mod.rs b/src/service/mod.rs index 691aa94..7137e71 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -1,6 +1,7 @@ //! Business rules, workflow locks, multi-call orchestration; calls db::*; no //! SurrealQL text. +pub mod answer_image; pub mod appointment; pub mod appointment_slot; pub mod class_blueprint; @@ -8,11 +9,14 @@ pub mod course; pub mod course_session; pub mod enrollment; pub mod exam; +pub mod exam_answer; pub mod exam_attempt; pub mod exam_question; +pub mod exam_result; pub mod meal_booking; pub mod note; pub mod payment_ledger; +pub mod question_image; pub mod session; pub mod settings; pub mod user; diff --git a/src/service/question_image.rs b/src/service/question_image.rs new file mode 100644 index 0000000..8c21e36 --- /dev/null +++ b/src/service/question_image.rs @@ -0,0 +1,58 @@ +//! The question-image workflows: the doors the web layer takes for every +//! question/choice image read and write. The blob I/O and its disk ordering +//! stay in the web layer; the row transactions (behind the question-freeze +//! gate) live in [`crate::db::question_image`]. + +use crate::database::Database; +use crate::db; +use crate::domain::exam::ExamId; +use crate::domain::exam_question::{ChoiceId, ExamQuestionId}; +use crate::domain::question_image::QuestionImage; +use crate::error::AppError; + +/// Create or replace the slot's image row, handing back what it stored plus +/// the blob name it replaced, for the caller to take off disk. +pub async fn upsert( + db: &Database, + image: QuestionImage, +) -> Result<(QuestionImage, Option), AppError> { + db::question_image::upsert(db, image).await +} + +/// The slot's image row, if any (`slot = None` is the question's +/// illustration). +pub async fn read_slot( + db: &Database, + question: &ExamQuestionId, + slot: Option<&ChoiceId>, +) -> Result, AppError> { + db::question_image::read_slot(db, question, slot).await +} + +/// Every image of the exam's questions — one query for the list views. +pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result, AppError> { + db::question_image::list_for_exam(db, exam).await +} + +/// Every image of one question — the illustration plus its option pictures. +pub async fn list_for_question( + db: &Database, + question: &ExamQuestionId, +) -> Result, AppError> { + db::question_image::list_for_question(db, question).await +} + +/// Drop the option pictures whose choice is gone, returning the removed rows +/// so the caller can take their blobs off disk. +pub async fn delete_choices_not_in( + db: &Database, + question: &ExamQuestionId, + keep: &[ChoiceId], +) -> Result, AppError> { + db::question_image::delete_choices_not_in(db, question, keep).await +} + +/// Drop one image row — the returned row names the blob to unlink. +pub async fn delete(db: &Database, image: QuestionImage) -> Result { + db::question_image::delete(db, image).await +} diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 7209a82..6baa446 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -66,7 +66,6 @@ use serde_json::{Value, json}; use crate::constant::{EXAM_WS_TICK_SECS, MAX_QUESTION_ID_LEN}; 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::timestamp::Timestamp; use crate::domain::user::UserId; @@ -337,10 +336,14 @@ async fn state_frame( let remaining_ms = (status == AttemptStatus::InProgress) .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0))) .flatten(); - let answered = - ExamAnswer::list_for_exam_user(exam.get_id(), attempt.get_user(), attempt.get_seq(), db) - .await? - .len(); + let answered = crate::service::exam_answer::list_for_exam_user( + db, + exam.get_id(), + attempt.get_user(), + attempt.get_seq(), + ) + .await? + .len(); let question_count = crate::service::exam_question::list_for_exam(db, exam.get_id(), None, 0) .await? .0 diff --git a/src/web/exams/attempts.rs b/src/web/exams/attempts.rs index 9735232..04f7f15 100644 --- a/src/web/exams/attempts.rs +++ b/src/web/exams/attempts.rs @@ -102,7 +102,7 @@ pub(crate) async fn attempt_progress( seq: i64, db: &Database, ) -> Result<(u64, u64), AppError> { - let answered = ExamAnswer::list_for_exam_user(exam, user, seq, db) + let answered = crate::service::exam_answer::list_for_exam_user(db, exam, user, seq) .await? .len() as u64; let question_count = crate::service::exam_question::list_for_exam(db, exam, None, 0) @@ -142,7 +142,7 @@ pub(crate) async fn start_attempt( ) -> Result<(StatusCode, Json), AppError> { let (exam, attempt, created) = exam_attempt::start_attempt(&st.db, &ExamId::from_key(&id), &user).await?; - let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) + let mark = crate::service::exam_result::read_for_user(&st.db, exam.get_id(), user.get_id()) .await? .map(|r| r.get_mark()); let (answered, question_count) = @@ -195,7 +195,7 @@ pub(crate) async fn my_attempt( let attempt = exam_attempt::read_latest_for_user(&st.db, exam.get_id(), user.get_id()) .await? .ok_or(AppError::NotFound)?; - let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) + let mark = crate::service::exam_result::read_for_user(&st.db, exam.get_id(), user.get_id()) .await? .map(|r| r.get_mark()); let (answered, question_count) = @@ -239,7 +239,7 @@ pub(crate) async fn finish_attempt( .await? .ok_or(AppError::NotFound)?; let finished = exam_attempt::finish_attempt(&st.db, &exam, user.get_id()).await?; - let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) + let mark = crate::service::exam_result::read_for_user(&st.db, exam.get_id(), user.get_id()) .await? .map(|r| r.get_mark()); let (answered, question_count) = @@ -347,7 +347,7 @@ pub(crate) async fn live_snapshot( } } } - let marks: HashMap = ExamResult::list_for_exam(exam.get_id(), db) + let marks: HashMap = crate::service::exam_result::list_for_exam(db, exam.get_id()) .await? .iter() .map(|result| { @@ -367,7 +367,7 @@ pub(crate) async fn live_snapshot( // seq to their latest attempt — or a re-sitting student's count would // double up their prior attempts. let mut progress: HashMap = HashMap::new(); - for answer in ExamAnswer::list_for_exam(exam.get_id(), db).await? { + for answer in crate::service::exam_answer::list_for_exam(db, exam.get_id()).await? { let key = answer.get_user().key().to_string(); if attempts.get(&key).map(ExamAttempt::get_seq) != Some(answer.get_seq()) { continue; @@ -588,13 +588,13 @@ pub(crate) async fn attempt_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) + crate::service::exam_answer::list_for_exam_user(&st.db, exam.get_id(), user.get_id(), seq) .await? .into_iter() .map(|answer| (answer.get_question().key().to_string(), answer)) .collect(); let answer_images: HashMap = - AnswerImage::list_for_exam_user(exam.get_id(), user.get_id(), seq, &st.db) + crate::service::answer_image::list_for_exam_user(&st.db, exam.get_id(), user.get_id(), seq) .await? .into_iter() .map(|image| (image.get_question().key().to_string(), image)) @@ -748,9 +748,10 @@ pub(crate) async fn answer_sheet( 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 answers = + crate::service::exam_answer::list_for_exam_user(db, exam.get_id(), target, seq).await?; let answer_images: HashMap = - AnswerImage::list_for_exam_user(exam.get_id(), target, seq, db) + crate::service::answer_image::list_for_exam_user(db, exam.get_id(), target, seq) .await? .into_iter() .map(|image| (image.get_question().key().to_string(), image)) diff --git a/src/web/exams/images.rs b/src/web/exams/images.rs index 6941ae5..c442c23 100644 --- a/src/web/exams/images.rs +++ b/src/web/exams/images.rs @@ -69,7 +69,7 @@ pub(crate) async fn images_by_question( db: &Database, ) -> Result>, AppError> { let mut buckets: HashMap> = HashMap::new(); - for image in QuestionImage::list_for_exam(exam, db).await? { + for image in crate::service::question_image::list_for_exam(db, exam).await? { buckets .entry(image.get_question().key().to_string()) .or_default() @@ -151,7 +151,10 @@ pub(crate) async fn store_image( data.len() as i64, ); let file = image.get_file().to_string(); - store_blob(st, &file, data, || async { image.upsert(&st.db).await }).await + store_blob(st, &file, data, || async { + crate::service::question_image::upsert(&st.db, image).await + }) + .await } /// The stored bytes, served inline via [`crate::web::serve_inline_blob`]. @@ -237,7 +240,7 @@ pub(crate) async fn get_question_image( .ok_or(AppError::NotFound)?; ensure_question_content_visible(&st, &exam, &user).await?; let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - let image = QuestionImage::read_slot(question.get_id(), None, &st.db) + let image = crate::service::question_image::read_slot(&st.db, question.get_id(), None) .await? .ok_or(AppError::NotFound)?; serve_image(&st, &image).await @@ -270,10 +273,10 @@ pub(crate) async fn delete_question_image( let exam = image_managed_exam(&st, &user, &id).await?; ensure_questions_editable(exam.get_id(), &st.db).await?; let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - let image = QuestionImage::read_slot(question.get_id(), None, &st.db) + let image = crate::service::question_image::read_slot(&st.db, question.get_id(), None) .await? .ok_or(AppError::NotFound)?; - let image = image.delete(&st.db).await?; + let image = crate::service::question_image::delete(&st.db, image).await?; remove_blob(&st.files_path, image.get_file()).await; Ok(StatusCode::NO_CONTENT) } @@ -350,7 +353,7 @@ pub(crate) async fn get_choice_image( ensure_question_content_visible(&st, &exam, &user).await?; let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; let slot = choice_slot(&question, &choice_id)?; - let image = QuestionImage::read_slot(question.get_id(), Some(&slot), &st.db) + let image = crate::service::question_image::read_slot(&st.db, question.get_id(), Some(&slot)) .await? .ok_or(AppError::NotFound)?; serve_image(&st, &image).await @@ -385,10 +388,10 @@ pub(crate) async fn delete_choice_image( ensure_questions_editable(exam.get_id(), &st.db).await?; let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; let slot = choice_slot(&question, &choice_id)?; - let image = QuestionImage::read_slot(question.get_id(), Some(&slot), &st.db) + let image = crate::service::question_image::read_slot(&st.db, question.get_id(), Some(&slot)) .await? .ok_or(AppError::NotFound)?; - let image = image.delete(&st.db).await?; + let image = crate::service::question_image::delete(&st.db, image).await?; remove_blob(&st.files_path, image.get_file()).await; Ok(StatusCode::NO_CONTENT) } @@ -424,7 +427,10 @@ pub(crate) async fn store_answer_image( data.len() as i64, ); let file = image.get_file().to_string(); - store_blob(st, &file, data, || async { image.upsert(&st.db).await }).await + store_blob(st, &file, data, || async { + crate::service::answer_image::upsert(&st.db, image).await + }) + .await } /// Attach (or replace) the caller's drawn answer to a question inside their @@ -498,17 +504,17 @@ pub(crate) async fn upload_answer_image( // UI only offers drawing on text questions), so they are skipped. Removing // the drawing later grooms this blank row away (see `delete_answer_image`). if question.get_kind().as_str() != "choice" - && ExamAnswer::read(question.get_id(), user.get_id(), seq, &st.db) + && crate::service::exam_answer::read(&st.db, question.get_id(), user.get_id(), seq) .await? .is_none() { - ExamAnswer::save( + crate::service::exam_answer::save( + &st.db, &question, user.get_id(), seq, None, Some(String::new()), - &st.db, ) .await?; } @@ -554,19 +560,22 @@ pub(crate) async fn delete_answer_image( check_rejoin(&exam, &attempt)?; let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; let seq = attempt.get_seq(); - let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db) + let image = crate::service::answer_image::read(&st.db, question.get_id(), user.get_id(), seq) .await? .ok_or(AppError::NotFound)?; - let image = image.delete(&st.db).await?; + let image = crate::service::answer_image::delete(&st.db, image).await?; remove_blob(&st.files_path, image.get_file()).await; // If the drawing was the whole answer (blank text, no choice — the row the // upload created for a drawing-only answer), drop it too so it stops counting // as answered. A typed answer keeps its row. - if let Some(answer) = ExamAnswer::read(question.get_id(), user.get_id(), seq, &st.db).await? { + if let Some(answer) = + crate::service::exam_answer::read(&st.db, question.get_id(), user.get_id(), seq).await? + { let blank = answer.get_selected().is_none() && answer.get_text().is_none_or(|t| t.as_str().is_empty()); if blank { - ExamAnswer::delete(question.get_id(), user.get_id(), seq, &st.db).await?; + crate::service::exam_answer::delete(&st.db, question.get_id(), user.get_id(), seq) + .await?; } } Ok(StatusCode::NO_CONTENT) @@ -605,7 +614,7 @@ pub(crate) async fn get_answer_image( .await? .ok_or(AppError::NotFound)? .get_seq(); - let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db) + let image = crate::service::answer_image::read(&st.db, question.get_id(), user.get_id(), seq) .await? .ok_or(AppError::NotFound)?; crate::web::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await @@ -652,7 +661,7 @@ pub(crate) async fn get_student_answer_image( .await? .ok_or(AppError::NotFound)? .get_seq(); - let image = AnswerImage::read(question.get_id(), &target, seq, &st.db) + let image = crate::service::answer_image::read(&st.db, question.get_id(), &target, seq) .await? .ok_or(AppError::NotFound)?; crate::web::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index 2569481..4ef8fa5 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -13,7 +13,6 @@ use utoipa_axum::routes; 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; use crate::domain::bank_question::{BankQuestion, BankQuestionId}; use crate::domain::bank_question_image::BankQuestionImage; @@ -32,7 +31,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, course_of, read_latest_for_user}; +use crate::service::exam_attempt::course_of; use crate::state::AppState; use super::bank_questions::BankQuestionResponse; @@ -525,12 +524,7 @@ async fn grade( Json(req): Json, ) -> Result, AppError> { let exam_id = ExamId::from_key(&id); - // Reader lease of [`EXAM_LOCK`] from the exam read through the result - // write: the draft gate below must be judged against the same row the - // mark lands under, or a concurrent re-draft (a writer, which checks for - // results) could slip between them and leave a mark on a hidden exam. - let _guard = EXAM_LOCK.read().await; - // Exam must exist. + // Exam must exist, and only a course manager may grade it. let exam = service::exam::read(&st.db, &exam_id) .await? .ok_or(AppError::NotFound)?; @@ -540,92 +534,18 @@ async fn grade( "only the course creator, an assigned teacher, or a manager/admin can grade this exam", )); } - crate::service::course::require_open(&st.db, &course).await?; - // Pre-flight: `ExamResult::grade` re-makes this check inside the mark's own - // transaction, so a re-draft landing after this read cannot leave a mark on - // a hidden exam. - if exam.is_draft() { - return Err(crate::domain::exam_result::draft_error()); - } - // The exam's kind must still be one the school offers. `kind_ref`'s retired - // bit is what actually refuses the mark inside `ExamResult::grade`, and it - // is a *different record* from the list — a settings PATCH moves both, so - // anything that leaves them disagreeing (a rolled-back retirement, a hand - // edit) would otherwise reopen grading under a kind nobody lists, which is - // also a mark that averages at weight 1 forever. Both gates, same answer; - // this one is a read, the counter's is the one that survives a race. - let kind = exam.get_kind().as_str(); - if !service::settings::load(&st.db) - .await? - .get_exam_kinds() - .iter() - .any(|offered| offered.get_name() == kind) - { - return Err(crate::domain::exam_result::retired_kind_error(kind)); - } - - let mark = Mark::try_new(req.mark)?; let target = UserId::from_key(&req.user_id); - - // Grading never targets oneself — no grader, whatever their role, may - // write their own mark. - if &target == teacher.get_id() { - return Err(AppError::Forbidden("grading yourself is not allowed")); - } - - // Target user must exist. - let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user_id", - reason: "target user does not exist", - })); - }; - - // Only students carry marks — the grade system is theirs alone. A stale - // enrollment left behind by a promotion can't reopen grading for staff. - if target_user.get_role() != Role::Student { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user_id", - reason: "only students can be graded", - })); - } - - // ... and be enrolled in the exam's course. - if service::enrollment::read_for_user(&st.db, exam.get_course(), &target) + // The workflow — the *reader* lease of [`EXAM_LOCK`] from the exam read + // through the result write (so a concurrent re-draft cannot slip a mark + // onto a hidden exam), the draft and kind pre-flights, the + // grader/target walls, the sitting resolution, the mark's own + // transaction, and the badge sync — is + // [`crate::service::exam_result::grade`]'s. + let result = + service::exam_result::grade(&st.db, &exam_id, teacher.get_id(), &target, req.mark).await?; + let target_user = service::user::read(&st.db, &target) .await? - .is_none() - { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user_id", - reason: "target user is not enrolled in this course", - })); - } - - // The mark lands on the student's current sitting; the latest seq is the - // grade-of-record. An offline-graded exam has no sitting — grade its base - // seq (1). - let seq = read_latest_for_user(&st.db, &exam_id, &target) - .await? - .map_or(1, |a| a.get_seq()); - let result = ExamResult::grade( - &exam_id, - &target, - seq, - mark, - teacher.get_id(), - exam.get_kind().as_str(), - &st.db, - ) - .await?; - // Both sides of the grade moved a counter — the grader's `marks_given`, - // the student's `high_mark` — so both are brought up to date. A badge is a - // decoration on top of the mark: losing one to a transient database error - // must never fail the grading, and the next counter move heals it. - for person in [teacher.get_id(), &target] { - if let Err(err) = badge::sync(person, &st.db).await { - tracing::warn!("failed to sync badges for {}: {err}", person.key()); - } - } + .ok_or(AppError::NotFound)?; let people = PersonRef::map_of(&[&target_user, &teacher]); Ok(Json(ExamResultResponse::new(&result, &people))) } @@ -665,7 +585,7 @@ async fn list_results( "only the course creator, an assigned teacher, or a manager/admin can list results", )); } - let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?; + let results = service::exam_result::list_for_exam(&st.db, exam.get_id()).await?; let total = results.len() as i64; // Join people onto the page alone — the lookup shrinks with the window. // Paged in the web layer: the list is deduped to the latest mark per @@ -703,7 +623,7 @@ async fn my_result( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { - let result = ExamResult::read_for_user(&ExamId::from_key(&id), user.get_id(), &st.db) + let result = service::exam_result::read_for_user(&st.db, &ExamId::from_key(&id), user.get_id()) .await? .ok_or(AppError::NotFound)?; let people = person_map( @@ -747,14 +667,9 @@ async fn remove_result( "only the course creator, an assigned teacher, or a manager/admin can remove results", )); } - crate::service::course::require_open(&st.db, &course).await?; - let removed = ExamResult::remove( - exam.get_id(), - &UserId::from_key(&target), - exam.get_kind().as_str(), - &st.db, - ) - .await?; + // The archived-term gate and the refunding delete are + // [`crate::service::exam_result::remove`]'s. + let removed = service::exam_result::remove(&st.db, &exam, &UserId::from_key(&target)).await?; if removed.is_none() { return Err(AppError::NotFound); } @@ -791,7 +706,7 @@ async fn exam_statistics( "only the course creator, an assigned teacher, or a manager/admin can view statistics", )); } - let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?; + let results = service::exam_result::list_for_exam(&st.db, exam.get_id()).await?; let marks: Vec = results.iter().map(|r| r.get_mark().as_i64()).collect(); let average = diff --git a/src/web/exams/questions.rs b/src/web/exams/questions.rs index 5e46570..da1e618 100644 --- a/src/web/exams/questions.rs +++ b/src/web/exams/questions.rs @@ -359,10 +359,14 @@ pub(crate) async fn update_question( .iter() .map(|choice| choice.get_id().clone()) .collect(); - for image in QuestionImage::delete_choices_not_in(updated.get_id(), &keep, &st.db).await? { + for image in + crate::service::question_image::delete_choices_not_in(&st.db, updated.get_id(), &keep) + .await? + { remove_blob(&st.files_path, image.get_file()).await; } - let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?; + let images = + crate::service::question_image::list_for_question(&st.db, updated.get_id()).await?; Ok(Json(QuestionResponse::new(&updated, &images))) } @@ -406,7 +410,8 @@ pub(crate) async fn delete_question( 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?; + let images = + crate::service::question_image::list_for_question(&st.db, question.get_id()).await?; exam_question::delete(&st.db, question).await?; for image in &images { remove_blob(&st.files_path, image.get_file()).await; @@ -536,7 +541,8 @@ pub(crate) async fn question_from_bank( } } } - let images = QuestionImage::list_for_question(question.get_id(), &st.db).await?; + let images = + crate::service::question_image::list_for_question(&st.db, question.get_id()).await?; Ok(( StatusCode::CREATED, Json(QuestionResponse::new(&question, &images)), @@ -662,12 +668,13 @@ pub(crate) async fn question_refresh_from_bank( // `store_image` upserts per slot, so a slot both sides have is replaced. let incoming_slots: Vec> = incoming.iter().map(|(image, _)| image.get_slot()).collect(); - for stale in QuestionImage::list_for_question(updated.get_id(), &st.db).await? { + for stale in crate::service::question_image::list_for_question(&st.db, updated.get_id()).await? + { if incoming_slots.contains(&stale.get_slot()) { continue; } let file = stale.get_file().to_string(); - stale.delete(&st.db).await?; + crate::service::question_image::delete(&st.db, stale).await?; remove_blob(&st.files_path, &file).await; } for (source, bytes) in &incoming { @@ -682,7 +689,8 @@ pub(crate) async fn question_refresh_from_bank( .await?; } - let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?; + let images = + crate::service::question_image::list_for_question(&st.db, updated.get_id()).await?; Ok(Json(QuestionResponse::new(&updated, &images))) } @@ -751,7 +759,8 @@ pub(crate) async fn question_to_bank( // mid-loop failure rolls back the fresh bank row (cascade drops the copied // image rows) and the blobs written so far; the source exam question stays // untouched. - let sources = QuestionImage::list_for_question(question.get_id(), &st.db).await?; + let sources = + crate::service::question_image::list_for_question(&st.db, question.get_id()).await?; let mut copied: Vec = Vec::new(); for source in &sources { let step = async { diff --git a/src/web/exams/review.rs b/src/web/exams/review.rs index a0861fb..f99c175 100644 --- a/src/web/exams/review.rs +++ b/src/web/exams/review.rs @@ -50,8 +50,11 @@ pub(crate) async fn student_attempts( ) -> Result>, AppError> { let exam = gradable_exam(&st, &user, &id).await?; let target = UserId::from_key(&target); - let mut seqs = ExamAnswer::list_seqs_for_user(exam.get_id(), &target, &st.db).await?; - for result in ExamResult::list_all_for_exam_user(exam.get_id(), &target, &st.db).await? { + let mut seqs = + crate::service::exam_answer::list_seqs_for_user(&st.db, exam.get_id(), &target).await?; + for result in + crate::service::exam_result::list_all_for_exam_user(&st.db, exam.get_id(), &target).await? + { seqs.push(result.get_seq()); } seqs.sort_unstable(); @@ -121,7 +124,7 @@ pub(crate) async fn student_attempt_answer_image( let exam = gradable_exam(&st, &user, &id).await?; let target = UserId::from_key(&target); 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) + let image = crate::service::answer_image::read(&st.db, question.get_id(), &target, seq) .await? .ok_or(AppError::NotFound)?; crate::web::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await @@ -153,7 +156,8 @@ pub(crate) async fn student_marks_history( ) -> Result>, AppError> { let exam = gradable_exam(&st, &user, &id).await?; let target = UserId::from_key(&target); - let results = ExamResult::list_all_for_exam_user(exam.get_id(), &target, &st.db).await?; + let results = + crate::service::exam_result::list_all_for_exam_user(&st.db, exam.get_id(), &target).await?; let people = person_map( results .iter() @@ -208,7 +212,7 @@ pub(crate) async fn reviewable_exam( if exam.is_draft() { return Err(AppError::NotFound); } - ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) + crate::service::exam_result::read_for_user(&st.db, exam.get_id(), user.get_id()) .await? .ok_or(AppError::NotFound)?; if !exam.get_allow_review() { @@ -302,8 +306,11 @@ pub(crate) async fn review_attempts( ) -> Result>, AppError> { let exam = reviewable_exam(&st, &user, &id).await?; let target = user.get_id().clone(); - let mut seqs = ExamAnswer::list_seqs_for_user(exam.get_id(), &target, &st.db).await?; - for result in ExamResult::list_all_for_exam_user(exam.get_id(), &target, &st.db).await? { + let mut seqs = + crate::service::exam_answer::list_seqs_for_user(&st.db, exam.get_id(), &target).await?; + for result in + crate::service::exam_result::list_all_for_exam_user(&st.db, exam.get_id(), &target).await? + { seqs.push(result.get_seq()); } seqs.sort_unstable(); @@ -417,7 +424,7 @@ pub(crate) async fn review_attempt_answer_image( ) -> Result { let exam = reviewable_exam(&st, &user, &id).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) + let image = crate::service::answer_image::read(&st.db, question.get_id(), user.get_id(), seq) .await? .ok_or(AppError::NotFound)?; crate::web::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await diff --git a/src/web/marks.rs b/src/web/marks.rs index 901bdf4..2f9af1f 100644 --- a/src/web/marks.rs +++ b/src/web/marks.rs @@ -11,7 +11,6 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::exam::Exam; -use crate::domain::exam_result::ExamResult; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse}; @@ -110,7 +109,8 @@ async fn build_report( 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?; + let results = + crate::service::exam_result::list_for_user_in_course(db, course.get_id(), user).await?; let mut entries = Vec::with_capacity(results.len()); let mut pairs = Vec::with_capacity(results.len()); for result in &results { diff --git a/tests/integration.rs b/tests/integration.rs index 65a4ac1..9ccf1c8 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -9631,8 +9631,8 @@ async fn live_monitor_tracks_answer_progress() { #[tokio::test] async fn questions_and_answers_cascade_with_deletes() { + use hezarfen_backend::db::exam_answer; use hezarfen_backend::db::exam_question; - use hezarfen_backend::domain::exam_answer::ExamAnswer; let (app, db) = app_and_db().await; let teacher = login_as(&app, &db, "qc_t", "teacher").await; @@ -9691,7 +9691,7 @@ async fn questions_and_answers_cascade_with_deletes() { 2 ); assert_eq!( - ExamAnswer::list_for_exam(&exam_id, &db) + exam_answer::list_for_exam(&db, &exam_id) .await .unwrap() .len(), @@ -9736,7 +9736,7 @@ async fn questions_and_answers_cascade_with_deletes() { 1 ); assert_eq!( - ExamAnswer::list_for_exam(&exam_id, &db) + exam_answer::list_for_exam(&db, &exam_id) .await .unwrap() .len(), @@ -9762,7 +9762,7 @@ async fn questions_and_answers_cascade_with_deletes() { .is_empty() ); assert!( - ExamAnswer::list_for_exam(&exam_id, &db) + exam_answer::list_for_exam(&db, &exam_id) .await .unwrap() .is_empty() @@ -9826,7 +9826,7 @@ async fn questions_and_answers_cascade_with_deletes() { .is_empty() ); assert!( - ExamAnswer::list_for_exam(&exam2_id, &db) + exam_answer::list_for_exam(&db, &exam2_id) .await .unwrap() .is_empty()