forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'layer-split/exam'

Browse files at this commit

e0fb40ee86da57a3d209cc9c9059dc5db9a0e8a3Ahmet Kaan GümüşParent: c4e9b2c606085d
# Conflicts:
#	src/db/mod.rs
#	src/domain/course_session.rs
#	src/domain/exam.rs
#	src/domain/exam_question.rs
#	src/service/mod.rs
#	tests/regress_course_child_orphans.rs

25 changed files +1583 -1390

src/db/course.rsmodified+1 -1
@@ -261,7 +261,7 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App
261 /// **Bank templates** survive it — they are a separate, reusable library261 /// **Bank templates** survive it — they are a separate, reusable library
262 /// spanning every course — so their `source_exam` and `subject` links are262 /// spanning every course — so their `source_exam` and `subject` links are
263 /// cleared instead, in this same transaction, exactly as263 /// cleared instead, in this same transaction, exactly as
264-/// [`crate::domain::exam::Exam::delete`] and264+/// [`crate::db::exam::delete`] and
265 /// [`crate::domain::subject::Subject::delete`] clear them one level down.265 /// [`crate::domain::subject::Subject::delete`] clear them one level down.
266 /// Deleting a course must leave the bank where deleting each of its exams266 /// Deleting a course must leave the bank where deleting each of its exams
267 /// and subjects by hand would have left it, or a template is left pointing267 /// and subjects by hand would have left it, or a template is left pointing
src/db/course_session.rsmodified+1 -1
@@ -113,7 +113,7 @@ pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSessi
113 &[("s".into(), session.id.record().into_value())],113 &[("s".into(), session.id.record().into_value())],
114 // No THROW of its own — an unconditional cascade, so the only114 // No THROW of its own — an unconditional cascade, so the only
115 // error worth telling apart is a lost round (see115 // error worth telling apart is a lost round (see
116- // [`crate::domain::exam::Exam::delete`]).116+ // [`crate::db::exam::delete`]).
117 &[],117 &[],
118 )118 )
119 .await?;119 .await?;
src/db/exam.rsadded+1109 -0
@@ -0,0 +1,1109 @@
1+//! The `exam` table: row reads and listings, the count-and-create that pins
2+//! the exam to a live course row, the compare-and-set every PATCH writes
3+//! through, and the cascading delete. The PATCH re-derive and the delete's
4+//! blob-key collection live in [`crate::service::exam`].
5+
6+use surrealdb::types::{RecordId, SurrealValue};
7+
8+use crate::constant::ENROLLMENT_COUNT_FIELD;
9+use crate::database::{Database, transaction_with_retry};
10+use crate::db::cap;
11+use crate::domain::course::CourseId;
12+use crate::domain::exam::{
13+ Exam, ExamAttemptLimit, ExamDescription, ExamId, ExamKind, ExamSchedule, ExamTitle,
14+ redraft_error,
15+};
16+use crate::domain::user::UserId;
17+use crate::error::AppError;
18+
19+#[expect(
20+ clippy::too_many_arguments,
21+ reason = "mirrors the sibling entities' create(field, field, ..) shape"
22+)]
23+pub async fn create(
24+ db: &Database,
25+ creator: &UserId,
26+ course: &CourseId,
27+ title: ExamTitle,
28+ description: ExamDescription,
29+ kind: ExamKind,
30+ schedule: ExamSchedule,
31+ max_attempts: ExamAttemptLimit,
32+ allow_rejoin: bool,
33+ allow_review: bool,
34+ draft: bool,
35+) -> Result<Exam, AppError> {
36+ let exam = Exam {
37+ id: ExamId::generate(),
38+ creator: creator.clone(),
39+ course: course.clone(),
40+ title,
41+ description,
42+ kind,
43+ mode: schedule.mode,
44+ starts_at: schedule.starts_at,
45+ ends_at: schedule.ends_at,
46+ duration_ms: schedule.duration_ms,
47+ max_attempts,
48+ allow_rejoin,
49+ allow_review,
50+ draft,
51+ result_count: None,
52+ };
53+ // The course row is *written* (bumped and put back), not read: a plain
54+ // read does not survive `Course::delete`'s window, and an exam that
55+ // outlives its course is unreachable for good — every route to one goes
56+ // through `course_of`, which answers a 500 no delete can clear, while
57+ // `GET /exams` still lists it. See [`cap::touch_and_create`].
58+ cap::touch_and_create(
59+ &course.record(),
60+ ENROLLMENT_COUNT_FIELD,
61+ &exam.id.record(),
62+ &exam,
63+ db,
64+ )
65+ .await?
66+ .ok_or(AppError::NotFound)
67+}
68+
69+pub async fn read(db: &Database, id: &ExamId) -> Result<Option<Exam>, AppError> {
70+ Ok(db.select(id.record()).await?)
71+}
72+
73+pub async fn list_all(db: &Database) -> Result<Vec<Exam>, AppError> {
74+ let mut result = db
75+ .query("SELECT * FROM exam ORDER BY id DESC")
76+ .await?
77+ .check()?;
78+ Ok(result.take::<Vec<Exam>>(0)?)
79+}
80+
81+pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Exam>, AppError> {
82+ let mut result = db
83+ .query("SELECT * FROM exam WHERE course = $course ORDER BY id DESC")
84+ .bind(("course", course.record()))
85+ .await?
86+ .check()?;
87+ Ok(result.take::<Vec<Exam>>(0)?)
88+}
89+
90+/// Every exam of every course in `courses` (one query) — the catalog as one
91+/// user sees it.
92+pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result<Vec<Exam>, AppError> {
93+ if courses.is_empty() {
94+ return Ok(Vec::new());
95+ }
96+ let records: Vec<RecordId> = courses.iter().map(CourseId::record).collect();
97+ let mut result = db
98+ .query("SELECT * FROM exam WHERE course IN $courses ORDER BY id DESC")
99+ .bind(("courses", records))
100+ .await?
101+ .check()?;
102+ Ok(result.take::<Vec<Exam>>(0)?)
103+}
104+
105+// `course` is deliberately not updatable — moving an exam between courses
106+// would strand results of students not enrolled in the target course.
107+#[expect(
108+ clippy::too_many_arguments,
109+ reason = "mirrors the sibling entities' update(field, field, ..) shape"
110+)]
111+/// Save the merged exam, but only while the row still reads as the
112+/// snapshot the caller merged over — `None` means a concurrent PATCH
113+/// landed in between and nothing was written: re-read, re-merge, retry.
114+///
115+/// Every column this write replaces is in the guard, which is what makes
116+/// the whole-row `CONTENT` save safe without a lock held across the
117+/// handler's read: the compare-and-set refuses precisely when that save
118+/// would have reverted somebody. `course`/`creator` are not editable and
119+/// ride along unchanged. Same shape as
120+/// [`crate::db::settings::save_if_unchanged`].
121+pub async fn update_if_unchanged(
122+ db: &Database,
123+ mut expected: Exam,
124+ title: ExamTitle,
125+ description: ExamDescription,
126+ kind: ExamKind,
127+ schedule: ExamSchedule,
128+ max_attempts: ExamAttemptLimit,
129+ allow_rejoin: bool,
130+ allow_review: bool,
131+ draft: bool,
132+) -> Result<Option<Exam>, AppError> {
133+ // Re-drafting hides an exam: it must be refused while any sitting or
134+ // mark exists, and that check has to be *in this transaction*. Holding
135+ // it under a lock outside would only order the two writers inside one
136+ // process — and it did not even do that, since grading takes the reader
137+ // lease this write does.
138+ let redraft = draft && !expected.draft;
139+ let was = (
140+ expected.title.clone(),
141+ expected.description.clone(),
142+ expected.kind.clone(),
143+ expected.mode.clone(),
144+ expected.starts_at,
145+ expected.ends_at,
146+ expected.duration_ms,
147+ expected.max_attempts,
148+ expected.allow_rejoin,
149+ expected.allow_review,
150+ expected.draft,
151+ );
152+ expected.title = title;
153+ expected.description = description;
154+ expected.kind = kind;
155+ expected.mode = schedule.mode;
156+ expected.starts_at = schedule.starts_at;
157+ expected.ends_at = schedule.ends_at;
158+ expected.duration_ms = schedule.duration_ms;
159+ expected.max_attempts = max_attempts;
160+ expected.allow_rejoin = allow_rejoin;
161+ expected.allow_review = allow_review;
162+ expected.draft = draft;
163+ // whole-row-save-ok: the WHERE below pins every column this replaces to
164+ // the caller's snapshot, so no concurrent write can be reverted
165+ //
166+ // Sent through the retry loop, not a bare `query`: this row now has a
167+ // hot writer. Every answer save touches it to tie itself to the exam
168+ // ([`crate::domain::exam_answer::ExamAnswer::save`]), so a teacher
169+ // flipping `allow_rejoin` mid-exam can lose a round to a student
170+ // typing — and a lost round is a re-send, never the 500 a bare `?` on
171+ // the conflict would have answered. Re-sending is sound because the
172+ // statement is a compare-and-set: the second pass carries the same
173+ // pinned snapshot, so it lands only if the row is still what the caller
174+ // read, and a rival that really moved it is refused as it was before.
175+ // Admissible for the loop — an `UPDATE`, an `IF`/`THROW` and a `SELECT`
176+ // can never answer "already exists".
177+ let (mut result, mut errors) = transaction_with_retry(
178+ db,
179+ "BEGIN TRANSACTION;
180+ IF $redraft AND (
181+ array::len((SELECT VALUE id FROM exam_attempt WHERE exam = $id LIMIT 1)) > 0
182+ OR array::len((SELECT VALUE id FROM exam_result WHERE exam = $id LIMIT 1)) > 0
183+ ) { THROW 'exam_redraft' };
184+ UPDATE $id CONTENT $new
185+ WHERE title = $was_title AND description = $was_description
186+ AND kind = $was_kind AND mode = $was_mode
187+ AND starts_at = $was_starts AND ends_at = $was_ends
188+ AND duration_ms = $was_duration
189+ AND max_attempts = $was_max_attempts
190+ AND allow_rejoin = $was_allow_rejoin
191+ AND allow_review = $was_allow_review
192+ AND draft = $was_draft
193+ AND (result_count ?? 0) = $was_results
194+ RETURN AFTER;
195+ COMMIT TRANSACTION;",
196+ &[
197+ ("redraft".into(), redraft.into_value()),
198+ ("id".into(), expected.id.record().into_value()),
199+ ("was_title".into(), was.0.into_value()),
200+ ("was_description".into(), was.1.into_value()),
201+ ("was_kind".into(), was.2.into_value()),
202+ ("was_mode".into(), was.3.into_value()),
203+ ("was_starts".into(), was.4.into_value()),
204+ ("was_ends".into(), was.5.into_value()),
205+ ("was_duration".into(), was.6.into_value()),
206+ ("was_max_attempts".into(), was.7.into_value()),
207+ ("was_allow_rejoin".into(), was.8.into_value()),
208+ ("was_allow_review".into(), was.9.into_value()),
209+ ("was_draft".into(), was.10.into_value()),
210+ // The mark counter is pinned like every other column this write
211+ // replaces, and for a sharper reason: a grade increments it, so
212+ // pinning it is what makes "this exam had no marks" — the gate
213+ // the handler refuses a kind change on — true at *write* time
214+ // and not merely at read time. A mark landing in between
215+ // refuses the save.
216+ (
217+ "was_results".into(),
218+ expected.result_count.unwrap_or(0).into_value(),
219+ ),
220+ ("new".into(), expected.into_value()),
221+ ],
222+ &["exam_redraft"],
223+ )
224+ .await?;
225+ // An aborted transaction errors every slot; only the THROW's names the
226+ // marker (the [`crate::db::exam_attempt::write_unfrozen`] treatment).
227+ if errors
228+ .values()
229+ .any(|error| error.to_string().contains("exam_redraft"))
230+ {
231+ return Err(redraft_error());
232+ }
233+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
234+ return Err(error.into());
235+ }
236+ // BEGIN and the IF take a slot each.
237+ Ok(result.take::<Vec<Exam>>(2)?.into_iter().next())
238+}
239+
240+/// Delete the exam and cascade-remove its result, attempt, question,
241+/// answer, question-image, and answer-image rows — all in one transaction,
242+/// so a failure can't leave an emptied-out exam shell behind. The image
243+/// *blobs* (question and answer) are the web layer's to remove — it collects
244+/// their names before calling this.
245+///
246+/// Bank templates saved out of this exam survive it — they are a separate,
247+/// reusable library — so only their `source_exam` provenance link is cleared,
248+/// in the same transaction, never left pointing at a dead exam.
249+///
250+/// The questions about to be cascaded each hold a reference on their
251+/// subject, which is what keeps that subject from being deleted under them.
252+/// They are given back in this same transaction, counted per subject, so
253+/// deleting an exam frees its subjects for deletion and nothing else does.
254+/// The marks give their *kind* references back the same way, and it has to
255+/// be the same way: counted outside the transaction, a mark deleted by a
256+/// concurrent `remove_result` in the gap would be released twice — once by
257+/// each — which on a kind another exam still uses reads as one mark too
258+/// few, and that is a kind wrongly free to leave the settings.
259+pub async fn delete(db: &Database, target: Exam) -> Result<Exam, AppError> {
260+ let (mut result, mut errors) = transaction_with_retry(
261+ db,
262+ "BEGIN TRANSACTION;
263+ FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result
264+ WHERE exam = $ex GROUP BY kind) ?? []) {
265+ UPDATE type::record('kind_ref', $row.kind) SET count =
266+ math::max([(count ?? 0) - $row.n, 0])
267+ };
268+ DELETE exam_result WHERE exam = $ex;
269+ DELETE exam_attempt WHERE exam = $ex;
270+ DELETE exam_answer WHERE exam = $ex;
271+ DELETE answer_image WHERE exam = $ex;
272+ DELETE question_image WHERE exam = $ex;
273+ FOR $row IN ((SELECT subject, count() AS n FROM exam_question
274+ WHERE exam = $ex GROUP BY subject) ?? []) {
275+ UPDATE $row.subject SET exam_question_count =
276+ math::max([(exam_question_count ?? 0) - $row.n, 0])
277+ };
278+ DELETE exam_question WHERE exam = $ex;
279+ UPDATE bank_question SET source_exam = NONE WHERE source_exam = $ex;
280+ LET $before = (DELETE $ex RETURN BEFORE);
281+ RETURN $before;
282+ COMMIT TRANSACTION;",
283+ &[("ex".into(), target.id.record().into_value())],
284+ // No THROW of its own: an unconditional cascade, so the only error
285+ // worth telling apart is a lost round, and `check()` — which took
286+ // the *first* error in the batch — could not. It reported a
287+ // sibling's "not executed" and made a retryable round a 500.
288+ &[],
289+ )
290+ .await?;
291+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
292+ return Err(error.into());
293+ }
294+ // The deleted row comes back through the transaction's trailing
295+ // `RETURN`, never a hand-counted slot: the old `take(8)` turned a
296+ // successful delete into a 404 the moment a cascade statement was
297+ // inserted above it (it already had to be bumped once). `RETURN` is
298+ // always the last statement before `COMMIT`, so its slot is derived
299+ // from the statement count and every insertion above it shifts it
300+ // along. `num_statements` counts BEGIN and COMMIT too, hence -2.
301+ let slot = result.num_statements().saturating_sub(2);
302+ let deleted: Option<Exam> = result.take::<Vec<Exam>>(slot)?.into_iter().next();
303+ deleted.ok_or(AppError::NotFound)
304+}
305+#[cfg(test)]
306+use crate::domain::settings::ExamKindDef;
307+
308+/// An unscheduled published exam — the minimum any test that writes a *child*
309+/// of an exam needs, in any module: every such write moves the exam row (see
310+/// [`crate::db::exam_attempt::write_unfrozen_with`]
311+/// and [`crate::domain::exam_answer::ExamAnswer::save`]), so a minted id whose
312+/// row was never created is a 404 rather than a silent orphan.
313+#[cfg(test)]
314+pub(crate) async fn published_exam(db: &Database) -> Exam {
315+ let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
316+ .get_exam_kinds()
317+ .to_vec();
318+ create(
319+ db,
320+ &UserId::generate(),
321+ &crate::db::course::a_test_course(db).await,
322+ ExamTitle::try_new("midterm").unwrap(),
323+ ExamDescription::try_new("").unwrap(),
324+ ExamKind::try_new("midterm", &allowed).unwrap(),
325+ ExamSchedule::try_new(None, None, None, None).unwrap(),
326+ ExamAttemptLimit::try_new(1).unwrap(),
327+ true,
328+ false,
329+ false,
330+ )
331+ .await
332+ .unwrap()
333+}
334+
335+#[cfg(test)]
336+mod tests {
337+ use super::*;
338+
339+ use super::published_exam as published;
340+
341+ use crate::constant::EXAM_TABLE;
342+ use crate::domain::exam::{ExamDuration, ExamMode};
343+ use crate::domain::settings::ExamKindDef;
344+ use crate::domain::timestamp::Timestamp;
345+ use crate::error::ValidationError;
346+
347+ /// An exam must not outlive the course it belongs to. It is the worst of
348+ /// the three children `Course::delete` used to leave behind: every exam
349+ /// route funnels through `course_of`, which answers
350+ /// `Internal("exam references a missing course")`, so an orphan **500s
351+ /// forever** on `GET`/`PATCH`/`DELETE /exams/{id}` — undeletable — while
352+ /// [`crate::db::exam::list_all`] still hands it to every manager+ on `GET /exams`.
353+ ///
354+ /// [`create`] therefore *writes* the course row rather than reading
355+ /// it ([`cap::touch_and_create`]); the harness and the window it races in
356+ /// are documented on
357+ /// [`crate::db::course::assert_no_child_outlives_a_course_delete`].
358+ /// Mutation-tested: with the bare `db.create` this shipped with, all four
359+ /// rounds orphan.
360+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
361+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
362+ async fn an_exam_never_outlives_its_course() {
363+ fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {
364+ tokio::spawn(async move {
365+ let kinds = crate::domain::settings::Settings::defaults()
366+ .get_exam_kinds()
367+ .to_vec();
368+ create(
369+ &db,
370+ &UserId::generate(),
371+ &course,
372+ ExamTitle::try_new("quiz").unwrap(),
373+ ExamDescription::try_new("").unwrap(),
374+ ExamKind::try_new("quiz", &kinds).unwrap(),
375+ ExamSchedule::try_new(None, None, None, None).unwrap(),
376+ ExamAttemptLimit::try_new(1).unwrap(),
377+ true,
378+ false,
379+ false,
380+ )
381+ .await
382+ .map(|_| ())
383+ })
384+ }
385+ crate::db::course::assert_no_child_outlives_a_course_delete(
386+ "exam_orphan_race",
387+ EXAM_TABLE,
388+ make,
389+ )
390+ .await;
391+ }
392+
393+ fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) {
394+ (
395+ exam.get_title().clone(),
396+ exam.get_description().clone(),
397+ exam.get_kind().clone(),
398+ ExamSchedule::try_new(None, None, None, None).unwrap(),
399+ )
400+ }
401+
402+ /// The bite test for the compare-and-set that replaced the writer lease on
403+ /// `PATCH /exams/{id}`: a merge built on a snapshot the row has moved past
404+ /// must be refused (the handler then re-reads and re-merges), never
405+ /// written over somebody else's edit. Asserts the *stored* row.
406+ #[tokio::test]
407+ async fn a_merge_built_on_a_stale_snapshot_is_refused() {
408+ let db = crate::database::init_mem().await.unwrap();
409+ let stale = published(&db).await;
410+ let (_, description, kind, schedule) = edit(&stale);
411+ let landed = update_if_unchanged(
412+ &db,
413+ stale.clone(),
414+ ExamTitle::try_new("theirs").unwrap(),
415+ description,
416+ kind,
417+ schedule,
418+ ExamAttemptLimit::try_new(1).unwrap(),
419+ true,
420+ false,
421+ false,
422+ )
423+ .await
424+ .unwrap();
425+ assert!(landed.is_some(), "the first write is on a fresh snapshot");
426+
427+ let (_, description, kind, schedule) = edit(&stale);
428+ let refused = update_if_unchanged(
429+ &db,
430+ stale,
431+ ExamTitle::try_new("mine").unwrap(),
432+ description,
433+ kind,
434+ schedule,
435+ ExamAttemptLimit::try_new(1).unwrap(),
436+ true,
437+ false,
438+ false,
439+ )
440+ .await
441+ .unwrap();
442+ assert!(refused.is_none(), "a stale merge must not be written");
443+ let stored = read(&db, landed.unwrap().get_id()).await.unwrap().unwrap();
444+ assert_eq!(stored.get_title().as_str(), "theirs");
445+ }
446+
447+ /// The bite test for the re-draft guard now living *inside* the update's
448+ /// transaction: a mark that lands after the handler's pre-flight gate (the
449+ /// grade path is a lock reader, exactly like this one) must still stop the
450+ /// exam from being hidden.
451+ #[tokio::test]
452+ async fn re_drafting_is_refused_by_the_write_itself_once_a_mark_exists() {
453+ use crate::domain::exam_result::{ExamResult, Mark};
454+ let db = crate::database::init_mem().await.unwrap();
455+ let exam = published(&db).await;
456+ let student = UserId::generate();
457+ ExamResult::grade(
458+ exam.get_id(),
459+ &student,
460+ 1,
461+ Mark::try_new(80).unwrap(),
462+ &UserId::generate(),
463+ exam.get_kind().as_str(),
464+ &db,
465+ )
466+ .await
467+ .unwrap();
468+
469+ let (title, description, kind, schedule) = edit(&exam);
470+ let refused = update_if_unchanged(
471+ &db,
472+ exam.clone(),
473+ title,
474+ description,
475+ kind,
476+ schedule,
477+ ExamAttemptLimit::try_new(1).unwrap(),
478+ true,
479+ false,
480+ true,
481+ )
482+ .await
483+ .expect_err("a graded exam cannot be re-drafted");
484+ assert!(refused.to_string().contains("back into a draft"));
485+ let stored = read(&db, exam.get_id()).await.unwrap().unwrap();
486+ assert!(!stored.is_draft(), "nothing may have been written");
487+ }
488+
489+ #[tokio::test]
490+ async fn title_is_required() {
491+ assert!(ExamTitle::try_new("midterm").is_ok());
492+ assert!(ExamTitle::try_new("").is_err());
493+ assert!(ExamTitle::try_new(" ").is_err());
494+ }
495+
496+ #[tokio::test]
497+ async fn description_is_optional() {
498+ assert!(ExamDescription::try_new("").is_ok());
499+ }
500+
501+ #[tokio::test]
502+ async fn kind_must_be_in_the_allowed_list() {
503+ let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
504+ .get_exam_kinds()
505+ .to_vec();
506+ for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] {
507+ assert_eq!(ExamKind::try_new(kind, &allowed).unwrap().as_str(), kind);
508+ }
509+ assert!(ExamKind::try_new("essay", &allowed).is_err());
510+ assert!(ExamKind::try_new("", &allowed).is_err());
511+ // A school-defined list swaps the acceptance set wholesale.
512+ let custom = vec![ExamKindDef::try_new("lab", 2).unwrap()];
513+ assert!(ExamKind::try_new("lab", &custom).is_ok());
514+ assert!(ExamKind::try_new("midterm", &custom).is_err());
515+ // Matching is exact, case included — the settings list is the wire
516+ // truth, not a case-folded suggestion.
517+ assert!(ExamKind::try_new("Lab", &custom).is_err());
518+ }
519+
520+ #[tokio::test]
521+ async fn mode_must_be_known() {
522+ for mode in ["sync", "async", "open"] {
523+ assert_eq!(ExamMode::try_new(mode).unwrap().as_str(), mode);
524+ }
525+ assert!(ExamMode::try_new("live").is_err());
526+ }
527+
528+ #[tokio::test]
529+ async fn attempt_limit_counts_or_never_runs_out() {
530+ let single = ExamAttemptLimit::single();
531+ assert_eq!(single.as_i64(), 1);
532+ assert!(!single.is_unlimited());
533+ assert!(single.allows_another(0));
534+ assert!(!single.allows_another(1));
535+
536+ let three = ExamAttemptLimit::try_new(3).unwrap();
537+ assert!(three.allows_another(2));
538+ assert!(!three.allows_another(3));
539+ assert!(!three.allows_another(4));
540+
541+ let unlimited = ExamAttemptLimit::try_new(0).unwrap();
542+ assert!(unlimited.is_unlimited());
543+ assert!(unlimited.allows_another(0));
544+ assert!(unlimited.allows_another(10_000));
545+
546+ assert!(ExamAttemptLimit::try_new(-1).is_err());
547+ assert!(ExamAttemptLimit::try_new(101).is_err());
548+ }
549+
550+ #[tokio::test]
551+ async fn schedule_invariants_hold() {
552+ let mode = |m| Some(ExamMode::try_new(m).unwrap());
553+ let at = |ms| Some(Timestamp::from_millis(ms));
554+ let dur = Some(ExamDuration::try_new(90 * 60 * 1000).unwrap());
555+
556+ // Unscheduled: nothing set is fine, any time/duration without a mode is not.
557+ assert!(ExamSchedule::try_new(None, None, None, None).is_ok());
558+ assert!(ExamSchedule::try_new(None, at(1), None, None).is_err());
559+ assert!(ExamSchedule::try_new(None, None, at(2), None).is_err());
560+ assert!(ExamSchedule::try_new(None, None, None, dur).is_err());
561+
562+ // Sync: fixed window, no duration.
563+ assert!(ExamSchedule::try_new(mode("sync"), at(1), at(2), None).is_ok());
564+ assert!(ExamSchedule::try_new(mode("sync"), None, at(2), None).is_err());
565+ assert!(ExamSchedule::try_new(mode("sync"), at(1), None, None).is_err());
566+ // Over-long `dur` in a 1ms window, but the root cause is that sync
567+ // takes no duration at all — that message wins over the window one.
568+ assert!(matches!(
569+ ExamSchedule::try_new(mode("sync"), at(1), at(2), dur),
570+ Err(ValidationError::Invalid {
571+ reason: "only async and open exams take a duration",
572+ ..
573+ })
574+ ));
575+
576+ // Async: window plus a per-student duration, which must fit inside it
577+ // (equal to the window is fine; the window `at(1), at(2)` above is
578+ // too narrow for `dur`, so give it one exactly `dur` wide instead).
579+ assert!(ExamSchedule::try_new(mode("async"), at(1), at(1 + 90 * 60 * 1000), dur).is_ok());
580+ assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), dur).is_err());
581+ assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), None).is_err());
582+
583+ // Open: no window, duration optional (limited or unlimited time).
584+ assert!(ExamSchedule::try_new(mode("open"), None, None, None).is_ok());
585+ assert!(ExamSchedule::try_new(mode("open"), None, None, dur).is_ok());
586+ assert!(ExamSchedule::try_new(mode("open"), at(1), None, None).is_err());
587+ assert!(ExamSchedule::try_new(mode("open"), None, at(2), None).is_err());
588+ assert!(ExamSchedule::try_new(mode("open"), at(1), at(2), dur).is_err());
589+
590+ // The window must be a real interval, whatever the mode.
591+ assert!(ExamSchedule::try_new(mode("sync"), at(2), at(2), None).is_err());
592+ assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err());
593+ }
594+
595+ /// GUARD, not a retry measurement — read the last paragraph before
596+ /// trusting this test with the retry. See
597+ /// [`crate::db::course::delete`]'s race test for why the rate is
598+ /// counted rather than asserted per round.
599+ ///
600+ /// This site has no `THROW` marker at all: it ends `.check()?`, which
601+ /// returns the *first* error in the batch, and an aborted transaction
602+ /// errors every slot — most of them with a generic "not executed". So a
603+ /// genuine conflict can be masked by a sibling, and either way there is no
604+ /// [`crate::database::lost_the_race`] check and no retry.
605+ ///
606+ /// The racer is a mark: [`ExamResult::grade`] claims the exam's own
607+ /// `result_count` (and the kind's reference) before writing, so it contends
608+ /// with the `DELETE $ex` and with the kind_ref decrement inside the same
609+ /// transaction. A round where *some* of the six grades 404 and the rest
610+ /// succeed is the witness that the delete landed inside the burst: the 404
611+ /// comes from `write_mark`'s existence gate, so it can only be answered by a
612+ /// grade that reached the store after the row was gone, and its siblings'
613+ /// success says the same burst also had grades that got there first. Stored
614+ /// state cannot say this any more — the gate is what stops a mark outliving
615+ /// its exam, so the sweep now finds nothing to leave behind in *every*
616+ /// round, which is asserted below as a fact rather than read as a signal.
617+ ///
618+ /// It does not prove the retry either: measured at 0 conflicts in 100 raced
619+ /// rounds, and green with
620+ /// [`crate::database::transaction_with_retry`]'s loop cut to a single
621+ /// attempt — the grades serialize behind `cap`'s claim lock, so they mostly
622+ /// queue rather than collide. So this guards the status codes and the
623+ /// cascade (marks either survive whole or are swept whole, never a 500).
624+ /// The retry is measured on [`crate::db::course::delete`].
625+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
626+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
627+ async fn a_delete_racing_a_mark_never_answers_500() {
628+ use crate::domain::exam_result::{ExamResult, Mark};
629+ let (db, _serialized) = crate::database::init_test_server("exam_delete_race").await;
630+ let (mut delete_500, mut grade_500) = (0, 0);
631+ let (mut split, mut swept) = (0, 0);
632+ let (mut last_delete, mut last_grade) = (String::new(), String::new());
633+ for round in 0..20 {
634+ let exam = published(&db).await;
635+ let kind = exam.get_kind().as_str().to_string();
636+
637+ // A burst of marks and a delete held back by a sweeping beat: this
638+ // site has no guard to lose to, so a single racer released with it
639+ // simply finishes on one side of it. Same recipe as
640+ // [`crate::db::course::delete`]'s race test.
641+ let drop_it = {
642+ let (exam, db) = (exam.clone(), db.clone());
643+ // A wide sweep, not the 0-3ms the other three use: each grade
644+ // takes two counter writes serialized behind `cap`'s claim
645+ // lock, so the burst runs tens of milliseconds and a short beat
646+ // always puts the delete in front of all six.
647+ let beat = std::time::Duration::from_millis(round * 2);
648+ tokio::spawn(async move {
649+ tokio::time::sleep(beat).await;
650+ delete(&db, exam).await
651+ })
652+ };
653+ let marks: Vec<_> = (0..6)
654+ .map(|seat| {
655+ let (id, db, kind) = (exam.get_id().clone(), db.clone(), kind.clone());
656+ let student = UserId::from_key(&format!("stu{round}_{seat}"));
657+ tokio::spawn(async move {
658+ ExamResult::grade(
659+ &id,
660+ &student,
661+ 1,
662+ Mark::try_new(50).unwrap(),
663+ &UserId::from_key("teacher"),
664+ &kind,
665+ &db,
666+ )
667+ .await
668+ })
669+ })
670+ .collect();
671+ let drop_it = drop_it.await.unwrap();
672+ if matches!(drop_it, Err(AppError::Db(_))) {
673+ delete_500 += 1;
674+ last_delete = format!("{drop_it:?}");
675+ }
676+ let mut refused = 0;
677+ for mark in marks {
678+ let mark = mark.await.unwrap();
679+ match mark {
680+ // The existence gate: this grade reached the store after
681+ // the row was gone.
682+ Err(AppError::NotFound) => refused += 1,
683+ Err(AppError::Db(_)) => {
684+ grade_500 += 1;
685+ last_grade = format!("{mark:?}");
686+ }
687+ _ => {}
688+ }
689+ }
690+ // Neither end of the burst: some grades beat the delete and some
691+ // lost to it, so the delete landed *between* them. A round that is
692+ // all-refused or all-through is one where it landed outside.
693+ if (1..6).contains(&refused) {
694+ split += 1;
695+ }
696+ if ExamResult::list_for_exam(exam.get_id(), &db)
697+ .await
698+ .unwrap()
699+ .is_empty()
700+ {
701+ swept += 1;
702+ }
703+ }
704+ eprintln!(
705+ "Exam::delete raced: {delete_500}/20 delete 500s, {grade_500} grade 500s, \
706+ {split} rounds split by the delete / {swept} swept clean"
707+ );
708+ assert!(
709+ split > 0,
710+ "the delete never landed inside the burst (0/20 rounds split)"
711+ );
712+ // Not a race signal, an invariant: the gate refuses a mark for an exam
713+ // that is gone, so no round can leave one behind for the next reader.
714+ assert_eq!(
715+ swept,
716+ 20,
717+ "a mark outlived its exam in {} rounds",
718+ 20 - swept
719+ );
720+ assert_eq!(
721+ delete_500, 0,
722+ "a raced delete must not 500: {delete_500}/20 rounds, last {last_delete}"
723+ );
724+ assert_eq!(
725+ grade_500, 0,
726+ "a raced grade must retry, not 500: {grade_500}/20 rounds, last {last_grade}"
727+ );
728+ }
729+
730+ /// One choice question on `exam`, with a real subject row behind it — a
731+ /// question claims a reference on its subject and is refused without one.
732+ async fn question_on(exam: &Exam, db: &Database) -> crate::domain::exam_question::ExamQuestion {
733+ use crate::domain::exam_question::{
734+ ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
735+ };
736+ let spec = QuestionSpec::try_new(
737+ QuestionKind::try_new("choice").unwrap(),
738+ Some(vec![
739+ ChoiceInput {
740+ id: Some("a".into()),
741+ text: "5".into(),
742+ },
743+ ChoiceInput {
744+ id: Some("b".into()),
745+ text: "6".into(),
746+ },
747+ ]),
748+ Some("b".into()),
749+ &[],
750+ )
751+ .unwrap();
752+ let subject = crate::domain::subject::Subject::create(
753+ &crate::db::course::a_test_course(db).await,
754+ crate::domain::subject::SubjectName::try_new("topic").unwrap(),
755+ crate::domain::subject::SubjectDescription::try_new("").unwrap(),
756+ db,
757+ )
758+ .await
759+ .unwrap();
760+ ExamQuestion::create(
761+ exam.get_id(),
762+ subject.get_id().clone(),
763+ QuestionText::try_new("3 + 3?").unwrap(),
764+ QuestionPoints::try_new(5).unwrap(),
765+ spec,
766+ db,
767+ )
768+ .await
769+ .unwrap()
770+ }
771+
772+ /// The `Menu::delete` defect, one domain over: a student's answer must not
773+ /// outlive the exam it belongs to. Guarding the save by *reading* the exam
774+ /// would not do it — the read sees a row [`crate::db::exam::delete`] has removed but
775+ /// not committed, while its `DELETE exam_answer WHERE exam = $ex` swept a
776+ /// snapshot predating the save, so both commit and the answer is left
777+ /// pointing at an exam that is gone. [`ExamAnswer::save`] writes the exam
778+ /// row instead (its `result_count`, back unchanged), so the two transactions
779+ /// touch one key and the store refuses one of them.
780+ ///
781+ /// The window is opened by the database, not by a lucky interleaving: a
782+ /// `DEFINE EVENT` on `exam` fires *inside* the delete's own transaction the
783+ /// instant the row goes, so the `SLEEP` lands exactly between the delete and
784+ /// its cascade every time. Nothing in `src/` knows about it; the seam is the
785+ /// schema.
786+ ///
787+ /// One child per round, deliberately — in the menu twin, two children in one
788+ /// round hid the bug: the first writer made the delete lose and re-send, and
789+ /// the re-sent sweep removed the other's row.
790+ ///
791+ /// Real server, and `#[ignore]`d for it: the subject *is* the store's
792+ /// conflict detection, which `init_mem`'s embedded engine does not have — it
793+ /// commits both writes and answers `Ok` to each, so this passes there on
794+ /// broken code. Mutation-tested: putting the bare
795+ /// `db.upsert(id).content(answer)` back turns it red (the exact output is in
796+ /// the commit that added it).
797+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
798+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
799+ async fn an_answer_written_inside_a_delete_never_outlives_the_exam() {
800+ use crate::domain::exam_answer::ExamAnswer;
801+ let (db, _serialized) = crate::database::init_test_server("exam_answer_race").await;
802+ // Hold the delete open for a full second after the row is gone, while
803+ // its cascade still has to run.
804+ db.query(
805+ "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
806+ THEN { SLEEP 1s; };",
807+ )
808+ .await
809+ .unwrap()
810+ .check()
811+ .unwrap();
812+
813+ let (mut answers, mut swept) = (0, 0);
814+ for round in 0..4 {
815+ let exam = published(&db).await;
816+ let question = question_on(&exam, &db).await;
817+ let id = exam.get_id().clone();
818+ let student = UserId::from_key(&format!("stu{round}"));
819+ // The stored choice ids are minted by the create, not the ones the
820+ // spec asked for — an answer must name one of *those*.
821+ let pick = question.get_choices().unwrap()[1]
822+ .get_id()
823+ .as_str()
824+ .to_string();
825+
826+ let drop_it = {
827+ let db = db.clone();
828+ tokio::spawn(async move { delete(&db, exam).await })
829+ };
830+ // The save starts inside the held window — the exam row is gone but
831+ // uncommitted, which is exactly what an exam read believes.
832+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
833+ let child = {
834+ let (db, question, student) = (db.clone(), question.clone(), student.clone());
835+ tokio::spawn(async move {
836+ ExamAnswer::save(&question, &student, 1, Some(pick), None, &db).await
837+ })
838+ };
839+ let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
840+ // A 404 for the save, or a NotFound for the delete, is a correct
841+ // answer — the only defect is stored state.
842+ assert!(
843+ !matches!(child, Err(AppError::Db(_))),
844+ "round {round}: a raced save must be answered, not 500: {child:?}"
845+ );
846+
847+ // Stored state is the whole verdict; a return value is not evidence.
848+ if read(&db, &id).await.unwrap().is_none() {
849+ swept += 1;
850+ answers += ExamAnswer::list_for_exam(&id, &db).await.unwrap().len();
851+ } else if drop_it.is_ok() {
852+ panic!("round {round}: the delete reported success but the exam is still there");
853+ }
854+ }
855+ eprintln!("Exam::delete raced by an answer save: {swept}/4 rounds deleted the exam");
856+ assert!(
857+ swept > 0,
858+ "no round ever deleted the exam, so the window was never reached"
859+ );
860+ assert_eq!(answers, 0, "an answer outlived its exam");
861+ }
862+
863+ /// The same defect on the teacher's side of the sheet, and a worse one: a
864+ /// question written inside the delete window kept the reference it claimed
865+ /// on its subject (the cascade's per-subject decrement counted only the
866+ /// rows it could see), and [`crate::domain::subject::Subject::delete`] is
867+ /// gated on that count reading zero — a subject nobody could ever delete
868+ /// again, hanging off an exam nobody could ever see. The freeze gate is a
869+ /// *read* of `exam_attempt` and never survived this window;
870+ /// [`crate::db::exam_attempt::write_unfrozen_with`] now writes the exam row too.
871+ ///
872+ /// Same seam, same `#[ignore]`, same reason as the answer twin above: the
873+ /// subject *is* the store's conflict detection, which the in-memory engine
874+ /// does not have.
875+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
876+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
877+ async fn a_question_written_inside_a_delete_never_outlives_the_exam() {
878+ use crate::domain::exam_question::{
879+ ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
880+ };
881+ use crate::domain::subject::Subject;
882+ let (db, _serialized) = crate::database::init_test_server("exam_question_race").await;
883+ db.query(
884+ "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
885+ THEN { SLEEP 1s; };",
886+ )
887+ .await
888+ .unwrap()
889+ .check()
890+ .unwrap();
891+
892+ let (mut questions, mut swept, mut stuck) = (0, 0, 0);
893+ for round in 0..4 {
894+ let exam = published(&db).await;
895+ let id = exam.get_id().clone();
896+ let subject = Subject::create(
897+ &crate::db::course::a_test_course(&db).await,
898+ crate::domain::subject::SubjectName::try_new("topic").unwrap(),
899+ crate::domain::subject::SubjectDescription::try_new("").unwrap(),
900+ &db,
901+ )
902+ .await
903+ .unwrap();
904+
905+ let drop_it = {
906+ let db = db.clone();
907+ tokio::spawn(async move { delete(&db, exam).await })
908+ };
909+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
910+ let child = {
911+ let (db, exam_id, on) = (db.clone(), id.clone(), subject.get_id().clone());
912+ tokio::spawn(async move {
913+ let spec = QuestionSpec::try_new(
914+ QuestionKind::try_new("choice").unwrap(),
915+ Some(vec![
916+ ChoiceInput {
917+ id: Some("a".into()),
918+ text: "5".into(),
919+ },
920+ ChoiceInput {
921+ id: Some("b".into()),
922+ text: "6".into(),
923+ },
924+ ]),
925+ Some("b".into()),
926+ &[],
927+ )
928+ .unwrap();
929+ ExamQuestion::create(
930+ &exam_id,
931+ on,
932+ QuestionText::try_new("3 + 3?").unwrap(),
933+ QuestionPoints::try_new(5).unwrap(),
934+ spec,
935+ &db,
936+ )
937+ .await
938+ })
939+ };
940+ let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
941+ assert!(
942+ !matches!(child, Err(AppError::Db(_))),
943+ "round {round}: a raced question write must be answered, not 500: {child:?}"
944+ );
945+
946+ if read(&db, &id).await.unwrap().is_none() {
947+ swept += 1;
948+ questions += ExamQuestion::list_for_exam(&id, None, 0, &db)
949+ .await
950+ .unwrap()
951+ .0
952+ .len();
953+ // The subject has to be free again: a stranded reference is the
954+ // half of this bug a row count alone would not catch.
955+ if Subject::read(subject.get_id(), &db)
956+ .await
957+ .unwrap()
958+ .unwrap()
959+ .delete(&db)
960+ .await
961+ .is_err()
962+ {
963+ stuck += 1;
964+ }
965+ } else if drop_it.is_ok() {
966+ panic!("round {round}: the delete reported success but the exam is still there");
967+ }
968+ }
969+ eprintln!("Exam::delete raced by a question write: {swept}/4 rounds deleted the exam");
970+ assert!(
971+ swept > 0,
972+ "no round ever deleted the exam, so the window was never reached"
973+ );
974+ assert_eq!(questions, 0, "a question outlived its exam");
975+ assert_eq!(stuck, 0, "an orphan question left its subject undeletable");
976+ }
977+
978+ /// The student's half of the same picture problem: a drawing is a bare
979+ /// `UPSERT` — the exact pre-fix shape of [`ExamAnswer::save`] — so it kept
980+ /// the hole the text answer just lost, blob and all.
981+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
982+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
983+ async fn a_drawing_written_inside_a_delete_never_outlives_the_exam() {
984+ use crate::domain::answer_image::AnswerImage;
985+ use crate::domain::note_file::FileContentType;
986+ let (db, _serialized) = crate::database::init_test_server("answer_image_race").await;
987+ db.query(
988+ "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
989+ THEN { SLEEP 1s; };",
990+ )
991+ .await
992+ .unwrap()
993+ .check()
994+ .unwrap();
995+
996+ let (mut drawings, mut swept) = (0, 0);
997+ for round in 0..4 {
998+ let exam = published(&db).await;
999+ let question = question_on(&exam, &db).await;
1000+ let id = exam.get_id().clone();
1001+ let student = UserId::from_key(&format!("stu{round}"));
1002+
1003+ let drop_it = {
1004+ let db = db.clone();
1005+ tokio::spawn(async move { delete(&db, exam).await })
1006+ };
1007+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1008+ let child = {
1009+ let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone());
1010+ tokio::spawn(async move {
1011+ AnswerImage::new(
1012+ &exam_id,
1013+ &on,
1014+ &student,
1015+ 1,
1016+ FileContentType::try_new("image/png").unwrap(),
1017+ 3,
1018+ )
1019+ .upsert(&db)
1020+ .await
1021+ })
1022+ };
1023+ let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1024+ assert!(
1025+ !matches!(child, Err(AppError::Db(_))),
1026+ "round {round}: a raced drawing write must be answered, not 500: {child:?}"
1027+ );
1028+
1029+ if read(&db, &id).await.unwrap().is_none() {
1030+ swept += 1;
1031+ drawings += AnswerImage::list_for_exam(&id, &db).await.unwrap().len();
1032+ } else if drop_it.is_ok() {
1033+ panic!("round {round}: the delete reported success but the exam is still there");
1034+ }
1035+ }
1036+ eprintln!("Exam::delete raced by a drawing write: {swept}/4 rounds deleted the exam");
1037+ assert!(
1038+ swept > 0,
1039+ "no round ever deleted the exam, so the window was never reached"
1040+ );
1041+ assert_eq!(drawings, 0, "a drawing outlived its exam");
1042+ }
1043+
1044+ /// A picture is written through the same freeze gate as the question it
1045+ /// hangs on, so it had the same hole — and one the row count does not even
1046+ /// show: `delete_exam` collects the blob names to unlink *before* it calls
1047+ /// [\`crate::db::exam::delete\`], so an image row landing after that snapshot strands
1048+ /// its bytes on disk forever as well.
1049+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1050+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1051+ async fn a_picture_written_inside_a_delete_never_outlives_the_exam() {
1052+ use crate::domain::note_file::FileContentType;
1053+ use crate::domain::question_image::QuestionImage;
1054+ let (db, _serialized) = crate::database::init_test_server("question_image_race").await;
1055+ db.query(
1056+ "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1057+ THEN { SLEEP 1s; };",
1058+ )
1059+ .await
1060+ .unwrap()
1061+ .check()
1062+ .unwrap();
1063+
1064+ let (mut images, mut swept) = (0, 0);
1065+ for round in 0..4 {
1066+ let exam = published(&db).await;
1067+ let question = question_on(&exam, &db).await;
1068+ let id = exam.get_id().clone();
1069+
1070+ let drop_it = {
1071+ let db = db.clone();
1072+ tokio::spawn(async move { delete(&db, exam).await })
1073+ };
1074+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1075+ let child = {
1076+ let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone());
1077+ tokio::spawn(async move {
1078+ QuestionImage::new(
1079+ &exam_id,
1080+ &on,
1081+ None,
1082+ FileContentType::try_new("image/png").unwrap(),
1083+ 3,
1084+ )
1085+ .upsert(&db)
1086+ .await
1087+ })
1088+ };
1089+ let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1090+ assert!(
1091+ !matches!(child, Err(AppError::Db(_))),
1092+ "round {round}: a raced picture write must be answered, not 500: {child:?}"
1093+ );
1094+
1095+ if read(&db, &id).await.unwrap().is_none() {
1096+ swept += 1;
1097+ images += QuestionImage::list_for_exam(&id, &db).await.unwrap().len();
1098+ } else if drop_it.is_ok() {
1099+ panic!("round {round}: the delete reported success but the exam is still there");
1100+ }
1101+ }
1102+ eprintln!("Exam::delete raced by a picture write: {swept}/4 rounds deleted the exam");
1103+ assert!(
1104+ swept > 0,
1105+ "no round ever deleted the exam, so the window was never reached"
1106+ );
1107+ assert_eq!(images, 0, "a picture outlived its exam");
1108+ }
1109+}
src/db/exam_attempt.rsmodified+3 -3
@@ -164,7 +164,7 @@ pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result<bool, AppError
164 /// The same transaction *writes* the exam row — bumping its mark counter164 /// The same transaction *writes* the exam row — bumping its mark counter
165 /// and putting it straight back — which is what ties every child written165 /// and putting it straight back — which is what ties every child written
166 /// through here to its exam. The freeze gate only *reads* `exam_attempt`,166 /// through here to its exam. The freeze gate only *reads* `exam_attempt`,
167-/// and a read does not survive [`Exam::delete`](crate::domain::exam::Exam::delete)'s167+/// and a read does not survive [`delete`](crate::db::exam::delete)'s
168 /// window: a question or picture landing after that delete removed the exam168 /// window: a question or picture landing after that delete removed the exam
169 /// but before it committed reads a row that is still there, while the169 /// but before it committed reads a row that is still there, while the
170 /// cascade's `DELETE exam_question WHERE exam = $ex` ran on a snapshot170 /// cascade's `DELETE exam_question WHERE exam = $ex` ran on a snapshot
@@ -307,7 +307,8 @@ mod tests {
307 let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");307 let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
308 let course = crate::db::course::a_test_course(db).await;308 let course = crate::db::course::a_test_course(db).await;
309 let kinds = Settings::defaults().get_exam_kinds().to_vec();309 let kinds = Settings::defaults().get_exam_kinds().to_vec();
310- let exam = Exam::create(310+ let exam = crate::db::exam::create(
311+ db,
311 &creator,312 &creator,
312 &course,313 &course,
313 ExamTitle::try_new("practice").unwrap(),314 ExamTitle::try_new("practice").unwrap(),
@@ -319,7 +320,6 @@ mod tests {
319 true,320 true,
320 false,321 false,
321 false,322 false,
322- db,
323 )323 )
324 .await324 .await
325 .unwrap();325 .unwrap();
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 enrollment;9 pub mod enrollment;
10+pub mod exam;
10 pub mod exam_attempt;11 pub mod exam_attempt;
11 pub mod exam_question;12 pub mod exam_question;
12 pub mod field_update;13 pub mod field_update;
src/domain/answer_image.rsmodified+2 -5
@@ -139,7 +139,7 @@ impl AnswerImage {
139 /// write moves the exam's mark counter and puts it straight back, in this139 /// write moves the exam's mark counter and puts it straight back, in this
140 /// one transaction, so the exam's existence is something this write140 /// one transaction, so the exam's existence is something this write
141 /// *writes* rather than something a gate read a moment earlier: a bare141 /// *writes* rather than something a gate read a moment earlier: a bare
142- /// upsert landing after [`Exam::delete`](crate::domain::exam::Exam::delete)142+ /// upsert landing after [`delete`](crate::db::exam::delete)
143 /// removed the exam but before it committed was swept by nothing — its143 /// removed the exam but before it committed was swept by nothing — its
144 /// `DELETE answer_image WHERE exam = $ex` ran on a snapshot predating this144 /// `DELETE answer_image WHERE exam = $ex` ran on a snapshot predating this
145 /// row — and both sides reported success. That stranded the blob as well as145 /// row — and both sides reported success. That stranded the blob as well as
@@ -323,10 +323,7 @@ mod tests {
323 /// what keeps it from outliving the exam), so a minted id nothing wrote is323 /// what keeps it from outliving the exam), so a minted id nothing wrote is
324 /// a 404.324 /// a 404.
325 async fn exam_row(db: &Database) -> ExamId {325 async fn exam_row(db: &Database) -> ExamId {
326- crate::domain::exam::published_exam(db)326+ crate::db::exam::published_exam(db).await.get_id().clone()
327- .await
328- .get_id()
329- .clone()
330 }327 }
331 328
332 fn student() -> UserId {329 fn student() -> UserId {
src/domain/bank_question.rsmodified+2 -8
@@ -833,14 +833,8 @@ mod tests {
833 // Real exam rows: instantiating a template moves the exam's counter833 // Real exam rows: instantiating a template moves the exam's counter
834 // (what keeps a question from outliving its exam), so a minted id834 // (what keeps a question from outliving its exam), so a minted id
835 // nothing wrote is a 404.835 // nothing wrote is a 404.
836- let exam = crate::domain::exam::published_exam(&db)836+ let exam = crate::db::exam::published_exam(&db).await.get_id().clone();
837- .await837+ let other_exam = crate::db::exam::published_exam(&db).await.get_id().clone();
838- .get_id()
839- .clone();
840- let other_exam = crate::domain::exam::published_exam(&db)
841- .await
842- .get_id()
843- .clone();
844 // A real subject row: an exam question claims a reference on its838 // A real subject row: an exam question claims a reference on its
845 // subject, so a minted id it never wrote would be refused.839 // subject, so a minted id it never wrote would be refused.
846 let subject = crate::domain::subject::Subject::create(840 let subject = crate::domain::subject::Subject::create(
src/domain/exam.rsmodified+27 -1120
@@ -1,11 +1,8 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3 use crate::constant::{3 use crate::constant::{
4- ENROLLMENT_COUNT_FIELD, EXAM_TABLE, MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN,4+ EXAM_TABLE, MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS,
5- UNLIMITED_EXAM_ATTEMPTS,
6 };5 };
7-use crate::database::{Database, transaction_with_retry};
8-use crate::db::cap;
9 use crate::domain::course::CourseId;6 use crate::domain::course::CourseId;
10 use crate::domain::monotonic_id::next_ulid;7 use crate::domain::monotonic_id::next_ulid;
11 use crate::domain::settings::ExamKindDef;8 use crate::domain::settings::ExamKindDef;
@@ -13,9 +10,10 @@ use crate::domain::timestamp::Timestamp;
13 use crate::domain::user::UserId;10 use crate::domain::user::UserId;
14 use crate::error::{AppError, ValidationError};11 use crate::error::{AppError, ValidationError};
15 12
16-/// The one spelling of the re-draft refusal, shared by the handler's13+/// The one spelling of the re-draft refusal, shared by the update workflow's
17-/// pre-flight gate and the in-transaction guard that re-makes it at write14+/// pre-flight gate ([`crate::service::exam::update`]) and the in-transaction
18-/// time — a client cannot tell which of the two refused.15+/// guard that re-makes it at write time — a client cannot tell which of the
16+/// two refused.
19 pub(crate) fn redraft_error() -> AppError {17 pub(crate) fn redraft_error() -> AppError {
20 AppError::Conflict(18 AppError::Conflict(
21 "cannot turn a published exam back into a draft after attempts or results exist",19 "cannot turn a published exam back into a draft after attempts or results exist",
@@ -31,7 +29,7 @@ pub struct ExamId(RecordId);
31 29
32 impl ExamId {30 impl ExamId {
33 /// Minted from the process-wide monotonic generator, not `Ulid::new()`:31 /// Minted from the process-wide monotonic generator, not `Ulid::new()`:
34- /// exams list `id DESC` (newest first, [`Exam::list_all`]),32+ /// exams list `id DESC` (newest first, [`crate::db::exam::list_all`]),
35 /// and a random low half scrambles rows minted in the same millisecond.33 /// and a random low half scrambles rows minted in the same millisecond.
36 pub fn generate() -> Self {34 pub fn generate() -> Self {
37 Self(RecordId::new(EXAM_TABLE, next_ulid().to_string()))35 Self(RecordId::new(EXAM_TABLE, next_ulid().to_string()))
@@ -186,10 +184,10 @@ impl ExamAttemptLimit {
186 /// - `ends_at` strictly after `starts_at` whenever the window exists.184 /// - `ends_at` strictly after `starts_at` whenever the window exists.
187 #[derive(Debug, Clone, Default)]185 #[derive(Debug, Clone, Default)]
188 pub struct ExamSchedule {186 pub struct ExamSchedule {
189- mode: Option<ExamMode>,187+ pub(crate) mode: Option<ExamMode>,
190- starts_at: Option<Timestamp>,188+ pub(crate) starts_at: Option<Timestamp>,
191- ends_at: Option<Timestamp>,189+ pub(crate) ends_at: Option<Timestamp>,
192- duration_ms: Option<ExamDuration>,190+ pub(crate) duration_ms: Option<ExamDuration>,
193 }191 }
194 192
195 impl ExamSchedule {193 impl ExamSchedule {
@@ -273,36 +271,37 @@ impl ExamSchedule {
273 271
274 #[derive(Debug, Clone, SurrealValue)]272 #[derive(Debug, Clone, SurrealValue)]
275 pub struct Exam {273 pub struct Exam {
276- id: ExamId,274+ pub(crate) id: ExamId,
277- creator: UserId,275+ pub(crate) creator: UserId,
278- course: CourseId,276+ pub(crate) course: CourseId,
279- title: ExamTitle,277+ pub(crate) title: ExamTitle,
280- description: ExamDescription,278+ pub(crate) description: ExamDescription,
281- kind: ExamKind,279+ pub(crate) kind: ExamKind,
282 // The schedule, flattened into columns (SCHEMAFULL keeps them typed).280 // The schedule, flattened into columns (SCHEMAFULL keeps them typed).
283 // Always written through an `ExamSchedule`, so the invariants above hold281 // Always written through an `ExamSchedule`, so the invariants above hold
284 // for every stored row; pre-schedule rows read back as all-`None`.282 // for every stored row; pre-schedule rows read back as all-`None`.
285- mode: Option<ExamMode>,283+ pub(crate) mode: Option<ExamMode>,
286- starts_at: Option<Timestamp>,284+ pub(crate) starts_at: Option<Timestamp>,
287- ends_at: Option<Timestamp>,285+ pub(crate) ends_at: Option<Timestamp>,
288- duration_ms: Option<ExamDuration>,286+ pub(crate) duration_ms: Option<ExamDuration>,
289 // Attempt policy. Rows predating these columns are backfilled by the boot287 // Attempt policy. Rows predating these columns are backfilled by the boot
290 // migration (limit 1, rejoin open), so reads never see them missing.288 // migration (limit 1, rejoin open), so reads never see them missing.
291- max_attempts: ExamAttemptLimit,289+ pub(crate) max_attempts: ExamAttemptLimit,
292- allow_rejoin: bool,290+ pub(crate) allow_rejoin: bool,
293- allow_review: bool,291+ pub(crate) allow_review: bool,
294 // Work-in-progress marker: a draft is visible only to its course's292 // Work-in-progress marker: a draft is visible only to its course's
295 // managers, cannot be sat, and cannot be graded. Rows predating the293 // managers, cannot be sat, and cannot be graded. Rows predating the
296 // column are backfilled published (`false`).294 // column are backfilled published (`false`).
297- draft: bool,295+ pub(crate) draft: bool,
298- /// How many marks the exam carries — a cap-style counter ([`cap::claim`]296+ /// How many marks the exam carries — a cap-style counter
297+ /// ([`crate::db::cap::claim`]
299 /// from the grade, decremented by every delete of a mark), absent meaning298 /// from the grade, decremented by every delete of a mark), absent meaning
300 /// zero. Unlike every other counter it is carried *in the struct*, because299 /// zero. Unlike every other counter it is carried *in the struct*, because
301 /// the save below is a whole-row `CONTENT` write: a column this type did300 /// the save below is a whole-row `CONTENT` write: a column this type did
302 /// not know about would be wiped by the next exam PATCH. Being in the row301 /// not know about would be wiped by the next exam PATCH. Being in the row
303 /// is also what makes it useful — the save pins it, so a grade landing302 /// is also what makes it useful — the save pins it, so a grade landing
304 /// mid-PATCH refuses the save instead of slipping past its gates.303 /// mid-PATCH refuses the save instead of slipping past its gates.
305- result_count: Option<i64>,304+ pub(crate) result_count: Option<i64>,
306 }305 }
307 306
308 impl Exam {307 impl Exam {
@@ -388,1096 +387,4 @@ impl Exam {
388 pub fn is_creator(&self, user: &UserId) -> bool {387 pub fn is_creator(&self, user: &UserId) -> bool {
389 &self.creator == user388 &self.creator == user
390 }389 }
391-
392- #[expect(
393- clippy::too_many_arguments,
394- reason = "mirrors the sibling entities' create(field, field, ..) shape"
395- )]
396- pub async fn create(
397- creator: &UserId,
398- course: &CourseId,
399- title: ExamTitle,
400- description: ExamDescription,
401- kind: ExamKind,
402- schedule: ExamSchedule,
403- max_attempts: ExamAttemptLimit,
404- allow_rejoin: bool,
405- allow_review: bool,
406- draft: bool,
407- db: &Database,
408- ) -> Result<Exam, AppError> {
409- let exam = Exam {
410- id: ExamId::generate(),
411- creator: creator.clone(),
412- course: course.clone(),
413- title,
414- description,
415- kind,
416- mode: schedule.mode,
417- starts_at: schedule.starts_at,
418- ends_at: schedule.ends_at,
419- duration_ms: schedule.duration_ms,
420- max_attempts,
421- allow_rejoin,
422- allow_review,
423- draft,
424- result_count: None,
425- };
426- // The course row is *written* (bumped and put back), not read: a plain
427- // read does not survive `Course::delete`'s window, and an exam that
428- // outlives its course is unreachable for good — every route to one goes
429- // through `course_of`, which answers a 500 no delete can clear, while
430- // `GET /exams` still lists it. See [`cap::touch_and_create`].
431- cap::touch_and_create(
432- &course.record(),
433- ENROLLMENT_COUNT_FIELD,
434- &exam.id.record(),
435- &exam,
436- db,
437- )
438- .await?
439- .ok_or(AppError::NotFound)
440- }
441-
442- pub async fn read(id: &ExamId, db: &Database) -> Result<Option<Exam>, AppError> {
443- Ok(db.select(id.record()).await?)
444- }
445-
446- pub async fn list_all(db: &Database) -> Result<Vec<Exam>, AppError> {
447- let mut result = db
448- .query("SELECT * FROM exam ORDER BY id DESC")
449- .await?
450- .check()?;
451- Ok(result.take::<Vec<Exam>>(0)?)
452- }
453-
454- pub async fn list_for_course(course: &CourseId, db: &Database) -> Result<Vec<Exam>, AppError> {
455- let mut result = db
456- .query("SELECT * FROM exam WHERE course = $course ORDER BY id DESC")
457- .bind(("course", course.record()))
458- .await?
459- .check()?;
460- Ok(result.take::<Vec<Exam>>(0)?)
461- }
462-
463- /// Every exam of every course in `courses` (one query) — the catalog as one
464- /// user sees it.
465- pub async fn list_for_courses(
466- courses: &[CourseId],
467- db: &Database,
468- ) -> Result<Vec<Exam>, AppError> {
469- if courses.is_empty() {
470- return Ok(Vec::new());
471- }
472- let records: Vec<RecordId> = courses.iter().map(CourseId::record).collect();
473- let mut result = db
474- .query("SELECT * FROM exam WHERE course IN $courses ORDER BY id DESC")
475- .bind(("courses", records))
476- .await?
477- .check()?;
478- Ok(result.take::<Vec<Exam>>(0)?)
479- }
480-
481- // `course` is deliberately not updatable — moving an exam between courses
482- // would strand results of students not enrolled in the target course.
483- #[expect(
484- clippy::too_many_arguments,
485- reason = "mirrors the sibling entities' update(field, field, ..) shape"
486- )]
487- /// Save the merged exam, but only while the row still reads as the
488- /// snapshot the caller merged over — `None` means a concurrent PATCH
489- /// landed in between and nothing was written: re-read, re-merge, retry.
490- ///
491- /// Every column this write replaces is in the guard, which is what makes
492- /// the whole-row `CONTENT` save safe without a lock held across the
493- /// handler's read: the compare-and-set refuses precisely when that save
494- /// would have reverted somebody. `course`/`creator` are not editable and
495- /// ride along unchanged. Same shape as
496- /// [`crate::db::settings::save_if_unchanged`].
497- pub async fn update_if_unchanged(
498- mut self,
499- title: ExamTitle,
500- description: ExamDescription,
501- kind: ExamKind,
502- schedule: ExamSchedule,
503- max_attempts: ExamAttemptLimit,
504- allow_rejoin: bool,
505- allow_review: bool,
506- draft: bool,
507- db: &Database,
508- ) -> Result<Option<Exam>, AppError> {
509- // Re-drafting hides an exam: it must be refused while any sitting or
510- // mark exists, and that check has to be *in this transaction*. Holding
511- // it under a lock outside would only order the two writers inside one
512- // process — and it did not even do that, since grading takes the reader
513- // lease this write does.
514- let redraft = draft && !self.draft;
515- let was = (
516- self.title.clone(),
517- self.description.clone(),
518- self.kind.clone(),
519- self.mode.clone(),
520- self.starts_at,
521- self.ends_at,
522- self.duration_ms,
523- self.max_attempts,
524- self.allow_rejoin,
525- self.allow_review,
526- self.draft,
527- );
528- self.title = title;
529- self.description = description;
530- self.kind = kind;
531- self.mode = schedule.mode;
532- self.starts_at = schedule.starts_at;
533- self.ends_at = schedule.ends_at;
534- self.duration_ms = schedule.duration_ms;
535- self.max_attempts = max_attempts;
536- self.allow_rejoin = allow_rejoin;
537- self.allow_review = allow_review;
538- self.draft = draft;
539- // whole-row-save-ok: the WHERE below pins every column this replaces to
540- // the caller's snapshot, so no concurrent write can be reverted
541- //
542- // Sent through the retry loop, not a bare `query`: this row now has a
543- // hot writer. Every answer save touches it to tie itself to the exam
544- // ([`crate::domain::exam_answer::ExamAnswer::save`]), so a teacher
545- // flipping `allow_rejoin` mid-exam can lose a round to a student
546- // typing — and a lost round is a re-send, never the 500 a bare `?` on
547- // the conflict would have answered. Re-sending is sound because the
548- // statement is a compare-and-set: the second pass carries the same
549- // pinned snapshot, so it lands only if the row is still what the caller
550- // read, and a rival that really moved it is refused as it was before.
551- // Admissible for the loop — an `UPDATE`, an `IF`/`THROW` and a `SELECT`
552- // can never answer "already exists".
553- let (mut result, mut errors) = transaction_with_retry(
554- db,
555- "BEGIN TRANSACTION;
556- IF $redraft AND (
557- array::len((SELECT VALUE id FROM exam_attempt WHERE exam = $id LIMIT 1)) > 0
558- OR array::len((SELECT VALUE id FROM exam_result WHERE exam = $id LIMIT 1)) > 0
559- ) { THROW 'exam_redraft' };
560- UPDATE $id CONTENT $new
561- WHERE title = $was_title AND description = $was_description
562- AND kind = $was_kind AND mode = $was_mode
563- AND starts_at = $was_starts AND ends_at = $was_ends
564- AND duration_ms = $was_duration
565- AND max_attempts = $was_max_attempts
566- AND allow_rejoin = $was_allow_rejoin
567- AND allow_review = $was_allow_review
568- AND draft = $was_draft
569- AND (result_count ?? 0) = $was_results
570- RETURN AFTER;
571- COMMIT TRANSACTION;",
572- &[
573- ("redraft".into(), redraft.into_value()),
574- ("id".into(), self.id.record().into_value()),
575- ("was_title".into(), was.0.into_value()),
576- ("was_description".into(), was.1.into_value()),
577- ("was_kind".into(), was.2.into_value()),
578- ("was_mode".into(), was.3.into_value()),
579- ("was_starts".into(), was.4.into_value()),
580- ("was_ends".into(), was.5.into_value()),
581- ("was_duration".into(), was.6.into_value()),
582- ("was_max_attempts".into(), was.7.into_value()),
583- ("was_allow_rejoin".into(), was.8.into_value()),
584- ("was_allow_review".into(), was.9.into_value()),
585- ("was_draft".into(), was.10.into_value()),
586- // The mark counter is pinned like every other column this write
587- // replaces, and for a sharper reason: a grade increments it, so
588- // pinning it is what makes "this exam had no marks" — the gate
589- // the handler refuses a kind change on — true at *write* time
590- // and not merely at read time. A mark landing in between
591- // refuses the save.
592- (
593- "was_results".into(),
594- self.result_count.unwrap_or(0).into_value(),
595- ),
596- ("new".into(), self.into_value()),
597- ],
598- &["exam_redraft"],
599- )
600- .await?;
601- // An aborted transaction errors every slot; only the THROW's names the
602- // marker (the [`crate::db::exam_attempt::write_unfrozen`] treatment).
603- if errors
604- .values()
605- .any(|error| error.to_string().contains("exam_redraft"))
606- {
607- return Err(redraft_error());
608- }
609- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
610- return Err(error.into());
611- }
612- // BEGIN and the IF take a slot each.
613- Ok(result.take::<Vec<Exam>>(2)?.into_iter().next())
614- }
615-
616- /// Delete the exam and cascade-remove its result, attempt, question,
617- /// answer, question-image, and answer-image rows — all in one transaction,
618- /// so a failure can't leave an emptied-out exam shell behind. The image
619- /// *blobs* (question and answer) are the web layer's to remove — it collects
620- /// their names before calling this.
621- ///
622- /// Bank templates saved out of this exam survive it — they are a separate,
623- /// reusable library — so only their `source_exam` provenance link is cleared,
624- /// in the same transaction, never left pointing at a dead exam.
625- ///
626- /// The questions about to be cascaded each hold a reference on their
627- /// subject, which is what keeps that subject from being deleted under them.
628- /// They are given back in this same transaction, counted per subject, so
629- /// deleting an exam frees its subjects for deletion and nothing else does.
630- /// The marks give their *kind* references back the same way, and it has to
631- /// be the same way: counted outside the transaction, a mark deleted by a
632- /// concurrent `remove_result` in the gap would be released twice — once by
633- /// each — which on a kind another exam still uses reads as one mark too
634- /// few, and that is a kind wrongly free to leave the settings.
635- pub async fn delete(self, db: &Database) -> Result<Exam, AppError> {
636- let (mut result, mut errors) = transaction_with_retry(
637- db,
638- "BEGIN TRANSACTION;
639- FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result
640- WHERE exam = $ex GROUP BY kind) ?? []) {
641- UPDATE type::record('kind_ref', $row.kind) SET count =
642- math::max([(count ?? 0) - $row.n, 0])
643- };
644- DELETE exam_result WHERE exam = $ex;
645- DELETE exam_attempt WHERE exam = $ex;
646- DELETE exam_answer WHERE exam = $ex;
647- DELETE answer_image WHERE exam = $ex;
648- DELETE question_image WHERE exam = $ex;
649- FOR $row IN ((SELECT subject, count() AS n FROM exam_question
650- WHERE exam = $ex GROUP BY subject) ?? []) {
651- UPDATE $row.subject SET exam_question_count =
652- math::max([(exam_question_count ?? 0) - $row.n, 0])
653- };
654- DELETE exam_question WHERE exam = $ex;
655- UPDATE bank_question SET source_exam = NONE WHERE source_exam = $ex;
656- LET $before = (DELETE $ex RETURN BEFORE);
657- RETURN $before;
658- COMMIT TRANSACTION;",
659- &[("ex".into(), self.id.record().into_value())],
660- // No THROW of its own: an unconditional cascade, so the only error
661- // worth telling apart is a lost round, and `check()` — which took
662- // the *first* error in the batch — could not. It reported a
663- // sibling's "not executed" and made a retryable round a 500.
664- &[],
665- )
666- .await?;
667- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
668- return Err(error.into());
669- }
670- // The deleted row comes back through the transaction's trailing
671- // `RETURN`, never a hand-counted slot: the old `take(8)` turned a
672- // successful delete into a 404 the moment a cascade statement was
673- // inserted above it (it already had to be bumped once). `RETURN` is
674- // always the last statement before `COMMIT`, so its slot is derived
675- // from the statement count and every insertion above it shifts it
676- // along. `num_statements` counts BEGIN and COMMIT too, hence -2.
677- let slot = result.num_statements().saturating_sub(2);
678- let deleted: Option<Exam> = result.take::<Vec<Exam>>(slot)?.into_iter().next();
679- deleted.ok_or(AppError::NotFound)
680- }
681-}
682-
683-/// An unscheduled published exam — the minimum any test that writes a *child*
684-/// of an exam needs, in any module: every such write moves the exam row (see
685-/// [`crate::db::exam_attempt::write_unfrozen_with`]
686-/// and [`crate::domain::exam_answer::ExamAnswer::save`]), so a minted id whose
687-/// row was never created is a 404 rather than a silent orphan.
688-#[cfg(test)]
689-pub(crate) async fn published_exam(db: &Database) -> Exam {
690- let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
691- .get_exam_kinds()
692- .to_vec();
693- Exam::create(
694- &UserId::generate(),
695- &crate::db::course::a_test_course(db).await,
696- ExamTitle::try_new("midterm").unwrap(),
697- ExamDescription::try_new("").unwrap(),
698- ExamKind::try_new("midterm", &allowed).unwrap(),
699- ExamSchedule::try_new(None, None, None, None).unwrap(),
700- ExamAttemptLimit::try_new(1).unwrap(),
701- true,
702- false,
703- false,
704- db,
705- )
706- .await
707- .unwrap()
708-}
709-
710-#[cfg(test)]
711-mod tests {
712- use super::*;
713-
714- use crate::domain::exam::published_exam as published;
715-
716- /// An exam must not outlive the course it belongs to. It is the worst of
717- /// the three children `Course::delete` used to leave behind: every exam
718- /// route funnels through `course_of`, which answers
719- /// `Internal("exam references a missing course")`, so an orphan **500s
720- /// forever** on `GET`/`PATCH`/`DELETE /exams/{id}` — undeletable — while
721- /// `Exam::list_all` still hands it to every manager+ on `GET /exams`.
722- ///
723- /// [`Exam::create`] therefore *writes* the course row rather than reading
724- /// it ([`cap::touch_and_create`]); the harness and the window it races in
725- /// are documented on
726- /// [`crate::db::course::assert_no_child_outlives_a_course_delete`].
727- /// Mutation-tested: with the bare `db.create` this shipped with, all four
728- /// rounds orphan.
729- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
730- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
731- async fn an_exam_never_outlives_its_course() {
732- fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {
733- tokio::spawn(async move {
734- let kinds = crate::domain::settings::Settings::defaults()
735- .get_exam_kinds()
736- .to_vec();
737- Exam::create(
738- &UserId::generate(),
739- &course,
740- ExamTitle::try_new("quiz").unwrap(),
741- ExamDescription::try_new("").unwrap(),
742- ExamKind::try_new("quiz", &kinds).unwrap(),
743- ExamSchedule::try_new(None, None, None, None).unwrap(),
744- ExamAttemptLimit::try_new(1).unwrap(),
745- true,
746- false,
747- false,
748- &db,
749- )
750- .await
751- .map(|_| ())
752- })
753- }
754- crate::db::course::assert_no_child_outlives_a_course_delete(
755- "exam_orphan_race",
756- EXAM_TABLE,
757- make,
758- )
759- .await;
760- }
761-
762- fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) {
763- (
764- exam.get_title().clone(),
765- exam.get_description().clone(),
766- exam.get_kind().clone(),
767- ExamSchedule::try_new(None, None, None, None).unwrap(),
768- )
769- }
770-
771- /// The bite test for the compare-and-set that replaced the writer lease on
772- /// `PATCH /exams/{id}`: a merge built on a snapshot the row has moved past
773- /// must be refused (the handler then re-reads and re-merges), never
774- /// written over somebody else's edit. Asserts the *stored* row.
775- #[tokio::test]
776- async fn a_merge_built_on_a_stale_snapshot_is_refused() {
777- let db = crate::database::init_mem().await.unwrap();
778- let stale = published(&db).await;
779- let (_, description, kind, schedule) = edit(&stale);
780- let landed = stale
781- .clone()
782- .update_if_unchanged(
783- ExamTitle::try_new("theirs").unwrap(),
784- description,
785- kind,
786- schedule,
787- ExamAttemptLimit::try_new(1).unwrap(),
788- true,
789- false,
790- false,
791- &db,
792- )
793- .await
794- .unwrap();
795- assert!(landed.is_some(), "the first write is on a fresh snapshot");
796-
797- let (_, description, kind, schedule) = edit(&stale);
798- let refused = stale
799- .update_if_unchanged(
800- ExamTitle::try_new("mine").unwrap(),
801- description,
802- kind,
803- schedule,
804- ExamAttemptLimit::try_new(1).unwrap(),
805- true,
806- false,
807- false,
808- &db,
809- )
810- .await
811- .unwrap();
812- assert!(refused.is_none(), "a stale merge must not be written");
813- let stored = Exam::read(landed.unwrap().get_id(), &db)
814- .await
815- .unwrap()
816- .unwrap();
817- assert_eq!(stored.get_title().as_str(), "theirs");
818- }
819-
820- /// The bite test for the re-draft guard now living *inside* the update's
821- /// transaction: a mark that lands after the handler's pre-flight gate (the
822- /// grade path is a lock reader, exactly like this one) must still stop the
823- /// exam from being hidden.
824- #[tokio::test]
825- async fn re_drafting_is_refused_by_the_write_itself_once_a_mark_exists() {
826- use crate::domain::exam_result::{ExamResult, Mark};
827- let db = crate::database::init_mem().await.unwrap();
828- let exam = published(&db).await;
829- let student = UserId::generate();
830- ExamResult::grade(
831- exam.get_id(),
832- &student,
833- 1,
834- Mark::try_new(80).unwrap(),
835- &UserId::generate(),
836- exam.get_kind().as_str(),
837- &db,
838- )
839- .await
840- .unwrap();
841-
842- let (title, description, kind, schedule) = edit(&exam);
843- let refused = exam
844- .clone()
845- .update_if_unchanged(
846- title,
847- description,
848- kind,
849- schedule,
850- ExamAttemptLimit::try_new(1).unwrap(),
851- true,
852- false,
853- true,
854- &db,
855- )
856- .await
857- .expect_err("a graded exam cannot be re-drafted");
858- assert!(refused.to_string().contains("back into a draft"));
859- let stored = Exam::read(exam.get_id(), &db).await.unwrap().unwrap();
860- assert!(!stored.is_draft(), "nothing may have been written");
861- }
862-
863- #[tokio::test]
864- async fn title_is_required() {
865- assert!(ExamTitle::try_new("midterm").is_ok());
866- assert!(ExamTitle::try_new("").is_err());
867- assert!(ExamTitle::try_new(" ").is_err());
868- }
869-
870- #[tokio::test]
871- async fn description_is_optional() {
872- assert!(ExamDescription::try_new("").is_ok());
873- }
874-
875- #[tokio::test]
876- async fn kind_must_be_in_the_allowed_list() {
877- let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
878- .get_exam_kinds()
879- .to_vec();
880- for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] {
881- assert_eq!(ExamKind::try_new(kind, &allowed).unwrap().as_str(), kind);
882- }
883- assert!(ExamKind::try_new("essay", &allowed).is_err());
884- assert!(ExamKind::try_new("", &allowed).is_err());
885- // A school-defined list swaps the acceptance set wholesale.
886- let custom = vec![ExamKindDef::try_new("lab", 2).unwrap()];
887- assert!(ExamKind::try_new("lab", &custom).is_ok());
888- assert!(ExamKind::try_new("midterm", &custom).is_err());
889- // Matching is exact, case included — the settings list is the wire
890- // truth, not a case-folded suggestion.
891- assert!(ExamKind::try_new("Lab", &custom).is_err());
892- }
893-
894- #[tokio::test]
895- async fn mode_must_be_known() {
896- for mode in ["sync", "async", "open"] {
897- assert_eq!(ExamMode::try_new(mode).unwrap().as_str(), mode);
898- }
899- assert!(ExamMode::try_new("live").is_err());
900- }
901-
902- #[tokio::test]
903- async fn attempt_limit_counts_or_never_runs_out() {
904- let single = ExamAttemptLimit::single();
905- assert_eq!(single.as_i64(), 1);
906- assert!(!single.is_unlimited());
907- assert!(single.allows_another(0));
908- assert!(!single.allows_another(1));
909-
910- let three = ExamAttemptLimit::try_new(3).unwrap();
911- assert!(three.allows_another(2));
912- assert!(!three.allows_another(3));
913- assert!(!three.allows_another(4));
914-
915- let unlimited = ExamAttemptLimit::try_new(0).unwrap();
916- assert!(unlimited.is_unlimited());
917- assert!(unlimited.allows_another(0));
918- assert!(unlimited.allows_another(10_000));
919-
920- assert!(ExamAttemptLimit::try_new(-1).is_err());
921- assert!(ExamAttemptLimit::try_new(101).is_err());
922- }
923-
924- #[tokio::test]
925- async fn schedule_invariants_hold() {
926- let mode = |m| Some(ExamMode::try_new(m).unwrap());
927- let at = |ms| Some(Timestamp::from_millis(ms));
928- let dur = Some(ExamDuration::try_new(90 * 60 * 1000).unwrap());
929-
930- // Unscheduled: nothing set is fine, any time/duration without a mode is not.
931- assert!(ExamSchedule::try_new(None, None, None, None).is_ok());
932- assert!(ExamSchedule::try_new(None, at(1), None, None).is_err());
933- assert!(ExamSchedule::try_new(None, None, at(2), None).is_err());
934- assert!(ExamSchedule::try_new(None, None, None, dur).is_err());
935-
936- // Sync: fixed window, no duration.
937- assert!(ExamSchedule::try_new(mode("sync"), at(1), at(2), None).is_ok());
938- assert!(ExamSchedule::try_new(mode("sync"), None, at(2), None).is_err());
939- assert!(ExamSchedule::try_new(mode("sync"), at(1), None, None).is_err());
940- // Over-long `dur` in a 1ms window, but the root cause is that sync
941- // takes no duration at all — that message wins over the window one.
942- assert!(matches!(
943- ExamSchedule::try_new(mode("sync"), at(1), at(2), dur),
944- Err(ValidationError::Invalid {
945- reason: "only async and open exams take a duration",
946- ..
947- })
948- ));
949-
950- // Async: window plus a per-student duration, which must fit inside it
951- // (equal to the window is fine; the window `at(1), at(2)` above is
952- // too narrow for `dur`, so give it one exactly `dur` wide instead).
953- assert!(ExamSchedule::try_new(mode("async"), at(1), at(1 + 90 * 60 * 1000), dur).is_ok());
954- assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), dur).is_err());
955- assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), None).is_err());
956-
957- // Open: no window, duration optional (limited or unlimited time).
958- assert!(ExamSchedule::try_new(mode("open"), None, None, None).is_ok());
959- assert!(ExamSchedule::try_new(mode("open"), None, None, dur).is_ok());
960- assert!(ExamSchedule::try_new(mode("open"), at(1), None, None).is_err());
961- assert!(ExamSchedule::try_new(mode("open"), None, at(2), None).is_err());
962- assert!(ExamSchedule::try_new(mode("open"), at(1), at(2), dur).is_err());
963-
964- // The window must be a real interval, whatever the mode.
965- assert!(ExamSchedule::try_new(mode("sync"), at(2), at(2), None).is_err());
966- assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err());
967- }
968-
969- /// GUARD, not a retry measurement — read the last paragraph before
970- /// trusting this test with the retry. See
971- /// [`crate::db::course::delete`]'s race test for why the rate is
972- /// counted rather than asserted per round.
973- ///
974- /// This site has no `THROW` marker at all: it ends `.check()?`, which
975- /// returns the *first* error in the batch, and an aborted transaction
976- /// errors every slot — most of them with a generic "not executed". So a
977- /// genuine conflict can be masked by a sibling, and either way there is no
978- /// [`crate::database::lost_the_race`] check and no retry.
979- ///
980- /// The racer is a mark: [`ExamResult::grade`] claims the exam's own
981- /// `result_count` (and the kind's reference) before writing, so it contends
982- /// with the `DELETE $ex` and with the kind_ref decrement inside the same
983- /// transaction. A round where *some* of the six grades 404 and the rest
984- /// succeed is the witness that the delete landed inside the burst: the 404
985- /// comes from `write_mark`'s existence gate, so it can only be answered by a
986- /// grade that reached the store after the row was gone, and its siblings'
987- /// success says the same burst also had grades that got there first. Stored
988- /// state cannot say this any more — the gate is what stops a mark outliving
989- /// its exam, so the sweep now finds nothing to leave behind in *every*
990- /// round, which is asserted below as a fact rather than read as a signal.
991- ///
992- /// It does not prove the retry either: measured at 0 conflicts in 100 raced
993- /// rounds, and green with
994- /// [`crate::database::transaction_with_retry`]'s loop cut to a single
995- /// attempt — the grades serialize behind `cap`'s claim lock, so they mostly
996- /// queue rather than collide. So this guards the status codes and the
997- /// cascade (marks either survive whole or are swept whole, never a 500).
998- /// The retry is measured on [`crate::db::course::delete`].
999- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1000- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1001- async fn a_delete_racing_a_mark_never_answers_500() {
1002- use crate::domain::exam_result::{ExamResult, Mark};
1003- let (db, _serialized) = crate::database::init_test_server("exam_delete_race").await;
1004- let (mut delete_500, mut grade_500) = (0, 0);
1005- let (mut split, mut swept) = (0, 0);
1006- let (mut last_delete, mut last_grade) = (String::new(), String::new());
1007- for round in 0..20 {
1008- let exam = published(&db).await;
1009- let kind = exam.get_kind().as_str().to_string();
1010-
1011- // A burst of marks and a delete held back by a sweeping beat: this
1012- // site has no guard to lose to, so a single racer released with it
1013- // simply finishes on one side of it. Same recipe as
1014- // [`crate::db::course::delete`]'s race test.
1015- let drop_it = {
1016- let (exam, db) = (exam.clone(), db.clone());
1017- // A wide sweep, not the 0-3ms the other three use: each grade
1018- // takes two counter writes serialized behind `cap`'s claim
1019- // lock, so the burst runs tens of milliseconds and a short beat
1020- // always puts the delete in front of all six.
1021- let beat = std::time::Duration::from_millis(round * 2);
1022- tokio::spawn(async move {
1023- tokio::time::sleep(beat).await;
1024- exam.delete(&db).await
1025- })
1026- };
1027- let marks: Vec<_> = (0..6)
1028- .map(|seat| {
1029- let (id, db, kind) = (exam.get_id().clone(), db.clone(), kind.clone());
1030- let student = UserId::from_key(&format!("stu{round}_{seat}"));
1031- tokio::spawn(async move {
1032- ExamResult::grade(
1033- &id,
1034- &student,
1035- 1,
1036- Mark::try_new(50).unwrap(),
1037- &UserId::from_key("teacher"),
1038- &kind,
1039- &db,
1040- )
1041- .await
1042- })
1043- })
1044- .collect();
1045- let drop_it = drop_it.await.unwrap();
1046- if matches!(drop_it, Err(AppError::Db(_))) {
1047- delete_500 += 1;
1048- last_delete = format!("{drop_it:?}");
1049- }
1050- let mut refused = 0;
1051- for mark in marks {
1052- let mark = mark.await.unwrap();
1053- match mark {
1054- // The existence gate: this grade reached the store after
1055- // the row was gone.
1056- Err(AppError::NotFound) => refused += 1,
1057- Err(AppError::Db(_)) => {
1058- grade_500 += 1;
1059- last_grade = format!("{mark:?}");
1060- }
1061- _ => {}
1062- }
1063- }
1064- // Neither end of the burst: some grades beat the delete and some
1065- // lost to it, so the delete landed *between* them. A round that is
1066- // all-refused or all-through is one where it landed outside.
1067- if (1..6).contains(&refused) {
1068- split += 1;
1069- }
1070- if ExamResult::list_for_exam(exam.get_id(), &db)
1071- .await
1072- .unwrap()
1073- .is_empty()
1074- {
1075- swept += 1;
1076- }
1077- }
1078- eprintln!(
1079- "Exam::delete raced: {delete_500}/20 delete 500s, {grade_500} grade 500s, \
1080- {split} rounds split by the delete / {swept} swept clean"
1081- );
1082- assert!(
1083- split > 0,
1084- "the delete never landed inside the burst (0/20 rounds split)"
1085- );
1086- // Not a race signal, an invariant: the gate refuses a mark for an exam
1087- // that is gone, so no round can leave one behind for the next reader.
1088- assert_eq!(
1089- swept,
1090- 20,
1091- "a mark outlived its exam in {} rounds",
1092- 20 - swept
1093- );
1094- assert_eq!(
1095- delete_500, 0,
1096- "a raced delete must not 500: {delete_500}/20 rounds, last {last_delete}"
1097- );
1098- assert_eq!(
1099- grade_500, 0,
1100- "a raced grade must retry, not 500: {grade_500}/20 rounds, last {last_grade}"
1101- );
1102- }
1103-
1104- /// One choice question on `exam`, with a real subject row behind it — a
1105- /// question claims a reference on its subject and is refused without one.
1106- async fn question_on(exam: &Exam, db: &Database) -> crate::domain::exam_question::ExamQuestion {
1107- use crate::domain::exam_question::{
1108- ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
1109- };
1110- let spec = QuestionSpec::try_new(
1111- QuestionKind::try_new("choice").unwrap(),
1112- Some(vec![
1113- ChoiceInput {
1114- id: Some("a".into()),
1115- text: "5".into(),
1116- },
1117- ChoiceInput {
1118- id: Some("b".into()),
1119- text: "6".into(),
1120- },
1121- ]),
1122- Some("b".into()),
1123- &[],
1124- )
1125- .unwrap();
1126- let subject = crate::domain::subject::Subject::create(
1127- &crate::db::course::a_test_course(db).await,
1128- crate::domain::subject::SubjectName::try_new("topic").unwrap(),
1129- crate::domain::subject::SubjectDescription::try_new("").unwrap(),
1130- db,
1131- )
1132- .await
1133- .unwrap();
1134- crate::db::exam_question::create(
1135- db,
1136- exam.get_id(),
1137- subject.get_id().clone(),
1138- QuestionText::try_new("3 + 3?").unwrap(),
1139- QuestionPoints::try_new(5).unwrap(),
1140- spec,
1141- )
1142- .await
1143- .unwrap()
1144- }
1145-
1146- /// The `Menu::delete` defect, one domain over: a student's answer must not
1147- /// outlive the exam it belongs to. Guarding the save by *reading* the exam
1148- /// would not do it — the read sees a row [`Exam::delete`] has removed but
1149- /// not committed, while its `DELETE exam_answer WHERE exam = $ex` swept a
1150- /// snapshot predating the save, so both commit and the answer is left
1151- /// pointing at an exam that is gone. [`ExamAnswer::save`] writes the exam
1152- /// row instead (its `result_count`, back unchanged), so the two transactions
1153- /// touch one key and the store refuses one of them.
1154- ///
1155- /// The window is opened by the database, not by a lucky interleaving: a
1156- /// `DEFINE EVENT` on `exam` fires *inside* the delete's own transaction the
1157- /// instant the row goes, so the `SLEEP` lands exactly between the delete and
1158- /// its cascade every time. Nothing in `src/` knows about it; the seam is the
1159- /// schema.
1160- ///
1161- /// One child per round, deliberately — in the menu twin, two children in one
1162- /// round hid the bug: the first writer made the delete lose and re-send, and
1163- /// the re-sent sweep removed the other's row.
1164- ///
1165- /// Real server, and `#[ignore]`d for it: the subject *is* the store's
1166- /// conflict detection, which `init_mem`'s embedded engine does not have — it
1167- /// commits both writes and answers `Ok` to each, so this passes there on
1168- /// broken code. Mutation-tested: putting the bare
1169- /// `db.upsert(id).content(answer)` back turns it red (the exact output is in
1170- /// the commit that added it).
1171- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1172- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1173- async fn an_answer_written_inside_a_delete_never_outlives_the_exam() {
1174- use crate::domain::exam_answer::ExamAnswer;
1175- let (db, _serialized) = crate::database::init_test_server("exam_answer_race").await;
1176- // Hold the delete open for a full second after the row is gone, while
1177- // its cascade still has to run.
1178- db.query(
1179- "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1180- THEN { SLEEP 1s; };",
1181- )
1182- .await
1183- .unwrap()
1184- .check()
1185- .unwrap();
1186-
1187- let (mut answers, mut swept) = (0, 0);
1188- for round in 0..4 {
1189- let exam = published(&db).await;
1190- let question = question_on(&exam, &db).await;
1191- let id = exam.get_id().clone();
1192- let student = UserId::from_key(&format!("stu{round}"));
1193- // The stored choice ids are minted by the create, not the ones the
1194- // spec asked for — an answer must name one of *those*.
1195- let pick = question.get_choices().unwrap()[1]
1196- .get_id()
1197- .as_str()
1198- .to_string();
1199-
1200- let drop_it = {
1201- let db = db.clone();
1202- tokio::spawn(async move { exam.delete(&db).await })
1203- };
1204- // The save starts inside the held window — the exam row is gone but
1205- // uncommitted, which is exactly what an exam read believes.
1206- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1207- let child = {
1208- let (db, question, student) = (db.clone(), question.clone(), student.clone());
1209- tokio::spawn(async move {
1210- ExamAnswer::save(&question, &student, 1, Some(pick), None, &db).await
1211- })
1212- };
1213- let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1214- // A 404 for the save, or a NotFound for the delete, is a correct
1215- // answer — the only defect is stored state.
1216- assert!(
1217- !matches!(child, Err(AppError::Db(_))),
1218- "round {round}: a raced save must be answered, not 500: {child:?}"
1219- );
1220-
1221- // Stored state is the whole verdict; a return value is not evidence.
1222- if Exam::read(&id, &db).await.unwrap().is_none() {
1223- swept += 1;
1224- answers += ExamAnswer::list_for_exam(&id, &db).await.unwrap().len();
1225- } else if drop_it.is_ok() {
1226- panic!("round {round}: the delete reported success but the exam is still there");
1227- }
1228- }
1229- eprintln!("Exam::delete raced by an answer save: {swept}/4 rounds deleted the exam");
1230- assert!(
1231- swept > 0,
1232- "no round ever deleted the exam, so the window was never reached"
1233- );
1234- assert_eq!(answers, 0, "an answer outlived its exam");
1235- }
1236-
1237- /// The same defect on the teacher's side of the sheet, and a worse one: a
1238- /// question written inside the delete window kept the reference it claimed
1239- /// on its subject (the cascade's per-subject decrement counted only the
1240- /// rows it could see), and [`crate::domain::subject::Subject::delete`] is
1241- /// gated on that count reading zero — a subject nobody could ever delete
1242- /// again, hanging off an exam nobody could ever see. The freeze gate is a
1243- /// *read* of `exam_attempt` and never survived this window;
1244- /// [`crate::db::exam_attempt::write_unfrozen_with`] now writes the exam row too.
1245- ///
1246- /// Same seam, same `#[ignore]`, same reason as the answer twin above: the
1247- /// subject *is* the store's conflict detection, which the in-memory engine
1248- /// does not have.
1249- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1250- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1251- async fn a_question_written_inside_a_delete_never_outlives_the_exam() {
1252- use crate::domain::exam_question::{
1253- ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
1254- };
1255- use crate::domain::subject::Subject;
1256- let (db, _serialized) = crate::database::init_test_server("exam_question_race").await;
1257- db.query(
1258- "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1259- THEN { SLEEP 1s; };",
1260- )
1261- .await
1262- .unwrap()
1263- .check()
1264- .unwrap();
1265-
1266- let (mut questions, mut swept, mut stuck) = (0, 0, 0);
1267- for round in 0..4 {
1268- let exam = published(&db).await;
1269- let id = exam.get_id().clone();
1270- let subject = Subject::create(
1271- &crate::db::course::a_test_course(&db).await,
1272- crate::domain::subject::SubjectName::try_new("topic").unwrap(),
1273- crate::domain::subject::SubjectDescription::try_new("").unwrap(),
1274- &db,
1275- )
1276- .await
1277- .unwrap();
1278-
1279- let drop_it = {
1280- let db = db.clone();
1281- tokio::spawn(async move { exam.delete(&db).await })
1282- };
1283- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1284- let child = {
1285- let (db, exam_id, on) = (db.clone(), id.clone(), subject.get_id().clone());
1286- tokio::spawn(async move {
1287- let spec = QuestionSpec::try_new(
1288- QuestionKind::try_new("choice").unwrap(),
1289- Some(vec![
1290- ChoiceInput {
1291- id: Some("a".into()),
1292- text: "5".into(),
1293- },
1294- ChoiceInput {
1295- id: Some("b".into()),
1296- text: "6".into(),
1297- },
1298- ]),
1299- Some("b".into()),
1300- &[],
1301- )
1302- .unwrap();
1303- crate::db::exam_question::create(
1304- &db,
1305- &exam_id,
1306- on,
1307- QuestionText::try_new("3 + 3?").unwrap(),
1308- QuestionPoints::try_new(5).unwrap(),
1309- spec,
1310- )
1311- .await
1312- })
1313- };
1314- let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1315- assert!(
1316- !matches!(child, Err(AppError::Db(_))),
1317- "round {round}: a raced question write must be answered, not 500: {child:?}"
1318- );
1319-
1320- if Exam::read(&id, &db).await.unwrap().is_none() {
1321- swept += 1;
1322- questions += crate::db::exam_question::list_for_exam(&db, &id, None, 0)
1323- .await
1324- .unwrap()
1325- .0
1326- .len();
1327- // The subject has to be free again: a stranded reference is the
1328- // half of this bug a row count alone would not catch.
1329- if Subject::read(subject.get_id(), &db)
1330- .await
1331- .unwrap()
1332- .unwrap()
1333- .delete(&db)
1334- .await
1335- .is_err()
1336- {
1337- stuck += 1;
1338- }
1339- } else if drop_it.is_ok() {
1340- panic!("round {round}: the delete reported success but the exam is still there");
1341- }
1342- }
1343- eprintln!("Exam::delete raced by a question write: {swept}/4 rounds deleted the exam");
1344- assert!(
1345- swept > 0,
1346- "no round ever deleted the exam, so the window was never reached"
1347- );
1348- assert_eq!(questions, 0, "a question outlived its exam");
1349- assert_eq!(stuck, 0, "an orphan question left its subject undeletable");
1350- }
1351-
1352- /// The student's half of the same picture problem: a drawing is a bare
1353- /// `UPSERT` — the exact pre-fix shape of [`ExamAnswer::save`] — so it kept
1354- /// the hole the text answer just lost, blob and all.
1355- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1356- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1357- async fn a_drawing_written_inside_a_delete_never_outlives_the_exam() {
1358- use crate::domain::answer_image::AnswerImage;
1359- use crate::domain::note_file::FileContentType;
1360- let (db, _serialized) = crate::database::init_test_server("answer_image_race").await;
1361- db.query(
1362- "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1363- THEN { SLEEP 1s; };",
1364- )
1365- .await
1366- .unwrap()
1367- .check()
1368- .unwrap();
1369-
1370- let (mut drawings, mut swept) = (0, 0);
1371- for round in 0..4 {
1372- let exam = published(&db).await;
1373- let question = question_on(&exam, &db).await;
1374- let id = exam.get_id().clone();
1375- let student = UserId::from_key(&format!("stu{round}"));
1376-
1377- let drop_it = {
1378- let db = db.clone();
1379- tokio::spawn(async move { exam.delete(&db).await })
1380- };
1381- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1382- let child = {
1383- let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone());
1384- tokio::spawn(async move {
1385- AnswerImage::new(
1386- &exam_id,
1387- &on,
1388- &student,
1389- 1,
1390- FileContentType::try_new("image/png").unwrap(),
1391- 3,
1392- )
1393- .upsert(&db)
1394- .await
1395- })
1396- };
1397- let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1398- assert!(
1399- !matches!(child, Err(AppError::Db(_))),
1400- "round {round}: a raced drawing write must be answered, not 500: {child:?}"
1401- );
1402-
1403- if Exam::read(&id, &db).await.unwrap().is_none() {
1404- swept += 1;
1405- drawings += AnswerImage::list_for_exam(&id, &db).await.unwrap().len();
1406- } else if drop_it.is_ok() {
1407- panic!("round {round}: the delete reported success but the exam is still there");
1408- }
1409- }
1410- eprintln!("Exam::delete raced by a drawing write: {swept}/4 rounds deleted the exam");
1411- assert!(
1412- swept > 0,
1413- "no round ever deleted the exam, so the window was never reached"
1414- );
1415- assert_eq!(drawings, 0, "a drawing outlived its exam");
1416- }
1417-
1418- /// A picture is written through the same freeze gate as the question it
1419- /// hangs on, so it had the same hole — and one the row count does not even
1420- /// show: `delete_exam` collects the blob names to unlink *before* it calls
1421- /// [`Exam::delete`], so an image row landing after that snapshot strands
1422- /// its bytes on disk forever as well.
1423- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1424- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1425- async fn a_picture_written_inside_a_delete_never_outlives_the_exam() {
1426- use crate::domain::note_file::FileContentType;
1427- use crate::domain::question_image::QuestionImage;
1428- let (db, _serialized) = crate::database::init_test_server("question_image_race").await;
1429- db.query(
1430- "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1431- THEN { SLEEP 1s; };",
1432- )
1433- .await
1434- .unwrap()
1435- .check()
1436- .unwrap();
1437-
1438- let (mut images, mut swept) = (0, 0);
1439- for round in 0..4 {
1440- let exam = published(&db).await;
1441- let question = question_on(&exam, &db).await;
1442- let id = exam.get_id().clone();
1443-
1444- let drop_it = {
1445- let db = db.clone();
1446- tokio::spawn(async move { exam.delete(&db).await })
1447- };
1448- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1449- let child = {
1450- let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone());
1451- tokio::spawn(async move {
1452- QuestionImage::new(
1453- &exam_id,
1454- &on,
1455- None,
1456- FileContentType::try_new("image/png").unwrap(),
1457- 3,
1458- )
1459- .upsert(&db)
1460- .await
1461- })
1462- };
1463- let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1464- assert!(
1465- !matches!(child, Err(AppError::Db(_))),
1466- "round {round}: a raced picture write must be answered, not 500: {child:?}"
1467- );
1468-
1469- if Exam::read(&id, &db).await.unwrap().is_none() {
1470- swept += 1;
1471- images += QuestionImage::list_for_exam(&id, &db).await.unwrap().len();
1472- } else if drop_it.is_ok() {
1473- panic!("round {round}: the delete reported success but the exam is still there");
1474- }
1475- }
1476- eprintln!("Exam::delete raced by a picture write: {swept}/4 rounds deleted the exam");
1477- assert!(
1478- swept > 0,
1479- "no round ever deleted the exam, so the window was never reached"
1480- );
1481- assert_eq!(images, 0, "a picture outlived its exam");
1482- }
1483 }390 }
src/domain/exam_answer.rsmodified+7 -7
@@ -173,7 +173,7 @@ impl ExamAnswer {
173 };173 };
174 // The save writes the *exam row* as well as the answer, in one174 // The save writes the *exam row* as well as the answer, in one
175 // transaction, and that is what ties the answer's fate to its exam:175 // transaction, and that is what ties the answer's fate to its exam:
176- // reading the exam does not survive [`crate::domain::exam::Exam::delete`]'s176+ // reading the exam does not survive [`crate::db::exam::delete`]'s
177 // window — a save landing after its `DELETE exam_answer WHERE exam = $ex`177 // window — a save landing after its `DELETE exam_answer WHERE exam = $ex`
178 // but before the commit reads an exam that is still there (uncommitted)178 // but before the commit reads an exam that is still there (uncommitted)
179 // while the sweep ran on a snapshot predating this row, so both commit179 // while the sweep ran on a snapshot predating this row, so both commit
@@ -240,7 +240,7 @@ impl ExamAnswer {
240 }240 }
241 // The trailing `RETURN` is the last statement before `COMMIT`, so its241 // The trailing `RETURN` is the last statement before `COMMIT`, so its
242 // slot follows the statement count rather than a hand-kept number (the242 // slot follows the statement count rather than a hand-kept number (the
243- // `Exam::delete` treatment); `num_statements` counts BEGIN and COMMIT.243+ // `db::exam::delete` treatment); `num_statements` counts BEGIN and COMMIT.
244 let slot = result.num_statements().saturating_sub(2);244 let slot = result.num_statements().saturating_sub(2);
245 result245 result
246 .take::<Vec<ExamAnswer>>(slot)?246 .take::<Vec<ExamAnswer>>(slot)?
@@ -491,22 +491,23 @@ mod tests {
491 }491 }
492 492
493 /// The bite test for the exam-row touch in [`ExamAnswer::save`]: it exists493 /// The bite test for the exam-row touch in [`ExamAnswer::save`]: it exists
494- /// to collide with [`crate::domain::exam::Exam::delete`], so it must leave494+ /// to collide with [`crate::db::exam::delete`], so it must leave
495 /// the counter it borrows exactly where it found it — absent stays absent495 /// the counter it borrows exactly where it found it — absent stays absent
496 /// (the boot backfill keys on `result_count = NONE`), and a real count is496 /// (the boot backfill keys on `result_count = NONE`), and a real count is
497 /// not moved by a student typing. The race half is497 /// not moved by a student typing. The race half is
498- /// `domain::exam::tests::an_answer_written_inside_a_delete_never_outlives_the_exam`,498+ /// `db::exam::tests::an_answer_written_inside_a_delete_never_outlives_the_exam`,
499 /// which needs a real server; this half is the arithmetic and runs anywhere.499 /// which needs a real server; this half is the arithmetic and runs anywhere.
500 #[tokio::test]500 #[tokio::test]
501 async fn a_save_puts_the_exams_mark_counter_back_exactly() {501 async fn a_save_puts_the_exams_mark_counter_back_exactly() {
502 use crate::domain::exam::{502 use crate::domain::exam::{
503- Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,503+ ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,
504 };504 };
505 let db = crate::database::init_mem().await.unwrap();505 let db = crate::database::init_mem().await.unwrap();
506 let kinds = crate::domain::settings::Settings::defaults()506 let kinds = crate::domain::settings::Settings::defaults()
507 .get_exam_kinds()507 .get_exam_kinds()
508 .to_vec();508 .to_vec();
509- let exam = Exam::create(509+ let exam = crate::db::exam::create(
510+ &db,
510 &student(),511 &student(),
511 &crate::db::course::a_test_course(&db).await,512 &crate::db::course::a_test_course(&db).await,
512 ExamTitle::try_new("quiz").unwrap(),513 ExamTitle::try_new("quiz").unwrap(),
@@ -517,7 +518,6 @@ mod tests {
517 true,518 true,
518 false,519 false,
519 false,520 false,
520- &db,
521 )521 )
522 .await522 .await
523 .unwrap();523 .unwrap();
src/domain/homework.rsmodified+2 -2
@@ -18,8 +18,8 @@ use crate::constant::{
18 };18 };
19 use crate::database::Database;19 use crate::database::Database;
20 use crate::db::cap;20 use crate::db::cap;
21-use crate::domain::course::CourseId;
22 use crate::db::field_update::FieldUpdate;21 use crate::db::field_update::FieldUpdate;
22+use crate::domain::course::CourseId;
23 use crate::domain::monotonic_id::next_ulid;23 use crate::domain::monotonic_id::next_ulid;
24 use crate::domain::subject::SubjectId;24 use crate::domain::subject::SubjectId;
25 use crate::domain::timestamp::Timestamp;25 use crate::domain::timestamp::Timestamp;
@@ -370,7 +370,7 @@ impl Homework {
370 .check()?;370 .check()?;
371 // The subject's reference is given back in this same transaction, off371 // The subject's reference is given back in this same transaction, off
372 // what the delete actually removed. Read through the trailing `RETURN`,372 // what the delete actually removed. Read through the trailing `RETURN`,
373- // not a hand-counted slot — see [`crate::domain::exam::Exam::delete`].373+ // not a hand-counted slot — see [`crate::db::exam::delete`].
374 let slot = result.num_statements().saturating_sub(2);374 let slot = result.num_statements().saturating_sub(2);
375 let deleted: Option<Homework> = result.take::<Vec<Homework>>(slot)?.into_iter().next();375 let deleted: Option<Homework> = result.take::<Vec<Homework>>(slot)?.into_iter().next();
376 deleted.ok_or(AppError::NotFound)376 deleted.ok_or(AppError::NotFound)
src/domain/question_image.rsmodified+1 -4
@@ -258,10 +258,7 @@ mod tests {
258 /// keeps a picture from outliving its exam), so a minted id nothing wrote258 /// keeps a picture from outliving its exam), so a minted id nothing wrote
259 /// is a 404.259 /// is a 404.
260 async fn exam_row(db: &Database) -> ExamId {260 async fn exam_row(db: &Database) -> ExamId {
261- crate::domain::exam::published_exam(db)261+ crate::db::exam::published_exam(db).await.get_id().clone()
262- .await
263- .get_id()
264- .clone()
265 }262 }
266 263
267 fn png() -> FileContentType {264 fn png() -> FileContentType {
src/domain/subject.rsmodified+2 -5
@@ -244,7 +244,7 @@ impl Subject {
244 return Err(error.into());244 return Err(error.into());
245 }245 }
246 // Read through the trailing `RETURN`, not a counted slot — see246 // Read through the trailing `RETURN`, not a counted slot — see
247- // [`crate::domain::exam::Exam::delete`].247+ // [`crate::db::exam::delete`].
248 let slot = result.num_statements().saturating_sub(2);248 let slot = result.num_statements().saturating_sub(2);
249 let deleted: Option<Subject> = result.take::<Vec<Subject>>(slot)?.into_iter().next();249 let deleted: Option<Subject> = result.take::<Vec<Subject>>(slot)?.into_iter().next();
250 deleted.ok_or(AppError::NotFound)250 deleted.ok_or(AppError::NotFound)
@@ -358,10 +358,7 @@ mod tests {
358 // A real exam row per round: a question write moves its exam's358 // A real exam row per round: a question write moves its exam's
359 // counter, so a minted id nothing wrote is a 404 and no round would359 // counter, so a minted id nothing wrote is a 404 and no round would
360 // reach the subject race this test is about.360 // reach the subject race this test is about.
361- let exam = crate::domain::exam::published_exam(&db)361+ let exam = crate::db::exam::published_exam(&db).await.get_id().clone();
362- .await
363- .get_id()
364- .clone();
365 let subject = Subject::create(362 let subject = Subject::create(
366 &course,363 &course,
367 SubjectName::try_new("Limits").unwrap(),364 SubjectName::try_new("Limits").unwrap(),
src/service/course.rsmodified+2 -3
@@ -11,8 +11,8 @@ use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, Cou
11 use crate::domain::course_note_file::CourseNoteFile;11 use crate::domain::course_note_file::CourseNoteFile;
12 use crate::domain::homework_file::HomeworkFile;12 use crate::domain::homework_file::HomeworkFile;
13 use crate::domain::question_image::QuestionImage;13 use crate::domain::question_image::QuestionImage;
14-use crate::domain::term::{self, TermId};
15 use crate::domain::role::Role;14 use crate::domain::role::Role;
15+use crate::domain::term::{self, TermId};
16 use crate::domain::user::{User, UserId};16 use crate::domain::user::{User, UserId};
17 use crate::error::{AppError, ValidationError};17 use crate::error::{AppError, ValidationError};
18 18
@@ -138,8 +138,7 @@ pub struct DeleteOutcome {
138 /// Delete the course: collect the image/homework/note-file blob keys, then138 /// Delete the course: collect the image/homework/note-file blob keys, then
139 /// run the cascading delete.139 /// run the cascading delete.
140 ///140 ///
141-/// Writer lease of [`crate::web::exams::EXAM_LOCK`] (moving to141+/// Writer lease of [`crate::service::exam_attempt::EXAM_LOCK`], for
142-/// `crate::service::exam_attempt` with the exam lane's split), for
143 /// `delete_exam`'s reason: this cascade sweeps the course's exams *and their142 /// `delete_exam`'s reason: this cascade sweeps the course's exams *and their
144 /// attempts*, and an attempt is the one exam child whose write cannot143 /// attempts*, and an attempt is the one exam child whose write cannot
145 /// collide with the sweep (its claim lands on the student's row, never the144 /// collide with the sweep (its claim lands on the student's row, never the
src/service/exam.rsadded+287 -0
@@ -0,0 +1,287 @@
1+//! Exam workflows: the PATCH re-derive — the merge (set / clear / keep per
2+//! field) re-judged against a fresh read every retry round, and the
3+//! mode-freeze, re-draft, and kind gates that guard it — and the delete that
4+//! collects the image blob keys under the writer lease before the cascade.
5+//! The queries live in [`crate::db::exam`]; the sitting workflows next door
6+//! in [`crate::service::exam_attempt`], whose [`EXAM_LOCK`] every path here
7+//! leases.
8+
9+use crate::constant::CAS_UPDATE_RETRIES;
10+use crate::database::Database;
11+use crate::db::exam;
12+use crate::domain::answer_image::AnswerImage;
13+use crate::domain::course::CourseId;
14+use crate::domain::exam::{
15+ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode,
16+ ExamSchedule, ExamTitle, redraft_error,
17+};
18+use crate::domain::exam_result::ExamResult;
19+use crate::domain::question_image::QuestionImage;
20+use crate::domain::timestamp::Timestamp;
21+use crate::domain::user::UserId;
22+use crate::error::AppError;
23+use crate::service::course::require_open;
24+use crate::service::exam_attempt::{EXAM_LOCK, any_for_exam, course_of};
25+
26+pub async fn create(
27+ db: &Database,
28+ creator: &UserId,
29+ course: &CourseId,
30+ title: ExamTitle,
31+ description: ExamDescription,
32+ kind: ExamKind,
33+ schedule: ExamSchedule,
34+ max_attempts: ExamAttemptLimit,
35+ allow_rejoin: bool,
36+ allow_review: bool,
37+ draft: bool,
38+) -> Result<Exam, AppError> {
39+ exam::create(
40+ db,
41+ creator,
42+ course,
43+ title,
44+ description,
45+ kind,
46+ schedule,
47+ max_attempts,
48+ allow_rejoin,
49+ allow_review,
50+ draft,
51+ )
52+ .await
53+}
54+
55+/// The exam row, for callers that only inspect it — the web layer's gates
56+/// read through here.
57+pub async fn read(db: &Database, id: &ExamId) -> Result<Option<Exam>, AppError> {
58+ exam::read(db, id).await
59+}
60+
61+pub async fn list_all(db: &Database) -> Result<Vec<Exam>, AppError> {
62+ exam::list_all(db).await
63+}
64+
65+pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Exam>, AppError> {
66+ exam::list_for_course(db, course).await
67+}
68+
69+/// Every exam of every course in `courses` (one query) — the catalog as one
70+/// user sees it.
71+pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result<Vec<Exam>, AppError> {
72+ exam::list_for_courses(db, courses).await
73+}
74+
75+/// A `PATCH /exams/{id}` request after field validation: every value the
76+/// request *set* is already validated (title, description, mode, duration,
77+/// and attempt limit by their newtypes; the kind against the school's
78+/// current list; newly set window ends by the web layer's no-past grace).
79+/// What is *kept* — and whether the merged whole is a legal schedule — are
80+/// the update's own decisions, re-derived against a fresh read every retry
81+/// round, so they live here and not in the web layer. A `None` field keeps
82+/// the stored value; the `Option<Option<..>>` schedule fields carry the
83+/// web DTO's set-or-clear spelling (`Some(None)` = explicit `null`).
84+pub struct ExamPatch {
85+ pub title: Option<ExamTitle>,
86+ pub description: Option<ExamDescription>,
87+ pub kind: Option<ExamKind>,
88+ pub mode: Option<Option<ExamMode>>,
89+ pub starts_at: Option<Option<Timestamp>>,
90+ pub ends_at: Option<Option<Timestamp>>,
91+ pub duration_ms: Option<Option<ExamDuration>>,
92+ pub max_attempts: Option<ExamAttemptLimit>,
93+ pub allow_rejoin: Option<bool>,
94+ pub allow_review: Option<bool>,
95+ pub draft: Option<bool>,
96+}
97+
98+/// Re-derive and save the exam: merge the patch over a fresh read, re-validate
99+/// the schedule as a unit, judge every business gate against that same row,
100+/// and land the whole merge with the compare-and-set — retried while the row
101+/// keeps moving under the snapshot.
102+///
103+/// *Reader* lease of [`EXAM_LOCK`] for exactly one pairing: the mode gate
104+/// below reads `exam_attempt`, and an attempt start takes the *writer*
105+/// lease, so a first sitting still cannot land between that gate and the
106+/// write, as it always did.
107+///
108+/// It buys nothing against grading, which is a reader too: the re-draft gate
109+/// is therefore enforced inside the update's own transaction
110+/// ([`exam::update_if_unchanged`]), where the store decides it. The gate
111+/// below stays as the pre-flight — same error, one round trip earlier.
112+/// Concurrent PATCHes of this exam no longer queue behind each other either:
113+/// the lost update they used to cause is refused by the compare-and-set.
114+pub async fn update(db: &Database, id: &ExamId, patch: &ExamPatch) -> Result<Exam, AppError> {
115+ let _guard = EXAM_LOCK.read().await;
116+ let mut left = CAS_UPDATE_RETRIES;
117+ loop {
118+ let current = exam::read(db, id).await?.ok_or(AppError::NotFound)?;
119+ let course = course_of(&current, db).await?;
120+ require_open(db, &course).await?;
121+
122+ let title = patch
123+ .title
124+ .clone()
125+ .unwrap_or_else(|| current.get_title().clone());
126+ let description = patch
127+ .description
128+ .clone()
129+ .unwrap_or_else(|| current.get_description().clone());
130+ let kind = patch
131+ .kind
132+ .clone()
133+ .unwrap_or_else(|| current.get_kind().clone());
134+
135+ // Merge the schedule (set / clear / keep per field), then re-validate it
136+ // as a unit — a PATCH can't leave a half-schedule behind. Only values this
137+ // request sets are held to the no-past rule: kept ones may legitimately be
138+ // past (a running exam's `starts_at`), and rechecking them would block
139+ // unrelated edits.
140+ let mode = match &patch.mode {
141+ Some(update) => update.clone(),
142+ None => current.get_mode().cloned(),
143+ };
144+ let starts_at = match patch.starts_at {
145+ Some(update) => update,
146+ None => current.get_starts_at(),
147+ };
148+ let ends_at = match patch.ends_at {
149+ Some(update) => update,
150+ None => current.get_ends_at(),
151+ };
152+ let duration_ms = match patch.duration_ms {
153+ Some(update) => update,
154+ None => current.get_duration_ms(),
155+ };
156+ let schedule = ExamSchedule::try_new(mode, starts_at, ends_at, duration_ms)?;
157+ let max_attempts = patch
158+ .max_attempts
159+ .unwrap_or_else(|| current.get_max_attempts());
160+ let allow_rejoin = patch
161+ .allow_rejoin
162+ .unwrap_or_else(|| current.get_allow_rejoin());
163+ let allow_review = patch
164+ .allow_review
165+ .unwrap_or_else(|| current.get_allow_review());
166+ let draft = patch.draft.unwrap_or(current.is_draft());
167+
168+ // Switching sync <-> async <-> open (or back to unscheduled) would
169+ // silently rewrite the deadline rules under students who already sat
170+ // down; extending times, the attempt limit, and the rejoin door are the
171+ // supported live adjustments instead. Gate read and write share the
172+ // call-wide reader lease of [`EXAM_LOCK`], so a first attempt can't
173+ // land in the gap and leave a sat exam's mode flipped under it.
174+ let mode_changed =
175+ schedule.get_mode().map(ExamMode::as_str) != current.get_mode().map(ExamMode::as_str);
176+ if mode_changed && any_for_exam(db, current.get_id()).await? {
177+ return Err(AppError::Conflict(
178+ "cannot change the exam mode after attempts have started",
179+ ));
180+ }
181+ // Re-drafting hides the exam — never out from under a student who
182+ // already sat it or holds a mark on it. Pre-flight only: the write's own
183+ // transaction re-makes this check and answers with the same error, so a
184+ // grade landing after this read still cannot leave a mark on a draft.
185+ if draft && !current.is_draft() {
186+ let sat = any_for_exam(db, current.get_id()).await?;
187+ let graded = !ExamResult::list_for_exam(current.get_id(), db)
188+ .await?
189+ .is_empty();
190+ if sat || graded {
191+ return Err(redraft_error());
192+ }
193+ }
194+
195+ // A graded exam keeps its kind. Moving it re-weights every mark it
196+ // already carries — the same silent re-weighting the settings' removal
197+ // guard refuses — and it would strand those marks' references on the
198+ // kind they were counted under, freeing the kind the exam now claims to
199+ // be. Marks are counted on the exam row, and the save below *pins* that
200+ // counter, so a grade landing between this read and the write refuses
201+ // the save (the loop then re-reads and answers the 409 below).
202+ if kind.as_str() != current.get_kind().as_str() && current.get_result_count() > 0 {
203+ return Err(AppError::Conflict(
204+ "cannot change the kind of an exam that already has marks",
205+ ));
206+ }
207+
208+ if let Some(updated) = exam::update_if_unchanged(
209+ db,
210+ current,
211+ title,
212+ description,
213+ kind,
214+ schedule,
215+ max_attempts,
216+ allow_rejoin,
217+ allow_review,
218+ draft,
219+ )
220+ .await?
221+ {
222+ return Ok(updated);
223+ }
224+ // The row moved under the snapshot every gate above judged: re-read and
225+ // re-merge, so both edits land instead of the later reverting the earlier.
226+ left -= 1;
227+ if left == 0 {
228+ return Err(AppError::Conflict(
229+ "the exam kept changing underneath this update — try again",
230+ ));
231+ }
232+ }
233+}
234+
235+/// What [`delete`] did: the blob keys of the image rows the cascade removed —
236+/// exactly whose files the web layer may unlink.
237+#[derive(Debug)]
238+pub struct DeleteOutcome {
239+ pub image_files: Vec<String>,
240+ pub answer_image_files: Vec<String>,
241+}
242+
243+/// Delete the exam: collect the question/answer image blob keys, then run the
244+/// cascading delete.
245+///
246+/// Writer lease of [`EXAM_LOCK`] across the whole cascade, blob names
247+/// included — the lease `delete_homework` has always held, and its absence
248+/// here is what made a sitting able to start inside this delete. Every other
249+/// child of an exam now writes the exam row in its own transaction, so the
250+/// store refuses the pair; an attempt cannot, because its claim lands on the
251+/// *student's* row (`exam_sat_total`) and touches nothing this delete
252+/// writes. `start_attempt` already takes the writer lease from its exam read
253+/// through the insert, so this one lease is the whole ordering: a start
254+/// either finishes before the sweep (which then takes its row) or reads no
255+/// exam at all and is a 404. Left orphaned, that attempt kept a sitting on
256+/// the student's lifetime counter and could mint a badge — awards are
257+/// add-only and never revoked — for an exam that never existed.
258+///
259+/// It spans the blob names too: they are collected *before* the rows go, so
260+/// an image row written after that snapshot would strand its bytes on disk
261+/// even though the row itself is now refused.
262+///
263+/// corner-cut: process-local, so it holds because the deployment runs one
264+/// process by contract with stop-the-world deploys (two overlapping
265+/// binaries would
266+/// reopen it). Closing it in the store means the `cap` shape the counter
267+/// work already sketched: `claim_and_create` gaining a second record to
268+/// touch, so the attempt writes the exam key as every other child does.
269+pub async fn delete(db: &Database, target: &Exam) -> Result<DeleteOutcome, AppError> {
270+ require_open(db, &course_of(target, db).await?).await?;
271+ let _guard = EXAM_LOCK.write().await;
272+ // Rows go first (the delete cascades them), blobs after — a crash in
273+ // between strands at worst an unreachable blob.
274+ let images = QuestionImage::list_for_exam(target.get_id(), db).await?;
275+ let answer_images = AnswerImage::list_for_exam(target.get_id(), db).await?;
276+ exam::delete(db, target.clone()).await?;
277+ Ok(DeleteOutcome {
278+ image_files: images
279+ .iter()
280+ .map(|image| image.get_file().to_string())
281+ .collect(),
282+ answer_image_files: answer_images
283+ .iter()
284+ .map(|image| image.get_file().to_string())
285+ .collect(),
286+ })
287+}
src/service/exam_attempt.rsmodified+3 -3
@@ -282,7 +282,7 @@ pub async fn start_attempt(
282 user: &User,282 user: &User,
283 ) -> Result<(Exam, ExamAttempt, bool), AppError> {283 ) -> Result<(Exam, ExamAttempt, bool), AppError> {
284 let _guard = EXAM_LOCK.write().await;284 let _guard = EXAM_LOCK.write().await;
285- let exam = crate::domain::exam::Exam::read(exam_id, db)285+ let exam = crate::db::exam::read(db, exam_id)
286 .await?286 .await?
287 .ok_or(AppError::NotFound)?;287 .ok_or(AppError::NotFound)?;
288 ensure_sittable(&exam)?;288 ensure_sittable(&exam)?;
@@ -489,7 +489,8 @@ mod tests {
489 let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");489 let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
490 let course = crate::db::course::a_test_course(db).await;490 let course = crate::db::course::a_test_course(db).await;
491 let kinds = Settings::defaults().get_exam_kinds().to_vec();491 let kinds = Settings::defaults().get_exam_kinds().to_vec();
492- let exam = Exam::create(492+ let exam = crate::db::exam::create(
493+ db,
493 &creator,494 &creator,
494 &course,495 &course,
495 ExamTitle::try_new("practice").unwrap(),496 ExamTitle::try_new("practice").unwrap(),
@@ -501,7 +502,6 @@ mod tests {
501 true,502 true,
502 false,503 false,
503 false,504 false,
504- db,
505 )505 )
506 .await506 .await
507 .unwrap();507 .unwrap();
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 enrollment;9 pub mod enrollment;
10+pub mod exam;
10 pub mod exam_attempt;11 pub mod exam_attempt;
11 pub mod exam_question;12 pub mod exam_question;
12 pub mod meal_booking;13 pub mod meal_booking;
src/web/courses.rsmodified+4 -5
@@ -14,8 +14,7 @@ use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, Cou
14 use crate::domain::course_session::SessionTopic;14 use crate::domain::course_session::SessionTopic;
15 use crate::domain::enrollment::Enrollment;15 use crate::domain::enrollment::Enrollment;
16 use crate::domain::exam::{16 use crate::domain::exam::{
17- Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule,17+ ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle,
18- ExamTitle,
19 };18 };
20 use crate::domain::homework::{Homework, HomeworkTitle};19 use crate::domain::homework::{Homework, HomeworkTitle};
21 use crate::domain::role::Role;20 use crate::domain::role::Role;
@@ -850,7 +849,8 @@ async fn create_exam_in_course(
850 Some(limit) => ExamAttemptLimit::try_new(limit)?,849 Some(limit) => ExamAttemptLimit::try_new(limit)?,
851 None => ExamAttemptLimit::single(),850 None => ExamAttemptLimit::single(),
852 };851 };
853- let exam = Exam::create(852+ let exam = crate::service::exam::create(
853+ &st.db,
854 user.get_id(),854 user.get_id(),
855 course.get_id(),855 course.get_id(),
856 title,856 title,
@@ -861,7 +861,6 @@ async fn create_exam_in_course(
861 req.allow_rejoin.unwrap_or(true),861 req.allow_rejoin.unwrap_or(true),
862 req.allow_review.unwrap_or(false),862 req.allow_review.unwrap_or(false),
863 req.draft.unwrap_or(false),863 req.draft.unwrap_or(false),
864- &st.db,
865 )864 )
866 .await?;865 .await?;
867 Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam))))866 Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam))))
@@ -901,7 +900,7 @@ async fn list_course_exams(
901 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course",900 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course",
902 ));901 ));
903 }902 }
904- let mut exams = Exam::list_for_course(course.get_id(), &st.db).await?;903+ let mut exams = crate::service::exam::list_for_course(&st.db, course.get_id()).await?;
905 // Drafts are the managers' workbench — enrolled students don't see them.904 // Drafts are the managers' workbench — enrolled students don't see them.
906 if !can_manage_course(&course, &user) {905 if !can_manage_course(&course, &user) {
907 exams.retain(|exam| !exam.is_draft());906 exams.retain(|exam| !exam.is_draft());
src/web/exam_ws.rsmodified+7 -5
@@ -143,7 +143,7 @@ pub async fn attempt_ws(
143 Path(id): Path<String>,143 Path(id): Path<String>,
144 ws: WebSocketUpgrade,144 ws: WebSocketUpgrade,
145 ) -> Result<Response, AppError> {145 ) -> Result<Response, AppError> {
146- let exam = Exam::read(&ExamId::from_key(&id), &st.db)146+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
147 .await?147 .await?
148 .ok_or(AppError::NotFound)?;148 .ok_or(AppError::NotFound)?;
149 ensure_sittable(&exam)?;149 ensure_sittable(&exam)?;
@@ -232,7 +232,7 @@ async fn room(
232 /// wins. Targeting the sitting by id (never "the latest") means a retake232 /// wins. Targeting the sitting by id (never "the latest") means a retake
233 /// started elsewhere can't be marked as left by an old room's teardown.233 /// started elsewhere can't be marked as left by an old room's teardown.
234 async fn stamp_left(exam_id: &ExamId, attempt_id: &ExamAttemptId, db: &Database) {234 async fn stamp_left(exam_id: &ExamId, attempt_id: &ExamAttemptId, db: &Database) {
235- let attempt = match Exam::read(exam_id, db).await {235+ let attempt = match crate::service::exam::read(db, exam_id).await {
236 Ok(Some(exam)) => match read(db, attempt_id).await {236 Ok(Some(exam)) => match read(db, attempt_id).await {
237 Ok(Some(attempt))237 Ok(Some(attempt))
238 if attempt.status(&exam, Timestamp::now()) == AttemptStatus::InProgress =>238 if attempt.status(&exam, Timestamp::now()) == AttemptStatus::InProgress =>
@@ -327,7 +327,9 @@ async fn state_frame(
327 attempt: &ExamAttemptId,327 attempt: &ExamAttemptId,
328 db: &Database,328 db: &Database,
329 ) -> Result<(Value, AttemptStatus, Option<i64>), AppError> {329 ) -> Result<(Value, AttemptStatus, Option<i64>), AppError> {
330- let exam = Exam::read(exam, db).await?.ok_or(AppError::NotFound)?;330+ let exam = crate::service::exam::read(db, exam)
331+ .await?
332+ .ok_or(AppError::NotFound)?;
331 let attempt = read(db, attempt).await?.ok_or(AppError::NotFound)?;333 let attempt = read(db, attempt).await?.ok_or(AppError::NotFound)?;
332 let now = Timestamp::now();334 let now = Timestamp::now();
333 let status = attempt.status(&exam, now);335 let status = attempt.status(&exam, now);
@@ -410,7 +412,7 @@ async fn handle_message(
410 // a failure possibly be about this one question rather than about412 // a failure possibly be about this one question rather than about
411 // the room. See [`error_frame_for`].413 // the room. See [`error_frame_for`].
412 let mut in_save = false;414 let mut in_save = false;
413- let saved = match Exam::read(exam_id, db).await {415+ let saved = match crate::service::exam::read(db, exam_id).await {
414 Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await {416 Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await {
415 Ok(attempt) => {417 Ok(attempt) => {
416 in_save = true;418 in_save = true;
@@ -452,7 +454,7 @@ async fn handle_message(
452 ClientMessage::Finish => {454 ClientMessage::Finish => {
453 // Submit the room's own sitting — a stale room must not submit a455 // Submit the room's own sitting — a stale room must not submit a
454 // retake it never hosted.456 // retake it never hosted.
455- let finished = match Exam::read(exam_id, db).await {457+ let finished = match crate::service::exam::read(db, exam_id).await {
456 Ok(Some(exam)) => {458 Ok(Some(exam)) => {
457 // Its own archived-term gate: `finish` is the one459 // Its own archived-term gate: `finish` is the one
458 // sitting-side write that does not go through460 // sitting-side write that does not go through
src/web/exams/attempts.rsmodified+6 -6
@@ -189,7 +189,7 @@ pub(crate) async fn my_attempt(
189 CurrentUser(user): CurrentUser,189 CurrentUser(user): CurrentUser,
190 Path(id): Path<String>,190 Path(id): Path<String>,
191 ) -> Result<Json<AttemptResponse>, AppError> {191 ) -> Result<Json<AttemptResponse>, AppError> {
192- let exam = Exam::read(&ExamId::from_key(&id), &st.db)192+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
193 .await?193 .await?
194 .ok_or(AppError::NotFound)?;194 .ok_or(AppError::NotFound)?;
195 let attempt = exam_attempt::read_latest_for_user(&st.db, exam.get_id(), user.get_id())195 let attempt = exam_attempt::read_latest_for_user(&st.db, exam.get_id(), user.get_id())
@@ -235,7 +235,7 @@ pub(crate) async fn finish_attempt(
235 CurrentUser(user): CurrentUser,235 CurrentUser(user): CurrentUser,
236 Path(id): Path<String>,236 Path(id): Path<String>,
237 ) -> Result<Json<AttemptResponse>, AppError> {237 ) -> Result<Json<AttemptResponse>, AppError> {
238- let exam = Exam::read(&ExamId::from_key(&id), &st.db)238+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
239 .await?239 .await?
240 .ok_or(AppError::NotFound)?;240 .ok_or(AppError::NotFound)?;
241 let finished = exam_attempt::finish_attempt(&st.db, &exam, user.get_id()).await?;241 let finished = exam_attempt::finish_attempt(&st.db, &exam, user.get_id()).await?;
@@ -458,7 +458,7 @@ pub(crate) async fn exam_live(
458 RequireTeacher(user): RequireTeacher,458 RequireTeacher(user): RequireTeacher,
459 Path(id): Path<String>,459 Path(id): Path<String>,
460 ) -> Result<Json<ExamLiveResponse>, AppError> {460 ) -> Result<Json<ExamLiveResponse>, AppError> {
461- let exam = Exam::read(&ExamId::from_key(&id), &st.db)461+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
462 .await?462 .await?
463 .ok_or(AppError::NotFound)?;463 .ok_or(AppError::NotFound)?;
464 let course = exam_attempt::course_of(&exam, &st.db).await?;464 let course = exam_attempt::course_of(&exam, &st.db).await?;
@@ -572,7 +572,7 @@ pub(crate) async fn attempt_questions(
572 CurrentUser(user): CurrentUser,572 CurrentUser(user): CurrentUser,
573 Path(id): Path<String>,573 Path(id): Path<String>,
574 ) -> Result<Json<Vec<AttemptQuestionResponse>>, AppError> {574 ) -> Result<Json<Vec<AttemptQuestionResponse>>, AppError> {
575- let exam = Exam::read(&ExamId::from_key(&id), &st.db)575+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
576 .await?576 .await?
577 .ok_or(AppError::NotFound)?;577 .ok_or(AppError::NotFound)?;
578 exam_attempt::ensure_enrolled(&exam, user.get_id(), &st.db).await?;578 exam_attempt::ensure_enrolled(&exam, user.get_id(), &st.db).await?;
@@ -659,7 +659,7 @@ pub(crate) async fn save_answer(
659 Path(id): Path<String>,659 Path(id): Path<String>,
660 Json(req): Json<SaveAnswer>,660 Json(req): Json<SaveAnswer>,
661 ) -> Result<Json<AnswerSavedResponse>, AppError> {661 ) -> Result<Json<AnswerSavedResponse>, AppError> {
662- let exam = Exam::read(&ExamId::from_key(&id), &st.db)662+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
663 .await?663 .await?
664 .ok_or(AppError::NotFound)?;664 .ok_or(AppError::NotFound)?;
665 let answer = exam_attempt::save_answer_checked(665 let answer = exam_attempt::save_answer_checked(
@@ -707,7 +707,7 @@ pub(crate) async fn attempt_answers(
707 RequireTeacher(user): RequireTeacher,707 RequireTeacher(user): RequireTeacher,
708 Path((id, target)): Path<(String, String)>,708 Path((id, target)): Path<(String, String)>,
709 ) -> Result<Json<AttemptAnswersResponse>, AppError> {709 ) -> Result<Json<AttemptAnswersResponse>, AppError> {
710- let exam = Exam::read(&ExamId::from_key(&id), &st.db)710+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
711 .await?711 .await?
712 .ok_or(AppError::NotFound)?;712 .ok_or(AppError::NotFound)?;
713 let course = exam_attempt::course_of(&exam, &st.db).await?;713 let course = exam_attempt::course_of(&exam, &st.db).await?;
src/web/exams/images.rsmodified+7 -7
@@ -96,7 +96,7 @@ pub(crate) async fn image_managed_exam(
96 user: &User,96 user: &User,
97 id: &str,97 id: &str,
98 ) -> Result<Exam, AppError> {98 ) -> Result<Exam, AppError> {
99- let exam = Exam::read(&ExamId::from_key(id), &st.db)99+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(id))
100 .await?100 .await?
101 .ok_or(AppError::NotFound)?;101 .ok_or(AppError::NotFound)?;
102 let course = course_of(&exam, &st.db).await?;102 let course = course_of(&exam, &st.db).await?;
@@ -232,7 +232,7 @@ pub(crate) async fn get_question_image(
232 CurrentUser(user): CurrentUser,232 CurrentUser(user): CurrentUser,
233 Path((id, qid)): Path<(String, String)>,233 Path((id, qid)): Path<(String, String)>,
234 ) -> Result<Response, AppError> {234 ) -> Result<Response, AppError> {
235- let exam = Exam::read(&ExamId::from_key(&id), &st.db)235+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
236 .await?236 .await?
237 .ok_or(AppError::NotFound)?;237 .ok_or(AppError::NotFound)?;
238 ensure_question_content_visible(&st, &exam, &user).await?;238 ensure_question_content_visible(&st, &exam, &user).await?;
@@ -344,7 +344,7 @@ pub(crate) async fn get_choice_image(
344 CurrentUser(user): CurrentUser,344 CurrentUser(user): CurrentUser,
345 Path((id, qid, choice_id)): Path<(String, String, String)>,345 Path((id, qid, choice_id)): Path<(String, String, String)>,
346 ) -> Result<Response, AppError> {346 ) -> Result<Response, AppError> {
347- let exam = Exam::read(&ExamId::from_key(&id), &st.db)347+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
348 .await?348 .await?
349 .ok_or(AppError::NotFound)?;349 .ok_or(AppError::NotFound)?;
350 ensure_question_content_visible(&st, &exam, &user).await?;350 ensure_question_content_visible(&st, &exam, &user).await?;
@@ -460,7 +460,7 @@ pub(crate) async fn upload_answer_image(
460 Path((id, qid)): Path<(String, String)>,460 Path((id, qid)): Path<(String, String)>,
461 mut multipart: Multipart,461 mut multipart: Multipart,
462 ) -> Result<(StatusCode, Json<ImageMetaResponse>), AppError> {462 ) -> Result<(StatusCode, Json<ImageMetaResponse>), AppError> {
463- let exam = Exam::read(&ExamId::from_key(&id), &st.db)463+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
464 .await?464 .await?
465 .ok_or(AppError::NotFound)?;465 .ok_or(AppError::NotFound)?;
466 ensure_student(&user)?;466 ensure_student(&user)?;
@@ -542,7 +542,7 @@ pub(crate) async fn delete_answer_image(
542 CurrentUser(user): CurrentUser,542 CurrentUser(user): CurrentUser,
543 Path((id, qid)): Path<(String, String)>,543 Path((id, qid)): Path<(String, String)>,
544 ) -> Result<StatusCode, AppError> {544 ) -> Result<StatusCode, AppError> {
545- let exam = Exam::read(&ExamId::from_key(&id), &st.db)545+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
546 .await?546 .await?
547 .ok_or(AppError::NotFound)?;547 .ok_or(AppError::NotFound)?;
548 ensure_student(&user)?;548 ensure_student(&user)?;
@@ -595,7 +595,7 @@ pub(crate) async fn get_answer_image(
595 CurrentUser(user): CurrentUser,595 CurrentUser(user): CurrentUser,
596 Path((id, qid)): Path<(String, String)>,596 Path((id, qid)): Path<(String, String)>,
597 ) -> Result<Response, AppError> {597 ) -> Result<Response, AppError> {
598- let exam = Exam::read(&ExamId::from_key(&id), &st.db)598+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
599 .await?599 .await?
600 .ok_or(AppError::NotFound)?;600 .ok_or(AppError::NotFound)?;
601 ensure_question_content_visible(&st, &exam, &user).await?;601 ensure_question_content_visible(&st, &exam, &user).await?;
@@ -635,7 +635,7 @@ pub(crate) async fn get_student_answer_image(
635 RequireTeacher(user): RequireTeacher,635 RequireTeacher(user): RequireTeacher,
636 Path((id, target, qid)): Path<(String, String, String)>,636 Path((id, target, qid)): Path<(String, String, String)>,
637 ) -> Result<Response, AppError> {637 ) -> Result<Response, AppError> {
638- let exam = Exam::read(&ExamId::from_key(&id), &st.db)638+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
639 .await?639 .await?
640 .ok_or(AppError::NotFound)?;640 .ok_or(AppError::NotFound)?;
641 let course = course_of(&exam, &st.db).await?;641 let course = course_of(&exam, &st.db).await?;
src/web/exams/mod.rsmodified+92 -189
@@ -10,7 +10,7 @@ use utoipa::ToSchema;
10 use utoipa_axum::router::OpenApiRouter;10 use utoipa_axum::router::OpenApiRouter;
11 use utoipa_axum::routes;11 use utoipa_axum::routes;
12 12
13-use crate::constant::{CAS_UPDATE_RETRIES, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};13+use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
14 use crate::database::Database;14 use crate::database::Database;
15 use crate::domain::answer_image::AnswerImage;15 use crate::domain::answer_image::AnswerImage;
16 use crate::domain::badge;16 use crate::domain::badge;
@@ -18,8 +18,7 @@ use crate::domain::bank_question::{BankQuestion, BankQuestionId};
18 use crate::domain::bank_question_image::BankQuestionImage;18 use crate::domain::bank_question_image::BankQuestionImage;
19 19
20 use crate::domain::exam::{20 use crate::domain::exam::{
21- Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode,21+ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, ExamTitle,
22- ExamSchedule, ExamTitle,
23 };22 };
24 use crate::domain::exam_answer::{ExamAnswer, auto_score};23 use crate::domain::exam_answer::{ExamAnswer, auto_score};
25 use crate::domain::exam_question::{24 use crate::domain::exam_question::{
@@ -33,7 +32,7 @@ use crate::domain::timestamp::Timestamp;
33 use crate::domain::user::{User, UserId};32 use crate::domain::user::{User, UserId};
34 use crate::error::{AppError, ErrorResponse, ValidationError};33 use crate::error::{AppError, ErrorResponse, ValidationError};
35 use crate::service;34 use crate::service;
36-use crate::service::exam_attempt::{EXAM_LOCK, any_for_exam, course_of, read_latest_for_user};35+use crate::service::exam_attempt::{EXAM_LOCK, course_of, read_latest_for_user};
37 use crate::state::AppState;36 use crate::state::AppState;
38 37
39 use super::bank_questions::BankQuestionResponse;38 use super::bank_questions::BankQuestionResponse;
@@ -267,7 +266,7 @@ async fn list_exams(
267 ) -> Result<Json<Page<ExamResponse>>, AppError> {266 ) -> Result<Json<Page<ExamResponse>>, AppError> {
268 let (limit, offset) = page.resolve()?;267 let (limit, offset) = page.resolve()?;
269 let exams = if user.get_role().at_least(Role::Manager) {268 let exams = if user.get_role().at_least(Role::Manager) {
270- Exam::list_all(&st.db).await?269+ service::exam::list_all(&st.db).await?
271 } else {270 } else {
272 let courses = visible_courses(&user, &st.db).await?;271 let courses = visible_courses(&user, &st.db).await?;
273 let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect();272 let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect();
@@ -278,7 +277,7 @@ async fn list_exams(
278 .filter(|c| can_manage_course(c, &user))277 .filter(|c| can_manage_course(c, &user))
279 .map(|c| c.get_id().key())278 .map(|c| c.get_id().key())
280 .collect();279 .collect();
281- let mut exams = Exam::list_for_courses(&ids, &st.db).await?;280+ let mut exams = service::exam::list_for_courses(&st.db, &ids).await?;
282 exams.retain(|exam| !exam.is_draft() || managed.contains(&exam.get_course().key()));281 exams.retain(|exam| !exam.is_draft() || managed.contains(&exam.get_course().key()));
283 exams282 exams
284 };283 };
@@ -321,7 +320,7 @@ async fn get_exam(
321 CurrentUser(user): CurrentUser,320 CurrentUser(user): CurrentUser,
322 Path(id): Path<String>,321 Path(id): Path<String>,
323 ) -> Result<Json<ExamResponse>, AppError> {322 ) -> Result<Json<ExamResponse>, AppError> {
324- let exam = Exam::read(&ExamId::from_key(&id), &st.db)323+ let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
325 .await?324 .await?
326 .ok_or(AppError::NotFound)?;325 .ok_or(AppError::NotFound)?;
327 let course = course_of(&exam, &st.db).await?;326 let course = course_of(&exam, &st.db).await?;
@@ -371,153 +370,82 @@ async fn update_exam(
371 Path(id): Path<String>,370 Path(id): Path<String>,
372 Json(req): Json<UpdateExam>,371 Json(req): Json<UpdateExam>,
373 ) -> Result<Json<ExamResponse>, AppError> {372 ) -> Result<Json<ExamResponse>, AppError> {
374- // *Reader* lease of [`EXAM_LOCK`] for exactly one pairing: the mode gate373+ let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
375- // below reads `exam_attempt`, and an attempt start takes the *writer*374+ .await?
376- // lease, so a first sitting still cannot land between that gate and the375+ .ok_or(AppError::NotFound)?;
377- // write, as it always did.376+ let course = course_of(&exam, &st.db).await?;
378- //377+ if !can_manage_course(&course, &user) {
379- // It buys nothing against grading, which is a reader too: the re-draft gate378+ return Err(AppError::Forbidden(
380- // is therefore enforced inside the update's own transaction379+ "only the course creator, an assigned teacher, or a manager/admin can edit this exam",
381- // (`Exam::update_if_unchanged`), where the store decides it. The gate380+ ));
382- // below stays as the pre-flight — same error, one round trip earlier.381+ }
383- // Concurrent PATCHes of this exam no longer queue behind each other either:382+ crate::service::course::require_open(&st.db, &course).await?;
384- // the lost update they used to cause is refused by the compare-and-set.
385- let _guard = EXAM_LOCK.read().await;
386- let mut left = CAS_UPDATE_RETRIES;
387- let exam = loop {
388- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
389- .await?
390- .ok_or(AppError::NotFound)?;
391- let course = course_of(&exam, &st.db).await?;
392- if !can_manage_course(&course, &user) {
393- return Err(AppError::Forbidden(
394- "only the course creator, an assigned teacher, or a manager/admin can edit this exam",
395- ));
396- }
397- crate::service::course::require_open(&st.db, &course).await?;
398-
399- let title = match req.title {
400- Some(ref title) => ExamTitle::try_new(title)?,
401- None => exam.get_title().clone(),
402- };
403- let description = match req.description {
404- Some(ref description) => ExamDescription::try_new(description)?,
405- None => exam.get_description().clone(),
406- };
407- let kind = match req.kind {
408- // Only a kind this request sets is held to the current settings list —
409- // a stored kind survives later list edits, like past times survive
410- // the no-past rule.
411- Some(ref kind) => {
412- let school = service::settings::load(&st.db).await?;
413- ExamKind::try_new(kind, school.get_exam_kinds())?
414- }
415- None => exam.get_kind().clone(),
416- };
417-
418- // Merge the schedule (set / clear / keep per field), then re-validate it
419- // as a unit — a PATCH can't leave a half-schedule behind. Only values this
420- // request sets are held to the no-past rule: kept ones may legitimately be
421- // past (a running exam's `starts_at`), and rechecking them would block
422- // unrelated edits.
423- let mode = match req.mode {
424- Some(ref update) => update.as_deref().map(ExamMode::try_new).transpose()?,
425- None => exam.get_mode().cloned(),
426- };
427- let starts_at = match req.starts_at {
428- Some(update) => {
429- let starts_at = update.map(Timestamp::from_millis);
430- check_not_past("starts_at", starts_at)?;
431- starts_at
432- }
433- None => exam.get_starts_at(),
434- };
435- let ends_at = match req.ends_at {
436- Some(update) => {
437- let ends_at = update.map(Timestamp::from_millis);
438- check_not_past("ends_at", ends_at)?;
439- ends_at
440- }
441- None => exam.get_ends_at(),
442- };
443- let duration_ms = match req.duration_ms {
444- Some(update) => update.map(ExamDuration::try_new).transpose()?,
445- None => exam.get_duration_ms(),
446- };
447- let schedule = ExamSchedule::try_new(mode, starts_at, ends_at, duration_ms)?;
448- let max_attempts = match req.max_attempts {
449- Some(limit) => ExamAttemptLimit::try_new(limit)?,
450- None => exam.get_max_attempts(),
451- };
452- let allow_rejoin = req.allow_rejoin.unwrap_or_else(|| exam.get_allow_rejoin());
453- let allow_review = req.allow_review.unwrap_or_else(|| exam.get_allow_review());
454- let draft = req.draft.unwrap_or_else(|| exam.is_draft());
455-
456- // Switching sync <-> async <-> open (or back to unscheduled) would
457- // silently rewrite the deadline rules under students who already sat
458- // down; extending times, the attempt limit, and the rejoin door are the
459- // supported live adjustments instead. Gate read and write share the
460- // handler-wide writer lease of [`EXAM_LOCK`], so a first attempt can't
461- // land in the gap and leave a sat exam's mode flipped under it.
462- let mode_changed =
463- schedule.get_mode().map(ExamMode::as_str) != exam.get_mode().map(ExamMode::as_str);
464- if mode_changed && any_for_exam(&st.db, exam.get_id()).await? {
465- return Err(AppError::Conflict(
466- "cannot change the exam mode after attempts have started",
467- ));
468- }
469- // Re-drafting hides the exam — never out from under a student who
470- // already sat it or holds a mark on it. Pre-flight only: the write's own
471- // transaction re-makes this check and answers with the same error, so a
472- // grade landing after this read still cannot leave a mark on a draft.
473- if draft && !exam.is_draft() {
474- let sat = any_for_exam(&st.db, exam.get_id()).await?;
475- let graded = !ExamResult::list_for_exam(exam.get_id(), &st.db)
476- .await?
477- .is_empty();
478- if sat || graded {
479- return Err(crate::domain::exam::redraft_error());
480- }
481- }
482-
483- // A graded exam keeps its kind. Moving it re-weights every mark it
484- // already carries — the same silent re-weighting the settings' removal
485- // guard refuses — and it would strand those marks' references on the
486- // kind they were counted under, freeing the kind the exam now claims to
487- // be. Marks are counted on the exam row, and the save below *pins* that
488- // counter, so a grade landing between this read and the write refuses
489- // the save (the loop then re-reads and answers the 409 below).
490- if kind.as_str() != exam.get_kind().as_str() && exam.get_result_count() > 0 {
491- return Err(AppError::Conflict(
492- "cannot change the kind of an exam that already has marks",
493- ));
494- }
495 383
496- if let Some(updated) = exam384+ // Field validation, in the order the request is judged — only values this
497- .update_if_unchanged(385+ // request sets are held to the rules (a stored kind survives list edits,
498- title,386+ // kept times may legitimately be past). The merge against the stored row,
499- description,387+ // the schedule re-validation as a unit, and the mode-freeze / re-draft /
500- kind,388+ // kind gates are the workflow's own steps:
501- schedule,389+ // [`crate::service::exam::update`] re-derives them per retry round behind
502- max_attempts,390+ // the compare-and-set.
503- allow_rejoin,391+ let title = req.title.as_deref().map(ExamTitle::try_new).transpose()?;
504- allow_review,392+ let description = req
505- draft,393+ .description
506- &st.db,394+ .as_deref()
507- )395+ .map(ExamDescription::try_new)
508- .await?396+ .transpose()?;
509- {397+ let kind = match &req.kind {
510- break updated;398+ // Only a kind this request sets is held to the current settings list —
399+ // a stored kind survives later list edits, like past times survive
400+ // the no-past rule.
401+ Some(kind) => Some(ExamKind::try_new(
402+ kind,
403+ service::settings::load(&st.db).await?.get_exam_kinds(),
404+ )?),
405+ None => None,
406+ };
407+ let mode = match &req.mode {
408+ Some(update) => Some(update.as_deref().map(ExamMode::try_new).transpose()?),
409+ None => None,
410+ };
411+ let starts_at = match req.starts_at {
412+ Some(update) => {
413+ let starts_at = update.map(Timestamp::from_millis);
414+ check_not_past("starts_at", starts_at)?;
415+ Some(starts_at)
511 }416 }
512- // The row moved under the snapshot every gate above judged: re-read and417+ None => None,
513- // re-merge, so both edits land instead of the later reverting the earlier.418+ };
514- left -= 1;419+ let ends_at = match req.ends_at {
515- if left == 0 {420+ Some(update) => {
516- return Err(AppError::Conflict(421+ let ends_at = update.map(Timestamp::from_millis);
517- "the exam kept changing underneath this update — try again",422+ check_not_past("ends_at", ends_at)?;
518- ));423+ Some(ends_at)
519 }424 }
425+ None => None,
426+ };
427+ let duration_ms = match req.duration_ms {
428+ Some(update) => Some(update.map(ExamDuration::try_new).transpose()?),
429+ None => None,
520 };430 };
431+ let max_attempts = req
432+ .max_attempts
433+ .map(ExamAttemptLimit::try_new)
434+ .transpose()?;
435+ let patch = service::exam::ExamPatch {
436+ title,
437+ description,
438+ kind,
439+ mode,
440+ starts_at,
441+ ends_at,
442+ duration_ms,
443+ max_attempts,
444+ allow_rejoin: req.allow_rejoin,
445+ allow_review: req.allow_review,
446+ draft: req.draft,
447+ };
448+ let exam = service::exam::update(&st.db, exam.get_id(), &patch).await?;
521 Ok(Json(ExamResponse::new(&exam)))449 Ok(Json(ExamResponse::new(&exam)))
522 }450 }
523 451
@@ -543,7 +471,7 @@ async fn delete_exam(
543 RequireTeacher(user): RequireTeacher,471 RequireTeacher(user): RequireTeacher,
544 Path(id): Path<String>,472 Path(id): Path<String>,
545 ) -> Result<StatusCode, AppError> {473 ) -> Result<StatusCode, AppError> {
546- let exam = Exam::read(&ExamId::from_key(&id), &st.db)474+ let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
547 .await?475 .await?
548 .ok_or(AppError::NotFound)?;476 .ok_or(AppError::NotFound)?;
549 let course = course_of(&exam, &st.db).await?;477 let course = course_of(&exam, &st.db).await?;
@@ -552,41 +480,16 @@ async fn delete_exam(
552 "only the course creator, an assigned teacher, or a manager/admin can delete this exam",480 "only the course creator, an assigned teacher, or a manager/admin can delete this exam",
553 ));481 ));
554 }482 }
555- crate::service::course::require_open(&st.db, &course).await?;483+ // The workflow — the archived-term gate, the *writer* lease of
556- // *Writer* lease of [`EXAM_LOCK`] across the whole cascade, blob names484+ // [`EXAM_LOCK`] across the cascade, blob-key collection, the delete — is
557- // included — the lease `delete_homework` has always held, and its absence485+ // [`crate::service::exam::delete`]'s. Blob unlinking stays here because
558- // here is what made a sitting able to start inside this delete. Every other486+ // only the web layer knows `files_path`.
559- // child of an exam now writes the exam row in its own transaction, so the487+ let outcome = service::exam::delete(&st.db, &exam).await?;
560- // store refuses the pair; an attempt cannot, because its claim lands on the488+ for file in &outcome.image_files {
561- // *student's* row (`exam_sat_total`) and touches nothing this delete489+ remove_blob(&st.files_path, file).await;
562- // writes. `start_attempt` already takes the writer lease from its exam read
563- // through the insert, so this one lease is the whole ordering: a start
564- // either finishes before the sweep (which then takes its row) or reads no
565- // exam at all and is a 404. Left orphaned, that attempt kept a sitting on
566- // the student's lifetime counter and could mint a badge — awards are
567- // add-only and never revoked — for an exam that never existed.
568- //
569- // It spans the blob names too: they are collected *before* the rows go, so
570- // an image row written after that snapshot would strand its bytes on disk
571- // even though the row itself is now refused.
572- //
573- // corner-cut: process-local, so it holds because the deployment runs one
574- // process by contract with stop-the-world deploys (two overlapping
575- // binaries would
576- // reopen it). Closing it in the store means the `cap` shape the counter
577- // work already sketched: `claim_and_create` gaining a second record to
578- // touch, so the attempt writes the exam key as every other child does.
579- let _guard = EXAM_LOCK.write().await;
580- // Rows go first (the delete cascades them), blobs after — a crash in
581- // between strands at worst an unreachable blob.
582- let images = QuestionImage::list_for_exam(exam.get_id(), &st.db).await?;
583- let answer_images = AnswerImage::list_for_exam(exam.get_id(), &st.db).await?;
584- exam.delete(&st.db).await?;
585- for image in &images {
586- remove_blob(&st.files_path, image.get_file()).await;
587 }490 }
588- for image in &answer_images {491+ for file in &outcome.answer_image_files {
589- remove_blob(&st.files_path, image.get_file()).await;492+ remove_blob(&st.files_path, file).await;
590 }493 }
591 Ok(StatusCode::NO_CONTENT)494 Ok(StatusCode::NO_CONTENT)
592 }495 }
@@ -628,7 +531,7 @@ async fn grade(
628 // results) could slip between them and leave a mark on a hidden exam.531 // results) could slip between them and leave a mark on a hidden exam.
629 let _guard = EXAM_LOCK.read().await;532 let _guard = EXAM_LOCK.read().await;
630 // Exam must exist.533 // Exam must exist.
631- let exam = Exam::read(&exam_id, &st.db)534+ let exam = service::exam::read(&st.db, &exam_id)
632 .await?535 .await?
633 .ok_or(AppError::NotFound)?;536 .ok_or(AppError::NotFound)?;
634 let course = course_of(&exam, &st.db).await?;537 let course = course_of(&exam, &st.db).await?;
@@ -753,7 +656,7 @@ async fn list_results(
753 ) -> Result<Json<Page<ExamResultResponse>>, AppError> {656 ) -> Result<Json<Page<ExamResultResponse>>, AppError> {
754 let (limit, offset) = page.resolve()?;657 let (limit, offset) = page.resolve()?;
755 // Exam must exist — a missing exam is a 404, not an empty result list.658 // Exam must exist — a missing exam is a 404, not an empty result list.
756- let exam = Exam::read(&ExamId::from_key(&id), &st.db)659+ let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
757 .await?660 .await?
758 .ok_or(AppError::NotFound)?;661 .ok_or(AppError::NotFound)?;
759 let course = course_of(&exam, &st.db).await?;662 let course = course_of(&exam, &st.db).await?;
@@ -835,7 +738,7 @@ async fn remove_result(
835 RequireTeacher(user): RequireTeacher,738 RequireTeacher(user): RequireTeacher,
836 Path((id, target)): Path<(String, String)>,739 Path((id, target)): Path<(String, String)>,
837 ) -> Result<StatusCode, AppError> {740 ) -> Result<StatusCode, AppError> {
838- let exam = Exam::read(&ExamId::from_key(&id), &st.db)741+ let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
839 .await?742 .await?
840 .ok_or(AppError::NotFound)?;743 .ok_or(AppError::NotFound)?;
841 let course = course_of(&exam, &st.db).await?;744 let course = course_of(&exam, &st.db).await?;
@@ -879,7 +782,7 @@ async fn exam_statistics(
879 Path(id): Path<String>,782 Path(id): Path<String>,
880 ) -> Result<Json<ExamStatisticsResponse>, AppError> {783 ) -> Result<Json<ExamStatisticsResponse>, AppError> {
881 // Exam must exist — a missing exam is a 404, not an empty statistic.784 // Exam must exist — a missing exam is a 404, not an empty statistic.
882- let exam = Exam::read(&ExamId::from_key(&id), &st.db)785+ let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
883 .await?786 .await?
884 .ok_or(AppError::NotFound)?;787 .ok_or(AppError::NotFound)?;
885 let course = course_of(&exam, &st.db).await?;788 let course = course_of(&exam, &st.db).await?;
src/web/exams/questions.rsmodified+7 -7
@@ -162,7 +162,7 @@ pub(crate) async fn create_question(
162 Path(id): Path<String>,162 Path(id): Path<String>,
163 Json(req): Json<CreateQuestion>,163 Json(req): Json<CreateQuestion>,
164 ) -> Result<(StatusCode, Json<QuestionResponse>), AppError> {164 ) -> Result<(StatusCode, Json<QuestionResponse>), AppError> {
165- let exam = Exam::read(&ExamId::from_key(&id), &st.db)165+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
166 .await?166 .await?
167 .ok_or(AppError::NotFound)?;167 .ok_or(AppError::NotFound)?;
168 let course = course_of(&exam, &st.db).await?;168 let course = course_of(&exam, &st.db).await?;
@@ -224,7 +224,7 @@ pub(crate) async fn list_questions(
224 Query(page): Query<PageParams>,224 Query(page): Query<PageParams>,
225 ) -> Result<Json<Page<QuestionResponse>>, AppError> {225 ) -> Result<Json<Page<QuestionResponse>>, AppError> {
226 let (limit, offset) = page.resolve()?;226 let (limit, offset) = page.resolve()?;
227- let exam = Exam::read(&ExamId::from_key(&id), &st.db)227+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
228 .await?228 .await?
229 .ok_or(AppError::NotFound)?;229 .ok_or(AppError::NotFound)?;
230 let course = course_of(&exam, &st.db).await?;230 let course = course_of(&exam, &st.db).await?;
@@ -302,7 +302,7 @@ pub(crate) async fn update_question(
302 Path((id, qid)): Path<(String, String)>,302 Path((id, qid)): Path<(String, String)>,
303 Json(req): Json<UpdateQuestion>,303 Json(req): Json<UpdateQuestion>,
304 ) -> Result<Json<QuestionResponse>, AppError> {304 ) -> Result<Json<QuestionResponse>, AppError> {
305- let exam = Exam::read(&ExamId::from_key(&id), &st.db)305+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
306 .await?306 .await?
307 .ok_or(AppError::NotFound)?;307 .ok_or(AppError::NotFound)?;
308 let course = course_of(&exam, &st.db).await?;308 let course = course_of(&exam, &st.db).await?;
@@ -390,7 +390,7 @@ pub(crate) async fn delete_question(
390 RequireTeacher(user): RequireTeacher,390 RequireTeacher(user): RequireTeacher,
391 Path((id, qid)): Path<(String, String)>,391 Path((id, qid)): Path<(String, String)>,
392 ) -> Result<StatusCode, AppError> {392 ) -> Result<StatusCode, AppError> {
393- let exam = Exam::read(&ExamId::from_key(&id), &st.db)393+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
394 .await?394 .await?
395 .ok_or(AppError::NotFound)?;395 .ok_or(AppError::NotFound)?;
396 let course = course_of(&exam, &st.db).await?;396 let course = course_of(&exam, &st.db).await?;
@@ -462,7 +462,7 @@ pub(crate) async fn question_from_bank(
462 Path((id, bid)): Path<(String, String)>,462 Path((id, bid)): Path<(String, String)>,
463 Json(req): Json<InstantiateFromBank>,463 Json(req): Json<InstantiateFromBank>,
464 ) -> Result<(StatusCode, Json<QuestionResponse>), AppError> {464 ) -> Result<(StatusCode, Json<QuestionResponse>), AppError> {
465- let exam = Exam::read(&ExamId::from_key(&id), &st.db)465+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
466 .await?466 .await?
467 .ok_or(AppError::NotFound)?;467 .ok_or(AppError::NotFound)?;
468 let course = course_of(&exam, &st.db).await?;468 let course = course_of(&exam, &st.db).await?;
@@ -593,7 +593,7 @@ pub(crate) async fn question_refresh_from_bank(
593 RequireTeacher(user): RequireTeacher,593 RequireTeacher(user): RequireTeacher,
594 Path((id, qid)): Path<(String, String)>,594 Path((id, qid)): Path<(String, String)>,
595 ) -> Result<Json<QuestionResponse>, AppError> {595 ) -> Result<Json<QuestionResponse>, AppError> {
596- let exam = Exam::read(&ExamId::from_key(&id), &st.db)596+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
597 .await?597 .await?
598 .ok_or(AppError::NotFound)?;598 .ok_or(AppError::NotFound)?;
599 let course = course_of(&exam, &st.db).await?;599 let course = course_of(&exam, &st.db).await?;
@@ -718,7 +718,7 @@ pub(crate) async fn question_to_bank(
718 RequireTeacher(user): RequireTeacher,718 RequireTeacher(user): RequireTeacher,
719 Path((id, qid)): Path<(String, String)>,719 Path((id, qid)): Path<(String, String)>,
720 ) -> Result<(StatusCode, Json<BankQuestionResponse>), AppError> {720 ) -> Result<(StatusCode, Json<BankQuestionResponse>), AppError> {
721- let exam = Exam::read(&ExamId::from_key(&id), &st.db)721+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
722 .await?722 .await?
723 .ok_or(AppError::NotFound)?;723 .ok_or(AppError::NotFound)?;
724 let course = course_of(&exam, &st.db).await?;724 let course = course_of(&exam, &st.db).await?;
src/web/exams/review.rsmodified+3 -3
@@ -12,7 +12,7 @@ use crate::service::exam_question;
12 12
13 /// The exam plus the manage-rights check the grading and history reads share.13 /// The exam plus the manage-rights check the grading and history reads share.
14 pub(crate) async fn gradable_exam(st: &AppState, user: &User, id: &str) -> Result<Exam, AppError> {14 pub(crate) async fn gradable_exam(st: &AppState, user: &User, id: &str) -> Result<Exam, AppError> {
15- let exam = Exam::read(&ExamId::from_key(id), &st.db)15+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(id))
16 .await?16 .await?
17 .ok_or(AppError::NotFound)?;17 .ok_or(AppError::NotFound)?;
18 let course = course_of(&exam, &st.db).await?;18 let course = course_of(&exam, &st.db).await?;
@@ -202,7 +202,7 @@ pub(crate) async fn reviewable_exam(
202 user: &User,202 user: &User,
203 id: &str,203 id: &str,
204 ) -> Result<Exam, AppError> {204 ) -> Result<Exam, AppError> {
205- let exam = Exam::read(&ExamId::from_key(id), &st.db)205+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(id))
206 .await?206 .await?
207 .ok_or(AppError::NotFound)?;207 .ok_or(AppError::NotFound)?;
208 if exam.is_draft() {208 if exam.is_draft() {
@@ -267,7 +267,7 @@ async fn live_elsewhere(
267 let now = Timestamp::now();267 let now = Timestamp::now();
268 let mut live = Vec::new();268 let mut live = Vec::new();
269 for attempt in list_unfinished_for_user(&st.db, user.get_id()).await? {269 for attempt in list_unfinished_for_user(&st.db, user.get_id()).await? {
270- let Some(other) = Exam::read(attempt.get_exam(), &st.db).await? else {270+ let Some(other) = crate::service::exam::read(&st.db, attempt.get_exam()).await? else {
271 continue;271 continue;
272 };272 };
273 if attempt.status(&other, now) == AttemptStatus::InProgress {273 if attempt.status(&other, now) == AttemptStatus::InProgress {
src/web/marks.rsmodified+1 -1
@@ -107,7 +107,7 @@ async fn build_report(
107 107
108 let mut blocks = Vec::with_capacity(courses.len());108 let mut blocks = Vec::with_capacity(courses.len());
109 for course in &courses {109 for course in &courses {
110- let exams = Exam::list_for_course(course.get_id(), db).await?;110+ let exams = crate::service::exam::list_for_course(db, course.get_id()).await?;
111 let by_key: HashMap<&str, &Exam> = exams.iter().map(|e| (e.get_id().key(), e)).collect();111 let by_key: HashMap<&str, &Exam> = exams.iter().map(|e| (e.get_id().key(), e)).collect();
112 112
113 let results = ExamResult::list_for_user_in_course(course.get_id(), user, db).await?;113 let results = ExamResult::list_for_user_in_course(course.get_id(), user, db).await?;
tests/regress_course_child_orphans.rsmodified+5 -5
@@ -31,10 +31,10 @@
31 //!31 //!
32 //! The **race** half drives the real interleaving and lives in-crate, one pin32 //! The **race** half drives the real interleaving and lives in-crate, one pin
33 //! per child beside the create it pins —33 //! per child beside the create it pins —
34-//! `domain::exam::tests::an_exam_never_outlives_its_course`,34+//! `db::exam::tests::an_exam_never_outlives_its_course`,
35 //! `db::course_session::tests::a_session_never_outlives_its_course`,35 //! `db::course_session::tests::a_session_never_outlives_its_course`,
36 //! `domain::subject::tests::a_subject_never_outlives_its_course` — over the36 //! `domain::subject::tests::a_subject_never_outlives_its_course` — over the
37-//! shared harness `domain::course::assert_no_child_outlives_a_course_delete`.37+//! shared harness `db::course::assert_no_child_outlives_a_course_delete`.
38 //! It is `#[ignore]`d and needs a real server, because the subject there *is*38 //! It is `#[ignore]`d and needs a real server, because the subject there *is*
39 //! the store's conflict detection, which the embedded engine does not have: it39 //! the store's conflict detection, which the embedded engine does not have: it
40 //! commits both sides and answers `Ok` to each, so a race test on `memory`40 //! commits both sides and answers `Ok` to each, so a race test on `memory`
@@ -55,7 +55,7 @@ use hezarfen_backend::domain::course_note::{CourseNote, CourseNoteContent, Cours
55 use hezarfen_backend::domain::course_note_file::{CourseNoteFile, FileContentType, FileName};55 use hezarfen_backend::domain::course_note_file::{CourseNoteFile, FileContentType, FileName};
56 use hezarfen_backend::domain::course_session::SessionTopic;56 use hezarfen_backend::domain::course_session::SessionTopic;
57 use hezarfen_backend::domain::exam::{57 use hezarfen_backend::domain::exam::{
58- Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,58+ ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,
59 };59 };
60 use hezarfen_backend::domain::settings::Settings;60 use hezarfen_backend::domain::settings::Settings;
61 use hezarfen_backend::domain::subject::{Subject, SubjectDescription, SubjectName};61 use hezarfen_backend::domain::subject::{Subject, SubjectDescription, SubjectName};
@@ -103,7 +103,8 @@ async fn drop_course(course: &CourseId, db: &Database) -> Result<bool, AppError>
103 fn make_exam(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> {103 fn make_exam(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> {
104 tokio::spawn(async move {104 tokio::spawn(async move {
105 let kinds = Settings::defaults().get_exam_kinds().to_vec();105 let kinds = Settings::defaults().get_exam_kinds().to_vec();
106- Exam::create(106+ hezarfen_backend::db::exam::create(
107+ &db,
107 &teacher(),108 &teacher(),
108 &course,109 &course,
109 ExamTitle::try_new("quiz").unwrap(),110 ExamTitle::try_new("quiz").unwrap(),
@@ -114,7 +115,6 @@ fn make_exam(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>>
114 true,115 true,
115 false,116 false,
116 false,117 false,
117- &db,
118 )118 )
119 .await119 .await
120 .map(|_| ())120 .map(|_| ())