Merge branch 'layer-split/exam_question'
Browse files at this commit16 changed files +973 -866
- src/db/exam_attempt.rs +2 -2
- src/db/exam_question.rs +722 -0
- src/db/mod.rs +1 -0
- src/domain/bank_question.rs +4 -6
- src/domain/exam.rs +12 -10
- src/domain/exam_question.rs +19 -721
- src/domain/subject.rs +12 -10
- src/service/exam_attempt.rs +4 -20
- src/service/exam_question.rs +134 -0
- src/service/mod.rs +1 -0
- src/web/exam_ws.rs +3 -3
- src/web/exams/attempts.rs +6 -4
- src/web/exams/images.rs +2 -1
- src/web/exams/questions.rs +30 -65
- src/web/exams/review.rs +6 -7
- tests/integration.rs +15 -17
src/db/exam_attempt.rsmodified+2 -2
| @@ -349,13 +349,13 @@ mod tests { | |||
| 349 | ) | 349 | ) |
| 350 | .await | 350 | .await |
| 351 | .unwrap(); | 351 | .unwrap(); |
| 352 | - let question = ExamQuestion::create( | 352 | + let question = crate::db::exam_question::create( |
| 353 | + db, | ||
| 353 | exam.get_id(), | 354 | exam.get_id(), |
| 354 | subject.get_id().clone(), | 355 | subject.get_id().clone(), |
| 355 | crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(), | 356 | crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(), |
| 356 | QuestionPoints::try_new(5).unwrap(), | 357 | QuestionPoints::try_new(5).unwrap(), |
| 357 | spec, | 358 | spec, |
| 358 | - db, | ||
| 359 | ) | 359 | ) |
| 360 | .await | 360 | .await |
| 361 | .unwrap(); | 361 | .unwrap(); |
src/db/exam_question.rsadded+722 -0
| @@ -0,0 +1,722 @@ | |||
| 1 | +//! The `exam_question` table: row reads and listings, the answer-key join | ||
| 2 | +//! behind review hiding, and the field-scoped writes that tie the freeze gate | ||
| 3 | +//! and the subject's reference counter into their own transaction. The | ||
| 4 | +//! workflows and the freeze pre-flight live in | ||
| 5 | +//! [`crate::service::exam_question`]. | ||
| 6 | + | ||
| 7 | +use std::collections::HashSet; | ||
| 8 | + | ||
| 9 | +use surrealdb::types::{RecordId, SurrealValue}; | ||
| 10 | + | ||
| 11 | +use crate::constant::SUBJECT_QUESTION_COUNT_FIELD; | ||
| 12 | +use crate::database::Database; | ||
| 13 | +use crate::db::cap; | ||
| 14 | +use crate::db::page::PagedList; | ||
| 15 | +use crate::domain::bank_question::BankQuestionId; | ||
| 16 | +use crate::domain::exam::ExamId; | ||
| 17 | +use crate::domain::exam_question::{ | ||
| 18 | + ExamQuestion, ExamQuestionId, QuestionPoints, QuestionSpec, QuestionText, | ||
| 19 | +}; | ||
| 20 | +use crate::domain::subject::SubjectId; | ||
| 21 | +use crate::error::{AppError, ValidationError}; | ||
| 22 | + | ||
| 23 | +/// The `THROW` markers the folded counter moves abort with: the subject the | ||
| 24 | +/// reference was to be claimed on is gone, the question being patched is gone, | ||
| 25 | +/// and the subject this move started from is no longer the one the handler | ||
| 26 | +/// read. File-local like every other marker set (`cap`'s, `subject`'s). | ||
| 27 | +const SUBJECT_MARK: &str = "question_subject_gone"; | ||
| 28 | +const ROW_MARK: &str = "question_row_gone"; | ||
| 29 | +const STALE_MARK: &str = "question_stale_move"; | ||
| 30 | + | ||
| 31 | +/// The one answer for a subject that isn't there — a claim missing it and the | ||
| 32 | +/// web layer's pre-flight lookup missing it are the same 400. | ||
| 33 | +fn dead_subject() -> AppError { | ||
| 34 | + AppError::Validation(ValidationError::Invalid { | ||
| 35 | + field: "subject_id", | ||
| 36 | + reason: "subject does not exist", | ||
| 37 | + }) | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +pub async fn create( | ||
| 41 | + db: &Database, | ||
| 42 | + exam: &ExamId, | ||
| 43 | + subject: SubjectId, | ||
| 44 | + text: QuestionText, | ||
| 45 | + points: QuestionPoints, | ||
| 46 | + spec: QuestionSpec, | ||
| 47 | +) -> Result<ExamQuestion, AppError> { | ||
| 48 | + insert(db, exam, subject, text, points, spec, None).await | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +/// Like [`create`], but records the bank template this question was | ||
| 52 | +/// instantiated from (`POST …/questions/from-bank/{bid}`). | ||
| 53 | +pub async fn create_from_bank( | ||
| 54 | + db: &Database, | ||
| 55 | + exam: &ExamId, | ||
| 56 | + subject: SubjectId, | ||
| 57 | + text: QuestionText, | ||
| 58 | + points: QuestionPoints, | ||
| 59 | + spec: QuestionSpec, | ||
| 60 | + source: BankQuestionId, | ||
| 61 | +) -> Result<ExamQuestion, AppError> { | ||
| 62 | + insert(db, exam, subject, text, points, spec, Some(source)).await | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +#[allow(clippy::too_many_arguments)] | ||
| 66 | +async fn insert( | ||
| 67 | + db: &Database, | ||
| 68 | + exam: &ExamId, | ||
| 69 | + subject: SubjectId, | ||
| 70 | + text: QuestionText, | ||
| 71 | + points: QuestionPoints, | ||
| 72 | + spec: QuestionSpec, | ||
| 73 | + from_bank: Option<BankQuestionId>, | ||
| 74 | +) -> Result<ExamQuestion, AppError> { | ||
| 75 | + let counted = subject.record(); | ||
| 76 | + let question = ExamQuestion { | ||
| 77 | + id: ExamQuestionId::generate(), | ||
| 78 | + exam: exam.clone(), | ||
| 79 | + subject, | ||
| 80 | + text, | ||
| 81 | + points, | ||
| 82 | + kind: spec.kind, | ||
| 83 | + choices: spec.choices, | ||
| 84 | + correct: spec.correct, | ||
| 85 | + from_bank, | ||
| 86 | + // An insert never banks anything: only a to-bank save writes this. | ||
| 87 | + banked_as: None, | ||
| 88 | + }; | ||
| 89 | + // The freeze gate and the subject's reference ride in the same | ||
| 90 | + // transaction as the insert: a question cannot appear under an exam | ||
| 91 | + // somebody has already started, and the claim that accounts for it | ||
| 92 | + // cannot outlive a row that never landed. Claiming in its own query | ||
| 93 | + // (with a release on failure, as this did) leaves a window where a | ||
| 94 | + // crash strands the count — and the subject delete is conditioned on | ||
| 95 | + // that count reading zero, so a stranded one makes the subject | ||
| 96 | + // undeletable forever. A missed claim means the subject is already gone | ||
| 97 | + // — the same 400 the web layer's pre-flight check answers with. | ||
| 98 | + // | ||
| 99 | + // Re-sendable despite the `CREATE`: a lost round aborts having written | ||
| 100 | + // nothing and `$id` is a ULID minted once per call, so the re-send | ||
| 101 | + // cannot answer "already exists" (there is no UNIQUE index on | ||
| 102 | + // `exam_question`) — the one thing the retry cannot survive. | ||
| 103 | + let id = question.id.record(); | ||
| 104 | + // One counter write in flight at a time, like every other counter write. | ||
| 105 | + let _guard = cap::counter_lock().await; | ||
| 106 | + let mut result = crate::db::exam_attempt::write_unfrozen_with( | ||
| 107 | + db, | ||
| 108 | + exam, | ||
| 109 | + &format!( | ||
| 110 | + "LET $seat = (UPDATE $subject SET {SUBJECT_QUESTION_COUNT_FIELD} = \ | ||
| 111 | + ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); | ||
| 112 | + IF array::len($seat) = 0 {{ THROW '{SUBJECT_MARK}' }}; | ||
| 113 | + CREATE $id CONTENT $question;" | ||
| 114 | + ), | ||
| 115 | + vec![ | ||
| 116 | + ("subject".into(), counted.into_value()), | ||
| 117 | + ("id".into(), id.into_value()), | ||
| 118 | + ("question".into(), question.into_value()), | ||
| 119 | + ], | ||
| 120 | + vec![(SUBJECT_MARK, dead_subject())], | ||
| 121 | + ) | ||
| 122 | + .await?; | ||
| 123 | + // Counted off the statements that actually ran rather than a fixed | ||
| 124 | + // slot, so folding another gate in above can never mis-read the row. | ||
| 125 | + let slot = result.num_statements().saturating_sub(2); | ||
| 126 | + result | ||
| 127 | + .take::<Vec<ExamQuestion>>(slot)? | ||
| 128 | + .into_iter() | ||
| 129 | + .next() | ||
| 130 | + .ok_or_else(|| AppError::Internal("failed to create exam question".into())) | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +pub async fn read(db: &Database, id: &ExamQuestionId) -> Result<Option<ExamQuestion>, AppError> { | ||
| 134 | + Ok(db.select(id.record()).await?) | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +/// The exam's questions in presentation order (ULID ids sort by creation). | ||
| 138 | +pub async fn list_for_exam( | ||
| 139 | + db: &Database, | ||
| 140 | + exam: &ExamId, | ||
| 141 | + limit: Option<i64>, | ||
| 142 | + offset: i64, | ||
| 143 | +) -> Result<(Vec<ExamQuestion>, i64), AppError> { | ||
| 144 | + PagedList::new("exam_question WHERE exam = $ex", "ORDER BY id ASC") | ||
| 145 | + .bind("ex", exam.record()) | ||
| 146 | + .run(limit, offset, db) | ||
| 147 | + .await | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +/// The ids of `exam`'s questions that share a bank template with a question | ||
| 151 | +/// under one of `live` — the questions two exams hold identical `correct` | ||
| 152 | +/// for, because the bank copies the key into every instantiation. Keyed on | ||
| 153 | +/// the template, never on the exam, so only the overlapping questions are | ||
| 154 | +/// named. Empty when `live` is empty. | ||
| 155 | +/// | ||
| 156 | +/// A question links to a template through *either* column and both must be | ||
| 157 | +/// read, on both sides of the join: `from_bank` is the template it was | ||
| 158 | +/// instantiated from, `banked_as` the template minted by saving it into the | ||
| 159 | +/// bank ([`link_banked_as`]). A question authored by hand in exam A | ||
| 160 | +/// and then saved to the bank holds only `banked_as`, while its copy in | ||
| 161 | +/// exam B holds only `from_bank` — matching `from_bank` to `from_bank` saw | ||
| 162 | +/// neither and leaked A's key while B was live. A single coalesced key per | ||
| 163 | +/// row is not enough either: a question instantiated from one template and | ||
| 164 | +/// re-saved as another carries *both*, and only the second one may be the | ||
| 165 | +/// shared link. | ||
| 166 | +/// | ||
| 167 | +/// So: collect every template id reachable from a live exam by either | ||
| 168 | +/// column, then name any of `exam`'s questions pointing at one by either | ||
| 169 | +/// column. `$shared` is built from `!= NONE` filters, so it never holds a | ||
| 170 | +/// `NONE` for an unlinked question's absent column to match against. | ||
| 171 | +pub async fn list_shared_with( | ||
| 172 | + db: &Database, | ||
| 173 | + exam: &ExamId, | ||
| 174 | + live: &[ExamId], | ||
| 175 | +) -> Result<HashSet<String>, AppError> { | ||
| 176 | + if live.is_empty() { | ||
| 177 | + return Ok(HashSet::new()); | ||
| 178 | + } | ||
| 179 | + let mut result = db | ||
| 180 | + .query( | ||
| 181 | + "LET $shared = array::union( | ||
| 182 | + (SELECT VALUE from_bank FROM exam_question | ||
| 183 | + WHERE exam IN $live AND from_bank != NONE), | ||
| 184 | + (SELECT VALUE banked_as FROM exam_question | ||
| 185 | + WHERE exam IN $live AND banked_as != NONE)); | ||
| 186 | + SELECT VALUE id FROM exam_question | ||
| 187 | + WHERE exam = $ex AND (from_bank IN $shared OR banked_as IN $shared)", | ||
| 188 | + ) | ||
| 189 | + .bind(("ex", exam.record())) | ||
| 190 | + .bind(( | ||
| 191 | + "live", | ||
| 192 | + live.iter().map(ExamId::record).collect::<Vec<RecordId>>(), | ||
| 193 | + )) | ||
| 194 | + .await? | ||
| 195 | + .check()?; | ||
| 196 | + Ok(result | ||
| 197 | + .take::<Vec<ExamQuestionId>>(1)? | ||
| 198 | + .iter() | ||
| 199 | + .map(|id| id.key().to_string()) | ||
| 200 | + .collect()) | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +/// Write the editable fields, refused outright once the exam has an | ||
| 204 | +/// attempt — the freeze gate is part of this transaction, not a check the | ||
| 205 | +/// caller made a moment earlier under a lock. | ||
| 206 | +/// | ||
| 207 | +/// Field-scoped, no longer a whole-row save. The row also carries | ||
| 208 | +/// `from_bank`/`banked_as`, which [`link_banked_as`] writes from a | ||
| 209 | +/// *different* request: re-stating this snapshot's copy of them would | ||
| 210 | +/// revert a to-bank save that landed in between. That is exactly what the | ||
| 211 | +/// caller's `EXAM_LOCK.write()` used to order (inside one process), and | ||
| 212 | +/// naming the columns removes the need for any ordering at all. | ||
| 213 | +pub async fn update( | ||
| 214 | + db: &Database, | ||
| 215 | + question: ExamQuestion, | ||
| 216 | + subject: SubjectId, | ||
| 217 | + text: QuestionText, | ||
| 218 | + points: QuestionPoints, | ||
| 219 | + spec: QuestionSpec, | ||
| 220 | +) -> Result<ExamQuestion, AppError> { | ||
| 221 | + // A re-tag moves a reference, and the move rides the very transaction | ||
| 222 | + // that moves the link: the old subject's release, the new one's claim | ||
| 223 | + // and the row write commit together or not at all, so no crash can | ||
| 224 | + // strand a count on a subject nothing points at (which would make it | ||
| 225 | + // undeletable forever). | ||
| 226 | + // | ||
| 227 | + // The two are armed on *different* conditions, which is the whole of | ||
| 228 | + // the rule ([`crate::db::field_update::FieldUpdate::refcount`] states | ||
| 229 | + // it the same way): the counter statements only when the link actually | ||
| 230 | + // changes, but the CAS whenever this write *carries* the link — and it | ||
| 231 | + // always does, because the handler fills an omitted `subject_id` from | ||
| 232 | + // the row it read (`web::exams::questions`), so `subject` is in the | ||
| 233 | + // `SET` of every one of these updates. Arming the CAS on "changed" | ||
| 234 | + // instead would leave the re-stater through: a PATCH carrying the | ||
| 235 | + // subject its own stale snapshot held, sent while a rival's move | ||
| 236 | + // already landed, writes that stale subject straight back over the | ||
| 237 | + // winner — a revert with the counters left pointing at the move. | ||
| 238 | + let retag = | ||
| 239 | + (subject != question.subject).then(|| (subject.record(), question.subject.record())); | ||
| 240 | + let write = "UPDATE $id SET subject = $subject, text = $text, points = $points, | ||
| 241 | + kind = $kind, choices = $choices, correct = $correct"; | ||
| 242 | + let mut bindings = vec![ | ||
| 243 | + ("id".into(), question.id.record().into_value()), | ||
| 244 | + ("subject".into(), subject.record().into_value()), | ||
| 245 | + ("text".into(), text.into_value()), | ||
| 246 | + ("points".into(), points.into_value()), | ||
| 247 | + ("kind".into(), spec.kind.into_value()), | ||
| 248 | + ("choices".into(), spec.choices.into_value()), | ||
| 249 | + ("correct".into(), spec.correct.into_value()), | ||
| 250 | + ]; | ||
| 251 | + let mut statements: Vec<String> = Vec::new(); | ||
| 252 | + let mut refusals: Vec<(&str, AppError)> = Vec::new(); | ||
| 253 | + if let Some((next, previous)) = &retag { | ||
| 254 | + statements.push(format!( | ||
| 255 | + "UPDATE $ref_release SET {SUBJECT_QUESTION_COUNT_FIELD} = \ | ||
| 256 | + math::max([({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) - 1, 0])" | ||
| 257 | + )); | ||
| 258 | + statements.push(format!( | ||
| 259 | + "LET $seat = (UPDATE $ref_claim SET {SUBJECT_QUESTION_COUNT_FIELD} = \ | ||
| 260 | + ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id)" | ||
| 261 | + )); | ||
| 262 | + statements.push(format!( | ||
| 263 | + "IF array::len($seat) = 0 {{ THROW '{SUBJECT_MARK}' }}" | ||
| 264 | + )); | ||
| 265 | + bindings.push(("ref_claim".into(), next.clone().into_value())); | ||
| 266 | + bindings.push(("ref_release".into(), previous.clone().into_value())); | ||
| 267 | + refusals.push((SUBJECT_MARK, dead_subject())); | ||
| 268 | + } | ||
| 269 | + // The CAS: the row write matches only while the question still sits on | ||
| 270 | + // the subject this handler read. A genuine no-op re-state passes it | ||
| 271 | + // trivially (the row holds exactly what is expected); a stale one — | ||
| 272 | + // whether it moves the link or restates it — matches nothing, aborts | ||
| 273 | + // the whole transaction, and so claims nothing and answers 409. | ||
| 274 | + bindings.push(( | ||
| 275 | + "ref_expected".into(), | ||
| 276 | + question.subject.record().into_value(), | ||
| 277 | + )); | ||
| 278 | + statements.push(format!( | ||
| 279 | + "LET $row = ({write} WHERE subject = $ref_expected RETURN AFTER)" | ||
| 280 | + )); | ||
| 281 | + statements.push(format!( | ||
| 282 | + "IF array::len($row) = 0 {{ \ | ||
| 283 | + LET $live = (UPDATE $id WHERE subject != $ref_expected RETURN VALUE id); \ | ||
| 284 | + IF array::len($live) = 0 {{ THROW '{ROW_MARK}' }} \ | ||
| 285 | + ELSE {{ THROW '{STALE_MARK}' }} }}" | ||
| 286 | + )); | ||
| 287 | + statements.push("RETURN $row".into()); | ||
| 288 | + refusals.push(( | ||
| 289 | + STALE_MARK, | ||
| 290 | + AppError::Conflict( | ||
| 291 | + "the subject this question was read on changed since; re-read and retry", | ||
| 292 | + ), | ||
| 293 | + )); | ||
| 294 | + // The row is gone: the same 404 an empty write answers with, so the | ||
| 295 | + // deleted-row case is unchanged. | ||
| 296 | + refusals.push((ROW_MARK, AppError::NotFound)); | ||
| 297 | + let statements = format!("{};", statements.join("; ")); | ||
| 298 | + // One counter write in flight at a time — only a move writes one. | ||
| 299 | + let _guard = match &retag { | ||
| 300 | + Some(_) => Some(cap::counter_lock().await), | ||
| 301 | + None => None, | ||
| 302 | + }; | ||
| 303 | + let mut result = crate::db::exam_attempt::write_unfrozen_with( | ||
| 304 | + db, | ||
| 305 | + &question.exam, | ||
| 306 | + &statements, | ||
| 307 | + bindings, | ||
| 308 | + refusals, | ||
| 309 | + ) | ||
| 310 | + .await?; | ||
| 311 | + // Read off the trailing `RETURN` rather than a fixed slot: a re-tag | ||
| 312 | + // arms three more statements than a plain PATCH does (and an `IF` | ||
| 313 | + // block is one slot whether or not it is taken). | ||
| 314 | + let slot = result.num_statements().saturating_sub(2); | ||
| 315 | + result | ||
| 316 | + .take::<Vec<ExamQuestion>>(slot)? | ||
| 317 | + .into_iter() | ||
| 318 | + .next() | ||
| 319 | + .ok_or(AppError::NotFound) | ||
| 320 | +} | ||
| 321 | + | ||
| 322 | +/// Point the question's `banked_as` at the bank template it was just saved | ||
| 323 | +/// into (`POST …/questions/{qid}/to-bank`). The mirror direction of the | ||
| 324 | +/// `from_bank` [`create_from_bank`] writes, and deliberately a | ||
| 325 | +/// *different* column: a question inserted from the bank has not been saved | ||
| 326 | +/// to it, and one field for both would make the client claim it was. | ||
| 327 | +/// Overwrites any earlier link: repeat saves mint a new template and the | ||
| 328 | +/// newest one wins. | ||
| 329 | +/// | ||
| 330 | +/// Field-scoped write, unlike [`update`]: the caller awaits a bank | ||
| 331 | +/// insert plus the whole blob-copy loop between reading this row and | ||
| 332 | +/// linking it, so the row it holds is long stale by now — a whole-row save | ||
| 333 | +/// would silently revert whatever landed in that window. (The caller takes | ||
| 334 | +/// `EXAM_LOCK.read()` around this call, which is what keeps | ||
| 335 | +/// [`update`]'s whole-row save from clobbering the link in the other | ||
| 336 | +/// direction; the lease guards the ordering, not the staleness.) | ||
| 337 | +pub async fn link_banked_as( | ||
| 338 | + db: &Database, | ||
| 339 | + question: ExamQuestion, | ||
| 340 | + template: BankQuestionId, | ||
| 341 | +) -> Result<ExamQuestion, AppError> { | ||
| 342 | + let mut result = db | ||
| 343 | + .query("UPDATE $id SET banked_as = $bank RETURN AFTER") | ||
| 344 | + .bind(("id", question.id.record())) | ||
| 345 | + .bind(("bank", template.record())) | ||
| 346 | + .await? | ||
| 347 | + .check()?; | ||
| 348 | + result | ||
| 349 | + .take::<Vec<ExamQuestion>>(0)? | ||
| 350 | + .into_iter() | ||
| 351 | + .next() | ||
| 352 | + .ok_or(AppError::NotFound) | ||
| 353 | +} | ||
| 354 | + | ||
| 355 | +/// Delete the question and cascade-remove its answers and image rows, so | ||
| 356 | +/// neither can point at a missing question. The image *blobs* are the web | ||
| 357 | +/// layer's to remove — it collects their names before calling this. | ||
| 358 | +/// Refused once the exam has an attempt, in the same transaction as the | ||
| 359 | +/// delete — and the cascade now shares that transaction too, so a failure | ||
| 360 | +/// mid-way can no longer strand answers whose question survived. | ||
| 361 | +pub async fn delete(db: &Database, question: ExamQuestion) -> Result<ExamQuestion, AppError> { | ||
| 362 | + let mut result = crate::db::exam_attempt::write_unfrozen( | ||
| 363 | + db, | ||
| 364 | + &question.exam, | ||
| 365 | + &format!( | ||
| 366 | + "DELETE exam_answer WHERE question = $q; | ||
| 367 | + DELETE question_image WHERE question = $q; | ||
| 368 | + LET $gone = (DELETE $q RETURN BEFORE); | ||
| 369 | + FOR $sub IN ($gone.subject ?? []) {{ | ||
| 370 | + UPDATE $sub SET {SUBJECT_QUESTION_COUNT_FIELD} = | ||
| 371 | + math::max([({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) - 1, 0]) | ||
| 372 | + }}; | ||
| 373 | + RETURN $gone;" | ||
| 374 | + ), | ||
| 375 | + vec![("q".into(), question.id.record().into_value())], | ||
| 376 | + ) | ||
| 377 | + .await?; | ||
| 378 | + // The subject's reference is given back inside this same transaction, | ||
| 379 | + // driven off what the delete actually removed — a question that wasn't | ||
| 380 | + // there decrements nothing. Read through the trailing `RETURN` rather | ||
| 381 | + // than a hand-counted slot, so inserting a cascade statement above can | ||
| 382 | + // never turn a delete into a 404 (see [`crate::domain::exam::Exam`]). | ||
| 383 | + let slot = result.num_statements().saturating_sub(2); | ||
| 384 | + result | ||
| 385 | + .take::<Vec<ExamQuestion>>(slot)? | ||
| 386 | + .into_iter() | ||
| 387 | + .next() | ||
| 388 | + .ok_or(AppError::NotFound) | ||
| 389 | +} | ||
| 390 | + | ||
| 391 | +#[cfg(test)] | ||
| 392 | +mod tests { | ||
| 393 | + use super::*; | ||
| 394 | + use crate::domain::exam_question::QuestionKind; | ||
| 395 | + | ||
| 396 | + fn kind(value: &str) -> QuestionKind { | ||
| 397 | + QuestionKind::try_new(value).unwrap() | ||
| 398 | + } | ||
| 399 | + | ||
| 400 | + /// The subject reference counter, which is what the subject's delete guard | ||
| 401 | + /// reads: every one of these asserts *stored* state, because a claim that | ||
| 402 | + /// outlives the row it accounts for makes its subject undeletable forever. | ||
| 403 | + mod counters { | ||
| 404 | + use super::*; | ||
| 405 | + use crate::database::init_mem; | ||
| 406 | + use crate::domain::exam::{ | ||
| 407 | + Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, | ||
| 408 | + }; | ||
| 409 | + use crate::domain::settings::Settings; | ||
| 410 | + use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | ||
| 411 | + use crate::domain::user::UserId; | ||
| 412 | + | ||
| 413 | + async fn an_exam(db: &Database) -> Exam { | ||
| 414 | + let kinds = Settings::defaults().get_exam_kinds().to_vec(); | ||
| 415 | + Exam::create( | ||
| 416 | + &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), | ||
| 417 | + &crate::db::course::a_test_course(db).await, | ||
| 418 | + ExamTitle::try_new("practice").unwrap(), | ||
| 419 | + ExamDescription::try_new("").unwrap(), | ||
| 420 | + ExamKind::try_new("quiz", &kinds).unwrap(), | ||
| 421 | + ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None) | ||
| 422 | + .unwrap(), | ||
| 423 | + ExamAttemptLimit::try_new(1).unwrap(), | ||
| 424 | + true, | ||
| 425 | + false, | ||
| 426 | + false, | ||
| 427 | + db, | ||
| 428 | + ) | ||
| 429 | + .await | ||
| 430 | + .unwrap() | ||
| 431 | + } | ||
| 432 | + | ||
| 433 | + async fn a_subject(db: &Database) -> Subject { | ||
| 434 | + Subject::create( | ||
| 435 | + &crate::db::course::a_test_course(db).await, | ||
| 436 | + SubjectName::try_new("topic").unwrap(), | ||
| 437 | + SubjectDescription::try_new("").unwrap(), | ||
| 438 | + db, | ||
| 439 | + ) | ||
| 440 | + .await | ||
| 441 | + .unwrap() | ||
| 442 | + } | ||
| 443 | + | ||
| 444 | + /// The editable payload, fresh per call (each one is consumed). | ||
| 445 | + fn body() -> (QuestionText, QuestionPoints, QuestionSpec) { | ||
| 446 | + ( | ||
| 447 | + QuestionText::try_new("3 + 3?").unwrap(), | ||
| 448 | + QuestionPoints::try_new(5).unwrap(), | ||
| 449 | + QuestionSpec::try_new(kind("text"), None, None, &[]).unwrap(), | ||
| 450 | + ) | ||
| 451 | + } | ||
| 452 | + | ||
| 453 | + async fn a_question(exam: &Exam, on: &SubjectId, db: &Database) -> ExamQuestion { | ||
| 454 | + let (text, points, spec) = body(); | ||
| 455 | + create(db, exam.get_id(), on.clone(), text, points, spec) | ||
| 456 | + .await | ||
| 457 | + .unwrap() | ||
| 458 | + } | ||
| 459 | + | ||
| 460 | + async fn moved( | ||
| 461 | + question: ExamQuestion, | ||
| 462 | + to: &SubjectId, | ||
| 463 | + db: &Database, | ||
| 464 | + ) -> Result<ExamQuestion, AppError> { | ||
| 465 | + let (text, points, spec) = body(); | ||
| 466 | + update(db, question, to.clone(), text, points, spec).await | ||
| 467 | + } | ||
| 468 | + | ||
| 469 | + /// The stored `exam_question_count` on one subject, absent = zero. | ||
| 470 | + async fn count_on(subject: &SubjectId, db: &Database) -> i64 { | ||
| 471 | + let mut result = db | ||
| 472 | + .query(format!( | ||
| 473 | + "SELECT VALUE ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) FROM $sub" | ||
| 474 | + )) | ||
| 475 | + .bind(("sub", subject.record())) | ||
| 476 | + .await | ||
| 477 | + .unwrap() | ||
| 478 | + .check() | ||
| 479 | + .unwrap(); | ||
| 480 | + result | ||
| 481 | + .take::<Vec<i64>>(0) | ||
| 482 | + .unwrap() | ||
| 483 | + .first() | ||
| 484 | + .copied() | ||
| 485 | + .unwrap_or(0) | ||
| 486 | + } | ||
| 487 | + | ||
| 488 | + async fn rows(sql: &str, db: &Database) -> usize { | ||
| 489 | + let mut result = db.query(sql).await.unwrap().check().unwrap(); | ||
| 490 | + result.take::<Vec<RecordId>>(0).unwrap().len() | ||
| 491 | + } | ||
| 492 | + | ||
| 493 | + /// The freeze outranks the counter move, on both paths — and because | ||
| 494 | + /// the claim now rides the refused transaction, "outranks" has to mean | ||
| 495 | + /// the counters read as if nothing ran. | ||
| 496 | + #[tokio::test] | ||
| 497 | + async fn a_frozen_exam_leaves_the_subject_counters_untouched() { | ||
| 498 | + let db = init_mem().await.unwrap(); | ||
| 499 | + let exam = an_exam(&db).await; | ||
| 500 | + let (from, to) = (a_subject(&db).await, a_subject(&db).await); | ||
| 501 | + let (from, to) = (from.get_id().clone(), to.get_id().clone()); | ||
| 502 | + let question = a_question(&exam, &from, &db).await; | ||
| 503 | + assert_eq!(count_on(&from, &db).await, 1); | ||
| 504 | + | ||
| 505 | + // A real user row: starting a sitting moves that student's badge | ||
| 506 | + // counter in the same transaction, and an `UPDATE` has nothing to | ||
| 507 | + // write to without one. | ||
| 508 | + let hash = crate::domain::user::Password::try_new("secret1") | ||
| 509 | + .unwrap() | ||
| 510 | + .hash_async() | ||
| 511 | + .await | ||
| 512 | + .unwrap(); | ||
| 513 | + let student = crate::domain::user::User::create( | ||
| 514 | + crate::domain::user::Username::try_new("ogrenci").unwrap(), | ||
| 515 | + hash, | ||
| 516 | + &db, | ||
| 517 | + ) | ||
| 518 | + .await | ||
| 519 | + .unwrap(); | ||
| 520 | + crate::service::exam_attempt::start(&db, &exam, student.get_id()) | ||
| 521 | + .await | ||
| 522 | + .unwrap(); | ||
| 523 | + | ||
| 524 | + let (text, points, spec) = body(); | ||
| 525 | + let error = create(&db, exam.get_id(), to.clone(), text, points, spec) | ||
| 526 | + .await | ||
| 527 | + .expect_err("a started exam takes no new questions"); | ||
| 528 | + assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); | ||
| 529 | + assert_eq!(count_on(&to, &db).await, 0, "the refused claim rolled back"); | ||
| 530 | + | ||
| 531 | + let error = moved(question, &to, &db) | ||
| 532 | + .await | ||
| 533 | + .expect_err("a started exam takes no re-tag either"); | ||
| 534 | + assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); | ||
| 535 | + assert_eq!(count_on(&from, &db).await, 1, "the release rolled back too"); | ||
| 536 | + assert_eq!(count_on(&to, &db).await, 0); | ||
| 537 | + } | ||
| 538 | + | ||
| 539 | + /// The create-path invariant: a refused create writes neither the row | ||
| 540 | + /// nor a count — least of all on a subject it would have to invent. | ||
| 541 | + #[tokio::test] | ||
| 542 | + async fn a_create_on_a_dead_subject_writes_neither_row_nor_count() { | ||
| 543 | + let db = init_mem().await.unwrap(); | ||
| 544 | + let exam = an_exam(&db).await; | ||
| 545 | + let subject = a_subject(&db).await; | ||
| 546 | + let id = subject.get_id().clone(); | ||
| 547 | + subject.delete(&db).await.unwrap(); | ||
| 548 | + | ||
| 549 | + let (text, points, spec) = body(); | ||
| 550 | + let error = create(&db, exam.get_id(), id, text, points, spec) | ||
| 551 | + .await | ||
| 552 | + .expect_err("a subject that is gone must not be taggable"); | ||
| 553 | + assert!(error.to_string().contains("subject does not exist")); | ||
| 554 | + assert_eq!( | ||
| 555 | + rows("SELECT VALUE id FROM exam_question", &db).await, | ||
| 556 | + 0, | ||
| 557 | + "a refused create may write no row" | ||
| 558 | + ); | ||
| 559 | + assert_eq!( | ||
| 560 | + rows("SELECT VALUE id FROM subject", &db).await, | ||
| 561 | + 0, | ||
| 562 | + "…and least of all a count on a subject it just brought back" | ||
| 563 | + ); | ||
| 564 | + } | ||
| 565 | + | ||
| 566 | + #[tokio::test] | ||
| 567 | + async fn a_subject_move_moves_the_count() { | ||
| 568 | + let db = init_mem().await.unwrap(); | ||
| 569 | + let exam = an_exam(&db).await; | ||
| 570 | + let (from, to) = (a_subject(&db).await, a_subject(&db).await); | ||
| 571 | + let (from, to) = (from.get_id().clone(), to.get_id().clone()); | ||
| 572 | + let question = a_question(&exam, &from, &db).await; | ||
| 573 | + | ||
| 574 | + let after = moved(question, &to, &db).await.unwrap(); | ||
| 575 | + assert_eq!(after.get_subject(), &to); | ||
| 576 | + assert_eq!(count_on(&from, &db).await, 0, "the old subject is free"); | ||
| 577 | + assert_eq!(count_on(&to, &db).await, 1, "the new one is not"); | ||
| 578 | + } | ||
| 579 | + | ||
| 580 | + #[tokio::test] | ||
| 581 | + async fn a_move_to_a_dead_subject_leaves_everything_untouched() { | ||
| 582 | + let db = init_mem().await.unwrap(); | ||
| 583 | + let exam = an_exam(&db).await; | ||
| 584 | + let from = a_subject(&db).await.get_id().clone(); | ||
| 585 | + let dead = a_subject(&db).await; | ||
| 586 | + let gone = dead.get_id().clone(); | ||
| 587 | + dead.delete(&db).await.unwrap(); | ||
| 588 | + let question = a_question(&exam, &from, &db).await; | ||
| 589 | + | ||
| 590 | + let error = moved(question.clone(), &gone, &db) | ||
| 591 | + .await | ||
| 592 | + .expect_err("a subject that is gone must not be taggable"); | ||
| 593 | + assert!(error.to_string().contains("subject does not exist")); | ||
| 594 | + let stored = read(&db, question.get_id()).await.unwrap().unwrap(); | ||
| 595 | + assert_eq!(stored.get_subject(), &from, "the link never moved"); | ||
| 596 | + assert_eq!( | ||
| 597 | + count_on(&from, &db).await, | ||
| 598 | + 1, | ||
| 599 | + "the release rolled back with the claim" | ||
| 600 | + ); | ||
| 601 | + assert_eq!(rows("SELECT VALUE id FROM subject", &db).await, 1); | ||
| 602 | + } | ||
| 603 | + | ||
| 604 | + /// The double-claim guard. Both movers compute their claim and release | ||
| 605 | + /// from the row as *they* read it, so two PATCHes re-tagging the same | ||
| 606 | + /// question both release the old subject and both claim their own | ||
| 607 | + /// target — two counts for one link, and the loser's target is | ||
| 608 | + /// undeletable forever. The second call here runs on the struct read | ||
| 609 | + /// before the first one landed: it must be refused outright, and the | ||
| 610 | + /// counts must read as if it never ran. | ||
| 611 | + /// | ||
| 612 | + /// Drop `AND subject = $ref_expected` from the row write in | ||
| 613 | + /// [`update`] and this goes red on the very first | ||
| 614 | + /// assertion — the stale mover is happily applied. | ||
| 615 | + #[tokio::test] | ||
| 616 | + async fn a_stale_mover_is_refused_and_claims_nothing() { | ||
| 617 | + let db = init_mem().await.unwrap(); | ||
| 618 | + let exam = an_exam(&db).await; | ||
| 619 | + let from = a_subject(&db).await.get_id().clone(); | ||
| 620 | + let to = a_subject(&db).await.get_id().clone(); | ||
| 621 | + let other = a_subject(&db).await.get_id().clone(); | ||
| 622 | + let question = a_question(&exam, &from, &db).await; | ||
| 623 | + let stale = question.clone(); | ||
| 624 | + | ||
| 625 | + moved(question, &to, &db).await.unwrap(); | ||
| 626 | + let error = moved(stale.clone(), &other, &db) | ||
| 627 | + .await | ||
| 628 | + .expect_err("a mover that read a subject it no longer holds must be refused"); | ||
| 629 | + assert!( | ||
| 630 | + matches!(error, AppError::Conflict(_)), | ||
| 631 | + "a lost CAS is a conflict, not a 404 or a 500: {error:?}" | ||
| 632 | + ); | ||
| 633 | + | ||
| 634 | + let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); | ||
| 635 | + assert_eq!(stored.get_subject(), &to, "the winner's link"); | ||
| 636 | + assert_eq!(count_on(&from, &db).await, 0, "released once, not twice"); | ||
| 637 | + assert_eq!(count_on(&to, &db).await, 1, "claimed once"); | ||
| 638 | + assert_eq!(count_on(&other, &db).await, 0, "never claimed"); | ||
| 639 | + } | ||
| 640 | + | ||
| 641 | + /// The other half of the same race, and the one arming on "the subject | ||
| 642 | + /// changed" lets through: this PATCH carries the subject its snapshot | ||
| 643 | + /// already held, so it moves no counter — but a rival's move landed | ||
| 644 | + /// first, and writing that stale subject back would revert the winner | ||
| 645 | + /// while both counters still describe the move. The handler fills an | ||
| 646 | + /// omitted `subject_id` from the row it read, so this is also every | ||
| 647 | + /// text-only PATCH sent from a stale snapshot. | ||
| 648 | + /// | ||
| 649 | + /// Arm the CAS on the re-tag instead of on the write and this goes red | ||
| 650 | + /// on the first assertion — the re-state lands 200. | ||
| 651 | + #[tokio::test] | ||
| 652 | + async fn a_stale_re_stater_is_refused_and_reverts_nothing() { | ||
| 653 | + let db = init_mem().await.unwrap(); | ||
| 654 | + let exam = an_exam(&db).await; | ||
| 655 | + let from = a_subject(&db).await.get_id().clone(); | ||
| 656 | + let to = a_subject(&db).await.get_id().clone(); | ||
| 657 | + let question = a_question(&exam, &from, &db).await; | ||
| 658 | + let stale = question.clone(); | ||
| 659 | + | ||
| 660 | + moved(question, &to, &db).await.unwrap(); | ||
| 661 | + let error = moved(stale.clone(), &from, &db) | ||
| 662 | + .await | ||
| 663 | + .expect_err("re-stating a subject a rival moved off must be refused"); | ||
| 664 | + assert!( | ||
| 665 | + matches!(error, AppError::Conflict(_)), | ||
| 666 | + "a lost CAS is a conflict, not a silent revert: {error:?}" | ||
| 667 | + ); | ||
| 668 | + | ||
| 669 | + let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); | ||
| 670 | + assert_eq!(stored.get_subject(), &to, "the winner's link stands"); | ||
| 671 | + assert_eq!( | ||
| 672 | + count_on(&from, &db).await, | ||
| 673 | + 0, | ||
| 674 | + "released once, and stayed so" | ||
| 675 | + ); | ||
| 676 | + assert_eq!(count_on(&to, &db).await, 1, "claimed once, and stayed so"); | ||
| 677 | + } | ||
| 678 | + | ||
| 679 | + /// …and the price of arming the CAS on every write is nothing: a PATCH | ||
| 680 | + /// re-stating the subject the row really holds passes it trivially. | ||
| 681 | + #[tokio::test] | ||
| 682 | + async fn a_no_op_re_state_still_lands() { | ||
| 683 | + let db = init_mem().await.unwrap(); | ||
| 684 | + let exam = an_exam(&db).await; | ||
| 685 | + let on = a_subject(&db).await.get_id().clone(); | ||
| 686 | + let question = a_question(&exam, &on, &db).await; | ||
| 687 | + | ||
| 688 | + let (_, points, spec) = body(); | ||
| 689 | + let after = update( | ||
| 690 | + &db, | ||
| 691 | + question, | ||
| 692 | + on.clone(), | ||
| 693 | + QuestionText::try_new("4 + 4?").unwrap(), | ||
| 694 | + points, | ||
| 695 | + spec, | ||
| 696 | + ) | ||
| 697 | + .await | ||
| 698 | + .expect("re-stating the subject the row holds is not a conflict"); | ||
| 699 | + assert_eq!(after.get_text().as_str(), "4 + 4?"); | ||
| 700 | + assert_eq!(after.get_subject(), &on); | ||
| 701 | + assert_eq!(count_on(&on, &db).await, 1, "no counter moved"); | ||
| 702 | + } | ||
| 703 | + | ||
| 704 | + /// A re-tag of a question whose row is gone is still the 404 it was, | ||
| 705 | + /// not the stale-mover 409 — the two empty-`$row` cases stay apart. | ||
| 706 | + #[tokio::test] | ||
| 707 | + async fn a_move_of_a_deleted_question_is_still_a_404() { | ||
| 708 | + let db = init_mem().await.unwrap(); | ||
| 709 | + let exam = an_exam(&db).await; | ||
| 710 | + let from = a_subject(&db).await.get_id().clone(); | ||
| 711 | + let to = a_subject(&db).await.get_id().clone(); | ||
| 712 | + let question = a_question(&exam, &from, &db).await; | ||
| 713 | + delete(&db, question.clone()).await.unwrap(); | ||
| 714 | + | ||
| 715 | + let error = moved(question, &to, &db) | ||
| 716 | + .await | ||
| 717 | + .expect_err("a deleted question cannot be re-tagged"); | ||
| 718 | + assert!(matches!(error, AppError::NotFound), "{error:?}"); | ||
| 719 | + assert_eq!(count_on(&to, &db).await, 0, "and nothing was claimed"); | ||
| 720 | + } | ||
| 721 | + } | ||
| 722 | +} | ||
src/db/mod.rsmodified+1 -0
| @@ -7,6 +7,7 @@ pub mod class_blueprint; | |||
| 7 | pub mod course; | 7 | pub mod course; |
| 8 | pub mod course_session; | 8 | pub mod course_session; |
| 9 | pub mod exam_attempt; | 9 | pub mod exam_attempt; |
| 10 | +pub mod exam_question; | ||
| 10 | pub mod field_update; | 11 | pub mod field_update; |
| 11 | pub mod note; | 12 | pub mod note; |
| 12 | pub mod page; | 13 | pub mod page; |
src/domain/bank_question.rsmodified+4 -6
| @@ -807,8 +807,6 @@ mod tests { | |||
| 807 | /// "0"), and questions authored by hand never counted. | 807 | /// "0"), and questions authored by hand never counted. |
| 808 | #[tokio::test] | 808 | #[tokio::test] |
| 809 | async fn usage_counts_tallies_a_page_in_one_statement() { | 809 | async fn usage_counts_tallies_a_page_in_one_statement() { |
| 810 | - use crate::domain::exam_question::ExamQuestion; | ||
| 811 | - | ||
| 812 | // One statement, so a page costs one round trip — a `;` here would mean | 810 | // One statement, so a page costs one round trip — a `;` here would mean |
| 813 | // the per-row N+1 crept back in. | 811 | // the per-row N+1 crept back in. |
| 814 | assert!( | 812 | assert!( |
| @@ -859,14 +857,14 @@ mod tests { | |||
| 859 | source: &BankQuestion, | 857 | source: &BankQuestion, |
| 860 | db: &Database, | 858 | db: &Database, |
| 861 | ) { | 859 | ) { |
| 862 | - ExamQuestion::create_from_bank( | 860 | + crate::db::exam_question::create_from_bank( |
| 861 | + db, | ||
| 863 | exam, | 862 | exam, |
| 864 | subject.clone(), | 863 | subject.clone(), |
| 865 | source.get_text().clone(), | 864 | source.get_text().clone(), |
| 866 | source.get_points(), | 865 | source.get_points(), |
| 867 | source.spec(), | 866 | source.spec(), |
| 868 | source.get_id().clone(), | 867 | source.get_id().clone(), |
| 869 | - db, | ||
| 870 | ) | 868 | ) |
| 871 | .await | 869 | .await |
| 872 | .unwrap(); | 870 | .unwrap(); |
| @@ -876,13 +874,13 @@ mod tests { | |||
| 876 | instantiate(&other_exam, subject.get_id(), &used_twice, &db).await; | 874 | instantiate(&other_exam, subject.get_id(), &used_twice, &db).await; |
| 877 | instantiate(&exam, subject.get_id(), &used_once, &db).await; | 875 | instantiate(&exam, subject.get_id(), &used_once, &db).await; |
| 878 | // A hand-authored question has no `from_bank` and must not be tallied. | 876 | // A hand-authored question has no `from_bank` and must not be tallied. |
| 879 | - ExamQuestion::create( | 877 | + crate::db::exam_question::create( |
| 878 | + &db, | ||
| 880 | &exam, | 879 | &exam, |
| 881 | subject.get_id().clone(), | 880 | subject.get_id().clone(), |
| 882 | QuestionText::try_new("mine").unwrap(), | 881 | QuestionText::try_new("mine").unwrap(), |
| 883 | QuestionPoints::try_new(1).unwrap(), | 882 | QuestionPoints::try_new(1).unwrap(), |
| 884 | spec(), | 883 | spec(), |
| 885 | - &db, | ||
| 886 | ) | 884 | ) |
| 887 | .await | 885 | .await |
| 888 | .unwrap(); | 886 | .unwrap(); |
src/domain/exam.rsmodified+12 -10
| @@ -751,9 +751,11 @@ mod tests { | |||
| 751 | .map(|_| ()) | 751 | .map(|_| ()) |
| 752 | }) | 752 | }) |
| 753 | } | 753 | } |
| 754 | - crate::db::course::assert_no_child_outlives_a_course_delete("exam_orphan_race", | 754 | + crate::db::course::assert_no_child_outlives_a_course_delete( |
| 755 | - EXAM_TABLE, | 755 | + "exam_orphan_race", |
| 756 | - make,) | 756 | + EXAM_TABLE, |
| 757 | + make, | ||
| 758 | + ) | ||
| 757 | .await; | 759 | .await; |
| 758 | } | 760 | } |
| 759 | 761 | ||
| @@ -1103,7 +1105,7 @@ mod tests { | |||
| 1103 | /// question claims a reference on its subject and is refused without one. | 1105 | /// question claims a reference on its subject and is refused without one. |
| 1104 | async fn question_on(exam: &Exam, db: &Database) -> crate::domain::exam_question::ExamQuestion { | 1106 | async fn question_on(exam: &Exam, db: &Database) -> crate::domain::exam_question::ExamQuestion { |
| 1105 | use crate::domain::exam_question::{ | 1107 | use crate::domain::exam_question::{ |
| 1106 | - ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, | 1108 | + ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, |
| 1107 | }; | 1109 | }; |
| 1108 | let spec = QuestionSpec::try_new( | 1110 | let spec = QuestionSpec::try_new( |
| 1109 | QuestionKind::try_new("choice").unwrap(), | 1111 | QuestionKind::try_new("choice").unwrap(), |
| @@ -1129,13 +1131,13 @@ mod tests { | |||
| 1129 | ) | 1131 | ) |
| 1130 | .await | 1132 | .await |
| 1131 | .unwrap(); | 1133 | .unwrap(); |
| 1132 | - ExamQuestion::create( | 1134 | + crate::db::exam_question::create( |
| 1135 | + db, | ||
| 1133 | exam.get_id(), | 1136 | exam.get_id(), |
| 1134 | subject.get_id().clone(), | 1137 | subject.get_id().clone(), |
| 1135 | QuestionText::try_new("3 + 3?").unwrap(), | 1138 | QuestionText::try_new("3 + 3?").unwrap(), |
| 1136 | QuestionPoints::try_new(5).unwrap(), | 1139 | QuestionPoints::try_new(5).unwrap(), |
| 1137 | spec, | 1140 | spec, |
| 1138 | - db, | ||
| 1139 | ) | 1141 | ) |
| 1140 | .await | 1142 | .await |
| 1141 | .unwrap() | 1143 | .unwrap() |
| @@ -1248,7 +1250,7 @@ mod tests { | |||
| 1248 | #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | 1250 | #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] |
| 1249 | async fn a_question_written_inside_a_delete_never_outlives_the_exam() { | 1251 | async fn a_question_written_inside_a_delete_never_outlives_the_exam() { |
| 1250 | use crate::domain::exam_question::{ | 1252 | use crate::domain::exam_question::{ |
| 1251 | - ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, | 1253 | + ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, |
| 1252 | }; | 1254 | }; |
| 1253 | use crate::domain::subject::Subject; | 1255 | use crate::domain::subject::Subject; |
| 1254 | let (db, _serialized) = crate::database::init_test_server("exam_question_race").await; | 1256 | let (db, _serialized) = crate::database::init_test_server("exam_question_race").await; |
| @@ -1298,13 +1300,13 @@ mod tests { | |||
| 1298 | &[], | 1300 | &[], |
| 1299 | ) | 1301 | ) |
| 1300 | .unwrap(); | 1302 | .unwrap(); |
| 1301 | - ExamQuestion::create( | 1303 | + crate::db::exam_question::create( |
| 1304 | + &db, | ||
| 1302 | &exam_id, | 1305 | &exam_id, |
| 1303 | on, | 1306 | on, |
| 1304 | QuestionText::try_new("3 + 3?").unwrap(), | 1307 | QuestionText::try_new("3 + 3?").unwrap(), |
| 1305 | QuestionPoints::try_new(5).unwrap(), | 1308 | QuestionPoints::try_new(5).unwrap(), |
| 1306 | spec, | 1309 | spec, |
| 1307 | - &db, | ||
| 1308 | ) | 1310 | ) |
| 1309 | .await | 1311 | .await |
| 1310 | }) | 1312 | }) |
| @@ -1317,7 +1319,7 @@ mod tests { | |||
| 1317 | 1319 | ||
| 1318 | if Exam::read(&id, &db).await.unwrap().is_none() { | 1320 | if Exam::read(&id, &db).await.unwrap().is_none() { |
| 1319 | swept += 1; | 1321 | swept += 1; |
| 1320 | - questions += ExamQuestion::list_for_exam(&id, None, 0, &db) | 1322 | + questions += crate::db::exam_question::list_for_exam(&db, &id, None, 0) |
| 1321 | .await | 1323 | .await |
| 1322 | .unwrap() | 1324 | .unwrap() |
| 1323 | .0 | 1325 | .0 |
src/domain/exam_question.rsmodified+19 -721
| @@ -1,45 +1,24 @@ | |||
| 1 | -use std::collections::HashSet; | ||
| 2 | - | ||
| 3 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 1 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 4 | use ulid::Ulid; | 2 | use ulid::Ulid; |
| 5 | 3 | ||
| 6 | use crate::constant::{ | 4 | use crate::constant::{ |
| 7 | EXAM_QUESTION_TABLE, MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, | 5 | EXAM_QUESTION_TABLE, MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, |
| 8 | - MIN_QUESTION_CHOICES, SUBJECT_QUESTION_COUNT_FIELD, | 6 | + MIN_QUESTION_CHOICES, |
| 9 | }; | 7 | }; |
| 10 | -use crate::database::Database; | ||
| 11 | -use crate::db::cap; | ||
| 12 | -use crate::db::page::PagedList; | ||
| 13 | use crate::domain::bank_question::BankQuestionId; | 8 | use crate::domain::bank_question::BankQuestionId; |
| 14 | use crate::domain::exam::ExamId; | 9 | use crate::domain::exam::ExamId; |
| 15 | use crate::domain::monotonic_id::next_ulid; | 10 | use crate::domain::monotonic_id::next_ulid; |
| 16 | use crate::domain::subject::SubjectId; | 11 | use crate::domain::subject::SubjectId; |
| 17 | -use crate::error::{AppError, ValidationError}; | 12 | +use crate::error::ValidationError; |
| 18 | use crate::validate::{validate_question_kind, validate_question_points, validate_required}; | 13 | use crate::validate::{validate_question_kind, validate_question_points, validate_required}; |
| 19 | 14 | ||
| 20 | -/// The `THROW` markers the folded counter moves abort with: the subject the | ||
| 21 | -/// reference was to be claimed on is gone, the question being patched is gone, | ||
| 22 | -/// and the subject this move started from is no longer the one the handler | ||
| 23 | -/// read. File-local like every other marker set (`cap`'s, `subject`'s). | ||
| 24 | -const SUBJECT_MARK: &str = "question_subject_gone"; | ||
| 25 | -const ROW_MARK: &str = "question_row_gone"; | ||
| 26 | -const STALE_MARK: &str = "question_stale_move"; | ||
| 27 | - | ||
| 28 | -/// The one answer for a subject that isn't there — a claim missing it and the | ||
| 29 | -/// web layer's pre-flight lookup missing it are the same 400. | ||
| 30 | -fn dead_subject() -> AppError { | ||
| 31 | - AppError::Validation(ValidationError::Invalid { | ||
| 32 | - field: "subject_id", | ||
| 33 | - reason: "subject does not exist", | ||
| 34 | - }) | ||
| 35 | -} | ||
| 36 | - | ||
| 37 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 15 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 38 | pub struct ExamQuestionId(RecordId); | 16 | pub struct ExamQuestionId(RecordId); |
| 39 | 17 | ||
| 40 | impl ExamQuestionId { | 18 | impl ExamQuestionId { |
| 41 | /// Minted from the process-wide monotonic generator, not `Ulid::new()`: the | 19 | /// Minted from the process-wide monotonic generator, not `Ulid::new()`: the |
| 42 | - /// id *is* the question's presentation order ([`ExamQuestion::list_for_exam`] | 20 | + /// id *is* the question's presentation order |
| 21 | + /// ([`crate::db::exam_question::list_for_exam`] | ||
| 43 | /// sorts `id ASC`), and a random low half scrambles a burst of saves that | 22 | /// sorts `id ASC`), and a random low half scrambles a burst of saves that |
| 44 | /// lands inside one millisecond. | 23 | /// lands inside one millisecond. |
| 45 | pub fn generate() -> Self { | 24 | pub fn generate() -> Self { |
| @@ -181,9 +160,9 @@ pub struct ChoiceInput { | |||
| 181 | /// - `choice` → 2–10 `choices` plus a `correct` naming one of them. | 160 | /// - `choice` → 2–10 `choices` plus a `correct` naming one of them. |
| 182 | #[derive(Debug, Clone)] | 161 | #[derive(Debug, Clone)] |
| 183 | pub struct QuestionSpec { | 162 | pub struct QuestionSpec { |
| 184 | - kind: QuestionKind, | 163 | + pub(crate) kind: QuestionKind, |
| 185 | - choices: Option<Vec<Choice>>, | 164 | + pub(crate) choices: Option<Vec<Choice>>, |
| 186 | - correct: Option<ChoiceId>, | 165 | + pub(crate) correct: Option<ChoiceId>, |
| 187 | } | 166 | } |
| 188 | 167 | ||
| 189 | impl QuestionSpec { | 168 | impl QuestionSpec { |
| @@ -305,25 +284,26 @@ impl QuestionSpec { | |||
| 305 | /// subject's course matches before any write. | 284 | /// subject's course matches before any write. |
| 306 | #[derive(Debug, Clone, SurrealValue)] | 285 | #[derive(Debug, Clone, SurrealValue)] |
| 307 | pub struct ExamQuestion { | 286 | pub struct ExamQuestion { |
| 308 | - id: ExamQuestionId, | 287 | + pub(crate) id: ExamQuestionId, |
| 309 | - exam: ExamId, | 288 | + pub(crate) exam: ExamId, |
| 310 | - subject: SubjectId, | 289 | + pub(crate) subject: SubjectId, |
| 311 | - text: QuestionText, | 290 | + pub(crate) text: QuestionText, |
| 312 | - kind: QuestionKind, | 291 | + pub(crate) kind: QuestionKind, |
| 313 | - points: QuestionPoints, | 292 | + pub(crate) points: QuestionPoints, |
| 314 | - choices: Option<Vec<Choice>>, | 293 | + pub(crate) choices: Option<Vec<Choice>>, |
| 315 | - correct: Option<ChoiceId>, | 294 | + pub(crate) correct: Option<ChoiceId>, |
| 316 | /// The bank template this question was created *from*, if it was inserted | 295 | /// The bank template this question was created *from*, if it was inserted |
| 317 | /// out of the bank. Written once, at insert. | 296 | /// out of the bank. Written once, at insert. |
| 318 | #[surreal(default)] | 297 | #[surreal(default)] |
| 319 | - from_bank: Option<BankQuestionId>, | 298 | + pub(crate) from_bank: Option<BankQuestionId>, |
| 320 | /// The bank template most recently created *by saving this question* into | 299 | /// The bank template most recently created *by saving this question* into |
| 321 | - /// the bank, if any. Written by [`Self::link_banked_as`], repointed by every | 300 | + /// the bank, if any. Written by |
| 301 | + /// [`crate::db::exam_question::link_banked_as`], repointed by every | ||
| 322 | /// repeat save. Never set by an insert-from-bank: the two directions are | 302 | /// repeat save. Never set by an insert-from-bank: the two directions are |
| 323 | /// separate columns precisely so "came from the bank" can't be misread as | 303 | /// separate columns precisely so "came from the bank" can't be misread as |
| 324 | /// "already saved to the bank". | 304 | /// "already saved to the bank". |
| 325 | #[surreal(default)] | 305 | #[surreal(default)] |
| 326 | - banked_as: Option<BankQuestionId>, | 306 | + pub(crate) banked_as: Option<BankQuestionId>, |
| 327 | } | 307 | } |
| 328 | 308 | ||
| 329 | impl ExamQuestion { | 309 | impl ExamQuestion { |
| @@ -377,356 +357,6 @@ impl ExamQuestion { | |||
| 377 | ) | 357 | ) |
| 378 | } | 358 | } |
| 379 | 359 | ||
| 380 | - pub async fn create( | ||
| 381 | - exam: &ExamId, | ||
| 382 | - subject: SubjectId, | ||
| 383 | - text: QuestionText, | ||
| 384 | - points: QuestionPoints, | ||
| 385 | - spec: QuestionSpec, | ||
| 386 | - db: &Database, | ||
| 387 | - ) -> Result<ExamQuestion, AppError> { | ||
| 388 | - Self::insert(exam, subject, text, points, spec, None, db).await | ||
| 389 | - } | ||
| 390 | - | ||
| 391 | - /// Like [`Self::create`], but records the bank template this question was | ||
| 392 | - /// instantiated from (`POST …/questions/from-bank/{bid}`). | ||
| 393 | - pub async fn create_from_bank( | ||
| 394 | - exam: &ExamId, | ||
| 395 | - subject: SubjectId, | ||
| 396 | - text: QuestionText, | ||
| 397 | - points: QuestionPoints, | ||
| 398 | - spec: QuestionSpec, | ||
| 399 | - source: BankQuestionId, | ||
| 400 | - db: &Database, | ||
| 401 | - ) -> Result<ExamQuestion, AppError> { | ||
| 402 | - Self::insert(exam, subject, text, points, spec, Some(source), db).await | ||
| 403 | - } | ||
| 404 | - | ||
| 405 | - #[allow(clippy::too_many_arguments)] | ||
| 406 | - async fn insert( | ||
| 407 | - exam: &ExamId, | ||
| 408 | - subject: SubjectId, | ||
| 409 | - text: QuestionText, | ||
| 410 | - points: QuestionPoints, | ||
| 411 | - spec: QuestionSpec, | ||
| 412 | - from_bank: Option<BankQuestionId>, | ||
| 413 | - db: &Database, | ||
| 414 | - ) -> Result<ExamQuestion, AppError> { | ||
| 415 | - let counted = subject.record(); | ||
| 416 | - let question = ExamQuestion { | ||
| 417 | - id: ExamQuestionId::generate(), | ||
| 418 | - exam: exam.clone(), | ||
| 419 | - subject, | ||
| 420 | - text, | ||
| 421 | - points, | ||
| 422 | - kind: spec.kind, | ||
| 423 | - choices: spec.choices, | ||
| 424 | - correct: spec.correct, | ||
| 425 | - from_bank, | ||
| 426 | - // An insert never banks anything: only a to-bank save writes this. | ||
| 427 | - banked_as: None, | ||
| 428 | - }; | ||
| 429 | - // The freeze gate and the subject's reference ride in the same | ||
| 430 | - // transaction as the insert: a question cannot appear under an exam | ||
| 431 | - // somebody has already started, and the claim that accounts for it | ||
| 432 | - // cannot outlive a row that never landed. Claiming in its own query | ||
| 433 | - // (with a release on failure, as this did) leaves a window where a | ||
| 434 | - // crash strands the count — and the subject delete is conditioned on | ||
| 435 | - // that count reading zero, so a stranded one makes the subject | ||
| 436 | - // undeletable forever. A missed claim means the subject is already gone | ||
| 437 | - // — the same 400 the web layer's pre-flight check answers with. | ||
| 438 | - // | ||
| 439 | - // Re-sendable despite the `CREATE`: a lost round aborts having written | ||
| 440 | - // nothing and `$id` is a ULID minted once per call, so the re-send | ||
| 441 | - // cannot answer "already exists" (there is no UNIQUE index on | ||
| 442 | - // `exam_question`) — the one thing the retry cannot survive. | ||
| 443 | - let id = question.id.record(); | ||
| 444 | - // One counter write in flight at a time, like every other counter write. | ||
| 445 | - let _guard = cap::counter_lock().await; | ||
| 446 | - let mut result = crate::db::exam_attempt::write_unfrozen_with( | ||
| 447 | - db, | ||
| 448 | - exam, | ||
| 449 | - &format!( | ||
| 450 | - "LET $seat = (UPDATE $subject SET {SUBJECT_QUESTION_COUNT_FIELD} = \ | ||
| 451 | - ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); | ||
| 452 | - IF array::len($seat) = 0 {{ THROW '{SUBJECT_MARK}' }}; | ||
| 453 | - CREATE $id CONTENT $question;" | ||
| 454 | - ), | ||
| 455 | - vec![ | ||
| 456 | - ("subject".into(), counted.into_value()), | ||
| 457 | - ("id".into(), id.into_value()), | ||
| 458 | - ("question".into(), question.into_value()), | ||
| 459 | - ], | ||
| 460 | - vec![(SUBJECT_MARK, dead_subject())], | ||
| 461 | - ) | ||
| 462 | - .await?; | ||
| 463 | - // Counted off the statements that actually ran rather than a fixed | ||
| 464 | - // slot, so folding another gate in above can never mis-read the row. | ||
| 465 | - let slot = result.num_statements().saturating_sub(2); | ||
| 466 | - result | ||
| 467 | - .take::<Vec<ExamQuestion>>(slot)? | ||
| 468 | - .into_iter() | ||
| 469 | - .next() | ||
| 470 | - .ok_or_else(|| AppError::Internal("failed to create exam question".into())) | ||
| 471 | - } | ||
| 472 | - | ||
| 473 | - pub async fn read( | ||
| 474 | - id: &ExamQuestionId, | ||
| 475 | - db: &Database, | ||
| 476 | - ) -> Result<Option<ExamQuestion>, AppError> { | ||
| 477 | - Ok(db.select(id.record()).await?) | ||
| 478 | - } | ||
| 479 | - | ||
| 480 | - /// The exam's questions in presentation order (ULID ids sort by creation). | ||
| 481 | - pub async fn list_for_exam( | ||
| 482 | - exam: &ExamId, | ||
| 483 | - limit: Option<i64>, | ||
| 484 | - offset: i64, | ||
| 485 | - db: &Database, | ||
| 486 | - ) -> Result<(Vec<ExamQuestion>, i64), AppError> { | ||
| 487 | - PagedList::new("exam_question WHERE exam = $ex", "ORDER BY id ASC") | ||
| 488 | - .bind("ex", exam.record()) | ||
| 489 | - .run(limit, offset, db) | ||
| 490 | - .await | ||
| 491 | - } | ||
| 492 | - | ||
| 493 | - /// The ids of `exam`'s questions that share a bank template with a question | ||
| 494 | - /// under one of `live` — the questions two exams hold identical `correct` | ||
| 495 | - /// for, because the bank copies the key into every instantiation. Keyed on | ||
| 496 | - /// the template, never on the exam, so only the overlapping questions are | ||
| 497 | - /// named. Empty when `live` is empty. | ||
| 498 | - /// | ||
| 499 | - /// A question links to a template through *either* column and both must be | ||
| 500 | - /// read, on both sides of the join: `from_bank` is the template it was | ||
| 501 | - /// instantiated from, `banked_as` the template minted by saving it into the | ||
| 502 | - /// bank ([`Self::link_banked_as`]). A question authored by hand in exam A | ||
| 503 | - /// and then saved to the bank holds only `banked_as`, while its copy in | ||
| 504 | - /// exam B holds only `from_bank` — matching `from_bank` to `from_bank` saw | ||
| 505 | - /// neither and leaked A's key while B was live. A single coalesced key per | ||
| 506 | - /// row is not enough either: a question instantiated from one template and | ||
| 507 | - /// re-saved as another carries *both*, and only the second one may be the | ||
| 508 | - /// shared link. | ||
| 509 | - /// | ||
| 510 | - /// So: collect every template id reachable from a live exam by either | ||
| 511 | - /// column, then name any of `exam`'s questions pointing at one by either | ||
| 512 | - /// column. `$shared` is built from `!= NONE` filters, so it never holds a | ||
| 513 | - /// `NONE` for an unlinked question's absent column to match against. | ||
| 514 | - pub async fn list_shared_with( | ||
| 515 | - exam: &ExamId, | ||
| 516 | - live: &[ExamId], | ||
| 517 | - db: &Database, | ||
| 518 | - ) -> Result<HashSet<String>, AppError> { | ||
| 519 | - if live.is_empty() { | ||
| 520 | - return Ok(HashSet::new()); | ||
| 521 | - } | ||
| 522 | - let mut result = db | ||
| 523 | - .query( | ||
| 524 | - "LET $shared = array::union( | ||
| 525 | - (SELECT VALUE from_bank FROM exam_question | ||
| 526 | - WHERE exam IN $live AND from_bank != NONE), | ||
| 527 | - (SELECT VALUE banked_as FROM exam_question | ||
| 528 | - WHERE exam IN $live AND banked_as != NONE)); | ||
| 529 | - SELECT VALUE id FROM exam_question | ||
| 530 | - WHERE exam = $ex AND (from_bank IN $shared OR banked_as IN $shared)", | ||
| 531 | - ) | ||
| 532 | - .bind(("ex", exam.record())) | ||
| 533 | - .bind(( | ||
| 534 | - "live", | ||
| 535 | - live.iter().map(ExamId::record).collect::<Vec<RecordId>>(), | ||
| 536 | - )) | ||
| 537 | - .await? | ||
| 538 | - .check()?; | ||
| 539 | - Ok(result | ||
| 540 | - .take::<Vec<ExamQuestionId>>(1)? | ||
| 541 | - .iter() | ||
| 542 | - .map(|id| id.key().to_string()) | ||
| 543 | - .collect()) | ||
| 544 | - } | ||
| 545 | - | ||
| 546 | - /// Write the editable fields, refused outright once the exam has an | ||
| 547 | - /// attempt — the freeze gate is part of this transaction, not a check the | ||
| 548 | - /// caller made a moment earlier under a lock. | ||
| 549 | - /// | ||
| 550 | - /// Field-scoped, no longer a whole-row save. The row also carries | ||
| 551 | - /// `from_bank`/`banked_as`, which [`Self::link_banked_as`] writes from a | ||
| 552 | - /// *different* request: re-stating this snapshot's copy of them would | ||
| 553 | - /// revert a to-bank save that landed in between. That is exactly what the | ||
| 554 | - /// caller's `EXAM_LOCK.write()` used to order (inside one process), and | ||
| 555 | - /// naming the columns removes the need for any ordering at all. | ||
| 556 | - pub async fn update( | ||
| 557 | - self, | ||
| 558 | - subject: SubjectId, | ||
| 559 | - text: QuestionText, | ||
| 560 | - points: QuestionPoints, | ||
| 561 | - spec: QuestionSpec, | ||
| 562 | - db: &Database, | ||
| 563 | - ) -> Result<ExamQuestion, AppError> { | ||
| 564 | - // A re-tag moves a reference, and the move rides the very transaction | ||
| 565 | - // that moves the link: the old subject's release, the new one's claim | ||
| 566 | - // and the row write commit together or not at all, so no crash can | ||
| 567 | - // strand a count on a subject nothing points at (which would make it | ||
| 568 | - // undeletable forever). | ||
| 569 | - // | ||
| 570 | - // The two are armed on *different* conditions, which is the whole of | ||
| 571 | - // the rule ([`crate::db::field_update::FieldUpdate::refcount`] states | ||
| 572 | - // it the same way): the counter statements only when the link actually | ||
| 573 | - // changes, but the CAS whenever this write *carries* the link — and it | ||
| 574 | - // always does, because the handler fills an omitted `subject_id` from | ||
| 575 | - // the row it read (`web::exams::questions`), so `subject` is in the | ||
| 576 | - // `SET` of every one of these updates. Arming the CAS on "changed" | ||
| 577 | - // instead would leave the re-stater through: a PATCH carrying the | ||
| 578 | - // subject its own stale snapshot held, sent while a rival's move | ||
| 579 | - // already landed, writes that stale subject straight back over the | ||
| 580 | - // winner — a revert with the counters left pointing at the move. | ||
| 581 | - let retag = (subject != self.subject).then(|| (subject.record(), self.subject.record())); | ||
| 582 | - let write = "UPDATE $id SET subject = $subject, text = $text, points = $points, | ||
| 583 | - kind = $kind, choices = $choices, correct = $correct"; | ||
| 584 | - let mut bindings = vec![ | ||
| 585 | - ("id".into(), self.id.record().into_value()), | ||
| 586 | - ("subject".into(), subject.record().into_value()), | ||
| 587 | - ("text".into(), text.into_value()), | ||
| 588 | - ("points".into(), points.into_value()), | ||
| 589 | - ("kind".into(), spec.kind.into_value()), | ||
| 590 | - ("choices".into(), spec.choices.into_value()), | ||
| 591 | - ("correct".into(), spec.correct.into_value()), | ||
| 592 | - ]; | ||
| 593 | - let mut statements: Vec<String> = Vec::new(); | ||
| 594 | - let mut refusals: Vec<(&str, AppError)> = Vec::new(); | ||
| 595 | - if let Some((next, previous)) = &retag { | ||
| 596 | - statements.push(format!( | ||
| 597 | - "UPDATE $ref_release SET {SUBJECT_QUESTION_COUNT_FIELD} = \ | ||
| 598 | - math::max([({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) - 1, 0])" | ||
| 599 | - )); | ||
| 600 | - statements.push(format!( | ||
| 601 | - "LET $seat = (UPDATE $ref_claim SET {SUBJECT_QUESTION_COUNT_FIELD} = \ | ||
| 602 | - ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id)" | ||
| 603 | - )); | ||
| 604 | - statements.push(format!( | ||
| 605 | - "IF array::len($seat) = 0 {{ THROW '{SUBJECT_MARK}' }}" | ||
| 606 | - )); | ||
| 607 | - bindings.push(("ref_claim".into(), next.clone().into_value())); | ||
| 608 | - bindings.push(("ref_release".into(), previous.clone().into_value())); | ||
| 609 | - refusals.push((SUBJECT_MARK, dead_subject())); | ||
| 610 | - } | ||
| 611 | - // The CAS: the row write matches only while the question still sits on | ||
| 612 | - // the subject this handler read. A genuine no-op re-state passes it | ||
| 613 | - // trivially (the row holds exactly what is expected); a stale one — | ||
| 614 | - // whether it moves the link or restates it — matches nothing, aborts | ||
| 615 | - // the whole transaction, and so claims nothing and answers 409. | ||
| 616 | - bindings.push(("ref_expected".into(), self.subject.record().into_value())); | ||
| 617 | - statements.push(format!( | ||
| 618 | - "LET $row = ({write} WHERE subject = $ref_expected RETURN AFTER)" | ||
| 619 | - )); | ||
| 620 | - statements.push(format!( | ||
| 621 | - "IF array::len($row) = 0 {{ \ | ||
| 622 | - LET $live = (UPDATE $id WHERE subject != $ref_expected RETURN VALUE id); \ | ||
| 623 | - IF array::len($live) = 0 {{ THROW '{ROW_MARK}' }} \ | ||
| 624 | - ELSE {{ THROW '{STALE_MARK}' }} }}" | ||
| 625 | - )); | ||
| 626 | - statements.push("RETURN $row".into()); | ||
| 627 | - refusals.push(( | ||
| 628 | - STALE_MARK, | ||
| 629 | - AppError::Conflict( | ||
| 630 | - "the subject this question was read on changed since; re-read and retry", | ||
| 631 | - ), | ||
| 632 | - )); | ||
| 633 | - // The row is gone: the same 404 an empty write answers with, so the | ||
| 634 | - // deleted-row case is unchanged. | ||
| 635 | - refusals.push((ROW_MARK, AppError::NotFound)); | ||
| 636 | - let statements = format!("{};", statements.join("; ")); | ||
| 637 | - // One counter write in flight at a time — only a move writes one. | ||
| 638 | - let _guard = match &retag { | ||
| 639 | - Some(_) => Some(cap::counter_lock().await), | ||
| 640 | - None => None, | ||
| 641 | - }; | ||
| 642 | - let mut result = crate::db::exam_attempt::write_unfrozen_with( | ||
| 643 | - db, | ||
| 644 | - &self.exam, | ||
| 645 | - &statements, | ||
| 646 | - bindings, | ||
| 647 | - refusals, | ||
| 648 | - ) | ||
| 649 | - .await?; | ||
| 650 | - // Read off the trailing `RETURN` rather than a fixed slot: a re-tag | ||
| 651 | - // arms three more statements than a plain PATCH does (and an `IF` | ||
| 652 | - // block is one slot whether or not it is taken). | ||
| 653 | - let slot = result.num_statements().saturating_sub(2); | ||
| 654 | - result | ||
| 655 | - .take::<Vec<ExamQuestion>>(slot)? | ||
| 656 | - .into_iter() | ||
| 657 | - .next() | ||
| 658 | - .ok_or(AppError::NotFound) | ||
| 659 | - } | ||
| 660 | - | ||
| 661 | - /// Point the question's `banked_as` at the bank template it was just saved | ||
| 662 | - /// into (`POST …/questions/{qid}/to-bank`). The mirror direction of the | ||
| 663 | - /// `from_bank` [`Self::create_from_bank`] writes, and deliberately a | ||
| 664 | - /// *different* column: a question inserted from the bank has not been saved | ||
| 665 | - /// to it, and one field for both would make the client claim it was. | ||
| 666 | - /// Overwrites any earlier link: repeat saves mint a new template and the | ||
| 667 | - /// newest one wins. | ||
| 668 | - /// | ||
| 669 | - /// Field-scoped write, unlike [`Self::update`]: the caller awaits a bank | ||
| 670 | - /// insert plus the whole blob-copy loop between reading this row and | ||
| 671 | - /// linking it, so the row it holds is long stale by now — a whole-row save | ||
| 672 | - /// would silently revert whatever landed in that window. (The caller takes | ||
| 673 | - /// `EXAM_LOCK.read()` around this call, which is what keeps | ||
| 674 | - /// [`Self::update`]'s whole-row save from clobbering the link in the other | ||
| 675 | - /// direction; the lease guards the ordering, not the staleness.) | ||
| 676 | - pub async fn link_banked_as( | ||
| 677 | - self, | ||
| 678 | - template: BankQuestionId, | ||
| 679 | - db: &Database, | ||
| 680 | - ) -> Result<ExamQuestion, AppError> { | ||
| 681 | - let mut result = db | ||
| 682 | - .query("UPDATE $id SET banked_as = $bank RETURN AFTER") | ||
| 683 | - .bind(("id", self.id.record())) | ||
| 684 | - .bind(("bank", template.record())) | ||
| 685 | - .await? | ||
| 686 | - .check()?; | ||
| 687 | - result | ||
| 688 | - .take::<Vec<ExamQuestion>>(0)? | ||
| 689 | - .into_iter() | ||
| 690 | - .next() | ||
| 691 | - .ok_or(AppError::NotFound) | ||
| 692 | - } | ||
| 693 | - | ||
| 694 | - /// Delete the question and cascade-remove its answers and image rows, so | ||
| 695 | - /// neither can point at a missing question. The image *blobs* are the web | ||
| 696 | - /// layer's to remove — it collects their names before calling this. | ||
| 697 | - /// Refused once the exam has an attempt, in the same transaction as the | ||
| 698 | - /// delete — and the cascade now shares that transaction too, so a failure | ||
| 699 | - /// mid-way can no longer strand answers whose question survived. | ||
| 700 | - pub async fn delete(self, db: &Database) -> Result<ExamQuestion, AppError> { | ||
| 701 | - let mut result = crate::db::exam_attempt::write_unfrozen( | ||
| 702 | - db, | ||
| 703 | - &self.exam, | ||
| 704 | - &format!( | ||
| 705 | - "DELETE exam_answer WHERE question = $q; | ||
| 706 | - DELETE question_image WHERE question = $q; | ||
| 707 | - LET $gone = (DELETE $q RETURN BEFORE); | ||
| 708 | - FOR $sub IN ($gone.subject ?? []) {{ | ||
| 709 | - UPDATE $sub SET {SUBJECT_QUESTION_COUNT_FIELD} = | ||
| 710 | - math::max([({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) - 1, 0]) | ||
| 711 | - }}; | ||
| 712 | - RETURN $gone;" | ||
| 713 | - ), | ||
| 714 | - vec![("q".into(), self.id.record().into_value())], | ||
| 715 | - ) | ||
| 716 | - .await?; | ||
| 717 | - // The subject's reference is given back inside this same transaction, | ||
| 718 | - // driven off what the delete actually removed — a question that wasn't | ||
| 719 | - // there decrements nothing. Read through the trailing `RETURN` rather | ||
| 720 | - // than a hand-counted slot, so inserting a cascade statement above can | ||
| 721 | - // never turn a delete into a 404 (see [`crate::domain::exam::Exam`]). | ||
| 722 | - let slot = result.num_statements().saturating_sub(2); | ||
| 723 | - result | ||
| 724 | - .take::<Vec<ExamQuestion>>(slot)? | ||
| 725 | - .into_iter() | ||
| 726 | - .next() | ||
| 727 | - .ok_or(AppError::NotFound) | ||
| 728 | - } | ||
| 729 | - | ||
| 730 | /// A question constructed without a database, for pure-function tests. | 360 | /// A question constructed without a database, for pure-function tests. |
| 731 | #[cfg(test)] | 361 | #[cfg(test)] |
| 732 | pub fn test_new(exam: &ExamId, text: &str, points: i64, spec: QuestionSpec) -> ExamQuestion { | 362 | pub fn test_new(exam: &ExamId, text: &str, points: i64, spec: QuestionSpec) -> ExamQuestion { |
| @@ -1081,338 +711,6 @@ mod tests { | |||
| 1081 | } | 711 | } |
| 1082 | } | 712 | } |
| 1083 | 713 | ||
| 1084 | - /// The subject reference counter, which is what the subject's delete guard | ||
| 1085 | - /// reads: every one of these asserts *stored* state, because a claim that | ||
| 1086 | - /// outlives the row it accounts for makes its subject undeletable forever. | ||
| 1087 | - mod counters { | ||
| 1088 | - use super::*; | ||
| 1089 | - use crate::database::init_mem; | ||
| 1090 | - use crate::domain::exam::{ | ||
| 1091 | - Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, | ||
| 1092 | - }; | ||
| 1093 | - use crate::domain::settings::Settings; | ||
| 1094 | - use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | ||
| 1095 | - use crate::domain::user::UserId; | ||
| 1096 | - | ||
| 1097 | - async fn an_exam(db: &Database) -> Exam { | ||
| 1098 | - let kinds = Settings::defaults().get_exam_kinds().to_vec(); | ||
| 1099 | - Exam::create( | ||
| 1100 | - &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), | ||
| 1101 | - &crate::db::course::a_test_course(db).await, | ||
| 1102 | - ExamTitle::try_new("practice").unwrap(), | ||
| 1103 | - ExamDescription::try_new("").unwrap(), | ||
| 1104 | - ExamKind::try_new("quiz", &kinds).unwrap(), | ||
| 1105 | - ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None) | ||
| 1106 | - .unwrap(), | ||
| 1107 | - ExamAttemptLimit::try_new(1).unwrap(), | ||
| 1108 | - true, | ||
| 1109 | - false, | ||
| 1110 | - false, | ||
| 1111 | - db, | ||
| 1112 | - ) | ||
| 1113 | - .await | ||
| 1114 | - .unwrap() | ||
| 1115 | - } | ||
| 1116 | - | ||
| 1117 | - async fn a_subject(db: &Database) -> Subject { | ||
| 1118 | - Subject::create( | ||
| 1119 | - &crate::db::course::a_test_course(db).await, | ||
| 1120 | - SubjectName::try_new("topic").unwrap(), | ||
| 1121 | - SubjectDescription::try_new("").unwrap(), | ||
| 1122 | - db, | ||
| 1123 | - ) | ||
| 1124 | - .await | ||
| 1125 | - .unwrap() | ||
| 1126 | - } | ||
| 1127 | - | ||
| 1128 | - /// The editable payload, fresh per call (each one is consumed). | ||
| 1129 | - fn body() -> (QuestionText, QuestionPoints, QuestionSpec) { | ||
| 1130 | - ( | ||
| 1131 | - QuestionText::try_new("3 + 3?").unwrap(), | ||
| 1132 | - QuestionPoints::try_new(5).unwrap(), | ||
| 1133 | - QuestionSpec::try_new(kind("text"), None, None, &[]).unwrap(), | ||
| 1134 | - ) | ||
| 1135 | - } | ||
| 1136 | - | ||
| 1137 | - async fn a_question(exam: &Exam, on: &SubjectId, db: &Database) -> ExamQuestion { | ||
| 1138 | - let (text, points, spec) = body(); | ||
| 1139 | - ExamQuestion::create(exam.get_id(), on.clone(), text, points, spec, db) | ||
| 1140 | - .await | ||
| 1141 | - .unwrap() | ||
| 1142 | - } | ||
| 1143 | - | ||
| 1144 | - async fn moved( | ||
| 1145 | - question: ExamQuestion, | ||
| 1146 | - to: &SubjectId, | ||
| 1147 | - db: &Database, | ||
| 1148 | - ) -> Result<ExamQuestion, AppError> { | ||
| 1149 | - let (text, points, spec) = body(); | ||
| 1150 | - question.update(to.clone(), text, points, spec, db).await | ||
| 1151 | - } | ||
| 1152 | - | ||
| 1153 | - /// The stored `exam_question_count` on one subject, absent = zero. | ||
| 1154 | - async fn count_on(subject: &SubjectId, db: &Database) -> i64 { | ||
| 1155 | - let mut result = db | ||
| 1156 | - .query(format!( | ||
| 1157 | - "SELECT VALUE ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) FROM $sub" | ||
| 1158 | - )) | ||
| 1159 | - .bind(("sub", subject.record())) | ||
| 1160 | - .await | ||
| 1161 | - .unwrap() | ||
| 1162 | - .check() | ||
| 1163 | - .unwrap(); | ||
| 1164 | - result | ||
| 1165 | - .take::<Vec<i64>>(0) | ||
| 1166 | - .unwrap() | ||
| 1167 | - .first() | ||
| 1168 | - .copied() | ||
| 1169 | - .unwrap_or(0) | ||
| 1170 | - } | ||
| 1171 | - | ||
| 1172 | - async fn rows(sql: &str, db: &Database) -> usize { | ||
| 1173 | - let mut result = db.query(sql).await.unwrap().check().unwrap(); | ||
| 1174 | - result.take::<Vec<RecordId>>(0).unwrap().len() | ||
| 1175 | - } | ||
| 1176 | - | ||
| 1177 | - /// The freeze outranks the counter move, on both paths — and because | ||
| 1178 | - /// the claim now rides the refused transaction, "outranks" has to mean | ||
| 1179 | - /// the counters read as if nothing ran. | ||
| 1180 | - #[tokio::test] | ||
| 1181 | - async fn a_frozen_exam_leaves_the_subject_counters_untouched() { | ||
| 1182 | - let db = init_mem().await.unwrap(); | ||
| 1183 | - let exam = an_exam(&db).await; | ||
| 1184 | - let (from, to) = (a_subject(&db).await, a_subject(&db).await); | ||
| 1185 | - let (from, to) = (from.get_id().clone(), to.get_id().clone()); | ||
| 1186 | - let question = a_question(&exam, &from, &db).await; | ||
| 1187 | - assert_eq!(count_on(&from, &db).await, 1); | ||
| 1188 | - | ||
| 1189 | - // A real user row: starting a sitting moves that student's badge | ||
| 1190 | - // counter in the same transaction, and an `UPDATE` has nothing to | ||
| 1191 | - // write to without one. | ||
| 1192 | - let hash = crate::domain::user::Password::try_new("secret1") | ||
| 1193 | - .unwrap() | ||
| 1194 | - .hash_async() | ||
| 1195 | - .await | ||
| 1196 | - .unwrap(); | ||
| 1197 | - let student = crate::domain::user::User::create( | ||
| 1198 | - crate::domain::user::Username::try_new("ogrenci").unwrap(), | ||
| 1199 | - hash, | ||
| 1200 | - &db, | ||
| 1201 | - ) | ||
| 1202 | - .await | ||
| 1203 | - .unwrap(); | ||
| 1204 | - crate::service::exam_attempt::start(&db, &exam, student.get_id()) | ||
| 1205 | - .await | ||
| 1206 | - .unwrap(); | ||
| 1207 | - | ||
| 1208 | - let (text, points, spec) = body(); | ||
| 1209 | - let error = ExamQuestion::create(exam.get_id(), to.clone(), text, points, spec, &db) | ||
| 1210 | - .await | ||
| 1211 | - .expect_err("a started exam takes no new questions"); | ||
| 1212 | - assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); | ||
| 1213 | - assert_eq!(count_on(&to, &db).await, 0, "the refused claim rolled back"); | ||
| 1214 | - | ||
| 1215 | - let error = moved(question, &to, &db) | ||
| 1216 | - .await | ||
| 1217 | - .expect_err("a started exam takes no re-tag either"); | ||
| 1218 | - assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); | ||
| 1219 | - assert_eq!(count_on(&from, &db).await, 1, "the release rolled back too"); | ||
| 1220 | - assert_eq!(count_on(&to, &db).await, 0); | ||
| 1221 | - } | ||
| 1222 | - | ||
| 1223 | - /// The create-path invariant: a refused create writes neither the row | ||
| 1224 | - /// nor a count — least of all on a subject it would have to invent. | ||
| 1225 | - #[tokio::test] | ||
| 1226 | - async fn a_create_on_a_dead_subject_writes_neither_row_nor_count() { | ||
| 1227 | - let db = init_mem().await.unwrap(); | ||
| 1228 | - let exam = an_exam(&db).await; | ||
| 1229 | - let subject = a_subject(&db).await; | ||
| 1230 | - let id = subject.get_id().clone(); | ||
| 1231 | - subject.delete(&db).await.unwrap(); | ||
| 1232 | - | ||
| 1233 | - let (text, points, spec) = body(); | ||
| 1234 | - let error = ExamQuestion::create(exam.get_id(), id, text, points, spec, &db) | ||
| 1235 | - .await | ||
| 1236 | - .expect_err("a subject that is gone must not be taggable"); | ||
| 1237 | - assert!(error.to_string().contains("subject does not exist")); | ||
| 1238 | - assert_eq!( | ||
| 1239 | - rows("SELECT VALUE id FROM exam_question", &db).await, | ||
| 1240 | - 0, | ||
| 1241 | - "a refused create may write no row" | ||
| 1242 | - ); | ||
| 1243 | - assert_eq!( | ||
| 1244 | - rows("SELECT VALUE id FROM subject", &db).await, | ||
| 1245 | - 0, | ||
| 1246 | - "…and least of all a count on a subject it just brought back" | ||
| 1247 | - ); | ||
| 1248 | - } | ||
| 1249 | - | ||
| 1250 | - #[tokio::test] | ||
| 1251 | - async fn a_subject_move_moves_the_count() { | ||
| 1252 | - let db = init_mem().await.unwrap(); | ||
| 1253 | - let exam = an_exam(&db).await; | ||
| 1254 | - let (from, to) = (a_subject(&db).await, a_subject(&db).await); | ||
| 1255 | - let (from, to) = (from.get_id().clone(), to.get_id().clone()); | ||
| 1256 | - let question = a_question(&exam, &from, &db).await; | ||
| 1257 | - | ||
| 1258 | - let after = moved(question, &to, &db).await.unwrap(); | ||
| 1259 | - assert_eq!(after.get_subject(), &to); | ||
| 1260 | - assert_eq!(count_on(&from, &db).await, 0, "the old subject is free"); | ||
| 1261 | - assert_eq!(count_on(&to, &db).await, 1, "the new one is not"); | ||
| 1262 | - } | ||
| 1263 | - | ||
| 1264 | - #[tokio::test] | ||
| 1265 | - async fn a_move_to_a_dead_subject_leaves_everything_untouched() { | ||
| 1266 | - let db = init_mem().await.unwrap(); | ||
| 1267 | - let exam = an_exam(&db).await; | ||
| 1268 | - let from = a_subject(&db).await.get_id().clone(); | ||
| 1269 | - let dead = a_subject(&db).await; | ||
| 1270 | - let gone = dead.get_id().clone(); | ||
| 1271 | - dead.delete(&db).await.unwrap(); | ||
| 1272 | - let question = a_question(&exam, &from, &db).await; | ||
| 1273 | - | ||
| 1274 | - let error = moved(question.clone(), &gone, &db) | ||
| 1275 | - .await | ||
| 1276 | - .expect_err("a subject that is gone must not be taggable"); | ||
| 1277 | - assert!(error.to_string().contains("subject does not exist")); | ||
| 1278 | - let stored = ExamQuestion::read(question.get_id(), &db) | ||
| 1279 | - .await | ||
| 1280 | - .unwrap() | ||
| 1281 | - .unwrap(); | ||
| 1282 | - assert_eq!(stored.get_subject(), &from, "the link never moved"); | ||
| 1283 | - assert_eq!( | ||
| 1284 | - count_on(&from, &db).await, | ||
| 1285 | - 1, | ||
| 1286 | - "the release rolled back with the claim" | ||
| 1287 | - ); | ||
| 1288 | - assert_eq!(rows("SELECT VALUE id FROM subject", &db).await, 1); | ||
| 1289 | - } | ||
| 1290 | - | ||
| 1291 | - /// The double-claim guard. Both movers compute their claim and release | ||
| 1292 | - /// from the row as *they* read it, so two PATCHes re-tagging the same | ||
| 1293 | - /// question both release the old subject and both claim their own | ||
| 1294 | - /// target — two counts for one link, and the loser's target is | ||
| 1295 | - /// undeletable forever. The second call here runs on the struct read | ||
| 1296 | - /// before the first one landed: it must be refused outright, and the | ||
| 1297 | - /// counts must read as if it never ran. | ||
| 1298 | - /// | ||
| 1299 | - /// Drop `AND subject = $ref_expected` from the row write in | ||
| 1300 | - /// [`ExamQuestion::update`] and this goes red on the very first | ||
| 1301 | - /// assertion — the stale mover is happily applied. | ||
| 1302 | - #[tokio::test] | ||
| 1303 | - async fn a_stale_mover_is_refused_and_claims_nothing() { | ||
| 1304 | - let db = init_mem().await.unwrap(); | ||
| 1305 | - let exam = an_exam(&db).await; | ||
| 1306 | - let from = a_subject(&db).await.get_id().clone(); | ||
| 1307 | - let to = a_subject(&db).await.get_id().clone(); | ||
| 1308 | - let other = a_subject(&db).await.get_id().clone(); | ||
| 1309 | - let question = a_question(&exam, &from, &db).await; | ||
| 1310 | - let stale = question.clone(); | ||
| 1311 | - | ||
| 1312 | - moved(question, &to, &db).await.unwrap(); | ||
| 1313 | - let error = moved(stale.clone(), &other, &db) | ||
| 1314 | - .await | ||
| 1315 | - .expect_err("a mover that read a subject it no longer holds must be refused"); | ||
| 1316 | - assert!( | ||
| 1317 | - matches!(error, AppError::Conflict(_)), | ||
| 1318 | - "a lost CAS is a conflict, not a 404 or a 500: {error:?}" | ||
| 1319 | - ); | ||
| 1320 | - | ||
| 1321 | - let stored = ExamQuestion::read(stale.get_id(), &db) | ||
| 1322 | - .await | ||
| 1323 | - .unwrap() | ||
| 1324 | - .unwrap(); | ||
| 1325 | - assert_eq!(stored.get_subject(), &to, "the winner's link"); | ||
| 1326 | - assert_eq!(count_on(&from, &db).await, 0, "released once, not twice"); | ||
| 1327 | - assert_eq!(count_on(&to, &db).await, 1, "claimed once"); | ||
| 1328 | - assert_eq!(count_on(&other, &db).await, 0, "never claimed"); | ||
| 1329 | - } | ||
| 1330 | - | ||
| 1331 | - /// The other half of the same race, and the one arming on "the subject | ||
| 1332 | - /// changed" lets through: this PATCH carries the subject its snapshot | ||
| 1333 | - /// already held, so it moves no counter — but a rival's move landed | ||
| 1334 | - /// first, and writing that stale subject back would revert the winner | ||
| 1335 | - /// while both counters still describe the move. The handler fills an | ||
| 1336 | - /// omitted `subject_id` from the row it read, so this is also every | ||
| 1337 | - /// text-only PATCH sent from a stale snapshot. | ||
| 1338 | - /// | ||
| 1339 | - /// Arm the CAS on the re-tag instead of on the write and this goes red | ||
| 1340 | - /// on the first assertion — the re-state lands 200. | ||
| 1341 | - #[tokio::test] | ||
| 1342 | - async fn a_stale_re_stater_is_refused_and_reverts_nothing() { | ||
| 1343 | - let db = init_mem().await.unwrap(); | ||
| 1344 | - let exam = an_exam(&db).await; | ||
| 1345 | - let from = a_subject(&db).await.get_id().clone(); | ||
| 1346 | - let to = a_subject(&db).await.get_id().clone(); | ||
| 1347 | - let question = a_question(&exam, &from, &db).await; | ||
| 1348 | - let stale = question.clone(); | ||
| 1349 | - | ||
| 1350 | - moved(question, &to, &db).await.unwrap(); | ||
| 1351 | - let error = moved(stale.clone(), &from, &db) | ||
| 1352 | - .await | ||
| 1353 | - .expect_err("re-stating a subject a rival moved off must be refused"); | ||
| 1354 | - assert!( | ||
| 1355 | - matches!(error, AppError::Conflict(_)), | ||
| 1356 | - "a lost CAS is a conflict, not a silent revert: {error:?}" | ||
| 1357 | - ); | ||
| 1358 | - | ||
| 1359 | - let stored = ExamQuestion::read(stale.get_id(), &db) | ||
| 1360 | - .await | ||
| 1361 | - .unwrap() | ||
| 1362 | - .unwrap(); | ||
| 1363 | - assert_eq!(stored.get_subject(), &to, "the winner's link stands"); | ||
| 1364 | - assert_eq!( | ||
| 1365 | - count_on(&from, &db).await, | ||
| 1366 | - 0, | ||
| 1367 | - "released once, and stayed so" | ||
| 1368 | - ); | ||
| 1369 | - assert_eq!(count_on(&to, &db).await, 1, "claimed once, and stayed so"); | ||
| 1370 | - } | ||
| 1371 | - | ||
| 1372 | - /// …and the price of arming the CAS on every write is nothing: a PATCH | ||
| 1373 | - /// re-stating the subject the row really holds passes it trivially. | ||
| 1374 | - #[tokio::test] | ||
| 1375 | - async fn a_no_op_re_state_still_lands() { | ||
| 1376 | - let db = init_mem().await.unwrap(); | ||
| 1377 | - let exam = an_exam(&db).await; | ||
| 1378 | - let on = a_subject(&db).await.get_id().clone(); | ||
| 1379 | - let question = a_question(&exam, &on, &db).await; | ||
| 1380 | - | ||
| 1381 | - let (_, points, spec) = body(); | ||
| 1382 | - let after = question | ||
| 1383 | - .update( | ||
| 1384 | - on.clone(), | ||
| 1385 | - QuestionText::try_new("4 + 4?").unwrap(), | ||
| 1386 | - points, | ||
| 1387 | - spec, | ||
| 1388 | - &db, | ||
| 1389 | - ) | ||
| 1390 | - .await | ||
| 1391 | - .expect("re-stating the subject the row holds is not a conflict"); | ||
| 1392 | - assert_eq!(after.get_text().as_str(), "4 + 4?"); | ||
| 1393 | - assert_eq!(after.get_subject(), &on); | ||
| 1394 | - assert_eq!(count_on(&on, &db).await, 1, "no counter moved"); | ||
| 1395 | - } | ||
| 1396 | - | ||
| 1397 | - /// A re-tag of a question whose row is gone is still the 404 it was, | ||
| 1398 | - /// not the stale-mover 409 — the two empty-`$row` cases stay apart. | ||
| 1399 | - #[tokio::test] | ||
| 1400 | - async fn a_move_of_a_deleted_question_is_still_a_404() { | ||
| 1401 | - let db = init_mem().await.unwrap(); | ||
| 1402 | - let exam = an_exam(&db).await; | ||
| 1403 | - let from = a_subject(&db).await.get_id().clone(); | ||
| 1404 | - let to = a_subject(&db).await.get_id().clone(); | ||
| 1405 | - let question = a_question(&exam, &from, &db).await; | ||
| 1406 | - question.clone().delete(&db).await.unwrap(); | ||
| 1407 | - | ||
| 1408 | - let error = moved(question, &to, &db) | ||
| 1409 | - .await | ||
| 1410 | - .expect_err("a deleted question cannot be re-tagged"); | ||
| 1411 | - assert!(matches!(error, AppError::NotFound), "{error:?}"); | ||
| 1412 | - assert_eq!(count_on(&to, &db).await, 0, "and nothing was claimed"); | ||
| 1413 | - } | ||
| 1414 | - } | ||
| 1415 | - | ||
| 1416 | #[tokio::test] | 714 | #[tokio::test] |
| 1417 | async fn spec_rejects_blank_or_oversized_choices() { | 715 | async fn spec_rejects_blank_or_oversized_choices() { |
| 1418 | let with = |text: String| { | 716 | let with = |text: String| { |
src/domain/subject.rsmodified+12 -10
| @@ -5,10 +5,10 @@ use crate::constant::{ | |||
| 5 | }; | 5 | }; |
| 6 | use crate::database::{Database, transaction_with_retry}; | 6 | use crate::database::{Database, transaction_with_retry}; |
| 7 | use crate::db::cap; | 7 | use crate::db::cap; |
| 8 | -use crate::domain::course::CourseId; | ||
| 9 | use crate::db::field_update::FieldUpdate; | 8 | use crate::db::field_update::FieldUpdate; |
| 10 | -use crate::domain::monotonic_id::next_ulid; | ||
| 11 | use crate::db::page::PagedList; | 9 | use crate::db::page::PagedList; |
| 10 | +use crate::domain::course::CourseId; | ||
| 11 | +use crate::domain::monotonic_id::next_ulid; | ||
| 12 | use crate::error::{AppError, ValidationError}; | 12 | use crate::error::{AppError, ValidationError}; |
| 13 | use crate::validate::{validate_optional, validate_required}; | 13 | use crate::validate::{validate_optional, validate_required}; |
| 14 | 14 | ||
| @@ -281,9 +281,11 @@ mod tests { | |||
| 281 | .map(|_| ()) | 281 | .map(|_| ()) |
| 282 | }) | 282 | }) |
| 283 | } | 283 | } |
| 284 | - crate::db::course::assert_no_child_outlives_a_course_delete("subject_orphan_race", | 284 | + crate::db::course::assert_no_child_outlives_a_course_delete( |
| 285 | - SUBJECT_TABLE, | 285 | + "subject_orphan_race", |
| 286 | - make,) | 286 | + SUBJECT_TABLE, |
| 287 | + make, | ||
| 288 | + ) | ||
| 287 | .await; | 289 | .await; |
| 288 | } | 290 | } |
| 289 | 291 | ||
| @@ -322,7 +324,7 @@ mod tests { | |||
| 322 | /// is counted rather than asserted per round, and why this needs the real | 324 | /// is counted rather than asserted per round, and why this needs the real |
| 323 | /// server and a multi-threaded runtime. | 325 | /// server and a multi-threaded runtime. |
| 324 | /// | 326 | /// |
| 325 | - /// The racer is [`ExamQuestion::create`], which claims the subject's | 327 | + /// The racer is [`crate::db::exam_question::create`], which claims the subject's |
| 326 | /// question reference *before* it writes the row — a conditional write on | 328 | /// question reference *before* it writes the row — a conditional write on |
| 327 | /// the same record the delete's `WHERE` reads. `Err(Conflict)` (still | 329 | /// the same record the delete's `WHERE` reads. `Err(Conflict)` (still |
| 328 | /// referenced), `Err(NotFound)` and the claim's `Validation` miss are all | 330 | /// referenced), `Err(NotFound)` and the claim's `Validation` miss are all |
| @@ -345,7 +347,7 @@ mod tests { | |||
| 345 | #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | 347 | #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] |
| 346 | async fn a_delete_racing_a_question_never_answers_500() { | 348 | async fn a_delete_racing_a_question_never_answers_500() { |
| 347 | use crate::domain::exam_question::{ | 349 | use crate::domain::exam_question::{ |
| 348 | - ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, | 350 | + QuestionKind, QuestionPoints, QuestionSpec, QuestionText, |
| 349 | }; | 351 | }; |
| 350 | let (db, _serialized) = crate::database::init_test_server("subject_delete_race").await; | 352 | let (db, _serialized) = crate::database::init_test_server("subject_delete_race").await; |
| 351 | let (mut delete_500, mut question_500) = (0, 0); | 353 | let (mut delete_500, mut question_500) = (0, 0); |
| @@ -398,7 +400,8 @@ mod tests { | |||
| 398 | }; | 400 | }; |
| 399 | tokio::spawn(async move { | 401 | tokio::spawn(async move { |
| 400 | tokio::time::sleep(head_start).await; | 402 | tokio::time::sleep(head_start).await; |
| 401 | - ExamQuestion::create( | 403 | + crate::db::exam_question::create( |
| 404 | + &db, | ||
| 402 | &exam, | 405 | &exam, |
| 403 | id, | 406 | id, |
| 404 | QuestionText::try_new("why").unwrap(), | 407 | QuestionText::try_new("why").unwrap(), |
| @@ -410,7 +413,6 @@ mod tests { | |||
| 410 | &[], | 413 | &[], |
| 411 | ) | 414 | ) |
| 412 | .unwrap(), | 415 | .unwrap(), |
| 413 | - &db, | ||
| 414 | ) | 416 | ) |
| 415 | .await | 417 | .await |
| 416 | }) | 418 | }) |
| @@ -438,7 +440,7 @@ mod tests { | |||
| 438 | { | 440 | { |
| 439 | wiped += 1; | 441 | wiped += 1; |
| 440 | } | 442 | } |
| 441 | - if !ExamQuestion::list_for_exam(&exam, None, 0, &db) | 443 | + if !crate::db::exam_question::list_for_exam(&db, &exam, None, 0) |
| 442 | .await | 444 | .await |
| 443 | .unwrap() | 445 | .unwrap() |
| 444 | .0 | 446 | .0 |
src/service/exam_attempt.rsmodified+4 -20
| @@ -12,7 +12,6 @@ use crate::domain::enrollment::Enrollment; | |||
| 12 | use crate::domain::exam::{Exam, ExamId}; | 12 | use crate::domain::exam::{Exam, ExamId}; |
| 13 | use crate::domain::exam_answer::ExamAnswer; | 13 | use crate::domain::exam_answer::ExamAnswer; |
| 14 | use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId}; | 14 | use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId}; |
| 15 | -use crate::domain::exam_question::{ExamQuestion, ExamQuestionId}; | ||
| 16 | use crate::domain::role::Role; | 15 | use crate::domain::role::Role; |
| 17 | use crate::domain::timestamp::Timestamp; | 16 | use crate::domain::timestamp::Timestamp; |
| 18 | use crate::domain::user::{User, UserId}; | 17 | use crate::domain::user::{User, UserId}; |
| @@ -148,22 +147,6 @@ pub async fn course_of(exam: &Exam, db: &Database) -> Result<Course, AppError> { | |||
| 148 | .ok_or_else(|| AppError::Internal("exam references a missing course".into())) | 147 | .ok_or_else(|| AppError::Internal("exam references a missing course".into())) |
| 149 | } | 148 | } |
| 150 | 149 | ||
| 151 | -/// The question, provided it belongs to `exam` — a qid under someone else's | ||
| 152 | -/// exam is a plain 404, not a leak. | ||
| 153 | -pub async fn question_of_exam( | ||
| 154 | - exam: &ExamId, | ||
| 155 | - qid: &str, | ||
| 156 | - db: &Database, | ||
| 157 | -) -> Result<ExamQuestion, AppError> { | ||
| 158 | - let question = ExamQuestion::read(&ExamQuestionId::from_key(qid), db) | ||
| 159 | - .await? | ||
| 160 | - .ok_or(AppError::NotFound)?; | ||
| 161 | - if question.get_exam() != exam { | ||
| 162 | - return Err(AppError::NotFound); | ||
| 163 | - } | ||
| 164 | - Ok(question) | ||
| 165 | -} | ||
| 166 | - | ||
| 167 | /// Start, resume, or retake `user`'s attempt at `exam`. Returns the attempt | 150 | /// Start, resume, or retake `user`'s attempt at `exam`. Returns the attempt |
| 168 | /// plus whether it was newly created. | 151 | /// plus whether it was newly created. |
| 169 | /// | 152 | /// |
| @@ -400,7 +383,8 @@ pub async fn save_answer_in( | |||
| 400 | ensure_enrolled(exam, attempt.get_user(), db).await?; | 383 | ensure_enrolled(exam, attempt.get_user(), db).await?; |
| 401 | check_rejoin(exam, attempt)?; | 384 | check_rejoin(exam, attempt)?; |
| 402 | crate::service::course::require_open(db, &course_of(exam, db).await?).await?; | 385 | crate::service::course::require_open(db, &course_of(exam, db).await?).await?; |
| 403 | - let question = question_of_exam(exam.get_id(), question_id, db).await?; | 386 | + let question = |
| 387 | + crate::service::exam_question::question_of_exam(exam.get_id(), question_id, db).await?; | ||
| 404 | crate::domain::exam_answer::ExamAnswer::save( | 388 | crate::domain::exam_answer::ExamAnswer::save( |
| 405 | &question, | 389 | &question, |
| 406 | attempt.get_user(), | 390 | attempt.get_user(), |
| @@ -547,13 +531,13 @@ mod tests { | |||
| 547 | ) | 531 | ) |
| 548 | .await | 532 | .await |
| 549 | .unwrap(); | 533 | .unwrap(); |
| 550 | - let question = ExamQuestion::create( | 534 | + let question = crate::db::exam_question::create( |
| 535 | + db, | ||
| 551 | exam.get_id(), | 536 | exam.get_id(), |
| 552 | subject.get_id().clone(), | 537 | subject.get_id().clone(), |
| 553 | crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(), | 538 | crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(), |
| 554 | QuestionPoints::try_new(5).unwrap(), | 539 | QuestionPoints::try_new(5).unwrap(), |
| 555 | spec, | 540 | spec, |
| 556 | - db, | ||
| 557 | ) | 541 | ) |
| 558 | .await | 542 | .await |
| 559 | .unwrap(); | 543 | .unwrap(); |
src/service/exam_question.rsadded+134 -0
| @@ -0,0 +1,134 @@ | |||
| 1 | +//! Exam-question authoring rules: the freeze pre-flight every authoring path | ||
| 2 | +//! runs, the question-lookup and option-addressing gates, and the read and | ||
| 3 | +//! write funnels the web layer goes through. The queries and their | ||
| 4 | +//! transactions live in [`crate::db::exam_question`]; the HTTP shaping stays | ||
| 5 | +//! in the web layer. | ||
| 6 | + | ||
| 7 | +use crate::database::Database; | ||
| 8 | +use crate::domain::bank_question::BankQuestionId; | ||
| 9 | +use crate::domain::exam::ExamId; | ||
| 10 | +use crate::domain::exam_question::{ | ||
| 11 | + ChoiceId, ExamQuestion, ExamQuestionId, QuestionPoints, QuestionSpec, QuestionText, | ||
| 12 | +}; | ||
| 13 | +use crate::domain::subject::SubjectId; | ||
| 14 | +use crate::error::{AppError, ValidationError}; | ||
| 15 | + | ||
| 16 | +/// The questions freeze once anyone has started an attempt — editing them | ||
| 17 | +/// under a student mid-exam would fork what "the exam" means. | ||
| 18 | +pub async fn ensure_questions_editable(exam: &ExamId, db: &Database) -> Result<(), AppError> { | ||
| 19 | + if crate::service::exam_attempt::any_for_exam(db, exam).await? { | ||
| 20 | + return Err(AppError::Conflict( | ||
| 21 | + "cannot change questions after attempts have started", | ||
| 22 | + )); | ||
| 23 | + } | ||
| 24 | + Ok(()) | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +/// The question's option named by `choice_id` — a 400 for a text question or an | ||
| 28 | +/// id the question doesn't have, so an option picture can only ever be | ||
| 29 | +/// addressed through an option that exists. | ||
| 30 | +pub fn choice_slot(question: &ExamQuestion, choice_id: &str) -> Result<ChoiceId, AppError> { | ||
| 31 | + let Some(choices) = question.get_choices() else { | ||
| 32 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 33 | + field: "choice_id", | ||
| 34 | + reason: "only choice questions take option pictures", | ||
| 35 | + })); | ||
| 36 | + }; | ||
| 37 | + choices | ||
| 38 | + .iter() | ||
| 39 | + .find(|choice| choice.get_id().as_str() == choice_id) | ||
| 40 | + .map(|choice| choice.get_id().clone()) | ||
| 41 | + .ok_or(AppError::Validation(ValidationError::Invalid { | ||
| 42 | + field: "choice_id", | ||
| 43 | + reason: "must name one of the choices", | ||
| 44 | + })) | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// The question, provided it belongs to `exam` — a qid under someone else's | ||
| 48 | +/// exam is a plain 404, not a leak. | ||
| 49 | +pub async fn question_of_exam( | ||
| 50 | + exam: &ExamId, | ||
| 51 | + qid: &str, | ||
| 52 | + db: &Database, | ||
| 53 | +) -> Result<ExamQuestion, AppError> { | ||
| 54 | + let question = crate::db::exam_question::read(db, &ExamQuestionId::from_key(qid)) | ||
| 55 | + .await? | ||
| 56 | + .ok_or(AppError::NotFound)?; | ||
| 57 | + if question.get_exam() != exam { | ||
| 58 | + return Err(AppError::NotFound); | ||
| 59 | + } | ||
| 60 | + Ok(question) | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +/// Add a question to an exam. The freeze gate and the subject's reference | ||
| 64 | +/// counter ride in the write's own transaction. | ||
| 65 | +pub async fn create( | ||
| 66 | + db: &Database, | ||
| 67 | + exam: &ExamId, | ||
| 68 | + subject: SubjectId, | ||
| 69 | + text: QuestionText, | ||
| 70 | + points: QuestionPoints, | ||
| 71 | + spec: QuestionSpec, | ||
| 72 | +) -> Result<ExamQuestion, AppError> { | ||
| 73 | + crate::db::exam_question::create(db, exam, subject, text, points, spec).await | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// Like [`create`], but records the bank template the question was | ||
| 77 | +/// instantiated from. | ||
| 78 | +pub async fn create_from_bank( | ||
| 79 | + db: &Database, | ||
| 80 | + exam: &ExamId, | ||
| 81 | + subject: SubjectId, | ||
| 82 | + text: QuestionText, | ||
| 83 | + points: QuestionPoints, | ||
| 84 | + spec: QuestionSpec, | ||
| 85 | + source: BankQuestionId, | ||
| 86 | +) -> Result<ExamQuestion, AppError> { | ||
| 87 | + crate::db::exam_question::create_from_bank(db, exam, subject, text, points, spec, source).await | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +/// The exam's questions in presentation order — the web layer's paging read. | ||
| 91 | +pub async fn list_for_exam( | ||
| 92 | + db: &Database, | ||
| 93 | + exam: &ExamId, | ||
| 94 | + limit: Option<i64>, | ||
| 95 | + offset: i64, | ||
| 96 | +) -> Result<(Vec<ExamQuestion>, i64), AppError> { | ||
| 97 | + crate::db::exam_question::list_for_exam(db, exam, limit, offset).await | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +/// The question ids of `exam` sharing a bank template with a question under | ||
| 101 | +/// one of `live` — the review hiding key. | ||
| 102 | +pub async fn list_shared_with( | ||
| 103 | + db: &Database, | ||
| 104 | + exam: &ExamId, | ||
| 105 | + live: &[ExamId], | ||
| 106 | +) -> Result<std::collections::HashSet<String>, AppError> { | ||
| 107 | + crate::db::exam_question::list_shared_with(db, exam, live).await | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +/// Write the editable fields; a stale read is a 409, nothing was written. | ||
| 111 | +pub async fn update( | ||
| 112 | + db: &Database, | ||
| 113 | + question: ExamQuestion, | ||
| 114 | + subject: SubjectId, | ||
| 115 | + text: QuestionText, | ||
| 116 | + points: QuestionPoints, | ||
| 117 | + spec: QuestionSpec, | ||
| 118 | +) -> Result<ExamQuestion, AppError> { | ||
| 119 | + crate::db::exam_question::update(db, question, subject, text, points, spec).await | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +/// Delete the question and cascade its answers and image rows. | ||
| 123 | +pub async fn delete(db: &Database, question: ExamQuestion) -> Result<ExamQuestion, AppError> { | ||
| 124 | + crate::db::exam_question::delete(db, question).await | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +/// Point the question's `banked_as` at the bank template it was saved into. | ||
| 128 | +pub async fn link_banked_as( | ||
| 129 | + db: &Database, | ||
| 130 | + question: ExamQuestion, | ||
| 131 | + template: BankQuestionId, | ||
| 132 | +) -> Result<ExamQuestion, AppError> { | ||
| 133 | + crate::db::exam_question::link_banked_as(db, question, template).await | ||
| 134 | +} | ||
src/service/mod.rsmodified+1 -0
| @@ -7,6 +7,7 @@ pub mod class_blueprint; | |||
| 7 | pub mod course; | 7 | pub mod course; |
| 8 | pub mod course_session; | 8 | pub mod course_session; |
| 9 | pub mod exam_attempt; | 9 | pub mod exam_attempt; |
| 10 | +pub mod exam_question; | ||
| 10 | pub mod note; | 11 | pub mod note; |
| 11 | pub mod payment_ledger; | 12 | pub mod payment_ledger; |
| 12 | pub mod session; | 13 | pub mod session; |
src/web/exam_ws.rsmodified+3 -3
| @@ -68,7 +68,6 @@ use crate::database::Database; | |||
| 68 | use crate::domain::exam::{Exam, ExamId}; | 68 | use crate::domain::exam::{Exam, ExamId}; |
| 69 | use crate::domain::exam_answer::ExamAnswer; | 69 | use crate::domain::exam_answer::ExamAnswer; |
| 70 | use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId}; | 70 | use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId}; |
| 71 | -use crate::domain::exam_question::ExamQuestion; | ||
| 72 | use crate::domain::timestamp::Timestamp; | 71 | use crate::domain::timestamp::Timestamp; |
| 73 | use crate::domain::user::UserId; | 72 | use crate::domain::user::UserId; |
| 74 | use crate::error::AppError; | 73 | use crate::error::AppError; |
| @@ -340,7 +339,7 @@ async fn state_frame( | |||
| 340 | ExamAnswer::list_for_exam_user(exam.get_id(), attempt.get_user(), attempt.get_seq(), db) | 339 | ExamAnswer::list_for_exam_user(exam.get_id(), attempt.get_user(), attempt.get_seq(), db) |
| 341 | .await? | 340 | .await? |
| 342 | .len(); | 341 | .len(); |
| 343 | - let question_count = ExamQuestion::list_for_exam(exam.get_id(), None, 0, db) | 342 | + let question_count = crate::service::exam_question::list_for_exam(db, exam.get_id(), None, 0) |
| 344 | .await? | 343 | .await? |
| 345 | .0 | 344 | .0 |
| 346 | .len(); | 345 | .len(); |
| @@ -461,7 +460,8 @@ async fn handle_message( | |||
| 461 | // same error frame as every other conflict. | 460 | // same error frame as every other conflict. |
| 462 | async { | 461 | async { |
| 463 | let attempt = writable_room_attempt(&exam, attempt_id, user, db).await?; | 462 | let attempt = writable_room_attempt(&exam, attempt_id, user, db).await?; |
| 464 | - crate::service::course::require_open(db, &course_of(&exam, db).await?).await?; | 463 | + crate::service::course::require_open(db, &course_of(&exam, db).await?) |
| 464 | + .await?; | ||
| 465 | finish(db, attempt).await | 465 | finish(db, attempt).await |
| 466 | } | 466 | } |
| 467 | .await | 467 | .await |
src/web/exams/attempts.rsmodified+6 -4
| @@ -105,7 +105,7 @@ pub(crate) async fn attempt_progress( | |||
| 105 | let answered = ExamAnswer::list_for_exam_user(exam, user, seq, db) | 105 | let answered = ExamAnswer::list_for_exam_user(exam, user, seq, db) |
| 106 | .await? | 106 | .await? |
| 107 | .len() as u64; | 107 | .len() as u64; |
| 108 | - let question_count = ExamQuestion::list_for_exam(exam, None, 0, db) | 108 | + let question_count = crate::service::exam_question::list_for_exam(db, exam, None, 0) |
| 109 | .await? | 109 | .await? |
| 110 | .0 | 110 | .0 |
| 111 | .len() as u64; | 111 | .len() as u64; |
| @@ -356,7 +356,7 @@ pub(crate) async fn live_snapshot( | |||
| 356 | ) | 356 | ) |
| 357 | }) | 357 | }) |
| 358 | .collect(); | 358 | .collect(); |
| 359 | - let question_count = ExamQuestion::list_for_exam(exam.get_id(), None, 0, db) | 359 | + let question_count = crate::service::exam_question::list_for_exam(db, exam.get_id(), None, 0) |
| 360 | .await? | 360 | .await? |
| 361 | .0 | 361 | .0 |
| 362 | .len() as u64; | 362 | .len() as u64; |
| @@ -583,7 +583,8 @@ pub(crate) async fn attempt_questions( | |||
| 583 | .ok_or(AppError::NotFound)? | 583 | .ok_or(AppError::NotFound)? |
| 584 | .get_seq(); | 584 | .get_seq(); |
| 585 | 585 | ||
| 586 | - let (questions, _) = ExamQuestion::list_for_exam(exam.get_id(), None, 0, &st.db).await?; | 586 | + let (questions, _) = |
| 587 | + crate::service::exam_question::list_for_exam(&st.db, exam.get_id(), None, 0).await?; | ||
| 587 | let images = images_by_question(exam.get_id(), &st.db).await?; | 588 | let images = images_by_question(exam.get_id(), &st.db).await?; |
| 588 | let answers: HashMap<String, ExamAnswer> = | 589 | let answers: HashMap<String, ExamAnswer> = |
| 589 | ExamAnswer::list_for_exam_user(exam.get_id(), user.get_id(), seq, &st.db) | 590 | ExamAnswer::list_for_exam_user(exam.get_id(), user.get_id(), seq, &st.db) |
| @@ -743,7 +744,8 @@ pub(crate) async fn answer_sheet( | |||
| 743 | hidden: &HashSet<String>, | 744 | hidden: &HashSet<String>, |
| 744 | db: &Database, | 745 | db: &Database, |
| 745 | ) -> Result<AttemptAnswersResponse, AppError> { | 746 | ) -> Result<AttemptAnswersResponse, AppError> { |
| 746 | - let (mut questions, _) = ExamQuestion::list_for_exam(exam.get_id(), None, 0, db).await?; | 747 | + let (mut questions, _) = |
| 748 | + crate::service::exam_question::list_for_exam(db, exam.get_id(), None, 0).await?; | ||
| 747 | questions.retain(|question| !hidden.contains(question.get_id().key())); | 749 | questions.retain(|question| !hidden.contains(question.get_id().key())); |
| 748 | let answers = ExamAnswer::list_for_exam_user(exam.get_id(), target, seq, db).await?; | 750 | let answers = ExamAnswer::list_for_exam_user(exam.get_id(), target, seq, db).await?; |
| 749 | let answer_images: HashMap<String, AnswerImage> = | 751 | let answer_images: HashMap<String, AnswerImage> = |
src/web/exams/images.rsmodified+2 -1
| @@ -2,8 +2,9 @@ use super::*; | |||
| 2 | 2 | ||
| 3 | use crate::service::exam_attempt::{ | 3 | use crate::service::exam_attempt::{ |
| 4 | EXAM_LOCK, check_rejoin, course_of, ensure_enrolled, ensure_student, ensure_student_now, | 4 | EXAM_LOCK, check_rejoin, course_of, ensure_enrolled, ensure_student, ensure_student_now, |
| 5 | - question_of_exam, read_latest_for_user, writable_attempt, | 5 | + read_latest_for_user, writable_attempt, |
| 6 | }; | 6 | }; |
| 7 | +use crate::service::exam_question::{choice_slot, ensure_questions_editable, question_of_exam}; | ||
| 7 | 8 | ||
| 8 | /// A stored question image's metadata; the bytes come from the image | 9 | /// A stored question image's metadata; the bytes come from the image |
| 9 | /// endpoints (`GET .../image`, `GET .../choices/{choice_id}/image`). | 10 | /// endpoints (`GET .../image`, `GET .../choices/{choice_id}/image`). |
src/web/exams/questions.rsmodified+30 -65
| @@ -1,7 +1,6 @@ | |||
| 1 | use super::*; | 1 | use super::*; |
| 2 | 2 | ||
| 3 | -use crate::service::exam_attempt; | 3 | +use crate::service::exam_question; |
| 4 | -use crate::service::exam_attempt::question_of_exam; | ||
| 5 | 4 | ||
| 6 | // ---- questions -------------------------------------------------------------- | 5 | // ---- questions -------------------------------------------------------------- |
| 7 | // Teachers author the question list before the exam runs; it freezes the | 6 | // Teachers author the question list before the exam runs; it freezes the |
| @@ -135,40 +134,6 @@ impl QuestionResponse { | |||
| 135 | } | 134 | } |
| 136 | } | 135 | } |
| 137 | 136 | ||
| 138 | -/// The questions freeze once anyone has started an attempt — editing them | ||
| 139 | -/// under a student mid-exam would fork what "the exam" means. | ||
| 140 | -pub(crate) async fn ensure_questions_editable( | ||
| 141 | - exam: &ExamId, | ||
| 142 | - db: &Database, | ||
| 143 | -) -> Result<(), AppError> { | ||
| 144 | - if exam_attempt::any_for_exam(db, exam).await? { | ||
| 145 | - return Err(AppError::Conflict( | ||
| 146 | - "cannot change questions after attempts have started", | ||
| 147 | - )); | ||
| 148 | - } | ||
| 149 | - Ok(()) | ||
| 150 | -} | ||
| 151 | - | ||
| 152 | -/// The question's option named by `choice_id` — a 400 for a text question or an | ||
| 153 | -/// id the question doesn't have, so an option picture can only ever be | ||
| 154 | -/// addressed through an option that exists. | ||
| 155 | -pub(crate) fn choice_slot(question: &ExamQuestion, choice_id: &str) -> Result<ChoiceId, AppError> { | ||
| 156 | - let Some(choices) = question.get_choices() else { | ||
| 157 | - return Err(AppError::Validation(ValidationError::Invalid { | ||
| 158 | - field: "choice_id", | ||
| 159 | - reason: "only choice questions take option pictures", | ||
| 160 | - })); | ||
| 161 | - }; | ||
| 162 | - choices | ||
| 163 | - .iter() | ||
| 164 | - .find(|choice| choice.get_id().as_str() == choice_id) | ||
| 165 | - .map(|choice| choice.get_id().clone()) | ||
| 166 | - .ok_or(AppError::Validation(ValidationError::Invalid { | ||
| 167 | - field: "choice_id", | ||
| 168 | - reason: "must name one of the choices", | ||
| 169 | - })) | ||
| 170 | -} | ||
| 171 | - | ||
| 172 | /// Add a question to an exam. Requires teacher+ and management rights over the | 137 | /// Add a question to an exam. Requires teacher+ and management rights over the |
| 173 | /// exam's course. `subject_id` must name one of the course's subjects | 138 | /// exam's course. `subject_id` must name one of the course's subjects |
| 174 | /// (`GET /courses/{id}/subjects`) — every question belongs to a subject. | 139 | /// (`GET /courses/{id}/subjects`) — every question belongs to a subject. |
| @@ -211,7 +176,7 @@ pub(crate) async fn create_question( | |||
| 211 | // and the insert takes the subject's reference counter in the same breath — | 176 | // and the insert takes the subject's reference counter in the same breath — |
| 212 | // a subject delete lands either wholly before it (400) or is refused. The | 177 | // a subject delete lands either wholly before it (400) or is refused. The |
| 213 | // freeze gate rides inside the insert's own transaction. | 178 | // freeze gate rides inside the insert's own transaction. |
| 214 | - ensure_questions_editable(exam.get_id(), &st.db).await?; | 179 | + exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; |
| 215 | 180 | ||
| 216 | let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; | 181 | let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; |
| 217 | let text = QuestionText::try_new(&req.text)?; | 182 | let text = QuestionText::try_new(&req.text)?; |
| @@ -224,7 +189,8 @@ pub(crate) async fn create_question( | |||
| 224 | req.correct, | 189 | req.correct, |
| 225 | &[], | 190 | &[], |
| 226 | )?; | 191 | )?; |
| 227 | - let question = ExamQuestion::create(exam.get_id(), subject, text, points, spec, &st.db).await?; | 192 | + let question = |
| 193 | + exam_question::create(&st.db, exam.get_id(), subject, text, points, spec).await?; | ||
| 228 | // A question is born imageless — uploads come after, against its id. | 194 | // A question is born imageless — uploads come after, against its id. |
| 229 | Ok(( | 195 | Ok(( |
| 230 | StatusCode::CREATED, | 196 | StatusCode::CREATED, |
| @@ -283,7 +249,7 @@ pub(crate) async fn question_page( | |||
| 283 | hidden: &HashSet<String>, | 249 | hidden: &HashSet<String>, |
| 284 | db: &Database, | 250 | db: &Database, |
| 285 | ) -> Result<Page<QuestionResponse>, AppError> { | 251 | ) -> Result<Page<QuestionResponse>, AppError> { |
| 286 | - let (questions, total) = ExamQuestion::list_for_exam(exam.get_id(), limit, offset, db).await?; | 252 | + let (questions, total) = exam_question::list_for_exam(db, exam.get_id(), limit, offset).await?; |
| 287 | let images = images_by_question(exam.get_id(), db).await?; | 253 | let images = images_by_question(exam.get_id(), db).await?; |
| 288 | let items = questions | 254 | let items = questions |
| 289 | .iter() | 255 | .iter() |
| @@ -348,8 +314,8 @@ pub(crate) async fn update_question( | |||
| 348 | crate::service::course::require_open(&st.db, &course).await?; | 314 | crate::service::course::require_open(&st.db, &course).await?; |
| 349 | // No lease — see `create_question`; a re-tag moves the subject's reference | 315 | // No lease — see `create_question`; a re-tag moves the subject's reference |
| 350 | // counter, and the freeze gate rides in the update's transaction. | 316 | // counter, and the freeze gate rides in the update's transaction. |
| 351 | - ensure_questions_editable(exam.get_id(), &st.db).await?; | 317 | + exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; |
| 352 | - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; | 318 | + let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; |
| 353 | 319 | ||
| 354 | let subject = match req.subject_id { | 320 | let subject = match req.subject_id { |
| 355 | Some(ref subject_id) => subject_in_course(subject_id, course.get_id(), &st.db).await?, | 321 | Some(ref subject_id) => subject_in_course(subject_id, course.get_id(), &st.db).await?, |
| @@ -382,7 +348,7 @@ pub(crate) async fn update_question( | |||
| 382 | let stored: Vec<Choice> = question.get_choices().unwrap_or_default().to_vec(); | 348 | let stored: Vec<Choice> = question.get_choices().unwrap_or_default().to_vec(); |
| 383 | let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?; | 349 | let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?; |
| 384 | 350 | ||
| 385 | - let updated = question.update(subject, text, points, spec, &st.db).await?; | 351 | + let updated = exam_question::update(&st.db, question, subject, text, points, spec).await?; |
| 386 | // Only the options that are actually *gone* lose their pictures: keyed by | 352 | // Only the options that are actually *gone* lose their pictures: keyed by |
| 387 | // choice id, an option that survives the edit keeps its image no matter | 353 | // choice id, an option that survives the edit keeps its image no matter |
| 388 | // where it moved in the list. (This used to wipe every option picture | 354 | // where it moved in the list. (This used to wipe every option picture |
| @@ -436,12 +402,12 @@ pub(crate) async fn delete_question( | |||
| 436 | crate::service::course::require_open(&st.db, &course).await?; | 402 | crate::service::course::require_open(&st.db, &course).await?; |
| 437 | // No lock: the freeze gate is part of the delete's own transaction, and | 403 | // No lock: the freeze gate is part of the delete's own transaction, and |
| 438 | // this path checks no subject. The pre-flight below is the fast 409. | 404 | // this path checks no subject. The pre-flight below is the fast 409. |
| 439 | - ensure_questions_editable(exam.get_id(), &st.db).await?; | 405 | + exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; |
| 440 | - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; | 406 | + let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; |
| 441 | // Rows go first (the delete cascades them), blobs after — a crash in | 407 | // Rows go first (the delete cascades them), blobs after — a crash in |
| 442 | // between strands at worst an unreachable blob. | 408 | // between strands at worst an unreachable blob. |
| 443 | let images = QuestionImage::list_for_question(question.get_id(), &st.db).await?; | 409 | let images = QuestionImage::list_for_question(question.get_id(), &st.db).await?; |
| 444 | - question.delete(&st.db).await?; | 410 | + exam_question::delete(&st.db, question).await?; |
| 445 | for image in &images { | 411 | for image in &images { |
| 446 | remove_blob(&st.files_path, image.get_file()).await; | 412 | remove_blob(&st.files_path, image.get_file()).await; |
| 447 | } | 413 | } |
| @@ -508,7 +474,7 @@ pub(crate) async fn question_from_bank( | |||
| 508 | crate::service::course::require_open(&st.db, &course).await?; | 474 | crate::service::course::require_open(&st.db, &course).await?; |
| 509 | // No lease — same reasoning as `create_question`. The freeze gate rides in | 475 | // No lease — same reasoning as `create_question`. The freeze gate rides in |
| 510 | // the insert's transaction. | 476 | // the insert's transaction. |
| 511 | - ensure_questions_editable(exam.get_id(), &st.db).await?; | 477 | + exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; |
| 512 | let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; | 478 | let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; |
| 513 | 479 | ||
| 514 | let template = BankQuestion::read(&BankQuestionId::from_key(&bid), &st.db) | 480 | let template = BankQuestion::read(&BankQuestionId::from_key(&bid), &st.db) |
| @@ -520,14 +486,14 @@ pub(crate) async fn question_from_bank( | |||
| 520 | if !crate::web::bank_questions::can_see(&template, &user) { | 486 | if !crate::web::bank_questions::can_see(&template, &user) { |
| 521 | return Err(AppError::NotFound); | 487 | return Err(AppError::NotFound); |
| 522 | } | 488 | } |
| 523 | - let question = ExamQuestion::create_from_bank( | 489 | + let question = exam_question::create_from_bank( |
| 490 | + &st.db, | ||
| 524 | exam.get_id(), | 491 | exam.get_id(), |
| 525 | subject, | 492 | subject, |
| 526 | template.get_text().clone(), | 493 | template.get_text().clone(), |
| 527 | template.get_points(), | 494 | template.get_points(), |
| 528 | template.spec(), | 495 | template.spec(), |
| 529 | template.get_id().clone(), | 496 | template.get_id().clone(), |
| 530 | - &st.db, | ||
| 531 | ) | 497 | ) |
| 532 | .await?; | 498 | .await?; |
| 533 | 499 | ||
| @@ -565,7 +531,7 @@ pub(crate) async fn question_from_bank( | |||
| 565 | for file in &copied { | 531 | for file in &copied { |
| 566 | remove_blob(&st.files_path, file).await; | 532 | remove_blob(&st.files_path, file).await; |
| 567 | } | 533 | } |
| 568 | - let _ = question.delete(&st.db).await; | 534 | + let _ = exam_question::delete(&st.db, question).await; |
| 569 | return Err(err); | 535 | return Err(err); |
| 570 | } | 536 | } |
| 571 | } | 537 | } |
| @@ -640,8 +606,8 @@ pub(crate) async fn question_refresh_from_bank( | |||
| 640 | // No lock: the question keeps its own subject here, so there is nothing to | 606 | // No lock: the question keeps its own subject here, so there is nothing to |
| 641 | // pair with a subject delete, and the freeze gate rides in the overwrite's | 607 | // pair with a subject delete, and the freeze gate rides in the overwrite's |
| 642 | // transaction. | 608 | // transaction. |
| 643 | - ensure_questions_editable(exam.get_id(), &st.db).await?; | 609 | + exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; |
| 644 | - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; | 610 | + let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; |
| 645 | 611 | ||
| 646 | let Some(source) = question.get_from_bank().cloned() else { | 612 | let Some(source) = question.get_from_bank().cloned() else { |
| 647 | return Err(AppError::Validation(ValidationError::Invalid { | 613 | return Err(AppError::Validation(ValidationError::Invalid { |
| @@ -680,15 +646,15 @@ pub(crate) async fn question_refresh_from_bank( | |||
| 680 | let subject = question.get_subject().clone(); | 646 | let subject = question.get_subject().clone(); |
| 681 | // `spec()` hands over the template's stored choices *with their ids* rather | 647 | // `spec()` hands over the template's stored choices *with their ids* rather |
| 682 | // than re-minting any — the same funnel `question_from_bank` uses. | 648 | // than re-minting any — the same funnel `question_from_bank` uses. |
| 683 | - let updated = question | 649 | + let updated = exam_question::update( |
| 684 | - .update( | 650 | + &st.db, |
| 685 | - subject, | 651 | + question, |
| 686 | - template.get_text().clone(), | 652 | + subject, |
| 687 | - template.get_points(), | 653 | + template.get_text().clone(), |
| 688 | - template.spec(), | 654 | + template.get_points(), |
| 689 | - &st.db, | 655 | + template.spec(), |
| 690 | - ) | 656 | + ) |
| 691 | - .await?; | 657 | + .await?; |
| 692 | 658 | ||
| 693 | // Make the pictures match the template exactly: drop every slot the | 659 | // Make the pictures match the template exactly: drop every slot the |
| 694 | // template has no picture for (including the illustration, and every option | 660 | // template has no picture for (including the illustration, and every option |
| @@ -765,7 +731,7 @@ pub(crate) async fn question_to_bank( | |||
| 765 | // No lease: `BANK_LOCK` is gone with the subject delete's writer lease, and | 731 | // No lease: `BANK_LOCK` is gone with the subject delete's writer lease, and |
| 766 | // a template left holding a deleted subject reads as an empty | 732 | // a template left holding a deleted subject reads as an empty |
| 767 | // `subject_name` either way (see [`crate::web::bank_questions`]). | 733 | // `subject_name` either way (see [`crate::web::bank_questions`]). |
| 768 | - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; | 734 | + let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; |
| 769 | 735 | ||
| 770 | // `create_from_exam` mints its own id and insert (the funnel), fed the | 736 | // `create_from_exam` mints its own id and insert (the funnel), fed the |
| 771 | // question's fields plus the origin exam it was saved off. | 737 | // question's fields plus the origin exam it was saved off. |
| @@ -827,14 +793,13 @@ pub(crate) async fn question_to_bank( | |||
| 827 | // template with no back-link (the next save re-links it). | 793 | // template with no back-link (the next save re-links it). |
| 828 | let question_key = question.get_id().key().to_string(); | 794 | let question_key = question.get_id().key().to_string(); |
| 829 | // No exam lease around the back-link any more, and none is needed: this is a | 795 | // No exam lease around the back-link any more, and none is needed: this is a |
| 830 | - // single-column `UPDATE`, and `ExamQuestion::update` no longer re-states | 796 | + // single-column `UPDATE`, and the question row `UPDATE` no longer re-states |
| 831 | // this column from a snapshot (it names the columns it writes), so a | 797 | // this column from a snapshot (it names the columns it writes), so a |
| 832 | // question edit racing the link cannot revert it. That lease existed only to | 798 | // question edit racing the link cannot revert it. That lease existed only to |
| 833 | // order those two, and the ordering requirement is gone with the whole-row | 799 | // order those two, and the ordering requirement is gone with the whole-row |
| 834 | // save that created it. | 800 | // save that created it. |
| 835 | - if let Err(err) = question | 801 | + if let Err(err) = |
| 836 | - .link_banked_as(template.get_id().clone(), &st.db) | 802 | + exam_question::link_banked_as(&st.db, question, template.get_id().clone()).await |
| 837 | - .await | ||
| 838 | { | 803 | { |
| 839 | tracing::warn!( | 804 | tracing::warn!( |
| 840 | "saved question {question_key} to the bank but could not link it back: {err}" | 805 | "saved question {question_key} to the bank but could not link it back: {err}" |
src/web/exams/review.rsmodified+6 -7
| @@ -1,9 +1,8 @@ | |||
| 1 | use super::*; | 1 | use super::*; |
| 2 | 2 | ||
| 3 | use crate::domain::exam_attempt::AttemptStatus; | 3 | use crate::domain::exam_attempt::AttemptStatus; |
| 4 | -use crate::service::exam_attempt::{ | 4 | +use crate::service::exam_attempt::{course_of, list_for_user, list_unfinished_for_user}; |
| 5 | - course_of, list_for_user, list_unfinished_for_user, question_of_exam, | 5 | +use crate::service::exam_question; |
| 6 | -}; | ||
| 7 | 6 | ||
| 8 | // ---- per-attempt history ---------------------------------------------------- | 7 | // ---- per-attempt history ---------------------------------------------------- |
| 9 | // The grading views above show the latest sitting; these expose every prior | 8 | // The grading views above show the latest sitting; these expose every prior |
| @@ -121,7 +120,7 @@ pub(crate) async fn student_attempt_answer_image( | |||
| 121 | ) -> Result<Response, AppError> { | 120 | ) -> Result<Response, AppError> { |
| 122 | let exam = gradable_exam(&st, &user, &id).await?; | 121 | let exam = gradable_exam(&st, &user, &id).await?; |
| 123 | let target = UserId::from_key(&target); | 122 | let target = UserId::from_key(&target); |
| 124 | - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; | 123 | + let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; |
| 125 | let image = AnswerImage::read(question.get_id(), &target, seq, &st.db) | 124 | let image = AnswerImage::read(question.get_id(), &target, seq, &st.db) |
| 126 | .await? | 125 | .await? |
| 127 | .ok_or(AppError::NotFound)?; | 126 | .ok_or(AppError::NotFound)?; |
| @@ -253,7 +252,7 @@ pub(crate) async fn reviewable_exam( | |||
| 253 | /// count — a question authored by hand and *saved* to the bank shares its key | 252 | /// count — a question authored by hand and *saved* to the bank shares its key |
| 254 | /// with every later instantiation just as an instantiated one does, so only a | 253 | /// with every later instantiation just as an instantiated one does, so only a |
| 255 | /// question with no bank link at all is never hidden | 254 | /// question with no bank link at all is never hidden |
| 256 | -/// ([`ExamQuestion::list_shared_with`]). | 255 | +/// ([`crate::service::exam_question::list_shared_with`]). |
| 257 | /// | 256 | /// |
| 258 | /// The open sittings are read whole and judged here rather than filtered in | 257 | /// The open sittings are read whole and judged here rather than filtered in |
| 259 | /// SurrealQL, because "in progress" is [`ExamAttempt::status`]'s call off the | 258 | /// SurrealQL, because "in progress" is [`ExamAttempt::status`]'s call off the |
| @@ -275,7 +274,7 @@ async fn live_elsewhere( | |||
| 275 | live.push(other.get_id().clone()); | 274 | live.push(other.get_id().clone()); |
| 276 | } | 275 | } |
| 277 | } | 276 | } |
| 278 | - ExamQuestion::list_shared_with(exam.get_id(), &live, &st.db).await | 277 | + exam_question::list_shared_with(&st.db, exam.get_id(), &live).await |
| 279 | } | 278 | } |
| 280 | 279 | ||
| 281 | /// The caller's own sitting numbers at an exam — every seq that carries answers | 280 | /// The caller's own sitting numbers at an exam — every seq that carries answers |
| @@ -417,7 +416,7 @@ pub(crate) async fn review_attempt_answer_image( | |||
| 417 | Path((id, seq, qid)): Path<(String, i64, String)>, | 416 | Path((id, seq, qid)): Path<(String, i64, String)>, |
| 418 | ) -> Result<Response, AppError> { | 417 | ) -> Result<Response, AppError> { |
| 419 | let exam = reviewable_exam(&st, &user, &id).await?; | 418 | let exam = reviewable_exam(&st, &user, &id).await?; |
| 420 | - let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; | 419 | + let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; |
| 421 | let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db) | 420 | let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db) |
| 422 | .await? | 421 | .await? |
| 423 | .ok_or(AppError::NotFound)?; | 422 | .ok_or(AppError::NotFound)?; |
tests/integration.rsmodified+15 -17
| @@ -9625,8 +9625,8 @@ async fn live_monitor_tracks_answer_progress() { | |||
| 9625 | 9625 | ||
| 9626 | #[tokio::test] | 9626 | #[tokio::test] |
| 9627 | async fn questions_and_answers_cascade_with_deletes() { | 9627 | async fn questions_and_answers_cascade_with_deletes() { |
| 9628 | + use hezarfen_backend::db::exam_question; | ||
| 9628 | use hezarfen_backend::domain::exam_answer::ExamAnswer; | 9629 | use hezarfen_backend::domain::exam_answer::ExamAnswer; |
| 9629 | - use hezarfen_backend::domain::exam_question::ExamQuestion; | ||
| 9630 | 9630 | ||
| 9631 | let (app, db) = app_and_db().await; | 9631 | let (app, db) = app_and_db().await; |
| 9632 | let teacher = login_as(&app, &db, "qc_t", "teacher").await; | 9632 | let teacher = login_as(&app, &db, "qc_t", "teacher").await; |
| @@ -9677,7 +9677,7 @@ async fn questions_and_answers_cascade_with_deletes() { | |||
| 9677 | } | 9677 | } |
| 9678 | let exam_id = ExamId::from_key(&exam); | 9678 | let exam_id = ExamId::from_key(&exam); |
| 9679 | assert_eq!( | 9679 | assert_eq!( |
| 9680 | - ExamQuestion::list_for_exam(&exam_id, None, 0, &db) | 9680 | + exam_question::list_for_exam(&db, &exam_id, None, 0) |
| 9681 | .await | 9681 | .await |
| 9682 | .unwrap() | 9682 | .unwrap() |
| 9683 | .0 | 9683 | .0 |
| @@ -9693,10 +9693,10 @@ async fn questions_and_answers_cascade_with_deletes() { | |||
| 9693 | ); | 9693 | ); |
| 9694 | 9694 | ||
| 9695 | // Deleting one question takes its answers with it. The freeze gate now | 9695 | // Deleting one question takes its answers with it. The freeze gate now |
| 9696 | - // lives inside `ExamQuestion::delete`'s own transaction (not in a lock the | 9696 | + // lives inside `db::exam_question::delete`'s own transaction (not in a lock the |
| 9697 | // handler held), so the attempt has to go first for the cascade to be | 9697 | // handler held), so the attempt has to go first for the cascade to be |
| 9698 | // exercised at all — that refusal is asserted here before it is cleared. | 9698 | // exercised at all — that refusal is asserted here before it is cleared. |
| 9699 | - let frozen = ExamQuestion::list_for_exam(&exam_id, None, 0, &db) | 9699 | + let frozen = exam_question::list_for_exam(&db, &exam_id, None, 0) |
| 9700 | .await | 9700 | .await |
| 9701 | .unwrap() | 9701 | .unwrap() |
| 9702 | .0 | 9702 | .0 |
| @@ -9704,7 +9704,7 @@ async fn questions_and_answers_cascade_with_deletes() { | |||
| 9704 | .next() | 9704 | .next() |
| 9705 | .unwrap(); | 9705 | .unwrap(); |
| 9706 | assert!( | 9706 | assert!( |
| 9707 | - matches!(frozen.delete(&db).await, Err(err) if err.to_string().contains("after attempts")), | 9707 | + matches!(exam_question::delete(&db, frozen).await, Err(err) if err.to_string().contains("after attempts")), |
| 9708 | "the gate must refuse a question delete while an attempt exists" | 9708 | "the gate must refuse a question delete while an attempt exists" |
| 9709 | ); | 9709 | ); |
| 9710 | db.query("DELETE exam_attempt WHERE exam = $ex") | 9710 | db.query("DELETE exam_attempt WHERE exam = $ex") |
| @@ -9713,16 +9713,16 @@ async fn questions_and_answers_cascade_with_deletes() { | |||
| 9713 | .unwrap() | 9713 | .unwrap() |
| 9714 | .check() | 9714 | .check() |
| 9715 | .unwrap(); | 9715 | .unwrap(); |
| 9716 | - let question = ExamQuestion::list_for_exam(&exam_id, None, 0, &db) | 9716 | + let question = exam_question::list_for_exam(&db, &exam_id, None, 0) |
| 9717 | .await | 9717 | .await |
| 9718 | .unwrap() | 9718 | .unwrap() |
| 9719 | .0 | 9719 | .0 |
| 9720 | .into_iter() | 9720 | .into_iter() |
| 9721 | .next() | 9721 | .next() |
| 9722 | .unwrap(); | 9722 | .unwrap(); |
| 9723 | - question.delete(&db).await.unwrap(); | 9723 | + exam_question::delete(&db, question).await.unwrap(); |
| 9724 | assert_eq!( | 9724 | assert_eq!( |
| 9725 | - ExamQuestion::list_for_exam(&exam_id, None, 0, &db) | 9725 | + exam_question::list_for_exam(&db, &exam_id, None, 0) |
| 9726 | .await | 9726 | .await |
| 9727 | .unwrap() | 9727 | .unwrap() |
| 9728 | .0 | 9728 | .0 |
| @@ -9749,7 +9749,7 @@ async fn questions_and_answers_cascade_with_deletes() { | |||
| 9749 | .await; | 9749 | .await; |
| 9750 | assert_eq!(res.status, StatusCode::NO_CONTENT); | 9750 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 9751 | assert!( | 9751 | assert!( |
| 9752 | - ExamQuestion::list_for_exam(&exam_id, None, 0, &db) | 9752 | + exam_question::list_for_exam(&db, &exam_id, None, 0) |
| 9753 | .await | 9753 | .await |
| 9754 | .unwrap() | 9754 | .unwrap() |
| 9755 | .0 | 9755 | .0 |
| @@ -9813,7 +9813,7 @@ async fn questions_and_answers_cascade_with_deletes() { | |||
| 9813 | assert_eq!(res.status, StatusCode::NO_CONTENT); | 9813 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 9814 | let exam2_id = ExamId::from_key(&exam2); | 9814 | let exam2_id = ExamId::from_key(&exam2); |
| 9815 | assert!( | 9815 | assert!( |
| 9816 | - ExamQuestion::list_for_exam(&exam2_id, None, 0, &db) | 9816 | + exam_question::list_for_exam(&db, &exam2_id, None, 0) |
| 9817 | .await | 9817 | .await |
| 9818 | .unwrap() | 9818 | .unwrap() |
| 9819 | .0 | 9819 | .0 |
| @@ -20592,8 +20592,9 @@ async fn to_bank_links_the_question_at_the_new_template() { | |||
| 20592 | /// domain level: HTTP offers no way to interleave inside the handler. | 20592 | /// domain level: HTTP offers no way to interleave inside the handler. |
| 20593 | #[tokio::test] | 20593 | #[tokio::test] |
| 20594 | async fn linking_the_banked_template_does_not_clobber_a_concurrent_edit() { | 20594 | async fn linking_the_banked_template_does_not_clobber_a_concurrent_edit() { |
| 20595 | + use hezarfen_backend::db::exam_question; | ||
| 20595 | use hezarfen_backend::domain::bank_question::BankQuestionId; | 20596 | use hezarfen_backend::domain::bank_question::BankQuestionId; |
| 20596 | - use hezarfen_backend::domain::exam_question::{ExamQuestion, ExamQuestionId}; | 20597 | + use hezarfen_backend::domain::exam_question::ExamQuestionId; |
| 20597 | 20598 | ||
| 20598 | let (app, db) = app_and_db().await; | 20599 | let (app, db) = app_and_db().await; |
| 20599 | let teacher = login_as(&app, &db, "bclob_t", "teacher").await; | 20600 | let teacher = login_as(&app, &db, "bclob_t", "teacher").await; |
| @@ -20619,7 +20620,7 @@ async fn linking_the_banked_template_does_not_clobber_a_concurrent_edit() { | |||
| 20619 | let bid = id_of(&res.body); | 20620 | let bid = id_of(&res.body); |
| 20620 | 20621 | ||
| 20621 | // The handler's read, then someone else's edit lands mid-window. | 20622 | // The handler's read, then someone else's edit lands mid-window. |
| 20622 | - let stale = ExamQuestion::read(&ExamQuestionId::from_key(&qid), &db) | 20623 | + let stale = exam_question::read(&db, &ExamQuestionId::from_key(&qid)) |
| 20623 | .await | 20624 | .await |
| 20624 | .unwrap() | 20625 | .unwrap() |
| 20625 | .expect("question exists"); | 20626 | .expect("question exists"); |
| @@ -20633,8 +20634,7 @@ async fn linking_the_banked_template_does_not_clobber_a_concurrent_edit() { | |||
| 20633 | .await; | 20634 | .await; |
| 20634 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); | 20635 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 20635 | 20636 | ||
| 20636 | - stale | 20637 | + exam_question::link_banked_as(&db, stale, BankQuestionId::from_key(&bid)) |
| 20637 | - .link_banked_as(BankQuestionId::from_key(&bid), &db) | ||
| 20638 | .await | 20638 | .await |
| 20639 | .expect("link written"); | 20639 | .expect("link written"); |
| 20640 | 20640 | ||
| @@ -21287,9 +21287,7 @@ async fn refreshing_a_question_recopies_its_template() { | |||
| 21287 | #[tokio::test] | 21287 | #[tokio::test] |
| 21288 | async fn a_course_patch_does_not_clobber_a_concurrent_teacher_assignment() { | 21288 | async fn a_course_patch_does_not_clobber_a_concurrent_teacher_assignment() { |
| 21289 | use hezarfen_backend::db::course; | 21289 | use hezarfen_backend::db::course; |
| 21290 | - use hezarfen_backend::domain::course::{ | 21290 | + use hezarfen_backend::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; |
| 21291 | - CourseDescription, CourseId, CourseKind, CourseTitle, | ||
| 21292 | - }; | ||
| 21293 | 21291 | ||
| 21294 | let (app, db) = app_and_db().await; | 21292 | let (app, db) = app_and_db().await; |
| 21295 | let owner = login_as(&app, &db, "cclob_o", "teacher").await; | 21293 | let owner = login_as(&app, &db, "cclob_o", "teacher").await; |