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

answer_image.rs375 lines, 13.5 KiBHistoryRawDownload
1//! The `answer_image` table: the drawing upsert that names the blob it
2//! replaces from inside its own transaction, the per-sitting and per-exam
3//! reads, and the sweeps the retake and cascades use. The row's pure half —
4//! ids and the fresh-blob-name constructor — lives in
5//! [`crate::domain::answer_image`]; the blob bytes stay the web layer's.
6
7use sqlx::PgConnection;
8
9use crate::database::{Database, tx_with_retry};
10use crate::domain::answer_image::AnswerImage;
11use crate::domain::course::CourseId;
12use crate::domain::exam::ExamId;
13use crate::domain::exam_question::ExamQuestionId;
14use crate::domain::note_file::FileContentType;
15use crate::domain::user::UserId;
16use crate::error::AppError;
17
18/// Create or replace the student's drawing for the question — the natural
19/// (question, user, seq) primary key makes this the whole "one drawing per
20/// student per question per sitting" story — handing back what it stored
21/// plus the blob name it replaced, for the caller to take off disk.
22///
23/// The replaced name is read *inside this transaction*, not by the caller
24/// in front of it: two uploads to one (question, user, seq) both write this
25/// row, so they contend and the loser re-reads the winner's blob name,
26/// where two pre-reads both saw the *old* blob and left the loser's fresh
27/// one on disk with nothing pointing at it. Same shape as
28/// [`crate::db::question_image::upsert`].
29///
30/// `NotFound` = the exam is gone, and the drawing was *not* written. The
31/// write locks the exam row before upserting, in this one transaction, so
32/// the exam's existence is something this write *locks* rather than
33/// something a gate read a moment earlier: a bare upsert landing after
34/// [`delete`](crate::db::exam::delete) removed the exam but before it
35/// committed was swept by nothing — its `DELETE answer_image WHERE exam`
36/// ran on a snapshot predating this row — and both sides reported success.
37/// That stranded the blob as well as the row: `delete_exam` collects the
38/// names to unlink *before* it calls the delete, so bytes written after
39/// that snapshot stay on disk forever. Locking the key the delete removes
40/// serializes the pair — this is the shape
41/// [`crate::db::exam_answer::save`] takes for the text half of the same
42/// answer sheet, and for the same reason.
43pub async fn upsert(
44 db: &Database,
45 image: AnswerImage,
46) -> Result<(AnswerImage, Option<String>), AppError> {
47 tx_with_retry(db, false, async move |conn| upsert_in(conn, &image).await).await
48}
49
50/// The locked exam-row probe plus the upsert, on one connection.
51pub(crate) async fn upsert_in(
52 conn: &mut PgConnection,
53 image: &AnswerImage,
54) -> Result<(AnswerImage, Option<String>), AppError> {
55 let touched = sqlx::query!(
56 r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#,
57 image.exam.uuid(),
58 )
59 .fetch_optional(&mut *conn)
60 .await?;
61 if touched.is_none() {
62 return Err(AppError::NotFound);
63 }
64 let replaced = sqlx::query!(
65 r#"SELECT file FROM answer_image
66 WHERE question = $1 AND app_user = $2 AND seq = $3"#,
67 image.question.uuid(),
68 image.user.uuid(),
69 image.seq,
70 )
71 .fetch_optional(&mut *conn)
72 .await?
73 .map(|row| row.file);
74 let stored = sqlx::query_as!(
75 AnswerImage,
76 r#"INSERT INTO answer_image (exam, question, app_user, file, content_type, size, seq)
77 VALUES ($1, $2, $3, $4, $5, $6, $7)
78 ON CONFLICT (question, app_user, seq) DO UPDATE
79 SET file = EXCLUDED.file, content_type = EXCLUDED.content_type,
80 size = EXCLUDED.size
81 RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId",
82 app_user AS "user: UserId", seq, file,
83 content_type AS "content_type: FileContentType", size"#,
84 image.exam.uuid(),
85 image.question.uuid(),
86 image.user.uuid(),
87 image.file,
88 image.content_type.as_str(),
89 image.size,
90 image.seq,
91 )
92 .fetch_one(&mut *conn)
93 .await?;
94 Ok((stored, replaced))
95}
96
97/// The student's drawing for one question in one sitting, if any.
98pub async fn read(
99 db: &Database,
100 question: &ExamQuestionId,
101 user: &UserId,
102 seq: i64,
103) -> Result<Option<AnswerImage>, AppError> {
104 Ok(sqlx::query_as!(
105 AnswerImage,
106 r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
107 app_user AS "user: UserId", seq, file,
108 content_type AS "content_type: FileContentType", size
109 FROM answer_image
110 WHERE question = $1 AND app_user = $2 AND seq = $3"#,
111 question.uuid(),
112 user.uuid(),
113 seq,
114 )
115 .fetch_optional(db)
116 .await?)
117}
118
119/// Every answer drawing of the exam — one query for the exam-delete cascade.
120pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<AnswerImage>, AppError> {
121 Ok(sqlx::query_as!(
122 AnswerImage,
123 r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
124 app_user AS "user: UserId", seq, file,
125 content_type AS "content_type: FileContentType", size
126 FROM answer_image WHERE exam = $1"#,
127 exam.uuid(),
128 )
129 .fetch_all(db)
130 .await?)
131}
132
133/// One student's answer drawings for a single sitting — the parallel to
134/// [`crate::db::exam_answer::list_for_exam_user`], feeding
135/// the sitting/grading answer-image maps for that attempt's `seq`.
136pub async fn list_for_exam_user(
137 db: &Database,
138 exam: &ExamId,
139 user: &UserId,
140 seq: i64,
141) -> Result<Vec<AnswerImage>, AppError> {
142 Ok(sqlx::query_as!(
143 AnswerImage,
144 r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
145 app_user AS "user: UserId", seq, file,
146 content_type AS "content_type: FileContentType", size
147 FROM answer_image WHERE exam = $1 AND app_user = $2 AND seq = $3"#,
148 exam.uuid(),
149 user.uuid(),
150 seq,
151 )
152 .fetch_all(db)
153 .await?)
154}
155
156/// The distinct sittings (`seq`, ascending) this student has any answer
157/// drawing for at this exam — the history index behind a per-attempt view.
158pub async fn list_seqs_for_user(
159 db: &Database,
160 exam: &ExamId,
161 user: &UserId,
162) -> Result<Vec<i64>, AppError> {
163 let rows = sqlx::query!(
164 r#"SELECT DISTINCT seq FROM answer_image
165 WHERE exam = $1 AND app_user = $2 ORDER BY seq ASC"#,
166 exam.uuid(),
167 user.uuid(),
168 )
169 .fetch_all(db)
170 .await?;
171 Ok(rows.into_iter().map(|row| row.seq).collect())
172}
173
174/// The blob names behind every answer drawing of every exam of `course` —
175/// collected *before* the course-delete cascade wipes the rows.
176pub async fn file_keys_for_course(
177 db: &Database,
178 course: &CourseId,
179) -> Result<Vec<String>, AppError> {
180 let rows = sqlx::query!(
181 r#"SELECT ai.file FROM answer_image ai
182 JOIN exam e ON e.id = ai.exam
183 JOIN class_course cc ON cc.id = e.class_course
184 WHERE cc.course = $1"#,
185 course.uuid(),
186 )
187 .fetch_all(db)
188 .await?;
189 Ok(rows.into_iter().map(|row| row.file).collect())
190}
191
192pub async fn delete(db: &Database, image: AnswerImage) -> Result<AnswerImage, AppError> {
193 let deleted = sqlx::query_as!(
194 AnswerImage,
195 r#"DELETE FROM answer_image WHERE question = $1 AND app_user = $2 AND seq = $3
196 RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId",
197 app_user AS "user: UserId", seq, file,
198 content_type AS "content_type: FileContentType", size"#,
199 image.question.uuid(),
200 image.user.uuid(),
201 image.seq,
202 )
203 .fetch_optional(db)
204 .await?;
205 deleted.ok_or(AppError::NotFound)
206}
207
208/// Drop one student's answer drawings across an exam — a retake starts from
209/// a blank sheet. Rows only; the caller GCs the blobs. The retake path
210/// itself wipes nothing: a retake's rows live at their own `seq`, and this
211/// is the standalone mirror of
212/// [`crate::db::exam_answer::delete_for_exam_user`].
213pub async fn delete_for_exam_user(
214 db: &Database,
215 exam: &ExamId,
216 user: &UserId,
217) -> Result<(), AppError> {
218 sqlx::query!(
219 r#"DELETE FROM answer_image WHERE exam = $1 AND app_user = $2"#,
220 exam.uuid(),
221 user.uuid(),
222 )
223 .execute(db)
224 .await?;
225 Ok(())
226}
227
228#[cfg(test)]
229mod tests {
230 use super::*;
231 use crate::domain::note_file::FileContentType;
232
233 fn png() -> FileContentType {
234 FileContentType::try_new("image/png").unwrap()
235 }
236
237 /// A real exam row: a drawing's write moves its exam's counter (that is
238 /// what keeps it from outliving the exam), so a minted id nothing wrote is
239 /// a 404.
240 async fn exam_row(db: &Database) -> ExamId {
241 crate::db::exam::published_exam(db).await.get_id().clone()
242 }
243
244 /// A real `app_user` row under a fixed key: the sheet's owner is a
245 /// foreign key now.
246 async fn a_student(db: &Database) -> UserId {
247 let user = UserId::from_key("019732e3-7b00-7000-8000-00000000a11a");
248 sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, 'a11a', 0)")
249 .bind(user.uuid())
250 .execute(db)
251 .await
252 .unwrap();
253 user
254 }
255
256 /// A real question row on `exam`: a drawing hangs off it by foreign key.
257 async fn a_question(db: &Database, exam: &ExamId) -> ExamQuestionId {
258 let subject = crate::db::subject::create(
259 db,
260 &crate::db::course::a_test_course(db).await,
261 crate::domain::subject::SubjectName::try_new("topic").unwrap(),
262 crate::domain::subject::SubjectDescription::try_new("").unwrap(),
263 )
264 .await
265 .unwrap();
266 let spec = crate::domain::exam_question::QuestionSpec::try_new(
267 crate::domain::exam_question::QuestionKind::try_new("text").unwrap(),
268 None,
269 None,
270 &[],
271 )
272 .unwrap();
273 crate::db::exam_question::create(
274 db,
275 exam,
276 *subject.get_id(),
277 crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(),
278 crate::domain::exam_question::QuestionPoints::try_new(1).unwrap(),
279 spec,
280 )
281 .await
282 .unwrap()
283 .get_id()
284 .clone()
285 }
286
287 #[tokio::test]
288 async fn upsert_replaces_within_a_sitting_but_not_across_them() {
289 let (db, _leases) = crate::database::init_test_db().await;
290 let exam = exam_row(&db).await;
291 let question = a_question(&db, &exam).await;
292 let user = a_student(&db).await;
293
294 let (first, retired) = upsert(&db, AnswerImage::new(&exam, &question, &user, 1, png(), 3))
295 .await
296 .unwrap();
297 assert_eq!(retired, None, "a first upload retires no blob");
298 let (second, retired) = upsert(&db, AnswerImage::new(&exam, &question, &user, 1, png(), 5))
299 .await
300 .unwrap();
301 // Same (question, user, seq), same row — the replace swapped the blob,
302 // and the write itself names the blob the caller must unlink.
303 assert_ne!(first.get_file(), second.get_file());
304 assert_eq!(retired.as_deref(), Some(first.get_file()));
305 let rows = list_for_exam_user(&db, &exam, &user, 1).await.unwrap();
306 assert_eq!(rows.len(), 1);
307 assert_eq!(rows[0].get_size(), 5);
308
309 // A retake (seq 2) accumulates: it is its own row, not an overwrite.
310 upsert(&db, AnswerImage::new(&exam, &question, &user, 2, png(), 9))
311 .await
312 .unwrap();
313 assert_eq!(
314 list_for_exam_user(&db, &exam, &user, 1)
315 .await
316 .unwrap()
317 .len(),
318 1,
319 "the seq-2 image must not overwrite seq-1"
320 );
321 assert_eq!(
322 list_for_exam_user(&db, &exam, &user, 2).await.unwrap()[0].get_size(),
323 9
324 );
325 assert_eq!(
326 list_seqs_for_user(&db, &exam, &user).await.unwrap(),
327 vec![1, 2]
328 );
329
330 // Another student's drawing for the same question/sitting is its own row.
331 let other = UserId::generate();
332 sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, 'b22b', 0)")
333 .bind(other.uuid())
334 .execute(&db)
335 .await
336 .unwrap();
337 upsert(&db, AnswerImage::new(&exam, &question, &other, 1, png(), 7))
338 .await
339 .unwrap();
340 assert_eq!(list_for_exam(&db, &exam).await.unwrap().len(), 3);
341 assert!(read(&db, &question, &user, 2).await.unwrap().is_some());
342 }
343
344 #[tokio::test]
345 async fn listing_scopes_by_exam_and_user() {
346 let (db, _leases) = crate::database::init_test_db().await;
347 let exam_a = exam_row(&db).await;
348 let exam_b = exam_row(&db).await;
349 let user = a_student(&db).await;
350 let question = a_question(&db, &exam_a).await;
351 upsert(
352 &db,
353 AnswerImage::new(&exam_a, &question, &user, 1, png(), 1),
354 )
355 .await
356 .unwrap();
357 assert_eq!(
358 list_for_exam_user(&db, &exam_a, &user, 1)
359 .await
360 .unwrap()
361 .len(),
362 1
363 );
364 assert!(list_for_exam(&db, &exam_b).await.unwrap().is_empty());
365
366 // delete_for_exam_user clears the student's sheet across all sittings.
367 delete_for_exam_user(&db, &exam_a, &user).await.unwrap();
368 assert!(
369 list_for_exam_user(&db, &exam_a, &user, 1)
370 .await
371 .unwrap()
372 .is_empty()
373 );
374 }
375}