Split exam_answer/exam_result/answer_image/question_image into domain/db/service layers
Browse files at this commit61990de60876b283f046a54ae2106a6c57d5e4c7Parent: 387eb31- chore
- split exam_answer/exam_result/answer_image/question_image into domain/db/service layers
34 changed files +2402 -2064
- src/db/answer_image.rs +320 -0
- src/db/cap.rs +1 -1
- src/db/exam.rs +31 -25
- src/db/exam_answer.rs +362 -0
- src/db/exam_attempt.rs +1 -1
- src/db/exam_result.rs +802 -0
- src/db/mod.rs +4 -0
- src/db/question_image.rs +332 -0
- src/domain/answer_image.rs +15 -340
- src/domain/attendance.rs +2 -2
- src/domain/chatbot_thread.rs +1 -1
- src/domain/class_pump.rs +1 -1
- src/domain/exam_answer.rs +10 -322
- src/domain/exam_result.rs +34 -828
- src/domain/homework_submission.rs +2 -2
- src/domain/pool_question.rs +1 -1
- src/domain/question_image.rs +13 -359
- src/domain/session_attendance.rs +2 -2
- src/service/answer_image.rs +46 -0
- src/service/course.rs +3 -4
- src/service/exam.rs +6 -6
- src/service/exam_answer.rs +71 -0
- src/service/exam_attempt.rs +10 -10
- src/service/exam_result.rs +167 -0
- src/service/mod.rs +4 -0
- src/service/question_image.rs +58 -0
- src/web/exam_ws.rs +8 -5
- src/web/exams/attempts.rs +11 -10
- src/web/exams/images.rs +27 -18
- src/web/exams/mod.rs +18 -103
- src/web/exams/questions.rs +17 -8
- src/web/exams/review.rs +15 -8
- src/web/marks.rs +2 -2
- tests/integration.rs +5 -5
src/db/answer_image.rsadded+320 -0
| @@ -0,0 +1,320 @@ | ||
| 1 | +//! The `answer_image` table: the drawing upsert that names the blob it | |
| 2 | +//! replaces from inside its own transaction, the per-sitting and per-exam | |
| 3 | +//! reads, and the sweeps the retake and cascades use. The row's pure half — | |
| 4 | +//! ids and the fresh-blob-name constructor — lives in | |
| 5 | +//! [`crate::domain::answer_image`]; the blob bytes stay the web layer's. | |
| 6 | + | |
| 7 | +use surrealdb::types::SurrealValue; | |
| 8 | + | |
| 9 | +use crate::constant::EXAM_RESULT_COUNT_FIELD; | |
| 10 | +use crate::database::{Database, transaction_with_retry}; | |
| 11 | +use crate::domain::answer_image::{AnswerImage, AnswerImageId}; | |
| 12 | +use crate::domain::course::CourseId; | |
| 13 | +use crate::domain::exam::ExamId; | |
| 14 | +use crate::domain::exam_question::ExamQuestionId; | |
| 15 | +use crate::domain::user::UserId; | |
| 16 | +use crate::error::AppError; | |
| 17 | + | |
| 18 | +/// What one [`upsert`] transaction returns: the row it stored and | |
| 19 | +/// the blob name it replaced. Both are arrays because SurrealDB drops an object | |
| 20 | +/// key valued `NONE` on the way out, while an empty array survives — "nothing | |
| 21 | +/// was replaced" has to be readable, not missing. | |
| 22 | +#[derive(SurrealValue)] | |
| 23 | +struct UpsertOutcome { | |
| 24 | + stored: Vec<AnswerImage>, | |
| 25 | + replaced: Vec<String>, | |
| 26 | +} | |
| 27 | + | |
| 28 | +/// Create or replace the student's drawing for the question — the | |
| 29 | +/// deterministic id makes this the whole "one drawing per student per | |
| 30 | +/// question" story — handing back what it stored plus the blob name it | |
| 31 | +/// replaced, for the caller to take off disk. | |
| 32 | +/// | |
| 33 | +/// The replaced name is read *here*, inside this transaction, not by the | |
| 34 | +/// caller in front of it: two uploads to one (question, user, seq) both | |
| 35 | +/// write this row, so they contend and the loser re-reads the winner's blob | |
| 36 | +/// name, where two pre-reads both saw the *old* blob and left the loser's | |
| 37 | +/// fresh one on disk with nothing pointing at it. Same shape as | |
| 38 | +/// [`crate::db::question_image::upsert`]. | |
| 39 | +/// | |
| 40 | +/// `NotFound` = the exam is gone, and the drawing was *not* written. The | |
| 41 | +/// write moves the exam's mark counter and puts it straight back, in this | |
| 42 | +/// one transaction, so the exam's existence is something this write | |
| 43 | +/// *writes* rather than something a gate read a moment earlier: a bare | |
| 44 | +/// upsert landing after [`delete`](crate::db::exam::delete) | |
| 45 | +/// removed the exam but before it committed was swept by nothing — its | |
| 46 | +/// `DELETE answer_image WHERE exam = $ex` ran on a snapshot predating this | |
| 47 | +/// row — and both sides reported success. That stranded the blob as well as | |
| 48 | +/// the row: `delete_exam` collects the names to unlink *before* it calls | |
| 49 | +/// the delete, so bytes written after that snapshot stay on disk forever. | |
| 50 | +/// This is the shape [`crate::db::exam_answer::save`] takes | |
| 51 | +/// for the text half of the same answer sheet, and for the same reason. | |
| 52 | +/// | |
| 53 | +/// The restore is by captured value, `NONE` included, so the row is | |
| 54 | +/// byte-identical afterwards and a teacher's PATCH — which pins that | |
| 55 | +/// counter — is not refused because a student drew. Writing the same value | |
| 56 | +/// back would buy nothing: an `UPDATE` that leaves the document unchanged | |
| 57 | +/// is elided and never reaches the store's write set. | |
| 58 | +/// | |
| 59 | +/// Admissible for [`transaction_with_retry`]: the `UPDATE`s, `SELECT`, | |
| 60 | +/// `IF`/`THROW` and `RETURN` can never answer "already exists", and the | |
| 61 | +/// `UPSERT`'s id is bijective with the (question, user, seq) triple this | |
| 62 | +/// table keys — a lost round wrote nothing, and re-sending resolves onto | |
| 63 | +/// the same row rather than colliding with it. | |
| 64 | +pub async fn upsert( | |
| 65 | + db: &Database, | |
| 66 | + image: AnswerImage, | |
| 67 | +) -> Result<(AnswerImage, Option<String>), AppError> { | |
| 68 | + // 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 | |
| 69 | + let (exam, id) = (image.exam.record(), image.id.record()); | |
| 70 | + let (mut result, mut errors) = transaction_with_retry( | |
| 71 | + db, | |
| 72 | + &format!( | |
| 73 | + "BEGIN TRANSACTION; | |
| 74 | + LET $was = (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $ex); | |
| 75 | + LET $touched = (UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = \ | |
| 76 | + ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); | |
| 77 | + IF array::len($touched) = 0 {{ THROW 'no_exam' }}; | |
| 78 | + UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = $was; | |
| 79 | + LET $replaced = (SELECT VALUE file FROM $id); | |
| 80 | + LET $row = (UPSERT $id CONTENT $image RETURN AFTER); | |
| 81 | + RETURN {{ stored: $row, replaced: $replaced }}; | |
| 82 | + COMMIT TRANSACTION;" | |
| 83 | + ), | |
| 84 | + &[ | |
| 85 | + ("ex".into(), exam.into_value()), | |
| 86 | + ("id".into(), id.into_value()), | |
| 87 | + ("image".into(), image.into_value()), | |
| 88 | + ], | |
| 89 | + &["no_exam"], | |
| 90 | + ) | |
| 91 | + .await?; | |
| 92 | + // An aborted transaction errors *every* slot, most with a generic "not | |
| 93 | + // executed" — only the THROW's own slot names the reason. | |
| 94 | + if errors | |
| 95 | + .values() | |
| 96 | + .any(|error| error.to_string().contains("no_exam")) | |
| 97 | + { | |
| 98 | + return Err(AppError::NotFound); | |
| 99 | + } | |
| 100 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | |
| 101 | + return Err(error.into()); | |
| 102 | + } | |
| 103 | + // The trailing `RETURN` is the last statement before `COMMIT`, so its | |
| 104 | + // slot follows the statement count rather than a hand-kept number; | |
| 105 | + // `num_statements` counts BEGIN and COMMIT. | |
| 106 | + let slot = result.num_statements().saturating_sub(2); | |
| 107 | + let failed = || AppError::Internal("failed to store answer image".into()); | |
| 108 | + let outcome = result | |
| 109 | + .take::<Vec<UpsertOutcome>>(slot)? | |
| 110 | + .into_iter() | |
| 111 | + .next() | |
| 112 | + .ok_or_else(failed)?; | |
| 113 | + let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; | |
| 114 | + Ok((stored, outcome.replaced.into_iter().next())) | |
| 115 | +} | |
| 116 | + | |
| 117 | +/// The student's drawing for one question in one sitting, if any. | |
| 118 | +pub async fn read( | |
| 119 | + db: &Database, | |
| 120 | + question: &ExamQuestionId, | |
| 121 | + user: &UserId, | |
| 122 | + seq: i64, | |
| 123 | +) -> Result<Option<AnswerImage>, AppError> { | |
| 124 | + Ok(db | |
| 125 | + .select(AnswerImageId::composite(question, user, seq).record()) | |
| 126 | + .await?) | |
| 127 | +} | |
| 128 | + | |
| 129 | +/// Every answer drawing of the exam — one query for the exam-delete cascade. | |
| 130 | +pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<AnswerImage>, AppError> { | |
| 131 | + let mut result = db | |
| 132 | + .query("SELECT * FROM answer_image WHERE exam = $ex") | |
| 133 | + .bind(("ex", exam.record())) | |
| 134 | + .await? | |
| 135 | + .check()?; | |
| 136 | + Ok(result.take::<Vec<AnswerImage>>(0)?) | |
| 137 | +} | |
| 138 | + | |
| 139 | +/// One student's answer drawings for a single sitting — the parallel to | |
| 140 | +/// [`crate::db::exam_answer::list_for_exam_user`], feeding | |
| 141 | +/// the sitting/grading answer-image maps for that attempt's `seq`. | |
| 142 | +pub async fn list_for_exam_user( | |
| 143 | + db: &Database, | |
| 144 | + exam: &ExamId, | |
| 145 | + user: &UserId, | |
| 146 | + seq: i64, | |
| 147 | +) -> Result<Vec<AnswerImage>, AppError> { | |
| 148 | + let mut result = db | |
| 149 | + .query("SELECT * FROM answer_image WHERE exam = $ex AND user = $usr AND seq = $seq") | |
| 150 | + .bind(("ex", exam.record())) | |
| 151 | + .bind(("usr", user.record())) | |
| 152 | + .bind(("seq", seq)) | |
| 153 | + .await? | |
| 154 | + .check()?; | |
| 155 | + Ok(result.take::<Vec<AnswerImage>>(0)?) | |
| 156 | +} | |
| 157 | + | |
| 158 | +/// The distinct sittings (`seq`, ascending) this student has any answer | |
| 159 | +/// drawing for at this exam — the history index behind a per-attempt view. | |
| 160 | +pub async fn list_seqs_for_user( | |
| 161 | + db: &Database, | |
| 162 | + exam: &ExamId, | |
| 163 | + user: &UserId, | |
| 164 | +) -> Result<Vec<i64>, AppError> { | |
| 165 | + let mut result = db | |
| 166 | + .query( | |
| 167 | + "SELECT VALUE seq FROM answer_image \ | |
| 168 | + WHERE exam = $ex AND user = $usr ORDER BY seq", | |
| 169 | + ) | |
| 170 | + .bind(("ex", exam.record())) | |
| 171 | + .bind(("usr", user.record())) | |
| 172 | + .await? | |
| 173 | + .check()?; | |
| 174 | + let mut seqs = result.take::<Vec<i64>>(0)?; | |
| 175 | + seqs.dedup(); | |
| 176 | + Ok(seqs) | |
| 177 | +} | |
| 178 | + | |
| 179 | +/// The blob names behind every answer drawing of every exam of `course` — | |
| 180 | +/// collected *before* the course-delete cascade wipes the rows. | |
| 181 | +pub async fn file_keys_for_course( | |
| 182 | + db: &Database, | |
| 183 | + course: &CourseId, | |
| 184 | +) -> Result<Vec<String>, AppError> { | |
| 185 | + let mut result = db | |
| 186 | + .query( | |
| 187 | + "SELECT VALUE file FROM answer_image \ | |
| 188 | + WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)", | |
| 189 | + ) | |
| 190 | + .bind(("course", course.record())) | |
| 191 | + .await? | |
| 192 | + .check()?; | |
| 193 | + Ok(result.take::<Vec<String>>(0)?) | |
| 194 | +} | |
| 195 | + | |
| 196 | +pub async fn delete(db: &Database, image: AnswerImage) -> Result<AnswerImage, AppError> { | |
| 197 | + let deleted: Option<AnswerImage> = db.delete(image.id.record()).await?; | |
| 198 | + deleted.ok_or(AppError::NotFound) | |
| 199 | +} | |
| 200 | + | |
| 201 | +/// Drop one student's answer drawings across an exam — a retake starts from | |
| 202 | +/// a blank sheet. Rows only; the caller GCs the blobs. The retake path itself | |
| 203 | +/// wipes rows inside `ExamAttempt::wipe_and_create`'s transaction; this is | |
| 204 | +/// the standalone mirror of [`crate::db::exam_answer::delete_for_exam_user`]. | |
| 205 | +pub async fn delete_for_exam_user( | |
| 206 | + db: &Database, | |
| 207 | + exam: &ExamId, | |
| 208 | + user: &UserId, | |
| 209 | +) -> Result<(), AppError> { | |
| 210 | + db.query("DELETE answer_image WHERE exam = $ex AND user = $usr") | |
| 211 | + .bind(("ex", exam.record())) | |
| 212 | + .bind(("usr", user.record())) | |
| 213 | + .await? | |
| 214 | + .check()?; | |
| 215 | + Ok(()) | |
| 216 | +} | |
| 217 | + | |
| 218 | +#[cfg(test)] | |
| 219 | +mod tests { | |
| 220 | + use super::*; | |
| 221 | + use crate::domain::note_file::FileContentType; | |
| 222 | + | |
| 223 | + fn png() -> FileContentType { | |
| 224 | + FileContentType::try_new("image/png").unwrap() | |
| 225 | + } | |
| 226 | + | |
| 227 | + /// A real exam row: a drawing's write moves its exam's counter (that is | |
| 228 | + /// what keeps it from outliving the exam), so a minted id nothing wrote is | |
| 229 | + /// a 404. | |
| 230 | + async fn exam_row(db: &Database) -> ExamId { | |
| 231 | + crate::db::exam::published_exam(db).await.get_id().clone() | |
| 232 | + } | |
| 233 | + | |
| 234 | + fn student() -> UserId { | |
| 235 | + UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA") | |
| 236 | + } | |
| 237 | + | |
| 238 | + #[tokio::test] | |
| 239 | + async fn upsert_replaces_within_a_sitting_but_not_across_them() { | |
| 240 | + let db = crate::database::init_mem().await.unwrap(); | |
| 241 | + let exam = exam_row(&db).await; | |
| 242 | + let question = ExamQuestionId::generate(); | |
| 243 | + let user = student(); | |
| 244 | + | |
| 245 | + let (first, retired) = upsert(&db, AnswerImage::new(&exam, &question, &user, 1, png(), 3)) | |
| 246 | + .await | |
| 247 | + .unwrap(); | |
| 248 | + assert_eq!(retired, None, "a first upload retires no blob"); | |
| 249 | + let (second, retired) = upsert(&db, AnswerImage::new(&exam, &question, &user, 1, png(), 5)) | |
| 250 | + .await | |
| 251 | + .unwrap(); | |
| 252 | + // Same (question, user, seq), same row — the replace swapped the blob, | |
| 253 | + // and the write itself names the blob the caller must unlink. | |
| 254 | + assert_ne!(first.get_file(), second.get_file()); | |
| 255 | + assert_eq!(retired.as_deref(), Some(first.get_file())); | |
| 256 | + let rows = list_for_exam_user(&db, &exam, &user, 1).await.unwrap(); | |
| 257 | + assert_eq!(rows.len(), 1); | |
| 258 | + assert_eq!(rows[0].get_size(), 5); | |
| 259 | + | |
| 260 | + // A retake (seq 2) accumulates: it is its own row, not an overwrite. | |
| 261 | + upsert(&db, AnswerImage::new(&exam, &question, &user, 2, png(), 9)) | |
| 262 | + .await | |
| 263 | + .unwrap(); | |
| 264 | + assert_eq!( | |
| 265 | + list_for_exam_user(&db, &exam, &user, 1) | |
| 266 | + .await | |
| 267 | + .unwrap() | |
| 268 | + .len(), | |
| 269 | + 1, | |
| 270 | + "the seq-2 image must not overwrite seq-1" | |
| 271 | + ); | |
| 272 | + assert_eq!( | |
| 273 | + list_for_exam_user(&db, &exam, &user, 2).await.unwrap()[0].get_size(), | |
| 274 | + 9 | |
| 275 | + ); | |
| 276 | + assert_eq!( | |
| 277 | + list_seqs_for_user(&db, &exam, &user).await.unwrap(), | |
| 278 | + vec![1, 2] | |
| 279 | + ); | |
| 280 | + | |
| 281 | + // Another student's drawing for the same question/sitting is its own row. | |
| 282 | + let other = UserId::from_key("01TESTSTUDENTBBBBBBBBBBBBB"); | |
| 283 | + upsert(&db, AnswerImage::new(&exam, &question, &other, 1, png(), 7)) | |
| 284 | + .await | |
| 285 | + .unwrap(); | |
| 286 | + assert_eq!(list_for_exam(&db, &exam).await.unwrap().len(), 3); | |
| 287 | + assert!(read(&db, &question, &user, 2).await.unwrap().is_some()); | |
| 288 | + } | |
| 289 | + | |
| 290 | + #[tokio::test] | |
| 291 | + async fn listing_scopes_by_exam_and_user() { | |
| 292 | + let db = crate::database::init_mem().await.unwrap(); | |
| 293 | + let exam_a = exam_row(&db).await; | |
| 294 | + let exam_b = exam_row(&db).await; | |
| 295 | + let user = student(); | |
| 296 | + upsert( | |
| 297 | + &db, | |
| 298 | + AnswerImage::new(&exam_a, &ExamQuestionId::generate(), &user, 1, png(), 1), | |
| 299 | + ) | |
| 300 | + .await | |
| 301 | + .unwrap(); | |
| 302 | + assert_eq!( | |
| 303 | + list_for_exam_user(&db, &exam_a, &user, 1) | |
| 304 | + .await | |
| 305 | + .unwrap() | |
| 306 | + .len(), | |
| 307 | + 1 | |
| 308 | + ); | |
| 309 | + assert!(list_for_exam(&db, &exam_b).await.unwrap().is_empty()); | |
| 310 | + | |
| 311 | + // delete_for_exam_user clears the student's sheet across all sittings. | |
| 312 | + delete_for_exam_user(&db, &exam_a, &user).await.unwrap(); | |
| 313 | + assert!( | |
| 314 | + list_for_exam_user(&db, &exam_a, &user, 1) | |
| 315 | + .await | |
| 316 | + .unwrap() | |
| 317 | + .is_empty() | |
| 318 | + ); | |
| 319 | + } | |
| 320 | +} |
src/db/cap.rsmodified+1 -1
| @@ -387,7 +387,7 @@ const GONE_MARK: &str = "cap_gone"; | ||
| 387 | 387 | /// write set: `SET x = x` sits on no key at all and collides with nothing |
| 388 | 388 | /// (measured on 3.2.3, and the reason |
| 389 | 389 | /// [`crate::domain::class_pump::Axis::pivot_claim`] and |
| 390 | -/// [`crate::domain::exam_answer::ExamAnswer::save`] have the same shape). Both | |
| 390 | +/// [`crate::db::exam_answer::save`] have the same shape). Both | |
| 391 | 391 | /// statements are inside the transaction, so an abort between them cannot leave |
| 392 | 392 | /// the counter up. |
| 393 | 393 | /// |
src/db/exam.rsmodified+31 -25
| @@ -165,7 +165,7 @@ pub async fn update_if_unchanged( | ||
| 165 | 165 | // |
| 166 | 166 | // Sent through the retry loop, not a bare `query`: this row now has a |
| 167 | 167 | // hot writer. Every answer save touches it to tie itself to the exam |
| 168 | - // ([`crate::domain::exam_answer::ExamAnswer::save`]), so a teacher | |
| 168 | + // ([`crate::db::exam_answer::save`]), so a teacher | |
| 169 | 169 | // flipping `allow_rejoin` mid-exam can lose a round to a student |
| 170 | 170 | // typing — and a lost round is a re-send, never the 500 a bare `?` on |
| 171 | 171 | // the conflict would have answered. Re-sending is sound because the |
| @@ -308,7 +308,7 @@ use crate::domain::settings::ExamKindDef; | ||
| 308 | 308 | /// An unscheduled published exam — the minimum any test that writes a *child* |
| 309 | 309 | /// of an exam needs, in any module: every such write moves the exam row (see |
| 310 | 310 | /// [`crate::db::exam_attempt::write_unfrozen_with`] |
| 311 | -/// and [`crate::domain::exam_answer::ExamAnswer::save`]), so a minted id whose | |
| 311 | +/// and [`crate::db::exam_answer::save`]), so a minted id whose | |
| 312 | 312 | /// row was never created is a 404 rather than a silent orphan. |
| 313 | 313 | #[cfg(test)] |
| 314 | 314 | pub(crate) async fn published_exam(db: &Database) -> Exam { |
| @@ -450,18 +450,19 @@ mod tests { | ||
| 450 | 450 | /// exam from being hidden. |
| 451 | 451 | #[tokio::test] |
| 452 | 452 | async fn re_drafting_is_refused_by_the_write_itself_once_a_mark_exists() { |
| 453 | - use crate::domain::exam_result::{ExamResult, Mark}; | |
| 453 | + use crate::db::exam_result; | |
| 454 | + use crate::domain::exam_result::Mark; | |
| 454 | 455 | let db = crate::database::init_mem().await.unwrap(); |
| 455 | 456 | let exam = published(&db).await; |
| 456 | 457 | let student = UserId::generate(); |
| 457 | - ExamResult::grade( | |
| 458 | + exam_result::grade( | |
| 459 | + &db, | |
| 458 | 460 | exam.get_id(), |
| 459 | 461 | &student, |
| 460 | 462 | 1, |
| 461 | 463 | Mark::try_new(80).unwrap(), |
| 462 | 464 | &UserId::generate(), |
| 463 | 465 | exam.get_kind().as_str(), |
| 464 | - &db, | |
| 465 | 466 | ) |
| 466 | 467 | .await |
| 467 | 468 | .unwrap(); |
| @@ -603,7 +604,7 @@ mod tests { | ||
| 603 | 604 | /// genuine conflict can be masked by a sibling, and either way there is no |
| 604 | 605 | /// [`crate::database::lost_the_race`] check and no retry. |
| 605 | 606 | /// |
| 606 | - /// The racer is a mark: [`ExamResult::grade`] claims the exam's own | |
| 607 | + /// The racer is a mark: [`crate::db::exam_result::grade`] claims the exam's own | |
| 607 | 608 | /// `result_count` (and the kind's reference) before writing, so it contends |
| 608 | 609 | /// with the `DELETE $ex` and with the kind_ref decrement inside the same |
| 609 | 610 | /// transaction. A round where *some* of the six grades 404 and the rest |
| @@ -625,7 +626,8 @@ mod tests { | ||
| 625 | 626 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 626 | 627 | #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] |
| 627 | 628 | async fn a_delete_racing_a_mark_never_answers_500() { |
| 628 | - use crate::domain::exam_result::{ExamResult, Mark}; | |
| 629 | + use crate::db::exam_result; | |
| 630 | + use crate::domain::exam_result::Mark; | |
| 629 | 631 | let (db, _serialized) = crate::database::init_test_server("exam_delete_race").await; |
| 630 | 632 | let (mut delete_500, mut grade_500) = (0, 0); |
| 631 | 633 | let (mut split, mut swept) = (0, 0); |
| @@ -655,14 +657,14 @@ mod tests { | ||
| 655 | 657 | let (id, db, kind) = (exam.get_id().clone(), db.clone(), kind.clone()); |
| 656 | 658 | let student = UserId::from_key(&format!("stu{round}_{seat}")); |
| 657 | 659 | tokio::spawn(async move { |
| 658 | - ExamResult::grade( | |
| 660 | + exam_result::grade( | |
| 661 | + &db, | |
| 659 | 662 | &id, |
| 660 | 663 | &student, |
| 661 | 664 | 1, |
| 662 | 665 | Mark::try_new(50).unwrap(), |
| 663 | 666 | &UserId::from_key("teacher"), |
| 664 | 667 | &kind, |
| 665 | - &db, | |
| 666 | 668 | ) |
| 667 | 669 | .await |
| 668 | 670 | }) |
| @@ -693,7 +695,7 @@ mod tests { | ||
| 693 | 695 | if (1..6).contains(&refused) { |
| 694 | 696 | split += 1; |
| 695 | 697 | } |
| 696 | - if ExamResult::list_for_exam(exam.get_id(), &db) | |
| 698 | + if exam_result::list_for_exam(&db, exam.get_id()) | |
| 697 | 699 | .await |
| 698 | 700 | .unwrap() |
| 699 | 701 | .is_empty() |
| @@ -774,7 +776,7 @@ mod tests { | ||
| 774 | 776 | /// would not do it — the read sees a row [`crate::db::exam::delete`] has removed but |
| 775 | 777 | /// not committed, while its `DELETE exam_answer WHERE exam = $ex` swept a |
| 776 | 778 | /// snapshot predating the save, so both commit and the answer is left |
| 777 | - /// pointing at an exam that is gone. [`ExamAnswer::save`] writes the exam | |
| 779 | + /// pointing at an exam that is gone. [`crate::db::exam_answer::save`] writes the exam | |
| 778 | 780 | /// row instead (its `result_count`, back unchanged), so the two transactions |
| 779 | 781 | /// touch one key and the store refuses one of them. |
| 780 | 782 | /// |
| @@ -797,7 +799,7 @@ mod tests { | ||
| 797 | 799 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 798 | 800 | #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] |
| 799 | 801 | async fn an_answer_written_inside_a_delete_never_outlives_the_exam() { |
| 800 | - use crate::domain::exam_answer::ExamAnswer; | |
| 802 | + use crate::db::exam_answer; | |
| 801 | 803 | let (db, _serialized) = crate::database::init_test_server("exam_answer_race").await; |
| 802 | 804 | // Hold the delete open for a full second after the row is gone, while |
| 803 | 805 | // its cascade still has to run. |
| @@ -833,7 +835,7 @@ mod tests { | ||
| 833 | 835 | let child = { |
| 834 | 836 | let (db, question, student) = (db.clone(), question.clone(), student.clone()); |
| 835 | 837 | tokio::spawn(async move { |
| 836 | - ExamAnswer::save(&question, &student, 1, Some(pick), None, &db).await | |
| 838 | + exam_answer::save(&db, &question, &student, 1, Some(pick), None).await | |
| 837 | 839 | }) |
| 838 | 840 | }; |
| 839 | 841 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| @@ -847,7 +849,7 @@ mod tests { | ||
| 847 | 849 | // Stored state is the whole verdict; a return value is not evidence. |
| 848 | 850 | if read(&db, &id).await.unwrap().is_none() { |
| 849 | 851 | swept += 1; |
| 850 | - answers += ExamAnswer::list_for_exam(&id, &db).await.unwrap().len(); | |
| 852 | + answers += exam_answer::list_for_exam(&db, &id).await.unwrap().len(); | |
| 851 | 853 | } else if drop_it.is_ok() { |
| 852 | 854 | panic!("round {round}: the delete reported success but the exam is still there"); |
| 853 | 855 | } |
| @@ -976,7 +978,7 @@ mod tests { | ||
| 976 | 978 | } |
| 977 | 979 | |
| 978 | 980 | /// The student's half of the same picture problem: a drawing is a bare |
| 979 | - /// `UPSERT` — the exact pre-fix shape of [`ExamAnswer::save`] — so it kept | |
| 981 | + /// `UPSERT` — the exact pre-fix shape of [`crate::db::exam_answer::save`] — so it kept | |
| 980 | 982 | /// the hole the text answer just lost, blob and all. |
| 981 | 983 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 982 | 984 | #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] |
| @@ -1008,16 +1010,15 @@ mod tests { | ||
| 1008 | 1010 | let child = { |
| 1009 | 1011 | let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone()); |
| 1010 | 1012 | tokio::spawn(async move { |
| 1011 | - AnswerImage::new( | |
| 1013 | + let image = AnswerImage::new( | |
| 1012 | 1014 | &exam_id, |
| 1013 | 1015 | &on, |
| 1014 | 1016 | &student, |
| 1015 | 1017 | 1, |
| 1016 | 1018 | FileContentType::try_new("image/png").unwrap(), |
| 1017 | 1019 | 3, |
| 1018 | - ) | |
| 1019 | - .upsert(&db) | |
| 1020 | - .await | |
| 1020 | + ); | |
| 1021 | + crate::db::answer_image::upsert(&db, image).await | |
| 1021 | 1022 | }) |
| 1022 | 1023 | }; |
| 1023 | 1024 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| @@ -1028,7 +1029,10 @@ mod tests { | ||
| 1028 | 1029 | |
| 1029 | 1030 | if read(&db, &id).await.unwrap().is_none() { |
| 1030 | 1031 | swept += 1; |
| 1031 | - drawings += AnswerImage::list_for_exam(&id, &db).await.unwrap().len(); | |
| 1032 | + drawings += crate::db::answer_image::list_for_exam(&db, &id) | |
| 1033 | + .await | |
| 1034 | + .unwrap() | |
| 1035 | + .len(); | |
| 1032 | 1036 | } else if drop_it.is_ok() { |
| 1033 | 1037 | panic!("round {round}: the delete reported success but the exam is still there"); |
| 1034 | 1038 | } |
| @@ -1075,15 +1079,14 @@ mod tests { | ||
| 1075 | 1079 | let child = { |
| 1076 | 1080 | let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone()); |
| 1077 | 1081 | tokio::spawn(async move { |
| 1078 | - QuestionImage::new( | |
| 1082 | + let image = QuestionImage::new( | |
| 1079 | 1083 | &exam_id, |
| 1080 | 1084 | &on, |
| 1081 | 1085 | None, |
| 1082 | 1086 | FileContentType::try_new("image/png").unwrap(), |
| 1083 | 1087 | 3, |
| 1084 | - ) | |
| 1085 | - .upsert(&db) | |
| 1086 | - .await | |
| 1088 | + ); | |
| 1089 | + crate::db::question_image::upsert(&db, image).await | |
| 1087 | 1090 | }) |
| 1088 | 1091 | }; |
| 1089 | 1092 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| @@ -1094,7 +1097,10 @@ mod tests { | ||
| 1094 | 1097 | |
| 1095 | 1098 | if read(&db, &id).await.unwrap().is_none() { |
| 1096 | 1099 | swept += 1; |
| 1097 | - images += QuestionImage::list_for_exam(&id, &db).await.unwrap().len(); | |
| 1100 | + images += crate::db::question_image::list_for_exam(&db, &id) | |
| 1101 | + .await | |
| 1102 | + .unwrap() | |
| 1103 | + .len(); | |
| 1098 | 1104 | } else if drop_it.is_ok() { |
| 1099 | 1105 | panic!("round {round}: the delete reported success but the exam is still there"); |
| 1100 | 1106 | } |
src/db/exam_answer.rsadded+362 -0
| @@ -0,0 +1,362 @@ | ||
| 1 | +//! The `exam_answer` table: the autosave upsert keyed by the (question, user, | |
| 2 | +//! seq) sitting triple, the per-sitting and per-exam reads, and the sweeps a | |
| 3 | +//! retake and the cascades use. The sitting key shape and the payload | |
| 4 | +//! validation's pure half live in [`crate::domain::exam_answer`]. | |
| 5 | + | |
| 6 | +use surrealdb::types::SurrealValue; | |
| 7 | + | |
| 8 | +use crate::constant::EXAM_RESULT_COUNT_FIELD; | |
| 9 | +use crate::database::{Database, transaction_with_retry}; | |
| 10 | +use crate::domain::exam::ExamId; | |
| 11 | +use crate::domain::exam_answer::{AnswerText, ExamAnswer, ExamAnswerId}; | |
| 12 | +use crate::domain::exam_question::{ExamQuestion, ExamQuestionId}; | |
| 13 | +use crate::domain::timestamp::Timestamp; | |
| 14 | +use crate::domain::user::UserId; | |
| 15 | +use crate::error::{AppError, ValidationError}; | |
| 16 | + | |
| 17 | +/// Save (or overwrite) `user`'s answer to `question` for sitting `seq` — | |
| 18 | +/// the one write path, shared by the REST handler and the WebSocket room. | |
| 19 | +/// The payload must match the question's kind: a choice question takes | |
| 20 | +/// `selected` (the id of one of its choices), a text question takes `text`. | |
| 21 | +/// The caller has already checked that the attempt is in progress. Keyed | |
| 22 | +/// by `seq`, so a retake's save is a new row, not an overwrite of an | |
| 23 | +/// earlier sitting's answer. | |
| 24 | +pub async fn save( | |
| 25 | + db: &Database, | |
| 26 | + question: &ExamQuestion, | |
| 27 | + user: &UserId, | |
| 28 | + seq: i64, | |
| 29 | + selected: Option<String>, | |
| 30 | + text: Option<String>, | |
| 31 | +) -> Result<ExamAnswer, AppError> { | |
| 32 | + let invalid = |field, reason| AppError::Validation(ValidationError::Invalid { field, reason }); | |
| 33 | + let (selected, text) = match question.get_kind().as_str() { | |
| 34 | + "choice" => { | |
| 35 | + if text.is_some() { | |
| 36 | + return Err(invalid( | |
| 37 | + "text", | |
| 38 | + "a choice question takes selected, not text", | |
| 39 | + )); | |
| 40 | + } | |
| 41 | + let Some(selected) = selected else { | |
| 42 | + return Err(invalid("selected", "required for a choice question")); | |
| 43 | + }; | |
| 44 | + // Membership, not a range: `selected` names an option by its | |
| 45 | + // stable id, so a reorder of the list can never repoint it. | |
| 46 | + let picked = question | |
| 47 | + .get_choices() | |
| 48 | + .unwrap_or_default() | |
| 49 | + .iter() | |
| 50 | + .find(|choice| choice.get_id().as_str() == selected) | |
| 51 | + .ok_or_else(|| invalid("selected", "must name one of the question's choices"))?; | |
| 52 | + (Some(picked.get_id().clone()), None) | |
| 53 | + } | |
| 54 | + _ => { | |
| 55 | + if selected.is_some() { | |
| 56 | + return Err(invalid( | |
| 57 | + "selected", | |
| 58 | + "a text question takes text, not selected", | |
| 59 | + )); | |
| 60 | + } | |
| 61 | + let Some(text) = text else { | |
| 62 | + return Err(invalid("text", "required for a text question")); | |
| 63 | + }; | |
| 64 | + (None, Some(AnswerText::try_new(&text)?)) | |
| 65 | + } | |
| 66 | + }; | |
| 67 | + let answer = ExamAnswer { | |
| 68 | + id: ExamAnswerId::composite(question.get_id(), user, seq), | |
| 69 | + exam: question.get_exam().clone(), | |
| 70 | + question: question.get_id().clone(), | |
| 71 | + user: user.clone(), | |
| 72 | + seq, | |
| 73 | + selected, | |
| 74 | + text, | |
| 75 | + updated_at: Timestamp::now(), | |
| 76 | + }; | |
| 77 | + // The save writes the *exam row* as well as the answer, in one | |
| 78 | + // transaction, and that is what ties the answer's fate to its exam: | |
| 79 | + // reading the exam does not survive [`crate::db::exam::delete`]'s | |
| 80 | + // window — a save landing after its `DELETE exam_answer WHERE exam = $ex` | |
| 81 | + // but before the commit reads an exam that is still there (uncommitted) | |
| 82 | + // while the sweep ran on a snapshot predating this row, so both commit | |
| 83 | + // and the answer outlives the exam (measured 4 of 4 raced rounds). | |
| 84 | + // Writing the key the delete removes makes the two collide, and the | |
| 85 | + // store refuses one of them. It is the shape | |
| 86 | + // [`crate::domain::menu::bump_menu_and_write`] uses, and the one a mark | |
| 87 | + // already uses on this very row | |
| 88 | + // ([`crate::db::exam_result::grade`]). | |
| 89 | + // | |
| 90 | + // The bump-and-restore is not a flourish, it is the whole instrument. | |
| 91 | + // The exam carries no revision to bump and must not grow one — its save | |
| 92 | + // is a whole-row `CONTENT` write, so a column this struct did not know | |
| 93 | + // about would be wiped by the next PATCH — so this touches the one | |
| 94 | + // counter it already has and puts it back. Writing the *same* value is | |
| 95 | + // not enough: an `UPDATE` that leaves the document unchanged is elided | |
| 96 | + // and never reaches the store's write set, which the race test proved | |
| 97 | + // (green on the raced delete, red the moment the value moves for real). | |
| 98 | + // The restore is by captured value, `NONE` included, so the row is | |
| 99 | + // byte-identical afterwards: the boot backfill still finds the rows it | |
| 100 | + // keys on (`WHERE result_count = NONE`), the PATCH's | |
| 101 | + // `(result_count ?? 0) = $was_results` still passes, and no teacher's | |
| 102 | + // edit is refused because a student typed. Both statements are inside | |
| 103 | + // the transaction, so a crash between them cannot leave the counter up. | |
| 104 | + // No `cap::counter_lock` either: no counter moves here, and the hottest | |
| 105 | + // write path in the app should not queue behind one. | |
| 106 | + // | |
| 107 | + // Admissible for `transaction_with_retry`: the `UPDATE`s, `SELECT`, | |
| 108 | + // `IF`/`THROW` and `RETURN` can never answer "already exists", and the | |
| 109 | + // `UPSERT`'s id is bijective with the (question, user, seq) triple | |
| 110 | + // `exam_answer` keys — a lost round wrote nothing, and re-sending | |
| 111 | + // resolves onto the same row rather than colliding with it. | |
| 112 | + let (mut result, mut errors) = transaction_with_retry( | |
| 113 | + db, | |
| 114 | + &format!( | |
| 115 | + "BEGIN TRANSACTION; | |
| 116 | + LET $was = (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $ex); | |
| 117 | + LET $touched = (UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = \ | |
| 118 | + ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); | |
| 119 | + IF array::len($touched) = 0 {{ THROW 'no_exam' }}; | |
| 120 | + UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = $was; | |
| 121 | + LET $row = (UPSERT $id CONTENT $answer RETURN AFTER); | |
| 122 | + RETURN $row[0]; | |
| 123 | + COMMIT TRANSACTION;" | |
| 124 | + ), | |
| 125 | + &[ | |
| 126 | + ("ex".into(), answer.exam.record().into_value()), | |
| 127 | + ("id".into(), answer.id.record().into_value()), | |
| 128 | + ("answer".into(), answer.into_value()), | |
| 129 | + ], | |
| 130 | + &["no_exam"], | |
| 131 | + ) | |
| 132 | + .await?; | |
| 133 | + // An aborted transaction errors *every* slot, most with a generic "not | |
| 134 | + // executed" — only the THROW's own slot names the reason. | |
| 135 | + if errors | |
| 136 | + .values() | |
| 137 | + .any(|error| error.to_string().contains("no_exam")) | |
| 138 | + { | |
| 139 | + return Err(AppError::NotFound); | |
| 140 | + } | |
| 141 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | |
| 142 | + return Err(error.into()); | |
| 143 | + } | |
| 144 | + // The trailing `RETURN` is the last statement before `COMMIT`, so its | |
| 145 | + // slot follows the statement count rather than a hand-kept number (the | |
| 146 | + // `db::exam::delete` treatment); `num_statements` counts BEGIN and COMMIT. | |
| 147 | + let slot = result.num_statements().saturating_sub(2); | |
| 148 | + result | |
| 149 | + .take::<Vec<ExamAnswer>>(slot)? | |
| 150 | + .into_iter() | |
| 151 | + .next() | |
| 152 | + .ok_or_else(|| AppError::Internal("failed to save exam answer".into())) | |
| 153 | +} | |
| 154 | + | |
| 155 | +/// One student's stored answer for a question in sitting `seq`, if any. | |
| 156 | +pub async fn read( | |
| 157 | + db: &Database, | |
| 158 | + question: &ExamQuestionId, | |
| 159 | + user: &UserId, | |
| 160 | + seq: i64, | |
| 161 | +) -> Result<Option<ExamAnswer>, AppError> { | |
| 162 | + Ok(db | |
| 163 | + .select(ExamAnswerId::composite(question, user, seq).record()) | |
| 164 | + .await?) | |
| 165 | +} | |
| 166 | + | |
| 167 | +/// Drop one student's answer to a single question in sitting `seq`. | |
| 168 | +pub async fn delete( | |
| 169 | + db: &Database, | |
| 170 | + question: &ExamQuestionId, | |
| 171 | + user: &UserId, | |
| 172 | + seq: i64, | |
| 173 | +) -> Result<(), AppError> { | |
| 174 | + let _: Option<ExamAnswer> = db | |
| 175 | + .delete(ExamAnswerId::composite(question, user, seq).record()) | |
| 176 | + .await?; | |
| 177 | + Ok(()) | |
| 178 | +} | |
| 179 | + | |
| 180 | +/// One student's answers for a single sitting (`seq`) across an exam, in | |
| 181 | +/// question (ULID) order — the live-sitting read-back and, for a past | |
| 182 | +/// `seq`, that attempt's answer sheet. | |
| 183 | +pub async fn list_for_exam_user( | |
| 184 | + db: &Database, | |
| 185 | + exam: &ExamId, | |
| 186 | + user: &UserId, | |
| 187 | + seq: i64, | |
| 188 | +) -> Result<Vec<ExamAnswer>, AppError> { | |
| 189 | + let mut result = db | |
| 190 | + .query( | |
| 191 | + "SELECT * FROM exam_answer WHERE exam = $ex AND user = $usr AND seq = $seq | |
| 192 | + ORDER BY question ASC", | |
| 193 | + ) | |
| 194 | + .bind(("ex", exam.record())) | |
| 195 | + .bind(("usr", user.record())) | |
| 196 | + .bind(("seq", seq)) | |
| 197 | + .await? | |
| 198 | + .check()?; | |
| 199 | + Ok(result.take::<Vec<ExamAnswer>>(0)?) | |
| 200 | +} | |
| 201 | + | |
| 202 | +/// The distinct sittings a student has any answer for at `exam`, ascending | |
| 203 | +/// — the index a history view lists attempts from. | |
| 204 | +pub async fn list_seqs_for_user( | |
| 205 | + db: &Database, | |
| 206 | + exam: &ExamId, | |
| 207 | + user: &UserId, | |
| 208 | +) -> Result<Vec<i64>, AppError> { | |
| 209 | + let mut result = db | |
| 210 | + .query( | |
| 211 | + "SELECT VALUE seq FROM exam_answer WHERE exam = $ex AND user = $usr | |
| 212 | + ORDER BY seq ASC", | |
| 213 | + ) | |
| 214 | + .bind(("ex", exam.record())) | |
| 215 | + .bind(("usr", user.record())) | |
| 216 | + .await? | |
| 217 | + .check()?; | |
| 218 | + let mut seqs = result.take::<Vec<i64>>(0)?; | |
| 219 | + seqs.dedup(); | |
| 220 | + Ok(seqs) | |
| 221 | +} | |
| 222 | + | |
| 223 | +/// Every answer of an exam — the live monitor aggregates these per student. | |
| 224 | +pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<ExamAnswer>, AppError> { | |
| 225 | + let mut result = db | |
| 226 | + .query("SELECT * FROM exam_answer WHERE exam = $ex ORDER BY question ASC") | |
| 227 | + .bind(("ex", exam.record())) | |
| 228 | + .await? | |
| 229 | + .check()?; | |
| 230 | + Ok(result.take::<Vec<ExamAnswer>>(0)?) | |
| 231 | +} | |
| 232 | + | |
| 233 | +/// Drop one student's answers across an exam — a retake starts from a | |
| 234 | +/// blank sheet. | |
| 235 | +pub async fn delete_for_exam_user( | |
| 236 | + db: &Database, | |
| 237 | + exam: &ExamId, | |
| 238 | + user: &UserId, | |
| 239 | +) -> Result<(), AppError> { | |
| 240 | + db.query("DELETE exam_answer WHERE exam = $ex AND user = $usr") | |
| 241 | + .bind(("ex", exam.record())) | |
| 242 | + .bind(("usr", user.record())) | |
| 243 | + .await? | |
| 244 | + .check()?; | |
| 245 | + Ok(()) | |
| 246 | +} | |
| 247 | + | |
| 248 | +#[cfg(test)] | |
| 249 | +mod tests { | |
| 250 | + use super::*; | |
| 251 | + use crate::domain::exam::ExamId; | |
| 252 | + use crate::domain::exam_question::{ChoiceId, ChoiceInput, QuestionKind, QuestionSpec}; | |
| 253 | + | |
| 254 | + /// A three-option question whose `correct` is the option at `correct`. | |
| 255 | + /// Positions are a *test* convenience only — the ids are minted, and every | |
| 256 | + /// assertion below goes through `choice_id`. | |
| 257 | + fn choice_question(exam: &ExamId, points: i64, correct: usize) -> ExamQuestion { | |
| 258 | + let labels = ["a", "b", "c"]; | |
| 259 | + let spec = QuestionSpec::try_new( | |
| 260 | + QuestionKind::try_new("choice").unwrap(), | |
| 261 | + Some( | |
| 262 | + labels | |
| 263 | + .iter() | |
| 264 | + .map(|l| ChoiceInput { | |
| 265 | + id: Some((*l).into()), | |
| 266 | + text: (*l).into(), | |
| 267 | + }) | |
| 268 | + .collect(), | |
| 269 | + ), | |
| 270 | + Some(labels[correct].into()), | |
| 271 | + &[], | |
| 272 | + ) | |
| 273 | + .unwrap(); | |
| 274 | + ExamQuestion::test_new(exam, "pick one", points, spec) | |
| 275 | + } | |
| 276 | + | |
| 277 | + /// The minted id of the question's option at `index`. | |
| 278 | + fn choice_id(question: &ExamQuestion, index: usize) -> ChoiceId { | |
| 279 | + question.get_choices().unwrap()[index].get_id().clone() | |
| 280 | + } | |
| 281 | + | |
| 282 | + fn student() -> UserId { | |
| 283 | + UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA") | |
| 284 | + } | |
| 285 | + | |
| 286 | + /// The bite test for the exam-row touch in [`save`]: it exists | |
| 287 | + /// to collide with [`crate::db::exam::delete`], so it must leave | |
| 288 | + /// the counter it borrows exactly where it found it — absent stays absent | |
| 289 | + /// (the boot backfill keys on `result_count = NONE`), and a real count is | |
| 290 | + /// not moved by a student typing. The race half is | |
| 291 | + /// `db::exam::tests::an_answer_written_inside_a_delete_never_outlives_the_exam`, | |
| 292 | + /// which needs a real server; this half is the arithmetic and runs anywhere. | |
| 293 | + #[tokio::test] | |
| 294 | + async fn a_save_puts_the_exams_mark_counter_back_exactly() { | |
| 295 | + use crate::domain::exam::{ | |
| 296 | + ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle, | |
| 297 | + }; | |
| 298 | + let db = crate::database::init_mem().await.unwrap(); | |
| 299 | + let kinds = crate::domain::settings::Settings::defaults() | |
| 300 | + .get_exam_kinds() | |
| 301 | + .to_vec(); | |
| 302 | + let exam = crate::db::exam::create( | |
| 303 | + &db, | |
| 304 | + &student(), | |
| 305 | + &crate::db::course::a_test_course(&db).await, | |
| 306 | + ExamTitle::try_new("quiz").unwrap(), | |
| 307 | + ExamDescription::try_new("").unwrap(), | |
| 308 | + ExamKind::try_new("quiz", &kinds).unwrap(), | |
| 309 | + ExamSchedule::try_new(None, None, None, None).unwrap(), | |
| 310 | + ExamAttemptLimit::try_new(1).unwrap(), | |
| 311 | + true, | |
| 312 | + false, | |
| 313 | + false, | |
| 314 | + ) | |
| 315 | + .await | |
| 316 | + .unwrap(); | |
| 317 | + let stored = async |db: &Database| -> Option<i64> { | |
| 318 | + let mut result = db | |
| 319 | + .query("SELECT VALUE result_count FROM ONLY $ex") | |
| 320 | + .bind(("ex", exam.get_id().record())) | |
| 321 | + .await | |
| 322 | + .unwrap() | |
| 323 | + .check() | |
| 324 | + .unwrap(); | |
| 325 | + result.take::<Option<i64>>(0).unwrap() | |
| 326 | + }; | |
| 327 | + let question = choice_question(exam.get_id(), 10, 1); | |
| 328 | + let pick = choice_id(&question, 1).as_str().to_string(); | |
| 329 | + | |
| 330 | + // A fresh exam carries no counter at all, and must still not after a save. | |
| 331 | + assert_eq!(stored(&db).await, None, "the fixture must start absent"); | |
| 332 | + save(&db, &question, &student(), 1, Some(pick.clone()), None) | |
| 333 | + .await | |
| 334 | + .unwrap(); | |
| 335 | + assert_eq!( | |
| 336 | + stored(&db).await, | |
| 337 | + None, | |
| 338 | + "the touch left the counter set — the backfill keys on NONE" | |
| 339 | + ); | |
| 340 | + | |
| 341 | + // …and a counter that marks have moved is put back at its own value. | |
| 342 | + db.query("UPDATE $ex SET result_count = 7") | |
| 343 | + .bind(("ex", exam.get_id().record())) | |
| 344 | + .await | |
| 345 | + .unwrap() | |
| 346 | + .check() | |
| 347 | + .unwrap(); | |
| 348 | + save(&db, &question, &student(), 2, Some(pick), None) | |
| 349 | + .await | |
| 350 | + .unwrap(); | |
| 351 | + assert_eq!(stored(&db).await, Some(7), "the touch moved a real count"); | |
| 352 | + | |
| 353 | + // The gate that makes the touch worth having: no exam, no answer. | |
| 354 | + let orphan = choice_question(&ExamId::from_key("01NOSUCHEXAMAAAAAAAAAAAAAA"), 10, 0); | |
| 355 | + let pick = choice_id(&orphan, 0).as_str().to_string(); | |
| 356 | + let refused = save(&db, &orphan, &student(), 1, Some(pick), None).await; | |
| 357 | + assert!( | |
| 358 | + matches!(refused, Err(AppError::NotFound)), | |
| 359 | + "a save into a missing exam must 404, got {refused:?}" | |
| 360 | + ); | |
| 361 | + } | |
| 362 | +} |
src/db/exam_attempt.rsmodified+1 -1
| @@ -171,7 +171,7 @@ pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result<bool, AppError | ||
| 171 | 171 | /// predating this insert — so both commit and the child outlives the exam, |
| 172 | 172 | /// with neither caller told anything. Writing a key the delete also writes |
| 173 | 173 | /// makes the two collide and the store refuses one side. It is the shape |
| 174 | -/// [`crate::domain::exam_answer::ExamAnswer::save`] and | |
| 174 | +/// [`crate::db::exam_answer::save`] and | |
| 175 | 175 | /// [`crate::domain::menu::bump_menu_and_write`] already use. |
| 176 | 176 | /// |
| 177 | 177 | /// An orphan here is not merely untidy: an `exam_question` that outlives |
src/db/exam_result.rsadded+802 -0
| @@ -0,0 +1,802 @@ | ||
| 1 | +//! The `exam_result` table: the mark's claim-riding upsert, the per-sitting | |
| 2 | +//! history reads, and the refunding delete. The grade pre-flight (draft, kind, | |
| 3 | +//! grader/target walls) and the `EXAM_LOCK` lease live in | |
| 4 | +//! [`crate::service::exam_result`]; the mark newtype and the latest-per-pair | |
| 5 | +//! fold live in [`crate::domain::exam_result`]. | |
| 6 | + | |
| 7 | +use surrealdb::types::SurrealValue; | |
| 8 | + | |
| 9 | +use crate::constant::{ | |
| 10 | + EXAM_RESULT_COUNT_FIELD, HIGH_MARK_MIN, HIGH_MARK_TOTAL_FIELD, MARKS_GIVEN_TOTAL_FIELD, | |
| 11 | + REF_COUNT_FIELD, REF_RETIRED_FIELD, | |
| 12 | +}; | |
| 13 | +use crate::database::{Database, transaction_with_retry}; | |
| 14 | +use crate::db::cap; | |
| 15 | +use crate::domain::course::CourseId; | |
| 16 | +use crate::domain::exam::ExamId; | |
| 17 | +use crate::domain::exam_result::{ | |
| 18 | + ExamResult, ExamResultId, Mark, draft_error, kind_ref, latest_per_pair, retired_kind_error, | |
| 19 | +}; | |
| 20 | +use crate::domain::user::UserId; | |
| 21 | +use crate::error::AppError; | |
| 22 | + | |
| 23 | +/// The `THROW` marker the in-transaction kind claim aborts with — the mark's | |
| 24 | +/// own transaction refusing a name the school has retired. | |
| 25 | +const RETIRED_MARK: &str = "kind_retired"; | |
| 26 | + | |
| 27 | +/// A single user's result for an exam, if graded — the latest sitting's mark. | |
| 28 | +async fn find(db: &Database, exam: &ExamId, user: &UserId) -> Result<Option<ExamResult>, AppError> { | |
| 29 | + // Grade-of-record is the latest sitting's mark: the highest seq wins. | |
| 30 | + let mut result = db | |
| 31 | + .query( | |
| 32 | + "SELECT * FROM exam_result WHERE exam = $ex AND user = $usr | |
| 33 | + ORDER BY seq DESC LIMIT 1", | |
| 34 | + ) | |
| 35 | + .bind(("ex", exam.record())) | |
| 36 | + .bind(("usr", user.record())) | |
| 37 | + .await? | |
| 38 | + .check()?; | |
| 39 | + Ok(result.take::<Vec<ExamResult>>(0)?.into_iter().next()) | |
| 40 | +} | |
| 41 | + | |
| 42 | +/// Record (or overwrite) `user`'s mark for the `seq`th sitting of `exam`. | |
| 43 | +/// One row per (exam, user, seq), keyed by a deterministic composite id so | |
| 44 | +/// this is a single atomic UPSERT — concurrent grades for the same sitting | |
| 45 | +/// converge on one row instead of racing the unique index into a 500. | |
| 46 | +/// Grading a retake writes a fresh mark at the current seq and never touches | |
| 47 | +/// prior sittings' marks; the latest seq is the grade-of-record. | |
| 48 | +/// | |
| 49 | +/// `kind` is the exam's kind, and this is where a mark takes its reference | |
| 50 | +/// on it — claimed *inside the mark's own transaction*, and only on the | |
| 51 | +/// branch that is about to add a row. A kind the school has retired refuses | |
| 52 | +/// the claim, which is the same invariant the settings guard enforces from | |
| 53 | +/// the other side. Claimed before the write and released after, the pair had | |
| 54 | +/// two crash windows either side of the write that leaked a reference (a | |
| 55 | +/// kind frozen out of the settings for good) and an exam's `result_count`; | |
| 56 | +/// riding the transaction, both counters land exactly when the row does. | |
| 57 | +/// | |
| 58 | +/// The exam's own `result_count` is claimed in the same breath, and it is | |
| 59 | +/// what a kind change is refused against: the exam PATCH pins that counter, | |
| 60 | +/// so a mark landing while it decides cannot slip past its gate and leave | |
| 61 | +/// itself counted under a kind its exam no longer carries. | |
| 62 | +/// | |
| 63 | +/// An overwrite (a regrade of a sitting already marked) claims *nothing*: | |
| 64 | +/// one mark, one reference, so the branch that finds a row simply leaves | |
| 65 | +/// both counters where they are — there is no claim to give back, and so no | |
| 66 | +/// window in which a crash could fail to give it. | |
| 67 | +/// | |
| 68 | +/// The grader's `marks_given_total` rides that same first-time branch: a | |
| 69 | +/// regrade of a sitting moves it however often it is run, while a retake, | |
| 70 | +/// being a distinct `seq` and so a distinct row, counts on its own. | |
| 71 | +/// | |
| 72 | +/// The student's `high_mark_total` cannot ride it, because it is not a | |
| 73 | +/// count of rows but a count of rows *at or above* [`HIGH_MARK_MIN`], and a | |
| 74 | +/// regrade moves a mark across that line without adding or removing a row. | |
| 75 | +/// It moves by the difference between the mark about to be stored and the | |
| 76 | +/// one already there — `+1` crossing up, `-1` crossing down, nothing at all | |
| 77 | +/// when both sides sit on the same side of the line, so an overwrite still | |
| 78 | +/// costs the student's row no write unless the answer actually changed. | |
| 79 | +/// Decided on the first branch alone it drifted upward without bound: 95 | |
| 80 | +/// credited, regraded to 40 (no row added, so no move), then deleted, whose | |
| 81 | +/// refund reads the *stored* mark and so found nothing to give back — a | |
| 82 | +/// counter of one over zero stored high marks, looped into a permanent | |
| 83 | +/// badge. Both counters are written field-scoped: a user row also carries | |
| 84 | +/// admin-owned data (`role`) that a whole-row save would revert. | |
| 85 | +pub async fn grade( | |
| 86 | + db: &Database, | |
| 87 | + exam: &ExamId, | |
| 88 | + user: &UserId, | |
| 89 | + seq: i64, | |
| 90 | + mark: Mark, | |
| 91 | + graded_by: &UserId, | |
| 92 | + kind: &str, | |
| 93 | +) -> Result<ExamResult, AppError> { | |
| 94 | + let result = ExamResult { | |
| 95 | + id: ExamResultId::composite(exam, user, seq), | |
| 96 | + exam: exam.clone(), | |
| 97 | + user: user.clone(), | |
| 98 | + seq, | |
| 99 | + mark, | |
| 100 | + graded_by: graded_by.clone(), | |
| 101 | + }; | |
| 102 | + // The "exists" and "not a draft" gates ride in the same transaction as | |
| 103 | + // the mark, the mirror of the re-draft gate on | |
| 104 | + // `crate::db::exam::update_if_unchanged`: between them, a mark and a | |
| 105 | + // re-draft racing each other can only ever leave one of the two applied, | |
| 106 | + // whichever process either ran in. The existence gate is not | |
| 107 | + // redundant with the draft one — a deleted exam reads NONE, which is | |
| 108 | + // *falsy*, so the draft gate alone waved a mark onto an exam that no | |
| 109 | + // longer existed. The caller's pre-flight check answers the same 409 | |
| 110 | + // one round trip earlier. It is also what makes a separate "did the | |
| 111 | + // exam survive my claim?" check moot: the claim now sits behind this | |
| 112 | + // gate instead of in front of it. | |
| 113 | + // | |
| 114 | + // `$before` is the sitting's *previous mark*, and it answers both | |
| 115 | + // questions off one read: `mark` is a mandatory column on a schemafull | |
| 116 | + // row, so `NONE` there means no row at all — the claim branch — while a | |
| 117 | + // number is what the student's counter takes its difference against. | |
| 118 | + // Read one statement before the counters inside the same transaction: | |
| 119 | + // read anywhere else it would be a guess about a row two graders may be | |
| 120 | + // writing at once, and the difference would be taken against a mark | |
| 121 | + // some other round had already replaced. | |
| 122 | + // | |
| 123 | + // Re-sent while the store answers "conflict, retry": the gates read a | |
| 124 | + // column an exam PATCH writes, and the counters are the ones a | |
| 125 | + // concurrent delete gives back, so this contends on three records by | |
| 126 | + // design. Sound to re-send because no statement in it can legitimately | |
| 127 | + // answer "already exists": the counter writes are `UPDATE`/`UPSERT` on | |
| 128 | + // ids no rival can collide *into*, and the mark's own UPSERT is on a | |
| 129 | + // deterministic id bijective with the `exam_result_exam_user_seq` | |
| 130 | + // unique tuple — `key::sitting(exam, user, seq)` *is* that tuple, so | |
| 131 | + // the index entry can only ever point at the row the id already names | |
| 132 | + // and the write resolves onto it. A lost round aborts having written | |
| 133 | + // nothing, counters included. | |
| 134 | + let _guard = cap::counter_lock().await; | |
| 135 | + let (mut written, mut errors) = transaction_with_retry( | |
| 136 | + db, | |
| 137 | + &format!( | |
| 138 | + "BEGIN TRANSACTION; | |
| 139 | + IF (SELECT VALUE id FROM ONLY $exam) IS NONE {{ THROW 'exam_missing' }}; | |
| 140 | + IF (SELECT VALUE draft FROM ONLY $exam) {{ THROW 'exam_draft' }}; | |
| 141 | + LET $before = (SELECT VALUE mark FROM ONLY $id); | |
| 142 | + IF $before = NONE {{ | |
| 143 | + LET $kind = (UPSERT $kref SET {REF_COUNT_FIELD} = ({REF_COUNT_FIELD} ?? 0) + 1 | |
| 144 | + WHERE {REF_RETIRED_FIELD} != true RETURN VALUE id); | |
| 145 | + IF array::len($kind) = 0 {{ THROW '{RETIRED_MARK}' }}; | |
| 146 | + UPDATE $exam SET {EXAM_RESULT_COUNT_FIELD} = | |
| 147 | + ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1; | |
| 148 | + UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = | |
| 149 | + ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1; | |
| 150 | + }}; | |
| 151 | + LET $high = (IF $result.mark >= {HIGH_MARK_MIN} {{ 1 }} ELSE {{ 0 }}) | |
| 152 | + - (IF ($before ?? -1) >= {HIGH_MARK_MIN} {{ 1 }} ELSE {{ 0 }}); | |
| 153 | + IF $high != 0 {{ | |
| 154 | + UPDATE $student SET {HIGH_MARK_TOTAL_FIELD} = | |
| 155 | + math::max([({HIGH_MARK_TOTAL_FIELD} ?? 0) + $high, 0]) | |
| 156 | + }}; | |
| 157 | + LET $after = (UPSERT $id CONTENT $result RETURN AFTER); | |
| 158 | + RETURN $after[0]; | |
| 159 | + COMMIT TRANSACTION;" | |
| 160 | + ), | |
| 161 | + &[ | |
| 162 | + ("exam".into(), exam.record().into_value()), | |
| 163 | + ("id".into(), result.id.record().into_value()), | |
| 164 | + ("kref".into(), kind_ref(kind).into_value()), | |
| 165 | + ("grader".into(), graded_by.record().into_value()), | |
| 166 | + ("student".into(), user.record().into_value()), | |
| 167 | + ("result".into(), result.into_value()), | |
| 168 | + ], | |
| 169 | + &["exam_missing", "exam_draft", RETIRED_MARK], | |
| 170 | + ) | |
| 171 | + .await?; | |
| 172 | + // An aborted transaction errors every slot and only the THROW's own | |
| 173 | + // slot names the marker, so a refusal is read by marker while a lost | |
| 174 | + // round was already re-sent — never reported as a 500. | |
| 175 | + let thrown = |marker: &str| { | |
| 176 | + errors | |
| 177 | + .values() | |
| 178 | + .any(|error| error.to_string().contains(marker)) | |
| 179 | + }; | |
| 180 | + if thrown("exam_missing") { | |
| 181 | + return Err(AppError::NotFound); | |
| 182 | + } | |
| 183 | + if thrown("exam_draft") { | |
| 184 | + return Err(draft_error()); | |
| 185 | + } | |
| 186 | + if thrown(RETIRED_MARK) { | |
| 187 | + return Err(retired_kind_error(kind)); | |
| 188 | + } | |
| 189 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | |
| 190 | + return Err(error.into()); | |
| 191 | + } | |
| 192 | + // The trailing `RETURN` is always the last statement before `COMMIT`, | |
| 193 | + // so its slot follows the statement count instead of a hand-kept | |
| 194 | + // number — see `db::exam::delete` for the bug the hand-kept one caused. | |
| 195 | + // Probed on crate 3.2.3: an `IF { … }` block occupies exactly one slot | |
| 196 | + // however many statements it holds, and one whether or not it is taken. | |
| 197 | + let slot = written.num_statements().saturating_sub(2); | |
| 198 | + written | |
| 199 | + .take::<Vec<ExamResult>>(slot)? | |
| 200 | + .into_iter() | |
| 201 | + .next() | |
| 202 | + .ok_or_else(|| AppError::Internal("failed to record exam result".into())) | |
| 203 | +} | |
| 204 | + | |
| 205 | +/// The user's graded results restricted to one course's exams — the raw | |
| 206 | +/// rows behind the per-course block of the marks report. | |
| 207 | +pub async fn list_for_user_in_course( | |
| 208 | + db: &Database, | |
| 209 | + course: &CourseId, | |
| 210 | + user: &UserId, | |
| 211 | +) -> Result<Vec<ExamResult>, AppError> { | |
| 212 | + let mut result = db | |
| 213 | + .query( | |
| 214 | + "SELECT * FROM exam_result WHERE user = $usr | |
| 215 | + AND exam IN (SELECT VALUE id FROM exam WHERE course = $course) | |
| 216 | + ORDER BY id DESC", | |
| 217 | + ) | |
| 218 | + .bind(("usr", user.record())) | |
| 219 | + .bind(("course", course.record())) | |
| 220 | + .await? | |
| 221 | + .check()?; | |
| 222 | + Ok(latest_per_pair(result.take::<Vec<ExamResult>>(0)?)) | |
| 223 | +} | |
| 224 | + | |
| 225 | +pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<ExamResult>, AppError> { | |
| 226 | + let mut result = db | |
| 227 | + .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC") | |
| 228 | + .bind(("ex", exam.record())) | |
| 229 | + .await? | |
| 230 | + .check()?; | |
| 231 | + Ok(latest_per_pair(result.take::<Vec<ExamResult>>(0)?)) | |
| 232 | +} | |
| 233 | + | |
| 234 | +/// Every sitting's mark for one (exam, user) pair, oldest first — the | |
| 235 | +/// per-attempt grade history behind the FE's attempt-by-attempt view. | |
| 236 | +pub async fn list_all_for_exam_user( | |
| 237 | + db: &Database, | |
| 238 | + exam: &ExamId, | |
| 239 | + user: &UserId, | |
| 240 | +) -> Result<Vec<ExamResult>, AppError> { | |
| 241 | + let mut result = db | |
| 242 | + .query( | |
| 243 | + "SELECT * FROM exam_result WHERE exam = $ex AND user = $usr | |
| 244 | + ORDER BY seq ASC", | |
| 245 | + ) | |
| 246 | + .bind(("ex", exam.record())) | |
| 247 | + .bind(("usr", user.record())) | |
| 248 | + .await? | |
| 249 | + .check()?; | |
| 250 | + Ok(result.take::<Vec<ExamResult>>(0)?) | |
| 251 | +} | |
| 252 | + | |
| 253 | +/// A single user's result for an exam, if graded. | |
| 254 | +pub async fn read_for_user( | |
| 255 | + db: &Database, | |
| 256 | + exam: &ExamId, | |
| 257 | + user: &UserId, | |
| 258 | +) -> Result<Option<ExamResult>, AppError> { | |
| 259 | + find(db, exam, user).await | |
| 260 | +} | |
| 261 | + | |
| 262 | +/// Delete every sitting's mark for one (exam, user) pair. `kind` is the | |
| 263 | +/// exam's: the marks give their references back, so a kind nothing is | |
| 264 | +/// graded under any more can leave the settings again. | |
| 265 | +/// | |
| 266 | +/// The two badge counters come back the same way, and for a reason the | |
| 267 | +/// other counters do not need: [`grade`] credits them on the | |
| 268 | +/// branch that finds no row, and a deleted row *is* no row. Left standing, | |
| 269 | +/// ungrade-then-regrade credited a second time off one stored mark, and | |
| 270 | +/// looped it minted a badge from a single exam — permanently, since an | |
| 271 | +/// award is never revoked. Each is given back off the rows this statement | |
| 272 | +/// actually deleted: `marks_given_total` to each row's *own* grader (two | |
| 273 | +/// teachers can hold two sittings of the same pair), and `high_mark_total` | |
| 274 | +/// once per removed row that cleared [`HIGH_MARK_MIN`], read off the | |
| 275 | +/// `BEFORE` image rather than re-derived. That last one is why | |
| 276 | +/// [`grade`] has to move the student's counter on a *regrade* | |
| 277 | +/// too: this end reads the stored mark, so the other end must be decided by | |
| 278 | +/// the stored mark as well, or a mark walked across the line between the | |
| 279 | +/// two leaves a credit no delete can find to give back. | |
| 280 | +pub async fn remove( | |
| 281 | + db: &Database, | |
| 282 | + exam: &ExamId, | |
| 283 | + user: &UserId, | |
| 284 | + kind: &str, | |
| 285 | +) -> Result<Option<ExamResult>, AppError> { | |
| 286 | + // Both counters go back *inside* the delete's own transaction, driven | |
| 287 | + // off the rows this statement actually deleted. Counted outside it, a | |
| 288 | + // cascade (exam or course delete) taking the same rows in the gap would | |
| 289 | + // release them a second time, and on a kind another exam still grades | |
| 290 | + // under, one release too many reads as one mark too few — a kind | |
| 291 | + // wrongly free to leave the settings. | |
| 292 | + // | |
| 293 | + // Re-sent while the store answers "conflict, retry": the counters this | |
| 294 | + // touches are the ones a concurrent grade claims, so a lost round is | |
| 295 | + // routine and aborts having written nothing. `check()` cannot be used | |
| 296 | + // to read the outcome — it takes the *lowest*-slot error, and an | |
| 297 | + // aborted transaction's generic "not executed" sibling masked the real | |
| 298 | + // conflict, the exact defect deleted from `db::exam::delete`. No THROW | |
| 299 | + // of its own, and only `DELETE`/`UPDATE` inside, so nothing here can | |
| 300 | + // answer "already exists" and make a retry unsound. | |
| 301 | + let (mut result, mut errors) = transaction_with_retry( | |
| 302 | + db, | |
| 303 | + &format!( | |
| 304 | + "BEGIN TRANSACTION; | |
| 305 | + LET $gone = (DELETE exam_result WHERE exam = $ex AND user = $usr RETURN BEFORE); | |
| 306 | + IF array::len($gone) > 0 {{ | |
| 307 | + UPDATE type::record('kind_ref', $kind) SET {REF_COUNT_FIELD} = | |
| 308 | + math::max([({REF_COUNT_FIELD} ?? 0) - array::len($gone), 0]); | |
| 309 | + UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = | |
| 310 | + math::max([({EXAM_RESULT_COUNT_FIELD} ?? 0) - array::len($gone), 0]); | |
| 311 | + LET $high = array::len($gone[WHERE mark >= {HIGH_MARK_MIN}]); | |
| 312 | + IF $high > 0 {{ | |
| 313 | + UPDATE $usr SET {HIGH_MARK_TOTAL_FIELD} = | |
| 314 | + math::max([({HIGH_MARK_TOTAL_FIELD} ?? 0) - $high, 0]) | |
| 315 | + }}; | |
| 316 | + FOR $row IN $gone {{ | |
| 317 | + LET $grader = $row.graded_by; | |
| 318 | + UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = | |
| 319 | + math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0]) | |
| 320 | + }}; | |
| 321 | + }}; | |
| 322 | + RETURN $gone; | |
| 323 | + COMMIT TRANSACTION;" | |
| 324 | + ), | |
| 325 | + &[ | |
| 326 | + ("ex".into(), exam.record().into_value()), | |
| 327 | + ("usr".into(), user.record().into_value()), | |
| 328 | + ("kind".into(), kind.to_string().into_value()), | |
| 329 | + ], | |
| 330 | + &[], | |
| 331 | + ) | |
| 332 | + .await?; | |
| 333 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | |
| 334 | + return Err(error.into()); | |
| 335 | + } | |
| 336 | + // `RETURN` is the last statement before `COMMIT`; its slot follows the | |
| 337 | + // statement count, as in `db::exam::delete`. | |
| 338 | + let slot = result.num_statements().saturating_sub(2); | |
| 339 | + let removed = result.take::<Vec<ExamResult>>(slot)?; | |
| 340 | + Ok(removed.into_iter().next()) | |
| 341 | +} | |
| 342 | + | |
| 343 | +#[cfg(test)] | |
| 344 | +mod tests { | |
| 345 | + use super::*; | |
| 346 | + use crate::database::init_mem; | |
| 347 | + | |
| 348 | + #[tokio::test] | |
| 349 | + async fn retakes_keep_a_mark_per_sitting_with_the_latest_as_grade_of_record() { | |
| 350 | + let db = init_mem().await.unwrap(); | |
| 351 | + let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA"); | |
| 352 | + let user = UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"); | |
| 353 | + let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | |
| 354 | + // The exam has to be real: a mark is refused on one that isn't. | |
| 355 | + db.query( | |
| 356 | + "CREATE $ex SET creator = $t, course = course:c, title = 't', | |
| 357 | + description = '', kind = 'midterm'", | |
| 358 | + ) | |
| 359 | + .bind(("ex", exam.record())) | |
| 360 | + .bind(("t", teacher.record())) | |
| 361 | + .await | |
| 362 | + .unwrap() | |
| 363 | + .check() | |
| 364 | + .unwrap(); | |
| 365 | + | |
| 366 | + // Grade sitting #1, then a retake as sitting #2 — two rows, not one. | |
| 367 | + super::grade( | |
| 368 | + &db, | |
| 369 | + &exam, | |
| 370 | + &user, | |
| 371 | + 1, | |
| 372 | + Mark::try_new(40).unwrap(), | |
| 373 | + &teacher, | |
| 374 | + "midterm", | |
| 375 | + ) | |
| 376 | + .await | |
| 377 | + .unwrap(); | |
| 378 | + let second = super::grade( | |
| 379 | + &db, | |
| 380 | + &exam, | |
| 381 | + &user, | |
| 382 | + 2, | |
| 383 | + Mark::try_new(90).unwrap(), | |
| 384 | + &teacher, | |
| 385 | + "midterm", | |
| 386 | + ) | |
| 387 | + .await | |
| 388 | + .unwrap(); | |
| 389 | + assert_eq!(second.get_seq(), 2); | |
| 390 | + | |
| 391 | + // Grade-of-record is the latest sitting's mark. | |
| 392 | + let latest = read_for_user(&db, &exam, &user) | |
| 393 | + .await | |
| 394 | + .unwrap() | |
| 395 | + .expect("graded"); | |
| 396 | + assert_eq!(latest.get_mark().as_i64(), 90); | |
| 397 | + assert_eq!(latest.get_seq(), 2); | |
| 398 | + | |
| 399 | + // The roster yields exactly one row per pair — the latest. | |
| 400 | + let roster = list_for_exam(&db, &exam).await.unwrap(); | |
| 401 | + assert_eq!(roster.len(), 1); | |
| 402 | + assert_eq!(roster[0].get_mark().as_i64(), 90); | |
| 403 | + | |
| 404 | + // History keeps both sittings, oldest first. | |
| 405 | + let history = list_all_for_exam_user(&db, &exam, &user).await.unwrap(); | |
| 406 | + assert_eq!( | |
| 407 | + history | |
| 408 | + .iter() | |
| 409 | + .map(|r| r.get_mark().as_i64()) | |
| 410 | + .collect::<Vec<_>>(), | |
| 411 | + vec![40, 90] | |
| 412 | + ); | |
| 413 | + | |
| 414 | + // Deleting the pair removes every sitting. | |
| 415 | + remove(&db, &exam, &user, "midterm").await.unwrap(); | |
| 416 | + assert!( | |
| 417 | + list_all_for_exam_user(&db, &exam, &user) | |
| 418 | + .await | |
| 419 | + .unwrap() | |
| 420 | + .is_empty() | |
| 421 | + ); | |
| 422 | + } | |
| 423 | + | |
| 424 | + /// A deleted exam reads NONE, and NONE is falsy — the draft gate alone let | |
| 425 | + /// a mark land on an exam that no longer existed. | |
| 426 | + #[tokio::test] | |
| 427 | + async fn a_mark_is_refused_on_an_exam_that_no_longer_exists() { | |
| 428 | + let db = init_mem().await.unwrap(); | |
| 429 | + let exam = ExamId::from_key("01TESTGONEEXAMAAAAAAAAAAAA"); | |
| 430 | + let user = UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"); | |
| 431 | + let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | |
| 432 | + | |
| 433 | + let refused = super::grade( | |
| 434 | + &db, | |
| 435 | + &exam, | |
| 436 | + &user, | |
| 437 | + 1, | |
| 438 | + Mark::try_new(40).unwrap(), | |
| 439 | + &teacher, | |
| 440 | + "midterm", | |
| 441 | + ) | |
| 442 | + .await; | |
| 443 | + assert!(matches!(refused, Err(AppError::NotFound)), "{refused:?}"); | |
| 444 | + assert!( | |
| 445 | + list_all_for_exam_user(&db, &exam, &user) | |
| 446 | + .await | |
| 447 | + .unwrap() | |
| 448 | + .is_empty() | |
| 449 | + ); | |
| 450 | + assert_eq!(counters(&db, "midterm").await, (0, 0)); | |
| 451 | + } | |
| 452 | + | |
| 453 | + /// The two counters, re-read out of the store — never off a return value, | |
| 454 | + /// which the in-memory engine forges wins on (see `cap::CLAIM_LOCK`). A | |
| 455 | + /// missing `kind_ref` row is a zero, which is exactly how the backfill | |
| 456 | + /// treats it (`tests/persistence.rs` — no zero pass, deliberately). | |
| 457 | + async fn counters(db: &Database, kind: &str) -> (i64, i64) { | |
| 458 | + let mut result = db | |
| 459 | + .query( | |
| 460 | + "SELECT VALUE count ?? 0 FROM kind_ref WHERE record::id(id) = $kind; | |
| 461 | + SELECT VALUE result_count ?? 0 FROM exam;", | |
| 462 | + ) | |
| 463 | + .bind(("kind", kind.to_string())) | |
| 464 | + .await | |
| 465 | + .unwrap() | |
| 466 | + .check() | |
| 467 | + .unwrap(); | |
| 468 | + let kinds: Vec<i64> = result.take(0).unwrap(); | |
| 469 | + let exams: Vec<i64> = result.take(1).unwrap(); | |
| 470 | + ( | |
| 471 | + kinds.into_iter().next().unwrap_or(0), | |
| 472 | + exams.into_iter().next().unwrap_or(0), | |
| 473 | + ) | |
| 474 | + } | |
| 475 | + | |
| 476 | + async fn an_exam(db: &Database, exam: &ExamId, kind: &str) { | |
| 477 | + db.query( | |
| 478 | + "CREATE $ex SET creator = user:t, course = course:c, title = 't', | |
| 479 | + description = '', kind = $kind", | |
| 480 | + ) | |
| 481 | + .bind(("ex", exam.record())) | |
| 482 | + .bind(("kind", kind.to_string())) | |
| 483 | + .await | |
| 484 | + .unwrap() | |
| 485 | + .check() | |
| 486 | + .unwrap(); | |
| 487 | + } | |
| 488 | + | |
| 489 | + const STUDENT: &str = "01TESTSTUDENTAAAAAAAAAAAAA"; | |
| 490 | + const TEACHER: &str = "01TESTTEACHERAAAAAAAAAAAAA"; | |
| 491 | + | |
| 492 | + /// The tests' handle on [`super::grade`] with the grader and target | |
| 493 | + /// pinned to the two test people. | |
| 494 | + async fn grade( | |
| 495 | + db: &Database, | |
| 496 | + exam: &ExamId, | |
| 497 | + seq: i64, | |
| 498 | + mark: i64, | |
| 499 | + kind: &str, | |
| 500 | + ) -> Result<ExamResult, AppError> { | |
| 501 | + super::grade( | |
| 502 | + db, | |
| 503 | + exam, | |
| 504 | + &UserId::from_key(STUDENT), | |
| 505 | + seq, | |
| 506 | + Mark::try_new(mark).unwrap(), | |
| 507 | + &UserId::from_key(TEACHER), | |
| 508 | + kind, | |
| 509 | + ) | |
| 510 | + .await | |
| 511 | + } | |
| 512 | + | |
| 513 | + /// Both counters ride the mark's own transaction: a new mark claims each | |
| 514 | + /// exactly once, and a *regrade* of the same sitting claims neither — one | |
| 515 | + /// mark, one reference. Claimed-then-released around the write, a regrade | |
| 516 | + /// drifted them upward and froze the kind out of the settings for good. | |
| 517 | + #[tokio::test] | |
| 518 | + async fn a_new_mark_moves_both_counters_and_a_regrade_moves_neither() { | |
| 519 | + let db = init_mem().await.unwrap(); | |
| 520 | + let exam = ExamId::from_key("01TESTEXAMCOUNTAAAAAAAAAAA"); | |
| 521 | + an_exam(&db, &exam, "midterm").await; | |
| 522 | + | |
| 523 | + grade(&db, &exam, 1, 40, "midterm").await.unwrap(); | |
| 524 | + assert_eq!(counters(&db, "midterm").await, (1, 1)); | |
| 525 | + | |
| 526 | + // Same sitting, new mark: an overwrite, so neither counter moves. | |
| 527 | + let regraded = grade(&db, &exam, 1, 90, "midterm").await.unwrap(); | |
| 528 | + assert_eq!(regraded.get_mark().as_i64(), 90); | |
| 529 | + assert_eq!(counters(&db, "midterm").await, (1, 1)); | |
| 530 | + | |
| 531 | + // A retake is a second row, so it does claim. | |
| 532 | + grade(&db, &exam, 2, 70, "midterm").await.unwrap(); | |
| 533 | + assert_eq!(counters(&db, "midterm").await, (2, 2)); | |
| 534 | + } | |
| 535 | + | |
| 536 | + /// The two badge counters, re-read out of the store: the grader's marks | |
| 537 | + /// given and the student's high marks. | |
| 538 | + async fn badge_counters(db: &Database) -> (i64, i64) { | |
| 539 | + let mut result = db | |
| 540 | + .query(format!( | |
| 541 | + "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $grader; | |
| 542 | + SELECT VALUE ({HIGH_MARK_TOTAL_FIELD} ?? 0) FROM $student;" | |
| 543 | + )) | |
| 544 | + .bind(("grader", UserId::from_key(TEACHER).record())) | |
| 545 | + .bind(("student", UserId::from_key(STUDENT).record())) | |
| 546 | + .await | |
| 547 | + .unwrap() | |
| 548 | + .check() | |
| 549 | + .unwrap(); | |
| 550 | + let given: Vec<i64> = result.take(0).unwrap(); | |
| 551 | + let high: Vec<i64> = result.take(1).unwrap(); | |
| 552 | + ( | |
| 553 | + given.into_iter().next().unwrap_or(0), | |
| 554 | + high.into_iter().next().unwrap_or(0), | |
| 555 | + ) | |
| 556 | + } | |
| 557 | + | |
| 558 | + /// The rows a counter needs to land on — `UPDATE` writes nothing to a user | |
| 559 | + /// that does not exist, so the badge tests must make both real. | |
| 560 | + async fn the_two_people(db: &Database) { | |
| 561 | + for key in [TEACHER, STUDENT] { | |
| 562 | + db.query("CREATE $usr SET username = $name, password_hash = 'x'") | |
| 563 | + .bind(("usr", UserId::from_key(key).record())) | |
| 564 | + .bind(("name", key.to_string())) | |
| 565 | + .await | |
| 566 | + .unwrap() | |
| 567 | + .check() | |
| 568 | + .unwrap(); | |
| 569 | + } | |
| 570 | + } | |
| 571 | + | |
| 572 | + /// A first grade credits the grader once and the student only when the mark | |
| 573 | + /// clears the line; a regrade of the same sitting credits neither again, | |
| 574 | + /// while a retake — a distinct seq, so a distinct row — counts on its own. | |
| 575 | + #[tokio::test] | |
| 576 | + async fn a_grade_credits_the_grader_once_and_a_high_mark_the_student() { | |
| 577 | + let db = init_mem().await.unwrap(); | |
| 578 | + let exam = ExamId::from_key("01TESTEXAMBADGEAAAAAAAAAAA"); | |
| 579 | + an_exam(&db, &exam, "midterm").await; | |
| 580 | + the_two_people(&db).await; | |
| 581 | + | |
| 582 | + grade(&db, &exam, 1, 90, "midterm").await.unwrap(); | |
| 583 | + assert_eq!(badge_counters(&db).await, (1, 1), "at the line earns it"); | |
| 584 | + | |
| 585 | + // Same sitting graded again: neither counter may move, however high. | |
| 586 | + grade(&db, &exam, 1, 100, "midterm").await.unwrap(); | |
| 587 | + assert_eq!(badge_counters(&db).await, (1, 1), "a regrade moves nothing"); | |
| 588 | + | |
| 589 | + // A retake below the line: the grader is credited, the student is not. | |
| 590 | + grade(&db, &exam, 2, 89, "midterm").await.unwrap(); | |
| 591 | + assert_eq!(badge_counters(&db).await, (2, 1), "89 is under the line"); | |
| 592 | + | |
| 593 | + // …and a high-scoring retake counts as its own sitting. | |
| 594 | + grade(&db, &exam, 3, 95, "midterm").await.unwrap(); | |
| 595 | + assert_eq!(badge_counters(&db).await, (3, 2)); | |
| 596 | + } | |
| 597 | + | |
| 598 | + /// Ungrading gives both badge counters back, so grade → ungrade → regrade | |
| 599 | + /// nets to one credit however often it is run. Crediting the grade without | |
| 600 | + /// refunding the delete let that loop mint a badge off a single exam — and | |
| 601 | + /// an award, once earned, is never taken back. | |
| 602 | + #[tokio::test] | |
| 603 | + async fn ungrading_gives_the_badge_counters_back() { | |
| 604 | + let db = init_mem().await.unwrap(); | |
| 605 | + let exam = ExamId::from_key("01TESTEXAMUNGRADEAAAAAAAAA"); | |
| 606 | + an_exam(&db, &exam, "midterm").await; | |
| 607 | + the_two_people(&db).await; | |
| 608 | + let student = UserId::from_key(STUDENT); | |
| 609 | + | |
| 610 | + for _ in 0..3 { | |
| 611 | + grade(&db, &exam, 1, 95, "midterm").await.unwrap(); | |
| 612 | + assert_eq!(badge_counters(&db).await, (1, 1)); | |
| 613 | + remove(&db, &exam, &student, "midterm") | |
| 614 | + .await | |
| 615 | + .unwrap() | |
| 616 | + .expect("the mark was there"); | |
| 617 | + assert_eq!(badge_counters(&db).await, (0, 0), "the loop kept a credit"); | |
| 618 | + // The kind's reference and the exam's count come back as before. | |
| 619 | + assert_eq!(counters(&db, "midterm").await, (0, 0)); | |
| 620 | + } | |
| 621 | + | |
| 622 | + // Every removed sitting is refunded, and only the ones that took: the | |
| 623 | + // grader gets both back, the student only the mark that cleared the line. | |
| 624 | + grade(&db, &exam, 1, 40, "midterm").await.unwrap(); | |
| 625 | + grade(&db, &exam, 2, 95, "midterm").await.unwrap(); | |
| 626 | + assert_eq!(badge_counters(&db).await, (2, 1)); | |
| 627 | + remove(&db, &exam, &student, "midterm") | |
| 628 | + .await | |
| 629 | + .unwrap() | |
| 630 | + .expect("both sittings were there"); | |
| 631 | + assert_eq!(badge_counters(&db).await, (0, 0)); | |
| 632 | + | |
| 633 | + // Nothing to remove is nothing to give back — the floor holds. | |
| 634 | + assert!( | |
| 635 | + remove(&db, &exam, &student, "midterm") | |
| 636 | + .await | |
| 637 | + .unwrap() | |
| 638 | + .is_none() | |
| 639 | + ); | |
| 640 | + assert_eq!(badge_counters(&db).await, (0, 0)); | |
| 641 | + } | |
| 642 | + | |
| 643 | + /// A regrade walks the *same* sitting across [`HIGH_MARK_MIN`], and the | |
| 644 | + /// student's counter has to walk with it — the delete refunds off the mark | |
| 645 | + /// it finds stored, so a credit decided by a mark that is no longer there | |
| 646 | + /// is a credit nothing can give back. Left on the first-write branch alone, | |
| 647 | + /// grade-high → regrade-low → delete kept a phantom high mark every round | |
| 648 | + /// and looped it into a permanent badge. | |
| 649 | + #[tokio::test] | |
| 650 | + async fn a_regrade_across_the_line_moves_the_student_counter_with_it() { | |
| 651 | + let db = init_mem().await.unwrap(); | |
| 652 | + let exam = ExamId::from_key("01TESTEXAMREGRADEAAAAAAAAA"); | |
| 653 | + an_exam(&db, &exam, "midterm").await; | |
| 654 | + the_two_people(&db).await; | |
| 655 | + let student = UserId::from_key(STUDENT); | |
| 656 | + | |
| 657 | + // Up across the line: no row is added, but a high mark now exists. | |
| 658 | + grade(&db, &exam, 1, 40, "midterm").await.unwrap(); | |
| 659 | + assert_eq!(badge_counters(&db).await, (1, 0), "40 is under the line"); | |
| 660 | + grade(&db, &exam, 1, 95, "midterm").await.unwrap(); | |
| 661 | + assert_eq!(badge_counters(&db).await, (1, 1), "the regrade crossed up"); | |
| 662 | + remove(&db, &exam, &student, "midterm") | |
| 663 | + .await | |
| 664 | + .unwrap() | |
| 665 | + .expect("the mark was there"); | |
| 666 | + assert_eq!(badge_counters(&db).await, (0, 0)); | |
| 667 | + | |
| 668 | + // Down across it: the credit goes back the moment the mark does, so | |
| 669 | + // the delete has nothing left to refund and the counter still lands | |
| 670 | + // on zero rather than under it. | |
| 671 | + grade(&db, &exam, 1, 95, "midterm").await.unwrap(); | |
| 672 | + assert_eq!(badge_counters(&db).await, (1, 1)); | |
| 673 | + grade(&db, &exam, 1, 40, "midterm").await.unwrap(); | |
| 674 | + assert_eq!( | |
| 675 | + badge_counters(&db).await, | |
| 676 | + (1, 0), | |
| 677 | + "the regrade crossed down" | |
| 678 | + ); | |
| 679 | + remove(&db, &exam, &student, "midterm") | |
| 680 | + .await | |
| 681 | + .unwrap() | |
| 682 | + .expect("the mark was there"); | |
| 683 | + assert_eq!(badge_counters(&db).await, (0, 0)); | |
| 684 | + | |
| 685 | + // Both sides of a regrade above the line: nothing crosses, nothing moves. | |
| 686 | + grade(&db, &exam, 1, 90, "midterm").await.unwrap(); | |
| 687 | + grade(&db, &exam, 1, 100, "midterm").await.unwrap(); | |
| 688 | + assert_eq!(badge_counters(&db).await, (1, 1), "90 → 100 stays one"); | |
| 689 | + | |
| 690 | + // The loop that minted the badge: three rounds of high → low → delete | |
| 691 | + // must leave the counter exactly where it started. | |
| 692 | + for _ in 0..3 { | |
| 693 | + grade(&db, &exam, 1, 95, "midterm").await.unwrap(); | |
| 694 | + grade(&db, &exam, 1, 40, "midterm").await.unwrap(); | |
| 695 | + remove(&db, &exam, &student, "midterm") | |
| 696 | + .await | |
| 697 | + .unwrap() | |
| 698 | + .expect("the mark was there"); | |
| 699 | + } | |
| 700 | + assert_eq!( | |
| 701 | + badge_counters(&db).await, | |
| 702 | + (0, 0), | |
| 703 | + "the loop kept a high mark with no high mark stored" | |
| 704 | + ); | |
| 705 | + } | |
| 706 | + | |
| 707 | + /// The other half of the same asymmetry: a refund read off a stored mark | |
| 708 | + /// that was never credited eats a credit earned somewhere else. One exam | |
| 709 | + /// holds a genuine high mark while a second is graded low, regraded high | |
| 710 | + /// and deleted — the first exam's credit must still be standing. | |
| 711 | + #[tokio::test] | |
| 712 | + async fn one_exams_regrade_never_eats_another_exams_high_mark() { | |
| 713 | + let db = init_mem().await.unwrap(); | |
| 714 | + let first = ExamId::from_key("01TESTEXAMSTEALONEAAAAAAAA"); | |
| 715 | + let second = ExamId::from_key("01TESTEXAMSTEALTWOAAAAAAAA"); | |
| 716 | + an_exam(&db, &first, "midterm").await; | |
| 717 | + an_exam(&db, &second, "midterm").await; | |
| 718 | + the_two_people(&db).await; | |
| 719 | + let student = UserId::from_key(STUDENT); | |
| 720 | + | |
| 721 | + grade(&db, &first, 1, 95, "midterm").await.unwrap(); | |
| 722 | + assert_eq!( | |
| 723 | + badge_counters(&db).await, | |
| 724 | + (1, 1), | |
| 725 | + "earned on the first exam" | |
| 726 | + ); | |
| 727 | + | |
| 728 | + grade(&db, &second, 1, 40, "midterm").await.unwrap(); | |
| 729 | + grade(&db, &second, 1, 95, "midterm").await.unwrap(); | |
| 730 | + assert_eq!(badge_counters(&db).await, (2, 2)); | |
| 731 | + remove(&db, &second, &student, "midterm") | |
| 732 | + .await | |
| 733 | + .unwrap() | |
| 734 | + .expect("the mark was there"); | |
| 735 | + assert_eq!( | |
| 736 | + badge_counters(&db).await, | |
| 737 | + (1, 1), | |
| 738 | + "the first exam's high mark was eaten" | |
| 739 | + ); | |
| 740 | + } | |
| 741 | + | |
| 742 | + /// A refused mark leaves the badge counters where the other two are left. | |
| 743 | + #[tokio::test] | |
| 744 | + async fn a_refused_mark_credits_nobody() { | |
| 745 | + let db = init_mem().await.unwrap(); | |
| 746 | + let exam = ExamId::from_key("01TESTEXAMBADGEDRAFTAAAAAA"); | |
| 747 | + an_exam(&db, &exam, "midterm").await; | |
| 748 | + the_two_people(&db).await; | |
| 749 | + db.query("UPDATE $ex SET draft = true") | |
| 750 | + .bind(("ex", exam.record())) | |
| 751 | + .await | |
| 752 | + .unwrap() | |
| 753 | + .check() | |
| 754 | + .unwrap(); | |
| 755 | + | |
| 756 | + assert!(grade(&db, &exam, 1, 100, "midterm").await.is_err()); | |
| 757 | + assert_eq!(badge_counters(&db).await, (0, 0)); | |
| 758 | + } | |
| 759 | + | |
| 760 | + /// A retired kind refuses the claim from inside the transaction, which | |
| 761 | + /// takes the mark and the exam's counter down with it — the settings guard | |
| 762 | + /// enforcing the same invariant from the other side. | |
| 763 | + #[tokio::test] | |
| 764 | + async fn a_retired_kind_refuses_the_mark_and_leaves_both_counters_alone() { | |
| 765 | + let db = init_mem().await.unwrap(); | |
| 766 | + let exam = ExamId::from_key("01TESTEXAMRETIREDAAAAAAAAA"); | |
| 767 | + an_exam(&db, &exam, "midterm").await; | |
| 768 | + assert!(cap::retire(&kind_ref("midterm"), &db).await.unwrap()); | |
| 769 | + | |
| 770 | + let refused = grade(&db, &exam, 1, 40, "midterm").await; | |
| 771 | + assert!( | |
| 772 | + matches!(&refused, Err(AppError::ConflictOwned(message)) | |
| 773 | + if message.contains("has been removed from the school's settings")), | |
| 774 | + "{refused:?}" | |
| 775 | + ); | |
| 776 | + assert!( | |
| 777 | + list_for_exam(&db, &exam).await.unwrap().is_empty(), | |
| 778 | + "the mark must not have landed" | |
| 779 | + ); | |
| 780 | + assert_eq!(counters(&db, "midterm").await, (0, 0)); | |
| 781 | + } | |
| 782 | + | |
| 783 | + /// A draft exam refuses the mark, and the counters stay put — the gate | |
| 784 | + /// runs before the claim now, so there is nothing to give back. | |
| 785 | + #[tokio::test] | |
| 786 | + async fn a_draft_exam_refuses_the_mark_and_leaves_both_counters_alone() { | |
| 787 | + let db = init_mem().await.unwrap(); | |
| 788 | + let exam = ExamId::from_key("01TESTEXAMDRAFTAAAAAAAAAAA"); | |
| 789 | + an_exam(&db, &exam, "midterm").await; | |
| 790 | + db.query("UPDATE $ex SET draft = true") | |
| 791 | + .bind(("ex", exam.record())) | |
| 792 | + .await | |
| 793 | + .unwrap() | |
| 794 | + .check() | |
| 795 | + .unwrap(); | |
| 796 | + | |
| 797 | + let refused = grade(&db, &exam, 1, 40, "midterm").await; | |
| 798 | + assert!(matches!(refused, Err(AppError::Conflict(_))), "{refused:?}"); | |
| 799 | + assert!(list_for_exam(&db, &exam).await.unwrap().is_empty()); | |
| 800 | + assert_eq!(counters(&db, "midterm").await, (0, 0)); | |
| 801 | + } | |
| 802 | +} |
src/db/mod.rsmodified+4 -0
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | //! The only layer that executes queries. |
| 2 | 2 | |
| 3 | +pub mod answer_image; | |
| 3 | 4 | pub mod appointment; |
| 4 | 5 | pub mod appointment_slot; |
| 5 | 6 | pub mod cap; |
| @@ -8,13 +9,16 @@ pub mod course; | ||
| 8 | 9 | pub mod course_session; |
| 9 | 10 | pub mod enrollment; |
| 10 | 11 | pub mod exam; |
| 12 | +pub mod exam_answer; | |
| 11 | 13 | pub mod exam_attempt; |
| 12 | 14 | pub mod exam_question; |
| 15 | +pub mod exam_result; | |
| 13 | 16 | pub mod field_update; |
| 14 | 17 | pub mod meal_booking; |
| 15 | 18 | pub mod note; |
| 16 | 19 | pub mod page; |
| 17 | 20 | pub mod payment_ledger; |
| 21 | +pub mod question_image; | |
| 18 | 22 | pub mod session; |
| 19 | 23 | pub mod settings; |
| 20 | 24 | pub mod user; |
src/db/question_image.rsadded+332 -0
| @@ -0,0 +1,332 @@ | ||
| 1 | +//! The `question_image` table: the slot-keyed upsert (and delete) behind the | |
| 2 | +//! question-freeze gate, the listing reads, and the choice-cleanup sweep a | |
| 3 | +//! question PATCH drives. The row's pure half — ids and the fresh-blob-name | |
| 4 | +//! constructor — lives in [`crate::domain::question_image`]; the blob bytes | |
| 5 | +//! stay the web layer's. | |
| 6 | + | |
| 7 | +use surrealdb::types::SurrealValue; | |
| 8 | + | |
| 9 | +use crate::database::Database; | |
| 10 | +use crate::domain::course::CourseId; | |
| 11 | +use crate::domain::exam::ExamId; | |
| 12 | +use crate::domain::exam_question::{ChoiceId, ExamQuestionId}; | |
| 13 | +use crate::domain::question_image::{QuestionImage, QuestionImageId}; | |
| 14 | +use crate::error::AppError; | |
| 15 | + | |
| 16 | +/// What one [`upsert`] transaction returns: the row it stored | |
| 17 | +/// and the blob name it replaced. Both are arrays because SurrealDB drops an object | |
| 18 | +/// key valued `NONE` on the way out, while an empty array survives — "nothing | |
| 19 | +/// was replaced" has to be readable, not missing. | |
| 20 | +#[derive(SurrealValue)] | |
| 21 | +struct UpsertOutcome { | |
| 22 | + stored: Vec<QuestionImage>, | |
| 23 | + replaced: Vec<String>, | |
| 24 | +} | |
| 25 | + | |
| 26 | +/// Create or replace the slot's image row — the deterministic id makes | |
| 27 | +/// this the whole "one image per slot" story — handing back what it stored | |
| 28 | +/// plus the blob name it replaced, for the caller to take off disk. Refused | |
| 29 | +/// once the exam has an attempt: pictures are part of the question, so they | |
| 30 | +/// freeze with it, and the gate is in this transaction rather than in a lock | |
| 31 | +/// the caller held. | |
| 32 | +/// | |
| 33 | +/// The replaced name is read *here*, not by the caller before it: two | |
| 34 | +/// uploads to one slot both write this row, so they contend and the loser | |
| 35 | +/// re-reads the winner's blob name, where two pre-reads both saw the *old* | |
| 36 | +/// blob and left the loser's fresh one orphaned on disk. | |
| 37 | +pub async fn upsert( | |
| 38 | + db: &Database, | |
| 39 | + image: QuestionImage, | |
| 40 | +) -> Result<(QuestionImage, Option<String>), AppError> { | |
| 41 | + // whole-row-save-ok: image is built in place, never read back, and the slot id is deterministic | |
| 42 | + let (exam, id) = (image.exam.clone(), image.id.record()); | |
| 43 | + let mut result = crate::db::exam_attempt::write_unfrozen( | |
| 44 | + db, | |
| 45 | + &exam, | |
| 46 | + "LET $replaced = (SELECT VALUE file FROM $id); | |
| 47 | + LET $stored = (UPSERT $id CONTENT $image); | |
| 48 | + RETURN { stored: $stored, replaced: $replaced };", | |
| 49 | + vec![ | |
| 50 | + ("id".into(), id.into_value()), | |
| 51 | + ("image".into(), image.into_value()), | |
| 52 | + ], | |
| 53 | + ) | |
| 54 | + .await?; | |
| 55 | + // The trailing `RETURN` is the last statement before `COMMIT`, so its | |
| 56 | + // slot follows the statement count rather than a hand-kept number; | |
| 57 | + // `num_statements` counts BEGIN and COMMIT. | |
| 58 | + let slot = result.num_statements().saturating_sub(2); | |
| 59 | + let failed = || AppError::Internal("failed to store question image".into()); | |
| 60 | + let outcome = result | |
| 61 | + .take::<Vec<UpsertOutcome>>(slot)? | |
| 62 | + .into_iter() | |
| 63 | + .next() | |
| 64 | + .ok_or_else(failed)?; | |
| 65 | + let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; | |
| 66 | + Ok((stored, outcome.replaced.into_iter().next())) | |
| 67 | +} | |
| 68 | + | |
| 69 | +pub async fn read_slot( | |
| 70 | + db: &Database, | |
| 71 | + question: &ExamQuestionId, | |
| 72 | + slot: Option<&ChoiceId>, | |
| 73 | +) -> Result<Option<QuestionImage>, AppError> { | |
| 74 | + Ok(db | |
| 75 | + .select(QuestionImageId::for_slot(question, slot).record()) | |
| 76 | + .await?) | |
| 77 | +} | |
| 78 | + | |
| 79 | +/// Every image of the exam's questions — one query for the list views. | |
| 80 | +pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<QuestionImage>, AppError> { | |
| 81 | + let mut result = db | |
| 82 | + .query("SELECT * FROM question_image WHERE exam = $ex") | |
| 83 | + .bind(("ex", exam.record())) | |
| 84 | + .await? | |
| 85 | + .check()?; | |
| 86 | + Ok(result.take::<Vec<QuestionImage>>(0)?) | |
| 87 | +} | |
| 88 | + | |
| 89 | +pub async fn list_for_question( | |
| 90 | + db: &Database, | |
| 91 | + question: &ExamQuestionId, | |
| 92 | +) -> Result<Vec<QuestionImage>, AppError> { | |
| 93 | + let mut result = db | |
| 94 | + .query("SELECT * FROM question_image WHERE question = $q") | |
| 95 | + .bind(("q", question.record())) | |
| 96 | + .await? | |
| 97 | + .check()?; | |
| 98 | + Ok(result.take::<Vec<QuestionImage>>(0)?) | |
| 99 | +} | |
| 100 | + | |
| 101 | +/// Drop the option pictures whose choice is gone — every choice image of | |
| 102 | +/// the question whose `slot` is *not* in `keep` (the question's own | |
| 103 | +/// illustration always stays), returning the removed rows so the caller can | |
| 104 | +/// take their blobs off disk. | |
| 105 | +/// | |
| 106 | +/// This is what makes an edit non-destructive: a PATCH that reorders, | |
| 107 | +/// renames, or drops options passes the surviving choice ids as `keep`, so | |
| 108 | +/// only the pictures of genuinely removed options go. `keep = &[]` (a text | |
| 109 | +/// question, or an all-new choice list) still clears the lot. | |
| 110 | +pub async fn delete_choices_not_in( | |
| 111 | + db: &Database, | |
| 112 | + question: &ExamQuestionId, | |
| 113 | + keep: &[ChoiceId], | |
| 114 | +) -> Result<Vec<QuestionImage>, AppError> { | |
| 115 | + let keep: Vec<String> = keep.iter().map(|id| id.as_str().to_string()).collect(); | |
| 116 | + let mut result = db | |
| 117 | + .query( | |
| 118 | + "DELETE question_image \ | |
| 119 | + WHERE question = $q AND slot != NONE AND slot NOT IN $keep RETURN BEFORE", | |
| 120 | + ) | |
| 121 | + .bind(("q", question.record())) | |
| 122 | + .bind(("keep", keep)) | |
| 123 | + .await? | |
| 124 | + .check()?; | |
| 125 | + Ok(result.take::<Vec<QuestionImage>>(0)?) | |
| 126 | +} | |
| 127 | + | |
| 128 | +/// The blob names behind every image of every exam of `course` — collected | |
| 129 | +/// *before* the course-delete cascade wipes the rows. | |
| 130 | +pub async fn file_keys_for_course( | |
| 131 | + db: &Database, | |
| 132 | + course: &CourseId, | |
| 133 | +) -> Result<Vec<String>, AppError> { | |
| 134 | + let mut result = db | |
| 135 | + .query( | |
| 136 | + "SELECT VALUE file FROM question_image \ | |
| 137 | + WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)", | |
| 138 | + ) | |
| 139 | + .bind(("course", course.record())) | |
| 140 | + .await? | |
| 141 | + .check()?; | |
| 142 | + Ok(result.take::<Vec<String>>(0)?) | |
| 143 | +} | |
| 144 | + | |
| 145 | +/// Refused once the exam has an attempt, in the same transaction — same | |
| 146 | +/// gate, same reason as [`upsert`]. | |
| 147 | +pub async fn delete(db: &Database, image: QuestionImage) -> Result<QuestionImage, AppError> { | |
| 148 | + let mut result = crate::db::exam_attempt::write_unfrozen( | |
| 149 | + db, | |
| 150 | + &image.exam, | |
| 151 | + "DELETE $id RETURN BEFORE;", | |
| 152 | + vec![("id".into(), image.id.record().into_value())], | |
| 153 | + ) | |
| 154 | + .await?; | |
| 155 | + result | |
| 156 | + .take::<Vec<QuestionImage>>(crate::db::exam_attempt::FROZEN_SLOT)? | |
| 157 | + .into_iter() | |
| 158 | + .next() | |
| 159 | + .ok_or(AppError::NotFound) | |
| 160 | +} | |
| 161 | + | |
| 162 | +#[cfg(test)] | |
| 163 | +mod tests { | |
| 164 | + use super::*; | |
| 165 | + use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec}; | |
| 166 | + use crate::domain::note_file::FileContentType; | |
| 167 | + | |
| 168 | + /// A real exam row: an image write moves its exam's counter (that is what | |
| 169 | + /// keeps a picture from outliving its exam), so a minted id nothing wrote | |
| 170 | + /// is a 404. | |
| 171 | + async fn exam_row(db: &Database) -> ExamId { | |
| 172 | + crate::db::exam::published_exam(db).await.get_id().clone() | |
| 173 | + } | |
| 174 | + | |
| 175 | + fn png() -> FileContentType { | |
| 176 | + FileContentType::try_new("image/png").unwrap() | |
| 177 | + } | |
| 178 | + | |
| 179 | + /// Three minted choice ids to slot pictures against. | |
| 180 | + fn choice_ids() -> Vec<ChoiceId> { | |
| 181 | + QuestionSpec::try_new( | |
| 182 | + QuestionKind::try_new("choice").unwrap(), | |
| 183 | + Some( | |
| 184 | + ["a", "b", "c"] | |
| 185 | + .iter() | |
| 186 | + .map(|l| ChoiceInput { | |
| 187 | + id: Some((*l).into()), | |
| 188 | + text: (*l).into(), | |
| 189 | + }) | |
| 190 | + .collect(), | |
| 191 | + ), | |
| 192 | + Some("a".into()), | |
| 193 | + &[], | |
| 194 | + ) | |
| 195 | + .unwrap() | |
| 196 | + .into_parts() | |
| 197 | + .1 | |
| 198 | + .unwrap() | |
| 199 | + .iter() | |
| 200 | + .map(|c| c.get_id().clone()) | |
| 201 | + .collect() | |
| 202 | + } | |
| 203 | + | |
| 204 | + #[tokio::test] | |
| 205 | + async fn upsert_replaces_per_slot() { | |
| 206 | + let db = crate::database::init_mem().await.unwrap(); | |
| 207 | + let exam = exam_row(&db).await; | |
| 208 | + let question = ExamQuestionId::generate(); | |
| 209 | + let ids = choice_ids(); | |
| 210 | + | |
| 211 | + let (first, retired) = upsert(&db, QuestionImage::new(&exam, &question, None, png(), 3)) | |
| 212 | + .await | |
| 213 | + .unwrap(); | |
| 214 | + assert_eq!(retired, None, "a first upload retires no blob"); | |
| 215 | + let (second, retired) = upsert(&db, QuestionImage::new(&exam, &question, None, png(), 5)) | |
| 216 | + .await | |
| 217 | + .unwrap(); | |
| 218 | + // Same slot, same row — the replace swapped the blob pointer, and the | |
| 219 | + // write itself names the blob the caller must unlink. | |
| 220 | + assert_ne!(first.get_file(), second.get_file()); | |
| 221 | + assert_eq!(retired.as_deref(), Some(first.get_file())); | |
| 222 | + let rows = list_for_question(&db, &question).await.unwrap(); | |
| 223 | + assert_eq!(rows.len(), 1); | |
| 224 | + assert_eq!(rows[0].get_size(), 5); | |
| 225 | + | |
| 226 | + // A choice slot is its own row, keyed by the option's id. | |
| 227 | + upsert( | |
| 228 | + &db, | |
| 229 | + QuestionImage::new(&exam, &question, Some(&ids[0]), png(), 7), | |
| 230 | + ) | |
| 231 | + .await | |
| 232 | + .unwrap(); | |
| 233 | + assert_eq!(list_for_question(&db, &question).await.unwrap().len(), 2); | |
| 234 | + let choice = read_slot(&db, &question, Some(&ids[0])) | |
| 235 | + .await | |
| 236 | + .unwrap() | |
| 237 | + .unwrap(); | |
| 238 | + assert_eq!(choice.get_slot(), Some(&ids[0])); | |
| 239 | + assert!( | |
| 240 | + read_slot(&db, &question, Some(&ids[1])) | |
| 241 | + .await | |
| 242 | + .unwrap() | |
| 243 | + .is_none() | |
| 244 | + ); | |
| 245 | + } | |
| 246 | + | |
| 247 | + /// The behaviour the whole remodel exists for: an edit that keeps some | |
| 248 | + /// options keeps exactly their pictures, and drops only the removed one's. | |
| 249 | + #[tokio::test] | |
| 250 | + async fn only_the_dropped_options_lose_their_pictures() { | |
| 251 | + let db = crate::database::init_mem().await.unwrap(); | |
| 252 | + let exam = exam_row(&db).await; | |
| 253 | + let question = ExamQuestionId::generate(); | |
| 254 | + let ids = choice_ids(); | |
| 255 | + upsert(&db, QuestionImage::new(&exam, &question, None, png(), 1)) | |
| 256 | + .await | |
| 257 | + .unwrap(); | |
| 258 | + for id in &ids { | |
| 259 | + upsert( | |
| 260 | + &db, | |
| 261 | + QuestionImage::new(&exam, &question, Some(id), png(), 1), | |
| 262 | + ) | |
| 263 | + .await | |
| 264 | + .unwrap(); | |
| 265 | + } | |
| 266 | + | |
| 267 | + // Keep the first and last option (reordered — order is irrelevant now). | |
| 268 | + let keep = vec![ids[2].clone(), ids[0].clone()]; | |
| 269 | + let dropped = delete_choices_not_in(&db, &question, &keep).await.unwrap(); | |
| 270 | + assert_eq!(dropped.len(), 1); | |
| 271 | + assert_eq!(dropped[0].get_slot(), Some(&ids[1])); | |
| 272 | + | |
| 273 | + let left = list_for_question(&db, &question).await.unwrap(); | |
| 274 | + // The question illustration plus the two surviving option pictures. | |
| 275 | + assert_eq!(left.len(), 3); | |
| 276 | + assert!( | |
| 277 | + read_slot(&db, &question, Some(&ids[0])) | |
| 278 | + .await | |
| 279 | + .unwrap() | |
| 280 | + .is_some() | |
| 281 | + ); | |
| 282 | + assert!( | |
| 283 | + read_slot(&db, &question, Some(&ids[2])) | |
| 284 | + .await | |
| 285 | + .unwrap() | |
| 286 | + .is_some() | |
| 287 | + ); | |
| 288 | + assert!(read_slot(&db, &question, None).await.unwrap().is_some()); | |
| 289 | + } | |
| 290 | + | |
| 291 | + #[tokio::test] | |
| 292 | + async fn an_empty_keep_set_clears_every_option_picture_but_not_the_illustration() { | |
| 293 | + let db = crate::database::init_mem().await.unwrap(); | |
| 294 | + let exam = exam_row(&db).await; | |
| 295 | + let question = ExamQuestionId::generate(); | |
| 296 | + let ids = choice_ids(); | |
| 297 | + upsert(&db, QuestionImage::new(&exam, &question, None, png(), 1)) | |
| 298 | + .await | |
| 299 | + .unwrap(); | |
| 300 | + for id in &ids[..2] { | |
| 301 | + upsert( | |
| 302 | + &db, | |
| 303 | + QuestionImage::new(&exam, &question, Some(id), png(), 1), | |
| 304 | + ) | |
| 305 | + .await | |
| 306 | + .unwrap(); | |
| 307 | + } | |
| 308 | + | |
| 309 | + let dropped = delete_choices_not_in(&db, &question, &[]).await.unwrap(); | |
| 310 | + assert_eq!(dropped.len(), 2); | |
| 311 | + assert!(dropped.iter().all(|image| image.get_slot().is_some())); | |
| 312 | + | |
| 313 | + let left = list_for_question(&db, &question).await.unwrap(); | |
| 314 | + assert_eq!(left.len(), 1); | |
| 315 | + assert_eq!(left[0].get_slot(), None); | |
| 316 | + } | |
| 317 | + | |
| 318 | + #[tokio::test] | |
| 319 | + async fn exam_listing_scopes_by_exam() { | |
| 320 | + let db = crate::database::init_mem().await.unwrap(); | |
| 321 | + let exam_a = exam_row(&db).await; | |
| 322 | + let exam_b = exam_row(&db).await; | |
| 323 | + upsert( | |
| 324 | + &db, | |
| 325 | + QuestionImage::new(&exam_a, &ExamQuestionId::generate(), None, png(), 1), | |
| 326 | + ) | |
| 327 | + .await | |
| 328 | + .unwrap(); | |
| 329 | + assert_eq!(list_for_exam(&db, &exam_a).await.unwrap().len(), 1); | |
| 330 | + assert!(list_for_exam(&db, &exam_b).await.unwrap().is_empty()); | |
| 331 | + } | |
| 332 | +} |
src/domain/answer_image.rsmodified+15 -340
| @@ -8,22 +8,20 @@ | ||
| 8 | 8 | //! shape as [`crate::domain::exam_attempt::ExamAttemptId::composite`] — so "one |
| 9 | 9 | //! drawing per student per question per sitting" holds by construction and a |
| 10 | 10 | //! replace within a sitting is a plain UPSERT, while a retake (`seq + 1`) |
| 11 | -//! accumulates its own rows instead of overwriting. The web layer owns the | |
| 12 | -//! blob I/O and its ordering (new blob before row, row before old blob); this | |
| 13 | -//! module owns the rows. | |
| 11 | +//! accumulates its own rows instead of overwriting. The queries and | |
| 12 | +//! transactions over these rows live in [`crate::db::answer_image`]; the web | |
| 13 | +//! layer owns the blob I/O and its ordering (new blob before row, row before | |
| 14 | +//! old blob). | |
| 14 | 15 | |
| 15 | 16 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 16 | 17 | use ulid::Ulid; |
| 17 | 18 | |
| 18 | -use crate::constant::{ANSWER_IMAGE_TABLE, EXAM_RESULT_COUNT_FIELD}; | |
| 19 | -use crate::database::{Database, transaction_with_retry}; | |
| 20 | -use crate::domain::course::CourseId; | |
| 19 | +use crate::constant::ANSWER_IMAGE_TABLE; | |
| 21 | 20 | use crate::domain::exam::ExamId; |
| 22 | 21 | use crate::domain::exam_question::ExamQuestionId; |
| 23 | 22 | use crate::domain::key; |
| 24 | 23 | use crate::domain::note_file::FileContentType; |
| 25 | 24 | use crate::domain::user::UserId; |
| 26 | -use crate::error::AppError; | |
| 27 | 25 | |
| 28 | 26 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 29 | 27 | pub struct AnswerImageId(RecordId); |
| @@ -55,33 +53,24 @@ impl AnswerImageId { | ||
| 55 | 53 | /// through `exam_question`. |
| 56 | 54 | #[derive(Debug, Clone, SurrealValue)] |
| 57 | 55 | pub struct AnswerImage { |
| 58 | - id: AnswerImageId, | |
| 59 | - exam: ExamId, | |
| 60 | - question: ExamQuestionId, | |
| 61 | - user: UserId, | |
| 56 | + pub(crate) id: AnswerImageId, | |
| 57 | + pub(crate) exam: ExamId, | |
| 58 | + pub(crate) question: ExamQuestionId, | |
| 59 | + pub(crate) user: UserId, | |
| 62 | 60 | /// Which sitting this drawing belongs to — 1 for the first attempt, |
| 63 | 61 | /// counting up, so retakes accumulate instead of overwriting. |
| 64 | - seq: i64, | |
| 62 | + pub(crate) seq: i64, | |
| 65 | 63 | /// The blob's on-disk name — a fresh ULID every upload. |
| 66 | - file: String, | |
| 67 | - content_type: FileContentType, | |
| 68 | - size: i64, | |
| 69 | -} | |
| 70 | - | |
| 71 | -/// What one [`AnswerImage::upsert`] transaction returns: the row it stored and | |
| 72 | -/// the blob name it replaced. Both are arrays because SurrealDB drops an object | |
| 73 | -/// key valued `NONE` on the way out, while an empty array survives — "nothing | |
| 74 | -/// was replaced" has to be readable, not missing. | |
| 75 | -#[derive(SurrealValue)] | |
| 76 | -struct UpsertOutcome { | |
| 77 | - stored: Vec<AnswerImage>, | |
| 78 | - replaced: Vec<String>, | |
| 64 | + pub(crate) file: String, | |
| 65 | + pub(crate) content_type: FileContentType, | |
| 66 | + pub(crate) size: i64, | |
| 79 | 67 | } |
| 80 | 68 | |
| 81 | 69 | impl AnswerImage { |
| 82 | 70 | /// Assemble a row (fresh blob name generated here) without persisting it. |
| 83 | 71 | /// The caller writes the blob under [`Self::get_file`] first, then calls |
| 84 | - /// [`Self::upsert`] — so a stored row always points at a real blob. | |
| 72 | + /// [`crate::db::answer_image::upsert`] — so a stored row always points at | |
| 73 | + /// a real blob. | |
| 85 | 74 | pub fn new( |
| 86 | 75 | exam: &ExamId, |
| 87 | 76 | question: &ExamQuestionId, |
| @@ -122,318 +111,4 @@ impl AnswerImage { | ||
| 122 | 111 | pub fn get_size(&self) -> i64 { |
| 123 | 112 | self.size |
| 124 | 113 | } |
| 125 | - | |
| 126 | - /// Create or replace the student's drawing for the question — the | |
| 127 | - /// deterministic id makes this the whole "one drawing per student per | |
| 128 | - /// question" story — handing back what it stored plus the blob name it | |
| 129 | - /// replaced, for the caller to take off disk. | |
| 130 | - /// | |
| 131 | - /// The replaced name is read *here*, inside this transaction, not by the | |
| 132 | - /// caller in front of it: two uploads to one (question, user, seq) both | |
| 133 | - /// write this row, so they contend and the loser re-reads the winner's blob | |
| 134 | - /// name, where two pre-reads both saw the *old* blob and left the loser's | |
| 135 | - /// fresh one on disk with nothing pointing at it. Same shape as | |
| 136 | - /// [`crate::domain::question_image::QuestionImage::upsert`]. | |
| 137 | - /// | |
| 138 | - /// `NotFound` = the exam is gone, and the drawing was *not* written. The | |
| 139 | - /// write moves the exam's mark counter and puts it straight back, in this | |
| 140 | - /// one transaction, so the exam's existence is something this write | |
| 141 | - /// *writes* rather than something a gate read a moment earlier: a bare | |
| 142 | - /// upsert landing after [`delete`](crate::db::exam::delete) | |
| 143 | - /// removed the exam but before it committed was swept by nothing — its | |
| 144 | - /// `DELETE answer_image WHERE exam = $ex` ran on a snapshot predating this | |
| 145 | - /// row — and both sides reported success. That stranded the blob as well as | |
| 146 | - /// the row: `delete_exam` collects the names to unlink *before* it calls | |
| 147 | - /// the delete, so bytes written after that snapshot stay on disk forever. | |
| 148 | - /// This is the shape [`crate::domain::exam_answer::ExamAnswer::save`] takes | |
| 149 | - /// for the text half of the same answer sheet, and for the same reason. | |
| 150 | - /// | |
| 151 | - /// The restore is by captured value, `NONE` included, so the row is | |
| 152 | - /// byte-identical afterwards and a teacher's PATCH — which pins that | |
| 153 | - /// counter — is not refused because a student drew. Writing the same value | |
| 154 | - /// back would buy nothing: an `UPDATE` that leaves the document unchanged | |
| 155 | - /// is elided and never reaches the store's write set. | |
| 156 | - /// | |
| 157 | - /// Admissible for [`transaction_with_retry`]: the `UPDATE`s, `SELECT`, | |
| 158 | - /// `IF`/`THROW` and `RETURN` can never answer "already exists", and the | |
| 159 | - /// `UPSERT`'s id is bijective with the (question, user, seq) triple this | |
| 160 | - /// table keys — a lost round wrote nothing, and re-sending resolves onto | |
| 161 | - /// the same row rather than colliding with it. | |
| 162 | - pub async fn upsert(self, db: &Database) -> Result<(AnswerImage, Option<String>), AppError> { | |
| 163 | - // 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 | |
| 164 | - let (exam, id) = (self.exam.record(), self.id.record()); | |
| 165 | - let (mut result, mut errors) = transaction_with_retry( | |
| 166 | - db, | |
| 167 | - &format!( | |
| 168 | - "BEGIN TRANSACTION; | |
| 169 | - LET $was = (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $ex); | |
| 170 | - LET $touched = (UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = \ | |
| 171 | - ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); | |
| 172 | - IF array::len($touched) = 0 {{ THROW 'no_exam' }}; | |
| 173 | - UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = $was; | |
| 174 | - LET $replaced = (SELECT VALUE file FROM $id); | |
| 175 | - LET $row = (UPSERT $id CONTENT $image RETURN AFTER); | |
| 176 | - RETURN {{ stored: $row, replaced: $replaced }}; | |
| 177 | - COMMIT TRANSACTION;" | |
| 178 | - ), | |
| 179 | - &[ | |
| 180 | - ("ex".into(), exam.into_value()), | |
| 181 | - ("id".into(), id.into_value()), | |
| 182 | - ("image".into(), self.into_value()), | |
| 183 | - ], | |
| 184 | - &["no_exam"], | |
| 185 | - ) | |
| 186 | - .await?; | |
| 187 | - // An aborted transaction errors *every* slot, most with a generic "not | |
| 188 | - // executed" — only the THROW's own slot names the reason. | |
| 189 | - if errors | |
| 190 | - .values() | |
| 191 | - .any(|error| error.to_string().contains("no_exam")) | |
| 192 | - { | |
| 193 | - return Err(AppError::NotFound); | |
| 194 | - } | |
| 195 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | |
| 196 | - return Err(error.into()); | |
| 197 | - } | |
| 198 | - // The trailing `RETURN` is the last statement before `COMMIT`, so its | |
| 199 | - // slot follows the statement count rather than a hand-kept number; | |
| 200 | - // `num_statements` counts BEGIN and COMMIT. | |
| 201 | - let slot = result.num_statements().saturating_sub(2); | |
| 202 | - let failed = || AppError::Internal("failed to store answer image".into()); | |
| 203 | - let outcome = result | |
| 204 | - .take::<Vec<UpsertOutcome>>(slot)? | |
| 205 | - .into_iter() | |
| 206 | - .next() | |
| 207 | - .ok_or_else(failed)?; | |
| 208 | - let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; | |
| 209 | - Ok((stored, outcome.replaced.into_iter().next())) | |
| 210 | - } | |
| 211 | - | |
| 212 | - /// The student's drawing for one question in one sitting, if any. | |
| 213 | - pub async fn read( | |
| 214 | - question: &ExamQuestionId, | |
| 215 | - user: &UserId, | |
| 216 | - seq: i64, | |
| 217 | - db: &Database, | |
| 218 | - ) -> Result<Option<AnswerImage>, AppError> { | |
| 219 | - Ok(db | |
| 220 | - .select(AnswerImageId::composite(question, user, seq).record()) | |
| 221 | - .await?) | |
| 222 | - } | |
| 223 | - | |
| 224 | - /// Every answer drawing of the exam — one query for the exam-delete cascade. | |
| 225 | - pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<AnswerImage>, AppError> { | |
| 226 | - let mut result = db | |
| 227 | - .query("SELECT * FROM answer_image WHERE exam = $ex") | |
| 228 | - .bind(("ex", exam.record())) | |
| 229 | - .await? | |
| 230 | - .check()?; | |
| 231 | - Ok(result.take::<Vec<AnswerImage>>(0)?) | |
| 232 | - } | |
| 233 | - | |
| 234 | - /// One student's answer drawings for a single sitting — the parallel to | |
| 235 | - /// [`crate::domain::exam_answer::ExamAnswer::list_for_exam_user`], feeding | |
| 236 | - /// the sitting/grading answer-image maps for that attempt's `seq`. | |
| 237 | - pub async fn list_for_exam_user( | |
| 238 | - exam: &ExamId, | |
| 239 | - user: &UserId, | |
| 240 | - seq: i64, | |
| 241 | - db: &Database, | |
| 242 | - ) -> Result<Vec<AnswerImage>, AppError> { | |
| 243 | - let mut result = db | |
| 244 | - .query("SELECT * FROM answer_image WHERE exam = $ex AND user = $usr AND seq = $seq") | |
| 245 | - .bind(("ex", exam.record())) | |
| 246 | - .bind(("usr", user.record())) | |
| 247 | - .bind(("seq", seq)) | |
| 248 | - .await? | |
| 249 | - .check()?; | |
| 250 | - Ok(result.take::<Vec<AnswerImage>>(0)?) | |
| 251 | - } | |
| 252 | - | |
| 253 | - /// The distinct sittings (`seq`, ascending) this student has any answer | |
| 254 | - /// drawing for at this exam — the history index behind a per-attempt view. | |
| 255 | - pub async fn list_seqs_for_user( | |
| 256 | - exam: &ExamId, | |
| 257 | - user: &UserId, | |
| 258 | - db: &Database, | |
| 259 | - ) -> Result<Vec<i64>, AppError> { | |
| 260 | - let mut result = db | |
| 261 | - .query( | |
| 262 | - "SELECT VALUE seq FROM answer_image \ | |
| 263 | - WHERE exam = $ex AND user = $usr ORDER BY seq", | |
| 264 | - ) | |
| 265 | - .bind(("ex", exam.record())) | |
| 266 | - .bind(("usr", user.record())) | |
| 267 | - .await? | |
| 268 | - .check()?; | |
| 269 | - let mut seqs = result.take::<Vec<i64>>(0)?; | |
| 270 | - seqs.dedup(); | |
| 271 | - Ok(seqs) | |
| 272 | - } | |
| 273 | - | |
| 274 | - /// The blob names behind every answer drawing of every exam of `course` — | |
| 275 | - /// collected *before* the course-delete cascade wipes the rows. | |
| 276 | - pub async fn file_keys_for_course( | |
| 277 | - course: &CourseId, | |
| 278 | - db: &Database, | |
| 279 | - ) -> Result<Vec<String>, AppError> { | |
| 280 | - let mut result = db | |
| 281 | - .query( | |
| 282 | - "SELECT VALUE file FROM answer_image \ | |
| 283 | - WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)", | |
| 284 | - ) | |
| 285 | - .bind(("course", course.record())) | |
| 286 | - .await? | |
| 287 | - .check()?; | |
| 288 | - Ok(result.take::<Vec<String>>(0)?) | |
| 289 | - } | |
| 290 | - | |
| 291 | - pub async fn delete(self, db: &Database) -> Result<AnswerImage, AppError> { | |
| 292 | - let deleted: Option<AnswerImage> = db.delete(self.id.record()).await?; | |
| 293 | - deleted.ok_or(AppError::NotFound) | |
| 294 | - } | |
| 295 | - | |
| 296 | - /// Drop one student's answer drawings across an exam — a retake starts from | |
| 297 | - /// a blank sheet. Rows only; the caller GCs the blobs. The retake path itself | |
| 298 | - /// wipes rows inside `ExamAttempt::wipe_and_create`'s transaction; this is | |
| 299 | - /// the standalone mirror of [`crate::domain::exam_answer::ExamAnswer::delete_for_exam_user`]. | |
| 300 | - pub async fn delete_for_exam_user( | |
| 301 | - exam: &ExamId, | |
| 302 | - user: &UserId, | |
| 303 | - db: &Database, | |
| 304 | - ) -> Result<(), AppError> { | |
| 305 | - db.query("DELETE answer_image WHERE exam = $ex AND user = $usr") | |
| 306 | - .bind(("ex", exam.record())) | |
| 307 | - .bind(("usr", user.record())) | |
| 308 | - .await? | |
| 309 | - .check()?; | |
| 310 | - Ok(()) | |
| 311 | - } | |
| 312 | -} | |
| 313 | - | |
| 314 | -#[cfg(test)] | |
| 315 | -mod tests { | |
| 316 | - use super::*; | |
| 317 | - | |
| 318 | - fn png() -> FileContentType { | |
| 319 | - FileContentType::try_new("image/png").unwrap() | |
| 320 | - } | |
| 321 | - | |
| 322 | - /// A real exam row: a drawing's write moves its exam's counter (that is | |
| 323 | - /// what keeps it from outliving the exam), so a minted id nothing wrote is | |
| 324 | - /// a 404. | |
| 325 | - async fn exam_row(db: &Database) -> ExamId { | |
| 326 | - crate::db::exam::published_exam(db).await.get_id().clone() | |
| 327 | - } | |
| 328 | - | |
| 329 | - fn student() -> UserId { | |
| 330 | - UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA") | |
| 331 | - } | |
| 332 | - | |
| 333 | - #[tokio::test] | |
| 334 | - async fn upsert_replaces_within_a_sitting_but_not_across_them() { | |
| 335 | - let db = crate::database::init_mem().await.unwrap(); | |
| 336 | - let exam = exam_row(&db).await; | |
| 337 | - let question = ExamQuestionId::generate(); | |
| 338 | - let user = student(); | |
| 339 | - | |
| 340 | - let (first, retired) = AnswerImage::new(&exam, &question, &user, 1, png(), 3) | |
| 341 | - .upsert(&db) | |
| 342 | - .await | |
| 343 | - .unwrap(); | |
| 344 | - assert_eq!(retired, None, "a first upload retires no blob"); | |
| 345 | - let (second, retired) = AnswerImage::new(&exam, &question, &user, 1, png(), 5) | |
| 346 | - .upsert(&db) | |
| 347 | - .await | |
| 348 | - .unwrap(); | |
| 349 | - // Same (question, user, seq), same row — the replace swapped the blob, | |
| 350 | - // and the write itself names the blob the caller must unlink. | |
| 351 | - assert_ne!(first.get_file(), second.get_file()); | |
| 352 | - assert_eq!(retired.as_deref(), Some(first.get_file())); | |
| 353 | - let rows = AnswerImage::list_for_exam_user(&exam, &user, 1, &db) | |
| 354 | - .await | |
| 355 | - .unwrap(); | |
| 356 | - assert_eq!(rows.len(), 1); | |
| 357 | - assert_eq!(rows[0].get_size(), 5); | |
| 358 | - | |
| 359 | - // A retake (seq 2) accumulates: it is its own row, not an overwrite. | |
| 360 | - AnswerImage::new(&exam, &question, &user, 2, png(), 9) | |
| 361 | - .upsert(&db) | |
| 362 | - .await | |
| 363 | - .unwrap(); | |
| 364 | - assert_eq!( | |
| 365 | - AnswerImage::list_for_exam_user(&exam, &user, 1, &db) | |
| 366 | - .await | |
| 367 | - .unwrap() | |
| 368 | - .len(), | |
| 369 | - 1, | |
| 370 | - "the seq-2 image must not overwrite seq-1" | |
| 371 | - ); | |
| 372 | - assert_eq!( | |
| 373 | - AnswerImage::list_for_exam_user(&exam, &user, 2, &db) | |
| 374 | - .await | |
| 375 | - .unwrap()[0] | |
| 376 | - .get_size(), | |
| 377 | - 9 | |
| 378 | - ); | |
| 379 | - assert_eq!( | |
| 380 | - AnswerImage::list_seqs_for_user(&exam, &user, &db) | |
| 381 | - .await | |
| 382 | - .unwrap(), | |
| 383 | - vec![1, 2] | |
| 384 | - ); | |
| 385 | - | |
| 386 | - // Another student's drawing for the same question/sitting is its own row. | |
| 387 | - let other = UserId::from_key("01TESTSTUDENTBBBBBBBBBBBBB"); | |
| 388 | - AnswerImage::new(&exam, &question, &other, 1, png(), 7) | |
| 389 | - .upsert(&db) | |
| 390 | - .await | |
| 391 | - .unwrap(); | |
| 392 | - assert_eq!( | |
| 393 | - AnswerImage::list_for_exam(&exam, &db).await.unwrap().len(), | |
| 394 | - 3 | |
| 395 | - ); | |
| 396 | - assert!( | |
| 397 | - AnswerImage::read(&question, &user, 2, &db) | |
| 398 | - .await | |
| 399 | - .unwrap() | |
| 400 | - .is_some() | |
| 401 | - ); | |
| 402 | - } | |
| 403 | - | |
| 404 | - #[tokio::test] | |
| 405 | - async fn listing_scopes_by_exam_and_user() { | |
| 406 | - let db = crate::database::init_mem().await.unwrap(); | |
| 407 | - let exam_a = exam_row(&db).await; | |
| 408 | - let exam_b = exam_row(&db).await; | |
| 409 | - let user = student(); | |
| 410 | - AnswerImage::new(&exam_a, &ExamQuestionId::generate(), &user, 1, png(), 1) | |
| 411 | - .upsert(&db) | |
| 412 | - .await | |
| 413 | - .unwrap(); | |
| 414 | - assert_eq!( | |
| 415 | - AnswerImage::list_for_exam_user(&exam_a, &user, 1, &db) | |
| 416 | - .await | |
| 417 | - .unwrap() | |
| 418 | - .len(), | |
| 419 | - 1 | |
| 420 | - ); | |
| 421 | - assert!( | |
| 422 | - AnswerImage::list_for_exam(&exam_b, &db) | |
| 423 | - .await | |
| 424 | - .unwrap() | |
| 425 | - .is_empty() | |
| 426 | - ); | |
| 427 | - | |
| 428 | - // delete_for_exam_user clears the student's sheet across all sittings. | |
| 429 | - AnswerImage::delete_for_exam_user(&exam_a, &user, &db) | |
| 430 | - .await | |
| 431 | - .unwrap(); | |
| 432 | - assert!( | |
| 433 | - AnswerImage::list_for_exam_user(&exam_a, &user, 1, &db) | |
| 434 | - .await | |
| 435 | - .unwrap() | |
| 436 | - .is_empty() | |
| 437 | - ); | |
| 438 | - } | |
| 439 | 114 | } |
src/domain/attendance.rsmodified+2 -2
| @@ -2,8 +2,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | 2 | |
| 3 | 3 | use crate::constant::{ATTENDANCE_TABLE, REGISTRATION_COUNT_FIELD}; |
| 4 | 4 | use crate::database::{Database, transaction_with_retry}; |
| 5 | -use crate::domain::event::EventId; | |
| 6 | 5 | use crate::db::page::PagedList; |
| 6 | +use crate::domain::event::EventId; | |
| 7 | 7 | use crate::domain::user::UserId; |
| 8 | 8 | use crate::error::{AppError, ValidationError}; |
| 9 | 9 | |
| @@ -101,7 +101,7 @@ impl Attendance { | ||
| 101 | 101 | /// Reading the event here would not have closed it either: SurrealDB 3.2.3 |
| 102 | 102 | /// conflict-checks write sets, not read sets, so the proof has to *move* a |
| 103 | 103 | /// value on the event row. It is the bump-and-restore of |
| 104 | - /// [`crate::domain::exam_answer::ExamAnswer::save`], on the counter the | |
| 104 | + /// [`crate::db::exam_answer::save`], on the counter the | |
| 105 | 105 | /// event already carries: matching nothing is the existence gate, writing |
| 106 | 106 | /// the key the delete removes is the collision, and the restore is by |
| 107 | 107 | /// captured value (`NONE` included) so no seat is spent or freed. |
src/domain/chatbot_thread.rsmodified+1 -1
| @@ -60,7 +60,7 @@ impl ChatbotThreadId { | ||
| 60 | 60 | /// Reads do not conflict; only a write that *moves* a value on a key the delete |
| 61 | 61 | /// also writes does. That is the shape |
| 62 | 62 | /// [`bump_menu_and_write`](crate::domain::menu::bump_menu_and_write) and |
| 63 | -/// [`ExamAnswer::save`](crate::domain::exam_answer::ExamAnswer::save) already | |
| 63 | +/// [`ExamAnswer::save`](crate::db::exam_answer::save) already | |
| 64 | 64 | /// use, and the sweep's ordering inside the delete stops mattering once it is |
| 65 | 65 | /// in place. |
| 66 | 66 | /// |
src/domain/class_pump.rsmodified+1 -1
| @@ -233,7 +233,7 @@ impl Axis { | ||
| 233 | 233 | /// and never enters the write set, so `count = count` sat on no key at all |
| 234 | 234 | /// and a concurrent `DELETE /courses/{id}` committed beside it with both |
| 235 | 235 | /// callers told OK (measured on 3.2.3, counter present and absent alike). |
| 236 | - /// Same shape as [`crate::domain::exam_answer::ExamAnswer::save`]: the | |
| 236 | + /// Same shape as [`crate::db::exam_answer::save`]: the | |
| 237 | 237 | /// restore is by captured value, `NONE` included, so the row is |
| 238 | 238 | /// byte-identical afterwards and the boot backfill still sees the `NONE` it |
| 239 | 239 | /// seeds off. Both statements are inside the transaction, so an abort |
src/domain/exam_answer.rsmodified+10 -322
| @@ -1,13 +1,12 @@ | ||
| 1 | 1 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 2 | 2 | |
| 3 | -use crate::constant::{EXAM_ANSWER_TABLE, EXAM_RESULT_COUNT_FIELD, MAX_ANSWER_TEXT_LEN}; | |
| 4 | -use crate::database::{Database, transaction_with_retry}; | |
| 3 | +use crate::constant::{EXAM_ANSWER_TABLE, MAX_ANSWER_TEXT_LEN}; | |
| 5 | 4 | use crate::domain::exam::ExamId; |
| 6 | 5 | use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId}; |
| 7 | 6 | use crate::domain::key; |
| 8 | 7 | use crate::domain::timestamp::Timestamp; |
| 9 | 8 | use crate::domain::user::UserId; |
| 10 | -use crate::error::{AppError, ValidationError}; | |
| 9 | +use crate::error::ValidationError; | |
| 11 | 10 | use crate::validate::validate_optional; |
| 12 | 11 | |
| 13 | 12 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| @@ -57,14 +56,14 @@ impl AnswerText { | ||
| 57 | 56 | /// cascades) don't fan out through `exam_question`. |
| 58 | 57 | #[derive(Debug, Clone, SurrealValue)] |
| 59 | 58 | pub struct ExamAnswer { |
| 60 | - id: ExamAnswerId, | |
| 61 | - exam: ExamId, | |
| 62 | - question: ExamQuestionId, | |
| 63 | - user: UserId, | |
| 64 | - seq: i64, | |
| 65 | - selected: Option<ChoiceId>, | |
| 66 | - text: Option<AnswerText>, | |
| 67 | - updated_at: Timestamp, | |
| 59 | + pub(crate) id: ExamAnswerId, | |
| 60 | + pub(crate) exam: ExamId, | |
| 61 | + pub(crate) question: ExamQuestionId, | |
| 62 | + pub(crate) user: UserId, | |
| 63 | + pub(crate) seq: i64, | |
| 64 | + pub(crate) selected: Option<ChoiceId>, | |
| 65 | + pub(crate) text: Option<AnswerText>, | |
| 66 | + pub(crate) updated_at: Timestamp, | |
| 68 | 67 | } |
| 69 | 68 | |
| 70 | 69 | impl ExamAnswer { |
| @@ -107,240 +106,6 @@ impl ExamAnswer { | ||
| 107 | 106 | let correct = question.get_correct()?; |
| 108 | 107 | Some(self.selected.as_ref() == Some(correct)) |
| 109 | 108 | } |
| 110 | - | |
| 111 | - /// Save (or overwrite) `user`'s answer to `question` for sitting `seq` — | |
| 112 | - /// the one write path, shared by the REST handler and the WebSocket room. | |
| 113 | - /// The payload must match the question's kind: a choice question takes | |
| 114 | - /// `selected` (the id of one of its choices), a text question takes `text`. | |
| 115 | - /// The caller has already checked that the attempt is in progress. Keyed | |
| 116 | - /// by `seq`, so a retake's save is a new row, not an overwrite of an | |
| 117 | - /// earlier sitting's answer. | |
| 118 | - pub async fn save( | |
| 119 | - question: &ExamQuestion, | |
| 120 | - user: &UserId, | |
| 121 | - seq: i64, | |
| 122 | - selected: Option<String>, | |
| 123 | - text: Option<String>, | |
| 124 | - db: &Database, | |
| 125 | - ) -> Result<ExamAnswer, AppError> { | |
| 126 | - let invalid = | |
| 127 | - |field, reason| AppError::Validation(ValidationError::Invalid { field, reason }); | |
| 128 | - let (selected, text) = match question.get_kind().as_str() { | |
| 129 | - "choice" => { | |
| 130 | - if text.is_some() { | |
| 131 | - return Err(invalid( | |
| 132 | - "text", | |
| 133 | - "a choice question takes selected, not text", | |
| 134 | - )); | |
| 135 | - } | |
| 136 | - let Some(selected) = selected else { | |
| 137 | - return Err(invalid("selected", "required for a choice question")); | |
| 138 | - }; | |
| 139 | - // Membership, not a range: `selected` names an option by its | |
| 140 | - // stable id, so a reorder of the list can never repoint it. | |
| 141 | - let picked = question | |
| 142 | - .get_choices() | |
| 143 | - .unwrap_or_default() | |
| 144 | - .iter() | |
| 145 | - .find(|choice| choice.get_id().as_str() == selected) | |
| 146 | - .ok_or_else(|| { | |
| 147 | - invalid("selected", "must name one of the question's choices") | |
| 148 | - })?; | |
| 149 | - (Some(picked.get_id().clone()), None) | |
| 150 | - } | |
| 151 | - _ => { | |
| 152 | - if selected.is_some() { | |
| 153 | - return Err(invalid( | |
| 154 | - "selected", | |
| 155 | - "a text question takes text, not selected", | |
| 156 | - )); | |
| 157 | - } | |
| 158 | - let Some(text) = text else { | |
| 159 | - return Err(invalid("text", "required for a text question")); | |
| 160 | - }; | |
| 161 | - (None, Some(AnswerText::try_new(&text)?)) | |
| 162 | - } | |
| 163 | - }; | |
| 164 | - let answer = ExamAnswer { | |
| 165 | - id: ExamAnswerId::composite(question.get_id(), user, seq), | |
| 166 | - exam: question.get_exam().clone(), | |
| 167 | - question: question.get_id().clone(), | |
| 168 | - user: user.clone(), | |
| 169 | - seq, | |
| 170 | - selected, | |
| 171 | - text, | |
| 172 | - updated_at: Timestamp::now(), | |
| 173 | - }; | |
| 174 | - // The save writes the *exam row* as well as the answer, in one | |
| 175 | - // transaction, and that is what ties the answer's fate to its exam: | |
| 176 | - // reading the exam does not survive [`crate::db::exam::delete`]'s | |
| 177 | - // window — a save landing after its `DELETE exam_answer WHERE exam = $ex` | |
| 178 | - // but before the commit reads an exam that is still there (uncommitted) | |
| 179 | - // while the sweep ran on a snapshot predating this row, so both commit | |
| 180 | - // and the answer outlives the exam (measured 4 of 4 raced rounds). | |
| 181 | - // Writing the key the delete removes makes the two collide, and the | |
| 182 | - // store refuses one of them. It is the shape | |
| 183 | - // [`crate::domain::menu::bump_menu_and_write`] uses, and the one a mark | |
| 184 | - // already uses on this very row | |
| 185 | - // ([`crate::domain::exam_result::ExamResult::grade`]). | |
| 186 | - // | |
| 187 | - // The bump-and-restore is not a flourish, it is the whole instrument. | |
| 188 | - // The exam carries no revision to bump and must not grow one — its save | |
| 189 | - // is a whole-row `CONTENT` write, so a column this struct did not know | |
| 190 | - // about would be wiped by the next PATCH — so this touches the one | |
| 191 | - // counter it already has and puts it back. Writing the *same* value is | |
| 192 | - // not enough: an `UPDATE` that leaves the document unchanged is elided | |
| 193 | - // and never reaches the store's write set, which the race test proved | |
| 194 | - // (green on the raced delete, red the moment the value moves for real). | |
| 195 | - // The restore is by captured value, `NONE` included, so the row is | |
| 196 | - // byte-identical afterwards: the boot backfill still finds the rows it | |
| 197 | - // keys on (`WHERE result_count = NONE`), the PATCH's | |
| 198 | - // `(result_count ?? 0) = $was_results` still passes, and no teacher's | |
| 199 | - // edit is refused because a student typed. Both statements are inside | |
| 200 | - // the transaction, so a crash between them cannot leave the counter up. | |
| 201 | - // No `cap::counter_lock` either: no counter moves here, and the hottest | |
| 202 | - // write path in the app should not queue behind one. | |
| 203 | - // | |
| 204 | - // Admissible for `transaction_with_retry`: the `UPDATE`s, `SELECT`, | |
| 205 | - // `IF`/`THROW` and `RETURN` can never answer "already exists", and the | |
| 206 | - // `UPSERT`'s id is bijective with the (question, user, seq) triple | |
| 207 | - // `exam_answer` keys — a lost round wrote nothing, and re-sending | |
| 208 | - // resolves onto the same row rather than colliding with it. | |
| 209 | - let (mut result, mut errors) = transaction_with_retry( | |
| 210 | - db, | |
| 211 | - &format!( | |
| 212 | - "BEGIN TRANSACTION; | |
| 213 | - LET $was = (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $ex); | |
| 214 | - LET $touched = (UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = \ | |
| 215 | - ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); | |
| 216 | - IF array::len($touched) = 0 {{ THROW 'no_exam' }}; | |
| 217 | - UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = $was; | |
| 218 | - LET $row = (UPSERT $id CONTENT $answer RETURN AFTER); | |
| 219 | - RETURN $row[0]; | |
| 220 | - COMMIT TRANSACTION;" | |
| 221 | - ), | |
| 222 | - &[ | |
| 223 | - ("ex".into(), answer.exam.record().into_value()), | |
| 224 | - ("id".into(), answer.id.record().into_value()), | |
| 225 | - ("answer".into(), answer.into_value()), | |
| 226 | - ], | |
| 227 | - &["no_exam"], | |
| 228 | - ) | |
| 229 | - .await?; | |
| 230 | - // An aborted transaction errors *every* slot, most with a generic "not | |
| 231 | - // executed" — only the THROW's own slot names the reason. | |
| 232 | - if errors | |
| 233 | - .values() | |
| 234 | - .any(|error| error.to_string().contains("no_exam")) | |
| 235 | - { | |
| 236 | - return Err(AppError::NotFound); | |
| 237 | - } | |
| 238 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | |
| 239 | - return Err(error.into()); | |
| 240 | - } | |
| 241 | - // The trailing `RETURN` is the last statement before `COMMIT`, so its | |
| 242 | - // slot follows the statement count rather than a hand-kept number (the | |
| 243 | - // `db::exam::delete` treatment); `num_statements` counts BEGIN and COMMIT. | |
| 244 | - let slot = result.num_statements().saturating_sub(2); | |
| 245 | - result | |
| 246 | - .take::<Vec<ExamAnswer>>(slot)? | |
| 247 | - .into_iter() | |
| 248 | - .next() | |
| 249 | - .ok_or_else(|| AppError::Internal("failed to save exam answer".into())) | |
| 250 | - } | |
| 251 | - | |
| 252 | - /// One student's stored answer for a question in sitting `seq`, if any. | |
| 253 | - pub async fn read( | |
| 254 | - question: &ExamQuestionId, | |
| 255 | - user: &UserId, | |
| 256 | - seq: i64, | |
| 257 | - db: &Database, | |
| 258 | - ) -> Result<Option<ExamAnswer>, AppError> { | |
| 259 | - Ok(db | |
| 260 | - .select(ExamAnswerId::composite(question, user, seq).record()) | |
| 261 | - .await?) | |
| 262 | - } | |
| 263 | - | |
| 264 | - /// Drop one student's answer to a single question in sitting `seq`. | |
| 265 | - pub async fn delete( | |
| 266 | - question: &ExamQuestionId, | |
| 267 | - user: &UserId, | |
| 268 | - seq: i64, | |
| 269 | - db: &Database, | |
| 270 | - ) -> Result<(), AppError> { | |
| 271 | - let _: Option<ExamAnswer> = db | |
| 272 | - .delete(ExamAnswerId::composite(question, user, seq).record()) | |
| 273 | - .await?; | |
| 274 | - Ok(()) | |
| 275 | - } | |
| 276 | - | |
| 277 | - /// One student's answers for a single sitting (`seq`) across an exam, in | |
| 278 | - /// question (ULID) order — the live-sitting read-back and, for a past | |
| 279 | - /// `seq`, that attempt's answer sheet. | |
| 280 | - pub async fn list_for_exam_user( | |
| 281 | - exam: &ExamId, | |
| 282 | - user: &UserId, | |
| 283 | - seq: i64, | |
| 284 | - db: &Database, | |
| 285 | - ) -> Result<Vec<ExamAnswer>, AppError> { | |
| 286 | - let mut result = db | |
| 287 | - .query( | |
| 288 | - "SELECT * FROM exam_answer WHERE exam = $ex AND user = $usr AND seq = $seq | |
| 289 | - ORDER BY question ASC", | |
| 290 | - ) | |
| 291 | - .bind(("ex", exam.record())) | |
| 292 | - .bind(("usr", user.record())) | |
| 293 | - .bind(("seq", seq)) | |
| 294 | - .await? | |
| 295 | - .check()?; | |
| 296 | - Ok(result.take::<Vec<ExamAnswer>>(0)?) | |
| 297 | - } | |
| 298 | - | |
| 299 | - /// The distinct sittings a student has any answer for at `exam`, ascending | |
| 300 | - /// — the index a history view lists attempts from. | |
| 301 | - pub async fn list_seqs_for_user( | |
| 302 | - exam: &ExamId, | |
| 303 | - user: &UserId, | |
| 304 | - db: &Database, | |
| 305 | - ) -> Result<Vec<i64>, AppError> { | |
| 306 | - let mut result = db | |
| 307 | - .query( | |
| 308 | - "SELECT VALUE seq FROM exam_answer WHERE exam = $ex AND user = $usr | |
| 309 | - ORDER BY seq ASC", | |
| 310 | - ) | |
| 311 | - .bind(("ex", exam.record())) | |
| 312 | - .bind(("usr", user.record())) | |
| 313 | - .await? | |
| 314 | - .check()?; | |
| 315 | - let mut seqs = result.take::<Vec<i64>>(0)?; | |
| 316 | - seqs.dedup(); | |
| 317 | - Ok(seqs) | |
| 318 | - } | |
| 319 | - | |
| 320 | - /// Every answer of an exam — the live monitor aggregates these per student. | |
| 321 | - pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<ExamAnswer>, AppError> { | |
| 322 | - let mut result = db | |
| 323 | - .query("SELECT * FROM exam_answer WHERE exam = $ex ORDER BY question ASC") | |
| 324 | - .bind(("ex", exam.record())) | |
| 325 | - .await? | |
| 326 | - .check()?; | |
| 327 | - Ok(result.take::<Vec<ExamAnswer>>(0)?) | |
| 328 | - } | |
| 329 | - | |
| 330 | - /// Drop one student's answers across an exam — a retake starts from a | |
| 331 | - /// blank sheet. | |
| 332 | - pub async fn delete_for_exam_user( | |
| 333 | - exam: &ExamId, | |
| 334 | - user: &UserId, | |
| 335 | - db: &Database, | |
| 336 | - ) -> Result<(), AppError> { | |
| 337 | - db.query("DELETE exam_answer WHERE exam = $ex AND user = $usr") | |
| 338 | - .bind(("ex", exam.record())) | |
| 339 | - .bind(("usr", user.record())) | |
| 340 | - .await? | |
| 341 | - .check()?; | |
| 342 | - Ok(()) | |
| 343 | - } | |
| 344 | 109 | } |
| 345 | 110 | |
| 346 | 111 | /// The choice-question score suggested by the machine: `earned` points from |
| @@ -489,81 +254,4 @@ mod tests { | ||
| 489 | 254 | let text = text_question(&exam, 10); |
| 490 | 255 | assert_eq!(answer(&text, &user, None).is_correct(&text), None); |
| 491 | 256 | } |
| 492 | - | |
| 493 | - /// The bite test for the exam-row touch in [`ExamAnswer::save`]: it exists | |
| 494 | - /// to collide with [`crate::db::exam::delete`], so it must leave | |
| 495 | - /// the counter it borrows exactly where it found it — absent stays absent | |
| 496 | - /// (the boot backfill keys on `result_count = NONE`), and a real count is | |
| 497 | - /// not moved by a student typing. The race half is | |
| 498 | - /// `db::exam::tests::an_answer_written_inside_a_delete_never_outlives_the_exam`, | |
| 499 | - /// which needs a real server; this half is the arithmetic and runs anywhere. | |
| 500 | - #[tokio::test] | |
| 501 | - async fn a_save_puts_the_exams_mark_counter_back_exactly() { | |
| 502 | - use crate::domain::exam::{ | |
| 503 | - ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle, | |
| 504 | - }; | |
| 505 | - let db = crate::database::init_mem().await.unwrap(); | |
| 506 | - let kinds = crate::domain::settings::Settings::defaults() | |
| 507 | - .get_exam_kinds() | |
| 508 | - .to_vec(); | |
| 509 | - let exam = crate::db::exam::create( | |
| 510 | - &db, | |
| 511 | - &student(), | |
| 512 | - &crate::db::course::a_test_course(&db).await, | |
| 513 | - ExamTitle::try_new("quiz").unwrap(), | |
| 514 | - ExamDescription::try_new("").unwrap(), | |
| 515 | - ExamKind::try_new("quiz", &kinds).unwrap(), | |
| 516 | - ExamSchedule::try_new(None, None, None, None).unwrap(), | |
| 517 | - ExamAttemptLimit::try_new(1).unwrap(), | |
| 518 | - true, | |
| 519 | - false, | |
| 520 | - false, | |
| 521 | - ) | |
| 522 | - .await | |
| 523 | - .unwrap(); | |
| 524 | - let stored = async |db: &Database| -> Option<i64> { | |
| 525 | - let mut result = db | |
| 526 | - .query("SELECT VALUE result_count FROM ONLY $ex") | |
| 527 | - .bind(("ex", exam.get_id().record())) | |
| 528 | - .await | |
| 529 | - .unwrap() | |
| 530 | - .check() | |
| 531 | - .unwrap(); | |
| 532 | - result.take::<Option<i64>>(0).unwrap() | |
| 533 | - }; | |
| 534 | - let question = choice_question(exam.get_id(), 10, 1); | |
| 535 | - let pick = choice_id(&question, 1).as_str().to_string(); | |
| 536 | - | |
| 537 | - // A fresh exam carries no counter at all, and must still not after a save. | |
| 538 | - assert_eq!(stored(&db).await, None, "the fixture must start absent"); | |
| 539 | - ExamAnswer::save(&question, &student(), 1, Some(pick.clone()), None, &db) | |
| 540 | - .await | |
| 541 | - .unwrap(); | |
| 542 | - assert_eq!( | |
| 543 | - stored(&db).await, | |
| 544 | - None, | |
| 545 | - "the touch left the counter set — the backfill keys on NONE" | |
| 546 | - ); | |
| 547 | - | |
| 548 | - // …and a counter that marks have moved is put back at its own value. | |
| 549 | - db.query("UPDATE $ex SET result_count = 7") | |
| 550 | - .bind(("ex", exam.get_id().record())) | |
| 551 | - .await | |
| 552 | - .unwrap() | |
| 553 | - .check() | |
| 554 | - .unwrap(); | |
| 555 | - ExamAnswer::save(&question, &student(), 2, Some(pick), None, &db) | |
| 556 | - .await | |
| 557 | - .unwrap(); | |
| 558 | - assert_eq!(stored(&db).await, Some(7), "the touch moved a real count"); | |
| 559 | - | |
| 560 | - // The gate that makes the touch worth having: no exam, no answer. | |
| 561 | - let orphan = choice_question(&ExamId::from_key("01NOSUCHEXAMAAAAAAAAAAAAAA"), 10, 0); | |
| 562 | - let pick = choice_id(&orphan, 0).as_str().to_string(); | |
| 563 | - let refused = ExamAnswer::save(&orphan, &student(), 1, Some(pick), None, &db).await; | |
| 564 | - assert!( | |
| 565 | - matches!(refused, Err(AppError::NotFound)), | |
| 566 | - "a save into a missing exam must 404, got {refused:?}" | |
| 567 | - ); | |
| 568 | - } | |
| 569 | 257 | } |
src/domain/exam_result.rsmodified+34 -828
| @@ -2,21 +2,16 @@ use std::collections::HashMap; | ||
| 2 | 2 | |
| 3 | 3 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 4 | 4 | |
| 5 | -use crate::constant::{ | |
| 6 | - EXAM_RESULT_COUNT_FIELD, EXAM_RESULT_TABLE, HIGH_MARK_MIN, HIGH_MARK_TOTAL_FIELD, | |
| 7 | - KIND_REF_TABLE, MARKS_GIVEN_TOTAL_FIELD, REF_COUNT_FIELD, REF_RETIRED_FIELD, | |
| 8 | -}; | |
| 9 | -use crate::database::{Database, transaction_with_retry}; | |
| 10 | -use crate::db::cap; | |
| 11 | -use crate::domain::course::CourseId; | |
| 5 | +use crate::constant::{EXAM_RESULT_TABLE, KIND_REF_TABLE}; | |
| 12 | 6 | use crate::domain::exam::ExamId; |
| 13 | 7 | use crate::domain::key; |
| 14 | 8 | use crate::domain::user::UserId; |
| 15 | 9 | use crate::error::{AppError, ValidationError}; |
| 16 | 10 | use crate::validate::validate_mark; |
| 17 | 11 | |
| 18 | -/// The one spelling of "this exam is hidden", shared by the grade handler's | |
| 19 | -/// pre-flight gate and the in-transaction guard on the mark write. | |
| 12 | +/// The one spelling of "this exam is hidden", shared by the grading | |
| 13 | +/// pre-flight gate ([`crate::service::exam_result::grade`]) and the | |
| 14 | +/// in-transaction guard on the mark write. | |
| 20 | 15 | pub(crate) fn draft_error() -> AppError { |
| 21 | 16 | AppError::Conflict("this exam is a draft — publish it before grading") |
| 22 | 17 | } |
| @@ -82,18 +77,14 @@ impl Mark { | ||
| 82 | 77 | } |
| 83 | 78 | } |
| 84 | 79 | |
| 85 | -/// The `THROW` marker the in-transaction kind claim aborts with — the mark's | |
| 86 | -/// own transaction refusing a name the school has retired. | |
| 87 | -const RETIRED_MARK: &str = "kind_retired"; | |
| 88 | - | |
| 89 | 80 | #[derive(Debug, Clone, SurrealValue)] |
| 90 | 81 | pub struct ExamResult { |
| 91 | - id: ExamResultId, | |
| 92 | - exam: ExamId, | |
| 93 | - user: UserId, | |
| 94 | - seq: i64, | |
| 95 | - mark: Mark, | |
| 96 | - graded_by: UserId, | |
| 82 | + pub(crate) id: ExamResultId, | |
| 83 | + pub(crate) exam: ExamId, | |
| 84 | + pub(crate) user: UserId, | |
| 85 | + pub(crate) seq: i64, | |
| 86 | + pub(crate) mark: Mark, | |
| 87 | + pub(crate) graded_by: UserId, | |
| 97 | 88 | } |
| 98 | 89 | |
| 99 | 90 | impl ExamResult { |
| @@ -121,359 +112,39 @@ impl ExamResult { | ||
| 121 | 112 | pub fn get_graded_by(&self) -> &UserId { |
| 122 | 113 | &self.graded_by |
| 123 | 114 | } |
| 115 | +} | |
| 124 | 116 | |
| 125 | - async fn find( | |
| 126 | - exam: &ExamId, | |
| 127 | - user: &UserId, | |
| 128 | - db: &Database, | |
| 129 | - ) -> Result<Option<ExamResult>, AppError> { | |
| 130 | - // Grade-of-record is the latest sitting's mark: the highest seq wins. | |
| 131 | - let mut result = db | |
| 132 | - .query( | |
| 133 | - "SELECT * FROM exam_result WHERE exam = $ex AND user = $usr | |
| 134 | - ORDER BY seq DESC LIMIT 1", | |
| 135 | - ) | |
| 136 | - .bind(("ex", exam.record())) | |
| 137 | - .bind(("usr", user.record())) | |
| 138 | - .await? | |
| 139 | - .check()?; | |
| 140 | - Ok(result.take::<Vec<ExamResult>>(0)?.into_iter().next()) | |
| 141 | - } | |
| 142 | - | |
| 143 | - /// The latest-seq mark per (exam, user) pair, preserving the outer list's | |
| 144 | - /// row order (first appearance of each pair). Grade-of-record is the latest | |
| 145 | - /// attempt's mark, so a pair with retakes collapses to its highest seq. Done | |
| 146 | - /// in Rust rather than SQL: SurrealDB's `GROUP BY` can't return the whole | |
| 147 | - /// row that carries the max, and id-order can't stand in for seq-order once | |
| 148 | - /// seq reaches two digits. | |
| 149 | - fn latest_per_pair(rows: Vec<ExamResult>) -> Vec<ExamResult> { | |
| 150 | - let mut order: Vec<(String, String)> = Vec::new(); | |
| 151 | - let mut best: HashMap<(String, String), ExamResult> = HashMap::new(); | |
| 152 | - for row in rows { | |
| 153 | - let key = (row.exam.key().to_string(), row.user.key().to_string()); | |
| 154 | - match best.get(&key) { | |
| 155 | - Some(existing) if existing.seq >= row.seq => {} | |
| 156 | - Some(_) => { | |
| 157 | - best.insert(key, row); | |
| 158 | - } | |
| 159 | - None => { | |
| 160 | - order.push(key.clone()); | |
| 161 | - best.insert(key, row); | |
| 162 | - } | |
| 117 | +/// The latest-seq mark per (exam, user) pair, preserving the outer list's | |
| 118 | +/// row order (first appearance of each pair). Grade-of-record is the latest | |
| 119 | +/// attempt's mark, so a pair with retakes collapses to its highest seq. Done | |
| 120 | +/// in Rust rather than SQL: SurrealDB's `GROUP BY` can't return the whole | |
| 121 | +/// row that carries the max, and id-order can't stand in for seq-order once | |
| 122 | +/// seq reaches two digits. | |
| 123 | +pub(crate) fn latest_per_pair(rows: Vec<ExamResult>) -> Vec<ExamResult> { | |
| 124 | + let mut order: Vec<(String, String)> = Vec::new(); | |
| 125 | + let mut best: HashMap<(String, String), ExamResult> = HashMap::new(); | |
| 126 | + for row in rows { | |
| 127 | + let key = (row.exam.key().to_string(), row.user.key().to_string()); | |
| 128 | + match best.get(&key) { | |
| 129 | + Some(existing) if existing.seq >= row.seq => {} | |
| 130 | + Some(_) => { | |
| 131 | + best.insert(key, row); | |
| 132 | + } | |
| 133 | + None => { | |
| 134 | + order.push(key.clone()); | |
| 135 | + best.insert(key, row); | |
| 163 | 136 | } |
| 164 | 137 | } |
| 165 | - order | |
| 166 | - .into_iter() | |
| 167 | - .map(|key| best.remove(&key).expect("key was recorded on insert")) | |
| 168 | - .collect() | |
| 169 | - } | |
| 170 | - | |
| 171 | - /// A single user's result for an exam, if graded. | |
| 172 | - pub async fn read_for_user( | |
| 173 | - exam: &ExamId, | |
| 174 | - user: &UserId, | |
| 175 | - db: &Database, | |
| 176 | - ) -> Result<Option<ExamResult>, AppError> { | |
| 177 | - Self::find(exam, user, db).await | |
| 178 | - } | |
| 179 | - | |
| 180 | - /// Record (or overwrite) `user`'s mark for the `seq`th sitting of `exam`. | |
| 181 | - /// One row per (exam, user, seq), keyed by a deterministic composite id so | |
| 182 | - /// this is a single atomic UPSERT — concurrent grades for the same sitting | |
| 183 | - /// converge on one row instead of racing the unique index into a 500. | |
| 184 | - /// Grading a retake writes a fresh mark at the current seq and never touches | |
| 185 | - /// prior sittings' marks; the latest seq is the grade-of-record. | |
| 186 | - /// | |
| 187 | - /// `kind` is the exam's kind, and this is where a mark takes its reference | |
| 188 | - /// on it — claimed *inside the mark's own transaction*, and only on the | |
| 189 | - /// branch that is about to add a row. A kind the school has retired refuses | |
| 190 | - /// the claim, which is the same invariant the settings guard enforces from | |
| 191 | - /// the other side. Claimed before the write and released after, the pair had | |
| 192 | - /// two crash windows either side of the write that leaked a reference (a | |
| 193 | - /// kind frozen out of the settings for good) and an exam's `result_count`; | |
| 194 | - /// riding the transaction, both counters land exactly when the row does. | |
| 195 | - /// | |
| 196 | - /// The exam's own `result_count` is claimed in the same breath, and it is | |
| 197 | - /// what a kind change is refused against: the exam PATCH pins that counter, | |
| 198 | - /// so a mark landing while it decides cannot slip past its gate and leave | |
| 199 | - /// itself counted under a kind its exam no longer carries. | |
| 200 | - /// | |
| 201 | - /// An overwrite (a regrade of a sitting already marked) claims *nothing*: | |
| 202 | - /// one mark, one reference, so the branch that finds a row simply leaves | |
| 203 | - /// both counters where they are — there is no claim to give back, and so no | |
| 204 | - /// window in which a crash could fail to give it. | |
| 205 | - /// | |
| 206 | - /// The grader's `marks_given_total` rides that same first-time branch: a | |
| 207 | - /// regrade of a sitting moves it however often it is run, while a retake, | |
| 208 | - /// being a distinct `seq` and so a distinct row, counts on its own. | |
| 209 | - /// | |
| 210 | - /// The student's `high_mark_total` cannot ride it, because it is not a | |
| 211 | - /// count of rows but a count of rows *at or above* [`HIGH_MARK_MIN`], and a | |
| 212 | - /// regrade moves a mark across that line without adding or removing a row. | |
| 213 | - /// It moves by the difference between the mark about to be stored and the | |
| 214 | - /// one already there — `+1` crossing up, `-1` crossing down, nothing at all | |
| 215 | - /// when both sides sit on the same side of the line, so an overwrite still | |
| 216 | - /// costs the student's row no write unless the answer actually changed. | |
| 217 | - /// Decided on the first branch alone it drifted upward without bound: 95 | |
| 218 | - /// credited, regraded to 40 (no row added, so no move), then deleted, whose | |
| 219 | - /// refund reads the *stored* mark and so found nothing to give back — a | |
| 220 | - /// counter of one over zero stored high marks, looped into a permanent | |
| 221 | - /// badge. Both counters are written field-scoped: a user row also carries | |
| 222 | - /// admin-owned data (`role`) that a whole-row save would revert. | |
| 223 | - pub async fn grade( | |
| 224 | - exam: &ExamId, | |
| 225 | - user: &UserId, | |
| 226 | - seq: i64, | |
| 227 | - mark: Mark, | |
| 228 | - graded_by: &UserId, | |
| 229 | - kind: &str, | |
| 230 | - db: &Database, | |
| 231 | - ) -> Result<ExamResult, AppError> { | |
| 232 | - let result = ExamResult { | |
| 233 | - id: ExamResultId::composite(exam, user, seq), | |
| 234 | - exam: exam.clone(), | |
| 235 | - user: user.clone(), | |
| 236 | - seq, | |
| 237 | - mark, | |
| 238 | - graded_by: graded_by.clone(), | |
| 239 | - }; | |
| 240 | - // The "exists" and "not a draft" gates ride in the same transaction as | |
| 241 | - // the mark, the mirror of the re-draft gate on | |
| 242 | - // `Exam::update_if_unchanged`: between them, a mark and a re-draft | |
| 243 | - // racing each other can only ever leave one of the two applied, | |
| 244 | - // whichever process either ran in. The existence gate is not | |
| 245 | - // redundant with the draft one — a deleted exam reads NONE, which is | |
| 246 | - // *falsy*, so the draft gate alone waved a mark onto an exam that no | |
| 247 | - // longer existed. The caller's pre-flight check answers the same 409 | |
| 248 | - // one round trip earlier. It is also what makes a separate "did the | |
| 249 | - // exam survive my claim?" check moot: the claim now sits behind this | |
| 250 | - // gate instead of in front of it. | |
| 251 | - // | |
| 252 | - // `$before` is the sitting's *previous mark*, and it answers both | |
| 253 | - // questions off one read: `mark` is a mandatory column on a schemafull | |
| 254 | - // row, so `NONE` there means no row at all — the claim branch — while a | |
| 255 | - // number is what the student's counter takes its difference against. | |
| 256 | - // Read one statement before the counters inside the same transaction: | |
| 257 | - // read anywhere else it would be a guess about a row two graders may be | |
| 258 | - // writing at once, and the difference would be taken against a mark | |
| 259 | - // some other round had already replaced. | |
| 260 | - // | |
| 261 | - // Re-sent while the store answers "conflict, retry": the gates read a | |
| 262 | - // column an exam PATCH writes, and the counters are the ones a | |
| 263 | - // concurrent delete gives back, so this contends on three records by | |
| 264 | - // design. Sound to re-send because no statement in it can legitimately | |
| 265 | - // answer "already exists": the counter writes are `UPDATE`/`UPSERT` on | |
| 266 | - // ids no rival can collide *into*, and the mark's own UPSERT is on a | |
| 267 | - // deterministic id bijective with the `exam_result_exam_user_seq` | |
| 268 | - // unique tuple — `key::sitting(exam, user, seq)` *is* that tuple, so | |
| 269 | - // the index entry can only ever point at the row the id already names | |
| 270 | - // and the write resolves onto it. A lost round aborts having written | |
| 271 | - // nothing, counters included. | |
| 272 | - let _guard = cap::counter_lock().await; | |
| 273 | - let (mut written, mut errors) = transaction_with_retry( | |
| 274 | - db, | |
| 275 | - &format!( | |
| 276 | - "BEGIN TRANSACTION; | |
| 277 | - IF (SELECT VALUE id FROM ONLY $exam) IS NONE {{ THROW 'exam_missing' }}; | |
| 278 | - IF (SELECT VALUE draft FROM ONLY $exam) {{ THROW 'exam_draft' }}; | |
| 279 | - LET $before = (SELECT VALUE mark FROM ONLY $id); | |
| 280 | - IF $before = NONE {{ | |
| 281 | - LET $kind = (UPSERT $kref SET {REF_COUNT_FIELD} = ({REF_COUNT_FIELD} ?? 0) + 1 | |
| 282 | - WHERE {REF_RETIRED_FIELD} != true RETURN VALUE id); | |
| 283 | - IF array::len($kind) = 0 {{ THROW '{RETIRED_MARK}' }}; | |
| 284 | - UPDATE $exam SET {EXAM_RESULT_COUNT_FIELD} = | |
| 285 | - ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1; | |
| 286 | - UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = | |
| 287 | - ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1; | |
| 288 | - }}; | |
| 289 | - LET $high = (IF $result.mark >= {HIGH_MARK_MIN} {{ 1 }} ELSE {{ 0 }}) | |
| 290 | - - (IF ($before ?? -1) >= {HIGH_MARK_MIN} {{ 1 }} ELSE {{ 0 }}); | |
| 291 | - IF $high != 0 {{ | |
| 292 | - UPDATE $student SET {HIGH_MARK_TOTAL_FIELD} = | |
| 293 | - math::max([({HIGH_MARK_TOTAL_FIELD} ?? 0) + $high, 0]) | |
| 294 | - }}; | |
| 295 | - LET $after = (UPSERT $id CONTENT $result RETURN AFTER); | |
| 296 | - RETURN $after[0]; | |
| 297 | - COMMIT TRANSACTION;" | |
| 298 | - ), | |
| 299 | - &[ | |
| 300 | - ("exam".into(), exam.record().into_value()), | |
| 301 | - ("id".into(), result.id.record().into_value()), | |
| 302 | - ("kref".into(), kind_ref(kind).into_value()), | |
| 303 | - ("grader".into(), graded_by.record().into_value()), | |
| 304 | - ("student".into(), user.record().into_value()), | |
| 305 | - ("result".into(), result.into_value()), | |
| 306 | - ], | |
| 307 | - &["exam_missing", "exam_draft", RETIRED_MARK], | |
| 308 | - ) | |
| 309 | - .await?; | |
| 310 | - // An aborted transaction errors every slot and only the THROW's own | |
| 311 | - // slot names the marker, so a refusal is read by marker while a lost | |
| 312 | - // round was already re-sent — never reported as a 500. | |
| 313 | - let thrown = |marker: &str| { | |
| 314 | - errors | |
| 315 | - .values() | |
| 316 | - .any(|error| error.to_string().contains(marker)) | |
| 317 | - }; | |
| 318 | - if thrown("exam_missing") { | |
| 319 | - return Err(AppError::NotFound); | |
| 320 | - } | |
| 321 | - if thrown("exam_draft") { | |
| 322 | - return Err(draft_error()); | |
| 323 | - } | |
| 324 | - if thrown(RETIRED_MARK) { | |
| 325 | - return Err(retired_kind_error(kind)); | |
| 326 | - } | |
| 327 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | |
| 328 | - return Err(error.into()); | |
| 329 | - } | |
| 330 | - // The trailing `RETURN` is always the last statement before `COMMIT`, | |
| 331 | - // so its slot follows the statement count instead of a hand-kept | |
| 332 | - // number — see `Exam::delete` for the bug the hand-kept one caused. | |
| 333 | - // Probed on crate 3.2.3: an `IF { … }` block occupies exactly one slot | |
| 334 | - // however many statements it holds, and one whether or not it is taken. | |
| 335 | - let slot = written.num_statements().saturating_sub(2); | |
| 336 | - written | |
| 337 | - .take::<Vec<ExamResult>>(slot)? | |
| 338 | - .into_iter() | |
| 339 | - .next() | |
| 340 | - .ok_or_else(|| AppError::Internal("failed to record exam result".into())) | |
| 341 | - } | |
| 342 | - | |
| 343 | - /// The user's graded results restricted to one course's exams — the raw | |
| 344 | - /// rows behind the per-course block of the marks report. | |
| 345 | - pub async fn list_for_user_in_course( | |
| 346 | - course: &CourseId, | |
| 347 | - user: &UserId, | |
| 348 | - db: &Database, | |
| 349 | - ) -> Result<Vec<ExamResult>, AppError> { | |
| 350 | - let mut result = db | |
| 351 | - .query( | |
| 352 | - "SELECT * FROM exam_result WHERE user = $usr | |
| 353 | - AND exam IN (SELECT VALUE id FROM exam WHERE course = $course) | |
| 354 | - ORDER BY id DESC", | |
| 355 | - ) | |
| 356 | - .bind(("usr", user.record())) | |
| 357 | - .bind(("course", course.record())) | |
| 358 | - .await? | |
| 359 | - .check()?; | |
| 360 | - Ok(Self::latest_per_pair(result.take::<Vec<ExamResult>>(0)?)) | |
| 361 | - } | |
| 362 | - | |
| 363 | - pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<ExamResult>, AppError> { | |
| 364 | - let mut result = db | |
| 365 | - .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC") | |
| 366 | - .bind(("ex", exam.record())) | |
| 367 | - .await? | |
| 368 | - .check()?; | |
| 369 | - Ok(Self::latest_per_pair(result.take::<Vec<ExamResult>>(0)?)) | |
| 370 | - } | |
| 371 | - | |
| 372 | - /// Every sitting's mark for one (exam, user) pair, oldest first — the | |
| 373 | - /// per-attempt grade history behind the FE's attempt-by-attempt view. | |
| 374 | - pub async fn list_all_for_exam_user( | |
| 375 | - exam: &ExamId, | |
| 376 | - user: &UserId, | |
| 377 | - db: &Database, | |
| 378 | - ) -> Result<Vec<ExamResult>, AppError> { | |
| 379 | - let mut result = db | |
| 380 | - .query( | |
| 381 | - "SELECT * FROM exam_result WHERE exam = $ex AND user = $usr | |
| 382 | - ORDER BY seq ASC", | |
| 383 | - ) | |
| 384 | - .bind(("ex", exam.record())) | |
| 385 | - .bind(("usr", user.record())) | |
| 386 | - .await? | |
| 387 | - .check()?; | |
| 388 | - Ok(result.take::<Vec<ExamResult>>(0)?) | |
| 389 | - } | |
| 390 | - | |
| 391 | - /// Delete every sitting's mark for one (exam, user) pair. `kind` is the | |
| 392 | - /// exam's: the marks give their references back, so a kind nothing is | |
| 393 | - /// graded under any more can leave the settings again. | |
| 394 | - /// | |
| 395 | - /// The two badge counters come back the same way, and for a reason the | |
| 396 | - /// other counters do not need: [`grade`](Self::grade) credits them on the | |
| 397 | - /// branch that finds no row, and a deleted row *is* no row. Left standing, | |
| 398 | - /// ungrade-then-regrade credited a second time off one stored mark, and | |
| 399 | - /// looped it minted a badge from a single exam — permanently, since an | |
| 400 | - /// award is never revoked. Each is given back off the rows this statement | |
| 401 | - /// actually deleted: `marks_given_total` to each row's *own* grader (two | |
| 402 | - /// teachers can hold two sittings of the same pair), and `high_mark_total` | |
| 403 | - /// once per removed row that cleared [`HIGH_MARK_MIN`], read off the | |
| 404 | - /// `BEFORE` image rather than re-derived. That last one is why | |
| 405 | - /// [`grade`](Self::grade) has to move the student's counter on a *regrade* | |
| 406 | - /// too: this end reads the stored mark, so the other end must be decided by | |
| 407 | - /// the stored mark as well, or a mark walked across the line between the | |
| 408 | - /// two leaves a credit no delete can find to give back. | |
| 409 | - pub async fn remove( | |
| 410 | - exam: &ExamId, | |
| 411 | - user: &UserId, | |
| 412 | - kind: &str, | |
| 413 | - db: &Database, | |
| 414 | - ) -> Result<Option<ExamResult>, AppError> { | |
| 415 | - // Both counters go back *inside* the delete's own transaction, driven | |
| 416 | - // off the rows this statement actually deleted. Counted outside it, a | |
| 417 | - // cascade (exam or course delete) taking the same rows in the gap would | |
| 418 | - // release them a second time, and on a kind another exam still grades | |
| 419 | - // under, one release too many reads as one mark too few — a kind | |
| 420 | - // wrongly free to leave the settings. | |
| 421 | - // | |
| 422 | - // Re-sent while the store answers "conflict, retry": the counters this | |
| 423 | - // touches are the ones a concurrent grade claims, so a lost round is | |
| 424 | - // routine and aborts having written nothing. `check()` cannot be used | |
| 425 | - // to read the outcome — it takes the *lowest*-slot error, and an | |
| 426 | - // aborted transaction's generic "not executed" sibling masked the real | |
| 427 | - // conflict, the exact defect deleted from `Exam::delete`. No THROW of | |
| 428 | - // its own, and only `DELETE`/`UPDATE` inside, so nothing here can | |
| 429 | - // answer "already exists" and make a retry unsound. | |
| 430 | - let (mut result, mut errors) = transaction_with_retry( | |
| 431 | - db, | |
| 432 | - &format!( | |
| 433 | - "BEGIN TRANSACTION; | |
| 434 | - LET $gone = (DELETE exam_result WHERE exam = $ex AND user = $usr RETURN BEFORE); | |
| 435 | - IF array::len($gone) > 0 {{ | |
| 436 | - UPDATE type::record('kind_ref', $kind) SET {REF_COUNT_FIELD} = | |
| 437 | - math::max([({REF_COUNT_FIELD} ?? 0) - array::len($gone), 0]); | |
| 438 | - UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = | |
| 439 | - math::max([({EXAM_RESULT_COUNT_FIELD} ?? 0) - array::len($gone), 0]); | |
| 440 | - LET $high = array::len($gone[WHERE mark >= {HIGH_MARK_MIN}]); | |
| 441 | - IF $high > 0 {{ | |
| 442 | - UPDATE $usr SET {HIGH_MARK_TOTAL_FIELD} = | |
| 443 | - math::max([({HIGH_MARK_TOTAL_FIELD} ?? 0) - $high, 0]) | |
| 444 | - }}; | |
| 445 | - FOR $row IN $gone {{ | |
| 446 | - LET $grader = $row.graded_by; | |
| 447 | - UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = | |
| 448 | - math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0]) | |
| 449 | - }}; | |
| 450 | - }}; | |
| 451 | - RETURN $gone; | |
| 452 | - COMMIT TRANSACTION;" | |
| 453 | - ), | |
| 454 | - &[ | |
| 455 | - ("ex".into(), exam.record().into_value()), | |
| 456 | - ("usr".into(), user.record().into_value()), | |
| 457 | - ("kind".into(), kind.to_string().into_value()), | |
| 458 | - ], | |
| 459 | - &[], | |
| 460 | - ) | |
| 461 | - .await?; | |
| 462 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | |
| 463 | - return Err(error.into()); | |
| 464 | - } | |
| 465 | - // `RETURN` is the last statement before `COMMIT`; its slot follows the | |
| 466 | - // statement count, as in `Exam::delete`. | |
| 467 | - let slot = result.num_statements().saturating_sub(2); | |
| 468 | - let removed = result.take::<Vec<ExamResult>>(slot)?; | |
| 469 | - Ok(removed.into_iter().next()) | |
| 470 | 138 | } |
| 139 | + order | |
| 140 | + .into_iter() | |
| 141 | + .map(|key| best.remove(&key).expect("key was recorded on insert")) | |
| 142 | + .collect() | |
| 471 | 143 | } |
| 472 | 144 | |
| 473 | 145 | #[cfg(test)] |
| 474 | 146 | mod tests { |
| 475 | 147 | use super::*; |
| 476 | - use crate::database::init_mem; | |
| 477 | 148 | |
| 478 | 149 | #[tokio::test] |
| 479 | 150 | async fn mark_range_is_enforced() { |
| @@ -482,469 +153,4 @@ mod tests { | ||
| 482 | 153 | assert!(Mark::try_new(-1).is_err()); |
| 483 | 154 | assert!(Mark::try_new(101).is_err()); |
| 484 | 155 | } |
| 485 | - | |
| 486 | - #[tokio::test] | |
| 487 | - async fn retakes_keep_a_mark_per_sitting_with_the_latest_as_grade_of_record() { | |
| 488 | - let db = init_mem().await.unwrap(); | |
| 489 | - let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA"); | |
| 490 | - let user = UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"); | |
| 491 | - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | |
| 492 | - // The exam has to be real: a mark is refused on one that isn't. | |
| 493 | - db.query( | |
| 494 | - "CREATE $ex SET creator = $t, course = course:c, title = 't', | |
| 495 | - description = '', kind = 'midterm'", | |
| 496 | - ) | |
| 497 | - .bind(("ex", exam.record())) | |
| 498 | - .bind(("t", teacher.record())) | |
| 499 | - .await | |
| 500 | - .unwrap() | |
| 501 | - .check() | |
| 502 | - .unwrap(); | |
| 503 | - | |
| 504 | - // Grade sitting #1, then a retake as sitting #2 — two rows, not one. | |
| 505 | - ExamResult::grade( | |
| 506 | - &exam, | |
| 507 | - &user, | |
| 508 | - 1, | |
| 509 | - Mark::try_new(40).unwrap(), | |
| 510 | - &teacher, | |
| 511 | - "midterm", | |
| 512 | - &db, | |
| 513 | - ) | |
| 514 | - .await | |
| 515 | - .unwrap(); | |
| 516 | - let second = ExamResult::grade( | |
| 517 | - &exam, | |
| 518 | - &user, | |
| 519 | - 2, | |
| 520 | - Mark::try_new(90).unwrap(), | |
| 521 | - &teacher, | |
| 522 | - "midterm", | |
| 523 | - &db, | |
| 524 | - ) | |
| 525 | - .await | |
| 526 | - .unwrap(); | |
| 527 | - assert_eq!(second.get_seq(), 2); | |
| 528 | - | |
| 529 | - // Grade-of-record is the latest sitting's mark. | |
| 530 | - let latest = ExamResult::read_for_user(&exam, &user, &db) | |
| 531 | - .await | |
| 532 | - .unwrap() | |
| 533 | - .expect("graded"); | |
| 534 | - assert_eq!(latest.get_mark().as_i64(), 90); | |
| 535 | - assert_eq!(latest.get_seq(), 2); | |
| 536 | - | |
| 537 | - // The roster yields exactly one row per pair — the latest. | |
| 538 | - let roster = ExamResult::list_for_exam(&exam, &db).await.unwrap(); | |
| 539 | - assert_eq!(roster.len(), 1); | |
| 540 | - assert_eq!(roster[0].get_mark().as_i64(), 90); | |
| 541 | - | |
| 542 | - // History keeps both sittings, oldest first. | |
| 543 | - let history = ExamResult::list_all_for_exam_user(&exam, &user, &db) | |
| 544 | - .await | |
| 545 | - .unwrap(); | |
| 546 | - assert_eq!( | |
| 547 | - history | |
| 548 | - .iter() | |
| 549 | - .map(|r| r.get_mark().as_i64()) | |
| 550 | - .collect::<Vec<_>>(), | |
| 551 | - vec![40, 90] | |
| 552 | - ); | |
| 553 | - | |
| 554 | - // Deleting the pair removes every sitting. | |
| 555 | - ExamResult::remove(&exam, &user, "midterm", &db) | |
| 556 | - .await | |
| 557 | - .unwrap(); | |
| 558 | - assert!( | |
| 559 | - ExamResult::list_all_for_exam_user(&exam, &user, &db) | |
| 560 | - .await | |
| 561 | - .unwrap() | |
| 562 | - .is_empty() | |
| 563 | - ); | |
| 564 | - } | |
| 565 | - | |
| 566 | - /// A deleted exam reads NONE, and NONE is falsy — the draft gate alone let | |
| 567 | - /// a mark land on an exam that no longer existed. | |
| 568 | - #[tokio::test] | |
| 569 | - async fn a_mark_is_refused_on_an_exam_that_no_longer_exists() { | |
| 570 | - let db = init_mem().await.unwrap(); | |
| 571 | - let exam = ExamId::from_key("01TESTGONEEXAMAAAAAAAAAAAA"); | |
| 572 | - let user = UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"); | |
| 573 | - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | |
| 574 | - | |
| 575 | - let refused = ExamResult::grade( | |
| 576 | - &exam, | |
| 577 | - &user, | |
| 578 | - 1, | |
| 579 | - Mark::try_new(40).unwrap(), | |
| 580 | - &teacher, | |
| 581 | - "midterm", | |
| 582 | - &db, | |
| 583 | - ) | |
| 584 | - .await; | |
| 585 | - assert!(matches!(refused, Err(AppError::NotFound)), "{refused:?}"); | |
| 586 | - assert!( | |
| 587 | - ExamResult::list_all_for_exam_user(&exam, &user, &db) | |
| 588 | - .await | |
| 589 | - .unwrap() | |
| 590 | - .is_empty() | |
| 591 | - ); | |
| 592 | - assert_eq!(counters(&db, "midterm").await, (0, 0)); | |
| 593 | - } | |
| 594 | - | |
| 595 | - /// The two counters, re-read out of the store — never off a return value, | |
| 596 | - /// which the in-memory engine forges wins on (see `cap::CLAIM_LOCK`). A | |
| 597 | - /// missing `kind_ref` row is a zero, which is exactly how the backfill | |
| 598 | - /// treats it (`tests/persistence.rs` — no zero pass, deliberately). | |
| 599 | - async fn counters(db: &Database, kind: &str) -> (i64, i64) { | |
| 600 | - let mut result = db | |
| 601 | - .query( | |
| 602 | - "SELECT VALUE count ?? 0 FROM kind_ref WHERE record::id(id) = $kind; | |
| 603 | - SELECT VALUE result_count ?? 0 FROM exam;", | |
| 604 | - ) | |
| 605 | - .bind(("kind", kind.to_string())) | |
| 606 | - .await | |
| 607 | - .unwrap() | |
| 608 | - .check() | |
| 609 | - .unwrap(); | |
| 610 | - let kinds: Vec<i64> = result.take(0).unwrap(); | |
| 611 | - let exams: Vec<i64> = result.take(1).unwrap(); | |
| 612 | - ( | |
| 613 | - kinds.into_iter().next().unwrap_or(0), | |
| 614 | - exams.into_iter().next().unwrap_or(0), | |
| 615 | - ) | |
| 616 | - } | |
| 617 | - | |
| 618 | - async fn an_exam(db: &Database, exam: &ExamId, kind: &str) { | |
| 619 | - db.query( | |
| 620 | - "CREATE $ex SET creator = user:t, course = course:c, title = 't', | |
| 621 | - description = '', kind = $kind", | |
| 622 | - ) | |
| 623 | - .bind(("ex", exam.record())) | |
| 624 | - .bind(("kind", kind.to_string())) | |
| 625 | - .await | |
| 626 | - .unwrap() | |
| 627 | - .check() | |
| 628 | - .unwrap(); | |
| 629 | - } | |
| 630 | - | |
| 631 | - const STUDENT: &str = "01TESTSTUDENTAAAAAAAAAAAAA"; | |
| 632 | - const TEACHER: &str = "01TESTTEACHERAAAAAAAAAAAAA"; | |
| 633 | - | |
| 634 | - async fn grade( | |
| 635 | - db: &Database, | |
| 636 | - exam: &ExamId, | |
| 637 | - seq: i64, | |
| 638 | - mark: i64, | |
| 639 | - kind: &str, | |
| 640 | - ) -> Result<ExamResult, AppError> { | |
| 641 | - ExamResult::grade( | |
| 642 | - exam, | |
| 643 | - &UserId::from_key(STUDENT), | |
| 644 | - seq, | |
| 645 | - Mark::try_new(mark).unwrap(), | |
| 646 | - &UserId::from_key(TEACHER), | |
| 647 | - kind, | |
| 648 | - db, | |
| 649 | - ) | |
| 650 | - .await | |
| 651 | - } | |
| 652 | - | |
| 653 | - /// Both counters ride the mark's own transaction: a new mark claims each | |
| 654 | - /// exactly once, and a *regrade* of the same sitting claims neither — one | |
| 655 | - /// mark, one reference. Claimed-then-released around the write, a regrade | |
| 656 | - /// drifted them upward and froze the kind out of the settings for good. | |
| 657 | - #[tokio::test] | |
| 658 | - async fn a_new_mark_moves_both_counters_and_a_regrade_moves_neither() { | |
| 659 | - let db = init_mem().await.unwrap(); | |
| 660 | - let exam = ExamId::from_key("01TESTEXAMCOUNTAAAAAAAAAAA"); | |
| 661 | - an_exam(&db, &exam, "midterm").await; | |
| 662 | - | |
| 663 | - grade(&db, &exam, 1, 40, "midterm").await.unwrap(); | |
| 664 | - assert_eq!(counters(&db, "midterm").await, (1, 1)); | |
| 665 | - | |
| 666 | - // Same sitting, new mark: an overwrite, so neither counter moves. | |
| 667 | - let regraded = grade(&db, &exam, 1, 90, "midterm").await.unwrap(); | |
| 668 | - assert_eq!(regraded.get_mark().as_i64(), 90); | |
| 669 | - assert_eq!(counters(&db, "midterm").await, (1, 1)); | |
| 670 | - | |
| 671 | - // A retake is a second row, so it does claim. | |
| 672 | - grade(&db, &exam, 2, 70, "midterm").await.unwrap(); | |
| 673 | - assert_eq!(counters(&db, "midterm").await, (2, 2)); | |
| 674 | - } | |
| 675 | - | |
| 676 | - /// The two badge counters, re-read out of the store: the grader's marks | |
| 677 | - /// given and the student's high marks. | |
| 678 | - async fn badge_counters(db: &Database) -> (i64, i64) { | |
| 679 | - let mut result = db | |
| 680 | - .query(format!( | |
| 681 | - "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $grader; | |
| 682 | - SELECT VALUE ({HIGH_MARK_TOTAL_FIELD} ?? 0) FROM $student;" | |
| 683 | - )) | |
| 684 | - .bind(("grader", UserId::from_key(TEACHER).record())) | |
| 685 | - .bind(("student", UserId::from_key(STUDENT).record())) | |
| 686 | - .await | |
| 687 | - .unwrap() | |
| 688 | - .check() | |
| 689 | - .unwrap(); | |
| 690 | - let given: Vec<i64> = result.take(0).unwrap(); | |
| 691 | - let high: Vec<i64> = result.take(1).unwrap(); | |
| 692 | - ( | |
| 693 | - given.into_iter().next().unwrap_or(0), | |
| 694 | - high.into_iter().next().unwrap_or(0), | |
| 695 | - ) | |
| 696 | - } | |
| 697 | - | |
| 698 | - /// The rows a counter needs to land on — `UPDATE` writes nothing to a user | |
| 699 | - /// that does not exist, so the badge tests must make both real. | |
| 700 | - async fn the_two_people(db: &Database) { | |
| 701 | - for key in [TEACHER, STUDENT] { | |
| 702 | - db.query("CREATE $usr SET username = $name, password_hash = 'x'") | |
| 703 | - .bind(("usr", UserId::from_key(key).record())) | |
| 704 | - .bind(("name", key.to_string())) | |
| 705 | - .await | |
| 706 | - .unwrap() | |
| 707 | - .check() | |
| 708 | - .unwrap(); | |
| 709 | - } | |
| 710 | - } | |
| 711 | - | |
| 712 | - /// A first grade credits the grader once and the student only when the mark | |
| 713 | - /// clears the line; a regrade of the same sitting credits neither again, | |
| 714 | - /// while a retake — a distinct seq, so a distinct row — counts on its own. | |
| 715 | - #[tokio::test] | |
| 716 | - async fn a_grade_credits_the_grader_once_and_a_high_mark_the_student() { | |
| 717 | - let db = init_mem().await.unwrap(); | |
| 718 | - let exam = ExamId::from_key("01TESTEXAMBADGEAAAAAAAAAAA"); | |
| 719 | - an_exam(&db, &exam, "midterm").await; | |
| 720 | - the_two_people(&db).await; | |
| 721 | - | |
| 722 | - grade(&db, &exam, 1, 90, "midterm").await.unwrap(); | |
| 723 | - assert_eq!(badge_counters(&db).await, (1, 1), "at the line earns it"); | |
| 724 | - | |
| 725 | - // Same sitting graded again: neither counter may move, however high. | |
| 726 | - grade(&db, &exam, 1, 100, "midterm").await.unwrap(); | |
| 727 | - assert_eq!(badge_counters(&db).await, (1, 1), "a regrade moves nothing"); | |
| 728 | - | |
| 729 | - // A retake below the line: the grader is credited, the student is not. | |
| 730 | - grade(&db, &exam, 2, 89, "midterm").await.unwrap(); | |
| 731 | - assert_eq!(badge_counters(&db).await, (2, 1), "89 is under the line"); | |
| 732 | - | |
| 733 | - // …and a high-scoring retake counts as its own sitting. | |
| 734 | - grade(&db, &exam, 3, 95, "midterm").await.unwrap(); | |
| 735 | - assert_eq!(badge_counters(&db).await, (3, 2)); | |
| 736 | - } | |
| 737 | - | |
| 738 | - /// Ungrading gives both badge counters back, so grade → ungrade → regrade | |
| 739 | - /// nets to one credit however often it is run. Crediting the grade without | |
| 740 | - /// refunding the delete let that loop mint a badge off a single exam — and | |
| 741 | - /// an award, once earned, is never taken back. | |
| 742 | - #[tokio::test] | |
| 743 | - async fn ungrading_gives_the_badge_counters_back() { | |
| 744 | - let db = init_mem().await.unwrap(); | |
| 745 | - let exam = ExamId::from_key("01TESTEXAMUNGRADEAAAAAAAAA"); | |
| 746 | - an_exam(&db, &exam, "midterm").await; | |
| 747 | - the_two_people(&db).await; | |
| 748 | - let student = UserId::from_key(STUDENT); | |
| 749 | - | |
| 750 | - for _ in 0..3 { | |
| 751 | - grade(&db, &exam, 1, 95, "midterm").await.unwrap(); | |
| 752 | - assert_eq!(badge_counters(&db).await, (1, 1)); | |
| 753 | - ExamResult::remove(&exam, &student, "midterm", &db) | |
| 754 | - .await | |
| 755 | - .unwrap() | |
| 756 | - .expect("the mark was there"); | |
| 757 | - assert_eq!(badge_counters(&db).await, (0, 0), "the loop kept a credit"); | |
| 758 | - // The kind's reference and the exam's count come back as before. | |
| 759 | - assert_eq!(counters(&db, "midterm").await, (0, 0)); | |
| 760 | - } | |
| 761 | - | |
| 762 | - // Every removed sitting is refunded, and only the ones that took: the | |
| 763 | - // grader gets both back, the student only the mark that cleared the line. | |
| 764 | - grade(&db, &exam, 1, 40, "midterm").await.unwrap(); | |
| 765 | - grade(&db, &exam, 2, 95, "midterm").await.unwrap(); | |
| 766 | - assert_eq!(badge_counters(&db).await, (2, 1)); | |
| 767 | - ExamResult::remove(&exam, &student, "midterm", &db) | |
| 768 | - .await | |
| 769 | - .unwrap() | |
| 770 | - .expect("both sittings were there"); | |
| 771 | - assert_eq!(badge_counters(&db).await, (0, 0)); | |
| 772 | - | |
| 773 | - // Nothing to remove is nothing to give back — the floor holds. | |
| 774 | - assert!( | |
| 775 | - ExamResult::remove(&exam, &student, "midterm", &db) | |
| 776 | - .await | |
| 777 | - .unwrap() | |
| 778 | - .is_none() | |
| 779 | - ); | |
| 780 | - assert_eq!(badge_counters(&db).await, (0, 0)); | |
| 781 | - } | |
| 782 | - | |
| 783 | - /// A regrade walks the *same* sitting across [`HIGH_MARK_MIN`], and the | |
| 784 | - /// student's counter has to walk with it — the delete refunds off the mark | |
| 785 | - /// it finds stored, so a credit decided by a mark that is no longer there | |
| 786 | - /// is a credit nothing can give back. Left on the first-write branch alone, | |
| 787 | - /// grade-high → regrade-low → delete kept a phantom high mark every round | |
| 788 | - /// and looped it into a permanent badge. | |
| 789 | - #[tokio::test] | |
| 790 | - async fn a_regrade_across_the_line_moves_the_student_counter_with_it() { | |
| 791 | - let db = init_mem().await.unwrap(); | |
| 792 | - let exam = ExamId::from_key("01TESTEXAMREGRADEAAAAAAAAA"); | |
| 793 | - an_exam(&db, &exam, "midterm").await; | |
| 794 | - the_two_people(&db).await; | |
| 795 | - let student = UserId::from_key(STUDENT); | |
| 796 | - | |
| 797 | - // Up across the line: no row is added, but a high mark now exists. | |
| 798 | - grade(&db, &exam, 1, 40, "midterm").await.unwrap(); | |
| 799 | - assert_eq!(badge_counters(&db).await, (1, 0), "40 is under the line"); | |
| 800 | - grade(&db, &exam, 1, 95, "midterm").await.unwrap(); | |
| 801 | - assert_eq!(badge_counters(&db).await, (1, 1), "the regrade crossed up"); | |
| 802 | - ExamResult::remove(&exam, &student, "midterm", &db) | |
| 803 | - .await | |
| 804 | - .unwrap() | |
| 805 | - .expect("the mark was there"); | |
| 806 | - assert_eq!(badge_counters(&db).await, (0, 0)); | |
| 807 | - | |
| 808 | - // Down across it: the credit goes back the moment the mark does, so | |
| 809 | - // the delete has nothing left to refund and the counter still lands | |
| 810 | - // on zero rather than under it. | |
| 811 | - grade(&db, &exam, 1, 95, "midterm").await.unwrap(); | |
| 812 | - assert_eq!(badge_counters(&db).await, (1, 1)); | |
| 813 | - grade(&db, &exam, 1, 40, "midterm").await.unwrap(); | |
| 814 | - assert_eq!( | |
| 815 | - badge_counters(&db).await, | |
| 816 | - (1, 0), | |
| 817 | - "the regrade crossed down" | |
| 818 | - ); | |
| 819 | - ExamResult::remove(&exam, &student, "midterm", &db) | |
| 820 | - .await | |
| 821 | - .unwrap() | |
| 822 | - .expect("the mark was there"); | |
| 823 | - assert_eq!(badge_counters(&db).await, (0, 0)); | |
| 824 | - | |
| 825 | - // Both sides of a regrade above the line: nothing crosses, nothing moves. | |
| 826 | - grade(&db, &exam, 1, 90, "midterm").await.unwrap(); | |
| 827 | - grade(&db, &exam, 1, 100, "midterm").await.unwrap(); | |
| 828 | - assert_eq!(badge_counters(&db).await, (1, 1), "90 → 100 stays one"); | |
| 829 | - | |
| 830 | - // The loop that minted the badge: three rounds of high → low → delete | |
| 831 | - // must leave the counter exactly where it started. | |
| 832 | - for _ in 0..3 { | |
| 833 | - grade(&db, &exam, 1, 95, "midterm").await.unwrap(); | |
| 834 | - grade(&db, &exam, 1, 40, "midterm").await.unwrap(); | |
| 835 | - ExamResult::remove(&exam, &student, "midterm", &db) | |
| 836 | - .await | |
| 837 | - .unwrap() | |
| 838 | - .expect("the mark was there"); | |
| 839 | - } | |
| 840 | - assert_eq!( | |
| 841 | - badge_counters(&db).await, | |
| 842 | - (0, 0), | |
| 843 | - "the loop kept a high mark with no high mark stored" | |
| 844 | - ); | |
| 845 | - } | |
| 846 | - | |
| 847 | - /// The other half of the same asymmetry: a refund read off a stored mark | |
| 848 | - /// that was never credited eats a credit earned somewhere else. One exam | |
| 849 | - /// holds a genuine high mark while a second is graded low, regraded high | |
| 850 | - /// and deleted — the first exam's credit must still be standing. | |
| 851 | - #[tokio::test] | |
| 852 | - async fn one_exams_regrade_never_eats_another_exams_high_mark() { | |
| 853 | - let db = init_mem().await.unwrap(); | |
| 854 | - let first = ExamId::from_key("01TESTEXAMSTEALONEAAAAAAAA"); | |
| 855 | - let second = ExamId::from_key("01TESTEXAMSTEALTWOAAAAAAAA"); | |
| 856 | - an_exam(&db, &first, "midterm").await; | |
| 857 | - an_exam(&db, &second, "midterm").await; | |
| 858 | - the_two_people(&db).await; | |
| 859 | - let student = UserId::from_key(STUDENT); | |
| 860 | - | |
| 861 | - grade(&db, &first, 1, 95, "midterm").await.unwrap(); | |
| 862 | - assert_eq!( | |
| 863 | - badge_counters(&db).await, | |
| 864 | - (1, 1), | |
| 865 | - "earned on the first exam" | |
| 866 | - ); | |
| 867 | - | |
| 868 | - grade(&db, &second, 1, 40, "midterm").await.unwrap(); | |
| 869 | - grade(&db, &second, 1, 95, "midterm").await.unwrap(); | |
| 870 | - assert_eq!(badge_counters(&db).await, (2, 2)); | |
| 871 | - ExamResult::remove(&second, &student, "midterm", &db) | |
| 872 | - .await | |
| 873 | - .unwrap() | |
| 874 | - .expect("the mark was there"); | |
| 875 | - assert_eq!( | |
| 876 | - badge_counters(&db).await, | |
| 877 | - (1, 1), | |
| 878 | - "the first exam's high mark was eaten" | |
| 879 | - ); | |
| 880 | - } | |
| 881 | - | |
| 882 | - /// A refused mark leaves the badge counters where the other two are left. | |
| 883 | - #[tokio::test] | |
| 884 | - async fn a_refused_mark_credits_nobody() { | |
| 885 | - let db = init_mem().await.unwrap(); | |
| 886 | - let exam = ExamId::from_key("01TESTEXAMBADGEDRAFTAAAAAA"); | |
| 887 | - an_exam(&db, &exam, "midterm").await; | |
| 888 | - the_two_people(&db).await; | |
| 889 | - db.query("UPDATE $ex SET draft = true") | |
| 890 | - .bind(("ex", exam.record())) | |
| 891 | - .await | |
| 892 | - .unwrap() | |
| 893 | - .check() | |
| 894 | - .unwrap(); | |
| 895 | - | |
| 896 | - assert!(grade(&db, &exam, 1, 100, "midterm").await.is_err()); | |
| 897 | - assert_eq!(badge_counters(&db).await, (0, 0)); | |
| 898 | - } | |
| 899 | - | |
| 900 | - /// A retired kind refuses the claim from inside the transaction, which | |
| 901 | - /// takes the mark and the exam's counter down with it — the settings guard | |
| 902 | - /// enforcing the same invariant from the other side. | |
| 903 | - #[tokio::test] | |
| 904 | - async fn a_retired_kind_refuses_the_mark_and_leaves_both_counters_alone() { | |
| 905 | - let db = init_mem().await.unwrap(); | |
| 906 | - let exam = ExamId::from_key("01TESTEXAMRETIREDAAAAAAAAA"); | |
| 907 | - an_exam(&db, &exam, "midterm").await; | |
| 908 | - assert!(cap::retire(&kind_ref("midterm"), &db).await.unwrap()); | |
| 909 | - | |
| 910 | - let refused = grade(&db, &exam, 1, 40, "midterm").await; | |
| 911 | - assert!( | |
| 912 | - matches!(&refused, Err(AppError::ConflictOwned(message)) | |
| 913 | - if message.contains("has been removed from the school's settings")), | |
| 914 | - "{refused:?}" | |
| 915 | - ); | |
| 916 | - assert!( | |
| 917 | - ExamResult::list_for_exam(&exam, &db) | |
| 918 | - .await | |
| 919 | - .unwrap() | |
| 920 | - .is_empty(), | |
| 921 | - "the mark must not have landed" | |
| 922 | - ); | |
| 923 | - assert_eq!(counters(&db, "midterm").await, (0, 0)); | |
| 924 | - } | |
| 925 | - | |
| 926 | - /// A draft exam refuses the mark, and the counters stay put — the gate | |
| 927 | - /// runs before the claim now, so there is nothing to give back. | |
| 928 | - #[tokio::test] | |
| 929 | - async fn a_draft_exam_refuses_the_mark_and_leaves_both_counters_alone() { | |
| 930 | - let db = init_mem().await.unwrap(); | |
| 931 | - let exam = ExamId::from_key("01TESTEXAMDRAFTAAAAAAAAAAA"); | |
| 932 | - an_exam(&db, &exam, "midterm").await; | |
| 933 | - db.query("UPDATE $ex SET draft = true") | |
| 934 | - .bind(("ex", exam.record())) | |
| 935 | - .await | |
| 936 | - .unwrap() | |
| 937 | - .check() | |
| 938 | - .unwrap(); | |
| 939 | - | |
| 940 | - let refused = grade(&db, &exam, 1, 40, "midterm").await; | |
| 941 | - assert!(matches!(refused, Err(AppError::Conflict(_))), "{refused:?}"); | |
| 942 | - assert!( | |
| 943 | - ExamResult::list_for_exam(&exam, &db) | |
| 944 | - .await | |
| 945 | - .unwrap() | |
| 946 | - .is_empty() | |
| 947 | - ); | |
| 948 | - assert_eq!(counters(&db, "midterm").await, (0, 0)); | |
| 949 | - } | |
| 950 | 156 | } |
src/domain/homework_submission.rsmodified+2 -2
| @@ -124,7 +124,7 @@ impl HomeworkSubmission { | ||
| 124 | 124 | /// transaction, and the order is load-bearing: the increment sits *after* |
| 125 | 125 | /// the UPSERT and is conditional on it having matched a row, because a |
| 126 | 126 | /// frozen row makes that `WHERE` match nothing **silently** (unlike |
| 127 | - /// [`crate::domain::exam_result::ExamResult::grade`], which `THROW`s) — put | |
| 127 | + /// [`crate::db::exam_result::grade`], which `THROW`s) — put | |
| 128 | 128 | /// first, it would count a submission the freeze refused. `$before = NONE` |
| 129 | 129 | /// keeps it to a genuine first create, so an edit moves neither counter, |
| 130 | 130 | /// which is what makes the live count mean the same thing the one-time |
| @@ -160,7 +160,7 @@ impl HomeworkSubmission { | ||
| 160 | 160 | /// homework row — `due_at` up by one and straight back to the captured |
| 161 | 161 | /// value, so the row is byte-identical afterwards — because only a write |
| 162 | 162 | /// collides, and `SET x = x` is elided and never reaches the write set. It |
| 163 | - /// is [`crate::domain::exam_answer::ExamAnswer::save`]'s shape exactly. | |
| 163 | + /// is [`crate::db::exam_answer::save`]'s shape exactly. | |
| 164 | 164 | /// `Err(NotFound)` means the homework is gone, which is the 404 the web |
| 165 | 165 | /// layer's own lookup would have answered. |
| 166 | 166 | pub async fn upsert( |
src/domain/pool_question.rsmodified+1 -1
| @@ -717,7 +717,7 @@ mod tests { | ||
| 717 | 717 | ); |
| 718 | 718 | } |
| 719 | 719 | |
| 720 | - /// The [`crate::domain::exam_answer::ExamAnswer::save`] defect, one domain | |
| 720 | + /// The [`crate::db::exam_answer::save`] defect, one domain | |
| 721 | 721 | /// over: a solution offered inside its question's delete window must not |
| 722 | 722 | /// outlive it. Guarding the offer by *reading* the question does not do it |
| 723 | 723 | /// — the read sees a row [`PoolQuestion::delete`] has removed but not |
src/domain/question_image.rsmodified+13 -359
| @@ -5,21 +5,19 @@ | ||
| 5 | 5 | //! `file` — a fresh server-generated ULID per upload, so no user input ever |
| 6 | 6 | //! shapes a disk path and a replace never overwrites bytes in place. The row |
| 7 | 7 | //! id is *deterministic* per (question, slot), so "one image per slot" holds |
| 8 | -//! by construction and a replace is a plain UPSERT. The web layer owns the | |
| 9 | -//! blob I/O and its ordering (new blob before row, row before old blob); | |
| 10 | -//! this module owns the rows. | |
| 8 | +//! by construction and a replace is a plain UPSERT. The queries and | |
| 9 | +//! transactions over these rows live in [`crate::db::question_image`]; the web | |
| 10 | +//! layer owns the blob I/O and its ordering (new blob before row, row before | |
| 11 | +//! old blob). | |
| 11 | 12 | |
| 12 | 13 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 13 | 14 | use ulid::Ulid; |
| 14 | 15 | |
| 15 | 16 | use crate::constant::QUESTION_IMAGE_TABLE; |
| 16 | -use crate::database::Database; | |
| 17 | -use crate::domain::course::CourseId; | |
| 18 | 17 | use crate::domain::exam::ExamId; |
| 19 | 18 | use crate::domain::exam_question::{ChoiceId, ExamQuestionId}; |
| 20 | 19 | use crate::domain::key; |
| 21 | 20 | use crate::domain::note_file::FileContentType; |
| 22 | -use crate::error::AppError; | |
| 23 | 21 | |
| 24 | 22 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 25 | 23 | pub struct QuestionImageId(RecordId); |
| @@ -48,32 +46,23 @@ impl QuestionImageId { | ||
| 48 | 46 | |
| 49 | 47 | #[derive(Debug, Clone, SurrealValue)] |
| 50 | 48 | pub struct QuestionImage { |
| 51 | - id: QuestionImageId, | |
| 52 | - exam: ExamId, | |
| 53 | - question: ExamQuestionId, | |
| 49 | + pub(crate) id: QuestionImageId, | |
| 50 | + pub(crate) exam: ExamId, | |
| 51 | + pub(crate) question: ExamQuestionId, | |
| 54 | 52 | /// `NONE` = the question's illustration; otherwise the id of the option |
| 55 | 53 | /// this picture belongs to. |
| 56 | - slot: Option<ChoiceId>, | |
| 54 | + pub(crate) slot: Option<ChoiceId>, | |
| 57 | 55 | /// The blob's on-disk name — a fresh ULID every upload. |
| 58 | - file: String, | |
| 59 | - content_type: FileContentType, | |
| 60 | - size: i64, | |
| 61 | -} | |
| 62 | - | |
| 63 | -/// What one [`QuestionImage::upsert`] transaction returns: the row it stored | |
| 64 | -/// and the blob name it replaced. Both are arrays because SurrealDB drops an | |
| 65 | -/// object key valued `NONE` on the way out, while an empty array survives — | |
| 66 | -/// "nothing was replaced" has to be readable, not missing. | |
| 67 | -#[derive(SurrealValue)] | |
| 68 | -struct UpsertOutcome { | |
| 69 | - stored: Vec<QuestionImage>, | |
| 70 | - replaced: Vec<String>, | |
| 56 | + pub(crate) file: String, | |
| 57 | + pub(crate) content_type: FileContentType, | |
| 58 | + pub(crate) size: i64, | |
| 71 | 59 | } |
| 72 | 60 | |
| 73 | 61 | impl QuestionImage { |
| 74 | 62 | /// Assemble a row (fresh blob name generated here) without persisting it. |
| 75 | 63 | /// The caller writes the blob under [`Self::get_file`] first, then calls |
| 76 | - /// [`Self::upsert`] — so a stored row always points at a real blob. | |
| 64 | + /// [`crate::db::question_image::upsert`] — so a stored row always points | |
| 65 | + /// at a real blob. | |
| 77 | 66 | pub fn new( |
| 78 | 67 | exam: &ExamId, |
| 79 | 68 | question: &ExamQuestionId, |
| @@ -111,339 +100,4 @@ impl QuestionImage { | ||
| 111 | 100 | pub fn get_size(&self) -> i64 { |
| 112 | 101 | self.size |
| 113 | 102 | } |
| 114 | - | |
| 115 | - /// Create or replace the slot's image row — the deterministic id makes | |
| 116 | - /// this the whole "one image per slot" story — handing back what it stored | |
| 117 | - /// plus the blob name it replaced, for the caller to take off disk. Refused | |
| 118 | - /// once the exam has an attempt: pictures are part of the question, so they | |
| 119 | - /// freeze with it, and the gate is in this transaction rather than in a lock | |
| 120 | - /// the caller held. | |
| 121 | - /// | |
| 122 | - /// The replaced name is read *here*, not by the caller before it: two | |
| 123 | - /// uploads to one slot both write this row, so they contend and the loser | |
| 124 | - /// re-reads the winner's blob name, where two pre-reads both saw the *old* | |
| 125 | - /// blob and left the loser's fresh one orphaned on disk. | |
| 126 | - pub async fn upsert(self, db: &Database) -> Result<(QuestionImage, Option<String>), AppError> { | |
| 127 | - // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic | |
| 128 | - let (exam, id) = (self.exam.clone(), self.id.record()); | |
| 129 | - let mut result = crate::db::exam_attempt::write_unfrozen( | |
| 130 | - db, | |
| 131 | - &exam, | |
| 132 | - "LET $replaced = (SELECT VALUE file FROM $id); | |
| 133 | - LET $stored = (UPSERT $id CONTENT $image); | |
| 134 | - RETURN { stored: $stored, replaced: $replaced };", | |
| 135 | - vec![ | |
| 136 | - ("id".into(), id.into_value()), | |
| 137 | - ("image".into(), self.into_value()), | |
| 138 | - ], | |
| 139 | - ) | |
| 140 | - .await?; | |
| 141 | - // The trailing `RETURN` is the last statement before `COMMIT`, so its | |
| 142 | - // slot follows the statement count rather than a hand-kept number; | |
| 143 | - // `num_statements` counts BEGIN and COMMIT. | |
| 144 | - let slot = result.num_statements().saturating_sub(2); | |
| 145 | - let failed = || AppError::Internal("failed to store question image".into()); | |
| 146 | - let outcome = result | |
| 147 | - .take::<Vec<UpsertOutcome>>(slot)? | |
| 148 | - .into_iter() | |
| 149 | - .next() | |
| 150 | - .ok_or_else(failed)?; | |
| 151 | - let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; | |
| 152 | - Ok((stored, outcome.replaced.into_iter().next())) | |
| 153 | - } | |
| 154 | - | |
| 155 | - pub async fn read_slot( | |
| 156 | - question: &ExamQuestionId, | |
| 157 | - slot: Option<&ChoiceId>, | |
| 158 | - db: &Database, | |
| 159 | - ) -> Result<Option<QuestionImage>, AppError> { | |
| 160 | - Ok(db | |
| 161 | - .select(QuestionImageId::for_slot(question, slot).record()) | |
| 162 | - .await?) | |
| 163 | - } | |
| 164 | - | |
| 165 | - /// Every image of the exam's questions — one query for the list views. | |
| 166 | - pub async fn list_for_exam( | |
| 167 | - exam: &ExamId, | |
| 168 | - db: &Database, | |
| 169 | - ) -> Result<Vec<QuestionImage>, AppError> { | |
| 170 | - let mut result = db | |
| 171 | - .query("SELECT * FROM question_image WHERE exam = $ex") | |
| 172 | - .bind(("ex", exam.record())) | |
| 173 | - .await? | |
| 174 | - .check()?; | |
| 175 | - Ok(result.take::<Vec<QuestionImage>>(0)?) | |
| 176 | - } | |
| 177 | - | |
| 178 | - pub async fn list_for_question( | |
| 179 | - question: &ExamQuestionId, | |
| 180 | - db: &Database, | |
| 181 | - ) -> Result<Vec<QuestionImage>, AppError> { | |
| 182 | - let mut result = db | |
| 183 | - .query("SELECT * FROM question_image WHERE question = $q") | |
| 184 | - .bind(("q", question.record())) | |
| 185 | - .await? | |
| 186 | - .check()?; | |
| 187 | - Ok(result.take::<Vec<QuestionImage>>(0)?) | |
| 188 | - } | |
| 189 | - | |
| 190 | - /// Drop the option pictures whose choice is gone — every choice image of | |
| 191 | - /// the question whose `slot` is *not* in `keep` (the question's own | |
| 192 | - /// illustration always stays), returning the removed rows so the caller can | |
| 193 | - /// take their blobs off disk. | |
| 194 | - /// | |
| 195 | - /// This is what makes an edit non-destructive: a PATCH that reorders, | |
| 196 | - /// renames, or drops options passes the surviving choice ids as `keep`, so | |
| 197 | - /// only the pictures of genuinely removed options go. `keep = &[]` (a text | |
| 198 | - /// question, or an all-new choice list) still clears the lot. | |
| 199 | - pub async fn delete_choices_not_in( | |
| 200 | - question: &ExamQuestionId, | |
| 201 | - keep: &[ChoiceId], | |
| 202 | - db: &Database, | |
| 203 | - ) -> Result<Vec<QuestionImage>, AppError> { | |
| 204 | - let keep: Vec<String> = keep.iter().map(|id| id.as_str().to_string()).collect(); | |
| 205 | - let mut result = db | |
| 206 | - .query( | |
| 207 | - "DELETE question_image \ | |
| 208 | - WHERE question = $q AND slot != NONE AND slot NOT IN $keep RETURN BEFORE", | |
| 209 | - ) | |
| 210 | - .bind(("q", question.record())) | |
| 211 | - .bind(("keep", keep)) | |
| 212 | - .await? | |
| 213 | - .check()?; | |
| 214 | - Ok(result.take::<Vec<QuestionImage>>(0)?) | |
| 215 | - } | |
| 216 | - | |
| 217 | - /// The blob names behind every image of every exam of `course` — collected | |
| 218 | - /// *before* the course-delete cascade wipes the rows. | |
| 219 | - pub async fn file_keys_for_course( | |
| 220 | - course: &CourseId, | |
| 221 | - db: &Database, | |
| 222 | - ) -> Result<Vec<String>, AppError> { | |
| 223 | - let mut result = db | |
| 224 | - .query( | |
| 225 | - "SELECT VALUE file FROM question_image \ | |
| 226 | - WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)", | |
| 227 | - ) | |
| 228 | - .bind(("course", course.record())) | |
| 229 | - .await? | |
| 230 | - .check()?; | |
| 231 | - Ok(result.take::<Vec<String>>(0)?) | |
| 232 | - } | |
| 233 | - | |
| 234 | - /// Refused once the exam has an attempt, in the same transaction — same | |
| 235 | - /// gate, same reason as [`Self::upsert`]. | |
| 236 | - pub async fn delete(self, db: &Database) -> Result<QuestionImage, AppError> { | |
| 237 | - let mut result = crate::db::exam_attempt::write_unfrozen( | |
| 238 | - db, | |
| 239 | - &self.exam, | |
| 240 | - "DELETE $id RETURN BEFORE;", | |
| 241 | - vec![("id".into(), self.id.record().into_value())], | |
| 242 | - ) | |
| 243 | - .await?; | |
| 244 | - result | |
| 245 | - .take::<Vec<QuestionImage>>(crate::db::exam_attempt::FROZEN_SLOT)? | |
| 246 | - .into_iter() | |
| 247 | - .next() | |
| 248 | - .ok_or(AppError::NotFound) | |
| 249 | - } | |
| 250 | -} | |
| 251 | - | |
| 252 | -#[cfg(test)] | |
| 253 | -mod tests { | |
| 254 | - use super::*; | |
| 255 | - use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec}; | |
| 256 | - | |
| 257 | - /// A real exam row: an image write moves its exam's counter (that is what | |
| 258 | - /// keeps a picture from outliving its exam), so a minted id nothing wrote | |
| 259 | - /// is a 404. | |
| 260 | - async fn exam_row(db: &Database) -> ExamId { | |
| 261 | - crate::db::exam::published_exam(db).await.get_id().clone() | |
| 262 | - } | |
| 263 | - | |
| 264 | - fn png() -> FileContentType { | |
| 265 | - FileContentType::try_new("image/png").unwrap() | |
| 266 | - } | |
| 267 | - | |
| 268 | - /// Three minted choice ids to slot pictures against. | |
| 269 | - fn choice_ids() -> Vec<ChoiceId> { | |
| 270 | - QuestionSpec::try_new( | |
| 271 | - QuestionKind::try_new("choice").unwrap(), | |
| 272 | - Some( | |
| 273 | - ["a", "b", "c"] | |
| 274 | - .iter() | |
| 275 | - .map(|l| ChoiceInput { | |
| 276 | - id: Some((*l).into()), | |
| 277 | - text: (*l).into(), | |
| 278 | - }) | |
| 279 | - .collect(), | |
| 280 | - ), | |
| 281 | - Some("a".into()), | |
| 282 | - &[], | |
| 283 | - ) | |
| 284 | - .unwrap() | |
| 285 | - .into_parts() | |
| 286 | - .1 | |
| 287 | - .unwrap() | |
| 288 | - .iter() | |
| 289 | - .map(|c| c.get_id().clone()) | |
| 290 | - .collect() | |
| 291 | - } | |
| 292 | - | |
| 293 | - #[tokio::test] | |
| 294 | - async fn upsert_replaces_per_slot() { | |
| 295 | - let db = crate::database::init_mem().await.unwrap(); | |
| 296 | - let exam = exam_row(&db).await; | |
| 297 | - let question = ExamQuestionId::generate(); | |
| 298 | - let ids = choice_ids(); | |
| 299 | - | |
| 300 | - let (first, retired) = QuestionImage::new(&exam, &question, None, png(), 3) | |
| 301 | - .upsert(&db) | |
| 302 | - .await | |
| 303 | - .unwrap(); | |
| 304 | - assert_eq!(retired, None, "a first upload retires no blob"); | |
| 305 | - let (second, retired) = QuestionImage::new(&exam, &question, None, png(), 5) | |
| 306 | - .upsert(&db) | |
| 307 | - .await | |
| 308 | - .unwrap(); | |
| 309 | - // Same slot, same row — the replace swapped the blob pointer, and the | |
| 310 | - // write itself names the blob the caller must unlink. | |
| 311 | - assert_ne!(first.get_file(), second.get_file()); | |
| 312 | - assert_eq!(retired.as_deref(), Some(first.get_file())); | |
| 313 | - let rows = QuestionImage::list_for_question(&question, &db) | |
| 314 | - .await | |
| 315 | - .unwrap(); | |
| 316 | - assert_eq!(rows.len(), 1); | |
| 317 | - assert_eq!(rows[0].get_size(), 5); | |
| 318 | - | |
| 319 | - // A choice slot is its own row, keyed by the option's id. | |
| 320 | - QuestionImage::new(&exam, &question, Some(&ids[0]), png(), 7) | |
| 321 | - .upsert(&db) | |
| 322 | - .await | |
| 323 | - .unwrap(); | |
| 324 | - assert_eq!( | |
| 325 | - QuestionImage::list_for_question(&question, &db) | |
| 326 | - .await | |
| 327 | - .unwrap() | |
| 328 | - .len(), | |
| 329 | - 2 | |
| 330 | - ); | |
| 331 | - let choice = QuestionImage::read_slot(&question, Some(&ids[0]), &db) | |
| 332 | - .await | |
| 333 | - .unwrap() | |
| 334 | - .unwrap(); | |
| 335 | - assert_eq!(choice.get_slot(), Some(&ids[0])); | |
| 336 | - assert!( | |
| 337 | - QuestionImage::read_slot(&question, Some(&ids[1]), &db) | |
| 338 | - .await | |
| 339 | - .unwrap() | |
| 340 | - .is_none() | |
| 341 | - ); | |
| 342 | - } | |
| 343 | - | |
| 344 | - /// The behaviour the whole remodel exists for: an edit that keeps some | |
| 345 | - /// options keeps exactly their pictures, and drops only the removed one's. | |
| 346 | - #[tokio::test] | |
| 347 | - async fn only_the_dropped_options_lose_their_pictures() { | |
| 348 | - let db = crate::database::init_mem().await.unwrap(); | |
| 349 | - let exam = exam_row(&db).await; | |
| 350 | - let question = ExamQuestionId::generate(); | |
| 351 | - let ids = choice_ids(); | |
| 352 | - QuestionImage::new(&exam, &question, None, png(), 1) | |
| 353 | - .upsert(&db) | |
| 354 | - .await | |
| 355 | - .unwrap(); | |
| 356 | - for id in &ids { | |
| 357 | - QuestionImage::new(&exam, &question, Some(id), png(), 1) | |
| 358 | - .upsert(&db) | |
| 359 | - .await | |
| 360 | - .unwrap(); | |
| 361 | - } | |
| 362 | - | |
| 363 | - // Keep the first and last option (reordered — order is irrelevant now). | |
| 364 | - let keep = vec![ids[2].clone(), ids[0].clone()]; | |
| 365 | - let dropped = QuestionImage::delete_choices_not_in(&question, &keep, &db) | |
| 366 | - .await | |
| 367 | - .unwrap(); | |
| 368 | - assert_eq!(dropped.len(), 1); | |
| 369 | - assert_eq!(dropped[0].get_slot(), Some(&ids[1])); | |
| 370 | - | |
| 371 | - let left = QuestionImage::list_for_question(&question, &db) | |
| 372 | - .await | |
| 373 | - .unwrap(); | |
| 374 | - // The question illustration plus the two surviving option pictures. | |
| 375 | - assert_eq!(left.len(), 3); | |
| 376 | - assert!( | |
| 377 | - QuestionImage::read_slot(&question, Some(&ids[0]), &db) | |
| 378 | - .await | |
| 379 | - .unwrap() | |
| 380 | - .is_some() | |
| 381 | - ); | |
| 382 | - assert!( | |
| 383 | - QuestionImage::read_slot(&question, Some(&ids[2]), &db) | |
| 384 | - .await | |
| 385 | - .unwrap() | |
| 386 | - .is_some() | |
| 387 | - ); | |
| 388 | - assert!( | |
| 389 | - QuestionImage::read_slot(&question, None, &db) | |
| 390 | - .await | |
| 391 | - .unwrap() | |
| 392 | - .is_some() | |
| 393 | - ); | |
| 394 | - } | |
| 395 | - | |
| 396 | - #[tokio::test] | |
| 397 | - async fn an_empty_keep_set_clears_every_option_picture_but_not_the_illustration() { | |
| 398 | - let db = crate::database::init_mem().await.unwrap(); | |
| 399 | - let exam = exam_row(&db).await; | |
| 400 | - let question = ExamQuestionId::generate(); | |
| 401 | - let ids = choice_ids(); | |
| 402 | - QuestionImage::new(&exam, &question, None, png(), 1) | |
| 403 | - .upsert(&db) | |
| 404 | - .await | |
| 405 | - .unwrap(); | |
| 406 | - for id in &ids[..2] { | |
| 407 | - QuestionImage::new(&exam, &question, Some(id), png(), 1) | |
| 408 | - .upsert(&db) | |
| 409 | - .await | |
| 410 | - .unwrap(); | |
| 411 | - } | |
| 412 | - | |
| 413 | - let dropped = QuestionImage::delete_choices_not_in(&question, &[], &db) | |
| 414 | - .await | |
| 415 | - .unwrap(); | |
| 416 | - assert_eq!(dropped.len(), 2); | |
| 417 | - assert!(dropped.iter().all(|image| image.get_slot().is_some())); | |
| 418 | - | |
| 419 | - let left = QuestionImage::list_for_question(&question, &db) | |
| 420 | - .await | |
| 421 | - .unwrap(); | |
| 422 | - assert_eq!(left.len(), 1); | |
| 423 | - assert_eq!(left[0].get_slot(), None); | |
| 424 | - } | |
| 425 | - | |
| 426 | - #[tokio::test] | |
| 427 | - async fn exam_listing_scopes_by_exam() { | |
| 428 | - let db = crate::database::init_mem().await.unwrap(); | |
| 429 | - let exam_a = exam_row(&db).await; | |
| 430 | - let exam_b = exam_row(&db).await; | |
| 431 | - QuestionImage::new(&exam_a, &ExamQuestionId::generate(), None, png(), 1) | |
| 432 | - .upsert(&db) | |
| 433 | - .await | |
| 434 | - .unwrap(); | |
| 435 | - assert_eq!( | |
| 436 | - QuestionImage::list_for_exam(&exam_a, &db) | |
| 437 | - .await | |
| 438 | - .unwrap() | |
| 439 | - .len(), | |
| 440 | - 1 | |
| 441 | - ); | |
| 442 | - assert!( | |
| 443 | - QuestionImage::list_for_exam(&exam_b, &db) | |
| 444 | - .await | |
| 445 | - .unwrap() | |
| 446 | - .is_empty() | |
| 447 | - ); | |
| 448 | - } | |
| 449 | 103 | } |
src/domain/session_attendance.rsmodified+2 -2
| @@ -106,7 +106,7 @@ impl SessionAttendance { | ||
| 106 | 106 | /// route 404ing on the vanished session while the attendance report went |
| 107 | 107 | /// on counting it. A deleted session reads NONE, which is falsy, so the |
| 108 | 108 | /// gate is written as an explicit `IS NONE` (see |
| 109 | - /// [`crate::domain::exam_result::ExamResult::grade`]). It reads the | |
| 109 | + /// [`crate::db::exam_result::grade`]). It reads the | |
| 110 | 110 | /// session's `teacher` — required on every row, so NONE means "no row" just |
| 111 | 111 | /// as `id` did — because the counter below needs that teacher anyway, and |
| 112 | 112 | /// one read serves both. |
| @@ -115,7 +115,7 @@ impl SessionAttendance { | ||
| 115 | 115 | /// sets, not read sets, so that gate alone only closes the *sequential* |
| 116 | 116 | /// order (delete committed, then the mark arrives). To make the two really |
| 117 | 117 | /// collide, this transaction also *writes* the session row, unconditionally |
| 118 | - /// — the bump-and-restore of [`crate::domain::exam_answer::ExamAnswer::save`] | |
| 118 | + /// — the bump-and-restore of [`crate::db::exam_answer::save`] | |
| 119 | 119 | /// on the one column this write already owns, [`LESSON_COUNTED_AT_FIELD`]. |
| 120 | 120 | /// Unconditional is the whole point: the credit branch below writes that |
| 121 | 121 | /// column already, but it fires only for the first roll call of a lesson |
src/service/answer_image.rsadded+46 -0
| @@ -0,0 +1,46 @@ | ||
| 1 | +//! The drawn-answer workflows: the doors the web layer takes for every | |
| 2 | +//! answer-image read and write. The blob I/O and its disk ordering stay in | |
| 3 | +//! the web layer; the row transactions live in [`crate::db::answer_image`]. | |
| 4 | + | |
| 5 | +use crate::database::Database; | |
| 6 | +use crate::db; | |
| 7 | +use crate::domain::answer_image::AnswerImage; | |
| 8 | +use crate::domain::exam::ExamId; | |
| 9 | +use crate::domain::exam_question::ExamQuestionId; | |
| 10 | +use crate::domain::user::UserId; | |
| 11 | +use crate::error::AppError; | |
| 12 | + | |
| 13 | +/// Create or replace the student's drawing for the question, handing back | |
| 14 | +/// what it stored plus the blob name it replaced, for the caller to take | |
| 15 | +/// off disk. | |
| 16 | +pub async fn upsert( | |
| 17 | + db: &Database, | |
| 18 | + image: AnswerImage, | |
| 19 | +) -> Result<(AnswerImage, Option<String>), AppError> { | |
| 20 | + db::answer_image::upsert(db, image).await | |
| 21 | +} | |
| 22 | + | |
| 23 | +/// The student's drawing for one question in one sitting, if any. | |
| 24 | +pub async fn read( | |
| 25 | + db: &Database, | |
| 26 | + question: &ExamQuestionId, | |
| 27 | + user: &UserId, | |
| 28 | + seq: i64, | |
| 29 | +) -> Result<Option<AnswerImage>, AppError> { | |
| 30 | + db::answer_image::read(db, question, user, seq).await | |
| 31 | +} | |
| 32 | + | |
| 33 | +/// Drop one drawing — the returned row names the blob to unlink. | |
| 34 | +pub async fn delete(db: &Database, image: AnswerImage) -> Result<AnswerImage, AppError> { | |
| 35 | + db::answer_image::delete(db, image).await | |
| 36 | +} | |
| 37 | + | |
| 38 | +/// One student's answer drawings for a single sitting. | |
| 39 | +pub async fn list_for_exam_user( | |
| 40 | + db: &Database, | |
| 41 | + exam: &ExamId, | |
| 42 | + user: &UserId, | |
| 43 | + seq: i64, | |
| 44 | +) -> Result<Vec<AnswerImage>, AppError> { | |
| 45 | + db::answer_image::list_for_exam_user(db, exam, user, seq).await | |
| 46 | +} |
src/service/course.rsmodified+3 -4
| @@ -6,11 +6,9 @@ | ||
| 6 | 6 | |
| 7 | 7 | use crate::database::Database; |
| 8 | 8 | use crate::db::course; |
| 9 | -use crate::domain::answer_image::AnswerImage; | |
| 10 | 9 | use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; |
| 11 | 10 | use crate::domain::course_note_file::CourseNoteFile; |
| 12 | 11 | use crate::domain::homework_file::HomeworkFile; |
| 13 | -use crate::domain::question_image::QuestionImage; | |
| 14 | 12 | use crate::domain::role::Role; |
| 15 | 13 | use crate::domain::term::{self, TermId}; |
| 16 | 14 | use crate::domain::user::UserId; |
| @@ -165,8 +163,9 @@ pub async fn delete(db: &Database, course: &Course) -> Result<DeleteOutcome, App | ||
| 165 | 163 | require_open(db, course).await?; |
| 166 | 164 | let _guard = crate::service::exam_attempt::EXAM_LOCK.write().await; |
| 167 | 165 | let _homework_guard = crate::web::homework::HOMEWORK_LOCK.write().await; |
| 168 | - let image_files = QuestionImage::file_keys_for_course(course.get_id(), db).await?; | |
| 169 | - let answer_image_files = AnswerImage::file_keys_for_course(course.get_id(), db).await?; | |
| 166 | + let image_files = crate::db::question_image::file_keys_for_course(db, course.get_id()).await?; | |
| 167 | + let answer_image_files = | |
| 168 | + crate::db::answer_image::file_keys_for_course(db, course.get_id()).await?; | |
| 170 | 169 | let homework_files = HomeworkFile::file_keys_for_course(course.get_id(), db).await?; |
| 171 | 170 | let course_note_files = CourseNoteFile::file_keys_for_course(course.get_id(), db).await?; |
| 172 | 171 | let deleted = course::delete(db, course.clone()).await?; |
src/service/exam.rsmodified+6 -6
| @@ -8,15 +8,15 @@ | ||
| 8 | 8 | |
| 9 | 9 | use crate::constant::CAS_UPDATE_RETRIES; |
| 10 | 10 | use crate::database::Database; |
| 11 | +use crate::db::answer_image; | |
| 11 | 12 | use crate::db::exam; |
| 12 | -use crate::domain::answer_image::AnswerImage; | |
| 13 | +use crate::db::exam_result; | |
| 14 | +use crate::db::question_image; | |
| 13 | 15 | use crate::domain::course::CourseId; |
| 14 | 16 | use crate::domain::exam::{ |
| 15 | 17 | Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, |
| 16 | 18 | ExamSchedule, ExamTitle, redraft_error, |
| 17 | 19 | }; |
| 18 | -use crate::domain::exam_result::ExamResult; | |
| 19 | -use crate::domain::question_image::QuestionImage; | |
| 20 | 20 | use crate::domain::timestamp::Timestamp; |
| 21 | 21 | use crate::domain::user::UserId; |
| 22 | 22 | use crate::error::AppError; |
| @@ -184,7 +184,7 @@ pub async fn update(db: &Database, id: &ExamId, patch: &ExamPatch) -> Result<Exa | ||
| 184 | 184 | // grade landing after this read still cannot leave a mark on a draft. |
| 185 | 185 | if draft && !current.is_draft() { |
| 186 | 186 | let sat = any_for_exam(db, current.get_id()).await?; |
| 187 | - let graded = !ExamResult::list_for_exam(current.get_id(), db) | |
| 187 | + let graded = !exam_result::list_for_exam(db, current.get_id()) | |
| 188 | 188 | .await? |
| 189 | 189 | .is_empty(); |
| 190 | 190 | if sat || graded { |
| @@ -271,8 +271,8 @@ pub async fn delete(db: &Database, target: &Exam) -> Result<DeleteOutcome, AppEr | ||
| 271 | 271 | let _guard = EXAM_LOCK.write().await; |
| 272 | 272 | // Rows go first (the delete cascades them), blobs after — a crash in |
| 273 | 273 | // between strands at worst an unreachable blob. |
| 274 | - let images = QuestionImage::list_for_exam(target.get_id(), db).await?; | |
| 275 | - let answer_images = AnswerImage::list_for_exam(target.get_id(), db).await?; | |
| 274 | + let images = question_image::list_for_exam(db, target.get_id()).await?; | |
| 275 | + let answer_images = answer_image::list_for_exam(db, target.get_id()).await?; | |
| 276 | 276 | exam::delete(db, target.clone()).await?; |
| 277 | 277 | Ok(DeleteOutcome { |
| 278 | 278 | image_files: images |
src/service/exam_answer.rsadded+71 -0
| @@ -0,0 +1,71 @@ | ||
| 1 | +//! The sitting answer sheet's workflows: the doors the web layer takes for | |
| 2 | +//! every answer read and write (the gate chain itself lives in | |
| 3 | +//! [`crate::service::exam_attempt`], which funnels every save through | |
| 4 | +//! [`save`]). The queries live in [`crate::db::exam_answer`]. | |
| 5 | + | |
| 6 | +use crate::database::Database; | |
| 7 | +use crate::db; | |
| 8 | +use crate::domain::exam::ExamId; | |
| 9 | +use crate::domain::exam_answer::ExamAnswer; | |
| 10 | +use crate::domain::exam_question::{ExamQuestion, ExamQuestionId}; | |
| 11 | +use crate::domain::user::UserId; | |
| 12 | +use crate::error::AppError; | |
| 13 | + | |
| 14 | +/// Save (or overwrite) one answer — the payload validation and the atomic | |
| 15 | +/// exam-row-touching upsert. The caller has already checked that the attempt | |
| 16 | +/// is in progress. | |
| 17 | +pub async fn save( | |
| 18 | + db: &Database, | |
| 19 | + question: &ExamQuestion, | |
| 20 | + user: &UserId, | |
| 21 | + seq: i64, | |
| 22 | + selected: Option<String>, | |
| 23 | + text: Option<String>, | |
| 24 | +) -> Result<ExamAnswer, AppError> { | |
| 25 | + db::exam_answer::save(db, question, user, seq, selected, text).await | |
| 26 | +} | |
| 27 | + | |
| 28 | +/// One student's stored answer for a question in sitting `seq`, if any. | |
| 29 | +pub async fn read( | |
| 30 | + db: &Database, | |
| 31 | + question: &ExamQuestionId, | |
| 32 | + user: &UserId, | |
| 33 | + seq: i64, | |
| 34 | +) -> Result<Option<ExamAnswer>, AppError> { | |
| 35 | + db::exam_answer::read(db, question, user, seq).await | |
| 36 | +} | |
| 37 | + | |
| 38 | +/// Drop one student's answer to a single question in sitting `seq`. | |
| 39 | +pub async fn delete( | |
| 40 | + db: &Database, | |
| 41 | + question: &ExamQuestionId, | |
| 42 | + user: &UserId, | |
| 43 | + seq: i64, | |
| 44 | +) -> Result<(), AppError> { | |
| 45 | + db::exam_answer::delete(db, question, user, seq).await | |
| 46 | +} | |
| 47 | + | |
| 48 | +/// One student's answers for a single sitting (`seq`) across an exam. | |
| 49 | +pub async fn list_for_exam_user( | |
| 50 | + db: &Database, | |
| 51 | + exam: &ExamId, | |
| 52 | + user: &UserId, | |
| 53 | + seq: i64, | |
| 54 | +) -> Result<Vec<ExamAnswer>, AppError> { | |
| 55 | + db::exam_answer::list_for_exam_user(db, exam, user, seq).await | |
| 56 | +} | |
| 57 | + | |
| 58 | +/// Every answer of an exam — the live monitor aggregates these per student. | |
| 59 | +pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<ExamAnswer>, AppError> { | |
| 60 | + db::exam_answer::list_for_exam(db, exam).await | |
| 61 | +} | |
| 62 | + | |
| 63 | +/// The distinct sittings a student has any answer for at `exam`, ascending | |
| 64 | +/// — the index a history view lists attempts from. | |
| 65 | +pub async fn list_seqs_for_user( | |
| 66 | + db: &Database, | |
| 67 | + exam: &ExamId, | |
| 68 | + user: &UserId, | |
| 69 | +) -> Result<Vec<i64>, AppError> { | |
| 70 | + db::exam_answer::list_seqs_for_user(db, exam, user).await | |
| 71 | +} |
src/service/exam_attempt.rsmodified+10 -10
| @@ -385,13 +385,13 @@ pub async fn save_answer_in( | ||
| 385 | 385 | crate::service::course::require_open(db, &course_of(exam, db).await?).await?; |
| 386 | 386 | let question = |
| 387 | 387 | crate::service::exam_question::question_of_exam(exam.get_id(), question_id, db).await?; |
| 388 | - crate::domain::exam_answer::ExamAnswer::save( | |
| 388 | + crate::db::exam_answer::save( | |
| 389 | + db, | |
| 389 | 390 | &question, |
| 390 | 391 | attempt.get_user(), |
| 391 | 392 | attempt.get_seq(), |
| 392 | 393 | selected, |
| 393 | 394 | text, |
| 394 | - db, | |
| 395 | 395 | ) |
| 396 | 396 | .await |
| 397 | 397 | } |
| @@ -465,10 +465,10 @@ pub async fn set_left( | ||
| 465 | 465 | mod tests { |
| 466 | 466 | use super::*; |
| 467 | 467 | use crate::database::init_mem; |
| 468 | + use crate::db::exam_answer; | |
| 468 | 469 | use crate::domain::exam::{ |
| 469 | 470 | ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, |
| 470 | 471 | }; |
| 471 | - use crate::domain::exam_answer::ExamAnswer; | |
| 472 | 472 | use crate::domain::exam_question::{ |
| 473 | 473 | ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, |
| 474 | 474 | }; |
| @@ -665,13 +665,13 @@ mod tests { | ||
| 665 | 665 | let (first, created) = start(&db, &exam, &user).await.unwrap(); |
| 666 | 666 | assert!(created); |
| 667 | 667 | assert_eq!(first.get_seq(), 1); |
| 668 | - ExamAnswer::save( | |
| 668 | + exam_answer::save( | |
| 669 | + &db, | |
| 669 | 670 | &question, |
| 670 | 671 | &user, |
| 671 | 672 | 1, |
| 672 | 673 | Some(second_choice(&question)), |
| 673 | 674 | None, |
| 674 | - &db, | |
| 675 | 675 | ) |
| 676 | 676 | .await |
| 677 | 677 | .unwrap(); |
| @@ -683,12 +683,12 @@ mod tests { | ||
| 683 | 683 | assert_eq!(second.get_seq(), 2); |
| 684 | 684 | |
| 685 | 685 | // Sitting #1's answer is still there, read at its own seq. |
| 686 | - let prior = ExamAnswer::read(question.get_id(), &user, 1, &db) | |
| 686 | + let prior = exam_answer::read(&db, question.get_id(), &user, 1) | |
| 687 | 687 | .await |
| 688 | 688 | .unwrap(); |
| 689 | 689 | assert!(prior.is_some(), "the retake must preserve seq 1's answer"); |
| 690 | 690 | // The new sitting starts blank at its own seq. |
| 691 | - let fresh = ExamAnswer::list_for_exam_user(exam.get_id(), &user, 2, &db) | |
| 691 | + let fresh = exam_answer::list_for_exam_user(&db, exam.get_id(), &user, 2) | |
| 692 | 692 | .await |
| 693 | 693 | .unwrap(); |
| 694 | 694 | assert!(fresh.is_empty(), "seq 2 starts blank"); |
| @@ -706,13 +706,13 @@ mod tests { | ||
| 706 | 706 | let (winner, created) = start(&db, &exam, &user).await.unwrap(); |
| 707 | 707 | assert!(created); |
| 708 | 708 | assert_eq!(winner.get_seq(), 2); |
| 709 | - ExamAnswer::save( | |
| 709 | + exam_answer::save( | |
| 710 | + &db, | |
| 710 | 711 | &question, |
| 711 | 712 | &user, |
| 712 | 713 | 2, |
| 713 | 714 | Some(second_choice(&question)), |
| 714 | 715 | None, |
| 715 | - &db, | |
| 716 | 716 | ) |
| 717 | 717 | .await |
| 718 | 718 | .unwrap(); |
| @@ -732,7 +732,7 @@ mod tests { | ||
| 732 | 732 | let lost: Result<Option<ExamAttempt>, surrealdb::Error> = |
| 733 | 733 | db.create(loser.id.record()).content(loser).await; |
| 734 | 734 | assert!(lost.is_err(), "the duplicate-seq create must be rejected"); |
| 735 | - let answers = ExamAnswer::list_for_exam_user(exam.get_id(), &user, 2, &db) | |
| 735 | + let answers = exam_answer::list_for_exam_user(&db, exam.get_id(), &user, 2) | |
| 736 | 736 | .await |
| 737 | 737 | .unwrap(); |
| 738 | 738 | assert_eq!( |
src/service/exam_result.rsadded+167 -0
| @@ -0,0 +1,167 @@ | ||
| 1 | +//! Exam-mark workflows: the grading gate chain under the exam subsystem's | |
| 2 | +//! reader lease, ungrading behind the archived-term gate, and the read doors | |
| 3 | +//! the web layer takes. The mark's own claim-riding transaction lives in | |
| 4 | +//! [`crate::db::exam_result`]. | |
| 5 | + | |
| 6 | +use crate::database::Database; | |
| 7 | +use crate::db; | |
| 8 | +use crate::domain::badge; | |
| 9 | +use crate::domain::course::CourseId; | |
| 10 | +use crate::domain::exam::{Exam, ExamId}; | |
| 11 | +use crate::domain::exam_result::{ExamResult, Mark}; | |
| 12 | +use crate::domain::role::Role; | |
| 13 | +use crate::domain::user::UserId; | |
| 14 | +use crate::error::{AppError, ValidationError}; | |
| 15 | +use crate::service::exam_attempt::{EXAM_LOCK, course_of, read_latest_for_user}; | |
| 16 | + | |
| 17 | +/// Grade a student's current sitting: every wall the handler used to run | |
| 18 | +/// (draft, retired kind, self-grade, target existence/role/enrollment), then | |
| 19 | +/// the mark's own transaction. | |
| 20 | +/// | |
| 21 | +/// *Reader* lease of [`EXAM_LOCK`] from the exam read through the result | |
| 22 | +/// write: the draft gate below must be judged against the same row the | |
| 23 | +/// mark lands under, or a concurrent re-draft (a writer, which checks for | |
| 24 | +/// results) could slip between them and leave a mark on a hidden exam. The | |
| 25 | +/// mark's transaction re-makes the draft check inside the store, so the | |
| 26 | +/// pre-flight here answers the same `409` one round trip earlier. | |
| 27 | +/// | |
| 28 | +/// The kind gate is the settings-list twin of the counter's retired bit: | |
| 29 | +/// `kind_ref`'s bit is what actually refuses the mark inside | |
| 30 | +/// [`db::exam_result::grade`], and it is a *different record* from the | |
| 31 | +/// list — a settings PATCH moves both, so anything that leaves them | |
| 32 | +/// disagreeing (a rolled-back retirement, a hand edit) would otherwise | |
| 33 | +/// reopen grading under a kind nobody lists, which is also a mark that | |
| 34 | +/// averages at weight 1 forever. Both gates, same answer; this one is a | |
| 35 | +/// read, the counter's is the one that survives a race. | |
| 36 | +/// | |
| 37 | +/// `mark` arrives raw because its range check is deliberately sequenced | |
| 38 | +/// *after* the draft and kind gates — validation order is observable. | |
| 39 | +/// | |
| 40 | +/// Both sides of the grade moved a counter — the grader's `marks_given`, | |
| 41 | +/// the student's `high_mark` — so both are brought up to date. A badge is a | |
| 42 | +/// decoration on top of the mark: losing one to a transient database error | |
| 43 | +/// must never fail the grading, and the next counter move heals it. | |
| 44 | +pub async fn grade( | |
| 45 | + db: &Database, | |
| 46 | + exam_id: &ExamId, | |
| 47 | + grader: &UserId, | |
| 48 | + target: &UserId, | |
| 49 | + mark: i64, | |
| 50 | +) -> Result<ExamResult, AppError> { | |
| 51 | + // Reader lease of [`EXAM_LOCK`] — see above. | |
| 52 | + let _guard = EXAM_LOCK.read().await; | |
| 53 | + // Exam must exist. | |
| 54 | + let exam = crate::service::exam::read(db, exam_id) | |
| 55 | + .await? | |
| 56 | + .ok_or(AppError::NotFound)?; | |
| 57 | + crate::service::course::require_open(db, &course_of(&exam, db).await?).await?; | |
| 58 | + // Pre-flight: `db::exam_result::grade` re-makes this check inside the | |
| 59 | + // mark's own transaction, so a re-draft landing after this read cannot | |
| 60 | + // leave a mark on a hidden exam. | |
| 61 | + if exam.is_draft() { | |
| 62 | + return Err(crate::domain::exam_result::draft_error()); | |
| 63 | + } | |
| 64 | + let kind = exam.get_kind().as_str(); | |
| 65 | + if !crate::service::settings::load(db) | |
| 66 | + .await? | |
| 67 | + .get_exam_kinds() | |
| 68 | + .iter() | |
| 69 | + .any(|offered| offered.get_name() == kind) | |
| 70 | + { | |
| 71 | + return Err(crate::domain::exam_result::retired_kind_error(kind)); | |
| 72 | + } | |
| 73 | + | |
| 74 | + let mark = Mark::try_new(mark)?; | |
| 75 | + | |
| 76 | + // Grading never targets oneself — no grader, whatever their role, may | |
| 77 | + // write their own mark. | |
| 78 | + if target == grader { | |
| 79 | + return Err(AppError::Forbidden("grading yourself is not allowed")); | |
| 80 | + } | |
| 81 | + | |
| 82 | + // Target user must exist. | |
| 83 | + let Some(target_user) = crate::service::user::read(db, target).await? else { | |
| 84 | + return Err(AppError::Validation(ValidationError::Invalid { | |
| 85 | + field: "user_id", | |
| 86 | + reason: "target user does not exist", | |
| 87 | + })); | |
| 88 | + }; | |
| 89 | + | |
| 90 | + // Only students carry marks — the grade system is theirs alone. A stale | |
| 91 | + // enrollment left behind by a promotion can't reopen grading for staff. | |
| 92 | + if target_user.get_role() != Role::Student { | |
| 93 | + return Err(AppError::Validation(ValidationError::Invalid { | |
| 94 | + field: "user_id", | |
| 95 | + reason: "only students can be graded", | |
| 96 | + })); | |
| 97 | + } | |
| 98 | + | |
| 99 | + // ... and be enrolled in the exam's course. | |
| 100 | + if crate::service::enrollment::read_for_user(db, exam.get_course(), target) | |
| 101 | + .await? | |
| 102 | + .is_none() | |
| 103 | + { | |
| 104 | + return Err(AppError::Validation(ValidationError::Invalid { | |
| 105 | + field: "user_id", | |
| 106 | + reason: "target user is not enrolled in this course", | |
| 107 | + })); | |
| 108 | + } | |
| 109 | + | |
| 110 | + // The mark lands on the student's current sitting; the latest seq is the | |
| 111 | + // grade-of-record. An offline-graded exam has no sitting — grade its base | |
| 112 | + // seq (1). | |
| 113 | + let seq = read_latest_for_user(db, exam_id, target) | |
| 114 | + .await? | |
| 115 | + .map_or(1, |a| a.get_seq()); | |
| 116 | + let result = db::exam_result::grade(db, exam_id, target, seq, mark, grader, kind).await?; | |
| 117 | + for person in [grader, target] { | |
| 118 | + if let Err(err) = badge::sync(person, db).await { | |
| 119 | + tracing::warn!("failed to sync badges for {}: {err}", person.key()); | |
| 120 | + } | |
| 121 | + } | |
| 122 | + Ok(result) | |
| 123 | +} | |
| 124 | + | |
| 125 | +/// Remove a student's results from an exam — every sitting's marks at once, | |
| 126 | +/// behind the archived-term gate. `NotFound` mapping stays with the caller. | |
| 127 | +pub async fn remove( | |
| 128 | + db: &Database, | |
| 129 | + exam: &Exam, | |
| 130 | + target: &UserId, | |
| 131 | +) -> Result<Option<ExamResult>, AppError> { | |
| 132 | + crate::service::course::require_open(db, &course_of(exam, db).await?).await?; | |
| 133 | + db::exam_result::remove(db, exam.get_id(), target, exam.get_kind().as_str()).await | |
| 134 | +} | |
| 135 | + | |
| 136 | +/// A single user's result for an exam, if graded. | |
| 137 | +pub async fn read_for_user( | |
| 138 | + db: &Database, | |
| 139 | + exam: &ExamId, | |
| 140 | + user: &UserId, | |
| 141 | +) -> Result<Option<ExamResult>, AppError> { | |
| 142 | + db::exam_result::read_for_user(db, exam, user).await | |
| 143 | +} | |
| 144 | + | |
| 145 | +/// An exam's graded results, deduped to the latest mark per (exam, user). | |
| 146 | +pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<ExamResult>, AppError> { | |
| 147 | + db::exam_result::list_for_exam(db, exam).await | |
| 148 | +} | |
| 149 | + | |
| 150 | +/// Every sitting's mark for one (exam, user) pair, oldest first. | |
| 151 | +pub async fn list_all_for_exam_user( | |
| 152 | + db: &Database, | |
| 153 | + exam: &ExamId, | |
| 154 | + user: &UserId, | |
| 155 | +) -> Result<Vec<ExamResult>, AppError> { | |
| 156 | + db::exam_result::list_all_for_exam_user(db, exam, user).await | |
| 157 | +} | |
| 158 | + | |
| 159 | +/// The user's graded results restricted to one course's exams — the raw | |
| 160 | +/// rows behind the per-course block of the marks report. | |
| 161 | +pub async fn list_for_user_in_course( | |
| 162 | + db: &Database, | |
| 163 | + course: &CourseId, | |
| 164 | + user: &UserId, | |
| 165 | +) -> Result<Vec<ExamResult>, AppError> { | |
| 166 | + db::exam_result::list_for_user_in_course(db, course, user).await | |
| 167 | +} |
src/service/mod.rsmodified+4 -0
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | //! Business rules, workflow locks, multi-call orchestration; calls db::*; no |
| 2 | 2 | //! SurrealQL text. |
| 3 | 3 | |
| 4 | +pub mod answer_image; | |
| 4 | 5 | pub mod appointment; |
| 5 | 6 | pub mod appointment_slot; |
| 6 | 7 | pub mod class_blueprint; |
| @@ -8,11 +9,14 @@ pub mod course; | ||
| 8 | 9 | pub mod course_session; |
| 9 | 10 | pub mod enrollment; |
| 10 | 11 | pub mod exam; |
| 12 | +pub mod exam_answer; | |
| 11 | 13 | pub mod exam_attempt; |
| 12 | 14 | pub mod exam_question; |
| 15 | +pub mod exam_result; | |
| 13 | 16 | pub mod meal_booking; |
| 14 | 17 | pub mod note; |
| 15 | 18 | pub mod payment_ledger; |
| 19 | +pub mod question_image; | |
| 16 | 20 | pub mod session; |
| 17 | 21 | pub mod settings; |
| 18 | 22 | pub mod user; |
src/service/question_image.rsadded+58 -0
| @@ -0,0 +1,58 @@ | ||
| 1 | +//! The question-image workflows: the doors the web layer takes for every | |
| 2 | +//! question/choice image read and write. The blob I/O and its disk ordering | |
| 3 | +//! stay in the web layer; the row transactions (behind the question-freeze | |
| 4 | +//! gate) live in [`crate::db::question_image`]. | |
| 5 | + | |
| 6 | +use crate::database::Database; | |
| 7 | +use crate::db; | |
| 8 | +use crate::domain::exam::ExamId; | |
| 9 | +use crate::domain::exam_question::{ChoiceId, ExamQuestionId}; | |
| 10 | +use crate::domain::question_image::QuestionImage; | |
| 11 | +use crate::error::AppError; | |
| 12 | + | |
| 13 | +/// Create or replace the slot's image row, handing back what it stored plus | |
| 14 | +/// the blob name it replaced, for the caller to take off disk. | |
| 15 | +pub async fn upsert( | |
| 16 | + db: &Database, | |
| 17 | + image: QuestionImage, | |
| 18 | +) -> Result<(QuestionImage, Option<String>), AppError> { | |
| 19 | + db::question_image::upsert(db, image).await | |
| 20 | +} | |
| 21 | + | |
| 22 | +/// The slot's image row, if any (`slot = None` is the question's | |
| 23 | +/// illustration). | |
| 24 | +pub async fn read_slot( | |
| 25 | + db: &Database, | |
| 26 | + question: &ExamQuestionId, | |
| 27 | + slot: Option<&ChoiceId>, | |
| 28 | +) -> Result<Option<QuestionImage>, AppError> { | |
| 29 | + db::question_image::read_slot(db, question, slot).await | |
| 30 | +} | |
| 31 | + | |
| 32 | +/// Every image of the exam's questions — one query for the list views. | |
| 33 | +pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<QuestionImage>, AppError> { | |
| 34 | + db::question_image::list_for_exam(db, exam).await | |
| 35 | +} | |
| 36 | + | |
| 37 | +/// Every image of one question — the illustration plus its option pictures. | |
| 38 | +pub async fn list_for_question( | |
| 39 | + db: &Database, | |
| 40 | + question: &ExamQuestionId, | |
| 41 | +) -> Result<Vec<QuestionImage>, AppError> { | |
| 42 | + db::question_image::list_for_question(db, question).await | |
| 43 | +} | |
| 44 | + | |
| 45 | +/// Drop the option pictures whose choice is gone, returning the removed rows | |
| 46 | +/// so the caller can take their blobs off disk. | |
| 47 | +pub async fn delete_choices_not_in( | |
| 48 | + db: &Database, | |
| 49 | + question: &ExamQuestionId, | |
| 50 | + keep: &[ChoiceId], | |
| 51 | +) -> Result<Vec<QuestionImage>, AppError> { | |
| 52 | + db::question_image::delete_choices_not_in(db, question, keep).await | |
| 53 | +} | |
| 54 | + | |
| 55 | +/// Drop one image row — the returned row names the blob to unlink. | |
| 56 | +pub async fn delete(db: &Database, image: QuestionImage) -> Result<QuestionImage, AppError> { | |
| 57 | + db::question_image::delete(db, image).await | |
| 58 | +} |
src/web/exam_ws.rsmodified+8 -5
| @@ -66,7 +66,6 @@ use serde_json::{Value, json}; | ||
| 66 | 66 | use crate::constant::{EXAM_WS_TICK_SECS, MAX_QUESTION_ID_LEN}; |
| 67 | 67 | use crate::database::Database; |
| 68 | 68 | use crate::domain::exam::{Exam, ExamId}; |
| 69 | -use crate::domain::exam_answer::ExamAnswer; | |
| 70 | 69 | use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId}; |
| 71 | 70 | use crate::domain::timestamp::Timestamp; |
| 72 | 71 | use crate::domain::user::UserId; |
| @@ -337,10 +336,14 @@ async fn state_frame( | ||
| 337 | 336 | let remaining_ms = (status == AttemptStatus::InProgress) |
| 338 | 337 | .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0))) |
| 339 | 338 | .flatten(); |
| 340 | - let answered = | |
| 341 | - ExamAnswer::list_for_exam_user(exam.get_id(), attempt.get_user(), attempt.get_seq(), db) | |
| 342 | - .await? | |
| 343 | - .len(); | |
| 339 | + let answered = crate::service::exam_answer::list_for_exam_user( | |
| 340 | + db, | |
| 341 | + exam.get_id(), | |
| 342 | + attempt.get_user(), | |
| 343 | + attempt.get_seq(), | |
| 344 | + ) | |
| 345 | + .await? | |
| 346 | + .len(); | |
| 344 | 347 | let question_count = crate::service::exam_question::list_for_exam(db, exam.get_id(), None, 0) |
| 345 | 348 | .await? |
| 346 | 349 | .0 |
src/web/exams/attempts.rsmodified+11 -10
| @@ -102,7 +102,7 @@ pub(crate) async fn attempt_progress( | ||
| 102 | 102 | seq: i64, |
| 103 | 103 | db: &Database, |
| 104 | 104 | ) -> Result<(u64, u64), AppError> { |
| 105 | - let answered = ExamAnswer::list_for_exam_user(exam, user, seq, db) | |
| 105 | + let answered = crate::service::exam_answer::list_for_exam_user(db, exam, user, seq) | |
| 106 | 106 | .await? |
| 107 | 107 | .len() as u64; |
| 108 | 108 | let question_count = crate::service::exam_question::list_for_exam(db, exam, None, 0) |
| @@ -142,7 +142,7 @@ pub(crate) async fn start_attempt( | ||
| 142 | 142 | ) -> Result<(StatusCode, Json<AttemptResponse>), AppError> { |
| 143 | 143 | let (exam, attempt, created) = |
| 144 | 144 | exam_attempt::start_attempt(&st.db, &ExamId::from_key(&id), &user).await?; |
| 145 | - let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) | |
| 145 | + let mark = crate::service::exam_result::read_for_user(&st.db, exam.get_id(), user.get_id()) | |
| 146 | 146 | .await? |
| 147 | 147 | .map(|r| r.get_mark()); |
| 148 | 148 | let (answered, question_count) = |
| @@ -195,7 +195,7 @@ pub(crate) async fn my_attempt( | ||
| 195 | 195 | let attempt = exam_attempt::read_latest_for_user(&st.db, exam.get_id(), user.get_id()) |
| 196 | 196 | .await? |
| 197 | 197 | .ok_or(AppError::NotFound)?; |
| 198 | - let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) | |
| 198 | + let mark = crate::service::exam_result::read_for_user(&st.db, exam.get_id(), user.get_id()) | |
| 199 | 199 | .await? |
| 200 | 200 | .map(|r| r.get_mark()); |
| 201 | 201 | let (answered, question_count) = |
| @@ -239,7 +239,7 @@ pub(crate) async fn finish_attempt( | ||
| 239 | 239 | .await? |
| 240 | 240 | .ok_or(AppError::NotFound)?; |
| 241 | 241 | let finished = exam_attempt::finish_attempt(&st.db, &exam, user.get_id()).await?; |
| 242 | - let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) | |
| 242 | + let mark = crate::service::exam_result::read_for_user(&st.db, exam.get_id(), user.get_id()) | |
| 243 | 243 | .await? |
| 244 | 244 | .map(|r| r.get_mark()); |
| 245 | 245 | let (answered, question_count) = |
| @@ -347,7 +347,7 @@ pub(crate) async fn live_snapshot( | ||
| 347 | 347 | } |
| 348 | 348 | } |
| 349 | 349 | } |
| 350 | - let marks: HashMap<String, i64> = ExamResult::list_for_exam(exam.get_id(), db) | |
| 350 | + let marks: HashMap<String, i64> = crate::service::exam_result::list_for_exam(db, exam.get_id()) | |
| 351 | 351 | .await? |
| 352 | 352 | .iter() |
| 353 | 353 | .map(|result| { |
| @@ -367,7 +367,7 @@ pub(crate) async fn live_snapshot( | ||
| 367 | 367 | // seq to their latest attempt — or a re-sitting student's count would |
| 368 | 368 | // double up their prior attempts. |
| 369 | 369 | let mut progress: HashMap<String, (u64, i64)> = HashMap::new(); |
| 370 | - for answer in ExamAnswer::list_for_exam(exam.get_id(), db).await? { | |
| 370 | + for answer in crate::service::exam_answer::list_for_exam(db, exam.get_id()).await? { | |
| 371 | 371 | let key = answer.get_user().key().to_string(); |
| 372 | 372 | if attempts.get(&key).map(ExamAttempt::get_seq) != Some(answer.get_seq()) { |
| 373 | 373 | continue; |
| @@ -588,13 +588,13 @@ pub(crate) async fn attempt_questions( | ||
| 588 | 588 | crate::service::exam_question::list_for_exam(&st.db, exam.get_id(), None, 0).await?; |
| 589 | 589 | let images = images_by_question(exam.get_id(), &st.db).await?; |
| 590 | 590 | let answers: HashMap<String, ExamAnswer> = |
| 591 | - ExamAnswer::list_for_exam_user(exam.get_id(), user.get_id(), seq, &st.db) | |
| 591 | + crate::service::exam_answer::list_for_exam_user(&st.db, exam.get_id(), user.get_id(), seq) | |
| 592 | 592 | .await? |
| 593 | 593 | .into_iter() |
| 594 | 594 | .map(|answer| (answer.get_question().key().to_string(), answer)) |
| 595 | 595 | .collect(); |
| 596 | 596 | let answer_images: HashMap<String, AnswerImage> = |
| 597 | - AnswerImage::list_for_exam_user(exam.get_id(), user.get_id(), seq, &st.db) | |
| 597 | + crate::service::answer_image::list_for_exam_user(&st.db, exam.get_id(), user.get_id(), seq) | |
| 598 | 598 | .await? |
| 599 | 599 | .into_iter() |
| 600 | 600 | .map(|image| (image.get_question().key().to_string(), image)) |
| @@ -748,9 +748,10 @@ pub(crate) async fn answer_sheet( | ||
| 748 | 748 | let (mut questions, _) = |
| 749 | 749 | crate::service::exam_question::list_for_exam(db, exam.get_id(), None, 0).await?; |
| 750 | 750 | questions.retain(|question| !hidden.contains(question.get_id().key())); |
| 751 | - let answers = ExamAnswer::list_for_exam_user(exam.get_id(), target, seq, db).await?; | |
| 751 | + let answers = | |
| 752 | + crate::service::exam_answer::list_for_exam_user(db, exam.get_id(), target, seq).await?; | |
| 752 | 753 | let answer_images: HashMap<String, AnswerImage> = |
| 753 | - AnswerImage::list_for_exam_user(exam.get_id(), target, seq, db) | |
| 754 | + crate::service::answer_image::list_for_exam_user(db, exam.get_id(), target, seq) | |
| 754 | 755 | .await? |
| 755 | 756 | .into_iter() |
| 756 | 757 | .map(|image| (image.get_question().key().to_string(), image)) |
src/web/exams/images.rsmodified+27 -18
| @@ -69,7 +69,7 @@ pub(crate) async fn images_by_question( | ||
| 69 | 69 | db: &Database, |
| 70 | 70 | ) -> Result<HashMap<String, Vec<QuestionImage>>, AppError> { |
| 71 | 71 | let mut buckets: HashMap<String, Vec<QuestionImage>> = HashMap::new(); |
| 72 | - for image in QuestionImage::list_for_exam(exam, db).await? { | |
| 72 | + for image in crate::service::question_image::list_for_exam(db, exam).await? { | |
| 73 | 73 | buckets |
| 74 | 74 | .entry(image.get_question().key().to_string()) |
| 75 | 75 | .or_default() |
| @@ -151,7 +151,10 @@ pub(crate) async fn store_image( | ||
| 151 | 151 | data.len() as i64, |
| 152 | 152 | ); |
| 153 | 153 | let file = image.get_file().to_string(); |
| 154 | - store_blob(st, &file, data, || async { image.upsert(&st.db).await }).await | |
| 154 | + store_blob(st, &file, data, || async { | |
| 155 | + crate::service::question_image::upsert(&st.db, image).await | |
| 156 | + }) | |
| 157 | + .await | |
| 155 | 158 | } |
| 156 | 159 | |
| 157 | 160 | /// The stored bytes, served inline via [`crate::web::serve_inline_blob`]. |
| @@ -237,7 +240,7 @@ pub(crate) async fn get_question_image( | ||
| 237 | 240 | .ok_or(AppError::NotFound)?; |
| 238 | 241 | ensure_question_content_visible(&st, &exam, &user).await?; |
| 239 | 242 | let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; |
| 240 | - let image = QuestionImage::read_slot(question.get_id(), None, &st.db) | |
| 243 | + let image = crate::service::question_image::read_slot(&st.db, question.get_id(), None) | |
| 241 | 244 | .await? |
| 242 | 245 | .ok_or(AppError::NotFound)?; |
| 243 | 246 | serve_image(&st, &image).await |
| @@ -270,10 +273,10 @@ pub(crate) async fn delete_question_image( | ||
| 270 | 273 | let exam = image_managed_exam(&st, &user, &id).await?; |
| 271 | 274 | ensure_questions_editable(exam.get_id(), &st.db).await?; |
| 272 | 275 | let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; |
| 273 | - let image = QuestionImage::read_slot(question.get_id(), None, &st.db) | |
| 276 | + let image = crate::service::question_image::read_slot(&st.db, question.get_id(), None) | |
| 274 | 277 | .await? |
| 275 | 278 | .ok_or(AppError::NotFound)?; |
| 276 | - let image = image.delete(&st.db).await?; | |
| 279 | + let image = crate::service::question_image::delete(&st.db, image).await?; | |
| 277 | 280 | remove_blob(&st.files_path, image.get_file()).await; |
| 278 | 281 | Ok(StatusCode::NO_CONTENT) |
| 279 | 282 | } |
| @@ -350,7 +353,7 @@ pub(crate) async fn get_choice_image( | ||
| 350 | 353 | ensure_question_content_visible(&st, &exam, &user).await?; |
| 351 | 354 | let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; |
| 352 | 355 | let slot = choice_slot(&question, &choice_id)?; |
| 353 | - let image = QuestionImage::read_slot(question.get_id(), Some(&slot), &st.db) | |
| 356 | + let image = crate::service::question_image::read_slot(&st.db, question.get_id(), Some(&slot)) | |
| 354 | 357 | .await? |
| 355 | 358 | .ok_or(AppError::NotFound)?; |
| 356 | 359 | serve_image(&st, &image).await |
| @@ -385,10 +388,10 @@ pub(crate) async fn delete_choice_image( | ||
| 385 | 388 | ensure_questions_editable(exam.get_id(), &st.db).await?; |
| 386 | 389 | let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; |
| 387 | 390 | let slot = choice_slot(&question, &choice_id)?; |
| 388 | - let image = QuestionImage::read_slot(question.get_id(), Some(&slot), &st.db) | |
| 391 | + let image = crate::service::question_image::read_slot(&st.db, question.get_id(), Some(&slot)) | |
| 389 | 392 | .await? |
| 390 | 393 | .ok_or(AppError::NotFound)?; |
| 391 | - let image = image.delete(&st.db).await?; | |
| 394 | + let image = crate::service::question_image::delete(&st.db, image).await?; | |
| 392 | 395 | remove_blob(&st.files_path, image.get_file()).await; |
| 393 | 396 | Ok(StatusCode::NO_CONTENT) |
| 394 | 397 | } |
| @@ -424,7 +427,10 @@ pub(crate) async fn store_answer_image( | ||
| 424 | 427 | data.len() as i64, |
| 425 | 428 | ); |
| 426 | 429 | let file = image.get_file().to_string(); |
| 427 | - store_blob(st, &file, data, || async { image.upsert(&st.db).await }).await | |
| 430 | + store_blob(st, &file, data, || async { | |
| 431 | + crate::service::answer_image::upsert(&st.db, image).await | |
| 432 | + }) | |
| 433 | + .await | |
| 428 | 434 | } |
| 429 | 435 | |
| 430 | 436 | /// Attach (or replace) the caller's drawn answer to a question inside their |
| @@ -498,17 +504,17 @@ pub(crate) async fn upload_answer_image( | ||
| 498 | 504 | // UI only offers drawing on text questions), so they are skipped. Removing |
| 499 | 505 | // the drawing later grooms this blank row away (see `delete_answer_image`). |
| 500 | 506 | if question.get_kind().as_str() != "choice" |
| 501 | - && ExamAnswer::read(question.get_id(), user.get_id(), seq, &st.db) | |
| 507 | + && crate::service::exam_answer::read(&st.db, question.get_id(), user.get_id(), seq) | |
| 502 | 508 | .await? |
| 503 | 509 | .is_none() |
| 504 | 510 | { |
| 505 | - ExamAnswer::save( | |
| 511 | + crate::service::exam_answer::save( | |
| 512 | + &st.db, | |
| 506 | 513 | &question, |
| 507 | 514 | user.get_id(), |
| 508 | 515 | seq, |
| 509 | 516 | None, |
| 510 | 517 | Some(String::new()), |
| 511 | - &st.db, | |
| 512 | 518 | ) |
| 513 | 519 | .await?; |
| 514 | 520 | } |
| @@ -554,19 +560,22 @@ pub(crate) async fn delete_answer_image( | ||
| 554 | 560 | check_rejoin(&exam, &attempt)?; |
| 555 | 561 | let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; |
| 556 | 562 | let seq = attempt.get_seq(); |
| 557 | - let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db) | |
| 563 | + let image = crate::service::answer_image::read(&st.db, question.get_id(), user.get_id(), seq) | |
| 558 | 564 | .await? |
| 559 | 565 | .ok_or(AppError::NotFound)?; |
| 560 | - let image = image.delete(&st.db).await?; | |
| 566 | + let image = crate::service::answer_image::delete(&st.db, image).await?; | |
| 561 | 567 | remove_blob(&st.files_path, image.get_file()).await; |
| 562 | 568 | // If the drawing was the whole answer (blank text, no choice — the row the |
| 563 | 569 | // upload created for a drawing-only answer), drop it too so it stops counting |
| 564 | 570 | // as answered. A typed answer keeps its row. |
| 565 | - if let Some(answer) = ExamAnswer::read(question.get_id(), user.get_id(), seq, &st.db).await? { | |
| 571 | + if let Some(answer) = | |
| 572 | + crate::service::exam_answer::read(&st.db, question.get_id(), user.get_id(), seq).await? | |
| 573 | + { | |
| 566 | 574 | let blank = answer.get_selected().is_none() |
| 567 | 575 | && answer.get_text().is_none_or(|t| t.as_str().is_empty()); |
| 568 | 576 | if blank { |
| 569 | - ExamAnswer::delete(question.get_id(), user.get_id(), seq, &st.db).await?; | |
| 577 | + crate::service::exam_answer::delete(&st.db, question.get_id(), user.get_id(), seq) | |
| 578 | + .await?; | |
| 570 | 579 | } |
| 571 | 580 | } |
| 572 | 581 | Ok(StatusCode::NO_CONTENT) |
| @@ -605,7 +614,7 @@ pub(crate) async fn get_answer_image( | ||
| 605 | 614 | .await? |
| 606 | 615 | .ok_or(AppError::NotFound)? |
| 607 | 616 | .get_seq(); |
| 608 | - let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db) | |
| 617 | + let image = crate::service::answer_image::read(&st.db, question.get_id(), user.get_id(), seq) | |
| 609 | 618 | .await? |
| 610 | 619 | .ok_or(AppError::NotFound)?; |
| 611 | 620 | 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( | ||
| 652 | 661 | .await? |
| 653 | 662 | .ok_or(AppError::NotFound)? |
| 654 | 663 | .get_seq(); |
| 655 | - let image = AnswerImage::read(question.get_id(), &target, seq, &st.db) | |
| 664 | + let image = crate::service::answer_image::read(&st.db, question.get_id(), &target, seq) | |
| 656 | 665 | .await? |
| 657 | 666 | .ok_or(AppError::NotFound)?; |
| 658 | 667 | crate::web::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await |
src/web/exams/mod.rsmodified+18 -103
| @@ -13,7 +13,6 @@ use utoipa_axum::routes; | ||
| 13 | 13 | use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; |
| 14 | 14 | use crate::database::Database; |
| 15 | 15 | use crate::domain::answer_image::AnswerImage; |
| 16 | -use crate::domain::badge; | |
| 17 | 16 | use crate::domain::bank_question::{BankQuestion, BankQuestionId}; |
| 18 | 17 | use crate::domain::bank_question_image::BankQuestionImage; |
| 19 | 18 | |
| @@ -32,7 +31,7 @@ use crate::domain::timestamp::Timestamp; | ||
| 32 | 31 | use crate::domain::user::{User, UserId}; |
| 33 | 32 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 34 | 33 | use crate::service; |
| 35 | -use crate::service::exam_attempt::{EXAM_LOCK, course_of, read_latest_for_user}; | |
| 34 | +use crate::service::exam_attempt::course_of; | |
| 36 | 35 | use crate::state::AppState; |
| 37 | 36 | |
| 38 | 37 | use super::bank_questions::BankQuestionResponse; |
| @@ -525,12 +524,7 @@ async fn grade( | ||
| 525 | 524 | Json(req): Json<GradeResult>, |
| 526 | 525 | ) -> Result<Json<ExamResultResponse>, AppError> { |
| 527 | 526 | let exam_id = ExamId::from_key(&id); |
| 528 | - // Reader lease of [`EXAM_LOCK`] from the exam read through the result | |
| 529 | - // write: the draft gate below must be judged against the same row the | |
| 530 | - // mark lands under, or a concurrent re-draft (a writer, which checks for | |
| 531 | - // results) could slip between them and leave a mark on a hidden exam. | |
| 532 | - let _guard = EXAM_LOCK.read().await; | |
| 533 | - // Exam must exist. | |
| 527 | + // Exam must exist, and only a course manager may grade it. | |
| 534 | 528 | let exam = service::exam::read(&st.db, &exam_id) |
| 535 | 529 | .await? |
| 536 | 530 | .ok_or(AppError::NotFound)?; |
| @@ -540,92 +534,18 @@ async fn grade( | ||
| 540 | 534 | "only the course creator, an assigned teacher, or a manager/admin can grade this exam", |
| 541 | 535 | )); |
| 542 | 536 | } |
| 543 | - crate::service::course::require_open(&st.db, &course).await?; | |
| 544 | - // Pre-flight: `ExamResult::grade` re-makes this check inside the mark's own | |
| 545 | - // transaction, so a re-draft landing after this read cannot leave a mark on | |
| 546 | - // a hidden exam. | |
| 547 | - if exam.is_draft() { | |
| 548 | - return Err(crate::domain::exam_result::draft_error()); | |
| 549 | - } | |
| 550 | - // The exam's kind must still be one the school offers. `kind_ref`'s retired | |
| 551 | - // bit is what actually refuses the mark inside `ExamResult::grade`, and it | |
| 552 | - // is a *different record* from the list — a settings PATCH moves both, so | |
| 553 | - // anything that leaves them disagreeing (a rolled-back retirement, a hand | |
| 554 | - // edit) would otherwise reopen grading under a kind nobody lists, which is | |
| 555 | - // also a mark that averages at weight 1 forever. Both gates, same answer; | |
| 556 | - // this one is a read, the counter's is the one that survives a race. | |
| 557 | - let kind = exam.get_kind().as_str(); | |
| 558 | - if !service::settings::load(&st.db) | |
| 559 | - .await? | |
| 560 | - .get_exam_kinds() | |
| 561 | - .iter() | |
| 562 | - .any(|offered| offered.get_name() == kind) | |
| 563 | - { | |
| 564 | - return Err(crate::domain::exam_result::retired_kind_error(kind)); | |
| 565 | - } | |
| 566 | - | |
| 567 | - let mark = Mark::try_new(req.mark)?; | |
| 568 | 537 | let target = UserId::from_key(&req.user_id); |
| 569 | - | |
| 570 | - // Grading never targets oneself — no grader, whatever their role, may | |
| 571 | - // write their own mark. | |
| 572 | - if &target == teacher.get_id() { | |
| 573 | - return Err(AppError::Forbidden("grading yourself is not allowed")); | |
| 574 | - } | |
| 575 | - | |
| 576 | - // Target user must exist. | |
| 577 | - let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { | |
| 578 | - return Err(AppError::Validation(ValidationError::Invalid { | |
| 579 | - field: "user_id", | |
| 580 | - reason: "target user does not exist", | |
| 581 | - })); | |
| 582 | - }; | |
| 583 | - | |
| 584 | - // Only students carry marks — the grade system is theirs alone. A stale | |
| 585 | - // enrollment left behind by a promotion can't reopen grading for staff. | |
| 586 | - if target_user.get_role() != Role::Student { | |
| 587 | - return Err(AppError::Validation(ValidationError::Invalid { | |
| 588 | - field: "user_id", | |
| 589 | - reason: "only students can be graded", | |
| 590 | - })); | |
| 591 | - } | |
| 592 | - | |
| 593 | - // ... and be enrolled in the exam's course. | |
| 594 | - if service::enrollment::read_for_user(&st.db, exam.get_course(), &target) | |
| 538 | + // The workflow — the *reader* lease of [`EXAM_LOCK`] from the exam read | |
| 539 | + // through the result write (so a concurrent re-draft cannot slip a mark | |
| 540 | + // onto a hidden exam), the draft and kind pre-flights, the | |
| 541 | + // grader/target walls, the sitting resolution, the mark's own | |
| 542 | + // transaction, and the badge sync — is | |
| 543 | + // [`crate::service::exam_result::grade`]'s. | |
| 544 | + let result = | |
| 545 | + service::exam_result::grade(&st.db, &exam_id, teacher.get_id(), &target, req.mark).await?; | |
| 546 | + let target_user = service::user::read(&st.db, &target) | |
| 595 | 547 | .await? |
| 596 | - .is_none() | |
| 597 | - { | |
| 598 | - return Err(AppError::Validation(ValidationError::Invalid { | |
| 599 | - field: "user_id", | |
| 600 | - reason: "target user is not enrolled in this course", | |
| 601 | - })); | |
| 602 | - } | |
| 603 | - | |
| 604 | - // The mark lands on the student's current sitting; the latest seq is the | |
| 605 | - // grade-of-record. An offline-graded exam has no sitting — grade its base | |
| 606 | - // seq (1). | |
| 607 | - let seq = read_latest_for_user(&st.db, &exam_id, &target) | |
| 608 | - .await? | |
| 609 | - .map_or(1, |a| a.get_seq()); | |
| 610 | - let result = ExamResult::grade( | |
| 611 | - &exam_id, | |
| 612 | - &target, | |
| 613 | - seq, | |
| 614 | - mark, | |
| 615 | - teacher.get_id(), | |
| 616 | - exam.get_kind().as_str(), | |
| 617 | - &st.db, | |
| 618 | - ) | |
| 619 | - .await?; | |
| 620 | - // Both sides of the grade moved a counter — the grader's `marks_given`, | |
| 621 | - // the student's `high_mark` — so both are brought up to date. A badge is a | |
| 622 | - // decoration on top of the mark: losing one to a transient database error | |
| 623 | - // must never fail the grading, and the next counter move heals it. | |
| 624 | - for person in [teacher.get_id(), &target] { | |
| 625 | - if let Err(err) = badge::sync(person, &st.db).await { | |
| 626 | - tracing::warn!("failed to sync badges for {}: {err}", person.key()); | |
| 627 | - } | |
| 628 | - } | |
| 548 | + .ok_or(AppError::NotFound)?; | |
| 629 | 549 | let people = PersonRef::map_of(&[&target_user, &teacher]); |
| 630 | 550 | Ok(Json(ExamResultResponse::new(&result, &people))) |
| 631 | 551 | } |
| @@ -665,7 +585,7 @@ async fn list_results( | ||
| 665 | 585 | "only the course creator, an assigned teacher, or a manager/admin can list results", |
| 666 | 586 | )); |
| 667 | 587 | } |
| 668 | - let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?; | |
| 588 | + let results = service::exam_result::list_for_exam(&st.db, exam.get_id()).await?; | |
| 669 | 589 | let total = results.len() as i64; |
| 670 | 590 | // Join people onto the page alone — the lookup shrinks with the window. |
| 671 | 591 | // Paged in the web layer: the list is deduped to the latest mark per |
| @@ -703,7 +623,7 @@ async fn my_result( | ||
| 703 | 623 | CurrentUser(user): CurrentUser, |
| 704 | 624 | Path(id): Path<String>, |
| 705 | 625 | ) -> Result<Json<ExamResultResponse>, AppError> { |
| 706 | - let result = ExamResult::read_for_user(&ExamId::from_key(&id), user.get_id(), &st.db) | |
| 626 | + let result = service::exam_result::read_for_user(&st.db, &ExamId::from_key(&id), user.get_id()) | |
| 707 | 627 | .await? |
| 708 | 628 | .ok_or(AppError::NotFound)?; |
| 709 | 629 | let people = person_map( |
| @@ -747,14 +667,9 @@ async fn remove_result( | ||
| 747 | 667 | "only the course creator, an assigned teacher, or a manager/admin can remove results", |
| 748 | 668 | )); |
| 749 | 669 | } |
| 750 | - crate::service::course::require_open(&st.db, &course).await?; | |
| 751 | - let removed = ExamResult::remove( | |
| 752 | - exam.get_id(), | |
| 753 | - &UserId::from_key(&target), | |
| 754 | - exam.get_kind().as_str(), | |
| 755 | - &st.db, | |
| 756 | - ) | |
| 757 | - .await?; | |
| 670 | + // The archived-term gate and the refunding delete are | |
| 671 | + // [`crate::service::exam_result::remove`]'s. | |
| 672 | + let removed = service::exam_result::remove(&st.db, &exam, &UserId::from_key(&target)).await?; | |
| 758 | 673 | if removed.is_none() { |
| 759 | 674 | return Err(AppError::NotFound); |
| 760 | 675 | } |
| @@ -791,7 +706,7 @@ async fn exam_statistics( | ||
| 791 | 706 | "only the course creator, an assigned teacher, or a manager/admin can view statistics", |
| 792 | 707 | )); |
| 793 | 708 | } |
| 794 | - let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?; | |
| 709 | + let results = service::exam_result::list_for_exam(&st.db, exam.get_id()).await?; | |
| 795 | 710 | |
| 796 | 711 | let marks: Vec<i64> = results.iter().map(|r| r.get_mark().as_i64()).collect(); |
| 797 | 712 | let average = |
src/web/exams/questions.rsmodified+17 -8
| @@ -359,10 +359,14 @@ pub(crate) async fn update_question( | ||
| 359 | 359 | .iter() |
| 360 | 360 | .map(|choice| choice.get_id().clone()) |
| 361 | 361 | .collect(); |
| 362 | - for image in QuestionImage::delete_choices_not_in(updated.get_id(), &keep, &st.db).await? { | |
| 362 | + for image in | |
| 363 | + crate::service::question_image::delete_choices_not_in(&st.db, updated.get_id(), &keep) | |
| 364 | + .await? | |
| 365 | + { | |
| 363 | 366 | remove_blob(&st.files_path, image.get_file()).await; |
| 364 | 367 | } |
| 365 | - let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?; | |
| 368 | + let images = | |
| 369 | + crate::service::question_image::list_for_question(&st.db, updated.get_id()).await?; | |
| 366 | 370 | Ok(Json(QuestionResponse::new(&updated, &images))) |
| 367 | 371 | } |
| 368 | 372 | |
| @@ -406,7 +410,8 @@ pub(crate) async fn delete_question( | ||
| 406 | 410 | let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; |
| 407 | 411 | // Rows go first (the delete cascades them), blobs after — a crash in |
| 408 | 412 | // between strands at worst an unreachable blob. |
| 409 | - let images = QuestionImage::list_for_question(question.get_id(), &st.db).await?; | |
| 413 | + let images = | |
| 414 | + crate::service::question_image::list_for_question(&st.db, question.get_id()).await?; | |
| 410 | 415 | exam_question::delete(&st.db, question).await?; |
| 411 | 416 | for image in &images { |
| 412 | 417 | remove_blob(&st.files_path, image.get_file()).await; |
| @@ -536,7 +541,8 @@ pub(crate) async fn question_from_bank( | ||
| 536 | 541 | } |
| 537 | 542 | } |
| 538 | 543 | } |
| 539 | - let images = QuestionImage::list_for_question(question.get_id(), &st.db).await?; | |
| 544 | + let images = | |
| 545 | + crate::service::question_image::list_for_question(&st.db, question.get_id()).await?; | |
| 540 | 546 | Ok(( |
| 541 | 547 | StatusCode::CREATED, |
| 542 | 548 | Json(QuestionResponse::new(&question, &images)), |
| @@ -662,12 +668,13 @@ pub(crate) async fn question_refresh_from_bank( | ||
| 662 | 668 | // `store_image` upserts per slot, so a slot both sides have is replaced. |
| 663 | 669 | let incoming_slots: Vec<Option<&ChoiceId>> = |
| 664 | 670 | incoming.iter().map(|(image, _)| image.get_slot()).collect(); |
| 665 | - for stale in QuestionImage::list_for_question(updated.get_id(), &st.db).await? { | |
| 671 | + for stale in crate::service::question_image::list_for_question(&st.db, updated.get_id()).await? | |
| 672 | + { | |
| 666 | 673 | if incoming_slots.contains(&stale.get_slot()) { |
| 667 | 674 | continue; |
| 668 | 675 | } |
| 669 | 676 | let file = stale.get_file().to_string(); |
| 670 | - stale.delete(&st.db).await?; | |
| 677 | + crate::service::question_image::delete(&st.db, stale).await?; | |
| 671 | 678 | remove_blob(&st.files_path, &file).await; |
| 672 | 679 | } |
| 673 | 680 | for (source, bytes) in &incoming { |
| @@ -682,7 +689,8 @@ pub(crate) async fn question_refresh_from_bank( | ||
| 682 | 689 | .await?; |
| 683 | 690 | } |
| 684 | 691 | |
| 685 | - let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?; | |
| 692 | + let images = | |
| 693 | + crate::service::question_image::list_for_question(&st.db, updated.get_id()).await?; | |
| 686 | 694 | Ok(Json(QuestionResponse::new(&updated, &images))) |
| 687 | 695 | } |
| 688 | 696 | |
| @@ -751,7 +759,8 @@ pub(crate) async fn question_to_bank( | ||
| 751 | 759 | // mid-loop failure rolls back the fresh bank row (cascade drops the copied |
| 752 | 760 | // image rows) and the blobs written so far; the source exam question stays |
| 753 | 761 | // untouched. |
| 754 | - let sources = QuestionImage::list_for_question(question.get_id(), &st.db).await?; | |
| 762 | + let sources = | |
| 763 | + crate::service::question_image::list_for_question(&st.db, question.get_id()).await?; | |
| 755 | 764 | let mut copied: Vec<String> = Vec::new(); |
| 756 | 765 | for source in &sources { |
| 757 | 766 | let step = async { |
src/web/exams/review.rsmodified+15 -8
| @@ -50,8 +50,11 @@ pub(crate) async fn student_attempts( | ||
| 50 | 50 | ) -> Result<Json<Vec<i64>>, AppError> { |
| 51 | 51 | let exam = gradable_exam(&st, &user, &id).await?; |
| 52 | 52 | let target = UserId::from_key(&target); |
| 53 | - let mut seqs = ExamAnswer::list_seqs_for_user(exam.get_id(), &target, &st.db).await?; | |
| 54 | - for result in ExamResult::list_all_for_exam_user(exam.get_id(), &target, &st.db).await? { | |
| 53 | + let mut seqs = | |
| 54 | + crate::service::exam_answer::list_seqs_for_user(&st.db, exam.get_id(), &target).await?; | |
| 55 | + for result in | |
| 56 | + crate::service::exam_result::list_all_for_exam_user(&st.db, exam.get_id(), &target).await? | |
| 57 | + { | |
| 55 | 58 | seqs.push(result.get_seq()); |
| 56 | 59 | } |
| 57 | 60 | seqs.sort_unstable(); |
| @@ -121,7 +124,7 @@ pub(crate) async fn student_attempt_answer_image( | ||
| 121 | 124 | let exam = gradable_exam(&st, &user, &id).await?; |
| 122 | 125 | let target = UserId::from_key(&target); |
| 123 | 126 | let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; |
| 124 | - let image = AnswerImage::read(question.get_id(), &target, seq, &st.db) | |
| 127 | + let image = crate::service::answer_image::read(&st.db, question.get_id(), &target, seq) | |
| 125 | 128 | .await? |
| 126 | 129 | .ok_or(AppError::NotFound)?; |
| 127 | 130 | 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( | ||
| 153 | 156 | ) -> Result<Json<Vec<ExamResultResponse>>, AppError> { |
| 154 | 157 | let exam = gradable_exam(&st, &user, &id).await?; |
| 155 | 158 | let target = UserId::from_key(&target); |
| 156 | - let results = ExamResult::list_all_for_exam_user(exam.get_id(), &target, &st.db).await?; | |
| 159 | + let results = | |
| 160 | + crate::service::exam_result::list_all_for_exam_user(&st.db, exam.get_id(), &target).await?; | |
| 157 | 161 | let people = person_map( |
| 158 | 162 | results |
| 159 | 163 | .iter() |
| @@ -208,7 +212,7 @@ pub(crate) async fn reviewable_exam( | ||
| 208 | 212 | if exam.is_draft() { |
| 209 | 213 | return Err(AppError::NotFound); |
| 210 | 214 | } |
| 211 | - ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) | |
| 215 | + crate::service::exam_result::read_for_user(&st.db, exam.get_id(), user.get_id()) | |
| 212 | 216 | .await? |
| 213 | 217 | .ok_or(AppError::NotFound)?; |
| 214 | 218 | if !exam.get_allow_review() { |
| @@ -302,8 +306,11 @@ pub(crate) async fn review_attempts( | ||
| 302 | 306 | ) -> Result<Json<Vec<i64>>, AppError> { |
| 303 | 307 | let exam = reviewable_exam(&st, &user, &id).await?; |
| 304 | 308 | let target = user.get_id().clone(); |
| 305 | - let mut seqs = ExamAnswer::list_seqs_for_user(exam.get_id(), &target, &st.db).await?; | |
| 306 | - for result in ExamResult::list_all_for_exam_user(exam.get_id(), &target, &st.db).await? { | |
| 309 | + let mut seqs = | |
| 310 | + crate::service::exam_answer::list_seqs_for_user(&st.db, exam.get_id(), &target).await?; | |
| 311 | + for result in | |
| 312 | + crate::service::exam_result::list_all_for_exam_user(&st.db, exam.get_id(), &target).await? | |
| 313 | + { | |
| 307 | 314 | seqs.push(result.get_seq()); |
| 308 | 315 | } |
| 309 | 316 | seqs.sort_unstable(); |
| @@ -417,7 +424,7 @@ pub(crate) async fn review_attempt_answer_image( | ||
| 417 | 424 | ) -> Result<Response, AppError> { |
| 418 | 425 | let exam = reviewable_exam(&st, &user, &id).await?; |
| 419 | 426 | let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; |
| 420 | - let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db) | |
| 427 | + let image = crate::service::answer_image::read(&st.db, question.get_id(), user.get_id(), seq) | |
| 421 | 428 | .await? |
| 422 | 429 | .ok_or(AppError::NotFound)?; |
| 423 | 430 | crate::web::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await |
src/web/marks.rsmodified+2 -2
| @@ -11,7 +11,6 @@ use utoipa_axum::routes; | ||
| 11 | 11 | use crate::database::Database; |
| 12 | 12 | |
| 13 | 13 | use crate::domain::exam::Exam; |
| 14 | -use crate::domain::exam_result::ExamResult; | |
| 15 | 14 | use crate::domain::role::Role; |
| 16 | 15 | use crate::domain::user::{User, UserId}; |
| 17 | 16 | use crate::error::{AppError, ErrorResponse}; |
| @@ -110,7 +109,8 @@ async fn build_report( | ||
| 110 | 109 | let exams = crate::service::exam::list_for_course(db, course.get_id()).await?; |
| 111 | 110 | let by_key: HashMap<&str, &Exam> = exams.iter().map(|e| (e.get_id().key(), e)).collect(); |
| 112 | 111 | |
| 113 | - let results = ExamResult::list_for_user_in_course(course.get_id(), user, db).await?; | |
| 112 | + let results = | |
| 113 | + crate::service::exam_result::list_for_user_in_course(db, course.get_id(), user).await?; | |
| 114 | 114 | let mut entries = Vec::with_capacity(results.len()); |
| 115 | 115 | let mut pairs = Vec::with_capacity(results.len()); |
| 116 | 116 | for result in &results { |
tests/integration.rsmodified+5 -5
| @@ -9631,8 +9631,8 @@ async fn live_monitor_tracks_answer_progress() { | ||
| 9631 | 9631 | |
| 9632 | 9632 | #[tokio::test] |
| 9633 | 9633 | async fn questions_and_answers_cascade_with_deletes() { |
| 9634 | + use hezarfen_backend::db::exam_answer; | |
| 9634 | 9635 | use hezarfen_backend::db::exam_question; |
| 9635 | - use hezarfen_backend::domain::exam_answer::ExamAnswer; | |
| 9636 | 9636 | |
| 9637 | 9637 | let (app, db) = app_and_db().await; |
| 9638 | 9638 | let teacher = login_as(&app, &db, "qc_t", "teacher").await; |
| @@ -9691,7 +9691,7 @@ async fn questions_and_answers_cascade_with_deletes() { | ||
| 9691 | 9691 | 2 |
| 9692 | 9692 | ); |
| 9693 | 9693 | assert_eq!( |
| 9694 | - ExamAnswer::list_for_exam(&exam_id, &db) | |
| 9694 | + exam_answer::list_for_exam(&db, &exam_id) | |
| 9695 | 9695 | .await |
| 9696 | 9696 | .unwrap() |
| 9697 | 9697 | .len(), |
| @@ -9736,7 +9736,7 @@ async fn questions_and_answers_cascade_with_deletes() { | ||
| 9736 | 9736 | 1 |
| 9737 | 9737 | ); |
| 9738 | 9738 | assert_eq!( |
| 9739 | - ExamAnswer::list_for_exam(&exam_id, &db) | |
| 9739 | + exam_answer::list_for_exam(&db, &exam_id) | |
| 9740 | 9740 | .await |
| 9741 | 9741 | .unwrap() |
| 9742 | 9742 | .len(), |
| @@ -9762,7 +9762,7 @@ async fn questions_and_answers_cascade_with_deletes() { | ||
| 9762 | 9762 | .is_empty() |
| 9763 | 9763 | ); |
| 9764 | 9764 | assert!( |
| 9765 | - ExamAnswer::list_for_exam(&exam_id, &db) | |
| 9765 | + exam_answer::list_for_exam(&db, &exam_id) | |
| 9766 | 9766 | .await |
| 9767 | 9767 | .unwrap() |
| 9768 | 9768 | .is_empty() |
| @@ -9826,7 +9826,7 @@ async fn questions_and_answers_cascade_with_deletes() { | ||
| 9826 | 9826 | .is_empty() |
| 9827 | 9827 | ); |
| 9828 | 9828 | assert!( |
| 9829 | - ExamAnswer::list_for_exam(&exam2_id, &db) | |
| 9829 | + exam_answer::list_for_exam(&db, &exam2_id) | |
| 9830 | 9830 | .await |
| 9831 | 9831 | .unwrap() |
| 9832 | 9832 | .is_empty() |