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_answer.rs416 lines, 15.1 KiBHistoryRawDownload
1//! The `exam_answer` table: the autosave upsert keyed by the (question, user,
2//! seq) sitting triple, the per-sitting and per-exam reads, and the sweeps a
3//! retake and the cascades use. The sitting key shape and the payload
4//! validation's pure half live in [`crate::domain::exam_answer`].
5
6use sqlx::PgConnection;
7
8use crate::database::{Database, tx_with_retry};
9use crate::domain::exam::ExamId;
10use crate::domain::exam_answer::{AnswerText, ExamAnswer};
11use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId};
12use crate::domain::timestamp::Timestamp;
13use crate::domain::user::UserId;
14use crate::error::{AppError, ValidationError};
15
16/// Save (or overwrite) `user`'s answer to `question` for sitting `seq` —
17/// the one write path, shared by the REST handler and the WebSocket room.
18/// The payload must match the question's kind: a choice question takes
19/// `selected` (the id of one of its choices), a text question takes `text`.
20/// The caller has already checked that the attempt is in progress. Keyed
21/// by `seq`, so a retake's save is a new row, not an overwrite of an
22/// earlier sitting's answer.
23pub async fn save(
24 db: &Database,
25 question: &ExamQuestion,
26 user: &UserId,
27 seq: i64,
28 selected: Option<String>,
29 text: Option<String>,
30) -> Result<ExamAnswer, AppError> {
31 let invalid = |field, reason| AppError::Validation(ValidationError::Invalid { field, reason });
32 let (selected, text) = match question.get_kind().as_str() {
33 "choice" => {
34 if text.is_some() {
35 return Err(invalid(
36 "text",
37 "a choice question takes selected, not text",
38 ));
39 }
40 let Some(selected) = selected else {
41 return Err(invalid("selected", "required for a choice question"));
42 };
43 // Membership, not a range: `selected` names an option by its
44 // stable id, so a reorder of the list can never repoint it.
45 let picked = question
46 .get_choices()
47 .unwrap_or_default()
48 .iter()
49 .find(|choice| choice.get_id().as_str() == selected)
50 .ok_or_else(|| invalid("selected", "must name one of the question's choices"))?;
51 (Some(picked.get_id().clone()), None)
52 }
53 _ => {
54 if selected.is_some() {
55 return Err(invalid(
56 "selected",
57 "a text question takes text, not selected",
58 ));
59 }
60 let Some(text) = text else {
61 return Err(invalid("text", "required for a text question"));
62 };
63 (None, Some(AnswerText::try_new(&text)?))
64 }
65 };
66 // The save locks the *exam row* before upserting the answer, in one
67 // transaction, and that is what ties the answer's fate to its exam:
68 // reading the exam does not survive
69 // [`crate::db::exam::delete`]'s window — a save landing after its
70 // cascade swept the answers but before it committed would have read an
71 // exam that was still there and written an orphan no sweep would ever
72 // visit. Locking the key the delete removes first makes the two
73 // serialize: the save either lands before the sweep (which then takes
74 // the row too) or finds no exam and answers the same `404` the old
75 // `no_exam` THROW did. Real foreign keys stand behind the lock — a
76 // child insert whose parent is gone refuses itself — which is what
77 // retired the bump-and-restore this used to ride on.
78 let question = question.clone();
79 let user = *user;
80 tx_with_retry(db, false, async move |conn| {
81 save_in(conn, &question, &user, seq, selected.clone(), text.clone()).await
82 })
83 .await
84}
85
86/// The locked exam-row probe plus the upsert, on one connection — split out
87/// so the exam room's room-bound save shares the exact statements.
88pub(crate) async fn save_in(
89 conn: &mut PgConnection,
90 question: &ExamQuestion,
91 user: &UserId,
92 seq: i64,
93 selected: Option<ChoiceId>,
94 text: Option<AnswerText>,
95) -> Result<ExamAnswer, AppError> {
96 let touched = sqlx::query!(
97 r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#,
98 question.get_exam().uuid(),
99 )
100 .fetch_optional(&mut *conn)
101 .await?;
102 if touched.is_none() {
103 return Err(AppError::NotFound);
104 }
105 let now = Timestamp::now();
106 sqlx::query_as!(
107 ExamAnswer,
108 r#"INSERT INTO exam_answer (exam, question, app_user, selected, text, updated_at, seq)
109 VALUES ($1, $2, $3, $4, $5, $6, $7)
110 ON CONFLICT (question, app_user, seq) DO UPDATE
111 SET selected = EXCLUDED.selected, text = EXCLUDED.text,
112 updated_at = EXCLUDED.updated_at
113 RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId",
114 app_user AS "user: UserId", seq,
115 selected AS "selected: ChoiceId",
116 text AS "text: AnswerText",
117 updated_at AS "updated_at: Timestamp""#,
118 question.get_exam().uuid(),
119 question.get_id().uuid(),
120 user.uuid(),
121 selected.as_ref().map(ChoiceId::as_str),
122 text.as_ref().map(AnswerText::as_str),
123 now.as_millis(),
124 seq,
125 )
126 .fetch_one(&mut *conn)
127 .await
128 .map_err(AppError::from)
129}
130
131/// One student's stored answer for a question in sitting `seq`, if any.
132pub async fn read(
133 db: &Database,
134 question: &ExamQuestionId,
135 user: &UserId,
136 seq: i64,
137) -> Result<Option<ExamAnswer>, AppError> {
138 Ok(sqlx::query_as!(
139 ExamAnswer,
140 r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
141 app_user AS "user: UserId", seq,
142 selected AS "selected: ChoiceId",
143 text AS "text: AnswerText",
144 updated_at AS "updated_at: Timestamp"
145 FROM exam_answer
146 WHERE question = $1 AND app_user = $2 AND seq = $3"#,
147 question.uuid(),
148 user.uuid(),
149 seq,
150 )
151 .fetch_optional(db)
152 .await?)
153}
154
155/// Drop one student's answer to a single question in sitting `seq`.
156pub async fn delete(
157 db: &Database,
158 question: &ExamQuestionId,
159 user: &UserId,
160 seq: i64,
161) -> Result<(), AppError> {
162 sqlx::query!(
163 r#"DELETE FROM exam_answer WHERE question = $1 AND app_user = $2 AND seq = $3"#,
164 question.uuid(),
165 user.uuid(),
166 seq,
167 )
168 .execute(db)
169 .await?;
170 Ok(())
171}
172
173/// One student's answers for a single sitting (`seq`) across an exam, in
174/// question (id) order — the live-sitting read-back and, for a past
175/// `seq`, that attempt's answer sheet.
176pub async fn list_for_exam_user(
177 db: &Database,
178 exam: &ExamId,
179 user: &UserId,
180 seq: i64,
181) -> Result<Vec<ExamAnswer>, AppError> {
182 Ok(sqlx::query_as!(
183 ExamAnswer,
184 r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
185 app_user AS "user: UserId", seq,
186 selected AS "selected: ChoiceId",
187 text AS "text: AnswerText",
188 updated_at AS "updated_at: Timestamp"
189 FROM exam_answer
190 WHERE exam = $1 AND app_user = $2 AND seq = $3
191 ORDER BY question ASC"#,
192 exam.uuid(),
193 user.uuid(),
194 seq,
195 )
196 .fetch_all(db)
197 .await?)
198}
199
200/// The distinct sittings a student has any answer for at `exam`, ascending
201/// — the index a history view lists attempts from.
202pub async fn list_seqs_for_user(
203 db: &Database,
204 exam: &ExamId,
205 user: &UserId,
206) -> Result<Vec<i64>, AppError> {
207 let rows = sqlx::query!(
208 r#"SELECT DISTINCT seq FROM exam_answer
209 WHERE exam = $1 AND app_user = $2 ORDER BY seq ASC"#,
210 exam.uuid(),
211 user.uuid(),
212 )
213 .fetch_all(db)
214 .await?;
215 Ok(rows.into_iter().map(|row| row.seq).collect())
216}
217
218/// Every answer of an exam — the live monitor aggregates these per student.
219pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<ExamAnswer>, AppError> {
220 Ok(sqlx::query_as!(
221 ExamAnswer,
222 r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
223 app_user AS "user: UserId", seq,
224 selected AS "selected: ChoiceId",
225 text AS "text: AnswerText",
226 updated_at AS "updated_at: Timestamp"
227 FROM exam_answer WHERE exam = $1 ORDER BY question ASC"#,
228 exam.uuid(),
229 )
230 .fetch_all(db)
231 .await?)
232}
233
234/// Drop one student's answers across an exam — a retake starts from a
235/// blank sheet.
236pub async fn delete_for_exam_user(
237 db: &Database,
238 exam: &ExamId,
239 user: &UserId,
240) -> Result<(), AppError> {
241 sqlx::query!(
242 r#"DELETE FROM exam_answer WHERE exam = $1 AND app_user = $2"#,
243 exam.uuid(),
244 user.uuid(),
245 )
246 .execute(db)
247 .await?;
248 Ok(())
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254 use crate::domain::exam::ExamId;
255 use crate::domain::exam_question::{ChoiceId, ChoiceInput, QuestionKind, QuestionSpec};
256
257 /// A three-option question whose `correct` is the option at `correct`.
258 /// Positions are a *test* convenience only — the ids are minted, and every
259 /// assertion below goes through `choice_id`.
260 fn choice_question(exam: &ExamId, points: i64, correct: usize) -> ExamQuestion {
261 let labels = ["a", "b", "c"];
262 let spec = QuestionSpec::try_new(
263 QuestionKind::try_new("choice").unwrap(),
264 Some(
265 labels
266 .iter()
267 .map(|l| ChoiceInput {
268 id: Some((*l).into()),
269 text: (*l).into(),
270 })
271 .collect(),
272 ),
273 Some(labels[correct].into()),
274 &[],
275 )
276 .unwrap();
277 ExamQuestion::test_new(exam, "pick one", points, spec)
278 }
279
280 /// The minted id of the question's option at `index`.
281 fn choice_id(question: &ExamQuestion, index: usize) -> ChoiceId {
282 question.get_choices().unwrap()[index].get_id().clone()
283 }
284
285 fn student() -> UserId {
286 UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa")
287 }
288
289 /// The bite test for the exam-row touch in [`save`]: it exists
290 /// to collide with [`crate::db::exam::delete`], so it must leave
291 /// the counter it borrows exactly where it found it — absent stays absent
292 /// (the boot backfill keys on `result_count = NONE`), and a real count is
293 /// not moved by a student typing. The race half is
294 /// `db::exam::tests::an_answer_written_inside_a_delete_never_outlives_the_exam`,
295 /// which needs a real server; this half is the arithmetic and runs anywhere.
296 #[tokio::test]
297 async fn a_save_puts_the_exams_mark_counter_back_exactly() {
298 use crate::domain::exam::{
299 ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,
300 };
301 let (db, _leases) = crate::database::init_test_db().await;
302 // The student is a foreign key now: a real row under the fixture's
303 // fixed key.
304 sqlx::query(
305 "INSERT INTO app_user (id, username, created_at) \
306 VALUES ($1, 'aaaa-fixture', 0)",
307 )
308 .bind(student().uuid())
309 .execute(&db)
310 .await
311 .unwrap();
312 let kinds = crate::domain::settings::Settings::defaults()
313 .get_exam_kinds()
314 .to_vec();
315 // The instance and the term are foreign keys now: real rows the
316 // fixture mints.
317 let (instance, _course) = crate::db::course::a_test_instance(&db).await;
318 let term = crate::db::term::a_test_term(&db).await;
319 let exam = crate::db::exam::create(
320 &db,
321 &student(),
322 &instance,
323 &term,
324 ExamTitle::try_new("quiz").unwrap(),
325 ExamDescription::try_new("").unwrap(),
326 ExamKind::try_new("yazili", &kinds).unwrap(),
327 ExamSchedule::try_new(None, None, None, None).unwrap(),
328 ExamAttemptLimit::try_new(1).unwrap(),
329 true,
330 false,
331 false,
332 )
333 .await
334 .unwrap();
335 let stored = async |db: &Database| -> Option<i64> {
336 sqlx::query_scalar::<_, Option<i64>>("SELECT result_count FROM exam WHERE id = $1")
337 .bind(exam.get_id().uuid())
338 .fetch_optional(db)
339 .await
340 .unwrap()
341 .flatten()
342 };
343 // The question is a foreign key: a real row, so the choice ids the
344 // answer names exist in the store too.
345 let spec = QuestionSpec::try_new(
346 QuestionKind::try_new("choice").unwrap(),
347 Some(
348 ["a", "b", "c"]
349 .iter()
350 .map(|l| ChoiceInput {
351 id: Some((*l).into()),
352 text: (*l).into(),
353 })
354 .collect(),
355 ),
356 Some("b".into()),
357 &[],
358 )
359 .unwrap();
360 let subject = crate::db::subject::create(
361 &db,
362 &crate::db::course::a_test_course(&db).await,
363 crate::domain::subject::SubjectName::try_new("sorular").unwrap(),
364 crate::domain::subject::SubjectDescription::try_new("").unwrap(),
365 )
366 .await
367 .unwrap();
368 let question = crate::db::exam_question::create(
369 &db,
370 exam.get_id(),
371 *subject.get_id(),
372 crate::domain::exam_question::QuestionText::try_new("pick one").unwrap(),
373 crate::domain::exam_question::QuestionPoints::try_new(10).unwrap(),
374 spec,
375 )
376 .await
377 .unwrap();
378 let pick = choice_id(&question, 1).as_str().to_string();
379
380 // A fresh exam's counter is zero (the column is NOT NULL DEFAULT 0),
381 // and a save must still not move it.
382 assert_eq!(stored(&db).await, Some(0), "the fixture starts at zero");
383 save(&db, &question, &student(), 1, Some(pick.clone()), None)
384 .await
385 .unwrap();
386 assert_eq!(
387 stored(&db).await,
388 Some(0),
389 "the touch left the counter alone"
390 );
391
392 // …and a counter that marks have moved is put back at its own value.
393 sqlx::query("UPDATE exam SET result_count = 7 WHERE id = $1")
394 .bind(exam.get_id().uuid())
395 .execute(&db)
396 .await
397 .unwrap();
398 save(&db, &question, &student(), 2, Some(pick), None)
399 .await
400 .unwrap();
401 assert_eq!(stored(&db).await, Some(7), "the touch moved a real count");
402
403 // The gate that makes the touch worth having: no exam, no answer.
404 let orphan = choice_question(
405 &ExamId::from_key("019732e3-7b00-7000-8000-00000000e0a0"),
406 10,
407 0,
408 );
409 let pick = choice_id(&orphan, 0).as_str().to_string();
410 let refused = save(&db, &orphan, &student(), 1, Some(pick), None).await;
411 assert!(
412 matches!(refused, Err(AppError::NotFound)),
413 "a save into a missing exam must 404, got {refused:?}"
414 );
415 }
416}