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.rs244 lines, 9.6 KiBHistoryRawDownload
1//! Homework workflows: the cascading delete and the shared student-side wall
2//! ([`gate_own_submission`]) every submission path walks. Row reads and
3//! listings pass through to [`crate::db::homework`]; the submission, file,
4//! and grade workflows live in the sibling `service::homework_*` modules.
5//!
6//! There is no homework subsystem lock any more: the writes that used to
7//! serialize on one — the PATCH's orphan guard, the delete cascade, grading,
8//! and every student-side write — now contend on the *homework row itself*
9//! (`SELECT … FOR UPDATE` inside each transaction), so the ordering they
10//! need survives a multi-process deployment. See
11//! [`crate::db::homework::update`] and
12//! [`crate::db::homework_result::grade`].
13
14use crate::database::Database;
15use crate::db::homework;
16use crate::domain::class_course::ClassCourseId;
17use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};
18use crate::domain::role::Role;
19use crate::domain::subject::SubjectId;
20use crate::domain::timestamp::Timestamp;
21use crate::domain::user::{User, UserId};
22use crate::error::AppError;
23
24#[expect(
25 clippy::too_many_arguments,
26 reason = "mirrors the sibling entities' create(field, field, ..) shape"
27)]
28pub async fn create(
29 db: &Database,
30 class_course: &ClassCourseId,
31 subject: &SubjectId,
32 title: HomeworkTitle,
33 description: Option<HomeworkDescription>,
34 due_at: Timestamp,
35 assigned: Option<Vec<UserId>>,
36 created_by: &UserId,
37) -> Result<Homework, AppError> {
38 // The subject tag is checked against the instance's *resolved* subject
39 // set — override-or-inherit — not merely against the catalog course.
40 // Service-side, so every caller (the route under `/instances` included)
41 // enforces the syllabus rule even though its own pre-flight only sees
42 // the course.
43 let instance = crate::service::class_course::read(db, class_course)
44 .await?
45 .ok_or(AppError::NotFound)?;
46 crate::service::offering_subject::ensure_resolved_member(db, &instance, subject).await?;
47 homework::create(
48 db,
49 class_course,
50 subject,
51 title,
52 description,
53 due_at,
54 assigned,
55 created_by,
56 )
57 .await
58}
59
60/// The homework row, for callers that only inspect it — the web layer's gates
61/// read through here.
62pub async fn read(db: &Database, id: &HomeworkId) -> Result<Option<Homework>, AppError> {
63 homework::read(db, id).await
64}
65
66/// The optional predicates of the cross-instance homework reads — the
67/// `?due_after=&due_before=&class_course=` scoping of `GET /homework`.
68/// Absent fields widen the read; none of them widens the caller's
69/// visibility, which the web layer still applies on top.
70#[derive(Debug, Clone, Default)]
71pub struct HomeworkListFilter {
72 /// Keep homework due at or after this instant (Unix ms) — the open tab.
73 pub due_after: Option<i64>,
74 /// Keep homework due before this instant (Unix ms) — the past tab.
75 pub due_before: Option<i64>,
76 /// Keep only this class×course instance's homework.
77 pub class_course: Option<ClassCourseId>,
78}
79
80/// Every homework, newest first — the manager+ view, narrowed by `filter`
81/// in SQL and paged in the database (a manager retains nothing in Rust, so
82/// the window and the count are both the database's).
83pub async fn list_all(
84 db: &Database,
85 filter: &HomeworkListFilter,
86 limit: Option<i64>,
87 offset: i64,
88) -> Result<(Vec<Homework>, i64), AppError> {
89 homework::list_all(
90 db,
91 filter.due_after,
92 filter.due_before,
93 filter.class_course.as_ref(),
94 limit,
95 offset,
96 )
97 .await
98}
99
100/// The homework of one class×course instance, newest first — the read behind
101/// `GET /instances/{id}/homework`.
102pub async fn list_for_class_course(
103 db: &Database,
104 class_course: &ClassCourseId,
105) -> Result<Vec<Homework>, AppError> {
106 homework::list_for_class_course(db, class_course).await
107}
108
109/// Every homework of every instance in `instances` (one query) — the read
110/// behind a caller's visible courses, narrowed by `filter` in SQL. Unpaged:
111/// the caller may still drop rows in Rust (a student's audience), so a
112/// window here could only hide rows that trim was about to keep.
113pub async fn list_for_class_courses(
114 db: &Database,
115 instances: &[ClassCourseId],
116 filter: &HomeworkListFilter,
117) -> Result<Vec<Homework>, AppError> {
118 homework::list_for_class_courses(
119 db,
120 instances,
121 filter.due_after,
122 filter.due_before,
123 filter.class_course.as_ref(),
124 )
125 .await
126}
127
128/// The homework of one instance that `user` is meant to see — the per-instance
129/// block of a homework report.
130pub async fn list_for_user_in_class_course(
131 db: &Database,
132 class_course: &ClassCourseId,
133 user: &UserId,
134) -> Result<Vec<Homework>, AppError> {
135 homework::list_for_user_in_course(db, class_course, user).await
136}
137
138/// Re-scope (or re-tag, re-title, re-describe, re-schedule) the homework.
139///
140/// The audience-narrowing orphan guard and the stale-re-tag refusal are one
141/// transaction with the write in [`homework::update`], under the homework
142/// row's lock — a submission (which locks the same row before writing)
143/// cannot land between the check and the narrowing it would have refused.
144pub async fn update(
145 db: &Database,
146 homework: Homework,
147 subject: Option<SubjectId>,
148 title: Option<HomeworkTitle>,
149 description: Option<Option<HomeworkDescription>>,
150 due_at: Option<Timestamp>,
151 assigned: Option<Option<Vec<UserId>>>,
152) -> Result<Homework, AppError> {
153 homework::update(db, homework, subject, title, description, due_at, assigned).await
154}
155
156/// Delete the homework: run the cascading delete (submissions, their files,
157/// results, then the row — one transaction, children first) and return the
158/// submission-file blob keys, which the transaction collected before the
159/// wipes so no file added mid-delete can strand its blob. The web layer
160/// unlinks the blobs once the rows are gone; a crash in between strands at
161/// worst an unreachable file.
162pub async fn delete(db: &Database, homework: Homework) -> Result<Vec<String>, AppError> {
163 let (_, blob_keys) = homework::delete(db, homework).await?;
164 Ok(blob_keys)
165}
166
167/// A 403 unless `user` is enrolled in the instance the homework belongs to —
168/// the homework twin of the exam sitting wall
169/// ([`crate::service::exam_attempt::ensure_enrolled`], which is `Exam`-shaped).
170/// Submitting is course content, so leaving the instance closes it; re-checked
171/// on every submission and file write, so an unenrollment mid-task bites the
172/// next.
173async fn ensure_enrolled(
174 class_course: &ClassCourseId,
175 user: &UserId,
176 db: &Database,
177) -> Result<(), AppError> {
178 if crate::service::enrollment::read_for_user(db, class_course, user)
179 .await?
180 .is_none()
181 {
182 return Err(AppError::Forbidden(
183 "you are not enrolled in this homework's course",
184 ));
185 }
186 Ok(())
187}
188
189/// Read a homework and clear `user` to act on their own submission to it — the
190/// shared wall of the submission, file, and (student side of the) download
191/// paths. Three gates, in order:
192///
193/// 1. Exact `Student` on the *live* role. Teachers assign homework, they never
194/// hand it in; the `RequireStudent` extractor's ≥Student would wave a
195/// promoted teacher through, so this checks the role `CurrentUser` read for
196/// this very request — the same reasoning as [`crate::service::exam_attempt::ensure_student`].
197/// 2. Current enrollment in the course.
198/// 3. The audience check: a student a subset homework does not name gets a 404,
199/// never a 403, so a subset assignment never leaks to those left out (the
200/// no-leak idiom an unseen exam draft uses).
201pub async fn gate_own_submission(
202 id: &str,
203 user: &User,
204 db: &Database,
205) -> Result<Homework, AppError> {
206 let homework = homework::read(db, &HomeworkId::from_key(id))
207 .await?
208 .ok_or(AppError::NotFound)?;
209 if user.get_role() != Role::Student {
210 return Err(AppError::Forbidden(
211 "only students have homework submissions",
212 ));
213 }
214 ensure_enrolled(homework.get_class_course(), user.get_id(), db).await?;
215 if !homework.student_sees(user.get_id()) {
216 return Err(AppError::NotFound);
217 }
218 Ok(homework)
219}
220
221/// The year wall of the student side: an archived year makes past structure
222/// read-only. Deliberately *not* inside [`gate_own_submission`] — that gate
223/// also fronts the download read, and an archived year is still browsable. So
224/// every student *write* calls this right after the gate, which keeps the
225/// order that matters: a student the homework never named is refused by the
226/// audience check with a 404 and never learns the homework exists.
227///
228/// The gate keys on the homework's instance → its class section → that
229/// section's year (D8): a term archived inside an open year does not close
230/// homework, the year does.
231pub async fn require_open_instance(homework: &Homework, db: &Database) -> Result<(), AppError> {
232 crate::service::class_course::require_open(db, homework.get_class_course()).await
233}
234
235/// Bring one user's badge awards up to date after a write moved their counters
236/// — the student's after a submission, the grader's after a grade. Never fails
237/// the request it follows: a badge is a decoration on top
238/// of the work, and losing one to a transient database error is not worth
239/// refusing a hand-in over — the next counter move re-runs this and heals it.
240pub(crate) async fn award_badges(user: &UserId, db: &Database) {
241 if let Err(err) = crate::db::badge::sync(db, user).await {
242 tracing::warn!("failed to sync badges for {}: {err}", user.key());
243 }
244}