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.rs1150 lines, 46.8 KiBHistoryRawDownload
1//! The `homework` table: row reads and listings, the subject-counter claim
2//! that pins a homework to a live subject row, the reference-counting PATCH —
3//! whose audience-narrowing orphan guard is one transaction with the write,
4//! serialized on the homework row's `FOR UPDATE` lock — and the cascading
5//! delete.
6
7use crate::database::{Database, tx_with_retry};
8use crate::domain::class_course::ClassCourseId;
9use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};
10use crate::domain::subject::SubjectId;
11use crate::domain::timestamp::Timestamp;
12use crate::domain::user::UserId;
13use crate::error::{AppError, ValidationError};
14use sqlx::PgConnection;
15
16use crate::db::page::{PagedList, Param};
17
18/// The answer a link to a subject that is not there gets, on create and on
19/// re-tag alike — the conditional claim on the subject row matches nothing,
20/// and the caller says exactly what the web layer's pre-flight lookup would
21/// have.
22fn subject_gone() -> AppError {
23 AppError::Validation(ValidationError::Invalid {
24 field: "subject_id",
25 reason: "subject does not exist",
26 })
27}
28
29/// What a stale re-tag answers. The shared PATCH builder
30/// ([`crate::db::field_update`]) carries the same refusal; the homework PATCH
31/// keeps its own copy because its orphan guard needs the row lock the generic
32/// builder cannot take.
33const STALE_MOVE: &str = "the link this update moves changed since it was read; re-read and retry";
34
35#[expect(
36 clippy::too_many_arguments,
37 reason = "mirrors the sibling entities' create(field, field, ..) shape"
38)]
39pub async fn create(
40 db: &Database,
41 class_course: &ClassCourseId,
42 subject: &SubjectId,
43 title: HomeworkTitle,
44 description: Option<HomeworkDescription>,
45 due_at: Timestamp,
46 assigned: Option<Vec<UserId>>,
47 created_by: &UserId,
48) -> Result<Homework, AppError> {
49 // The subject's reference is taken in the very statement that writes the
50 // row — the exam question's twin ([`crate::db::exam_question`]): the
51 // claim (`UPDATE subject … +1`) and the insert are one CTE, so a subject
52 // a delete already removed matches nothing and nothing is written, which
53 // is the 400 the web layer's pre-flight check answers with. The subject
54 // delete is refused while this counter is non-zero, so the two writers
55 // contend on the subject row itself, and a crash cannot strand a claim
56 // that would make the subject undeletable forever. The audience rows
57 // ride the same transaction: a subset homework never appears
58 // whole-course, not even for the instant of its create.
59 let homework = Homework {
60 id: HomeworkId::generate(),
61 class_course: class_course.clone(),
62 subject: *subject,
63 title,
64 description,
65 due_at,
66 assigned,
67 created_by: *created_by,
68 created_at: Timestamp::now(),
69 };
70 let assigned_values: Vec<uuid::Uuid> = homework
71 .assigned
72 .as_deref()
73 .unwrap_or_default()
74 .iter()
75 .map(UserId::uuid)
76 .collect();
77 // The subset the caller passed is the truth — the store holds no roster
78 // column to read back; the whole-course case stays `None`. Cloned out
79 // here because the closure below consumes `homework`.
80 let assigned = homework.assigned.clone();
81 // Owned BEFORE the closure. A reference parameter captured by the
82 // coroutine (`&CourseId`, `&SubjectId`) leaves that borrow in the
83 // statement future, and the `Send` proof at the `routes!` registration
84 // comes back "not general enough" over the higher-ranked connection
85 // lease — every tx_with_retry site captures only owned values.
86 let subject = *subject;
87 let class_course = class_course.clone();
88 tx_with_retry(db, false, async move |tx| {
89 // And every bind is a precomputed value of this coroutine's own: a
90 // bind expression reading a capture inside the macro keeps that
91 // borrow alive across the await to the same `Send` end.
92 let subject_uuid = subject.uuid();
93 let class_course_uuid = class_course.uuid();
94 let homework_uuid = homework.id.uuid();
95 let title = homework.title.clone();
96 let description = homework.description.clone();
97 let due_at_millis = homework.due_at.as_millis();
98 let created_by_uuid = homework.created_by.uuid();
99 let created_at_millis = homework.created_at.as_millis();
100 let assigned_values = assigned_values.clone();
101 let created = sqlx::query_as!(
102 Homework,
103 r#"WITH seat AS (
104 UPDATE subject SET homework_count = homework_count + 1
105 WHERE id = $1
106 RETURNING 1
107 )
108 INSERT INTO homework (id, class_course, subject, title, description, due_at, created_by, created_at)
109 SELECT $2, $3, $1, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat)
110 RETURNING id AS "id: HomeworkId",
111 class_course AS "class_course: ClassCourseId",
112 subject AS "subject: SubjectId",
113 title AS "title: HomeworkTitle",
114 description AS "description: HomeworkDescription",
115 due_at AS "due_at: Timestamp",
116 NULL::uuid[] AS "assigned: Vec<UserId>",
117 created_by AS "created_by: UserId",
118 created_at AS "created_at: Timestamp""#,
119 subject_uuid,
120 homework_uuid,
121 class_course_uuid,
122 title.as_str(),
123 description.as_ref().map(HomeworkDescription::as_str),
124 due_at_millis,
125 created_by_uuid,
126 created_at_millis,
127 )
128 .fetch_optional(&mut *tx)
129 .await
130 .map_err(|err| {
131 if crate::database::unique_violation(&err).is_some() {
132 AppError::Internal("failed to create homework".into())
133 } else {
134 AppError::from(err)
135 }
136 })?;
137 // The audience subset, written beside the row it scopes: a refused
138 // create (subject gone) writes no audience either, and any other
139 // failure rolls the homework row back with its audience rows.
140 if created.is_some() && !assigned_values.is_empty() {
141 sqlx::query!(
142 "INSERT INTO homework_assignment (homework, student)
143 SELECT $2, s FROM unnest($1::uuid[]) AS t(s)",
144 &assigned_values,
145 homework_uuid
146 )
147 .execute(&mut *tx)
148 .await?;
149 }
150 created.ok_or_else(subject_gone)
151 })
152 .await
153 .map(move |mut created| {
154 created.assigned = assigned;
155 created
156 })
157}
158
159pub async fn read(db: &Database, id: &HomeworkId) -> Result<Option<Homework>, AppError> {
160 Ok(sqlx::query_as!(
161 Homework,
162 r#"SELECT id AS "id: HomeworkId",
163 class_course AS "class_course: ClassCourseId",
164 subject AS "subject: SubjectId",
165 title AS "title: HomeworkTitle",
166 description AS "description: HomeworkDescription",
167 due_at AS "due_at: Timestamp",
168 (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a
169 WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
170 created_by AS "created_by: UserId",
171 created_at AS "created_at: Timestamp"
172 FROM homework WHERE id = $1"#,
173 id.uuid()
174 )
175 .fetch_optional(db)
176 .await?)
177}
178
179/// The instance's homework, newest first (v7 ids sort by creation). The web
180/// layer retains only the rows a given student `student_sees`.
181pub async fn list_for_class_course(
182 db: &Database,
183 class_course: &ClassCourseId,
184) -> Result<Vec<Homework>, AppError> {
185 Ok(sqlx::query_as!(
186 Homework,
187 r#"SELECT id AS "id: HomeworkId",
188 class_course AS "class_course: ClassCourseId",
189 subject AS "subject: SubjectId",
190 title AS "title: HomeworkTitle",
191 description AS "description: HomeworkDescription",
192 due_at AS "due_at: Timestamp",
193 (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a
194 WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
195 created_by AS "created_by: UserId",
196 created_at AS "created_at: Timestamp"
197 FROM homework WHERE class_course = $1 ORDER BY id DESC"#,
198 class_course.uuid()
199 )
200 .fetch_all(db)
201 .await?)
202}
203
204/// The homework table as `SELECT *` cannot read it: the assigned-student
205/// roster is not a column but the `homework_assignment` junction, aggregated
206/// per row. Every runtime ([`PagedList`]) read of homework selects through
207/// this derived table, so its rows decode exactly like the `query_as!` reads
208/// beside them; the alias names the row set the outer WHERE filters.
209const HOMEWORK_WITH_ASSIGNED: &str = "(SELECT h.*, \
210 (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a \
211 WHERE a.homework = h.id) AS assigned \
212 FROM homework h) AS homework";
213
214/// Every homework in the system, newest first — the manager+ view of the
215/// cross-course "my homework" list, narrowed by the optional due window and
216/// instance scope before anything leaves the database, so a manager asking
217/// for open homework never loads the school's whole history. Paged in SQL:
218/// a manager retains nothing in Rust, so the window and the count are the
219/// database's to do.
220pub async fn list_all(
221 db: &Database,
222 due_after: Option<i64>,
223 due_before: Option<i64>,
224 class_course: Option<&ClassCourseId>,
225 limit: Option<i64>,
226 offset: i64,
227) -> Result<(Vec<Homework>, i64), AppError> {
228 let mut from_where = HOMEWORK_WITH_ASSIGNED.to_string();
229 let mut next = 1;
230 let mut conds: Vec<String> = Vec::new();
231 if due_after.is_some() {
232 conds.push(format!("due_at >= ${next}"));
233 next += 1;
234 }
235 if due_before.is_some() {
236 conds.push(format!("due_at < ${next}"));
237 next += 1;
238 }
239 if class_course.is_some() {
240 conds.push(format!("class_course = ${next}"));
241 }
242 if !conds.is_empty() {
243 from_where.push_str(" WHERE ");
244 from_where.push_str(&conds.join(" AND "));
245 }
246 let mut list = PagedList::new(from_where, "ORDER BY id DESC");
247 if let Some(after) = due_after {
248 list = list.bind(after);
249 }
250 if let Some(before) = due_before {
251 list = list.bind(before);
252 }
253 if let Some(course) = class_course {
254 list = list.bind(course.uuid());
255 }
256 list.run::<Homework>(limit, offset, db).await
257}
258
259/// Every homework of every instance in `instances`, newest first (one
260/// query) — the cross-instance list over a caller's visible courses, with
261/// the same optional due-window and instance narrowing as the manager view.
262/// Unbounded by design: the web layer still trims each instance's rows to
263/// what the caller may see (a student to the ones they `student_sees`), and
264/// a window here could only hide rows that trim was about to keep.
265pub async fn list_for_class_courses(
266 db: &Database,
267 instances: &[ClassCourseId],
268 due_after: Option<i64>,
269 due_before: Option<i64>,
270 class_course: Option<&ClassCourseId>,
271) -> Result<Vec<Homework>, AppError> {
272 if instances.is_empty() {
273 return Ok(Vec::new());
274 }
275 // The instance set rides as TEXT: `Param` (the closed bind enum of
276 // db::page) has no uuid-array arm, and `uuid::text` is the canonical
277 // lowercase spelling both sides of the comparison agree on.
278 let scope: Vec<String> = instances.iter().map(|id| id.uuid().to_string()).collect();
279 let mut conds: Vec<String> = vec![String::from("class_course::text = ANY($1)")];
280 let mut next = 2;
281 if due_after.is_some() {
282 conds.push(format!("due_at >= ${next}"));
283 next += 1;
284 }
285 if due_before.is_some() {
286 conds.push(format!("due_at < ${next}"));
287 next += 1;
288 }
289 if class_course.is_some() {
290 conds.push(format!("class_course = ${next}"));
291 }
292 let from_where = format!(
293 "{} WHERE {}",
294 HOMEWORK_WITH_ASSIGNED,
295 conds.join(" AND ")
296 );
297 let mut list = PagedList::new(from_where, "ORDER BY id DESC").bind(Param::Texts(scope));
298 if let Some(after) = due_after {
299 list = list.bind(after);
300 }
301 if let Some(before) = due_before {
302 list = list.bind(before);
303 }
304 if let Some(course) = class_course {
305 list = list.bind(course.uuid());
306 }
307 // No window: the rows in hand are the whole filtered read, which the
308 // caller retains and pages in the web layer.
309 let (rows, _) = list.run::<Homework>(None, 0, db).await?;
310 Ok(rows)
311}
312
313/// The homework of one instance that `user` is meant to see — whole-class
314/// ones plus any subset that names them — newest first. Backs a student's (or
315/// an observer's) per-instance homework report; mirrors
316/// [`Homework::student_sees`](crate::domain::homework::Homework::student_sees)
317/// in SQL so the filter runs in the database.
318pub async fn list_for_user_in_course(
319 db: &Database,
320 class_course: &ClassCourseId,
321 user: &UserId,
322) -> Result<Vec<Homework>, AppError> {
323 Ok(sqlx::query_as!(
324 Homework,
325 r#"SELECT id AS "id: HomeworkId",
326 class_course AS "class_course: ClassCourseId",
327 subject AS "subject: SubjectId",
328 title AS "title: HomeworkTitle",
329 description AS "description: HomeworkDescription",
330 due_at AS "due_at: Timestamp",
331 (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a
332 WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
333 created_by AS "created_by: UserId",
334 created_at AS "created_at: Timestamp"
335 FROM homework
336 WHERE class_course = $1
337 AND (NOT EXISTS (SELECT 1 FROM homework_assignment a
338 WHERE a.homework = homework.id)
339 OR EXISTS (SELECT 1 FROM homework_assignment a
340 WHERE a.homework = homework.id AND a.student = $2))
341 ORDER BY id DESC"#,
342 class_course.uuid(),
343 user.uuid()
344 )
345 .fetch_all(db)
346 .await?)
347}
348
349/// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework.
350/// Request-scoped: every parameter is `Option`, `None` meaning the PATCH
351/// did not carry that field, so it is not written at all. Handing the
352/// snapshot's value back instead would revert a concurrent edit of that
353/// field — under the row lock below, an uncarried field keeps the value read
354/// *under that lock*, never the handler's snapshot. `course`, `created_by`,
355/// and `created_at` are readonly and never appear in the write.
356///
357/// `description` takes `Some(None)` to clear; `assigned` takes `Some(None)`
358/// to widen back to the whole course (stored as no `homework_assignment` rows,
359/// read back as `None`).
360/// The web layer has already re-checked a new `due_at` against now, a new
361/// `subject` against the course, and — inside the transaction here — the
362/// narrowing against the work that would be orphaned by it.
363pub async fn update(
364 db: &Database,
365 homework: Homework,
366 subject: Option<SubjectId>,
367 title: Option<HomeworkTitle>,
368 description: Option<Option<HomeworkDescription>>,
369 due_at: Option<Timestamp>,
370 assigned: Option<Option<Vec<UserId>>>,
371) -> Result<Homework, AppError> {
372 tx_with_retry(db, false, async move |tx| {
373 // The homework row's lock. The orphan guard's reads and the write
374 // below are one transaction with it, so a submission — whose own
375 // transaction locks this very row before writing — cannot land
376 // between the check and the narrowing, orphaned by an audience change
377 // that just missed it. The lock also replaces the old CAS's row read:
378 // the re-tag check below compares the handler's snapshot against the
379 // row as it is *locked*, not as it was first read.
380 let current = sqlx::query_as!(
381 Homework,
382 r#"SELECT id AS "id: HomeworkId",
383 class_course AS "class_course: ClassCourseId",
384 subject AS "subject: SubjectId",
385 title AS "title: HomeworkTitle",
386 description AS "description: HomeworkDescription",
387 due_at AS "due_at: Timestamp",
388 (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a
389 WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
390 created_by AS "created_by: UserId",
391 created_at AS "created_at: Timestamp"
392 FROM homework WHERE id = $1 FOR UPDATE"#,
393 homework.get_id().uuid()
394 )
395 .fetch_optional(&mut *tx)
396 .await?
397 .ok_or(AppError::NotFound)?;
398
399 // The orphan guard runs on exactly the requests that re-scope the
400 // audience. An absent `assigned` writes nothing, so the stored subset
401 // is untouched and no narrowing can happen behind the guard's back.
402 if let Some(resolved) = assigned.as_ref() {
403 ensure_no_orphans(&current, resolved.as_deref(), tx).await?;
404 }
405
406 // A re-tag moves a reference: the new subject's claim and the old
407 // one's release ride the same transaction as the link write, so no
408 // crash can leave a count without its link (the subject would be
409 // undeletable forever) or a link without its count. The release goes
410 // first and the claim refuses on a gone row, so a move to a deleted
411 // subject is a rolled-back no-op — every abort takes the whole move
412 // back with it.
413 let moving = subject.as_ref().filter(|next| **next != homework.subject);
414 if let Some(next) = moving {
415 sqlx::query!(
416 "UPDATE subject SET homework_count = GREATEST(homework_count - 1, 0) WHERE id = $1",
417 current.subject.uuid()
418 )
419 .execute(&mut *tx)
420 .await?;
421 let seat = sqlx::query!(
422 r#"UPDATE subject SET homework_count = homework_count + 1
423 WHERE id = $1 RETURNING 1 AS "seat: i32""#,
424 next.uuid()
425 )
426 .fetch_optional(&mut *tx)
427 .await?;
428 if seat.is_none() {
429 return Err(subject_gone());
430 }
431 }
432
433 // The stale-re-tag check. Armed by the request *carrying* the subject
434 // — even when it re-states the tag its snapshot showed, shifting no
435 // counter — so two PATCHes moving the same homework off the same
436 // subject cannot both claim their target: the loser's snapshot says
437 // A, the locked row says B, and the refusal is the 409 the generic
438 // PATCH builder has always answered with.
439 if subject.is_some() && current.subject != homework.subject {
440 return Err(AppError::Conflict(STALE_MOVE));
441 }
442 // The carried `assigned` replaces the junction rows wholesale —
443 // delete-then-insert under the row lock, so the audience (or its
444 // absence, = whole course) is exactly what the request named. An
445 // uncarried `assigned` writes no rows, keeping the stored audience.
446 if let Some(resolved) = assigned.as_ref() {
447 sqlx::query!(
448 "DELETE FROM homework_assignment WHERE homework = $1",
449 homework.get_id().uuid()
450 )
451 .execute(&mut *tx)
452 .await?;
453 let values: Vec<uuid::Uuid> = resolved.iter().flatten().map(UserId::uuid).collect();
454 if !values.is_empty() {
455 sqlx::query!(
456 "INSERT INTO homework_assignment (homework, student)
457 SELECT $2, s FROM unnest($1::uuid[]) AS t(s)",
458 &values,
459 homework.get_id().uuid()
460 )
461 .execute(&mut *tx)
462 .await?;
463 }
464 }
465
466 // What the PATCH carried is written; what it did not carry keeps the
467 // value just read under the lock. Under that lock this resolved
468 // full-row write is exactly the request-scoped SET the old builder
469 // emitted — except it is one static statement instead of a runtime
470 // build.
471 let new_subject = subject.unwrap_or(current.subject);
472 let new_title = title.clone().unwrap_or_else(|| current.title.clone());
473 let new_description = match description.clone() {
474 None => current.description.clone(),
475 Some(None) => None,
476 Some(Some(text)) => Some(text),
477 };
478 let new_due_at = due_at.unwrap_or(current.due_at);
479 sqlx::query_as!(
480 Homework,
481 r#"UPDATE homework SET subject = $2, title = $3, description = $4,
482 due_at = $5
483 WHERE id = $1
484 RETURNING id AS "id: HomeworkId",
485 class_course AS "class_course: ClassCourseId",
486 subject AS "subject: SubjectId",
487 title AS "title: HomeworkTitle",
488 description AS "description: HomeworkDescription",
489 due_at AS "due_at: Timestamp",
490 (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a
491 WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
492 created_by AS "created_by: UserId",
493 created_at AS "created_at: Timestamp""#,
494 homework.get_id().uuid(),
495 new_subject.uuid(),
496 new_title.as_str(),
497 new_description.as_ref().map(HomeworkDescription::as_str),
498 new_due_at.as_millis(),
499 )
500 .fetch_optional(&mut *tx)
501 .await?
502 .ok_or(AppError::NotFound)
503 })
504 .await
505}
506
507/// Refuse (409) a PATCH that would narrow `homework`'s audience so a student
508/// who already submitted or was graded falls outside it — their work would be
509/// stranded. `new_assigned` is the proposed subset (`None` = whole course, in
510/// which case no one can be orphaned). The blocking students are named in the
511/// message so the teacher knows whose work to clear (or whom to keep assigned)
512/// first.
513///
514/// Runs inside the caller's transaction, under the homework row's lock, so
515/// the check and the narrowing cannot be driven through by a submission.
516async fn ensure_no_orphans(
517 homework: &Homework,
518 new_assigned: Option<&[UserId]>,
519 tx: &mut PgConnection,
520) -> Result<(), AppError> {
521 // Whole-course covers everyone — no narrowing, no orphans.
522 let Some(subset) = new_assigned else {
523 return Ok(());
524 };
525 let submitted: Vec<UserId> = sqlx::query!(
526 r#"SELECT app_user AS "user: UserId" FROM homework_submission WHERE homework = $1"#,
527 homework.get_id().uuid()
528 )
529 .fetch_all(&mut *tx)
530 .await?
531 .into_iter()
532 .map(|row| row.user)
533 .collect();
534 let graded: Vec<UserId> = sqlx::query!(
535 r#"SELECT app_user AS "user: UserId" FROM homework_result WHERE homework = $1"#,
536 homework.get_id().uuid()
537 )
538 .fetch_all(&mut *tx)
539 .await?
540 .into_iter()
541 .map(|row| row.user)
542 .collect();
543 let mut blocked: Vec<String> = Vec::new();
544 for user in submitted.iter().chain(graded.iter()) {
545 let key = user.key().to_string();
546 if !subset.contains(user) && !blocked.contains(&key) {
547 blocked.push(key);
548 }
549 }
550 if blocked.is_empty() {
551 Ok(())
552 } else {
553 Err(AppError::ConflictOwned(format!(
554 "narrowing the assigned list would orphan existing work by {} student(s): {}",
555 blocked.len(),
556 blocked.join(", ")
557 )))
558 }
559}
560
561/// Delete the homework and cascade its submissions, their files, and its
562/// results — one transaction, so a crash can't orphan a submission under a
563/// vanished homework. The cascade runs children-first (every FK here is
564/// `ON DELETE NO ACTION`): files, then submissions — whose `graded_by_result`
565/// stamp points at a result row, so they must be gone before it — then the
566/// results, the audience rows, then the homework. The submission file *blobs*
567/// are the web
568/// layer's to unlink: their names are returned (collected inside the
569/// transaction, before the wipes — a file row inserted after an
570/// out-of-transaction collection would be deleted here while its key was
571/// already gone from the list, stranding the blob) and removed after the
572/// rows are gone.
573pub async fn delete(
574 db: &Database,
575 homework: Homework,
576) -> Result<(Homework, Vec<String>), AppError> {
577 tx_with_retry(db, true, async move |tx| {
578 let blob_keys: Vec<String> = sqlx::query!(
579 r#"SELECT file FROM homework_file
580 WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#,
581 homework.get_id().uuid()
582 )
583 .fetch_all(&mut *tx)
584 .await?
585 .into_iter()
586 .map(|row| row.file)
587 .collect();
588 sqlx::query!(
589 r#"DELETE FROM homework_file
590 WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#,
591 homework.get_id().uuid()
592 )
593 .execute(&mut *tx)
594 .await?;
595 sqlx::query!(
596 "DELETE FROM homework_submission WHERE homework = $1",
597 homework.get_id().uuid()
598 )
599 .execute(&mut *tx)
600 .await?;
601 sqlx::query!(
602 "DELETE FROM homework_result WHERE homework = $1",
603 homework.get_id().uuid()
604 )
605 .execute(&mut *tx)
606 .await?;
607 sqlx::query!(
608 "DELETE FROM homework_assignment WHERE homework = $1",
609 homework.get_id().uuid()
610 )
611 .execute(&mut *tx)
612 .await?;
613 let deleted = sqlx::query_as!(
614 Homework,
615 r#"DELETE FROM homework WHERE id = $1
616 RETURNING id AS "id: HomeworkId",
617 class_course AS "class_course: ClassCourseId",
618 subject AS "subject: SubjectId",
619 title AS "title: HomeworkTitle",
620 description AS "description: HomeworkDescription",
621 due_at AS "due_at: Timestamp",
622 (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a
623 WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
624 created_by AS "created_by: UserId",
625 created_at AS "created_at: Timestamp""#,
626 homework.get_id().uuid()
627 )
628 .fetch_optional(&mut *tx)
629 .await?
630 .ok_or(AppError::NotFound)?;
631 // The subject's reference is given back in this same transaction, off
632 // the row the delete actually removed.
633 sqlx::query!(
634 "UPDATE subject SET homework_count = GREATEST(homework_count - 1, 0) WHERE id = $1",
635 deleted.subject.uuid()
636 )
637 .execute(&mut *tx)
638 .await?;
639 Ok((deleted, blob_keys))
640 })
641 .await
642}
643
644#[cfg(test)]
645mod tests {
646 use super::*;
647 use crate::domain::subject::{Subject, SubjectDescription, SubjectName};
648
649 async fn a_subject(name: &str, db: &Database) -> Subject {
650 crate::db::subject::create(
651 db,
652 &crate::db::course::a_test_course(db).await,
653 SubjectName::try_new(name).unwrap(),
654 SubjectDescription::try_new("").unwrap(),
655 )
656 .await
657 .unwrap()
658 }
659
660 async fn homework_on(subject: &SubjectId, db: &Database) -> Homework {
661 // The instance and the teacher are foreign keys now: a real instance
662 // row (the class, the course and their link, minted by the fixture)
663 // and a real teacher.
664 let teacher = UserId::generate();
665 sqlx::query(
666 "INSERT INTO app_user (id, username, created_at, role) \
667 VALUES ($1, $2, 0, 'teacher')",
668 )
669 .bind(teacher.uuid())
670 .bind(format!("homework-fixture-{}", &teacher.key()[30..]))
671 .execute(db)
672 .await
673 .unwrap();
674 create(
675 db,
676 &crate::db::course::a_test_instance(db).await.0,
677 subject,
678 HomeworkTitle::try_new("essay").unwrap(),
679 None,
680 Timestamp::from_millis(1),
681 None,
682 &teacher,
683 )
684 .await
685 .unwrap()
686 }
687
688 /// The stored `homework_count` on one subject, absent counting as zero.
689 async fn count_on(subject: &SubjectId, db: &Database) -> i64 {
690 sqlx::query_scalar::<_, i64>("SELECT homework_count FROM subject WHERE id = $1")
691 .bind(subject.uuid())
692 .fetch_optional(db)
693 .await
694 .unwrap()
695 .unwrap_or(0)
696 }
697
698 /// How many rows `sql` selects ids for.
699 async fn rows(sql: &str, db: &Database) -> usize {
700 sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!(
701 "SELECT count(*) FROM ({sql}) AS t"
702 )))
703 .fetch_one(db)
704 .await
705 .unwrap() as usize
706 }
707
708 /// The invariant on the create path: the claim and the row it accounts for
709 /// commit together or not at all. A refused create leaves *neither* — no
710 /// homework row, and no count stranded on a subject (the subject's delete
711 /// guard reads that count, so a stray one makes it undeletable forever).
712 #[tokio::test]
713 async fn a_refused_create_writes_neither_row_nor_count() {
714 let (db, _leases) = crate::database::init_test_db().await;
715 let subject = a_subject("algebra", &db).await;
716 let id = *subject.get_id();
717 crate::db::subject::delete(&db, subject).await.unwrap();
718
719 let error = create(
720 &db,
721 &crate::domain::class_course::ClassCourseId::from_key("course"),
722 &id,
723 HomeworkTitle::try_new("essay").unwrap(),
724 None,
725 Timestamp::from_millis(1),
726 None,
727 &UserId::from_key("teacher"),
728 )
729 .await
730 .expect_err("a subject that is gone must not be taggable");
731 assert!(error.to_string().contains("subject does not exist"));
732 assert_eq!(
733 rows("SELECT id FROM homework", &db).await,
734 0,
735 "a refused create may write no row"
736 );
737 assert_eq!(
738 rows("SELECT id FROM subject", &db).await,
739 0,
740 "…and least of all a count on a subject it just brought back"
741 );
742 }
743
744 /// The invariant on the PATCH path: a re-tag carries the new subject's
745 /// claim and the old one's release with the link itself.
746 #[tokio::test]
747 async fn a_subject_move_moves_the_count() {
748 let (db, _leases) = crate::database::init_test_db().await;
749 let from = a_subject("algebra", &db).await;
750 let to = a_subject("geometry", &db).await;
751 let homework = homework_on(from.get_id(), &db).await;
752 assert_eq!(count_on(from.get_id(), &db).await, 1);
753
754 let moved = update(&db, homework, Some(*to.get_id()), None, None, None, None)
755 .await
756 .unwrap();
757 assert_eq!(moved.get_subject(), to.get_id());
758 assert_eq!(
759 count_on(from.get_id(), &db).await,
760 0,
761 "the old subject is free"
762 );
763 assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not");
764 assert!(
765 crate::db::subject::delete(&db, from).await.is_ok(),
766 "no reference left"
767 );
768 assert!(
769 crate::db::subject::delete(&db, to).await.is_err(),
770 "the reference moved here refuses the delete"
771 );
772 }
773
774 /// The claim throws inside the same transaction as the link write, so a
775 /// move onto a subject that is gone rolls the release back with it: the row
776 /// keeps its tag and both counters read as if nothing ran.
777 #[tokio::test]
778 async fn a_move_to_a_dead_subject_leaves_everything_untouched() {
779 let (db, _leases) = crate::database::init_test_db().await;
780 let from = a_subject("algebra", &db).await;
781 let dead = a_subject("geometry", &db).await;
782 let gone = *dead.get_id();
783 crate::db::subject::delete(&db, dead).await.unwrap();
784 let homework = homework_on(from.get_id(), &db).await;
785
786 let error = update(&db, homework.clone(), Some(gone), None, None, None, None)
787 .await
788 .expect_err("a subject that is gone must not be taggable");
789 assert!(error.to_string().contains("subject does not exist"));
790 let stored = read(&db, homework.get_id()).await.unwrap().unwrap();
791 assert_eq!(stored.get_subject(), from.get_id(), "the tag never moved");
792 assert_eq!(
793 count_on(from.get_id(), &db).await,
794 1,
795 "the release rolled back with the claim"
796 );
797 assert_eq!(
798 rows("SELECT id FROM subject", &db).await,
799 1,
800 "the dead subject was not brought back by a count"
801 );
802 assert_eq!(count_on(&gone, &db).await, 0);
803 }
804
805 /// The double-claim guard. Both movers compute their claim and release from
806 /// the row as *they* read it, so two PATCHes re-tagging the same homework
807 /// off the same subject both release it and both claim their target — two
808 /// counts for one link, and the loser's target is undeletable forever. The
809 /// second call here runs on the struct read before the first one landed,
810 /// which is that race with the interleaving pinned: it must be refused
811 /// outright, and the counts must read as if it never ran.
812 #[tokio::test]
813 async fn a_stale_mover_is_refused_and_claims_nothing() {
814 let (db, _leases) = crate::database::init_test_db().await;
815 let from = a_subject("algebra", &db).await;
816 let to = a_subject("geometry", &db).await;
817 let other = a_subject("calculus", &db).await;
818 let homework = homework_on(from.get_id(), &db).await;
819 let stale = homework.clone();
820 update(&db, homework, Some(*to.get_id()), None, None, None, None)
821 .await
822 .unwrap();
823
824 let error = update(
825 &db,
826 stale.clone(),
827 Some(*other.get_id()),
828 None,
829 None,
830 None,
831 None,
832 )
833 .await
834 .expect_err("a mover that read a tag it no longer holds must be refused");
835 assert!(
836 matches!(error, AppError::Conflict(_)),
837 "a lost CAS is a conflict, not a 404 or a 500: {error:?}"
838 );
839 let stored = read(&db, stale.get_id()).await.unwrap().unwrap();
840 assert_eq!(stored.get_subject(), to.get_id(), "the winner's tag");
841 assert_eq!(
842 count_on(from.get_id(), &db).await,
843 0,
844 "released once, not twice"
845 );
846 assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once");
847 assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed");
848 }
849
850 /// The same race with the counters taken out of it. A PATCH that re-states
851 /// the subject its snapshot showed shifts *nothing* — no claim and no
852 /// release — so if the guard were armed off the counter move it would not be
853 /// armed here at all, and the write would land: the winner's tag silently
854 /// dragged back, its claim stranded on a subject nothing points at
855 /// (undeletable forever) and the reverted-to subject tagged at a count of
856 /// zero (deletable while tagged). The guard is armed by the request
857 /// *carrying* the column instead, which is why this is refused.
858 #[tokio::test]
859 async fn a_stale_re_stater_is_refused_and_reverts_nothing() {
860 let (db, _leases) = crate::database::init_test_db().await;
861 let from = a_subject("algebra", &db).await;
862 let to = a_subject("geometry", &db).await;
863 let homework = homework_on(from.get_id(), &db).await;
864 let stale = homework.clone();
865 update(&db, homework, Some(*to.get_id()), None, None, None, None)
866 .await
867 .unwrap();
868
869 let error = update(
870 &db,
871 stale.clone(),
872 Some(*from.get_id()),
873 None,
874 None,
875 None,
876 None,
877 )
878 .await
879 .expect_err("re-stating a tag someone else moved must be refused");
880 assert!(
881 matches!(error, AppError::Conflict(_)),
882 "a lost CAS is a conflict, not a silent 200: {error:?}"
883 );
884 let stored = read(&db, stale.get_id()).await.unwrap().unwrap();
885 assert_eq!(stored.get_subject(), to.get_id(), "the winner's tag");
886 assert_eq!(
887 count_on(from.get_id(), &db).await,
888 0,
889 "the reverted-to subject must not end up tagged at zero"
890 );
891 assert_eq!(
892 count_on(to.get_id(), &db).await,
893 1,
894 "…nor the winner's subject counted with nothing pointing at it"
895 );
896
897 // A *genuine* no-op re-state — nobody moved underneath it — still lands,
898 // and still moves no counter: the CAS passes trivially.
899 let fresh = read(&db, stale.get_id()).await.unwrap().unwrap();
900 let same = update(&db, fresh, Some(*to.get_id()), None, None, None, None)
901 .await
902 .expect("re-stating the tag actually held is not a race");
903 assert_eq!(same.get_subject(), to.get_id());
904 assert_eq!(
905 count_on(from.get_id(), &db).await,
906 0,
907 "still no counter move"
908 );
909 assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once, still");
910 }
911
912 /// The audience contract in SQL: no `homework_assignment` rows = the whole
913 /// course (every student's list, later enrollees included); rows name the
914 /// subset, and `list_for_user_in_course` answers it to the named student
915 /// alone. The read-back roster is the junction itself.
916 #[tokio::test]
917 async fn a_subset_reaches_only_the_named_and_widening_clears_the_rows() {
918 let (db, _leases) = crate::database::init_test_db().await;
919 let subject = a_subject("tarih", &db).await;
920 let teacher = UserId::generate();
921 sqlx::query(
922 "INSERT INTO app_user (id, username, created_at, role) \
923 VALUES ($1, $2, 0, 'teacher')",
924 )
925 .bind(teacher.uuid())
926 .bind(format!("homework-audience-{}", &teacher.key()[30..]))
927 .execute(&db)
928 .await
929 .unwrap();
930 let ali = UserId::generate();
931 sqlx::query(
932 "INSERT INTO app_user (id, username, created_at, role) \
933 VALUES ($1, $2, 0, 'student')",
934 )
935 .bind(ali.uuid())
936 .bind(format!("homework-audience-{}", &ali.key()[30..]))
937 .execute(&db)
938 .await
939 .unwrap();
940 let veli = UserId::generate();
941 sqlx::query(
942 "INSERT INTO app_user (id, username, created_at, role) \
943 VALUES ($1, $2, 0, 'student')",
944 )
945 .bind(veli.uuid())
946 .bind(format!("homework-audience-{}", &veli.key()[30..]))
947 .execute(&db)
948 .await
949 .unwrap();
950 let instance = crate::db::course::a_test_instance(&db).await.0;
951 let homework = create(
952 &db,
953 &instance,
954 subject.get_id(),
955 HomeworkTitle::try_new("essay").unwrap(),
956 None,
957 Timestamp::from_millis(1),
958 Some(vec![ali]),
959 &teacher,
960 )
961 .await
962 .unwrap();
963 assert_eq!(homework.get_assigned(), Some(&[ali][..]));
964 assert_eq!(
965 list_for_user_in_course(&db, &instance, &ali)
966 .await
967 .unwrap()
968 .len(),
969 1,
970 "the named student sees the subset"
971 );
972 assert!(
973 list_for_user_in_course(&db, &instance, &veli)
974 .await
975 .unwrap()
976 .is_empty(),
977 "an unnamed student sees nothing"
978 );
979 // Widening back to the whole instance (`Some(None)`) empties the
980 // junction: everyone — including the never-named student — is covered.
981 let widened = update(&db, homework, None, None, None, None, Some(None))
982 .await
983 .unwrap();
984 assert_eq!(widened.get_assigned(), None);
985 assert_eq!(
986 list_for_user_in_course(&db, &instance, &veli)
987 .await
988 .unwrap()
989 .len(),
990 1,
991 "whole-instance reaches the never-named student"
992 );
993 }
994
995 /// A real teacher row — `created_by` is a foreign key.
996 async fn a_teacher(db: &Database) -> UserId {
997 let teacher = UserId::generate();
998 sqlx::query(
999 "INSERT INTO app_user (id, username, created_at, role) \
1000 VALUES ($1, $2, 0, 'teacher')",
1001 )
1002 .bind(teacher.uuid())
1003 .bind(format!("homework-filter-{}", &teacher.key()[30..]))
1004 .execute(db)
1005 .await
1006 .unwrap();
1007 teacher
1008 }
1009
1010 /// One homework with a chosen due instant on `instance`.
1011 async fn homework_due(
1012 db: &Database,
1013 instance: &ClassCourseId,
1014 subject: &SubjectId,
1015 due_at: i64,
1016 title: &str,
1017 ) -> Homework {
1018 create(
1019 db,
1020 instance,
1021 subject,
1022 HomeworkTitle::try_new(title).unwrap(),
1023 None,
1024 Timestamp::from_millis(due_at),
1025 None,
1026 &a_teacher(db).await,
1027 )
1028 .await
1029 .unwrap()
1030 }
1031
1032 /// The SQL predicates the cross-instance lists gained: the due window and
1033 /// the instance scope both run in the WHERE, and (for the manager path)
1034 /// the page window sits after them, with the count over the same clause.
1035 #[tokio::test]
1036 async fn list_all_filters_by_due_window_and_instance_in_sql() {
1037 let (db, _leases) = crate::database::init_test_db().await;
1038 let (here, _) = crate::db::course::a_test_instance(&db).await;
1039 let (there, course2) = crate::db::course::a_test_instance(&db).await;
1040 let subject = a_subject("matematik", &db).await;
1041 let subject2 = crate::db::subject::create(
1042 &db,
1043 &course2,
1044 SubjectName::try_new("fizik").unwrap(),
1045 SubjectDescription::try_new("").unwrap(),
1046 )
1047 .await
1048 .unwrap();
1049 let now = Timestamp::now().as_millis();
1050 let day = 86_400_000_i64;
1051 let past = homework_due(&db, &here, subject.get_id(), now - day, "past-here").await;
1052 let open = homework_due(&db, &here, subject.get_id(), now + day, "open-here").await;
1053 let other = homework_due(&db, &there, subject2.get_id(), now + 2 * day, "open-there").await;
1054
1055 // The open tab: due at or after the bound.
1056 let (rows, total) = list_all(&db, Some(now), None, None, None, 0)
1057 .await
1058 .unwrap();
1059 assert_eq!(total, 2);
1060 assert_eq!(
1061 rows.iter().map(Homework::get_id).collect::<Vec<_>>(),
1062 vec![other.get_id(), open.get_id()],
1063 "newest first, past rows left out"
1064 );
1065 // The past tab: due strictly before the bound — the bounds share no
1066 // instant and leave no gap.
1067 let (rows, total) = list_all(&db, None, Some(now), None, None, 0)
1068 .await
1069 .unwrap();
1070 assert_eq!(total, 1);
1071 assert_eq!(rows[0].get_id(), past.get_id());
1072 // The instance scope: the other instance's rows stay behind.
1073 let (rows, total) = list_all(&db, None, None, Some(&there), None, 0)
1074 .await
1075 .unwrap();
1076 assert_eq!(total, 1);
1077 assert_eq!(rows[0].get_id(), other.get_id());
1078 // A well-formed id that names no row is an empty page, not an error.
1079 let (rows, total) = list_all(&db, None, None, Some(&ClassCourseId::generate()), None, 0)
1080 .await
1081 .unwrap();
1082 assert_eq!((rows.len(), total), (0, 0));
1083 // The page window applies after the filter, and the count stays the
1084 // filtered length, not the page size.
1085 let (rows, total) = list_all(&db, Some(now), None, None, Some(1), 0)
1086 .await
1087 .unwrap();
1088 assert_eq!((rows.len(), total), (1, 2));
1089 let (rows, total) = list_all(&db, Some(now), None, None, Some(1), 1)
1090 .await
1091 .unwrap();
1092 assert_eq!((rows.len(), total), (1, 2));
1093 assert_eq!(rows[0].get_id(), open.get_id());
1094 // Absent params: every row, unchanged.
1095 let (_, total) = list_all(&db, None, None, None, None, 0).await.unwrap();
1096 assert_eq!(total, 3);
1097 }
1098
1099 /// The per-instance path: the caller's instances scope the read in SQL,
1100 /// and the due window and single-instance filter apply on top of it.
1101 #[tokio::test]
1102 async fn list_for_class_courses_applies_the_same_predicates() {
1103 let (db, _leases) = crate::database::init_test_db().await;
1104 let (here, _) = crate::db::course::a_test_instance(&db).await;
1105 let (there, course2) = crate::db::course::a_test_instance(&db).await;
1106 let subject = a_subject("matematik", &db).await;
1107 let subject2 = crate::db::subject::create(
1108 &db,
1109 &course2,
1110 SubjectName::try_new("fizik").unwrap(),
1111 SubjectDescription::try_new("").unwrap(),
1112 )
1113 .await
1114 .unwrap();
1115 let now = Timestamp::now().as_millis();
1116 let day = 86_400_000_i64;
1117 let _past = homework_due(&db, &here, subject.get_id(), now - day, "past-here").await;
1118 let open = homework_due(&db, &here, subject.get_id(), now + day, "open-here").await;
1119 let other = homework_due(&db, &there, subject2.get_id(), now + 2 * day, "open-there").await;
1120 let both = vec![here.clone(), there.clone()];
1121
1122 let rows = list_for_class_courses(&db, &both, Some(now), None, None)
1123 .await
1124 .unwrap();
1125 assert_eq!(
1126 rows.iter().map(Homework::get_id).collect::<Vec<_>>(),
1127 vec![other.get_id(), open.get_id()]
1128 );
1129 let rows = list_for_class_courses(&db, &both, None, Some(now), None)
1130 .await
1131 .unwrap();
1132 assert_eq!(rows.len(), 1, "the past tab keeps only the past row");
1133 // A filter naming an instance outside the caller's visible set matches
1134 // nothing — the scopes intersect, they do not override each other.
1135 let rows = list_for_class_courses(&db, &both, None, None, Some(&here))
1136 .await
1137 .unwrap();
1138 assert_eq!(rows.len(), 2, "both here rows, past and open");
1139 let stranger = ClassCourseId::generate();
1140 let rows = list_for_class_courses(&db, &both, None, None, Some(&stranger))
1141 .await
1142 .unwrap();
1143 assert!(rows.is_empty(), "an unknown instance names no row");
1144 // Absent filters: the whole visible read, unchanged.
1145 let rows = list_for_class_courses(&db, &both, None, None, None)
1146 .await
1147 .unwrap();
1148 assert_eq!(rows.len(), 3);
1149 }
1150}