diff --git a/src/db/homework.rs b/src/db/homework.rs index 4545a10..2a41c6a 100644 --- a/src/db/homework.rs +++ b/src/db/homework.rs @@ -1,25 +1,22 @@ -//! 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`]. +//! The `homework` table: row reads and listings, the subject-counter claim +//! that pins a homework to a live subject row, the reference-counting PATCH — +//! whose audience-narrowing orphan guard is one transaction with the write, +//! serialized on the homework row's `FOR UPDATE` lock — and the cascading +//! delete. -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::database::{Database, tx_with_retry}; 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}; +use sqlx::PgConnection; /// 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. +/// re-tag alike — the conditional claim on the subject row 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", @@ -27,6 +24,12 @@ fn subject_gone() -> AppError { }) } +/// What a stale re-tag answers. The shared PATCH builder +/// ([`crate::db::field_update`]) carries the same refusal; the homework PATCH +/// keeps its own copy because its orphan guard needs the row lock the generic +/// builder cannot take. +const STALE_MOVE: &str = "the link this update moves changed since it was read; re-read and retry"; + #[expect( clippy::too_many_arguments, reason = "mirrors the sibling entities' create(field, field, ..) shape" @@ -41,16 +44,14 @@ pub async fn create( 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(); + // The subject's reference is taken in the very statement that writes the + // row — the exam question's twin ([`crate::db::exam_question`]): the + // claim (`UPDATE subject … +1`) and the insert are one CTE, so a subject + // a delete already removed matches nothing and nothing is written, which + // is the 400 the web layer's pre-flight check answers with. The subject + // delete is refused while this counter is non-zero, so the two writers + // contend on the subject row itself, and a crash cannot strand a claim + // that would make the subject undeletable forever. let homework = Homework { id: HomeworkId::generate(), course: course.clone(), @@ -62,46 +63,111 @@ pub async fn create( 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, + let assigned_values = homework.assigned.clone().unwrap_or_default(); + // The fresh v7 id cannot collide, so the pair-unique answer has no rival + // here; the mapping is kept for symmetry with the other claim sites. + let created = sqlx::query_as!( + Homework, + r#"WITH seat AS ( + UPDATE subject SET homework_count = homework_count + 1 + WHERE id = $1 + RETURNING 1 + ) + INSERT INTO homework (id, course, subject, title, description, due_at, assigned, created_by, created_at) + SELECT $2, $3, $1, $4, $5, $6, $7, $8, $9 WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp""#, + subject, + homework.id, + course, + homework.title, + homework.description, + homework.due_at, + assigned_values, + homework.created_by, + homework.created_at, ) - .await? - { - cap::Claimed::Made(created) => Ok(created), - cap::Claimed::Full => Err(subject_gone()), - cap::Claimed::Duplicate => Err(AppError::Internal("failed to create homework".into())), - } + .fetch_optional(db) + .await + .map_err(|err| { + if crate::database::unique_violation(&err).is_some() { + AppError::Internal("failed to create homework".into()) + } else { + AppError::from(err) + } + })?; + created.ok_or_else(subject_gone) } pub async fn read(db: &Database, id: &HomeworkId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + Ok(sqlx::query_as!( + Homework, + r#"SELECT id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework WHERE id = $1"#, + id + ) + .fetch_optional(db) + .await?) } -/// The course's homework, newest first (ULID ids sort by creation). The web +/// The course's homework, newest first (v7 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)?) + Ok(sqlx::query_as!( + Homework, + r#"SELECT id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework WHERE course = $1 ORDER BY id DESC"#, + course + ) + .fetch_all(db) + .await?) } /// 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)?) + Ok(sqlx::query_as!( + Homework, + r#"SELECT id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework ORDER BY id DESC"#, + ) + .fetch_all(db) + .await?) } /// Every homework of every course in `courses`, newest first (one query) — @@ -115,51 +181,71 @@ pub async fn list_for_courses( 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)?) + let ids: Vec = courses.to_vec(); + Ok(sqlx::query_as!( + Homework, + r#"SELECT id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework WHERE course = ANY($1) ORDER BY id DESC"#, + ids + ) + .fetch_all(db) + .await?) } /// 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. +/// in SQL 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)?) + Ok(sqlx::query_as!( + Homework, + r#"SELECT id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework + WHERE course = $1 AND (cardinality(assigned) = 0 OR $2 = ANY(assigned)) + ORDER BY id DESC"#, + course, + user + ) + .fetch_all(db) + .await?) } /// 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. +/// field — under the row lock below, an uncarried field keeps the value read +/// *under that lock*, never the handler's snapshot. `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. +/// `description` takes `Some(None)` to clear; `assigned` takes `Some(None)` +/// to widen back to the whole course (stored as `'{}'`, read back as `None`). +/// The web layer has already re-checked a new `due_at` against now, a new +/// `subject` against the course, and — inside the transaction here — the +/// narrowing against the work that would be orphaned by it. pub async fn update( db: &Database, homework: Homework, @@ -169,75 +255,250 @@ pub async fn update( 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(), + tx_with_retry(db, false, async |tx| { + // The homework row's lock. The orphan guard's reads and the write + // below are one transaction with it, so a submission — whose own + // transaction locks this very row before writing — cannot land + // between the check and the narrowing, orphaned by an audience change + // that just missed it. The lock also replaces the old CAS's row read: + // the re-tag check below compares the handler's snapshot against the + // row as it is *locked*, not as it was first read. + let current = sqlx::query_as!( + Homework, + r#"SELECT id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework WHERE id = $1 FOR UPDATE"#, + homework.get_id() ) - .run::(db) - .await + .fetch_optional(&mut *tx) + .await? + .ok_or(AppError::NotFound)?; + + // 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. + if let Some(resolved) = assigned.as_ref() { + ensure_no_orphans(¤t, resolved.as_deref(), tx).await?; + } + + // 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. The release goes + // first and the claim refuses on a gone row, so a move to a deleted + // subject is a rolled-back no-op — every abort takes the whole move + // back with it. + let moving = subject.as_ref().filter(|next| **next != homework.subject); + if let Some(next) = moving { + sqlx::query!( + "UPDATE subject SET homework_count = GREATEST(homework_count - 1, 0) WHERE id = $1", + current.subject + ) + .execute(&mut *tx) + .await?; + let seat = sqlx::query!( + r#"UPDATE subject SET homework_count = homework_count + 1 + WHERE id = $1 RETURNING 1 AS "seat: i32""#, + next + ) + .fetch_optional(&mut *tx) + .await?; + if seat.is_none() { + return Err(subject_gone()); + } + } + + // The stale-re-tag check. Armed by the request *carrying* the subject + // — even when it re-states the tag its snapshot showed, shifting no + // counter — so two PATCHes moving the same homework off the same + // subject cannot both claim their target: the loser's snapshot says + // A, the locked row says B, and the refusal is the 409 the generic + // PATCH builder has always answered with. + if subject.is_some() && current.subject != homework.subject { + return Err(AppError::Conflict(STALE_MOVE.to_string())); + } + + // What the PATCH carried is written; what it did not carry keeps the + // value just read under the lock. Under that lock this resolved + // full-row write is exactly the request-scoped SET the old builder + // emitted — except it is one static statement instead of a runtime + // build. + let new_subject = subject.clone().unwrap_or_else(|| current.subject.clone()); + let new_title = title.unwrap_or_else(|| current.title.clone()); + let new_description = match description { + None => current.description.clone(), + Some(None) => None, + Some(Some(text)) => Some(text), + }; + let new_due_at = due_at.unwrap_or(current.due_at); + let new_assigned = match assigned { + None => current.assigned.clone(), + // Clear = the whole course, stored as `'{}'`. + Some(None) => None, + Some(Some(subset)) => Some(subset), + }; + let assigned_values = new_assigned.unwrap_or_default(); + sqlx::query_as!( + Homework, + r#"UPDATE homework SET subject = $2, title = $3, description = $4, + due_at = $5, assigned = $6 + WHERE id = $1 + RETURNING id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp""#, + homework.get_id(), + new_subject, + new_title, + new_description, + new_due_at, + assigned_values, + ) + .fetch_optional(&mut *tx) + .await? + .ok_or(AppError::NotFound) + }) + .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. +/// +/// Runs inside the caller's transaction, under the homework row's lock, so +/// the check and the narrowing cannot be driven through by a submission. +async fn ensure_no_orphans( + homework: &Homework, + new_assigned: Option<&[UserId]>, + tx: &mut PgConnection, +) -> Result<(), AppError> { + // Whole-course covers everyone — no narrowing, no orphans. + let Some(subset) = new_assigned else { + return Ok(()); + }; + let submitted: Vec = sqlx::query!( + r#"SELECT app_user AS "user: UserId" FROM homework_submission WHERE homework = $1"#, + homework.get_id() + ) + .fetch_all(&mut *tx) + .await? + .into_iter() + .map(|row| row.user) + .collect(); + let graded: Vec = sqlx::query!( + r#"SELECT app_user AS "user: UserId" FROM homework_result WHERE homework = $1"#, + homework.get_id() + ) + .fetch_all(&mut *tx) + .await? + .into_iter() + .map(|row| row.user) + .collect(); + let mut blocked: Vec = Vec::new(); + for user in submitted.iter().chain(graded.iter()) { + 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 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;" - ), +/// unlink: their names are returned (collected inside the transaction, +/// before the wipes — a file row inserted after an out-of-transaction +/// collection would be deleted here while its key was already gone from the +/// list, stranding the blob) and removed after the rows are gone. +pub async fn delete( + db: &Database, + homework: Homework, +) -> Result<(Homework, Vec), AppError> { + tx_with_retry(db, true, async |tx| { + let blob_keys: Vec = sqlx::query!( + r#"SELECT file FROM homework_file + WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#, + homework.get_id() ) - .bind(("hw", homework.id.record())) + .fetch_all(&mut *tx) .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) + .into_iter() + .map(|row| row.file) + .collect(); + sqlx::query!( + r#"DELETE FROM homework_file + WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#, + homework.get_id() + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "DELETE FROM homework_result WHERE homework = $1", + homework.get_id() + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "DELETE FROM homework_submission WHERE homework = $1", + homework.get_id() + ) + .execute(&mut *tx) + .await?; + let deleted = sqlx::query_as!( + Homework, + r#"DELETE FROM homework WHERE id = $1 + RETURNING id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp""#, + homework.get_id() + ) + .fetch_optional(&mut *tx) + .await? + .ok_or(AppError::NotFound)?; + // The subject's reference is given back in this same transaction, off + // the row the delete actually removed. + sqlx::query!( + "UPDATE subject SET homework_count = GREATEST(homework_count - 1, 0) WHERE id = $1", + deleted.subject + ) + .execute(&mut *tx) + .await?; + Ok((deleted, blob_keys)) + }) + .await } #[cfg(test)] @@ -360,7 +621,10 @@ mod tests { "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, from).await.is_ok(), + "no reference left" + ); assert!( crate::db::subject::delete(&db, to).await.is_err(), "the reference moved here refuses the delete" diff --git a/src/db/homework_file.rs b/src/db/homework_file.rs index 3e9669a..2ab6a5c 100644 --- a/src/db/homework_file.rs +++ b/src/db/homework_file.rs @@ -4,56 +4,70 @@ //! 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::constant::MAX_HOMEWORK_FILES_PER_SUBMISSION; +use crate::database::{Database, tx_with_retry}; use crate::domain::course::CourseId; use crate::domain::homework::HomeworkId; use crate::domain::homework_file::HomeworkFile; +use crate::domain::homework_file::HomeworkFileId; +use crate::domain::homework_submission::HomeworkSubmissionId; +use crate::domain::note_file::{FileContentType, FileName}; 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". +/// wording). Both are decided by one guarded insert on the submission row — +/// the seat (`UPDATE … file_count + 1 WHERE file_count < $cap AND +/// graded_by_result IS NULL`) and the file row commit together in one CTE, 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: zero rows 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, + let created = sqlx::query_as!( + HomeworkFile, + r#"WITH seat AS ( + UPDATE homework_submission SET file_count = file_count + 1 + WHERE id = $2 AND file_count < $1 AND graded_by_result IS NULL + RETURNING 1 + ) + INSERT INTO homework_file (id, submission, name, content_type, size, file, created_at) + SELECT $3, $2, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id AS "id: HomeworkFileId", + submission AS "submission: HomeworkSubmissionId", + name AS "name: FileName", + content_type AS "content_type: FileContentType", + size, + file, + created_at AS "created_at: Timestamp""#, MAX_HOMEWORK_FILES_PER_SUBMISSION as i64, - SUBMISSION_OPEN_GUARD, - &file.id.record(), - &file, - db, + file.submission, + file.id, + file.name, + file.content_type, + file.size, + file.file, + file.created_at, ) - .await? - { - cap::Claimed::Made(created) => Ok(Some(created)), - cap::Claimed::Full => { + .fetch_optional(db) + .await + .map_err(|err| { + // The id is a fresh v7 minted by `new`, so a row already holding it + // is a collision, not a re-upload. + if crate::database::unique_violation(&err).is_some() { + AppError::Internal("homework file id collided".into()) + } else { + AppError::from(err) + } + })?; + match created { + Some(row) => Ok(Some(row)), + None => { if super::homework_submission::is_graded(db, &file.submission).await? { return Ok(None); } @@ -61,9 +75,6 @@ pub async fn insert(db: &Database, file: HomeworkFile) -> Result Err(AppError::Internal("homework file id collided".into())), } } @@ -74,8 +85,21 @@ pub async fn read_for( 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)) + Ok(sqlx::query_as!( + HomeworkFile, + r#"SELECT id AS "id: HomeworkFileId", + submission AS "submission: HomeworkSubmissionId", + name AS "name: FileName", + content_type AS "content_type: FileContentType", + size, + file, + created_at AS "created_at: Timestamp" + FROM homework_file WHERE id = $1 AND submission = $2"#, + id, + submission + ) + .fetch_optional(db) + .await?) } /// Read a file by id only if it hangs off a submission to `homework` — the @@ -89,16 +113,23 @@ pub async fn read_in_homework( 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()) + Ok(sqlx::query_as!( + HomeworkFile, + r#"SELECT id AS "id: HomeworkFileId", + submission AS "submission: HomeworkSubmissionId", + name AS "name: FileName", + content_type AS "content_type: FileContentType", + size, + file, + created_at AS "created_at: Timestamp" + FROM homework_file + WHERE id = $1 + AND submission IN (SELECT id FROM homework_submission WHERE homework = $2)"#, + id, + homework + ) + .fetch_optional(db) + .await?) } /// All of `submission`'s files, newest first. @@ -106,40 +137,56 @@ 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)?) + Ok(sqlx::query_as!( + HomeworkFile, + r#"SELECT id AS "id: HomeworkFileId", + submission AS "submission: HomeworkSubmissionId", + name AS "name: FileName", + content_type AS "content_type: FileContentType", + size, + file, + created_at AS "created_at: Timestamp" + FROM homework_file WHERE submission = $1 ORDER BY id DESC"#, + submission + ) + .fetch_all(db) + .await?) } -/// 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. +/// How many files `submission` holds. Counting the rows (not the counter +/// column) 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()) + let row = sqlx::query!( + r#"SELECT count(*) AS "count: i64" FROM homework_file WHERE submission = $1"#, + submission + ) + .fetch_one(db) + .await?; + Ok(row.count as usize) } /// 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. +/// the GC keys of a homework delete (collected inside the delete's own +/// transaction by [`crate::db::homework::delete`]; this read backs it and +/// the tests). 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)?) + Ok(sqlx::query!( + r#"SELECT file FROM homework_file + WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#, + homework + ) + .fetch_all(db) + .await? + .into_iter() + .map(|row| row.file) + .collect()) } /// The blob names behind every homework file of `course` — collected @@ -148,17 +195,19 @@ 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)?) + Ok(sqlx::query!( + r#"SELECT file FROM homework_file + WHERE submission IN ( + SELECT id FROM homework_submission + WHERE homework IN (SELECT id FROM homework WHERE course = $1) + )"#, + course + ) + .fetch_all(db) + .await? + .into_iter() + .map(|row| row.file) + .collect()) } /// Delete the row and give its slot back in the same transaction. The @@ -167,57 +216,58 @@ pub async fn file_keys_for_course( /// /// 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. +/// anyway. Its row lock is also the serialization point against an upload's +/// seat claim on the same row: one of the two waits, and the winner re-reads +/// the counter before moving it, so no lost round and no 500 — 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. 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) + let now = Timestamp::now(); + tx_with_retry(db, false, async |tx| { + let open = sqlx::query!( + r#"UPDATE homework_submission SET updated_at = $2 + WHERE id = $1 AND graded_by_result IS NULL + RETURNING 1 AS "open: i32""#, + file.submission, + now + ) + .fetch_optional(&mut *tx) + .await?; + if open.is_none() { + return Ok(None); + } + let gone = sqlx::query_as!( + HomeworkFile, + r#"DELETE FROM homework_file WHERE id = $1 AND submission = $2 + RETURNING id AS "id: HomeworkFileId", + submission AS "submission: HomeworkSubmissionId", + name AS "name: FileName", + content_type AS "content_type: FileContentType", + size, + file, + created_at AS "created_at: Timestamp""#, + file.id, + file.submission + ) + .fetch_optional(&mut *tx) + .await?; + match gone { + Some(row) => { + sqlx::query!( + "UPDATE homework_submission SET file_count = GREATEST(file_count - 1, 0) + WHERE id = $1", + file.submission + ) + .execute(&mut *tx) + .await?; + Ok(Some(row)) + } + // The submission was open but the file had already vanished. + None => Err(AppError::NotFound), + } + }) + .await } #[cfg(test)] diff --git a/src/db/homework_result.rs b/src/db/homework_result.rs index 27b9e16..944a2de 100644 --- a/src/db/homework_result.rs +++ b/src/db/homework_result.rs @@ -5,48 +5,51 @@ //! 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::database::{Database, tx_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). +/// Record (or overwrite) the grade for (homework, user). One row per pair by +/// the pair's UNIQUE constraint, so grading is one atomic UPSERT — +/// concurrent grades for the same pair converge on one row instead of +/// racing a duplicate 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). +/// (`graded_by_result`), which is what freezes it: every student-side write +/// to that row then fails its own `graded_by_result IS NULL` 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 +/// That one case is where this statement 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. +/// land unstamped, leaving a grade beside an editable submission. What +/// forbids it here is the homework row's lock: every student-side write +/// locks the homework row across its write, and so does this transaction, so +/// the interleaving is ordered away instead of leased away — either the +/// grade saw the row to stamp, or the submission saw no grade and created +/// under a lock this transaction already held. +/// +/// Whether the pair was already graded is read one statement ahead of the +/// write, under the same lock — 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 homework row's `FOR UPDATE` is also the parent gate: the id is minted +/// fresh, so a grade landing inside a homework (or course) delete's window +/// would otherwise *re-create* 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. A vanished row answers +/// `Err(NotFound)` — the 404 the web layer's own lookup would have answered. pub async fn grade( db: &Database, homework: &HomeworkId, @@ -55,102 +58,73 @@ pub async fn grade( 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())) + let id = HomeworkResultId::generate(); + let now = Timestamp::now(); + tx_with_retry(db, false, async |tx| { + let alive = sqlx::query!( + r#"SELECT 1 AS "row: i32" FROM homework WHERE id = $1 FOR UPDATE"#, + homework + ) + .fetch_optional(&mut *tx) + .await?; + if alive.is_none() { + return Err(AppError::NotFound); + } + let before = sqlx::query!( + r#"SELECT 1 AS "row: i32" FROM homework_result + WHERE homework = $1 AND app_user = $2 FOR UPDATE"#, + homework, + user + ) + .fetch_optional(&mut *tx) + .await? + .is_some(); + // A regrade overwrites status, mark, grader and stamp — `id` and + // `homework`/`app_user` are the row's identity and stay. + let graded = sqlx::query_as!( + HomeworkResult, + r#"INSERT INTO homework_result (id, homework, app_user, status, mark, graded_by, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7) + ON CONFLICT (homework, app_user) DO UPDATE + SET status = EXCLUDED.status, mark = EXCLUDED.mark, + graded_by = EXCLUDED.graded_by, created_at = EXCLUDED.created_at + RETURNING id AS "id: HomeworkResultId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + status AS "status: HomeworkStatus", + mark AS "mark: Option", + graded_by AS "graded_by: UserId", + created_at AS "created_at: Timestamp""#, + id, + homework, + user, + status, + mark, + graded_by, + now, + ) + .fetch_one(&mut *tx) + .await?; + sqlx::query!( + r#"UPDATE homework_submission SET graded_by_result = $3 + WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL"#, + homework, + user, + graded.id + ) + .execute(&mut *tx) + .await?; + if !before { + sqlx::query!( + "UPDATE app_user SET marks_given_total = marks_given_total + 1 WHERE id = $1", + graded_by + ) + .execute(&mut *tx) + .await?; + } + Ok(graded) + }) + .await } /// `user`'s grade for `homework`, if graded. @@ -159,9 +133,21 @@ pub async fn read_for( homework: &HomeworkId, user: &UserId, ) -> Result, AppError> { - Ok(db - .select(HomeworkResultId::composite(homework, user).record()) - .await?) + Ok(sqlx::query_as!( + HomeworkResult, + r#"SELECT id AS "id: HomeworkResultId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + status AS "status: HomeworkStatus", + mark AS "mark: Option", + graded_by AS "graded_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework_result WHERE homework = $1 AND app_user = $2"#, + homework, + user + ) + .fetch_optional(db) + .await?) } /// Every grade for `homework` — the roster joins these onto the submissions. @@ -169,12 +155,20 @@ 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)?) + Ok(sqlx::query_as!( + HomeworkResult, + r#"SELECT id AS "id: HomeworkResultId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + status AS "status: HomeworkStatus", + mark AS "mark: Option", + graded_by AS "graded_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework_result WHERE homework = $1 ORDER BY id DESC"#, + homework + ) + .fetch_all(db) + .await?) } /// `user`'s homework grades across one course — the raw rows behind the @@ -185,17 +179,24 @@ pub async fn list_for_user_in_course( 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)?) + Ok(sqlx::query_as!( + HomeworkResult, + r#"SELECT id AS "id: HomeworkResultId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + status AS "status: HomeworkStatus", + mark AS "mark: Option", + graded_by AS "graded_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework_result + WHERE app_user = $1 + AND homework IN (SELECT id FROM homework WHERE course = $2) + ORDER BY id DESC"#, + user, + course + ) + .fetch_all(db) + .await?) } /// Un-grade (homework, user), returning the removed row (`None` if there @@ -212,53 +213,70 @@ pub async fn list_for_user_in_course( /// 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()) + tx_with_retry(db, false, async |tx| { + // The homework row's lock orders this against a concurrent grade + // (which locks the same row before inserting): either this delete + // wins and the re-grade lands after as a fresh grade, or the grade + // lands first and this removes *it*. A homework already cascaded + // away left no result rows behind — `None`, the 404 the web layer + // answers. + let alive = sqlx::query!( + r#"SELECT 1 AS "row: i32" FROM homework WHERE id = $1 FOR UPDATE"#, + homework + ) + .fetch_optional(&mut *tx) + .await?; + if alive.is_none() { + return Ok(None); + } + let gone = sqlx::query!( + r#"DELETE FROM homework_result WHERE homework = $1 AND app_user = $2 + RETURNING id AS "id: HomeworkResultId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + status AS "status: HomeworkStatus", + mark AS "mark: Option", + graded_by AS "graded_by: UserId", + created_at AS "created_at: Timestamp""#, + homework, + user + ) + .fetch_optional(&mut *tx) + .await?; + let Some(removed) = gone else { + return Ok(None); + }; + sqlx::query!( + r#"UPDATE homework_submission SET graded_by_result = NULL + WHERE homework = $1 AND app_user = $2 AND graded_by_result = $3"#, + homework, + user, + removed.id + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "UPDATE app_user SET marks_given_total = GREATEST(marks_given_total - 1, 0) WHERE id = $1", + removed.graded_by + ) + .execute(&mut *tx) + .await?; + Ok(Some(HomeworkResult { + id: removed.id, + homework: removed.homework, + user: removed.user, + status: removed.status, + mark: removed.mark, + graded_by: removed.graded_by, + created_at: removed.created_at, + })) + }) + .await } #[cfg(test)] diff --git a/src/db/homework_submission.rs b/src/db/homework_submission.rs index ff447a4..f80d4ba 100644 --- a/src/db/homework_submission.rs +++ b/src/db/homework_submission.rs @@ -5,186 +5,217 @@ //! [`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::database::{Database, tx_with_retry}; use crate::domain::homework::Homework; +use crate::domain::homework::HomeworkId; 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. +/// moves to now every time; `submitted_at` (the first-submit stamp) is kept +/// on an existing row and set only on a fresh one. Returns the row plus +/// whether it existed before this call (the web layer's 200-vs-201, and the +/// only-a-first-hand-in-earns-badges rule). /// -/// 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. +/// `preserve_text` is the photo-upload auto-create's switch: an existing row +/// keeps its text (and its stamp moves, as any touch), because the upload +/// never offered a text to replace it. A submit passes `false` — an absent +/// text clears, as on the wire. /// -/// 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 `graded_by_result IS NULL` predicate is the freeze: "not graded yet" +/// is a condition of the write itself, so a refused write answers `None` +/// instead of wiping graded work. An absent row satisfies it trivially, 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). +/// transaction, and only on the create arm — an edit moves neither counter, +/// which is what makes the live count mean one per row. /// -/// `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 +/// `counted_on_time` is stamped on the row from the same `on_time` verdict +/// the increment adds, in the same transaction: 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. +/// That deadline is `was_due`, the one read *inside this transaction* under +/// the homework row's lock — never the caller's [`Homework`] snapshot, which +/// was read before the request's gates and is exactly one `PATCH due_at` old +/// in the "teacher extends the deadline at 23:59 while the class submits" +/// moment. The lock is also the serialization point: grading locks the same +/// row before stamping, the audience-narrowing PATCH before its orphan +/// check, and a rival first hand-in before its own insert — so the +/// read-then-write below cannot interleave with any of them. (The pair's +/// UNIQUE constraint backs this up; under the lock it can never fire.) pub async fn upsert( db: &Database, homework: &Homework, user: &UserId, text: Option, -) -> Result, AppError> { - let id = HomeworkSubmissionId::composite(homework.get_id(), user); + preserve_text: bool, +) -> Result, AppError> { 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()) + tx_with_retry(db, false, async |tx| { + // The parent gate: the homework row is locked and its deadline read + // in the very transaction that writes the submission. The id is + // minted fresh, so nothing else here would fail against a homework a + // cascade already removed — it would simply create a row under it, + // badge counters and all, unreachable ever after (every route to a + // submission goes through its homework). `Err(NotFound)` means the + // homework is gone, which is the 404 the web layer's own lookup + // would have answered. + let was_due = sqlx::query!( + "SELECT due_at FROM homework WHERE id = $1 FOR UPDATE", + homework.get_id() + ) + .fetch_optional(&mut *tx) + .await? + .map(|row| row.due_at); + let Some(was_due) = was_due else { + return Err(AppError::NotFound); + }; + // Equal counts as on time, exactly as the deadline has always been + // judged. + let on_time = i64::from(now <= was_due); + + // The row, read under the homework's lock: its existence decides the + // arm (and the counters). + let existing = sqlx::query!( + r#"SELECT 1 AS "row: i32" FROM homework_submission + WHERE homework = $1 AND app_user = $2 FOR UPDATE"#, + homework.get_id(), + user + ) + .fetch_optional(&mut *tx) + .await? + .is_some(); + + if existing { + // Re-submit: text is replaced (unless the upload auto-create is + // asking — it has no text to replace), `updated_at` moves, and + // `submitted_at` is left alone. A frozen row matches nothing and + // answers `None`, the caller's 409. + let updated = if preserve_text { + sqlx::query_as!( + HomeworkSubmission, + r#"UPDATE homework_submission SET updated_at = $3 + WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL + RETURNING id AS "id: HomeworkSubmissionId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + text AS "text: Option", + submitted_at AS "submitted_at: Timestamp", + updated_at AS "updated_at: Timestamp""#, + homework.get_id(), + user, + now + ) + .fetch_optional(&mut *tx) + .await? + } else { + sqlx::query_as!( + HomeworkSubmission, + r#"UPDATE homework_submission SET text = $3, updated_at = $4 + WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL + RETURNING id AS "id: HomeworkSubmissionId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + text AS "text: Option", + submitted_at AS "submitted_at: Timestamp", + updated_at AS "updated_at: Timestamp""#, + homework.get_id(), + user, + text, + now + ) + .fetch_optional(&mut *tx) + .await? + }; + return Ok(updated.map(|submission| (submission, existing))); + } + + // First hand-in: the verdict is stored beside the counter it credits, + // so the two can never disagree. + let created = sqlx::query_as!( + HomeworkSubmission, + r#"INSERT INTO homework_submission + (id, homework, app_user, text, submitted_at, updated_at, file_count, counted_on_time) + VALUES ($1, $2, $3, $4, $5, $5, 0, $6) + RETURNING id AS "id: HomeworkSubmissionId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + text AS "text: Option", + submitted_at AS "submitted_at: Timestamp", + updated_at AS "updated_at: Timestamp""#, + HomeworkSubmissionId::generate(), + homework.get_id(), + user, + text, + now, + on_time != 0, + ) + .fetch_optional(&mut *tx) + .await?; + sqlx::query!( + r#"UPDATE app_user SET + homework_submitted_total = homework_submitted_total + 1, + homework_on_time_total = homework_on_time_total + $2 + WHERE id = $1"#, + user, + on_time + ) + .execute(&mut *tx) + .await?; + Ok(created.map(|submission| (submission, existing))) + }) + .await } /// 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. +/// even though the text row is unchanged. A targeted single-field UPDATE, so +/// the readonly `submitted_at` is never re-sent. 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) + sqlx::query_as!( + HomeworkSubmission, + r#"UPDATE homework_submission SET updated_at = $2 WHERE id = $1 + RETURNING id AS "id: HomeworkSubmissionId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + text AS "text: Option", + submitted_at AS "submitted_at: Timestamp", + updated_at AS "updated_at: Timestamp""#, + id, + now + ) + .fetch_optional(db) + .await? + .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()) + let row = sqlx::query!( + r#"SELECT EXISTS(SELECT 1 FROM homework_submission + WHERE id = $1 AND graded_by_result IS NOT NULL) AS "graded""#, + id + ) + .fetch_one(db) + .await?; + Ok(row.graded) } /// `user`'s submission to `homework`, if they have one. @@ -193,23 +224,40 @@ pub async fn read_for( homework: &crate::domain::homework::HomeworkId, user: &UserId, ) -> Result, AppError> { - Ok(db - .select(HomeworkSubmissionId::composite(homework, user).record()) - .await?) + Ok(sqlx::query_as!( + HomeworkSubmission, + r#"SELECT id AS "id: HomeworkSubmissionId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + text AS "text: Option", + submitted_at AS "submitted_at: Timestamp", + updated_at AS "updated_at: Timestamp" + FROM homework_submission WHERE homework = $1 AND app_user = $2"#, + homework, + user + ) + .fetch_optional(db) + .await?) } -/// Every submission to `homework`, in student (composite-id) order — the -/// roster's raw rows. +/// Every submission to `homework`, in creation 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)?) + Ok(sqlx::query_as!( + HomeworkSubmission, + r#"SELECT id AS "id: HomeworkSubmissionId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + text AS "text: Option", + submitted_at AS "submitted_at: Timestamp", + updated_at AS "updated_at: Timestamp" + FROM homework_submission WHERE homework = $1 ORDER BY id ASC"#, + homework + ) + .fetch_all(db) + .await?) } /// Delete this submission and its files in one transaction — so a crash @@ -217,9 +265,8 @@ pub async fn list_for_homework( /// 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. +/// answers 409): the delete carries `graded_by_result IS NULL` as its own +/// condition, so a refused delete leaves the files 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 @@ -234,12 +281,10 @@ pub async fn list_for_homework( /// 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. +/// `submitted`. A row with no stored verdict falls back to the old cut +/// (`submitted_at`, the stamp the increment judged, against the deadline +/// read here); a homework already gone counts as late, matching the +/// backfill. Floored at zero. /// /// Badges already earned are never taken away — [`crate::domain::badge`] is /// add-only, which is where that permanence lives. @@ -247,42 +292,66 @@ 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()) + tx_with_retry(db, false, async |tx| { + // The homework row's lock is the serialization point against grading: + // a grade locks the same row before it stamps, so either this delete + // refuses off the stamp, or the grade landed on a row that is now + // gone — grading absent work, which is allowed. Its `due_at` read is + // also the replay fallback's deadline. + let due = sqlx::query!( + "SELECT due_at FROM homework WHERE id = $1 FOR UPDATE", + submission.get_homework() + ) + .fetch_optional(&mut *tx) + .await? + .map(|row| row.due_at); + let gone = sqlx::query!( + r#"DELETE FROM homework_submission + WHERE id = $1 AND graded_by_result IS NULL + RETURNING id AS "id: HomeworkSubmissionId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + text AS "text: Option", + submitted_at AS "submitted_at: Timestamp", + updated_at AS "updated_at: Timestamp", + counted_on_time AS "counted_on_time: Option""#, + submission.get_id() + ) + .fetch_optional(&mut *tx) + .await?; + let Some(removed) = gone else { + // Frozen, or already withdrawn by a rival — one refusal, as + // before. + return Ok(None); + }; + sqlx::query!( + "DELETE FROM homework_file WHERE submission = $1", + removed.id + ) + .execute(&mut *tx) + .await?; + let judged_on_time = due.map(|d| removed.submitted_at <= d).unwrap_or(false); + let on_time = i64::from(removed.counted_on_time.unwrap_or(judged_on_time)); + sqlx::query!( + r#"UPDATE app_user SET + homework_submitted_total = GREATEST(homework_submitted_total - 1, 0), + homework_on_time_total = GREATEST(homework_on_time_total - $2, 0) + WHERE id = $1"#, + removed.user, + on_time + ) + .execute(&mut *tx) + .await?; + Ok(Some(HomeworkSubmission { + id: removed.id, + homework: removed.homework, + user: removed.user, + text: removed.text, + submitted_at: removed.submitted_at, + updated_at: removed.updated_at, + })) + }) + .await } #[cfg(test)] diff --git a/src/domain/homework_result.rs b/src/domain/homework_result.rs index 8d27666..0e8f074 100644 --- a/src/domain/homework_result.rs +++ b/src/domain/homework_result.rs @@ -76,6 +76,7 @@ impl HomeworkStatus { pub struct HomeworkResult { pub(crate) id: HomeworkResultId, pub(crate) homework: HomeworkId, + #[sqlx(rename = "app_user")] pub(crate) user: UserId, pub(crate) status: HomeworkStatus, pub(crate) mark: Option, diff --git a/src/domain/homework_submission.rs b/src/domain/homework_submission.rs index 8207ad8..e1f0f41 100644 --- a/src/domain/homework_submission.rs +++ b/src/domain/homework_submission.rs @@ -70,6 +70,7 @@ impl SubmissionText { pub struct HomeworkSubmission { pub(crate) id: HomeworkSubmissionId, pub(crate) homework: HomeworkId, + #[sqlx(rename = "app_user")] pub(crate) user: UserId, pub(crate) text: Option, pub(crate) submitted_at: Timestamp, diff --git a/src/service/homework.rs b/src/service/homework.rs index 1fca412..70bb81f 100644 --- a/src/service/homework.rs +++ b/src/service/homework.rs @@ -1,63 +1,26 @@ -//! Homework workflows: the PATCH re-scope with its orphan guard, the -//! cascading delete, and the shared student-side wall +//! Homework workflows: 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`]. +//! and grade workflows live in the sibling `service::homework_*` modules. +//! +//! There is no homework subsystem lock any more: the writes that used to +//! serialize on one — the PATCH's orphan guard, the delete cascade, grading, +//! and every student-side write — now contend on the *homework row itself* +//! (`SELECT … FOR UPDATE` inside each transaction), so the ordering they +//! need survives a multi-process deployment. See +//! [`crate::db::homework::update`] and +//! [`crate::db::homework_result::grade`]. 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::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" @@ -120,17 +83,10 @@ pub async fn list_for_user_in_course( /// 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. +/// The audience-narrowing orphan guard and the stale-re-tag refusal are one +/// transaction with the write in [`homework::update`], under the homework +/// row's lock — a submission (which locks the same row before writing) +/// cannot land between the check and the narrowing it would have refused. pub async fn update( db: &Database, homework: Homework, @@ -140,62 +96,17 @@ pub async fn update( 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. +/// Delete the homework: run the cascading delete (submissions, their files, +/// results, then the row — one transaction, children first) and return the +/// submission-file blob keys, which the transaction collected before the +/// wipes so no file added mid-delete can strand its blob. The web layer +/// unlinks the blobs once the rows are gone; 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?; + let (_, blob_keys) = homework::delete(db, homework).await?; Ok(blob_keys) } diff --git a/src/service/homework_file.rs b/src/service/homework_file.rs index a5d735b..068eff9 100644 --- a/src/service/homework_file.rs +++ b/src/service/homework_file.rs @@ -2,9 +2,8 @@ //! 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`]. +//! stay the web layer's — it owns `files_path`. The row writes live in +//! [`crate::db::homework_file`]. use crate::database::Database; use crate::db::homework_file; @@ -18,10 +17,11 @@ 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. +/// to carry the file (an existing one's text is preserved — `upsert` is +/// called with `preserve_text`, so even a rival hand-in landing mid-request +/// keeps its text). 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, @@ -30,7 +30,7 @@ pub async fn ensure_can_attach( 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. + // The common-case gate; the freeze itself rides on the write below. if crate::db::homework_result::read_for(db, homework.get_id(), user.get_id()) .await? .is_some() @@ -40,17 +40,21 @@ pub async fn ensure_can_attach( 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; + let Some((created, fresh)) = + homework_submission::upsert(db, homework, user.get_id(), None, true).await? + else { + return Err(GRADED); + }; + if fresh { + 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 +/// guarded insert (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 diff --git a/src/service/homework_result.rs b/src/service/homework_result.rs index e7612a8..ad79957 100644 --- a/src/service/homework_result.rs +++ b/src/service/homework_result.rs @@ -1,10 +1,9 @@ //! 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. +//! transaction lives in [`crate::db::homework_result`]; it locks the +//! homework row across the stamp, which is what orders a grade against every +//! student-side write — there is no subsystem lock here any more. use crate::database::Database; use crate::db::homework; @@ -20,11 +19,11 @@ 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: +/// re-run or decided against the row the grade transaction locks: /// -/// - 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); +/// - the homework is re-read (a homework delete is a fellow writer — both +/// contend on the homework row's lock, 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 — @@ -40,7 +39,6 @@ pub async fn grade( 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. @@ -100,7 +98,6 @@ pub async fn ungrade( id: &HomeworkId, target: &UserId, ) -> Result, AppError> { - let _guard = crate::service::homework::HOMEWORK_LOCK.write().await; homework_result::remove(db, id, target).await } diff --git a/src/service/homework_submission.rs b/src/service/homework_submission.rs index 1aeac18..8bf7df3 100644 --- a/src/service/homework_submission.rs +++ b/src/service/homework_submission.rs @@ -1,8 +1,9 @@ -//! 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). +//! Homework submission workflows: the student's submit (the graded gate and +//! the audience interlock around the guarded upsert) and the withdrawal that +//! gives the badge counters back. The row writes live in +//! [`crate::db::homework_submission`]; the freeze itself is a condition of +//! those writes, and the homework row's lock is what orders them against +//! grading — there is no subsystem lock here any more. use crate::database::Database; use crate::db::homework_file; @@ -23,29 +24,22 @@ pub struct Submitted { } /// 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. +/// read below answers the common case — graded minutes ago, and the student +/// who never submitted has no row to carry the freeze; the upsert's own +/// `graded_by_result IS NULL` condition is what holds when the grade lands +/// *while* this request runs (grade and write serialize on the homework +/// row's lock). /// -/// `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. +/// `None` from [`homework_submission::upsert`] is that freeze biting; both +/// refusals 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", ); @@ -55,12 +49,11 @@ pub async fn submit( { 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? + // `existed` comes back from the transaction itself, so the 201-vs-200 + // answer and the badge rule are exact even against a rival first + // hand-in. + let Some((submission, existed)) = + homework_submission::upsert(db, &homework, user.get_id(), text, false).await? else { return Err(GRADED); }; @@ -85,7 +78,6 @@ pub async fn submit( 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", ); diff --git a/src/web/homework.rs b/src/web/homework.rs index 627a2c5..e32c83c 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -4,8 +4,9 @@ //! and the per-course listing live under `/courses/{id}/homework` (see //! [`super::courses`]); everything shares the visibility rule //! ([`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. +//! The freeze and the audience interlock are conditions of the writes +//! themselves ([`crate::db::homework_submission`]), serialized on the +//! homework row's lock inside each transaction. use crate::web::tenant_state::State; use axum::Json; @@ -26,9 +27,7 @@ use crate::domain::exam_result::Mark; use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle}; use crate::domain::homework_file::{HomeworkFile, HomeworkFileId}; use crate::domain::homework_result::{HomeworkResult, HomeworkStatus}; -use crate::domain::homework_submission::{ - HomeworkSubmission, HomeworkSubmissionId, SubmissionText, -}; +use crate::domain::homework_submission::{HomeworkSubmission, SubmissionText}; use crate::domain::note_file::{FileContentType, FileName}; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; @@ -310,11 +309,11 @@ async fn update_homework( } crate::service::course::require_open(&st.db, &course).await?; - // 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 orphan guard and the write are one unit in + // [`service::homework::update`]: the guard reads the live submissions and + // results inside the write's transaction, under the homework row's lock — + // a submission (which locks the same row before writing) cannot land + // between the check and 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 @@ -333,7 +332,9 @@ async fn update_homework( // 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(subject_id) => Some(crate::service::subject::in_course(&st.db, subject_id, course.get_id()).await?), + Some(subject_id) => { + Some(crate::service::subject::in_course(&st.db, subject_id, course.get_id()).await?) + } None => None, }; // The orphan guard runs on exactly the requests that re-scope the audience. @@ -360,11 +361,11 @@ async fn update_homework( /// 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 -/// 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. +/// management rights over its course. The cascade is one transaction whose +/// homework-row lock keeps a submission from landing under the homework +/// mid-delete; the blob names are collected inside that transaction, before +/// the rows are wiped, and removed after, so a crash in between strands at +/// worst an unreachable file. #[utoipa::path( delete, path = "/{id}", @@ -391,7 +392,7 @@ async fn delete_homework( )); } crate::service::course::require_open(&st.db, &course).await?; - // The writer lease, the blob-key collection, and the cascade are + // 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?; @@ -548,10 +549,9 @@ async fn submit( Some(text) if !text.is_empty() => Some(SubmissionText::try_new(text)?), _ => None, }; - // 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). + // 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?; @@ -721,19 +721,15 @@ async fn upload_submission_file( const GRADED: AppError = AppError::Conflict( "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 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 - // can name a homework that no longer exists, and this handler would then - // 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. + // Re-read the homework. Streaming the body takes as long as the client + // wants it to, and a homework delete can commit inside that window — so + // the pre-flight snapshot can name a homework that no longer exists, and + // this handler would then 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. The writes below are still ordered against a delete, a grade + // and a PATCH narrowing the audience — each contends on the homework + // row's lock inside its own transaction. let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?; // Re-walled too: the term can be archived while the body streams. service::homework::require_open_term(&homework, &st.db).await?; @@ -801,8 +797,11 @@ async fn download_submission_file( let file = if user.get_role() == Role::Student { // Student: only their own file, behind the full submission gate. let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?; - let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id()); - service::homework_file::read_for(&st.db, &file_id, &submission) + let submission = + service::homework_submission::read_for(&st.db, homework.get_id(), user.get_id()) + .await? + .ok_or(AppError::NotFound)?; + service::homework_file::read_for(&st.db, &file_id, submission.get_id()) .await? .ok_or(AppError::NotFound)? } else { @@ -850,19 +849,23 @@ async fn delete_submission_file( 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 = 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 = - service::homework_file::read_for(&st.db, &HomeworkFileId::from_key(&fid), &submission) + let submission = + service::homework_submission::read_for(&st.db, homework.get_id(), user.get_id()) .await? .ok_or(AppError::NotFound)?; + let file = service::homework_file::read_for( + &st.db, + &HomeworkFileId::from_key(&fid), + submission.get_id(), + ) + .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 @@ -923,12 +926,11 @@ async fn grade_homework( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - // 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. + // The grading gates live in [`service::homework_result::grade`]; the + // grade transaction locks the homework row across the freeze stamp, which + // orders it against every student-side write — and keeps a homework + // delete from letting the upsert resurrect a result row under a vanished + // homework (the vanished row answers 404). let (homework, course) = homework_with_course(&id, &st.db).await?; if !can_manage_course(&course, &teacher) { return Err(AppError::Forbidden( @@ -974,9 +976,9 @@ async fn remove_homework_result( RequireTeacher(user): RequireTeacher, Path((id, target)): Path<(String, String)>, ) -> Result { - // 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. + // Removing the grade is what unfreezes the submission; the un-grade's + // transaction takes the homework row's lock, so it cannot straddle a + // student-side write either. let (homework, course) = homework_with_course(&id, &st.db).await?; if !can_manage_course(&course, &user) { return Err(AppError::Forbidden(