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

question_image.rs422 lines, 15.1 KiBHistoryRawDownload
1//! The `question_image` table: the slot-keyed upsert (and delete) behind the
2//! question-freeze gate, the listing reads, and the choice-cleanup sweep a
3//! question PATCH drives. The row's pure half — ids and the fresh-blob-name
4//! constructor — lives in [`crate::domain::question_image`]; the blob bytes
5//! stay the web layer's.
6
7use sqlx::PgConnection;
8
9use crate::database::{Database, tx_with_retry};
10use crate::db::exam_attempt::freeze_gate;
11use crate::domain::course::CourseId;
12use crate::domain::exam::ExamId;
13use crate::domain::exam_question::{ChoiceId, ExamQuestionId};
14use crate::domain::note_file::FileContentType;
15use crate::domain::question_image::QuestionImage;
16use crate::error::AppError;
17
18/// Create or replace the slot's image row — the `UNIQUE NULLS NOT DISTINCT`
19/// (question, slot) constraint makes this the whole "one image per slot"
20/// story — handing back what it stored plus the blob name it replaced, for
21/// the caller to take off disk. Refused once the exam has an attempt:
22/// pictures are part of the question, so they freeze with it, and the gate
23/// is in this transaction rather than in a lock the caller held.
24///
25/// The replaced name is read *inside the same transaction*, not by the
26/// caller before it: two uploads to one slot both write this row, so they
27/// contend on it and the loser re-reads the winner's blob name, where two
28/// pre-reads both saw the *old* blob and left the loser's fresh one
29/// orphaned on disk.
30pub async fn upsert(
31 db: &Database,
32 image: QuestionImage,
33) -> Result<(QuestionImage, Option<String>), AppError> {
34 tx_with_retry(db, false, async move |conn| {
35 upsert_in(conn, image.clone()).await
36 })
37 .await
38}
39
40/// The gated read-and-replace, on one connection.
41pub(crate) async fn upsert_in(
42 conn: &mut PgConnection,
43 image: QuestionImage,
44) -> Result<(QuestionImage, Option<String>), AppError> {
45 freeze_gate(conn, &image.exam).await?;
46 let replaced = replaced_file(conn, &image.question, image.slot.as_ref()).await?;
47 let stored = sqlx::query_as!(
48 QuestionImage,
49 r#"INSERT INTO question_image (exam, question, slot, file, content_type, size)
50 VALUES ($1, $2, $3, $4, $5, $6)
51 ON CONFLICT (question, slot) DO UPDATE
52 SET file = EXCLUDED.file, content_type = EXCLUDED.content_type,
53 size = EXCLUDED.size
54 RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId",
55 slot AS "slot: ChoiceId", file,
56 content_type AS "content_type: FileContentType", size"#,
57 image.exam.uuid(),
58 image.question.uuid(),
59 image.slot.as_ref().map(ChoiceId::as_str),
60 image.file,
61 image.content_type.as_str(),
62 image.size,
63 )
64 .fetch_one(&mut *conn)
65 .await?;
66 Ok((stored, replaced))
67}
68
69/// The blob name a slot's row currently names — the file a replace takes
70/// off disk. `IS NOT DISTINCT FROM` is what makes the illustration slot's
71/// `NULL` match itself.
72pub(crate) async fn replaced_file(
73 conn: &mut PgConnection,
74 question: &ExamQuestionId,
75 slot: Option<&ChoiceId>,
76) -> Result<Option<String>, AppError> {
77 let row = sqlx::query!(
78 r#"SELECT file FROM question_image
79 WHERE question = $1 AND slot IS NOT DISTINCT FROM $2"#,
80 question.uuid(),
81 slot.map(ChoiceId::as_str),
82 )
83 .fetch_optional(conn)
84 .await?;
85 Ok(row.map(|row| row.file))
86}
87
88pub async fn read_slot(
89 db: &Database,
90 question: &ExamQuestionId,
91 slot: Option<&ChoiceId>,
92) -> Result<Option<QuestionImage>, AppError> {
93 Ok(sqlx::query_as!(
94 QuestionImage,
95 r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
96 slot AS "slot: ChoiceId", file,
97 content_type AS "content_type: FileContentType", size
98 FROM question_image
99 WHERE question = $1 AND slot IS NOT DISTINCT FROM $2"#,
100 question.uuid(),
101 slot.map(ChoiceId::as_str),
102 )
103 .fetch_optional(db)
104 .await?)
105}
106
107/// Every image of the exam's questions — one query for the list views.
108pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<QuestionImage>, AppError> {
109 Ok(sqlx::query_as!(
110 QuestionImage,
111 r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
112 slot AS "slot: ChoiceId", file,
113 content_type AS "content_type: FileContentType", size
114 FROM question_image WHERE exam = $1"#,
115 exam.uuid(),
116 )
117 .fetch_all(db)
118 .await?)
119}
120
121pub async fn list_for_question(
122 db: &Database,
123 question: &ExamQuestionId,
124) -> Result<Vec<QuestionImage>, AppError> {
125 Ok(sqlx::query_as!(
126 QuestionImage,
127 r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
128 slot AS "slot: ChoiceId", file,
129 content_type AS "content_type: FileContentType", size
130 FROM question_image WHERE question = $1"#,
131 question.uuid(),
132 )
133 .fetch_all(db)
134 .await?)
135}
136
137/// Drop the option pictures whose choice is gone — every choice image of
138/// the question whose `slot` is *not* in `keep` (the question's own
139/// illustration always stays), returning the removed rows so the caller can
140/// take their blobs off disk.
141///
142/// This is what makes an edit non-destructive: a PATCH that reorders,
143/// renames, or drops options passes the surviving choice ids as `keep`, so
144/// only the pictures of genuinely removed options go. `keep = &[]` (a text
145/// question, or an all-new choice list) still clears the lot.
146pub async fn delete_choices_not_in(
147 db: &Database,
148 question: &ExamQuestionId,
149 keep: &[ChoiceId],
150) -> Result<Vec<QuestionImage>, AppError> {
151 let keep = keep
152 .iter()
153 .map(|id| id.as_str().to_string())
154 .collect::<Vec<_>>();
155 Ok(sqlx::query_as!(
156 QuestionImage,
157 r#"DELETE FROM question_image
158 WHERE question = $1 AND slot IS NOT NULL AND NOT (slot = ANY($2))
159 RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId",
160 slot AS "slot: ChoiceId", file,
161 content_type AS "content_type: FileContentType", size"#,
162 question.uuid(),
163 &keep,
164 )
165 .fetch_all(db)
166 .await?)
167}
168
169/// The blob names behind every image of every exam of `course` — collected
170/// *before* the course-delete cascade wipes the rows. The exams belong to the
171/// course's instances since D1, so the join goes through `class_course`.
172pub async fn file_keys_for_course(
173 db: &Database,
174 course: &CourseId,
175) -> Result<Vec<String>, AppError> {
176 let rows = sqlx::query!(
177 r#"SELECT qi.file FROM question_image qi
178 JOIN exam e ON e.id = qi.exam
179 JOIN class_course cc ON cc.id = e.class_course
180 WHERE cc.course = $1"#,
181 course.uuid(),
182 )
183 .fetch_all(db)
184 .await?;
185 Ok(rows.into_iter().map(|row| row.file).collect())
186}
187
188/// Refused once the exam has an attempt, in the same transaction — same
189/// gate, same reason as [`upsert`].
190pub async fn delete(db: &Database, image: QuestionImage) -> Result<QuestionImage, AppError> {
191 tx_with_retry(db, false, async move |conn| {
192 freeze_gate(conn, &image.exam).await?;
193 let deleted = sqlx::query_as!(
194 QuestionImage,
195 r#"DELETE FROM question_image
196 WHERE question = $1 AND slot IS NOT DISTINCT FROM $2
197 RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId",
198 slot AS "slot: ChoiceId", file,
199 content_type AS "content_type: FileContentType", size"#,
200 image.question.uuid(),
201 image.slot.as_ref().map(ChoiceId::as_str),
202 )
203 .fetch_optional(&mut *conn)
204 .await?;
205 deleted.ok_or(AppError::NotFound)
206 })
207 .await
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213 use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec};
214 use crate::domain::note_file::FileContentType;
215
216 /// A real exam row: an image write moves its exam's counter (that is what
217 /// keeps a picture from outliving its exam), so a minted id nothing wrote
218 /// is a 404.
219 async fn exam_row(db: &Database) -> ExamId {
220 crate::db::exam::published_exam(db).await.get_id().clone()
221 }
222
223 fn png() -> FileContentType {
224 FileContentType::try_new("image/png").unwrap()
225 }
226
227 /// Three minted choice ids to slot pictures against.
228 fn choice_ids() -> Vec<ChoiceId> {
229 QuestionSpec::try_new(
230 QuestionKind::try_new("choice").unwrap(),
231 Some(
232 ["a", "b", "c"]
233 .iter()
234 .map(|l| ChoiceInput {
235 id: Some((*l).into()),
236 text: (*l).into(),
237 })
238 .collect(),
239 ),
240 Some("a".into()),
241 &[],
242 )
243 .unwrap()
244 .into_parts()
245 .1
246 .unwrap()
247 .iter()
248 .map(|c| c.get_id().clone())
249 .collect()
250 }
251
252 /// A real question row on `exam`: images are FK children of their
253 /// question, so a minted id is refused outright.
254 async fn a_question(db: &Database, exam: &ExamId) -> ExamQuestionId {
255 use crate::domain::exam_question::{QuestionPoints, QuestionText};
256 use crate::domain::subject::{SubjectDescription, SubjectName};
257 let spec = QuestionSpec::try_new(
258 QuestionKind::try_new("choice").unwrap(),
259 Some(
260 ["a", "b", "c"]
261 .iter()
262 .map(|l| ChoiceInput {
263 id: Some((*l).into()),
264 text: (*l).into(),
265 })
266 .collect(),
267 ),
268 Some("a".into()),
269 &[],
270 )
271 .unwrap();
272 let subject = crate::db::subject::create(
273 db,
274 &crate::db::course::a_test_course(db).await,
275 SubjectName::try_new("pictures").unwrap(),
276 SubjectDescription::try_new("").unwrap(),
277 )
278 .await
279 .unwrap();
280 crate::db::exam_question::create(
281 db,
282 exam,
283 *subject.get_id(),
284 QuestionText::try_new("pick one").unwrap(),
285 QuestionPoints::try_new(1).unwrap(),
286 spec,
287 )
288 .await
289 .unwrap()
290 .get_id()
291 .clone()
292 }
293
294 #[tokio::test]
295 async fn upsert_replaces_per_slot() {
296 let (db, _leases) = crate::database::init_test_db().await;
297 let exam = exam_row(&db).await;
298 let question = a_question(&db, &exam).await;
299 let ids = choice_ids();
300
301 let (first, retired) = upsert(&db, QuestionImage::new(&exam, &question, None, png(), 3))
302 .await
303 .unwrap();
304 assert_eq!(retired, None, "a first upload retires no blob");
305 let (second, retired) = upsert(&db, QuestionImage::new(&exam, &question, None, png(), 5))
306 .await
307 .unwrap();
308 // Same slot, same row — the replace swapped the blob pointer, and the
309 // write itself names the blob the caller must unlink.
310 assert_ne!(first.get_file(), second.get_file());
311 assert_eq!(retired.as_deref(), Some(first.get_file()));
312 let rows = list_for_question(&db, &question).await.unwrap();
313 assert_eq!(rows.len(), 1);
314 assert_eq!(rows[0].get_size(), 5);
315
316 // A choice slot is its own row, keyed by the option's id.
317 upsert(
318 &db,
319 QuestionImage::new(&exam, &question, Some(&ids[0]), png(), 7),
320 )
321 .await
322 .unwrap();
323 assert_eq!(list_for_question(&db, &question).await.unwrap().len(), 2);
324 let choice = read_slot(&db, &question, Some(&ids[0]))
325 .await
326 .unwrap()
327 .unwrap();
328 assert_eq!(choice.get_slot(), Some(&ids[0]));
329 assert!(
330 read_slot(&db, &question, Some(&ids[1]))
331 .await
332 .unwrap()
333 .is_none()
334 );
335 }
336
337 /// The behaviour the whole remodel exists for: an edit that keeps some
338 /// options keeps exactly their pictures, and drops only the removed one's.
339 #[tokio::test]
340 async fn only_the_dropped_options_lose_their_pictures() {
341 let (db, _leases) = crate::database::init_test_db().await;
342 let exam = exam_row(&db).await;
343 let question = a_question(&db, &exam).await;
344 let ids = choice_ids();
345 upsert(&db, QuestionImage::new(&exam, &question, None, png(), 1))
346 .await
347 .unwrap();
348 for id in &ids {
349 upsert(
350 &db,
351 QuestionImage::new(&exam, &question, Some(id), png(), 1),
352 )
353 .await
354 .unwrap();
355 }
356
357 // Keep the first and last option (reordered — order is irrelevant now).
358 let keep = vec![ids[2].clone(), ids[0].clone()];
359 let dropped = delete_choices_not_in(&db, &question, &keep).await.unwrap();
360 assert_eq!(dropped.len(), 1);
361 assert_eq!(dropped[0].get_slot(), Some(&ids[1]));
362
363 let left = list_for_question(&db, &question).await.unwrap();
364 // The question illustration plus the two surviving option pictures.
365 assert_eq!(left.len(), 3);
366 assert!(
367 read_slot(&db, &question, Some(&ids[0]))
368 .await
369 .unwrap()
370 .is_some()
371 );
372 assert!(
373 read_slot(&db, &question, Some(&ids[2]))
374 .await
375 .unwrap()
376 .is_some()
377 );
378 assert!(read_slot(&db, &question, None).await.unwrap().is_some());
379 }
380
381 #[tokio::test]
382 async fn an_empty_keep_set_clears_every_option_picture_but_not_the_illustration() {
383 let (db, _leases) = crate::database::init_test_db().await;
384 let exam = exam_row(&db).await;
385 let question = a_question(&db, &exam).await;
386 let ids = choice_ids();
387 upsert(&db, QuestionImage::new(&exam, &question, None, png(), 1))
388 .await
389 .unwrap();
390 for id in &ids[..2] {
391 upsert(
392 &db,
393 QuestionImage::new(&exam, &question, Some(id), png(), 1),
394 )
395 .await
396 .unwrap();
397 }
398
399 let dropped = delete_choices_not_in(&db, &question, &[]).await.unwrap();
400 assert_eq!(dropped.len(), 2);
401 assert!(dropped.iter().all(|image| image.get_slot().is_some()));
402
403 let left = list_for_question(&db, &question).await.unwrap();
404 assert_eq!(left.len(), 1);
405 assert_eq!(left[0].get_slot(), None);
406 }
407
408 #[tokio::test]
409 async fn exam_listing_scopes_by_exam() {
410 let (db, _leases) = crate::database::init_test_db().await;
411 let exam_a = exam_row(&db).await;
412 let exam_b = exam_row(&db).await;
413 upsert(
414 &db,
415 QuestionImage::new(&exam_a, &a_question(&db, &exam_a).await, None, png(), 1),
416 )
417 .await
418 .unwrap();
419 assert_eq!(list_for_exam(&db, &exam_a).await.unwrap().len(), 1);
420 assert!(list_for_exam(&db, &exam_b).await.unwrap().is_empty());
421 }
422}