diff --git a/src/db/answer_image.rs b/src/db/answer_image.rs index 324e868..7c51720 100644 --- a/src/db/answer_image.rs +++ b/src/db/answer_image.rs @@ -4,114 +4,96 @@ //! ids and the fresh-blob-name constructor — lives in //! [`crate::domain::answer_image`]; the blob bytes stay the web layer's. -use surrealdb::types::SurrealValue; +use sqlx::PgConnection; -use crate::constant::EXAM_RESULT_COUNT_FIELD; -use crate::database::{Database, transaction_with_retry}; -use crate::domain::answer_image::{AnswerImage, AnswerImageId}; +use crate::database::{Database, tx_with_retry}; +use crate::domain::answer_image::AnswerImage; use crate::domain::course::CourseId; use crate::domain::exam::ExamId; use crate::domain::exam_question::ExamQuestionId; use crate::domain::user::UserId; use crate::error::AppError; -/// What one [`upsert`] transaction returns: the row it stored and -/// the blob name it replaced. Both are arrays because SurrealDB drops an object -/// key valued `NONE` on the way out, while an empty array survives — "nothing -/// was replaced" has to be readable, not missing. -#[derive(SurrealValue)] -struct UpsertOutcome { - stored: Vec, - replaced: Vec, -} - -/// Create or replace the student's drawing for the question — the -/// deterministic id makes this the whole "one drawing per student per -/// question" story — handing back what it stored plus the blob name it -/// replaced, for the caller to take off disk. +/// Create or replace the student's drawing for the question — the natural +/// (question, user, seq) primary key makes this the whole "one drawing per +/// student per question per sitting" story — handing back what it stored +/// plus the blob name it replaced, for the caller to take off disk. /// -/// The replaced name is read *here*, inside this transaction, not by the -/// caller in front of it: two uploads to one (question, user, seq) both -/// write this row, so they contend and the loser re-reads the winner's blob -/// name, where two pre-reads both saw the *old* blob and left the loser's -/// fresh one on disk with nothing pointing at it. Same shape as +/// The replaced name is read *inside this transaction*, not by the caller +/// in front of it: two uploads to one (question, user, seq) both write this +/// row, so they contend and the loser re-reads the winner's blob name, +/// where two pre-reads both saw the *old* blob and left the loser's fresh +/// one on disk with nothing pointing at it. Same shape as /// [`crate::db::question_image::upsert`]. /// /// `NotFound` = the exam is gone, and the drawing was *not* written. The -/// write moves the exam's mark counter and puts it straight back, in this -/// one transaction, so the exam's existence is something this write -/// *writes* rather than something a gate read a moment earlier: a bare -/// upsert landing after [`delete`](crate::db::exam::delete) -/// removed the exam but before it committed was swept by nothing — its -/// `DELETE answer_image WHERE exam = $ex` ran on a snapshot predating this -/// row — and both sides reported success. That stranded the blob as well as -/// the row: `delete_exam` collects the names to unlink *before* it calls -/// the delete, so bytes written after that snapshot stay on disk forever. -/// This is the shape [`crate::db::exam_answer::save`] takes -/// for the text half of the same answer sheet, and for the same reason. -/// -/// The restore is by captured value, `NONE` included, so the row is -/// byte-identical afterwards and a teacher's PATCH — which pins that -/// counter — is not refused because a student drew. Writing the same value -/// back would buy nothing: an `UPDATE` that leaves the document unchanged -/// is elided and never reaches the store's write set. -/// -/// Admissible for [`transaction_with_retry`]: the `UPDATE`s, `SELECT`, -/// `IF`/`THROW` and `RETURN` can never answer "already exists", and the -/// `UPSERT`'s id is bijective with the (question, user, seq) triple this -/// table keys — a lost round wrote nothing, and re-sending resolves onto -/// the same row rather than colliding with it. +/// write locks the exam row before upserting, in this one transaction, so +/// the exam's existence is something this write *locks* rather than +/// something a gate read a moment earlier: a bare upsert landing after +/// [`delete`](crate::db::exam::delete) removed the exam but before it +/// committed was swept by nothing — its `DELETE answer_image WHERE exam` +/// ran on a snapshot predating this row — and both sides reported success. +/// That stranded the blob as well as the row: `delete_exam` collects the +/// names to unlink *before* it calls the delete, so bytes written after +/// that snapshot stay on disk forever. Locking the key the delete removes +/// serializes the pair — this is the shape +/// [`crate::db::exam_answer::save`] takes for the text half of the same +/// answer sheet, and for the same reason. pub async fn upsert( db: &Database, image: AnswerImage, ) -> Result<(AnswerImage, Option), AppError> { - // whole-row-save-ok: image is built in place from the request, never read back, and the (question, user, seq) id is deterministic — replacing the row *is* the operation - let (exam, id) = (image.exam.record(), image.id.record()); - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $was = (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $ex); - LET $touched = (UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = \ - ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); - IF array::len($touched) = 0 {{ THROW 'no_exam' }}; - UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = $was; - LET $replaced = (SELECT VALUE file FROM $id); - LET $row = (UPSERT $id CONTENT $image RETURN AFTER); - RETURN {{ stored: $row, replaced: $replaced }}; - COMMIT TRANSACTION;" - ), - &[ - ("ex".into(), exam.into_value()), - ("id".into(), id.into_value()), - ("image".into(), image.into_value()), - ], - &["no_exam"], + tx_with_retry(db, false, async |conn| { + upsert_in(conn, image).await + }) + .await +} + +/// The locked exam-row probe plus the upsert, on one connection. +pub(crate) async fn upsert_in( + conn: &mut PgConnection, + image: &AnswerImage, +) -> Result<(AnswerImage, Option), AppError> { + let touched = sqlx::query!( + r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, + image.exam as &ExamId, ) + .fetch_optional(&mut *conn) .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_exam")) - { + if touched.is_none() { return Err(AppError::NotFound); } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is the last statement before `COMMIT`, so its - // slot follows the statement count rather than a hand-kept number; - // `num_statements` counts BEGIN and COMMIT. - let slot = result.num_statements().saturating_sub(2); - let failed = || AppError::Internal("failed to store answer image".into()); - let outcome = result - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(failed)?; - let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; - Ok((stored, outcome.replaced.into_iter().next())) + let replaced = sqlx::query!( + r#"SELECT file FROM answer_image + WHERE question = $1 AND app_user = $2 AND seq = $3"#, + image.question as &ExamQuestionId, + image.user as &UserId, + image.seq, + ) + .fetch_optional(&mut *conn) + .await? + .map(|row| row.file); + let stored = sqlx::query_as!( + AnswerImage, + r#"INSERT INTO answer_image (exam, question, app_user, file, content_type, size, seq) + VALUES ($1, $2, $3, $4, $5, $6, $7) + ON CONFLICT (question, app_user, seq) DO UPDATE + SET file = EXCLUDED.file, content_type = EXCLUDED.content_type, + size = EXCLUDED.size + RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", + app_user AS "user: UserId", seq, file, + content_type AS "content_type: FileContentType", size"#, + image.exam as &ExamId, + image.question as &ExamQuestionId, + image.user as &UserId, + image.file, + image.content_type, + image.size, + image.seq, + ) + .fetch_one(&mut *conn) + .await?; + Ok((stored, replaced)) } /// The student's drawing for one question in one sitting, if any. @@ -121,19 +103,33 @@ pub async fn read( user: &UserId, seq: i64, ) -> Result, AppError> { - Ok(db - .select(AnswerImageId::composite(question, user, seq).record()) - .await?) + Ok(sqlx::query_as!( + AnswerImage, + r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", + app_user AS "user: UserId", seq, file, + content_type AS "content_type: FileContentType", size + FROM answer_image + WHERE question = $1 AND app_user = $2 AND seq = $3"#, + question as &ExamQuestionId, + user as &UserId, + seq, + ) + .fetch_optional(db) + .await?) } /// Every answer drawing of the exam — one query for the exam-delete cascade. pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM answer_image WHERE exam = $ex") - .bind(("ex", exam.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + AnswerImage, + r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", + app_user AS "user: UserId", seq, file, + content_type AS "content_type: FileContentType", size + FROM answer_image WHERE exam = $1"#, + exam as &ExamId, + ) + .fetch_all(db) + .await?) } /// One student's answer drawings for a single sitting — the parallel to @@ -145,14 +141,18 @@ pub async fn list_for_exam_user( user: &UserId, seq: i64, ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM answer_image WHERE exam = $ex AND user = $usr AND seq = $seq") - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .bind(("seq", seq)) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + AnswerImage, + r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", + app_user AS "user: UserId", seq, file, + content_type AS "content_type: FileContentType", size + FROM answer_image WHERE exam = $1 AND app_user = $2 AND seq = $3"#, + exam as &ExamId, + user as &UserId, + seq, + ) + .fetch_all(db) + .await?) } /// The distinct sittings (`seq`, ascending) this student has any answer @@ -162,18 +162,15 @@ pub async fn list_seqs_for_user( exam: &ExamId, user: &UserId, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT VALUE seq FROM answer_image \ - WHERE exam = $ex AND user = $usr ORDER BY seq", - ) - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .await? - .check()?; - let mut seqs = result.take::>(0)?; - seqs.dedup(); - Ok(seqs) + let rows = sqlx::query!( + r#"SELECT DISTINCT seq FROM answer_image + WHERE exam = $1 AND app_user = $2 ORDER BY seq ASC"#, + exam as &ExamId, + user as &UserId, + ) + .fetch_all(db) + .await?; + Ok(rows.into_iter().map(|row| row.seq).collect()) } /// The blob names behind every answer drawing of every exam of `course` — @@ -182,36 +179,49 @@ pub async fn file_keys_for_course( db: &Database, course: &CourseId, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT VALUE file FROM answer_image \ - WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)", - ) - .bind(("course", course.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + let rows = sqlx::query!( + r#"SELECT ai.file FROM answer_image ai + JOIN exam e ON e.id = ai.exam WHERE e.course = $1"#, + course as &CourseId, + ) + .fetch_all(db) + .await?; + Ok(rows.into_iter().map(|row| row.file).collect()) } pub async fn delete(db: &Database, image: AnswerImage) -> Result { - let deleted: Option = db.delete(image.id.record()).await?; + let deleted = sqlx::query_as!( + AnswerImage, + r#"DELETE FROM answer_image WHERE question = $1 AND app_user = $2 AND seq = $3 + RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", + app_user AS "user: UserId", seq, file, + content_type AS "content_type: FileContentType", size"#, + image.question as &ExamQuestionId, + image.user as &UserId, + image.seq, + ) + .fetch_optional(db) + .await?; deleted.ok_or(AppError::NotFound) } /// Drop one student's answer drawings across an exam — a retake starts from -/// a blank sheet. Rows only; the caller GCs the blobs. The retake path itself -/// wipes rows inside `ExamAttempt::wipe_and_create`'s transaction; this is -/// the standalone mirror of [`crate::db::exam_answer::delete_for_exam_user`]. +/// a blank sheet. Rows only; the caller GCs the blobs. The retake path +/// itself wipes nothing: a retake's rows live at their own `seq`, and this +/// is the standalone mirror of +/// [`crate::db::exam_answer::delete_for_exam_user`]. pub async fn delete_for_exam_user( db: &Database, exam: &ExamId, user: &UserId, ) -> Result<(), AppError> { - db.query("DELETE answer_image WHERE exam = $ex AND user = $usr") - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .await? - .check()?; + sqlx::query!( + r#"DELETE FROM answer_image WHERE exam = $1 AND app_user = $2"#, + exam as &ExamId, + user as &UserId, + ) + .execute(db) + .await?; Ok(()) } diff --git a/src/db/exam.rs b/src/db/exam.rs index 74f72f1..7154dbd 100644 --- a/src/db/exam.rs +++ b/src/db/exam.rs @@ -1,18 +1,14 @@ -//! The `exam` table: row reads and listings, the count-and-create that pins -//! the exam to a live course row, the compare-and-set every PATCH writes -//! through, and the cascading delete. The PATCH re-derive and the delete's -//! blob-key collection live in [`crate::service::exam`]. +//! The `exam` table: row reads and listings, the gated create that refuses a +//! course that is gone, the compare-and-set every PATCH writes through, and +//! the cascading delete. The PATCH re-derive lives in [`crate::service::exam`]. -use surrealdb::types::{RecordId, SurrealValue}; - -use crate::constant::ENROLLMENT_COUNT_FIELD; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; +use crate::database::{Database, foreign_key_violation, tx_with_retry}; use crate::domain::course::CourseId; use crate::domain::exam::{ Exam, ExamAttemptLimit, ExamDescription, ExamId, ExamKind, ExamSchedule, ExamTitle, redraft_error, }; +use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -33,58 +29,104 @@ pub async fn create( allow_review: bool, draft: bool, ) -> Result { - let exam = Exam { - id: ExamId::generate(), - creator: creator.clone(), - course: course.clone(), + // A missing parent is refused by the real foreign keys: a course or a + // creator that is gone is `SQLSTATE 23503`, and this call site's + // parent-gone answer is the same `NotFound` the old existence-proof + // touch (`cap::touch_and_create`, deleted) answered with. The bump that + // touch made and unmade is gone with it — an exam was never counted + // anywhere. + let created = sqlx::query_as!( + Exam, + r#"INSERT INTO exam (id, creator, course, title, description, kind, mode, + starts_at, ends_at, duration_ms, max_attempts, + allow_rejoin, allow_review, draft) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) + RETURNING id AS "id: ExamId", creator AS "creator: UserId", + course AS "course: CourseId", title AS "title: ExamTitle", + description AS "description: ExamDescription", + kind AS "kind: ExamKind", mode AS "mode: Option", + starts_at AS "starts_at: Option", + ends_at AS "ends_at: Option", + duration_ms AS "duration_ms: Option", + max_attempts AS "max_attempts: ExamAttemptLimit", + allow_rejoin, allow_review, draft"#, + ExamId::generate(), + creator as &UserId, + course as &CourseId, title, description, kind, - mode: schedule.mode, - starts_at: schedule.starts_at, - ends_at: schedule.ends_at, - duration_ms: schedule.duration_ms, + schedule.mode, + schedule.starts_at, + schedule.ends_at, + schedule.duration_ms, max_attempts, allow_rejoin, allow_review, draft, - result_count: None, - }; - // The course row is *written* (bumped and put back), not read: a plain - // read does not survive `Course::delete`'s window, and an exam that - // outlives its course is unreachable for good — every route to one goes - // through `course_of`, which answers a 500 no delete can clear, while - // `GET /exams` still lists it. See [`cap::touch_and_create`]. - cap::touch_and_create( - &course.record(), - ENROLLMENT_COUNT_FIELD, - &exam.id.record(), - &exam, - db, ) - .await? - .ok_or(AppError::NotFound) + .fetch_one(db) + .await; + match created { + Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound), + Err(err) => Err(err.into()), + Ok(exam) => Ok(exam), + } } pub async fn read(db: &Database, id: &ExamId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + Ok(sqlx::query_as!( + Exam, + r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", + title AS "title: ExamTitle", description AS "description: ExamDescription", + kind AS "kind: ExamKind", mode AS "mode: Option", + starts_at AS "starts_at: Option", + ends_at AS "ends_at: Option", + duration_ms AS "duration_ms: Option", + max_attempts AS "max_attempts: ExamAttemptLimit", + allow_rejoin, allow_review, draft + FROM exam WHERE id = $1"#, + id as &ExamId, + ) + .fetch_optional(db) + .await?) } +/// The exams, newest first — `ORDER BY id` on a UUIDv7 column is creation +/// order, the sort the old record ids gave for free. pub async fn list_all(db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM exam ORDER BY id DESC") - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + Exam, + r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", + title AS "title: ExamTitle", description AS "description: ExamDescription", + kind AS "kind: ExamKind", mode AS "mode: Option", + starts_at AS "starts_at: Option", + ends_at AS "ends_at: Option", + duration_ms AS "duration_ms: Option", + max_attempts AS "max_attempts: ExamAttemptLimit", + allow_rejoin, allow_review, draft + FROM exam ORDER BY id DESC"#, + ) + .fetch_all(db) + .await?) } pub async fn list_for_course(db: &Database, course: &CourseId) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM exam WHERE course = $course ORDER BY id DESC") - .bind(("course", course.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + Exam, + r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", + title AS "title: ExamTitle", description AS "description: ExamDescription", + kind AS "kind: ExamKind", mode AS "mode: Option", + starts_at AS "starts_at: Option", + ends_at AS "ends_at: Option", + duration_ms AS "duration_ms: Option", + max_attempts AS "max_attempts: ExamAttemptLimit", + allow_rejoin, allow_review, draft + FROM exam WHERE course = $1 ORDER BY id DESC"#, + course as &CourseId, + ) + .fetch_all(db) + .await?) } /// Every exam of every course in `courses` (one query) — the catalog as one @@ -93,13 +135,36 @@ pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result = courses.iter().map(CourseId::record).collect(); - let mut result = db - .query("SELECT * FROM exam WHERE course IN $courses ORDER BY id DESC") - .bind(("courses", records)) - .await? - .check()?; - Ok(result.take::>(0)?) + let courses = courses.iter().map(CourseId::uuid).collect::>(); + Ok(sqlx::query_as!( + Exam, + r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", + title AS "title: ExamTitle", description AS "description: ExamDescription", + kind AS "kind: ExamKind", mode AS "mode: Option", + starts_at AS "starts_at: Option", + ends_at AS "ends_at: Option", + duration_ms AS "duration_ms: Option", + max_attempts AS "max_attempts: ExamAttemptLimit", + allow_rejoin, allow_review, draft + FROM exam WHERE course = ANY($1) ORDER BY id DESC"#, + courses, + ) + .fetch_all(db) + .await?) +} + +/// The exam's mark counter, read on its own — the one column no struct +/// carries and no whole-row rewrite touches. The kind-change gate reads it +/// here (pre-flight) and `update_if_unchanged` pins it inside its own +/// transaction (write time). +pub async fn result_count(db: &Database, id: &ExamId) -> Result { + let row = sqlx::query!( + r#"SELECT result_count AS "result_count: i64" FROM exam WHERE id = $1"#, + id as &ExamId, + ) + .fetch_one(db) + .await?; + Ok(row.result_count) } // `course` is deliberately not updatable — moving an exam between courses @@ -113,11 +178,23 @@ pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result Result, AppError> { - // Re-drafting hides an exam: it must be refused while any sitting or - // mark exists, and that check has to be *in this transaction*. Holding - // it under a lock outside would only order the two writers inside one - // process — and it did not even do that, since grading takes the reader - // lease this write does. let redraft = draft && !expected.draft; let was = ( expected.title.clone(), @@ -160,92 +232,114 @@ pub async fn update_if_unchanged( expected.allow_rejoin = allow_rejoin; expected.allow_review = allow_review; expected.draft = draft; - // whole-row-save-ok: the WHERE below pins every column this replaces to - // the caller's snapshot, so no concurrent write can be reverted - // - // Sent through the retry loop, not a bare `query`: this row now has a - // hot writer. Every answer save touches it to tie itself to the exam - // ([`crate::db::exam_answer::save`]), so a teacher - // flipping `allow_rejoin` mid-exam can lose a round to a student - // typing — and a lost round is a re-send, never the 500 a bare `?` on - // the conflict would have answered. Re-sending is sound because the - // statement is a compare-and-set: the second pass carries the same - // pinned snapshot, so it lands only if the row is still what the caller - // read, and a rival that really moved it is refused as it was before. - // Admissible for the loop — an `UPDATE`, an `IF`/`THROW` and a `SELECT` - // can never answer "already exists". - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - IF $redraft AND ( - array::len((SELECT VALUE id FROM exam_attempt WHERE exam = $id LIMIT 1)) > 0 - OR array::len((SELECT VALUE id FROM exam_result WHERE exam = $id LIMIT 1)) > 0 - ) { THROW 'exam_redraft' }; - UPDATE $id CONTENT $new - WHERE title = $was_title AND description = $was_description - AND kind = $was_kind AND mode = $was_mode - AND starts_at = $was_starts AND ends_at = $was_ends - AND duration_ms = $was_duration - AND max_attempts = $was_max_attempts - AND allow_rejoin = $was_allow_rejoin - AND allow_review = $was_allow_review - AND draft = $was_draft - AND (result_count ?? 0) = $was_results - RETURN AFTER; - COMMIT TRANSACTION;", - &[ - ("redraft".into(), redraft.into_value()), - ("id".into(), expected.id.record().into_value()), - ("was_title".into(), was.0.into_value()), - ("was_description".into(), was.1.into_value()), - ("was_kind".into(), was.2.into_value()), - ("was_mode".into(), was.3.into_value()), - ("was_starts".into(), was.4.into_value()), - ("was_ends".into(), was.5.into_value()), - ("was_duration".into(), was.6.into_value()), - ("was_max_attempts".into(), was.7.into_value()), - ("was_allow_rejoin".into(), was.8.into_value()), - ("was_allow_review".into(), was.9.into_value()), - ("was_draft".into(), was.10.into_value()), - // The mark counter is pinned like every other column this write - // replaces, and for a sharper reason: a grade increments it, so - // pinning it is what makes "this exam had no marks" — the gate - // the handler refuses a kind change on — true at *write* time - // and not merely at read time. A mark landing in between - // refuses the save. - ( - "was_results".into(), - expected.result_count.unwrap_or(0).into_value(), - ), - ("new".into(), expected.into_value()), - ], - &["exam_redraft"], - ) + let saved = tx_with_retry(db, false, async |conn| { + if redraft { + // `exam_redraft`: the same refusal the handler's pre-flight + // answers, re-made at write time. A sitting or a mark existing + // hides nothing. + let gates = sqlx::query!( + r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat, + EXISTS(SELECT 1 FROM exam_result WHERE exam = $1) AS graded"#, + expected.id as &ExamId, + ) + .fetch_one(&mut *conn) + .await?; + if gates.sat || gates.graded { + return Err(redraft_error()); + } + } + let was_results = sqlx::query!( + r#"SELECT result_count AS "result_count: i64" FROM exam WHERE id = $1"#, + expected.id as &ExamId, + ) + .fetch_optional(&mut *conn) + .await? + .map(|row| row.result_count) + .unwrap_or(0); + let written = sqlx::query_as!( + Exam, + r#"UPDATE exam SET title = $2, description = $3, kind = $4, mode = $5, + starts_at = $6, ends_at = $7, duration_ms = $8, + max_attempts = $9, allow_rejoin = $10, allow_review = $11, + draft = $12 + WHERE id = $1 + AND title = $13 AND description = $14 AND kind = $15 + AND mode IS NOT DISTINCT FROM $16 + AND starts_at IS NOT DISTINCT FROM $17 + AND ends_at IS NOT DISTINCT FROM $18 + AND duration_ms IS NOT DISTINCT FROM $19 + AND max_attempts = $20 AND allow_rejoin = $21 AND allow_review = $22 + AND draft = $23 + AND result_count = $24 + RETURNING id AS "id: ExamId", creator AS "creator: UserId", + course AS "course: CourseId", title AS "title: ExamTitle", + description AS "description: ExamDescription", + kind AS "kind: ExamKind", mode AS "mode: Option", + starts_at AS "starts_at: Option", + ends_at AS "ends_at: Option", + duration_ms AS "duration_ms: Option", + max_attempts AS "max_attempts: ExamAttemptLimit", + allow_rejoin, allow_review, draft"#, + expected.id as &ExamId, + expected.title, + expected.description, + expected.kind, + expected.mode, + expected.starts_at, + expected.ends_at, + expected.duration_ms, + expected.max_attempts, + expected.allow_rejoin, + expected.allow_review, + expected.draft, + was.0, + was.1, + was.2, + was.3, + was.4, + was.5, + was.6, + was.7, + was.8, + was.9, + was.10, + was_results, + ) + .fetch_optional(&mut *conn) + .await?; + Ok(written) + }) .await?; - // An aborted transaction errors every slot; only the THROW's names the - // marker (the [`crate::db::exam_attempt::write_unfrozen`] treatment). - if errors - .values() - .any(|error| error.to_string().contains("exam_redraft")) - { - return Err(redraft_error()); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // BEGIN and the IF take a slot each. - Ok(result.take::>(2)?.into_iter().next()) + Ok(saved) +} + +/// What [`delete`] collects on its way through: the deleted row plus the +/// blob keys of the image rows its cascade removed — exactly whose files +/// the web layer may unlink. +pub struct Deleted { + pub exam: Exam, + pub question_image_files: Vec, + pub answer_image_files: Vec, } /// Delete the exam and cascade-remove its result, attempt, question, /// answer, question-image, and answer-image rows — all in one transaction, /// so a failure can't leave an emptied-out exam shell behind. The image -/// *blobs* (question and answer) are the web layer's to remove — it collects -/// their names before calling this. +/// *blobs* are the caller's to remove — this returns the names, collected +/// inside the same transaction that removes the rows. +/// +/// The transaction opens by taking the exam row `FOR UPDATE` — the store +/// replacement of the writer lease the delete used to hold. Every child +/// writer that matters locks the same row first (a sitting create's guard, +/// the freeze gate, an answer save ahead of its upsert), so a start or a +/// save either finished before the sweep (which then takes its row) or +/// finds no exam and is a `404`. Left orphaned, an attempt kept a sitting +/// on the student's lifetime counter and could mint a badge — awards are +/// add-only and never revoked — for an exam that never existed. /// /// Bank templates saved out of this exam survive it — they are a separate, -/// reusable library — so only their `source_exam` provenance link is cleared, -/// in the same transaction, never left pointing at a dead exam. +/// reusable library — so only their `source_exam` provenance link is +/// cleared, in the same transaction, never left pointing at a dead exam. /// /// The questions about to be cascaded each hold a reference on their /// subject, which is what keeps that subject from being deleted under them. @@ -256,52 +350,156 @@ pub async fn update_if_unchanged( /// concurrent `remove_result` in the gap would be released twice — once by /// each — which on a kind another exam still uses reads as one mark too /// few, and that is a kind wrongly free to leave the settings. -pub async fn delete(db: &Database, target: Exam) -> Result { - let (mut result, mut errors) = transaction_with_retry( +pub async fn delete(db: &Database, target: Exam) -> Result { + tx_with_retry( + db, + true, + async |conn| { + // The row lock every other exam-child writer contends on. + let locked = sqlx::query!( + r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, + target.id as &ExamId, + ) + .fetch_optional(&mut *conn) + .await?; + if locked.is_none() { + return Err(AppError::NotFound); + } + // The blob names, collected *before* the rows go — inside the + // lock, so an image row written after this snapshot cannot + // strand its bytes on disk even though the row itself would be + // refused. + let image_files = sqlx::query!( + r#"SELECT file FROM question_image WHERE exam = $1"#, + target.id as &ExamId, + ) + .fetch_all(&mut *conn) + .await? + .into_iter() + .map(|row| row.file) + .collect(); + let answer_image_files = sqlx::query!( + r#"SELECT file FROM answer_image WHERE exam = $1"#, + target.id as &ExamId, + ) + .fetch_all(&mut *conn) + .await? + .into_iter() + .map(|row| row.file) + .collect(); + // The marks give their kind references back, counted per kind + // off the results this exam still has. The ref row always + // exists here: a mark's own claim creates it before any result + // can land. + sqlx::query!( + r#"WITH kinds AS ( + SELECT e.kind AS kind, count(*) AS n + FROM exam_result r JOIN exam e ON e.id = r.exam + WHERE r.exam = $1 + GROUP BY e.kind) + UPDATE kind_ref k SET count = GREATEST(k.count - c.n, 0) + FROM kinds c WHERE k.name = c.kind"#, + target.id as &ExamId, + ) + .execute(&mut *conn) + .await?; + sqlx::query!(r#"DELETE FROM exam_result WHERE exam = $1"#, target.id as &ExamId) + .execute(&mut *conn) + .await?; + sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = $1"#, target.id as &ExamId) + .execute(&mut *conn) + .await?; + sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = $1"#, target.id as &ExamId) + .execute(&mut *conn) + .await?; + sqlx::query!(r#"DELETE FROM answer_image WHERE exam = $1"#, target.id as &ExamId) + .execute(&mut *conn) + .await?; + sqlx::query!(r#"DELETE FROM question_image WHERE exam = $1"#, target.id as &ExamId) + .execute(&mut *conn) + .await?; + // The cascaded questions give their subject references back, + // counted per subject off the rows still present — before the + // questions themselves go. + sqlx::query!( + r#"WITH subs AS ( + SELECT subject, count(*) AS n + FROM exam_question WHERE exam = $1 + GROUP BY subject) + UPDATE subject s SET exam_question_count = GREATEST(s.exam_question_count - c.n, 0) + FROM subs c WHERE s.id = c.subject"#, + target.id as &ExamId, + ) + .execute(&mut *conn) + .await?; + sqlx::query!(r#"DELETE FROM exam_question WHERE exam = $1"#, target.id as &ExamId) + .execute(&mut *conn) + .await?; + sqlx::query!( + r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = $1"#, + target.id as &ExamId, + ) + .execute(&mut *conn) + .await?; + let deleted = sqlx::query_as!( + Exam, + r#"DELETE FROM exam WHERE id = $1 + RETURNING id AS "id: ExamId", creator AS "creator: UserId", + course AS "course: CourseId", title AS "title: ExamTitle", + description AS "description: ExamDescription", + kind AS "kind: ExamKind", mode AS "mode: Option", + starts_at AS "starts_at: Option", + ends_at AS "ends_at: Option", + duration_ms AS "duration_ms: Option", + max_attempts AS "max_attempts: ExamAttemptLimit", + allow_rejoin, allow_review, draft"#, + target.id as &ExamId, + ) + .fetch_optional(&mut *conn) + .await?; + let Some(exam) = deleted else { + return Err(AppError::NotFound); + }; + Ok(Deleted { + exam, + question_image_files: image_files, + answer_image_files, + }) + }, + ) + .await +} + +#[cfg(test)] +use crate::domain::settings::ExamKindDef; + +/// An unscheduled published exam — the minimum any test that writes a *child* +/// of an exam needs, in any module: every such write moves the exam row (see +/// [`crate::db::exam_attempt::write_unfrozen_with`] +/// and [`crate::db::exam_answer::save`]), so a minted id whose +/// row was never created is a 404 rather than a silent orphan. +#[cfg(test)] +pub(crate) async fn published_exam(db: &Database) -> Exam { + let allowed: Vec = crate::domain::settings::Settings::defaults() + .get_exam_kinds() + .to_vec(); + create( db, - "BEGIN TRANSACTION; - FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result - WHERE exam = $ex GROUP BY kind) ?? []) { - UPDATE type::record('kind_ref', $row.kind) SET count = - math::max([(count ?? 0) - $row.n, 0]) - }; - DELETE exam_result WHERE exam = $ex; - DELETE exam_attempt WHERE exam = $ex; - DELETE exam_answer WHERE exam = $ex; - DELETE answer_image WHERE exam = $ex; - DELETE question_image WHERE exam = $ex; - FOR $row IN ((SELECT subject, count() AS n FROM exam_question - WHERE exam = $ex GROUP BY subject) ?? []) { - UPDATE $row.subject SET exam_question_count = - math::max([(exam_question_count ?? 0) - $row.n, 0]) - }; - DELETE exam_question WHERE exam = $ex; - UPDATE bank_question SET source_exam = NONE WHERE source_exam = $ex; - LET $before = (DELETE $ex RETURN BEFORE); - RETURN $before; - COMMIT TRANSACTION;", - &[("ex".into(), target.id.record().into_value())], - // No THROW of its own: an unconditional cascade, so the only error - // worth telling apart is a lost round, and `check()` — which took - // the *first* error in the batch — could not. It reported a - // sibling's "not executed" and made a retryable round a 500. - &[], + &UserId::generate(), + &crate::db::course::a_test_course(db).await, + ExamTitle::try_new("midterm").unwrap(), + ExamDescription::try_new("").unwrap(), + ExamKind::try_new("midterm", &allowed).unwrap(), + ExamSchedule::try_new(None, None, None, None).unwrap(), + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + false, ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The deleted row comes back through the transaction's trailing - // `RETURN`, never a hand-counted slot: the old `take(8)` turned a - // successful delete into a 404 the moment a cascade statement was - // inserted above it (it already had to be bumped once). `RETURN` is - // always the last statement before `COMMIT`, so its slot is derived - // from the statement count and every insertion above it shifts it - // along. `num_statements` counts BEGIN and COMMIT too, hence -2. - let slot = result.num_statements().saturating_sub(2); - let deleted: Option = result.take::>(slot)?.into_iter().next(); - deleted.ok_or(AppError::NotFound) + .await + .unwrap() } + #[cfg(test)] use crate::domain::settings::ExamKindDef; diff --git a/src/db/exam_answer.rs b/src/db/exam_answer.rs index e7ab1a8..4b60638 100644 --- a/src/db/exam_answer.rs +++ b/src/db/exam_answer.rs @@ -3,13 +3,12 @@ //! retake and the cascades use. The sitting key shape and the payload //! validation's pure half live in [`crate::domain::exam_answer`]. -use surrealdb::types::SurrealValue; +use sqlx::PgConnection; -use crate::constant::EXAM_RESULT_COUNT_FIELD; -use crate::database::{Database, transaction_with_retry}; +use crate::database::{Database, tx_with_retry}; use crate::domain::exam::ExamId; -use crate::domain::exam_answer::{AnswerText, ExamAnswer, ExamAnswerId}; -use crate::domain::exam_question::{ExamQuestion, ExamQuestionId}; +use crate::domain::exam_answer::{AnswerText, ExamAnswer}; +use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -64,92 +63,66 @@ pub async fn save( (None, Some(AnswerText::try_new(&text)?)) } }; - let answer = ExamAnswer { - id: ExamAnswerId::composite(question.get_id(), user, seq), - exam: question.get_exam().clone(), - question: question.get_id().clone(), - user: user.clone(), - seq, - selected, - text, - updated_at: Timestamp::now(), - }; - // The save writes the *exam row* as well as the answer, in one + // The save locks the *exam row* before upserting the answer, in one // transaction, and that is what ties the answer's fate to its exam: - // reading the exam does not survive [`crate::db::exam::delete`]'s - // window — a save landing after its `DELETE exam_answer WHERE exam = $ex` - // but before the commit reads an exam that is still there (uncommitted) - // while the sweep ran on a snapshot predating this row, so both commit - // and the answer outlives the exam (measured 4 of 4 raced rounds). - // Writing the key the delete removes makes the two collide, and the - // store refuses one of them. It is the shape - // [`crate::domain::menu::bump_menu_and_write`] uses, and the one a mark - // already uses on this very row - // ([`crate::db::exam_result::grade`]). - // - // The bump-and-restore is not a flourish, it is the whole instrument. - // The exam carries no revision to bump and must not grow one — its save - // is a whole-row `CONTENT` write, so a column this struct did not know - // about would be wiped by the next PATCH — so this touches the one - // counter it already has and puts it back. Writing the *same* value is - // not enough: an `UPDATE` that leaves the document unchanged is elided - // and never reaches the store's write set, which the race test proved - // (green on the raced delete, red the moment the value moves for real). - // The restore is by captured value, `NONE` included, so the row is - // byte-identical afterwards: the boot backfill still finds the rows it - // keys on (`WHERE result_count = NONE`), the PATCH's - // `(result_count ?? 0) = $was_results` still passes, and no teacher's - // edit is refused because a student typed. Both statements are inside - // the transaction, so a crash between them cannot leave the counter up. - // No `cap::counter_lock` either: no counter moves here, and the hottest - // write path in the app should not queue behind one. - // - // Admissible for `transaction_with_retry`: the `UPDATE`s, `SELECT`, - // `IF`/`THROW` and `RETURN` can never answer "already exists", and the - // `UPSERT`'s id is bijective with the (question, user, seq) triple - // `exam_answer` keys — a lost round wrote nothing, and re-sending - // resolves onto the same row rather than colliding with it. - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $was = (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $ex); - LET $touched = (UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = \ - ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); - IF array::len($touched) = 0 {{ THROW 'no_exam' }}; - UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = $was; - LET $row = (UPSERT $id CONTENT $answer RETURN AFTER); - RETURN $row[0]; - COMMIT TRANSACTION;" - ), - &[ - ("ex".into(), answer.exam.record().into_value()), - ("id".into(), answer.id.record().into_value()), - ("answer".into(), answer.into_value()), - ], - &["no_exam"], + // reading the exam does not survive + // [`crate::db::exam::delete`]'s window — a save landing after its + // cascade swept the answers but before it committed would have read an + // exam that was still there and written an orphan no sweep would ever + // visit. Locking the key the delete removes first makes the two + // serialize: the save either lands before the sweep (which then takes + // the row too) or finds no exam and answers the same `404` the old + // `no_exam` THROW did. Real foreign keys stand behind the lock — a + // child insert whose parent is gone refuses itself — which is what + // retired the bump-and-restore this used to ride on. + tx_with_retry(db, false, async |conn| { + save_in(conn, question, user, seq, selected, text).await + }) + .await +} + +/// The locked exam-row probe plus the upsert, on one connection — split out +/// so the exam room's room-bound save shares the exact statements. +pub(crate) async fn save_in( + conn: &mut PgConnection, + question: &ExamQuestion, + user: &UserId, + seq: i64, + selected: Option, + text: Option, +) -> Result { + let touched = sqlx::query!( + r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, + question.get_exam() as &ExamId, ) + .fetch_optional(&mut *conn) .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_exam")) - { + if touched.is_none() { return Err(AppError::NotFound); } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is the last statement before `COMMIT`, so its - // slot follows the statement count rather than a hand-kept number (the - // `db::exam::delete` treatment); `num_statements` counts BEGIN and COMMIT. - let slot = result.num_statements().saturating_sub(2); - result - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to save exam answer".into())) + let now = Timestamp::now(); + sqlx::query_as!( + ExamAnswer, + r#"INSERT INTO exam_answer (exam, question, app_user, selected, text, updated_at, seq) + VALUES ($1, $2, $3, $4, $5, $6, $7) + ON CONFLICT (question, app_user, seq) DO UPDATE + SET selected = EXCLUDED.selected, text = EXCLUDED.text, + updated_at = EXCLUDED.updated_at + RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", + app_user AS "user: UserId", seq, + selected AS "selected: Option", + text AS "text: Option", + updated_at AS "updated_at: Timestamp""#, + question.get_exam() as &ExamId, + question.get_id() as &ExamQuestionId, + user as &UserId, + seq, + selected, + text, + now, + ) + .fetch_one(&mut *conn) + .await } /// One student's stored answer for a question in sitting `seq`, if any. @@ -159,9 +132,21 @@ pub async fn read( user: &UserId, seq: i64, ) -> Result, AppError> { - Ok(db - .select(ExamAnswerId::composite(question, user, seq).record()) - .await?) + Ok(sqlx::query_as!( + ExamAnswer, + r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", + app_user AS "user: UserId", seq, + selected AS "selected: Option", + text AS "text: Option", + updated_at AS "updated_at: Timestamp" + FROM exam_answer + WHERE question = $1 AND app_user = $2 AND seq = $3"#, + question as &ExamQuestionId, + user as &UserId, + seq, + ) + .fetch_optional(db) + .await?) } /// Drop one student's answer to a single question in sitting `seq`. @@ -171,14 +156,19 @@ pub async fn delete( user: &UserId, seq: i64, ) -> Result<(), AppError> { - let _: Option = db - .delete(ExamAnswerId::composite(question, user, seq).record()) - .await?; + sqlx::query!( + r#"DELETE FROM exam_answer WHERE question = $1 AND app_user = $2 AND seq = $3"#, + question as &ExamQuestionId, + user as &UserId, + seq, + ) + .execute(db) + .await?; Ok(()) } /// One student's answers for a single sitting (`seq`) across an exam, in -/// question (ULID) order — the live-sitting read-back and, for a past +/// question (id) order — the live-sitting read-back and, for a past /// `seq`, that attempt's answer sheet. pub async fn list_for_exam_user( db: &Database, @@ -186,17 +176,22 @@ pub async fn list_for_exam_user( user: &UserId, seq: i64, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM exam_answer WHERE exam = $ex AND user = $usr AND seq = $seq - ORDER BY question ASC", - ) - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .bind(("seq", seq)) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + ExamAnswer, + r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", + app_user AS "user: UserId", seq, + selected AS "selected: Option", + text AS "text: Option", + updated_at AS "updated_at: Timestamp" + FROM exam_answer + WHERE exam = $1 AND app_user = $2 AND seq = $3 + ORDER BY question ASC"#, + exam as &ExamId, + user as &UserId, + seq, + ) + .fetch_all(db) + .await?) } /// The distinct sittings a student has any answer for at `exam`, ascending @@ -206,28 +201,31 @@ pub async fn list_seqs_for_user( exam: &ExamId, user: &UserId, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT VALUE seq FROM exam_answer WHERE exam = $ex AND user = $usr - ORDER BY seq ASC", - ) - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .await? - .check()?; - let mut seqs = result.take::>(0)?; - seqs.dedup(); - Ok(seqs) + let rows = sqlx::query!( + r#"SELECT DISTINCT seq FROM exam_answer + WHERE exam = $1 AND app_user = $2 ORDER BY seq ASC"#, + exam as &ExamId, + user as &UserId, + ) + .fetch_all(db) + .await?; + Ok(rows.into_iter().map(|row| row.seq).collect()) } /// Every answer of an exam — the live monitor aggregates these per student. pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM exam_answer WHERE exam = $ex ORDER BY question ASC") - .bind(("ex", exam.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + ExamAnswer, + r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", + app_user AS "user: UserId", seq, + selected AS "selected: Option", + text AS "text: Option", + updated_at AS "updated_at: Timestamp" + FROM exam_answer WHERE exam = $1 ORDER BY question ASC"#, + exam as &ExamId, + ) + .fetch_all(db) + .await?) } /// Drop one student's answers across an exam — a retake starts from a @@ -237,11 +235,13 @@ pub async fn delete_for_exam_user( exam: &ExamId, user: &UserId, ) -> Result<(), AppError> { - db.query("DELETE exam_answer WHERE exam = $ex AND user = $usr") - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .await? - .check()?; + sqlx::query!( + r#"DELETE FROM exam_answer WHERE exam = $1 AND app_user = $2"#, + exam as &ExamId, + user as &UserId, + ) + .execute(db) + .await?; Ok(()) } diff --git a/src/db/exam_attempt.rs b/src/db/exam_attempt.rs index c265936..0429a48 100644 --- a/src/db/exam_attempt.rs +++ b/src/db/exam_attempt.rs @@ -1,31 +1,61 @@ //! The `exam_attempt` table: sitting reads, the two field-scoped writes -//! (`finished_at`, `left_at`), and the `write_unfrozen` transaction gateway -//! that ties exam-child writes to their exam row. +//! (`finished_at`, `left_at`), the guarded sitting create, and the freeze +//! gate — the in-transaction check every exam-child write runs before it +//! touches anything. -use surrealdb::types::{RecordId, SurrealValue}; +use sqlx::PgConnection; -use crate::constant::EXAM_RESULT_COUNT_FIELD; -use crate::database::{Database, transaction_with_retry}; +use crate::database::{Database, tx_with_retry, unique_violation}; +use crate::db::cap::{self, Claimed}; use crate::domain::exam::ExamId; use crate::domain::exam_attempt::{ExamAttempt, ExamAttemptId}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; -/// The `THROW` marker the freeze gate aborts with, and the one 409 both it and -/// the handler's pre-flight check answer with — a client cannot tell which of -/// the two refused. -const FROZEN_MARK: &str = "questions_frozen"; - -/// The `THROW` marker the exam-existence touch aborts with — the exam row this -/// write hangs off is gone, so the write is a 404 and nothing lands. -const GONE_MARK: &str = "no_exam"; - -/// The 409 the freeze gate's marker means. +/// The 409 the freeze gate answers — the same one the handlers' pre-flight +/// check ([`crate::service::exam_question::ensure_questions_editable`]) +/// answers, so a client cannot tell which of the two refused. fn frozen_error() -> AppError { AppError::Conflict("cannot change questions after attempts have started") } +/// The freeze gate, run inside a caller's transaction on that caller's own +/// connection: take the exam row `FOR UPDATE`, then refuse unless the exam +/// still exists and nobody has started an attempt. +/// +/// This is the whole of the old `write_unfrozen` machinery — the +/// `questions_frozen` THROW and the bump-and-restore existence touch — with +/// Postgres doing the work the tricks stood in for. The row lock makes the +/// check-and-write one unit against [`crate::db::exam::delete`] (which locks +/// the same row before its cascade) and against a sitting create (whose +/// guard below locks it too): a question edit can no longer sail past an +/// attempt that started in the gate's gap, and a child whose exam died +/// mid-flight finds no row here and is the same 404 the old `no_exam` THROW +/// answered with. Real foreign keys retire the bump-and-restore: the child +/// inserts themselves refuse a parent that is gone. +pub(crate) async fn freeze_gate(conn: &mut PgConnection, exam: &ExamId) -> Result<(), AppError> { + let row = sqlx::query!( + r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, + exam as &ExamId, + ) + .fetch_optional(&mut *conn) + .await?; + if row.is_none() { + return Err(AppError::NotFound); + } + let sat = sqlx::query!( + r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat"#, + exam as &ExamId, + ) + .fetch_one(&mut *conn) + .await?; + if sat.sat { + return Err(frozen_error()); + } + Ok(()) +} + /// Stamp the submission time. The caller has already checked the deadline /// and that the attempt isn't finished. /// @@ -36,17 +66,23 @@ fn frozen_error() -> AppError { /// A whole-row write from the pre-read snapshot would carry its stale /// `left_at` back over that stamp, erasing the recorded walk-out. pub async fn finish(db: &Database, attempt: ExamAttempt) -> Result { - let mut result = db - .query("UPDATE $id SET finished_at = $at RETURN AFTER") - .bind(("id", attempt.id.record())) - .bind(("at", Some(Timestamp::now()))) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + let id = attempt.get_id(); + let updated = sqlx::query_as!( + ExamAttempt, + r#"UPDATE exam_attempt SET finished_at = $1 + WHERE exam = $2 AND app_user = $3 AND seq = $4 + RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq, + started_at AS "started_at: Timestamp", + finished_at AS "finished_at: Option", + left_at AS "left_at: Option""#, + Timestamp::now(), + id.exam, + id.user, + id.seq, + ) + .fetch_optional(db) + .await?; + updated.ok_or(AppError::NotFound) } /// Stamp (or clear) the walked-out marker. The exam room sets it when the @@ -63,23 +99,73 @@ pub async fn set_left( attempt: ExamAttempt, left_at: Option, ) -> Result { - let mut result = db - .query("UPDATE $id SET left_at = $left RETURN AFTER") - .bind(("id", attempt.id.record())) - .bind(("left", left_at)) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + let id = attempt.get_id(); + let updated = sqlx::query_as!( + ExamAttempt, + r#"UPDATE exam_attempt SET left_at = $1 + WHERE exam = $2 AND app_user = $3 AND seq = $4 + RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq, + started_at AS "started_at: Timestamp", + finished_at AS "finished_at: Option", + left_at AS "left_at: Option""#, + left_at, + id.exam, + id.user, + id.seq, + ) + .fetch_optional(db) + .await?; + updated.ok_or(AppError::NotFound) +} + +/// Stamp `left_at` on one sitting, but only while it is genuinely in +/// progress: nothing stamped yet, nothing submitted, and the exam's *live* +/// schedule has not run past the sitting's deadline. One conditional +/// statement — the exam-room teardown's whole stamp, with the re-derive +/// [`crate::domain::exam_attempt::ExamAttempt::status`] used to do folded +/// into the `WHERE` (joined to `exam` so a deleted exam's sitting is simply +/// not stamped, and concurrent last-outs are harmless: only the first finds +/// `left_at IS NULL`). +pub async fn stamp_left_if_running( + db: &Database, + attempt_id: &ExamAttemptId, + now: Timestamp, +) -> Result<(), AppError> { + sqlx::query!( + r#"UPDATE exam_attempt a SET left_at = $4 + FROM exam e + WHERE e.id = a.exam + AND a.exam = $1 AND a.app_user = $2 AND a.seq = $3 + AND a.left_at IS NULL AND a.finished_at IS NULL + AND (e.duration_ms IS NULL OR $4 < a.started_at + e.duration_ms) + AND (e.duration_ms IS NOT NULL OR e.ends_at IS NULL OR $4 < e.ends_at)"#, + attempt_id.exam, + attempt_id.user, + attempt_id.seq, + now, + ) + .execute(db) + .await?; + Ok(()) } /// One sitting by id — the exam room re-reads its own attempt this way, /// so a retake started elsewhere can never be mistaken for it. pub async fn read(db: &Database, id: &ExamAttemptId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + Ok(sqlx::query_as!( + ExamAttempt, + r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, + started_at AS "started_at: Timestamp", + finished_at AS "finished_at: Option", + left_at AS "left_at: Option" + FROM exam_attempt + WHERE exam = $1 AND app_user = $2 AND seq = $3"#, + id.exam, + id.user, + id.seq, + ) + .fetch_optional(db) + .await?) } /// The student's current sitting — the highest `seq` for the pair. All @@ -89,16 +175,21 @@ pub async fn read_latest_for_user( exam: &ExamId, user: &UserId, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM exam_attempt WHERE exam = $ex AND user = $usr - ORDER BY seq DESC LIMIT 1", - ) - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + Ok(sqlx::query_as!( + ExamAttempt, + r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, + started_at AS "started_at: Timestamp", + finished_at AS "finished_at: Option", + left_at AS "left_at: Option" + FROM exam_attempt + WHERE exam = $1 AND app_user = $2 + ORDER BY seq DESC + LIMIT 1"#, + exam as &ExamId, + user as &UserId, + ) + .fetch_optional(db) + .await?) } /// Every sitting of `user` at `exam`, newest first. @@ -107,187 +198,180 @@ pub async fn list_for_user( exam: &ExamId, user: &UserId, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM exam_attempt WHERE exam = $ex AND user = $usr - ORDER BY seq DESC", - ) - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + ExamAttempt, + r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, + started_at AS "started_at: Timestamp", + finished_at AS "finished_at: Option", + left_at AS "left_at: Option" + FROM exam_attempt + WHERE exam = $1 AND app_user = $2 + ORDER BY seq DESC"#, + exam as &ExamId, + user as &UserId, + ) + .fetch_all(db) + .await?) } /// Every sitting of `user` nobody has submitted yet, across all exams. Only /// the *candidates* for "in progress": a deadline comes off the exam's live /// schedule, so the caller still judges [`ExamAttempt::status`] per exam rather -/// than re-spelling that rule in SurrealQL. +/// than re-spelling that rule in SQL. pub async fn list_unfinished_for_user( db: &Database, user: &UserId, ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM exam_attempt WHERE user = $usr AND finished_at = NONE") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + ExamAttempt, + r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, + started_at AS "started_at: Timestamp", + finished_at AS "finished_at: Option", + left_at AS "left_at: Option" + FROM exam_attempt + WHERE app_user = $1 AND finished_at IS NULL + ORDER BY started_at, exam"#, + user as &UserId, + ) + .fetch_all(db) + .await?) } pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM exam_attempt WHERE exam = $ex ORDER BY id DESC") - .bind(("ex", exam.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + ExamAttempt, + r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, + started_at AS "started_at: Timestamp", + finished_at AS "finished_at: Option", + left_at AS "left_at: Option" + FROM exam_attempt + WHERE exam = $1 + ORDER BY started_at DESC, seq DESC"#, + exam as &ExamId, + ) + .fetch_all(db) + .await?) } /// Whether anyone has started this exam — the gate that freezes `mode` /// edits once an attempt exists. pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result { - let mut result = db - .query("SELECT VALUE id FROM exam_attempt WHERE exam = $ex LIMIT 1") - .bind(("ex", exam.record())) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) -} - -/// Send `statements` wrapped in a transaction that refuses to run them at -/// all once `exam` has an attempt — the freeze gate, made atomic with the -/// write it guards instead of merely preceding it. `freeze_exam` is bound -/// here; the caller binds the rest and reads its own results from -/// [`FROZEN_SLOT`] onwards. -/// -/// The same transaction *writes* the exam row — bumping its mark counter -/// and putting it straight back — which is what ties every child written -/// through here to its exam. The freeze gate only *reads* `exam_attempt`, -/// and a read does not survive [`delete`](crate::db::exam::delete)'s -/// window: a question or picture landing after that delete removed the exam -/// but before it committed reads a row that is still there, while the -/// cascade's `DELETE exam_question WHERE exam = $ex` ran on a snapshot -/// predating this insert — so both commit and the child outlives the exam, -/// with neither caller told anything. Writing a key the delete also writes -/// makes the two collide and the store refuses one side. It is the shape -/// [`crate::db::exam_answer::save`] and -/// [`crate::db::menu::bump_menu_and_write`] already use. -/// -/// An orphan here is not merely untidy: an `exam_question` that outlives -/// its exam keeps the reference it claimed on its subject (the cascade's -/// per-subject decrement counted the rows it could see), and -/// [`crate::db::subject::delete`] is gated on that count -/// reading zero — a subject nobody can ever delete again. -/// -/// The bump is restored *by captured value*, `NONE` included, so the row is -/// byte-identical afterwards: the boot backfill still finds the rows it -/// keys on (`WHERE result_count = NONE`) and a teacher's PATCH, which pins -/// that counter, is not refused because somebody added a question. Writing -/// the same value back would not do — an `UPDATE` that leaves the document -/// unchanged is elided and never reaches the store's write set, so it -/// collides with nothing. -/// -/// This replaces a process-wide `EXAM_LOCK.write()` held across the check -/// and the write. That lock ordered the two requests but still read the -/// attempt table a round trip before it wrote; the gate checks inside the -/// writing statement, so a question edit can no longer sail past an attempt -/// that started in that gap. -/// -/// The send lives here rather than at the five call sites because a lost -/// round has to be re-sent, and only whoever owns the send can re-send: the -/// gate reads the very table its rival writes, so the two contend by design -/// and a raced edit used to answer 500. The refusal outranks the conflict — -/// `FROZEN_MARK` is a decision and stays the 409 the pre-flight check -/// answers with, and only exhausting the tries becomes a 500. See -/// [`transaction_with_retry`] for why the whole error map is scanned: an -/// aborted transaction errors *every* slot and all but one say a generic -/// "not executed". -/// -/// Returning only on an empty error map is what keeps [`FROZEN_SLOT`] -/// (and any slot counted off `num_statements`) correct — `take_errors` -/// `swap_remove`s errored slots, so a fixed slot read is meaningless once -/// anything failed. -// -// corner-cut: the count and a concurrent `CREATE exam_attempt` are still not -// serialized against each other — SurrealDB does not conflict-check a -// cross-record count (the write skew `db::cap` exists for), so an -// attempt landing in the same instant as an edit can still interleave -// either way. The mutex this replaces closed that inside one process only, -// and there are two, so nothing is lost. Closing it properly means the -// cap.rs shape: an attempt counter on the exam row, incremented by the -// attempt create, and the write conditioned on `count ?? 0 = 0`. -pub async fn write_unfrozen( - db: &Database, - exam: &ExamId, - statements: &str, - bindings: Vec<(String, surrealdb::types::Value)>, -) -> Result { - write_unfrozen_with(db, exam, statements, bindings, Vec::new()).await + let row = sqlx::query!( + r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat"#, + exam as &ExamId, + ) + .fetch_one(db) + .await?; + Ok(row.sat) } -/// [`write_unfrozen`] for statements that carry gates of their own: -/// each `(marker, refusal)` names a `THROW` the caller's SQL aborts with and -/// the error it means. The markers are handed to [`transaction_with_retry`] -/// too, so an abort on one is a refusal rather than a round to re-send. -/// -/// The freeze still outranks every one of them: a caller folding a counter -/// claim in here is refused as frozen even when its own gate would also have -/// fired, which is the answer the pre-flight check has always given. -pub async fn write_unfrozen_with( - db: &Database, +/// The sitting-create guard: the exam row locked `FOR UPDATE` and +/// re-judged *inside the inserting transaction* — draft (a 404, a draft is +/// invisible to students), no mode (a 409: visible, nothing to sit), the +/// window not yet open, the window already closed. This is what the old +/// writer lease `EXAM_LOCK` used to buy the sittable/window gates: they are +/// now judged against the locked row the attempt lands under, so a mode +/// change or re-draft cannot slip between a gate and the insert. The +/// refusal texts are [`crate::service::exam_attempt`]'s own — the same +/// words that pre-flight answers, so a client cannot tell which fired. +pub(crate) async fn guard_start( + conn: &mut PgConnection, exam: &ExamId, - statements: &str, - bindings: Vec<(String, surrealdb::types::Value)>, - refusals: Vec<(&str, AppError)>, -) -> Result { - let sql = format!( - "BEGIN TRANSACTION; - IF array::len((SELECT VALUE id FROM exam_attempt \ - WHERE exam = $freeze_exam LIMIT 1)) > 0 {{ THROW '{FROZEN_MARK}' }}; - LET $was_results = \ - (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $freeze_exam); - LET $touched = (UPDATE $freeze_exam SET {EXAM_RESULT_COUNT_FIELD} = \ - ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); - IF array::len($touched) = 0 {{ THROW '{GONE_MARK}' }}; - UPDATE $freeze_exam SET {EXAM_RESULT_COUNT_FIELD} = $was_results; - {statements} - COMMIT TRANSACTION;" - ); - let mut bound = vec![("freeze_exam".into(), exam.record().into_value())]; - bound.extend(bindings); - let mut marks = vec![FROZEN_MARK, GONE_MARK]; - marks.extend(refusals.iter().map(|(marker, _)| *marker)); - let (result, mut errors) = transaction_with_retry(db, &sql, &bound, &marks).await?; - let thrown = |marker: &str| { - errors - .values() - .any(|error| error.to_string().contains(marker)) + now: Timestamp, +) -> Result<(), AppError> { + let row = sqlx::query!( + r#"SELECT draft AS "draft: bool", mode AS "mode: Option", + starts_at AS "starts_at: Option", + ends_at AS "ends_at: Option" + FROM exam WHERE id = $1 FOR UPDATE"#, + exam as &ExamId, + ) + .fetch_optional(&mut *conn) + .await?; + let Some(row) = row else { + return Err(AppError::NotFound); }; - if thrown(FROZEN_MARK) { - return Err(frozen_error()); - } - // The exam is gone: the same 404 every one of these writes' handlers - // answers a missing exam with, and it outranks the callers' own gates - // for the freeze's reason — there is nothing left to refuse *about*. - if thrown(GONE_MARK) { + if row.draft { return Err(AppError::NotFound); } - for (marker, refusal) in refusals { - if thrown(marker) { - return Err(refusal); - } + if row.mode.is_none() { + return Err(AppError::Conflict( + "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)", + )); + } + if row.starts_at.is_some_and(|starts_at| now < starts_at) { + return Err(AppError::Conflict("the exam has not started yet")); } - match errors.drain().map(|(_, error)| error).next() { - Some(error) => Err(error.into()), - None => Ok(result), + if row.ends_at.is_some_and(|ends_at| now >= ends_at) { + return Err(AppError::Conflict("the exam has already ended")); } + Ok(()) } -/// The first slot a [`write_unfrozen`] caller's own statements land -/// in: `BEGIN`, the freeze `IF`, and the exam touch's two `LET`s, `IF` and -/// restoring `UPDATE` take one each. -pub const FROZEN_SLOT: usize = 6; +/// Insert the sitting row, claiming the student's `exam_sat_total` in the +/// same statement when — and only when — this is a first sitting (`seq == +/// 1`): that counter is *exams sat*, not sittings, and a retake counts +/// nothing. The claim-CTE recipe ([`cap`]): bump the counter row, insert +/// the child only if the bump landed, and let the sitting's natural +/// composite primary key (`exam_attempt_exam_user_seq`) answer "another +/// writer started this very sitting first" as `Claimed::Duplicate`. The +/// bump rides the insert's own transaction, so a refused insert takes its +/// increment straight back. +/// +/// `Claimed::Full` here can only mean the student's account row is missing +/// — nothing caps sittings — which the caller surfaces as its own internal. +pub(crate) async fn create_in( + conn: &mut PgConnection, + attempt: &ExamAttempt, + count_sitting: bool, +) -> Result, AppError> { + let bump = i64::from(count_sitting); + let created = sqlx::query_as!( + ExamAttempt, + r#"WITH seat AS ( + UPDATE app_user SET exam_sat_total = app_user.exam_sat_total + $4 + WHERE id = $2 + RETURNING 1) + INSERT INTO exam_attempt (exam, app_user, seq, started_at, finished_at, left_at) + SELECT $1, $2, $3, $5, NULL, NULL WHERE EXISTS (SELECT 1 FROM seat) + RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq, + started_at AS "started_at: Timestamp", + finished_at AS "finished_at: Option", + left_at AS "left_at: Option""#, + attempt.exam, + attempt.user, + attempt.seq, + bump, + attempt.started_at, + ) + .fetch_optional(&mut *conn) + .await; + match created { + Err(err) if unique_violation(&err) == Some("exam_attempt_exam_user_seq") => { + Ok(Claimed::Duplicate) + } + Err(err) => Err(err.into()), + Ok(None) => Ok(Claimed::Full), + Ok(Some(attempt)) => Ok(Claimed::Made(attempt)), + } +} + +/// The sitting create as one transaction: [`guard_start`], then +/// [`create_in`]. Retried while Postgres answers "contended"; a duplicate +/// or a missing student row is a verdict, not a conflict, and is never +/// re-sent. +pub async fn create( + db: &Database, + attempt: &ExamAttempt, + count_sitting: bool, + now: Timestamp, +) -> Result, AppError> { + tx_with_retry(db, false, async |conn| { + guard_start(conn, &attempt.exam, now).await?; + create_in(conn, attempt, count_sitting).await + }) + .await +} #[cfg(test)] mod tests { diff --git a/src/db/exam_question.rs b/src/db/exam_question.rs index 393e677..6f49b53 100644 --- a/src/db/exam_question.rs +++ b/src/db/exam_question.rs @@ -6,27 +6,19 @@ use std::collections::HashSet; -use surrealdb::types::{RecordId, SurrealValue}; +use sqlx::PgConnection; -use crate::constant::SUBJECT_QUESTION_COUNT_FIELD; -use crate::database::Database; -use crate::db::cap; -use crate::db::page::PagedList; +use crate::database::{Database, tx_with_retry}; +use crate::db::exam_attempt::freeze_gate; +use crate::db::page::{PagedList, Param}; use crate::domain::bank_question::BankQuestionId; use crate::domain::exam::ExamId; use crate::domain::exam_question::{ - ExamQuestion, ExamQuestionId, QuestionPoints, QuestionSpec, QuestionText, + Choice, ExamQuestion, ExamQuestionId, QuestionPoints, QuestionSpec, QuestionText, }; use crate::domain::subject::SubjectId; use crate::error::{AppError, ValidationError}; - -/// The `THROW` markers the folded counter moves abort with: the subject the -/// reference was to be claimed on is gone, the question being patched is gone, -/// and the subject this move started from is no longer the one the handler -/// read. File-local like every other marker set (`cap`'s, `subject`'s). -const SUBJECT_MARK: &str = "question_subject_gone"; -const ROW_MARK: &str = "question_row_gone"; -const STALE_MARK: &str = "question_stale_move"; +use sqlx::types::Json; /// The one answer for a subject that isn't there — a claim missing it and the /// web layer's pre-flight lookup missing it are the same 400. @@ -72,7 +64,6 @@ async fn insert( spec: QuestionSpec, from_bank: Option, ) -> Result { - let counted = subject.record(); let question = ExamQuestion { id: ExamQuestionId::generate(), exam: exam.clone(), @@ -89,61 +80,87 @@ async fn insert( // The freeze gate and the subject's reference ride in the same // transaction as the insert: a question cannot appear under an exam // somebody has already started, and the claim that accounts for it - // cannot outlive a row that never landed. Claiming in its own query - // (with a release on failure, as this did) leaves a window where a - // crash strands the count — and the subject delete is conditioned on - // that count reading zero, so a stranded one makes the subject - // undeletable forever. A missed claim means the subject is already gone - // — the same 400 the web layer's pre-flight check answers with. + // cannot outlive a row that never landed. A missed claim means the + // subject is already gone — the same 400 the web layer's pre-flight + // check answers with. // - // Re-sendable despite the `CREATE`: a lost round aborts having written - // nothing and `$id` is a ULID minted once per call, so the re-send - // cannot answer "already exists" (there is no UNIQUE index on - // `exam_question`) — the one thing the retry cannot survive. - let id = question.id.record(); - // One counter write in flight at a time, like every other counter write. - let _guard = cap::counter_lock().await; - let mut result = crate::db::exam_attempt::write_unfrozen_with( - db, - exam, - &format!( - "LET $seat = (UPDATE $subject SET {SUBJECT_QUESTION_COUNT_FIELD} = \ - ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); - IF array::len($seat) = 0 {{ THROW '{SUBJECT_MARK}' }}; - CREATE $id CONTENT $question;" - ), - vec![ - ("subject".into(), counted.into_value()), - ("id".into(), id.into_value()), - ("question".into(), question.into_value()), - ], - vec![(SUBJECT_MARK, dead_subject())], + // The id is a freshly minted UUIDv7, so no rival can aim at it: the + // only possible duplicate key is one this call minted, which is none. + tx_with_retry(db, false, async |conn| { + freeze_gate(conn, exam).await?; + claim_subject_and_insert(conn, &question).await + }) + .await +} + +/// The subject's reference claim and the row insert as one statement — the +/// counter and the row commit together, and zero rows out means the subject +/// was already gone (the claim's `UPDATE` found nothing to increment). The +/// same verdict as the old `question_subject_gone` THROW, which nothing +/// else could reach: the insert is refused with its claim, atomically. +async fn claim_subject_and_insert( + conn: &mut PgConnection, + question: &ExamQuestion, +) -> Result { + let created = sqlx::query_as!( + ExamQuestion, + r#"WITH seat AS ( + UPDATE subject SET exam_question_count = subject.exam_question_count + 1 + WHERE id = $1 + RETURNING 1) + INSERT INTO exam_question (id, exam, subject, text, kind, points, + choices, correct, from_bank, banked_as) + SELECT $2, $3, $1, $4, $5, $6, $7, $8, $9, NULL + WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId", + subject AS "subject: SubjectId", text AS "text: QuestionText", + kind AS "kind: QuestionKind", points AS "points: QuestionPoints", + choices AS "choices: Option>>", + correct AS "correct: Option", + from_bank AS "from_bank: Option", + banked_as AS "banked_as: Option""#, + question.subject, + question.id, + question.exam, + question.text, + question.kind, + question.points, + question.choices, + question.correct, + question.from_bank, ) + .fetch_optional(&mut *conn) .await?; - // Counted off the statements that actually ran rather than a fixed - // slot, so folding another gate in above can never mis-read the row. - let slot = result.num_statements().saturating_sub(2); - result - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to create exam question".into())) + created.ok_or_else(dead_subject) } pub async fn read(db: &Database, id: &ExamQuestionId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + Ok(sqlx::query_as!( + ExamQuestion, + r#"SELECT id AS "id: ExamQuestionId", exam AS "exam: ExamId", + subject AS "subject: SubjectId", text AS "text: QuestionText", + kind AS "kind: QuestionKind", points AS "points: QuestionPoints", + choices AS "choices: Option>>", + correct AS "correct: Option", + from_bank AS "from_bank: Option", + banked_as AS "banked_as: Option" + FROM exam_question WHERE id = $1"#, + id as &ExamQuestionId, + ) + .fetch_optional(db) + .await?) } -/// The exam's questions in presentation order (ULID ids sort by creation). +/// The exam's questions in presentation order (UUIDv7 ids sort by creation). pub async fn list_for_exam( db: &Database, exam: &ExamId, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("exam_question WHERE exam = $ex", "ORDER BY id ASC") - .bind("ex", exam.record()) - .run(limit, offset, db) + PagedList::new("exam_question WHERE exam = $1", "ORDER BY id ASC") + .bind(Param::Uuid(exam.uuid())) + .run::(limit, offset, db) .await } @@ -166,8 +183,7 @@ pub async fn list_for_exam( /// /// So: collect every template id reachable from a live exam by either /// column, then name any of `exam`'s questions pointing at one by either -/// column. `$shared` is built from `!= NONE` filters, so it never holds a -/// `NONE` for an unlinked question's absent column to match against. +/// column. pub async fn list_shared_with( db: &Database, exam: &ExamId, @@ -176,27 +192,26 @@ pub async fn list_shared_with( if live.is_empty() { return Ok(HashSet::new()); } - let mut result = db - .query( - "LET $shared = array::union( - (SELECT VALUE from_bank FROM exam_question - WHERE exam IN $live AND from_bank != NONE), - (SELECT VALUE banked_as FROM exam_question - WHERE exam IN $live AND banked_as != NONE)); - SELECT VALUE id FROM exam_question - WHERE exam = $ex AND (from_bank IN $shared OR banked_as IN $shared)", - ) - .bind(("ex", exam.record())) - .bind(( - "live", - live.iter().map(ExamId::record).collect::>(), - )) - .await? - .check()?; - Ok(result - .take::>(1)? - .iter() - .map(|id| id.key().to_string()) + let live = live.iter().map(ExamId::uuid).collect::>(); + let rows = sqlx::query!( + r#"WITH shared AS ( + SELECT from_bank AS t FROM exam_question + WHERE exam = ANY($1) AND from_bank IS NOT NULL + UNION + SELECT banked_as FROM exam_question + WHERE exam = ANY($1) AND banked_as IS NOT NULL) + SELECT q.id AS "id: ExamQuestionId" FROM exam_question q + WHERE q.exam = $2 + AND (q.from_bank IN (SELECT t FROM shared) + OR q.banked_as IN (SELECT t FROM shared))"#, + live, + exam as &ExamId, + ) + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .map(|row| row.id.key()) .collect()) } @@ -208,7 +223,7 @@ pub async fn list_shared_with( /// `from_bank`/`banked_as`, which [`link_banked_as`] writes from a /// *different* request: re-stating this snapshot's copy of them would /// revert a to-bank save that landed in between. That is exactly what the -/// caller's `EXAM_LOCK.write()` used to order (inside one process), and +/// caller's old `EXAM_LOCK.write()` used to order (inside one process), and /// naming the columns removes the need for any ordering at all. pub async fn update( db: &Database, @@ -225,8 +240,7 @@ pub async fn update( // undeletable forever). // // The two are armed on *different* conditions, which is the whole of - // the rule ([`crate::db::field_update::FieldUpdate::refcount`] states - // it the same way): the counter statements only when the link actually + // the rule: the counter statements only when the link actually // changes, but the CAS whenever this write *carries* the link — and it // always does, because the handler fills an omitted `subject_id` from // the row it read (`web::exams::questions`), so `subject` is in the @@ -235,88 +249,81 @@ pub async fn update( // subject its own stale snapshot held, sent while a rival's move // already landed, writes that stale subject straight back over the // winner — a revert with the counters left pointing at the move. - let retag = - (subject != question.subject).then(|| (subject.record(), question.subject.record())); - let write = "UPDATE $id SET subject = $subject, text = $text, points = $points, - kind = $kind, choices = $choices, correct = $correct"; - let mut bindings = vec![ - ("id".into(), question.id.record().into_value()), - ("subject".into(), subject.record().into_value()), - ("text".into(), text.into_value()), - ("points".into(), points.into_value()), - ("kind".into(), spec.kind.into_value()), - ("choices".into(), spec.choices.into_value()), - ("correct".into(), spec.correct.into_value()), - ]; - let mut statements: Vec = Vec::new(); - let mut refusals: Vec<(&str, AppError)> = Vec::new(); - if let Some((next, previous)) = &retag { - statements.push(format!( - "UPDATE $ref_release SET {SUBJECT_QUESTION_COUNT_FIELD} = \ - math::max([({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) - 1, 0])" - )); - statements.push(format!( - "LET $seat = (UPDATE $ref_claim SET {SUBJECT_QUESTION_COUNT_FIELD} = \ - ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id)" - )); - statements.push(format!( - "IF array::len($seat) = 0 {{ THROW '{SUBJECT_MARK}' }}" - )); - bindings.push(("ref_claim".into(), next.clone().into_value())); - bindings.push(("ref_release".into(), previous.clone().into_value())); - refusals.push((SUBJECT_MARK, dead_subject())); - } - // The CAS: the row write matches only while the question still sits on - // the subject this handler read. A genuine no-op re-state passes it - // trivially (the row holds exactly what is expected); a stale one — - // whether it moves the link or restates it — matches nothing, aborts - // the whole transaction, and so claims nothing and answers 409. - bindings.push(( - "ref_expected".into(), - question.subject.record().into_value(), - )); - statements.push(format!( - "LET $row = ({write} WHERE subject = $ref_expected RETURN AFTER)" - )); - statements.push(format!( - "IF array::len($row) = 0 {{ \ - LET $live = (UPDATE $id WHERE subject != $ref_expected RETURN VALUE id); \ - IF array::len($live) = 0 {{ THROW '{ROW_MARK}' }} \ - ELSE {{ THROW '{STALE_MARK}' }} }}" - )); - statements.push("RETURN $row".into()); - refusals.push(( - STALE_MARK, - AppError::Conflict( - "the subject this question was read on changed since; re-read and retry", - ), - )); - // The row is gone: the same 404 an empty write answers with, so the - // deleted-row case is unchanged. - refusals.push((ROW_MARK, AppError::NotFound)); - let statements = format!("{};", statements.join("; ")); - // One counter write in flight at a time — only a move writes one. - let _guard = match &retag { - Some(_) => Some(cap::counter_lock().await), - None => None, - }; - let mut result = crate::db::exam_attempt::write_unfrozen_with( - db, - &question.exam, - &statements, - bindings, - refusals, - ) - .await?; - // Read off the trailing `RETURN` rather than a fixed slot: a re-tag - // arms three more statements than a plain PATCH does (and an `IF` - // block is one slot whether or not it is taken). - let slot = result.num_statements().saturating_sub(2); - result - .take::>(slot)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + let retag = (subject != question.subject).then(|| (subject, question.subject.clone())); + tx_with_retry(db, false, async |conn| { + // Freeze first, as always: it outranks every caller gate, and a + // frozen exam answers the same 409 the pre-flight check gave. + freeze_gate(conn, &question.exam).await?; + if let Some((next, previous)) = &retag { + sqlx::query!( + r#"UPDATE subject SET exam_question_count = + GREATEST(exam_question_count - 1, 0) + WHERE id = $1"#, + previous as &SubjectId, + ) + .execute(&mut *conn) + .await?; + let claimed = sqlx::query!( + r#"UPDATE subject SET exam_question_count = subject.exam_question_count + 1 + WHERE id = $1 RETURNING 1"#, + next as &SubjectId, + ) + .fetch_optional(&mut *conn) + .await?; + if claimed.is_none() { + return Err(dead_subject()); + } + } + // The CAS: the row write matches only while the question still sits on + // the subject this handler read. A genuine no-op re-state passes it + // trivially (the row holds exactly what is expected); a stale one — + // whether it moves the link or restates it — matches nothing, aborts + // the whole transaction, and so claims nothing and answers 409. + let written = sqlx::query_as!( + ExamQuestion, + r#"UPDATE exam_question + SET subject = $2, text = $3, points = $4, kind = $5, + choices = $6, correct = $7 + WHERE id = $1 AND subject = $8 + RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId", + subject AS "subject: SubjectId", text AS "text: QuestionText", + kind AS "kind: QuestionKind", points AS "points: QuestionPoints", + choices AS "choices: Option>>", + correct AS "correct: Option", + from_bank AS "from_bank: Option", + banked_as AS "banked_as: Option""#, + question.id as &ExamQuestionId, + subject, + text, + points, + spec.kind, + spec.choices, + spec.correct, + question.subject as &SubjectId, + ) + .fetch_optional(&mut *conn) + .await?; + let Some(written) = written else { + // The row is gone, or it moved under the snapshot. The same + // 404 an empty write used to answer with distinguishes the + // deleted-row case; anything still standing is a stale read, + // which is the 409. + let live = sqlx::query!( + r#"SELECT EXISTS(SELECT 1 FROM exam_question WHERE id = $1) AS live"#, + question.id as &ExamQuestionId, + ) + .fetch_one(&mut *conn) + .await?; + if !live.live { + return Err(AppError::NotFound); + } + return Err(AppError::Conflict( + "the subject this question was read on changed since; re-read and retry", + )); + }; + Ok(written) + }) + .await } /// Point the question's `banked_as` at the bank template it was just saved @@ -330,26 +337,28 @@ pub async fn update( /// Field-scoped write, unlike [`update`]: the caller awaits a bank /// insert plus the whole blob-copy loop between reading this row and /// linking it, so the row it holds is long stale by now — a whole-row save -/// would silently revert whatever landed in that window. (The caller takes -/// `EXAM_LOCK.read()` around this call, which is what keeps -/// [`update`]'s whole-row save from clobbering the link in the other -/// direction; the lease guards the ordering, not the staleness.) +/// would silently revert whatever landed in that window. pub async fn link_banked_as( db: &Database, question: ExamQuestion, template: BankQuestionId, ) -> Result { - let mut result = db - .query("UPDATE $id SET banked_as = $bank RETURN AFTER") - .bind(("id", question.id.record())) - .bind(("bank", template.record())) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + let linked = sqlx::query_as!( + ExamQuestion, + r#"UPDATE exam_question SET banked_as = $2 WHERE id = $1 + RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId", + subject AS "subject: SubjectId", text AS "text: QuestionText", + kind AS "kind: QuestionKind", points AS "points: QuestionPoints", + choices AS "choices: Option>>", + correct AS "correct: Option", + from_bank AS "from_bank: Option", + banked_as AS "banked_as: Option""#, + question.id as &ExamQuestionId, + template as &BankQuestionId, + ) + .fetch_optional(db) + .await?; + linked.ok_or(AppError::NotFound) } /// Delete the question and cascade-remove its answers and image rows, so @@ -359,33 +368,50 @@ pub async fn link_banked_as( /// delete — and the cascade now shares that transaction too, so a failure /// mid-way can no longer strand answers whose question survived. pub async fn delete(db: &Database, question: ExamQuestion) -> Result { - let mut result = crate::db::exam_attempt::write_unfrozen( - db, - &question.exam, - &format!( - "DELETE exam_answer WHERE question = $q; - DELETE question_image WHERE question = $q; - LET $gone = (DELETE $q RETURN BEFORE); - FOR $sub IN ($gone.subject ?? []) {{ - UPDATE $sub SET {SUBJECT_QUESTION_COUNT_FIELD} = - math::max([({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) - 1, 0]) - }}; - RETURN $gone;" - ), - vec![("q".into(), question.id.record().into_value())], - ) - .await?; - // The subject's reference is given back inside this same transaction, - // driven off what the delete actually removed — a question that wasn't - // there decrements nothing. Read through the trailing `RETURN` rather - // than a hand-counted slot, so inserting a cascade statement above can - // never turn a delete into a 404 (see [`crate::domain::exam::Exam`]). - let slot = result.num_statements().saturating_sub(2); - result - .take::>(slot)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + tx_with_retry(db, false, async |conn| { + freeze_gate(conn, &question.exam).await?; + sqlx::query!( + r#"DELETE FROM exam_answer WHERE question = $1"#, + question.id as &ExamQuestionId, + ) + .execute(&mut *conn) + .await?; + sqlx::query!( + r#"DELETE FROM question_image WHERE question = $1"#, + question.id as &ExamQuestionId, + ) + .execute(&mut *conn) + .await?; + let deleted = sqlx::query_as!( + ExamQuestion, + r#"DELETE FROM exam_question WHERE id = $1 + RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId", + subject AS "subject: SubjectId", text AS "text: QuestionText", + kind AS "kind: QuestionKind", points AS "points: QuestionPoints", + choices AS "choices: Option>>", + correct AS "correct: Option", + from_bank AS "from_bank: Option", + banked_as AS "banked_as: Option""#, + question.id as &ExamQuestionId, + ) + .fetch_optional(&mut *conn) + .await?; + // The subject's reference is given back inside this same transaction, + // driven off what the delete actually removed — a question that wasn't + // there decrements nothing. + if let Some(deleted) = &deleted { + sqlx::query!( + r#"UPDATE subject SET exam_question_count = + GREATEST(exam_question_count - 1, 0) + WHERE id = $1"#, + deleted.subject as &SubjectId, + ) + .execute(&mut *conn) + .await?; + } + deleted.ok_or(AppError::NotFound) + }) + .await } #[cfg(test)] diff --git a/src/db/exam_result.rs b/src/db/exam_result.rs index 4c39b29..3337d0b 100644 --- a/src/db/exam_result.rs +++ b/src/db/exam_result.rs @@ -1,50 +1,42 @@ //! The `exam_result` table: the mark's claim-riding upsert, the per-sitting //! history reads, and the refunding delete. The grade pre-flight (draft, kind, -//! grader/target walls) and the `EXAM_LOCK` lease live in +//! grader/target walls) lives in //! [`crate::service::exam_result`]; the mark newtype and the latest-per-pair //! fold live in [`crate::domain::exam_result`]. -use surrealdb::types::SurrealValue; - -use crate::constant::{ - EXAM_RESULT_COUNT_FIELD, HIGH_MARK_MIN, HIGH_MARK_TOTAL_FIELD, MARKS_GIVEN_TOTAL_FIELD, - REF_COUNT_FIELD, REF_RETIRED_FIELD, -}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; +use crate::constant::HIGH_MARK_MIN; +use crate::database::{Database, tx_with_retry}; use crate::domain::course::CourseId; use crate::domain::exam::ExamId; use crate::domain::exam_result::{ - ExamResult, ExamResultId, Mark, draft_error, kind_ref, latest_per_pair, retired_kind_error, + ExamResult, Mark, draft_error, latest_per_pair, retired_kind_error, }; use crate::domain::user::UserId; use crate::error::AppError; -/// The `THROW` marker the in-transaction kind claim aborts with — the mark's -/// own transaction refusing a name the school has retired. -const RETIRED_MARK: &str = "kind_retired"; - /// A single user's result for an exam, if graded — the latest sitting's mark. async fn find(db: &Database, exam: &ExamId, user: &UserId) -> Result, AppError> { // Grade-of-record is the latest sitting's mark: the highest seq wins. - let mut result = db - .query( - "SELECT * FROM exam_result WHERE exam = $ex AND user = $usr - ORDER BY seq DESC LIMIT 1", - ) - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + Ok(sqlx::query_as!( + ExamResult, + r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, + mark AS "mark: Mark", graded_by AS "graded_by: UserId" + FROM exam_result WHERE exam = $1 AND app_user = $2 + ORDER BY seq DESC LIMIT 1"#, + exam as &ExamId, + user as &UserId, + ) + .fetch_optional(db) + .await?) } /// Record (or overwrite) `user`'s mark for the `seq`th sitting of `exam`. -/// One row per (exam, user, seq), keyed by a deterministic composite id so -/// this is a single atomic UPSERT — concurrent grades for the same sitting -/// converge on one row instead of racing the unique index into a 500. -/// Grading a retake writes a fresh mark at the current seq and never touches -/// prior sittings' marks; the latest seq is the grade-of-record. +/// One row per (exam, user, seq), keyed by the natural composite primary key +/// `exam_result_exam_user_seq`, so this is a single atomic UPSERT — +/// concurrent grades for the same sitting converge on one row instead of +/// racing the unique index into a 500. Grading a retake writes a fresh mark +/// at the current seq and never touches prior sittings' marks; the latest +/// seq is the grade-of-record. /// /// `kind` is the exam's kind, and this is where a mark takes its reference /// on it — claimed *inside the mark's own transaction*, and only on the @@ -58,7 +50,10 @@ async fn find(db: &Database, exam: &ExamId, user: &UserId) -> Result Result { - let result = ExamResult { - id: ExamResultId::composite(exam, user, seq), - exam: exam.clone(), - user: user.clone(), - seq, - mark, - graded_by: graded_by.clone(), - }; // The "exists" and "not a draft" gates ride in the same transaction as // the mark, the mirror of the re-draft gate on // `crate::db::exam::update_if_unchanged`: between them, a mark and a // re-draft racing each other can only ever leave one of the two applied, // whichever process either ran in. The existence gate is not - // redundant with the draft one — a deleted exam reads NONE, which is - // *falsy*, so the draft gate alone waved a mark onto an exam that no - // longer existed. The caller's pre-flight check answers the same 409 - // one round trip earlier. It is also what makes a separate "did the - // exam survive my claim?" check moot: the claim now sits behind this - // gate instead of in front of it. + // redundant with the draft one — a missing row answers the same `404` + // the old `exam_missing` THROW answered with, and `draft` alone could + // never see a row that is not there. The caller's pre-flight check + // answers the same 409 one round trip earlier. // - // `$before` is the sitting's *previous mark*, and it answers both - // questions off one read: `mark` is a mandatory column on a schemafull - // row, so `NONE` there means no row at all — the claim branch — while a - // number is what the student's counter takes its difference against. - // Read one statement before the counters inside the same transaction: - // read anywhere else it would be a guess about a row two graders may be - // writing at once, and the difference would be taken against a mark - // some other round had already replaced. - // - // Re-sent while the store answers "conflict, retry": the gates read a - // column an exam PATCH writes, and the counters are the ones a - // concurrent delete gives back, so this contends on three records by - // design. Sound to re-send because no statement in it can legitimately - // answer "already exists": the counter writes are `UPDATE`/`UPSERT` on - // ids no rival can collide *into*, and the mark's own UPSERT is on a - // deterministic id bijective with the `exam_result_exam_user_seq` - // unique tuple — `key::sitting(exam, user, seq)` *is* that tuple, so - // the index entry can only ever point at the row the id already names - // and the write resolves onto it. A lost round aborts having written - // nothing, counters included. - let _guard = cap::counter_lock().await; - let (mut written, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - IF (SELECT VALUE id FROM ONLY $exam) IS NONE {{ THROW 'exam_missing' }}; - IF (SELECT VALUE draft FROM ONLY $exam) {{ THROW 'exam_draft' }}; - LET $before = (SELECT VALUE mark FROM ONLY $id); - IF $before = NONE {{ - LET $kind = (UPSERT $kref SET {REF_COUNT_FIELD} = ({REF_COUNT_FIELD} ?? 0) + 1 - WHERE {REF_RETIRED_FIELD} != true RETURN VALUE id); - IF array::len($kind) = 0 {{ THROW '{RETIRED_MARK}' }}; - UPDATE $exam SET {EXAM_RESULT_COUNT_FIELD} = - ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1; - UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = - ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1; - }}; - LET $high = (IF $result.mark >= {HIGH_MARK_MIN} {{ 1 }} ELSE {{ 0 }}) - - (IF ($before ?? -1) >= {HIGH_MARK_MIN} {{ 1 }} ELSE {{ 0 }}); - IF $high != 0 {{ - UPDATE $student SET {HIGH_MARK_TOTAL_FIELD} = - math::max([({HIGH_MARK_TOTAL_FIELD} ?? 0) + $high, 0]) - }}; - LET $after = (UPSERT $id CONTENT $result RETURN AFTER); - RETURN $after[0]; - COMMIT TRANSACTION;" - ), - &[ - ("exam".into(), exam.record().into_value()), - ("id".into(), result.id.record().into_value()), - ("kref".into(), kind_ref(kind).into_value()), - ("grader".into(), graded_by.record().into_value()), - ("student".into(), user.record().into_value()), - ("result".into(), result.into_value()), - ], - &["exam_missing", "exam_draft", RETIRED_MARK], - ) - .await?; - // An aborted transaction errors every slot and only the THROW's own - // slot names the marker, so a refusal is read by marker while a lost - // round was already re-sent — never reported as a 500. - let thrown = |marker: &str| { - errors - .values() - .any(|error| error.to_string().contains(marker)) - }; - if thrown("exam_missing") { - return Err(AppError::NotFound); - } - if thrown("exam_draft") { - return Err(draft_error()); - } - if thrown(RETIRED_MARK) { - return Err(retired_kind_error(kind)); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`, - // so its slot follows the statement count instead of a hand-kept - // number — see `db::exam::delete` for the bug the hand-kept one caused. - // Probed on crate 3.2.3: an `IF { … }` block occupies exactly one slot - // however many statements it holds, and one whether or not it is taken. - let slot = written.num_statements().saturating_sub(2); - written - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to record exam result".into())) + // `$before` — the sitting's previous mark — answers both counter + // questions off one read: `None` there means no row at all (the claim + // branch), while a number is what the student's counter takes its + // difference against. Read one statement before the counters inside + // the same transaction: read anywhere else it would be a guess about a + // row two graders may be writing at once, and the difference would be + // taken against a mark some other round had already replaced. The exam + // row's `FOR UPDATE` is what makes that read the write's own: a rival + // grade holds the same lock across its whole transaction, so the two + // serialize instead of interleaving their counter moves. + tx_with_retry(db, false, async |conn| { + let exam_row = sqlx::query!( + r#"SELECT draft AS "draft: bool" FROM exam WHERE id = $1 FOR UPDATE"#, + exam as &ExamId, + ) + .fetch_optional(&mut *conn) + .await?; + let Some(exam_row) = exam_row else { + return Err(AppError::NotFound); + }; + if exam_row.draft { + return Err(draft_error()); + } + let before = sqlx::query!( + r#"SELECT mark AS "mark: Mark" FROM exam_result + WHERE exam = $1 AND app_user = $2 AND seq = $3"#, + exam as &ExamId, + user as &UserId, + seq, + ) + .fetch_optional(&mut *conn) + .await? + .map(|row| row.mark); + if before.is_none() { + // `kind_retired`: the mark's own transaction refusing a name + // the school has retired. Zero rows — retired, or the ref row + // gone with the kind — refuse the claim; a live row takes the + // count. + let claimed = sqlx::query!( + r#"UPDATE kind_ref SET count = kind_ref.count + 1 + WHERE name = $1 AND retired = false + RETURNING 1"#, + kind, + ) + .fetch_optional(&mut *conn) + .await?; + if claimed.is_none() { + return Err(retired_kind_error(kind)); + } + sqlx::query!( + r#"UPDATE exam SET result_count = exam.result_count + 1 WHERE id = $1"#, + exam as &ExamId, + ) + .execute(&mut *conn) + .await?; + sqlx::query!( + r#"UPDATE app_user SET marks_given_total = app_user.marks_given_total + 1 + WHERE id = $1"#, + graded_by as &UserId, + ) + .execute(&mut *conn) + .await?; + } + let stored = before.map_or(-1, |mark| mark.as_i64()); + let high = i64::from(mark.as_i64() >= HIGH_MARK_MIN) - i64::from(stored >= HIGH_MARK_MIN); + if high != 0 { + sqlx::query!( + r#"UPDATE app_user SET high_mark_total = + GREATEST(high_mark_total + $2, 0) + WHERE id = $1"#, + user as &UserId, + high, + ) + .execute(&mut *conn) + .await?; + } + let written = sqlx::query_as!( + ExamResult, + r#"INSERT INTO exam_result (exam, app_user, seq, mark, graded_by) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (exam, app_user, seq) DO UPDATE + SET mark = EXCLUDED.mark, graded_by = EXCLUDED.graded_by + RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq, + mark AS "mark: Mark", graded_by AS "graded_by: UserId""#, + exam as &ExamId, + user as &UserId, + seq, + mark, + graded_by as &UserId, + ) + .fetch_one(&mut *conn) + .await?; + Ok(written) + }) + .await } /// The user's graded results restricted to one course's exams — the raw @@ -209,26 +200,33 @@ pub async fn list_for_user_in_course( course: &CourseId, user: &UserId, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM exam_result WHERE user = $usr - AND exam IN (SELECT VALUE id FROM exam WHERE course = $course) - ORDER BY id DESC", - ) - .bind(("usr", user.record())) - .bind(("course", course.record())) - .await? - .check()?; - Ok(latest_per_pair(result.take::>(0)?)) + let rows = sqlx::query_as!( + ExamResult, + r#"SELECT r.exam AS "exam: ExamId", r.app_user AS "user: UserId", r.seq, + r.mark AS "mark: Mark", r.graded_by AS "graded_by: UserId" + FROM exam_result r JOIN exam e ON e.id = r.exam + WHERE r.app_user = $1 AND e.course = $2 + ORDER BY r.exam DESC, r.seq DESC"#, + user as &UserId, + course as &CourseId, + ) + .fetch_all(db) + .await?; + Ok(latest_per_pair(rows)) } pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC") - .bind(("ex", exam.record())) - .await? - .check()?; - Ok(latest_per_pair(result.take::>(0)?)) + let rows = sqlx::query_as!( + ExamResult, + r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, + mark AS "mark: Mark", graded_by AS "graded_by: UserId" + FROM exam_result WHERE exam = $1 + ORDER BY exam DESC, seq DESC"#, + exam as &ExamId, + ) + .fetch_all(db) + .await?; + Ok(latest_per_pair(rows)) } /// Every sitting's mark for one (exam, user) pair, oldest first — the @@ -238,16 +236,17 @@ pub async fn list_all_for_exam_user( exam: &ExamId, user: &UserId, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM exam_result WHERE exam = $ex AND user = $usr - ORDER BY seq ASC", - ) - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + ExamResult, + r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, + mark AS "mark: Mark", graded_by AS "graded_by: UserId" + FROM exam_result WHERE exam = $1 AND app_user = $2 + ORDER BY seq ASC"#, + exam as &ExamId, + user as &UserId, + ) + .fetch_all(db) + .await?) } /// A single user's result for an exam, if graded. @@ -272,7 +271,7 @@ pub async fn read_for_user( /// actually deleted: `marks_given_total` to each row's *own* grader (two /// teachers can hold two sittings of the same pair), and `high_mark_total` /// once per removed row that cleared [`HIGH_MARK_MIN`], read off the -/// `BEFORE` image rather than re-derived. That last one is why +/// deleted image rather than re-derived. That last one is why /// [`grade`] has to move the student's counter on a *regrade* /// too: this end reads the stored mark, so the other end must be decided by /// the stored mark as well, or a mark walked across the line between the @@ -289,57 +288,92 @@ pub async fn remove( // release them a second time, and on a kind another exam still grades // under, one release too many reads as one mark too few — a kind // wrongly free to leave the settings. - // - // Re-sent while the store answers "conflict, retry": the counters this - // touches are the ones a concurrent grade claims, so a lost round is - // routine and aborts having written nothing. `check()` cannot be used - // to read the outcome — it takes the *lowest*-slot error, and an - // aborted transaction's generic "not executed" sibling masked the real - // conflict, the exact defect deleted from `db::exam::delete`. No THROW - // of its own, and only `DELETE`/`UPDATE` inside, so nothing here can - // answer "already exists" and make a retry unsound. - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $gone = (DELETE exam_result WHERE exam = $ex AND user = $usr RETURN BEFORE); - IF array::len($gone) > 0 {{ - UPDATE type::record('kind_ref', $kind) SET {REF_COUNT_FIELD} = - math::max([({REF_COUNT_FIELD} ?? 0) - array::len($gone), 0]); - UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = - math::max([({EXAM_RESULT_COUNT_FIELD} ?? 0) - array::len($gone), 0]); - LET $high = array::len($gone[WHERE mark >= {HIGH_MARK_MIN}]); - IF $high > 0 {{ - UPDATE $usr SET {HIGH_MARK_TOTAL_FIELD} = - math::max([({HIGH_MARK_TOTAL_FIELD} ?? 0) - $high, 0]) - }}; - FOR $row IN $gone {{ - LET $grader = $row.graded_by; - UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = - math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0]) - }}; - }}; - RETURN $gone; - COMMIT TRANSACTION;" - ), - &[ - ("ex".into(), exam.record().into_value()), - ("usr".into(), user.record().into_value()), - ("kind".into(), kind.to_string().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // `RETURN` is the last statement before `COMMIT`; its slot follows the - // statement count, as in `db::exam::delete`. - let slot = result.num_statements().saturating_sub(2); - let removed = result.take::>(slot)?; - Ok(removed.into_iter().next()) + tx_with_retry(db, false, async |conn| { + // The `gone` CTE deletes and reports in one statement: the counters + // below move by exactly what this delete removed, so a concurrent + // grade's rows (it holds the exam row's lock, and this statement's + // sibling below takes the same lock before touching `result_count`) + // can never be half-counted. + let gone = sqlx::query!( + r#"WITH gone AS ( + DELETE FROM exam_result + WHERE exam = $1 AND app_user = $2 + RETURNING mark AS "mark: Mark", graded_by AS "graded_by: UserId", seq) + SELECT seq, mark AS "mark: Mark", graded_by AS "graded_by: UserId" + FROM gone ORDER BY seq ASC"#, + exam as &ExamId, + user as &UserId, + ) + .fetch_all(&mut *conn) + .await?; + if gone.is_empty() { + return Ok(None); + } + sqlx::query!( + r#"UPDATE kind_ref SET count = GREATEST(kind_ref.count - $2, 0) + WHERE name = $1"#, + kind, + gone.len() as i64, + ) + .execute(&mut *conn) + .await?; + sqlx::query!( + r#"UPDATE exam SET result_count = GREATEST(exam.result_count - $2, 0) + WHERE id = $1"#, + exam as &ExamId, + gone.len() as i64, + ) + .execute(&mut *conn) + .await?; + let high = gone.iter().filter(|row| row.mark.as_i64() >= HIGH_MARK_MIN).count() as i64; + if high > 0 { + sqlx::query!( + r#"UPDATE app_user SET high_mark_total = + GREATEST(high_mark_total - $2, 0) + WHERE id = $1"#, + user as &UserId, + high, + ) + .execute(&mut *conn) + .await?; + } + // One give-back per distinct grader: two teachers can hold two + // sittings of the same pair. + let mut per_grader: Vec<(UserId, i64)> = Vec::new(); + for row in &gone { + if let Some((_, n)) = + per_grader.iter_mut().find(|(grader, _)| grader == &row.graded_by) + { + *n += 1; + } else { + per_grader.push((row.graded_by.clone(), 1)); + } + } + for (grader, n) in &per_grader { + sqlx::query!( + r#"UPDATE app_user SET marks_given_total = + GREATEST(marks_given_total - $2, 0) + WHERE id = $1"#, + grader as &UserId, + n, + ) + .execute(&mut *conn) + .await?; + } + // The first sitting's row comes back — the same shape the old + // `RETURN` handed over, whose caller only asks whether anything was + // removed and what the latest standing was. + let first = gone.into_iter().next().map(|row| ExamResult { + exam: exam.clone(), + user: user.clone(), + seq: row.seq, + mark: row.mark, + graded_by: row.graded_by, + }); + Ok(first) + }) + .await } - #[cfg(test)] mod tests { use super::*; diff --git a/src/db/question_image.rs b/src/db/question_image.rs index f48f094..ad59c44 100644 --- a/src/db/question_image.rs +++ b/src/db/question_image.rs @@ -4,66 +4,84 @@ //! constructor — lives in [`crate::domain::question_image`]; the blob bytes //! stay the web layer's. -use surrealdb::types::SurrealValue; +use sqlx::PgConnection; -use crate::database::Database; +use crate::database::{Database, tx_with_retry}; +use crate::db::exam_attempt::freeze_gate; use crate::domain::course::CourseId; use crate::domain::exam::ExamId; use crate::domain::exam_question::{ChoiceId, ExamQuestionId}; -use crate::domain::question_image::{QuestionImage, QuestionImageId}; +use crate::domain::question_image::QuestionImage; use crate::error::AppError; -/// What one [`upsert`] transaction returns: the row it stored -/// and the blob name it replaced. Both are arrays because SurrealDB drops an object -/// key valued `NONE` on the way out, while an empty array survives — "nothing -/// was replaced" has to be readable, not missing. -#[derive(SurrealValue)] -struct UpsertOutcome { - stored: Vec, - replaced: Vec, -} - -/// Create or replace the slot's image row — the deterministic id makes -/// this the whole "one image per slot" story — handing back what it stored -/// plus the blob name it replaced, for the caller to take off disk. Refused -/// once the exam has an attempt: pictures are part of the question, so they -/// freeze with it, and the gate is in this transaction rather than in a lock -/// the caller held. +/// Create or replace the slot's image row — the `UNIQUE NULLS NOT DISTINCT` +/// (question, slot) constraint makes this the whole "one image per slot" +/// story — handing back what it stored plus the blob name it replaced, for +/// the caller to take off disk. Refused once the exam has an attempt: +/// pictures are part of the question, so they freeze with it, and the gate +/// is in this transaction rather than in a lock the caller held. /// -/// The replaced name is read *here*, not by the caller before it: two -/// uploads to one slot both write this row, so they contend and the loser -/// re-reads the winner's blob name, where two pre-reads both saw the *old* -/// blob and left the loser's fresh one orphaned on disk. +/// The replaced name is read *inside the same transaction*, not by the +/// caller before it: two uploads to one slot both write this row, so they +/// contend on it and the loser re-reads the winner's blob name, where two +/// pre-reads both saw the *old* blob and left the loser's fresh one +/// orphaned on disk. pub async fn upsert( db: &Database, image: QuestionImage, ) -> Result<(QuestionImage, Option), AppError> { - // whole-row-save-ok: image is built in place, never read back, and the slot id is deterministic - let (exam, id) = (image.exam.clone(), image.id.record()); - let mut result = crate::db::exam_attempt::write_unfrozen( - db, - &exam, - "LET $replaced = (SELECT VALUE file FROM $id); - LET $stored = (UPSERT $id CONTENT $image); - RETURN { stored: $stored, replaced: $replaced };", - vec![ - ("id".into(), id.into_value()), - ("image".into(), image.into_value()), - ], + tx_with_retry(db, false, async |conn| { + upsert_in(conn, image).await + }) + .await +} + +/// The gated read-and-replace, on one connection. +pub(crate) async fn upsert_in( + conn: &mut PgConnection, + image: QuestionImage, +) -> Result<(QuestionImage, Option), AppError> { + freeze_gate(conn, &image.exam).await?; + let replaced = replaced_file(conn, &image.question, image.slot.as_ref()).await?; + let stored = sqlx::query_as!( + QuestionImage, + r#"INSERT INTO question_image (exam, question, slot, file, content_type, size) + VALUES ($1, $2, $3, $4, $5, $6) + ON CONFLICT (question, slot) DO UPDATE + SET file = EXCLUDED.file, content_type = EXCLUDED.content_type, + size = EXCLUDED.size + RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", + slot AS "slot: Option", file, + content_type AS "content_type: FileContentType", size"#, + image.exam as &ExamId, + image.question as &ExamQuestionId, + image.slot, + image.file, + image.content_type, + image.size, + ) + .fetch_one(&mut *conn) + .await?; + Ok((stored, replaced)) +} + +/// The blob name a slot's row currently names — the file a replace takes +/// off disk. `IS NOT DISTINCT FROM` is what makes the illustration slot's +/// `NULL` match itself. +pub(crate) async fn replaced_file( + conn: &mut PgConnection, + question: &ExamQuestionId, + slot: Option<&ChoiceId>, +) -> Result, AppError> { + let row = sqlx::query!( + r#"SELECT file FROM question_image + WHERE question = $1 AND slot IS NOT DISTINCT FROM $2"#, + question as &ExamQuestionId, + slot.map(ChoiceId::clone), ) + .fetch_optional(conn) .await?; - // The trailing `RETURN` is the last statement before `COMMIT`, so its - // slot follows the statement count rather than a hand-kept number; - // `num_statements` counts BEGIN and COMMIT. - let slot = result.num_statements().saturating_sub(2); - let failed = || AppError::Internal("failed to store question image".into()); - let outcome = result - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(failed)?; - let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; - Ok((stored, outcome.replaced.into_iter().next())) + Ok(row.map(|row| row.file)) } pub async fn read_slot( @@ -71,31 +89,48 @@ pub async fn read_slot( question: &ExamQuestionId, slot: Option<&ChoiceId>, ) -> Result, AppError> { - Ok(db - .select(QuestionImageId::for_slot(question, slot).record()) - .await?) + Ok(sqlx::query_as!( + QuestionImage, + r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", + slot AS "slot: Option", file, + content_type AS "content_type: FileContentType", size + FROM question_image + WHERE question = $1 AND slot IS NOT DISTINCT FROM $2"#, + question as &ExamQuestionId, + slot.map(ChoiceId::clone), + ) + .fetch_optional(db) + .await?) } /// Every image of the exam's questions — one query for the list views. pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM question_image WHERE exam = $ex") - .bind(("ex", exam.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + QuestionImage, + r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", + slot AS "slot: Option", file, + content_type AS "content_type: FileContentType", size + FROM question_image WHERE exam = $1"#, + exam as &ExamId, + ) + .fetch_all(db) + .await?) } pub async fn list_for_question( db: &Database, question: &ExamQuestionId, ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM question_image WHERE question = $q") - .bind(("q", question.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + QuestionImage, + r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", + slot AS "slot: Option", file, + content_type AS "content_type: FileContentType", size + FROM question_image WHERE question = $1"#, + question as &ExamQuestionId, + ) + .fetch_all(db) + .await?) } /// Drop the option pictures whose choice is gone — every choice image of @@ -112,17 +147,19 @@ pub async fn delete_choices_not_in( question: &ExamQuestionId, keep: &[ChoiceId], ) -> Result, AppError> { - let keep: Vec = keep.iter().map(|id| id.as_str().to_string()).collect(); - let mut result = db - .query( - "DELETE question_image \ - WHERE question = $q AND slot != NONE AND slot NOT IN $keep RETURN BEFORE", - ) - .bind(("q", question.record())) - .bind(("keep", keep)) - .await? - .check()?; - Ok(result.take::>(0)?) + let keep = keep.iter().map(ChoiceId::as_str).collect::>(); + Ok(sqlx::query_as!( + QuestionImage, + r#"DELETE FROM question_image + WHERE question = $1 AND slot IS NOT NULL AND NOT (slot = ANY($2)) + RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", + slot AS "slot: Option", file, + content_type AS "content_type: FileContentType", size"#, + question as &ExamQuestionId, + keep, + ) + .fetch_all(db) + .await?) } /// The blob names behind every image of every exam of `course` — collected @@ -131,32 +168,36 @@ pub async fn file_keys_for_course( db: &Database, course: &CourseId, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT VALUE file FROM question_image \ - WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)", - ) - .bind(("course", course.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + let rows = sqlx::query!( + r#"SELECT qi.file FROM question_image qi + JOIN exam e ON e.id = qi.exam WHERE e.course = $1"#, + course as &CourseId, + ) + .fetch_all(db) + .await?; + Ok(rows.into_iter().map(|row| row.file).collect()) } /// Refused once the exam has an attempt, in the same transaction — same /// gate, same reason as [`upsert`]. pub async fn delete(db: &Database, image: QuestionImage) -> Result { - let mut result = crate::db::exam_attempt::write_unfrozen( - db, - &image.exam, - "DELETE $id RETURN BEFORE;", - vec![("id".into(), image.id.record().into_value())], - ) - .await?; - result - .take::>(crate::db::exam_attempt::FROZEN_SLOT)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + tx_with_retry(db, false, async |conn| { + freeze_gate(conn, &image.exam).await?; + let deleted = sqlx::query_as!( + QuestionImage, + r#"DELETE FROM question_image + WHERE question = $1 AND slot IS NOT DISTINCT FROM $2 + RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", + slot AS "slot: Option", file, + content_type AS "content_type: FileContentType", size"#, + image.question as &ExamQuestionId, + image.slot, + ) + .fetch_optional(&mut *conn) + .await?; + deleted.ok_or(AppError::NotFound) + }) + .await } #[cfg(test)]