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.rs1945 lines, 79.3 KiBHistoryRawDownload
1//! The `exam` table: row reads and listings, the gated create that refuses a
2//! course that is gone, the compare-and-set every PATCH writes through, and
3//! the cascading delete. The PATCH re-derive lives in [`crate::service::exam`].
4
5use sqlx::PgConnection;
6
7use crate::database::{Database, foreign_key_violation, tx_with_retry};
8use crate::db::page::{PagedList, Param};
9use crate::domain::class_course::ClassCourseId;
10use crate::domain::course::CourseId;
11use crate::domain::exam::{
12 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode,
13 ExamSchedule, ExamTitle, redraft_error,
14};
15use crate::domain::term::TermId;
16use crate::domain::timestamp::Timestamp;
17use crate::domain::user::UserId;
18use crate::error::AppError;
19
20#[expect(
21 clippy::too_many_arguments,
22 reason = "mirrors the sibling entities' create(field, field, ..) shape"
23)]
24pub async fn create(
25 db: &Database,
26 creator: &UserId,
27 class_course: &ClassCourseId,
28 term: &TermId,
29 title: ExamTitle,
30 description: ExamDescription,
31 kind: ExamKind,
32 schedule: ExamSchedule,
33 max_attempts: ExamAttemptLimit,
34 allow_rejoin: bool,
35 allow_review: bool,
36 draft: bool,
37) -> Result<Exam, AppError> {
38 // A missing parent is refused by the real foreign keys: an instance, a
39 // term or a creator that is gone is `SQLSTATE 23503`, and this call
40 // site's parent-gone answer is the same `NotFound` the old
41 // existence-proof touch answered with.
42 //
43 // The term is *claimed* in the same statement as the row (`exam_count`
44 // +1, a conditional write on the term row), the shape the old course
45 // create used against `term.course_count`: the count is what the term's
46 // own delete guard reads, and claim-and-insert in one CTE means no crash
47 // can leave one half without the other.
48 //
49 // The owner's `exam_audience` row is written in the same transaction,
50 // *always*: the audience is what every listing reads through, so an exam
51 // with no audience row would be invisible to its own instance. A shared
52 // exam is extra audience rows on this one exam (D2), never a second
53 // shape.
54 let id = ExamId::generate();
55 let creator = *creator;
56 let class_course = class_course.clone();
57 // `TermId` is `Copy`: one copy here, and the per-attempt closure below
58 // re-yields values rather than clones.
59 let term = *term;
60 // The binds are hoisted to owned values so the closure below only has to
61 // clone them per attempt: the write itself is a named future, for the
62 // reason [`insert_in`] gives.
63 let title_text = title.as_str().to_string();
64 let description_text = description.as_str().to_string();
65 let kind_text = kind.as_str().to_string();
66 let mode_text = schedule.mode.as_ref().map(|mode| mode.as_str().to_string());
67 let starts_at = schedule.starts_at.map(|at| at.as_millis());
68 let ends_at = schedule.ends_at.map(|at| at.as_millis());
69 let duration_ms = schedule.duration_ms.map(|duration| duration.as_millis());
70 let max_attempts = max_attempts.as_i64();
71 let created = tx_with_retry(db, false, async move |tx| {
72 insert_in(
73 tx,
74 id.clone(),
75 creator,
76 class_course.clone(),
77 term,
78 title_text.clone(),
79 description_text.clone(),
80 kind_text.clone(),
81 mode_text.clone(),
82 starts_at,
83 ends_at,
84 duration_ms,
85 max_attempts,
86 allow_rejoin,
87 allow_review,
88 draft,
89 )
90 .await
91 })
92 .await?;
93 Ok(created)
94}
95
96/// The claim, the row and its audience row, on one connection — [`create`]'s
97/// body as a *named* future.
98///
99/// Named, and taking owned values, because the anonymous `async move |tx|`
100/// closure does not work here: with this many binds, rustc cannot prove the
101/// closure's future is `Send` under [`tx_with_retry`]'s
102/// `AsyncFnMut(&mut PgConnection)` higher-ranked bound, so every axum handler
103/// that awaits [`create`] fails with "implementation of `Send` is not general
104/// enough" pointing at its `routes!` entry. A named `async fn` has a concrete
105/// future type rustc can check, exactly as
106/// [`crate::db::answer_image::upsert_in`] does for the same reason.
107///
108/// Everything it decides is the closure's own: a claim that matched no term
109/// row is [`crate::domain::term::gone_error`], any other foreign key is the
110/// parent-gone `NotFound`, and the audience row is written in the same
111/// transaction as the row it names.
112#[expect(
113 clippy::too_many_arguments,
114 reason = "the create's own field list, spelled once for the named future"
115)]
116pub(crate) async fn insert_in(
117 tx: &mut PgConnection,
118 id: ExamId,
119 creator: UserId,
120 class_course: ClassCourseId,
121 term: TermId,
122 title: String,
123 description: String,
124 kind: String,
125 mode: Option<String>,
126 starts_at: Option<i64>,
127 ends_at: Option<i64>,
128 duration_ms: Option<i64>,
129 max_attempts: i64,
130 allow_rejoin: bool,
131 allow_review: bool,
132 draft: bool,
133) -> Result<Exam, AppError> {
134 let written = sqlx::query_as!(
135 Exam,
136 r#"WITH room AS (
137 UPDATE term SET exam_count = exam_count + 1
138 WHERE id = $3
139 RETURNING 1)
140 INSERT INTO exam (id, creator, class_course, term, title, description, kind, mode,
141 starts_at, ends_at, duration_ms, max_attempts,
142 allow_rejoin, allow_review, draft)
143 SELECT $1, $2, $4, $3, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15
144 WHERE EXISTS (SELECT 1 FROM room)
145 RETURNING id AS "id: ExamId", creator AS "creator: UserId",
146 class_course AS "class_course: ClassCourseId",
147 term AS "term: TermId", title AS "title: ExamTitle",
148 description AS "description: ExamDescription",
149 kind AS "kind: ExamKind", mode AS "mode: ExamMode",
150 starts_at AS "starts_at: Timestamp",
151 ends_at AS "ends_at: Timestamp",
152 duration_ms AS "duration_ms: ExamDuration",
153 max_attempts AS "max_attempts: ExamAttemptLimit",
154 allow_rejoin, allow_review, draft"#,
155 id.uuid(),
156 creator.uuid(),
157 term.uuid(),
158 class_course.uuid(),
159 title.as_str(),
160 description.as_str(),
161 kind.as_str(),
162 mode.as_deref(),
163 starts_at,
164 ends_at,
165 duration_ms,
166 max_attempts,
167 allow_rejoin,
168 allow_review,
169 draft,
170 )
171 .fetch_optional(&mut *tx)
172 .await;
173 let exam = match written {
174 Ok(Some(exam)) => exam,
175 // The conditional claim matched no term row: the term is gone.
176 Ok(None) => return Err(crate::domain::term::gone_error()),
177 Err(err) if foreign_key_violation(&err) => return Err(AppError::NotFound),
178 Err(err) => return Err(err.into()),
179 };
180 sqlx::query!(
181 r#"INSERT INTO exam_audience (exam, class_course) VALUES ($1, $2)"#,
182 exam.id.uuid(),
183 exam.class_course.uuid(),
184 )
185 .execute(&mut *tx)
186 .await?;
187 Ok(exam)
188}
189
190pub async fn read(db: &Database, id: &ExamId) -> Result<Option<Exam>, AppError> {
191 Ok(sqlx::query_as!(
192 Exam,
193 r#"SELECT id AS "id: ExamId", creator AS "creator: UserId",
194 class_course AS "class_course: ClassCourseId", term AS "term: TermId",
195 title AS "title: ExamTitle", description AS "description: ExamDescription",
196 kind AS "kind: ExamKind", mode AS "mode: ExamMode",
197 starts_at AS "starts_at: Timestamp",
198 ends_at AS "ends_at: Timestamp",
199 duration_ms AS "duration_ms: ExamDuration",
200 max_attempts AS "max_attempts: ExamAttemptLimit",
201 allow_rejoin, allow_review, draft
202 FROM exam WHERE id = $1"#,
203 id.uuid(),
204 )
205 .fetch_optional(db)
206 .await?)
207}
208
209/// The schedule window and the page of [`list_windowed`], in one struct —
210/// the fields outgrew a readable argument list. The four optional bounds
211/// are [`crate::web::page::WindowParams`]'s schedule window, validated
212/// upstream. The default is the windowless, unpaged read: all four bounds
213/// absent keeps `id DESC` (newest first); any bound set drops window-less
214/// exams (no `mode` → both schedule columns null, so every predicate is
215/// `NULL`-rejecting) and flips the order to ascending by schedule —
216/// `starts_at`, falling back to `ends_at`, ties by id — the order
217/// `WindowParams::apply` used to produce in Rust.
218#[derive(Default)]
219pub struct WindowedListParams {
220 pub starts_after: Option<i64>,
221 pub ends_after: Option<i64>,
222 pub starts_before: Option<i64>,
223 pub ends_before: Option<i64>,
224 /// `None` = the full list.
225 pub limit: Option<i64>,
226 pub offset: i64,
227}
228
229/// The exams list behind `GET /exams`, paged by the database — visibility,
230/// the draft rule, the schedule window, the `LIMIT/OFFSET` and the `total`
231/// count all share one `WHERE` per branch, so a filtered page never decodes
232/// the exams it skips.
233///
234/// `visible`/`managed` are the non-manager read: the exams addressed to any
235/// of `visible` (through `exam_audience`, deduplicated — a shared exam is one
236/// exam), with `NOT draft OR owner ∈ managed`, today's rule unchanged — a
237/// draft shows only to someone who manages its owner instance. Both `None` is
238/// the manager+ whole-table read.
239pub async fn list_windowed(
240 db: &Database,
241 visible: Option<&[ClassCourseId]>,
242 managed: Option<&[ClassCourseId]>,
243 params: WindowedListParams,
244) -> Result<(Vec<Exam>, i64), AppError> {
245 let WindowedListParams {
246 starts_after,
247 ends_after,
248 starts_before,
249 ends_before,
250 limit,
251 offset,
252 } = params;
253 // Window predicates and binds move together: each bound appends its
254 // predicate with the placeholder number its bind position lands on. The
255 // two visibility binds of the non-manager branch claim $1 and $2, so the
256 // window numbering continues after them.
257 let base = usize::from(visible.is_some()) * 2;
258 let mut conds: Vec<String> = Vec::new();
259 let mut bounds: Vec<i64> = Vec::new();
260 let mut bound = |column: &str, op: &str, value: Option<i64>| {
261 if let Some(value) = value {
262 conds.push(format!("{column} {op} ${}", base + bounds.len() + 1));
263 bounds.push(value);
264 }
265 };
266 bound("starts_at", ">", starts_after);
267 bound("starts_at", "<", starts_before);
268 bound("COALESCE(ends_at, starts_at)", ">", ends_after);
269 bound("COALESCE(ends_at, starts_at)", "<", ends_before);
270 let window = if conds.is_empty() {
271 String::new()
272 } else {
273 format!(" AND {}", conds.join(" AND "))
274 };
275 let (from_where, mut binds): (String, Vec<Param>) = match visible {
276 None => (
277 if conds.is_empty() {
278 "exam".to_owned()
279 } else {
280 format!("exam WHERE {}", conds.join(" AND "))
281 },
282 Vec::new(),
283 ),
284 Some(visible) => {
285 let managed = managed.expect("visible and managed travel together");
286 (
287 format!(
288 "(SELECT DISTINCT ON (e.id) e.* \
289 FROM exam e \
290 JOIN exam_audience a ON a.exam = e.id \
291 WHERE a.class_course = ANY($1::uuid[]) \
292 AND (NOT e.draft OR e.class_course = ANY($2::uuid[])){window} \
293 ORDER BY e.id)"
294 ),
295 vec![
296 Param::Texts(visible.iter().map(ClassCourseId::key).collect()),
297 Param::Texts(managed.iter().map(ClassCourseId::key).collect()),
298 ],
299 )
300 }
301 };
302 let order = if conds.is_empty() {
303 "ORDER BY id DESC"
304 } else {
305 "ORDER BY COALESCE(starts_at, ends_at) ASC, id ASC"
306 };
307 let mut list = PagedList::new(from_where, order);
308 for bind in binds.drain(..) {
309 list = list.bind(bind);
310 }
311 for value in bounds {
312 list = list.bind(value);
313 }
314 list.run::<Exam>(limit, offset, db).await
315}
316
317/// The exams of one instance, newest first.
318///
319/// It reads through `exam_audience` rather than off `exam.class_course`: the
320/// owner's row is always there (the create writes it), so the two agree for
321/// every exam this instance owns, and the join is what lets a shared exam be
322/// one exam addressed to several instances (D2) without a second read path.
323pub async fn list_for_class_course(
324 db: &Database,
325 class_course: &ClassCourseId,
326) -> Result<Vec<Exam>, AppError> {
327 Ok(sqlx::query_as!(
328 Exam,
329 r#"SELECT DISTINCT ON (e.id)
330 e.id AS "id: ExamId", e.creator AS "creator: UserId",
331 e.class_course AS "class_course: ClassCourseId",
332 e.term AS "term: TermId", e.title AS "title: ExamTitle",
333 e.description AS "description: ExamDescription",
334 e.kind AS "kind: ExamKind", e.mode AS "mode: ExamMode",
335 e.starts_at AS "starts_at: Timestamp",
336 e.ends_at AS "ends_at: Timestamp",
337 e.duration_ms AS "duration_ms: ExamDuration",
338 e.max_attempts AS "max_attempts: ExamAttemptLimit",
339 e.allow_rejoin, e.allow_review, e.draft
340 FROM exam e
341 JOIN exam_audience a ON a.exam = e.id
342 WHERE a.class_course = $1
343 ORDER BY e.id DESC"#,
344 class_course.uuid(),
345 )
346 .fetch_all(db)
347 .await?)
348}
349
350/// Every exam of every instance in `instances` (one query) — the report card and
351/// marks reports' cross-instance read, and the list behind a caller's visible
352/// courses.
353///
354/// `DISTINCT ON (e.id)` because an exam may be addressed to several instances
355/// at once (a shared exam): the filters ask "is this exam visible here", not
356/// "how many audiences does it have", so each exam is returned once with its
357/// own owner instance.
358pub async fn list_for_class_course_courses(
359 db: &Database,
360 instances: &[ClassCourseId],
361) -> Result<Vec<Exam>, AppError> {
362 if instances.is_empty() {
363 return Ok(Vec::new());
364 }
365 let instances = instances
366 .iter()
367 .map(ClassCourseId::uuid)
368 .collect::<Vec<_>>();
369 Ok(sqlx::query_as!(
370 Exam,
371 r#"SELECT DISTINCT ON (e.id)
372 e.id AS "id: ExamId", e.creator AS "creator: UserId",
373 e.class_course AS "class_course: ClassCourseId",
374 e.term AS "term: TermId", e.title AS "title: ExamTitle",
375 e.description AS "description: ExamDescription",
376 e.kind AS "kind: ExamKind", e.mode AS "mode: ExamMode",
377 e.starts_at AS "starts_at: Timestamp",
378 e.ends_at AS "ends_at: Timestamp",
379 e.duration_ms AS "duration_ms: ExamDuration",
380 e.max_attempts AS "max_attempts: ExamAttemptLimit",
381 e.allow_rejoin, e.allow_review, e.draft
382 FROM exam e
383 JOIN exam_audience a ON a.exam = e.id
384 WHERE a.class_course = ANY($1)
385 ORDER BY e.id DESC"#,
386 &instances,
387 )
388 .fetch_all(db)
389 .await?)
390}
391
392/// Every exam of every *catalog* course in `courses` (one query) — the
393/// catalog as one user sees it, across the instances those courses are taught
394/// in.
395pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result<Vec<Exam>, AppError> {
396 if courses.is_empty() {
397 return Ok(Vec::new());
398 }
399 let courses = courses.iter().map(CourseId::uuid).collect::<Vec<_>>();
400 Ok(sqlx::query_as!(
401 Exam,
402 r#"SELECT DISTINCT ON (e.id)
403 e.id AS "id: ExamId", e.creator AS "creator: UserId",
404 e.class_course AS "class_course: ClassCourseId",
405 e.term AS "term: TermId", e.title AS "title: ExamTitle",
406 e.description AS "description: ExamDescription",
407 e.kind AS "kind: ExamKind", e.mode AS "mode: ExamMode",
408 e.starts_at AS "starts_at: Timestamp",
409 e.ends_at AS "ends_at: Timestamp",
410 e.duration_ms AS "duration_ms: ExamDuration",
411 e.max_attempts AS "max_attempts: ExamAttemptLimit",
412 e.allow_rejoin, e.allow_review, e.draft
413 FROM exam e
414 JOIN exam_audience a ON a.exam = e.id
415 JOIN class_course cc ON cc.id = a.class_course
416 WHERE cc.course = ANY($1)
417 ORDER BY e.id DESC"#,
418 &courses,
419 )
420 .fetch_all(db)
421 .await?)
422}
423
424/// The exam's mark counter, read on its own — the one column no struct
425/// carries and no whole-row rewrite touches. The kind-change gate reads it
426/// here (pre-flight) and `update_if_unchanged` pins it inside its own
427/// transaction (write time).
428pub async fn result_count(db: &Database, id: &ExamId) -> Result<i64, AppError> {
429 let row = sqlx::query!(
430 r#"SELECT result_count AS "result_count: i64" FROM exam WHERE id = $1"#,
431 id.uuid(),
432 )
433 .fetch_one(db)
434 .await?;
435 Ok(row.result_count)
436}
437
438// `course` is deliberately not updatable — moving an exam between courses
439// would strand results of students not enrolled in the target course.
440#[expect(
441 clippy::too_many_arguments,
442 reason = "mirrors the sibling entities' update(field, field, ..) shape"
443)]
444/// Save the merged exam, but only while the row still reads as the
445/// snapshot the caller merged over — `None` means a concurrent PATCH
446/// landed in between and nothing was written: re-read, re-merge, retry.
447///
448/// Every column this write replaces is in the guard, which is what makes
449/// the whole-row save safe without a lock held across the handler's read:
450/// the compare-and-set refuses precisely when that save would have
451/// reverted somebody. `course`/`creator` are not editable and ride along
452/// unchanged. Same shape as [`crate::db::settings::save_if_unchanged`].
453///
454/// The mark counter is pinned too, read *inside* this transaction rather
455/// than carried on the snapshot: a grade increments it, so pinning it is
456/// what makes "this exam had no marks" — the gate the handler refuses a
457/// kind change on — true at *write* time and not merely at read time. A
458/// mark landing between the read and the guarded write makes the UPDATE
459/// re-check its `WHERE` against the new row version, find the counter
460/// moved, and refuse the save — the same answer the old pinned snapshot
461/// gave, without a stale snapshot able to pin a counter it cannot see.
462///
463/// The re-draft gate rides in the same transaction, as before: re-drafting
464/// hides an exam, so it must be refused while any sitting or mark exists,
465/// and the check has to see the write's own moment, not the handler's.
466pub async fn update_if_unchanged(
467 db: &Database,
468 mut expected: Exam,
469 title: ExamTitle,
470 description: ExamDescription,
471 kind: ExamKind,
472 schedule: ExamSchedule,
473 max_attempts: ExamAttemptLimit,
474 allow_rejoin: bool,
475 allow_review: bool,
476 draft: bool,
477) -> Result<Option<Exam>, AppError> {
478 let redraft = draft && !expected.draft;
479 let was = (
480 expected.title.clone(),
481 expected.description.clone(),
482 expected.kind.clone(),
483 expected.mode.clone(),
484 expected.starts_at,
485 expected.ends_at,
486 expected.duration_ms,
487 expected.max_attempts,
488 expected.allow_rejoin,
489 expected.allow_review,
490 expected.draft,
491 );
492 expected.title = title;
493 expected.description = description;
494 expected.kind = kind;
495 expected.mode = schedule.mode;
496 expected.starts_at = schedule.starts_at;
497 expected.ends_at = schedule.ends_at;
498 expected.duration_ms = schedule.duration_ms;
499 expected.max_attempts = max_attempts;
500 expected.allow_rejoin = allow_rejoin;
501 expected.allow_review = allow_review;
502 expected.draft = draft;
503 let saved = tx_with_retry(db, false, async move |conn| {
504 if redraft {
505 // `exam_redraft`: the same refusal the handler's pre-flight
506 // answers, re-made at write time. A sitting or a mark existing
507 // hides nothing.
508 let gates = sqlx::query!(
509 r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat,
510 EXISTS(SELECT 1 FROM exam_result WHERE exam = $1) AS graded"#,
511 expected.id.uuid(),
512 )
513 .fetch_one(&mut *conn)
514 .await?;
515 if gates.sat.unwrap_or(false) || gates.graded.unwrap_or(false) {
516 return Err(redraft_error());
517 }
518 }
519 let was_results = sqlx::query!(
520 r#"SELECT result_count AS "result_count: i64" FROM exam WHERE id = $1"#,
521 expected.id.uuid(),
522 )
523 .fetch_optional(&mut *conn)
524 .await?
525 .map(|row| row.result_count)
526 .unwrap_or(0);
527 let written = sqlx::query_as!(
528 Exam,
529 r#"UPDATE exam SET title = $2, description = $3, kind = $4, mode = $5,
530 starts_at = $6, ends_at = $7, duration_ms = $8,
531 max_attempts = $9, allow_rejoin = $10, allow_review = $11,
532 draft = $12
533 WHERE id = $1
534 AND title = $13 AND description = $14 AND kind = $15
535 AND mode IS NOT DISTINCT FROM $16
536 AND starts_at IS NOT DISTINCT FROM $17
537 AND ends_at IS NOT DISTINCT FROM $18
538 AND duration_ms IS NOT DISTINCT FROM $19
539 AND max_attempts = $20 AND allow_rejoin = $21 AND allow_review = $22
540 AND draft = $23
541 AND result_count = $24
542 RETURNING id AS "id: ExamId", creator AS "creator: UserId",
543 class_course AS "class_course: ClassCourseId",
544 term AS "term: TermId", title AS "title: ExamTitle",
545 description AS "description: ExamDescription",
546 kind AS "kind: ExamKind", mode AS "mode: ExamMode",
547 starts_at AS "starts_at: Timestamp",
548 ends_at AS "ends_at: Timestamp",
549 duration_ms AS "duration_ms: ExamDuration",
550 max_attempts AS "max_attempts: ExamAttemptLimit",
551 allow_rejoin, allow_review, draft"#,
552 expected.id.uuid(),
553 expected.title.as_str(),
554 expected.description.as_str(),
555 expected.kind.as_str(),
556 expected.mode.as_ref().map(ExamMode::as_str),
557 expected.starts_at.map(|at| at.as_millis()),
558 expected.ends_at.map(|at| at.as_millis()),
559 expected.duration_ms.map(|duration| duration.as_millis()),
560 expected.max_attempts.as_i64(),
561 expected.allow_rejoin,
562 expected.allow_review,
563 expected.draft,
564 was.0.as_str(),
565 was.1.as_str(),
566 was.2.as_str(),
567 was.3.as_ref().map(ExamMode::as_str),
568 was.4.map(|at| at.as_millis()),
569 was.5.map(|at| at.as_millis()),
570 was.6.map(|duration| duration.as_millis()),
571 was.7.as_i64(),
572 was.8,
573 was.9,
574 was.10,
575 was_results,
576 )
577 .fetch_optional(&mut *conn)
578 .await?;
579 Ok(written)
580 })
581 .await?;
582 Ok(saved)
583}
584
585/// What [`delete`] collects on its way through: the deleted row plus the
586/// blob keys of the image rows its cascade removed — exactly whose files
587/// the web layer may unlink.
588#[derive(Debug)]
589pub struct Deleted {
590 pub exam: Exam,
591 pub question_image_files: Vec<String>,
592 pub answer_image_files: Vec<String>,
593}
594
595/// Delete the exam and cascade-remove its result, attempt, question,
596/// answer, question-image, and answer-image rows — all in one transaction,
597/// so a failure can't leave an emptied-out exam shell behind. The image
598/// *blobs* are the caller's to remove — this returns the names, collected
599/// inside the same transaction that removes the rows.
600///
601/// The transaction opens by taking the exam row `FOR UPDATE` — the store
602/// replacement of the writer lease the delete used to hold. Every child
603/// writer that matters locks the same row first (a sitting create's guard,
604/// the freeze gate, an answer save ahead of its upsert), so a start or a
605/// save either finished before the sweep (which then takes its row) or
606/// finds no exam and is a `404`. Left orphaned, an attempt kept a sitting
607/// on the student's lifetime counter and could mint a badge — awards are
608/// add-only and never revoked — for an exam that never existed.
609///
610/// Bank templates saved out of this exam survive it — they are a separate,
611/// reusable library — so only their `source_exam` provenance link is
612/// cleared, in the same transaction, never left pointing at a dead exam.
613///
614/// The questions about to be cascaded each hold a reference on their
615/// subject, which is what keeps that subject from being deleted under them.
616/// They are given back in this same transaction, counted per subject, so
617/// deleting an exam frees its subjects for deletion and nothing else does.
618/// The marks give their *kind* references back the same way, and it has to
619/// be the same way: counted outside the transaction, a mark deleted by a
620/// concurrent `remove_result` in the gap would be released twice — once by
621/// each — which on a kind another exam still uses reads as one mark too
622/// few, and that is a kind wrongly free to leave the settings.
623pub async fn delete(db: &Database, target: Exam) -> Result<Deleted, AppError> {
624 tx_with_retry(
625 db,
626 true,
627 async move |conn| {
628 // The row lock every other exam-child writer contends on. The
629 // term rides out of the same read: the term's `exam_count` is
630 // given back in this transaction, and the row that names it is
631 // the one being deleted.
632 let locked = sqlx::query!(
633 r#"SELECT term AS "term: TermId" FROM exam WHERE id = $1 FOR UPDATE"#,
634 target.id.uuid(),
635 )
636 .fetch_optional(&mut *conn)
637 .await?;
638 let Some(locked) = locked else {
639 return Err(AppError::NotFound);
640 };
641 // The blob names, collected *before* the rows go — inside the
642 // lock, so an image row written after this snapshot cannot
643 // strand its bytes on disk even though the row itself would be
644 // refused.
645 let image_files = sqlx::query!(
646 r#"SELECT file FROM question_image WHERE exam = $1"#,
647 target.id.uuid(),
648 )
649 .fetch_all(&mut *conn)
650 .await?
651 .into_iter()
652 .map(|row| row.file)
653 .collect();
654 let answer_image_files = sqlx::query!(
655 r#"SELECT file FROM answer_image WHERE exam = $1"#,
656 target.id.uuid(),
657 )
658 .fetch_all(&mut *conn)
659 .await?
660 .into_iter()
661 .map(|row| row.file)
662 .collect();
663 // The marks give their kind references back, counted per kind
664 // off the results this exam still has. The ref row always
665 // exists here: a mark's own claim creates it before any result
666 // can land.
667 sqlx::query!(
668 r#"WITH kinds AS (
669 SELECT e.kind AS kind, count(*) AS n
670 FROM exam_result r JOIN exam e ON e.id = r.exam
671 WHERE r.exam = $1
672 GROUP BY e.kind)
673 UPDATE kind_ref k SET count = GREATEST(k.count - c.n, 0)
674 FROM kinds c WHERE k.name = c.kind"#,
675 target.id.uuid(),
676 )
677 .execute(&mut *conn)
678 .await?;
679 sqlx::query!(r#"DELETE FROM exam_result WHERE exam = $1"#, target.id.uuid())
680 .execute(&mut *conn)
681 .await?;
682 sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = $1"#, target.id.uuid())
683 .execute(&mut *conn)
684 .await?;
685 sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = $1"#, target.id.uuid())
686 .execute(&mut *conn)
687 .await?;
688 sqlx::query!(r#"DELETE FROM answer_image WHERE exam = $1"#, target.id.uuid())
689 .execute(&mut *conn)
690 .await?;
691 sqlx::query!(r#"DELETE FROM question_image WHERE exam = $1"#, target.id.uuid())
692 .execute(&mut *conn)
693 .await?;
694 // The cascaded questions give their subject references back,
695 // counted per subject off the rows still present — before the
696 // questions themselves go.
697 sqlx::query!(
698 r#"WITH subs AS (
699 SELECT subject, count(*) AS n
700 FROM exam_question WHERE exam = $1
701 GROUP BY subject)
702 UPDATE subject s SET exam_question_count = GREATEST(s.exam_question_count - c.n, 0)
703 FROM subs c WHERE s.id = c.subject"#,
704 target.id.uuid(),
705 )
706 .execute(&mut *conn)
707 .await?;
708 sqlx::query!(r#"DELETE FROM exam_question WHERE exam = $1"#, target.id.uuid())
709 .execute(&mut *conn)
710 .await?;
711 sqlx::query!(
712 r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = $1"#,
713 target.id.uuid(),
714 )
715 .execute(&mut *conn)
716 .await?;
717 // The sitting instances go with the exam: every read goes through
718 // the audience join, so a row pointing at a deleted exam would be
719 // both invisible and undeletable.
720 sqlx::query!(
721 r#"DELETE FROM exam_audience WHERE exam = $1"#,
722 target.id.uuid(),
723 )
724 .execute(&mut *conn)
725 .await?;
726 let deleted = sqlx::query_as!(
727 Exam,
728 r#"DELETE FROM exam WHERE id = $1
729 RETURNING id AS "id: ExamId", creator AS "creator: UserId",
730 class_course AS "class_course: ClassCourseId",
731 term AS "term: TermId", title AS "title: ExamTitle",
732 description AS "description: ExamDescription",
733 kind AS "kind: ExamKind", mode AS "mode: ExamMode",
734 starts_at AS "starts_at: Timestamp",
735 ends_at AS "ends_at: Timestamp",
736 duration_ms AS "duration_ms: ExamDuration",
737 max_attempts AS "max_attempts: ExamAttemptLimit",
738 allow_rejoin, allow_review, draft"#,
739 target.id.uuid(),
740 )
741 .fetch_optional(&mut *conn)
742 .await?;
743 let Some(exam) = deleted else {
744 return Err(AppError::NotFound);
745 };
746 // The term gets its exam reference back inside the same
747 // transaction — the other half of the claim `create` makes.
748 sqlx::query!(
749 r#"UPDATE term SET exam_count = GREATEST(exam_count - 1, 0)
750 WHERE id = $1"#,
751 locked.term.uuid(),
752 )
753 .execute(&mut *conn)
754 .await?;
755 Ok(Deleted {
756 exam,
757 question_image_files: image_files,
758 answer_image_files,
759 })
760 },
761 )
762 .await
763}
764
765#[cfg(test)]
766use crate::domain::settings::ExamKindDef;
767
768/// An unscheduled published exam — the minimum any test that writes a *child*
769/// of an exam needs, in any module: every such write moves the exam row (see
770/// [`crate::db::exam_attempt::write_unfrozen_with`]
771/// and [`crate::db::exam_answer::save`]), so a minted id whose
772/// row was never created is a 404 rather than a silent orphan.
773#[cfg(test)]
774pub(crate) async fn published_exam(db: &Database) -> Exam {
775 let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
776 .get_exam_kinds()
777 .to_vec();
778 // The creator is a foreign key now: a real `app_user` row, minted per call.
779 let creator = UserId::generate();
780 sqlx::query(
781 "INSERT INTO app_user (id, username, created_at, role) \
782 VALUES ($1, $2, 0, 'teacher')",
783 )
784 .bind(creator.uuid())
785 .bind(format!("exam-fixture-{}", &creator.key()[30..]))
786 .execute(db)
787 .await
788 .unwrap();
789 // The exam hangs off the *instance* and carries the term it is graded in
790 // (both foreign keys): both are real rows, minted per call —
791 // [`crate::db::course::a_test_instance`] mints the class, the course and
792 // the link, [`crate::db::term::a_test_term`] the year under the term.
793 let (instance, _course) = crate::db::course::a_test_instance(db).await;
794 let term = crate::db::term::a_test_term(db).await;
795 create(
796 db,
797 &creator,
798 &instance,
799 &term,
800 ExamTitle::try_new("midterm").unwrap(),
801 ExamDescription::try_new("").unwrap(),
802 ExamKind::try_new("yazili", &allowed).unwrap(),
803 ExamSchedule::try_new(None, None, None, None).unwrap(),
804 ExamAttemptLimit::try_new(1).unwrap(),
805 true,
806 false,
807 false,
808 )
809 .await
810 .unwrap()
811}
812
813#[cfg(test)]
814mod tests {
815 use super::*;
816
817 use super::published_exam as published;
818
819 use crate::domain::exam::{ExamDuration, ExamMode};
820 use crate::domain::settings::ExamKindDef;
821 use crate::domain::timestamp::Timestamp;
822 use crate::error::ValidationError;
823
824 /// An exam must not outlive the course it belongs to. It is the worst of
825 /// the three children `Course::delete` used to leave behind: every exam
826 /// route funnels through `class_course_of`, which answers
827 /// `Internal("exam references a missing course")`, so an orphan **500s
828 /// forever** on `GET`/`PATCH`/`DELETE /exams/{id}` — undeletable — while
829 /// [`crate::db::exam::list_windowed`] still hands it to every manager+ on
830 /// `GET /exams`.
831 ///
832 /// [`create`] therefore *writes* the course row rather than reading
833 /// it ([`cap::touch_and_create`]); the harness and the window it races in
834 /// are documented on
835 /// [`crate::db::course::assert_no_child_outlives_a_course_delete`].
836 /// Mutation-tested: with the bare `db.create` this shipped with, all four
837 /// rounds orphan.
838 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
839 async fn an_exam_never_outlives_its_course() {
840 fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {
841 tokio::spawn(async move {
842 let kinds = crate::domain::settings::Settings::defaults()
843 .get_exam_kinds()
844 .to_vec();
845 let creator = UserId::generate();
846 sqlx::query(
847 "INSERT INTO app_user (id, username, created_at, role) \
848 VALUES ($1, $2, 0, 'teacher')",
849 )
850 .bind(creator.uuid())
851 .bind(format!("orphan-race-{}", &creator.key()[30..]))
852 .execute(&db)
853 .await
854 .unwrap();
855 // The exam's parents: a term, and an instance of *this*
856 // course. Attaching it is the claim the racing delete
857 // contends on, so the round where the course is gone refuses
858 // here — which is the refusal this test wants to see answered.
859 let term = crate::db::term::a_test_term(&db).await;
860 let class = crate::db::class_group::create(
861 &db,
862 &creator,
863 crate::domain::class_group::ClassName::try_new("9-A").unwrap(),
864 crate::domain::grade::GradeLevel::new(9).unwrap(),
865 None,
866 None,
867 )
868 .await?
869 .get_id()
870 .clone();
871 let instance = crate::service::class_course::attach(&db, &class, &course, &creator)
872 .await?
873 .get_id()
874 .clone();
875 create(
876 &db,
877 &creator,
878 &instance,
879 &term,
880 ExamTitle::try_new("quiz").unwrap(),
881 ExamDescription::try_new("").unwrap(),
882 ExamKind::try_new("yazili", &kinds).unwrap(),
883 ExamSchedule::try_new(None, None, None, None).unwrap(),
884 ExamAttemptLimit::try_new(1).unwrap(),
885 true,
886 false,
887 false,
888 )
889 .await
890 .map(|_| ())
891 })
892 }
893 crate::db::course::assert_no_child_outlives_a_course_delete(
894 "exam",
895 "SELECT count(*) FROM exam e JOIN class_course cc ON cc.id = e.class_course
896 WHERE cc.course = $1",
897 make,
898 )
899 .await;
900 }
901
902 /// A real `app_user` row: students and graders are foreign keys now. The
903 /// label names the row's username; the id is minted, so repeated calls are
904 /// new people, not the same row.
905 async fn a_person(db: &Database, label: &str, role: &str) -> UserId {
906 let user = UserId::generate();
907 sqlx::query(
908 "INSERT INTO app_user (id, username, created_at, role) \
909 VALUES ($1, $2, 0, $3)",
910 )
911 .bind(user.uuid())
912 .bind(format!("{label}-{}", &user.key()[30..]))
913 .bind(role)
914 .execute(db)
915 .await
916 .unwrap();
917 user
918 }
919
920 fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) {
921 (
922 exam.get_title().clone(),
923 exam.get_description().clone(),
924 exam.get_kind().clone(),
925 ExamSchedule::try_new(None, None, None, None).unwrap(),
926 )
927 }
928
929 /// The bite test for the compare-and-set that replaced the writer lease on
930 /// `PATCH /exams/{id}`: a merge built on a snapshot the row has moved past
931 /// must be refused (the handler then re-reads and re-merges), never
932 /// written over somebody else's edit. Asserts the *stored* row.
933 #[tokio::test]
934 async fn a_merge_built_on_a_stale_snapshot_is_refused() {
935 let (db, _leases) = crate::database::init_test_db().await;
936 let stale = published(&db).await;
937 let (_, description, kind, schedule) = edit(&stale);
938 let landed = update_if_unchanged(
939 &db,
940 stale.clone(),
941 ExamTitle::try_new("theirs").unwrap(),
942 description,
943 kind,
944 schedule,
945 ExamAttemptLimit::try_new(1).unwrap(),
946 true,
947 false,
948 false,
949 )
950 .await
951 .unwrap();
952 assert!(landed.is_some(), "the first write is on a fresh snapshot");
953
954 let (_, description, kind, schedule) = edit(&stale);
955 let refused = update_if_unchanged(
956 &db,
957 stale,
958 ExamTitle::try_new("mine").unwrap(),
959 description,
960 kind,
961 schedule,
962 ExamAttemptLimit::try_new(1).unwrap(),
963 true,
964 false,
965 false,
966 )
967 .await
968 .unwrap();
969 assert!(refused.is_none(), "a stale merge must not be written");
970 let stored = read(&db, landed.unwrap().get_id()).await.unwrap().unwrap();
971 assert_eq!(stored.get_title().as_str(), "theirs");
972 }
973
974 /// The bite test for the re-draft guard now living *inside* the update's
975 /// transaction: a mark that lands after the handler's pre-flight gate (the
976 /// grade path is a lock reader, exactly like this one) must still stop the
977 /// exam from being hidden.
978 #[tokio::test]
979 async fn re_drafting_is_refused_by_the_write_itself_once_a_mark_exists() {
980 use crate::db::exam_result;
981 use crate::domain::exam_result::Mark;
982 let (db, _leases) = crate::database::init_test_db().await;
983 let exam = published(&db).await;
984 let student = a_person(&db, "student", "student").await;
985 let grader = a_person(&db, "teacher", "teacher").await;
986 exam_result::grade(
987 &db,
988 exam.get_id(),
989 &student,
990 1,
991 Mark::try_new(80).unwrap(),
992 &grader,
993 exam.get_kind().as_str(),
994 )
995 .await
996 .unwrap();
997
998 let (title, description, kind, schedule) = edit(&exam);
999 let refused = update_if_unchanged(
1000 &db,
1001 exam.clone(),
1002 title,
1003 description,
1004 kind,
1005 schedule,
1006 ExamAttemptLimit::try_new(1).unwrap(),
1007 true,
1008 false,
1009 true,
1010 )
1011 .await
1012 .expect_err("a graded exam cannot be re-drafted");
1013 assert!(refused.to_string().contains("back into a draft"));
1014 let stored = read(&db, exam.get_id()).await.unwrap().unwrap();
1015 assert!(!stored.is_draft(), "nothing may have been written");
1016 }
1017
1018 #[tokio::test]
1019 async fn title_is_required() {
1020 assert!(ExamTitle::try_new("midterm").is_ok());
1021 assert!(ExamTitle::try_new("").is_err());
1022 assert!(ExamTitle::try_new(" ").is_err());
1023 }
1024
1025 #[tokio::test]
1026 async fn description_is_optional() {
1027 assert!(ExamDescription::try_new("").is_ok());
1028 }
1029
1030 #[tokio::test]
1031 async fn kind_must_be_in_the_allowed_list() {
1032 let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
1033 .get_exam_kinds()
1034 .to_vec();
1035 // The K12 defaults, pinned by name: the acceptance set of a fresh
1036 // school is exactly these three, and the pre-remodel vocabulary
1037 // ("quiz", "midterm", …) is not in it.
1038 for kind in ["yazili", "sozlu", "uygulama"] {
1039 assert_eq!(ExamKind::try_new(kind, &allowed).unwrap().as_str(), kind);
1040 }
1041 for stale in ["quiz", "midterm", "exam"] {
1042 assert!(
1043 ExamKind::try_new(stale, &allowed).is_err(),
1044 "{stale} is not in the school's list"
1045 );
1046 }
1047 assert!(ExamKind::try_new("", &allowed).is_err());
1048 // A school-defined list swaps the acceptance set wholesale.
1049 let custom = vec![ExamKindDef::try_new("lab", 2).unwrap()];
1050 assert!(ExamKind::try_new("lab", &custom).is_ok());
1051 assert!(ExamKind::try_new("midterm", &custom).is_err());
1052 // Matching is exact, case included — the settings list is the wire
1053 // truth, not a case-folded suggestion.
1054 assert!(ExamKind::try_new("Lab", &custom).is_err());
1055 }
1056
1057 #[tokio::test]
1058 async fn mode_must_be_known() {
1059 for mode in ["sync", "async", "open"] {
1060 assert_eq!(ExamMode::try_new(mode).unwrap().as_str(), mode);
1061 }
1062 assert!(ExamMode::try_new("live").is_err());
1063 }
1064
1065 #[tokio::test]
1066 async fn attempt_limit_counts_or_never_runs_out() {
1067 let single = ExamAttemptLimit::single();
1068 assert_eq!(single.as_i64(), 1);
1069 assert!(!single.is_unlimited());
1070 assert!(single.allows_another(0));
1071 assert!(!single.allows_another(1));
1072
1073 let three = ExamAttemptLimit::try_new(3).unwrap();
1074 assert!(three.allows_another(2));
1075 assert!(!three.allows_another(3));
1076 assert!(!three.allows_another(4));
1077
1078 let unlimited = ExamAttemptLimit::try_new(0).unwrap();
1079 assert!(unlimited.is_unlimited());
1080 assert!(unlimited.allows_another(0));
1081 assert!(unlimited.allows_another(10_000));
1082
1083 assert!(ExamAttemptLimit::try_new(-1).is_err());
1084 assert!(ExamAttemptLimit::try_new(101).is_err());
1085 }
1086
1087 #[tokio::test]
1088 async fn schedule_invariants_hold() {
1089 let mode = |m| Some(ExamMode::try_new(m).unwrap());
1090 let at = |ms| Some(Timestamp::from_millis(ms));
1091 let dur = Some(ExamDuration::try_new(90 * 60 * 1000).unwrap());
1092
1093 // Unscheduled: nothing set is fine, any time/duration without a mode is not.
1094 assert!(ExamSchedule::try_new(None, None, None, None).is_ok());
1095 assert!(ExamSchedule::try_new(None, at(1), None, None).is_err());
1096 assert!(ExamSchedule::try_new(None, None, at(2), None).is_err());
1097 assert!(ExamSchedule::try_new(None, None, None, dur).is_err());
1098
1099 // Sync: fixed window, no duration.
1100 assert!(ExamSchedule::try_new(mode("sync"), at(1), at(2), None).is_ok());
1101 assert!(ExamSchedule::try_new(mode("sync"), None, at(2), None).is_err());
1102 assert!(ExamSchedule::try_new(mode("sync"), at(1), None, None).is_err());
1103 // Over-long `dur` in a 1ms window, but the root cause is that sync
1104 // takes no duration at all — that message wins over the window one.
1105 assert!(matches!(
1106 ExamSchedule::try_new(mode("sync"), at(1), at(2), dur),
1107 Err(ValidationError::Invalid {
1108 reason: "only async and open exams take a duration",
1109 ..
1110 })
1111 ));
1112
1113 // Async: window plus a per-student duration, which must fit inside it
1114 // (equal to the window is fine; the window `at(1), at(2)` above is
1115 // too narrow for `dur`, so give it one exactly `dur` wide instead).
1116 assert!(ExamSchedule::try_new(mode("async"), at(1), at(1 + 90 * 60 * 1000), dur).is_ok());
1117 assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), dur).is_err());
1118 assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), None).is_err());
1119
1120 // Open: no window, duration optional (limited or unlimited time).
1121 assert!(ExamSchedule::try_new(mode("open"), None, None, None).is_ok());
1122 assert!(ExamSchedule::try_new(mode("open"), None, None, dur).is_ok());
1123 assert!(ExamSchedule::try_new(mode("open"), at(1), None, None).is_err());
1124 assert!(ExamSchedule::try_new(mode("open"), None, at(2), None).is_err());
1125 assert!(ExamSchedule::try_new(mode("open"), at(1), at(2), dur).is_err());
1126
1127 // The window must be a real interval, whatever the mode.
1128 assert!(ExamSchedule::try_new(mode("sync"), at(2), at(2), None).is_err());
1129 assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err());
1130 }
1131
1132 /// GUARD, not a retry measurement — read the last paragraph before
1133 /// trusting this test with the retry. See
1134 /// [`crate::db::course::delete`]'s race test for why the rate is
1135 /// counted rather than asserted per round.
1136 ///
1137 /// This site has no marker at all: the delete's statements share one
1138 /// transaction whose first failure aborts the rest, so a genuine conflict
1139 /// can be masked by a sibling error, and either way there is no
1140 /// [`crate::database::lost_the_race`] check and no retry.
1141 ///
1142 /// The racer is a mark: [`crate::db::exam_result::grade`] claims the exam's own
1143 /// `result_count` (and the kind's reference) before writing, so it contends
1144 /// with the `DELETE $ex` and with the kind_ref decrement inside the same
1145 /// transaction. The witness that the site is genuinely raced is read per
1146 /// round and asserted over the whole run — the subject twin's shape. A
1147 /// grade answered 404 says the delete landed before it (`write_mark`'s
1148 /// existence gate is the only thing that can answer that); a grade going
1149 /// through says that grade beat the delete. Which side wins a *round* is
1150 /// load luck: under a busy machine the delete lands wholly on one side of
1151 /// the burst in every round (measured 0/20 same-round splits, 3 runs in 5
1152 /// red, with the integration suite running concurrently), so a same-round
1153 /// split must not be the gate. Stored state cannot witness the straddle —
1154 /// the gate is what stops a mark outliving its exam, so the sweep now
1155 /// finds nothing to leave behind in *every* round, which is asserted
1156 /// below as a fact rather than read as a signal.
1157 ///
1158 /// It does not prove the retry either: measured at 0 conflicts in 100 raced
1159 /// rounds, and green with
1160 /// [`crate::database::transaction_with_retry`]'s loop cut to a single
1161 /// attempt — the grades serialize behind `cap`'s claim lock, so they mostly
1162 /// queue rather than collide. So this guards the status codes and the
1163 /// cascade (marks either survive whole or are swept whole, never a 500).
1164 /// The retry is measured on [`crate::db::course::delete`].
1165 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1166 async fn a_delete_racing_a_mark_never_answers_500() {
1167 use crate::db::exam_result;
1168 use crate::domain::exam_result::Mark;
1169 let (db, _leases) = crate::database::init_test_db().await;
1170 let teacher = a_person(&db, "teacher", "teacher").await;
1171 let (mut delete_500, mut grade_500) = (0, 0);
1172 let (mut delete_first, mut grade_first, mut swept) = (0, 0, 0);
1173 let (mut last_delete, mut last_grade) = (String::new(), String::new());
1174 for round in 0..20 {
1175 let exam = published(&db).await;
1176 let kind = exam.get_kind().as_str().to_string();
1177
1178 // A burst of marks and a delete held back by a sweeping beat: this
1179 // site has no guard to lose to, so a single racer released with it
1180 // simply finishes on one side of it. Same recipe as
1181 // [`crate::db::course::delete`]'s race test.
1182 let drop_it = {
1183 let (exam, db) = (exam.clone(), db.clone());
1184 // A wide sweep, not the 0-3ms the other three use: each grade
1185 // takes two counter writes serialized behind `cap`'s claim
1186 // lock, so the burst runs tens of milliseconds and a short beat
1187 // always puts the delete in front of all six.
1188 let beat = std::time::Duration::from_millis(round * 2);
1189 tokio::spawn(async move {
1190 tokio::time::sleep(beat).await;
1191 delete(&db, exam).await
1192 })
1193 };
1194 // Six real students per round: the mark's app_user is a foreign
1195 // key now.
1196 let mut students = Vec::with_capacity(6);
1197 for _ in 0..6 {
1198 students.push(a_person(&db, "student", "student").await);
1199 }
1200 let marks: Vec<_> = (0..6)
1201 .map(|seat| {
1202 let (id, db, kind) = (exam.get_id().clone(), db.clone(), kind.clone());
1203 let (student, teacher) = (students[seat], teacher);
1204 tokio::spawn(async move {
1205 exam_result::grade(
1206 &db,
1207 &id,
1208 &student,
1209 1,
1210 Mark::try_new(50).unwrap(),
1211 &teacher,
1212 &kind,
1213 )
1214 .await
1215 })
1216 })
1217 .collect();
1218 let drop_it = drop_it.await.unwrap();
1219 if matches!(drop_it, Err(AppError::Db(_))) {
1220 delete_500 += 1;
1221 last_delete = format!("{:?}", drop_it.as_ref().err());
1222 }
1223 let mut refused = 0;
1224 for mark in marks {
1225 let mark = mark.await.unwrap();
1226 match mark {
1227 // The existence gate: this grade reached the store after
1228 // the row was gone.
1229 Err(AppError::NotFound) => refused += 1,
1230 Err(AppError::Db(_)) => {
1231 grade_500 += 1;
1232 last_grade = format!("{mark:?}");
1233 }
1234 _ => {}
1235 }
1236 }
1237 // Which side won, read per round and asserted over the whole run:
1238 // a round with a refused grade saw the delete land first, a round
1239 // with a grade through saw a grade land first. One round can be
1240 // both — that is the same-round split, welcome but not required.
1241 if refused > 0 {
1242 delete_first += 1;
1243 }
1244 if refused < 6 {
1245 grade_first += 1;
1246 }
1247 if exam_result::list_for_exam(&db, exam.get_id())
1248 .await
1249 .unwrap()
1250 .is_empty()
1251 {
1252 swept += 1;
1253 }
1254 }
1255 eprintln!(
1256 "Exam::delete raced: {delete_500}/20 delete 500s, {grade_500} grade 500s, \
1257 {delete_first} rounds with a grade refused / {grade_first} with one through, \
1258 {swept} swept clean"
1259 );
1260 assert!(
1261 delete_first > 0 && grade_first > 0,
1262 "the sweep never crossed the window ({delete_first} rounds with a grade \
1263 refused / {grade_first} with one through)"
1264 );
1265 // Not a race signal, an invariant: the gate refuses a mark for an exam
1266 // that is gone, so no round can leave one behind for the next reader.
1267 assert_eq!(
1268 swept,
1269 20,
1270 "a mark outlived its exam in {} rounds",
1271 20 - swept
1272 );
1273 assert_eq!(
1274 delete_500, 0,
1275 "a raced delete must not 500: {delete_500}/20 rounds, last {last_delete}"
1276 );
1277 assert_eq!(
1278 grade_500, 0,
1279 "a raced grade must retry, not 500: {grade_500}/20 rounds, last {last_grade}"
1280 );
1281 }
1282
1283 /// One choice question on `exam`, with a real subject row behind it — a
1284 /// question claims a reference on its subject and is refused without one.
1285 async fn question_on(exam: &Exam, db: &Database) -> crate::domain::exam_question::ExamQuestion {
1286 use crate::domain::exam_question::{
1287 ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
1288 };
1289 let spec = QuestionSpec::try_new(
1290 QuestionKind::try_new("choice").unwrap(),
1291 Some(vec![
1292 ChoiceInput {
1293 id: Some("a".into()),
1294 text: "5".into(),
1295 },
1296 ChoiceInput {
1297 id: Some("b".into()),
1298 text: "6".into(),
1299 },
1300 ]),
1301 Some("b".into()),
1302 &[],
1303 )
1304 .unwrap();
1305 let subject = crate::db::subject::create(
1306 db,
1307 &crate::db::course::a_test_course(db).await,
1308 crate::domain::subject::SubjectName::try_new("topic").unwrap(),
1309 crate::domain::subject::SubjectDescription::try_new("").unwrap(),
1310 )
1311 .await
1312 .unwrap();
1313 crate::db::exam_question::create(
1314 db,
1315 exam.get_id(),
1316 *subject.get_id(),
1317 QuestionText::try_new("3 + 3?").unwrap(),
1318 QuestionPoints::try_new(5).unwrap(),
1319 spec,
1320 )
1321 .await
1322 .unwrap()
1323 }
1324
1325 /// The `Menu::delete` defect, one domain over: a student's answer must not
1326 /// outlive the exam it belongs to. Guarding the save by *reading* the exam
1327 /// would not do it — the read sees a row [`crate::db::exam::delete`] has removed but
1328 /// not committed, while its cascade swept a snapshot predating the save, so
1329 /// both commit and the answer is left pointing at an exam that is gone.
1330 /// [`crate::db::exam_answer::save`] writes the exam row instead (its
1331 /// `result_count`, back unchanged), so the two transactions touch one row
1332 /// and Postgres refuses one of them.
1333 ///
1334 /// One child per round, deliberately — in the menu twin, two children in one
1335 /// round hid the bug: the first writer made the delete lose and re-send, and
1336 /// the re-sent sweep removed the other's row. Both orders are forced by
1337 /// awaiting one side to completion before the other starts. Overlapped
1338 /// rounds may all lose the delete; that is not a failure.
1339 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1340 async fn an_answer_written_inside_a_delete_never_outlives_the_exam() {
1341 use crate::db::exam_answer;
1342 let (db, _leases) = crate::database::init_test_db().await;
1343
1344 let student = a_person(&db, "student", "student").await;
1345
1346 // Delete-first: the exam is gone before the save starts.
1347 {
1348 let exam = published(&db).await;
1349 let question = question_on(&exam, &db).await;
1350 let id = exam.get_id().clone();
1351 let pick = question.get_choices().unwrap()[1]
1352 .get_id()
1353 .as_str()
1354 .to_string();
1355 let dropped = delete(&db, exam).await;
1356 assert!(
1357 !matches!(dropped, Err(AppError::Db(_))),
1358 "delete-first: a delete must be answered, not 500: {dropped:?}"
1359 );
1360 assert!(
1361 read(&db, &id).await.unwrap().is_none(),
1362 "delete-first: the exam is still there after delete: {dropped:?}"
1363 );
1364 let child = exam_answer::save(&db, &question, &student, 1, Some(pick), None).await;
1365 assert!(
1366 !matches!(child, Err(AppError::Db(_))),
1367 "delete-first: a save must be answered, not 500: {child:?}"
1368 );
1369 assert_eq!(
1370 exam_answer::list_for_exam(&db, &id).await.unwrap().len(),
1371 0,
1372 "an answer outlived its exam"
1373 );
1374 }
1375
1376 // Write-first: the save lands, then the delete sweeps it.
1377 {
1378 let exam = published(&db).await;
1379 let question = question_on(&exam, &db).await;
1380 let id = exam.get_id().clone();
1381 let pick = question.get_choices().unwrap()[1]
1382 .get_id()
1383 .as_str()
1384 .to_string();
1385 let child = exam_answer::save(&db, &question, &student, 1, Some(pick), None).await;
1386 assert!(
1387 child.is_ok(),
1388 "write-first: the save must land before the delete: {child:?}"
1389 );
1390 let dropped = delete(&db, exam).await;
1391 assert!(
1392 !matches!(dropped, Err(AppError::Db(_))),
1393 "write-first: a delete must be answered, not 500: {dropped:?}"
1394 );
1395 assert!(
1396 read(&db, &id).await.unwrap().is_none(),
1397 "write-first: the exam is still there"
1398 );
1399 assert_eq!(
1400 exam_answer::list_for_exam(&db, &id).await.unwrap().len(),
1401 0,
1402 "an answer outlived its exam"
1403 );
1404 }
1405
1406 // Overlapped rounds. Delete may lose every one of them.
1407 let mut swept = 0;
1408 for round in 0..4 {
1409 let exam = published(&db).await;
1410 let question = question_on(&exam, &db).await;
1411 let id = exam.get_id().clone();
1412 let pick = question.get_choices().unwrap()[1]
1413 .get_id()
1414 .as_str()
1415 .to_string();
1416
1417 let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
1418 let drop_it = {
1419 let (db, exam, gate) = (db.clone(), exam, gate.clone());
1420 tokio::spawn(async move {
1421 gate.wait().await;
1422 delete(&db, exam).await
1423 })
1424 };
1425 let child = {
1426 let (db, question, student, pick, gate) =
1427 (db.clone(), question, student, pick, gate);
1428 tokio::spawn(async move {
1429 gate.wait().await;
1430 exam_answer::save(&db, &question, &student, 1, Some(pick), None).await
1431 })
1432 };
1433 let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1434 assert!(
1435 !matches!(child, Err(AppError::Db(_))),
1436 "round {round}: a raced save must be answered, not 500: {child:?}"
1437 );
1438 assert!(
1439 !matches!(drop_it, Err(AppError::Db(_))),
1440 "round {round}: a raced delete must be answered, not 500: {drop_it:?}"
1441 );
1442
1443 if read(&db, &id).await.unwrap().is_none() {
1444 swept += 1;
1445 assert_eq!(
1446 exam_answer::list_for_exam(&db, &id).await.unwrap().len(),
1447 0,
1448 "round {round}: an answer outlived its exam"
1449 );
1450 } else if drop_it.is_ok() {
1451 panic!("round {round}: the delete reported success but the exam is still there");
1452 }
1453 }
1454 eprintln!("Exam::delete raced by an answer save: {swept}/4 concurrent rounds deleted the exam");
1455 }
1456
1457 /// The same defect on the teacher's side of the sheet, and a worse one: a
1458 /// question written inside the delete window kept the reference it claimed
1459 /// on its subject (the cascade's per-subject decrement counted only the
1460 /// rows it could see), and [`crate::db::subject::delete`] is gated on that
1461 /// count reading zero — a subject nobody could ever delete again, hanging
1462 /// off an exam nobody could ever see. The freeze gate is a *read* of
1463 /// `exam_attempt` and never survived this window;
1464 /// [`crate::db::exam_attempt::write_unfrozen_with`] now writes the exam row
1465 /// too. Both orders are forced by awaiting one side to completion before
1466 /// the other starts. Overlapped rounds may all lose the delete; that is
1467 /// not a failure.
1468 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1469 async fn a_question_written_inside_a_delete_never_outlives_the_exam() {
1470 use crate::domain::exam_question::{
1471 ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
1472 };
1473 let (db, _leases) = crate::database::init_test_db().await;
1474
1475 fn spec() -> QuestionSpec {
1476 QuestionSpec::try_new(
1477 QuestionKind::try_new("choice").unwrap(),
1478 Some(vec![
1479 ChoiceInput {
1480 id: Some("a".into()),
1481 text: "5".into(),
1482 },
1483 ChoiceInput {
1484 id: Some("b".into()),
1485 text: "6".into(),
1486 },
1487 ]),
1488 Some("b".into()),
1489 &[],
1490 )
1491 .unwrap()
1492 }
1493
1494 async fn ask(
1495 db: &Database,
1496 exam: &ExamId,
1497 on: crate::domain::subject::SubjectId,
1498 ) -> Result<crate::domain::exam_question::ExamQuestion, AppError> {
1499 crate::db::exam_question::create(
1500 db,
1501 exam,
1502 on,
1503 QuestionText::try_new("3 + 3?").unwrap(),
1504 QuestionPoints::try_new(5).unwrap(),
1505 spec(),
1506 )
1507 .await
1508 }
1509
1510 async fn subject_stuck(db: &Database, subject: &crate::domain::subject::Subject) -> bool {
1511 crate::db::subject::delete(
1512 db,
1513 crate::db::subject::read(db, subject.get_id())
1514 .await
1515 .unwrap()
1516 .unwrap(),
1517 )
1518 .await
1519 .is_err()
1520 }
1521
1522 async fn a_subject(db: &Database) -> crate::domain::subject::Subject {
1523 crate::db::subject::create(
1524 db,
1525 &crate::db::course::a_test_course(db).await,
1526 crate::domain::subject::SubjectName::try_new("topic").unwrap(),
1527 crate::domain::subject::SubjectDescription::try_new("").unwrap(),
1528 )
1529 .await
1530 .unwrap()
1531 }
1532
1533 // Delete-first: the exam is gone before the question write starts.
1534 {
1535 let exam = published(&db).await;
1536 let id = exam.get_id().clone();
1537 let subject = a_subject(&db).await;
1538 let dropped = delete(&db, exam).await;
1539 assert!(
1540 !matches!(dropped, Err(AppError::Db(_))),
1541 "delete-first: a delete must be answered, not 500: {dropped:?}"
1542 );
1543 assert!(
1544 read(&db, &id).await.unwrap().is_none(),
1545 "delete-first: the exam is still there after delete: {dropped:?}"
1546 );
1547 let child = ask(&db, &id, *subject.get_id()).await;
1548 assert!(
1549 !matches!(child, Err(AppError::Db(_))),
1550 "delete-first: a question write must be answered, not 500: {child:?}"
1551 );
1552 assert_eq!(
1553 crate::db::exam_question::list_for_exam(&db, &id, None, 0)
1554 .await
1555 .unwrap()
1556 .0
1557 .len(),
1558 0,
1559 "a question outlived its exam"
1560 );
1561 assert!(
1562 !subject_stuck(&db, &subject).await,
1563 "an orphan question left its subject undeletable"
1564 );
1565 }
1566
1567 // Write-first: the question lands, then the delete sweeps it and frees
1568 // the subject reference it claimed.
1569 {
1570 let exam = published(&db).await;
1571 let id = exam.get_id().clone();
1572 let subject = a_subject(&db).await;
1573 let child = ask(&db, &id, *subject.get_id()).await;
1574 assert!(
1575 child.is_ok(),
1576 "write-first: the question must land before the delete: {child:?}"
1577 );
1578 let dropped = delete(&db, exam).await;
1579 assert!(
1580 !matches!(dropped, Err(AppError::Db(_))),
1581 "write-first: a delete must be answered, not 500: {dropped:?}"
1582 );
1583 assert!(
1584 read(&db, &id).await.unwrap().is_none(),
1585 "write-first: the exam is still there"
1586 );
1587 assert_eq!(
1588 crate::db::exam_question::list_for_exam(&db, &id, None, 0)
1589 .await
1590 .unwrap()
1591 .0
1592 .len(),
1593 0,
1594 "a question outlived its exam"
1595 );
1596 assert!(
1597 !subject_stuck(&db, &subject).await,
1598 "an orphan question left its subject undeletable"
1599 );
1600 }
1601
1602 // Overlapped rounds. Delete may lose every one of them.
1603 let mut swept = 0;
1604 for round in 0..4 {
1605 let exam = published(&db).await;
1606 let id = exam.get_id().clone();
1607 let subject = a_subject(&db).await;
1608
1609 let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
1610 let drop_it = {
1611 let (db, exam, gate) = (db.clone(), exam, gate.clone());
1612 tokio::spawn(async move {
1613 gate.wait().await;
1614 delete(&db, exam).await
1615 })
1616 };
1617 let child = {
1618 let (db, exam_id, on, gate) = (db.clone(), id.clone(), *subject.get_id(), gate);
1619 tokio::spawn(async move {
1620 gate.wait().await;
1621 ask(&db, &exam_id, on).await
1622 })
1623 };
1624 let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1625 assert!(
1626 !matches!(child, Err(AppError::Db(_))),
1627 "round {round}: a raced question write must be answered, not 500: {child:?}"
1628 );
1629 assert!(
1630 !matches!(drop_it, Err(AppError::Db(_))),
1631 "round {round}: a raced delete must be answered, not 500: {drop_it:?}"
1632 );
1633
1634 if read(&db, &id).await.unwrap().is_none() {
1635 swept += 1;
1636 assert_eq!(
1637 crate::db::exam_question::list_for_exam(&db, &id, None, 0)
1638 .await
1639 .unwrap()
1640 .0
1641 .len(),
1642 0,
1643 "round {round}: a question outlived its exam"
1644 );
1645 assert!(
1646 !subject_stuck(&db, &subject).await,
1647 "round {round}: an orphan question left its subject undeletable"
1648 );
1649 } else if drop_it.is_ok() {
1650 panic!("round {round}: the delete reported success but the exam is still there");
1651 }
1652 }
1653 eprintln!(
1654 "Exam::delete raced by a question write: {swept}/4 concurrent rounds deleted the exam"
1655 );
1656 }
1657
1658 /// The student's half of the same picture problem: a drawing is a bare
1659 /// upsert — the exact pre-fix shape of [`crate::db::exam_answer::save`] — so it kept
1660 /// the hole the text answer just lost, blob and all. It now rides the same
1661 /// exam-row write the answer does. Both orders are forced by awaiting one
1662 /// side to completion before the other starts. Overlapped rounds may all
1663 /// lose the delete; that is not a failure.
1664 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1665 async fn a_drawing_written_inside_a_delete_never_outlives_the_exam() {
1666 use crate::domain::answer_image::AnswerImage;
1667 use crate::domain::note_file::FileContentType;
1668 let (db, _leases) = crate::database::init_test_db().await;
1669 let student = a_person(&db, "student", "student").await;
1670
1671 async fn draw(
1672 db: &Database,
1673 exam: &ExamId,
1674 question: &crate::domain::exam_question::ExamQuestionId,
1675 student: &UserId,
1676 ) -> Result<(AnswerImage, Option<String>), AppError> {
1677 let image = AnswerImage::new(
1678 exam,
1679 question,
1680 student,
1681 1,
1682 FileContentType::try_new("image/png").unwrap(),
1683 3,
1684 );
1685 crate::db::answer_image::upsert(db, image).await
1686 }
1687
1688 // Delete-first: the exam is gone before the drawing starts.
1689 {
1690 let exam = published(&db).await;
1691 let question = question_on(&exam, &db).await;
1692 let id = exam.get_id().clone();
1693 let on = question.get_id().clone();
1694 let dropped = delete(&db, exam).await;
1695 assert!(
1696 !matches!(dropped, Err(AppError::Db(_))),
1697 "delete-first: a delete must be answered, not 500: {dropped:?}"
1698 );
1699 assert!(
1700 read(&db, &id).await.unwrap().is_none(),
1701 "delete-first: the exam is still there after delete: {dropped:?}"
1702 );
1703 let child = draw(&db, &id, &on, &student).await;
1704 assert!(
1705 !matches!(child, Err(AppError::Db(_))),
1706 "delete-first: a drawing write must be answered, not 500: {child:?}"
1707 );
1708 assert_eq!(
1709 crate::db::answer_image::list_for_exam(&db, &id)
1710 .await
1711 .unwrap()
1712 .len(),
1713 0,
1714 "a drawing outlived its exam"
1715 );
1716 }
1717
1718 // Write-first: the drawing lands, then the delete sweeps it.
1719 {
1720 let exam = published(&db).await;
1721 let question = question_on(&exam, &db).await;
1722 let id = exam.get_id().clone();
1723 let on = question.get_id().clone();
1724 let child = draw(&db, &id, &on, &student).await;
1725 assert!(
1726 child.is_ok(),
1727 "write-first: the drawing must land before the delete: {child:?}"
1728 );
1729 let dropped = delete(&db, exam).await;
1730 assert!(
1731 !matches!(dropped, Err(AppError::Db(_))),
1732 "write-first: a delete must be answered, not 500: {dropped:?}"
1733 );
1734 assert!(
1735 read(&db, &id).await.unwrap().is_none(),
1736 "write-first: the exam is still there"
1737 );
1738 assert_eq!(
1739 crate::db::answer_image::list_for_exam(&db, &id)
1740 .await
1741 .unwrap()
1742 .len(),
1743 0,
1744 "a drawing outlived its exam"
1745 );
1746 }
1747
1748 // Overlapped rounds. Delete may lose every one of them.
1749 let mut swept = 0;
1750 for round in 0..4 {
1751 let exam = published(&db).await;
1752 let question = question_on(&exam, &db).await;
1753 let id = exam.get_id().clone();
1754
1755 let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
1756 let drop_it = {
1757 let (db, exam, gate) = (db.clone(), exam, gate.clone());
1758 tokio::spawn(async move {
1759 gate.wait().await;
1760 delete(&db, exam).await
1761 })
1762 };
1763 let child = {
1764 let (db, exam_id, on, student, gate) = (
1765 db.clone(),
1766 id.clone(),
1767 question.get_id().clone(),
1768 student,
1769 gate,
1770 );
1771 tokio::spawn(async move {
1772 gate.wait().await;
1773 draw(&db, &exam_id, &on, &student).await
1774 })
1775 };
1776 let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1777 assert!(
1778 !matches!(child, Err(AppError::Db(_))),
1779 "round {round}: a raced drawing write must be answered, not 500: {child:?}"
1780 );
1781 assert!(
1782 !matches!(drop_it, Err(AppError::Db(_))),
1783 "round {round}: a raced delete must be answered, not 500: {drop_it:?}"
1784 );
1785
1786 if read(&db, &id).await.unwrap().is_none() {
1787 swept += 1;
1788 assert_eq!(
1789 crate::db::answer_image::list_for_exam(&db, &id)
1790 .await
1791 .unwrap()
1792 .len(),
1793 0,
1794 "round {round}: a drawing outlived its exam"
1795 );
1796 } else if drop_it.is_ok() {
1797 panic!("round {round}: the delete reported success but the exam is still there");
1798 }
1799 }
1800 eprintln!(
1801 "Exam::delete raced by a drawing write: {swept}/4 concurrent rounds deleted the exam"
1802 );
1803 }
1804
1805 /// A picture is written through the same freeze gate as the question it
1806 /// hangs on, so it had the same hole — and one the row count does not even
1807 /// show: `delete_exam` collects the blob names to unlink *before* it calls
1808 /// [`crate::db::exam::delete`], so an image row landing after that snapshot
1809 /// strands its bytes on disk forever as well. It now rides the same
1810 /// exam-row write the question does. Both orders are forced by awaiting
1811 /// one side to completion before the other starts. Overlapped rounds may
1812 /// all lose the delete; that is not a failure.
1813 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1814 async fn a_picture_written_inside_a_delete_never_outlives_the_exam() {
1815 use crate::domain::note_file::FileContentType;
1816 use crate::domain::question_image::QuestionImage;
1817 let (db, _leases) = crate::database::init_test_db().await;
1818
1819 async fn shoot(
1820 db: &Database,
1821 exam: &ExamId,
1822 question: &crate::domain::exam_question::ExamQuestionId,
1823 ) -> Result<(QuestionImage, Option<String>), AppError> {
1824 let image = QuestionImage::new(
1825 exam,
1826 question,
1827 None,
1828 FileContentType::try_new("image/png").unwrap(),
1829 3,
1830 );
1831 crate::db::question_image::upsert(db, image).await
1832 }
1833
1834 // Delete-first: the exam is gone before the picture starts.
1835 {
1836 let exam = published(&db).await;
1837 let question = question_on(&exam, &db).await;
1838 let id = exam.get_id().clone();
1839 let on = question.get_id().clone();
1840 let dropped = delete(&db, exam).await;
1841 assert!(
1842 !matches!(dropped, Err(AppError::Db(_))),
1843 "delete-first: a delete must be answered, not 500: {dropped:?}"
1844 );
1845 assert!(
1846 read(&db, &id).await.unwrap().is_none(),
1847 "delete-first: the exam is still there after delete: {dropped:?}"
1848 );
1849 let child = shoot(&db, &id, &on).await;
1850 assert!(
1851 !matches!(child, Err(AppError::Db(_))),
1852 "delete-first: a picture write must be answered, not 500: {child:?}"
1853 );
1854 assert_eq!(
1855 crate::db::question_image::list_for_exam(&db, &id)
1856 .await
1857 .unwrap()
1858 .len(),
1859 0,
1860 "a picture outlived its exam"
1861 );
1862 }
1863
1864 // Write-first: the picture lands, then the delete sweeps it.
1865 {
1866 let exam = published(&db).await;
1867 let question = question_on(&exam, &db).await;
1868 let id = exam.get_id().clone();
1869 let on = question.get_id().clone();
1870 let child = shoot(&db, &id, &on).await;
1871 assert!(
1872 child.is_ok(),
1873 "write-first: the picture must land before the delete: {child:?}"
1874 );
1875 let dropped = delete(&db, exam).await;
1876 assert!(
1877 !matches!(dropped, Err(AppError::Db(_))),
1878 "write-first: a delete must be answered, not 500: {dropped:?}"
1879 );
1880 assert!(
1881 read(&db, &id).await.unwrap().is_none(),
1882 "write-first: the exam is still there"
1883 );
1884 assert_eq!(
1885 crate::db::question_image::list_for_exam(&db, &id)
1886 .await
1887 .unwrap()
1888 .len(),
1889 0,
1890 "a picture outlived its exam"
1891 );
1892 }
1893
1894 // Overlapped rounds. Delete may lose every one of them.
1895 let mut swept = 0;
1896 for round in 0..4 {
1897 let exam = published(&db).await;
1898 let question = question_on(&exam, &db).await;
1899 let id = exam.get_id().clone();
1900
1901 let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
1902 let drop_it = {
1903 let (db, exam, gate) = (db.clone(), exam, gate.clone());
1904 tokio::spawn(async move {
1905 gate.wait().await;
1906 delete(&db, exam).await
1907 })
1908 };
1909 let child = {
1910 let (db, exam_id, on, gate) =
1911 (db.clone(), id.clone(), question.get_id().clone(), gate);
1912 tokio::spawn(async move {
1913 gate.wait().await;
1914 shoot(&db, &exam_id, &on).await
1915 })
1916 };
1917 let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1918 assert!(
1919 !matches!(child, Err(AppError::Db(_))),
1920 "round {round}: a raced picture write must be answered, not 500: {child:?}"
1921 );
1922 assert!(
1923 !matches!(drop_it, Err(AppError::Db(_))),
1924 "round {round}: a raced delete must be answered, not 500: {drop_it:?}"
1925 );
1926
1927 if read(&db, &id).await.unwrap().is_none() {
1928 swept += 1;
1929 assert_eq!(
1930 crate::db::question_image::list_for_exam(&db, &id)
1931 .await
1932 .unwrap()
1933 .len(),
1934 0,
1935 "round {round}: a picture outlived its exam"
1936 );
1937 } else if drop_it.is_ok() {
1938 panic!("round {round}: the delete reported success but the exam is still there");
1939 }
1940 }
1941 eprintln!(
1942 "Exam::delete raced by a picture write: {swept}/4 concurrent rounds deleted the exam"
1943 );
1944 }
1945}