forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'layer-split/exam_attempt'

Browse files at this commit

7267caae829416a0fda3735d379a0e63c8a2ca86Ahmet Kaan GümüşParent: ecd88d4c13b51d
# Conflicts:
#	src/db/mod.rs
#	src/domain/exam_attempt.rs
#	src/service/mod.rs
#	src/web/courses.rs
#	src/web/exam_ws.rs
#	src/web/exams/attempts.rs
#	src/web/exams/mod.rs
#	tests/regress_course_delete.rs

18 changed files +1367 -1139

src/db/exam_attempt.rsadded+488 -0
@@ -0,0 +1,488 @@
1+//! The `exam_attempt` table: sitting reads, the two field-scoped writes
2+//! (`finished_at`, `left_at`), and the `write_unfrozen` transaction gateway
3+//! that ties exam-child writes to their exam row.
4+
5+use surrealdb::types::{RecordId, SurrealValue};
6+
7+use crate::constant::EXAM_RESULT_COUNT_FIELD;
8+use crate::database::{Database, transaction_with_retry};
9+use crate::domain::exam::ExamId;
10+use crate::domain::exam_attempt::{ExamAttempt, ExamAttemptId};
11+use crate::domain::timestamp::Timestamp;
12+use crate::domain::user::UserId;
13+use crate::error::AppError;
14+
15+/// The `THROW` marker the freeze gate aborts with, and the one 409 both it and
16+/// the handler's pre-flight check answer with — a client cannot tell which of
17+/// the two refused.
18+const FROZEN_MARK: &str = "questions_frozen";
19+
20+/// The `THROW` marker the exam-existence touch aborts with — the exam row this
21+/// write hangs off is gone, so the write is a 404 and nothing lands.
22+const GONE_MARK: &str = "no_exam";
23+
24+/// The 409 the freeze gate's marker means.
25+fn frozen_error() -> AppError {
26+ AppError::Conflict("cannot change questions after attempts have started")
27+}
28+
29+/// Stamp the submission time. The caller has already checked the deadline
30+/// and that the attempt isn't finished.
31+///
32+/// Writes *only* `finished_at`, for the mirror image of
33+/// [`set_left`]'s reason: the submit path reads the attempt,
34+/// then awaits its deadline and already-finished checks before writing, and
35+/// the exam room stamps or clears `left_at` on the same row from a socket.
36+/// A whole-row write from the pre-read snapshot would carry its stale
37+/// `left_at` back over that stamp, erasing the recorded walk-out.
38+pub async fn finish(db: &Database, attempt: ExamAttempt) -> Result<ExamAttempt, AppError> {
39+ let mut result = db
40+ .query("UPDATE $id SET finished_at = $at RETURN AFTER")
41+ .bind(("id", attempt.id.record()))
42+ .bind(("at", Some(Timestamp::now())))
43+ .await?
44+ .check()?;
45+ result
46+ .take::<Vec<ExamAttempt>>(0)?
47+ .into_iter()
48+ .next()
49+ .ok_or(AppError::NotFound)
50+}
51+
52+/// Stamp (or clear) the walked-out marker. The exam room sets it when the
53+/// student's socket closes mid-attempt and clears it when they come back.
54+///
55+/// Writes *only* the `left_at` field (never the whole row): the room's
56+/// teardown reads the attempt, sees it in progress, then stamps here — and
57+/// a submission that lands in that gap must survive. A whole-row write from
58+/// the pre-read snapshot would carry its blank `finished_at` back over the
59+/// fresh submission, silently un-submitting the exam (and, with
60+/// `allow_rejoin` off, locking the student out).
61+pub async fn set_left(
62+ db: &Database,
63+ attempt: ExamAttempt,
64+ left_at: Option<Timestamp>,
65+) -> Result<ExamAttempt, AppError> {
66+ let mut result = db
67+ .query("UPDATE $id SET left_at = $left RETURN AFTER")
68+ .bind(("id", attempt.id.record()))
69+ .bind(("left", left_at))
70+ .await?
71+ .check()?;
72+ result
73+ .take::<Vec<ExamAttempt>>(0)?
74+ .into_iter()
75+ .next()
76+ .ok_or(AppError::NotFound)
77+}
78+
79+/// One sitting by id — the exam room re-reads its own attempt this way,
80+/// so a retake started elsewhere can never be mistaken for it.
81+pub async fn read(db: &Database, id: &ExamAttemptId) -> Result<Option<ExamAttempt>, AppError> {
82+ Ok(db.select(id.record()).await?)
83+}
84+
85+/// The student's current sitting — the highest `seq` for the pair. All
86+/// reads that used to mean "the attempt" mean this now.
87+pub async fn read_latest_for_user(
88+ db: &Database,
89+ exam: &ExamId,
90+ user: &UserId,
91+) -> Result<Option<ExamAttempt>, AppError> {
92+ let mut result = db
93+ .query(
94+ "SELECT * FROM exam_attempt WHERE exam = $ex AND user = $usr
95+ ORDER BY seq DESC LIMIT 1",
96+ )
97+ .bind(("ex", exam.record()))
98+ .bind(("usr", user.record()))
99+ .await?
100+ .check()?;
101+ Ok(result.take::<Vec<ExamAttempt>>(0)?.into_iter().next())
102+}
103+
104+/// Every sitting of `user` at `exam`, newest first.
105+pub async fn list_for_user(
106+ db: &Database,
107+ exam: &ExamId,
108+ user: &UserId,
109+) -> Result<Vec<ExamAttempt>, AppError> {
110+ let mut result = db
111+ .query(
112+ "SELECT * FROM exam_attempt WHERE exam = $ex AND user = $usr
113+ ORDER BY seq DESC",
114+ )
115+ .bind(("ex", exam.record()))
116+ .bind(("usr", user.record()))
117+ .await?
118+ .check()?;
119+ Ok(result.take::<Vec<ExamAttempt>>(0)?)
120+}
121+
122+/// Every sitting of `user` nobody has submitted yet, across all exams. Only
123+/// the *candidates* for "in progress": a deadline comes off the exam's live
124+/// schedule, so the caller still judges [`ExamAttempt::status`] per exam rather
125+/// than re-spelling that rule in SurrealQL.
126+pub async fn list_unfinished_for_user(
127+ db: &Database,
128+ user: &UserId,
129+) -> Result<Vec<ExamAttempt>, AppError> {
130+ let mut result = db
131+ .query("SELECT * FROM exam_attempt WHERE user = $usr AND finished_at = NONE")
132+ .bind(("usr", user.record()))
133+ .await?
134+ .check()?;
135+ Ok(result.take::<Vec<ExamAttempt>>(0)?)
136+}
137+
138+pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<ExamAttempt>, AppError> {
139+ let mut result = db
140+ .query("SELECT * FROM exam_attempt WHERE exam = $ex ORDER BY id DESC")
141+ .bind(("ex", exam.record()))
142+ .await?
143+ .check()?;
144+ Ok(result.take::<Vec<ExamAttempt>>(0)?)
145+}
146+
147+/// Whether anyone has started this exam — the gate that freezes `mode`
148+/// edits once an attempt exists.
149+pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result<bool, AppError> {
150+ let mut result = db
151+ .query("SELECT VALUE id FROM exam_attempt WHERE exam = $ex LIMIT 1")
152+ .bind(("ex", exam.record()))
153+ .await?
154+ .check()?;
155+ Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
156+}
157+
158+/// Send `statements` wrapped in a transaction that refuses to run them at
159+/// all once `exam` has an attempt — the freeze gate, made atomic with the
160+/// write it guards instead of merely preceding it. `freeze_exam` is bound
161+/// here; the caller binds the rest and reads its own results from
162+/// [`FROZEN_SLOT`] onwards.
163+///
164+/// The same transaction *writes* the exam row — bumping its mark counter
165+/// 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`,
167+/// and a read does not survive [`Exam::delete`](crate::domain::exam::Exam::delete)'s
168+/// 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 the
170+/// cascade's `DELETE exam_question WHERE exam = $ex` ran on a snapshot
171+/// predating this insert — so both commit and the child outlives the exam,
172+/// with neither caller told anything. Writing a key the delete also writes
173+/// makes the two collide and the store refuses one side. It is the shape
174+/// [`crate::domain::exam_answer::ExamAnswer::save`] and
175+/// [`crate::domain::menu::bump_menu_and_write`] already use.
176+///
177+/// An orphan here is not merely untidy: an `exam_question` that outlives
178+/// its exam keeps the reference it claimed on its subject (the cascade's
179+/// per-subject decrement counted the rows it could see), and
180+/// [`crate::domain::subject::Subject::delete`] is gated on that count
181+/// reading zero — a subject nobody can ever delete again.
182+///
183+/// The bump is restored *by captured value*, `NONE` included, so the row is
184+/// byte-identical afterwards: the boot backfill still finds the rows it
185+/// keys on (`WHERE result_count = NONE`) and a teacher's PATCH, which pins
186+/// that counter, is not refused because somebody added a question. Writing
187+/// the same value back would not do — an `UPDATE` that leaves the document
188+/// unchanged is elided and never reaches the store's write set, so it
189+/// collides with nothing.
190+///
191+/// This replaces a process-wide `EXAM_LOCK.write()` held across the check
192+/// and the write. That lock ordered the two requests but still read the
193+/// attempt table a round trip before it wrote; the gate checks inside the
194+/// writing statement, so a question edit can no longer sail past an attempt
195+/// that started in that gap.
196+///
197+/// The send lives here rather than at the five call sites because a lost
198+/// round has to be re-sent, and only whoever owns the send can re-send: the
199+/// gate reads the very table its rival writes, so the two contend by design
200+/// and a raced edit used to answer 500. The refusal outranks the conflict —
201+/// `FROZEN_MARK` is a decision and stays the 409 the pre-flight check
202+/// answers with, and only exhausting the tries becomes a 500. See
203+/// [`transaction_with_retry`] for why the whole error map is scanned: an
204+/// aborted transaction errors *every* slot and all but one say a generic
205+/// "not executed".
206+///
207+/// Returning only on an empty error map is what keeps [`FROZEN_SLOT`]
208+/// (and any slot counted off `num_statements`) correct — `take_errors`
209+/// `swap_remove`s errored slots, so a fixed slot read is meaningless once
210+/// anything failed.
211+//
212+// corner-cut: the count and a concurrent `CREATE exam_attempt` are still not
213+// serialized against each other — SurrealDB does not conflict-check a
214+// cross-record count (the write skew `db::cap` exists for), so an
215+// attempt landing in the same instant as an edit can still interleave
216+// either way. The mutex this replaces closed that inside one process only,
217+// and there are two, so nothing is lost. Closing it properly means the
218+// cap.rs shape: an attempt counter on the exam row, incremented by the
219+// attempt create, and the write conditioned on `count ?? 0 = 0`.
220+pub async fn write_unfrozen(
221+ db: &Database,
222+ exam: &ExamId,
223+ statements: &str,
224+ bindings: Vec<(String, surrealdb::types::Value)>,
225+) -> Result<surrealdb::IndexedResults, AppError> {
226+ write_unfrozen_with(db, exam, statements, bindings, Vec::new()).await
227+}
228+
229+/// [`write_unfrozen`] for statements that carry gates of their own:
230+/// each `(marker, refusal)` names a `THROW` the caller's SQL aborts with and
231+/// the error it means. The markers are handed to [`transaction_with_retry`]
232+/// too, so an abort on one is a refusal rather than a round to re-send.
233+///
234+/// The freeze still outranks every one of them: a caller folding a counter
235+/// claim in here is refused as frozen even when its own gate would also have
236+/// fired, which is the answer the pre-flight check has always given.
237+pub async fn write_unfrozen_with(
238+ db: &Database,
239+ exam: &ExamId,
240+ statements: &str,
241+ bindings: Vec<(String, surrealdb::types::Value)>,
242+ refusals: Vec<(&str, AppError)>,
243+) -> Result<surrealdb::IndexedResults, AppError> {
244+ let sql = format!(
245+ "BEGIN TRANSACTION;
246+ IF array::len((SELECT VALUE id FROM exam_attempt \
247+ WHERE exam = $freeze_exam LIMIT 1)) > 0 {{ THROW '{FROZEN_MARK}' }};
248+ LET $was_results = \
249+ (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $freeze_exam);
250+ LET $touched = (UPDATE $freeze_exam SET {EXAM_RESULT_COUNT_FIELD} = \
251+ ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id);
252+ IF array::len($touched) = 0 {{ THROW '{GONE_MARK}' }};
253+ UPDATE $freeze_exam SET {EXAM_RESULT_COUNT_FIELD} = $was_results;
254+ {statements}
255+ COMMIT TRANSACTION;"
256+ );
257+ let mut bound = vec![("freeze_exam".into(), exam.record().into_value())];
258+ bound.extend(bindings);
259+ let mut marks = vec![FROZEN_MARK, GONE_MARK];
260+ marks.extend(refusals.iter().map(|(marker, _)| *marker));
261+ let (result, mut errors) = transaction_with_retry(db, &sql, &bound, &marks).await?;
262+ let thrown = |marker: &str| {
263+ errors
264+ .values()
265+ .any(|error| error.to_string().contains(marker))
266+ };
267+ if thrown(FROZEN_MARK) {
268+ return Err(frozen_error());
269+ }
270+ // The exam is gone: the same 404 every one of these writes' handlers
271+ // answers a missing exam with, and it outranks the callers' own gates
272+ // for the freeze's reason — there is nothing left to refuse *about*.
273+ if thrown(GONE_MARK) {
274+ return Err(AppError::NotFound);
275+ }
276+ for (marker, refusal) in refusals {
277+ if thrown(marker) {
278+ return Err(refusal);
279+ }
280+ }
281+ match errors.drain().map(|(_, error)| error).next() {
282+ Some(error) => Err(error.into()),
283+ None => Ok(result),
284+ }
285+}
286+
287+/// The first slot a [`write_unfrozen`] caller's own statements land
288+/// in: `BEGIN`, the freeze `IF`, and the exam touch's two `LET`s, `IF` and
289+/// restoring `UPDATE` take one each.
290+pub const FROZEN_SLOT: usize = 6;
291+
292+#[cfg(test)]
293+mod tests {
294+ use super::*;
295+ use crate::database::init_mem;
296+ use crate::domain::exam::{
297+ Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,
298+ };
299+ use crate::domain::exam_question::{
300+ ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec,
301+ };
302+ use crate::domain::settings::Settings;
303+
304+ /// An open exam with retakes allowed, plus one choice question — enough
305+ /// rows to exercise the attempt lifecycle without the HTTP layer.
306+ async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) {
307+ let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
308+ let course = crate::domain::course::a_test_course(db).await;
309+ let kinds = Settings::defaults().get_exam_kinds().to_vec();
310+ let exam = Exam::create(
311+ &creator,
312+ &course,
313+ ExamTitle::try_new("practice").unwrap(),
314+ ExamDescription::try_new("").unwrap(),
315+ ExamKind::try_new("quiz", &kinds).unwrap(),
316+ ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None)
317+ .unwrap(),
318+ ExamAttemptLimit::try_new(max_attempts).unwrap(),
319+ true,
320+ false,
321+ false,
322+ db,
323+ )
324+ .await
325+ .unwrap();
326+ let spec = QuestionSpec::try_new(
327+ QuestionKind::try_new("choice").unwrap(),
328+ Some(vec![
329+ ChoiceInput {
330+ id: Some("a".into()),
331+ text: "5".into(),
332+ },
333+ ChoiceInput {
334+ id: Some("b".into()),
335+ text: "6".into(),
336+ },
337+ ]),
338+ Some("b".into()),
339+ &[],
340+ )
341+ .unwrap();
342+ // A real subject row, not a minted id: a question claims a reference on
343+ // its subject and is refused if that subject does not exist.
344+ let subject = crate::domain::subject::Subject::create(
345+ &crate::domain::course::a_test_course(db).await,
346+ crate::domain::subject::SubjectName::try_new("topic").unwrap(),
347+ crate::domain::subject::SubjectDescription::try_new("").unwrap(),
348+ db,
349+ )
350+ .await
351+ .unwrap();
352+ let question = ExamQuestion::create(
353+ exam.get_id(),
354+ subject.get_id().clone(),
355+ crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(),
356+ QuestionPoints::try_new(5).unwrap(),
357+ spec,
358+ db,
359+ )
360+ .await
361+ .unwrap();
362+ (exam, question)
363+ }
364+
365+ /// A real user row: the sitting counter lives on it, and the claim that
366+ /// rides the attempt's create has nothing to write to without one.
367+ async fn student(db: &Database) -> UserId {
368+ let hash = crate::domain::user::Password::try_new("secret1")
369+ .unwrap()
370+ .hash_async()
371+ .await
372+ .unwrap();
373+ crate::domain::user::User::create(
374+ crate::domain::user::Username::try_new("ogrenci").unwrap(),
375+ hash,
376+ db,
377+ )
378+ .await
379+ .unwrap()
380+ .get_id()
381+ .clone()
382+ }
383+
384+ #[tokio::test]
385+ async fn submitting_never_reverts_a_walk_out_that_raced_it() {
386+ let db = init_mem().await.unwrap();
387+ let (exam, _question) = open_exam_with_question(&db, 1).await;
388+ let user = student(&db).await;
389+
390+ let (attempt, _) = crate::service::exam_attempt::start(&db, &exam, &user)
391+ .await
392+ .unwrap();
393+
394+ // The REST submit path reads the attempt, then checks the deadline and
395+ // the already-finished guard — several awaits before it writes.
396+ let stale = read(&db, attempt.get_id())
397+ .await
398+ .unwrap()
399+ .expect("attempt exists");
400+ assert!(stale.get_left_at().is_none());
401+
402+ // In that gap the exam room's teardown stamps the walk-out (or a join
403+ // clears it) — a field-scoped write to the same row.
404+ set_left(
405+ &db,
406+ read(&db, attempt.get_id())
407+ .await
408+ .unwrap()
409+ .expect("attempt exists"),
410+ Some(Timestamp::now()),
411+ )
412+ .await
413+ .unwrap();
414+
415+ // The submit now writes from its stale snapshot. It owns `finished_at`
416+ // and nothing else: carrying the snapshot's blank `left_at` back over
417+ // the fresh stamp erases the recorded walk-out.
418+ let finished = finish(&db, stale).await.unwrap();
419+ assert!(finished.get_finished_at().is_some());
420+
421+ let after = read(&db, attempt.get_id())
422+ .await
423+ .unwrap()
424+ .expect("attempt still exists");
425+ assert!(
426+ after.get_left_at().is_some(),
427+ "submitting must not revert a walk-out stamp that raced it"
428+ );
429+ assert!(after.get_finished_at().is_some(), "the submission stands");
430+ }
431+
432+ #[tokio::test]
433+ async fn stamping_left_never_reverts_a_submission() {
434+ let db = init_mem().await.unwrap();
435+ let (exam, _question) = open_exam_with_question(&db, 1).await;
436+ let user = student(&db).await;
437+
438+ // The student is sitting the exam.
439+ let (attempt, _) = crate::service::exam_attempt::start(&db, &exam, &user)
440+ .await
441+ .unwrap();
442+ assert_eq!(attempt.get_seq(), 1);
443+
444+ // The exam-room teardown reads the attempt while it is still in
445+ // progress (`stamp_left`'s read) — a snapshot with `finished_at` unset.
446+ let stale = read(&db, attempt.get_id())
447+ .await
448+ .unwrap()
449+ .expect("attempt exists");
450+ assert!(stale.get_finished_at().is_none());
451+ let finished = finish(
452+ &db,
453+ read(&db, attempt.get_id())
454+ .await
455+ .unwrap()
456+ .expect("attempt exists"),
457+ )
458+ .await
459+ .unwrap();
460+ assert!(finished.get_finished_at().is_some());
461+
462+ // Now the last socket's teardown stamps `left_at` from its stale
463+ // snapshot. Stamping the walk-out must touch only `left_at` — it must
464+ // not carry the snapshot's blank `finished_at` back over the fresh
465+ // submission, or the student's submitted exam silently reopens (and,
466+ // with `allow_rejoin` off, locks them out of a room they left after
467+ // finishing).
468+ set_left(&db, stale, Some(Timestamp::now())).await.unwrap();
469+
470+ let after = read(&db, attempt.get_id())
471+ .await
472+ .unwrap()
473+ .expect("attempt still exists");
474+ assert!(
475+ after.get_finished_at().is_some(),
476+ "stamping left_at must not revert a submission that raced it"
477+ );
478+ assert!(
479+ after.get_left_at().is_some(),
480+ "the walk-out is still recorded"
481+ );
482+ assert_eq!(
483+ after.status(&exam, Timestamp::now()),
484+ crate::domain::exam_attempt::AttemptStatus::Submitted,
485+ "the attempt stays submitted"
486+ );
487+ }
488+}
src/db/mod.rsmodified+1 -0
@@ -3,6 +3,7 @@
3 pub mod appointment;3 pub mod appointment;
4 pub mod cap;4 pub mod cap;
5 pub mod course;5 pub mod course;
6+pub mod exam_attempt;
6 pub mod field_update;7 pub mod field_update;
7 pub mod note;8 pub mod note;
8 pub mod page;9 pub mod page;
src/domain/exam.rsmodified+3 -3
@@ -599,7 +599,7 @@ impl Exam {
599 )599 )
600 .await?;600 .await?;
601 // An aborted transaction errors every slot; only the THROW's names the601 // An aborted transaction errors every slot; only the THROW's names the
602- // marker (the [`ExamAttempt::write_unfrozen`] treatment).602+ // marker (the [`crate::db::exam_attempt::write_unfrozen`] treatment).
603 if errors603 if errors
604 .values()604 .values()
605 .any(|error| error.to_string().contains("exam_redraft"))605 .any(|error| error.to_string().contains("exam_redraft"))
@@ -682,7 +682,7 @@ impl Exam {
682 682
683 /// An unscheduled published exam — the minimum any test that writes a *child*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 (see684 /// of an exam needs, in any module: every such write moves the exam row (see
685-/// [`ExamAttempt::write_unfrozen_with`](crate::domain::exam_attempt::ExamAttempt)685+/// [`crate::db::exam_attempt::write_unfrozen_with`]
686 /// and [`crate::domain::exam_answer::ExamAnswer::save`]), so a minted id whose686 /// 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.687 /// row was never created is a 404 rather than a silent orphan.
688 #[cfg(test)]688 #[cfg(test)]
@@ -1239,7 +1239,7 @@ mod tests {
1239 /// gated on that count reading zero — a subject nobody could ever delete1239 /// gated on that count reading zero — a subject nobody could ever delete
1240 /// again, hanging off an exam nobody could ever see. The freeze gate is a1240 /// again, hanging off an exam nobody could ever see. The freeze gate is a
1241 /// *read* of `exam_attempt` and never survived this window;1241 /// *read* of `exam_attempt` and never survived this window;
1242- /// [`ExamAttempt::write_unfrozen_with`] now writes the exam row too.1242+ /// [`crate::db::exam_attempt::write_unfrozen_with`] now writes the exam row too.
1243 ///1243 ///
1244 /// Same seam, same `#[ignore]`, same reason as the answer twin above: the1244 /// Same seam, same `#[ignore]`, same reason as the answer twin above: the
1245 /// subject *is* the store's conflict detection, which the in-memory engine1245 /// subject *is* the store's conflict detection, which the in-memory engine
src/domain/exam_attempt.rsmodified+17 -779
@@ -1,36 +1,20 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3-use crate::constant::{EXAM_ATTEMPT_TABLE, EXAM_RESULT_COUNT_FIELD, EXAM_SAT_TOTAL_FIELD};3+use crate::constant::EXAM_ATTEMPT_TABLE;
4-use crate::database::{Database, transaction_with_retry};
5 use crate::domain::exam::Exam;4 use crate::domain::exam::Exam;
6 use crate::domain::exam::ExamId;5 use crate::domain::exam::ExamId;
6+use crate::domain::key;
7 use crate::domain::timestamp::Timestamp;7 use crate::domain::timestamp::Timestamp;
8 use crate::domain::user::UserId;8 use crate::domain::user::UserId;
9-use crate::db::cap;
10-use crate::domain::{badge, key};
11-use crate::error::AppError;
12-
13-/// The `THROW` marker the freeze gate aborts with, and the one 409 both it and
14-/// the handler's pre-flight check answer with — a client cannot tell which of
15-/// the two refused.
16-const FROZEN_MARK: &str = "questions_frozen";
17-
18-/// The `THROW` marker the exam-existence touch aborts with — the exam row this
19-/// write hangs off is gone, so the write is a 404 and nothing lands.
20-const GONE_MARK: &str = "no_exam";
21-
22-pub(crate) fn frozen_error() -> AppError {
23- AppError::Conflict("cannot change questions after attempts have started")
24-}
25 9
10+/// A deterministic id for the (exam, user, seq) triple, so sitting `seq`
11+/// exists at most once by construction — a concurrent double "start" races
12+/// on the same id and exactly one create wins. See [`key::sitting`] for the
13+/// key shape and why the first sitting stays bare.
26 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]14 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
27 pub struct ExamAttemptId(RecordId);15 pub struct ExamAttemptId(RecordId);
28 16
29 impl ExamAttemptId {17 impl ExamAttemptId {
30- /// A deterministic id for the (exam, user, seq) triple, so sitting `seq`
31- /// exists at most once by construction — a concurrent double "start" races
32- /// on the same id and exactly one create wins. See [`key::sitting`] for the
33- /// key shape and why the first sitting stays bare.
34 pub fn composite(exam: &ExamId, user: &UserId, seq: i64) -> Self {18 pub fn composite(exam: &ExamId, user: &UserId, seq: i64) -> Self {
35 let key = key::sitting(exam.key(), user.key(), seq);19 let key = key::sitting(exam.key(), user.key(), seq);
36 Self(RecordId::new(EXAM_ATTEMPT_TABLE, key))20 Self(RecordId::new(EXAM_ATTEMPT_TABLE, key))
@@ -75,15 +59,19 @@ impl AttemptStatus {
75 /// `finished_at` the submission. `seq` numbers the sittings (1, 2, …) when the59 /// `finished_at` the submission. `seq` numbers the sittings (1, 2, …) when the
76 /// exam allows retakes; `left_at` marks a student who walked out of the exam60 /// exam allows retakes; `left_at` marks a student who walked out of the exam
77 /// room mid-attempt. Grading stays a separate `exam_result` row.61 /// room mid-attempt. Grading stays a separate `exam_result` row.
62+///
63+/// Fields are crate-visible: [`crate::db::exam_attempt`] reads the id to
64+/// target its field-scoped writes and [`crate::service::exam_attempt::start`]
65+/// mints the rows on create.
78 #[derive(Debug, Clone, SurrealValue)]66 #[derive(Debug, Clone, SurrealValue)]
79 pub struct ExamAttempt {67 pub struct ExamAttempt {
80- id: ExamAttemptId,68+ pub(crate) id: ExamAttemptId,
81- exam: ExamId,69+ pub(crate) exam: ExamId,
82- user: UserId,70+ pub(crate) user: UserId,
83- seq: i64,71+ pub(crate) seq: i64,
84- started_at: Timestamp,72+ pub(crate) started_at: Timestamp,
85- finished_at: Option<Timestamp>,73+ pub(crate) finished_at: Option<Timestamp>,
86- left_at: Option<Timestamp>,74+ pub(crate) left_at: Option<Timestamp>,
87 }75 }
88 76
89 impl ExamAttempt {77 impl ExamAttempt {
@@ -151,754 +139,4 @@ impl ExamAttempt {
151 _ => AttemptStatus::InProgress,139 _ => AttemptStatus::InProgress,
152 }140 }
153 }141 }
154-
155- /// Start (or resume) `user`'s attempt at `exam`. Returns the attempt plus
156- /// whether it was newly created.
157- ///
158- /// - A still-running latest attempt is returned untouched, so a
159- /// reconnecting client gets its original clock back instead of a reset —
160- /// re-"starting" can never buy more time.
161- /// - A terminal latest attempt (submitted or expired) starts sitting
162- /// `seq + 1` if the exam's `max_attempts` allows another, and is a
163- /// conflict otherwise. A retake preserves every prior sitting: the new
164- /// row is created at the new `seq` and the student's earlier answers,
165- /// drawings, and marks stay put at their own seq — the fresh sitting
166- /// simply writes into an empty higher seq.
167- ///
168- /// The composite id makes each create atomic; a concurrent double-start
169- /// races on the same seq, loses to the unique id, and reads the winner's
170- /// row.
171- ///
172- /// A created row rides [`cap::create_counting`] so the student's
173- /// `exam_sat_total` moves in the same transaction — but only for `seq == 1`,
174- /// because that counter is *exams sat*, not sittings. A retake is the same
175- /// exam again, and counting it made a badge a student could mint alone: an
176- /// open exam with unlimited attempts is a start/finish loop nobody else has
177- /// to touch. `seq == 1` is the whole condition and needs no extra read —
178- /// the first sitting's id is one deterministic key, so of every writer
179- /// aiming at it exactly one `CREATE` commits and the losers' increments
180- /// abort with their duplicates, while a retake computes its seq from a row
181- /// that already exists. A `SELECT` inside the transaction would be strictly
182- /// worse: SurrealDB 3.2.3 conflict-checks write sets, not read sets.
183- pub async fn start(
184- exam: &Exam,
185- user: &UserId,
186- db: &Database,
187- ) -> Result<(ExamAttempt, bool), AppError> {
188- let attempts = Self::list_for_user(exam.get_id(), user, db).await?;
189- let next_seq = match attempts.first() {
190- None => 1,
191- Some(latest) if latest.status(exam, Timestamp::now()) == AttemptStatus::InProgress => {
192- return Ok((latest.clone(), false));
193- }
194- Some(latest) => {
195- if !exam.get_max_attempts().allows_another(attempts.len()) {
196- return Err(AppError::Conflict(
197- "no attempts remaining — this exam's attempt limit is used up",
198- ));
199- }
200- latest.seq + 1
201- }
202- };
203- let attempt = ExamAttempt {
204- id: ExamAttemptId::composite(exam.get_id(), user, next_seq),
205- exam: exam.get_id().clone(),
206- user: user.clone(),
207- seq: next_seq,
208- started_at: Timestamp::now(),
209- finished_at: None,
210- left_at: None,
211- };
212- let id = attempt.id.record();
213- let first = next_seq == 1;
214- match cap::create_counting(
215- &user.record(),
216- EXAM_SAT_TOTAL_FIELD,
217- first,
218- &id,
219- &attempt,
220- db,
221- )
222- .await?
223- {
224- cap::Claimed::Made(created) => {
225- // Only a moved counter can have crossed a threshold.
226- if first && let Err(err) = badge::sync(user, db).await {
227- tracing::warn!("failed to sync badges for {}: {err}", user.key());
228- }
229- Ok((created, true))
230- }
231- // Only a still-running row proves the loss was a double-start
232- // collision (the winner's fresh sitting); a terminal or missing
233- // latest means the create genuinely failed — surface that instead
234- // of passing a finished sitting off as a resume. The duplicate
235- // aborted the transaction, so the loser's increment went with it.
236- cap::Claimed::Duplicate => {
237- match Self::read_latest_for_user(exam.get_id(), user, db).await? {
238- Some(existing)
239- if existing.status(exam, Timestamp::now()) == AttemptStatus::InProgress =>
240- {
241- Ok((existing, false))
242- }
243- _ => Err(AppError::Internal("failed to start exam attempt".into())),
244- }
245- }
246- // Nothing caps sittings, so the conditional write can only miss by
247- // finding no user row — not a state a live session can reach, and
248- // passing it off as a resume would hand out a sitting the counter
249- // never learned about.
250- cap::Claimed::Full => Err(AppError::Internal(
251- "cannot start an exam attempt: the student's account row is missing".into(),
252- )),
253- }
254- }
255-
256- /// Stamp the submission time. The caller has already checked the deadline
257- /// and that the attempt isn't finished.
258- ///
259- /// Writes *only* `finished_at`, for the mirror image of
260- /// [`ExamAttempt::set_left`]'s reason: the submit path reads the attempt,
261- /// then awaits its deadline and already-finished checks before writing, and
262- /// the exam room stamps or clears `left_at` on the same row from a socket.
263- /// A whole-row write from the pre-read snapshot would carry its stale
264- /// `left_at` back over that stamp, erasing the recorded walk-out.
265- pub async fn finish(self, db: &Database) -> Result<ExamAttempt, AppError> {
266- let mut result = db
267- .query("UPDATE $id SET finished_at = $at RETURN AFTER")
268- .bind(("id", self.id.record()))
269- .bind(("at", Some(Timestamp::now())))
270- .await?
271- .check()?;
272- result
273- .take::<Vec<ExamAttempt>>(0)?
274- .into_iter()
275- .next()
276- .ok_or(AppError::NotFound)
277- }
278-
279- /// Stamp (or clear) the walked-out marker. The exam room sets it when the
280- /// student's socket closes mid-attempt and clears it when they come back.
281- ///
282- /// Writes *only* the `left_at` field (never the whole row): the room's
283- /// teardown reads the attempt, sees it in progress, then stamps here — and
284- /// a submission that lands in that gap must survive. A whole-row write from
285- /// the pre-read snapshot would carry its blank `finished_at` back over the
286- /// fresh submission, silently un-submitting the exam (and, with
287- /// `allow_rejoin` off, locking the student out).
288- pub async fn set_left(
289- self,
290- left_at: Option<Timestamp>,
291- db: &Database,
292- ) -> Result<ExamAttempt, AppError> {
293- let mut result = db
294- .query("UPDATE $id SET left_at = $left RETURN AFTER")
295- .bind(("id", self.id.record()))
296- .bind(("left", left_at))
297- .await?
298- .check()?;
299- result
300- .take::<Vec<ExamAttempt>>(0)?
301- .into_iter()
302- .next()
303- .ok_or(AppError::NotFound)
304- }
305-
306- /// One sitting by id — the exam room re-reads its own attempt this way,
307- /// so a retake started elsewhere can never be mistaken for it.
308- pub async fn read(id: &ExamAttemptId, db: &Database) -> Result<Option<ExamAttempt>, AppError> {
309- Ok(db.select(id.record()).await?)
310- }
311-
312- /// The student's current sitting — the highest `seq` for the pair. All
313- /// reads that used to mean "the attempt" mean this now.
314- pub async fn read_latest_for_user(
315- exam: &ExamId,
316- user: &UserId,
317- db: &Database,
318- ) -> Result<Option<ExamAttempt>, AppError> {
319- let mut result = db
320- .query(
321- "SELECT * FROM exam_attempt WHERE exam = $ex AND user = $usr
322- ORDER BY seq DESC LIMIT 1",
323- )
324- .bind(("ex", exam.record()))
325- .bind(("usr", user.record()))
326- .await?
327- .check()?;
328- Ok(result.take::<Vec<ExamAttempt>>(0)?.into_iter().next())
329- }
330-
331- /// Every sitting of `user` at `exam`, newest first.
332- pub async fn list_for_user(
333- exam: &ExamId,
334- user: &UserId,
335- db: &Database,
336- ) -> Result<Vec<ExamAttempt>, AppError> {
337- let mut result = db
338- .query(
339- "SELECT * FROM exam_attempt WHERE exam = $ex AND user = $usr
340- ORDER BY seq DESC",
341- )
342- .bind(("ex", exam.record()))
343- .bind(("usr", user.record()))
344- .await?
345- .check()?;
346- Ok(result.take::<Vec<ExamAttempt>>(0)?)
347- }
348-
349- /// Every sitting of `user` nobody has submitted yet, across all exams. Only
350- /// the *candidates* for "in progress": a deadline comes off the exam's live
351- /// schedule, so the caller still judges [`Self::status`] per exam rather
352- /// than re-spelling that rule in SurrealQL.
353- pub async fn list_unfinished_for_user(
354- user: &UserId,
355- db: &Database,
356- ) -> Result<Vec<ExamAttempt>, AppError> {
357- let mut result = db
358- .query("SELECT * FROM exam_attempt WHERE user = $usr AND finished_at = NONE")
359- .bind(("usr", user.record()))
360- .await?
361- .check()?;
362- Ok(result.take::<Vec<ExamAttempt>>(0)?)
363- }
364-
365- pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<ExamAttempt>, AppError> {
366- let mut result = db
367- .query("SELECT * FROM exam_attempt WHERE exam = $ex ORDER BY id DESC")
368- .bind(("ex", exam.record()))
369- .await?
370- .check()?;
371- Ok(result.take::<Vec<ExamAttempt>>(0)?)
372- }
373-
374- /// Send `statements` wrapped in a transaction that refuses to run them at
375- /// all once `exam` has an attempt — the freeze gate, made atomic with the
376- /// write it guards instead of merely preceding it. `freeze_exam` is bound
377- /// here; the caller binds the rest and reads its own results from
378- /// [`Self::FROZEN_SLOT`] onwards.
379- ///
380- /// The same transaction *writes* the exam row — bumping its mark counter
381- /// and putting it straight back — which is what ties every child written
382- /// through here to its exam. The freeze gate only *reads* `exam_attempt`,
383- /// and a read does not survive [`Exam::delete`](crate::domain::exam::Exam::delete)'s
384- /// window: a question or picture landing after that delete removed the exam
385- /// but before it committed reads a row that is still there, while the
386- /// cascade's `DELETE exam_question WHERE exam = $ex` ran on a snapshot
387- /// predating this insert — so both commit and the child outlives the exam,
388- /// with neither caller told anything. Writing a key the delete also writes
389- /// makes the two collide and the store refuses one side. It is the shape
390- /// [`crate::domain::exam_answer::ExamAnswer::save`] and
391- /// [`crate::domain::menu::bump_menu_and_write`] already use.
392- ///
393- /// An orphan here is not merely untidy: an `exam_question` that outlives
394- /// its exam keeps the reference it claimed on its subject (the cascade's
395- /// per-subject decrement counted the rows it could see), and
396- /// [`crate::domain::subject::Subject::delete`] is gated on that count
397- /// reading zero — a subject nobody can ever delete again.
398- ///
399- /// The bump is restored *by captured value*, `NONE` included, so the row is
400- /// byte-identical afterwards: the boot backfill still finds the rows it
401- /// keys on (`WHERE result_count = NONE`) and a teacher's PATCH, which pins
402- /// that counter, is not refused because somebody added a question. Writing
403- /// the same value back would not do — an `UPDATE` that leaves the document
404- /// unchanged is elided and never reaches the store's write set, so it
405- /// collides with nothing.
406- ///
407- /// This replaces a process-wide `EXAM_LOCK.write()` held across the check
408- /// and the write. That lock ordered the two requests but still read the
409- /// attempt table a round trip before it wrote; the gate checks inside the
410- /// writing statement, so a question edit can no longer sail past an attempt
411- /// that started in that gap.
412- ///
413- /// The send lives here rather than at the five call sites because a lost
414- /// round has to be re-sent, and only whoever owns the send can re-send: the
415- /// gate reads the very table its rival writes, so the two contend by design
416- /// and a raced edit used to answer 500. The refusal outranks the conflict —
417- /// `FROZEN_MARK` is a decision and stays the 409 the pre-flight check
418- /// answers with, and only exhausting the tries becomes a 500. See
419- /// [`transaction_with_retry`] for why the whole error map is scanned: an
420- /// aborted transaction errors *every* slot and all but one say a generic
421- /// "not executed".
422- ///
423- /// Returning only on an empty error map is what keeps [`Self::FROZEN_SLOT`]
424- /// (and any slot counted off `num_statements`) correct — `take_errors`
425- /// `swap_remove`s errored slots, so a fixed slot read is meaningless once
426- /// anything failed.
427- //
428- // corner-cut: the count and a concurrent `CREATE exam_attempt` are still not
429- // serialized against each other — SurrealDB does not conflict-check a
430- // cross-record count (the write skew `db::cap` exists for), so an
431- // attempt landing in the same instant as an edit can still interleave
432- // either way. The mutex this replaces closed that inside one process only,
433- // and there are two, so nothing is lost. Closing it properly means the
434- // cap.rs shape: an attempt counter on the exam row, incremented by the
435- // attempt create, and the write conditioned on `count ?? 0 = 0`.
436- pub(crate) async fn write_unfrozen(
437- exam: &ExamId,
438- statements: &str,
439- bindings: Vec<(String, surrealdb::types::Value)>,
440- db: &Database,
441- ) -> Result<surrealdb::IndexedResults, AppError> {
442- Self::write_unfrozen_with(exam, statements, bindings, Vec::new(), db).await
443- }
444-
445- /// [`Self::write_unfrozen`] for statements that carry gates of their own:
446- /// each `(marker, refusal)` names a `THROW` the caller's SQL aborts with and
447- /// the error it means. The markers are handed to [`transaction_with_retry`]
448- /// too, so an abort on one is a refusal rather than a round to re-send.
449- ///
450- /// The freeze still outranks every one of them: a caller folding a counter
451- /// claim in here is refused as frozen even when its own gate would also have
452- /// fired, which is the answer the pre-flight check has always given.
453- pub(crate) async fn write_unfrozen_with(
454- exam: &ExamId,
455- statements: &str,
456- bindings: Vec<(String, surrealdb::types::Value)>,
457- refusals: Vec<(&str, AppError)>,
458- db: &Database,
459- ) -> Result<surrealdb::IndexedResults, AppError> {
460- let sql = format!(
461- "BEGIN TRANSACTION;
462- IF array::len((SELECT VALUE id FROM exam_attempt \
463- WHERE exam = $freeze_exam LIMIT 1)) > 0 {{ THROW '{FROZEN_MARK}' }};
464- LET $was_results = \
465- (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $freeze_exam);
466- LET $touched = (UPDATE $freeze_exam SET {EXAM_RESULT_COUNT_FIELD} = \
467- ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id);
468- IF array::len($touched) = 0 {{ THROW '{GONE_MARK}' }};
469- UPDATE $freeze_exam SET {EXAM_RESULT_COUNT_FIELD} = $was_results;
470- {statements}
471- COMMIT TRANSACTION;"
472- );
473- let mut bound = vec![("freeze_exam".into(), exam.record().into_value())];
474- bound.extend(bindings);
475- let mut marks = vec![FROZEN_MARK, GONE_MARK];
476- marks.extend(refusals.iter().map(|(marker, _)| *marker));
477- let (result, mut errors) = transaction_with_retry(db, &sql, &bound, &marks).await?;
478- let thrown = |marker: &str| {
479- errors
480- .values()
481- .any(|error| error.to_string().contains(marker))
482- };
483- if thrown(FROZEN_MARK) {
484- return Err(frozen_error());
485- }
486- // The exam is gone: the same 404 every one of these writes' handlers
487- // answers a missing exam with, and it outranks the callers' own gates
488- // for the freeze's reason — there is nothing left to refuse *about*.
489- if thrown(GONE_MARK) {
490- return Err(AppError::NotFound);
491- }
492- for (marker, refusal) in refusals {
493- if thrown(marker) {
494- return Err(refusal);
495- }
496- }
497- match errors.drain().map(|(_, error)| error).next() {
498- Some(error) => Err(error.into()),
499- None => Ok(result),
500- }
501- }
502-
503- /// The first slot a [`Self::write_unfrozen`] caller's own statements land
504- /// in: `BEGIN`, the freeze `IF`, and the exam touch's two `LET`s, `IF` and
505- /// restoring `UPDATE` take one each.
506- pub(crate) const FROZEN_SLOT: usize = 6;
507-
508- /// Whether anyone has started this exam — the gate that freezes `mode`
509- /// edits once an attempt exists.
510- pub async fn any_for_exam(exam: &ExamId, db: &Database) -> Result<bool, AppError> {
511- let mut result = db
512- .query("SELECT VALUE id FROM exam_attempt WHERE exam = $ex LIMIT 1")
513- .bind(("ex", exam.record()))
514- .await?
515- .check()?;
516- Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
517- }
518-}
519-
520-#[cfg(test)]
521-mod tests {
522- use super::*;
523- use crate::database::init_mem;
524- use crate::domain::exam::{
525- ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,
526- };
527- use crate::domain::exam_answer::ExamAnswer;
528- use crate::domain::exam_question::{
529- ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec,
530- };
531-
532- /// The id of the question's second option — what these tests used to write
533- /// as the index `1`.
534- fn second_choice(question: &ExamQuestion) -> String {
535- question.get_choices().unwrap()[1]
536- .get_id()
537- .as_str()
538- .to_string()
539- }
540- use crate::domain::settings::Settings;
541-
542- /// An open exam with retakes allowed, plus one choice question — enough
543- /// rows to exercise the attempt lifecycle without the HTTP layer.
544- async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) {
545- let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
546- let course = crate::db::course::a_test_course(db).await;
547- let kinds = Settings::defaults().get_exam_kinds().to_vec();
548- let exam = Exam::create(
549- &creator,
550- &course,
551- ExamTitle::try_new("practice").unwrap(),
552- ExamDescription::try_new("").unwrap(),
553- ExamKind::try_new("quiz", &kinds).unwrap(),
554- ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None)
555- .unwrap(),
556- ExamAttemptLimit::try_new(max_attempts).unwrap(),
557- true,
558- false,
559- false,
560- db,
561- )
562- .await
563- .unwrap();
564- let spec = QuestionSpec::try_new(
565- QuestionKind::try_new("choice").unwrap(),
566- Some(vec![
567- ChoiceInput {
568- id: Some("a".into()),
569- text: "5".into(),
570- },
571- ChoiceInput {
572- id: Some("b".into()),
573- text: "6".into(),
574- },
575- ]),
576- Some("b".into()),
577- &[],
578- )
579- .unwrap();
580- // A real subject row, not a minted id: a question claims a reference on
581- // its subject and is refused if that subject does not exist.
582- let subject = crate::domain::subject::Subject::create(
583- &crate::db::course::a_test_course(db).await,
584- crate::domain::subject::SubjectName::try_new("topic").unwrap(),
585- crate::domain::subject::SubjectDescription::try_new("").unwrap(),
586- db,
587- )
588- .await
589- .unwrap();
590- let question = ExamQuestion::create(
591- exam.get_id(),
592- subject.get_id().clone(),
593- crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(),
594- QuestionPoints::try_new(5).unwrap(),
595- spec,
596- db,
597- )
598- .await
599- .unwrap();
600- (exam, question)
601- }
602-
603- /// A real user row: the sitting counter lives on it, and the claim that
604- /// rides the attempt's create has nothing to write to without one.
605- async fn student(db: &Database) -> UserId {
606- let hash = crate::domain::user::Password::try_new("secret1")
607- .unwrap()
608- .hash_async()
609- .await
610- .unwrap();
611- crate::domain::user::User::create(
612- crate::domain::user::Username::try_new("ogrenci").unwrap(),
613- hash,
614- db,
615- )
616- .await
617- .unwrap()
618- .get_id()
619- .clone()
620- }
621-
622- /// The student's lifetime sitting count, absent reading as zero.
623- async fn sat_total(user: &UserId, db: &Database) -> i64 {
624- let mut result = db
625- .query(format!(
626- "SELECT VALUE ({EXAM_SAT_TOTAL_FIELD} ?? 0) FROM $usr"
627- ))
628- .bind(("usr", user.record()))
629- .await
630- .unwrap()
631- .check()
632- .unwrap();
633- result
634- .take::<Vec<i64>>(0)
635- .unwrap()
636- .into_iter()
637- .next()
638- .unwrap()
639- }
640-
641- /// The badge counter counts *exams sat*, one per first sitting — so a start
642- /// moves it by exactly one and a resume, which creates nothing, leaves it
643- /// alone. Anything else and a seeded account and a fresh one would mean
644- /// different things by the same number.
645- #[tokio::test]
646- async fn starting_counts_one_sitting_and_resuming_counts_none() {
647- let db = init_mem().await.unwrap();
648- let (exam, _question) = open_exam_with_question(&db, 2).await;
649- let user = student(&db).await;
650- assert_eq!(sat_total(&user, &db).await, 0, "a fresh row reads as zero");
651-
652- let (_, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
653- assert!(created);
654- assert_eq!(sat_total(&user, &db).await, 1);
655-
656- // Still in progress: this start returns the running sitting untouched.
657- let (_, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
658- assert!(!created);
659- assert_eq!(
660- sat_total(&user, &db).await,
661- 1,
662- "a resume writes no row, so it counts nothing"
663- );
664- }
665-
666- /// A retake is the same exam again: the row lands at the next `seq` and the
667- /// counter stays where it is. Counting it is the farm — an open exam with
668- /// unlimited attempts would mint `exam_sat_25` off one exam and no teacher.
669- #[tokio::test]
670- async fn a_retake_writes_its_row_and_counts_nothing() {
671- let db = init_mem().await.unwrap();
672- let (exam, _question) = open_exam_with_question(&db, 3).await;
673- let user = student(&db).await;
674-
675- let (first, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
676- first.finish(&db).await.unwrap();
677- let (second, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
678- assert!(created);
679- assert_eq!(second.get_seq(), 2);
680- assert_eq!(sat_total(&user, &db).await, 1);
681- }
682-
683- /// The lost half of a double-start race. `start` can only reach that branch
684- /// by interleaving with a rival, so the claim is put to the counter
685- /// directly — the same call `start` makes, aimed at a row that already
686- /// exists. The duplicate aborts the transaction and takes its increment
687- /// with it: a sitting is never counted twice.
688- #[tokio::test]
689- async fn a_lost_start_race_never_counts_the_sitting_twice() {
690- let db = init_mem().await.unwrap();
691- let (exam, _question) = open_exam_with_question(&db, 1).await;
692- let user = student(&db).await;
693-
694- let (winner, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
695- assert_eq!(sat_total(&user, &db).await, 1);
696-
697- let claimed = cap::claim_and_create(
698- &user.record(),
699- EXAM_SAT_TOTAL_FIELD,
700- cap::UNLIMITED,
701- &winner.id.record(),
702- &winner,
703- &db,
704- )
705- .await
706- .unwrap();
707- assert!(matches!(claimed, cap::Claimed::Duplicate));
708- assert_eq!(
709- sat_total(&user, &db).await,
710- 1,
711- "the loser's increment rolled back with its duplicate create"
712- );
713- }
714-
715- #[tokio::test]
716- async fn a_retake_preserves_the_prior_sittings_sheet() {
717- let db = init_mem().await.unwrap();
718- let (exam, question) = open_exam_with_question(&db, 2).await;
719- let user = student(&db).await;
720-
721- let (first, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
722- assert!(created);
723- assert_eq!(first.get_seq(), 1);
724- ExamAnswer::save(
725- &question,
726- &user,
727- 1,
728- Some(second_choice(&question)),
729- None,
730- &db,
731- )
732- .await
733- .unwrap();
734- first.finish(&db).await.unwrap();
735-
736- // The retake lands as sitting #2 without touching sitting #1's answers.
737- let (second, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
738- assert!(created);
739- assert_eq!(second.get_seq(), 2);
740-
741- // Sitting #1's answer is still there, read at its own seq.
742- let prior = ExamAnswer::read(question.get_id(), &user, 1, &db)
743- .await
744- .unwrap();
745- assert!(prior.is_some(), "the retake must preserve seq 1's answer");
746- // The new sitting starts blank at its own seq.
747- let fresh = ExamAnswer::list_for_exam_user(exam.get_id(), &user, 2, &db)
748- .await
749- .unwrap();
750- assert!(fresh.is_empty(), "seq 2 starts blank");
751- }
752-
753- #[tokio::test]
754- async fn a_lost_retake_race_cannot_touch_the_winners_sheet() {
755- let db = init_mem().await.unwrap();
756- let (exam, question) = open_exam_with_question(&db, 3).await;
757- let user = student(&db).await;
758-
759- // Sitting #1 ends; the winner starts sitting #2 and saves an answer.
760- let (first, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
761- first.finish(&db).await.unwrap();
762- let (winner, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
763- assert!(created);
764- assert_eq!(winner.get_seq(), 2);
765- ExamAnswer::save(
766- &question,
767- &user,
768- 2,
769- Some(second_choice(&question)),
770- None,
771- &db,
772- )
773- .await
774- .unwrap();
775-
776- // A stale double-start races on the same seq and loses to the
777- // composite id: the duplicate create is rejected, and with no wipe in
778- // the path the winner's fresh answer is untouched either way.
779- let loser = ExamAttempt {
780- id: ExamAttemptId::composite(exam.get_id(), &user, 2),
781- exam: exam.get_id().clone(),
782- user: user.clone(),
783- seq: 2,
784- started_at: Timestamp::now(),
785- finished_at: None,
786- left_at: None,
787- };
788- let lost: Result<Option<ExamAttempt>, surrealdb::Error> =
789- db.create(loser.id.record()).content(loser).await;
790- assert!(lost.is_err(), "the duplicate-seq create must be rejected");
791- let answers = ExamAnswer::list_for_exam_user(exam.get_id(), &user, 2, &db)
792- .await
793- .unwrap();
794- assert_eq!(
795- answers.len(),
796- 1,
797- "the lost race must not disturb the winner's saved answer"
798- );
799-
800- // The public path shrugs the race off: a re-start resumes the winner.
801- let (resumed, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
802- assert!(!created);
803- assert_eq!(resumed.get_seq(), 2);
804- }
805-
806- #[tokio::test]
807- async fn submitting_never_reverts_a_walk_out_that_raced_it() {
808- let db = init_mem().await.unwrap();
809- let (exam, _question) = open_exam_with_question(&db, 1).await;
810- let user = student(&db).await;
811-
812- let (attempt, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
813-
814- // The REST submit path reads the attempt, then checks the deadline and
815- // the already-finished guard — several awaits before it writes.
816- let stale = ExamAttempt::read(attempt.get_id(), &db)
817- .await
818- .unwrap()
819- .expect("attempt exists");
820- assert!(stale.get_left_at().is_none());
821-
822- // In that gap the exam room's teardown stamps the walk-out (or a join
823- // clears it) — a field-scoped write to the same row.
824- ExamAttempt::read(attempt.get_id(), &db)
825- .await
826- .unwrap()
827- .expect("attempt exists")
828- .set_left(Some(Timestamp::now()), &db)
829- .await
830- .unwrap();
831-
832- // The submit now writes from its stale snapshot. It owns `finished_at`
833- // and nothing else: carrying the snapshot's blank `left_at` back over
834- // the fresh stamp erases the recorded walk-out.
835- let finished = stale.finish(&db).await.unwrap();
836- assert!(finished.get_finished_at().is_some());
837-
838- let after = ExamAttempt::read(attempt.get_id(), &db)
839- .await
840- .unwrap()
841- .expect("attempt still exists");
842- assert!(
843- after.get_left_at().is_some(),
844- "submitting must not revert a walk-out stamp that raced it"
845- );
846- assert!(after.get_finished_at().is_some(), "the submission stands");
847- }
848-
849- #[tokio::test]
850- async fn stamping_left_never_reverts_a_submission() {
851- let db = init_mem().await.unwrap();
852- let (exam, _question) = open_exam_with_question(&db, 1).await;
853- let user = student(&db).await;
854-
855- // The student is sitting the exam.
856- let (attempt, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
857- assert_eq!(attempt.get_seq(), 1);
858-
859- // The exam-room teardown reads the attempt while it is still in
860- // progress (`stamp_left`'s read) — a snapshot with `finished_at` unset.
861- let stale = ExamAttempt::read(attempt.get_id(), &db)
862- .await
863- .unwrap()
864- .expect("attempt exists");
865- assert!(stale.get_finished_at().is_none());
866-
867- // Before the teardown writes, the student submits (a REST finish, or a
868- // finish over another socket) — the submission lands.
869- let finished = ExamAttempt::read(attempt.get_id(), &db)
870- .await
871- .unwrap()
872- .expect("attempt exists")
873- .finish(&db)
874- .await
875- .unwrap();
876- assert!(finished.get_finished_at().is_some());
877-
878- // Now the last socket's teardown stamps `left_at` from its stale
879- // snapshot. Stamping the walk-out must touch only `left_at` — it must
880- // not carry the snapshot's blank `finished_at` back over the fresh
881- // submission, or the student's submitted exam silently reopens (and,
882- // with `allow_rejoin` off, locks them out of a room they left after
883- // finishing).
884- stale.set_left(Some(Timestamp::now()), &db).await.unwrap();
885-
886- let after = ExamAttempt::read(attempt.get_id(), &db)
887- .await
888- .unwrap()
889- .expect("attempt still exists");
890- assert!(
891- after.get_finished_at().is_some(),
892- "stamping left_at must not revert a submission that raced it"
893- );
894- assert!(
895- after.get_left_at().is_some(),
896- "the walk-out is still recorded"
897- );
898- assert_eq!(
899- after.status(&exam, Timestamp::now()),
900- AttemptStatus::Submitted,
901- "the attempt stays submitted"
902- );
903- }
904 }142 }
src/domain/exam_question.rsmodified+15 -11
@@ -8,12 +8,11 @@ use crate::constant::{
8 MIN_QUESTION_CHOICES, SUBJECT_QUESTION_COUNT_FIELD,8 MIN_QUESTION_CHOICES, SUBJECT_QUESTION_COUNT_FIELD,
9 };9 };
10 use crate::database::Database;10 use crate::database::Database;
11-use crate::domain::bank_question::BankQuestionId;
12 use crate::db::cap;11 use crate::db::cap;
12+use crate::db::page::PagedList;
13+use crate::domain::bank_question::BankQuestionId;
13 use crate::domain::exam::ExamId;14 use crate::domain::exam::ExamId;
14-use crate::domain::exam_attempt::ExamAttempt;
15 use crate::domain::monotonic_id::next_ulid;15 use crate::domain::monotonic_id::next_ulid;
16-use crate::db::page::PagedList;
17 use crate::domain::subject::SubjectId;16 use crate::domain::subject::SubjectId;
18 use crate::error::{AppError, ValidationError};17 use crate::error::{AppError, ValidationError};
19 use crate::validate::{validate_question_kind, validate_question_points, validate_required};18 use crate::validate::{validate_question_kind, validate_question_points, validate_required};
@@ -444,7 +443,8 @@ impl ExamQuestion {
444 let id = question.id.record();443 let id = question.id.record();
445 // One counter write in flight at a time, like every other counter write.444 // One counter write in flight at a time, like every other counter write.
446 let _guard = cap::counter_lock().await;445 let _guard = cap::counter_lock().await;
447- let mut result = ExamAttempt::write_unfrozen_with(446+ let mut result = crate::db::exam_attempt::write_unfrozen_with(
447+ db,
448 exam,448 exam,
449 &format!(449 &format!(
450 "LET $seat = (UPDATE $subject SET {SUBJECT_QUESTION_COUNT_FIELD} = \450 "LET $seat = (UPDATE $subject SET {SUBJECT_QUESTION_COUNT_FIELD} = \
@@ -458,7 +458,6 @@ impl ExamQuestion {
458 ("question".into(), question.into_value()),458 ("question".into(), question.into_value()),
459 ],459 ],
460 vec![(SUBJECT_MARK, dead_subject())],460 vec![(SUBJECT_MARK, dead_subject())],
461- db,
462 )461 )
463 .await?;462 .await?;
464 // Counted off the statements that actually ran rather than a fixed463 // Counted off the statements that actually ran rather than a fixed
@@ -640,9 +639,14 @@ impl ExamQuestion {
640 Some(_) => Some(cap::counter_lock().await),639 Some(_) => Some(cap::counter_lock().await),
641 None => None,640 None => None,
642 };641 };
643- let mut result =642+ let mut result = crate::db::exam_attempt::write_unfrozen_with(
644- ExamAttempt::write_unfrozen_with(&self.exam, &statements, bindings, refusals, db)643+ db,
645- .await?;644+ &self.exam,
645+ &statements,
646+ bindings,
647+ refusals,
648+ )
649+ .await?;
646 // Read off the trailing `RETURN` rather than a fixed slot: a re-tag650 // Read off the trailing `RETURN` rather than a fixed slot: a re-tag
647 // arms three more statements than a plain PATCH does (and an `IF`651 // arms three more statements than a plain PATCH does (and an `IF`
648 // block is one slot whether or not it is taken).652 // block is one slot whether or not it is taken).
@@ -694,7 +698,8 @@ impl ExamQuestion {
694 /// delete — and the cascade now shares that transaction too, so a failure698 /// delete — and the cascade now shares that transaction too, so a failure
695 /// mid-way can no longer strand answers whose question survived.699 /// mid-way can no longer strand answers whose question survived.
696 pub async fn delete(self, db: &Database) -> Result<ExamQuestion, AppError> {700 pub async fn delete(self, db: &Database) -> Result<ExamQuestion, AppError> {
697- let mut result = ExamAttempt::write_unfrozen(701+ let mut result = crate::db::exam_attempt::write_unfrozen(
702+ db,
698 &self.exam,703 &self.exam,
699 &format!(704 &format!(
700 "DELETE exam_answer WHERE question = $q;705 "DELETE exam_answer WHERE question = $q;
@@ -707,7 +712,6 @@ impl ExamQuestion {
707 RETURN $gone;"712 RETURN $gone;"
708 ),713 ),
709 vec![("q".into(), self.id.record().into_value())],714 vec![("q".into(), self.id.record().into_value())],
710- db,
711 )715 )
712 .await?;716 .await?;
713 // The subject's reference is given back inside this same transaction,717 // The subject's reference is given back inside this same transaction,
@@ -1197,7 +1201,7 @@ mod tests {
1197 )1201 )
1198 .await1202 .await
1199 .unwrap();1203 .unwrap();
1200- ExamAttempt::start(&exam, student.get_id(), &db)1204+ crate::service::exam_attempt::start(&db, &exam, student.get_id())
1201 .await1205 .await
1202 .unwrap();1206 .unwrap();
1203 1207
src/domain/question_image.rsmodified+5 -6
@@ -16,7 +16,6 @@ use crate::constant::QUESTION_IMAGE_TABLE;
16 use crate::database::Database;16 use crate::database::Database;
17 use crate::domain::course::CourseId;17 use crate::domain::course::CourseId;
18 use crate::domain::exam::ExamId;18 use crate::domain::exam::ExamId;
19-use crate::domain::exam_attempt::ExamAttempt;
20 use crate::domain::exam_question::{ChoiceId, ExamQuestionId};19 use crate::domain::exam_question::{ChoiceId, ExamQuestionId};
21 use crate::domain::key;20 use crate::domain::key;
22 use crate::domain::note_file::FileContentType;21 use crate::domain::note_file::FileContentType;
@@ -127,7 +126,8 @@ impl QuestionImage {
127 pub async fn upsert(self, db: &Database) -> Result<(QuestionImage, Option<String>), AppError> {126 pub async fn upsert(self, db: &Database) -> Result<(QuestionImage, Option<String>), AppError> {
128 // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic127 // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic
129 let (exam, id) = (self.exam.clone(), self.id.record());128 let (exam, id) = (self.exam.clone(), self.id.record());
130- let mut result = ExamAttempt::write_unfrozen(129+ let mut result = crate::db::exam_attempt::write_unfrozen(
130+ db,
131 &exam,131 &exam,
132 "LET $replaced = (SELECT VALUE file FROM $id);132 "LET $replaced = (SELECT VALUE file FROM $id);
133 LET $stored = (UPSERT $id CONTENT $image);133 LET $stored = (UPSERT $id CONTENT $image);
@@ -136,7 +136,6 @@ impl QuestionImage {
136 ("id".into(), id.into_value()),136 ("id".into(), id.into_value()),
137 ("image".into(), self.into_value()),137 ("image".into(), self.into_value()),
138 ],138 ],
139- db,
140 )139 )
141 .await?;140 .await?;
142 // The trailing `RETURN` is the last statement before `COMMIT`, so its141 // The trailing `RETURN` is the last statement before `COMMIT`, so its
@@ -235,15 +234,15 @@ impl QuestionImage {
235 /// Refused once the exam has an attempt, in the same transaction — same234 /// Refused once the exam has an attempt, in the same transaction — same
236 /// gate, same reason as [`Self::upsert`].235 /// gate, same reason as [`Self::upsert`].
237 pub async fn delete(self, db: &Database) -> Result<QuestionImage, AppError> {236 pub async fn delete(self, db: &Database) -> Result<QuestionImage, AppError> {
238- let mut result = ExamAttempt::write_unfrozen(237+ let mut result = crate::db::exam_attempt::write_unfrozen(
238+ db,
239 &self.exam,239 &self.exam,
240 "DELETE $id RETURN BEFORE;",240 "DELETE $id RETURN BEFORE;",
241 vec![("id".into(), self.id.record().into_value())],241 vec![("id".into(), self.id.record().into_value())],
242- db,
243 )242 )
244 .await?;243 .await?;
245 result244 result
246- .take::<Vec<QuestionImage>>(ExamAttempt::FROZEN_SLOT)?245+ .take::<Vec<QuestionImage>>(crate::db::exam_attempt::FROZEN_SLOT)?
247 .into_iter()246 .into_iter()
248 .next()247 .next()
249 .ok_or(AppError::NotFound)248 .ok_or(AppError::NotFound)
src/service/exam_attempt.rsadded+765 -0
@@ -0,0 +1,765 @@
1+//! The exam-sitting workflows: starting, resuming, and finishing sittings,
2+//! saving answers into them, and the gates (sittable, student, enrollment,
3+//! rejoin, archived term) every sitting path shares. The queries live in
4+//! [`crate::db::exam_attempt`]; the HTTP shaping stays in the web layer.
5+
6+use crate::constant::EXAM_SAT_TOTAL_FIELD;
7+use crate::database::Database;
8+use crate::db::cap;
9+use crate::domain::badge;
10+use crate::domain::course::Course;
11+use crate::domain::enrollment::Enrollment;
12+use crate::domain::exam::{Exam, ExamId};
13+use crate::domain::exam_answer::ExamAnswer;
14+use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId};
15+use crate::domain::exam_question::{ExamQuestion, ExamQuestionId};
16+use crate::domain::role::Role;
17+use crate::domain::timestamp::Timestamp;
18+use crate::domain::user::{User, UserId};
19+use crate::error::AppError;
20+
21+/// Serializes the exam subsystem's cross-record check-then-writes, which
22+/// `BEGIN…COMMIT` cannot (write skew) — the reasoning in [`crate::db::cap`].
23+/// It orders requests, but only around what it wraps — every invariant that
24+/// could be moved into the database itself has been, so a gap between a read
25+/// and its write is decided by the store. What is left here needs a
26+/// cross-record read and a write held together, which no single statement
27+/// expresses:
28+///
29+/// Read side — the answer saves (REST and the exam room), from the
30+/// writable-attempt gate through the upsert; the grade write (draft gate
31+/// through the result upsert); and the exam PATCH, whose mode/re-draft gates
32+/// count attempts and results. These stay concurrent with each other.
33+///
34+/// Write side — attempt starts alone (the max-attempts count and the retake's
35+/// answer wipe). So a save can never land on a sheet a retake just wiped, and a
36+/// mark can never land on an exam mid-flight into hiding.
37+///
38+/// Two rules have left this list. The question freeze gate rides inside each
39+/// question/image write's own transaction
40+/// ([`crate::db::exam_attempt::write_unfrozen`]), and the exam PATCH
41+/// no longer needs the writer lease because its save is a compare-and-set. The
42+/// subject delete's cascade — the only writer outside attempt starts, paired
43+/// with the question writes' subject check — is now a conditional statement on
44+/// the subject's own reference counter
45+/// ([`crate::domain::subject::Subject::delete`]), which every question create,
46+/// re-tag and delete moves.
47+// corner-cut: global RwLock, shard per-exam if save latency ever matters.
48+pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
49+
50+/// Rejects sitting an exam that can't be sat. A draft is a `404`, not a
51+/// `409` — sitting is a student act, drafts are invisible to students, and a
52+/// state-specific error would leak the existence this feature hides. A
53+/// modeless (offline-graded) exam is a `409`: visible, just nothing to sit.
54+/// Enrollment and window checks for the caller are the caller's own state —
55+/// also `Conflict`, not validation.
56+pub fn ensure_sittable(exam: &Exam) -> Result<(), AppError> {
57+ if exam.is_draft() {
58+ return Err(AppError::NotFound);
59+ }
60+ if exam.get_mode().is_none() {
61+ return Err(AppError::Conflict(
62+ "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)",
63+ ));
64+ }
65+ Ok(())
66+}
67+
68+/// A 403 unless `user` is a student. Sitting an exam is a student action —
69+/// teachers and above run exams, they never take them — so the sit paths
70+/// (start, room, save) enforce it on the *current* role. Checking the live
71+/// role, not just enrollment, closes the gap a mid-exam promotion would open
72+/// and neutralizes any stale non-student enrollment. Reading one's own attempt
73+/// and finishing stay ungated: a non-student has no attempt to read, and
74+/// finishing only submits work already saved.
75+pub fn ensure_student(user: &User) -> Result<(), AppError> {
76+ if user.get_role() != Role::Student {
77+ return Err(AppError::Forbidden("only students can sit exams"));
78+ }
79+ Ok(())
80+}
81+
82+/// The answer path's live edition of [`ensure_student`]: re-read the row and
83+/// judge the *current* role, exactly like the enrollment wall beside it. Both
84+/// save paths run through here (REST per request, the exam room per message),
85+/// so a promotion out of `student` mid-exam closes the sheet on the very next
86+/// save — the room's door check is not the last word for a socket that
87+/// outlives the role.
88+pub async fn ensure_student_now(user: &UserId, db: &Database) -> Result<(), AppError> {
89+ let user = crate::domain::user::User::read(user, db)
90+ .await?
91+ .ok_or(AppError::Unauthorized)?;
92+ ensure_student(&user)
93+}
94+
95+/// A 403 unless `user` is enrolled in the exam's course — the same wall the
96+/// exam room checks at its door, re-applied to the sitting's content paths so
97+/// an unenrollment mid-exam cuts them too. Finishing stays exempt: like the
98+/// rejoin lock, submitting what's already saved writes nothing new.
99+pub async fn ensure_enrolled(exam: &Exam, user: &UserId, db: &Database) -> Result<(), AppError> {
100+ if Enrollment::read_for_user(exam.get_course(), user, db)
101+ .await?
102+ .is_none()
103+ {
104+ return Err(AppError::Forbidden(
105+ "you are not enrolled in this exam's course",
106+ ));
107+ }
108+ Ok(())
109+}
110+
111+/// A 409 when the student has walked out of the exam room and the exam's
112+/// rejoin door is closed: no more answering (from anywhere) until the teacher
113+/// flips `allow_rejoin` back on. Finishing is deliberately exempt — see
114+/// the finish workflow.
115+pub fn check_rejoin(exam: &Exam, attempt: &ExamAttempt) -> Result<(), AppError> {
116+ if attempt.get_left_at().is_some() && !exam.get_allow_rejoin() {
117+ return Err(AppError::Conflict(
118+ "you left the exam and rejoin is closed — ask your teacher to reopen it",
119+ ));
120+ }
121+ Ok(())
122+}
123+
124+/// The caller's latest attempt provided it is still writable, or the error
125+/// that says why not: no attempt yet (404 — start it first), already
126+/// submitted (409), deadline passed (409). One gate shared by REST saves and
127+/// the WebSocket room.
128+pub async fn writable_attempt(
129+ exam: &Exam,
130+ user: &UserId,
131+ db: &Database,
132+) -> Result<ExamAttempt, AppError> {
133+ let attempt = crate::db::exam_attempt::read_latest_for_user(db, exam.get_id(), user)
134+ .await?
135+ .ok_or(AppError::NotFound)?;
136+ match attempt.status(exam, Timestamp::now()) {
137+ AttemptStatus::Submitted => Err(AppError::Conflict("the attempt is already submitted")),
138+ AttemptStatus::Expired => Err(AppError::Conflict("time is up — the attempt has expired")),
139+ AttemptStatus::InProgress => Ok(attempt),
140+ }
141+}
142+
143+/// The course an exam belongs to. A dangling reference means the course-delete
144+/// cascade was violated — surface it loudly as a 500, not a user-facing 404.
145+pub async fn course_of(exam: &Exam, db: &Database) -> Result<Course, AppError> {
146+ crate::domain::course::Course::read(exam.get_course(), db)
147+ .await?
148+ .ok_or_else(|| AppError::Internal("exam references a missing course".into()))
149+}
150+
151+/// The question, provided it belongs to `exam` — a qid under someone else's
152+/// exam is a plain 404, not a leak.
153+pub async fn question_of_exam(
154+ exam: &ExamId,
155+ qid: &str,
156+ db: &Database,
157+) -> Result<ExamQuestion, AppError> {
158+ let question = ExamQuestion::read(&ExamQuestionId::from_key(qid), db)
159+ .await?
160+ .ok_or(AppError::NotFound)?;
161+ if question.get_exam() != exam {
162+ return Err(AppError::NotFound);
163+ }
164+ Ok(question)
165+}
166+
167+/// Start, resume, or retake `user`'s attempt at `exam`. Returns the attempt
168+/// plus whether it was newly created.
169+///
170+/// - A still-running latest attempt is returned untouched, so a
171+/// reconnecting client gets its original clock back instead of a reset —
172+/// re-"starting" can never buy more time.
173+/// - A terminal latest attempt (submitted or expired) starts sitting
174+/// `seq + 1` if the exam's `max_attempts` allows another, and is a
175+/// conflict otherwise. A retake preserves every prior sitting: the new
176+/// row is created at the new `seq` and the student's earlier answers,
177+/// drawings, and marks stay put at their own seq — the fresh sitting
178+/// simply writes into an empty higher seq.
179+///
180+/// The composite id makes each create atomic; a concurrent double-start
181+/// races on the same seq, loses to the unique id, and reads the winner's
182+/// row.
183+///
184+/// A created row rides [`cap::create_counting`] so the student's
185+/// `exam_sat_total` moves in the same transaction — but only for `seq == 1`,
186+/// because that counter is *exams sat*, not sittings. A retake is the same
187+/// exam again, and counting it made a badge a student could mint alone: an
188+/// open exam with unlimited attempts is a start/finish loop nobody else has
189+/// to touch. `seq == 1` is the whole condition and needs no extra read —
190+/// the first sitting's id is one deterministic key, so of every writer
191+/// aiming at it exactly one `CREATE` commits and the losers' increments
192+/// abort with their duplicates, while a retake computes its seq from a row
193+/// that already exists. A `SELECT` inside the transaction would be strictly
194+/// worse: SurrealDB 3.2.3 conflict-checks write sets, not read sets.
195+pub async fn start(
196+ db: &Database,
197+ exam: &Exam,
198+ user: &UserId,
199+) -> Result<(ExamAttempt, bool), AppError> {
200+ let attempts = crate::db::exam_attempt::list_for_user(db, exam.get_id(), user).await?;
201+ let next_seq = match attempts.first() {
202+ None => 1,
203+ Some(latest) if latest.status(exam, Timestamp::now()) == AttemptStatus::InProgress => {
204+ return Ok((latest.clone(), false));
205+ }
206+ Some(latest) => {
207+ if !exam.get_max_attempts().allows_another(attempts.len()) {
208+ return Err(AppError::Conflict(
209+ "no attempts remaining — this exam's attempt limit is used up",
210+ ));
211+ }
212+ latest.seq + 1
213+ }
214+ };
215+ let attempt = ExamAttempt {
216+ id: ExamAttemptId::composite(exam.get_id(), user, next_seq),
217+ exam: exam.get_id().clone(),
218+ user: user.clone(),
219+ seq: next_seq,
220+ started_at: Timestamp::now(),
221+ finished_at: None,
222+ left_at: None,
223+ };
224+ let id = attempt.id.record();
225+ let first = next_seq == 1;
226+ match cap::create_counting(
227+ &user.record(),
228+ EXAM_SAT_TOTAL_FIELD,
229+ first,
230+ &id,
231+ &attempt,
232+ db,
233+ )
234+ .await?
235+ {
236+ cap::Claimed::Made(created) => {
237+ // Only a moved counter can have crossed a threshold.
238+ if first && let Err(err) = badge::sync(user, db).await {
239+ tracing::warn!("failed to sync badges for {}: {err}", user.key());
240+ }
241+ Ok((created, true))
242+ }
243+ // Only a still-running row proves the loss was a double-start
244+ // collision (the winner's fresh sitting); a terminal or missing
245+ // latest means the create genuinely failed — surface that instead
246+ // of passing a finished sitting off as a resume. The duplicate
247+ // aborted the transaction, so the loser's increment went with it.
248+ cap::Claimed::Duplicate => {
249+ match crate::db::exam_attempt::read_latest_for_user(db, exam.get_id(), user).await? {
250+ Some(existing)
251+ if existing.status(exam, Timestamp::now()) == AttemptStatus::InProgress =>
252+ {
253+ Ok((existing, false))
254+ }
255+ _ => Err(AppError::Internal("failed to start exam attempt".into())),
256+ }
257+ }
258+ // Nothing caps sittings, so the conditional write can only miss by
259+ // finding no user row — not a state a live session can reach, and
260+ // passing it off as a resume would hand out a sitting the counter
261+ // never learned about.
262+ cap::Claimed::Full => Err(AppError::Internal(
263+ "cannot start an exam attempt: the student's account row is missing".into(),
264+ )),
265+ }
266+}
267+
268+/// Start, resume, or retake the caller's attempt at `exam_id`. Requires the
269+/// student role (staff run exams, they don't sit them), enrollment in the
270+/// exam's course, a sittable exam (`sync`/`async`/`open` mode), and — when a
271+/// window exists — the window to be open. Returns the exam the gates judged
272+/// (the response describes that row) plus the attempt and whether it was
273+/// newly created.
274+///
275+/// Writer lease of [`EXAM_LOCK`] from the exam read through the start: the
276+/// sittable/window gates must be judged against the same exam row the
277+/// attempt lands under (the mirror of `update_exam`'s re-derive — without
278+/// it, a mode change or re-draft at legally-zero attempts could slip
279+/// between this gate and the insert, leaving an attempt on an unsittable
280+/// exam). The lease
281+/// also keeps the max-attempts count and the retake's wipe-and-create
282+/// from interleaving with an in-flight answer save (a reader). The caller
283+/// drops nothing: the lease lives and dies inside this call, before the
284+/// response reads — they only describe the row.
285+///
286+/// A still-running attempt comes back as-is (the handler answers `200`
287+/// instead of `201`), so a reconnecting client gets its original clock
288+/// back — re-starting never resets the time. Once the latest attempt is
289+/// submitted or expired, re-posting starts the next sitting while the
290+/// exam's `max_attempts` (0 = unlimited) allows it.
291+///
292+/// A retake no longer wipes the prior sitting — each attempt's answers,
293+/// drawings, and marks stay put at their own seq (per-attempt history), so
294+/// there are no orphaned blobs to GC here. The exam-delete cascade still
295+/// cleans every sitting's blobs.
296+pub async fn start_attempt(
297+ db: &Database,
298+ exam_id: &ExamId,
299+ user: &User,
300+) -> Result<(Exam, ExamAttempt, bool), AppError> {
301+ let _guard = EXAM_LOCK.write().await;
302+ let exam = crate::domain::exam::Exam::read(exam_id, db)
303+ .await?
304+ .ok_or(AppError::NotFound)?;
305+ ensure_sittable(&exam)?;
306+ ensure_student(user)?;
307+ ensure_enrolled(&exam, user.get_id(), db).await?;
308+ course_of(&exam, db).await?.require_open(db).await?;
309+ let now = Timestamp::now();
310+ if let Some(starts_at) = exam.get_starts_at()
311+ && now < starts_at
312+ {
313+ return Err(AppError::Conflict("the exam has not started yet"));
314+ }
315+ if let Some(ends_at) = exam.get_ends_at()
316+ && now >= ends_at
317+ {
318+ return Err(AppError::Conflict("the exam has already ended"));
319+ }
320+ let (attempt, created) = start(db, &exam, user.get_id()).await?;
321+ Ok((exam, attempt, created))
322+}
323+
324+/// Submit `user`'s latest attempt at `exam`. Allowed while the deadline
325+/// hasn't passed; after it, the attempt is already `expired` (a valid
326+/// terminal state — the student used their full time) and submitting is a
327+/// `409`.
328+///
329+/// Deliberately no rejoin check: a student locked out of the room may
330+/// still submit what they saved — finishing answers nothing new.
331+pub async fn finish_attempt(
332+ db: &Database,
333+ exam: &Exam,
334+ user: &UserId,
335+) -> Result<ExamAttempt, AppError> {
336+ let attempt = crate::db::exam_attempt::read_latest_for_user(db, exam.get_id(), user)
337+ .await?
338+ .ok_or(AppError::NotFound)?;
339+ if attempt.get_finished_at().is_some() {
340+ return Err(AppError::Conflict("the attempt is already submitted"));
341+ }
342+ let now = Timestamp::now();
343+ if let Some(deadline) = attempt.deadline(exam)
344+ && now >= deadline
345+ {
346+ return Err(AppError::Conflict("time is up — the attempt has expired"));
347+ }
348+ course_of(exam, db).await?.require_open(db).await?;
349+ crate::db::exam_attempt::finish(db, attempt).await
350+}
351+
352+/// Save one answer inside the caller's in-progress attempt — the whole write
353+/// path (student gate, attempt gate, rejoin gate via [`save_answer_in`],
354+/// question lookup, kind check, upsert). The REST handler saves into the
355+/// latest sitting via this; the WebSocket room
356+/// resolves its own sitting first and shares [`save_answer_in`], so the two
357+/// can never drift.
358+pub async fn save_answer_checked(
359+ db: &Database,
360+ exam: &Exam,
361+ user: &User,
362+ question_id: &str,
363+ selected: Option<String>,
364+ text: Option<String>,
365+) -> Result<ExamAnswer, AppError> {
366+ ensure_student(user)?;
367+ // Reader lease of [`EXAM_LOCK`]: the writable gate and the upsert are
368+ // one unit, or a retake's wipe-and-create (a writer) slips in between
369+ // and this stale save lands on the fresh blank sheet.
370+ //
371+ // The lease covers the gate *and* the upsert here, so a retake cannot
372+ // interleave with this path at all. The accepted late-save race lives in
373+ // the exam-room socket instead, which writes into the sitting it joined
374+ // with — a value chosen before any lease is taken. See
375+ // [`crate::web::exam_ws`].
376+ let _guard = EXAM_LOCK.read().await;
377+ let attempt = writable_attempt(exam, user.get_id(), db).await?;
378+ save_answer_in(db, exam, &attempt, question_id, selected, text).await
379+}
380+
381+/// The tail of the answer write path, given the sitting to write in: the
382+/// student wall and the enrollment wall (a promotion out of `student` or an
383+/// unenrollment closes the sheet, mid-exam included), the rejoin gate, the
384+/// archived-term gate, the question lookup, and the upsert.
385+///
386+/// The archived-term refusal sits here because this is the single funnel every
387+/// answer write passes: REST `POST /exams/{id}/attempt/answers` (via
388+/// [`save_answer_checked`]) *and* every `answer` frame of the exam-room
389+/// WebSocket ([`crate::web::exam_ws`]). The answer-image writes are the only
390+/// answer-side writes outside it, and carry their own guard.
391+pub async fn save_answer_in(
392+ db: &Database,
393+ exam: &Exam,
394+ attempt: &ExamAttempt,
395+ question_id: &str,
396+ selected: Option<String>,
397+ text: Option<String>,
398+) -> Result<ExamAnswer, AppError> {
399+ ensure_student_now(attempt.get_user(), db).await?;
400+ ensure_enrolled(exam, attempt.get_user(), db).await?;
401+ check_rejoin(exam, attempt)?;
402+ course_of(exam, db).await?.require_open(db).await?;
403+ let question = question_of_exam(exam.get_id(), question_id, db).await?;
404+ crate::domain::exam_answer::ExamAnswer::save(
405+ &question,
406+ attempt.get_user(),
407+ attempt.get_seq(),
408+ selected,
409+ text,
410+ db,
411+ )
412+ .await
413+}
414+
415+/// One sitting by id — the exam room re-reads its own attempt this way.
416+pub async fn read(db: &Database, id: &ExamAttemptId) -> Result<Option<ExamAttempt>, AppError> {
417+ crate::db::exam_attempt::read(db, id).await
418+}
419+
420+/// The student's current sitting — the highest `seq` for the pair.
421+pub async fn read_latest_for_user(
422+ db: &Database,
423+ exam: &ExamId,
424+ user: &UserId,
425+) -> Result<Option<ExamAttempt>, AppError> {
426+ crate::db::exam_attempt::read_latest_for_user(db, exam, user).await
427+}
428+
429+/// Every sitting of `user` at `exam`, newest first.
430+pub async fn list_for_user(
431+ db: &Database,
432+ exam: &ExamId,
433+ user: &UserId,
434+) -> Result<Vec<ExamAttempt>, AppError> {
435+ crate::db::exam_attempt::list_for_user(db, exam, user).await
436+}
437+
438+/// Every sitting of `user` nobody has submitted yet, across all exams.
439+pub async fn list_unfinished_for_user(
440+ db: &Database,
441+ user: &UserId,
442+) -> Result<Vec<ExamAttempt>, AppError> {
443+ crate::db::exam_attempt::list_unfinished_for_user(db, user).await
444+}
445+
446+/// Every sitting at `exam`, newest id first.
447+pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<ExamAttempt>, AppError> {
448+ crate::db::exam_attempt::list_for_exam(db, exam).await
449+}
450+
451+/// Whether anyone has started this exam — the gate that freezes `mode`
452+/// edits once an attempt exists.
453+pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result<bool, AppError> {
454+ crate::db::exam_attempt::any_for_exam(db, exam).await
455+}
456+
457+/// How many sittings `user` has used at `exam`.
458+pub async fn attempts_used(db: &Database, exam: &ExamId, user: &UserId) -> Result<u64, AppError> {
459+ Ok(crate::db::exam_attempt::list_for_user(db, exam, user)
460+ .await?
461+ .len() as u64)
462+}
463+
464+/// Stamp the submission time. The caller has already checked the deadline
465+/// and that the attempt isn't finished.
466+pub async fn finish(db: &Database, attempt: ExamAttempt) -> Result<ExamAttempt, AppError> {
467+ crate::db::exam_attempt::finish(db, attempt).await
468+}
469+
470+/// Stamp (or clear) the walked-out marker. The exam room sets it when the
471+/// student's socket closes mid-attempt and clears it when they come back.
472+pub async fn set_left(
473+ db: &Database,
474+ attempt: ExamAttempt,
475+ left_at: Option<Timestamp>,
476+) -> Result<ExamAttempt, AppError> {
477+ crate::db::exam_attempt::set_left(db, attempt, left_at).await
478+}
479+
480+#[cfg(test)]
481+mod tests {
482+ use super::*;
483+ use crate::database::init_mem;
484+ use crate::domain::exam::{
485+ ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,
486+ };
487+ use crate::domain::exam_answer::ExamAnswer;
488+ use crate::domain::exam_question::{
489+ ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec,
490+ };
491+ use crate::domain::settings::Settings;
492+
493+ /// The id of the question's second option — what these tests used to write
494+ /// as the index `1`.
495+ fn second_choice(question: &ExamQuestion) -> String {
496+ question.get_choices().unwrap()[1]
497+ .get_id()
498+ .as_str()
499+ .to_string()
500+ }
501+
502+ /// An open exam with retakes allowed, plus one choice question — enough
503+ /// rows to exercise the attempt lifecycle without the HTTP layer.
504+ async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) {
505+ let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
506+ let course = crate::domain::course::a_test_course(db).await;
507+ let kinds = Settings::defaults().get_exam_kinds().to_vec();
508+ let exam = Exam::create(
509+ &creator,
510+ &course,
511+ ExamTitle::try_new("practice").unwrap(),
512+ ExamDescription::try_new("").unwrap(),
513+ ExamKind::try_new("quiz", &kinds).unwrap(),
514+ ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None)
515+ .unwrap(),
516+ ExamAttemptLimit::try_new(max_attempts).unwrap(),
517+ true,
518+ false,
519+ false,
520+ db,
521+ )
522+ .await
523+ .unwrap();
524+ let spec = QuestionSpec::try_new(
525+ QuestionKind::try_new("choice").unwrap(),
526+ Some(vec![
527+ ChoiceInput {
528+ id: Some("a".into()),
529+ text: "5".into(),
530+ },
531+ ChoiceInput {
532+ id: Some("b".into()),
533+ text: "6".into(),
534+ },
535+ ]),
536+ Some("b".into()),
537+ &[],
538+ )
539+ .unwrap();
540+ // A real subject row, not a minted id: a question claims a reference on
541+ // its subject and is refused if that subject does not exist.
542+ let subject = crate::domain::subject::Subject::create(
543+ &crate::domain::course::a_test_course(db).await,
544+ crate::domain::subject::SubjectName::try_new("topic").unwrap(),
545+ crate::domain::subject::SubjectDescription::try_new("").unwrap(),
546+ db,
547+ )
548+ .await
549+ .unwrap();
550+ let question = ExamQuestion::create(
551+ exam.get_id(),
552+ subject.get_id().clone(),
553+ crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(),
554+ QuestionPoints::try_new(5).unwrap(),
555+ spec,
556+ db,
557+ )
558+ .await
559+ .unwrap();
560+ (exam, question)
561+ }
562+
563+ /// A real user row: the sitting counter lives on it, and the claim that
564+ /// rides the attempt's create has nothing to write to without one.
565+ async fn student(db: &Database) -> UserId {
566+ let hash = crate::domain::user::Password::try_new("secret1")
567+ .unwrap()
568+ .hash_async()
569+ .await
570+ .unwrap();
571+ crate::domain::user::User::create(
572+ crate::domain::user::Username::try_new("ogrenci").unwrap(),
573+ hash,
574+ db,
575+ )
576+ .await
577+ .unwrap()
578+ .get_id()
579+ .clone()
580+ }
581+
582+ /// The student's lifetime sitting count, absent reading as zero.
583+ async fn sat_total(user: &UserId, db: &Database) -> i64 {
584+ let mut result = db
585+ .query(format!(
586+ "SELECT VALUE ({EXAM_SAT_TOTAL_FIELD} ?? 0) FROM $usr"
587+ ))
588+ .bind(("usr", user.record()))
589+ .await
590+ .unwrap()
591+ .check()
592+ .unwrap();
593+ result
594+ .take::<Vec<i64>>(0)
595+ .unwrap()
596+ .into_iter()
597+ .next()
598+ .unwrap()
599+ }
600+
601+ /// The badge counter counts *exams sat*, one per first sitting — so a start
602+ /// moves it by exactly one and a resume, which creates nothing, leaves it
603+ /// alone. Anything else and a seeded account and a fresh one would mean
604+ /// different things by the same number.
605+ #[tokio::test]
606+ async fn starting_counts_one_sitting_and_resuming_counts_none() {
607+ let db = init_mem().await.unwrap();
608+ let (exam, _question) = open_exam_with_question(&db, 2).await;
609+ let user = student(&db).await;
610+ assert_eq!(sat_total(&user, &db).await, 0, "a fresh row reads as zero");
611+
612+ let (_, created) = start(&db, &exam, &user).await.unwrap();
613+ assert!(created);
614+ assert_eq!(sat_total(&user, &db).await, 1);
615+
616+ // Still in progress: this start returns the running sitting untouched.
617+ let (_, created) = start(&db, &exam, &user).await.unwrap();
618+ assert!(!created);
619+ assert_eq!(
620+ sat_total(&user, &db).await,
621+ 1,
622+ "a resume writes no row, so it counts nothing"
623+ );
624+ }
625+
626+ /// A retake is the same exam again: the row lands at the next `seq` and the
627+ /// counter stays where it is. Counting it is the farm — an open exam with
628+ /// unlimited attempts would mint `exam_sat_25` off one exam and no teacher.
629+ #[tokio::test]
630+ async fn a_retake_writes_its_row_and_counts_nothing() {
631+ let db = init_mem().await.unwrap();
632+ let (exam, _question) = open_exam_with_question(&db, 3).await;
633+ let user = student(&db).await;
634+
635+ let (first, _) = start(&db, &exam, &user).await.unwrap();
636+ finish(&db, first).await.unwrap();
637+ let (second, created) = start(&db, &exam, &user).await.unwrap();
638+ assert!(created);
639+ assert_eq!(second.get_seq(), 2);
640+ assert_eq!(sat_total(&user, &db).await, 1);
641+ }
642+
643+ /// The lost half of a double-start race. `start` can only reach that branch
644+ /// by interleaving with a rival, so the claim is put to the counter
645+ /// directly — the same call `start` makes, aimed at a row that already
646+ /// exists. The duplicate aborts the transaction and takes its increment
647+ /// with it: a sitting is never counted twice.
648+ #[tokio::test]
649+ async fn a_lost_start_race_never_counts_the_sitting_twice() {
650+ let db = init_mem().await.unwrap();
651+ let (exam, _question) = open_exam_with_question(&db, 1).await;
652+ let user = student(&db).await;
653+
654+ let (winner, _) = start(&db, &exam, &user).await.unwrap();
655+ assert_eq!(sat_total(&user, &db).await, 1);
656+
657+ let claimed = cap::claim_and_create(
658+ &user.record(),
659+ EXAM_SAT_TOTAL_FIELD,
660+ cap::UNLIMITED,
661+ &winner.id.record(),
662+ &winner,
663+ &db,
664+ )
665+ .await
666+ .unwrap();
667+ assert!(matches!(claimed, cap::Claimed::Duplicate));
668+ assert_eq!(
669+ sat_total(&user, &db).await,
670+ 1,
671+ "the loser's increment rolled back with its duplicate create"
672+ );
673+ }
674+
675+ #[tokio::test]
676+ async fn a_retake_preserves_the_prior_sittings_sheet() {
677+ let db = init_mem().await.unwrap();
678+ let (exam, question) = open_exam_with_question(&db, 2).await;
679+ let user = student(&db).await;
680+
681+ let (first, created) = start(&db, &exam, &user).await.unwrap();
682+ assert!(created);
683+ assert_eq!(first.get_seq(), 1);
684+ ExamAnswer::save(
685+ &question,
686+ &user,
687+ 1,
688+ Some(second_choice(&question)),
689+ None,
690+ &db,
691+ )
692+ .await
693+ .unwrap();
694+ finish(&db, first).await.unwrap();
695+
696+ // The retake lands as sitting #2 without touching sitting #1's answers.
697+ let (second, created) = start(&db, &exam, &user).await.unwrap();
698+ assert!(created);
699+ assert_eq!(second.get_seq(), 2);
700+
701+ // Sitting #1's answer is still there, read at its own seq.
702+ let prior = ExamAnswer::read(question.get_id(), &user, 1, &db)
703+ .await
704+ .unwrap();
705+ assert!(prior.is_some(), "the retake must preserve seq 1's answer");
706+ // The new sitting starts blank at its own seq.
707+ let fresh = ExamAnswer::list_for_exam_user(exam.get_id(), &user, 2, &db)
708+ .await
709+ .unwrap();
710+ assert!(fresh.is_empty(), "seq 2 starts blank");
711+ }
712+
713+ #[tokio::test]
714+ async fn a_lost_retake_race_cannot_touch_the_winners_sheet() {
715+ let db = init_mem().await.unwrap();
716+ let (exam, question) = open_exam_with_question(&db, 3).await;
717+ let user = student(&db).await;
718+
719+ // Sitting #1 ends; the winner starts sitting #2 and saves an answer.
720+ let (first, _) = start(&db, &exam, &user).await.unwrap();
721+ finish(&db, first).await.unwrap();
722+ let (winner, created) = start(&db, &exam, &user).await.unwrap();
723+ assert!(created);
724+ assert_eq!(winner.get_seq(), 2);
725+ ExamAnswer::save(
726+ &question,
727+ &user,
728+ 2,
729+ Some(second_choice(&question)),
730+ None,
731+ &db,
732+ )
733+ .await
734+ .unwrap();
735+
736+ // A stale double-start races on the same seq and loses to the
737+ // composite id: the duplicate create is rejected, and with no wipe in
738+ // the path the winner's fresh answer is untouched either way.
739+ let loser = ExamAttempt {
740+ id: ExamAttemptId::composite(exam.get_id(), &user, 2),
741+ exam: exam.get_id().clone(),
742+ user: user.clone(),
743+ seq: 2,
744+ started_at: Timestamp::now(),
745+ finished_at: None,
746+ left_at: None,
747+ };
748+ let lost: Result<Option<ExamAttempt>, surrealdb::Error> =
749+ db.create(loser.id.record()).content(loser).await;
750+ assert!(lost.is_err(), "the duplicate-seq create must be rejected");
751+ let answers = ExamAnswer::list_for_exam_user(exam.get_id(), &user, 2, &db)
752+ .await
753+ .unwrap();
754+ assert_eq!(
755+ answers.len(),
756+ 1,
757+ "the lost race must not disturb the winner's saved answer"
758+ );
759+
760+ // The public path shrugs the race off: a re-start resumes the winner.
761+ let (resumed, created) = start(&db, &exam, &user).await.unwrap();
762+ assert!(!created);
763+ assert_eq!(resumed.get_seq(), 2);
764+ }
765+}
src/service/mod.rsmodified+1 -0
@@ -3,6 +3,7 @@
3 3
4 pub mod appointment;4 pub mod appointment;
5 pub mod course;5 pub mod course;
6+pub mod exam_attempt;
6 pub mod note;7 pub mod note;
7 pub mod payment_ledger;8 pub mod payment_ledger;
8 pub mod session;9 pub mod session;
src/web/exam_ws.rsmodified+12 -14
@@ -72,14 +72,14 @@ use crate::domain::exam_question::ExamQuestion;
72 use crate::domain::timestamp::Timestamp;72 use crate::domain::timestamp::Timestamp;
73 use crate::domain::user::UserId;73 use crate::domain::user::UserId;
74 use crate::error::AppError;74 use crate::error::AppError;
75+use crate::service::exam_attempt::{
76+ EXAM_LOCK, check_rejoin, course_of, ensure_enrolled, ensure_sittable, ensure_student, finish,
77+ read, save_answer_in, set_left, writable_attempt,
78+};
75 use crate::state::AppState;79 use crate::state::AppState;
76 use crate::tenant::Slug;80 use crate::tenant::Slug;
77 use crate::validate::validate_required;81 use crate::validate::validate_required;
78 use crate::web::CurrentUser;82 use crate::web::CurrentUser;
79-use crate::web::exams::{
80- EXAM_LOCK, check_rejoin, course_of, ensure_enrolled, ensure_sittable, ensure_student,
81- save_answer_in, writable_attempt,
82-};
83 use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq};83 use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq};
84 84
85 /// How this room names itself in the logs [`room::public_message`] writes.85 /// How this room names itself in the logs [`room::public_message`] writes.
@@ -152,7 +152,7 @@ pub async fn attempt_ws(
152 ensure_enrolled(&exam, user.get_id(), &st.db).await?;152 ensure_enrolled(&exam, user.get_id(), &st.db).await?;
153 let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?;153 let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?;
154 check_rejoin(&exam, &attempt)?;154 check_rejoin(&exam, &attempt)?;
155- crate::service::course::require_open(&st.db, &course_of(&exam, &st.db).await?).await?;155+ course_of(&exam, &st.db).await?.require_open(&st.db).await?;
156 156
157 let user_id = user.get_id().clone();157 let user_id = user.get_id().clone();
158 Ok(ws.on_upgrade(move |socket| room(socket, st, slug, exam, attempt, user_id)))158 Ok(ws.on_upgrade(move |socket| room(socket, st, slug, exam, attempt, user_id)))
@@ -184,7 +184,7 @@ async fn room(
184 {184 {
185 let _guard = PRESENCE_LOCK.lock().await;185 let _guard = PRESENCE_LOCK.lock().await;
186 st.exam_presence.enter(&slug, attempt_id.key());186 st.exam_presence.enter(&slug, attempt_id.key());
187- if let Err(err) = attempt.set_left(None, &st.db).await {187+ if let Err(err) = set_left(&st.db, attempt, None).await {
188 tracing::warn!("exam room could not clear left_at on join: {err}");188 tracing::warn!("exam room could not clear left_at on join: {err}");
189 }189 }
190 }190 }
@@ -234,7 +234,7 @@ async fn room(
234 /// started elsewhere can't be marked as left by an old room's teardown.234 /// started elsewhere can't be marked as left by an old room's teardown.
235 async fn stamp_left(exam_id: &ExamId, attempt_id: &ExamAttemptId, db: &Database) {235 async fn stamp_left(exam_id: &ExamId, attempt_id: &ExamAttemptId, db: &Database) {
236 let attempt = match Exam::read(exam_id, db).await {236 let attempt = match Exam::read(exam_id, db).await {
237- Ok(Some(exam)) => match ExamAttempt::read(attempt_id, db).await {237+ Ok(Some(exam)) => match read(db, attempt_id).await {
238 Ok(Some(attempt))238 Ok(Some(attempt))
239 if attempt.status(&exam, Timestamp::now()) == AttemptStatus::InProgress =>239 if attempt.status(&exam, Timestamp::now()) == AttemptStatus::InProgress =>
240 {240 {
@@ -253,7 +253,7 @@ async fn stamp_left(exam_id: &ExamId, attempt_id: &ExamAttemptId, db: &Database)
253 }253 }
254 };254 };
255 if let Some(attempt) = attempt255 if let Some(attempt) = attempt
256- && let Err(err) = attempt.set_left(Some(Timestamp::now()), db).await256+ && let Err(err) = set_left(db, attempt, Some(Timestamp::now())).await
257 {257 {
258 tracing::warn!("exam room could not stamp left_at: {err}");258 tracing::warn!("exam room could not stamp left_at: {err}");
259 }259 }
@@ -329,9 +329,7 @@ async fn state_frame(
329 db: &Database,329 db: &Database,
330 ) -> Result<(Value, AttemptStatus, Option<i64>), AppError> {330 ) -> Result<(Value, AttemptStatus, Option<i64>), AppError> {
331 let exam = Exam::read(exam, db).await?.ok_or(AppError::NotFound)?;331 let exam = Exam::read(exam, db).await?.ok_or(AppError::NotFound)?;
332- let attempt = ExamAttempt::read(attempt, db)332+ let attempt = read(db, attempt).await?.ok_or(AppError::NotFound)?;
333- .await?
334- .ok_or(AppError::NotFound)?;
335 let now = Timestamp::now();333 let now = Timestamp::now();
336 let status = attempt.status(&exam, now);334 let status = attempt.status(&exam, now);
337 let deadline = attempt.deadline(&exam);335 let deadline = attempt.deadline(&exam);
@@ -417,7 +415,7 @@ async fn handle_message(
417 Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await {415 Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await {
418 Ok(attempt) => {416 Ok(attempt) => {
419 in_save = true;417 in_save = true;
420- save_answer_in(&exam, &attempt, &question_id, selected, text, db).await418+ save_answer_in(db, &exam, &attempt, &question_id, selected, text).await
421 }419 }
422 Err(err) => Err(err),420 Err(err) => Err(err),
423 },421 },
@@ -463,8 +461,8 @@ async fn handle_message(
463 // same error frame as every other conflict.461 // same error frame as every other conflict.
464 async {462 async {
465 let attempt = writable_room_attempt(&exam, attempt_id, user, db).await?;463 let attempt = writable_room_attempt(&exam, attempt_id, user, db).await?;
466- crate::service::course::require_open(db, &course_of(&exam, db).await?).await?;464+ course_of(&exam, db).await?.require_open(db).await?;
467- attempt.finish(db).await465+ finish(db, attempt).await
468 }466 }
469 .await467 .await
470 }468 }
src/web/exams/attempts.rsmodified+20 -232
@@ -1,5 +1,8 @@
1 use super::*;1 use super::*;
2 2
3+use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt};
4+use crate::service::exam_attempt;
5+
3 // ---- attempts -------------------------------------------------------------6 // ---- attempts -------------------------------------------------------------
4 // A sittable exam (sync, async, or open mode) is *sat*: starting an attempt7 // A sittable exam (sync, async, or open mode) is *sat*: starting an attempt
5 // is the live-attendance signal, finishing is the submission. The exam's8 // is the live-attendance signal, finishing is the submission. The exam's
@@ -109,33 +112,6 @@ pub(crate) async fn attempt_progress(
109 Ok((answered, question_count))112 Ok((answered, question_count))
110 }113 }
111 114
112-/// Rejects sitting an exam that can't be sat. A draft is a `404`, not a
113-/// `409` — sitting is a student act, drafts are invisible to students, and a
114-/// state-specific error would leak the existence this feature hides. A
115-/// modeless (offline-graded) exam is a `409`: visible, just nothing to sit.
116-/// Enrollment and window checks for the caller are the caller's own state —
117-/// also `Conflict`, not validation.
118-pub(crate) fn ensure_sittable(exam: &Exam) -> Result<(), AppError> {
119- if exam.is_draft() {
120- return Err(AppError::NotFound);
121- }
122- if exam.get_mode().is_none() {
123- return Err(AppError::Conflict(
124- "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)",
125- ));
126- }
127- Ok(())
128-}
129-
130-/// How many sittings the caller has used at this exam.
131-pub(crate) async fn attempts_used(
132- exam: &ExamId,
133- user: &UserId,
134- db: &Database,
135-) -> Result<u64, AppError> {
136- Ok(ExamAttempt::list_for_user(exam, user, db).await?.len() as u64)
137-}
138-
139 /// Start, resume, or retake the caller's attempt. Requires the student role115 /// Start, resume, or retake the caller's attempt. Requires the student role
140 /// (staff run exams, they don't sit them), enrollment in the exam's course, a116 /// (staff run exams, they don't sit them), enrollment in the exam's course, a
141 /// sittable exam (`sync`/`async`/`open` mode), and — when a window exists — the117 /// sittable exam (`sync`/`async`/`open` mode), and — when a window exists — the
@@ -164,47 +140,14 @@ pub(crate) async fn start_attempt(
164 CurrentUser(user): CurrentUser,140 CurrentUser(user): CurrentUser,
165 Path(id): Path<String>,141 Path(id): Path<String>,
166 ) -> Result<(StatusCode, Json<AttemptResponse>), AppError> {142 ) -> Result<(StatusCode, Json<AttemptResponse>), AppError> {
167- // Writer lease of [`EXAM_LOCK`] from the exam read through the start: the143+ let (exam, attempt, created) =
168- // sittable/window gates must be judged against the same exam row the144+ exam_attempt::start_attempt(&st.db, &ExamId::from_key(&id), &user).await?;
169- // attempt lands under (the mirror of `update_exam`'s re-derive — without
170- // it, a mode change or re-draft at legally-zero attempts could slip
171- // between this gate and the insert, leaving an attempt on an unsittable
172- // exam). The lease
173- // also keeps the max-attempts count and the retake's wipe-and-create
174- // from interleaving with an in-flight answer save (a reader). Dropped
175- // before the response reads — they only describe the row.
176- let guard = EXAM_LOCK.write().await;
177- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
178- .await?
179- .ok_or(AppError::NotFound)?;
180- ensure_sittable(&exam)?;
181- ensure_student(&user)?;
182- ensure_enrolled(&exam, user.get_id(), &st.db).await?;
183- crate::service::course::require_open(&st.db, &course_of(&exam, &st.db).await?).await?;
184- let now = Timestamp::now();
185- if let Some(starts_at) = exam.get_starts_at()
186- && now < starts_at
187- {
188- return Err(AppError::Conflict("the exam has not started yet"));
189- }
190- if let Some(ends_at) = exam.get_ends_at()
191- && now >= ends_at
192- {
193- return Err(AppError::Conflict("the exam has already ended"));
194- }
195-
196- // A retake no longer wipes the prior sitting — each attempt's answers,
197- // drawings, and marks stay put at their own seq (per-attempt history), so
198- // there are no orphaned blobs to GC here. The exam-delete cascade still
199- // cleans every sitting's blobs.
200- let (attempt, created) = ExamAttempt::start(&exam, user.get_id(), &st.db).await?;
201- drop(guard);
202 let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)145 let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
203 .await?146 .await?
204 .map(|r| r.get_mark());147 .map(|r| r.get_mark());
205 let (answered, question_count) =148 let (answered, question_count) =
206 attempt_progress(exam.get_id(), user.get_id(), attempt.get_seq(), &st.db).await?;149 attempt_progress(exam.get_id(), user.get_id(), attempt.get_seq(), &st.db).await?;
207- let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?;150+ let used = exam_attempt::attempts_used(&st.db, exam.get_id(), user.get_id()).await?;
208 let people = PersonRef::map_of(&[&user]);151 let people = PersonRef::map_of(&[&user]);
209 let status = if created {152 let status = if created {
210 StatusCode::CREATED153 StatusCode::CREATED
@@ -249,7 +192,7 @@ pub(crate) async fn my_attempt(
249 let exam = Exam::read(&ExamId::from_key(&id), &st.db)192 let exam = Exam::read(&ExamId::from_key(&id), &st.db)
250 .await?193 .await?
251 .ok_or(AppError::NotFound)?;194 .ok_or(AppError::NotFound)?;
252- let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db)195+ let attempt = exam_attempt::read_latest_for_user(&st.db, exam.get_id(), user.get_id())
253 .await?196 .await?
254 .ok_or(AppError::NotFound)?;197 .ok_or(AppError::NotFound)?;
255 let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)198 let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
@@ -257,7 +200,7 @@ pub(crate) async fn my_attempt(
257 .map(|r| r.get_mark());200 .map(|r| r.get_mark());
258 let (answered, question_count) =201 let (answered, question_count) =
259 attempt_progress(exam.get_id(), user.get_id(), attempt.get_seq(), &st.db).await?;202 attempt_progress(exam.get_id(), user.get_id(), attempt.get_seq(), &st.db).await?;
260- let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?;203+ let used = exam_attempt::attempts_used(&st.db, exam.get_id(), user.get_id()).await?;
261 let people = PersonRef::map_of(&[&user]);204 let people = PersonRef::map_of(&[&user]);
262 Ok(Json(AttemptResponse::new(205 Ok(Json(AttemptResponse::new(
263 &attempt,206 &attempt,
@@ -295,29 +238,13 @@ pub(crate) async fn finish_attempt(
295 let exam = Exam::read(&ExamId::from_key(&id), &st.db)238 let exam = Exam::read(&ExamId::from_key(&id), &st.db)
296 .await?239 .await?
297 .ok_or(AppError::NotFound)?;240 .ok_or(AppError::NotFound)?;
298- let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db)241+ let finished = exam_attempt::finish_attempt(&st.db, &exam, user.get_id()).await?;
299- .await?
300- .ok_or(AppError::NotFound)?;
301- if attempt.get_finished_at().is_some() {
302- return Err(AppError::Conflict("the attempt is already submitted"));
303- }
304- let now = Timestamp::now();
305- if let Some(deadline) = attempt.deadline(&exam)
306- && now >= deadline
307- {
308- return Err(AppError::Conflict("time is up — the attempt has expired"));
309- }
310- crate::service::course::require_open(&st.db, &course_of(&exam, &st.db).await?).await?;
311-
312- // Deliberately no rejoin check: a student locked out of the room may
313- // still submit what they saved — finishing answers nothing new.
314- let finished = attempt.finish(&st.db).await?;
315 let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)242 let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
316 .await?243 .await?
317 .map(|r| r.get_mark());244 .map(|r| r.get_mark());
318 let (answered, question_count) =245 let (answered, question_count) =
319 attempt_progress(exam.get_id(), user.get_id(), finished.get_seq(), &st.db).await?;246 attempt_progress(exam.get_id(), user.get_id(), finished.get_seq(), &st.db).await?;
320- let used = attempts_used(exam.get_id(), user.get_id(), &st.db).await?;247+ let used = exam_attempt::attempts_used(&st.db, exam.get_id(), user.get_id()).await?;
321 let people = PersonRef::map_of(&[&user]);248 let people = PersonRef::map_of(&[&user]);
322 Ok(Json(AttemptResponse::new(249 Ok(Json(AttemptResponse::new(
323 &finished,250 &finished,
@@ -405,7 +332,7 @@ pub(crate) async fn live_snapshot(
405 // many they've used.332 // many they've used.
406 let mut attempts: HashMap<String, ExamAttempt> = HashMap::new();333 let mut attempts: HashMap<String, ExamAttempt> = HashMap::new();
407 let mut used: HashMap<String, u64> = HashMap::new();334 let mut used: HashMap<String, u64> = HashMap::new();
408- for attempt in ExamAttempt::list_for_exam(exam.get_id(), db).await? {335+ for attempt in exam_attempt::list_for_exam(db, exam.get_id()).await? {
409 let key = attempt.get_user().key().to_string();336 let key = attempt.get_user().key().to_string();
410 *used.entry(key.clone()).or_insert(0) += 1;337 *used.entry(key.clone()).or_insert(0) += 1;
411 match attempts.entry(key) {338 match attempts.entry(key) {
@@ -533,7 +460,7 @@ pub(crate) async fn exam_live(
533 let exam = Exam::read(&ExamId::from_key(&id), &st.db)460 let exam = Exam::read(&ExamId::from_key(&id), &st.db)
534 .await?461 .await?
535 .ok_or(AppError::NotFound)?;462 .ok_or(AppError::NotFound)?;
536- let course = course_of(&exam, &st.db).await?;463+ let course = exam_attempt::course_of(&exam, &st.db).await?;
537 if !can_manage_course(&course, &user) {464 if !can_manage_course(&course, &user) {
538 return Err(AppError::Forbidden(465 return Err(AppError::Forbidden(
539 "only the course creator, an assigned teacher, or a manager/admin can monitor this exam",466 "only the course creator, an assigned teacher, or a manager/admin can monitor this exam",
@@ -619,144 +546,6 @@ pub(crate) struct AnswerSavedResponse {
619 updated_at: i64,546 updated_at: i64,
620 }547 }
621 548
622-/// The caller's latest attempt provided it is still writable, or the error
623-/// that says why not: no attempt yet (404 — start it first), already
624-/// submitted (409), deadline passed (409). One gate shared by REST saves and
625-/// the WebSocket room.
626-pub(crate) async fn writable_attempt(
627- exam: &Exam,
628- user: &UserId,
629- db: &Database,
630-) -> Result<ExamAttempt, AppError> {
631- let attempt = ExamAttempt::read_latest_for_user(exam.get_id(), user, db)
632- .await?
633- .ok_or(AppError::NotFound)?;
634- match attempt.status(exam, Timestamp::now()) {
635- AttemptStatus::Submitted => Err(AppError::Conflict("the attempt is already submitted")),
636- AttemptStatus::Expired => Err(AppError::Conflict("time is up — the attempt has expired")),
637- AttemptStatus::InProgress => Ok(attempt),
638- }
639-}
640-
641-/// A 409 when the student has walked out of the exam room and the exam's
642-/// rejoin door is closed: no more answering (from anywhere) until the teacher
643-/// flips `allow_rejoin` back on. Finishing is deliberately exempt — see
644-/// `finish_attempt`.
645-pub(crate) fn check_rejoin(exam: &Exam, attempt: &ExamAttempt) -> Result<(), AppError> {
646- if attempt.get_left_at().is_some() && !exam.get_allow_rejoin() {
647- return Err(AppError::Conflict(
648- "you left the exam and rejoin is closed — ask your teacher to reopen it",
649- ));
650- }
651- Ok(())
652-}
653-
654-/// Save one answer inside the caller's in-progress attempt — the whole write
655-/// path (attempt gate, rejoin gate, question lookup, kind check, upsert). The
656-/// REST handler saves into the latest sitting via this; the WebSocket room
657-/// resolves its own sitting first and shares [`save_answer_in`], so the two
658-/// can never drift.
659-pub(crate) async fn save_answer_checked(
660- exam: &Exam,
661- user: &UserId,
662- question_id: &str,
663- selected: Option<String>,
664- text: Option<String>,
665- db: &Database,
666-) -> Result<ExamAnswer, AppError> {
667- // Reader lease of [`EXAM_LOCK`]: the writable gate and the upsert are
668- // one unit, or a retake's wipe-and-create (a writer) slips in between
669- // and this stale save lands on the fresh blank sheet.
670- //
671- // The lease covers the gate *and* the upsert here, so a retake cannot
672- // interleave with this path at all. The accepted late-save race lives in
673- // the exam-room socket instead, which writes into the sitting it joined
674- // with — a value chosen before any lease is taken. See
675- // [`crate::web::exam_ws`].
676- let _guard = EXAM_LOCK.read().await;
677- let attempt = writable_attempt(exam, user, db).await?;
678- save_answer_in(exam, &attempt, question_id, selected, text, db).await
679-}
680-
681-/// The tail of the answer write path, given the sitting to write in: the
682-/// student wall and the enrollment wall (a promotion out of `student` or an
683-/// unenrollment closes the sheet, mid-exam included), the rejoin gate, the
684-/// archived-term gate, the question lookup, and the upsert.
685-///
686-/// The archived-term refusal sits here because this is the single funnel every
687-/// answer write passes: REST `POST /exams/{id}/attempt/answers` (via
688-/// [`save_answer_checked`]) *and* every `answer` frame of the exam-room
689-/// WebSocket ([`crate::web::exam_ws`]). The answer-image writes are the only
690-/// answer-side writes outside it, and carry their own guard.
691-pub(crate) async fn save_answer_in(
692- exam: &Exam,
693- attempt: &ExamAttempt,
694- question_id: &str,
695- selected: Option<String>,
696- text: Option<String>,
697- db: &Database,
698-) -> Result<ExamAnswer, AppError> {
699- ensure_student_now(attempt.get_user(), db).await?;
700- ensure_enrolled(exam, attempt.get_user(), db).await?;
701- check_rejoin(exam, attempt)?;
702- crate::service::course::require_open(db, &course_of(exam, db).await?).await?;
703- let question = question_of_exam(exam.get_id(), question_id, db).await?;
704- ExamAnswer::save(
705- &question,
706- attempt.get_user(),
707- attempt.get_seq(),
708- selected,
709- text,
710- db,
711- )
712- .await
713-}
714-
715-/// A 403 unless `user` is a student. Sitting an exam is a student action —
716-/// teachers and above run exams, they never take them — so the sit paths
717-/// (start, room, save) enforce it on the *current* role. Checking the live
718-/// role, not just enrollment, closes the gap a mid-exam promotion would open
719-/// and neutralizes any stale non-student enrollment. Reading one's own attempt
720-/// and finishing stay ungated: a non-student has no attempt to read, and
721-/// finishing only submits work already saved.
722-pub(crate) fn ensure_student(user: &User) -> Result<(), AppError> {
723- if user.get_role() != Role::Student {
724- return Err(AppError::Forbidden("only students can sit exams"));
725- }
726- Ok(())
727-}
728-
729-/// The answer path's live edition of [`ensure_student`]: re-read the row and
730-/// judge the *current* role, exactly like the enrollment wall beside it. Both
731-/// save paths run through here (REST per request, the exam room per message),
732-/// so a promotion out of `student` mid-exam closes the sheet on the very next
733-/// save — the room's door check is not the last word for a socket that
734-/// outlives the role.
735-pub(crate) async fn ensure_student_now(user: &UserId, db: &Database) -> Result<(), AppError> {
736- let user = User::read(user, db).await?.ok_or(AppError::Unauthorized)?;
737- ensure_student(&user)
738-}
739-
740-/// A 403 unless `user` is enrolled in the exam's course — the same wall the
741-/// exam room checks at its door, re-applied to the sitting's content paths so
742-/// an unenrollment mid-exam cuts them too. Finishing stays exempt: like the
743-/// rejoin lock, submitting what's already saved writes nothing new.
744-pub(crate) async fn ensure_enrolled(
745- exam: &Exam,
746- user: &UserId,
747- db: &Database,
748-) -> Result<(), AppError> {
749- if Enrollment::read_for_user(exam.get_course(), user, db)
750- .await?
751- .is_none()
752- {
753- return Err(AppError::Forbidden(
754- "you are not enrolled in this exam's course",
755- ));
756- }
757- Ok(())
758-}
759-
760 /// The exam's questions as the sitting student sees them: `correct` stripped,549 /// The exam's questions as the sitting student sees them: `correct` stripped,
761 /// their own saved answers embedded — the latest sitting's, since a retake550 /// their own saved answers embedded — the latest sitting's, since a retake
762 /// starts from a blank sheet. Requires enrollment in the exam's course (the551 /// starts from a blank sheet. Requires enrollment in the exam's course (the
@@ -785,11 +574,11 @@ pub(crate) async fn attempt_questions(
785 let exam = Exam::read(&ExamId::from_key(&id), &st.db)574 let exam = Exam::read(&ExamId::from_key(&id), &st.db)
786 .await?575 .await?
787 .ok_or(AppError::NotFound)?;576 .ok_or(AppError::NotFound)?;
788- ensure_enrolled(&exam, user.get_id(), &st.db).await?;577+ exam_attempt::ensure_enrolled(&exam, user.get_id(), &st.db).await?;
789 // The question list is for sitting students; without an attempt there is578 // The question list is for sitting students; without an attempt there is
790 // nothing to sit behind — and no early peek at the questions. The embedded579 // nothing to sit behind — and no early peek at the questions. The embedded
791 // answers are the *current* sitting's only, so the seq scopes the reads.580 // answers are the *current* sitting's only, so the seq scopes the reads.
792- let seq = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db)581+ let seq = exam_attempt::read_latest_for_user(&st.db, exam.get_id(), user.get_id())
793 .await?582 .await?
794 .ok_or(AppError::NotFound)?583 .ok_or(AppError::NotFound)?
795 .get_seq();584 .get_seq();
@@ -844,7 +633,7 @@ pub(crate) async fn attempt_questions(
844 /// promotion out of `student`) mid-exam closes the sheet. Rejected once the633 /// promotion out of `student`) mid-exam closes the sheet. Rejected once the
845 /// attempt is submitted or its deadline has passed —634 /// attempt is submitted or its deadline has passed —
846 /// the server clock, not the client's, is the judge — and rejected while the635 /// the server clock, not the client's, is the judge — and rejected while the
847-/// student has left the exam room with the exam's rejoin door closed.636+/// student has left the exam room with the rejoin door closed.
848 #[utoipa::path(637 #[utoipa::path(
849 post,638 post,
850 path = "/{id}/attempt/answers",639 path = "/{id}/attempt/answers",
@@ -871,14 +660,13 @@ pub(crate) async fn save_answer(
871 let exam = Exam::read(&ExamId::from_key(&id), &st.db)660 let exam = Exam::read(&ExamId::from_key(&id), &st.db)
872 .await?661 .await?
873 .ok_or(AppError::NotFound)?;662 .ok_or(AppError::NotFound)?;
874- ensure_student(&user)?;663+ let answer = exam_attempt::save_answer_checked(
875- let answer = save_answer_checked(664+ &st.db,
876 &exam,665 &exam,
877- user.get_id(),666+ &user,
878 &req.question_id,667 &req.question_id,
879 req.selected,668 req.selected,
880 req.text,669 req.text,
881- &st.db,
882 )670 )
883 .await?;671 .await?;
884 Ok(Json(AnswerSavedResponse {672 Ok(Json(AnswerSavedResponse {
@@ -920,7 +708,7 @@ pub(crate) async fn attempt_answers(
920 let exam = Exam::read(&ExamId::from_key(&id), &st.db)708 let exam = Exam::read(&ExamId::from_key(&id), &st.db)
921 .await?709 .await?
922 .ok_or(AppError::NotFound)?;710 .ok_or(AppError::NotFound)?;
923- let course = course_of(&exam, &st.db).await?;711+ let course = exam_attempt::course_of(&exam, &st.db).await?;
924 if !can_manage_course(&course, &user) {712 if !can_manage_course(&course, &user) {
925 return Err(AppError::Forbidden(713 return Err(AppError::Forbidden(
926 "only the course creator, an assigned teacher, or a manager/admin can read answer sheets",714 "only the course creator, an assigned teacher, or a manager/admin can read answer sheets",
@@ -930,7 +718,7 @@ pub(crate) async fn attempt_answers(
930 // No attempt means no answer sheet — a 404, not an empty one. This grading718 // No attempt means no answer sheet — a 404, not an empty one. This grading
931 // view shows the *latest* sitting; prior sittings live under the719 // view shows the *latest* sitting; prior sittings live under the
932 // per-attempt history endpoints.720 // per-attempt history endpoints.
933- let seq = ExamAttempt::read_latest_for_user(exam.get_id(), &target, &st.db)721+ let seq = exam_attempt::read_latest_for_user(&st.db, exam.get_id(), &target)
934 .await?722 .await?
935 .ok_or(AppError::NotFound)?723 .ok_or(AppError::NotFound)?
936 .get_seq();724 .get_seq();
src/web/exams/images.rsmodified+8 -3
@@ -1,5 +1,10 @@
1 use super::*;1 use super::*;
2 2
3+use crate::service::exam_attempt::{
4+ EXAM_LOCK, check_rejoin, course_of, ensure_enrolled, ensure_student, ensure_student_now,
5+ question_of_exam, read_latest_for_user, writable_attempt,
6+};
7+
3 /// A stored question image's metadata; the bytes come from the image8 /// A stored question image's metadata; the bytes come from the image
4 /// endpoints (`GET .../image`, `GET .../choices/{choice_id}/image`).9 /// endpoints (`GET .../image`, `GET .../choices/{choice_id}/image`).
5 #[derive(Serialize, ToSchema)]10 #[derive(Serialize, ToSchema)]
@@ -117,7 +122,7 @@ pub(crate) async fn ensure_question_content_visible(
117 return Ok(());122 return Ok(());
118 }123 }
119 ensure_enrolled(exam, user.get_id(), &st.db).await?;124 ensure_enrolled(exam, user.get_id(), &st.db).await?;
120- ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db)125+ read_latest_for_user(&st.db, exam.get_id(), user.get_id())
121 .await?126 .await?
122 .ok_or(AppError::NotFound)?;127 .ok_or(AppError::NotFound)?;
123 Ok(())128 Ok(())
@@ -595,7 +600,7 @@ pub(crate) async fn get_answer_image(
595 ensure_question_content_visible(&st, &exam, &user).await?;600 ensure_question_content_visible(&st, &exam, &user).await?;
596 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;601 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
597 // The caller's current sitting — the drawing belongs to their latest seq.602 // The caller's current sitting — the drawing belongs to their latest seq.
598- let seq = ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db)603+ let seq = read_latest_for_user(&st.db, exam.get_id(), user.get_id())
599 .await?604 .await?
600 .ok_or(AppError::NotFound)?605 .ok_or(AppError::NotFound)?
601 .get_seq();606 .get_seq();
@@ -642,7 +647,7 @@ pub(crate) async fn get_student_answer_image(
642 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;647 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
643 // The grader's default view is the latest sitting; per-attempt drawings648 // The grader's default view is the latest sitting; per-attempt drawings
644 // come from the history image endpoint.649 // come from the history image endpoint.
645- let seq = ExamAttempt::read_latest_for_user(exam.get_id(), &target, &st.db)650+ let seq = read_latest_for_user(&st.db, exam.get_id(), &target)
646 .await?651 .await?
647 .ok_or(AppError::NotFound)?652 .ok_or(AppError::NotFound)?
648 .get_seq();653 .get_seq();
src/web/exams/mod.rsmodified+9 -48
@@ -16,17 +16,14 @@ use crate::domain::answer_image::AnswerImage;
16 use crate::domain::badge;16 use crate::domain::badge;
17 use crate::domain::bank_question::{BankQuestion, BankQuestionId};17 use crate::domain::bank_question::{BankQuestion, BankQuestionId};
18 use crate::domain::bank_question_image::BankQuestionImage;18 use crate::domain::bank_question_image::BankQuestionImage;
19-use crate::domain::course::Course;
20 use crate::domain::enrollment::Enrollment;19 use crate::domain::enrollment::Enrollment;
21 use crate::domain::exam::{20 use crate::domain::exam::{
22 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode,21 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode,
23 ExamSchedule, ExamTitle,22 ExamSchedule, ExamTitle,
24 };23 };
25 use crate::domain::exam_answer::{ExamAnswer, auto_score};24 use crate::domain::exam_answer::{ExamAnswer, auto_score};
26-use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt};
27 use crate::domain::exam_question::{25 use crate::domain::exam_question::{
28- Choice, ChoiceId, ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec,26+ Choice, ChoiceId, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
29- QuestionText,
30 };27 };
31 use crate::domain::exam_result::{ExamResult, Mark};28 use crate::domain::exam_result::{ExamResult, Mark};
32 use crate::domain::note_file::FileContentType;29 use crate::domain::note_file::FileContentType;
@@ -36,6 +33,7 @@ use crate::domain::timestamp::Timestamp;
36 use crate::domain::user::{User, UserId};33 use crate::domain::user::{User, UserId};
37 use crate::error::{AppError, ErrorResponse, ValidationError};34 use crate::error::{AppError, ErrorResponse, ValidationError};
38 use crate::service;35 use crate::service;
36+use crate::service::exam_attempt::{EXAM_LOCK, any_for_exam, course_of, read_latest_for_user};
39 use crate::state::AppState;37 use crate::state::AppState;
40 38
41 use super::bank_questions::BankQuestionResponse;39 use super::bank_questions::BankQuestionResponse;
@@ -71,35 +69,6 @@ impl Scheduled for Exam {
71 }69 }
72 }70 }
73 71
74-/// Serializes the exam subsystem's cross-record check-then-writes, which
75-/// `BEGIN…COMMIT` cannot (write skew) — the reasoning in [`crate::db::cap`].
76-/// It orders requests, but only around what it wraps — every invariant that
77-/// could be moved into the database itself has been, so a gap between a read
78-/// and its write is decided by the store. What is left here needs a
79-/// cross-record read and a write held together, which no single statement
80-/// expresses:
81-///
82-/// Read side — the answer saves (REST and the exam room), from the
83-/// writable-attempt gate through the upsert; the grade write (draft gate
84-/// through the result upsert); and the exam PATCH, whose mode/re-draft gates
85-/// count attempts and results. These stay concurrent with each other.
86-///
87-/// Write side — attempt starts alone (the max-attempts count and the retake's
88-/// answer wipe). So a save can never land on a sheet a retake just wiped, and a
89-/// mark can never land on an exam mid-flight into hiding.
90-///
91-/// Two rules have left this list. The question freeze gate rides inside each
92-/// question/image write's own transaction
93-/// ([`crate::domain::exam_attempt::ExamAttempt::write_unfrozen`]), and the exam PATCH
94-/// no longer needs the writer lease because its save is a compare-and-set. The
95-/// subject delete's cascade — the only writer outside attempt starts, paired
96-/// with the question writes' subject check — is now a conditional statement on
97-/// the subject's own reference counter
98-/// ([`crate::domain::subject::Subject::delete`]), which every question create,
99-/// re-tag and delete moves.
100-// corner-cut: global RwLock, shard per-exam if save latency ever matters.
101-pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
102-
103 pub fn routes() -> OpenApiRouter<AppState> {72 pub fn routes() -> OpenApiRouter<AppState> {
104 OpenApiRouter::new()73 OpenApiRouter::new()
105 // Plain route: OpenApiRouter can't describe a WebSocket upgrade, so74 // Plain route: OpenApiRouter can't describe a WebSocket upgrade, so
@@ -263,14 +232,6 @@ struct ExamStatisticsResponse {
263 max: Option<i64>,232 max: Option<i64>,
264 }233 }
265 234
266-/// The course an exam belongs to. A dangling reference means the course-delete
267-/// cascade was violated — surface it loudly as a 500, not a user-facing 404.
268-pub(crate) async fn course_of(exam: &Exam, db: &Database) -> Result<Course, AppError> {
269- crate::service::course::read(db, exam.get_course())
270- .await?
271- .ok_or_else(|| AppError::Internal("exam references a missing course".into()))
272-}
273-
274 // ---- exams --------------------------------------------------------------235 // ---- exams --------------------------------------------------------------
275 // Exams are created inside a course: `POST /courses/{id}/exams`.236 // Exams are created inside a course: `POST /courses/{id}/exams`.
276 237
@@ -433,7 +394,7 @@ async fn update_exam(
433 "only the course creator, an assigned teacher, or a manager/admin can edit this exam",394 "only the course creator, an assigned teacher, or a manager/admin can edit this exam",
434 ));395 ));
435 }396 }
436- crate::service::course::require_open(&st.db, &course).await?;397+ course.require_open(&st.db).await?;
437 398
438 let title = match req.title {399 let title = match req.title {
439 Some(ref title) => ExamTitle::try_new(title)?,400 Some(ref title) => ExamTitle::try_new(title)?,
@@ -500,7 +461,7 @@ async fn update_exam(
500 // land in the gap and leave a sat exam's mode flipped under it.461 // land in the gap and leave a sat exam's mode flipped under it.
501 let mode_changed =462 let mode_changed =
502 schedule.get_mode().map(ExamMode::as_str) != exam.get_mode().map(ExamMode::as_str);463 schedule.get_mode().map(ExamMode::as_str) != exam.get_mode().map(ExamMode::as_str);
503- if mode_changed && ExamAttempt::any_for_exam(exam.get_id(), &st.db).await? {464+ if mode_changed && any_for_exam(&st.db, exam.get_id()).await? {
504 return Err(AppError::Conflict(465 return Err(AppError::Conflict(
505 "cannot change the exam mode after attempts have started",466 "cannot change the exam mode after attempts have started",
506 ));467 ));
@@ -510,7 +471,7 @@ async fn update_exam(
510 // transaction re-makes this check and answers with the same error, so a471 // transaction re-makes this check and answers with the same error, so a
511 // grade landing after this read still cannot leave a mark on a draft.472 // grade landing after this read still cannot leave a mark on a draft.
512 if draft && !exam.is_draft() {473 if draft && !exam.is_draft() {
513- let sat = ExamAttempt::any_for_exam(exam.get_id(), &st.db).await?;474+ let sat = any_for_exam(&st.db, exam.get_id()).await?;
514 let graded = !ExamResult::list_for_exam(exam.get_id(), &st.db)475 let graded = !ExamResult::list_for_exam(exam.get_id(), &st.db)
515 .await?476 .await?
516 .is_empty();477 .is_empty();
@@ -591,7 +552,7 @@ async fn delete_exam(
591 "only the course creator, an assigned teacher, or a manager/admin can delete this exam",552 "only the course creator, an assigned teacher, or a manager/admin can delete this exam",
592 ));553 ));
593 }554 }
594- crate::service::course::require_open(&st.db, &course).await?;555+ course.require_open(&st.db).await?;
595 // *Writer* lease of [`EXAM_LOCK`] across the whole cascade, blob names556 // *Writer* lease of [`EXAM_LOCK`] across the whole cascade, blob names
596 // included — the lease `delete_homework` has always held, and its absence557 // included — the lease `delete_homework` has always held, and its absence
597 // here is what made a sitting able to start inside this delete. Every other558 // here is what made a sitting able to start inside this delete. Every other
@@ -676,7 +637,7 @@ async fn grade(
676 "only the course creator, an assigned teacher, or a manager/admin can grade this exam",637 "only the course creator, an assigned teacher, or a manager/admin can grade this exam",
677 ));638 ));
678 }639 }
679- crate::service::course::require_open(&st.db, &course).await?;640+ course.require_open(&st.db).await?;
680 // Pre-flight: `ExamResult::grade` re-makes this check inside the mark's own641 // Pre-flight: `ExamResult::grade` re-makes this check inside the mark's own
681 // transaction, so a re-draft landing after this read cannot leave a mark on642 // transaction, so a re-draft landing after this read cannot leave a mark on
682 // a hidden exam.643 // a hidden exam.
@@ -740,7 +701,7 @@ async fn grade(
740 // The mark lands on the student's current sitting; the latest seq is the701 // The mark lands on the student's current sitting; the latest seq is the
741 // grade-of-record. An offline-graded exam has no sitting — grade its base702 // grade-of-record. An offline-graded exam has no sitting — grade its base
742 // seq (1).703 // seq (1).
743- let seq = ExamAttempt::read_latest_for_user(&exam_id, &target, &st.db)704+ let seq = read_latest_for_user(&st.db, &exam_id, &target)
744 .await?705 .await?
745 .map_or(1, |a| a.get_seq());706 .map_or(1, |a| a.get_seq());
746 let result = ExamResult::grade(707 let result = ExamResult::grade(
@@ -883,7 +844,7 @@ async fn remove_result(
883 "only the course creator, an assigned teacher, or a manager/admin can remove results",844 "only the course creator, an assigned teacher, or a manager/admin can remove results",
884 ));845 ));
885 }846 }
886- crate::service::course::require_open(&st.db, &course).await?;847+ course.require_open(&st.db).await?;
887 let removed = ExamResult::remove(848 let removed = ExamResult::remove(
888 exam.get_id(),849 exam.get_id(),
889 &UserId::from_key(&target),850 &UserId::from_key(&target),
src/web/exams/questions.rsmodified+4 -17
@@ -1,5 +1,8 @@
1 use super::*;1 use super::*;
2 2
3+use crate::service::exam_attempt;
4+use crate::service::exam_attempt::question_of_exam;
5+
3 // ---- questions --------------------------------------------------------------6 // ---- questions --------------------------------------------------------------
4 // Teachers author the question list before the exam runs; it freezes the7 // Teachers author the question list before the exam runs; it freezes the
5 // moment anyone starts an attempt, so every student sits the same exam.8 // moment anyone starts an attempt, so every student sits the same exam.
@@ -138,7 +141,7 @@ pub(crate) async fn ensure_questions_editable(
138 exam: &ExamId,141 exam: &ExamId,
139 db: &Database,142 db: &Database,
140 ) -> Result<(), AppError> {143 ) -> Result<(), AppError> {
141- if ExamAttempt::any_for_exam(exam, db).await? {144+ if exam_attempt::any_for_exam(db, exam).await? {
142 return Err(AppError::Conflict(145 return Err(AppError::Conflict(
143 "cannot change questions after attempts have started",146 "cannot change questions after attempts have started",
144 ));147 ));
@@ -146,22 +149,6 @@ pub(crate) async fn ensure_questions_editable(
146 Ok(())149 Ok(())
147 }150 }
148 151
149-/// The question, provided it belongs to `exam` — a qid under someone else's
150-/// exam is a plain 404, not a leak.
151-pub(crate) async fn question_of_exam(
152- exam: &ExamId,
153- qid: &str,
154- db: &Database,
155-) -> Result<ExamQuestion, AppError> {
156- let question = ExamQuestion::read(&ExamQuestionId::from_key(qid), db)
157- .await?
158- .ok_or(AppError::NotFound)?;
159- if question.get_exam() != exam {
160- return Err(AppError::NotFound);
161- }
162- Ok(question)
163-}
164-
165 /// The question's option named by `choice_id` — a 400 for a text question or an152 /// The question's option named by `choice_id` — a 400 for a text question or an
166 /// id the question doesn't have, so an option picture can only ever be153 /// id the question doesn't have, so an option picture can only ever be
167 /// addressed through an option that exists.154 /// addressed through an option that exists.
src/web/exams/review.rsmodified+8 -3
@@ -1,5 +1,10 @@
1 use super::*;1 use super::*;
2 2
3+use crate::domain::exam_attempt::AttemptStatus;
4+use crate::service::exam_attempt::{
5+ course_of, list_for_user, list_unfinished_for_user, question_of_exam,
6+};
7+
3 // ---- per-attempt history ----------------------------------------------------8 // ---- per-attempt history ----------------------------------------------------
4 // The grading views above show the latest sitting; these expose every prior9 // The grading views above show the latest sitting; these expose every prior
5 // sitting a re-taking student left behind. Same wall as grading: teacher+ who10 // sitting a re-taking student left behind. Same wall as grading: teacher+ who
@@ -210,7 +215,7 @@ pub(crate) async fn reviewable_exam(
210 if !exam.get_allow_review() {215 if !exam.get_allow_review() {
211 return Err(AppError::Forbidden("review not enabled for this exam"));216 return Err(AppError::Forbidden("review not enabled for this exam"));
212 }217 }
213- let attempts = ExamAttempt::list_for_user(exam.get_id(), user.get_id(), &st.db).await?;218+ let attempts = list_for_user(&st.db, exam.get_id(), user.get_id()).await?;
214 let now = Timestamp::now();219 let now = Timestamp::now();
215 if attempts220 if attempts
216 .first()221 .first()
@@ -221,7 +226,7 @@ pub(crate) async fn reviewable_exam(
221 ));226 ));
222 }227 }
223 // The same three conditions `POST /exams/{id}/attempt` starts a sitting228 // The same three conditions `POST /exams/{id}/attempt` starts a sitting
224- // under (`ensure_sittable` + the window + `ExamAttempt::start`'s limit229+ // under (`ensure_sittable` + the window + `exam_attempt::start`'s limit
225 // check), minus the caller's role and enrollment: those bar the sitting230 // check), minus the caller's role and enrollment: those bar the sitting
226 // without making the key any safer to hand out, and a student dropped from231 // without making the key any safer to hand out, and a student dropped from
227 // the course after being marked should still read their own review back.232 // the course after being marked should still read their own review back.
@@ -262,7 +267,7 @@ async fn live_elsewhere(
262 ) -> Result<HashSet<String>, AppError> {267 ) -> Result<HashSet<String>, AppError> {
263 let now = Timestamp::now();268 let now = Timestamp::now();
264 let mut live = Vec::new();269 let mut live = Vec::new();
265- for attempt in ExamAttempt::list_unfinished_for_user(user.get_id(), &st.db).await? {270+ for attempt in list_unfinished_for_user(&st.db, user.get_id()).await? {
266 let Some(other) = Exam::read(attempt.get_exam(), &st.db).await? else {271 let Some(other) = Exam::read(attempt.get_exam(), &st.db).await? else {
267 continue;272 continue;
268 };273 };
src/web/homework.rsmodified+3 -3
@@ -46,7 +46,7 @@ use super::{
46 46
47 /// Serializes the homework subsystem's cross-record check-then-writes, which47 /// Serializes the homework subsystem's cross-record check-then-writes, which
48 /// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as48 /// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as
49-/// [`crate::web::exams::EXAM_LOCK`]. Every lease below is held across the49+/// [`crate::service::exam_attempt::EXAM_LOCK`]. Every lease below is held across the
50 /// database write it guards, so within this one process it does order a full50 /// database write it guards, so within this one process it does order a full
51 /// round trip — but the freeze no longer *rests* on that: a graded submission51 /// round trip — but the freeze no longer *rests* on that: a graded submission
52 /// used to stay unedited only because the "no grade yet" read and the write it52 /// used to stay unedited only because the "no grade yet" read and the write it
@@ -476,7 +476,7 @@ async fn delete_homework(
476 }476 }
477 477
478 /// A 403 unless `user` is enrolled in `course` — the homework twin of the exam478 /// A 403 unless `user` is enrolled in `course` — the homework twin of the exam
479-/// sitting wall ([`super::exams::ensure_enrolled`], which is `Exam`-shaped).479+/// sitting wall ([`crate::service::exam_attempt::ensure_enrolled`], which is `Exam`-shaped).
480 /// Submitting is course content, so leaving the course closes it; re-checked on480 /// Submitting is course content, so leaving the course closes it; re-checked on
481 /// every submission and file write, so an unenrollment mid-task bites the next.481 /// every submission and file write, so an unenrollment mid-task bites the next.
482 async fn ensure_enrolled(course: &CourseId, user: &UserId, db: &Database) -> Result<(), AppError> {482 async fn ensure_enrolled(course: &CourseId, user: &UserId, db: &Database) -> Result<(), AppError> {
@@ -495,7 +495,7 @@ async fn ensure_enrolled(course: &CourseId, user: &UserId, db: &Database) -> Res
495 /// 1. Exact `Student` on the *live* role. Teachers assign homework, they never495 /// 1. Exact `Student` on the *live* role. Teachers assign homework, they never
496 /// hand it in; the `RequireStudent` extractor's ≥Student would wave a496 /// hand it in; the `RequireStudent` extractor's ≥Student would wave a
497 /// promoted teacher through, so this checks the role `CurrentUser` read for497 /// promoted teacher through, so this checks the role `CurrentUser` read for
498-/// this very request — the same reasoning as [`super::exams::ensure_student`].498+/// this very request — the same reasoning as [`crate::service::exam_attempt::ensure_student`].
499 /// 2. Current enrollment in the course.499 /// 2. Current enrollment in the course.
500 /// 3. The audience check: a student a subset homework does not name gets a 404,500 /// 3. The audience check: a student a subset homework does not name gets a 404,
501 /// never a 403, so a subset assignment never leaks to those left out (the501 /// never a 403, so a subset assignment never leaks to those left out (the
tests/integration.rsmodified+4 -16
@@ -15,6 +15,7 @@ use hezarfen_backend::constant::{
15 BANK_VISIBILITY_SCHOOL, MAX_BOARD_STROKES, MAX_BOARDS_PER_CREATOR, MAX_COURSE_NOTE_FILES,15 BANK_VISIBILITY_SCHOOL, MAX_BOARD_STROKES, MAX_BOARDS_PER_CREATOR, MAX_COURSE_NOTE_FILES,
16 MAX_EPOCH_STROKES, MAX_FEE_PLAN_ASSIGN_STUDENTS,16 MAX_EPOCH_STROKES, MAX_FEE_PLAN_ASSIGN_STUDENTS,
17 };17 };
18+use hezarfen_backend::db::exam_attempt::any_for_exam;
18 use hezarfen_backend::db::session;19 use hezarfen_backend::db::session;
19 use hezarfen_backend::domain::board::{Board, BoardId};20 use hezarfen_backend::domain::board::{Board, BoardId};
20 use hezarfen_backend::domain::board_stroke::{BoardStroke, BoardStrokeId};21 use hezarfen_backend::domain::board_stroke::{BoardStroke, BoardStrokeId};
@@ -24,7 +25,6 @@ use hezarfen_backend::domain::course::CourseId;
24 use hezarfen_backend::domain::course_note::CourseNoteId;25 use hezarfen_backend::domain::course_note::CourseNoteId;
25 use hezarfen_backend::domain::course_note_file::CourseNoteFileId;26 use hezarfen_backend::domain::course_note_file::CourseNoteFileId;
26 use hezarfen_backend::domain::exam::ExamId;27 use hezarfen_backend::domain::exam::ExamId;
27-use hezarfen_backend::domain::exam_attempt::ExamAttempt;
28 use hezarfen_backend::domain::rag_output::RagOutput;28 use hezarfen_backend::domain::rag_output::RagOutput;
29 use hezarfen_backend::domain::timestamp::Timestamp;29 use hezarfen_backend::domain::timestamp::Timestamp;
30 use hezarfen_backend::domain::user::{Password, User, UserId, Username};30 use hezarfen_backend::domain::user::{Password, User, UserId, Username};
@@ -7887,11 +7887,7 @@ async fn attempts_cascade_with_exam_and_course_deletion() {
7887 )7887 )
7888 .await;7888 .await;
7889 assert_eq!(res.status, StatusCode::CREATED);7889 assert_eq!(res.status, StatusCode::CREATED);
7890- assert!(7890+ assert!(any_for_exam(&db, &ExamId::from_key(&exam)).await.unwrap());
7891- ExamAttempt::any_for_exam(&ExamId::from_key(&exam), &db)
7892- .await
7893- .unwrap()
7894- );
7895 let res = send(7891 let res = send(
7896 &app,7892 &app,
7897 "DELETE",7893 "DELETE",
@@ -7901,11 +7897,7 @@ async fn attempts_cascade_with_exam_and_course_deletion() {
7901 )7897 )
7902 .await;7898 .await;
7903 assert_eq!(res.status, StatusCode::NO_CONTENT);7899 assert_eq!(res.status, StatusCode::NO_CONTENT);
7904- assert!(7900+ assert!(!any_for_exam(&db, &ExamId::from_key(&exam)).await.unwrap());
7905- !ExamAttempt::any_for_exam(&ExamId::from_key(&exam), &db)
7906- .await
7907- .unwrap()
7908- );
7909 7901
7910 // Deleting the whole course cascades through its exams' attempts too.7902 // Deleting the whole course cascades through its exams' attempts too.
7911 let exam = scheduled_exam(&app, &teacher, &course, schedule).await;7903 let exam = scheduled_exam(&app, &teacher, &course, schedule).await;
@@ -7928,11 +7920,7 @@ async fn attempts_cascade_with_exam_and_course_deletion() {
7928 )7920 )
7929 .await;7921 .await;
7930 assert_eq!(res.status, StatusCode::NO_CONTENT);7922 assert_eq!(res.status, StatusCode::NO_CONTENT);
7931- assert!(7923+ assert!(!any_for_exam(&db, &ExamId::from_key(&exam)).await.unwrap());
7932- !ExamAttempt::any_for_exam(&ExamId::from_key(&exam), &db)
7933- .await
7934- .unwrap()
7935- );
7936 }7924 }
7937 7925
7938 /// An `open` exam is sittable anytime — no window, no deadline — and7926 /// An `open` exam is sittable anytime — no window, no deadline — and
tests/regress_course_delete.rsmodified+2 -2
@@ -28,9 +28,9 @@ use common::{
28 login_as, me_id, send, unenroll,28 login_as, me_id, send, unenroll,
29 };29 };
30 use hezarfen_backend::db::course;30 use hezarfen_backend::db::course;
31+use hezarfen_backend::db::exam_attempt::list_for_exam;
31 use hezarfen_backend::domain::course::CourseId;32 use hezarfen_backend::domain::course::CourseId;
32 use hezarfen_backend::domain::exam::ExamId;33 use hezarfen_backend::domain::exam::ExamId;
33-use hezarfen_backend::domain::exam_attempt::ExamAttempt;
34 use serde_json::json;34 use serde_json::json;
35 35
36 /// Delete `course` the way the handler would, minus its `EXAM_LOCK` lease.36 /// Delete `course` the way the handler would, minus its `EXAM_LOCK` lease.
@@ -257,7 +257,7 @@ async fn an_attempt_started_inside_a_course_delete_never_outlives_it() {
257 );257 );
258 // Stored state is the whole verdict; a response code is not evidence.258 // Stored state is the whole verdict; a response code is not evidence.
259 assert_eq!(259 assert_eq!(
260- ExamAttempt::list_for_exam(&ExamId::from_key(&exam), &db)260+ list_for_exam(&db, &ExamId::from_key(&exam))
261 .await261 .await
262 .unwrap()262 .unwrap()
263 .len(),263 .len(),
tests/regress_exam_delete.rsmodified+2 -2
@@ -18,8 +18,8 @@ mod common;
18 18
19 use axum::http::StatusCode;19 use axum::http::StatusCode;
20 use common::{app_and_db, create_exam_with, enroll, id_of, login_as, me_id, send};20 use common::{app_and_db, create_exam_with, enroll, id_of, login_as, me_id, send};
21+use hezarfen_backend::db::exam_attempt::list_for_exam;
21 use hezarfen_backend::domain::exam::ExamId;22 use hezarfen_backend::domain::exam::ExamId;
22-use hezarfen_backend::domain::exam_attempt::ExamAttempt;
23 use serde_json::json;23 use serde_json::json;
24 24
25 /// The delete is held open for a second *after* the exam row is gone but25 /// The delete is held open for a second *after* the exam row is gone but
@@ -122,7 +122,7 @@ async fn an_attempt_started_inside_a_delete_never_outlives_the_exam() {
122 122
123 // Stored state is the whole verdict; a response code is not evidence.123 // Stored state is the whole verdict; a response code is not evidence.
124 let id = ExamId::from_key(&exam);124 let id = ExamId::from_key(&exam);
125- sittings += ExamAttempt::list_for_exam(&id, &db).await.unwrap().len();125+ sittings += list_for_exam(&db, &id).await.unwrap().len();
126 }126 }
127 assert_eq!(sittings, 0, "a sitting outlived its exam");127 assert_eq!(sittings, 0, "a sitting outlived its exam");
128 }128 }