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_result.rs475 lines, 18.0 KiBHistoryRawDownload
1//! The `homework_result` table: one grade per (homework, user) — the
2//! freeze-stamping UPSERT, the reads the roster and report join on, and the
3//! un-grade that gives the grader's counter back. Grading's policy gates
4//! (who may grade whom) live in [`crate::service::homework_result`]; the
5//! validated status and mark types in
6//! [`crate::domain::homework_result`].
7
8use crate::database::{Database, tx_with_retry};
9use crate::domain::class_course::ClassCourseId;
10use crate::domain::exam_result::Mark;
11use crate::domain::homework::HomeworkId;
12use crate::domain::homework_result::{HomeworkResult, HomeworkResultId, HomeworkStatus};
13use crate::domain::timestamp::Timestamp;
14use crate::domain::user::UserId;
15use crate::error::AppError;
16
17/// Record (or overwrite) the grade for (homework, user). One row per pair by
18/// the pair's UNIQUE constraint, so grading is one atomic UPSERT —
19/// concurrent grades for the same pair converge on one row instead of
20/// racing a duplicate into a 500. Grading before the due date, or before any
21/// submission exists, is allowed (the caller's policy call).
22///
23/// In the same transaction the grade *stamps* the student's submission
24/// (`graded_by_result`), which is what freezes it: every student-side write
25/// to that row then fails its own `graded_by_result IS NULL` condition, with
26/// no cross-table read for a concurrent write to slip past. A submission
27/// that does not exist yet is left alone — grading absent work must not
28/// conjure a hand-in (the report reads `submitted`/`missing`/`late` straight
29/// off that row).
30///
31/// That one case is where this statement stops defending itself: a student's
32/// *first* hand-in committing between this grade and nothing-to-stamp would
33/// land unstamped, leaving a grade beside an editable submission. What
34/// forbids it here is the homework row's lock: every student-side write
35/// locks the homework row across its write, and so does this transaction, so
36/// the interleaving is ordered away instead of leased away — either the
37/// grade saw the row to stamp, or the submission saw no grade and created
38/// under a lock this transaction already held.
39///
40/// Whether the pair was already graded is read one statement ahead of the
41/// write, under the same lock — it is what keeps a regrade from crediting
42/// the grader a second time. No mark counter here: a homework mark is
43/// optional and most grades are status-only, so `high_mark` is an exam-only
44/// family.
45///
46/// The homework row's `FOR UPDATE` is also the parent gate: the id is minted
47/// fresh, so a grade landing inside a homework (or course) delete's window
48/// would otherwise *re-create* a result row under a homework that is gone,
49/// readable ever after at `GET /homework/{id}/result` (no existence check
50/// there) with a `marks_given_total` no ungrade can reach, because every
51/// route to the grade goes through the homework. A vanished row answers
52/// `Err(NotFound)` — the 404 the web layer's own lookup would have answered.
53pub async fn grade(
54 db: &Database,
55 homework: &HomeworkId,
56 user: &UserId,
57 status: HomeworkStatus,
58 mark: Option<Mark>,
59 graded_by: &UserId,
60) -> Result<HomeworkResult, AppError> {
61 let id = HomeworkResultId::generate();
62 let now = Timestamp::now();
63 // Owned captures (`Send` rule of `tx_with_retry` closures).
64 let homework = homework.clone();
65 let user = *user;
66 let graded_by = *graded_by;
67 tx_with_retry(db, false, async move |tx| {
68 let alive = sqlx::query!(
69 r#"SELECT 1 AS "row: i32" FROM homework WHERE id = $1 FOR UPDATE"#,
70 homework.uuid()
71 )
72 .fetch_optional(&mut *tx)
73 .await?;
74 if alive.is_none() {
75 return Err(AppError::NotFound);
76 }
77 let before = sqlx::query!(
78 r#"SELECT 1 AS "row: i32" FROM homework_result
79 WHERE homework = $1 AND app_user = $2 FOR UPDATE"#,
80 homework.uuid(),
81 user.uuid()
82 )
83 .fetch_optional(&mut *tx)
84 .await?
85 .is_some();
86 // A regrade overwrites status, mark, grader and stamp — `id` and
87 // `homework`/`app_user` are the row's identity and stay.
88 let graded = sqlx::query_as!(
89 HomeworkResult,
90 r#"INSERT INTO homework_result (id, homework, app_user, status, mark, graded_by, created_at)
91 VALUES ($1, $2, $3, $4, $5, $6, $7)
92 ON CONFLICT (homework, app_user) DO UPDATE
93 SET status = EXCLUDED.status, mark = EXCLUDED.mark,
94 graded_by = EXCLUDED.graded_by, created_at = EXCLUDED.created_at
95 RETURNING id AS "id: HomeworkResultId",
96 homework AS "homework: HomeworkId",
97 app_user AS "user: UserId",
98 status AS "status: HomeworkStatus",
99 mark AS "mark: Mark",
100 graded_by AS "graded_by: UserId",
101 created_at AS "created_at: Timestamp""#,
102 id.uuid(),
103 homework.uuid(),
104 user.uuid(),
105 status.as_str(),
106 mark.map(|mark| mark.as_i64()),
107 graded_by.uuid(),
108 now.as_millis(),
109 )
110 .fetch_one(&mut *tx)
111 .await?;
112 sqlx::query!(
113 r#"UPDATE homework_submission SET graded_by_result = $3
114 WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL"#,
115 homework.uuid(),
116 user.uuid(),
117 graded.id.uuid()
118 )
119 .execute(&mut *tx)
120 .await?;
121 if !before {
122 sqlx::query!(
123 "UPDATE app_user SET marks_given_total = marks_given_total + 1 WHERE id = $1",
124 graded_by.uuid()
125 )
126 .execute(&mut *tx)
127 .await?;
128 }
129 Ok(graded)
130 })
131 .await
132}
133
134/// `user`'s grade for `homework`, if graded.
135pub async fn read_for(
136 db: &Database,
137 homework: &HomeworkId,
138 user: &UserId,
139) -> Result<Option<HomeworkResult>, AppError> {
140 Ok(sqlx::query_as!(
141 HomeworkResult,
142 r#"SELECT id AS "id: HomeworkResultId",
143 homework AS "homework: HomeworkId",
144 app_user AS "user: UserId",
145 status AS "status: HomeworkStatus",
146 mark AS "mark: Mark",
147 graded_by AS "graded_by: UserId",
148 created_at AS "created_at: Timestamp"
149 FROM homework_result WHERE homework = $1 AND app_user = $2"#,
150 homework.uuid(),
151 user.uuid()
152 )
153 .fetch_optional(db)
154 .await?)
155}
156
157/// Every grade for `homework` — the roster joins these onto the submissions.
158pub async fn list_for_homework(
159 db: &Database,
160 homework: &HomeworkId,
161) -> Result<Vec<HomeworkResult>, AppError> {
162 Ok(sqlx::query_as!(
163 HomeworkResult,
164 r#"SELECT id AS "id: HomeworkResultId",
165 homework AS "homework: HomeworkId",
166 app_user AS "user: UserId",
167 status AS "status: HomeworkStatus",
168 mark AS "mark: Mark",
169 graded_by AS "graded_by: UserId",
170 created_at AS "created_at: Timestamp"
171 FROM homework_result WHERE homework = $1 ORDER BY id DESC"#,
172 homework.uuid()
173 )
174 .fetch_all(db)
175 .await?)
176}
177
178/// `user`'s homework grades across one course — the raw rows behind the
179/// per-course block of a homework report. Mirrors
180/// `ExamResult::list_for_user_in_course`.
181pub async fn list_for_user_in_course(
182 db: &Database,
183 class_course: &ClassCourseId,
184 user: &UserId,
185) -> Result<Vec<HomeworkResult>, AppError> {
186 Ok(sqlx::query_as!(
187 HomeworkResult,
188 r#"SELECT id AS "id: HomeworkResultId",
189 homework AS "homework: HomeworkId",
190 app_user AS "user: UserId",
191 status AS "status: HomeworkStatus",
192 mark AS "mark: Mark",
193 graded_by AS "graded_by: UserId",
194 created_at AS "created_at: Timestamp"
195 FROM homework_result
196 WHERE app_user = $1
197 AND homework IN (SELECT id FROM homework WHERE class_course = $2)
198 ORDER BY id DESC"#,
199 user.uuid(),
200 class_course.uuid()
201 )
202 .fetch_all(db)
203 .await?)
204}
205
206/// Un-grade (homework, user), returning the removed row (`None` if there
207/// was none). Removing the grade unfreezes the student's submission, so the
208/// stamp [`grade`] left on it is cleared in the same
209/// transaction — scoped to *this* grade's id, so it can never wipe a stamp a
210/// concurrent re-grade has just written.
211///
212/// The grader's `marks_given_total` comes back with it, in that same
213/// transaction and only when a row was really deleted. [`grade`]
214/// credits on the branch that finds no row, and a deleted row *is* no row:
215/// left standing, ungrade-then-regrade credited a second time off one
216/// stored grade, and looped it minted a badge with no exam, no mark and no
217/// submission behind it — permanently, since an award is never revoked.
218/// Given back to the *removed row's own* grader, not the caller: a manager
219/// may un-grade what a teacher graded, and the credit is the teacher's.
220pub async fn remove(
221 db: &Database,
222 homework: &HomeworkId,
223 user: &UserId,
224) -> Result<Option<HomeworkResult>, AppError> {
225 // Owned captures (`Send` rule of `tx_with_retry` closures).
226 let homework = homework.clone();
227 let user = *user;
228 tx_with_retry(db, false, async move |tx| {
229 // The homework row's lock orders this against a concurrent grade
230 // (which locks the same row before inserting): either this delete
231 // wins and the re-grade lands after as a fresh grade, or the grade
232 // lands first and this removes *it*. A homework already cascaded
233 // away left no result rows behind — `None`, the 404 the web layer
234 // answers.
235 let alive = sqlx::query!(
236 r#"SELECT 1 AS "row: i32" FROM homework WHERE id = $1 FOR UPDATE"#,
237 homework.uuid()
238 )
239 .fetch_optional(&mut *tx)
240 .await?;
241 if alive.is_none() {
242 return Ok(None);
243 }
244 // The stamp clears *before* the delete: the submission's
245 // `graded_by_result` FK points at the grade row (`NO ACTION`), so the
246 // delete must not run while it stands. The subselect scopes the clear
247 // to *this* pair's grade id — it can never wipe a stamp a concurrent
248 // re-grade has just written (none can interleave: the homework row is
249 // locked above).
250 sqlx::query!(
251 r#"UPDATE homework_submission SET graded_by_result = NULL
252 WHERE homework = $1 AND app_user = $2 AND graded_by_result IN (
253 SELECT id FROM homework_result WHERE homework = $1 AND app_user = $2)"#,
254 homework.uuid(),
255 user.uuid()
256 )
257 .execute(&mut *tx)
258 .await?;
259 let gone = sqlx::query!(
260 r#"DELETE FROM homework_result WHERE homework = $1 AND app_user = $2
261 RETURNING id AS "id: HomeworkResultId",
262 homework AS "homework: HomeworkId",
263 app_user AS "user: UserId",
264 status AS "status: HomeworkStatus",
265 mark AS "mark: Mark",
266 graded_by AS "graded_by: UserId",
267 created_at AS "created_at: Timestamp""#,
268 homework.uuid(),
269 user.uuid()
270 )
271 .fetch_optional(&mut *tx)
272 .await?;
273 let Some(removed) = gone else {
274 return Ok(None);
275 };
276 sqlx::query!(
277 "UPDATE app_user SET marks_given_total = GREATEST(marks_given_total - 1, 0) WHERE id = $1",
278 removed.graded_by.uuid()
279 )
280 .execute(&mut *tx)
281 .await?;
282 Ok(Some(HomeworkResult {
283 id: removed.id,
284 homework: removed.homework,
285 user: removed.user,
286 status: removed.status,
287 mark: removed.mark,
288 graded_by: removed.graded_by,
289 created_at: removed.created_at,
290 }))
291 })
292 .await
293}
294
295#[cfg(test)]
296mod tests {
297 use super::*;
298
299 /// A real homework row (with the course and subject it needs): the grade now
300 /// carries a parent gate, so a minted id nothing wrote is a `404` here, the
301 /// same way it already is for a submission.
302 async fn a_homework(db: &Database) -> HomeworkId {
303 use crate::db::homework;
304 use crate::domain::homework::HomeworkTitle;
305 use crate::domain::subject::{SubjectDescription, SubjectName};
306
307 let (instance, course) = crate::db::course::a_test_instance(db).await;
308 let subject = crate::db::subject::create(
309 db,
310 &course,
311 SubjectName::try_new("topic").unwrap(),
312 SubjectDescription::try_new("").unwrap(),
313 )
314 .await
315 .unwrap();
316 homework::create(
317 db,
318 &instance,
319 subject.get_id(),
320 HomeworkTitle::try_new("essay").unwrap(),
321 None,
322 Timestamp::from_millis(1),
323 None,
324 &a_teacher(db).await,
325 )
326 .await
327 .unwrap()
328 .get_id()
329 .clone()
330 }
331
332 /// A real `app_user` teacher row: graders are foreign keys too.
333 async fn a_teacher(db: &Database) -> UserId {
334 let user = UserId::generate();
335 sqlx::query(
336 "INSERT INTO app_user (id, username, created_at, role) \
337 VALUES ($1, $2, 0, 'teacher')",
338 )
339 .bind(user.uuid())
340 .bind(format!("t-{}", &user.key()[30..]))
341 .execute(db)
342 .await
343 .unwrap();
344 user
345 }
346
347 /// A real `app_user` student row: graded users are foreign keys too.
348 async fn a_student(db: &Database) -> UserId {
349 let user = UserId::generate();
350 sqlx::query(
351 "INSERT INTO app_user (id, username, created_at, role) \
352 VALUES ($1, $2, 0, 'student')",
353 )
354 .bind(user.uuid())
355 .bind(format!("s-{}", &user.key()[30..]))
356 .execute(db)
357 .await
358 .unwrap();
359 user
360 }
361
362 #[tokio::test]
363 async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() {
364 let (db, _leases) = crate::database::init_test_db().await;
365 let homework = a_homework(&db).await;
366 let user = a_student(&db).await;
367 let teacher = a_teacher(&db).await;
368
369 let first = grade(
370 &db,
371 &homework,
372 &user,
373 HomeworkStatus::try_new("incomplete").unwrap(),
374 None,
375 &teacher,
376 )
377 .await
378 .unwrap();
379 // A regrade lands on the same row (composite id), overwriting the grade.
380 let second = grade(
381 &db,
382 &homework,
383 &user,
384 HomeworkStatus::try_new("done").unwrap(),
385 Some(Mark::try_new(80).unwrap()),
386 &teacher,
387 )
388 .await
389 .unwrap();
390 assert_eq!(first.get_id(), second.get_id());
391 assert_eq!(second.get_status().as_str(), "done");
392 assert_eq!(second.get_mark().unwrap().as_i64(), 80);
393 assert_eq!(list_for_homework(&db, &homework).await.unwrap().len(), 1);
394
395 assert!(read_for(&db, &homework, &user).await.unwrap().is_some());
396 assert!(remove(&db, &homework, &user).await.unwrap().is_some());
397 assert!(read_for(&db, &homework, &user).await.unwrap().is_none());
398 }
399
400 /// The grader is credited once per graded pair: a regrade lands on the same
401 /// row, so it is not a mark given twice. The student's counters are not
402 /// touched at all — a homework grade is not a homework submission.
403 #[tokio::test]
404 async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() {
405 let (db, _leases) = crate::database::init_test_db().await;
406 let homework = a_homework(&db).await;
407 let user = a_student(&db).await;
408 let teacher = a_teacher(&db).await;
409
410 for status in ["incomplete", "done"] {
411 grade(
412 &db,
413 &homework,
414 &user,
415 HomeworkStatus::try_new(status).unwrap(),
416 None,
417 &teacher,
418 )
419 .await
420 .unwrap();
421 }
422 assert_eq!(
423 marks_given(&teacher, &db).await,
424 1,
425 "one graded pair, one mark given"
426 );
427 }
428
429 /// Un-grading gives the credit back, so grade → ungrade → regrade nets to
430 /// one however often it is run. Crediting the grade without refunding the
431 /// delete was the cheapest counter farm in the codebase — two requests per
432 /// mark given, with no exam, no mark and no submission behind them.
433 #[tokio::test]
434 async fn ungrading_gives_the_grader_credit_back() {
435 let (db, _leases) = crate::database::init_test_db().await;
436 let homework = a_homework(&db).await;
437 let user = a_student(&db).await;
438 let teacher = a_teacher(&db).await;
439
440 for _ in 0..3 {
441 grade(
442 &db,
443 &homework,
444 &user,
445 HomeworkStatus::try_new("missing").unwrap(),
446 None,
447 &teacher,
448 )
449 .await
450 .unwrap();
451 assert_eq!(marks_given(&teacher, &db).await, 1);
452 assert!(
453 remove(&db, &homework, &user).await.unwrap().is_some(),
454 "the grade was there"
455 );
456 assert_eq!(marks_given(&teacher, &db).await, 0, "the loop kept one");
457 }
458
459 // Nothing to remove is nothing to give back — the floor holds.
460 assert!(remove(&db, &homework, &user).await.unwrap().is_none());
461 assert_eq!(marks_given(&teacher, &db).await, 0);
462 }
463 /// The grader's badge counter, re-read out of the store.
464 async fn marks_given(user: &UserId, db: &Database) -> i64 {
465 use sqlx::Row as _;
466
467 sqlx::query("SELECT marks_given_total FROM app_user WHERE id = $1")
468 .bind(user.uuid())
469 .fetch_one(db)
470 .await
471 .unwrap()
472 .try_get::<i64, _>(0)
473 .unwrap()
474 }
475}