forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 commits

answer_image.rs328 lines, 11.8 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 WHERE e.course = $1"#,
183 course.uuid(),
184 )
185 .fetch_all(db)
186 .await?;
187 Ok(rows.into_iter().map(|row| row.file).collect())
188}
189
190pub async fn delete(db: &Database, image: AnswerImage) -> Result<AnswerImage, AppError> {
191 let deleted = sqlx::query_as!(
192 AnswerImage,
193 r#"DELETE FROM answer_image WHERE question = $1 AND app_user = $2 AND seq = $3
194 RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId",
195 app_user AS "user: UserId", seq, file,
196 content_type AS "content_type: FileContentType", size"#,
197 image.question.uuid(),
198 image.user.uuid(),
199 image.seq,
200 )
201 .fetch_optional(db)
202 .await?;
203 deleted.ok_or(AppError::NotFound)
204}
205
206/// Drop one student's answer drawings across an exam — a retake starts from
207/// a blank sheet. Rows only; the caller GCs the blobs. The retake path
208/// itself wipes nothing: a retake's rows live at their own `seq`, and this
209/// is the standalone mirror of
210/// [`crate::db::exam_answer::delete_for_exam_user`].
211pub async fn delete_for_exam_user(
212 db: &Database,
213 exam: &ExamId,
214 user: &UserId,
215) -> Result<(), AppError> {
216 sqlx::query!(
217 r#"DELETE FROM answer_image WHERE exam = $1 AND app_user = $2"#,
218 exam.uuid(),
219 user.uuid(),
220 )
221 .execute(db)
222 .await?;
223 Ok(())
224}
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229 use crate::domain::note_file::FileContentType;
230
231 fn png() -> FileContentType {
232 FileContentType::try_new("image/png").unwrap()
233 }
234
235 /// A real exam row: a drawing's write moves its exam's counter (that is
236 /// what keeps it from outliving the exam), so a minted id nothing wrote is
237 /// a 404.
238 async fn exam_row(db: &Database) -> ExamId {
239 crate::db::exam::published_exam(db).await.get_id().clone()
240 }
241
242 fn student() -> UserId {
243 UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA")
244 }
245
246 #[tokio::test]
247 async fn upsert_replaces_within_a_sitting_but_not_across_them() {
248 let db = crate::database::init_mem().await.unwrap();
249 let exam = exam_row(&db).await;
250 let question = ExamQuestionId::generate();
251 let user = student();
252
253 let (first, retired) = upsert(&db, AnswerImage::new(&exam, &question, &user, 1, png(), 3))
254 .await
255 .unwrap();
256 assert_eq!(retired, None, "a first upload retires no blob");
257 let (second, retired) = upsert(&db, AnswerImage::new(&exam, &question, &user, 1, png(), 5))
258 .await
259 .unwrap();
260 // Same (question, user, seq), same row — the replace swapped the blob,
261 // and the write itself names the blob the caller must unlink.
262 assert_ne!(first.get_file(), second.get_file());
263 assert_eq!(retired.as_deref(), Some(first.get_file()));
264 let rows = list_for_exam_user(&db, &exam, &user, 1).await.unwrap();
265 assert_eq!(rows.len(), 1);
266 assert_eq!(rows[0].get_size(), 5);
267
268 // A retake (seq 2) accumulates: it is its own row, not an overwrite.
269 upsert(&db, AnswerImage::new(&exam, &question, &user, 2, png(), 9))
270 .await
271 .unwrap();
272 assert_eq!(
273 list_for_exam_user(&db, &exam, &user, 1)
274 .await
275 .unwrap()
276 .len(),
277 1,
278 "the seq-2 image must not overwrite seq-1"
279 );
280 assert_eq!(
281 list_for_exam_user(&db, &exam, &user, 2).await.unwrap()[0].get_size(),
282 9
283 );
284 assert_eq!(
285 list_seqs_for_user(&db, &exam, &user).await.unwrap(),
286 vec![1, 2]
287 );
288
289 // Another student's drawing for the same question/sitting is its own row.
290 let other = UserId::from_key("01TESTSTUDENTBBBBBBBBBBBBB");
291 upsert(&db, AnswerImage::new(&exam, &question, &other, 1, png(), 7))
292 .await
293 .unwrap();
294 assert_eq!(list_for_exam(&db, &exam).await.unwrap().len(), 3);
295 assert!(read(&db, &question, &user, 2).await.unwrap().is_some());
296 }
297
298 #[tokio::test]
299 async fn listing_scopes_by_exam_and_user() {
300 let db = crate::database::init_mem().await.unwrap();
301 let exam_a = exam_row(&db).await;
302 let exam_b = exam_row(&db).await;
303 let user = student();
304 upsert(
305 &db,
306 AnswerImage::new(&exam_a, &ExamQuestionId::generate(), &user, 1, png(), 1),
307 )
308 .await
309 .unwrap();
310 assert_eq!(
311 list_for_exam_user(&db, &exam_a, &user, 1)
312 .await
313 .unwrap()
314 .len(),
315 1
316 );
317 assert!(list_for_exam(&db, &exam_b).await.unwrap().is_empty());
318
319 // delete_for_exam_user clears the student's sheet across all sittings.
320 delete_for_exam_user(&db, &exam_a, &user).await.unwrap();
321 assert!(
322 list_for_exam_user(&db, &exam_a, &user, 1)
323 .await
324 .unwrap()
325 .is_empty()
326 );
327 }
328}