diff --git a/src/db/homework.rs b/src/db/homework.rs new file mode 100644 index 0000000..c609e4b --- /dev/null +++ b/src/db/homework.rs @@ -0,0 +1,539 @@ +//! The `homework` table: row reads and listings, the count-and-create that +//! pins a homework to a live subject row, the reference-counting PATCH, and +//! the cascading delete. The PATCH's orphan guard and the audience gate live +//! in [`crate::service::homework`]. + +use surrealdb::types::RecordId; + +use crate::constant::SUBJECT_HOMEWORK_COUNT_FIELD; +use crate::database::Database; +use crate::db::cap; +use crate::db::field_update::FieldUpdate; +use crate::domain::course::CourseId; +use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle}; +use crate::domain::subject::SubjectId; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; + +/// The answer a link to a subject that is not there gets, on create and on +/// re-tag alike — both claims are conditional writes on the subject row, so a +/// subject a delete already removed matches nothing and the caller says exactly +/// what the web layer's pre-flight lookup would have. +fn subject_gone() -> AppError { + AppError::Validation(ValidationError::Invalid { + field: "subject_id", + reason: "subject does not exist", + }) +} + +#[expect( + clippy::too_many_arguments, + reason = "mirrors the sibling entities' create(field, field, ..) shape" +)] +pub async fn create( + db: &Database, + course: &CourseId, + subject: &SubjectId, + title: HomeworkTitle, + description: Option, + due_at: Timestamp, + assigned: Option>, + created_by: &UserId, +) -> Result { + // The subject's reference is taken in the very transaction that writes + // the row — the exam question's twin + // ([`crate::db::exam_question`]): the subject delete + // is refused while this counter is non-zero, so the create and the + // delete contend on the subject record rather than on a cross-table + // count neither of them sees the other move, and a crash can no longer + // strand a claim that would make the subject undeletable forever. A + // refused claim means the subject is already gone, which is the 400 the + // web layer's pre-flight check answers with. + let counted = subject.record(); + let homework = Homework { + id: HomeworkId::generate(), + course: course.clone(), + subject: subject.clone(), + title, + description, + due_at, + assigned, + created_by: created_by.clone(), + created_at: Timestamp::now(), + }; + let id = homework.id.record(); + match cap::claim_and_create( + &counted, + SUBJECT_HOMEWORK_COUNT_FIELD, + cap::UNLIMITED, + &id, + &homework, + db, + ) + .await? + { + cap::Claimed::Made(created) => Ok(created), + cap::Claimed::Full => Err(subject_gone()), + cap::Claimed::Duplicate => Err(AppError::Internal("failed to create homework".into())), + } +} + +pub async fn read(db: &Database, id: &HomeworkId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// The course's homework, newest first (ULID ids sort by creation). The web +/// layer retains only the rows a given student `student_sees`. +pub async fn list_for_course(db: &Database, course: &CourseId) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM homework WHERE course = $course ORDER BY id DESC") + .bind(("course", course.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Every homework in the system, newest first — the manager+ view of the +/// cross-course "my homework" list. +pub async fn list_all(db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM homework ORDER BY id DESC") + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Every homework of every course in `courses`, newest first (one query) — +/// the cross-course list over a caller's visible courses. The web layer +/// still trims each course's rows to what the caller may see (a student to +/// the ones they `student_sees`). +pub async fn list_for_courses( + db: &Database, + courses: &[CourseId], +) -> Result, AppError> { + if courses.is_empty() { + return Ok(Vec::new()); + } + let records: Vec = courses.iter().map(CourseId::record).collect(); + let mut result = db + .query("SELECT * FROM homework WHERE course IN $courses ORDER BY id DESC") + .bind(("courses", records)) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// The homework of `course` that `user` is meant to see — whole-course ones +/// plus any subset that names them — newest first. Backs a student's (or an +/// observer's) per-course homework report; mirrors +/// [`Homework::student_sees`](crate::domain::homework::Homework::student_sees) +/// in SurQL so the filter runs in the database. +pub async fn list_for_user_in_course( + db: &Database, + course: &CourseId, + user: &UserId, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM homework + WHERE course = $course + AND (assigned = NONE OR assigned = [] OR $usr IN assigned) + ORDER BY id DESC", + ) + .bind(("course", course.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework. +/// Request-scoped: every parameter is `Option`, `None` meaning the PATCH +/// did not carry that field, so it is not written at all. Handing the +/// snapshot's value back instead would revert a concurrent edit of that +/// field — scoping the `SET` alone does not prevent that, the *values* must +/// come from the request. `course`, `created_by`, and `created_at` are +/// `READONLY` and never appear in the write. +/// +/// `description` and `assigned` are nullable columns, so they take a +/// `NONE` (clear the description / widen back to the whole course). The web +/// layer has already re-checked a new `due_at` against now, a new `subject` +/// against the course, and refused a narrowing that would orphan work. +pub async fn update( + db: &Database, + homework: Homework, + subject: Option, + title: Option, + description: Option>, + due_at: Option, + assigned: Option>>, +) -> Result { + let assigned = assigned + .map(|subset| subset.map(|users| users.iter().map(UserId::record).collect::>())); + // A re-tag moves a reference: the new subject's claim and the old one's + // release ride the same transaction as the link write, so no crash can + // leave a count without its link (the subject would be undeletable + // forever) or a link without its count. `subject` is required, so the + // snapshot's value is always the CAS expectation — two PATCHes moving + // the same homework off the same subject would otherwise both claim + // their target, and the loser is refused with a 409 instead. The + // `.refcount` call is unconditional: the CAS is armed by the request + // *carrying* `subject_id`, not by a counter moving, so a PATCH that + // re-states the tag its snapshot showed — shifting no counter at all — + // is still refused when a rival moved the tag in between. A PATCH that + // carried no `subject_id` arms nothing and writes what it always did. + let (claim, release) = subject + .as_ref() + .filter(|next| **next != homework.subject) + .map(|next| (next.record(), homework.subject.record())) + .unzip(); + FieldUpdate::new(homework.id.record()) + .set("subject", subject.map(|subject| subject.record())) + .set("title", title) + .set("description", description) + .set("due_at", due_at) + .set("assigned", assigned) + .refcount( + SUBJECT_HOMEWORK_COUNT_FIELD, + "subject", + Some(homework.subject.record()), + claim, + release, + subject_gone(), + ) + .run::(db) + .await +} + +/// Delete the homework and cascade its submissions, their files, and its +/// results — one transaction, so a crash can't orphan a submission under a +/// vanished homework. The submission file *blobs* are the web layer's to +/// unlink: it collects their names via +/// [`crate::db::homework_file::file_keys_for_homework`] +/// before calling this, and removes them after the rows are gone. +pub async fn delete(db: &Database, homework: Homework) -> Result { + let mut result = db + .query( + format!( + "BEGIN TRANSACTION; + DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw); + DELETE homework_submission WHERE homework = $hw; + DELETE homework_result WHERE homework = $hw; + LET $gone = (DELETE $hw RETURN BEFORE); + FOR $sub IN ($gone.subject ?? []) {{ + UPDATE $sub SET {SUBJECT_HOMEWORK_COUNT_FIELD} = + math::max([({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) - 1, 0]) + }}; + RETURN $gone; + COMMIT TRANSACTION;" + ), + ) + .bind(("hw", homework.id.record())) + .await? + .check()?; + // The subject's reference is given back in this same transaction, off + // what the delete actually removed. Read through the trailing `RETURN`, + // not a hand-counted slot — see [`crate::db::exam::delete`]. + let slot = result.num_statements().saturating_sub(2); + let deleted: Option = result.take::>(slot)?.into_iter().next(); + deleted.ok_or(AppError::NotFound) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; + + async fn a_subject(name: &str, db: &Database) -> Subject { + Subject::create( + &crate::db::course::a_test_course(db).await, + SubjectName::try_new(name).unwrap(), + SubjectDescription::try_new("").unwrap(), + db, + ) + .await + .unwrap() + } + + async fn homework_on(subject: &SubjectId, db: &Database) -> Homework { + create( + db, + &CourseId::from_key("course"), + subject, + HomeworkTitle::try_new("essay").unwrap(), + None, + Timestamp::from_millis(1), + None, + &UserId::from_key("teacher"), + ) + .await + .unwrap() + } + + /// The stored `homework_count` on one subject, absent counting as zero. + async fn count_on(subject: &SubjectId, db: &Database) -> i64 { + let mut result = db + .query(format!( + "SELECT VALUE ({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) FROM $sub" + )) + .bind(("sub", subject.record())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .first() + .copied() + .unwrap_or(0) + } + + /// How many rows `sql` selects ids for. + async fn rows(sql: &str, db: &Database) -> usize { + let mut result = db.query(sql).await.unwrap().check().unwrap(); + result.take::>(0).unwrap().len() + } + + /// The invariant on the create path: the claim and the row it accounts for + /// commit together or not at all. A refused create leaves *neither* — no + /// homework row, and no count stranded on a subject (the subject's delete + /// guard reads that count, so a stray one makes it undeletable forever). + #[tokio::test] + async fn a_refused_create_writes_neither_row_nor_count() { + let db = crate::database::init_mem().await.unwrap(); + let subject = a_subject("algebra", &db).await; + let id = subject.get_id().clone(); + subject.delete(&db).await.unwrap(); + + let error = create( + &db, + &CourseId::from_key("course"), + &id, + HomeworkTitle::try_new("essay").unwrap(), + None, + Timestamp::from_millis(1), + None, + &UserId::from_key("teacher"), + ) + .await + .expect_err("a subject that is gone must not be taggable"); + assert!(error.to_string().contains("subject does not exist")); + assert_eq!( + rows("SELECT VALUE id FROM homework", &db).await, + 0, + "a refused create may write no row" + ); + assert_eq!( + rows("SELECT VALUE id FROM subject", &db).await, + 0, + "…and least of all a count on a subject it just brought back" + ); + } + + /// The invariant on the PATCH path: a re-tag carries the new subject's + /// claim and the old one's release with the link itself. + #[tokio::test] + async fn a_subject_move_moves_the_count() { + let db = crate::database::init_mem().await.unwrap(); + let from = a_subject("algebra", &db).await; + let to = a_subject("geometry", &db).await; + let homework = homework_on(from.get_id(), &db).await; + assert_eq!(count_on(from.get_id(), &db).await, 1); + + let moved = update( + &db, + homework, + Some(to.get_id().clone()), + None, + None, + None, + None, + ) + .await + .unwrap(); + assert_eq!(moved.get_subject(), to.get_id()); + assert_eq!( + count_on(from.get_id(), &db).await, + 0, + "the old subject is free" + ); + assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); + assert!(from.delete(&db).await.is_ok(), "no reference left"); + assert!( + to.delete(&db).await.is_err(), + "the reference moved here refuses the delete" + ); + } + + /// The claim throws inside the same transaction as the link write, so a + /// move onto a subject that is gone rolls the release back with it: the row + /// keeps its tag and both counters read as if nothing ran. + #[tokio::test] + async fn a_move_to_a_dead_subject_leaves_everything_untouched() { + let db = crate::database::init_mem().await.unwrap(); + let from = a_subject("algebra", &db).await; + let dead = a_subject("geometry", &db).await; + let gone = dead.get_id().clone(); + dead.delete(&db).await.unwrap(); + let homework = homework_on(from.get_id(), &db).await; + + let error = update( + &db, + homework.clone(), + Some(gone.clone()), + None, + None, + None, + None, + ) + .await + .expect_err("a subject that is gone must not be taggable"); + assert!(error.to_string().contains("subject does not exist")); + let stored = read(&db, homework.get_id()).await.unwrap().unwrap(); + assert_eq!(stored.get_subject(), from.get_id(), "the tag never moved"); + assert_eq!( + count_on(from.get_id(), &db).await, + 1, + "the release rolled back with the claim" + ); + assert_eq!( + rows("SELECT VALUE id FROM subject", &db).await, + 1, + "the dead subject was not brought back by a count" + ); + assert_eq!(count_on(&gone, &db).await, 0); + } + + /// The double-claim guard. Both movers compute their claim and release from + /// the row as *they* read it, so two PATCHes re-tagging the same homework + /// off the same subject both release it and both claim their target — two + /// counts for one link, and the loser's target is undeletable forever. The + /// second call here runs on the struct read before the first one landed, + /// which is that race with the interleaving pinned: it must be refused + /// outright, and the counts must read as if it never ran. + #[tokio::test] + async fn a_stale_mover_is_refused_and_claims_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let from = a_subject("algebra", &db).await; + let to = a_subject("geometry", &db).await; + let other = a_subject("calculus", &db).await; + let homework = homework_on(from.get_id(), &db).await; + let stale = homework.clone(); + update( + &db, + homework, + Some(to.get_id().clone()), + None, + None, + None, + None, + ) + .await + .unwrap(); + + let error = update( + &db, + stale.clone(), + Some(other.get_id().clone()), + None, + None, + None, + None, + ) + .await + .expect_err("a mover that read a tag it no longer holds must be refused"); + assert!( + matches!(error, AppError::Conflict(_)), + "a lost CAS is a conflict, not a 404 or a 500: {error:?}" + ); + let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); + assert_eq!(stored.get_subject(), to.get_id(), "the winner's tag"); + assert_eq!( + count_on(from.get_id(), &db).await, + 0, + "released once, not twice" + ); + assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once"); + assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed"); + } + + /// The same race with the counters taken out of it. A PATCH that re-states + /// the subject its snapshot showed shifts *nothing* — no claim and no + /// release — so if the guard were armed off the counter move it would not be + /// armed here at all, and the write would land: the winner's tag silently + /// dragged back, its claim stranded on a subject nothing points at + /// (undeletable forever) and the reverted-to subject tagged at a count of + /// zero (deletable while tagged). The guard is armed by the request + /// *carrying* the column instead, which is why this is refused. + #[tokio::test] + async fn a_stale_re_stater_is_refused_and_reverts_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let from = a_subject("algebra", &db).await; + let to = a_subject("geometry", &db).await; + let homework = homework_on(from.get_id(), &db).await; + let stale = homework.clone(); + update( + &db, + homework, + Some(to.get_id().clone()), + None, + None, + None, + None, + ) + .await + .unwrap(); + + let error = update( + &db, + stale.clone(), + Some(from.get_id().clone()), + None, + None, + None, + None, + ) + .await + .expect_err("re-stating a tag someone else moved must be refused"); + assert!( + matches!(error, AppError::Conflict(_)), + "a lost CAS is a conflict, not a silent 200: {error:?}" + ); + let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); + assert_eq!(stored.get_subject(), to.get_id(), "the winner's tag"); + assert_eq!( + count_on(from.get_id(), &db).await, + 0, + "the reverted-to subject must not end up tagged at zero" + ); + assert_eq!( + count_on(to.get_id(), &db).await, + 1, + "…nor the winner's subject counted with nothing pointing at it" + ); + + // A *genuine* no-op re-state — nobody moved underneath it — still lands, + // and still moves no counter: the CAS passes trivially. + let fresh = read(&db, stale.get_id()).await.unwrap().unwrap(); + let same = update( + &db, + fresh, + Some(to.get_id().clone()), + None, + None, + None, + None, + ) + .await + .expect("re-stating the tag actually held is not a race"); + assert_eq!(same.get_subject(), to.get_id()); + assert_eq!( + count_on(from.get_id(), &db).await, + 0, + "still no counter move" + ); + assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once, still"); + } +} diff --git a/src/db/homework_file.rs b/src/db/homework_file.rs new file mode 100644 index 0000000..9b51eaf --- /dev/null +++ b/src/db/homework_file.rs @@ -0,0 +1,419 @@ +//! The `homework_file` table: the attachment rows behind a submission's +//! files — the seat-claiming insert, the scoped reads, the GC key +//! collectors, and the gate-guarded delete. The rows' assembly (`new`) and +//! their validated fields live in [`crate::domain::homework_file`]; the +//! upload workflow around them in [`crate::service::homework_file`]. + +use surrealdb::types::SurrealValue; + +use crate::constant::{ + MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD, SUBMISSION_OPEN_GUARD, +}; +use crate::database::{Database, transaction_with_retry}; +use crate::db::cap; +use crate::domain::course::CourseId; +use crate::domain::homework::HomeworkId; +use crate::domain::homework_file::HomeworkFile; +use crate::domain::timestamp::Timestamp; +use crate::error::AppError; + +/// What [`delete`]'s transaction reports: whether the submission +/// was still open (`open` = 1, the gate bit) and the row it then removed. Two +/// answers in one object because an empty `gone` alone cannot say whether the +/// delete was refused or the file had simply vanished. +#[derive(Debug, SurrealValue)] +struct DeleteOutcome { + open: i64, + gone: Vec, +} + +/// Persist the row assembled by +/// [`HomeworkFile::new`](crate::domain::homework_file::HomeworkFile::new), +/// refusing once its submission already holds +/// [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`) +/// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own +/// wording). Both are decided by one [`cap::claim_when_and_create`] on the +/// submission row — the seat and the file row commit together, so a crash +/// between them can no longer leave a slot claimed by a file that does not +/// exist, and a losing upload never has to be un-counted. Which of the two +/// conditions refused it is read back afterwards, off the losing path only, +/// and only to pick the message: `Claimed::Full` says "full *or* graded *or* +/// the submission is gone". +pub async fn insert(db: &Database, file: HomeworkFile) -> Result, AppError> { + // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber + match cap::claim_when_and_create( + &file.submission.record(), + SUBMISSION_FILE_COUNT_FIELD, + MAX_HOMEWORK_FILES_PER_SUBMISSION as i64, + SUBMISSION_OPEN_GUARD, + &file.id.record(), + &file, + db, + ) + .await? + { + cap::Claimed::Made(created) => Ok(Some(created)), + cap::Claimed::Full => { + if super::homework_submission::is_graded(db, &file.submission).await? { + return Ok(None); + } + Err(AppError::Conflict( + "the submission already holds the maximum of 10 files — delete one first", + )) + } + // The id is a fresh ULID minted by `new`, so a row already holding it + // is a collision, not a re-upload. + cap::Claimed::Duplicate => Err(AppError::Internal("homework file id collided".into())), + } +} + +/// Read a file's row only if it belongs to `submission` — callers have +/// already checked the submission belongs to the requesting user. +pub async fn read_for( + db: &Database, + id: &crate::domain::homework_file::HomeworkFileId, + submission: &crate::domain::homework_submission::HomeworkSubmissionId, +) -> Result, AppError> { + let file: Option = db.select(id.record()).await?; + Ok(file.filter(|file| &file.submission == submission)) +} + +/// Read a file by id only if it hangs off a submission to `homework` — the +/// grader's download scoping. The teacher download path carries the homework +/// id but not the owning student (unlike `read_for`, which needs the +/// submission), so this both finds the file and confirms it belongs under +/// `homework`: a teacher can't pass a homework they manage to read a file +/// from a different (perhaps unmanaged) one. +pub async fn read_in_homework( + db: &Database, + id: &crate::domain::homework_file::HomeworkFileId, + homework: &HomeworkId, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM homework_file WHERE id = $id AND submission IN \ + (SELECT VALUE id FROM homework_submission WHERE homework = $hw)", + ) + .bind(("id", id.record())) + .bind(("hw", homework.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) +} + +/// All of `submission`'s files, newest first. +pub async fn list_for_submission( + db: &Database, + submission: &crate::domain::homework_submission::HomeworkSubmissionId, +) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM homework_file WHERE submission = $sub ORDER BY id DESC") + .bind(("sub", submission.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// How many files `submission` holds — the cap check reads this under the +/// lock. Counting via the rows (not a `count()` query) keeps it identical +/// to `NoteFile`'s proven cap check; at a ceiling of 10 the cost is nil. +pub async fn count_for_submission( + db: &Database, + submission: &crate::domain::homework_submission::HomeworkSubmissionId, +) -> Result { + Ok(list_for_submission(db, submission).await?.len()) +} + +/// The blob names behind every file of every submission to `homework` — +/// collected *before* the homework-delete cascade wipes the rows, so the +/// web layer can unlink them once the rows are gone. +pub async fn file_keys_for_homework( + db: &Database, + homework: &HomeworkId, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT VALUE file FROM homework_file \ + WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw)", + ) + .bind(("hw", homework.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// The blob names behind every homework file of `course` — collected +/// *before* the course-delete cascade wipes the rows. +pub async fn file_keys_for_course( + db: &Database, + course: &CourseId, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT VALUE file FROM homework_file WHERE submission IN ( \ + SELECT VALUE id FROM homework_submission \ + WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course) \ + )", + ) + .bind(("course", course.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Delete the row and give its slot back in the same transaction. The +/// submission survives, so its counter has to be corrected; the cascades +/// that delete the submission itself take the counter with it. +/// +/// The gate is the first statement: a conditional write on the *submission* +/// row — the "last touched" re-stamp a file delete owes the late flag +/// anyway — carrying [`SUBMISSION_OPEN_GUARD`]. Nothing else in the +/// transaction runs unless it bit, so a grade landing concurrently either +/// stamps first (this delete is refused, `Ok(None)`) or stamps after (the +/// file was already gone when it graded). `Err(NotFound)` still means the +/// file row itself had vanished. +/// +/// Sound to re-send while the store answers "conflict, retry", and it has +/// to be: the gate writes the *submission* row, the very record an upload's +/// [`insert`] claims its seat on, and both handlers hold only +/// `HOMEWORK_LOCK.read()` — so a concurrent add and delete of two files of +/// one submission contend by design, and a lost round used to come back as +/// a 500 on a request that had written nothing. Only `UPDATE` and `DELETE` +/// are in the batch, and neither can legitimately answer "already exists", +/// which is what makes the whole of it re-sendable. +pub async fn delete(db: &Database, file: HomeworkFile) -> Result, AppError> { + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $open = (UPDATE $sub SET updated_at = $now \ + WHERE {SUBMISSION_OPEN_GUARD} RETURN VALUE id); + LET $gone = IF array::len($open) > 0 {{ (DELETE $id RETURN BEFORE) }} ELSE {{ [] }}; + UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); + RETURN {{ open: array::len($open), gone: $gone }}; + COMMIT TRANSACTION;" + ), + &[ + ("id".into(), file.id.record().into_value()), + ("sub".into(), file.submission.record().into_value()), + ("now".into(), Timestamp::now().into_value()), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // BEGIN is slot 0, the two LETs slots 1-2 and the counter fix slot 3; + // the RETURN is slot 4. + let outcome: Option = result.take::>(4)?.into_iter().next(); + let outcome = + outcome.ok_or_else(|| AppError::Internal("failed to delete homework file".into()))?; + if outcome.open == 0 { + return Ok(None); + } + outcome + .gone + .into_iter() + .next() + .map(Some) + .ok_or(AppError::NotFound) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::homework_submission::HomeworkSubmissionId; + use crate::domain::note_file::{FileContentType, FileName}; + use crate::domain::user::UserId; + + /// A real homework row (with the subject it references): `upsert` reads the + /// deadline off the entity now, so a bare id no longer does. + async fn a_homework(db: &Database) -> crate::domain::homework::Homework { + use crate::db::homework as hw; + use crate::domain::homework::HomeworkTitle; + use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; + + let course = crate::db::course::a_test_course(db).await; + let subject = Subject::create( + &course, + SubjectName::try_new("topic").unwrap(), + SubjectDescription::try_new("").unwrap(), + db, + ) + .await + .unwrap(); + hw::create( + db, + &course, + subject.get_id(), + HomeworkTitle::try_new("essay").unwrap(), + None, + crate::domain::timestamp::Timestamp::from_millis(1), + None, + &UserId::from_key("teacher"), + ) + .await + .unwrap() + } + + fn a_file(submission: &HomeworkSubmissionId) -> HomeworkFile { + HomeworkFile::new( + submission, + FileName::try_new("answer.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ) + } + + /// The counter as *stored* — the only witness that the seat and the row + /// moved together, since every other read counts the rows themselves. + async fn stored_count(submission: &HomeworkSubmissionId, db: &Database) -> i64 { + db.query("SELECT VALUE file_count FROM $sub") + .bind(("sub", submission.record())) + .await + .unwrap() + .take::>(0) + .unwrap() + .into_iter() + .next() + .unwrap_or(0) + } + #[tokio::test] + async fn rows_scope_to_their_submission_gc_and_cap() { + let db = crate::database::init_mem().await.unwrap(); + let hw = a_homework(&db).await; + let homework = hw.get_id().clone(); + let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); + // A real submission row, so the GC join through it resolves. + let submission = crate::db::homework_submission::upsert(&db, &hw, &user, None) + .await + .unwrap() + .unwrap(); + let sub_a = submission.get_id().clone(); + let sub_b = HomeworkSubmissionId::composite( + &homework, + &UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB"), + ); + + let stored = insert(&db, a_file(&sub_a)).await.unwrap().unwrap(); + // Readable under its own submission, invisible under another. + assert!( + read_for(&db, stored.get_id(), &sub_a) + .await + .unwrap() + .is_some() + ); + assert!( + read_for(&db, stored.get_id(), &sub_b) + .await + .unwrap() + .is_none() + ); + assert_eq!(count_for_submission(&db, &sub_a).await.unwrap(), 1); + assert_eq!( + stored_count(&sub_a, &db).await, + 1, + "the seat rode with the row" + ); + + // The grader's download scoping: found under its own homework, invisible + // under another — so a teacher can't read it by naming a homework they + // happen to manage. + assert!( + read_in_homework(&db, stored.get_id(), &homework) + .await + .unwrap() + .is_some() + ); + assert!( + read_in_homework( + &db, + stored.get_id(), + &HomeworkId::from_key("01TESTHWBBBBBBBBBBBBBBBBBB"), + ) + .await + .unwrap() + .is_none() + ); + + // The blob name is collectable for GC before a cascade wipes the rows. + let keys = file_keys_for_homework(&db, &homework).await.unwrap(); + assert_eq!(keys, vec![stored.get_file().to_string()]); + + // Fill to the cap, then the 11th is refused. + for _ in 1..MAX_HOMEWORK_FILES_PER_SUBMISSION { + insert(&db, a_file(&sub_a)).await.unwrap().unwrap(); + } + assert!(matches!( + insert(&db, a_file(&sub_a)).await, + Err(AppError::Conflict(_)) + )); + // The refusal wrote nothing at all: neither a row nor a seat. + assert_eq!( + count_for_submission(&db, &sub_a).await.unwrap() as i64, + stored_count(&sub_a, &db).await, + ); + assert_eq!( + stored_count(&sub_a, &db).await, + MAX_HOMEWORK_FILES_PER_SUBMISSION as i64 + ); + } + + /// A graded submission takes no more files and gives none up — decided by + /// the same conditional write that claims the file slot, so no + /// `homework_result` read stands between the check and the write. + /// + /// Bite check: drop [`SUBMISSION_OPEN_GUARD`] from [`insert`]'s + /// [`cap::claim_when_and_create`] and the add below lands; drop it from + /// [`delete`]'s gate and the delete below succeeds. + #[tokio::test] + async fn a_grade_freezes_the_files_too() { + use crate::db::homework_result; + use crate::domain::homework_result::HomeworkStatus; + + let db = crate::database::init_mem().await.unwrap(); + let hw = a_homework(&db).await; + let homework = hw.get_id().clone(); + let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); + let submission = crate::db::homework_submission::upsert(&db, &hw, &user, None) + .await + .unwrap() + .unwrap(); + let sub = submission.get_id().clone(); + let stored = insert(&db, a_file(&sub)).await.unwrap().unwrap(); + + homework_result::grade( + &db, + &homework, + &user, + HomeworkStatus::try_new("done").unwrap(), + None, + &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), + ) + .await + .unwrap(); + + // Neither adding nor removing an attachment: `None` is the freeze, and + // the cap's own `Err(Conflict)` stays distinct from it. + assert!(insert(&db, a_file(&sub)).await.unwrap().is_none()); + assert!(delete(&db, stored.clone()).await.unwrap().is_none()); + assert_eq!( + count_for_submission(&db, &sub).await.unwrap(), + 1, + "the graded submission keeps exactly the files it was graded on" + ); + // Refused by the *guard*, not the cap (nine seats free) — and still no + // seat moved, so the counter matches the rows. + assert_eq!(stored_count(&sub, &db).await, 1); + // The refused add took no slot either, so un-grading gives back a + // submission with room, not one that silently lost nine. + homework_result::remove(&db, &homework, &user) + .await + .unwrap(); + for _ in 1..MAX_HOMEWORK_FILES_PER_SUBMISSION { + insert(&db, a_file(&sub)).await.unwrap().unwrap(); + } + assert!(delete(&db, stored).await.unwrap().is_some()); + } +} diff --git a/src/db/homework_result.rs b/src/db/homework_result.rs new file mode 100644 index 0000000..39e4b2b --- /dev/null +++ b/src/db/homework_result.rs @@ -0,0 +1,433 @@ +//! The `homework_result` table: one grade per (homework, user) — the +//! freeze-stamping UPSERT, the reads the roster and report join on, and the +//! un-grade that gives the grader's counter back. Grading's policy gates +//! (who may grade whom) live in [`crate::service::homework_result`]; the +//! validated status and mark types in +//! [`crate::domain::homework_result`]. + +use crate::constant::{MARKS_GIVEN_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD}; +use crate::database::{Database, transaction_with_retry}; +use crate::domain::course::CourseId; +use crate::domain::exam_result::Mark; +use crate::domain::homework::HomeworkId; +use crate::domain::homework_result::{HomeworkResult, HomeworkResultId, HomeworkStatus}; +use crate::domain::homework_submission::HomeworkSubmissionId; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; +use surrealdb::types::SurrealValue; + +/// Record (or overwrite) the grade for (homework, user). One row per pair, +/// keyed by the deterministic composite id, so this is a single atomic +/// UPSERT — concurrent grades for the same pair converge on one row instead +/// of racing a unique index into a 500. Grading before the due date, or +/// before any submission exists, is allowed (the caller's policy call). +/// +/// In the same transaction the grade *stamps* the student's submission +/// ([`crate::constant::SUBMISSION_GRADED_FIELD`]), which is what freezes it: +/// every student-side write to that row then fails its own +/// `graded_by_result = NONE` condition, with no cross-table read for a +/// concurrent write to slip past. A submission that does not exist yet is +/// left alone — grading absent work must not conjure a hand-in (the report reads +/// `submitted`/`missing`/`late` straight off that row). +/// +/// That one case is where this function stops defending itself: a student's +/// *first* hand-in committing between this grade and nothing-to-stamp would +/// land unstamped, leaving a grade beside an editable submission. Nothing +/// here forbids it — what forbids it is the caller. Grading holds +/// `HOMEWORK_LOCK` (see [`crate::service::homework`]) for writing across this +/// whole transaction while every student-side write holds it for reading across +/// its own, and the two leases are mutually exclusive in the one process +/// this backend runs as, so the interleaving never gets a window. +// +// corner-cut: that makes the freeze depend on lock discipline at the call +// sites, not on this row. Moving a student write's lease to *after* its +// database write — or sharding HOMEWORK_LOCK per homework — reopens the +// window with nothing to catch it. Closing it in the db layer needs a +// record both sides own (a per-(homework, user) row the grade can always +// stamp); a tombstone submission is not it, since every read path would +// have to learn to ignore it and one missed filter fabricates a hand-in. +pub async fn grade( + db: &Database, + homework: &HomeworkId, + user: &UserId, + status: HomeworkStatus, + mark: Option, + graded_by: &UserId, +) -> Result { + let id = HomeworkResultId::composite(homework, user); + let submission = HomeworkSubmissionId::composite(homework, user); + let result = HomeworkResult { + id: id.clone(), + homework: homework.clone(), + user: user.clone(), + status, + mark, + graded_by: graded_by.clone(), + created_at: Timestamp::now(), + }; + // Whether the pair was already graded is read one statement ahead of + // the write, inside the same transaction — it is what keeps a regrade + // from crediting the grader a second time. No mark counter here: a + // homework mark is optional and most grades are status-only, so + // `high_mark` is an exam-only family. + // + // The first three statements are the parent gate, the twin of + // [`crate::db::homework_submission::upsert`]'s + // and written the same way on purpose: the id is deterministic, so a + // grade landing inside a homework (or course) delete's window does not + // fail — it *re-creates* a result row under a homework that is gone, + // readable ever after at `GET /homework/{id}/result` (no existence check + // there) with a `marks_given_total` no ungrade can reach, because every + // route to the grade goes through the homework. Reading the homework + // first — which the web layer does, under the lease — cannot close that: + // the store conflict-checks write sets, not read sets. So the gate + // *moves* a value on the homework row (`due_at` up by one and straight + // back to the captured value, leaving the row byte-identical) and the + // cascade's delete of that same row is what refuses it. `homework` owns + // no counter column and is SCHEMAFULL, so `due_at` is the one `int` it + // already has; do not invent a second spelling. + // + // Not [`crate::db::cap::touch_and_create`], which is the same shape + // for a bare `CREATE`: a grade is an UPSERT (a regrade must overwrite), + // and the freeze stamp and the grader's counter have to ride the same + // transaction, which that helper has no room for. + // + // Sound to re-send, which is what the gate needed first — a `THROW` + // inside a plain `db.query` would have turned every lost round into a + // 500. `SELECT`, `UPDATE` and the `IF`/`THROW` can never answer "already + // exists", and the `UPSERT`'s id is bijective with the (homework, user) + // pair the table keys, on a table whose only index is non-unique + // (`homework_result_homework`), so its index entry can only ever point + // at the row the id already names: it resolves onto that row instead of + // colliding with it. A lost round wrote nothing. + let (mut saved, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $was_due = (SELECT VALUE due_at FROM ONLY $hw); + LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id); + IF array::len($alive) = 0 {{ THROW 'no_homework' }}; + UPDATE $hw SET due_at = $was_due; + LET $before = (SELECT VALUE id FROM ONLY $id); + LET $after = (UPSERT $id CONTENT $row RETURN AFTER); + UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = $id \ + WHERE {SUBMISSION_OPEN_GUARD}; + IF $before = NONE {{ + UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = + ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1 + }}; + RETURN $after; + COMMIT TRANSACTION;" + ), + &[ + ("hw".into(), homework.record().into_value()), + ("id".into(), id.record().into_value()), + ("sub".into(), submission.record().into_value()), + ("grader".into(), graded_by.record().into_value()), + ("row".into(), result.into_value()), + ], + &["no_homework"], + ) + .await?; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the THROW's own slot names the reason. + if errors + .values() + .any(|error| error.to_string().contains("no_homework")) + { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is always the last statement before `COMMIT`, + // so its slot follows the statement count instead of a hand-kept + // number — which the gate above would otherwise have shifted, silently + // handing back something else. + let slot = saved.num_statements().saturating_sub(2); + saved + .take::>(slot)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to record homework result".into())) +} + +/// `user`'s grade for `homework`, if graded. +pub async fn read_for( + db: &Database, + homework: &HomeworkId, + user: &UserId, +) -> Result, AppError> { + Ok(db + .select(HomeworkResultId::composite(homework, user).record()) + .await?) +} + +/// Every grade for `homework` — the roster joins these onto the submissions. +pub async fn list_for_homework( + db: &Database, + homework: &HomeworkId, +) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM homework_result WHERE homework = $hw ORDER BY id DESC") + .bind(("hw", homework.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// `user`'s homework grades across one course — the raw rows behind the +/// per-course block of a homework report. Mirrors +/// `ExamResult::list_for_user_in_course`. +pub async fn list_for_user_in_course( + db: &Database, + course: &CourseId, + user: &UserId, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM homework_result WHERE user = $usr + AND homework IN (SELECT VALUE id FROM homework WHERE course = $course) + ORDER BY id DESC", + ) + .bind(("usr", user.record())) + .bind(("course", course.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Un-grade (homework, user), returning the removed row (`None` if there +/// was none). Removing the grade unfreezes the student's submission, so the +/// stamp [`grade`] left on it is cleared in the same +/// transaction — scoped to *this* grade's id, so it can never wipe a stamp a +/// concurrent re-grade has just written. +/// +/// The grader's `marks_given_total` comes back with it, in that same +/// transaction and only when a row was really deleted. [`grade`] +/// credits on the branch that finds no row, and a deleted row *is* no row: +/// left standing, ungrade-then-regrade credited a second time off one +/// stored grade, and looped it minted a badge with no exam, no mark and no +/// submission behind it — permanently, since an award is never revoked. +/// Given back to the *removed row's own* grader, not the caller: a manager +/// may un-grade what a teacher graded, and the credit is the teacher's. +/// +/// Sound to re-send while the store answers "conflict, retry" — this is the +/// upgrade `grade` still wants, taken here because the counter above is what +/// makes it necessary: the grader's row is written by exam grading too, so +/// the delete now contends with another domain, and only `DELETE`/`UPDATE` +/// are in the batch, none of which can legitimately answer "already exists". +pub async fn remove( + db: &Database, + homework: &HomeworkId, + user: &UserId, +) -> Result, AppError> { + let id = HomeworkResultId::composite(homework, user); + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $gone = (DELETE $id RETURN BEFORE); + UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = NONE \ + WHERE {SUBMISSION_GRADED_FIELD} = $id; + IF array::len($gone) > 0 {{ + LET $grader = $gone[0].graded_by; + UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = + math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0]) + }}; + RETURN $gone; + COMMIT TRANSACTION;" + ), + &[ + ("id".into(), id.record().into_value()), + ( + "sub".into(), + HomeworkSubmissionId::composite(homework, user) + .record() + .into_value(), + ), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is always the last statement before `COMMIT`, so + // its slot follows the statement count — the hand-kept "slot 1" this + // replaces was one added statement away from handing back the unstamp. + let slot = result.num_statements().saturating_sub(2); + Ok(result.take::>(slot)?.into_iter().next()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A real homework row (with the course and subject it needs): the grade now + /// carries a parent gate, so a minted id nothing wrote is a `404` here, the + /// same way it already is for a submission. + async fn a_homework(db: &Database) -> HomeworkId { + use crate::db::homework; + use crate::domain::homework::HomeworkTitle; + use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; + + let course = crate::db::course::a_test_course(db).await; + let subject = Subject::create( + &course, + SubjectName::try_new("topic").unwrap(), + SubjectDescription::try_new("").unwrap(), + db, + ) + .await + .unwrap(); + homework::create( + db, + &course, + subject.get_id(), + HomeworkTitle::try_new("essay").unwrap(), + None, + Timestamp::from_millis(1), + None, + &UserId::from_key("teacher"), + ) + .await + .unwrap() + .get_id() + .clone() + } + + #[tokio::test] + async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() { + let db = crate::database::init_mem().await.unwrap(); + let homework = a_homework(&db).await; + let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); + let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + + let first = grade( + &db, + &homework, + &user, + HomeworkStatus::try_new("incomplete").unwrap(), + None, + &teacher, + ) + .await + .unwrap(); + // A regrade lands on the same row (composite id), overwriting the grade. + let second = grade( + &db, + &homework, + &user, + HomeworkStatus::try_new("done").unwrap(), + Some(Mark::try_new(80).unwrap()), + &teacher, + ) + .await + .unwrap(); + assert_eq!(first.get_id(), second.get_id()); + assert_eq!(second.get_status().as_str(), "done"); + assert_eq!(second.get_mark().unwrap().as_i64(), 80); + assert_eq!(list_for_homework(&db, &homework).await.unwrap().len(), 1); + + assert!(read_for(&db, &homework, &user).await.unwrap().is_some()); + assert!(remove(&db, &homework, &user).await.unwrap().is_some()); + assert!(read_for(&db, &homework, &user).await.unwrap().is_none()); + } + + /// The grader is credited once per graded pair: a regrade lands on the same + /// row, so it is not a mark given twice. The student's counters are not + /// touched at all — a homework grade is not a homework submission. + #[tokio::test] + async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() { + let db = crate::database::init_mem().await.unwrap(); + let homework = a_homework(&db).await; + let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); + let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + // `UPDATE` writes nothing to a user row that does not exist. + db.query("CREATE $usr SET username = 't', password_hash = 'x'") + .bind(("usr", teacher.record())) + .await + .unwrap() + .check() + .unwrap(); + + for status in ["incomplete", "done"] { + grade( + &db, + &homework, + &user, + HomeworkStatus::try_new(status).unwrap(), + None, + &teacher, + ) + .await + .unwrap(); + } + assert_eq!( + marks_given(&teacher, &db).await, + 1, + "one graded pair, one mark given" + ); + } + + /// Un-grading gives the credit back, so grade → ungrade → regrade nets to + /// one however often it is run. Crediting the grade without refunding the + /// delete was the cheapest counter farm in the codebase — two requests per + /// mark given, with no exam, no mark and no submission behind them. + #[tokio::test] + async fn ungrading_gives_the_grader_credit_back() { + let db = crate::database::init_mem().await.unwrap(); + let homework = a_homework(&db).await; + let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); + let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + db.query("CREATE $usr SET username = 't', password_hash = 'x'") + .bind(("usr", teacher.record())) + .await + .unwrap() + .check() + .unwrap(); + + for _ in 0..3 { + grade( + &db, + &homework, + &user, + HomeworkStatus::try_new("missing").unwrap(), + None, + &teacher, + ) + .await + .unwrap(); + assert_eq!(marks_given(&teacher, &db).await, 1); + assert!( + remove(&db, &homework, &user).await.unwrap().is_some(), + "the grade was there" + ); + assert_eq!(marks_given(&teacher, &db).await, 0, "the loop kept one"); + } + + // Nothing to remove is nothing to give back — the floor holds. + assert!(remove(&db, &homework, &user).await.unwrap().is_none()); + assert_eq!(marks_given(&teacher, &db).await, 0); + } + /// The grader's badge counter, re-read out of the store. + async fn marks_given(user: &UserId, db: &Database) -> i64 { + let mut result = db + .query(format!( + "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $usr" + )) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .into_iter() + .next() + .unwrap_or(0) + } +} diff --git a/src/db/homework_submission.rs b/src/db/homework_submission.rs new file mode 100644 index 0000000..ecfd3ed --- /dev/null +++ b/src/db/homework_submission.rs @@ -0,0 +1,720 @@ +//! The `homework_submission` table: one row per (homework, user) — the +//! freeze-guarded UPSERT with its badge counters, the touch, the reads the +//! roster and report join on, and the counter-returning delete. The +//! submit/withdraw workflows live in +//! [`crate::service::homework_submission`]; the validated text type in +//! [`crate::domain::homework_submission`]. + +use crate::constant::{ + HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMITTED_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, + SUBMISSION_OPEN_GUARD, +}; +use crate::database::{Database, transaction_with_retry}; +use crate::domain::homework::Homework; +use crate::domain::homework_submission::{ + HomeworkSubmission, HomeworkSubmissionId, SubmissionText, +}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; +use surrealdb::types::SurrealValue; + +/// Create or re-stamp `user`'s submission to `homework`, unless a grade has +/// frozen it — `None` means frozen, and the caller answers 409. `updated_at` +/// moves to now every time; `submitted_at` (readonly, the first-submit stamp) +/// is kept on an existing row and set only on a fresh one. +/// +/// Hand-written rather than `.content()` on purpose: `.content()` re-sends +/// the whole row, so it would carry a `submitted_at`, and any value differing +/// from the stored one trips the readonly guard. The +/// `submitted_at = submitted_at ?? $now` expression preserves it inside the +/// one UPSERT statement — race-free without a lock, where a read-then-content +/// could let two concurrent first-submits pick different stamps and 500. +/// +/// The `WHERE` is the freeze: [`SUBMISSION_OPEN_GUARD`] makes "not graded +/// yet" a condition of this very write instead of a read a concurrent grade +/// can land behind. An absent row satisfies it (the stamp is `NONE` there +/// too), so a first submit still creates. +/// +/// The badge counters on the student's user row move in this very +/// transaction, and the order is load-bearing: the increment sits *after* +/// the UPSERT and is conditional on it having matched a row, because a +/// frozen row makes that `WHERE` match nothing **silently** (unlike +/// [`crate::db::homework_result::grade`], which `THROW`s) — put +/// first, it would count a submission the freeze refused. `$before = NONE` +/// keeps it to a genuine first create, so an edit moves neither counter, +/// which is what makes the live count mean the same thing the one-time +/// backfill seeded (one per row; on time judged against `due_at`, equal +/// counting as on time). +/// +/// `counted_on_time` is stamped on the row from the *same* `$on_time` +/// expression the increment adds, in the same statement block: the deadline +/// is mutable, so a withdrawal that re-judged it against the live `due_at` +/// gave back something other than what was taken. Writing the verdict beside +/// the counter is what keeps the two from ever disagreeing — read back by +/// [`delete`], never re-derived. +/// +/// That deadline is `$was_due`, the one the gate below already read *inside +/// this transaction* — never the caller's [`Homework`] snapshot, which was +/// read before the lease and is exactly one `PATCH due_at` old in the +/// "teacher extends the deadline at 23:59 while the class submits" moment. +/// Judging on the snapshot stored a verdict the web layer's own `late` flag +/// (`updated_at > due_at`, re-derived live on every read) then contradicted +/// forever, in both directions. An in-process lock cannot fix this — it +/// orders two handlers, not two store transactions — so the comparison has +/// to live where the write does. The whole entity is still taken (both +/// callers hold the row, and the id comes off it); its `due_at` must not be. +/// +/// The first three statements are the parent gate, and they are why this +/// write cannot outlive its homework: the id is deterministic, so nothing +/// else here would fail against a homework a cascade already removed — it +/// would simply re-create the row, badge counters and all, unreachable ever +/// after (every route to a submission goes through its homework). A *read* +/// of the homework does not close that, on either side of the call: the +/// store does no read-set conflict detection, so a delete committing +/// alongside is invisible to it. The gate therefore *moves* a value on the +/// homework row — `due_at` up by one and straight back to the captured +/// value, so the row is byte-identical afterwards — because only a write +/// collides, and `SET x = x` is elided and never reaches the write set. It +/// is [`crate::domain::exam_answer::ExamAnswer::save`]'s shape exactly. +/// `Err(NotFound)` means the homework is gone, which is the 404 the web +/// layer's own lookup would have answered. +pub async fn upsert( + db: &Database, + homework: &Homework, + user: &UserId, + text: Option, +) -> Result, AppError> { + let id = HomeworkSubmissionId::composite(homework.get_id(), user); + let now = Timestamp::now(); + let text = text.map(|text| text.as_str().to_string()); + // Sound to re-send: the UPSERT is on a deterministic id on a table with + // no unique index, so it can never legitimately answer "already exists", + // and the counter UPDATEs never can either. + let (mut saved, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $was_due = (SELECT VALUE due_at FROM ONLY $hw); + LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id); + IF array::len($alive) = 0 {{ THROW 'no_homework' }}; + UPDATE $hw SET due_at = $was_due; + LET $before = (SELECT VALUE id FROM ONLY $id); + LET $on_time = $now <= $was_due; + LET $after = (UPSERT $id SET homework = $hw, user = $usr, text = $text, + updated_at = $now, submitted_at = submitted_at ?? $now + WHERE {SUBMISSION_OPEN_GUARD} RETURN AFTER); + IF $before = NONE AND array::len($after) > 0 {{ + UPDATE $id SET counted_on_time = $on_time; + UPDATE $usr SET + {HOMEWORK_SUBMITTED_TOTAL_FIELD} = ({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) + 1, + {HOMEWORK_ON_TIME_TOTAL_FIELD} = ({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) + + IF $on_time {{ 1 }} ELSE {{ 0 }} + }}; + RETURN $after; + COMMIT TRANSACTION;" + ), + &[ + ("id".into(), id.record().into_value()), + ("hw".into(), homework.get_id().record().into_value()), + ("usr".into(), user.record().into_value()), + ("text".into(), text.into_value()), + ("now".into(), now.into_value()), + ], + &["no_homework"], + ) + .await?; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the THROW's own slot names the reason. + if errors + .values() + .any(|error| error.to_string().contains("no_homework")) + { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is always the last statement before `COMMIT`, so + // its slot follows the statement count rather than a hand-kept number. + // It returns the whole array, never `$after[0]`: a refused write makes + // that `NONE`, which fails to deserialize ("expected object, got none") + // instead of reading as the "frozen" the caller answers 409 to. + let slot = saved.num_statements().saturating_sub(2); + Ok(saved + .take::>(slot)? + .into_iter() + .next()) +} + +/// Re-stamp a submission's `updated_at` to now, leaving its text and files +/// alone. A file add or delete modifies the submission as a whole, so its +/// "last touched" clock — which drives the computed late flag — must move +/// even though the text row is unchanged. Free-standing because the file +/// paths hold the composite id, not always the row. A targeted single-field +/// UPDATE, so the `READONLY` `submitted_at` is never re-sent (a `.content()` +/// would trip its guard). Returns the re-stamped row, or a 404 if it has +/// since vanished. +pub async fn touch( + db: &Database, + id: &HomeworkSubmissionId, +) -> Result { + let now = Timestamp::now(); + let mut result = db + .query("UPDATE $id SET updated_at = $now RETURN AFTER") + .bind(("id", id.record())) + .bind(("now", now)) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::NotFound) +} + +/// Whether a grade has frozen this submission. Only ever read to tell two +/// refusals apart *after* a conditional write has already refused one — the +/// stamp on the row, never this read, is what decides. +pub async fn is_graded(db: &Database, id: &HomeworkSubmissionId) -> Result { + let mut result = db + .query(format!( + "SELECT VALUE id FROM $id WHERE {SUBMISSION_GRADED_FIELD} != NONE" + )) + .bind(("id", id.record())) + .await? + .check()?; + Ok(!result.take::>(0)?.is_empty()) +} + +/// `user`'s submission to `homework`, if they have one. +pub async fn read_for( + db: &Database, + homework: &crate::domain::homework::HomeworkId, + user: &UserId, +) -> Result, AppError> { + Ok(db + .select(HomeworkSubmissionId::composite(homework, user).record()) + .await?) +} + +/// Every submission to `homework`, in student (composite-id) order — the +/// roster's raw rows. +pub async fn list_for_homework( + db: &Database, + homework: &crate::domain::homework::HomeworkId, +) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM homework_submission WHERE homework = $hw ORDER BY id ASC") + .bind(("hw", homework.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Delete this submission and its files in one transaction — so a crash +/// can't leave a file pointing at a vanished submission. The file *blobs* +/// are the web layer's to unlink: it lists them +/// ([`crate::db::homework_file::list_for_submission`]) +/// before calling this. `None` means a grade froze the row (the caller +/// answers 409): the submission's own delete carries +/// [`SUBMISSION_OPEN_GUARD`], and the file wipe is conditional on it having +/// bitten, so a refused delete leaves the children standing too. +/// +/// The one place either badge counter comes back down, and deliberately the +/// only one: this route is student-callable on their own row, so without it +/// a student farms "handed in 50 homeworks" by submit/delete/submit on a +/// single homework. A teacher's homework delete and the course cascade +/// leave the counters alone — history a teacher erased is still history the +/// student lived. +/// +/// The on-time half is given back by the verdict [`upsert`] +/// *stored* on the row, never by re-judging the deadline: `due_at` is +/// mutable, so re-deriving read whatever the teacher had moved it to since +/// and gave back something other than what was taken — extend it after a +/// late hand-in and this debited a credit that was never given; pull it back +/// after a punctual one and it debited nothing, leaving `on_time` above +/// `submitted`. A row from before the column exists carries no verdict, and +/// cannot be given one for a credit that already happened, so it falls back +/// to the old cut (`submitted_at`, the readonly stamp the increment judged, +/// against the live deadline); a dangling `homework` link leaves `$due` +/// `NONE` there, which compares false and so counts as late, matching the +/// backfill. Floored at zero: a row that predates the columns has none. +/// +/// Badges already earned are never taken away — [`crate::domain::badge`] is +/// add-only, which is where that permanence lives. +pub async fn delete( + db: &Database, + submission: HomeworkSubmission, +) -> Result, AppError> { + // Sound to re-send: DELETE and UPDATE can never answer "already exists". + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $due = (SELECT VALUE homework.due_at FROM ONLY $sub); + LET $gone = (DELETE $sub WHERE {SUBMISSION_OPEN_GUARD} RETURN BEFORE); + IF array::len($gone) > 0 {{ + DELETE homework_file WHERE submission = $sub; + LET $on_time = IF ($gone[0].counted_on_time + ?? ($gone[0].submitted_at <= $due)) {{ 1 }} ELSE {{ 0 }}; + UPDATE $usr SET + {HOMEWORK_SUBMITTED_TOTAL_FIELD} = + math::max([({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) - 1, 0]), + {HOMEWORK_ON_TIME_TOTAL_FIELD} = + math::max([({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) - $on_time, 0]) + }}; + RETURN $gone; + COMMIT TRANSACTION;" + ), + &[ + ("sub".into(), submission.id.record().into_value()), + ("usr".into(), submission.user.record().into_value()), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is always the last statement before `COMMIT`. + let slot = result.num_statements().saturating_sub(2); + Ok(result + .take::>(slot)? + .into_iter() + .next()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constant::{ + HOMEWORK_ON_TIME_TOTAL_FIELD as ON_TIME, HOMEWORK_SUBMITTED_TOTAL_FIELD as SUBMITTED, + }; + use crate::db::homework as homework_db; + use crate::domain::homework::HomeworkTitle; + use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; + + /// A real homework row (and the subject it must reference) due at `due_at` — + /// `upsert` now reads the deadline off the entity, so the tests need one. + async fn a_homework(due_at: Timestamp, db: &Database) -> Homework { + let course = crate::db::course::a_test_course(db).await; + let subject = Subject::create( + &course, + SubjectName::try_new("topic").unwrap(), + SubjectDescription::try_new("").unwrap(), + db, + ) + .await + .unwrap(); + homework_db::create( + db, + &course, + subject.get_id(), + HomeworkTitle::try_new("essay").unwrap(), + None, + due_at, + None, + &UserId::from_key("teacher"), + ) + .await + .unwrap() + } + + /// A deadline no test run can reach, so a submission is unambiguously on + /// time; `Timestamp::from_millis(1)` is its late twin. + fn far_future() -> Timestamp { + Timestamp::from_millis(Timestamp::now().as_millis() + 3_600_000) + } + + /// A real user row: the counters live on it, and an `UPDATE` has nothing to + /// write to without one. + async fn a_student(username: &str, db: &Database) -> UserId { + let hash = crate::domain::user::Password::try_new("secret1") + .unwrap() + .hash_async() + .await + .unwrap(); + crate::db::user::create( + db, + crate::domain::user::Username::try_new(username).unwrap(), + hash, + ) + .await + .unwrap() + .get_id() + .clone() + } + + /// Move the stored deadline the way a teacher's PATCH does, leaving the + /// caller's `homework` snapshot untouched — the stale-snapshot shape the + /// handler produces when a `PATCH due_at` commits between its gate read and + /// its write. + async fn deadline_moves_to(homework: &Homework, due_at: Timestamp, db: &Database) { + let stored = homework_db::read(db, homework.get_id()) + .await + .unwrap() + .expect("the homework exists"); + homework_db::update(db, stored, None, None, None, Some(due_at), None) + .await + .unwrap(); + } + + /// The verdict `upsert` stored on the row — what `delete` debits off. + /// `None` is a row from before the column existed. + async fn stored_verdict(id: &HomeworkSubmissionId, db: &Database) -> Option { + let mut result = db + .query("SELECT VALUE counted_on_time FROM $sub") + .bind(("sub", id.record())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>>(0) + .unwrap() + .into_iter() + .flatten() + .next() + } + + /// The web layer's computed flag, exactly as `SubmissionResponse::new` + /// derives it (`src/web/homework.rs`): `updated_at` against the *live* + /// deadline, re-read here because that is what a later GET reads. + async fn late_flag(submission: &HomeworkSubmission, db: &Database) -> bool { + let live = homework_db::read(db, submission.get_homework()) + .await + .unwrap() + .expect("the homework exists"); + submission.get_updated_at() > live.get_due_at() + } + + /// The two badge counters on a user row, absent counting as zero. + async fn counters(user: &UserId, db: &Database) -> (i64, i64) { + let mut result = db + .query(format!( + "SELECT VALUE [({SUBMITTED} ?? 0), ({ON_TIME} ?? 0)] FROM $usr" + )) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + let rows = result.take::>>(0).unwrap(); + let row = rows.first().cloned().unwrap_or_default(); + ( + row.first().copied().unwrap_or(0), + row.get(1).copied().unwrap_or(0), + ) + } + + #[tokio::test] + async fn resubmit_keeps_submitted_at_and_restamps_updated_at() { + let db = crate::database::init_mem().await.unwrap(); + let homework = a_homework(far_future(), &db).await; + let user = a_student("ogrenci", &db).await; + + let first = upsert( + &db, + &homework, + &user, + Some(SubmissionText::try_new("draft").unwrap()), + ) + .await + .unwrap() + .unwrap(); + // A re-submit lands on the same row: submitted_at (the first hand-in) + // pinned, updated_at moves forward, and the text can be cleared. + let second = upsert(&db, &homework, &user, None).await.unwrap().unwrap(); + // ... and it is one submission, not two: the edit moves no counter. + assert_eq!(counters(&user, &db).await, (1, 1)); + assert_eq!(first.get_id(), second.get_id()); + assert_eq!(first.get_submitted_at(), second.get_submitted_at()); + assert!(second.get_updated_at() >= first.get_updated_at()); + assert!(second.get_text().is_none()); + // One row per (homework, user), whatever the re-submit count. + assert_eq!( + list_for_homework(&db, homework.get_id()) + .await + .unwrap() + .len(), + 1 + ); + } + + /// The freeze, as stored state rather than as a race: the grade stamps the + /// submission row, and from then on the submission's own writes fail their + /// condition — no read of `homework_result` involved, which is what makes it + /// hold when the grade lands mid-request. Un-grading clears the stamp + /// and the row is writable again. + /// + /// Bite check: drop `WHERE graded_by_result = NONE` from + /// [`upsert`] and the "version B" upsert below comes + /// back `Some` — the exact swap this guards against. + #[tokio::test] + async fn a_grade_freezes_the_submission_row_itself() { + use crate::db::homework_result; + use crate::domain::homework_result::HomeworkStatus; + + let db = crate::database::init_mem().await.unwrap(); + let homework = a_homework(far_future(), &db).await; + let user = a_student("ogrenci", &db).await; + let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + let graded = |value| { + let text = SubmissionText::try_new(value).unwrap(); + upsert(&db, &homework, &user, Some(text)) + }; + + let version_a = graded("version A").await.unwrap().unwrap(); + assert!(!is_graded(&db, version_a.get_id()).await.unwrap()); + + assert_eq!(counters(&user, &db).await, (1, 1)); + + homework_result::grade( + &db, + homework.get_id(), + &user, + HomeworkStatus::try_new("done").unwrap(), + None, + &teacher, + ) + .await + .unwrap(); + assert!(is_graded(&db, version_a.get_id()).await.unwrap()); + + // The swap the teacher would never see: refused, and the stored text is + // still the version that was graded. + assert!(graded("version B").await.unwrap().is_none()); + assert_eq!( + read_for(&db, homework.get_id(), &user) + .await + .unwrap() + .and_then(|row| row.get_text().map(|text| text.as_str().to_string())), + Some("version A".to_string()) + ); + // The refusal is silent — the UPSERT simply matches nothing — so the + // counters are the only thing that can catch an increment placed in + // front of it: a submission the freeze refused must count for nothing. + assert_eq!(counters(&user, &db).await, (1, 1)); + // ... and so is withdrawing it wholesale. + let frozen = read_for(&db, homework.get_id(), &user) + .await + .unwrap() + .unwrap(); + assert!(delete(&db, frozen).await.unwrap().is_none()); + assert!( + read_for(&db, homework.get_id(), &user) + .await + .unwrap() + .is_some() + ); + // A refused delete decrements nothing either. + assert_eq!(counters(&user, &db).await, (1, 1)); + + // Un-grading unfreezes it, stamp and all. + homework_result::remove(&db, homework.get_id(), &user) + .await + .unwrap(); + assert!(!is_graded(&db, version_a.get_id()).await.unwrap()); + let reopened = graded("version B").await.unwrap().unwrap(); + assert_eq!( + reopened.get_text().map(SubmissionText::as_str), + Some("version B") + ); + // Still an edit to the row that was already counted, un-freeze or not. + assert_eq!(counters(&user, &db).await, (1, 1)); + // The two-stamp lateness rule is untouched by any of it: the first + // hand-in is still the first hand-in. + assert_eq!(reopened.get_submitted_at(), version_a.get_submitted_at()); + assert!(reopened.get_updated_at() >= version_a.get_updated_at()); + } + + #[tokio::test] + async fn touch_moves_updated_at_but_not_submitted_at_or_text() { + let db = crate::database::init_mem().await.unwrap(); + let homework = a_homework(far_future(), &db).await; + let user = a_student("ogrenci", &db).await; + + let original = upsert( + &db, + &homework, + &user, + Some(SubmissionText::try_new("photo answer").unwrap()), + ) + .await + .unwrap() + .unwrap(); + // A file add/delete touches the submission: updated_at moves (never + // backwards), while the first-submit stamp and the text stay put. + let touched = touch(&db, original.get_id()).await.unwrap(); + assert_eq!(touched.get_submitted_at(), original.get_submitted_at()); + assert!(touched.get_updated_at() >= original.get_updated_at()); + assert_eq!( + touched.get_text().map(SubmissionText::as_str), + Some("photo answer") + ); + } + + /// The farm, closed: `delete_submission` is the student's own route, so a + /// counter that only ever went up would let one homework be handed in fifty + /// times. Submit → withdraw → submit is worth exactly one submission. + /// + /// Bite check: drop the `UPDATE $usr` from [`delete`] + /// and the last assertion reads `(2, 2)` — the farm. + #[tokio::test] + async fn submit_delete_submit_is_worth_one_submission() { + let db = crate::database::init_mem().await.unwrap(); + let homework = a_homework(far_future(), &db).await; + let user = a_student("ogrenci", &db).await; + + upsert(&db, &homework, &user, None).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (1, 1)); + + let mine = read_for(&db, homework.get_id(), &user) + .await + .unwrap() + .unwrap(); + delete(&db, mine).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (0, 0)); + // Floored: a second withdrawal (or a row from before the columns + // existed) can never push either counter negative. + assert!( + read_for(&db, homework.get_id(), &user) + .await + .unwrap() + .is_none() + ); + + upsert(&db, &homework, &user, None).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (1, 1)); + } + + /// Lateness is judged against the homework's own deadline at hand-in, the + /// same cut the one-time backfill used, and only the on-time counter sees + /// it: a late hand-in is still a hand-in. Its withdrawal gives back only + /// what it took. + #[tokio::test] + async fn a_late_submission_counts_as_submitted_but_not_on_time() { + let db = crate::database::init_mem().await.unwrap(); + let punctual = a_homework(far_future(), &db).await; + let overdue = a_homework(Timestamp::from_millis(1), &db).await; + let user = a_student("ogrenci", &db).await; + + upsert(&db, &punctual, &user, None).await.unwrap().unwrap(); + upsert(&db, &overdue, &user, None).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (2, 1)); + + // Withdrawing the *late* one takes back only the submission, never the + // on-time credit the punctual one earned — the zero floor would hide a + // wrong subtraction here if the on-time count were sitting at zero. + let late = read_for(&db, overdue.get_id(), &user) + .await + .unwrap() + .unwrap(); + delete(&db, late).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (1, 1)); + + // ... and withdrawing the punctual one gives back exactly that credit. + let kept = read_for(&db, punctual.get_id(), &user) + .await + .unwrap() + .unwrap(); + delete(&db, kept).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (0, 0)); + } + + /// A row from before `counted_on_time` existed carries no verdict — it was + /// credited by a comparison that left no trace, and cannot be given one + /// retroactively. Withdrawing it falls back to that same comparison, so the + /// pre-2026-08-04 rows on a live volume keep behaving exactly as they did. + /// + /// Bite check: an absent verdict read as `false` rather than falling through + /// (`??` binding the wrong side of the `<=`) leaves the last assertion at + /// `(0, 1)` — on time above submitted, the shape the stored verdict exists + /// to prevent. + #[tokio::test] + async fn a_row_with_no_stored_verdict_falls_back_to_the_deadline() { + let db = crate::database::init_mem().await.unwrap(); + let punctual = a_homework(far_future(), &db).await; + let overdue = a_homework(Timestamp::from_millis(1), &db).await; + let user = a_student("ogrenci", &db).await; + + upsert(&db, &punctual, &user, None).await.unwrap().unwrap(); + upsert(&db, &overdue, &user, None).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (2, 1)); + // Aged into legacy rows: the counters keep the credit, the rows lose the + // verdict — the exact state of every submission on an existing volume. + db.query("UPDATE homework_submission UNSET counted_on_time") + .await + .unwrap() + .check() + .unwrap(); + + let late = read_for(&db, overdue.get_id(), &user) + .await + .unwrap() + .unwrap(); + delete(&db, late).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (1, 1)); + + let kept = read_for(&db, punctual.get_id(), &user) + .await + .unwrap() + .unwrap(); + delete(&db, kept).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (0, 0)); + } + + /// The stale snapshot, both directions: the teacher's `PATCH due_at` commits + /// between the handler's gate read and its write, so the caller's entity + /// carries a deadline the store no longer has. The verdict must follow the + /// *stored* deadline the write itself reads, because the API's `late` flag + /// is re-derived from that same stored value on every later read — a verdict + /// judged on the snapshot disagrees with it permanently, and `delete` then + /// gives back the wrong credit. + /// + /// Bite check: judge `$on_time` against the caller's `$due` instead of + /// `$was_due` and both halves fail — extended reads `(1, 0)` with a stored + /// `false` against a live `late = false`, pulled reads `(1, 1)` with a + /// stored `true` against a live `late = true`. + #[tokio::test] + async fn a_deadline_moved_under_the_caller_is_judged_by_the_stored_value() { + let db = crate::database::init_mem().await.unwrap(); + let user = a_student("ogrenci", &db).await; + + // Extended at 23:59: the snapshot says the deadline has passed, the + // store says it has not. A hand-in now is on time. + let extended = a_homework(Timestamp::from_millis(1), &db).await; + deadline_moves_to(&extended, far_future(), &db).await; + let landed = upsert(&db, &extended, &user, None).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (1, 1)); + assert_eq!(stored_verdict(landed.get_id(), &db).await, Some(true)); + assert!(!late_flag(&landed, &db).await); + + // Pulled earlier: the snapshot says there is time left, the store says + // the deadline is gone. The same hand-in is late. + let pulled = a_homework(far_future(), &db).await; + deadline_moves_to(&pulled, Timestamp::from_millis(1), &db).await; + let missed = upsert(&db, &pulled, &user, None).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (2, 1)); + assert_eq!(stored_verdict(missed.get_id(), &db).await, Some(false)); + assert!(late_flag(&missed, &db).await); + + // The invariant behind both: the stored verdict is the negation of the + // flag the web layer computes for the same submission, never its twin. + for submission in [&landed, &missed] { + assert_eq!( + stored_verdict(submission.get_id(), &db).await, + Some(!late_flag(submission, &db).await), + "stored verdict and the API's late flag must never disagree" + ); + } + + // ... and the withdrawal, which debits off the stamp, gives back exactly + // what each one took. + delete(&db, missed).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (1, 1)); + delete(&db, landed).await.unwrap().unwrap(); + assert_eq!(counters(&user, &db).await, (0, 0)); + } +} diff --git a/src/db/mod.rs b/src/db/mod.rs index 450cc1c..a803916 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -19,6 +19,10 @@ pub mod exam_question; pub mod fee_plan; pub mod fee_plan_assignment; pub mod field_update; +pub mod homework; +pub mod homework_file; +pub mod homework_result; +pub mod homework_submission; pub mod meal_attendance; pub mod meal_booking; pub mod meal_ledger; diff --git a/src/domain/homework.rs b/src/domain/homework.rs index dca363e..0b8ee20 100644 --- a/src/domain/homework.rs +++ b/src/domain/homework.rs @@ -1,8 +1,10 @@ //! A homework assignment: a teacher hands it out per course, optionally //! narrowed to a subset of the enrolled students, and every homework is tagged -//! with one of its course's subjects. Students submit against it -//! ([`crate::domain::homework_submission`]) and a teacher grades a status plus -//! an optional mark ([`crate::domain::homework_result`]). +//! with one of its course's subjects. +//! Students submit against it ([`crate::domain::homework_submission`]) and a +//! teacher grades a status plus an optional mark +//! ([`crate::domain::homework_result`]). Persistence lives in +//! [`crate::db::homework`], workflows in [`crate::service::homework`]. //! //! `course`, `created_by`, and `created_at` are fixed at creation (the schema //! marks them `READONLY`): moving a homework between courses would strand the @@ -12,32 +14,15 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ - HOMEWORK_TABLE, MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN, - SUBJECT_HOMEWORK_COUNT_FIELD, -}; -use crate::database::Database; -use crate::db::cap; -use crate::db::field_update::FieldUpdate; +use crate::constant::{HOMEWORK_TABLE, MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN}; use crate::domain::course::CourseId; use crate::domain::monotonic_id::next_ulid; use crate::domain::subject::SubjectId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::{validate_optional, validate_required}; -/// The answer a link to a subject that is not there gets, on create and on -/// re-tag alike — both claims are conditional writes on the subject row, so a -/// subject a delete already removed matches nothing and the caller says exactly -/// what the web layer's pre-flight lookup would have. -fn subject_gone() -> AppError { - AppError::Validation(ValidationError::Invalid { - field: "subject_id", - reason: "subject does not exist", - }) -} - #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct HomeworkId(RecordId); @@ -100,15 +85,15 @@ impl HomeworkDescription { /// snapshot of the students named at assign (or last PATCH) time. #[derive(Debug, Clone, SurrealValue)] pub struct Homework { - id: HomeworkId, - course: CourseId, - subject: SubjectId, - title: HomeworkTitle, - description: Option, - due_at: Timestamp, - assigned: Option>, - created_by: UserId, - created_at: Timestamp, + pub(crate) id: HomeworkId, + pub(crate) course: CourseId, + pub(crate) subject: SubjectId, + pub(crate) title: HomeworkTitle, + pub(crate) description: Option, + pub(crate) due_at: Timestamp, + pub(crate) assigned: Option>, + pub(crate) created_by: UserId, + pub(crate) created_at: Timestamp, } impl Homework { @@ -159,222 +144,6 @@ impl Homework { Some(assigned) => assigned.is_empty() || assigned.contains(user), } } - - #[expect( - clippy::too_many_arguments, - reason = "mirrors the sibling entities' create(field, field, ..) shape" - )] - pub async fn create( - course: &CourseId, - subject: &SubjectId, - title: HomeworkTitle, - description: Option, - due_at: Timestamp, - assigned: Option>, - created_by: &UserId, - db: &Database, - ) -> Result { - // The subject's reference is taken in the very transaction that writes - // the row — the exam question's twin - // ([`crate::domain::exam_question::ExamQuestion`]): the subject delete - // is refused while this counter is non-zero, so the create and the - // delete contend on the subject record rather than on a cross-table - // count neither of them sees the other move, and a crash can no longer - // strand a claim that would make the subject undeletable forever. A - // refused claim means the subject is already gone, which is the 400 the - // web layer's pre-flight check answers with. - let counted = subject.record(); - let homework = Homework { - id: HomeworkId::generate(), - course: course.clone(), - subject: subject.clone(), - title, - description, - due_at, - assigned, - created_by: created_by.clone(), - created_at: Timestamp::now(), - }; - let id = homework.id.record(); - match cap::claim_and_create( - &counted, - SUBJECT_HOMEWORK_COUNT_FIELD, - cap::UNLIMITED, - &id, - &homework, - db, - ) - .await? - { - cap::Claimed::Made(created) => Ok(created), - cap::Claimed::Full => Err(subject_gone()), - cap::Claimed::Duplicate => Err(AppError::Internal("failed to create homework".into())), - } - } - - pub async fn read(id: &HomeworkId, db: &Database) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// The course's homework, newest first (ULID ids sort by creation). The web - /// layer retains only the rows a given student `student_sees`. - pub async fn list_for_course( - course: &CourseId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM homework WHERE course = $course ORDER BY id DESC") - .bind(("course", course.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Every homework in the system, newest first — the manager+ view of the - /// cross-course "my homework" list. - pub async fn list_all(db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM homework ORDER BY id DESC") - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Every homework of every course in `courses`, newest first (one query) — - /// the cross-course list over a caller's visible courses. The web layer - /// still trims each course's rows to what the caller may see (a student to - /// the ones they `student_sees`). - pub async fn list_for_courses( - courses: &[CourseId], - db: &Database, - ) -> Result, AppError> { - if courses.is_empty() { - return Ok(Vec::new()); - } - let records: Vec = courses.iter().map(CourseId::record).collect(); - let mut result = db - .query("SELECT * FROM homework WHERE course IN $courses ORDER BY id DESC") - .bind(("courses", records)) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// The homework of `course` that `user` is meant to see — whole-course ones - /// plus any subset that names them — newest first. Backs a student's (or an - /// observer's) per-course homework report; mirrors [`Homework::student_sees`] - /// in SurQL so the filter runs in the database. - pub async fn list_for_user_in_course( - course: &CourseId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM homework - WHERE course = $course - AND (assigned = NONE OR assigned = [] OR $usr IN assigned) - ORDER BY id DESC", - ) - .bind(("course", course.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework. - /// Request-scoped: every parameter is `Option`, `None` meaning the PATCH - /// did not carry that field, so it is not written at all. Handing the - /// snapshot's value back instead would revert a concurrent edit of that - /// field — scoping the `SET` alone does not prevent that, the *values* must - /// come from the request. `course`, `created_by`, and `created_at` are - /// `READONLY` and never appear in the write. - /// - /// `description` and `assigned` are nullable columns, so they take a - /// *double* option: outer `None` = absent (keep), `Some(None)` = write - /// `NONE` (clear the description / widen back to the whole course). The web - /// layer has already re-checked a new `due_at` against now, a new `subject` - /// against the course, and refused a narrowing that would orphan work. - pub async fn update( - self, - subject: Option, - title: Option, - description: Option>, - due_at: Option, - assigned: Option>>, - db: &Database, - ) -> Result { - let assigned = assigned - .map(|subset| subset.map(|users| users.iter().map(UserId::record).collect::>())); - // A re-tag moves a reference: the new subject's claim and the old one's - // release ride the same transaction as the link write, so no crash can - // leave a count without its link (the subject would be undeletable - // forever) or a link without its count. `subject` is required, so the - // snapshot's value is always the CAS expectation — two PATCHes moving - // the same homework off the same subject would otherwise both claim - // their target, and the loser is refused with a 409 instead. The - // `.refcount` call is unconditional: the CAS is armed by the request - // *carrying* `subject_id`, not by a counter moving, so a PATCH that - // re-states the tag its snapshot showed — shifting no counter at all — - // is still refused when a rival moved the tag in between. A PATCH that - // carried no `subject_id` arms nothing and writes what it always did. - let (claim, release) = subject - .as_ref() - .filter(|next| **next != self.subject) - .map(|next| (next.record(), self.subject.record())) - .unzip(); - FieldUpdate::new(self.id.record()) - .set("subject", subject.map(|subject| subject.record())) - .set("title", title) - .set("description", description) - .set("due_at", due_at) - .set("assigned", assigned) - .refcount( - SUBJECT_HOMEWORK_COUNT_FIELD, - "subject", - Some(self.subject.record()), - claim, - release, - subject_gone(), - ) - .run::(db) - .await - } - - /// Delete the homework and cascade its submissions, their files, and its - /// results — one transaction, so a crash can't orphan a submission under a - /// vanished homework. The submission file *blobs* are the web layer's to - /// unlink: it collects their names via - /// [`crate::domain::homework_file::HomeworkFile::file_keys_for_homework`] - /// before calling this, and removes them after the rows are gone. - pub async fn delete(self, db: &Database) -> Result { - let mut result = db - .query( - format!( - "BEGIN TRANSACTION; - DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw); - DELETE homework_submission WHERE homework = $hw; - DELETE homework_result WHERE homework = $hw; - LET $gone = (DELETE $hw RETURN BEFORE); - FOR $sub IN ($gone.subject ?? []) {{ - UPDATE $sub SET {SUBJECT_HOMEWORK_COUNT_FIELD} = - math::max([({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) - 1, 0]) - }}; - RETURN $gone; - COMMIT TRANSACTION;" - ), - ) - .bind(("hw", self.id.record())) - .await? - .check()?; - // The subject's reference is given back in this same transaction, off - // what the delete actually removed. Read through the trailing `RETURN`, - // not a hand-counted slot — see [`crate::db::exam::delete`]. - let slot = result.num_statements().saturating_sub(2); - let deleted: Option = result.take::>(slot)?.into_iter().next(); - deleted.ok_or(AppError::NotFound) - } } #[cfg(test)] @@ -417,258 +186,4 @@ mod tests { assert!(with(Some(vec![a.clone()])).student_sees(&a)); assert!(!with(Some(vec![a.clone()])).student_sees(&b)); } - - use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; - - async fn a_subject(name: &str, db: &Database) -> Subject { - crate::db::subject::create( - db, - &crate::db::course::a_test_course(db).await, - SubjectName::try_new(name).unwrap(), - SubjectDescription::try_new("").unwrap(), - ) - .await - .unwrap() - } - - async fn homework_on(subject: &SubjectId, db: &Database) -> Homework { - Homework::create( - &CourseId::from_key("course"), - subject, - HomeworkTitle::try_new("essay").unwrap(), - None, - Timestamp::from_millis(1), - None, - &UserId::from_key("teacher"), - db, - ) - .await - .unwrap() - } - - /// The stored `homework_count` on one subject, absent counting as zero. - async fn count_on(subject: &SubjectId, db: &Database) -> i64 { - let mut result = db - .query(format!( - "SELECT VALUE ({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) FROM $sub" - )) - .bind(("sub", subject.record())) - .await - .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .first() - .copied() - .unwrap_or(0) - } - - /// How many rows `sql` selects ids for. - async fn rows(sql: &str, db: &Database) -> usize { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result.take::>(0).unwrap().len() - } - - /// The invariant on the create path: the claim and the row it accounts for - /// commit together or not at all. A refused create leaves *neither* — no - /// homework row, and no count stranded on a subject (the subject's delete - /// guard reads that count, so a stray one makes it undeletable forever). - #[tokio::test] - async fn a_refused_create_writes_neither_row_nor_count() { - let db = crate::database::init_mem().await.unwrap(); - let subject = a_subject("algebra", &db).await; - let id = subject.get_id().clone(); - crate::db::subject::delete(&db, subject).await.unwrap(); - - let error = Homework::create( - &CourseId::from_key("course"), - &id, - HomeworkTitle::try_new("essay").unwrap(), - None, - Timestamp::from_millis(1), - None, - &UserId::from_key("teacher"), - &db, - ) - .await - .expect_err("a subject that is gone must not be taggable"); - assert!(error.to_string().contains("subject does not exist")); - assert_eq!( - rows("SELECT VALUE id FROM homework", &db).await, - 0, - "a refused create may write no row" - ); - assert_eq!( - rows("SELECT VALUE id FROM subject", &db).await, - 0, - "…and least of all a count on a subject it just brought back" - ); - } - - /// The invariant on the PATCH path: a re-tag carries the new subject's - /// claim and the old one's release with the link itself. - #[tokio::test] - async fn a_subject_move_moves_the_count() { - let db = crate::database::init_mem().await.unwrap(); - let from = a_subject("algebra", &db).await; - let to = a_subject("geometry", &db).await; - let homework = homework_on(from.get_id(), &db).await; - assert_eq!(count_on(from.get_id(), &db).await, 1); - - let moved = homework - .update(Some(to.get_id().clone()), None, None, None, None, &db) - .await - .unwrap(); - assert_eq!(moved.get_subject(), to.get_id()); - assert_eq!( - count_on(from.get_id(), &db).await, - 0, - "the old subject is free" - ); - assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); - assert!( - crate::db::subject::delete(&db, from).await.is_ok(), - "no reference left" - ); - assert!( - crate::db::subject::delete(&db, to).await.is_err(), - "the reference moved here refuses the delete" - ); - } - - /// The claim throws inside the same transaction as the link write, so a - /// move onto a subject that is gone rolls the release back with it: the row - /// keeps its tag and both counters read as if nothing ran. - #[tokio::test] - async fn a_move_to_a_dead_subject_leaves_everything_untouched() { - let db = crate::database::init_mem().await.unwrap(); - let from = a_subject("algebra", &db).await; - let dead = a_subject("geometry", &db).await; - let gone = dead.get_id().clone(); - crate::db::subject::delete(&db, dead).await.unwrap(); - let homework = homework_on(from.get_id(), &db).await; - - let error = homework - .clone() - .update(Some(gone.clone()), None, None, None, None, &db) - .await - .expect_err("a subject that is gone must not be taggable"); - assert!(error.to_string().contains("subject does not exist")); - let stored = Homework::read(homework.get_id(), &db) - .await - .unwrap() - .unwrap(); - assert_eq!(stored.get_subject(), from.get_id(), "the tag never moved"); - assert_eq!( - count_on(from.get_id(), &db).await, - 1, - "the release rolled back with the claim" - ); - assert_eq!( - rows("SELECT VALUE id FROM subject", &db).await, - 1, - "the dead subject was not brought back by a count" - ); - assert_eq!(count_on(&gone, &db).await, 0); - } - - /// The double-claim guard. Both movers compute their claim and release from - /// the row as *they* read it, so two PATCHes re-tagging the same homework - /// off the same subject both release it and both claim their target — two - /// counts for one link, and the loser's target is undeletable forever. The - /// second call here runs on the struct read before the first one landed, - /// which is that race with the interleaving pinned: it must be refused - /// outright, and the counts must read as if it never ran. - #[tokio::test] - async fn a_stale_mover_is_refused_and_claims_nothing() { - let db = crate::database::init_mem().await.unwrap(); - let from = a_subject("algebra", &db).await; - let to = a_subject("geometry", &db).await; - let other = a_subject("calculus", &db).await; - let homework = homework_on(from.get_id(), &db).await; - let stale = homework.clone(); - homework - .update(Some(to.get_id().clone()), None, None, None, None, &db) - .await - .unwrap(); - - let error = stale - .clone() - .update(Some(other.get_id().clone()), None, None, None, None, &db) - .await - .expect_err("a mover that read a tag it no longer holds must be refused"); - assert!( - matches!(error, AppError::Conflict(_)), - "a lost CAS is a conflict, not a 404 or a 500: {error:?}" - ); - let stored = Homework::read(stale.get_id(), &db).await.unwrap().unwrap(); - assert_eq!(stored.get_subject(), to.get_id(), "the winner's tag"); - assert_eq!( - count_on(from.get_id(), &db).await, - 0, - "released once, not twice" - ); - assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once"); - assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed"); - } - - /// The same race with the counters taken out of it. A PATCH that re-states - /// the subject its snapshot showed shifts *nothing* — no claim and no - /// release — so if the guard were armed off the counter move it would not be - /// armed here at all, and the write would land: the winner's tag silently - /// dragged back, its claim stranded on a subject nothing points at - /// (undeletable forever) and the reverted-to subject tagged at a count of - /// zero (deletable while tagged). The guard is armed by the request - /// *carrying* the column instead, which is why this is refused. - #[tokio::test] - async fn a_stale_re_stater_is_refused_and_reverts_nothing() { - let db = crate::database::init_mem().await.unwrap(); - let from = a_subject("algebra", &db).await; - let to = a_subject("geometry", &db).await; - let homework = homework_on(from.get_id(), &db).await; - let stale = homework.clone(); - homework - .update(Some(to.get_id().clone()), None, None, None, None, &db) - .await - .unwrap(); - - let error = stale - .clone() - .update(Some(from.get_id().clone()), None, None, None, None, &db) - .await - .expect_err("re-stating a tag someone else moved must be refused"); - assert!( - matches!(error, AppError::Conflict(_)), - "a lost CAS is a conflict, not a silent 200: {error:?}" - ); - let stored = Homework::read(stale.get_id(), &db).await.unwrap().unwrap(); - assert_eq!(stored.get_subject(), to.get_id(), "the winner's tag"); - assert_eq!( - count_on(from.get_id(), &db).await, - 0, - "the reverted-to subject must not end up tagged at zero" - ); - assert_eq!( - count_on(to.get_id(), &db).await, - 1, - "…nor the winner's subject counted with nothing pointing at it" - ); - - // A *genuine* no-op re-state — nobody moved underneath it — still lands, - // and still moves no counter: the CAS passes trivially. - let fresh = Homework::read(stale.get_id(), &db).await.unwrap().unwrap(); - let same = fresh - .update(Some(to.get_id().clone()), None, None, None, None, &db) - .await - .expect("re-stating the tag actually held is not a race"); - assert_eq!(same.get_subject(), to.get_id()); - assert_eq!( - count_on(from.get_id(), &db).await, - 0, - "still no counter move" - ); - assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once, still"); - } } diff --git a/src/domain/homework_file.rs b/src/domain/homework_file.rs index a62cbaf..1914a00 100644 --- a/src/domain/homework_file.rs +++ b/src/domain/homework_file.rs @@ -6,24 +6,18 @@ //! disk path. Files are immutable: created and deleted, never updated, so the //! `READONLY` `submission`/`file`/`created_at` columns are only ever set once. //! The web layer owns the blob I/O and its ordering (blob before row on -//! upload, row before blob on delete); this module owns the rows. +//! upload, row before blob on delete); the rows are written and read by +//! [`crate::db::homework_file`], the upload/attach workflow by +//! [`crate::service::homework_file`]. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; -use crate::constant::{ - HOMEWORK_FILE_TABLE, MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD, - SUBMISSION_OPEN_GUARD, -}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; -use crate::domain::course::CourseId; -use crate::domain::homework::HomeworkId; -use crate::domain::homework_submission::{HomeworkSubmission, HomeworkSubmissionId}; +use crate::constant::HOMEWORK_FILE_TABLE; +use crate::domain::homework_submission::HomeworkSubmissionId; use crate::domain::monotonic_id::next_ulid; use crate::domain::note_file::{FileContentType, FileName}; use crate::domain::timestamp::Timestamp; -use crate::error::AppError; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct HomeworkFileId(RecordId); @@ -56,23 +50,13 @@ impl HomeworkFileId { /// upload), independent of the row id and reused as the GC key on cascade. #[derive(Debug, Clone, SurrealValue)] pub struct HomeworkFile { - id: HomeworkFileId, - submission: HomeworkSubmissionId, - name: FileName, - content_type: FileContentType, - size: i64, - file: String, - created_at: Timestamp, -} - -/// What [`HomeworkFile::delete`]'s transaction reports: whether the submission -/// was still open (`open` = 1, the gate bit) and the row it then removed. Two -/// answers in one object because an empty `gone` alone cannot say whether the -/// delete was refused or the file had simply vanished. -#[derive(Debug, SurrealValue)] -struct DeleteOutcome { - open: i64, - gone: Vec, + pub(crate) id: HomeworkFileId, + pub(crate) submission: HomeworkSubmissionId, + pub(crate) name: FileName, + pub(crate) content_type: FileContentType, + pub(crate) size: i64, + pub(crate) file: String, + pub(crate) created_at: Timestamp, } impl HomeworkFile { @@ -124,399 +108,4 @@ impl HomeworkFile { pub fn get_created_at(&self) -> Timestamp { self.created_at } - - /// Persist the row assembled by [`Self::new`], refusing once its submission - /// already holds [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`) - /// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own - /// wording). Both are decided by one [`cap::claim_when_and_create`] on the - /// submission row — the seat and the file row commit together, so a crash - /// between them can no longer leave a slot claimed by a file that does not - /// exist, and a losing upload never has to be un-counted. Which of the two - /// conditions refused it is read back afterwards, off the losing path only, - /// and only to pick the message: `Claimed::Full` says "full *or* graded *or* - /// the submission is gone". - pub async fn insert(self, db: &Database) -> Result, AppError> { - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber - match cap::claim_when_and_create( - &self.submission.record(), - SUBMISSION_FILE_COUNT_FIELD, - MAX_HOMEWORK_FILES_PER_SUBMISSION as i64, - SUBMISSION_OPEN_GUARD, - &self.id.record(), - &self, - db, - ) - .await? - { - cap::Claimed::Made(created) => Ok(Some(created)), - cap::Claimed::Full => { - if HomeworkSubmission::is_graded(&self.submission, db).await? { - return Ok(None); - } - Err(AppError::Conflict( - "the submission already holds the maximum of 10 files — delete one first", - )) - } - // The id is a fresh ULID minted by `new`, so a row already holding it - // is a collision, not a re-upload. - cap::Claimed::Duplicate => Err(AppError::Internal("homework file id collided".into())), - } - } - - /// Read a file's row only if it belongs to `submission` — callers have - /// already checked the submission belongs to the requesting user. - pub async fn read_for( - id: &HomeworkFileId, - submission: &HomeworkSubmissionId, - db: &Database, - ) -> Result, AppError> { - let file: Option = db.select(id.record()).await?; - Ok(file.filter(|file| &file.submission == submission)) - } - - /// Read a file by id only if it hangs off a submission to `homework` — the - /// grader's download scoping. The teacher download path carries the homework - /// id but not the owning student (unlike `read_for`, which needs the - /// submission), so this both finds the file and confirms it belongs under - /// `homework`: a teacher can't pass a homework they manage to read a file - /// from a different (perhaps unmanaged) one. - pub async fn read_in_homework( - id: &HomeworkFileId, - homework: &HomeworkId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM homework_file WHERE id = $id AND submission IN \ - (SELECT VALUE id FROM homework_submission WHERE homework = $hw)", - ) - .bind(("id", id.record())) - .bind(("hw", homework.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) - } - - /// All of `submission`'s files, newest first. - pub async fn list_for_submission( - submission: &HomeworkSubmissionId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM homework_file WHERE submission = $sub ORDER BY id DESC") - .bind(("sub", submission.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// How many files `submission` holds — the cap check reads this under the - /// lock. Counting via the rows (not a `count()` query) keeps it identical - /// to `NoteFile`'s proven cap check; at a ceiling of 10 the cost is nil. - pub async fn count_for_submission( - submission: &HomeworkSubmissionId, - db: &Database, - ) -> Result { - Ok(Self::list_for_submission(submission, db).await?.len()) - } - - /// The blob names behind every file of every submission to `homework` — - /// collected *before* the homework-delete cascade wipes the rows, so the - /// web layer can unlink them once the rows are gone. - pub async fn file_keys_for_homework( - homework: &HomeworkId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT VALUE file FROM homework_file \ - WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw)", - ) - .bind(("hw", homework.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// The blob names behind every homework file of `course` — collected - /// *before* the course-delete cascade wipes the rows. - pub async fn file_keys_for_course( - course: &CourseId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT VALUE file FROM homework_file WHERE submission IN ( \ - SELECT VALUE id FROM homework_submission \ - WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course) \ - )", - ) - .bind(("course", course.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Delete the row and give its slot back in the same transaction. The - /// submission survives, so its counter has to be corrected; the cascades - /// that delete the submission itself take the counter with it. - /// - /// The gate is the first statement: a conditional write on the *submission* - /// row — the "last touched" re-stamp a file delete owes the late flag - /// anyway — carrying [`SUBMISSION_OPEN_GUARD`]. Nothing else in the - /// transaction runs unless it bit, so a grade landing concurrently either - /// stamps first (this delete is refused, `Ok(None)`) or stamps after (the - /// file was already gone when it graded). `Err(NotFound)` still means the - /// file row itself had vanished. - /// - /// Sound to re-send while the store answers "conflict, retry", and it has - /// to be: the gate writes the *submission* row, the very record an upload's - /// [`HomeworkFile::insert`] claims its seat on, and both handlers hold only - /// `HOMEWORK_LOCK.read()` — so a concurrent add and delete of two files of - /// one submission contend by design, and a lost round used to come back as - /// a 500 on a request that had written nothing. Only `UPDATE` and `DELETE` - /// are in the batch, and neither can legitimately answer "already exists", - /// which is what makes the whole of it re-sendable. - pub async fn delete(self, db: &Database) -> Result, AppError> { - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $open = (UPDATE $sub SET updated_at = $now \ - WHERE {SUBMISSION_OPEN_GUARD} RETURN VALUE id); - LET $gone = IF array::len($open) > 0 {{ (DELETE $id RETURN BEFORE) }} ELSE {{ [] }}; - UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); - RETURN {{ open: array::len($open), gone: $gone }}; - COMMIT TRANSACTION;" - ), - &[ - ("id".into(), self.id.record().into_value()), - ("sub".into(), self.submission.record().into_value()), - ("now".into(), Timestamp::now().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // BEGIN is slot 0, the two LETs slots 1-2 and the counter fix slot 3; - // the RETURN is slot 4. - let outcome: Option = - result.take::>(4)?.into_iter().next(); - let outcome = - outcome.ok_or_else(|| AppError::Internal("failed to delete homework file".into()))?; - if outcome.open == 0 { - return Ok(None); - } - outcome - .gone - .into_iter() - .next() - .map(Some) - .ok_or(AppError::NotFound) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::domain::homework_submission::HomeworkSubmission; - use crate::domain::user::UserId; - - /// A real homework row (with the subject it references): `upsert` reads the - /// deadline off the entity now, so a bare id no longer does. - async fn a_homework(db: &Database) -> crate::domain::homework::Homework { - use crate::domain::homework::{Homework, HomeworkTitle}; - use crate::domain::subject::{SubjectDescription, SubjectName}; - - let course = crate::db::course::a_test_course(db).await; - let subject = crate::db::subject::create( - db, - &course, - SubjectName::try_new("topic").unwrap(), - SubjectDescription::try_new("").unwrap(), - ) - .await - .unwrap(); - Homework::create( - &course, - subject.get_id(), - HomeworkTitle::try_new("essay").unwrap(), - None, - crate::domain::timestamp::Timestamp::from_millis(1), - None, - &UserId::from_key("teacher"), - db, - ) - .await - .unwrap() - } - - fn a_file(submission: &HomeworkSubmissionId) -> HomeworkFile { - HomeworkFile::new( - submission, - FileName::try_new("answer.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ) - } - - /// The counter as *stored* — the only witness that the seat and the row - /// moved together, since every other read counts the rows themselves. - async fn stored_count(submission: &HomeworkSubmissionId, db: &Database) -> i64 { - db.query("SELECT VALUE file_count FROM $sub") - .bind(("sub", submission.record())) - .await - .unwrap() - .take::>(0) - .unwrap() - .into_iter() - .next() - .unwrap_or(0) - } - - #[tokio::test] - async fn rows_scope_to_their_submission_gc_and_cap() { - let db = crate::database::init_mem().await.unwrap(); - let hw = a_homework(&db).await; - let homework = hw.get_id().clone(); - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); - // A real submission row, so the GC join through it resolves. - let submission = HomeworkSubmission::upsert(&hw, &user, None, &db) - .await - .unwrap() - .unwrap(); - let sub_a = submission.get_id().clone(); - let sub_b = HomeworkSubmissionId::composite( - &homework, - &UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB"), - ); - - let stored = a_file(&sub_a).insert(&db).await.unwrap().unwrap(); - // Readable under its own submission, invisible under another. - assert!( - HomeworkFile::read_for(stored.get_id(), &sub_a, &db) - .await - .unwrap() - .is_some() - ); - assert!( - HomeworkFile::read_for(stored.get_id(), &sub_b, &db) - .await - .unwrap() - .is_none() - ); - assert_eq!( - HomeworkFile::count_for_submission(&sub_a, &db) - .await - .unwrap(), - 1 - ); - assert_eq!( - stored_count(&sub_a, &db).await, - 1, - "the seat rode with the row" - ); - - // The grader's download scoping: found under its own homework, invisible - // under another — so a teacher can't read it by naming a homework they - // happen to manage. - assert!( - HomeworkFile::read_in_homework(stored.get_id(), &homework, &db) - .await - .unwrap() - .is_some() - ); - assert!( - HomeworkFile::read_in_homework( - stored.get_id(), - &HomeworkId::from_key("01TESTHWBBBBBBBBBBBBBBBBBB"), - &db, - ) - .await - .unwrap() - .is_none() - ); - - // The blob name is collectable for GC before a cascade wipes the rows. - let keys = HomeworkFile::file_keys_for_homework(&homework, &db) - .await - .unwrap(); - assert_eq!(keys, vec![stored.get_file().to_string()]); - - // Fill to the cap, then the 11th is refused. - for _ in 1..MAX_HOMEWORK_FILES_PER_SUBMISSION { - a_file(&sub_a).insert(&db).await.unwrap().unwrap(); - } - assert!(matches!( - a_file(&sub_a).insert(&db).await, - Err(AppError::Conflict(_)) - )); - // The refusal wrote nothing at all: neither a row nor a seat. - assert_eq!( - HomeworkFile::count_for_submission(&sub_a, &db) - .await - .unwrap() as i64, - stored_count(&sub_a, &db).await, - ); - assert_eq!( - stored_count(&sub_a, &db).await, - MAX_HOMEWORK_FILES_PER_SUBMISSION as i64 - ); - } - - /// A graded submission takes no more files and gives none up — decided by - /// the same conditional write that claims the file slot, so no - /// `homework_result` read stands between the check and the write. - /// - /// Bite check: drop [`SUBMISSION_OPEN_GUARD`] from `insert`'s - /// [`cap::claim_when_and_create`] and the add below lands; drop it from - /// `delete`'s gate and the delete below succeeds. - #[tokio::test] - async fn a_grade_freezes_the_files_too() { - use crate::domain::homework_result::{HomeworkResult, HomeworkStatus}; - - let db = crate::database::init_mem().await.unwrap(); - let hw = a_homework(&db).await; - let homework = hw.get_id().clone(); - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); - let submission = HomeworkSubmission::upsert(&hw, &user, None, &db) - .await - .unwrap() - .unwrap(); - let sub = submission.get_id().clone(); - let stored = a_file(&sub).insert(&db).await.unwrap().unwrap(); - - HomeworkResult::grade( - &homework, - &user, - HomeworkStatus::try_new("done").unwrap(), - None, - &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), - &db, - ) - .await - .unwrap(); - - // Neither adding nor removing an attachment: `None` is the freeze, and - // the cap's own `Err(Conflict)` stays distinct from it. - assert!(a_file(&sub).insert(&db).await.unwrap().is_none()); - assert!(stored.clone().delete(&db).await.unwrap().is_none()); - assert_eq!( - HomeworkFile::count_for_submission(&sub, &db).await.unwrap(), - 1, - "the graded submission keeps exactly the files it was graded on" - ); - // Refused by the *guard*, not the cap (nine seats free) — and still no - // seat moved, so the counter matches the rows. - assert_eq!(stored_count(&sub, &db).await, 1); - // The refused add took no slot either, so un-grading gives back a - // submission with room, not one that silently lost nine. - HomeworkResult::remove(&homework, &user, &db).await.unwrap(); - for _ in 1..MAX_HOMEWORK_FILES_PER_SUBMISSION { - a_file(&sub).insert(&db).await.unwrap().unwrap(); - } - assert!(stored.delete(&db).await.unwrap().is_some()); - } } diff --git a/src/domain/homework_result.rs b/src/domain/homework_result.rs index 80ffb12..f6a0f8d 100644 --- a/src/domain/homework_result.rs +++ b/src/domain/homework_result.rs @@ -5,25 +5,22 @@ //! and there is exactly one grade per (homework, user) by construction. //! //! A stored result is what *freezes* a submission: while a grade exists the -//! student's submission and files are locked (the web layer answers 409), until -//! the teacher removes the grade to reopen them. The teacher-set `missing` -//! status is a deliberate verdict, distinct from the roster's *computed* -//! "missing" (unsubmitted past due) — the latter is derived in the web layer, -//! never stored. +//! student's submission and files are locked (the web layer answers 409), +//! until the teacher removes the grade to reopen them. The teacher-set +//! `missing` status is a deliberate verdict, distinct from the roster's +//! *computed* "missing" (unsubmitted past due) — the latter is derived in the +//! web layer, never stored. The grade transaction lives in +//! [`crate::db::homework_result`], the grading gates in +//! [`crate::service::homework_result`]. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ - HOMEWORK_RESULT_TABLE, MARKS_GIVEN_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD, -}; -use crate::database::{Database, transaction_with_retry}; -use crate::domain::course::CourseId; +use crate::constant::HOMEWORK_RESULT_TABLE; use crate::domain::exam_result::Mark; use crate::domain::homework::HomeworkId; -use crate::domain::homework_submission::HomeworkSubmissionId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::validate_homework_status; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -78,13 +75,13 @@ impl HomeworkStatus { #[derive(Debug, Clone, SurrealValue)] pub struct HomeworkResult { - id: HomeworkResultId, - homework: HomeworkId, - user: UserId, - status: HomeworkStatus, - mark: Option, - graded_by: UserId, - created_at: Timestamp, + pub(crate) id: HomeworkResultId, + pub(crate) homework: HomeworkId, + pub(crate) user: UserId, + pub(crate) status: HomeworkStatus, + pub(crate) mark: Option, + pub(crate) graded_by: UserId, + pub(crate) created_at: Timestamp, } impl HomeworkResult { @@ -116,250 +113,6 @@ impl HomeworkResult { pub fn get_created_at(&self) -> Timestamp { self.created_at } - - /// Record (or overwrite) the grade for (homework, user). One row per pair, - /// keyed by the deterministic composite id, so this is a single atomic - /// UPSERT — concurrent grades for the same pair converge on one row instead - /// of racing a unique index into a 500. Grading before the due date, or - /// before any submission exists, is allowed (the caller's policy call). - /// - /// In the same transaction the grade *stamps* the student's submission - /// ([`crate::constant::SUBMISSION_GRADED_FIELD`]), which is what freezes it: - /// every student-side write to that row then fails its own - /// `graded_by_result = NONE` condition, with no cross-table read for a - /// concurrent write to slip past. A submission that does not exist yet is - /// left alone — grading absent work must not conjure a hand-in (the report reads - /// `submitted`/`missing`/`late` straight off that row). - /// - /// That one case is where this function stops defending itself: a student's - /// *first* hand-in committing between this grade and nothing-to-stamp would - /// land unstamped, leaving a grade beside an editable submission. Nothing - /// here forbids it — what forbids it is the caller. Grading holds - /// `HOMEWORK_LOCK` (see `crate::web::homework`) for writing across this - /// whole transaction while every student-side write holds it for reading across - /// its own, and the two leases are mutually exclusive in the one process - /// this backend runs as, so the interleaving never gets a window. - // - // corner-cut: that makes the freeze depend on lock discipline at the call - // sites, not on this row. Moving a student write's lease to *after* its - // database write — or sharding HOMEWORK_LOCK per homework — reopens the - // window with nothing to catch it. Closing it in the domain layer needs a - // record both sides own (a per-(homework, user) row the grade can always - // stamp); a tombstone submission is not it, since every read path would - // have to learn to ignore it and one missed filter fabricates a hand-in. - pub async fn grade( - homework: &HomeworkId, - user: &UserId, - status: HomeworkStatus, - mark: Option, - graded_by: &UserId, - db: &Database, - ) -> Result { - let id = HomeworkResultId::composite(homework, user); - let submission = HomeworkSubmissionId::composite(homework, user); - let result = HomeworkResult { - id: id.clone(), - homework: homework.clone(), - user: user.clone(), - status, - mark, - graded_by: graded_by.clone(), - created_at: Timestamp::now(), - }; - // Whether the pair was already graded is read one statement ahead of - // the write, inside the same transaction — it is what keeps a regrade - // from crediting the grader a second time. No mark counter here: a - // homework mark is optional and most grades are status-only, so - // `high_mark` is an exam-only family. - // - // The first three statements are the parent gate, the twin of - // [`crate::domain::homework_submission::HomeworkSubmission::upsert`]'s - // and written the same way on purpose: the id is deterministic, so a - // grade landing inside a homework (or course) delete's window does not - // fail — it *re-creates* a result row under a homework that is gone, - // readable ever after at `GET /homework/{id}/result` (no existence check - // there) with a `marks_given_total` no ungrade can reach, because every - // route to the grade goes through the homework. Reading the homework - // first — which the web layer does, under the lease — cannot close that: - // the store conflict-checks write sets, not read sets. So the gate - // *moves* a value on the homework row (`due_at` up by one and straight - // back to the captured value, leaving the row byte-identical) and the - // cascade's delete of that same row is what refuses it. `homework` owns - // no counter column and is SCHEMAFULL, so `due_at` is the one `int` it - // already has; do not invent a second spelling. - // - // Not [`crate::db::cap::touch_and_create`], which is the same shape - // for a bare `CREATE`: a grade is an UPSERT (a regrade must overwrite), - // and the freeze stamp and the grader's counter have to ride the same - // transaction, which that helper has no room for. - // - // Sound to re-send, which is what the gate needed first — a `THROW` - // inside a plain `db.query` would have turned every lost round into a - // 500. `SELECT`, `UPDATE` and the `IF`/`THROW` can never answer "already - // exists", and the `UPSERT`'s id is bijective with the (homework, user) - // pair the table keys, on a table whose only index is non-unique - // (`homework_result_homework`), so its index entry can only ever point - // at the row the id already names: it resolves onto that row instead of - // colliding with it. A lost round wrote nothing. - let (mut saved, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $was_due = (SELECT VALUE due_at FROM ONLY $hw); - LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id); - IF array::len($alive) = 0 {{ THROW 'no_homework' }}; - UPDATE $hw SET due_at = $was_due; - LET $before = (SELECT VALUE id FROM ONLY $id); - LET $after = (UPSERT $id CONTENT $row RETURN AFTER); - UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = $id \ - WHERE {SUBMISSION_OPEN_GUARD}; - IF $before = NONE {{ - UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = - ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1 - }}; - RETURN $after; - COMMIT TRANSACTION;" - ), - &[ - ("hw".into(), homework.record().into_value()), - ("id".into(), id.record().into_value()), - ("sub".into(), submission.record().into_value()), - ("grader".into(), graded_by.record().into_value()), - ("row".into(), result.into_value()), - ], - &["no_homework"], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_homework")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`, - // so its slot follows the statement count instead of a hand-kept - // number — which the gate above would otherwise have shifted, silently - // handing back something else. - let slot = saved.num_statements().saturating_sub(2); - saved - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to record homework result".into())) - } - - /// `user`'s grade for `homework`, if graded. - pub async fn read_for( - homework: &HomeworkId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - Ok(db - .select(HomeworkResultId::composite(homework, user).record()) - .await?) - } - - /// Every grade for `homework` — the roster joins these onto the submissions. - pub async fn list_for_homework( - homework: &HomeworkId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM homework_result WHERE homework = $hw ORDER BY id DESC") - .bind(("hw", homework.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// `user`'s homework grades across one course — the raw rows behind the - /// per-course block of a homework report. Mirrors - /// `ExamResult::list_for_user_in_course`. - pub async fn list_for_user_in_course( - course: &CourseId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM homework_result WHERE user = $usr - AND homework IN (SELECT VALUE id FROM homework WHERE course = $course) - ORDER BY id DESC", - ) - .bind(("usr", user.record())) - .bind(("course", course.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Un-grade (homework, user), returning the removed row (`None` if there - /// was none). Removing the grade unfreezes the student's submission, so the - /// stamp [`grade`](Self::grade) left on it is cleared in the same - /// transaction — scoped to *this* grade's id, so it can never wipe a stamp a - /// concurrent re-grade has just written. - /// - /// The grader's `marks_given_total` comes back with it, in that same - /// transaction and only when a row was really deleted. [`grade`](Self::grade) - /// credits on the branch that finds no row, and a deleted row *is* no row: - /// left standing, ungrade-then-regrade credited a second time off one - /// stored grade, and looped it minted a badge with no exam, no mark and no - /// submission behind it — permanently, since an award is never revoked. - /// Given back to the *removed row's own* grader, not the caller: a manager - /// may un-grade what a teacher graded, and the credit is the teacher's. - /// - /// Sound to re-send while the store answers "conflict, retry" — this is the - /// upgrade `grade` still wants, taken here because the counter above is what - /// makes it necessary: the grader's row is written by exam grading too, so - /// the delete now contends with another domain, and only `DELETE`/`UPDATE` - /// are in the batch, none of which can legitimately answer "already exists". - pub async fn remove( - homework: &HomeworkId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let id = HomeworkResultId::composite(homework, user); - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $gone = (DELETE $id RETURN BEFORE); - UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = NONE \ - WHERE {SUBMISSION_GRADED_FIELD} = $id; - IF array::len($gone) > 0 {{ - LET $grader = $gone[0].graded_by; - UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = - math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0]) - }}; - RETURN $gone; - COMMIT TRANSACTION;" - ), - &[ - ("id".into(), id.record().into_value()), - ( - "sub".into(), - HomeworkSubmissionId::composite(homework, user) - .record() - .into_value(), - ), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`, so - // its slot follows the statement count — the hand-kept "slot 1" this - // replaces was one added statement away from handing back the unstamp. - let slot = result.num_statements().saturating_sub(2); - Ok(result.take::>(slot)?.into_iter().next()) - } } #[cfg(test)] @@ -368,38 +121,6 @@ mod tests { use crate::constant::HOMEWORK_STATUSES; use surrealdb::types::Value; - /// A real homework row (with the course and subject it needs): the grade now - /// carries a parent gate, so a minted id nothing wrote is a `404` here, the - /// same way it already is for a submission. - async fn a_homework(db: &Database) -> HomeworkId { - use crate::domain::homework::{Homework, HomeworkTitle}; - use crate::domain::subject::{SubjectDescription, SubjectName}; - - let course = crate::db::course::a_test_course(db).await; - let subject = crate::db::subject::create( - db, - &course, - SubjectName::try_new("topic").unwrap(), - SubjectDescription::try_new("").unwrap(), - ) - .await - .unwrap(); - Homework::create( - &course, - subject.get_id(), - HomeworkTitle::try_new("essay").unwrap(), - None, - Timestamp::from_millis(1), - None, - &UserId::from_key("teacher"), - db, - ) - .await - .unwrap() - .get_id() - .clone() - } - #[tokio::test] async fn status_is_held_to_the_const_and_stores_as_a_bare_string() { // Enforcement lives in the newtype against HOMEWORK_STATUSES (the DDL @@ -413,167 +134,4 @@ mod tests { assert!(HomeworkStatus::try_new("late").is_err()); assert!(HomeworkStatus::try_new("").is_err()); } - - #[tokio::test] - async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() { - let db = crate::database::init_mem().await.unwrap(); - let homework = a_homework(&db).await; - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); - - let first = HomeworkResult::grade( - &homework, - &user, - HomeworkStatus::try_new("incomplete").unwrap(), - None, - &teacher, - &db, - ) - .await - .unwrap(); - // A regrade lands on the same row (composite id), overwriting the grade. - let second = HomeworkResult::grade( - &homework, - &user, - HomeworkStatus::try_new("done").unwrap(), - Some(Mark::try_new(80).unwrap()), - &teacher, - &db, - ) - .await - .unwrap(); - assert_eq!(first.get_id(), second.get_id()); - assert_eq!(second.get_status().as_str(), "done"); - assert_eq!(second.get_mark().unwrap().as_i64(), 80); - assert_eq!( - HomeworkResult::list_for_homework(&homework, &db) - .await - .unwrap() - .len(), - 1 - ); - - assert!( - HomeworkResult::read_for(&homework, &user, &db) - .await - .unwrap() - .is_some() - ); - assert!( - HomeworkResult::remove(&homework, &user, &db) - .await - .unwrap() - .is_some() - ); - assert!( - HomeworkResult::read_for(&homework, &user, &db) - .await - .unwrap() - .is_none() - ); - } - - /// The grader is credited once per graded pair: a regrade lands on the same - /// row, so it is not a mark given twice. The student's counters are not - /// touched at all — a homework grade is not a homework submission. - #[tokio::test] - async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() { - let db = crate::database::init_mem().await.unwrap(); - let homework = a_homework(&db).await; - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); - // `UPDATE` writes nothing to a user row that does not exist. - db.query("CREATE $usr SET username = 't', password_hash = 'x'") - .bind(("usr", teacher.record())) - .await - .unwrap() - .check() - .unwrap(); - - for status in ["incomplete", "done"] { - HomeworkResult::grade( - &homework, - &user, - HomeworkStatus::try_new(status).unwrap(), - None, - &teacher, - &db, - ) - .await - .unwrap(); - } - assert_eq!( - marks_given(&teacher, &db).await, - 1, - "one graded pair, one mark given" - ); - } - - /// Un-grading gives the credit back, so grade → ungrade → regrade nets to - /// one however often it is run. Crediting the grade without refunding the - /// delete was the cheapest counter farm in the codebase — two requests per - /// mark given, with no exam, no mark and no submission behind them. - #[tokio::test] - async fn ungrading_gives_the_grader_credit_back() { - let db = crate::database::init_mem().await.unwrap(); - let homework = a_homework(&db).await; - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); - db.query("CREATE $usr SET username = 't', password_hash = 'x'") - .bind(("usr", teacher.record())) - .await - .unwrap() - .check() - .unwrap(); - - for _ in 0..3 { - HomeworkResult::grade( - &homework, - &user, - HomeworkStatus::try_new("missing").unwrap(), - None, - &teacher, - &db, - ) - .await - .unwrap(); - assert_eq!(marks_given(&teacher, &db).await, 1); - assert!( - HomeworkResult::remove(&homework, &user, &db) - .await - .unwrap() - .is_some(), - "the grade was there" - ); - assert_eq!(marks_given(&teacher, &db).await, 0, "the loop kept one"); - } - - // Nothing to remove is nothing to give back — the floor holds. - assert!( - HomeworkResult::remove(&homework, &user, &db) - .await - .unwrap() - .is_none() - ); - assert_eq!(marks_given(&teacher, &db).await, 0); - } - - /// The grader's badge counter, re-read out of the store. - async fn marks_given(user: &UserId, db: &Database) -> i64 { - let mut result = db - .query(format!( - "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $usr" - )) - .bind(("usr", user.record())) - .await - .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .into_iter() - .next() - .unwrap_or(0) - } } diff --git a/src/domain/homework_submission.rs b/src/domain/homework_submission.rs index 76cac33..15f2b58 100644 --- a/src/domain/homework_submission.rs +++ b/src/domain/homework_submission.rs @@ -5,24 +5,22 @@ //! UPSERT. //! //! `submitted_at` — the first-submit stamp — is `READONLY` and survives every -//! re-submit; [`HomeworkSubmission::upsert`] preserves it inside one statement -//! rather than through `.content()`, see there. `updated_at` moves to now on -//! every (re-)submit (and, later, on a file add/delete) and drives the computed -//! "late" flag (`updated_at > homework.due_at`, judged in the web layer, never -//! stored): `submitted_at` answers "was the first hand-in on time", `updated_at` -//! "was it touched after the deadline". +//! re-submit; [`crate::db::homework_submission::upsert`] preserves it inside one +//! statement rather than through `.content()`, see there. `updated_at` moves to +//! now on every (re-)submit (and, later, on a file add/delete) and drives the +//! computed "late" flag (`updated_at > homework.due_at`, judged in the web +//! layer, never stored): `submitted_at` answers "was the first hand-in on +//! time", `updated_at` "was it touched after the deadline". The row writes +//! live in [`crate::db::homework_submission`], the submit/withdraw workflows +//! in [`crate::service::homework_submission`]. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ - HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMISSION_TABLE, HOMEWORK_SUBMITTED_TOTAL_FIELD, - MAX_HOMEWORK_TEXT_LEN, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD, -}; -use crate::database::{Database, transaction_with_retry}; -use crate::domain::homework::{Homework, HomeworkId}; +use crate::constant::{HOMEWORK_SUBMISSION_TABLE, MAX_HOMEWORK_TEXT_LEN}; +use crate::domain::homework::HomeworkId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::validate_optional; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -70,12 +68,12 @@ impl SubmissionText { #[derive(Debug, Clone, SurrealValue)] pub struct HomeworkSubmission { - id: HomeworkSubmissionId, - homework: HomeworkId, - user: UserId, - text: Option, - submitted_at: Timestamp, - updated_at: Timestamp, + pub(crate) id: HomeworkSubmissionId, + pub(crate) homework: HomeworkId, + pub(crate) user: UserId, + pub(crate) text: Option, + pub(crate) submitted_at: Timestamp, + pub(crate) updated_at: Timestamp, } impl HomeworkSubmission { @@ -102,743 +100,16 @@ impl HomeworkSubmission { pub fn get_updated_at(&self) -> Timestamp { self.updated_at } - - /// Create or re-stamp `user`'s submission to `homework`, unless a grade has - /// frozen it — `None` means frozen, and the caller answers 409. `updated_at` - /// moves to now every time; `submitted_at` (readonly, the first-submit stamp) - /// is kept on an existing row and set only on a fresh one. - /// - /// Hand-written rather than `.content()` on purpose: `.content()` re-sends - /// the whole row, so it would carry a `submitted_at`, and any value differing - /// from the stored one trips the readonly guard. The - /// `submitted_at = submitted_at ?? $now` expression preserves it inside the - /// one UPSERT statement — race-free without a lock, where a read-then-content - /// could let two concurrent first-submits pick different stamps and 500. - /// - /// The `WHERE` is the freeze: [`SUBMISSION_OPEN_GUARD`] makes "not graded - /// yet" a condition of this very write instead of a read a concurrent grade - /// can land behind. An absent row satisfies it (the stamp is `NONE` there - /// too), so a first submit still creates. - /// - /// The badge counters on the student's user row move in this very - /// transaction, and the order is load-bearing: the increment sits *after* - /// the UPSERT and is conditional on it having matched a row, because a - /// frozen row makes that `WHERE` match nothing **silently** (unlike - /// [`crate::domain::exam_result::ExamResult::grade`], which `THROW`s) — put - /// first, it would count a submission the freeze refused. `$before = NONE` - /// keeps it to a genuine first create, so an edit moves neither counter, - /// which is what makes the live count mean the same thing the one-time - /// backfill seeded (one per row; on time judged against `due_at`, equal - /// counting as on time). - /// - /// `counted_on_time` is stamped on the row from the *same* `$on_time` - /// expression the increment adds, in the same statement block: the deadline - /// is mutable, so a withdrawal that re-judged it against the live `due_at` - /// gave back something other than what was taken. Writing the verdict beside - /// the counter is what keeps the two from ever disagreeing — read back by - /// [`HomeworkSubmission::delete`], never re-derived. - /// - /// That deadline is `$was_due`, the one the gate below already read *inside - /// this transaction* — never the caller's [`Homework`] snapshot, which was - /// read before the lease and is exactly one `PATCH due_at` old in the - /// "teacher extends the deadline at 23:59 while the class submits" moment. - /// Judging on the snapshot stored a verdict the web layer's own `late` flag - /// (`updated_at > due_at`, re-derived live on every read) then contradicted - /// forever, in both directions. An in-process lock cannot fix this — it - /// orders two handlers, not two store transactions — so the comparison has - /// to live where the write does. The whole entity is still taken (both - /// callers hold the row, and the id comes off it); its `due_at` must not be. - /// - /// The first three statements are the parent gate, and they are why this - /// write cannot outlive its homework: the id is deterministic, so nothing - /// else here would fail against a homework a cascade already removed — it - /// would simply re-create the row, badge counters and all, unreachable ever - /// after (every route to a submission goes through its homework). A *read* - /// of the homework does not close that, on either side of the call: the - /// store does no read-set conflict detection, so a delete committing - /// alongside is invisible to it. The gate therefore *moves* a value on the - /// homework row — `due_at` up by one and straight back to the captured - /// value, so the row is byte-identical afterwards — because only a write - /// collides, and `SET x = x` is elided and never reaches the write set. It - /// is [`crate::domain::exam_answer::ExamAnswer::save`]'s shape exactly. - /// `Err(NotFound)` means the homework is gone, which is the 404 the web - /// layer's own lookup would have answered. - pub async fn upsert( - homework: &Homework, - user: &UserId, - text: Option, - db: &Database, - ) -> Result, AppError> { - let id = HomeworkSubmissionId::composite(homework.get_id(), user); - let now = Timestamp::now(); - let text = text.map(|text| text.as_str().to_string()); - // Sound to re-send: the UPSERT is on a deterministic id on a table with - // no unique index, so it can never legitimately answer "already exists", - // and the counter UPDATEs never can either. - let (mut saved, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $was_due = (SELECT VALUE due_at FROM ONLY $hw); - LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id); - IF array::len($alive) = 0 {{ THROW 'no_homework' }}; - UPDATE $hw SET due_at = $was_due; - LET $before = (SELECT VALUE id FROM ONLY $id); - LET $on_time = $now <= $was_due; - LET $after = (UPSERT $id SET homework = $hw, user = $usr, text = $text, - updated_at = $now, submitted_at = submitted_at ?? $now - WHERE {SUBMISSION_OPEN_GUARD} RETURN AFTER); - IF $before = NONE AND array::len($after) > 0 {{ - UPDATE $id SET counted_on_time = $on_time; - UPDATE $usr SET - {HOMEWORK_SUBMITTED_TOTAL_FIELD} = ({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) + 1, - {HOMEWORK_ON_TIME_TOTAL_FIELD} = ({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) - + IF $on_time {{ 1 }} ELSE {{ 0 }} - }}; - RETURN $after; - COMMIT TRANSACTION;" - ), - &[ - ("id".into(), id.record().into_value()), - ("hw".into(), homework.get_id().record().into_value()), - ("usr".into(), user.record().into_value()), - ("text".into(), text.into_value()), - ("now".into(), now.into_value()), - ], - &["no_homework"], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_homework")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`, so - // its slot follows the statement count rather than a hand-kept number. - // It returns the whole array, never `$after[0]`: a refused write makes - // that `NONE`, which fails to deserialize ("expected object, got none") - // instead of reading as the "frozen" the caller answers 409 to. - let slot = saved.num_statements().saturating_sub(2); - Ok(saved - .take::>(slot)? - .into_iter() - .next()) - } - - /// Re-stamp a submission's `updated_at` to now, leaving its text and files - /// alone. A file add or delete modifies the submission as a whole, so its - /// "last touched" clock — which drives the computed late flag — must move - /// even though the text row is unchanged. Static because the file paths hold - /// the composite id, not always the row. A targeted single-field UPDATE, so - /// the `READONLY` `submitted_at` is never re-sent (a `.content()` would trip - /// its guard). Returns the re-stamped row, or a 404 if it has since vanished. - pub async fn touch( - id: &HomeworkSubmissionId, - db: &Database, - ) -> Result { - let now = Timestamp::now(); - let mut result = db - .query("UPDATE $id SET updated_at = $now RETURN AFTER") - .bind(("id", id.record())) - .bind(("now", now)) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) - } - - /// Whether a grade has frozen this submission. Only ever read to tell two - /// refusals apart *after* a conditional write has already refused one — the - /// stamp on the row, never this read, is what decides. - pub async fn is_graded(id: &HomeworkSubmissionId, db: &Database) -> Result { - let mut result = db - .query(format!( - "SELECT VALUE id FROM $id WHERE {SUBMISSION_GRADED_FIELD} != NONE" - )) - .bind(("id", id.record())) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) - } - - /// `user`'s submission to `homework`, if they have one. - pub async fn read_for( - homework: &HomeworkId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - Ok(db - .select(HomeworkSubmissionId::composite(homework, user).record()) - .await?) - } - - /// Every submission to `homework`, in student (composite-id) order — the - /// roster's raw rows. - pub async fn list_for_homework( - homework: &HomeworkId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM homework_submission WHERE homework = $hw ORDER BY id ASC") - .bind(("hw", homework.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Delete this submission and its files in one transaction — so a crash - /// can't leave a file pointing at a vanished submission. The file *blobs* - /// are the web layer's to unlink: it lists them - /// ([`crate::domain::homework_file::HomeworkFile::list_for_submission`]) - /// before calling this. `None` means a grade froze the row (the caller - /// answers 409): the submission's own delete carries - /// [`SUBMISSION_OPEN_GUARD`], and the file wipe is conditional on it having - /// bitten, so a refused delete leaves the children standing too. - /// - /// The one place either badge counter comes back down, and deliberately the - /// only one: this route is student-callable on their own row, so without it - /// a student farms "handed in 50 homeworks" by submit/delete/submit on a - /// single homework. A teacher's homework delete and the course cascade - /// leave the counters alone — history a teacher erased is still history the - /// student lived. - /// - /// The on-time half is given back by the verdict [`HomeworkSubmission::upsert`] - /// *stored* on the row, never by re-judging the deadline: `due_at` is - /// mutable, so re-deriving read whatever the teacher had moved it to since - /// and gave back something other than what was taken — extend it after a - /// late hand-in and this debited a credit that was never given; pull it back - /// after a punctual one and it debited nothing, leaving `on_time` above - /// `submitted`. A row from before the column exists carries no verdict, and - /// cannot be given one for a credit that already happened, so it falls back - /// to the old cut (`submitted_at`, the readonly stamp the increment judged, - /// against the live deadline); a dangling `homework` link leaves `$due` - /// `NONE` there, which compares false and so counts as late, matching the - /// backfill. Floored at zero: a row that predates the columns has none. - /// - /// Badges already earned are never taken away — [`crate::domain::badge`] is - /// add-only, which is where that permanence lives. - pub async fn delete(self, db: &Database) -> Result, AppError> { - // Sound to re-send: DELETE and UPDATE can never answer "already exists". - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $due = (SELECT VALUE homework.due_at FROM ONLY $sub); - LET $gone = (DELETE $sub WHERE {SUBMISSION_OPEN_GUARD} RETURN BEFORE); - IF array::len($gone) > 0 {{ - DELETE homework_file WHERE submission = $sub; - LET $on_time = IF ($gone[0].counted_on_time - ?? ($gone[0].submitted_at <= $due)) {{ 1 }} ELSE {{ 0 }}; - UPDATE $usr SET - {HOMEWORK_SUBMITTED_TOTAL_FIELD} = - math::max([({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) - 1, 0]), - {HOMEWORK_ON_TIME_TOTAL_FIELD} = - math::max([({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) - $on_time, 0]) - }}; - RETURN $gone; - COMMIT TRANSACTION;" - ), - &[ - ("sub".into(), self.id.record().into_value()), - ("usr".into(), self.user.record().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`. - let slot = result.num_statements().saturating_sub(2); - Ok(result - .take::>(slot)? - .into_iter() - .next()) - } } #[cfg(test)] mod tests { use super::*; - use crate::domain::homework::HomeworkTitle; - use crate::domain::subject::{SubjectDescription, SubjectName}; - - /// A real homework row (and the subject it must reference) due at `due_at` — - /// `upsert` now reads the deadline off the entity, so the tests need one. - async fn a_homework(due_at: Timestamp, db: &Database) -> Homework { - let course = crate::db::course::a_test_course(db).await; - let subject = crate::db::subject::create( - db, - &course, - SubjectName::try_new("topic").unwrap(), - SubjectDescription::try_new("").unwrap(), - ) - .await - .unwrap(); - Homework::create( - &course, - subject.get_id(), - HomeworkTitle::try_new("essay").unwrap(), - None, - due_at, - None, - &UserId::from_key("teacher"), - db, - ) - .await - .unwrap() - } - - /// A deadline no test run can reach, so a submission is unambiguously on - /// time; `Timestamp::from_millis(1)` is its late twin. - fn far_future() -> Timestamp { - Timestamp::from_millis(Timestamp::now().as_millis() + 3_600_000) - } - - /// A real user row: the counters live on it, and an `UPDATE` has nothing to - /// write to without one. - async fn a_student(username: &str, db: &Database) -> UserId { - let hash = crate::domain::user::Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(); - crate::db::user::create( - db, - crate::domain::user::Username::try_new(username).unwrap(), - hash, - ) - .await - .unwrap() - .get_id() - .clone() - } - - /// Move the stored deadline the way a teacher's PATCH does, leaving the - /// caller's `homework` snapshot untouched — the stale-snapshot shape the - /// handler produces when a `PATCH due_at` commits between its gate read and - /// its write. - async fn deadline_moves_to(homework: &Homework, due_at: Timestamp, db: &Database) { - Homework::read(homework.get_id(), db) - .await - .unwrap() - .expect("the homework exists") - .update(None, None, None, Some(due_at), None, db) - .await - .unwrap(); - } - - /// The verdict `upsert` stored on the row — what `delete` debits off. - /// `None` is a row from before the column existed. - async fn stored_verdict(id: &HomeworkSubmissionId, db: &Database) -> Option { - let mut result = db - .query("SELECT VALUE counted_on_time FROM $sub") - .bind(("sub", id.record())) - .await - .unwrap() - .check() - .unwrap(); - result - .take::>>(0) - .unwrap() - .into_iter() - .flatten() - .next() - } - - /// The web layer's computed flag, exactly as `SubmissionResponse::new` - /// derives it (`src/web/homework.rs`): `updated_at` against the *live* - /// deadline, re-read here because that is what a later GET reads. - async fn late_flag(submission: &HomeworkSubmission, db: &Database) -> bool { - let live = Homework::read(submission.get_homework(), db) - .await - .unwrap() - .expect("the homework exists"); - submission.get_updated_at() > live.get_due_at() - } - - /// The two badge counters on a user row, absent counting as zero. - async fn counters(user: &UserId, db: &Database) -> (i64, i64) { - let mut result = db - .query(format!( - "SELECT VALUE [({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0), - ({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0)] FROM $usr" - )) - .bind(("usr", user.record())) - .await - .unwrap() - .check() - .unwrap(); - let rows = result.take::>>(0).unwrap(); - let row = rows.first().cloned().unwrap_or_default(); - ( - row.first().copied().unwrap_or(0), - row.get(1).copied().unwrap_or(0), - ) - } - #[tokio::test] async fn text_is_optional_but_bounded() { assert!(SubmissionText::try_new("").is_ok()); assert!(SubmissionText::try_new(&"x".repeat(5_000)).is_ok()); assert!(SubmissionText::try_new(&"x".repeat(5_001)).is_err()); } - - #[tokio::test] - async fn resubmit_keeps_submitted_at_and_restamps_updated_at() { - let db = crate::database::init_mem().await.unwrap(); - let homework = a_homework(far_future(), &db).await; - let user = a_student("ogrenci", &db).await; - - let first = HomeworkSubmission::upsert( - &homework, - &user, - Some(SubmissionText::try_new("draft").unwrap()), - &db, - ) - .await - .unwrap() - .unwrap(); - // A re-submit lands on the same row: submitted_at (the first hand-in) - // pinned, updated_at moves forward, and the text can be cleared. - let second = HomeworkSubmission::upsert(&homework, &user, None, &db) - .await - .unwrap() - .unwrap(); - // ... and it is one submission, not two: the edit moves no counter. - assert_eq!(counters(&user, &db).await, (1, 1)); - assert_eq!(first.get_id(), second.get_id()); - assert_eq!(first.get_submitted_at(), second.get_submitted_at()); - assert!(second.get_updated_at() >= first.get_updated_at()); - assert!(second.get_text().is_none()); - // One row per (homework, user), whatever the re-submit count. - assert_eq!( - HomeworkSubmission::list_for_homework(homework.get_id(), &db) - .await - .unwrap() - .len(), - 1 - ); - } - - /// The freeze, as stored state rather than as a race: the grade stamps the - /// submission row, and from then on the submission's own writes fail their - /// condition — no read of `homework_result` involved, which is what makes it - /// hold when the grade lands mid-request. Un-grading clears the stamp - /// and the row is writable again. - /// - /// Bite check: drop `WHERE graded_by_result = NONE` from - /// [`HomeworkSubmission::upsert`] and the "version B" upsert below comes - /// back `Some` — the exact swap this guards against. - #[tokio::test] - async fn a_grade_freezes_the_submission_row_itself() { - let db = crate::database::init_mem().await.unwrap(); - let homework = a_homework(far_future(), &db).await; - let user = a_student("ogrenci", &db).await; - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); - let graded = |value| { - let text = SubmissionText::try_new(value).unwrap(); - HomeworkSubmission::upsert(&homework, &user, Some(text), &db) - }; - - let version_a = graded("version A").await.unwrap().unwrap(); - assert!( - !HomeworkSubmission::is_graded(version_a.get_id(), &db) - .await - .unwrap() - ); - - assert_eq!(counters(&user, &db).await, (1, 1)); - - crate::domain::homework_result::HomeworkResult::grade( - homework.get_id(), - &user, - crate::domain::homework_result::HomeworkStatus::try_new("done").unwrap(), - None, - &teacher, - &db, - ) - .await - .unwrap(); - assert!( - HomeworkSubmission::is_graded(version_a.get_id(), &db) - .await - .unwrap() - ); - - // The swap the teacher would never see: refused, and the stored text is - // still the version that was graded. - assert!(graded("version B").await.unwrap().is_none()); - assert_eq!( - HomeworkSubmission::read_for(homework.get_id(), &user, &db) - .await - .unwrap() - .and_then(|row| row.get_text().map(|text| text.as_str().to_string())), - Some("version A".to_string()) - ); - // The refusal is silent — the UPSERT simply matches nothing — so the - // counters are the only thing that can catch an increment placed in - // front of it: a submission the freeze refused must count for nothing. - assert_eq!(counters(&user, &db).await, (1, 1)); - // ... and so is withdrawing it wholesale. - let frozen = HomeworkSubmission::read_for(homework.get_id(), &user, &db) - .await - .unwrap() - .unwrap(); - assert!(frozen.delete(&db).await.unwrap().is_none()); - assert!( - HomeworkSubmission::read_for(homework.get_id(), &user, &db) - .await - .unwrap() - .is_some() - ); - // A refused delete decrements nothing either. - assert_eq!(counters(&user, &db).await, (1, 1)); - - // Un-grading unfreezes it, stamp and all. - crate::domain::homework_result::HomeworkResult::remove(homework.get_id(), &user, &db) - .await - .unwrap(); - assert!( - !HomeworkSubmission::is_graded(version_a.get_id(), &db) - .await - .unwrap() - ); - let reopened = graded("version B").await.unwrap().unwrap(); - assert_eq!( - reopened.get_text().map(SubmissionText::as_str), - Some("version B") - ); - // Still an edit to the row that was already counted, un-freeze or not. - assert_eq!(counters(&user, &db).await, (1, 1)); - // The two-stamp lateness rule is untouched by any of it: the first - // hand-in is still the first hand-in. - assert_eq!(reopened.get_submitted_at(), version_a.get_submitted_at()); - assert!(reopened.get_updated_at() >= version_a.get_updated_at()); - } - - #[tokio::test] - async fn touch_moves_updated_at_but_not_submitted_at_or_text() { - let db = crate::database::init_mem().await.unwrap(); - let homework = a_homework(far_future(), &db).await; - let user = a_student("ogrenci", &db).await; - - let original = HomeworkSubmission::upsert( - &homework, - &user, - Some(SubmissionText::try_new("photo answer").unwrap()), - &db, - ) - .await - .unwrap() - .unwrap(); - // A file add/delete touches the submission: updated_at moves (never - // backwards), while the first-submit stamp and the text stay put. - let touched = HomeworkSubmission::touch(original.get_id(), &db) - .await - .unwrap(); - assert_eq!(touched.get_submitted_at(), original.get_submitted_at()); - assert!(touched.get_updated_at() >= original.get_updated_at()); - assert_eq!( - touched.get_text().map(SubmissionText::as_str), - Some("photo answer") - ); - } - - /// The farm, closed: `delete_submission` is the student's own route, so a - /// counter that only ever went up would let one homework be handed in fifty - /// times. Submit → withdraw → submit is worth exactly one submission. - /// - /// Bite check: drop the `UPDATE $usr` from [`HomeworkSubmission::delete`] - /// and the last assertion reads `(2, 2)` — the farm. - #[tokio::test] - async fn submit_delete_submit_is_worth_one_submission() { - let db = crate::database::init_mem().await.unwrap(); - let homework = a_homework(far_future(), &db).await; - let user = a_student("ogrenci", &db).await; - - HomeworkSubmission::upsert(&homework, &user, None, &db) - .await - .unwrap() - .unwrap(); - assert_eq!(counters(&user, &db).await, (1, 1)); - - let mine = HomeworkSubmission::read_for(homework.get_id(), &user, &db) - .await - .unwrap() - .unwrap(); - mine.delete(&db).await.unwrap().unwrap(); - assert_eq!(counters(&user, &db).await, (0, 0)); - // Floored: a second withdrawal (or a row from before the columns - // existed) can never push either counter negative. - assert!( - HomeworkSubmission::read_for(homework.get_id(), &user, &db) - .await - .unwrap() - .is_none() - ); - - HomeworkSubmission::upsert(&homework, &user, None, &db) - .await - .unwrap() - .unwrap(); - assert_eq!(counters(&user, &db).await, (1, 1)); - } - - /// Lateness is judged against the homework's own deadline at hand-in, the - /// same cut the one-time backfill used, and only the on-time counter sees - /// it: a late hand-in is still a hand-in. Its withdrawal gives back only - /// what it took. - #[tokio::test] - async fn a_late_submission_counts_as_submitted_but_not_on_time() { - let db = crate::database::init_mem().await.unwrap(); - let punctual = a_homework(far_future(), &db).await; - let overdue = a_homework(Timestamp::from_millis(1), &db).await; - let user = a_student("ogrenci", &db).await; - - HomeworkSubmission::upsert(&punctual, &user, None, &db) - .await - .unwrap() - .unwrap(); - HomeworkSubmission::upsert(&overdue, &user, None, &db) - .await - .unwrap() - .unwrap(); - assert_eq!(counters(&user, &db).await, (2, 1)); - - // Withdrawing the *late* one takes back only the submission, never the - // on-time credit the punctual one earned — the zero floor would hide a - // wrong subtraction here if the on-time count were sitting at zero. - let late = HomeworkSubmission::read_for(overdue.get_id(), &user, &db) - .await - .unwrap() - .unwrap(); - late.delete(&db).await.unwrap().unwrap(); - assert_eq!(counters(&user, &db).await, (1, 1)); - - // ... and withdrawing the punctual one gives back exactly that credit. - let kept = HomeworkSubmission::read_for(punctual.get_id(), &user, &db) - .await - .unwrap() - .unwrap(); - kept.delete(&db).await.unwrap().unwrap(); - assert_eq!(counters(&user, &db).await, (0, 0)); - } - - /// A row from before `counted_on_time` existed carries no verdict — it was - /// credited by a comparison that left no trace, and cannot be given one - /// retroactively. Withdrawing it falls back to that same comparison, so the - /// pre-2026-08-04 rows on a live volume keep behaving exactly as they did. - /// - /// Bite check: an absent verdict read as `false` rather than falling through - /// (`??` binding the wrong side of the `<=`) leaves the last assertion at - /// `(0, 1)` — on time above submitted, the shape the stored verdict exists - /// to prevent. - #[tokio::test] - async fn a_row_with_no_stored_verdict_falls_back_to_the_deadline() { - let db = crate::database::init_mem().await.unwrap(); - let punctual = a_homework(far_future(), &db).await; - let overdue = a_homework(Timestamp::from_millis(1), &db).await; - let user = a_student("ogrenci", &db).await; - - HomeworkSubmission::upsert(&punctual, &user, None, &db) - .await - .unwrap() - .unwrap(); - HomeworkSubmission::upsert(&overdue, &user, None, &db) - .await - .unwrap() - .unwrap(); - assert_eq!(counters(&user, &db).await, (2, 1)); - // Aged into legacy rows: the counters keep the credit, the rows lose the - // verdict — the exact state of every submission on an existing volume. - db.query("UPDATE homework_submission UNSET counted_on_time") - .await - .unwrap() - .check() - .unwrap(); - - let late = HomeworkSubmission::read_for(overdue.get_id(), &user, &db) - .await - .unwrap() - .unwrap(); - late.delete(&db).await.unwrap().unwrap(); - assert_eq!(counters(&user, &db).await, (1, 1)); - - let kept = HomeworkSubmission::read_for(punctual.get_id(), &user, &db) - .await - .unwrap() - .unwrap(); - kept.delete(&db).await.unwrap().unwrap(); - assert_eq!(counters(&user, &db).await, (0, 0)); - } - - /// The stale snapshot, both directions: the teacher's `PATCH due_at` commits - /// between the handler's gate read and its write, so the caller's entity - /// carries a deadline the store no longer has. The verdict must follow the - /// *stored* deadline the write itself reads, because the API's `late` flag - /// is re-derived from that same stored value on every later read — a verdict - /// judged on the snapshot disagrees with it permanently, and `delete` then - /// gives back the wrong credit. - /// - /// Bite check: judge `$on_time` against the caller's `$due` instead of - /// `$was_due` and both halves fail — extended reads `(1, 0)` with a stored - /// `false` against a live `late = false`, pulled reads `(1, 1)` with a - /// stored `true` against a live `late = true`. - #[tokio::test] - async fn a_deadline_moved_under_the_caller_is_judged_by_the_stored_value() { - let db = crate::database::init_mem().await.unwrap(); - let user = a_student("ogrenci", &db).await; - - // Extended at 23:59: the snapshot says the deadline has passed, the - // store says it has not. A hand-in now is on time. - let extended = a_homework(Timestamp::from_millis(1), &db).await; - deadline_moves_to(&extended, far_future(), &db).await; - let landed = HomeworkSubmission::upsert(&extended, &user, None, &db) - .await - .unwrap() - .unwrap(); - assert_eq!(counters(&user, &db).await, (1, 1)); - assert_eq!(stored_verdict(landed.get_id(), &db).await, Some(true)); - assert!(!late_flag(&landed, &db).await); - - // Pulled earlier: the snapshot says there is time left, the store says - // the deadline is gone. The same hand-in is late. - let pulled = a_homework(far_future(), &db).await; - deadline_moves_to(&pulled, Timestamp::from_millis(1), &db).await; - let missed = HomeworkSubmission::upsert(&pulled, &user, None, &db) - .await - .unwrap() - .unwrap(); - assert_eq!(counters(&user, &db).await, (2, 1)); - assert_eq!(stored_verdict(missed.get_id(), &db).await, Some(false)); - assert!(late_flag(&missed, &db).await); - - // The invariant behind both: the stored verdict is the negation of the - // flag the web layer computes for the same submission, never its twin. - for submission in [&landed, &missed] { - assert_eq!( - stored_verdict(submission.get_id(), &db).await, - Some(!late_flag(submission, &db).await), - "stored verdict and the API's late flag must never disagree" - ); - } - - // ... and the withdrawal, which debits off the stamp, gives back exactly - // what each one took. - missed.delete(&db).await.unwrap().unwrap(); - assert_eq!(counters(&user, &db).await, (1, 1)); - landed.delete(&db).await.unwrap().unwrap(); - assert_eq!(counters(&user, &db).await, (0, 0)); - } } diff --git a/src/migration_sql.rs b/src/migration_sql.rs index 2f8e14a..f0cb839 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -703,7 +703,7 @@ pub const MIGRATION: &str = " -- above submitted. `option<>` because every row predating 2026-08-04 has no -- stored verdict and cannot be given one for a credit that already happened: -- those fall back to the old comparison (see - -- [`crate::domain::homework_submission::HomeworkSubmission::delete`]). + -- [`crate::db::homework_submission::delete`]). DEFINE FIELD IF NOT EXISTS counted_on_time ON homework_submission TYPE option; -- The grade that froze this submission, absent while it is still open. The -- freeze used to be a cross-table read (does a homework_result exist?) diff --git a/src/service/course.rs b/src/service/course.rs index 03035ed..19298e8 100644 --- a/src/service/course.rs +++ b/src/service/course.rs @@ -9,7 +9,6 @@ use crate::db::course; use crate::domain::answer_image::AnswerImage; use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; use crate::domain::course_note_file::CourseNoteFile; -use crate::domain::homework_file::HomeworkFile; use crate::domain::question_image::QuestionImage; use crate::domain::role::Role; use crate::domain::term::TermId; @@ -151,7 +150,7 @@ pub struct DeleteOutcome { /// And the homework half of the same cascade, for /// [`crate::web::homework::delete_homework`]'s reason: it sweeps the /// course's homework with its submissions, files and results, and grading -/// ([`crate::domain::homework_result::HomeworkResult::grade`]) writes a +/// ([`crate::db::homework_result::grade`]) writes a /// result row against a homework it only *read*, which a delete committing /// alongside is invisible to. Without this lease the grade lands behind the /// sweep: an orphan `homework_result` under a vanished homework, plus a @@ -165,10 +164,11 @@ pub struct DeleteOutcome { pub async fn delete(db: &Database, course: &Course) -> Result { require_open(db, course).await?; let _guard = crate::service::exam_attempt::EXAM_LOCK.write().await; - let _homework_guard = crate::web::homework::HOMEWORK_LOCK.write().await; + let _homework_guard = crate::service::homework::HOMEWORK_LOCK.write().await; let image_files = QuestionImage::file_keys_for_course(course.get_id(), db).await?; let answer_image_files = AnswerImage::file_keys_for_course(course.get_id(), db).await?; - let homework_files = HomeworkFile::file_keys_for_course(course.get_id(), db).await?; + let homework_files = + crate::db::homework_file::file_keys_for_course(db, course.get_id()).await?; let course_note_files = CourseNoteFile::file_keys_for_course(course.get_id(), db).await?; let deleted = course::delete(db, course.clone()).await?; Ok(DeleteOutcome { diff --git a/src/service/homework.rs b/src/service/homework.rs new file mode 100644 index 0000000..c7f5357 --- /dev/null +++ b/src/service/homework.rs @@ -0,0 +1,274 @@ +//! Homework workflows: the PATCH re-scope with its orphan guard, the +//! cascading delete, and the shared student-side wall +//! ([`gate_own_submission`]) every submission path walks. Row reads and +//! listings pass through to [`crate::db::homework`]; the submission, file, +//! and grade workflows live in the sibling `service::homework_*` modules, +//! whose every locked path leases [`HOMEWORK_LOCK`]. + +use crate::database::Database; +use crate::db::homework; +use crate::db::homework_file; +use crate::db::homework_result; +use crate::db::homework_submission; +use crate::domain::badge; +use crate::domain::course::CourseId; +use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle}; +use crate::domain::homework_result::HomeworkResult; +use crate::domain::homework_submission::HomeworkSubmission; +use crate::domain::role::Role; +use crate::domain::subject::SubjectId; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::{User, UserId}; +use crate::error::AppError; + +/// Serializes the homework subsystem's cross-record check-then-writes, which +/// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as +/// [`crate::service::exam_attempt::EXAM_LOCK`]. Every lease below is held across the +/// database write it guards, so within this one process it does order a full +/// round trip — but the freeze no longer *rests* on that: a graded submission +/// used to stay unedited only because the "no grade yet" read and the write it +/// licensed sat under one lease. That rule now lives in the database too — +/// grading stamps [`crate::constant::SUBMISSION_GRADED_FIELD`] on the +/// submission row and every student-side write carries `graded_by_result = +/// NONE` as its own condition. The one case the stamp cannot cover — grading +/// work with no submission row yet — falls back to the lease pair, so a write +/// lease must never stop spanning its own database call (see +/// [`crate::db::homework_result::grade`]). +/// +/// What still leases it, honestly: +/// - Write: the homework PATCH's orphan guard ([`update`]), the +/// homework-delete cascade ([`delete`]), and grade/ungrade — whose +/// freeze rule (the stamp landing on a submission that may be written in the +/// same instant) is the one thing here still resting on the two leases being +/// mutually exclusive. The *existence* half has left: a grade now moves a +/// value on the homework row inside its own transaction +/// ([`crate::db::homework_result::grade`]), so a +/// concurrent delete refuses it rather than being read around. +/// - Read: the student's submission/file writes, which no longer gate the +/// freeze but still must not land under a PATCH re-scoping the audience out +/// from under them. +/// +/// The subject rule has left: creating a homework and re-tagging one move the +/// subject's reference counter, and the subject delete is refused while that +/// counter is non-zero ([`crate::domain::subject::Subject::delete`]), so +/// neither the create (in `web::courses`) nor the outside writer the subject +/// delete used to take is on this list any more. +/// +/// Lock order, where both are taken: `HOMEWORK_LOCK` before the counter lock in +/// [`crate::db::cap`], never the reverse. +// corner-cut: global RwLock, shard per-homework if write latency ever matters. +pub(crate) static HOMEWORK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); + +#[expect( + clippy::too_many_arguments, + reason = "mirrors the sibling entities' create(field, field, ..) shape" +)] +pub async fn create( + db: &Database, + course: &CourseId, + subject: &SubjectId, + title: HomeworkTitle, + description: Option, + due_at: Timestamp, + assigned: Option>, + created_by: &UserId, +) -> Result { + homework::create( + db, + course, + subject, + title, + description, + due_at, + assigned, + created_by, + ) + .await +} + +/// The homework row, for callers that only inspect it — the web layer's gates +/// read through here. +pub async fn read(db: &Database, id: &HomeworkId) -> Result, AppError> { + homework::read(db, id).await +} + +pub async fn list_all(db: &Database) -> Result, AppError> { + homework::list_all(db).await +} + +pub async fn list_for_course(db: &Database, course: &CourseId) -> Result, AppError> { + homework::list_for_course(db, course).await +} + +/// Every homework of every course in `courses` (one query) — the catalog as +/// one user sees it. +pub async fn list_for_courses( + db: &Database, + courses: &[CourseId], +) -> Result, AppError> { + homework::list_for_courses(db, courses).await +} + +/// The homework of `course` that `user` is meant to see — the per-course +/// block of a homework report. +pub async fn list_for_user_in_course( + db: &Database, + course: &CourseId, + user: &UserId, +) -> Result, AppError> { + homework::list_for_user_in_course(db, course, user).await +} + +/// Re-scope (or re-tag, re-title, re-describe, re-schedule) the homework. +/// +/// Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the +/// live submissions and results, and the row write depends on what it saw — +/// without the lease a submission (a reader) could land between the check +/// and the write, orphaned by the narrowing that just missed it. The subject +/// re-tag no longer needs it — it moves the two subjects' reference counters +/// inside [`homework::update`]. +/// +/// The orphan guard runs on exactly the requests that re-scope the audience. +/// An absent `assigned` writes nothing, so the stored subset is untouched and +/// no narrowing can happen behind the guard's back — which the old "carry the +/// snapshot back" branch could do, re-narrowing over a concurrent widening. +pub async fn update( + db: &Database, + homework: Homework, + subject: Option, + title: Option, + description: Option>, + due_at: Option, + assigned: Option>>, +) -> Result { + let _guard = HOMEWORK_LOCK.write().await; + if let Some(resolved) = assigned.as_ref() { + ensure_no_orphans(&homework, resolved.as_deref(), db).await?; + } + homework::update(db, homework, subject, title, description, due_at, assigned).await +} + +/// Refuse (409) a PATCH that would narrow `homework`'s audience so a student +/// who already submitted or was graded falls outside it — their work would be +/// stranded. `new_assigned` is the proposed subset (`None` = whole course, in +/// which case no one can be orphaned). The blocking students are named in the +/// message so the teacher knows whose work to clear (or whom to keep assigned) +/// first. +async fn ensure_no_orphans( + homework: &Homework, + new_assigned: Option<&[UserId]>, + db: &Database, +) -> Result<(), AppError> { + // Whole-course covers everyone — no narrowing, no orphans. + let Some(subset) = new_assigned else { + return Ok(()); + }; + let submissions = homework_submission::list_for_homework(db, homework.get_id()).await?; + let results = homework_result::list_for_homework(db, homework.get_id()).await?; + let mut blocked: Vec = Vec::new(); + for user in submissions + .iter() + .map(HomeworkSubmission::get_user) + .chain(results.iter().map(HomeworkResult::get_user)) + { + let key = user.key().to_string(); + if !subset.contains(user) && !blocked.contains(&key) { + blocked.push(key); + } + } + if blocked.is_empty() { + Ok(()) + } else { + Err(AppError::ConflictOwned(format!( + "narrowing the assigned list would orphan existing work by {} student(s): {}", + blocked.len(), + blocked.join(", ") + ))) + } +} + +/// Delete the homework: collect the submission-file blob keys, then run the +/// cascading delete under [`HOMEWORK_LOCK`]'s write lease +/// so no submission can land under the homework mid-delete; the blob names are +/// collected before the rows are wiped (the cascade is one transaction, children +/// first) and removed after, so a crash in between strands at worst an +/// unreachable file. +pub async fn delete(db: &Database, homework: Homework) -> Result, AppError> { + let _guard = HOMEWORK_LOCK.write().await; + let blob_keys = homework_file::file_keys_for_homework(db, homework.get_id()).await?; + homework::delete(db, homework).await?; + Ok(blob_keys) +} + +/// A 403 unless `user` is enrolled in `course` — the homework twin of the exam +/// sitting wall ([`crate::service::exam_attempt::ensure_enrolled`], which is `Exam`-shaped). +/// Submitting is course content, so leaving the course closes it; re-checked on +/// every submission and file write, so an unenrollment mid-task bites the next. +async fn ensure_enrolled(course: &CourseId, user: &UserId, db: &Database) -> Result<(), AppError> { + if crate::service::enrollment::read_for_user(db, course, user) + .await? + .is_none() + { + return Err(AppError::Forbidden( + "you are not enrolled in this homework's course", + )); + } + Ok(()) +} + +/// Read a homework and clear `user` to act on their own submission to it — the +/// shared wall of the submission, file, and (student side of the) download +/// paths. Three gates, in order: +/// +/// 1. Exact `Student` on the *live* role. Teachers assign homework, they never +/// hand it in; the `RequireStudent` extractor's ≥Student would wave a +/// promoted teacher through, so this checks the role `CurrentUser` read for +/// this very request — the same reasoning as [`crate::service::exam_attempt::ensure_student`]. +/// 2. Current enrollment in the course. +/// 3. The audience check: a student a subset homework does not name gets a 404, +/// never a 403, so a subset assignment never leaks to those left out (the +/// no-leak idiom an unseen exam draft uses). +pub async fn gate_own_submission( + id: &str, + user: &User, + db: &Database, +) -> Result { + let homework = homework::read(db, &HomeworkId::from_key(id)) + .await? + .ok_or(AppError::NotFound)?; + if user.get_role() != Role::Student { + return Err(AppError::Forbidden( + "only students have homework submissions", + )); + } + ensure_enrolled(homework.get_course(), user.get_id(), db).await?; + if !homework.student_sees(user.get_id()) { + return Err(AppError::NotFound); + } + Ok(homework) +} + +/// The term wall of the student side: an archived term makes past years +/// read-only. Deliberately *not* inside [`gate_own_submission`] — that gate +/// also fronts the download read, and an archived year is still browsable. So +/// every student *write* calls this right after the gate, which keeps the +/// order that matters: a student the homework never named is refused by the +/// audience check with a 404 and never learns the homework exists. A course +/// that vanished under us is the gates' own business, not this one's. +pub async fn require_open_term(homework: &Homework, db: &Database) -> Result<(), AppError> { + if let Some(course) = crate::service::course::read(db, homework.get_course()).await? { + crate::service::course::require_open(db, &course).await?; + } + Ok(()) +} + +/// Bring one user's badge awards up to date after a write moved their counters +/// — the student's after a submission, the grader's after a grade. Never fails +/// the request it follows: a badge is a decoration on top +/// of the work, and losing one to a transient database error is not worth +/// refusing a hand-in over — the next counter move re-runs this and heals it. +pub(crate) async fn award_badges(user: &UserId, db: &Database) { + if let Err(err) = badge::sync(user, db).await { + tracing::warn!("failed to sync badges for {}: {err}", user.key()); + } +} diff --git a/src/service/homework_file.rs b/src/service/homework_file.rs new file mode 100644 index 0000000..a5d735b --- /dev/null +++ b/src/service/homework_file.rs @@ -0,0 +1,92 @@ +//! Homework file workflows: the attachment of one file to the caller's +//! submission (the graded gate plus the auto-created seat it hangs off) and +//! the pass-through reads the download paths scope through. The blob bytes +//! and their ordering (blob before row on upload, row before blob on delete) +//! stay the web layer's — it owns `files_path` — but every lease holder is +//! [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK)'s reader side. +//! The row writes live in [`crate::db::homework_file`]. + +use crate::database::Database; +use crate::db::homework_file; +use crate::db::homework_submission; +use crate::domain::homework::Homework; +use crate::domain::homework_file::{HomeworkFile, HomeworkFileId}; +use crate::domain::homework_submission::HomeworkSubmission; +use crate::domain::homework_submission::HomeworkSubmissionId; +use crate::domain::user::User; +use crate::error::AppError; + +/// The submission the file will hang off, created if absent — a photo-only +/// homework never types text, so an upload auto-creates an empty submission +/// to carry the file (an existing one's text is preserved). A photo-only +/// hand-in is a hand-in: it creates the row, so it moves the counters, so it +/// earns badges exactly as a text submit does. Refused (409) when a grade +/// has frozen the homework. +pub async fn ensure_can_attach( + db: &Database, + user: &User, + homework: &Homework, +) -> Result { + const GRADED: AppError = AppError::Conflict( + "this homework has been graded — ask the teacher to remove the grade before adding files", + ); + // The common-case gate; the freeze itself rides on the writes below. + if crate::db::homework_result::read_for(db, homework.get_id(), user.get_id()) + .await? + .is_some() + { + return Err(GRADED); + } + match homework_submission::read_for(db, homework.get_id(), user.get_id()).await? { + Some(existing) => Ok(existing), + None => { + let created = homework_submission::upsert(db, homework, user.get_id(), None) + .await? + .ok_or(GRADED)?; + crate::service::homework::award_badges(user.get_id(), db).await; + Ok(created) + } + } +} + +/// Persist the assembled row — the seat claim and the freeze in one +/// conditional write (see [`homework_file::insert`]). `Ok(None)` is the +/// freeze; the web layer keeps its own wording and unlinks the blob it wrote. +pub async fn insert(db: &Database, file: HomeworkFile) -> Result, AppError> { + homework_file::insert(db, file).await +} + +/// Delete one file row and give its seat back in the same transaction. +/// `Ok(None)` is the freeze biting (the caller answers 409); `Err(NotFound)` +/// means the row had already vanished. +pub async fn delete(db: &Database, file: HomeworkFile) -> Result, AppError> { + homework_file::delete(db, file).await +} + +/// Read a file's row only if it belongs to `submission` — the student's +/// download path, behind the submission gate. +pub async fn read_for( + db: &Database, + id: &HomeworkFileId, + submission: &HomeworkSubmissionId, +) -> Result, AppError> { + homework_file::read_for(db, id, submission).await +} + +/// Read a file by id only if it hangs off a submission to `homework` — the +/// grader's download scoping. +pub async fn read_in_homework( + db: &Database, + id: &HomeworkFileId, + homework: &crate::domain::homework::HomeworkId, +) -> Result, AppError> { + homework_file::read_in_homework(db, id, homework).await +} + +/// All of `submission`'s files, newest first. +pub async fn list_for_submission( + db: &Database, + submission: &HomeworkSubmissionId, +) -> Result, AppError> { + homework_file::list_for_submission(db, submission).await +} diff --git a/src/service/homework_result.rs b/src/service/homework_result.rs new file mode 100644 index 0000000..e7612a8 --- /dev/null +++ b/src/service/homework_result.rs @@ -0,0 +1,132 @@ +//! Homework grading workflows: the policy gates around the atomic grade — +//! nobody grades themselves, the target must be a live enrolled student in +//! the homework's audience — and the un-grade. The freeze-stamping +//! transaction lives in [`crate::db::homework_result`]; grading holds +//! [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK)'s writer lease +//! across its gates and the write, the reader side of every student write's +//! lease pair. + +use crate::database::Database; +use crate::db::homework; +use crate::db::homework_result; +use crate::domain::course::CourseId; +use crate::domain::exam_result::Mark; +use crate::domain::homework::HomeworkId; +use crate::domain::homework_result::{HomeworkResult, HomeworkStatus}; +use crate::domain::role::Role; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ValidationError}; + +/// Record (or overwrite) `target`'s grade for the homework. The web layer +/// has already read the homework, checked course-management rights, walled +/// the archived term, and validated the status and mark; everything here is +/// re-run or decided under the writer lease: +/// +/// - the homework is re-read (a homework delete is a fellow writer — its +/// lease excludes this one, so a grade cannot resurrect a result row under +/// a vanished homework; the vanished row answers 404); +/// - grading never targets oneself — no grader, whatever their role, may +/// write their own grade; +/// - the target user must exist, and only students carry homework grades — +/// the live role, so a stale enrollment left behind by a promotion can't +/// reopen grading for staff; +/// - the target must be enrolled in the homework's course, and in the +/// homework's audience — a subset assignment is also the grading roster. +pub async fn grade( + db: &Database, + id: &HomeworkId, + teacher: &User, + status: HomeworkStatus, + mark: Option, + target: &UserId, +) -> Result { + let _guard = crate::service::homework::HOMEWORK_LOCK.write().await; + let homework = homework::read(db, id).await?.ok_or(AppError::NotFound)?; + + // Grading never targets oneself. + if target == teacher.get_id() { + return Err(AppError::Forbidden("grading yourself is not allowed")); + } + + // Target user must exist. + let Some(target_user) = crate::service::user::read(db, target).await? else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user", + reason: "target user does not exist", + })); + }; + + // Only students carry homework grades. + if target_user.get_role() != Role::Student { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user", + reason: "only students can be graded", + })); + } + + // ... enrolled in the homework's course ... + if crate::service::enrollment::read_for_user(db, homework.get_course(), target) + .await? + .is_none() + { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user", + reason: "target user is not enrolled in this course", + })); + } + + // ... and in the homework's audience — a subset assignment is also the + // grading roster, so a grade can't land on a student the homework never + // named. + if !homework.student_sees(target) { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user", + reason: "target user is not in this homework's audience", + })); + } + + let result = homework_result::grade(db, id, target, status, mark, teacher.get_id()).await?; + // The grade credited the *grader*'s `marks_given`, not the student's — a + // homework grade moves no counter of the student's at all. + crate::service::homework::award_badges(teacher.get_id(), db).await; + Ok(result) +} + +/// Remove a student's grade from a homework — un-grading, which unfreezes +/// the student's submission and files for further edits. `None` means there +/// was no grade (the web layer answers 404). +pub async fn ungrade( + db: &Database, + id: &HomeworkId, + target: &UserId, +) -> Result, AppError> { + let _guard = crate::service::homework::HOMEWORK_LOCK.write().await; + homework_result::remove(db, id, target).await +} + +/// `user`'s grade for `homework`, if graded — the web layer's read paths go +/// through here. +pub async fn read_for( + db: &Database, + homework_id: &HomeworkId, + user: &UserId, +) -> Result, AppError> { + homework_result::read_for(db, homework_id, user).await +} + +/// Every grade for `homework` — the roster joins these onto the submissions. +pub async fn list_for_homework( + db: &Database, + homework_id: &HomeworkId, +) -> Result, AppError> { + homework_result::list_for_homework(db, homework_id).await +} + +/// `user`'s homework grades across one course. +pub async fn list_for_user_in_course( + db: &Database, + course: &CourseId, + user: &UserId, +) -> Result, AppError> { + homework_result::list_for_user_in_course(db, course, user).await +} diff --git a/src/service/homework_submission.rs b/src/service/homework_submission.rs new file mode 100644 index 0000000..1aeac18 --- /dev/null +++ b/src/service/homework_submission.rs @@ -0,0 +1,140 @@ +//! Homework submission workflows: the student's submit (the lease-to-write +//! window that keeps a PATCH's audience re-scope from stranding a hand-in) +//! and the withdrawal that gives the badge counters back. The row writes +//! live in [`crate::db::homework_submission`]; every locked path here +//! leases [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK). + +use crate::database::Database; +use crate::db::homework_file; +use crate::db::homework_result; +use crate::db::homework_submission; +use crate::domain::homework::Homework; +use crate::domain::homework_file::HomeworkFile; +use crate::domain::homework_submission::{HomeworkSubmission, SubmissionText}; +use crate::domain::user::User; +use crate::error::AppError; + +/// What [`submit`] landed: whether the (homework, user) row existed before +/// (the web layer's 200-vs-201), the homework it answered, and the row. +pub struct Submitted { + pub existed: bool, + pub homework: Homework, + pub submission: HomeworkSubmission, +} + +/// Submit (or re-submit) the caller's own work for a homework. The graded +/// gate and the audience interlock are the reader lease's — taken *before* +/// the gate read: read first and the audience this gate approved is one +/// committed PATCH old, so the narrowing that just passed the orphan guard +/// (no submission yet) is followed by the very submission it would have +/// refused. Holding the lease across gate *and* write is what makes the +/// PATCH wait and then see the row. +/// +/// `None` from [`homework_submission::upsert`] is a grade landing mid-request +/// (the stamp on the row refusing the write); the graded read above answers +/// the common case, and both return the same 409. +pub async fn submit( + db: &Database, + user: &User, + id: &str, + text: Option, +) -> Result { + let _guard = crate::service::homework::HOMEWORK_LOCK.read().await; + let homework = crate::service::homework::gate_own_submission(id, user, db).await?; + crate::service::homework::require_open_term(&homework, db).await?; + // The graded gate, twice over. This read answers the common case — graded + // minutes ago, and the student who never submitted has no row to carry the + // freeze; the upsert's own `WHERE` (the grade stamp on the row) is what + // holds when the grade lands *while* this request runs. + const GRADED: AppError = AppError::Conflict( + "this homework has been graded — ask the teacher to remove the grade before editing your submission", + ); + if homework_result::read_for(db, homework.get_id(), user.get_id()) + .await? + .is_some() + { + return Err(GRADED); + } + // 201-vs-200: a prior read is exact, where comparing the returned stamps + // would misreport a same-millisecond re-submit as a create. + let existed = homework_submission::read_for(db, homework.get_id(), user.get_id()) + .await? + .is_some(); + let Some(submission) = homework_submission::upsert(db, &homework, user.get_id(), text).await? + else { + return Err(GRADED); + }; + // Only a first hand-in moved a counter, so only a first hand-in can have + // earned anything — an edit re-runs nothing. + if !existed { + crate::service::homework::award_badges(user.get_id(), db).await; + } + Ok(Submitted { + existed, + homework, + submission, + }) +} + +/// Withdraw the caller's own submission — its text, its file rows, and their +/// blobs. Returns the file rows (the blobs are the web layer's to unlink: +/// collected before the wipe, unlinked after). Refused (409) once the work +/// is graded — the first read answers the common case, and the delete's own +/// freeze condition (the stamp on the row) holds when a grade lands since +/// the read above, refusing the write rather than wiping graded work. +pub async fn delete(db: &Database, user: &User, id: &str) -> Result, AppError> { + let homework = crate::service::homework::gate_own_submission(id, user, db).await?; + crate::service::homework::require_open_term(&homework, db).await?; + let _guard = crate::service::homework::HOMEWORK_LOCK.read().await; + const GRADED: AppError = AppError::Conflict( + "this homework has been graded — ask the teacher to remove the grade before deleting your submission", + ); + if homework_result::read_for(db, homework.get_id(), user.get_id()) + .await? + .is_some() + { + return Err(GRADED); + } + let submission = homework_submission::read_for(db, homework.get_id(), user.get_id()) + .await? + .ok_or(AppError::NotFound)?; + // Collect blob names before the cascade (the delete wipes the file + // rows in the same transaction), then unlink after the rows are gone. + let files = homework_file::list_for_submission(db, submission.get_id()).await?; + if homework_submission::delete(db, submission).await?.is_none() { + return Err(GRADED); + } + // The counters just came down; a badge already earned stays earned (`sync` + // only ever adds), so this is here to keep the award rows in step with the + // *next* submission rather than to take anything back. + crate::service::homework::award_badges(user.get_id(), db).await; + Ok(files) +} + +/// `user`'s submission to `homework`, if they have one — the web layer's +/// read paths go through here. +pub async fn read_for( + db: &Database, + homework: &crate::domain::homework::HomeworkId, + user: &crate::domain::user::UserId, +) -> Result, AppError> { + homework_submission::read_for(db, homework, user).await +} + +/// Re-stamp a submission's `updated_at` to now — a file add/delete moves the +/// submission's "last touched" clock (the late flag) without touching the +/// text. +pub async fn touch( + db: &Database, + id: &crate::domain::homework_submission::HomeworkSubmissionId, +) -> Result { + homework_submission::touch(db, id).await +} + +/// Every submission to `homework` — the roster's raw rows. +pub async fn list_for_homework( + db: &Database, + homework: &crate::domain::homework::HomeworkId, +) -> Result, AppError> { + homework_submission::list_for_homework(db, homework).await +} diff --git a/src/service/mod.rs b/src/service/mod.rs index 1e97bc3..569ec22 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -18,6 +18,10 @@ pub mod exam_attempt; pub mod exam_question; pub mod fee_plan; pub mod fee_plan_assignment; +pub mod homework; +pub mod homework_file; +pub mod homework_result; +pub mod homework_submission; pub mod meal_attendance; pub mod meal_booking; pub mod meal_ledger; diff --git a/src/web/courses.rs b/src/web/courses.rs index 1654b1f..147a78e 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -16,7 +16,7 @@ use crate::domain::enrollment::Enrollment; use crate::domain::exam::{ ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, }; -use crate::domain::homework::{Homework, HomeworkTitle}; +use crate::domain::homework::HomeworkTitle; use crate::domain::role::Role; use crate::domain::subject::{SubjectDescription, SubjectName}; use crate::domain::timestamp::Timestamp; @@ -1082,7 +1082,8 @@ async fn create_homework_in_course( // is non-zero — so the check below is only a pre-flight for the message. let subject = service::subject::in_course(&st.db, &req.subject_id, course.get_id()).await?; let assigned = resolve_assigned(req.assigned, course.get_id(), &st.db).await?; - let homework = Homework::create( + let homework = service::homework::create( + &st.db, course.get_id(), &subject, title, @@ -1090,7 +1091,6 @@ async fn create_homework_in_course( due_at, assigned, user.get_id(), - &st.db, ) .await?; Ok((StatusCode::CREATED, Json(HomeworkResponse::new(&homework)))) @@ -1132,7 +1132,7 @@ async fn list_course_homework( "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course", )); } - let mut homework = Homework::list_for_course(course.get_id(), &st.db).await?; + let mut homework = service::homework::list_for_course(&st.db, course.get_id()).await?; // A student sees only the homework they are assigned; managers see all. let manages = can_manage_course(&course, &user); if !manages { diff --git a/src/web/homework.rs b/src/web/homework.rs index b2253c3..3a9a010 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -3,7 +3,9 @@ //! files, the teacher's grading and roster, and the observer report. Creation //! and the per-course listing live under `/courses/{id}/homework` (see //! [`super::courses`]); everything shares the visibility rule -//! ([`Homework::student_sees`]) and the [`HOMEWORK_LOCK`]. +//! ([`Homework::student_sees`](crate::domain::homework::Homework::student_sees)) +//! and the [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK), whose +//! leases the workflows take in [`crate::service::homework`] and its siblings. use crate::web::tenant_state::State; use axum::Json; @@ -30,7 +32,7 @@ use crate::domain::homework_submission::{ use crate::domain::note_file::{FileContentType, FileName}; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; -use crate::domain::user::{User, UserId}; +use crate::domain::user::UserId; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::service; use crate::service::parent_link::ensure_can_observe; @@ -43,44 +45,6 @@ use super::{ check_not_past, paginate, read_upload, remove_blob, set_or_clear, }; -/// Serializes the homework subsystem's cross-record check-then-writes, which -/// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as -/// [`crate::service::exam_attempt::EXAM_LOCK`]. Every lease below is held across the -/// database write it guards, so within this one process it does order a full -/// round trip — but the freeze no longer *rests* on that: a graded submission -/// used to stay unedited only because the "no grade yet" read and the write it -/// licensed sat under one lease. That rule now lives in the database too — -/// grading stamps [`crate::constant::SUBMISSION_GRADED_FIELD`] on the -/// submission row and every student-side write carries `graded_by_result = -/// NONE` as its own condition. The one case the stamp cannot cover — grading -/// work with no submission row yet — falls back to the lease pair, so a write -/// lease must never stop spanning its own database call (see -/// [`crate::domain::homework_result::HomeworkResult::grade`]). -/// -/// What still leases it, honestly: -/// - Write: the homework PATCH's orphan guard ([`update_homework`]), the -/// homework-delete cascade ([`delete_homework`]), and grade/ungrade — whose -/// freeze rule (the stamp landing on a submission that may be written in the -/// same instant) is the one thing here still resting on the two leases being -/// mutually exclusive. The *existence* half has left: a grade now moves a -/// value on the homework row inside its own transaction -/// ([`crate::domain::homework_result::HomeworkResult::grade`]), so a -/// concurrent delete refuses it rather than being read around. -/// - Read: the student's submission/file writes, which no longer gate the -/// freeze but still must not land under a PATCH re-scoping the audience out -/// from under them. -/// -/// The subject rule has left: creating a homework and re-tagging one move the -/// subject's reference counter, and the subject delete is refused while that -/// counter is non-zero ([`crate::db::subject::delete`]), so -/// neither the create ([`super::courses`]) nor the outside writer the subject -/// delete used to take is on this list any more. -/// -/// Lock order, where both are taken: `HOMEWORK_LOCK` before the counter lock in -/// [`crate::db::cap`], never the reverse. -// corner-cut: global RwLock, shard per-homework if write latency ever matters. -pub(crate) static HOMEWORK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); - pub fn routes() -> OpenApiRouter { // The file-upload route carries a larger HTTP body cap than axum's 2 MB // default — the server-wide hard ceiling plus multipart framing headroom; @@ -162,7 +126,7 @@ pub(crate) fn description_or_none(text: &str) -> Result Result<(Homework, Course), AppError> { - let homework = Homework::read(&HomeworkId::from_key(id), db) + let homework = service::homework::read(db, &HomeworkId::from_key(id)) .await? .ok_or(AppError::NotFound)?; let course = crate::service::course::read(db, homework.get_course()) @@ -200,7 +164,7 @@ async fn list_homework( let manages_all = user.get_role().at_least(Role::Manager); let mut managed: Vec = Vec::new(); let homework = if manages_all { - Homework::list_all(&st.db).await? + service::homework::list_all(&st.db).await? } else { let courses = visible_courses(&user, &st.db).await?; let ids: Vec<_> = courses @@ -215,7 +179,7 @@ async fn list_homework( .filter(|course| can_manage_course(course, &user)) .map(|course| course.get_id().key().to_string()) .collect(); - let mut homework = Homework::list_for_courses(&ids, &st.db).await?; + let mut homework = service::homework::list_for_courses(&st.db, &ids).await?; homework.retain(|hw| { managed.iter().any(|key| key == hw.get_course().key()) || hw.student_sees(user.get_id()) }); @@ -346,13 +310,11 @@ async fn update_homework( } crate::service::course::require_open(&st.db, &course).await?; - // Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the - // live submissions and results, and the row write depends on what it saw — + // The writer lease of [`HOMEWORK_LOCK`], the orphan guard, and the write + // are one unit in [`service::homework::update`]: the guard reads the live + // submissions and results, and the row write depends on what it saw — // without the lease a submission (a reader) could land between the check - // and the write, orphaned by the narrowing that just missed it. The subject - // re-tag no longer needs it — it moves the two subjects' reference counters - // inside `Homework::update`. - let _guard = HOMEWORK_LOCK.write().await; + // and the write, orphaned by the narrowing that just missed it. // Only what the request carried: an omitted field stays `None` and is never // written, so a concurrent PATCH of another field survives. The two @@ -370,10 +332,8 @@ async fn update_homework( let due_at = req.due_at.map(Timestamp::from_millis); // A kept (absent) due date may already be past; a newly set one may not be. check_not_past("due_at", due_at)?; - let subject = match req.subject_id { - Some(ref subject_id) => { - Some(service::subject::in_course(&st.db, subject_id, course.get_id()).await?) - } + let subject = match &req.subject_id { + Some(subject_id) => Some(subject_in_course(subject_id, course.get_id(), &st.db).await?), None => None, }; // The orphan guard runs on exactly the requests that re-scope the audience. @@ -381,59 +341,23 @@ async fn update_homework( // no narrowing can happen behind the guard's back — which the old "carry the // snapshot back" branch could do, re-narrowing over a concurrent widening. let assigned = match req.assigned { - Some(assigned) => { - let resolved = resolve_assigned(assigned, course.get_id(), &st.db).await?; - ensure_no_orphans(&homework, resolved.as_deref(), &st.db).await?; - Some(resolved) - } + Some(assigned) => Some(resolve_assigned(assigned, course.get_id(), &st.db).await?), None => None, }; - let updated = homework - .update(subject, title, description, due_at, assigned, &st.db) - .await?; + let updated = service::homework::update( + &st.db, + homework, + subject, + title, + description, + due_at, + assigned, + ) + .await?; Ok(Json(HomeworkResponse::new(&updated))) } -/// Refuse (409) a PATCH that would narrow `homework`'s audience so a student -/// who already submitted or was graded falls outside it — their work would be -/// stranded. `new_assigned` is the proposed subset (`None` = whole course, in -/// which case no one can be orphaned). The blocking students are named in the -/// message so the teacher knows whose work to clear (or whom to keep assigned) -/// first. -async fn ensure_no_orphans( - homework: &Homework, - new_assigned: Option<&[UserId]>, - db: &Database, -) -> Result<(), AppError> { - // Whole-course covers everyone — no narrowing, no orphans. - let Some(subset) = new_assigned else { - return Ok(()); - }; - let submissions = HomeworkSubmission::list_for_homework(homework.get_id(), db).await?; - let results = HomeworkResult::list_for_homework(homework.get_id(), db).await?; - let mut blocked: Vec = Vec::new(); - for user in submissions - .iter() - .map(HomeworkSubmission::get_user) - .chain(results.iter().map(HomeworkResult::get_user)) - { - let key = user.key().to_string(); - if !subset.contains(user) && !blocked.contains(&key) { - blocked.push(key); - } - } - if blocked.is_empty() { - Ok(()) - } else { - Err(AppError::ConflictOwned(format!( - "narrowing the assigned list would orphan existing work by {} student(s): {}", - blocked.len(), - blocked.join(", ") - ))) - } -} - /// Delete a homework and everything under it — submissions, their files, and /// results — then unlink the file blobs from disk. Requires teacher+ and /// management rights over its course. Held under [`HOMEWORK_LOCK`]'s write lease @@ -467,73 +391,16 @@ async fn delete_homework( )); } crate::service::course::require_open(&st.db, &course).await?; - let _guard = HOMEWORK_LOCK.write().await; - let blob_keys = HomeworkFile::file_keys_for_homework(homework.get_id(), &st.db).await?; - homework.delete(&st.db).await?; + // The writer lease, the blob-key collection, and the cascade are + // [`service::homework::delete`]'s; unlinking the blobs stays here because + // only the web layer knows `files_path`. + let blob_keys = service::homework::delete(&st.db, homework).await?; for key in &blob_keys { remove_blob(&st.files_path, key).await; } Ok(StatusCode::NO_CONTENT) } -/// A 403 unless `user` is enrolled in `course` — the homework twin of the exam -/// sitting wall ([`crate::service::exam_attempt::ensure_enrolled`], which is `Exam`-shaped). -/// Submitting is course content, so leaving the course closes it; re-checked on -/// every submission and file write, so an unenrollment mid-task bites the next. -async fn ensure_enrolled(course: &CourseId, user: &UserId, db: &Database) -> Result<(), AppError> { - if service::enrollment::read_for_user(db, course, user) - .await? - .is_none() - { - return Err(AppError::Forbidden( - "you are not enrolled in this homework's course", - )); - } - Ok(()) -} - -/// Read a homework and clear `user` to act on their own submission to it — the -/// shared wall of the submission, file, and (student side of the) download -/// paths. Three gates, in order: -/// -/// 1. Exact `Student` on the *live* role. Teachers assign homework, they never -/// hand it in; the `RequireStudent` extractor's ≥Student would wave a -/// promoted teacher through, so this checks the role `CurrentUser` read for -/// this very request — the same reasoning as [`crate::service::exam_attempt::ensure_student`]. -/// 2. Current enrollment in the course. -/// 3. The audience check: a student a subset homework does not name gets a 404, -/// never a 403, so a subset assignment never leaks to those left out (the -/// no-leak idiom an unseen exam draft uses). -async fn gate_own_submission(id: &str, user: &User, db: &Database) -> Result { - let homework = Homework::read(&HomeworkId::from_key(id), db) - .await? - .ok_or(AppError::NotFound)?; - if user.get_role() != Role::Student { - return Err(AppError::Forbidden( - "only students have homework submissions", - )); - } - ensure_enrolled(homework.get_course(), user.get_id(), db).await?; - if !homework.student_sees(user.get_id()) { - return Err(AppError::NotFound); - } - Ok(homework) -} - -/// The term wall of the student side: an archived term makes past years -/// read-only. Deliberately *not* inside [`gate_own_submission`] — that gate -/// also fronts the download read, and an archived year is still browsable. So -/// every student *write* calls this right after the gate, which keeps the -/// order that matters: a student the homework never named is refused by the -/// audience check with a 404 and never learns the homework exists. A course -/// that vanished under us is the gates' own business, not this one's. -async fn require_open_term(homework: &Homework, db: &Database) -> Result<(), AppError> { - if let Some(course) = crate::service::course::read(db, homework.get_course()).await? { - crate::service::course::require_open(db, &course).await?; - } - Ok(()) -} - /// One file attached to a submission — metadata only; the bytes download /// separately from `GET /homework/{id}/submission/files/{fid}`. #[derive(Serialize, ToSchema)] @@ -677,62 +544,28 @@ async fn submit( Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { // Empty text stores as "no note", so a present-but-blank row is never left. - let text = match req.text { - Some(ref text) if !text.is_empty() => Some(SubmissionText::try_new(text)?), + let text = match &req.text { + Some(text) if !text.is_empty() => Some(SubmissionText::try_new(text)?), _ => None, }; - // Reader lease of HOMEWORK_LOCK: no longer the freeze (that is the stamp on - // the row, below), but still the interlock against a PATCH re-scoping this - // homework's audience while the submission lands under it. Taken *before* - // the gate read, as in `add_submission_file`: read first and the audience - // this gate approved is one committed PATCH old, so the narrowing that just - // passed `ensure_no_orphans` (no submission yet) is followed by the very - // submission it would have refused. Holding the lease across gate *and* - // write is what makes the PATCH wait and then see the row. - let _guard = HOMEWORK_LOCK.read().await; - let homework = gate_own_submission(&id, &user, &st.db).await?; - require_open_term(&homework, &st.db).await?; - // The graded gate, twice over. This read answers the common case — graded - // minutes ago, and the student who never submitted has no row to carry the - // freeze; the upsert's own `WHERE` (the grade stamp on the row) is what - // holds when the grade lands *while* this request runs. - if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db) - .await? - .is_some() - { - return Err(AppError::Conflict( - "this homework has been graded — ask the teacher to remove the grade before editing your submission", - )); - } - // 201-vs-200: a prior read is exact, where comparing the returned stamps - // would misreport a same-millisecond re-submit as a create. - let existed = HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db) - .await? - .is_some(); - let Some(submission) = - HomeworkSubmission::upsert(&homework, user.get_id(), text, &st.db).await? - else { - return Err(AppError::Conflict( - "this homework has been graded — ask the teacher to remove the grade before editing your submission", - )); - }; - // Only a first hand-in moved a counter, so only a first hand-in can have - // earned anything — an edit re-runs nothing. - if !existed { - award_badges(user.get_id(), &st.db).await; - } - let files = HomeworkFile::list_for_submission(submission.get_id(), &st.db).await?; - let status = if existed { + // The reader lease of [`HOMEWORK_LOCK`], the gate, the term wall, the + // graded check, and the upsert are one unit in + // [`service::homework_submission::submit`] — the audience interlock, not + // the freeze (that is the stamp on the row). + let landed = service::homework_submission::submit(&st.db, &user, &id, text).await?; + let files = + service::homework_file::list_for_submission(&st.db, landed.submission.get_id()).await?; + let status = if landed.existed { StatusCode::OK } else { StatusCode::CREATED }; - // A result can't exist here — the gate above would have 409'd. + // A result can't exist here — the gate would have 409'd. Ok(( status, Json(SubmissionResponse::new( - &homework, - &submission, + &landed.homework, + &landed.submission, &files, None, )), @@ -760,12 +593,14 @@ async fn get_submission( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { - let homework = gate_own_submission(&id, &user, &st.db).await?; - let submission = HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db) - .await? - .ok_or(AppError::NotFound)?; - let files = HomeworkFile::list_for_submission(submission.get_id(), &st.db).await?; - let result = HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db).await?; + let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?; + let submission = + service::homework_submission::read_for(&st.db, homework.get_id(), user.get_id()) + .await? + .ok_or(AppError::NotFound)?; + let files = service::homework_file::list_for_submission(&st.db, submission.get_id()).await?; + let result = + service::homework_result::read_for(&st.db, homework.get_id(), user.get_id()).await?; Ok(Json(SubmissionResponse::new( &homework, &submission, @@ -797,52 +632,16 @@ async fn delete_submission( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result { - let homework = gate_own_submission(&id, &user, &st.db).await?; - require_open_term(&homework, &st.db).await?; - // Reader lease as in `submit` — the audience interlock, not the freeze. - let _guard = HOMEWORK_LOCK.read().await; - if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db) - .await? - .is_some() - { - return Err(AppError::Conflict( - "this homework has been graded — ask the teacher to remove the grade before deleting your submission", - )); - } - let submission = HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db) - .await? - .ok_or(AppError::NotFound)?; - // Collect blob names before the cascade (submission.delete wipes the file - // rows in the same transaction), then unlink after the rows are gone. - let files = HomeworkFile::list_for_submission(submission.get_id(), &st.db).await?; - // The delete carries the freeze as its own condition, so a grade landing - // since the read above refuses it rather than wiping graded work. - if submission.delete(&st.db).await?.is_none() { - return Err(AppError::Conflict( - "this homework has been graded — ask the teacher to remove the grade before deleting your submission", - )); - } - // The counters just came down; a badge already earned stays earned (`sync` - // only ever adds), so this is here to keep the award rows in step with the - // *next* submission rather than to take anything back. - award_badges(user.get_id(), &st.db).await; + // Gate, term wall, graded check, and the cascade are + // [`service::homework_submission::delete`]'s; the file rows it returns + // carry the blob names to unlink now that the rows are gone. + let files = service::homework_submission::delete(&st.db, &user, &id).await?; for file in &files { remove_blob(&st.files_path, file.get_file()).await; } Ok(StatusCode::NO_CONTENT) } -/// Bring one user's badge awards up to date after a write moved their counters -/// — the student's after a submission, the grader's after a grade. Never fails -/// the request it follows: a badge is a decoration on top -/// of the work, and losing one to a transient database error is not worth -/// refusing a hand-in over — the next counter move re-runs this and heals it. -async fn award_badges(user: &UserId, db: &Database) { - if let Err(err) = service::badge::sync(db, user).await { - tracing::warn!("failed to sync badges for {}: {err}", user.key()); - } -} - /// Serve a submission file as a download — `Content-Disposition: attachment`, /// never inline. Homework files take *any* content type (documents, photos — /// and so a `text/html` or `image/svg+xml` too), so, unlike the raster-only, @@ -910,8 +709,8 @@ async fn upload_submission_file( // Pre-flight, so a caller with no business here is refused before uploading // 25 MiB; the gate that *licenses the write* is the one under the lease // below, because this snapshot goes stale while the body streams. - let preflight = gate_own_submission(&id, &user, &st.db).await?; - require_open_term(&preflight, &st.db).await?; + let preflight = service::homework::gate_own_submission(&id, &user, &st.db).await?; + service::homework::require_open_term(&preflight, &st.db).await?; let limit = service::settings::load(&st.db).await?.get_max_file_bytes(); // Consume the body before taking the lock — a slow upload must not stall the // homework subsystem (mirrors the exam/note image uploads). @@ -923,9 +722,11 @@ async fn upload_submission_file( "this homework has been graded — ask the teacher to remove the grade before adding files", ); // Reader lease as in `submit` — the audience interlock, not the freeze. - // Taken before the cap claim inside `insert`, never after (the lock order - // is HOMEWORK_LOCK, then the counter lock). - let _guard = HOMEWORK_LOCK.read().await; + // Taken before the cap claim inside the insert, never after (the lock + // order is HOMEWORK_LOCK, then the counter lock). The lock lives in + // [`service::homework`]; the blob write stays here, inside the lease, + // because the row's "stored row points at a real blob" ordering does. + let _guard = service::homework::HOMEWORK_LOCK.read().await; // Re-read the homework *under* the lease. Streaming the body takes as long // as the client wants it to, and a homework delete (a writer) both takes // and releases its lease inside that window — so the pre-flight snapshot @@ -933,31 +734,10 @@ async fn upload_submission_file( // auto-create a submission, credit the badge counters and write a file // under it, all unreachable afterwards. A gate read before the body is a // pre-flight; a gate read after it is the decision. - let homework = gate_own_submission(&id, &user, &st.db).await?; + let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?; // Re-walled too: the term can be archived while the body streams. - require_open_term(&homework, &st.db).await?; - // The common-case gate; the freeze itself rides on the writes below. - if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db) - .await? - .is_some() - { - return Err(GRADED); - } - // A submission row must exist to hang the file off; auto-create an empty one - // for the photo-only case rather than force a separate text submit first. - let submission = - match HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db).await? { - Some(existing) => existing, - // A photo-only hand-in is a hand-in: it creates the row, so it moves - // the counters, so it earns badges exactly as a text submit does. - None => { - let created = HomeworkSubmission::upsert(&homework, user.get_id(), None, &st.db) - .await? - .ok_or(GRADED)?; - award_badges(user.get_id(), &st.db).await; - created - } - }; + service::homework::require_open_term(&homework, &st.db).await?; + let submission = service::homework_file::ensure_can_attach(&st.db, &user, &homework).await?; // Blob first, row second — a stored row always points at a real blob. The // 10-file cap and the freeze are one conditional write on the submission row @@ -973,7 +753,7 @@ async fn upload_submission_file( tokio::fs::write(&path, &upload.data) .await .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; - let stored = match file.insert(&st.db).await { + let stored = match service::homework_file::insert(&st.db, file).await { Ok(Some(stored)) => stored, // `None` is the freeze biting, an `Err` the file cap (or worse); either // way the blob just written has no row and must go. @@ -983,7 +763,7 @@ async fn upload_submission_file( } }; // A landed file moves the submission's "last touched" clock (the late flag). - HomeworkSubmission::touch(submission.get_id(), &st.db).await?; + service::homework_submission::touch(&st.db, submission.get_id()).await?; Ok(( StatusCode::CREATED, Json(HomeworkFileResponse::new(&stored)), @@ -1020,9 +800,9 @@ async fn download_submission_file( let file_id = HomeworkFileId::from_key(&fid); let file = if user.get_role() == Role::Student { // Student: only their own file, behind the full submission gate. - let homework = gate_own_submission(&id, &user, &st.db).await?; + let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?; let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id()); - HomeworkFile::read_for(&file_id, &submission, &st.db) + service::homework_file::read_for(&st.db, &file_id, &submission) .await? .ok_or(AppError::NotFound)? } else { @@ -1033,7 +813,7 @@ async fn download_submission_file( "only the course creator, an assigned teacher, or a manager/admin can read submission files", )); } - HomeworkFile::read_in_homework(&file_id, homework.get_id(), &st.db) + service::homework_file::read_in_homework(&st.db, &file_id, homework.get_id()) .await? .ok_or(AppError::NotFound)? }; @@ -1065,28 +845,32 @@ async fn delete_submission_file( CurrentUser(user): CurrentUser, Path((id, fid)): Path<(String, String)>, ) -> Result { - let homework = gate_own_submission(&id, &user, &st.db).await?; - require_open_term(&homework, &st.db).await?; + let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?; + service::homework::require_open_term(&homework, &st.db).await?; const GRADED: AppError = AppError::Conflict( "this homework has been graded — ask the teacher to remove the grade before deleting files", ); // Reader lease as in `submit` — the audience interlock, not the freeze. - let _guard = HOMEWORK_LOCK.read().await; - if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db) + let _guard = service::homework::HOMEWORK_LOCK.read().await; + if service::homework_result::read_for(&st.db, homework.get_id(), user.get_id()) .await? .is_some() { return Err(GRADED); } let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id()); - let file = HomeworkFile::read_for(&HomeworkFileId::from_key(&fid), &submission, &st.db) - .await? - .ok_or(AppError::NotFound)?; + let file = + service::homework_file::read_for(&st.db, &HomeworkFileId::from_key(&fid), &submission) + .await? + .ok_or(AppError::NotFound)?; let blob = file.get_file().to_string(); // The delete's own transaction re-stamps the submission's "last touched" // clock (the late flag) as its freeze gate, so a refused delete moves // nothing and no separate touch is owed here. - if file.delete(&st.db).await?.is_none() { + if service::homework_file::delete(&st.db, file) + .await? + .is_none() + { return Err(GRADED); } remove_blob(&st.files_path, &blob).await; @@ -1139,12 +923,12 @@ async fn grade_homework( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - // Writer lease of [`HOMEWORK_LOCK`], taken before the homework read: a - // grade is what freezes a submission, so it must not interleave with the - // read side's gate-through-write submission edits — and reading the - // homework under the lease keeps a homework delete (a fellow writer) from - // letting this upsert resurrect a result row under a vanished homework. - let _guard = HOMEWORK_LOCK.write().await; + // The grading gates and the writer lease of [`HOMEWORK_LOCK`] live in + // [`service::homework_result::grade`]: a grade is what freezes a + // submission, so it must not interleave with the read side's + // gate-through-write submission edits — and the homework is re-read under + // the lease there, which keeps a homework delete (a fellow writer) from + // letting the upsert resurrect a result row under a vanished homework. let (homework, course) = homework_with_course(&id, &st.db).await?; if !can_manage_course(&course, &teacher) { return Err(AppError::Forbidden( @@ -1157,62 +941,11 @@ async fn grade_homework( let mark = req.mark.map(Mark::try_new).transpose()?; let target = UserId::from_key(&req.user); - // Grading never targets oneself — no grader, whatever their role, may - // write their own grade. - if &target == teacher.get_id() { - return Err(AppError::Forbidden("grading yourself is not allowed")); - } - - // Target user must exist. - let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user", - reason: "target user does not exist", - })); - }; - - // Only students carry homework grades — the live role, so a stale - // enrollment left behind by a promotion can't reopen grading for staff. - if target_user.get_role() != Role::Student { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user", - reason: "only students can be graded", - })); - } - - // ... enrolled in the homework's course ... - if service::enrollment::read_for_user(&st.db, homework.get_course(), &target) - .await? - .is_none() - { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user", - reason: "target user is not enrolled in this course", - })); - } - - // ... and in the homework's audience — a subset assignment is also the - // grading roster, so a grade can't land on a student the homework never - // named. - if !homework.student_sees(&target) { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user", - reason: "target user is not in this homework's audience", - })); - } - - let result = HomeworkResult::grade( - homework.get_id(), - &target, - status, - mark, - teacher.get_id(), - &st.db, - ) - .await?; - // The grade credited the *grader*'s `marks_given`, not the student's — a - // homework grade moves no counter of the student's at all. - award_badges(teacher.get_id(), &st.db).await; + // The self-grade, target-exists, live-student, enrollment, and audience + // gates run inside [`service::homework_result::grade`], under the lease. + let result = + service::homework_result::grade(&st.db, homework.get_id(), &teacher, status, mark, &target) + .await?; Ok(Json(HomeworkResultResponse::new(&result))) } @@ -1241,10 +974,9 @@ async fn remove_homework_result( RequireTeacher(user): RequireTeacher, Path((id, target)): Path<(String, String)>, ) -> Result { - // Writer lease, before the read — the twin of grading's: removing the - // grade is what unfreezes the submission, so it must not straddle the read - // side's gate-through-write edits either. - let _guard = HOMEWORK_LOCK.write().await; + // The writer lease of [`HOMEWORK_LOCK`] is [`service::homework_result::ungrade`]'s + // — removing the grade is what unfreezes the submission, so it must not + // straddle the read side's gate-through-write edits either. let (homework, course) = homework_with_course(&id, &st.db).await?; if !can_manage_course(&course, &user) { return Err(AppError::Forbidden( @@ -1253,7 +985,8 @@ async fn remove_homework_result( } crate::service::course::require_open(&st.db, &course).await?; let removed = - HomeworkResult::remove(homework.get_id(), &UserId::from_key(&target), &st.db).await?; + service::homework_result::ungrade(&st.db, homework.get_id(), &UserId::from_key(&target)) + .await?; if removed.is_none() { return Err(AppError::NotFound); } @@ -1281,9 +1014,10 @@ async fn my_homework_result( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { - let result = HomeworkResult::read_for(&HomeworkId::from_key(&id), user.get_id(), &st.db) - .await? - .ok_or(AppError::NotFound)?; + let result = + service::homework_result::read_for(&st.db, &HomeworkId::from_key(&id), user.get_id()) + .await? + .ok_or(AppError::NotFound)?; Ok(Json(HomeworkResultResponse::new(&result))) } @@ -1357,8 +1091,9 @@ async fn list_homework_submissions( "only the course creator, an assigned teacher, or a manager/admin can list submissions", )); } - let submissions = HomeworkSubmission::list_for_homework(homework.get_id(), &st.db).await?; - let results = HomeworkResult::list_for_homework(homework.get_id(), &st.db).await?; + let submissions = + service::homework_submission::list_for_homework(&st.db, homework.get_id()).await?; + let results = service::homework_result::list_for_homework(&st.db, homework.get_id()).await?; let enrolled: Vec = service::enrollment::list_for_course(&st.db, course.get_id(), None, 0) .await? @@ -1403,7 +1138,7 @@ async fn list_homework_submissions( submitted_at: submission.get_submitted_at().as_millis(), updated_at: submission.get_updated_at().as_millis(), late: submission.get_updated_at() > homework.get_due_at(), - files: HomeworkFile::list_for_submission(submission.get_id(), &st.db) + files: service::homework_file::list_for_submission(&st.db, submission.get_id()) .await? .iter() .map(HomeworkFileResponse::new) @@ -1492,15 +1227,18 @@ async fn homework_report( } let mut rows = Vec::new(); for course in &courses { - rows.extend(Homework::list_for_user_in_course(course.get_id(), &target, &st.db).await?); + rows.extend( + service::homework::list_for_user_in_course(&st.db, course.get_id(), &target).await?, + ); } let total = rows.len() as i64; // Join submissions and grades onto the page alone. let mut items = Vec::new(); // Paged in the web layer: the rows are gathered course by course. for homework in paginate(&rows, limit, offset) { - let submission = HomeworkSubmission::read_for(homework.get_id(), &target, &st.db).await?; - let result = HomeworkResult::read_for(homework.get_id(), &target, &st.db).await?; + let submission = + service::homework_submission::read_for(&st.db, homework.get_id(), &target).await?; + let result = service::homework_result::read_for(&st.db, homework.get_id(), &target).await?; items.push(HomeworkReportEntry { course: homework.get_course().key().to_string(), homework: homework.get_id().key().to_string(), diff --git a/tests/regress_homework_orphans.rs b/tests/regress_homework_orphans.rs index 32d167f..108e3da 100644 --- a/tests/regress_homework_orphans.rs +++ b/tests/regress_homework_orphans.rs @@ -316,8 +316,9 @@ async fn an_upload_inside_an_audience_patch_is_refused() { /// leaves behind. #[tokio::test] async fn a_submission_under_a_vanished_homework_is_refused() { - use hezarfen_backend::domain::homework::{Homework, HomeworkId}; - use hezarfen_backend::domain::homework_submission::HomeworkSubmission; + use hezarfen_backend::db::homework::read; + use hezarfen_backend::db::homework_submission::upsert; + use hezarfen_backend::domain::homework::HomeworkId; use hezarfen_backend::domain::user::UserId; let (app, db) = app_and_db().await; @@ -326,7 +327,7 @@ async fn a_submission_under_a_vanished_homework_is_refused() { course_with_student(&app, &db, &teacher, "kimya").await; let hw = create_homework(&app, &teacher, &course, &subject, "deneme", far_future()).await; // The stale snapshot a handler would still be holding. - let stale = Homework::read(&HomeworkId::from_key(&hw), &db) + let stale = read(&db, &HomeworkId::from_key(&hw)) .await .unwrap() .expect("the homework exists"); @@ -346,7 +347,7 @@ async fn a_submission_under_a_vanished_homework_is_refused() { "delete the homework" ); - let refused = HomeworkSubmission::upsert(&stale, &user, None, &db).await; + let refused = upsert(&db, &stale, &user, None).await; assert!( refused.is_err(), "a submission to a homework that is gone must be refused, got {refused:?}" @@ -385,8 +386,9 @@ async fn a_submission_under_a_vanished_homework_is_refused() { /// that holds when the lease does not, so no handler may be in the way of it. #[tokio::test] async fn a_grade_under_a_vanished_homework_is_refused() { + use hezarfen_backend::db::homework_result::grade; use hezarfen_backend::domain::homework::HomeworkId; - use hezarfen_backend::domain::homework_result::{HomeworkResult, HomeworkStatus}; + use hezarfen_backend::domain::homework_result::HomeworkStatus; use hezarfen_backend::domain::user::UserId; let (app, db) = app_and_db().await; @@ -411,13 +413,13 @@ async fn a_grade_under_a_vanished_homework_is_refused() { ); // The ids a handler mid-request would still be carrying. - let refused = HomeworkResult::grade( + let refused = grade( + &db, &HomeworkId::from_key(&hw), &UserId::from_key(&student_id), HomeworkStatus::try_new("done").unwrap(), None, &UserId::from_key(&teacher_id), - &db, ) .await; assert!(