forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

exam_attempt.rs581 lines, 21.8 KiBHistoryRawDownload
1//! The `exam_attempt` table: sitting reads, the two field-scoped writes
2//! (`finished_at`, `left_at`), the guarded sitting create, and the freeze
3//! gate — the in-transaction check every exam-child write runs before it
4//! touches anything.
5
6use sqlx::PgConnection;
7
8use crate::database::{Database, tx_with_retry, unique_violation};
9use crate::db::cap::Claimed;
10use crate::domain::exam::{ExamId, ExamMode};
11use crate::domain::exam_attempt::{ExamAttempt, ExamAttemptId};
12use crate::domain::timestamp::Timestamp;
13use crate::domain::user::UserId;
14use crate::error::AppError;
15
16/// The 409 the freeze gate answers — the same one the handlers' pre-flight
17/// check ([`crate::service::exam_question::ensure_questions_editable`])
18/// answers, so a client cannot tell which of the two refused.
19fn frozen_error() -> AppError {
20 AppError::Conflict("cannot change questions after attempts have started")
21}
22
23/// The freeze gate, run inside a caller's transaction on that caller's own
24/// connection: take the exam row `FOR UPDATE`, then refuse unless the exam
25/// still exists and nobody has started an attempt.
26///
27/// This is the whole of the old `write_unfrozen` machinery — the
28/// `questions_frozen` THROW and the bump-and-restore existence touch — with
29/// Postgres doing the work the tricks stood in for. The row lock makes the
30/// check-and-write one unit against [`crate::db::exam::delete`] (which locks
31/// the same row before its cascade) and against a sitting create (whose
32/// guard below locks it too): a question edit can no longer sail past an
33/// attempt that started in the gate's gap, and a child whose exam died
34/// mid-flight finds no row here and is the same 404 the old `no_exam` THROW
35/// answered with. Real foreign keys retire the bump-and-restore: the child
36/// inserts themselves refuse a parent that is gone.
37pub(crate) async fn freeze_gate(conn: &mut PgConnection, exam: &ExamId) -> Result<(), AppError> {
38 let row = sqlx::query!(
39 r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#,
40 exam.uuid(),
41 )
42 .fetch_optional(&mut *conn)
43 .await?;
44 if row.is_none() {
45 return Err(AppError::NotFound);
46 }
47 let sat = sqlx::query!(
48 r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat"#,
49 exam.uuid(),
50 )
51 .fetch_one(&mut *conn)
52 .await?;
53 if sat.sat.unwrap_or(false) {
54 return Err(frozen_error());
55 }
56 Ok(())
57}
58
59/// Stamp the submission time. The caller has already checked the deadline
60/// and that the attempt isn't finished.
61///
62/// Writes *only* `finished_at`, for the mirror image of
63/// [`set_left`]'s reason: the submit path reads the attempt,
64/// then awaits its deadline and already-finished checks before writing, and
65/// the exam room stamps or clears `left_at` on the same row from a socket.
66/// A whole-row write from the pre-read snapshot would carry its stale
67/// `left_at` back over that stamp, erasing the recorded walk-out.
68pub async fn finish(db: &Database, attempt: ExamAttempt) -> Result<ExamAttempt, AppError> {
69 let id = attempt.get_id();
70 let updated = sqlx::query_as!(
71 ExamAttempt,
72 r#"UPDATE exam_attempt SET finished_at = $1
73 WHERE exam = $2 AND app_user = $3 AND seq = $4
74 RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq,
75 started_at AS "started_at: Timestamp",
76 finished_at AS "finished_at: Timestamp",
77 left_at AS "left_at: Timestamp""#,
78 Timestamp::now().as_millis(),
79 id.exam.uuid(),
80 id.user.uuid(),
81 id.seq,
82 )
83 .fetch_optional(db)
84 .await?;
85 updated.ok_or(AppError::NotFound)
86}
87
88/// Stamp (or clear) the walked-out marker. The exam room sets it when the
89/// student's socket closes mid-attempt and clears it when they come back.
90///
91/// Writes *only* the `left_at` field (never the whole row): the room's
92/// teardown reads the attempt, sees it in progress, then stamps here — and
93/// a submission that lands in that gap must survive. A whole-row write from
94/// the pre-read snapshot would carry its blank `finished_at` back over the
95/// fresh submission, silently un-submitting the exam (and, with
96/// `allow_rejoin` off, locking the student out).
97pub async fn set_left(
98 db: &Database,
99 attempt: ExamAttempt,
100 left_at: Option<Timestamp>,
101) -> Result<ExamAttempt, AppError> {
102 let id = attempt.get_id();
103 let updated = sqlx::query_as!(
104 ExamAttempt,
105 r#"UPDATE exam_attempt SET left_at = $1
106 WHERE exam = $2 AND app_user = $3 AND seq = $4
107 RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq,
108 started_at AS "started_at: Timestamp",
109 finished_at AS "finished_at: Timestamp",
110 left_at AS "left_at: Timestamp""#,
111 left_at.map(|at| at.as_millis()),
112 id.exam.uuid(),
113 id.user.uuid(),
114 id.seq,
115 )
116 .fetch_optional(db)
117 .await?;
118 updated.ok_or(AppError::NotFound)
119}
120
121/// Stamp `left_at` on one sitting, but only while it is genuinely in
122/// progress: nothing stamped yet, nothing submitted, and the exam's *live*
123/// schedule has not run past the sitting's deadline. One conditional
124/// statement — the exam-room teardown's whole stamp, with the re-derive
125/// [`crate::domain::exam_attempt::ExamAttempt::status`] used to do folded
126/// into the `WHERE` (joined to `exam` so a deleted exam's sitting is simply
127/// not stamped, and concurrent last-outs are harmless: only the first finds
128/// `left_at IS NULL`).
129pub async fn stamp_left_if_running(
130 db: &Database,
131 attempt_id: &ExamAttemptId,
132 now: Timestamp,
133) -> Result<(), AppError> {
134 sqlx::query!(
135 r#"UPDATE exam_attempt a SET left_at = $4
136 FROM exam e
137 WHERE e.id = a.exam
138 AND a.exam = $1 AND a.app_user = $2 AND a.seq = $3
139 AND a.left_at IS NULL AND a.finished_at IS NULL
140 AND (e.duration_ms IS NULL OR $4 < a.started_at + e.duration_ms)
141 AND (e.duration_ms IS NOT NULL OR e.ends_at IS NULL OR $4 < e.ends_at)"#,
142 attempt_id.exam.uuid(),
143 attempt_id.user.uuid(),
144 attempt_id.seq,
145 now.as_millis(),
146 )
147 .execute(db)
148 .await?;
149 Ok(())
150}
151
152/// One sitting by id — the exam room re-reads its own attempt this way,
153/// so a retake started elsewhere can never be mistaken for it.
154pub async fn read(db: &Database, id: &ExamAttemptId) -> Result<Option<ExamAttempt>, AppError> {
155 Ok(sqlx::query_as!(
156 ExamAttempt,
157 r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq,
158 started_at AS "started_at: Timestamp",
159 finished_at AS "finished_at: Timestamp",
160 left_at AS "left_at: Timestamp"
161 FROM exam_attempt
162 WHERE exam = $1 AND app_user = $2 AND seq = $3"#,
163 id.exam.uuid(),
164 id.user.uuid(),
165 id.seq,
166 )
167 .fetch_optional(db)
168 .await?)
169}
170
171/// The student's current sitting — the highest `seq` for the pair. All
172/// reads that used to mean "the attempt" mean this now.
173pub async fn read_latest_for_user(
174 db: &Database,
175 exam: &ExamId,
176 user: &UserId,
177) -> Result<Option<ExamAttempt>, AppError> {
178 Ok(sqlx::query_as!(
179 ExamAttempt,
180 r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq,
181 started_at AS "started_at: Timestamp",
182 finished_at AS "finished_at: Timestamp",
183 left_at AS "left_at: Timestamp"
184 FROM exam_attempt
185 WHERE exam = $1 AND app_user = $2
186 ORDER BY seq DESC
187 LIMIT 1"#,
188 exam.uuid(),
189 user.uuid(),
190 )
191 .fetch_optional(db)
192 .await?)
193}
194
195/// Every sitting of `user` at `exam`, newest first.
196pub async fn list_for_user(
197 db: &Database,
198 exam: &ExamId,
199 user: &UserId,
200) -> Result<Vec<ExamAttempt>, AppError> {
201 Ok(sqlx::query_as!(
202 ExamAttempt,
203 r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq,
204 started_at AS "started_at: Timestamp",
205 finished_at AS "finished_at: Timestamp",
206 left_at AS "left_at: Timestamp"
207 FROM exam_attempt
208 WHERE exam = $1 AND app_user = $2
209 ORDER BY seq DESC"#,
210 exam.uuid(),
211 user.uuid(),
212 )
213 .fetch_all(db)
214 .await?)
215}
216
217/// Every sitting of `user` nobody has submitted yet, across all exams. Only
218/// the *candidates* for "in progress": a deadline comes off the exam's live
219/// schedule, so the caller still judges [`ExamAttempt::status`] per exam rather
220/// than re-spelling that rule in SQL.
221pub async fn list_unfinished_for_user(
222 db: &Database,
223 user: &UserId,
224) -> Result<Vec<ExamAttempt>, AppError> {
225 Ok(sqlx::query_as!(
226 ExamAttempt,
227 r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq,
228 started_at AS "started_at: Timestamp",
229 finished_at AS "finished_at: Timestamp",
230 left_at AS "left_at: Timestamp"
231 FROM exam_attempt
232 WHERE app_user = $1 AND finished_at IS NULL
233 ORDER BY started_at, exam"#,
234 user.uuid(),
235 )
236 .fetch_all(db)
237 .await?)
238}
239
240pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<ExamAttempt>, AppError> {
241 Ok(sqlx::query_as!(
242 ExamAttempt,
243 r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq,
244 started_at AS "started_at: Timestamp",
245 finished_at AS "finished_at: Timestamp",
246 left_at AS "left_at: Timestamp"
247 FROM exam_attempt
248 WHERE exam = $1
249 ORDER BY started_at DESC, seq DESC"#,
250 exam.uuid(),
251 )
252 .fetch_all(db)
253 .await?)
254}
255
256/// Whether anyone has started this exam — the gate that freezes `mode`
257/// edits once an attempt exists.
258pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result<bool, AppError> {
259 let row = sqlx::query!(
260 r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat"#,
261 exam.uuid(),
262 )
263 .fetch_one(db)
264 .await?;
265 Ok(row.sat.unwrap_or(false))
266}
267
268/// The sitting-create guard: the exam row locked `FOR UPDATE` and
269/// re-judged *inside the inserting transaction* — draft (a 404, a draft is
270/// invisible to students), no mode (a 409: visible, nothing to sit), the
271/// window not yet open, the window already closed. This is what the old
272/// writer lease `EXAM_LOCK` used to buy the sittable/window gates: they are
273/// now judged against the locked row the attempt lands under, so a mode
274/// change or re-draft cannot slip between a gate and the insert. The
275/// refusal texts are [`crate::service::exam_attempt`]'s own — the same
276/// words that pre-flight answers, so a client cannot tell which fired.
277pub(crate) async fn guard_start(
278 conn: &mut PgConnection,
279 exam: &ExamId,
280 now: Timestamp,
281) -> Result<(), AppError> {
282 let row = sqlx::query!(
283 r#"SELECT draft AS "draft: bool", mode AS "mode: ExamMode",
284 starts_at AS "starts_at: Timestamp",
285 ends_at AS "ends_at: Timestamp"
286 FROM exam WHERE id = $1 FOR UPDATE"#,
287 exam.uuid(),
288 )
289 .fetch_optional(&mut *conn)
290 .await?;
291 let Some(row) = row else {
292 return Err(AppError::NotFound);
293 };
294 if row.draft {
295 return Err(AppError::NotFound);
296 }
297 if row.mode.is_none() {
298 return Err(AppError::Conflict(
299 "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)",
300 ));
301 }
302 if row.starts_at.is_some_and(|starts_at| now < starts_at) {
303 return Err(AppError::Conflict("the exam has not started yet"));
304 }
305 if row.ends_at.is_some_and(|ends_at| now >= ends_at) {
306 return Err(AppError::Conflict("the exam has already ended"));
307 }
308 Ok(())
309}
310
311/// Insert the sitting row, claiming the student's `exam_sat_total` in the
312/// same statement when — and only when — this is a first sitting (`seq ==
313/// 1`): that counter is *exams sat*, not sittings, and a retake counts
314/// nothing. The claim-CTE recipe ([`cap`]): bump the counter row, insert
315/// the child only if the bump landed, and let the sitting's natural
316/// composite primary key (`exam_attempt_exam_user_seq`) answer "another
317/// writer started this very sitting first" as `Claimed::Duplicate`. The
318/// bump rides the insert's own transaction, so a refused insert takes its
319/// increment straight back.
320///
321/// `Claimed::Full` here can only mean the student's account row is missing
322/// — nothing caps sittings — which the caller surfaces as its own internal.
323pub(crate) async fn create_in(
324 conn: &mut PgConnection,
325 attempt: &ExamAttempt,
326 count_sitting: bool,
327) -> Result<Claimed<ExamAttempt>, AppError> {
328 let bump = i64::from(count_sitting);
329 let created = sqlx::query_as!(
330 ExamAttempt,
331 r#"WITH seat AS (
332 UPDATE app_user SET exam_sat_total = app_user.exam_sat_total + $4
333 WHERE id = $2
334 RETURNING 1)
335 INSERT INTO exam_attempt (exam, app_user, seq, started_at, finished_at, left_at)
336 SELECT $1, $2, $3, $5, NULL, NULL WHERE EXISTS (SELECT 1 FROM seat)
337 RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq,
338 started_at AS "started_at: Timestamp",
339 finished_at AS "finished_at: Timestamp",
340 left_at AS "left_at: Timestamp""#,
341 attempt.exam.uuid(),
342 attempt.user.uuid(),
343 attempt.seq,
344 bump,
345 attempt.started_at.as_millis(),
346 )
347 .fetch_optional(&mut *conn)
348 .await;
349 match created {
350 Err(err) if unique_violation(&err) == Some("exam_attempt_exam_user_seq") => {
351 Ok(Claimed::Duplicate)
352 }
353 Err(err) => Err(err.into()),
354 Ok(None) => Ok(Claimed::Full),
355 Ok(Some(attempt)) => Ok(Claimed::Made(attempt)),
356 }
357}
358
359/// The sitting create as one transaction: [`guard_start`], then
360/// [`create_in`]. Retried while Postgres answers "contended"; a duplicate
361/// or a missing student row is a verdict, not a conflict, and is never
362/// re-sent.
363pub(crate) async fn create(
364 db: &Database,
365 attempt: &ExamAttempt,
366 count_sitting: bool,
367 now: Timestamp,
368) -> Result<Claimed<ExamAttempt>, AppError> {
369 let attempt = attempt.clone();
370 tx_with_retry(db, false, async move |conn| {
371 guard_start(conn, &attempt.exam, now).await?;
372 create_in(conn, &attempt, count_sitting).await
373 })
374 .await
375}
376
377#[cfg(test)]
378mod tests {
379 use super::*;
380 use crate::database::init_test_db;
381 use crate::domain::exam::{
382 Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,
383 };
384 use crate::domain::exam_question::{
385 ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec,
386 };
387 use crate::domain::settings::Settings;
388
389 /// An open exam with retakes allowed, plus one choice question — enough
390 /// rows to exercise the attempt lifecycle without the HTTP layer.
391 async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) {
392 let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
393 // The creator is a foreign key now: a real `app_user` row under the
394 // fixture's fixed key.
395 sqlx::query(
396 "INSERT INTO app_user (id, username, created_at) \
397 VALUES ($1, 'acdc-fixture', 0) ON CONFLICT DO NOTHING",
398 )
399 .bind(creator.uuid())
400 .execute(db)
401 .await
402 .unwrap();
403 // The instance and the term are foreign keys now: real rows the
404 // fixture mints.
405 let (instance, _course) = crate::db::course::a_test_instance(db).await;
406 let term = crate::db::term::a_test_term(db).await;
407 let kinds = Settings::defaults().get_exam_kinds().to_vec();
408 let exam = crate::db::exam::create(
409 db,
410 &creator,
411 &instance,
412 &term,
413 ExamTitle::try_new("practice").unwrap(),
414 ExamDescription::try_new("").unwrap(),
415 ExamKind::try_new("yazili", &kinds).unwrap(),
416 ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None)
417 .unwrap(),
418 ExamAttemptLimit::try_new(max_attempts).unwrap(),
419 true,
420 false,
421 false,
422 )
423 .await
424 .unwrap();
425 let spec = QuestionSpec::try_new(
426 QuestionKind::try_new("choice").unwrap(),
427 Some(vec![
428 ChoiceInput {
429 id: Some("a".into()),
430 text: "5".into(),
431 },
432 ChoiceInput {
433 id: Some("b".into()),
434 text: "6".into(),
435 },
436 ]),
437 Some("b".into()),
438 &[],
439 )
440 .unwrap();
441 // A real subject row, not a minted id: a question claims a reference on
442 // its subject and is refused if that subject does not exist.
443 let subject = crate::db::subject::create(
444 db,
445 &crate::db::course::a_test_course(db).await,
446 crate::domain::subject::SubjectName::try_new("topic").unwrap(),
447 crate::domain::subject::SubjectDescription::try_new("").unwrap(),
448 )
449 .await
450 .unwrap();
451 let question = crate::db::exam_question::create(
452 db,
453 exam.get_id(),
454 *subject.get_id(),
455 crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(),
456 QuestionPoints::try_new(5).unwrap(),
457 spec,
458 )
459 .await
460 .unwrap();
461 (exam, question)
462 }
463
464 /// A real user row: the sitting counter lives on it, and the claim that
465 /// rides the attempt's create has nothing to write to without one.
466 async fn student(db: &Database) -> UserId {
467 *crate::db::user::create(
468 db,
469 crate::domain::user::Username::try_new("ogrenci").unwrap(),
470 None,
471 )
472 .await
473 .unwrap()
474 .get_id()
475 }
476
477 #[tokio::test]
478 async fn submitting_never_reverts_a_walk_out_that_raced_it() {
479 let (db, _leases) = init_test_db().await;
480 let (exam, _question) = open_exam_with_question(&db, 1).await;
481 let user = student(&db).await;
482
483 let (attempt, _) = crate::service::exam_attempt::start(&db, &exam, &user)
484 .await
485 .unwrap();
486
487 // The REST submit path reads the attempt, then checks the deadline and
488 // the already-finished guard — several awaits before it writes.
489 let stale = read(&db, &attempt.get_id())
490 .await
491 .unwrap()
492 .expect("attempt exists");
493 assert!(stale.get_left_at().is_none());
494
495 // In that gap the exam room's teardown stamps the walk-out (or a join
496 // clears it) — a field-scoped write to the same row.
497 set_left(
498 &db,
499 read(&db, &attempt.get_id())
500 .await
501 .unwrap()
502 .expect("attempt exists"),
503 Some(Timestamp::now()),
504 )
505 .await
506 .unwrap();
507
508 // The submit now writes from its stale snapshot. It owns `finished_at`
509 // and nothing else: carrying the snapshot's blank `left_at` back over
510 // the fresh stamp erases the recorded walk-out.
511 let finished = finish(&db, stale).await.unwrap();
512 assert!(finished.get_finished_at().is_some());
513
514 let after = read(&db, &attempt.get_id())
515 .await
516 .unwrap()
517 .expect("attempt still exists");
518 assert!(
519 after.get_left_at().is_some(),
520 "submitting must not revert a walk-out stamp that raced it"
521 );
522 assert!(after.get_finished_at().is_some(), "the submission stands");
523 }
524
525 #[tokio::test]
526 async fn stamping_left_never_reverts_a_submission() {
527 let (db, _leases) = init_test_db().await;
528 let (exam, _question) = open_exam_with_question(&db, 1).await;
529 let user = student(&db).await;
530
531 // The student is sitting the exam.
532 let (attempt, _) = crate::service::exam_attempt::start(&db, &exam, &user)
533 .await
534 .unwrap();
535 assert_eq!(attempt.get_seq(), 1);
536
537 // The exam-room teardown reads the attempt while it is still in
538 // progress (`stamp_left`'s read) — a snapshot with `finished_at` unset.
539 let stale = read(&db, &attempt.get_id())
540 .await
541 .unwrap()
542 .expect("attempt exists");
543 assert!(stale.get_finished_at().is_none());
544 let finished = finish(
545 &db,
546 read(&db, &attempt.get_id())
547 .await
548 .unwrap()
549 .expect("attempt exists"),
550 )
551 .await
552 .unwrap();
553 assert!(finished.get_finished_at().is_some());
554
555 // Now the last socket's teardown stamps `left_at` from its stale
556 // snapshot. Stamping the walk-out must touch only `left_at` — it must
557 // not carry the snapshot's blank `finished_at` back over the fresh
558 // submission, or the student's submitted exam silently reopens (and,
559 // with `allow_rejoin` off, locks them out of a room they left after
560 // finishing).
561 set_left(&db, stale, Some(Timestamp::now())).await.unwrap();
562
563 let after = read(&db, &attempt.get_id())
564 .await
565 .unwrap()
566 .expect("attempt still exists");
567 assert!(
568 after.get_finished_at().is_some(),
569 "stamping left_at must not revert a submission that raced it"
570 );
571 assert!(
572 after.get_left_at().is_some(),
573 "the walk-out is still recorded"
574 );
575 assert_eq!(
576 after.status(&exam, Timestamp::now()),
577 crate::domain::exam_attempt::AttemptStatus::Submitted,
578 "the attempt stays submitted"
579 );
580 }
581}