π merge: port homework to sqlx/Postgres (L5)
Browse files at this commit11 changed files +1175 -866
- src/db/homework.rs +403 -139
- src/db/homework_file.rs +183 -133
- src/db/homework_result.rs +206 -188
- src/db/homework_submission.rs +266 -197
- src/domain/homework_result.rs +1 -0
- src/domain/homework_submission.rs +1 -0
- src/service/homework.rs +21 -110
- src/service/homework_file.rs +17 -13
- src/service/homework_result.rs +7 -10
- src/service/homework_submission.rs +18 -26
- src/web/homework.rs +52 -50
src/db/homework.rsmodified+403 -139
| @@ -1,25 +1,22 @@ | |||
| 1 | -//! The `homework` table: row reads and listings, the count-and-create that | 1 | +//! The `homework` table: row reads and listings, the subject-counter claim |
| 2 | -//! pins a homework to a live subject row, the reference-counting PATCH, and | 2 | +//! that pins a homework to a live subject row, the reference-counting PATCH β |
| 3 | -//! the cascading delete. The PATCH's orphan guard and the audience gate live | 3 | +//! whose audience-narrowing orphan guard is one transaction with the write, |
| 4 | -//! in [`crate::service::homework`]. | 4 | +//! serialized on the homework row's `FOR UPDATE` lock β and the cascading |
| 5 | +//! delete. | ||
| 5 | 6 | ||
| 6 | -use surrealdb::types::RecordId; | 7 | +use crate::database::{Database, tx_with_retry}; |
| 7 | - | ||
| 8 | -use crate::constant::SUBJECT_HOMEWORK_COUNT_FIELD; | ||
| 9 | -use crate::database::Database; | ||
| 10 | -use crate::db::cap; | ||
| 11 | -use crate::db::field_update::FieldUpdate; | ||
| 12 | use crate::domain::course::CourseId; | 8 | use crate::domain::course::CourseId; |
| 13 | use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle}; | 9 | use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle}; |
| 14 | use crate::domain::subject::SubjectId; | 10 | use crate::domain::subject::SubjectId; |
| 15 | use crate::domain::timestamp::Timestamp; | 11 | use crate::domain::timestamp::Timestamp; |
| 16 | use crate::domain::user::UserId; | 12 | use crate::domain::user::UserId; |
| 17 | use crate::error::{AppError, ValidationError}; | 13 | use crate::error::{AppError, ValidationError}; |
| 14 | +use sqlx::PgConnection; | ||
| 18 | 15 | ||
| 19 | /// The answer a link to a subject that is not there gets, on create and on | 16 | /// The answer a link to a subject that is not there gets, on create and on |
| 20 | -/// re-tag alike β both claims are conditional writes on the subject row, so a | 17 | +/// re-tag alike β the conditional claim on the subject row matches nothing, |
| 21 | -/// subject a delete already removed matches nothing and the caller says exactly | 18 | +/// and the caller says exactly what the web layer's pre-flight lookup would |
| 22 | -/// what the web layer's pre-flight lookup would have. | 19 | +/// have. |
| 23 | fn subject_gone() -> AppError { | 20 | fn subject_gone() -> AppError { |
| 24 | AppError::Validation(ValidationError::Invalid { | 21 | AppError::Validation(ValidationError::Invalid { |
| 25 | field: "subject_id", | 22 | field: "subject_id", |
| @@ -27,6 +24,12 @@ fn subject_gone() -> AppError { | |||
| 27 | }) | 24 | }) |
| 28 | } | 25 | } |
| 29 | 26 | ||
| 27 | +/// What a stale re-tag answers. The shared PATCH builder | ||
| 28 | +/// ([`crate::db::field_update`]) carries the same refusal; the homework PATCH | ||
| 29 | +/// keeps its own copy because its orphan guard needs the row lock the generic | ||
| 30 | +/// builder cannot take. | ||
| 31 | +const STALE_MOVE: &str = "the link this update moves changed since it was read; re-read and retry"; | ||
| 32 | + | ||
| 30 | #[expect( | 33 | #[expect( |
| 31 | clippy::too_many_arguments, | 34 | clippy::too_many_arguments, |
| 32 | reason = "mirrors the sibling entities' create(field, field, ..) shape" | 35 | reason = "mirrors the sibling entities' create(field, field, ..) shape" |
| @@ -41,16 +44,14 @@ pub async fn create( | |||
| 41 | assigned: Option<Vec<UserId>>, | 44 | assigned: Option<Vec<UserId>>, |
| 42 | created_by: &UserId, | 45 | created_by: &UserId, |
| 43 | ) -> Result<Homework, AppError> { | 46 | ) -> Result<Homework, AppError> { |
| 44 | - // The subject's reference is taken in the very transaction that writes | 47 | + // The subject's reference is taken in the very statement that writes the |
| 45 | - // the row β the exam question's twin | 48 | + // row β the exam question's twin ([`crate::db::exam_question`]): the |
| 46 | - // ([`crate::db::exam_question`]): the subject delete | 49 | + // claim (`UPDATE subject β¦ +1`) and the insert are one CTE, so a subject |
| 47 | - // is refused while this counter is non-zero, so the create and the | 50 | + // a delete already removed matches nothing and nothing is written, which |
| 48 | - // delete contend on the subject record rather than on a cross-table | 51 | + // is the 400 the web layer's pre-flight check answers with. The subject |
| 49 | - // count neither of them sees the other move, and a crash can no longer | 52 | + // delete is refused while this counter is non-zero, so the two writers |
| 50 | - // strand a claim that would make the subject undeletable forever. A | 53 | + // contend on the subject row itself, and a crash cannot strand a claim |
| 51 | - // refused claim means the subject is already gone, which is the 400 the | 54 | + // that would make the subject undeletable forever. |
| 52 | - // web layer's pre-flight check answers with. | ||
| 53 | - let counted = subject.record(); | ||
| 54 | let homework = Homework { | 55 | let homework = Homework { |
| 55 | id: HomeworkId::generate(), | 56 | id: HomeworkId::generate(), |
| 56 | course: course.clone(), | 57 | course: course.clone(), |
| @@ -62,46 +63,111 @@ pub async fn create( | |||
| 62 | created_by: created_by.clone(), | 63 | created_by: created_by.clone(), |
| 63 | created_at: Timestamp::now(), | 64 | created_at: Timestamp::now(), |
| 64 | }; | 65 | }; |
| 65 | - let id = homework.id.record(); | 66 | + let assigned_values = homework.assigned.clone().unwrap_or_default(); |
| 66 | - match cap::claim_and_create( | 67 | + // The fresh v7 id cannot collide, so the pair-unique answer has no rival |
| 67 | - &counted, | 68 | + // here; the mapping is kept for symmetry with the other claim sites. |
| 68 | - SUBJECT_HOMEWORK_COUNT_FIELD, | 69 | + let created = sqlx::query_as!( |
| 69 | - cap::UNLIMITED, | 70 | + Homework, |
| 70 | - &id, | 71 | + r#"WITH seat AS ( |
| 71 | - &homework, | 72 | + UPDATE subject SET homework_count = homework_count + 1 |
| 72 | - db, | 73 | + WHERE id = $1 |
| 74 | + RETURNING 1 | ||
| 75 | + ) | ||
| 76 | + INSERT INTO homework (id, course, subject, title, description, due_at, assigned, created_by, created_at) | ||
| 77 | + SELECT $2, $3, $1, $4, $5, $6, $7, $8, $9 WHERE EXISTS (SELECT 1 FROM seat) | ||
| 78 | + RETURNING id AS "id: HomeworkId", | ||
| 79 | + course AS "course: CourseId", | ||
| 80 | + subject AS "subject: SubjectId", | ||
| 81 | + title AS "title: HomeworkTitle", | ||
| 82 | + description AS "description: Option<HomeworkDescription>", | ||
| 83 | + due_at AS "due_at: Timestamp", | ||
| 84 | + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END | ||
| 85 | + AS "assigned: Option<Vec<UserId>>", | ||
| 86 | + created_by AS "created_by: UserId", | ||
| 87 | + created_at AS "created_at: Timestamp""#, | ||
| 88 | + subject, | ||
| 89 | + homework.id, | ||
| 90 | + course, | ||
| 91 | + homework.title, | ||
| 92 | + homework.description, | ||
| 93 | + homework.due_at, | ||
| 94 | + assigned_values, | ||
| 95 | + homework.created_by, | ||
| 96 | + homework.created_at, | ||
| 73 | ) | 97 | ) |
| 74 | - .await? | 98 | + .fetch_optional(db) |
| 75 | - { | 99 | + .await |
| 76 | - cap::Claimed::Made(created) => Ok(created), | 100 | + .map_err(|err| { |
| 77 | - cap::Claimed::Full => Err(subject_gone()), | 101 | + if crate::database::unique_violation(&err).is_some() { |
| 78 | - cap::Claimed::Duplicate => Err(AppError::Internal("failed to create homework".into())), | 102 | + AppError::Internal("failed to create homework".into()) |
| 79 | - } | 103 | + } else { |
| 104 | + AppError::from(err) | ||
| 105 | + } | ||
| 106 | + })?; | ||
| 107 | + created.ok_or_else(subject_gone) | ||
| 80 | } | 108 | } |
| 81 | 109 | ||
| 82 | pub async fn read(db: &Database, id: &HomeworkId) -> Result<Option<Homework>, AppError> { | 110 | pub async fn read(db: &Database, id: &HomeworkId) -> Result<Option<Homework>, AppError> { |
| 83 | - Ok(db.select(id.record()).await?) | 111 | + Ok(sqlx::query_as!( |
| 112 | + Homework, | ||
| 113 | + r#"SELECT id AS "id: HomeworkId", | ||
| 114 | + course AS "course: CourseId", | ||
| 115 | + subject AS "subject: SubjectId", | ||
| 116 | + title AS "title: HomeworkTitle", | ||
| 117 | + description AS "description: Option<HomeworkDescription>", | ||
| 118 | + due_at AS "due_at: Timestamp", | ||
| 119 | + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END | ||
| 120 | + AS "assigned: Option<Vec<UserId>>", | ||
| 121 | + created_by AS "created_by: UserId", | ||
| 122 | + created_at AS "created_at: Timestamp" | ||
| 123 | + FROM homework WHERE id = $1"#, | ||
| 124 | + id | ||
| 125 | + ) | ||
| 126 | + .fetch_optional(db) | ||
| 127 | + .await?) | ||
| 84 | } | 128 | } |
| 85 | 129 | ||
| 86 | -/// The course's homework, newest first (ULID ids sort by creation). The web | 130 | +/// The course's homework, newest first (v7 ids sort by creation). The web |
| 87 | /// layer retains only the rows a given student `student_sees`. | 131 | /// layer retains only the rows a given student `student_sees`. |
| 88 | pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Homework>, AppError> { | 132 | pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Homework>, AppError> { |
| 89 | - let mut result = db | 133 | + Ok(sqlx::query_as!( |
| 90 | - .query("SELECT * FROM homework WHERE course = $course ORDER BY id DESC") | 134 | + Homework, |
| 91 | - .bind(("course", course.record())) | 135 | + r#"SELECT id AS "id: HomeworkId", |
| 92 | - .await? | 136 | + course AS "course: CourseId", |
| 93 | - .check()?; | 137 | + subject AS "subject: SubjectId", |
| 94 | - Ok(result.take::<Vec<Homework>>(0)?) | 138 | + title AS "title: HomeworkTitle", |
| 139 | + description AS "description: Option<HomeworkDescription>", | ||
| 140 | + due_at AS "due_at: Timestamp", | ||
| 141 | + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END | ||
| 142 | + AS "assigned: Option<Vec<UserId>>", | ||
| 143 | + created_by AS "created_by: UserId", | ||
| 144 | + created_at AS "created_at: Timestamp" | ||
| 145 | + FROM homework WHERE course = $1 ORDER BY id DESC"#, | ||
| 146 | + course | ||
| 147 | + ) | ||
| 148 | + .fetch_all(db) | ||
| 149 | + .await?) | ||
| 95 | } | 150 | } |
| 96 | 151 | ||
| 97 | /// Every homework in the system, newest first β the manager+ view of the | 152 | /// Every homework in the system, newest first β the manager+ view of the |
| 98 | /// cross-course "my homework" list. | 153 | /// cross-course "my homework" list. |
| 99 | pub async fn list_all(db: &Database) -> Result<Vec<Homework>, AppError> { | 154 | pub async fn list_all(db: &Database) -> Result<Vec<Homework>, AppError> { |
| 100 | - let mut result = db | 155 | + Ok(sqlx::query_as!( |
| 101 | - .query("SELECT * FROM homework ORDER BY id DESC") | 156 | + Homework, |
| 102 | - .await? | 157 | + r#"SELECT id AS "id: HomeworkId", |
| 103 | - .check()?; | 158 | + course AS "course: CourseId", |
| 104 | - Ok(result.take::<Vec<Homework>>(0)?) | 159 | + subject AS "subject: SubjectId", |
| 160 | + title AS "title: HomeworkTitle", | ||
| 161 | + description AS "description: Option<HomeworkDescription>", | ||
| 162 | + due_at AS "due_at: Timestamp", | ||
| 163 | + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END | ||
| 164 | + AS "assigned: Option<Vec<UserId>>", | ||
| 165 | + created_by AS "created_by: UserId", | ||
| 166 | + created_at AS "created_at: Timestamp" | ||
| 167 | + FROM homework ORDER BY id DESC"#, | ||
| 168 | + ) | ||
| 169 | + .fetch_all(db) | ||
| 170 | + .await?) | ||
| 105 | } | 171 | } |
| 106 | 172 | ||
| 107 | /// Every homework of every course in `courses`, newest first (one query) β | 173 | /// Every homework of every course in `courses`, newest first (one query) β |
| @@ -115,51 +181,71 @@ pub async fn list_for_courses( | |||
| 115 | if courses.is_empty() { | 181 | if courses.is_empty() { |
| 116 | return Ok(Vec::new()); | 182 | return Ok(Vec::new()); |
| 117 | } | 183 | } |
| 118 | - let records: Vec<RecordId> = courses.iter().map(CourseId::record).collect(); | 184 | + let ids: Vec<CourseId> = courses.to_vec(); |
| 119 | - let mut result = db | 185 | + Ok(sqlx::query_as!( |
| 120 | - .query("SELECT * FROM homework WHERE course IN $courses ORDER BY id DESC") | 186 | + Homework, |
| 121 | - .bind(("courses", records)) | 187 | + r#"SELECT id AS "id: HomeworkId", |
| 122 | - .await? | 188 | + course AS "course: CourseId", |
| 123 | - .check()?; | 189 | + subject AS "subject: SubjectId", |
| 124 | - Ok(result.take::<Vec<Homework>>(0)?) | 190 | + title AS "title: HomeworkTitle", |
| 191 | + description AS "description: Option<HomeworkDescription>", | ||
| 192 | + due_at AS "due_at: Timestamp", | ||
| 193 | + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END | ||
| 194 | + AS "assigned: Option<Vec<UserId>>", | ||
| 195 | + created_by AS "created_by: UserId", | ||
| 196 | + created_at AS "created_at: Timestamp" | ||
| 197 | + FROM homework WHERE course = ANY($1) ORDER BY id DESC"#, | ||
| 198 | + ids | ||
| 199 | + ) | ||
| 200 | + .fetch_all(db) | ||
| 201 | + .await?) | ||
| 125 | } | 202 | } |
| 126 | 203 | ||
| 127 | /// The homework of `course` that `user` is meant to see β whole-course ones | 204 | /// The homework of `course` that `user` is meant to see β whole-course ones |
| 128 | /// plus any subset that names them β newest first. Backs a student's (or an | 205 | /// plus any subset that names them β newest first. Backs a student's (or an |
| 129 | /// observer's) per-course homework report; mirrors | 206 | /// observer's) per-course homework report; mirrors |
| 130 | /// [`Homework::student_sees`](crate::domain::homework::Homework::student_sees) | 207 | /// [`Homework::student_sees`](crate::domain::homework::Homework::student_sees) |
| 131 | -/// in SurQL so the filter runs in the database. | 208 | +/// in SQL so the filter runs in the database. |
| 132 | pub async fn list_for_user_in_course( | 209 | pub async fn list_for_user_in_course( |
| 133 | db: &Database, | 210 | db: &Database, |
| 134 | course: &CourseId, | 211 | course: &CourseId, |
| 135 | user: &UserId, | 212 | user: &UserId, |
| 136 | ) -> Result<Vec<Homework>, AppError> { | 213 | ) -> Result<Vec<Homework>, AppError> { |
| 137 | - let mut result = db | 214 | + Ok(sqlx::query_as!( |
| 138 | - .query( | 215 | + Homework, |
| 139 | - "SELECT * FROM homework | 216 | + r#"SELECT id AS "id: HomeworkId", |
| 140 | - WHERE course = $course | 217 | + course AS "course: CourseId", |
| 141 | - AND (assigned = NONE OR assigned = [] OR $usr IN assigned) | 218 | + subject AS "subject: SubjectId", |
| 142 | - ORDER BY id DESC", | 219 | + title AS "title: HomeworkTitle", |
| 143 | - ) | 220 | + description AS "description: Option<HomeworkDescription>", |
| 144 | - .bind(("course", course.record())) | 221 | + due_at AS "due_at: Timestamp", |
| 145 | - .bind(("usr", user.record())) | 222 | + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END |
| 146 | - .await? | 223 | + AS "assigned: Option<Vec<UserId>>", |
| 147 | - .check()?; | 224 | + created_by AS "created_by: UserId", |
| 148 | - Ok(result.take::<Vec<Homework>>(0)?) | 225 | + created_at AS "created_at: Timestamp" |
| 226 | + FROM homework | ||
| 227 | + WHERE course = $1 AND (cardinality(assigned) = 0 OR $2 = ANY(assigned)) | ||
| 228 | + ORDER BY id DESC"#, | ||
| 229 | + course, | ||
| 230 | + user | ||
| 231 | + ) | ||
| 232 | + .fetch_all(db) | ||
| 233 | + .await?) | ||
| 149 | } | 234 | } |
| 150 | 235 | ||
| 151 | /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework. | 236 | /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework. |
| 152 | /// Request-scoped: every parameter is `Option`, `None` meaning the PATCH | 237 | /// Request-scoped: every parameter is `Option`, `None` meaning the PATCH |
| 153 | /// did not carry that field, so it is not written at all. Handing the | 238 | /// did not carry that field, so it is not written at all. Handing the |
| 154 | /// snapshot's value back instead would revert a concurrent edit of that | 239 | /// snapshot's value back instead would revert a concurrent edit of that |
| 155 | -/// field β scoping the `SET` alone does not prevent that, the *values* must | 240 | +/// field β under the row lock below, an uncarried field keeps the value read |
| 156 | -/// come from the request. `course`, `created_by`, and `created_at` are | 241 | +/// *under that lock*, never the handler's snapshot. `course`, `created_by`, |
| 157 | -/// `READONLY` and never appear in the write. | 242 | +/// and `created_at` are readonly and never appear in the write. |
| 158 | /// | 243 | /// |
| 159 | -/// `description` and `assigned` are nullable columns, so they take a | 244 | +/// `description` takes `Some(None)` to clear; `assigned` takes `Some(None)` |
| 160 | -/// `NONE` (clear the description / widen back to the whole course). The web | 245 | +/// to widen back to the whole course (stored as `'{}'`, read back as `None`). |
| 161 | -/// layer has already re-checked a new `due_at` against now, a new `subject` | 246 | +/// The web layer has already re-checked a new `due_at` against now, a new |
| 162 | -/// against the course, and refused a narrowing that would orphan work. | 247 | +/// `subject` against the course, and β inside the transaction here β the |
| 248 | +/// narrowing against the work that would be orphaned by it. | ||
| 163 | pub async fn update( | 249 | pub async fn update( |
| 164 | db: &Database, | 250 | db: &Database, |
| 165 | homework: Homework, | 251 | homework: Homework, |
| @@ -169,75 +255,250 @@ pub async fn update( | |||
| 169 | due_at: Option<Timestamp>, | 255 | due_at: Option<Timestamp>, |
| 170 | assigned: Option<Option<Vec<UserId>>>, | 256 | assigned: Option<Option<Vec<UserId>>>, |
| 171 | ) -> Result<Homework, AppError> { | 257 | ) -> Result<Homework, AppError> { |
| 172 | - let assigned = assigned | 258 | + tx_with_retry(db, false, async |tx| { |
| 173 | - .map(|subset| subset.map(|users| users.iter().map(UserId::record).collect::<Vec<_>>())); | 259 | + // The homework row's lock. The orphan guard's reads and the write |
| 174 | - // A re-tag moves a reference: the new subject's claim and the old one's | 260 | + // below are one transaction with it, so a submission β whose own |
| 175 | - // release ride the same transaction as the link write, so no crash can | 261 | + // transaction locks this very row before writing β cannot land |
| 176 | - // leave a count without its link (the subject would be undeletable | 262 | + // between the check and the narrowing, orphaned by an audience change |
| 177 | - // forever) or a link without its count. `subject` is required, so the | 263 | + // that just missed it. The lock also replaces the old CAS's row read: |
| 178 | - // snapshot's value is always the CAS expectation β two PATCHes moving | 264 | + // the re-tag check below compares the handler's snapshot against the |
| 179 | - // the same homework off the same subject would otherwise both claim | 265 | + // row as it is *locked*, not as it was first read. |
| 180 | - // their target, and the loser is refused with a 409 instead. The | 266 | + let current = sqlx::query_as!( |
| 181 | - // `.refcount` call is unconditional: the CAS is armed by the request | 267 | + Homework, |
| 182 | - // *carrying* `subject_id`, not by a counter moving, so a PATCH that | 268 | + r#"SELECT id AS "id: HomeworkId", |
| 183 | - // re-states the tag its snapshot showed β shifting no counter at all β | 269 | + course AS "course: CourseId", |
| 184 | - // is still refused when a rival moved the tag in between. A PATCH that | 270 | + subject AS "subject: SubjectId", |
| 185 | - // carried no `subject_id` arms nothing and writes what it always did. | 271 | + title AS "title: HomeworkTitle", |
| 186 | - let (claim, release) = subject | 272 | + description AS "description: Option<HomeworkDescription>", |
| 187 | - .as_ref() | 273 | + due_at AS "due_at: Timestamp", |
| 188 | - .filter(|next| **next != homework.subject) | 274 | + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END |
| 189 | - .map(|next| (next.record(), homework.subject.record())) | 275 | + AS "assigned: Option<Vec<UserId>>", |
| 190 | - .unzip(); | 276 | + created_by AS "created_by: UserId", |
| 191 | - FieldUpdate::new(homework.id.record()) | 277 | + created_at AS "created_at: Timestamp" |
| 192 | - .set("subject", subject.map(|subject| subject.record())) | 278 | + FROM homework WHERE id = $1 FOR UPDATE"#, |
| 193 | - .set("title", title) | 279 | + homework.get_id() |
| 194 | - .set("description", description) | ||
| 195 | - .set("due_at", due_at) | ||
| 196 | - .set("assigned", assigned) | ||
| 197 | - .refcount( | ||
| 198 | - SUBJECT_HOMEWORK_COUNT_FIELD, | ||
| 199 | - "subject", | ||
| 200 | - Some(homework.subject.record()), | ||
| 201 | - claim, | ||
| 202 | - release, | ||
| 203 | - subject_gone(), | ||
| 204 | ) | 280 | ) |
| 205 | - .run::<Homework>(db) | 281 | + .fetch_optional(&mut *tx) |
| 206 | - .await | 282 | + .await? |
| 283 | + .ok_or(AppError::NotFound)?; | ||
| 284 | + | ||
| 285 | + // The orphan guard runs on exactly the requests that re-scope the | ||
| 286 | + // audience. An absent `assigned` writes nothing, so the stored subset | ||
| 287 | + // is untouched and no narrowing can happen behind the guard's back. | ||
| 288 | + if let Some(resolved) = assigned.as_ref() { | ||
| 289 | + ensure_no_orphans(¤t, resolved.as_deref(), tx).await?; | ||
| 290 | + } | ||
| 291 | + | ||
| 292 | + // A re-tag moves a reference: the new subject's claim and the old | ||
| 293 | + // one's release ride the same transaction as the link write, so no | ||
| 294 | + // crash can leave a count without its link (the subject would be | ||
| 295 | + // undeletable forever) or a link without its count. The release goes | ||
| 296 | + // first and the claim refuses on a gone row, so a move to a deleted | ||
| 297 | + // subject is a rolled-back no-op β every abort takes the whole move | ||
| 298 | + // back with it. | ||
| 299 | + let moving = subject.as_ref().filter(|next| **next != homework.subject); | ||
| 300 | + if let Some(next) = moving { | ||
| 301 | + sqlx::query!( | ||
| 302 | + "UPDATE subject SET homework_count = GREATEST(homework_count - 1, 0) WHERE id = $1", | ||
| 303 | + current.subject | ||
| 304 | + ) | ||
| 305 | + .execute(&mut *tx) | ||
| 306 | + .await?; | ||
| 307 | + let seat = sqlx::query!( | ||
| 308 | + r#"UPDATE subject SET homework_count = homework_count + 1 | ||
| 309 | + WHERE id = $1 RETURNING 1 AS "seat: i32""#, | ||
| 310 | + next | ||
| 311 | + ) | ||
| 312 | + .fetch_optional(&mut *tx) | ||
| 313 | + .await?; | ||
| 314 | + if seat.is_none() { | ||
| 315 | + return Err(subject_gone()); | ||
| 316 | + } | ||
| 317 | + } | ||
| 318 | + | ||
| 319 | + // The stale-re-tag check. Armed by the request *carrying* the subject | ||
| 320 | + // β even when it re-states the tag its snapshot showed, shifting no | ||
| 321 | + // counter β so two PATCHes moving the same homework off the same | ||
| 322 | + // subject cannot both claim their target: the loser's snapshot says | ||
| 323 | + // A, the locked row says B, and the refusal is the 409 the generic | ||
| 324 | + // PATCH builder has always answered with. | ||
| 325 | + if subject.is_some() && current.subject != homework.subject { | ||
| 326 | + return Err(AppError::Conflict(STALE_MOVE.to_string())); | ||
| 327 | + } | ||
| 328 | + | ||
| 329 | + // What the PATCH carried is written; what it did not carry keeps the | ||
| 330 | + // value just read under the lock. Under that lock this resolved | ||
| 331 | + // full-row write is exactly the request-scoped SET the old builder | ||
| 332 | + // emitted β except it is one static statement instead of a runtime | ||
| 333 | + // build. | ||
| 334 | + let new_subject = subject.clone().unwrap_or_else(|| current.subject.clone()); | ||
| 335 | + let new_title = title.unwrap_or_else(|| current.title.clone()); | ||
| 336 | + let new_description = match description { | ||
| 337 | + None => current.description.clone(), | ||
| 338 | + Some(None) => None, | ||
| 339 | + Some(Some(text)) => Some(text), | ||
| 340 | + }; | ||
| 341 | + let new_due_at = due_at.unwrap_or(current.due_at); | ||
| 342 | + let new_assigned = match assigned { | ||
| 343 | + None => current.assigned.clone(), | ||
| 344 | + // Clear = the whole course, stored as `'{}'`. | ||
| 345 | + Some(None) => None, | ||
| 346 | + Some(Some(subset)) => Some(subset), | ||
| 347 | + }; | ||
| 348 | + let assigned_values = new_assigned.unwrap_or_default(); | ||
| 349 | + sqlx::query_as!( | ||
| 350 | + Homework, | ||
| 351 | + r#"UPDATE homework SET subject = $2, title = $3, description = $4, | ||
| 352 | + due_at = $5, assigned = $6 | ||
| 353 | + WHERE id = $1 | ||
| 354 | + RETURNING id AS "id: HomeworkId", | ||
| 355 | + course AS "course: CourseId", | ||
| 356 | + subject AS "subject: SubjectId", | ||
| 357 | + title AS "title: HomeworkTitle", | ||
| 358 | + description AS "description: Option<HomeworkDescription>", | ||
| 359 | + due_at AS "due_at: Timestamp", | ||
| 360 | + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END | ||
| 361 | + AS "assigned: Option<Vec<UserId>>", | ||
| 362 | + created_by AS "created_by: UserId", | ||
| 363 | + created_at AS "created_at: Timestamp""#, | ||
| 364 | + homework.get_id(), | ||
| 365 | + new_subject, | ||
| 366 | + new_title, | ||
| 367 | + new_description, | ||
| 368 | + new_due_at, | ||
| 369 | + assigned_values, | ||
| 370 | + ) | ||
| 371 | + .fetch_optional(&mut *tx) | ||
| 372 | + .await? | ||
| 373 | + .ok_or(AppError::NotFound) | ||
| 374 | + }) | ||
| 375 | + .await | ||
| 376 | +} | ||
| 377 | + | ||
| 378 | +/// Refuse (409) a PATCH that would narrow `homework`'s audience so a student | ||
| 379 | +/// who already submitted or was graded falls outside it β their work would be | ||
| 380 | +/// stranded. `new_assigned` is the proposed subset (`None` = whole course, in | ||
| 381 | +/// which case no one can be orphaned). The blocking students are named in the | ||
| 382 | +/// message so the teacher knows whose work to clear (or whom to keep assigned) | ||
| 383 | +/// first. | ||
| 384 | +/// | ||
| 385 | +/// Runs inside the caller's transaction, under the homework row's lock, so | ||
| 386 | +/// the check and the narrowing cannot be driven through by a submission. | ||
| 387 | +async fn ensure_no_orphans( | ||
| 388 | + homework: &Homework, | ||
| 389 | + new_assigned: Option<&[UserId]>, | ||
| 390 | + tx: &mut PgConnection, | ||
| 391 | +) -> Result<(), AppError> { | ||
| 392 | + // Whole-course covers everyone β no narrowing, no orphans. | ||
| 393 | + let Some(subset) = new_assigned else { | ||
| 394 | + return Ok(()); | ||
| 395 | + }; | ||
| 396 | + let submitted: Vec<UserId> = sqlx::query!( | ||
| 397 | + r#"SELECT app_user AS "user: UserId" FROM homework_submission WHERE homework = $1"#, | ||
| 398 | + homework.get_id() | ||
| 399 | + ) | ||
| 400 | + .fetch_all(&mut *tx) | ||
| 401 | + .await? | ||
| 402 | + .into_iter() | ||
| 403 | + .map(|row| row.user) | ||
| 404 | + .collect(); | ||
| 405 | + let graded: Vec<UserId> = sqlx::query!( | ||
| 406 | + r#"SELECT app_user AS "user: UserId" FROM homework_result WHERE homework = $1"#, | ||
| 407 | + homework.get_id() | ||
| 408 | + ) | ||
| 409 | + .fetch_all(&mut *tx) | ||
| 410 | + .await? | ||
| 411 | + .into_iter() | ||
| 412 | + .map(|row| row.user) | ||
| 413 | + .collect(); | ||
| 414 | + let mut blocked: Vec<String> = Vec::new(); | ||
| 415 | + for user in submitted.iter().chain(graded.iter()) { | ||
| 416 | + let key = user.key().to_string(); | ||
| 417 | + if !subset.contains(user) && !blocked.contains(&key) { | ||
| 418 | + blocked.push(key); | ||
| 419 | + } | ||
| 420 | + } | ||
| 421 | + if blocked.is_empty() { | ||
| 422 | + Ok(()) | ||
| 423 | + } else { | ||
| 424 | + Err(AppError::ConflictOwned(format!( | ||
| 425 | + "narrowing the assigned list would orphan existing work by {} student(s): {}", | ||
| 426 | + blocked.len(), | ||
| 427 | + blocked.join(", ") | ||
| 428 | + ))) | ||
| 429 | + } | ||
| 207 | } | 430 | } |
| 208 | 431 | ||
| 209 | /// Delete the homework and cascade its submissions, their files, and its | 432 | /// Delete the homework and cascade its submissions, their files, and its |
| 210 | /// results β one transaction, so a crash can't orphan a submission under a | 433 | /// results β one transaction, so a crash can't orphan a submission under a |
| 211 | /// vanished homework. The submission file *blobs* are the web layer's to | 434 | /// vanished homework. The submission file *blobs* are the web layer's to |
| 212 | -/// unlink: it collects their names via | 435 | +/// unlink: their names are returned (collected inside the transaction, |
| 213 | -/// [`crate::db::homework_file::file_keys_for_homework`] | 436 | +/// before the wipes β a file row inserted after an out-of-transaction |
| 214 | -/// before calling this, and removes them after the rows are gone. | 437 | +/// collection would be deleted here while its key was already gone from the |
| 215 | -pub async fn delete(db: &Database, homework: Homework) -> Result<Homework, AppError> { | 438 | +/// list, stranding the blob) and removed after the rows are gone. |
| 216 | - let mut result = db | 439 | +pub async fn delete( |
| 217 | - .query( | 440 | + db: &Database, |
| 218 | - format!( | 441 | + homework: Homework, |
| 219 | - "BEGIN TRANSACTION; | 442 | +) -> Result<(Homework, Vec<String>), AppError> { |
| 220 | - DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw); | 443 | + tx_with_retry(db, true, async |tx| { |
| 221 | - DELETE homework_submission WHERE homework = $hw; | 444 | + let blob_keys: Vec<String> = sqlx::query!( |
| 222 | - DELETE homework_result WHERE homework = $hw; | 445 | + r#"SELECT file FROM homework_file |
| 223 | - LET $gone = (DELETE $hw RETURN BEFORE); | 446 | + WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#, |
| 224 | - FOR $sub IN ($gone.subject ?? []) {{ | 447 | + homework.get_id() |
| 225 | - UPDATE $sub SET {SUBJECT_HOMEWORK_COUNT_FIELD} = | ||
| 226 | - math::max([({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) - 1, 0]) | ||
| 227 | - }}; | ||
| 228 | - RETURN $gone; | ||
| 229 | - COMMIT TRANSACTION;" | ||
| 230 | - ), | ||
| 231 | ) | 448 | ) |
| 232 | - .bind(("hw", homework.id.record())) | 449 | + .fetch_all(&mut *tx) |
| 233 | .await? | 450 | .await? |
| 234 | - .check()?; | 451 | + .into_iter() |
| 235 | - // The subject's reference is given back in this same transaction, off | 452 | + .map(|row| row.file) |
| 236 | - // what the delete actually removed. Read through the trailing `RETURN`, | 453 | + .collect(); |
| 237 | - // not a hand-counted slot β see [`crate::db::exam::delete`]. | 454 | + sqlx::query!( |
| 238 | - let slot = result.num_statements().saturating_sub(2); | 455 | + r#"DELETE FROM homework_file |
| 239 | - let deleted: Option<Homework> = result.take::<Vec<Homework>>(slot)?.into_iter().next(); | 456 | + WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#, |
| 240 | - deleted.ok_or(AppError::NotFound) | 457 | + homework.get_id() |
| 458 | + ) | ||
| 459 | + .execute(&mut *tx) | ||
| 460 | + .await?; | ||
| 461 | + sqlx::query!( | ||
| 462 | + "DELETE FROM homework_result WHERE homework = $1", | ||
| 463 | + homework.get_id() | ||
| 464 | + ) | ||
| 465 | + .execute(&mut *tx) | ||
| 466 | + .await?; | ||
| 467 | + sqlx::query!( | ||
| 468 | + "DELETE FROM homework_submission WHERE homework = $1", | ||
| 469 | + homework.get_id() | ||
| 470 | + ) | ||
| 471 | + .execute(&mut *tx) | ||
| 472 | + .await?; | ||
| 473 | + let deleted = sqlx::query_as!( | ||
| 474 | + Homework, | ||
| 475 | + r#"DELETE FROM homework WHERE id = $1 | ||
| 476 | + RETURNING id AS "id: HomeworkId", | ||
| 477 | + course AS "course: CourseId", | ||
| 478 | + subject AS "subject: SubjectId", | ||
| 479 | + title AS "title: HomeworkTitle", | ||
| 480 | + description AS "description: Option<HomeworkDescription>", | ||
| 481 | + due_at AS "due_at: Timestamp", | ||
| 482 | + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END | ||
| 483 | + AS "assigned: Option<Vec<UserId>>", | ||
| 484 | + created_by AS "created_by: UserId", | ||
| 485 | + created_at AS "created_at: Timestamp""#, | ||
| 486 | + homework.get_id() | ||
| 487 | + ) | ||
| 488 | + .fetch_optional(&mut *tx) | ||
| 489 | + .await? | ||
| 490 | + .ok_or(AppError::NotFound)?; | ||
| 491 | + // The subject's reference is given back in this same transaction, off | ||
| 492 | + // the row the delete actually removed. | ||
| 493 | + sqlx::query!( | ||
| 494 | + "UPDATE subject SET homework_count = GREATEST(homework_count - 1, 0) WHERE id = $1", | ||
| 495 | + deleted.subject | ||
| 496 | + ) | ||
| 497 | + .execute(&mut *tx) | ||
| 498 | + .await?; | ||
| 499 | + Ok((deleted, blob_keys)) | ||
| 500 | + }) | ||
| 501 | + .await | ||
| 241 | } | 502 | } |
| 242 | 503 | ||
| 243 | #[cfg(test)] | 504 | #[cfg(test)] |
| @@ -360,7 +621,10 @@ mod tests { | |||
| 360 | "the old subject is free" | 621 | "the old subject is free" |
| 361 | ); | 622 | ); |
| 362 | assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); | 623 | assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); |
| 363 | - assert!(crate::db::subject::delete(&db, from).await.is_ok(), "no reference left"); | 624 | + assert!( |
| 625 | + crate::db::subject::delete(&db, from).await.is_ok(), | ||
| 626 | + "no reference left" | ||
| 627 | + ); | ||
| 364 | assert!( | 628 | assert!( |
| 365 | crate::db::subject::delete(&db, to).await.is_err(), | 629 | crate::db::subject::delete(&db, to).await.is_err(), |
| 366 | "the reference moved here refuses the delete" | 630 | "the reference moved here refuses the delete" |
src/db/homework_file.rsmodified+183 -133
| @@ -4,56 +4,70 @@ | |||
| 4 | //! their validated fields live in [`crate::domain::homework_file`]; the | 4 | //! their validated fields live in [`crate::domain::homework_file`]; the |
| 5 | //! upload workflow around them in [`crate::service::homework_file`]. | 5 | //! upload workflow around them in [`crate::service::homework_file`]. |
| 6 | 6 | ||
| 7 | -use surrealdb::types::SurrealValue; | 7 | +use crate::constant::MAX_HOMEWORK_FILES_PER_SUBMISSION; |
| 8 | - | 8 | +use crate::database::{Database, tx_with_retry}; |
| 9 | -use crate::constant::{ | ||
| 10 | - MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD, SUBMISSION_OPEN_GUARD, | ||
| 11 | -}; | ||
| 12 | -use crate::database::{Database, transaction_with_retry}; | ||
| 13 | -use crate::db::cap; | ||
| 14 | use crate::domain::course::CourseId; | 9 | use crate::domain::course::CourseId; |
| 15 | use crate::domain::homework::HomeworkId; | 10 | use crate::domain::homework::HomeworkId; |
| 16 | use crate::domain::homework_file::HomeworkFile; | 11 | use crate::domain::homework_file::HomeworkFile; |
| 12 | +use crate::domain::homework_file::HomeworkFileId; | ||
| 13 | +use crate::domain::homework_submission::HomeworkSubmissionId; | ||
| 14 | +use crate::domain::note_file::{FileContentType, FileName}; | ||
| 17 | use crate::domain::timestamp::Timestamp; | 15 | use crate::domain::timestamp::Timestamp; |
| 18 | use crate::error::AppError; | 16 | use crate::error::AppError; |
| 19 | 17 | ||
| 20 | -/// What [`delete`]'s transaction reports: whether the submission | ||
| 21 | -/// was still open (`open` = 1, the gate bit) and the row it then removed. Two | ||
| 22 | -/// answers in one object because an empty `gone` alone cannot say whether the | ||
| 23 | -/// delete was refused or the file had simply vanished. | ||
| 24 | -#[derive(Debug, SurrealValue)] | ||
| 25 | -struct DeleteOutcome { | ||
| 26 | - open: i64, | ||
| 27 | - gone: Vec<HomeworkFile>, | ||
| 28 | -} | ||
| 29 | - | ||
| 30 | /// Persist the row assembled by | 18 | /// Persist the row assembled by |
| 31 | /// [`HomeworkFile::new`](crate::domain::homework_file::HomeworkFile::new), | 19 | /// [`HomeworkFile::new`](crate::domain::homework_file::HomeworkFile::new), |
| 32 | /// refusing once its submission already holds | 20 | /// refusing once its submission already holds |
| 33 | /// [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`) | 21 | /// [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`) |
| 34 | /// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own | 22 | /// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own |
| 35 | -/// wording). Both are decided by one [`cap::claim_when_and_create`] on the | 23 | +/// wording). Both are decided by one guarded insert on the submission row β |
| 36 | -/// submission row β the seat and the file row commit together, so a crash | 24 | +/// the seat (`UPDATE β¦ file_count + 1 WHERE file_count < $cap AND |
| 37 | -/// between them can no longer leave a slot claimed by a file that does not | 25 | +/// graded_by_result IS NULL`) and the file row commit together in one CTE, so |
| 38 | -/// exist, and a losing upload never has to be un-counted. Which of the two | 26 | +/// a crash between them can no longer leave a slot claimed by a file that |
| 39 | -/// conditions refused it is read back afterwards, off the losing path only, | 27 | +/// does not exist, and a losing upload never has to be un-counted. Which of |
| 40 | -/// and only to pick the message: `Claimed::Full` says "full *or* graded *or* | 28 | +/// the two conditions refused it is read back afterwards, off the losing |
| 41 | -/// the submission is gone". | 29 | +/// path only, and only to pick the message: zero rows says "full *or* graded |
| 30 | +/// *or* the submission is gone". | ||
| 42 | pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> { | 31 | pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> { |
| 43 | - // whole-row-save-ok: create of a fresh ULID row built in place by `new` β there is no prior row to clobber | 32 | + let created = sqlx::query_as!( |
| 44 | - match cap::claim_when_and_create( | 33 | + HomeworkFile, |
| 45 | - &file.submission.record(), | 34 | + r#"WITH seat AS ( |
| 46 | - SUBMISSION_FILE_COUNT_FIELD, | 35 | + UPDATE homework_submission SET file_count = file_count + 1 |
| 36 | + WHERE id = $2 AND file_count < $1 AND graded_by_result IS NULL | ||
| 37 | + RETURNING 1 | ||
| 38 | + ) | ||
| 39 | + INSERT INTO homework_file (id, submission, name, content_type, size, file, created_at) | ||
| 40 | + SELECT $3, $2, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat) | ||
| 41 | + RETURNING id AS "id: HomeworkFileId", | ||
| 42 | + submission AS "submission: HomeworkSubmissionId", | ||
| 43 | + name AS "name: FileName", | ||
| 44 | + content_type AS "content_type: FileContentType", | ||
| 45 | + size, | ||
| 46 | + file, | ||
| 47 | + created_at AS "created_at: Timestamp""#, | ||
| 47 | MAX_HOMEWORK_FILES_PER_SUBMISSION as i64, | 48 | MAX_HOMEWORK_FILES_PER_SUBMISSION as i64, |
| 48 | - SUBMISSION_OPEN_GUARD, | 49 | + file.submission, |
| 49 | - &file.id.record(), | 50 | + file.id, |
| 50 | - &file, | 51 | + file.name, |
| 51 | - db, | 52 | + file.content_type, |
| 53 | + file.size, | ||
| 54 | + file.file, | ||
| 55 | + file.created_at, | ||
| 52 | ) | 56 | ) |
| 53 | - .await? | 57 | + .fetch_optional(db) |
| 54 | - { | 58 | + .await |
| 55 | - cap::Claimed::Made(created) => Ok(Some(created)), | 59 | + .map_err(|err| { |
| 56 | - cap::Claimed::Full => { | 60 | + // The id is a fresh v7 minted by `new`, so a row already holding it |
| 61 | + // is a collision, not a re-upload. | ||
| 62 | + if crate::database::unique_violation(&err).is_some() { | ||
| 63 | + AppError::Internal("homework file id collided".into()) | ||
| 64 | + } else { | ||
| 65 | + AppError::from(err) | ||
| 66 | + } | ||
| 67 | + })?; | ||
| 68 | + match created { | ||
| 69 | + Some(row) => Ok(Some(row)), | ||
| 70 | + None => { | ||
| 57 | if super::homework_submission::is_graded(db, &file.submission).await? { | 71 | if super::homework_submission::is_graded(db, &file.submission).await? { |
| 58 | return Ok(None); | 72 | return Ok(None); |
| 59 | } | 73 | } |
| @@ -61,9 +75,6 @@ pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<Homework | |||
| 61 | "the submission already holds the maximum of 10 files β delete one first", | 75 | "the submission already holds the maximum of 10 files β delete one first", |
| 62 | )) | 76 | )) |
| 63 | } | 77 | } |
| 64 | - // The id is a fresh ULID minted by `new`, so a row already holding it | ||
| 65 | - // is a collision, not a re-upload. | ||
| 66 | - cap::Claimed::Duplicate => Err(AppError::Internal("homework file id collided".into())), | ||
| 67 | } | 78 | } |
| 68 | } | 79 | } |
| 69 | 80 | ||
| @@ -74,8 +85,21 @@ pub async fn read_for( | |||
| 74 | id: &crate::domain::homework_file::HomeworkFileId, | 85 | id: &crate::domain::homework_file::HomeworkFileId, |
| 75 | submission: &crate::domain::homework_submission::HomeworkSubmissionId, | 86 | submission: &crate::domain::homework_submission::HomeworkSubmissionId, |
| 76 | ) -> Result<Option<HomeworkFile>, AppError> { | 87 | ) -> Result<Option<HomeworkFile>, AppError> { |
| 77 | - let file: Option<HomeworkFile> = db.select(id.record()).await?; | 88 | + Ok(sqlx::query_as!( |
| 78 | - Ok(file.filter(|file| &file.submission == submission)) | 89 | + HomeworkFile, |
| 90 | + r#"SELECT id AS "id: HomeworkFileId", | ||
| 91 | + submission AS "submission: HomeworkSubmissionId", | ||
| 92 | + name AS "name: FileName", | ||
| 93 | + content_type AS "content_type: FileContentType", | ||
| 94 | + size, | ||
| 95 | + file, | ||
| 96 | + created_at AS "created_at: Timestamp" | ||
| 97 | + FROM homework_file WHERE id = $1 AND submission = $2"#, | ||
| 98 | + id, | ||
| 99 | + submission | ||
| 100 | + ) | ||
| 101 | + .fetch_optional(db) | ||
| 102 | + .await?) | ||
| 79 | } | 103 | } |
| 80 | 104 | ||
| 81 | /// Read a file by id only if it hangs off a submission to `homework` β the | 105 | /// 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( | |||
| 89 | id: &crate::domain::homework_file::HomeworkFileId, | 113 | id: &crate::domain::homework_file::HomeworkFileId, |
| 90 | homework: &HomeworkId, | 114 | homework: &HomeworkId, |
| 91 | ) -> Result<Option<HomeworkFile>, AppError> { | 115 | ) -> Result<Option<HomeworkFile>, AppError> { |
| 92 | - let mut result = db | 116 | + Ok(sqlx::query_as!( |
| 93 | - .query( | 117 | + HomeworkFile, |
| 94 | - "SELECT * FROM homework_file WHERE id = $id AND submission IN \ | 118 | + r#"SELECT id AS "id: HomeworkFileId", |
| 95 | - (SELECT VALUE id FROM homework_submission WHERE homework = $hw)", | 119 | + submission AS "submission: HomeworkSubmissionId", |
| 96 | - ) | 120 | + name AS "name: FileName", |
| 97 | - .bind(("id", id.record())) | 121 | + content_type AS "content_type: FileContentType", |
| 98 | - .bind(("hw", homework.record())) | 122 | + size, |
| 99 | - .await? | 123 | + file, |
| 100 | - .check()?; | 124 | + created_at AS "created_at: Timestamp" |
| 101 | - Ok(result.take::<Vec<HomeworkFile>>(0)?.into_iter().next()) | 125 | + FROM homework_file |
| 126 | + WHERE id = $1 | ||
| 127 | + AND submission IN (SELECT id FROM homework_submission WHERE homework = $2)"#, | ||
| 128 | + id, | ||
| 129 | + homework | ||
| 130 | + ) | ||
| 131 | + .fetch_optional(db) | ||
| 132 | + .await?) | ||
| 102 | } | 133 | } |
| 103 | 134 | ||
| 104 | /// All of `submission`'s files, newest first. | 135 | /// All of `submission`'s files, newest first. |
| @@ -106,40 +137,56 @@ pub async fn list_for_submission( | |||
| 106 | db: &Database, | 137 | db: &Database, |
| 107 | submission: &crate::domain::homework_submission::HomeworkSubmissionId, | 138 | submission: &crate::domain::homework_submission::HomeworkSubmissionId, |
| 108 | ) -> Result<Vec<HomeworkFile>, AppError> { | 139 | ) -> Result<Vec<HomeworkFile>, AppError> { |
| 109 | - let mut result = db | 140 | + Ok(sqlx::query_as!( |
| 110 | - .query("SELECT * FROM homework_file WHERE submission = $sub ORDER BY id DESC") | 141 | + HomeworkFile, |
| 111 | - .bind(("sub", submission.record())) | 142 | + r#"SELECT id AS "id: HomeworkFileId", |
| 112 | - .await? | 143 | + submission AS "submission: HomeworkSubmissionId", |
| 113 | - .check()?; | 144 | + name AS "name: FileName", |
| 114 | - Ok(result.take::<Vec<HomeworkFile>>(0)?) | 145 | + content_type AS "content_type: FileContentType", |
| 146 | + size, | ||
| 147 | + file, | ||
| 148 | + created_at AS "created_at: Timestamp" | ||
| 149 | + FROM homework_file WHERE submission = $1 ORDER BY id DESC"#, | ||
| 150 | + submission | ||
| 151 | + ) | ||
| 152 | + .fetch_all(db) | ||
| 153 | + .await?) | ||
| 115 | } | 154 | } |
| 116 | 155 | ||
| 117 | -/// How many files `submission` holds β the cap check reads this under the | 156 | +/// How many files `submission` holds. Counting the rows (not the counter |
| 118 | -/// lock. Counting via the rows (not a `count()` query) keeps it identical | 157 | +/// column) keeps it identical to `NoteFile`'s proven cap check; at a ceiling |
| 119 | -/// to `NoteFile`'s proven cap check; at a ceiling of 10 the cost is nil. | 158 | +/// of 10 the cost is nil. |
| 120 | pub async fn count_for_submission( | 159 | pub async fn count_for_submission( |
| 121 | db: &Database, | 160 | db: &Database, |
| 122 | submission: &crate::domain::homework_submission::HomeworkSubmissionId, | 161 | submission: &crate::domain::homework_submission::HomeworkSubmissionId, |
| 123 | ) -> Result<usize, AppError> { | 162 | ) -> Result<usize, AppError> { |
| 124 | - Ok(list_for_submission(db, submission).await?.len()) | 163 | + let row = sqlx::query!( |
| 164 | + r#"SELECT count(*) AS "count: i64" FROM homework_file WHERE submission = $1"#, | ||
| 165 | + submission | ||
| 166 | + ) | ||
| 167 | + .fetch_one(db) | ||
| 168 | + .await?; | ||
| 169 | + Ok(row.count as usize) | ||
| 125 | } | 170 | } |
| 126 | 171 | ||
| 127 | /// The blob names behind every file of every submission to `homework` β | 172 | /// The blob names behind every file of every submission to `homework` β |
| 128 | -/// collected *before* the homework-delete cascade wipes the rows, so the | 173 | +/// the GC keys of a homework delete (collected inside the delete's own |
| 129 | -/// web layer can unlink them once the rows are gone. | 174 | +/// transaction by [`crate::db::homework::delete`]; this read backs it and |
| 175 | +/// the tests). | ||
| 130 | pub async fn file_keys_for_homework( | 176 | pub async fn file_keys_for_homework( |
| 131 | db: &Database, | 177 | db: &Database, |
| 132 | homework: &HomeworkId, | 178 | homework: &HomeworkId, |
| 133 | ) -> Result<Vec<String>, AppError> { | 179 | ) -> Result<Vec<String>, AppError> { |
| 134 | - let mut result = db | 180 | + Ok(sqlx::query!( |
| 135 | - .query( | 181 | + r#"SELECT file FROM homework_file |
| 136 | - "SELECT VALUE file FROM homework_file \ | 182 | + WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#, |
| 137 | - WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw)", | 183 | + homework |
| 138 | - ) | 184 | + ) |
| 139 | - .bind(("hw", homework.record())) | 185 | + .fetch_all(db) |
| 140 | - .await? | 186 | + .await? |
| 141 | - .check()?; | 187 | + .into_iter() |
| 142 | - Ok(result.take::<Vec<String>>(0)?) | 188 | + .map(|row| row.file) |
| 189 | + .collect()) | ||
| 143 | } | 190 | } |
| 144 | 191 | ||
| 145 | /// The blob names behind every homework file of `course` β collected | 192 | /// The blob names behind every homework file of `course` β collected |
| @@ -148,17 +195,19 @@ pub async fn file_keys_for_course( | |||
| 148 | db: &Database, | 195 | db: &Database, |
| 149 | course: &CourseId, | 196 | course: &CourseId, |
| 150 | ) -> Result<Vec<String>, AppError> { | 197 | ) -> Result<Vec<String>, AppError> { |
| 151 | - let mut result = db | 198 | + Ok(sqlx::query!( |
| 152 | - .query( | 199 | + r#"SELECT file FROM homework_file |
| 153 | - "SELECT VALUE file FROM homework_file WHERE submission IN ( \ | 200 | + WHERE submission IN ( |
| 154 | - SELECT VALUE id FROM homework_submission \ | 201 | + SELECT id FROM homework_submission |
| 155 | - WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course) \ | 202 | + WHERE homework IN (SELECT id FROM homework WHERE course = $1) |
| 156 | - )", | 203 | + )"#, |
| 157 | - ) | 204 | + course |
| 158 | - .bind(("course", course.record())) | 205 | + ) |
| 159 | - .await? | 206 | + .fetch_all(db) |
| 160 | - .check()?; | 207 | + .await? |
| 161 | - Ok(result.take::<Vec<String>>(0)?) | 208 | + .into_iter() |
| 209 | + .map(|row| row.file) | ||
| 210 | + .collect()) | ||
| 162 | } | 211 | } |
| 163 | 212 | ||
| 164 | /// Delete the row and give its slot back in the same transaction. The | 213 | /// Delete the row and give its slot back in the same transaction. The |
| @@ -167,57 +216,58 @@ pub async fn file_keys_for_course( | |||
| 167 | /// | 216 | /// |
| 168 | /// The gate is the first statement: a conditional write on the *submission* | 217 | /// The gate is the first statement: a conditional write on the *submission* |
| 169 | /// row β the "last touched" re-stamp a file delete owes the late flag | 218 | /// row β the "last touched" re-stamp a file delete owes the late flag |
| 170 | -/// anyway β carrying [`SUBMISSION_OPEN_GUARD`]. Nothing else in the | 219 | +/// anyway. Its row lock is also the serialization point against an upload's |
| 171 | -/// transaction runs unless it bit, so a grade landing concurrently either | 220 | +/// seat claim on the same row: one of the two waits, and the winner re-reads |
| 172 | -/// stamps first (this delete is refused, `Ok(None)`) or stamps after (the | 221 | +/// the counter before moving it, so no lost round and no 500 β a grade |
| 173 | -/// file was already gone when it graded). `Err(NotFound)` still means the | 222 | +/// landing concurrently either stamps first (this delete is refused, |
| 174 | -/// file row itself had vanished. | 223 | +/// `Ok(None)`) or stamps after (the file was already gone when it graded). |
| 175 | -/// | 224 | +/// `Err(NotFound)` still means the file row itself had vanished. |
| 176 | -/// Sound to re-send while the store answers "conflict, retry", and it has | ||
| 177 | -/// to be: the gate writes the *submission* row, the very record an upload's | ||
| 178 | -/// [`insert`] claims its seat on, and both handlers hold only | ||
| 179 | -/// `HOMEWORK_LOCK.read()` β so a concurrent add and delete of two files of | ||
| 180 | -/// one submission contend by design, and a lost round used to come back as | ||
| 181 | -/// a 500 on a request that had written nothing. Only `UPDATE` and `DELETE` | ||
| 182 | -/// are in the batch, and neither can legitimately answer "already exists", | ||
| 183 | -/// which is what makes the whole of it re-sendable. | ||
| 184 | pub async fn delete(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> { | 225 | pub async fn delete(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> { |
| 185 | - let (mut result, mut errors) = transaction_with_retry( | 226 | + let now = Timestamp::now(); |
| 186 | - db, | 227 | + tx_with_retry(db, false, async |tx| { |
| 187 | - &format!( | 228 | + let open = sqlx::query!( |
| 188 | - "BEGIN TRANSACTION; | 229 | + r#"UPDATE homework_submission SET updated_at = $2 |
| 189 | - LET $open = (UPDATE $sub SET updated_at = $now \ | 230 | + WHERE id = $1 AND graded_by_result IS NULL |
| 190 | - WHERE {SUBMISSION_OPEN_GUARD} RETURN VALUE id); | 231 | + RETURNING 1 AS "open: i32""#, |
| 191 | - LET $gone = IF array::len($open) > 0 {{ (DELETE $id RETURN BEFORE) }} ELSE {{ [] }}; | 232 | + file.submission, |
| 192 | - UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); | 233 | + now |
| 193 | - RETURN {{ open: array::len($open), gone: $gone }}; | 234 | + ) |
| 194 | - COMMIT TRANSACTION;" | 235 | + .fetch_optional(&mut *tx) |
| 195 | - ), | 236 | + .await?; |
| 196 | - &[ | 237 | + if open.is_none() { |
| 197 | - ("id".into(), file.id.record().into_value()), | 238 | + return Ok(None); |
| 198 | - ("sub".into(), file.submission.record().into_value()), | 239 | + } |
| 199 | - ("now".into(), Timestamp::now().into_value()), | 240 | + let gone = sqlx::query_as!( |
| 200 | - ], | 241 | + HomeworkFile, |
| 201 | - &[], | 242 | + r#"DELETE FROM homework_file WHERE id = $1 AND submission = $2 |
| 202 | - ) | 243 | + RETURNING id AS "id: HomeworkFileId", |
| 203 | - .await?; | 244 | + submission AS "submission: HomeworkSubmissionId", |
| 204 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | 245 | + name AS "name: FileName", |
| 205 | - return Err(error.into()); | 246 | + content_type AS "content_type: FileContentType", |
| 206 | - } | 247 | + size, |
| 207 | - // BEGIN is slot 0, the two LETs slots 1-2 and the counter fix slot 3; | 248 | + file, |
| 208 | - // the RETURN is slot 4. | 249 | + created_at AS "created_at: Timestamp""#, |
| 209 | - let outcome: Option<DeleteOutcome> = result.take::<Vec<DeleteOutcome>>(4)?.into_iter().next(); | 250 | + file.id, |
| 210 | - let outcome = | 251 | + file.submission |
| 211 | - outcome.ok_or_else(|| AppError::Internal("failed to delete homework file".into()))?; | 252 | + ) |
| 212 | - if outcome.open == 0 { | 253 | + .fetch_optional(&mut *tx) |
| 213 | - return Ok(None); | 254 | + .await?; |
| 214 | - } | 255 | + match gone { |
| 215 | - outcome | 256 | + Some(row) => { |
| 216 | - .gone | 257 | + sqlx::query!( |
| 217 | - .into_iter() | 258 | + "UPDATE homework_submission SET file_count = GREATEST(file_count - 1, 0) |
| 218 | - .next() | 259 | + WHERE id = $1", |
| 219 | - .map(Some) | 260 | + file.submission |
| 220 | - .ok_or(AppError::NotFound) | 261 | + ) |
| 262 | + .execute(&mut *tx) | ||
| 263 | + .await?; | ||
| 264 | + Ok(Some(row)) | ||
| 265 | + } | ||
| 266 | + // The submission was open but the file had already vanished. | ||
| 267 | + None => Err(AppError::NotFound), | ||
| 268 | + } | ||
| 269 | + }) | ||
| 270 | + .await | ||
| 221 | } | 271 | } |
| 222 | 272 | ||
| 223 | #[cfg(test)] | 273 | #[cfg(test)] |
src/db/homework_result.rsmodified+206 -188
| @@ -5,48 +5,51 @@ | |||
| 5 | //! validated status and mark types in | 5 | //! validated status and mark types in |
| 6 | //! [`crate::domain::homework_result`]. | 6 | //! [`crate::domain::homework_result`]. |
| 7 | 7 | ||
| 8 | -use crate::constant::{MARKS_GIVEN_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD}; | 8 | +use crate::database::{Database, tx_with_retry}; |
| 9 | -use crate::database::{Database, transaction_with_retry}; | ||
| 10 | use crate::domain::course::CourseId; | 9 | use crate::domain::course::CourseId; |
| 11 | use crate::domain::exam_result::Mark; | 10 | use crate::domain::exam_result::Mark; |
| 12 | use crate::domain::homework::HomeworkId; | 11 | use crate::domain::homework::HomeworkId; |
| 13 | use crate::domain::homework_result::{HomeworkResult, HomeworkResultId, HomeworkStatus}; | 12 | use crate::domain::homework_result::{HomeworkResult, HomeworkResultId, HomeworkStatus}; |
| 14 | -use crate::domain::homework_submission::HomeworkSubmissionId; | ||
| 15 | use crate::domain::timestamp::Timestamp; | 13 | use crate::domain::timestamp::Timestamp; |
| 16 | use crate::domain::user::UserId; | 14 | use crate::domain::user::UserId; |
| 17 | use crate::error::AppError; | 15 | use crate::error::AppError; |
| 18 | -use surrealdb::types::SurrealValue; | ||
| 19 | 16 | ||
| 20 | -/// Record (or overwrite) the grade for (homework, user). One row per pair, | 17 | +/// Record (or overwrite) the grade for (homework, user). One row per pair by |
| 21 | -/// keyed by the deterministic composite id, so this is a single atomic | 18 | +/// the pair's UNIQUE constraint, so grading is one atomic UPSERT β |
| 22 | -/// UPSERT β concurrent grades for the same pair converge on one row instead | 19 | +/// concurrent grades for the same pair converge on one row instead of |
| 23 | -/// of racing a unique index into a 500. Grading before the due date, or | 20 | +/// racing a duplicate into a 500. Grading before the due date, or before any |
| 24 | -/// before any submission exists, is allowed (the caller's policy call). | 21 | +/// submission exists, is allowed (the caller's policy call). |
| 25 | /// | 22 | /// |
| 26 | /// In the same transaction the grade *stamps* the student's submission | 23 | /// In the same transaction the grade *stamps* the student's submission |
| 27 | -/// ([`crate::constant::SUBMISSION_GRADED_FIELD`]), which is what freezes it: | 24 | +/// (`graded_by_result`), which is what freezes it: every student-side write |
| 28 | -/// every student-side write to that row then fails its own | 25 | +/// to that row then fails its own `graded_by_result IS NULL` condition, with |
| 29 | -/// `graded_by_result = NONE` condition, with no cross-table read for a | 26 | +/// no cross-table read for a concurrent write to slip past. A submission |
| 30 | -/// concurrent write to slip past. A submission that does not exist yet is | 27 | +/// that does not exist yet is left alone β grading absent work must not |
| 31 | -/// left alone β grading absent work must not conjure a hand-in (the report reads | 28 | +/// conjure a hand-in (the report reads `submitted`/`missing`/`late` straight |
| 32 | -/// `submitted`/`missing`/`late` straight off that row). | 29 | +/// off that row). |
| 33 | /// | 30 | /// |
| 34 | -/// That one case is where this function stops defending itself: a student's | 31 | +/// That one case is where this statement stops defending itself: a student's |
| 35 | /// *first* hand-in committing between this grade and nothing-to-stamp would | 32 | /// *first* hand-in committing between this grade and nothing-to-stamp would |
| 36 | -/// land unstamped, leaving a grade beside an editable submission. Nothing | 33 | +/// land unstamped, leaving a grade beside an editable submission. What |
| 37 | -/// here forbids it β what forbids it is the caller. Grading holds | 34 | +/// forbids it here is the homework row's lock: every student-side write |
| 38 | -/// `HOMEWORK_LOCK` (see [`crate::service::homework`]) for writing across this | 35 | +/// locks the homework row across its write, and so does this transaction, so |
| 39 | -/// whole transaction while every student-side write holds it for reading across | 36 | +/// the interleaving is ordered away instead of leased away β either the |
| 40 | -/// its own, and the two leases are mutually exclusive in the one process | 37 | +/// grade saw the row to stamp, or the submission saw no grade and created |
| 41 | -/// this backend runs as, so the interleaving never gets a window. | 38 | +/// under a lock this transaction already held. |
| 42 | -// | 39 | +/// |
| 43 | -// corner-cut: that makes the freeze depend on lock discipline at the call | 40 | +/// Whether the pair was already graded is read one statement ahead of the |
| 44 | -// sites, not on this row. Moving a student write's lease to *after* its | 41 | +/// write, under the same lock β it is what keeps a regrade from crediting |
| 45 | -// database write β or sharding HOMEWORK_LOCK per homework β reopens the | 42 | +/// the grader a second time. No mark counter here: a homework mark is |
| 46 | -// window with nothing to catch it. Closing it in the db layer needs a | 43 | +/// optional and most grades are status-only, so `high_mark` is an exam-only |
| 47 | -// record both sides own (a per-(homework, user) row the grade can always | 44 | +/// family. |
| 48 | -// stamp); a tombstone submission is not it, since every read path would | 45 | +/// |
| 49 | -// have to learn to ignore it and one missed filter fabricates a hand-in. | 46 | +/// The homework row's `FOR UPDATE` is also the parent gate: the id is minted |
| 47 | +/// fresh, so a grade landing inside a homework (or course) delete's window | ||
| 48 | +/// would otherwise *re-create* a result row under a homework that is gone, | ||
| 49 | +/// readable ever after at `GET /homework/{id}/result` (no existence check | ||
| 50 | +/// there) with a `marks_given_total` no ungrade can reach, because every | ||
| 51 | +/// route to the grade goes through the homework. A vanished row answers | ||
| 52 | +/// `Err(NotFound)` β the 404 the web layer's own lookup would have answered. | ||
| 50 | pub async fn grade( | 53 | pub async fn grade( |
| 51 | db: &Database, | 54 | db: &Database, |
| 52 | homework: &HomeworkId, | 55 | homework: &HomeworkId, |
| @@ -55,102 +58,73 @@ pub async fn grade( | |||
| 55 | mark: Option<Mark>, | 58 | mark: Option<Mark>, |
| 56 | graded_by: &UserId, | 59 | graded_by: &UserId, |
| 57 | ) -> Result<HomeworkResult, AppError> { | 60 | ) -> Result<HomeworkResult, AppError> { |
| 58 | - let id = HomeworkResultId::composite(homework, user); | 61 | + let id = HomeworkResultId::generate(); |
| 59 | - let submission = HomeworkSubmissionId::composite(homework, user); | 62 | + let now = Timestamp::now(); |
| 60 | - let result = HomeworkResult { | 63 | + tx_with_retry(db, false, async |tx| { |
| 61 | - id: id.clone(), | 64 | + let alive = sqlx::query!( |
| 62 | - homework: homework.clone(), | 65 | + r#"SELECT 1 AS "row: i32" FROM homework WHERE id = $1 FOR UPDATE"#, |
| 63 | - user: user.clone(), | 66 | + homework |
| 64 | - status, | 67 | + ) |
| 65 | - mark, | 68 | + .fetch_optional(&mut *tx) |
| 66 | - graded_by: graded_by.clone(), | 69 | + .await?; |
| 67 | - created_at: Timestamp::now(), | 70 | + if alive.is_none() { |
| 68 | - }; | 71 | + return Err(AppError::NotFound); |
| 69 | - // Whether the pair was already graded is read one statement ahead of | 72 | + } |
| 70 | - // the write, inside the same transaction β it is what keeps a regrade | 73 | + let before = sqlx::query!( |
| 71 | - // from crediting the grader a second time. No mark counter here: a | 74 | + r#"SELECT 1 AS "row: i32" FROM homework_result |
| 72 | - // homework mark is optional and most grades are status-only, so | 75 | + WHERE homework = $1 AND app_user = $2 FOR UPDATE"#, |
| 73 | - // `high_mark` is an exam-only family. | 76 | + homework, |
| 74 | - // | 77 | + user |
| 75 | - // The first three statements are the parent gate, the twin of | 78 | + ) |
| 76 | - // [`crate::db::homework_submission::upsert`]'s | 79 | + .fetch_optional(&mut *tx) |
| 77 | - // and written the same way on purpose: the id is deterministic, so a | 80 | + .await? |
| 78 | - // grade landing inside a homework (or course) delete's window does not | 81 | + .is_some(); |
| 79 | - // fail β it *re-creates* a result row under a homework that is gone, | 82 | + // A regrade overwrites status, mark, grader and stamp β `id` and |
| 80 | - // readable ever after at `GET /homework/{id}/result` (no existence check | 83 | + // `homework`/`app_user` are the row's identity and stay. |
| 81 | - // there) with a `marks_given_total` no ungrade can reach, because every | 84 | + let graded = sqlx::query_as!( |
| 82 | - // route to the grade goes through the homework. Reading the homework | 85 | + HomeworkResult, |
| 83 | - // first β which the web layer does, under the lease β cannot close that: | 86 | + r#"INSERT INTO homework_result (id, homework, app_user, status, mark, graded_by, created_at) |
| 84 | - // the store conflict-checks write sets, not read sets. So the gate | 87 | + VALUES ($1, $2, $3, $4, $5, $6, $7) |
| 85 | - // *moves* a value on the homework row (`due_at` up by one and straight | 88 | + ON CONFLICT (homework, app_user) DO UPDATE |
| 86 | - // back to the captured value, leaving the row byte-identical) and the | 89 | + SET status = EXCLUDED.status, mark = EXCLUDED.mark, |
| 87 | - // cascade's delete of that same row is what refuses it. `homework` owns | 90 | + graded_by = EXCLUDED.graded_by, created_at = EXCLUDED.created_at |
| 88 | - // no counter column and is SCHEMAFULL, so `due_at` is the one `int` it | 91 | + RETURNING id AS "id: HomeworkResultId", |
| 89 | - // already has; do not invent a second spelling. | 92 | + homework AS "homework: HomeworkId", |
| 90 | - // | 93 | + app_user AS "user: UserId", |
| 91 | - // Not [`crate::db::cap::touch_and_create`], which is the same shape | 94 | + status AS "status: HomeworkStatus", |
| 92 | - // for a bare `CREATE`: a grade is an UPSERT (a regrade must overwrite), | 95 | + mark AS "mark: Option<Mark>", |
| 93 | - // and the freeze stamp and the grader's counter have to ride the same | 96 | + graded_by AS "graded_by: UserId", |
| 94 | - // transaction, which that helper has no room for. | 97 | + created_at AS "created_at: Timestamp""#, |
| 95 | - // | 98 | + id, |
| 96 | - // Sound to re-send, which is what the gate needed first β a `THROW` | 99 | + homework, |
| 97 | - // inside a plain `db.query` would have turned every lost round into a | 100 | + user, |
| 98 | - // 500. `SELECT`, `UPDATE` and the `IF`/`THROW` can never answer "already | 101 | + status, |
| 99 | - // exists", and the `UPSERT`'s id is bijective with the (homework, user) | 102 | + mark, |
| 100 | - // pair the table keys, on a table whose only index is non-unique | 103 | + graded_by, |
| 101 | - // (`homework_result_homework`), so its index entry can only ever point | 104 | + now, |
| 102 | - // at the row the id already names: it resolves onto that row instead of | 105 | + ) |
| 103 | - // colliding with it. A lost round wrote nothing. | 106 | + .fetch_one(&mut *tx) |
| 104 | - let (mut saved, mut errors) = transaction_with_retry( | 107 | + .await?; |
| 105 | - db, | 108 | + sqlx::query!( |
| 106 | - &format!( | 109 | + r#"UPDATE homework_submission SET graded_by_result = $3 |
| 107 | - "BEGIN TRANSACTION; | 110 | + WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL"#, |
| 108 | - LET $was_due = (SELECT VALUE due_at FROM ONLY $hw); | 111 | + homework, |
| 109 | - LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id); | 112 | + user, |
| 110 | - IF array::len($alive) = 0 {{ THROW 'no_homework' }}; | 113 | + graded.id |
| 111 | - UPDATE $hw SET due_at = $was_due; | 114 | + ) |
| 112 | - LET $before = (SELECT VALUE id FROM ONLY $id); | 115 | + .execute(&mut *tx) |
| 113 | - LET $after = (UPSERT $id CONTENT $row RETURN AFTER); | 116 | + .await?; |
| 114 | - UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = $id \ | 117 | + if !before { |
| 115 | - WHERE {SUBMISSION_OPEN_GUARD}; | 118 | + sqlx::query!( |
| 116 | - IF $before = NONE {{ | 119 | + "UPDATE app_user SET marks_given_total = marks_given_total + 1 WHERE id = $1", |
| 117 | - UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = | 120 | + graded_by |
| 118 | - ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1 | 121 | + ) |
| 119 | - }}; | 122 | + .execute(&mut *tx) |
| 120 | - RETURN $after; | 123 | + .await?; |
| 121 | - COMMIT TRANSACTION;" | 124 | + } |
| 122 | - ), | 125 | + Ok(graded) |
| 123 | - &[ | 126 | + }) |
| 124 | - ("hw".into(), homework.record().into_value()), | 127 | + .await |
| 125 | - ("id".into(), id.record().into_value()), | ||
| 126 | - ("sub".into(), submission.record().into_value()), | ||
| 127 | - ("grader".into(), graded_by.record().into_value()), | ||
| 128 | - ("row".into(), result.into_value()), | ||
| 129 | - ], | ||
| 130 | - &["no_homework"], | ||
| 131 | - ) | ||
| 132 | - .await?; | ||
| 133 | - // An aborted transaction errors *every* slot, most with a generic "not | ||
| 134 | - // executed" β only the THROW's own slot names the reason. | ||
| 135 | - if errors | ||
| 136 | - .values() | ||
| 137 | - .any(|error| error.to_string().contains("no_homework")) | ||
| 138 | - { | ||
| 139 | - return Err(AppError::NotFound); | ||
| 140 | - } | ||
| 141 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 142 | - return Err(error.into()); | ||
| 143 | - } | ||
| 144 | - // The trailing `RETURN` is always the last statement before `COMMIT`, | ||
| 145 | - // so its slot follows the statement count instead of a hand-kept | ||
| 146 | - // number β which the gate above would otherwise have shifted, silently | ||
| 147 | - // handing back something else. | ||
| 148 | - let slot = saved.num_statements().saturating_sub(2); | ||
| 149 | - saved | ||
| 150 | - .take::<Vec<HomeworkResult>>(slot)? | ||
| 151 | - .into_iter() | ||
| 152 | - .next() | ||
| 153 | - .ok_or_else(|| AppError::Internal("failed to record homework result".into())) | ||
| 154 | } | 128 | } |
| 155 | 129 | ||
| 156 | /// `user`'s grade for `homework`, if graded. | 130 | /// `user`'s grade for `homework`, if graded. |
| @@ -159,9 +133,21 @@ pub async fn read_for( | |||
| 159 | homework: &HomeworkId, | 133 | homework: &HomeworkId, |
| 160 | user: &UserId, | 134 | user: &UserId, |
| 161 | ) -> Result<Option<HomeworkResult>, AppError> { | 135 | ) -> Result<Option<HomeworkResult>, AppError> { |
| 162 | - Ok(db | 136 | + Ok(sqlx::query_as!( |
| 163 | - .select(HomeworkResultId::composite(homework, user).record()) | 137 | + HomeworkResult, |
| 164 | - .await?) | 138 | + r#"SELECT id AS "id: HomeworkResultId", |
| 139 | + homework AS "homework: HomeworkId", | ||
| 140 | + app_user AS "user: UserId", | ||
| 141 | + status AS "status: HomeworkStatus", | ||
| 142 | + mark AS "mark: Option<Mark>", | ||
| 143 | + graded_by AS "graded_by: UserId", | ||
| 144 | + created_at AS "created_at: Timestamp" | ||
| 145 | + FROM homework_result WHERE homework = $1 AND app_user = $2"#, | ||
| 146 | + homework, | ||
| 147 | + user | ||
| 148 | + ) | ||
| 149 | + .fetch_optional(db) | ||
| 150 | + .await?) | ||
| 165 | } | 151 | } |
| 166 | 152 | ||
| 167 | /// Every grade for `homework` β the roster joins these onto the submissions. | 153 | /// Every grade for `homework` β the roster joins these onto the submissions. |
| @@ -169,12 +155,20 @@ pub async fn list_for_homework( | |||
| 169 | db: &Database, | 155 | db: &Database, |
| 170 | homework: &HomeworkId, | 156 | homework: &HomeworkId, |
| 171 | ) -> Result<Vec<HomeworkResult>, AppError> { | 157 | ) -> Result<Vec<HomeworkResult>, AppError> { |
| 172 | - let mut result = db | 158 | + Ok(sqlx::query_as!( |
| 173 | - .query("SELECT * FROM homework_result WHERE homework = $hw ORDER BY id DESC") | 159 | + HomeworkResult, |
| 174 | - .bind(("hw", homework.record())) | 160 | + r#"SELECT id AS "id: HomeworkResultId", |
| 175 | - .await? | 161 | + homework AS "homework: HomeworkId", |
| 176 | - .check()?; | 162 | + app_user AS "user: UserId", |
| 177 | - Ok(result.take::<Vec<HomeworkResult>>(0)?) | 163 | + status AS "status: HomeworkStatus", |
| 164 | + mark AS "mark: Option<Mark>", | ||
| 165 | + graded_by AS "graded_by: UserId", | ||
| 166 | + created_at AS "created_at: Timestamp" | ||
| 167 | + FROM homework_result WHERE homework = $1 ORDER BY id DESC"#, | ||
| 168 | + homework | ||
| 169 | + ) | ||
| 170 | + .fetch_all(db) | ||
| 171 | + .await?) | ||
| 178 | } | 172 | } |
| 179 | 173 | ||
| 180 | /// `user`'s homework grades across one course β the raw rows behind the | 174 | /// `user`'s homework grades across one course β the raw rows behind the |
| @@ -185,17 +179,24 @@ pub async fn list_for_user_in_course( | |||
| 185 | course: &CourseId, | 179 | course: &CourseId, |
| 186 | user: &UserId, | 180 | user: &UserId, |
| 187 | ) -> Result<Vec<HomeworkResult>, AppError> { | 181 | ) -> Result<Vec<HomeworkResult>, AppError> { |
| 188 | - let mut result = db | 182 | + Ok(sqlx::query_as!( |
| 189 | - .query( | 183 | + HomeworkResult, |
| 190 | - "SELECT * FROM homework_result WHERE user = $usr | 184 | + r#"SELECT id AS "id: HomeworkResultId", |
| 191 | - AND homework IN (SELECT VALUE id FROM homework WHERE course = $course) | 185 | + homework AS "homework: HomeworkId", |
| 192 | - ORDER BY id DESC", | 186 | + app_user AS "user: UserId", |
| 193 | - ) | 187 | + status AS "status: HomeworkStatus", |
| 194 | - .bind(("usr", user.record())) | 188 | + mark AS "mark: Option<Mark>", |
| 195 | - .bind(("course", course.record())) | 189 | + graded_by AS "graded_by: UserId", |
| 196 | - .await? | 190 | + created_at AS "created_at: Timestamp" |
| 197 | - .check()?; | 191 | + FROM homework_result |
| 198 | - Ok(result.take::<Vec<HomeworkResult>>(0)?) | 192 | + WHERE app_user = $1 |
| 193 | + AND homework IN (SELECT id FROM homework WHERE course = $2) | ||
| 194 | + ORDER BY id DESC"#, | ||
| 195 | + user, | ||
| 196 | + course | ||
| 197 | + ) | ||
| 198 | + .fetch_all(db) | ||
| 199 | + .await?) | ||
| 199 | } | 200 | } |
| 200 | 201 | ||
| 201 | /// Un-grade (homework, user), returning the removed row (`None` if there | 202 | /// Un-grade (homework, user), returning the removed row (`None` if there |
| @@ -212,53 +213,70 @@ pub async fn list_for_user_in_course( | |||
| 212 | /// submission behind it β permanently, since an award is never revoked. | 213 | /// submission behind it β permanently, since an award is never revoked. |
| 213 | /// Given back to the *removed row's own* grader, not the caller: a manager | 214 | /// Given back to the *removed row's own* grader, not the caller: a manager |
| 214 | /// may un-grade what a teacher graded, and the credit is the teacher's. | 215 | /// may un-grade what a teacher graded, and the credit is the teacher's. |
| 215 | -/// | ||
| 216 | -/// Sound to re-send while the store answers "conflict, retry" β this is the | ||
| 217 | -/// upgrade `grade` still wants, taken here because the counter above is what | ||
| 218 | -/// makes it necessary: the grader's row is written by exam grading too, so | ||
| 219 | -/// the delete now contends with another domain, and only `DELETE`/`UPDATE` | ||
| 220 | -/// are in the batch, none of which can legitimately answer "already exists". | ||
| 221 | pub async fn remove( | 216 | pub async fn remove( |
| 222 | db: &Database, | 217 | db: &Database, |
| 223 | homework: &HomeworkId, | 218 | homework: &HomeworkId, |
| 224 | user: &UserId, | 219 | user: &UserId, |
| 225 | ) -> Result<Option<HomeworkResult>, AppError> { | 220 | ) -> Result<Option<HomeworkResult>, AppError> { |
| 226 | - let id = HomeworkResultId::composite(homework, user); | 221 | + tx_with_retry(db, false, async |tx| { |
| 227 | - let (mut result, mut errors) = transaction_with_retry( | 222 | + // The homework row's lock orders this against a concurrent grade |
| 228 | - db, | 223 | + // (which locks the same row before inserting): either this delete |
| 229 | - &format!( | 224 | + // wins and the re-grade lands after as a fresh grade, or the grade |
| 230 | - "BEGIN TRANSACTION; | 225 | + // lands first and this removes *it*. A homework already cascaded |
| 231 | - LET $gone = (DELETE $id RETURN BEFORE); | 226 | + // away left no result rows behind β `None`, the 404 the web layer |
| 232 | - UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = NONE \ | 227 | + // answers. |
| 233 | - WHERE {SUBMISSION_GRADED_FIELD} = $id; | 228 | + let alive = sqlx::query!( |
| 234 | - IF array::len($gone) > 0 {{ | 229 | + r#"SELECT 1 AS "row: i32" FROM homework WHERE id = $1 FOR UPDATE"#, |
| 235 | - LET $grader = $gone[0].graded_by; | 230 | + homework |
| 236 | - UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = | 231 | + ) |
| 237 | - math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0]) | 232 | + .fetch_optional(&mut *tx) |
| 238 | - }}; | 233 | + .await?; |
| 239 | - RETURN $gone; | 234 | + if alive.is_none() { |
| 240 | - COMMIT TRANSACTION;" | 235 | + return Ok(None); |
| 241 | - ), | 236 | + } |
| 242 | - &[ | 237 | + let gone = sqlx::query!( |
| 243 | - ("id".into(), id.record().into_value()), | 238 | + r#"DELETE FROM homework_result WHERE homework = $1 AND app_user = $2 |
| 244 | - ( | 239 | + RETURNING id AS "id: HomeworkResultId", |
| 245 | - "sub".into(), | 240 | + homework AS "homework: HomeworkId", |
| 246 | - HomeworkSubmissionId::composite(homework, user) | 241 | + app_user AS "user: UserId", |
| 247 | - .record() | 242 | + status AS "status: HomeworkStatus", |
| 248 | - .into_value(), | 243 | + mark AS "mark: Option<Mark>", |
| 249 | - ), | 244 | + graded_by AS "graded_by: UserId", |
| 250 | - ], | 245 | + created_at AS "created_at: Timestamp""#, |
| 251 | - &[], | 246 | + homework, |
| 252 | - ) | 247 | + user |
| 253 | - .await?; | 248 | + ) |
| 254 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | 249 | + .fetch_optional(&mut *tx) |
| 255 | - return Err(error.into()); | 250 | + .await?; |
| 256 | - } | 251 | + let Some(removed) = gone else { |
| 257 | - // The trailing `RETURN` is always the last statement before `COMMIT`, so | 252 | + return Ok(None); |
| 258 | - // its slot follows the statement count β the hand-kept "slot 1" this | 253 | + }; |
| 259 | - // replaces was one added statement away from handing back the unstamp. | 254 | + sqlx::query!( |
| 260 | - let slot = result.num_statements().saturating_sub(2); | 255 | + r#"UPDATE homework_submission SET graded_by_result = NULL |
| 261 | - Ok(result.take::<Vec<HomeworkResult>>(slot)?.into_iter().next()) | 256 | + WHERE homework = $1 AND app_user = $2 AND graded_by_result = $3"#, |
| 257 | + homework, | ||
| 258 | + user, | ||
| 259 | + removed.id | ||
| 260 | + ) | ||
| 261 | + .execute(&mut *tx) | ||
| 262 | + .await?; | ||
| 263 | + sqlx::query!( | ||
| 264 | + "UPDATE app_user SET marks_given_total = GREATEST(marks_given_total - 1, 0) WHERE id = $1", | ||
| 265 | + removed.graded_by | ||
| 266 | + ) | ||
| 267 | + .execute(&mut *tx) | ||
| 268 | + .await?; | ||
| 269 | + Ok(Some(HomeworkResult { | ||
| 270 | + id: removed.id, | ||
| 271 | + homework: removed.homework, | ||
| 272 | + user: removed.user, | ||
| 273 | + status: removed.status, | ||
| 274 | + mark: removed.mark, | ||
| 275 | + graded_by: removed.graded_by, | ||
| 276 | + created_at: removed.created_at, | ||
| 277 | + })) | ||
| 278 | + }) | ||
| 279 | + .await | ||
| 262 | } | 280 | } |
| 263 | 281 | ||
| 264 | #[cfg(test)] | 282 | #[cfg(test)] |
src/db/homework_submission.rsmodified+266 -197
| @@ -5,186 +5,217 @@ | |||
| 5 | //! [`crate::service::homework_submission`]; the validated text type in | 5 | //! [`crate::service::homework_submission`]; the validated text type in |
| 6 | //! [`crate::domain::homework_submission`]. | 6 | //! [`crate::domain::homework_submission`]. |
| 7 | 7 | ||
| 8 | -use crate::constant::{ | 8 | +use crate::database::{Database, tx_with_retry}; |
| 9 | - HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMITTED_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, | ||
| 10 | - SUBMISSION_OPEN_GUARD, | ||
| 11 | -}; | ||
| 12 | -use crate::database::{Database, transaction_with_retry}; | ||
| 13 | use crate::domain::homework::Homework; | 9 | use crate::domain::homework::Homework; |
| 10 | +use crate::domain::homework::HomeworkId; | ||
| 14 | use crate::domain::homework_submission::{ | 11 | use crate::domain::homework_submission::{ |
| 15 | HomeworkSubmission, HomeworkSubmissionId, SubmissionText, | 12 | HomeworkSubmission, HomeworkSubmissionId, SubmissionText, |
| 16 | }; | 13 | }; |
| 17 | use crate::domain::timestamp::Timestamp; | 14 | use crate::domain::timestamp::Timestamp; |
| 18 | use crate::domain::user::UserId; | 15 | use crate::domain::user::UserId; |
| 19 | use crate::error::AppError; | 16 | use crate::error::AppError; |
| 20 | -use surrealdb::types::SurrealValue; | ||
| 21 | 17 | ||
| 22 | /// Create or re-stamp `user`'s submission to `homework`, unless a grade has | 18 | /// Create or re-stamp `user`'s submission to `homework`, unless a grade has |
| 23 | /// frozen it β `None` means frozen, and the caller answers 409. `updated_at` | 19 | /// frozen it β `None` means frozen, and the caller answers 409. `updated_at` |
| 24 | -/// moves to now every time; `submitted_at` (readonly, the first-submit stamp) | 20 | +/// moves to now every time; `submitted_at` (the first-submit stamp) is kept |
| 25 | -/// is kept on an existing row and set only on a fresh one. | 21 | +/// on an existing row and set only on a fresh one. Returns the row plus |
| 22 | +/// whether it existed before this call (the web layer's 200-vs-201, and the | ||
| 23 | +/// only-a-first-hand-in-earns-badges rule). | ||
| 26 | /// | 24 | /// |
| 27 | -/// Hand-written rather than `.content()` on purpose: `.content()` re-sends | 25 | +/// `preserve_text` is the photo-upload auto-create's switch: an existing row |
| 28 | -/// the whole row, so it would carry a `submitted_at`, and any value differing | 26 | +/// keeps its text (and its stamp moves, as any touch), because the upload |
| 29 | -/// from the stored one trips the readonly guard. The | 27 | +/// never offered a text to replace it. A submit passes `false` β an absent |
| 30 | -/// `submitted_at = submitted_at ?? $now` expression preserves it inside the | 28 | +/// text clears, as on the wire. |
| 31 | -/// one UPSERT statement β race-free without a lock, where a read-then-content | ||
| 32 | -/// could let two concurrent first-submits pick different stamps and 500. | ||
| 33 | /// | 29 | /// |
| 34 | -/// The `WHERE` is the freeze: [`SUBMISSION_OPEN_GUARD`] makes "not graded | 30 | +/// The `graded_by_result IS NULL` predicate is the freeze: "not graded yet" |
| 35 | -/// yet" a condition of this very write instead of a read a concurrent grade | 31 | +/// is a condition of the write itself, so a refused write answers `None` |
| 36 | -/// can land behind. An absent row satisfies it (the stamp is `NONE` there | 32 | +/// instead of wiping graded work. An absent row satisfies it trivially, so a |
| 37 | -/// too), so a first submit still creates. | 33 | +/// first submit still creates. |
| 38 | /// | 34 | /// |
| 39 | /// The badge counters on the student's user row move in this very | 35 | /// The badge counters on the student's user row move in this very |
| 40 | -/// transaction, and the order is load-bearing: the increment sits *after* | 36 | +/// transaction, and only on the create arm β an edit moves neither counter, |
| 41 | -/// the UPSERT and is conditional on it having matched a row, because a | 37 | +/// which is what makes the live count mean one per row. |
| 42 | -/// frozen row makes that `WHERE` match nothing **silently** (unlike | ||
| 43 | -/// [`crate::db::homework_result::grade`], which `THROW`s) β put | ||
| 44 | -/// first, it would count a submission the freeze refused. `$before = NONE` | ||
| 45 | -/// keeps it to a genuine first create, so an edit moves neither counter, | ||
| 46 | -/// which is what makes the live count mean the same thing the one-time | ||
| 47 | -/// backfill seeded (one per row; on time judged against `due_at`, equal | ||
| 48 | -/// counting as on time). | ||
| 49 | /// | 38 | /// |
| 50 | -/// `counted_on_time` is stamped on the row from the *same* `$on_time` | 39 | +/// `counted_on_time` is stamped on the row from the same `on_time` verdict |
| 51 | -/// expression the increment adds, in the same statement block: the deadline | 40 | +/// the increment adds, in the same transaction: the deadline is mutable, so |
| 52 | -/// is mutable, so a withdrawal that re-judged it against the live `due_at` | 41 | +/// a withdrawal that re-judged it against the live `due_at` gave back |
| 53 | -/// gave back something other than what was taken. Writing the verdict beside | 42 | +/// something other than what was taken. Writing the verdict beside the |
| 54 | -/// the counter is what keeps the two from ever disagreeing β read back by | 43 | +/// counter is what keeps the two from ever disagreeing β read back by |
| 55 | /// [`delete`], never re-derived. | 44 | /// [`delete`], never re-derived. |
| 56 | /// | 45 | /// |
| 57 | -/// That deadline is `$was_due`, the one the gate below already read *inside | 46 | +/// That deadline is `was_due`, the one read *inside this transaction* under |
| 58 | -/// this transaction* β never the caller's [`Homework`] snapshot, which was | 47 | +/// the homework row's lock β never the caller's [`Homework`] snapshot, which |
| 59 | -/// read before the lease and is exactly one `PATCH due_at` old in the | 48 | +/// was read before the request's gates and is exactly one `PATCH due_at` old |
| 60 | -/// "teacher extends the deadline at 23:59 while the class submits" moment. | 49 | +/// in the "teacher extends the deadline at 23:59 while the class submits" |
| 61 | -/// Judging on the snapshot stored a verdict the web layer's own `late` flag | 50 | +/// moment. The lock is also the serialization point: grading locks the same |
| 62 | -/// (`updated_at > due_at`, re-derived live on every read) then contradicted | 51 | +/// row before stamping, the audience-narrowing PATCH before its orphan |
| 63 | -/// forever, in both directions. An in-process lock cannot fix this β it | 52 | +/// check, and a rival first hand-in before its own insert β so the |
| 64 | -/// orders two handlers, not two store transactions β so the comparison has | 53 | +/// read-then-write below cannot interleave with any of them. (The pair's |
| 65 | -/// to live where the write does. The whole entity is still taken (both | 54 | +/// UNIQUE constraint backs this up; under the lock it can never fire.) |
| 66 | -/// callers hold the row, and the id comes off it); its `due_at` must not be. | ||
| 67 | -/// | ||
| 68 | -/// The first three statements are the parent gate, and they are why this | ||
| 69 | -/// write cannot outlive its homework: the id is deterministic, so nothing | ||
| 70 | -/// else here would fail against a homework a cascade already removed β it | ||
| 71 | -/// would simply re-create the row, badge counters and all, unreachable ever | ||
| 72 | -/// after (every route to a submission goes through its homework). A *read* | ||
| 73 | -/// of the homework does not close that, on either side of the call: the | ||
| 74 | -/// store does no read-set conflict detection, so a delete committing | ||
| 75 | -/// alongside is invisible to it. The gate therefore *moves* a value on the | ||
| 76 | -/// homework row β `due_at` up by one and straight back to the captured | ||
| 77 | -/// value, so the row is byte-identical afterwards β because only a write | ||
| 78 | -/// collides, and `SET x = x` is elided and never reaches the write set. It | ||
| 79 | -/// is [`crate::domain::exam_answer::ExamAnswer::save`]'s shape exactly. | ||
| 80 | -/// `Err(NotFound)` means the homework is gone, which is the 404 the web | ||
| 81 | -/// layer's own lookup would have answered. | ||
| 82 | pub async fn upsert( | 55 | pub async fn upsert( |
| 83 | db: &Database, | 56 | db: &Database, |
| 84 | homework: &Homework, | 57 | homework: &Homework, |
| 85 | user: &UserId, | 58 | user: &UserId, |
| 86 | text: Option<SubmissionText>, | 59 | text: Option<SubmissionText>, |
| 87 | -) -> Result<Option<HomeworkSubmission>, AppError> { | 60 | + preserve_text: bool, |
| 88 | - let id = HomeworkSubmissionId::composite(homework.get_id(), user); | 61 | +) -> Result<Option<(HomeworkSubmission, bool)>, AppError> { |
| 89 | let now = Timestamp::now(); | 62 | let now = Timestamp::now(); |
| 90 | - let text = text.map(|text| text.as_str().to_string()); | 63 | + tx_with_retry(db, false, async |tx| { |
| 91 | - // Sound to re-send: the UPSERT is on a deterministic id on a table with | 64 | + // The parent gate: the homework row is locked and its deadline read |
| 92 | - // no unique index, so it can never legitimately answer "already exists", | 65 | + // in the very transaction that writes the submission. The id is |
| 93 | - // and the counter UPDATEs never can either. | 66 | + // minted fresh, so nothing else here would fail against a homework a |
| 94 | - let (mut saved, mut errors) = transaction_with_retry( | 67 | + // cascade already removed β it would simply create a row under it, |
| 95 | - db, | 68 | + // badge counters and all, unreachable ever after (every route to a |
| 96 | - &format!( | 69 | + // submission goes through its homework). `Err(NotFound)` means the |
| 97 | - "BEGIN TRANSACTION; | 70 | + // homework is gone, which is the 404 the web layer's own lookup |
| 98 | - LET $was_due = (SELECT VALUE due_at FROM ONLY $hw); | 71 | + // would have answered. |
| 99 | - LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id); | 72 | + let was_due = sqlx::query!( |
| 100 | - IF array::len($alive) = 0 {{ THROW 'no_homework' }}; | 73 | + "SELECT due_at FROM homework WHERE id = $1 FOR UPDATE", |
| 101 | - UPDATE $hw SET due_at = $was_due; | 74 | + homework.get_id() |
| 102 | - LET $before = (SELECT VALUE id FROM ONLY $id); | 75 | + ) |
| 103 | - LET $on_time = $now <= $was_due; | 76 | + .fetch_optional(&mut *tx) |
| 104 | - LET $after = (UPSERT $id SET homework = $hw, user = $usr, text = $text, | 77 | + .await? |
| 105 | - updated_at = $now, submitted_at = submitted_at ?? $now | 78 | + .map(|row| row.due_at); |
| 106 | - WHERE {SUBMISSION_OPEN_GUARD} RETURN AFTER); | 79 | + let Some(was_due) = was_due else { |
| 107 | - IF $before = NONE AND array::len($after) > 0 {{ | 80 | + return Err(AppError::NotFound); |
| 108 | - UPDATE $id SET counted_on_time = $on_time; | 81 | + }; |
| 109 | - UPDATE $usr SET | 82 | + // Equal counts as on time, exactly as the deadline has always been |
| 110 | - {HOMEWORK_SUBMITTED_TOTAL_FIELD} = ({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) + 1, | 83 | + // judged. |
| 111 | - {HOMEWORK_ON_TIME_TOTAL_FIELD} = ({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) | 84 | + let on_time = i64::from(now <= was_due); |
| 112 | - + IF $on_time {{ 1 }} ELSE {{ 0 }} | 85 | + |
| 113 | - }}; | 86 | + // The row, read under the homework's lock: its existence decides the |
| 114 | - RETURN $after; | 87 | + // arm (and the counters). |
| 115 | - COMMIT TRANSACTION;" | 88 | + let existing = sqlx::query!( |
| 116 | - ), | 89 | + r#"SELECT 1 AS "row: i32" FROM homework_submission |
| 117 | - &[ | 90 | + WHERE homework = $1 AND app_user = $2 FOR UPDATE"#, |
| 118 | - ("id".into(), id.record().into_value()), | 91 | + homework.get_id(), |
| 119 | - ("hw".into(), homework.get_id().record().into_value()), | 92 | + user |
| 120 | - ("usr".into(), user.record().into_value()), | 93 | + ) |
| 121 | - ("text".into(), text.into_value()), | 94 | + .fetch_optional(&mut *tx) |
| 122 | - ("now".into(), now.into_value()), | 95 | + .await? |
| 123 | - ], | 96 | + .is_some(); |
| 124 | - &["no_homework"], | 97 | + |
| 125 | - ) | 98 | + if existing { |
| 126 | - .await?; | 99 | + // Re-submit: text is replaced (unless the upload auto-create is |
| 127 | - // An aborted transaction errors *every* slot, most with a generic "not | 100 | + // asking β it has no text to replace), `updated_at` moves, and |
| 128 | - // executed" β only the THROW's own slot names the reason. | 101 | + // `submitted_at` is left alone. A frozen row matches nothing and |
| 129 | - if errors | 102 | + // answers `None`, the caller's 409. |
| 130 | - .values() | 103 | + let updated = if preserve_text { |
| 131 | - .any(|error| error.to_string().contains("no_homework")) | 104 | + sqlx::query_as!( |
| 132 | - { | 105 | + HomeworkSubmission, |
| 133 | - return Err(AppError::NotFound); | 106 | + r#"UPDATE homework_submission SET updated_at = $3 |
| 134 | - } | 107 | + WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL |
| 135 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | 108 | + RETURNING id AS "id: HomeworkSubmissionId", |
| 136 | - return Err(error.into()); | 109 | + homework AS "homework: HomeworkId", |
| 137 | - } | 110 | + app_user AS "user: UserId", |
| 138 | - // The trailing `RETURN` is always the last statement before `COMMIT`, so | 111 | + text AS "text: Option<SubmissionText>", |
| 139 | - // its slot follows the statement count rather than a hand-kept number. | 112 | + submitted_at AS "submitted_at: Timestamp", |
| 140 | - // It returns the whole array, never `$after[0]`: a refused write makes | 113 | + updated_at AS "updated_at: Timestamp""#, |
| 141 | - // that `NONE`, which fails to deserialize ("expected object, got none") | 114 | + homework.get_id(), |
| 142 | - // instead of reading as the "frozen" the caller answers 409 to. | 115 | + user, |
| 143 | - let slot = saved.num_statements().saturating_sub(2); | 116 | + now |
| 144 | - Ok(saved | 117 | + ) |
| 145 | - .take::<Vec<HomeworkSubmission>>(slot)? | 118 | + .fetch_optional(&mut *tx) |
| 146 | - .into_iter() | 119 | + .await? |
| 147 | - .next()) | 120 | + } else { |
| 121 | + sqlx::query_as!( | ||
| 122 | + HomeworkSubmission, | ||
| 123 | + r#"UPDATE homework_submission SET text = $3, updated_at = $4 | ||
| 124 | + WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL | ||
| 125 | + RETURNING id AS "id: HomeworkSubmissionId", | ||
| 126 | + homework AS "homework: HomeworkId", | ||
| 127 | + app_user AS "user: UserId", | ||
| 128 | + text AS "text: Option<SubmissionText>", | ||
| 129 | + submitted_at AS "submitted_at: Timestamp", | ||
| 130 | + updated_at AS "updated_at: Timestamp""#, | ||
| 131 | + homework.get_id(), | ||
| 132 | + user, | ||
| 133 | + text, | ||
| 134 | + now | ||
| 135 | + ) | ||
| 136 | + .fetch_optional(&mut *tx) | ||
| 137 | + .await? | ||
| 138 | + }; | ||
| 139 | + return Ok(updated.map(|submission| (submission, existing))); | ||
| 140 | + } | ||
| 141 | + | ||
| 142 | + // First hand-in: the verdict is stored beside the counter it credits, | ||
| 143 | + // so the two can never disagree. | ||
| 144 | + let created = sqlx::query_as!( | ||
| 145 | + HomeworkSubmission, | ||
| 146 | + r#"INSERT INTO homework_submission | ||
| 147 | + (id, homework, app_user, text, submitted_at, updated_at, file_count, counted_on_time) | ||
| 148 | + VALUES ($1, $2, $3, $4, $5, $5, 0, $6) | ||
| 149 | + RETURNING id AS "id: HomeworkSubmissionId", | ||
| 150 | + homework AS "homework: HomeworkId", | ||
| 151 | + app_user AS "user: UserId", | ||
| 152 | + text AS "text: Option<SubmissionText>", | ||
| 153 | + submitted_at AS "submitted_at: Timestamp", | ||
| 154 | + updated_at AS "updated_at: Timestamp""#, | ||
| 155 | + HomeworkSubmissionId::generate(), | ||
| 156 | + homework.get_id(), | ||
| 157 | + user, | ||
| 158 | + text, | ||
| 159 | + now, | ||
| 160 | + on_time != 0, | ||
| 161 | + ) | ||
| 162 | + .fetch_optional(&mut *tx) | ||
| 163 | + .await?; | ||
| 164 | + sqlx::query!( | ||
| 165 | + r#"UPDATE app_user SET | ||
| 166 | + homework_submitted_total = homework_submitted_total + 1, | ||
| 167 | + homework_on_time_total = homework_on_time_total + $2 | ||
| 168 | + WHERE id = $1"#, | ||
| 169 | + user, | ||
| 170 | + on_time | ||
| 171 | + ) | ||
| 172 | + .execute(&mut *tx) | ||
| 173 | + .await?; | ||
| 174 | + Ok(created.map(|submission| (submission, existing))) | ||
| 175 | + }) | ||
| 176 | + .await | ||
| 148 | } | 177 | } |
| 149 | 178 | ||
| 150 | /// Re-stamp a submission's `updated_at` to now, leaving its text and files | 179 | /// Re-stamp a submission's `updated_at` to now, leaving its text and files |
| 151 | /// alone. A file add or delete modifies the submission as a whole, so its | 180 | /// alone. A file add or delete modifies the submission as a whole, so its |
| 152 | /// "last touched" clock β which drives the computed late flag β must move | 181 | /// "last touched" clock β which drives the computed late flag β must move |
| 153 | -/// even though the text row is unchanged. Free-standing because the file | 182 | +/// even though the text row is unchanged. A targeted single-field UPDATE, so |
| 154 | -/// paths hold the composite id, not always the row. A targeted single-field | 183 | +/// the readonly `submitted_at` is never re-sent. Returns the re-stamped row, |
| 155 | -/// UPDATE, so the `READONLY` `submitted_at` is never re-sent (a `.content()` | 184 | +/// or a 404 if it has since vanished. |
| 156 | -/// would trip its guard). Returns the re-stamped row, or a 404 if it has | ||
| 157 | -/// since vanished. | ||
| 158 | pub async fn touch( | 185 | pub async fn touch( |
| 159 | db: &Database, | 186 | db: &Database, |
| 160 | id: &HomeworkSubmissionId, | 187 | id: &HomeworkSubmissionId, |
| 161 | ) -> Result<HomeworkSubmission, AppError> { | 188 | ) -> Result<HomeworkSubmission, AppError> { |
| 162 | let now = Timestamp::now(); | 189 | let now = Timestamp::now(); |
| 163 | - let mut result = db | 190 | + sqlx::query_as!( |
| 164 | - .query("UPDATE $id SET updated_at = $now RETURN AFTER") | 191 | + HomeworkSubmission, |
| 165 | - .bind(("id", id.record())) | 192 | + r#"UPDATE homework_submission SET updated_at = $2 WHERE id = $1 |
| 166 | - .bind(("now", now)) | 193 | + RETURNING id AS "id: HomeworkSubmissionId", |
| 167 | - .await? | 194 | + homework AS "homework: HomeworkId", |
| 168 | - .check()?; | 195 | + app_user AS "user: UserId", |
| 169 | - result | 196 | + text AS "text: Option<SubmissionText>", |
| 170 | - .take::<Vec<HomeworkSubmission>>(0)? | 197 | + submitted_at AS "submitted_at: Timestamp", |
| 171 | - .into_iter() | 198 | + updated_at AS "updated_at: Timestamp""#, |
| 172 | - .next() | 199 | + id, |
| 173 | - .ok_or(AppError::NotFound) | 200 | + now |
| 201 | + ) | ||
| 202 | + .fetch_optional(db) | ||
| 203 | + .await? | ||
| 204 | + .ok_or(AppError::NotFound) | ||
| 174 | } | 205 | } |
| 175 | 206 | ||
| 176 | /// Whether a grade has frozen this submission. Only ever read to tell two | 207 | /// Whether a grade has frozen this submission. Only ever read to tell two |
| 177 | /// refusals apart *after* a conditional write has already refused one β the | 208 | /// refusals apart *after* a conditional write has already refused one β the |
| 178 | /// stamp on the row, never this read, is what decides. | 209 | /// stamp on the row, never this read, is what decides. |
| 179 | pub async fn is_graded(db: &Database, id: &HomeworkSubmissionId) -> Result<bool, AppError> { | 210 | pub async fn is_graded(db: &Database, id: &HomeworkSubmissionId) -> Result<bool, AppError> { |
| 180 | - let mut result = db | 211 | + let row = sqlx::query!( |
| 181 | - .query(format!( | 212 | + r#"SELECT EXISTS(SELECT 1 FROM homework_submission |
| 182 | - "SELECT VALUE id FROM $id WHERE {SUBMISSION_GRADED_FIELD} != NONE" | 213 | + WHERE id = $1 AND graded_by_result IS NOT NULL) AS "graded""#, |
| 183 | - )) | 214 | + id |
| 184 | - .bind(("id", id.record())) | 215 | + ) |
| 185 | - .await? | 216 | + .fetch_one(db) |
| 186 | - .check()?; | 217 | + .await?; |
| 187 | - Ok(!result.take::<Vec<HomeworkSubmissionId>>(0)?.is_empty()) | 218 | + Ok(row.graded) |
| 188 | } | 219 | } |
| 189 | 220 | ||
| 190 | /// `user`'s submission to `homework`, if they have one. | 221 | /// `user`'s submission to `homework`, if they have one. |
| @@ -193,23 +224,40 @@ pub async fn read_for( | |||
| 193 | homework: &crate::domain::homework::HomeworkId, | 224 | homework: &crate::domain::homework::HomeworkId, |
| 194 | user: &UserId, | 225 | user: &UserId, |
| 195 | ) -> Result<Option<HomeworkSubmission>, AppError> { | 226 | ) -> Result<Option<HomeworkSubmission>, AppError> { |
| 196 | - Ok(db | 227 | + Ok(sqlx::query_as!( |
| 197 | - .select(HomeworkSubmissionId::composite(homework, user).record()) | 228 | + HomeworkSubmission, |
| 198 | - .await?) | 229 | + r#"SELECT id AS "id: HomeworkSubmissionId", |
| 230 | + homework AS "homework: HomeworkId", | ||
| 231 | + app_user AS "user: UserId", | ||
| 232 | + text AS "text: Option<SubmissionText>", | ||
| 233 | + submitted_at AS "submitted_at: Timestamp", | ||
| 234 | + updated_at AS "updated_at: Timestamp" | ||
| 235 | + FROM homework_submission WHERE homework = $1 AND app_user = $2"#, | ||
| 236 | + homework, | ||
| 237 | + user | ||
| 238 | + ) | ||
| 239 | + .fetch_optional(db) | ||
| 240 | + .await?) | ||
| 199 | } | 241 | } |
| 200 | 242 | ||
| 201 | -/// Every submission to `homework`, in student (composite-id) order β the | 243 | +/// Every submission to `homework`, in creation order β the roster's raw rows. |
| 202 | -/// roster's raw rows. | ||
| 203 | pub async fn list_for_homework( | 244 | pub async fn list_for_homework( |
| 204 | db: &Database, | 245 | db: &Database, |
| 205 | homework: &crate::domain::homework::HomeworkId, | 246 | homework: &crate::domain::homework::HomeworkId, |
| 206 | ) -> Result<Vec<HomeworkSubmission>, AppError> { | 247 | ) -> Result<Vec<HomeworkSubmission>, AppError> { |
| 207 | - let mut result = db | 248 | + Ok(sqlx::query_as!( |
| 208 | - .query("SELECT * FROM homework_submission WHERE homework = $hw ORDER BY id ASC") | 249 | + HomeworkSubmission, |
| 209 | - .bind(("hw", homework.record())) | 250 | + r#"SELECT id AS "id: HomeworkSubmissionId", |
| 210 | - .await? | 251 | + homework AS "homework: HomeworkId", |
| 211 | - .check()?; | 252 | + app_user AS "user: UserId", |
| 212 | - Ok(result.take::<Vec<HomeworkSubmission>>(0)?) | 253 | + text AS "text: Option<SubmissionText>", |
| 254 | + submitted_at AS "submitted_at: Timestamp", | ||
| 255 | + updated_at AS "updated_at: Timestamp" | ||
| 256 | + FROM homework_submission WHERE homework = $1 ORDER BY id ASC"#, | ||
| 257 | + homework | ||
| 258 | + ) | ||
| 259 | + .fetch_all(db) | ||
| 260 | + .await?) | ||
| 213 | } | 261 | } |
| 214 | 262 | ||
| 215 | /// Delete this submission and its files in one transaction β so a crash | 263 | /// Delete this submission and its files in one transaction β so a crash |
| @@ -217,9 +265,8 @@ pub async fn list_for_homework( | |||
| 217 | /// are the web layer's to unlink: it lists them | 265 | /// are the web layer's to unlink: it lists them |
| 218 | /// ([`crate::db::homework_file::list_for_submission`]) | 266 | /// ([`crate::db::homework_file::list_for_submission`]) |
| 219 | /// before calling this. `None` means a grade froze the row (the caller | 267 | /// before calling this. `None` means a grade froze the row (the caller |
| 220 | -/// answers 409): the submission's own delete carries | 268 | +/// answers 409): the delete carries `graded_by_result IS NULL` as its own |
| 221 | -/// [`SUBMISSION_OPEN_GUARD`], and the file wipe is conditional on it having | 269 | +/// condition, so a refused delete leaves the files standing too. |
| 222 | -/// bitten, so a refused delete leaves the children standing too. | ||
| 223 | /// | 270 | /// |
| 224 | /// The one place either badge counter comes back down, and deliberately the | 271 | /// The one place either badge counter comes back down, and deliberately the |
| 225 | /// only one: this route is student-callable on their own row, so without it | 272 | /// only one: this route is student-callable on their own row, so without it |
| @@ -234,12 +281,10 @@ pub async fn list_for_homework( | |||
| 234 | /// and gave back something other than what was taken β extend it after a | 281 | /// and gave back something other than what was taken β extend it after a |
| 235 | /// late hand-in and this debited a credit that was never given; pull it back | 282 | /// late hand-in and this debited a credit that was never given; pull it back |
| 236 | /// after a punctual one and it debited nothing, leaving `on_time` above | 283 | /// after a punctual one and it debited nothing, leaving `on_time` above |
| 237 | -/// `submitted`. A row from before the column exists carries no verdict, and | 284 | +/// `submitted`. A row with no stored verdict falls back to the old cut |
| 238 | -/// cannot be given one for a credit that already happened, so it falls back | 285 | +/// (`submitted_at`, the stamp the increment judged, against the deadline |
| 239 | -/// to the old cut (`submitted_at`, the readonly stamp the increment judged, | 286 | +/// read here); a homework already gone counts as late, matching the |
| 240 | -/// against the live deadline); a dangling `homework` link leaves `$due` | 287 | +/// backfill. Floored at zero. |
| 241 | -/// `NONE` there, which compares false and so counts as late, matching the | ||
| 242 | -/// backfill. Floored at zero: a row that predates the columns has none. | ||
| 243 | /// | 288 | /// |
| 244 | /// Badges already earned are never taken away β [`crate::domain::badge`] is | 289 | /// Badges already earned are never taken away β [`crate::domain::badge`] is |
| 245 | /// add-only, which is where that permanence lives. | 290 | /// add-only, which is where that permanence lives. |
| @@ -247,42 +292,66 @@ pub async fn delete( | |||
| 247 | db: &Database, | 292 | db: &Database, |
| 248 | submission: HomeworkSubmission, | 293 | submission: HomeworkSubmission, |
| 249 | ) -> Result<Option<HomeworkSubmission>, AppError> { | 294 | ) -> Result<Option<HomeworkSubmission>, AppError> { |
| 250 | - // Sound to re-send: DELETE and UPDATE can never answer "already exists". | 295 | + tx_with_retry(db, false, async |tx| { |
| 251 | - let (mut result, mut errors) = transaction_with_retry( | 296 | + // The homework row's lock is the serialization point against grading: |
| 252 | - db, | 297 | + // a grade locks the same row before it stamps, so either this delete |
| 253 | - &format!( | 298 | + // refuses off the stamp, or the grade landed on a row that is now |
| 254 | - "BEGIN TRANSACTION; | 299 | + // gone β grading absent work, which is allowed. Its `due_at` read is |
| 255 | - LET $due = (SELECT VALUE homework.due_at FROM ONLY $sub); | 300 | + // also the replay fallback's deadline. |
| 256 | - LET $gone = (DELETE $sub WHERE {SUBMISSION_OPEN_GUARD} RETURN BEFORE); | 301 | + let due = sqlx::query!( |
| 257 | - IF array::len($gone) > 0 {{ | 302 | + "SELECT due_at FROM homework WHERE id = $1 FOR UPDATE", |
| 258 | - DELETE homework_file WHERE submission = $sub; | 303 | + submission.get_homework() |
| 259 | - LET $on_time = IF ($gone[0].counted_on_time | 304 | + ) |
| 260 | - ?? ($gone[0].submitted_at <= $due)) {{ 1 }} ELSE {{ 0 }}; | 305 | + .fetch_optional(&mut *tx) |
| 261 | - UPDATE $usr SET | 306 | + .await? |
| 262 | - {HOMEWORK_SUBMITTED_TOTAL_FIELD} = | 307 | + .map(|row| row.due_at); |
| 263 | - math::max([({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) - 1, 0]), | 308 | + let gone = sqlx::query!( |
| 264 | - {HOMEWORK_ON_TIME_TOTAL_FIELD} = | 309 | + r#"DELETE FROM homework_submission |
| 265 | - math::max([({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) - $on_time, 0]) | 310 | + WHERE id = $1 AND graded_by_result IS NULL |
| 266 | - }}; | 311 | + RETURNING id AS "id: HomeworkSubmissionId", |
| 267 | - RETURN $gone; | 312 | + homework AS "homework: HomeworkId", |
| 268 | - COMMIT TRANSACTION;" | 313 | + app_user AS "user: UserId", |
| 269 | - ), | 314 | + text AS "text: Option<SubmissionText>", |
| 270 | - &[ | 315 | + submitted_at AS "submitted_at: Timestamp", |
| 271 | - ("sub".into(), submission.id.record().into_value()), | 316 | + updated_at AS "updated_at: Timestamp", |
| 272 | - ("usr".into(), submission.user.record().into_value()), | 317 | + counted_on_time AS "counted_on_time: Option<bool>""#, |
| 273 | - ], | 318 | + submission.get_id() |
| 274 | - &[], | 319 | + ) |
| 275 | - ) | 320 | + .fetch_optional(&mut *tx) |
| 276 | - .await?; | 321 | + .await?; |
| 277 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | 322 | + let Some(removed) = gone else { |
| 278 | - return Err(error.into()); | 323 | + // Frozen, or already withdrawn by a rival β one refusal, as |
| 279 | - } | 324 | + // before. |
| 280 | - // The trailing `RETURN` is always the last statement before `COMMIT`. | 325 | + return Ok(None); |
| 281 | - let slot = result.num_statements().saturating_sub(2); | 326 | + }; |
| 282 | - Ok(result | 327 | + sqlx::query!( |
| 283 | - .take::<Vec<HomeworkSubmission>>(slot)? | 328 | + "DELETE FROM homework_file WHERE submission = $1", |
| 284 | - .into_iter() | 329 | + removed.id |
| 285 | - .next()) | 330 | + ) |
| 331 | + .execute(&mut *tx) | ||
| 332 | + .await?; | ||
| 333 | + let judged_on_time = due.map(|d| removed.submitted_at <= d).unwrap_or(false); | ||
| 334 | + let on_time = i64::from(removed.counted_on_time.unwrap_or(judged_on_time)); | ||
| 335 | + sqlx::query!( | ||
| 336 | + r#"UPDATE app_user SET | ||
| 337 | + homework_submitted_total = GREATEST(homework_submitted_total - 1, 0), | ||
| 338 | + homework_on_time_total = GREATEST(homework_on_time_total - $2, 0) | ||
| 339 | + WHERE id = $1"#, | ||
| 340 | + removed.user, | ||
| 341 | + on_time | ||
| 342 | + ) | ||
| 343 | + .execute(&mut *tx) | ||
| 344 | + .await?; | ||
| 345 | + Ok(Some(HomeworkSubmission { | ||
| 346 | + id: removed.id, | ||
| 347 | + homework: removed.homework, | ||
| 348 | + user: removed.user, | ||
| 349 | + text: removed.text, | ||
| 350 | + submitted_at: removed.submitted_at, | ||
| 351 | + updated_at: removed.updated_at, | ||
| 352 | + })) | ||
| 353 | + }) | ||
| 354 | + .await | ||
| 286 | } | 355 | } |
| 287 | 356 | ||
| 288 | #[cfg(test)] | 357 | #[cfg(test)] |
src/domain/homework_result.rsmodified+1 -0
| @@ -76,6 +76,7 @@ impl HomeworkStatus { | |||
| 76 | pub struct HomeworkResult { | 76 | pub struct HomeworkResult { |
| 77 | pub(crate) id: HomeworkResultId, | 77 | pub(crate) id: HomeworkResultId, |
| 78 | pub(crate) homework: HomeworkId, | 78 | pub(crate) homework: HomeworkId, |
| 79 | + #[sqlx(rename = "app_user")] | ||
| 79 | pub(crate) user: UserId, | 80 | pub(crate) user: UserId, |
| 80 | pub(crate) status: HomeworkStatus, | 81 | pub(crate) status: HomeworkStatus, |
| 81 | pub(crate) mark: Option<Mark>, | 82 | pub(crate) mark: Option<Mark>, |
src/domain/homework_submission.rsmodified+1 -0
| @@ -70,6 +70,7 @@ impl SubmissionText { | |||
| 70 | pub struct HomeworkSubmission { | 70 | pub struct HomeworkSubmission { |
| 71 | pub(crate) id: HomeworkSubmissionId, | 71 | pub(crate) id: HomeworkSubmissionId, |
| 72 | pub(crate) homework: HomeworkId, | 72 | pub(crate) homework: HomeworkId, |
| 73 | + #[sqlx(rename = "app_user")] | ||
| 73 | pub(crate) user: UserId, | 74 | pub(crate) user: UserId, |
| 74 | pub(crate) text: Option<SubmissionText>, | 75 | pub(crate) text: Option<SubmissionText>, |
| 75 | pub(crate) submitted_at: Timestamp, | 76 | pub(crate) submitted_at: Timestamp, |
src/service/homework.rsmodified+21 -110
| @@ -1,63 +1,26 @@ | |||
| 1 | -//! Homework workflows: the PATCH re-scope with its orphan guard, the | 1 | +//! Homework workflows: the cascading delete and the shared student-side wall |
| 2 | -//! cascading delete, and the shared student-side wall | ||
| 3 | //! ([`gate_own_submission`]) every submission path walks. Row reads and | 2 | //! ([`gate_own_submission`]) every submission path walks. Row reads and |
| 4 | //! listings pass through to [`crate::db::homework`]; the submission, file, | 3 | //! listings pass through to [`crate::db::homework`]; the submission, file, |
| 5 | -//! and grade workflows live in the sibling `service::homework_*` modules, | 4 | +//! and grade workflows live in the sibling `service::homework_*` modules. |
| 6 | -//! whose every locked path leases [`HOMEWORK_LOCK`]. | 5 | +//! |
| 6 | +//! There is no homework subsystem lock any more: the writes that used to | ||
| 7 | +//! serialize on one β the PATCH's orphan guard, the delete cascade, grading, | ||
| 8 | +//! and every student-side write β now contend on the *homework row itself* | ||
| 9 | +//! (`SELECT β¦ FOR UPDATE` inside each transaction), so the ordering they | ||
| 10 | +//! need survives a multi-process deployment. See | ||
| 11 | +//! [`crate::db::homework::update`] and | ||
| 12 | +//! [`crate::db::homework_result::grade`]. | ||
| 7 | 13 | ||
| 8 | use crate::database::Database; | 14 | use crate::database::Database; |
| 9 | use crate::db::homework; | 15 | use crate::db::homework; |
| 10 | -use crate::db::homework_file; | ||
| 11 | -use crate::db::homework_result; | ||
| 12 | -use crate::db::homework_submission; | ||
| 13 | use crate::domain::course::CourseId; | 16 | use crate::domain::course::CourseId; |
| 14 | use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle}; | 17 | use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle}; |
| 15 | -use crate::domain::homework_result::HomeworkResult; | ||
| 16 | -use crate::domain::homework_submission::HomeworkSubmission; | ||
| 17 | use crate::domain::role::Role; | 18 | use crate::domain::role::Role; |
| 18 | use crate::domain::subject::SubjectId; | 19 | use crate::domain::subject::SubjectId; |
| 19 | use crate::domain::timestamp::Timestamp; | 20 | use crate::domain::timestamp::Timestamp; |
| 20 | use crate::domain::user::{User, UserId}; | 21 | use crate::domain::user::{User, UserId}; |
| 21 | use crate::error::AppError; | 22 | use crate::error::AppError; |
| 22 | 23 | ||
| 23 | -/// Serializes the homework subsystem's cross-record check-then-writes, which | ||
| 24 | -/// `BEGINβ¦COMMIT` cannot (write skew) β the same reasoning as | ||
| 25 | -/// [`crate::service::exam_attempt::EXAM_LOCK`]. Every lease below is held across the | ||
| 26 | -/// database write it guards, so within this one process it does order a full | ||
| 27 | -/// round trip β but the freeze no longer *rests* on that: a graded submission | ||
| 28 | -/// used to stay unedited only because the "no grade yet" read and the write it | ||
| 29 | -/// licensed sat under one lease. That rule now lives in the database too β | ||
| 30 | -/// grading stamps [`crate::constant::SUBMISSION_GRADED_FIELD`] on the | ||
| 31 | -/// submission row and every student-side write carries `graded_by_result = | ||
| 32 | -/// NONE` as its own condition. The one case the stamp cannot cover β grading | ||
| 33 | -/// work with no submission row yet β falls back to the lease pair, so a write | ||
| 34 | -/// lease must never stop spanning its own database call (see | ||
| 35 | -/// [`crate::db::homework_result::grade`]). | ||
| 36 | -/// | ||
| 37 | -/// What still leases it, honestly: | ||
| 38 | -/// - Write: the homework PATCH's orphan guard ([`update`]), the | ||
| 39 | -/// homework-delete cascade ([`delete`]), and grade/ungrade β whose | ||
| 40 | -/// freeze rule (the stamp landing on a submission that may be written in the | ||
| 41 | -/// same instant) is the one thing here still resting on the two leases being | ||
| 42 | -/// mutually exclusive. The *existence* half has left: a grade now moves a | ||
| 43 | -/// value on the homework row inside its own transaction | ||
| 44 | -/// ([`crate::db::homework_result::grade`]), so a | ||
| 45 | -/// concurrent delete refuses it rather than being read around. | ||
| 46 | -/// - Read: the student's submission/file writes, which no longer gate the | ||
| 47 | -/// freeze but still must not land under a PATCH re-scoping the audience out | ||
| 48 | -/// from under them. | ||
| 49 | -/// | ||
| 50 | -/// The subject rule has left: creating a homework and re-tagging one move the | ||
| 51 | -/// subject's reference counter, and the subject delete is refused while that | ||
| 52 | -/// counter is non-zero ([`crate::domain::subject::Subject::delete`]), so | ||
| 53 | -/// neither the create (in `web::courses`) nor the outside writer the subject | ||
| 54 | -/// delete used to take is on this list any more. | ||
| 55 | -/// | ||
| 56 | -/// Lock order, where both are taken: `HOMEWORK_LOCK` before the counter lock in | ||
| 57 | -/// [`crate::db::cap`], never the reverse. | ||
| 58 | -// corner-cut: global RwLock, shard per-homework if write latency ever matters. | ||
| 59 | -pub(crate) static HOMEWORK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); | ||
| 60 | - | ||
| 61 | #[expect( | 24 | #[expect( |
| 62 | clippy::too_many_arguments, | 25 | clippy::too_many_arguments, |
| 63 | reason = "mirrors the sibling entities' create(field, field, ..) shape" | 26 | reason = "mirrors the sibling entities' create(field, field, ..) shape" |
| @@ -120,17 +83,10 @@ pub async fn list_for_user_in_course( | |||
| 120 | 83 | ||
| 121 | /// Re-scope (or re-tag, re-title, re-describe, re-schedule) the homework. | 84 | /// Re-scope (or re-tag, re-title, re-describe, re-schedule) the homework. |
| 122 | /// | 85 | /// |
| 123 | -/// Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the | 86 | +/// The audience-narrowing orphan guard and the stale-re-tag refusal are one |
| 124 | -/// live submissions and results, and the row write depends on what it saw β | 87 | +/// transaction with the write in [`homework::update`], under the homework |
| 125 | -/// without the lease a submission (a reader) could land between the check | 88 | +/// row's lock β a submission (which locks the same row before writing) |
| 126 | -/// and the write, orphaned by the narrowing that just missed it. The subject | 89 | +/// cannot land between the check and the narrowing it would have refused. |
| 127 | -/// re-tag no longer needs it β it moves the two subjects' reference counters | ||
| 128 | -/// inside [`homework::update`]. | ||
| 129 | -/// | ||
| 130 | -/// The orphan guard runs on exactly the requests that re-scope the audience. | ||
| 131 | -/// An absent `assigned` writes nothing, so the stored subset is untouched and | ||
| 132 | -/// no narrowing can happen behind the guard's back β which the old "carry the | ||
| 133 | -/// snapshot back" branch could do, re-narrowing over a concurrent widening. | ||
| 134 | pub async fn update( | 90 | pub async fn update( |
| 135 | db: &Database, | 91 | db: &Database, |
| 136 | homework: Homework, | 92 | homework: Homework, |
| @@ -140,62 +96,17 @@ pub async fn update( | |||
| 140 | due_at: Option<Timestamp>, | 96 | due_at: Option<Timestamp>, |
| 141 | assigned: Option<Option<Vec<UserId>>>, | 97 | assigned: Option<Option<Vec<UserId>>>, |
| 142 | ) -> Result<Homework, AppError> { | 98 | ) -> Result<Homework, AppError> { |
| 143 | - let _guard = HOMEWORK_LOCK.write().await; | ||
| 144 | - if let Some(resolved) = assigned.as_ref() { | ||
| 145 | - ensure_no_orphans(&homework, resolved.as_deref(), db).await?; | ||
| 146 | - } | ||
| 147 | homework::update(db, homework, subject, title, description, due_at, assigned).await | 99 | homework::update(db, homework, subject, title, description, due_at, assigned).await |
| 148 | } | 100 | } |
| 149 | 101 | ||
| 150 | -/// Refuse (409) a PATCH that would narrow `homework`'s audience so a student | 102 | +/// Delete the homework: run the cascading delete (submissions, their files, |
| 151 | -/// who already submitted or was graded falls outside it β their work would be | 103 | +/// results, then the row β one transaction, children first) and return the |
| 152 | -/// stranded. `new_assigned` is the proposed subset (`None` = whole course, in | 104 | +/// submission-file blob keys, which the transaction collected before the |
| 153 | -/// which case no one can be orphaned). The blocking students are named in the | 105 | +/// wipes so no file added mid-delete can strand its blob. The web layer |
| 154 | -/// message so the teacher knows whose work to clear (or whom to keep assigned) | 106 | +/// unlinks the blobs once the rows are gone; a crash in between strands at |
| 155 | -/// first. | 107 | +/// worst an unreachable file. |
| 156 | -async fn ensure_no_orphans( | ||
| 157 | - homework: &Homework, | ||
| 158 | - new_assigned: Option<&[UserId]>, | ||
| 159 | - db: &Database, | ||
| 160 | -) -> Result<(), AppError> { | ||
| 161 | - // Whole-course covers everyone β no narrowing, no orphans. | ||
| 162 | - let Some(subset) = new_assigned else { | ||
| 163 | - return Ok(()); | ||
| 164 | - }; | ||
| 165 | - let submissions = homework_submission::list_for_homework(db, homework.get_id()).await?; | ||
| 166 | - let results = homework_result::list_for_homework(db, homework.get_id()).await?; | ||
| 167 | - let mut blocked: Vec<String> = Vec::new(); | ||
| 168 | - for user in submissions | ||
| 169 | - .iter() | ||
| 170 | - .map(HomeworkSubmission::get_user) | ||
| 171 | - .chain(results.iter().map(HomeworkResult::get_user)) | ||
| 172 | - { | ||
| 173 | - let key = user.key().to_string(); | ||
| 174 | - if !subset.contains(user) && !blocked.contains(&key) { | ||
| 175 | - blocked.push(key); | ||
| 176 | - } | ||
| 177 | - } | ||
| 178 | - if blocked.is_empty() { | ||
| 179 | - Ok(()) | ||
| 180 | - } else { | ||
| 181 | - Err(AppError::ConflictOwned(format!( | ||
| 182 | - "narrowing the assigned list would orphan existing work by {} student(s): {}", | ||
| 183 | - blocked.len(), | ||
| 184 | - blocked.join(", ") | ||
| 185 | - ))) | ||
| 186 | - } | ||
| 187 | -} | ||
| 188 | - | ||
| 189 | -/// Delete the homework: collect the submission-file blob keys, then run the | ||
| 190 | -/// cascading delete under [`HOMEWORK_LOCK`]'s write lease | ||
| 191 | -/// so no submission can land under the homework mid-delete; the blob names are | ||
| 192 | -/// collected before the rows are wiped (the cascade is one transaction, children | ||
| 193 | -/// first) and removed after, so a crash in between strands at worst an | ||
| 194 | -/// unreachable file. | ||
| 195 | pub async fn delete(db: &Database, homework: Homework) -> Result<Vec<String>, AppError> { | 108 | pub async fn delete(db: &Database, homework: Homework) -> Result<Vec<String>, AppError> { |
| 196 | - let _guard = HOMEWORK_LOCK.write().await; | 109 | + let (_, blob_keys) = homework::delete(db, homework).await?; |
| 197 | - let blob_keys = homework_file::file_keys_for_homework(db, homework.get_id()).await?; | ||
| 198 | - homework::delete(db, homework).await?; | ||
| 199 | Ok(blob_keys) | 110 | Ok(blob_keys) |
| 200 | } | 111 | } |
| 201 | 112 | ||
src/service/homework_file.rsmodified+17 -13
| @@ -2,9 +2,8 @@ | |||
| 2 | //! submission (the graded gate plus the auto-created seat it hangs off) and | 2 | //! submission (the graded gate plus the auto-created seat it hangs off) and |
| 3 | //! the pass-through reads the download paths scope through. The blob bytes | 3 | //! the pass-through reads the download paths scope through. The blob bytes |
| 4 | //! and their ordering (blob before row on upload, row before blob on delete) | 4 | //! and their ordering (blob before row on upload, row before blob on delete) |
| 5 | -//! stay the web layer's β it owns `files_path` β but every lease holder is | 5 | +//! stay the web layer's β it owns `files_path`. The row writes live in |
| 6 | -//! [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK)'s reader side. | 6 | +//! [`crate::db::homework_file`]. |
| 7 | -//! The row writes live in [`crate::db::homework_file`]. | ||
| 8 | 7 | ||
| 9 | use crate::database::Database; | 8 | use crate::database::Database; |
| 10 | use crate::db::homework_file; | 9 | use crate::db::homework_file; |
| @@ -18,10 +17,11 @@ use crate::error::AppError; | |||
| 18 | 17 | ||
| 19 | /// The submission the file will hang off, created if absent β a photo-only | 18 | /// The submission the file will hang off, created if absent β a photo-only |
| 20 | /// homework never types text, so an upload auto-creates an empty submission | 19 | /// homework never types text, so an upload auto-creates an empty submission |
| 21 | -/// to carry the file (an existing one's text is preserved). A photo-only | 20 | +/// to carry the file (an existing one's text is preserved β `upsert` is |
| 22 | -/// hand-in is a hand-in: it creates the row, so it moves the counters, so it | 21 | +/// called with `preserve_text`, so even a rival hand-in landing mid-request |
| 23 | -/// earns badges exactly as a text submit does. Refused (409) when a grade | 22 | +/// keeps its text). A photo-only hand-in is a hand-in: it creates the row, |
| 24 | -/// has frozen the homework. | 23 | +/// so it moves the counters, so it earns badges exactly as a text submit |
| 24 | +/// does. Refused (409) when a grade has frozen the homework. | ||
| 25 | pub async fn ensure_can_attach( | 25 | pub async fn ensure_can_attach( |
| 26 | db: &Database, | 26 | db: &Database, |
| 27 | user: &User, | 27 | user: &User, |
| @@ -30,7 +30,7 @@ pub async fn ensure_can_attach( | |||
| 30 | const GRADED: AppError = AppError::Conflict( | 30 | const GRADED: AppError = AppError::Conflict( |
| 31 | "this homework has been graded β ask the teacher to remove the grade before adding files", | 31 | "this homework has been graded β ask the teacher to remove the grade before adding files", |
| 32 | ); | 32 | ); |
| 33 | - // The common-case gate; the freeze itself rides on the writes below. | 33 | + // The common-case gate; the freeze itself rides on the write below. |
| 34 | if crate::db::homework_result::read_for(db, homework.get_id(), user.get_id()) | 34 | if crate::db::homework_result::read_for(db, homework.get_id(), user.get_id()) |
| 35 | .await? | 35 | .await? |
| 36 | .is_some() | 36 | .is_some() |
| @@ -40,17 +40,21 @@ pub async fn ensure_can_attach( | |||
| 40 | match homework_submission::read_for(db, homework.get_id(), user.get_id()).await? { | 40 | match homework_submission::read_for(db, homework.get_id(), user.get_id()).await? { |
| 41 | Some(existing) => Ok(existing), | 41 | Some(existing) => Ok(existing), |
| 42 | None => { | 42 | None => { |
| 43 | - let created = homework_submission::upsert(db, homework, user.get_id(), None) | 43 | + let Some((created, fresh)) = |
| 44 | - .await? | 44 | + homework_submission::upsert(db, homework, user.get_id(), None, true).await? |
| 45 | - .ok_or(GRADED)?; | 45 | + else { |
| 46 | - crate::service::homework::award_badges(user.get_id(), db).await; | 46 | + return Err(GRADED); |
| 47 | + }; | ||
| 48 | + if fresh { | ||
| 49 | + crate::service::homework::award_badges(user.get_id(), db).await; | ||
| 50 | + } | ||
| 47 | Ok(created) | 51 | Ok(created) |
| 48 | } | 52 | } |
| 49 | } | 53 | } |
| 50 | } | 54 | } |
| 51 | 55 | ||
| 52 | /// Persist the assembled row β the seat claim and the freeze in one | 56 | /// Persist the assembled row β the seat claim and the freeze in one |
| 53 | -/// conditional write (see [`homework_file::insert`]). `Ok(None)` is the | 57 | +/// guarded insert (see [`homework_file::insert`]). `Ok(None)` is the |
| 54 | /// freeze; the web layer keeps its own wording and unlinks the blob it wrote. | 58 | /// freeze; the web layer keeps its own wording and unlinks the blob it wrote. |
| 55 | pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> { | 59 | pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> { |
| 56 | homework_file::insert(db, file).await | 60 | homework_file::insert(db, file).await |
src/service/homework_result.rsmodified+7 -10
| @@ -1,10 +1,9 @@ | |||
| 1 | //! Homework grading workflows: the policy gates around the atomic grade β | 1 | //! Homework grading workflows: the policy gates around the atomic grade β |
| 2 | //! nobody grades themselves, the target must be a live enrolled student in | 2 | //! nobody grades themselves, the target must be a live enrolled student in |
| 3 | //! the homework's audience β and the un-grade. The freeze-stamping | 3 | //! the homework's audience β and the un-grade. The freeze-stamping |
| 4 | -//! transaction lives in [`crate::db::homework_result`]; grading holds | 4 | +//! transaction lives in [`crate::db::homework_result`]; it locks the |
| 5 | -//! [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK)'s writer lease | 5 | +//! homework row across the stamp, which is what orders a grade against every |
| 6 | -//! across its gates and the write, the reader side of every student write's | 6 | +//! student-side write β there is no subsystem lock here any more. |
| 7 | -//! lease pair. | ||
| 8 | 7 | ||
| 9 | use crate::database::Database; | 8 | use crate::database::Database; |
| 10 | use crate::db::homework; | 9 | use crate::db::homework; |
| @@ -20,11 +19,11 @@ use crate::error::{AppError, ValidationError}; | |||
| 20 | /// Record (or overwrite) `target`'s grade for the homework. The web layer | 19 | /// Record (or overwrite) `target`'s grade for the homework. The web layer |
| 21 | /// has already read the homework, checked course-management rights, walled | 20 | /// has already read the homework, checked course-management rights, walled |
| 22 | /// the archived term, and validated the status and mark; everything here is | 21 | /// the archived term, and validated the status and mark; everything here is |
| 23 | -/// re-run or decided under the writer lease: | 22 | +/// re-run or decided against the row the grade transaction locks: |
| 24 | /// | 23 | /// |
| 25 | -/// - the homework is re-read (a homework delete is a fellow writer β its | 24 | +/// - the homework is re-read (a homework delete is a fellow writer β both |
| 26 | -/// lease excludes this one, so a grade cannot resurrect a result row under | 25 | +/// contend on the homework row's lock, so a grade cannot resurrect a |
| 27 | -/// a vanished homework; the vanished row answers 404); | 26 | +/// result row under a vanished homework; the vanished row answers 404); |
| 28 | /// - grading never targets oneself β no grader, whatever their role, may | 27 | /// - grading never targets oneself β no grader, whatever their role, may |
| 29 | /// write their own grade; | 28 | /// write their own grade; |
| 30 | /// - the target user must exist, and only students carry homework grades β | 29 | /// - the target user must exist, and only students carry homework grades β |
| @@ -40,7 +39,6 @@ pub async fn grade( | |||
| 40 | mark: Option<Mark>, | 39 | mark: Option<Mark>, |
| 41 | target: &UserId, | 40 | target: &UserId, |
| 42 | ) -> Result<HomeworkResult, AppError> { | 41 | ) -> Result<HomeworkResult, AppError> { |
| 43 | - let _guard = crate::service::homework::HOMEWORK_LOCK.write().await; | ||
| 44 | let homework = homework::read(db, id).await?.ok_or(AppError::NotFound)?; | 42 | let homework = homework::read(db, id).await?.ok_or(AppError::NotFound)?; |
| 45 | 43 | ||
| 46 | // Grading never targets oneself. | 44 | // Grading never targets oneself. |
| @@ -100,7 +98,6 @@ pub async fn ungrade( | |||
| 100 | id: &HomeworkId, | 98 | id: &HomeworkId, |
| 101 | target: &UserId, | 99 | target: &UserId, |
| 102 | ) -> Result<Option<HomeworkResult>, AppError> { | 100 | ) -> Result<Option<HomeworkResult>, AppError> { |
| 103 | - let _guard = crate::service::homework::HOMEWORK_LOCK.write().await; | ||
| 104 | homework_result::remove(db, id, target).await | 101 | homework_result::remove(db, id, target).await |
| 105 | } | 102 | } |
| 106 | 103 | ||
src/service/homework_submission.rsmodified+18 -26
| @@ -1,8 +1,9 @@ | |||
| 1 | -//! Homework submission workflows: the student's submit (the lease-to-write | 1 | +//! Homework submission workflows: the student's submit (the graded gate and |
| 2 | -//! window that keeps a PATCH's audience re-scope from stranding a hand-in) | 2 | +//! the audience interlock around the guarded upsert) and the withdrawal that |
| 3 | -//! and the withdrawal that gives the badge counters back. The row writes | 3 | +//! gives the badge counters back. The row writes live in |
| 4 | -//! live in [`crate::db::homework_submission`]; every locked path here | 4 | +//! [`crate::db::homework_submission`]; the freeze itself is a condition of |
| 5 | -//! leases [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK). | 5 | +//! those writes, and the homework row's lock is what orders them against |
| 6 | +//! grading β there is no subsystem lock here any more. | ||
| 6 | 7 | ||
| 7 | use crate::database::Database; | 8 | use crate::database::Database; |
| 8 | use crate::db::homework_file; | 9 | use crate::db::homework_file; |
| @@ -23,29 +24,22 @@ pub struct Submitted { | |||
| 23 | } | 24 | } |
| 24 | 25 | ||
| 25 | /// Submit (or re-submit) the caller's own work for a homework. The graded | 26 | /// Submit (or re-submit) the caller's own work for a homework. The graded |
| 26 | -/// gate and the audience interlock are the reader lease's β taken *before* | 27 | +/// read below answers the common case β graded minutes ago, and the student |
| 27 | -/// the gate read: read first and the audience this gate approved is one | 28 | +/// who never submitted has no row to carry the freeze; the upsert's own |
| 28 | -/// committed PATCH old, so the narrowing that just passed the orphan guard | 29 | +/// `graded_by_result IS NULL` condition is what holds when the grade lands |
| 29 | -/// (no submission yet) is followed by the very submission it would have | 30 | +/// *while* this request runs (grade and write serialize on the homework |
| 30 | -/// refused. Holding the lease across gate *and* write is what makes the | 31 | +/// row's lock). |
| 31 | -/// PATCH wait and then see the row. | ||
| 32 | /// | 32 | /// |
| 33 | -/// `None` from [`homework_submission::upsert`] is a grade landing mid-request | 33 | +/// `None` from [`homework_submission::upsert`] is that freeze biting; both |
| 34 | -/// (the stamp on the row refusing the write); the graded read above answers | 34 | +/// refusals return the same 409. |
| 35 | -/// the common case, and both return the same 409. | ||
| 36 | pub async fn submit( | 35 | pub async fn submit( |
| 37 | db: &Database, | 36 | db: &Database, |
| 38 | user: &User, | 37 | user: &User, |
| 39 | id: &str, | 38 | id: &str, |
| 40 | text: Option<SubmissionText>, | 39 | text: Option<SubmissionText>, |
| 41 | ) -> Result<Submitted, AppError> { | 40 | ) -> Result<Submitted, AppError> { |
| 42 | - let _guard = crate::service::homework::HOMEWORK_LOCK.read().await; | ||
| 43 | let homework = crate::service::homework::gate_own_submission(id, user, db).await?; | 41 | let homework = crate::service::homework::gate_own_submission(id, user, db).await?; |
| 44 | crate::service::homework::require_open_term(&homework, db).await?; | 42 | crate::service::homework::require_open_term(&homework, db).await?; |
| 45 | - // The graded gate, twice over. This read answers the common case β graded | ||
| 46 | - // minutes ago, and the student who never submitted has no row to carry the | ||
| 47 | - // freeze; the upsert's own `WHERE` (the grade stamp on the row) is what | ||
| 48 | - // holds when the grade lands *while* this request runs. | ||
| 49 | const GRADED: AppError = AppError::Conflict( | 43 | const GRADED: AppError = AppError::Conflict( |
| 50 | "this homework has been graded β ask the teacher to remove the grade before editing your submission", | 44 | "this homework has been graded β ask the teacher to remove the grade before editing your submission", |
| 51 | ); | 45 | ); |
| @@ -55,12 +49,11 @@ pub async fn submit( | |||
| 55 | { | 49 | { |
| 56 | return Err(GRADED); | 50 | return Err(GRADED); |
| 57 | } | 51 | } |
| 58 | - // 201-vs-200: a prior read is exact, where comparing the returned stamps | 52 | + // `existed` comes back from the transaction itself, so the 201-vs-200 |
| 59 | - // would misreport a same-millisecond re-submit as a create. | 53 | + // answer and the badge rule are exact even against a rival first |
| 60 | - let existed = homework_submission::read_for(db, homework.get_id(), user.get_id()) | 54 | + // hand-in. |
| 61 | - .await? | 55 | + let Some((submission, existed)) = |
| 62 | - .is_some(); | 56 | + homework_submission::upsert(db, &homework, user.get_id(), text, false).await? |
| 63 | - let Some(submission) = homework_submission::upsert(db, &homework, user.get_id(), text).await? | ||
| 64 | else { | 57 | else { |
| 65 | return Err(GRADED); | 58 | return Err(GRADED); |
| 66 | }; | 59 | }; |
| @@ -85,7 +78,6 @@ pub async fn submit( | |||
| 85 | pub async fn delete(db: &Database, user: &User, id: &str) -> Result<Vec<HomeworkFile>, AppError> { | 78 | pub async fn delete(db: &Database, user: &User, id: &str) -> Result<Vec<HomeworkFile>, AppError> { |
| 86 | let homework = crate::service::homework::gate_own_submission(id, user, db).await?; | 79 | let homework = crate::service::homework::gate_own_submission(id, user, db).await?; |
| 87 | crate::service::homework::require_open_term(&homework, db).await?; | 80 | crate::service::homework::require_open_term(&homework, db).await?; |
| 88 | - let _guard = crate::service::homework::HOMEWORK_LOCK.read().await; | ||
| 89 | const GRADED: AppError = AppError::Conflict( | 81 | const GRADED: AppError = AppError::Conflict( |
| 90 | "this homework has been graded β ask the teacher to remove the grade before deleting your submission", | 82 | "this homework has been graded β ask the teacher to remove the grade before deleting your submission", |
| 91 | ); | 83 | ); |
src/web/homework.rsmodified+52 -50
| @@ -4,8 +4,9 @@ | |||
| 4 | //! and the per-course listing live under `/courses/{id}/homework` (see | 4 | //! and the per-course listing live under `/courses/{id}/homework` (see |
| 5 | //! [`super::courses`]); everything shares the visibility rule | 5 | //! [`super::courses`]); everything shares the visibility rule |
| 6 | //! ([`Homework::student_sees`](crate::domain::homework::Homework::student_sees)) | 6 | //! ([`Homework::student_sees`](crate::domain::homework::Homework::student_sees)) |
| 7 | -//! and the [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK), whose | 7 | +//! The freeze and the audience interlock are conditions of the writes |
| 8 | -//! leases the workflows take in [`crate::service::homework`] and its siblings. | 8 | +//! themselves ([`crate::db::homework_submission`]), serialized on the |
| 9 | +//! homework row's lock inside each transaction. | ||
| 9 | 10 | ||
| 10 | use crate::web::tenant_state::State; | 11 | use crate::web::tenant_state::State; |
| 11 | use axum::Json; | 12 | use axum::Json; |
| @@ -26,9 +27,7 @@ use crate::domain::exam_result::Mark; | |||
| 26 | use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle}; | 27 | use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle}; |
| 27 | use crate::domain::homework_file::{HomeworkFile, HomeworkFileId}; | 28 | use crate::domain::homework_file::{HomeworkFile, HomeworkFileId}; |
| 28 | use crate::domain::homework_result::{HomeworkResult, HomeworkStatus}; | 29 | use crate::domain::homework_result::{HomeworkResult, HomeworkStatus}; |
| 29 | -use crate::domain::homework_submission::{ | 30 | +use crate::domain::homework_submission::{HomeworkSubmission, SubmissionText}; |
| 30 | - HomeworkSubmission, HomeworkSubmissionId, SubmissionText, | ||
| 31 | -}; | ||
| 32 | use crate::domain::note_file::{FileContentType, FileName}; | 31 | use crate::domain::note_file::{FileContentType, FileName}; |
| 33 | use crate::domain::role::Role; | 32 | use crate::domain::role::Role; |
| 34 | use crate::domain::timestamp::Timestamp; | 33 | use crate::domain::timestamp::Timestamp; |
| @@ -310,11 +309,11 @@ async fn update_homework( | |||
| 310 | } | 309 | } |
| 311 | crate::service::course::require_open(&st.db, &course).await?; | 310 | crate::service::course::require_open(&st.db, &course).await?; |
| 312 | 311 | ||
| 313 | - // The writer lease of [`HOMEWORK_LOCK`], the orphan guard, and the write | 312 | + // The orphan guard and the write are one unit in |
| 314 | - // are one unit in [`service::homework::update`]: the guard reads the live | 313 | + // [`service::homework::update`]: the guard reads the live submissions and |
| 315 | - // submissions and results, and the row write depends on what it saw β | 314 | + // results inside the write's transaction, under the homework row's lock β |
| 316 | - // without the lease a submission (a reader) could land between the check | 315 | + // a submission (which locks the same row before writing) cannot land |
| 317 | - // and the write, orphaned by the narrowing that just missed it. | 316 | + // between the check and the narrowing that just missed it. |
| 318 | 317 | ||
| 319 | // Only what the request carried: an omitted field stays `None` and is never | 318 | // Only what the request carried: an omitted field stays `None` and is never |
| 320 | // written, so a concurrent PATCH of another field survives. The two | 319 | // written, so a concurrent PATCH of another field survives. The two |
| @@ -333,7 +332,9 @@ async fn update_homework( | |||
| 333 | // A kept (absent) due date may already be past; a newly set one may not be. | 332 | // A kept (absent) due date may already be past; a newly set one may not be. |
| 334 | check_not_past("due_at", due_at)?; | 333 | check_not_past("due_at", due_at)?; |
| 335 | let subject = match &req.subject_id { | 334 | let subject = match &req.subject_id { |
| 336 | - Some(subject_id) => Some(crate::service::subject::in_course(&st.db, subject_id, course.get_id()).await?), | 335 | + Some(subject_id) => { |
| 336 | + Some(crate::service::subject::in_course(&st.db, subject_id, course.get_id()).await?) | ||
| 337 | + } | ||
| 337 | None => None, | 338 | None => None, |
| 338 | }; | 339 | }; |
| 339 | // The orphan guard runs on exactly the requests that re-scope the audience. | 340 | // The orphan guard runs on exactly the requests that re-scope the audience. |
| @@ -360,11 +361,11 @@ async fn update_homework( | |||
| 360 | 361 | ||
| 361 | /// Delete a homework and everything under it β submissions, their files, and | 362 | /// Delete a homework and everything under it β submissions, their files, and |
| 362 | /// results β then unlink the file blobs from disk. Requires teacher+ and | 363 | /// results β then unlink the file blobs from disk. Requires teacher+ and |
| 363 | -/// management rights over its course. Held under [`HOMEWORK_LOCK`]'s write lease | 364 | +/// management rights over its course. The cascade is one transaction whose |
| 364 | -/// so no submission can land under the homework mid-delete; the blob names are | 365 | +/// homework-row lock keeps a submission from landing under the homework |
| 365 | -/// collected before the rows are wiped (the cascade is one transaction, children | 366 | +/// mid-delete; the blob names are collected inside that transaction, before |
| 366 | -/// first) and removed after, so a crash in between strands at worst an | 367 | +/// the rows are wiped, and removed after, so a crash in between strands at |
| 367 | -/// unreachable file. | 368 | +/// worst an unreachable file. |
| 368 | #[utoipa::path( | 369 | #[utoipa::path( |
| 369 | delete, | 370 | delete, |
| 370 | path = "/{id}", | 371 | path = "/{id}", |
| @@ -391,7 +392,7 @@ async fn delete_homework( | |||
| 391 | )); | 392 | )); |
| 392 | } | 393 | } |
| 393 | crate::service::course::require_open(&st.db, &course).await?; | 394 | crate::service::course::require_open(&st.db, &course).await?; |
| 394 | - // The writer lease, the blob-key collection, and the cascade are | 395 | + // The blob-key collection and the cascade are |
| 395 | // [`service::homework::delete`]'s; unlinking the blobs stays here because | 396 | // [`service::homework::delete`]'s; unlinking the blobs stays here because |
| 396 | // only the web layer knows `files_path`. | 397 | // only the web layer knows `files_path`. |
| 397 | let blob_keys = service::homework::delete(&st.db, homework).await?; | 398 | let blob_keys = service::homework::delete(&st.db, homework).await?; |
| @@ -548,10 +549,9 @@ async fn submit( | |||
| 548 | Some(text) if !text.is_empty() => Some(SubmissionText::try_new(text)?), | 549 | Some(text) if !text.is_empty() => Some(SubmissionText::try_new(text)?), |
| 549 | _ => None, | 550 | _ => None, |
| 550 | }; | 551 | }; |
| 551 | - // The reader lease of [`HOMEWORK_LOCK`], the gate, the term wall, the | 552 | + // The gate, the term wall, the graded check, and the upsert are one |
| 552 | - // graded check, and the upsert are one unit in | 553 | + // unit in [`service::homework_submission::submit`] β the audience |
| 553 | - // [`service::homework_submission::submit`] β the audience interlock, not | 554 | + // interlock, not the freeze (that is the stamp on the row). |
| 554 | - // the freeze (that is the stamp on the row). | ||
| 555 | let landed = service::homework_submission::submit(&st.db, &user, &id, text).await?; | 555 | let landed = service::homework_submission::submit(&st.db, &user, &id, text).await?; |
| 556 | let files = | 556 | let files = |
| 557 | service::homework_file::list_for_submission(&st.db, landed.submission.get_id()).await?; | 557 | service::homework_file::list_for_submission(&st.db, landed.submission.get_id()).await?; |
| @@ -721,19 +721,15 @@ async fn upload_submission_file( | |||
| 721 | const GRADED: AppError = AppError::Conflict( | 721 | const GRADED: AppError = AppError::Conflict( |
| 722 | "this homework has been graded β ask the teacher to remove the grade before adding files", | 722 | "this homework has been graded β ask the teacher to remove the grade before adding files", |
| 723 | ); | 723 | ); |
| 724 | - // Reader lease as in `submit` β the audience interlock, not the freeze. | 724 | + // Re-read the homework. Streaming the body takes as long as the client |
| 725 | - // Taken before the cap claim inside the insert, never after (the lock | 725 | + // wants it to, and a homework delete can commit inside that window β so |
| 726 | - // order is HOMEWORK_LOCK, then the counter lock). The lock lives in | 726 | + // the pre-flight snapshot can name a homework that no longer exists, and |
| 727 | - // [`service::homework`]; the blob write stays here, inside the lease, | 727 | + // this handler would then auto-create a submission, credit the badge |
| 728 | - // because the row's "stored row points at a real blob" ordering does. | 728 | + // counters and write a file under it, all unreachable afterwards. A gate |
| 729 | - let _guard = service::homework::HOMEWORK_LOCK.read().await; | 729 | + // read before the body is a pre-flight; a gate read after it is the |
| 730 | - // Re-read the homework *under* the lease. Streaming the body takes as long | 730 | + // decision. The writes below are still ordered against a delete, a grade |
| 731 | - // as the client wants it to, and a homework delete (a writer) both takes | 731 | + // and a PATCH narrowing the audience β each contends on the homework |
| 732 | - // and releases its lease inside that window β so the pre-flight snapshot | 732 | + // row's lock inside its own transaction. |
| 733 | - // can name a homework that no longer exists, and this handler would then | ||
| 734 | - // auto-create a submission, credit the badge counters and write a file | ||
| 735 | - // under it, all unreachable afterwards. A gate read before the body is a | ||
| 736 | - // pre-flight; a gate read after it is the decision. | ||
| 737 | let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?; | 733 | let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?; |
| 738 | // Re-walled too: the term can be archived while the body streams. | 734 | // Re-walled too: the term can be archived while the body streams. |
| 739 | service::homework::require_open_term(&homework, &st.db).await?; | 735 | service::homework::require_open_term(&homework, &st.db).await?; |
| @@ -801,8 +797,11 @@ async fn download_submission_file( | |||
| 801 | let file = if user.get_role() == Role::Student { | 797 | let file = if user.get_role() == Role::Student { |
| 802 | // Student: only their own file, behind the full submission gate. | 798 | // Student: only their own file, behind the full submission gate. |
| 803 | let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?; | 799 | let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?; |
| 804 | - let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id()); | 800 | + let submission = |
| 805 | - service::homework_file::read_for(&st.db, &file_id, &submission) | 801 | + service::homework_submission::read_for(&st.db, homework.get_id(), user.get_id()) |
| 802 | + .await? | ||
| 803 | + .ok_or(AppError::NotFound)?; | ||
| 804 | + service::homework_file::read_for(&st.db, &file_id, submission.get_id()) | ||
| 806 | .await? | 805 | .await? |
| 807 | .ok_or(AppError::NotFound)? | 806 | .ok_or(AppError::NotFound)? |
| 808 | } else { | 807 | } else { |
| @@ -850,19 +849,23 @@ async fn delete_submission_file( | |||
| 850 | const GRADED: AppError = AppError::Conflict( | 849 | const GRADED: AppError = AppError::Conflict( |
| 851 | "this homework has been graded β ask the teacher to remove the grade before deleting files", | 850 | "this homework has been graded β ask the teacher to remove the grade before deleting files", |
| 852 | ); | 851 | ); |
| 853 | - // Reader lease as in `submit` β the audience interlock, not the freeze. | ||
| 854 | - let _guard = service::homework::HOMEWORK_LOCK.read().await; | ||
| 855 | if service::homework_result::read_for(&st.db, homework.get_id(), user.get_id()) | 852 | if service::homework_result::read_for(&st.db, homework.get_id(), user.get_id()) |
| 856 | .await? | 853 | .await? |
| 857 | .is_some() | 854 | .is_some() |
| 858 | { | 855 | { |
| 859 | return Err(GRADED); | 856 | return Err(GRADED); |
| 860 | } | 857 | } |
| 861 | - let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id()); | 858 | + let submission = |
| 862 | - let file = | 859 | + service::homework_submission::read_for(&st.db, homework.get_id(), user.get_id()) |
| 863 | - service::homework_file::read_for(&st.db, &HomeworkFileId::from_key(&fid), &submission) | ||
| 864 | .await? | 860 | .await? |
| 865 | .ok_or(AppError::NotFound)?; | 861 | .ok_or(AppError::NotFound)?; |
| 862 | + let file = service::homework_file::read_for( | ||
| 863 | + &st.db, | ||
| 864 | + &HomeworkFileId::from_key(&fid), | ||
| 865 | + submission.get_id(), | ||
| 866 | + ) | ||
| 867 | + .await? | ||
| 868 | + .ok_or(AppError::NotFound)?; | ||
| 866 | let blob = file.get_file().to_string(); | 869 | let blob = file.get_file().to_string(); |
| 867 | // The delete's own transaction re-stamps the submission's "last touched" | 870 | // The delete's own transaction re-stamps the submission's "last touched" |
| 868 | // clock (the late flag) as its freeze gate, so a refused delete moves | 871 | // clock (the late flag) as its freeze gate, so a refused delete moves |
| @@ -923,12 +926,11 @@ async fn grade_homework( | |||
| 923 | Path(id): Path<String>, | 926 | Path(id): Path<String>, |
| 924 | Json(req): Json<GradeHomework>, | 927 | Json(req): Json<GradeHomework>, |
| 925 | ) -> Result<Json<HomeworkResultResponse>, AppError> { | 928 | ) -> Result<Json<HomeworkResultResponse>, AppError> { |
| 926 | - // The grading gates and the writer lease of [`HOMEWORK_LOCK`] live in | 929 | + // The grading gates live in [`service::homework_result::grade`]; the |
| 927 | - // [`service::homework_result::grade`]: a grade is what freezes a | 930 | + // grade transaction locks the homework row across the freeze stamp, which |
| 928 | - // submission, so it must not interleave with the read side's | 931 | + // orders it against every student-side write β and keeps a homework |
| 929 | - // gate-through-write submission edits β and the homework is re-read under | 932 | + // delete from letting the upsert resurrect a result row under a vanished |
| 930 | - // the lease there, which keeps a homework delete (a fellow writer) from | 933 | + // homework (the vanished row answers 404). |
| 931 | - // letting the upsert resurrect a result row under a vanished homework. | ||
| 932 | let (homework, course) = homework_with_course(&id, &st.db).await?; | 934 | let (homework, course) = homework_with_course(&id, &st.db).await?; |
| 933 | if !can_manage_course(&course, &teacher) { | 935 | if !can_manage_course(&course, &teacher) { |
| 934 | return Err(AppError::Forbidden( | 936 | return Err(AppError::Forbidden( |
| @@ -974,9 +976,9 @@ async fn remove_homework_result( | |||
| 974 | RequireTeacher(user): RequireTeacher, | 976 | RequireTeacher(user): RequireTeacher, |
| 975 | Path((id, target)): Path<(String, String)>, | 977 | Path((id, target)): Path<(String, String)>, |
| 976 | ) -> Result<StatusCode, AppError> { | 978 | ) -> Result<StatusCode, AppError> { |
| 977 | - // The writer lease of [`HOMEWORK_LOCK`] is [`service::homework_result::ungrade`]'s | 979 | + // Removing the grade is what unfreezes the submission; the un-grade's |
| 978 | - // β removing the grade is what unfreezes the submission, so it must not | 980 | + // transaction takes the homework row's lock, so it cannot straddle a |
| 979 | - // straddle the read side's gate-through-write edits either. | 981 | + // student-side write either. |
| 980 | let (homework, course) = homework_with_course(&id, &st.db).await?; | 982 | let (homework, course) = homework_with_course(&id, &st.db).await?; |
| 981 | if !can_manage_course(&course, &user) { | 983 | if !can_manage_course(&course, &user) { |
| 982 | return Err(AppError::Forbidden( | 984 | return Err(AppError::Forbidden( |