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

homework_file.rs497 lines, 18.5 KiBHistoryRawDownload
1//! The `homework_file` table: the attachment rows behind a submission's
2//! files — the seat-claiming insert, the scoped reads, the GC key
3//! collectors, and the gate-guarded delete. The rows' assembly (`new`) and
4//! their validated fields live in [`crate::domain::homework_file`]; the
5//! upload workflow around them in [`crate::service::homework_file`].
6
7use crate::constant::MAX_HOMEWORK_FILES_PER_SUBMISSION;
8use crate::database::{Database, tx_with_retry};
9use crate::domain::course::CourseId;
10use crate::domain::homework::HomeworkId;
11use crate::domain::homework_file::HomeworkFile;
12use crate::domain::homework_file::HomeworkFileId;
13use crate::domain::homework_submission::HomeworkSubmissionId;
14use crate::domain::note_file::{FileContentType, FileName};
15use crate::domain::timestamp::Timestamp;
16use crate::error::AppError;
17
18/// Persist the row assembled by
19/// [`HomeworkFile::new`](crate::domain::homework_file::HomeworkFile::new),
20/// refusing once its submission already holds
21/// [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`)
22/// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own
23/// wording). Both are decided by one guarded insert on the submission row —
24/// the seat (`UPDATE … file_count + 1 WHERE file_count < $cap AND
25/// graded_by_result IS NULL`) and the file row commit together in one CTE, so
26/// a crash between them can no longer leave a slot claimed by a file that
27/// does not exist, and a losing upload never has to be un-counted. Which of
28/// the two conditions refused it is read back afterwards, off the losing
29/// path only, and only to pick the message: zero rows says "full *or* graded
30/// *or* the submission is gone".
31pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> {
32 let created = sqlx::query_as!(
33 HomeworkFile,
34 r#"WITH seat AS (
35 UPDATE homework_submission SET file_count = file_count + 1
36 WHERE id = $2 AND file_count < $1 AND graded_by_result IS NULL
37 RETURNING 1
38 )
39 INSERT INTO homework_file (id, submission, name, content_type, size, file, created_at)
40 SELECT $3, $2, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat)
41 RETURNING id AS "id: HomeworkFileId",
42 submission AS "submission: HomeworkSubmissionId",
43 name AS "name: FileName",
44 content_type AS "content_type: FileContentType",
45 size,
46 file,
47 created_at AS "created_at: Timestamp""#,
48 MAX_HOMEWORK_FILES_PER_SUBMISSION as i64,
49 file.submission.uuid(),
50 file.id.uuid(),
51 file.name.as_str(),
52 file.content_type.as_str(),
53 file.size,
54 file.file,
55 file.created_at.as_millis(),
56 )
57 .fetch_optional(db)
58 .await
59 .map_err(|err| {
60 // The id is a fresh v7 minted by `new`, so a row already holding it
61 // is a collision, not a re-upload.
62 if crate::database::unique_violation(&err).is_some() {
63 AppError::Internal("homework file id collided".into())
64 } else {
65 AppError::from(err)
66 }
67 })?;
68 match created {
69 Some(row) => Ok(Some(row)),
70 None => {
71 if super::homework_submission::is_graded(db, &file.submission).await? {
72 return Ok(None);
73 }
74 Err(AppError::Conflict(
75 "the submission already holds the maximum of 10 files — delete one first",
76 ))
77 }
78 }
79}
80
81/// Read a file's row only if it belongs to `submission` — callers have
82/// already checked the submission belongs to the requesting user.
83pub async fn read_for(
84 db: &Database,
85 id: &crate::domain::homework_file::HomeworkFileId,
86 submission: &crate::domain::homework_submission::HomeworkSubmissionId,
87) -> Result<Option<HomeworkFile>, AppError> {
88 Ok(sqlx::query_as!(
89 HomeworkFile,
90 r#"SELECT id AS "id: HomeworkFileId",
91 submission AS "submission: HomeworkSubmissionId",
92 name AS "name: FileName",
93 content_type AS "content_type: FileContentType",
94 size,
95 file,
96 created_at AS "created_at: Timestamp"
97 FROM homework_file WHERE id = $1 AND submission = $2"#,
98 id.uuid(),
99 submission.uuid()
100 )
101 .fetch_optional(db)
102 .await?)
103}
104
105/// Read a file by id only if it hangs off a submission to `homework` — the
106/// grader's download scoping. The teacher download path carries the homework
107/// id but not the owning student (unlike `read_for`, which needs the
108/// submission), so this both finds the file and confirms it belongs under
109/// `homework`: a teacher can't pass a homework they manage to read a file
110/// from a different (perhaps unmanaged) one.
111pub async fn read_in_homework(
112 db: &Database,
113 id: &crate::domain::homework_file::HomeworkFileId,
114 homework: &HomeworkId,
115) -> Result<Option<HomeworkFile>, AppError> {
116 Ok(sqlx::query_as!(
117 HomeworkFile,
118 r#"SELECT id AS "id: HomeworkFileId",
119 submission AS "submission: HomeworkSubmissionId",
120 name AS "name: FileName",
121 content_type AS "content_type: FileContentType",
122 size,
123 file,
124 created_at AS "created_at: Timestamp"
125 FROM homework_file
126 WHERE id = $1
127 AND submission IN (SELECT id FROM homework_submission WHERE homework = $2)"#,
128 id.uuid(),
129 homework.uuid()
130 )
131 .fetch_optional(db)
132 .await?)
133}
134
135/// All of `submission`'s files, newest first.
136pub async fn list_for_submission(
137 db: &Database,
138 submission: &crate::domain::homework_submission::HomeworkSubmissionId,
139) -> Result<Vec<HomeworkFile>, AppError> {
140 Ok(sqlx::query_as!(
141 HomeworkFile,
142 r#"SELECT id AS "id: HomeworkFileId",
143 submission AS "submission: HomeworkSubmissionId",
144 name AS "name: FileName",
145 content_type AS "content_type: FileContentType",
146 size,
147 file,
148 created_at AS "created_at: Timestamp"
149 FROM homework_file WHERE submission = $1 ORDER BY id DESC"#,
150 submission.uuid()
151 )
152 .fetch_all(db)
153 .await?)
154}
155
156/// How many files `submission` holds. Counting the rows (not the counter
157/// column) keeps it identical to `NoteFile`'s proven cap check; at a ceiling
158/// of 10 the cost is nil.
159pub async fn count_for_submission(
160 db: &Database,
161 submission: &crate::domain::homework_submission::HomeworkSubmissionId,
162) -> Result<usize, AppError> {
163 let row = sqlx::query!(
164 r#"SELECT count(*) AS "count!: i64" FROM homework_file WHERE submission = $1"#,
165 submission.uuid()
166 )
167 .fetch_one(db)
168 .await?;
169 Ok(row.count as usize)
170}
171
172/// The blob names behind every file of every submission to `homework` —
173/// the GC keys of a homework delete (collected inside the delete's own
174/// transaction by [`crate::db::homework::delete`]; this read backs it and
175/// the tests).
176pub async fn file_keys_for_homework(
177 db: &Database,
178 homework: &HomeworkId,
179) -> Result<Vec<String>, AppError> {
180 Ok(sqlx::query!(
181 r#"SELECT file FROM homework_file
182 WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#,
183 homework.uuid()
184 )
185 .fetch_all(db)
186 .await?
187 .into_iter()
188 .map(|row| row.file)
189 .collect())
190}
191
192/// The blob names behind every homework file of `course` — collected
193/// *before* the course-delete cascade wipes the rows.
194pub async fn file_keys_for_course(
195 db: &Database,
196 course: &CourseId,
197) -> Result<Vec<String>, AppError> {
198 Ok(sqlx::query!(
199 r#"SELECT file FROM homework_file
200 WHERE submission IN (
201 SELECT id FROM homework_submission
202 WHERE homework IN (
203 SELECT h.id FROM homework h
204 JOIN class_course cc ON cc.id = h.class_course
205 WHERE cc.course = $1)
206 )"#,
207 course.uuid()
208 )
209 .fetch_all(db)
210 .await?
211 .into_iter()
212 .map(|row| row.file)
213 .collect())
214}
215
216/// Delete the row and give its slot back in the same transaction. The
217/// submission survives, so its counter has to be corrected; the cascades
218/// that delete the submission itself take the counter with it.
219///
220/// The gate is the first statement: a conditional write on the *submission*
221/// row — the "last touched" re-stamp a file delete owes the late flag
222/// anyway. Its row lock is also the serialization point against an upload's
223/// seat claim on the same row: one of the two waits, and the winner re-reads
224/// the counter before moving it, so no lost round and no 500 — a grade
225/// landing concurrently either stamps first (this delete is refused,
226/// `Ok(None)`) or stamps after (the file was already gone when it graded).
227/// `Err(NotFound)` still means the file row itself had vanished.
228pub async fn delete(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> {
229 let now = Timestamp::now();
230 tx_with_retry(db, false, async move |tx| {
231 let open = sqlx::query!(
232 r#"UPDATE homework_submission SET updated_at = $2
233 WHERE id = $1 AND graded_by_result IS NULL
234 RETURNING 1 AS "open: i32""#,
235 file.submission.uuid(),
236 now.as_millis()
237 )
238 .fetch_optional(&mut *tx)
239 .await?;
240 if open.is_none() {
241 return Ok(None);
242 }
243 let gone = sqlx::query_as!(
244 HomeworkFile,
245 r#"DELETE FROM homework_file WHERE id = $1 AND submission = $2
246 RETURNING id AS "id: HomeworkFileId",
247 submission AS "submission: HomeworkSubmissionId",
248 name AS "name: FileName",
249 content_type AS "content_type: FileContentType",
250 size,
251 file,
252 created_at AS "created_at: Timestamp""#,
253 file.id.uuid(),
254 file.submission.uuid()
255 )
256 .fetch_optional(&mut *tx)
257 .await?;
258 match gone {
259 Some(row) => {
260 sqlx::query!(
261 "UPDATE homework_submission SET file_count = GREATEST(file_count - 1, 0)
262 WHERE id = $1",
263 file.submission.uuid()
264 )
265 .execute(&mut *tx)
266 .await?;
267 Ok(Some(row))
268 }
269 // The submission was open but the file had already vanished.
270 None => Err(AppError::NotFound),
271 }
272 })
273 .await
274}
275
276#[cfg(test)]
277mod tests {
278 use super::*;
279 use crate::domain::homework_submission::HomeworkSubmissionId;
280 use crate::domain::note_file::{FileContentType, FileName};
281 use crate::domain::user::UserId;
282
283 /// A real homework row (with the subject it references): `upsert` reads the
284 /// deadline off the entity now, so a bare id no longer does.
285 async fn a_homework(db: &Database) -> crate::domain::homework::Homework {
286 use crate::db::homework as hw;
287 use crate::domain::homework::HomeworkTitle;
288 use crate::domain::subject::{SubjectDescription, SubjectName};
289
290 let (instance, course) = crate::db::course::a_test_instance(db).await;
291 let subject = crate::db::subject::create(
292 db,
293 &course,
294 SubjectName::try_new("topic").unwrap(),
295 SubjectDescription::try_new("").unwrap(),
296 )
297 .await
298 .unwrap();
299 hw::create(
300 db,
301 &instance,
302 subject.get_id(),
303 HomeworkTitle::try_new("essay").unwrap(),
304 None,
305 crate::domain::timestamp::Timestamp::from_millis(1),
306 None,
307 &a_teacher(db).await,
308 )
309 .await
310 .unwrap()
311 }
312
313 /// A real `app_user` row: submitters are foreign keys too.
314 async fn a_student(db: &Database) -> UserId {
315 let user = UserId::generate();
316 sqlx::query(
317 "INSERT INTO app_user (id, username, created_at, role) VALUES ($1, $2, 0, 'student')",
318 )
319 .bind(user.uuid())
320 .bind(format!("s-{}", &user.key()[30..]))
321 .execute(db)
322 .await
323 .unwrap();
324 user
325 }
326
327 /// A real `app_user` row: creators and submitters are foreign keys now.
328 async fn a_teacher(db: &Database) -> UserId {
329 let user = UserId::generate();
330 sqlx::query(
331 "INSERT INTO app_user (id, username, created_at, role) VALUES ($1, $2, 0, 'teacher')",
332 )
333 .bind(user.uuid())
334 .bind(format!("t-{}", &user.key()[30..]))
335 .execute(db)
336 .await
337 .unwrap();
338 user
339 }
340
341 fn a_file(submission: &HomeworkSubmissionId) -> HomeworkFile {
342 HomeworkFile::new(
343 submission,
344 FileName::try_new("answer.pdf").unwrap(),
345 FileContentType::try_new("application/pdf").unwrap(),
346 3,
347 )
348 }
349
350 /// The counter as *stored* — the only witness that the seat and the row
351 /// moved together, since every other read counts the rows themselves.
352 async fn stored_count(submission: &HomeworkSubmissionId, db: &Database) -> i64 {
353 use sqlx::Row as _;
354
355 sqlx::query("SELECT file_count FROM homework_submission WHERE id = $1")
356 .bind(submission.uuid())
357 .fetch_one(db)
358 .await
359 .unwrap()
360 .try_get::<i64, _>(0)
361 .unwrap()
362 }
363 #[tokio::test]
364 async fn rows_scope_to_their_submission_gc_and_cap() {
365 let (db, _leases) = crate::database::init_test_db().await;
366 let hw = a_homework(&db).await;
367 let homework = hw.get_id().clone();
368 let user = a_student(&db).await;
369 // A real submission row, so the GC join through it resolves.
370 let (submission, _) = crate::db::homework_submission::upsert(&db, &hw, &user, None, false)
371 .await
372 .unwrap()
373 .unwrap();
374 let sub_a = submission.get_id().clone();
375 let sub_b = HomeworkSubmissionId::generate();
376
377 let stored = insert(&db, a_file(&sub_a)).await.unwrap().unwrap();
378 // Readable under its own submission, invisible under another.
379 assert!(
380 read_for(&db, stored.get_id(), &sub_a)
381 .await
382 .unwrap()
383 .is_some()
384 );
385 assert!(
386 read_for(&db, stored.get_id(), &sub_b)
387 .await
388 .unwrap()
389 .is_none()
390 );
391 assert_eq!(count_for_submission(&db, &sub_a).await.unwrap(), 1);
392 assert_eq!(
393 stored_count(&sub_a, &db).await,
394 1,
395 "the seat rode with the row"
396 );
397
398 // The grader's download scoping: found under its own homework, invisible
399 // under another — so a teacher can't read it by naming a homework they
400 // happen to manage.
401 assert!(
402 read_in_homework(&db, stored.get_id(), &homework)
403 .await
404 .unwrap()
405 .is_some()
406 );
407 assert!(
408 read_in_homework(
409 &db,
410 stored.get_id(),
411 &HomeworkId::from_key("019732e3-7b00-7000-8000-00000000ebbe"),
412 )
413 .await
414 .unwrap()
415 .is_none()
416 );
417
418 // The blob name is collectable for GC before a cascade wipes the rows.
419 let keys = file_keys_for_homework(&db, &homework).await.unwrap();
420 assert_eq!(keys, vec![stored.get_file().to_string()]);
421
422 // Fill to the cap, then the 11th is refused.
423 for _ in 1..MAX_HOMEWORK_FILES_PER_SUBMISSION {
424 insert(&db, a_file(&sub_a)).await.unwrap().unwrap();
425 }
426 assert!(matches!(
427 insert(&db, a_file(&sub_a)).await,
428 Err(AppError::Conflict(_))
429 ));
430 // The refusal wrote nothing at all: neither a row nor a seat.
431 assert_eq!(
432 count_for_submission(&db, &sub_a).await.unwrap() as i64,
433 stored_count(&sub_a, &db).await,
434 );
435 assert_eq!(
436 stored_count(&sub_a, &db).await,
437 MAX_HOMEWORK_FILES_PER_SUBMISSION as i64
438 );
439 }
440
441 /// A graded submission takes no more files and gives none up — decided by
442 /// the same conditional write that claims the file slot, so no
443 /// `homework_result` read stands between the check and the write.
444 ///
445 /// Bite check: drop [`SUBMISSION_OPEN_GUARD`] from [`insert`]'s
446 /// [`cap::claim_when_and_create`] and the add below lands; drop it from
447 /// [`delete`]'s gate and the delete below succeeds.
448 #[tokio::test]
449 async fn a_grade_freezes_the_files_too() {
450 use crate::db::homework_result;
451 use crate::domain::homework_result::HomeworkStatus;
452
453 let (db, _leases) = crate::database::init_test_db().await;
454 let hw = a_homework(&db).await;
455 let homework = hw.get_id().clone();
456 let user = a_student(&db).await;
457 let (submission, _) = crate::db::homework_submission::upsert(&db, &hw, &user, None, false)
458 .await
459 .unwrap()
460 .unwrap();
461 let sub = submission.get_id().clone();
462 let stored = insert(&db, a_file(&sub)).await.unwrap().unwrap();
463
464 homework_result::grade(
465 &db,
466 &homework,
467 &user,
468 HomeworkStatus::try_new("done").unwrap(),
469 None,
470 &a_teacher(&db).await,
471 )
472 .await
473 .unwrap();
474
475 // Neither adding nor removing an attachment: `None` is the freeze, and
476 // the cap's own `Err(Conflict)` stays distinct from it.
477 assert!(insert(&db, a_file(&sub)).await.unwrap().is_none());
478 assert!(delete(&db, stored.clone()).await.unwrap().is_none());
479 assert_eq!(
480 count_for_submission(&db, &sub).await.unwrap(),
481 1,
482 "the graded submission keeps exactly the files it was graded on"
483 );
484 // Refused by the *guard*, not the cap (nine seats free) — and still no
485 // seat moved, so the counter matches the rows.
486 assert_eq!(stored_count(&sub, &db).await, 1);
487 // The refused add took no slot either, so un-grading gives back a
488 // submission with room, not one that silently lost nine.
489 homework_result::remove(&db, &homework, &user)
490 .await
491 .unwrap();
492 for _ in 1..MAX_HOMEWORK_FILES_PER_SUBMISSION {
493 insert(&db, a_file(&sub)).await.unwrap().unwrap();
494 }
495 assert!(delete(&db, stored).await.unwrap().is_some());
496 }
497}