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_question.rs762 lines, 32.1 KiBHistoryRawDownload
1//! The `exam_question` table: row reads and listings, the answer-key join
2//! behind review hiding, and the field-scoped writes that tie the freeze gate
3//! and the subject's reference counter into their own transaction. The
4//! workflows and the freeze pre-flight live in
5//! [`crate::service::exam_question`].
6
7use std::collections::HashSet;
8
9use sqlx::PgConnection;
10
11use crate::database::{Database, tx_with_retry};
12use crate::db::exam_attempt::freeze_gate;
13use crate::db::page::{PagedList, Param};
14use crate::domain::bank_question::BankQuestionId;
15use crate::domain::exam::ExamId;
16use crate::domain::exam_question::{
17 Choice, ChoiceId, ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec,
18 QuestionText,
19};
20use crate::domain::subject::SubjectId;
21use crate::error::{AppError, ValidationError};
22use sqlx::types::Json;
23
24/// The one answer for a subject that isn't there — a claim missing it and the
25/// web layer's pre-flight lookup missing it are the same 400.
26fn dead_subject() -> AppError {
27 AppError::Validation(ValidationError::Invalid {
28 field: "subject_id",
29 reason: "subject does not exist",
30 })
31}
32
33/// The `choices` JSONB bind as the macros type the parameter — a
34/// `serde_json::Value`. A `Choice` is two plain strings: serializing one
35/// cannot fail.
36fn choices_as_value(choices: &[Choice]) -> serde_json::Value {
37 serde_json::to_value(choices).expect("Choice serialization cannot fail")
38}
39
40pub async fn create(
41 db: &Database,
42 exam: &ExamId,
43 subject: SubjectId,
44 text: QuestionText,
45 points: QuestionPoints,
46 spec: QuestionSpec,
47) -> Result<ExamQuestion, AppError> {
48 insert(db, exam, subject, text, points, spec, None).await
49}
50
51/// Like [`create`], but records the bank template this question was
52/// instantiated from (`POST …/questions/from-bank/{bid}`).
53pub async fn create_from_bank(
54 db: &Database,
55 exam: &ExamId,
56 subject: SubjectId,
57 text: QuestionText,
58 points: QuestionPoints,
59 spec: QuestionSpec,
60 source: BankQuestionId,
61) -> Result<ExamQuestion, AppError> {
62 insert(db, exam, subject, text, points, spec, Some(source)).await
63}
64
65#[allow(clippy::too_many_arguments)]
66async fn insert(
67 db: &Database,
68 exam: &ExamId,
69 subject: SubjectId,
70 text: QuestionText,
71 points: QuestionPoints,
72 spec: QuestionSpec,
73 from_bank: Option<BankQuestionId>,
74) -> Result<ExamQuestion, AppError> {
75 let question = ExamQuestion {
76 id: ExamQuestionId::generate(),
77 exam: exam.clone(),
78 subject,
79 text,
80 points,
81 kind: spec.kind,
82 choices: spec.choices.map(Json),
83 correct: spec.correct,
84 from_bank,
85 // An insert never banks anything: only a to-bank save writes this.
86 banked_as: None,
87 };
88 // The freeze gate and the subject's reference ride in the same
89 // transaction as the insert: a question cannot appear under an exam
90 // somebody has already started, and the claim that accounts for it
91 // cannot outlive a row that never landed. A missed claim means the
92 // subject is already gone — the same 400 the web layer's pre-flight
93 // check answers with.
94 //
95 // The id is a freshly minted UUIDv7, so no rival can aim at it: the
96 // only possible duplicate key is one this call minted, which is none.
97 let exam = exam.clone();
98 tx_with_retry(db, false, async move |conn| {
99 freeze_gate(conn, &exam).await?;
100 claim_subject_and_insert(conn, &question).await
101 })
102 .await
103}
104
105/// The subject's reference claim and the row insert as one statement — the
106/// counter and the row commit together, and zero rows out means the subject
107/// was already gone (the claim's `UPDATE` found nothing to increment). The
108/// same verdict as the old `question_subject_gone` THROW, which nothing
109/// else could reach: the insert is refused with its claim, atomically.
110async fn claim_subject_and_insert(
111 conn: &mut PgConnection,
112 question: &ExamQuestion,
113) -> Result<ExamQuestion, AppError> {
114 let created = sqlx::query_as!(
115 ExamQuestion,
116 r#"WITH seat AS (
117 UPDATE subject SET exam_question_count = subject.exam_question_count + 1
118 WHERE id = $1
119 RETURNING 1)
120 INSERT INTO exam_question (id, exam, subject, text, kind, points,
121 choices, correct, from_bank, banked_as)
122 SELECT $2, $3, $1, $4, $5, $6, $7, $8, $9, NULL
123 WHERE EXISTS (SELECT 1 FROM seat)
124 RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId",
125 subject AS "subject: SubjectId", text AS "text: QuestionText",
126 kind AS "kind: QuestionKind", points AS "points: QuestionPoints",
127 choices AS "choices: Json<Vec<Choice>>",
128 correct AS "correct: ChoiceId",
129 from_bank AS "from_bank: BankQuestionId",
130 banked_as AS "banked_as: BankQuestionId""#,
131 question.subject.uuid(),
132 question.id.uuid(),
133 question.exam.uuid(),
134 question.text.as_str(),
135 question.kind.as_str(),
136 question.points.as_i64(),
137 question
138 .choices
139 .as_ref()
140 .map(|json| choices_as_value(&json.0)),
141 question.correct.as_ref().map(ChoiceId::as_str),
142 question.from_bank.as_ref().map(BankQuestionId::uuid),
143 )
144 .fetch_optional(&mut *conn)
145 .await?;
146 created.ok_or_else(dead_subject)
147}
148
149pub async fn read(db: &Database, id: &ExamQuestionId) -> Result<Option<ExamQuestion>, AppError> {
150 Ok(sqlx::query_as!(
151 ExamQuestion,
152 r#"SELECT id AS "id: ExamQuestionId", exam AS "exam: ExamId",
153 subject AS "subject: SubjectId", text AS "text: QuestionText",
154 kind AS "kind: QuestionKind", points AS "points: QuestionPoints",
155 choices AS "choices: Json<Vec<Choice>>",
156 correct AS "correct: ChoiceId",
157 from_bank AS "from_bank: BankQuestionId",
158 banked_as AS "banked_as: BankQuestionId"
159 FROM exam_question WHERE id = $1"#,
160 id.uuid(),
161 )
162 .fetch_optional(db)
163 .await?)
164}
165
166/// The exam's questions in presentation order (UUIDv7 ids sort by creation).
167pub async fn list_for_exam(
168 db: &Database,
169 exam: &ExamId,
170 limit: Option<i64>,
171 offset: i64,
172) -> Result<(Vec<ExamQuestion>, i64), AppError> {
173 PagedList::new("exam_question WHERE exam = $1", "ORDER BY id ASC")
174 .bind(Param::Uuid(exam.uuid()))
175 .run::<ExamQuestion>(limit, offset, db)
176 .await
177}
178
179/// The ids of `exam`'s questions that share a bank template with a question
180/// under one of `live` — the questions two exams hold identical `correct`
181/// for, because the bank copies the key into every instantiation. Keyed on
182/// the template, never on the exam, so only the overlapping questions are
183/// named. Empty when `live` is empty.
184///
185/// A question links to a template through *either* column and both must be
186/// read, on both sides of the join: `from_bank` is the template it was
187/// instantiated from, `banked_as` the template minted by saving it into the
188/// bank ([`link_banked_as`]). A question authored by hand in exam A
189/// and then saved to the bank holds only `banked_as`, while its copy in
190/// exam B holds only `from_bank` — matching `from_bank` to `from_bank` saw
191/// neither and leaked A's key while B was live. A single coalesced key per
192/// row is not enough either: a question instantiated from one template and
193/// re-saved as another carries *both*, and only the second one may be the
194/// shared link.
195///
196/// So: collect every template id reachable from a live exam by either
197/// column, then name any of `exam`'s questions pointing at one by either
198/// column.
199pub async fn list_shared_with(
200 db: &Database,
201 exam: &ExamId,
202 live: &[ExamId],
203) -> Result<HashSet<String>, AppError> {
204 if live.is_empty() {
205 return Ok(HashSet::new());
206 }
207 let live = live.iter().map(ExamId::uuid).collect::<Vec<_>>();
208 let rows = sqlx::query!(
209 r#"WITH shared AS (
210 SELECT from_bank AS t FROM exam_question
211 WHERE exam = ANY($1) AND from_bank IS NOT NULL
212 UNION
213 SELECT banked_as FROM exam_question
214 WHERE exam = ANY($1) AND banked_as IS NOT NULL)
215 SELECT q.id AS "id: ExamQuestionId" FROM exam_question q
216 WHERE q.exam = $2
217 AND (q.from_bank IN (SELECT t FROM shared)
218 OR q.banked_as IN (SELECT t FROM shared))"#,
219 &live,
220 exam.uuid(),
221 )
222 .fetch_all(db)
223 .await?;
224 Ok(rows.into_iter().map(|row| row.id.key()).collect())
225}
226
227/// Write the editable fields, refused outright once the exam has an
228/// attempt — the freeze gate is part of this transaction, not a check the
229/// caller made a moment earlier under a lock.
230///
231/// Field-scoped, no longer a whole-row save. The row also carries
232/// `from_bank`/`banked_as`, which [`link_banked_as`] writes from a
233/// *different* request: re-stating this snapshot's copy of them would
234/// revert a to-bank save that landed in between. That is exactly what the
235/// caller's old `EXAM_LOCK.write()` used to order (inside one process), and
236/// naming the columns removes the need for any ordering at all.
237pub async fn update(
238 db: &Database,
239 question: ExamQuestion,
240 subject: SubjectId,
241 text: QuestionText,
242 points: QuestionPoints,
243 spec: QuestionSpec,
244) -> Result<ExamQuestion, AppError> {
245 // A re-tag moves a reference, and the move rides the very transaction
246 // that moves the link: the old subject's release, the new one's claim
247 // and the row write commit together or not at all, so no crash can
248 // strand a count on a subject nothing points at (which would make it
249 // undeletable forever).
250 //
251 // The two are armed on *different* conditions, which is the whole of
252 // the rule: the counter statements only when the link actually
253 // changes, but the CAS whenever this write *carries* the link — and it
254 // always does, because the handler fills an omitted `subject_id` from
255 // the row it read (`web::exams::questions`), so `subject` is in the
256 // `SET` of every one of these updates. Arming the CAS on "changed"
257 // instead would leave the re-stater through: a PATCH carrying the
258 // subject its own stale snapshot held, sent while a rival's move
259 // already landed, writes that stale subject straight back over the
260 // winner — a revert with the counters left pointing at the move.
261 let retag = (subject != question.subject).then_some((subject, question.subject));
262 tx_with_retry(db, false, async move |conn| {
263 // Freeze first, as always: it outranks every caller gate, and a
264 // frozen exam answers the same 409 the pre-flight check gave.
265 freeze_gate(conn, &question.exam).await?;
266 if let Some((next, previous)) = &retag {
267 sqlx::query!(
268 r#"UPDATE subject SET exam_question_count =
269 GREATEST(exam_question_count - 1, 0)
270 WHERE id = $1"#,
271 previous.uuid(),
272 )
273 .execute(&mut *conn)
274 .await?;
275 let claimed = sqlx::query!(
276 r#"UPDATE subject SET exam_question_count = subject.exam_question_count + 1
277 WHERE id = $1 RETURNING 1 AS n"#,
278 next.uuid(),
279 )
280 .fetch_optional(&mut *conn)
281 .await?;
282 if claimed.is_none() {
283 return Err(dead_subject());
284 }
285 }
286 // The CAS: the row write matches only while the question still sits on
287 // the subject this handler read. A genuine no-op re-state passes it
288 // trivially (the row holds exactly what is expected); a stale one —
289 // whether it moves the link or restates it — matches nothing, aborts
290 // the whole transaction, and so claims nothing and answers 409.
291 let written = sqlx::query_as!(
292 ExamQuestion,
293 r#"UPDATE exam_question
294 SET subject = $2, text = $3, points = $4, kind = $5,
295 choices = $6, correct = $7
296 WHERE id = $1 AND subject = $8
297 RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId",
298 subject AS "subject: SubjectId", text AS "text: QuestionText",
299 kind AS "kind: QuestionKind", points AS "points: QuestionPoints",
300 choices AS "choices: Json<Vec<Choice>>",
301 correct AS "correct: ChoiceId",
302 from_bank AS "from_bank: BankQuestionId",
303 banked_as AS "banked_as: BankQuestionId""#,
304 question.id.uuid(),
305 subject.uuid(),
306 text.as_str(),
307 points.as_i64(),
308 spec.kind.as_str(),
309 spec.choices.as_deref().map(choices_as_value),
310 spec.correct.as_ref().map(ChoiceId::as_str),
311 question.subject.uuid(),
312 )
313 .fetch_optional(&mut *conn)
314 .await?;
315 let Some(written) = written else {
316 // The row is gone, or it moved under the snapshot. The same
317 // 404 an empty write used to answer with distinguishes the
318 // deleted-row case; anything still standing is a stale read,
319 // which is the 409.
320 let live = sqlx::query!(
321 r#"SELECT EXISTS(SELECT 1 FROM exam_question WHERE id = $1) AS live"#,
322 question.id.uuid(),
323 )
324 .fetch_one(&mut *conn)
325 .await?;
326 if !live.live.unwrap_or(false) {
327 return Err(AppError::NotFound);
328 }
329 return Err(AppError::Conflict(
330 "the subject this question was read on changed since; re-read and retry",
331 ));
332 };
333 Ok(written)
334 })
335 .await
336}
337
338/// Point the question's `banked_as` at the bank template it was just saved
339/// into (`POST …/questions/{qid}/to-bank`). The mirror direction of the
340/// `from_bank` [`create_from_bank`] writes, and deliberately a
341/// *different* column: a question inserted from the bank has not been saved
342/// to it, and one field for both would make the client claim it was.
343/// Overwrites any earlier link: repeat saves mint a new template and the
344/// newest one wins.
345///
346/// Field-scoped write, unlike [`update`]: the caller awaits a bank
347/// insert plus the whole blob-copy loop between reading this row and
348/// linking it, so the row it holds is long stale by now — a whole-row save
349/// would silently revert whatever landed in that window.
350pub async fn link_banked_as(
351 db: &Database,
352 question: ExamQuestion,
353 template: BankQuestionId,
354) -> Result<ExamQuestion, AppError> {
355 let linked = sqlx::query_as!(
356 ExamQuestion,
357 r#"UPDATE exam_question SET banked_as = $2 WHERE id = $1
358 RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId",
359 subject AS "subject: SubjectId", text AS "text: QuestionText",
360 kind AS "kind: QuestionKind", points AS "points: QuestionPoints",
361 choices AS "choices: Json<Vec<Choice>>",
362 correct AS "correct: ChoiceId",
363 from_bank AS "from_bank: BankQuestionId",
364 banked_as AS "banked_as: BankQuestionId""#,
365 question.id.uuid(),
366 template.uuid(),
367 )
368 .fetch_optional(db)
369 .await?;
370 linked.ok_or(AppError::NotFound)
371}
372
373/// Delete the question and cascade-remove its answers and image rows, so
374/// neither can point at a missing question. The image *blobs* are the web
375/// layer's to remove — it collects their names before calling this.
376/// Refused once the exam has an attempt, in the same transaction as the
377/// delete — and the cascade now shares that transaction too, so a failure
378/// mid-way can no longer strand answers whose question survived.
379pub async fn delete(db: &Database, question: ExamQuestion) -> Result<ExamQuestion, AppError> {
380 tx_with_retry(db, false, async move |conn| {
381 freeze_gate(conn, &question.exam).await?;
382 sqlx::query!(
383 r#"DELETE FROM exam_answer WHERE question = $1"#,
384 question.id.uuid(),
385 )
386 .execute(&mut *conn)
387 .await?;
388 sqlx::query!(
389 r#"DELETE FROM question_image WHERE question = $1"#,
390 question.id.uuid(),
391 )
392 .execute(&mut *conn)
393 .await?;
394 let deleted = sqlx::query_as!(
395 ExamQuestion,
396 r#"DELETE FROM exam_question WHERE id = $1
397 RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId",
398 subject AS "subject: SubjectId", text AS "text: QuestionText",
399 kind AS "kind: QuestionKind", points AS "points: QuestionPoints",
400 choices AS "choices: Json<Vec<Choice>>",
401 correct AS "correct: ChoiceId",
402 from_bank AS "from_bank: BankQuestionId",
403 banked_as AS "banked_as: BankQuestionId""#,
404 question.id.uuid(),
405 )
406 .fetch_optional(&mut *conn)
407 .await?;
408 // The subject's reference is given back inside this same transaction,
409 // driven off what the delete actually removed — a question that wasn't
410 // there decrements nothing.
411 if let Some(deleted) = &deleted {
412 sqlx::query!(
413 r#"UPDATE subject SET exam_question_count =
414 GREATEST(exam_question_count - 1, 0)
415 WHERE id = $1"#,
416 deleted.subject.uuid(),
417 )
418 .execute(&mut *conn)
419 .await?;
420 }
421 deleted.ok_or(AppError::NotFound)
422 })
423 .await
424}
425
426#[cfg(test)]
427mod tests {
428 use super::*;
429 use crate::domain::exam_question::QuestionKind;
430
431 fn kind(value: &str) -> QuestionKind {
432 QuestionKind::try_new(value).unwrap()
433 }
434
435 /// The subject reference counter, which is what the subject's delete guard
436 /// reads: every one of these asserts *stored* state, because a claim that
437 /// outlives the row it accounts for makes its subject undeletable forever.
438 mod counters {
439 use super::*;
440 use crate::database::init_test_db;
441 use crate::domain::exam::{
442 Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,
443 };
444 use crate::domain::settings::Settings;
445 use crate::domain::subject::{Subject, SubjectDescription, SubjectName};
446 use crate::domain::user::UserId;
447
448 async fn an_exam(db: &Database) -> Exam {
449 // The creator is a foreign key now: a real `app_user` row under
450 // the fixture's fixed key.
451 let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
452 sqlx::query(
453 "INSERT INTO app_user (id, username, created_at) \
454 VALUES ($1, 'acdc-fixture', 0)",
455 )
456 .bind(creator.uuid())
457 .execute(db)
458 .await
459 .unwrap();
460 let kinds = Settings::defaults().get_exam_kinds().to_vec();
461 // The instance and the term are foreign keys now: real rows the
462 // fixture mints, per call.
463 let (instance, _course) = crate::db::course::a_test_instance(db).await;
464 let term = crate::db::term::a_test_term(db).await;
465 crate::db::exam::create(
466 db,
467 &creator,
468 &instance,
469 &term,
470 ExamTitle::try_new("practice").unwrap(),
471 ExamDescription::try_new("").unwrap(),
472 ExamKind::try_new("yazili", &kinds).unwrap(),
473 ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None)
474 .unwrap(),
475 ExamAttemptLimit::try_new(1).unwrap(),
476 true,
477 false,
478 false,
479 )
480 .await
481 .unwrap()
482 }
483
484 async fn a_subject(db: &Database) -> Subject {
485 crate::db::subject::create(
486 db,
487 &crate::db::course::a_test_course(db).await,
488 SubjectName::try_new("topic").unwrap(),
489 SubjectDescription::try_new("").unwrap(),
490 )
491 .await
492 .unwrap()
493 }
494
495 /// The editable payload, fresh per call (each one is consumed).
496 fn body() -> (QuestionText, QuestionPoints, QuestionSpec) {
497 (
498 QuestionText::try_new("3 + 3?").unwrap(),
499 QuestionPoints::try_new(5).unwrap(),
500 QuestionSpec::try_new(kind("text"), None, None, &[]).unwrap(),
501 )
502 }
503
504 async fn a_question(exam: &Exam, on: &SubjectId, db: &Database) -> ExamQuestion {
505 let (text, points, spec) = body();
506 create(db, exam.get_id(), *on, text, points, spec)
507 .await
508 .unwrap()
509 }
510
511 async fn moved(
512 question: ExamQuestion,
513 to: &SubjectId,
514 db: &Database,
515 ) -> Result<ExamQuestion, AppError> {
516 let (text, points, spec) = body();
517 update(db, question, *to, text, points, spec).await
518 }
519
520 /// The stored `exam_question_count` on one subject, absent = zero.
521 async fn count_on(subject: &SubjectId, db: &Database) -> i64 {
522 sqlx::query_scalar::<_, i64>("SELECT exam_question_count FROM subject WHERE id = $1")
523 .bind(subject.uuid())
524 .fetch_one(db)
525 .await
526 .unwrap()
527 }
528
529 async fn rows(sql: &str, db: &Database) -> usize {
530 sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!(
531 "SELECT count(*) FROM ({sql}) AS t"
532 )))
533 .fetch_one(db)
534 .await
535 .unwrap() as usize
536 }
537
538 /// The freeze outranks the counter move, on both paths — and because
539 /// the claim now rides the refused transaction, "outranks" has to mean
540 /// the counters read as if nothing ran.
541 #[tokio::test]
542 async fn a_frozen_exam_leaves_the_subject_counters_untouched() {
543 let (db, _leases) = init_test_db().await;
544 let exam = an_exam(&db).await;
545 let (from, to) = (a_subject(&db).await, a_subject(&db).await);
546 let (from, to) = (*from.get_id(), *to.get_id());
547 let question = a_question(&exam, &from, &db).await;
548 assert_eq!(count_on(&from, &db).await, 1);
549
550 // A real user row: starting a sitting moves that student's badge
551 // counter in the same transaction, and an `UPDATE` has nothing to
552 // write to without one.
553 let student = crate::db::user::create(
554 &db,
555 crate::domain::user::Username::try_new("ogrenci").unwrap(),
556 None,
557 )
558 .await
559 .unwrap();
560 crate::service::exam_attempt::start(&db, &exam, student.get_id())
561 .await
562 .unwrap();
563
564 let (text, points, spec) = body();
565 let error = create(&db, exam.get_id(), to, text, points, spec)
566 .await
567 .expect_err("a started exam takes no new questions");
568 assert!(matches!(error, AppError::Conflict(_)), "{error:?}");
569 assert_eq!(count_on(&to, &db).await, 0, "the refused claim rolled back");
570
571 let error = moved(question, &to, &db)
572 .await
573 .expect_err("a started exam takes no re-tag either");
574 assert!(matches!(error, AppError::Conflict(_)), "{error:?}");
575 assert_eq!(count_on(&from, &db).await, 1, "the release rolled back too");
576 assert_eq!(count_on(&to, &db).await, 0);
577 }
578
579 /// The create-path invariant: a refused create writes neither the row
580 /// nor a count — least of all on a subject it would have to invent.
581 #[tokio::test]
582 async fn a_create_on_a_dead_subject_writes_neither_row_nor_count() {
583 let (db, _leases) = init_test_db().await;
584 let exam = an_exam(&db).await;
585 let subject = a_subject(&db).await;
586 let id = *subject.get_id();
587 crate::db::subject::delete(&db, subject).await.unwrap();
588
589 let (text, points, spec) = body();
590 let error = create(&db, exam.get_id(), id, text, points, spec)
591 .await
592 .expect_err("a subject that is gone must not be taggable");
593 assert!(error.to_string().contains("subject does not exist"));
594 assert_eq!(
595 rows("SELECT id FROM exam_question", &db).await,
596 0,
597 "a refused create may write no row"
598 );
599 assert_eq!(
600 rows("SELECT id FROM subject", &db).await,
601 0,
602 "…and least of all a count on a subject it just brought back"
603 );
604 }
605
606 #[tokio::test]
607 async fn a_subject_move_moves_the_count() {
608 let (db, _leases) = init_test_db().await;
609 let exam = an_exam(&db).await;
610 let (from, to) = (a_subject(&db).await, a_subject(&db).await);
611 let (from, to) = (*from.get_id(), *to.get_id());
612 let question = a_question(&exam, &from, &db).await;
613
614 let after = moved(question, &to, &db).await.unwrap();
615 assert_eq!(after.get_subject(), &to);
616 assert_eq!(count_on(&from, &db).await, 0, "the old subject is free");
617 assert_eq!(count_on(&to, &db).await, 1, "the new one is not");
618 }
619
620 #[tokio::test]
621 async fn a_move_to_a_dead_subject_leaves_everything_untouched() {
622 let (db, _leases) = init_test_db().await;
623 let exam = an_exam(&db).await;
624 let from = *a_subject(&db).await.get_id();
625 let dead = a_subject(&db).await;
626 let gone = *dead.get_id();
627 crate::db::subject::delete(&db, dead).await.unwrap();
628 let question = a_question(&exam, &from, &db).await;
629
630 let error = moved(question.clone(), &gone, &db)
631 .await
632 .expect_err("a subject that is gone must not be taggable");
633 assert!(error.to_string().contains("subject does not exist"));
634 let stored = read(&db, question.get_id()).await.unwrap().unwrap();
635 assert_eq!(stored.get_subject(), &from, "the link never moved");
636 assert_eq!(
637 count_on(&from, &db).await,
638 1,
639 "the release rolled back with the claim"
640 );
641 assert_eq!(rows("SELECT id FROM subject", &db).await, 1);
642 }
643
644 /// The double-claim guard. Both movers compute their claim and release
645 /// from the row as *they* read it, so two PATCHes re-tagging the same
646 /// question both release the old subject and both claim their own
647 /// target — two counts for one link, and the loser's target is
648 /// undeletable forever. The second call here runs on the struct read
649 /// before the first one landed: it must be refused outright, and the
650 /// counts must read as if it never ran.
651 ///
652 /// Drop `AND subject = $ref_expected` from the row write in
653 /// [`update`] and this goes red on the very first
654 /// assertion — the stale mover is happily applied.
655 #[tokio::test]
656 async fn a_stale_mover_is_refused_and_claims_nothing() {
657 let (db, _leases) = init_test_db().await;
658 let exam = an_exam(&db).await;
659 let from = *a_subject(&db).await.get_id();
660 let to = *a_subject(&db).await.get_id();
661 let other = *a_subject(&db).await.get_id();
662 let question = a_question(&exam, &from, &db).await;
663 let stale = question.clone();
664
665 moved(question, &to, &db).await.unwrap();
666 let error = moved(stale.clone(), &other, &db)
667 .await
668 .expect_err("a mover that read a subject it no longer holds must be refused");
669 assert!(
670 matches!(error, AppError::Conflict(_)),
671 "a lost CAS is a conflict, not a 404 or a 500: {error:?}"
672 );
673
674 let stored = read(&db, stale.get_id()).await.unwrap().unwrap();
675 assert_eq!(stored.get_subject(), &to, "the winner's link");
676 assert_eq!(count_on(&from, &db).await, 0, "released once, not twice");
677 assert_eq!(count_on(&to, &db).await, 1, "claimed once");
678 assert_eq!(count_on(&other, &db).await, 0, "never claimed");
679 }
680
681 /// The other half of the same race, and the one arming on "the subject
682 /// changed" lets through: this PATCH carries the subject its snapshot
683 /// already held, so it moves no counter — but a rival's move landed
684 /// first, and writing that stale subject back would revert the winner
685 /// while both counters still describe the move. The handler fills an
686 /// omitted `subject_id` from the row it read, so this is also every
687 /// text-only PATCH sent from a stale snapshot.
688 ///
689 /// Arm the CAS on the re-tag instead of on the write and this goes red
690 /// on the first assertion — the re-state lands 200.
691 #[tokio::test]
692 async fn a_stale_re_stater_is_refused_and_reverts_nothing() {
693 let (db, _leases) = init_test_db().await;
694 let exam = an_exam(&db).await;
695 let from = *a_subject(&db).await.get_id();
696 let to = *a_subject(&db).await.get_id();
697 let question = a_question(&exam, &from, &db).await;
698 let stale = question.clone();
699
700 moved(question, &to, &db).await.unwrap();
701 let error = moved(stale.clone(), &from, &db)
702 .await
703 .expect_err("re-stating a subject a rival moved off must be refused");
704 assert!(
705 matches!(error, AppError::Conflict(_)),
706 "a lost CAS is a conflict, not a silent revert: {error:?}"
707 );
708
709 let stored = read(&db, stale.get_id()).await.unwrap().unwrap();
710 assert_eq!(stored.get_subject(), &to, "the winner's link stands");
711 assert_eq!(
712 count_on(&from, &db).await,
713 0,
714 "released once, and stayed so"
715 );
716 assert_eq!(count_on(&to, &db).await, 1, "claimed once, and stayed so");
717 }
718
719 /// …and the price of arming the CAS on every write is nothing: a PATCH
720 /// re-stating the subject the row really holds passes it trivially.
721 #[tokio::test]
722 async fn a_no_op_re_state_still_lands() {
723 let (db, _leases) = init_test_db().await;
724 let exam = an_exam(&db).await;
725 let on = *a_subject(&db).await.get_id();
726 let question = a_question(&exam, &on, &db).await;
727
728 let (_, points, spec) = body();
729 let after = update(
730 &db,
731 question,
732 on,
733 QuestionText::try_new("4 + 4?").unwrap(),
734 points,
735 spec,
736 )
737 .await
738 .expect("re-stating the subject the row holds is not a conflict");
739 assert_eq!(after.get_text().as_str(), "4 + 4?");
740 assert_eq!(after.get_subject(), &on);
741 assert_eq!(count_on(&on, &db).await, 1, "no counter moved");
742 }
743
744 /// A re-tag of a question whose row is gone is still the 404 it was,
745 /// not the stale-mover 409 — the two empty-`$row` cases stay apart.
746 #[tokio::test]
747 async fn a_move_of_a_deleted_question_is_still_a_404() {
748 let (db, _leases) = init_test_db().await;
749 let exam = an_exam(&db).await;
750 let from = *a_subject(&db).await.get_id();
751 let to = *a_subject(&db).await.get_id();
752 let question = a_question(&exam, &from, &db).await;
753 delete(&db, question.clone()).await.unwrap();
754
755 let error = moved(question, &to, &db)
756 .await
757 .expect_err("a deleted question cannot be re-tagged");
758 assert!(matches!(error, AppError::NotFound), "{error:?}");
759 assert_eq!(count_on(&to, &db).await, 0, "and nothing was claimed");
760 }
761 }
762}