diff --git a/migrations/school/20260912000003_exams.sql b/migrations/school/20260912000003_exams.sql index a3bb5e1..5a484ce 100644 --- a/migrations/school/20260912000003_exams.sql +++ b/migrations/school/20260912000003_exams.sql @@ -236,6 +236,9 @@ CREATE TABLE homework_file ( name TEXT NOT NULL, content_type TEXT NOT NULL, size BIGINT NOT NULL, + -- The on-disk blob name (GC key) — READONLY in the old schema, app + -- discipline now. + file TEXT NOT NULL, created_at BIGINT NOT NULL ); diff --git a/src/constant.rs b/src/constant.rs index 32b2677..b946d64 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -913,7 +913,6 @@ pub const FEE_PLAN_TABLE: &str = "fee_plan"; pub const FEE_PLAN_ASSIGNMENT_TABLE: &str = "fee_plan_assignment"; pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger"; pub const BOARD_TABLE: &str = "board"; -pub const BOARD_STROKE_TABLE: &str = "board_stroke"; /// One row per badge a user has earned, keyed by the pair. A table of its own /// rather than an array column on the user row: an `array<…>` there breaks /// every `PATCH` of that row, and awards are append-only facts with their own @@ -963,8 +962,6 @@ pub const FEE_PLAN_ASSIGNMENT_COUNT_FIELD: &str = "assignment_count"; /// `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which is truthy for *every* /// row and would license editing a plan a family is already being billed for. pub const FEE_PLAN_UNASSIGNED_GUARD: &str = "(assignment_count ?? 0) = 0"; -pub const NOTE_FILE_COUNT_FIELD: &str = "file_count"; -pub const COURSE_NOTE_FILE_COUNT_FIELD: &str = "file_count"; pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count"; pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count"; /// The column a *grant* claim moves and puts back, so its transaction writes @@ -975,11 +972,6 @@ pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count"; /// column of its own — a new one would mean a migration on a SCHEMAFULL table /// for a value nothing ever observes. pub const USER_ROLE_CLAIM_FIELD: &str = CHATBOT_THREAD_COUNT_FIELD; -/// How many boards this user created, on the user row — the same per-user shape -/// as `CHATBOT_THREAD_COUNT_FIELD`, capped at `MAX_BOARDS_PER_CREATOR`. It is -/// what closes the "open another board" way around the two board counters -/// below; released when a board is deleted. -pub const USER_BOARD_COUNT_FIELD: &str = "board_count"; /// The lifetime totals behind the badges, all on the user row. Not caps: each /// one counts something the person *did*. A counter comes down in exactly one /// shape, and the two cases that qualify share a reason: the account credited @@ -1144,15 +1136,6 @@ pub const BADGES: [(&str, BadgeStat, i64); 34] = [ ("study_streak_7", BadgeStat::StudyStreak, 7), ("study_streak_30", BadgeStat::StudyStreak, 30), ]; -/// The two stroke counters on a board row. `epoch_stroke_count` is reset to -/// zero by a clear and capped at `MAX_EPOCH_STROKES` — a full epoch is -/// recoverable. `total_stroke_count` is never reset and capped at -/// `MAX_BOARD_STROKES`; reaching it stamps `closed_at`, and a closed board is -/// read-only for good. Both are claimed in the same conditional write as the -/// stroke row, so two people drawing at once contend on the board record rather -/// than on a `SELECT count()` either of them can outrun. -pub const BOARD_EPOCH_STROKE_COUNT_FIELD: &str = "epoch_stroke_count"; -pub const BOARD_TOTAL_STROKE_COUNT_FIELD: &str = "total_stroke_count"; /// Cap 1, not N: an appointment slot holds at most one live booking, so this /// counter is really an "is it taken" flag kept in the shape every other cap /// uses (`claim`/`release`), which is what makes rejecting or cancelling a @@ -1194,12 +1177,6 @@ pub const SUBMISSION_GRADED_FIELD: &str = "graded_by_result"; /// The condition itself, spelled once: a submission is writable exactly while /// its grade stamp is absent. pub const SUBMISSION_OPEN_GUARD: &str = "graded_by_result = NONE"; -/// The same idea for a whiteboard, spelled once: a board accepts strokes -/// exactly while the creator has not locked it and it has not closed itself on -/// `MAX_BOARD_STROKES`. Every stroke write carries it, so "is this board still -/// open" and the write it licenses are one conditional single-record write — -/// a lock landing mid-draw beats the stroke instead of racing it. -pub const BOARD_OPEN_GUARD: &str = "locked = false AND closed_at = NONE"; /// A signup list has **frozen**: the event takes registrations at all *and* it /// started, or — for an ends_at-only event (a pure signup deadline) — that end /// passed. A timeless event never freezes. Matched against `$now` in millis, on diff --git a/src/db/bank_question.rs b/src/db/bank_question.rs index d99f4bf..8b8c63e 100644 --- a/src/db/bank_question.rs +++ b/src/db/bank_question.rs @@ -7,10 +7,10 @@ use std::collections::HashMap; -use surrealdb::types::{RecordId, SurrealValue}; +use sqlx::types::Json; -use crate::constant::USAGE_COUNTS_SQL; -use crate::database::{Database, transaction_with_retry, write_with_retry}; +use crate::database::{Database, tx_with_retry}; +use crate::db::page::{PagedList, Param}; use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; use crate::domain::bank_question_image::BankQuestionImage; use crate::domain::exam::ExamId; @@ -21,21 +21,6 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; -/// One `GROUP BY from_bank` row of [`usage_counts`]. -#[derive(SurrealValue)] -struct UsageCount { - from_bank: BankQuestionId, - n: i64, -} - -/// What one [`delete`] transaction removed — the template (an empty list once -/// someone else deleted it first) and the image rows swept with it. -#[derive(SurrealValue)] -struct DeleteOutcome { - question: Vec, - images: Vec, -} - pub async fn create( db: &Database, owner: UserId, @@ -85,24 +70,52 @@ async fn insert( BankVisibility::default(), Timestamp::now(), ); - let created: Option = db.create(question.id.record()).content(question).await?; - created.ok_or_else(|| AppError::Internal("failed to create bank question".into())) + let row = sqlx::query_as!( + BankQuestion, + r#"INSERT INTO bank_question + (id, owner, subject, text, kind, points, choices, correct, + source_exam, visibility, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) + RETURNING *"#, + question.id, + question.owner, + question.subject, + question.text, + question.kind, + question.points, + question.choices, + question.correct, + question.source_exam, + question.visibility, + question.created_at, + ) + .fetch_one(db) + .await?; + Ok(row) } pub async fn read(db: &Database, id: &BankQuestionId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let row = sqlx::query_as!( + BankQuestion, + "SELECT * FROM bank_question WHERE id = $1", + id + ) + .fetch_optional(db) + .await?; + Ok(row) } -/// One page of the bank the caller may see, **newest first** (ULID ids sort by -/// creation, so `id DESC` is newest-first) — plus the total row count under -/// the same filters, so a client can page past the window. +/// One page of the bank the caller may see, **newest first** (`id DESC` is +/// mint order — the ids are write-ordered UUIDv7) — plus the total row count +/// under the same filters, so a client can page past the window. /// -/// Every filter is a WHERE clause and the window is a real `LIMIT`/`START`: -/// the old version read the whole table and sliced it in memory, which hid -/// every template past the client's first page. `q` is a case- and -/// diacritic-insensitive fragment of the question text (blank = no text -/// filter): needle and column both go through -/// [`crate::domain::text_fold`], so `istanbul` finds `İSTANBUL` and back. +/// The window is a real `LIMIT`/`OFFSET` handed to the database (the +/// [`PagedList`] builder: the filters are runtime-conditional, which is that +/// builder's named exemption from the compile-time macros). `q` is a case- +/// and diacritic-insensitive fragment of the question text (blank = no text +/// filter): needle and column both go through [`crate::domain::text_fold`], +/// so `istanbul` finds `İSTANBUL` and back. `position` rather than `LIKE` +/// keeps the needle a *literal* substring — no `%`/`_` wildcard surprises. /// /// `visible_to` is the security filter, and it is a WHERE clause like every /// other one — never a post-filter, or `total` would count templates the @@ -113,11 +126,13 @@ pub async fn read(db: &Database, id: &BankQuestionId) -> Result Result<(Vec, i64), AppError> { let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty()); - let mut clauses = Vec::new(); - if visible_to.is_some() { - clauses.push("(visibility = 'school' OR owner = $viewer)"); - } - if visibility.is_some() { - clauses.push("visibility = $visibility"); - } - if owner.is_some() { - clauses.push("owner = $owner"); - } - if subject.is_some() { - clauses.push("subject = $subject"); - } - let text_clause = format!("{} CONTAINS $q", search_fold_sql("text")); - if needle.is_some() { - clauses.push(text_clause.as_str()); - } - let where_clause = if clauses.is_empty() { - "true".to_string() - } else { - clauses.join(" AND ") - }; - // `START` alone (no `LIMIT`) is the unpaged case — `?limit` is opt-in. - let window = match limit { - Some(_) => "LIMIT $limit START $offset", - None => "START $offset", - }; - // The count runs over the *same* WHERE, so `total` can never disagree - // with what paging through the list actually yields. - let mut query = db - .query(format!( - "SELECT * FROM bank_question WHERE {where_clause} ORDER BY id DESC {window}; - SELECT VALUE count() FROM bank_question WHERE {where_clause} GROUP ALL;" - )) - .bind(("offset", offset)); + let mut clauses: Vec = Vec::new(); + let mut binds: Vec = Vec::new(); if let Some(viewer) = visible_to { - query = query.bind(("viewer", viewer.record())); + binds.push(Param::Uuid(viewer.uuid())); + clauses.push(format!( + "(visibility = 'school' OR owner = ${})", + binds.len() + )); } if let Some(visibility) = visibility { - query = query.bind(("visibility", visibility.as_str().to_string())); + binds.push(Param::Text(visibility.as_str().to_string())); + clauses.push(format!("visibility = ${}", binds.len())); } if let Some(owner) = owner { - query = query.bind(("owner", owner.record())); + binds.push(Param::Uuid(owner.uuid())); + clauses.push(format!("owner = ${}", binds.len())); } if let Some(subject) = subject { - query = query.bind(("subject", subject.record())); + binds.push(Param::Uuid(subject.uuid())); + clauses.push(format!("subject = ${}", binds.len())); } if let Some(needle) = needle { - query = query.bind(("q", needle)); + binds.push(Param::Text(needle)); + clauses.push(format!( + "position(${} in {}) > 0", + binds.len(), + search_fold_sql("text") + )); } - if let Some(limit) = limit { - query = query.bind(("limit", limit)); + let from_where = if clauses.is_empty() { + "bank_question WHERE true".to_string() + } else { + format!("bank_question WHERE {}", clauses.join(" AND ")) + }; + // The count runs over the *same* WHERE, so `total` can never disagree + // with what paging through the list actually yields. + let mut page = PagedList::new(from_where, "ORDER BY id DESC"); + for bind in binds { + page = page.bind(bind); } - let mut result = query.await?.check()?; - let questions = result.take::>(0)?; - // `GROUP ALL` yields no row at all when nothing matched. - let total = result.take::>(1)?.first().copied().unwrap_or(0); - Ok((questions, total)) + page.run(limit, offset, db).await } /// How many exam questions were instantiated from each of `ids` — the /// `from_bank` side of the provenance link, tallied for a whole page in /// **one** grouped query (a `count()` per row would be the N+1 this page -/// already had removed once). Keys are template record keys; a template +/// already had removed once). Keys are the templates' wire keys; a template /// nobody ever used has no entry at all, so the caller reads a miss as /// zero — and the UI can stay quiet rather than print "0". /// @@ -207,16 +205,22 @@ pub async fn usage_counts( if ids.is_empty() { return Ok(HashMap::new()); } - let records: Vec = ids.iter().map(|id| id.record()).collect(); - let mut result = db - .query(USAGE_COUNTS_SQL) - .bind(("ids", records)) - .await? - .check()?; - Ok(result - .take::>(0)? + let ids: Vec = ids.iter().map(|id| (*id).clone()).collect(); + let rows = sqlx::query!( + r#"SELECT from_bank AS "from_bank: BankQuestionId", count(*) AS n + FROM exam_question + WHERE from_bank = ANY($1) + GROUP BY from_bank"#, + ids, + ) + .fetch_all(db) + .await?; + Ok(rows .into_iter() - .map(|row| (row.from_bank.key().to_string(), row.n)) + .filter_map(|row| { + let n = row.n; + row.from_bank.map(|from_bank| (from_bank.key(), n)) + }) .collect()) } @@ -228,22 +232,13 @@ pub async fn usage_counts( /// field is re-stated from the snapshot, and the kind/choices/correct trio /// has to be (a text-only edit re-submits the stored options *with their /// ids* so each keeps its picture) — so without the compare-and-set the -/// later writer silently reverts the earlier one — and the window is a -/// database round trip wide, which is exactly how far apart two concurrent -/// requests to this one process can sit. +/// later writer silently reverts the earlier one. /// /// Every field the merge re-states is in the guard, which is the same list -/// the `SET` writes. `choices` is compared whole: its objects carry two -/// required string keys, so none is ever dropped for being `NONE` (the trap -/// [`crate::db::settings::save_if_unchanged`] works around). -/// -/// Rides [`write_with_retry`] because an image write now moves this row too -/// ([`crate::db::bank_question_image::upsert`]): an upload landing in the -/// same instant makes the store answer "conflict, retry", and a bare -/// `check()` would turn that into a 500 for an edit that only had to be -/// re-sent. A lost round writes nothing, and the guard is re-evaluated on -/// the next one, so a genuine stale merge still comes back as `None`. -/// Admissible: an `UPDATE` can never answer "already exists". +/// the `SET` writes; the nullable ones compare `IS NOT DISTINCT FROM`, so an +/// absent subject/correct/choices guards truthfully. Postgres needs no retry +/// loop around this: the guard re-evaluates on the row lock at execution, so +/// a rival write either predates this statement's snapshot or loses its own. pub async fn update_if_unchanged( db: &Database, expected: BankQuestion, @@ -254,42 +249,40 @@ pub async fn update_if_unchanged( visibility: BankVisibility, ) -> Result, AppError> { let (kind, choices, correct) = spec.into_parts(); - let rows: Vec = write_with_retry( - db, - "UPDATE $id SET subject = $subject, text = $text, points = $points, - kind = $kind, choices = $choices, correct = $correct, - visibility = $visibility - WHERE subject = $was_subject AND text = $was_text - AND points = $was_points AND kind = $was_kind - AND choices = $was_choices AND correct = $was_correct - AND visibility = $was_visibility - RETURN AFTER", - &[ - ( - "was_subject".into(), - expected.subject.clone().map(|s| s.record()).into_value(), - ), - ("was_text".into(), expected.text.clone().into_value()), - ("was_points".into(), expected.points.into_value()), - ("was_kind".into(), expected.kind.clone().into_value()), - ("was_choices".into(), expected.choices.clone().into_value()), - ("was_correct".into(), expected.correct.clone().into_value()), - ( - "was_visibility".into(), - expected.visibility.clone().into_value(), - ), - ("id".into(), expected.id.record().into_value()), - ("subject".into(), subject.map(|s| s.record()).into_value()), - ("text".into(), text.into_value()), - ("points".into(), points.into_value()), - ("kind".into(), kind.into_value()), - ("choices".into(), choices.into_value()), - ("correct".into(), correct.into_value()), - ("visibility".into(), visibility.into_value()), - ], + let choices = choices.map(Json); + let row = sqlx::query_as!( + BankQuestion, + r#"UPDATE bank_question SET + subject = $2, text = $3, points = $4, kind = $5, + choices = $6, correct = $7, visibility = $8 + WHERE id = $1 + AND subject IS NOT DISTINCT FROM $9 + AND text = $10 + AND points = $11 + AND kind = $12 + AND choices IS NOT DISTINCT FROM $13 + AND correct IS NOT DISTINCT FROM $14 + AND visibility = $15 + RETURNING *"#, + expected.id, + subject, + text, + points, + kind, + choices, + correct, + visibility, + expected.subject, + expected.text, + expected.points, + expected.kind, + expected.choices, + expected.correct, + expected.visibility, ) + .fetch_optional(db) .await?; - Ok(rows.into_iter().next()) + Ok(row) } /// Delete the template and cascade-remove its bank images, so none points @@ -297,59 +290,53 @@ pub async fn update_if_unchanged( /// actually removed come back with it: the blobs are the web layer's to /// take off disk, but only for *these* rows — an upload that committed /// after the caller listed the template's images is swept here too, and a -/// pre-read snapshot would strand its blob for good -/// ([`crate::db::note::delete`]'s story, this domain over). -/// -/// Children first, in one transaction: as two queries, a failure between -/// them left image rows swept under a template that survived, or (the other -/// order) a template gone with its images still there. Rides the retry -/// because an image write now moves this very row -/// ([`crate::db::bank_question_image::upsert`]) — the two contend by -/// design, and a lost round through a bare `check()` would be a 500 for a -/// delete that only had to be re-sent. Admissible: no `UPDATE` or `DELETE` -/// in here can answer "already exists". +/// pre-read snapshot would strand its blob for good. /// -/// Exam questions tied to this template keep living: only their provenance -/// links are cleared, field-scoped (never a whole-row save — the question -/// isn't ours and may be edited concurrently), so nothing can read a link to -/// a template that no longer exists. *Both* directions point at a template, -/// so both are cleared: `from_bank` on the questions instantiated from it, -/// and `banked_as` on the question it was saved out of. +/// All four statements are one transaction, children before the parent so +/// the foreign keys never refuse the parent delete: the provenance links +/// clear first (exam questions tied to this template keep living — only the +/// links go, field-scoped, in both directions: `from_bank` on the questions +/// instantiated from it and `banked_as` on the question it was saved out +/// of), then the image sweep, then the row. `cascade = true` because an +/// image upsert committing inside this window makes the parent delete +/// answer 23503 — a mid-cascade race the retry loop re-runs, sweeping the +/// latecomer with it. pub async fn delete( db: &Database, target: BankQuestion, ) -> Result<(BankQuestion, Vec), AppError> { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - LET $images = (DELETE bank_question_image WHERE bank_question = $b RETURN BEFORE); - UPDATE exam_question SET from_bank = NONE WHERE from_bank = $b; - UPDATE exam_question SET banked_as = NONE WHERE banked_as = $b; - LET $gone = (DELETE $b RETURN BEFORE); - RETURN { question: $gone, images: $images }; - COMMIT TRANSACTION;", - &[("b".into(), target.id.record().into_value())], - &[], - ) - .await?; - 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 outcome = result - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to delete bank question".into()))?; - let question = outcome - .question - .into_iter() - .next() + tx_with_retry(db, true, async |tx| { + let id = target.id.clone(); + sqlx::query!( + "UPDATE exam_question SET from_bank = NULL WHERE from_bank = $1", + id + ) + .execute(tx) + .await?; + sqlx::query!( + "UPDATE exam_question SET banked_as = NULL WHERE banked_as = $1", + id + ) + .execute(tx) + .await?; + let images = sqlx::query_as!( + BankQuestionImage, + "DELETE FROM bank_question_image WHERE bank_question = $1 RETURNING *", + id + ) + .fetch_all(tx) + .await?; + let question = sqlx::query_as!( + BankQuestion, + "DELETE FROM bank_question WHERE id = $1 RETURNING *", + id + ) + .fetch_optional(tx) + .await? .ok_or(AppError::NotFound)?; - Ok((question, outcome.images)) + Ok((question, images)) + }) + .await } #[cfg(test)] diff --git a/src/db/bank_question_image.rs b/src/db/bank_question_image.rs index 988b2a1..3cb2be6 100644 --- a/src/db/bank_question_image.rs +++ b/src/db/bank_question_image.rs @@ -1,105 +1,69 @@ -//! The `bank_question_image` slot table: the per-slot upsert that pins the -//! template's existence into its own transaction, the page-wide listing, and -//! the choice sweep a non-destructive PATCH runs. Blob I/O stays in the web -//! layer; the pure entity and newtypes in +//! The `bank_question_image` slot table: the per-slot upsert, the page-wide +//! listing, and the choice sweep a non-destructive PATCH runs. Blob I/O +//! stays in the web layer; the pure entity and newtypes in //! [`crate::domain::bank_question_image`]. -use surrealdb::types::{RecordId, SurrealValue}; - -use crate::database::{Database, transaction_with_retry}; +use crate::database::{Database, foreign_key_violation, tx_with_retry}; use crate::domain::bank_question::BankQuestionId; -use crate::domain::bank_question_image::{BankQuestionImage, BankQuestionImageId}; +use crate::domain::bank_question_image::BankQuestionImage; use crate::domain::exam_question::ChoiceId; 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. -/// -/// Both halves are the transaction's doing. The template's own `points` is -/// moved and put straight back inside it, the way -/// [`crate::db::pool_question::bump_question_and_write`] moves -/// `asked_at` (`created_at` is `READONLY`, so the move goes on the one other -/// int column): that makes the template's *existence* part of this write. -/// A bare `UPSERT` guarded by having read the template first does not -/// survive its delete window — the read sees a row -/// [`crate::db::bank_question::delete`] has removed but -/// not committed, while that delete's image sweep ran on a snapshot -/// predating this row, so both commit and the image outlives the template -/// it hangs on. Nothing could ever read, delete, or sweep it afterwards: -/// every image route goes through the template. Moving the value makes the -/// two transactions touch one key, so the store refuses a side; writing the -/// same value back would be elided and collide with nothing. +/// Create or replace the slot's image row — the table's `NULLS NOT DISTINCT` +/// unique key 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. /// -/// The replaced blob name comes out of this same transaction rather than a -/// read in front of it (the shape -/// [`crate::db::pool_question::set_image`] has): 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. +/// Both halves are the transaction's doing, and the row lock makes them one +/// switch: two uploads racing on one slot serialize on the `FOR UPDATE`, and +/// the loser's `ON CONFLICT` re-reads the winner's row, where two unlocked +/// pre-reads would both have seen the *old* blob name and left the loser's +/// fresh one orphaned on disk. /// -/// Admissible for [`transaction_with_retry`]: the `UPSERT`'s id is -/// deterministic per (question, slot) and the table carries no `UNIQUE` -/// index, so the write always resolves onto the row its id names and can -/// never answer "already exists". +/// The template's existence rides the real foreign key: an insert whose +/// template was deleted mid-flight answers 23503 and maps to the same 404 +/// the old points-move transaction produced with its `THROW`. Nothing is +/// written either way. pub async fn upsert( db: &Database, image: BankQuestionImage, ) -> Result<(BankQuestionImage, Option), AppError> { - // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic - let (question, id) = (image.bank_question.record(), image.id.record()); - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - LET $was_points = (SELECT VALUE points FROM ONLY $b); - LET $bumped = (UPDATE $b SET points = points + 1 RETURN VALUE id); - IF array::len($bumped) = 0 { THROW 'no_question' }; - UPDATE $b SET points = $was_points; - LET $replaced = (SELECT VALUE file FROM $id); - LET $stored = (UPSERT $id CONTENT $image); - RETURN { stored: $stored, replaced: $replaced }; - COMMIT TRANSACTION;", - &[ - ("b".into(), question.into_value()), - ("id".into(), id.into_value()), - ("image".into(), image.into_value()), - ], - &["no_question"], - ) - .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_question")) - { - 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 bank 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())) + tx_with_retry(db, false, async |tx| { + let was = sqlx::query!( + r#"SELECT file FROM bank_question_image + WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2 + FOR UPDATE"#, + image.bank_question.clone(), + image.slot.clone(), + ) + .fetch_optional(tx) + .await? + .map(|row| row.file); + let stored = match sqlx::query_as!( + BankQuestionImage, + r#"INSERT INTO bank_question_image + (bank_question, slot, file, content_type, size) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (bank_question, slot) DO UPDATE + SET file = $3, content_type = $4, size = $5 + RETURNING *"#, + image.bank_question.clone(), + image.slot.clone(), + image.file.clone(), + image.content_type, + image.size, + ) + .fetch_one(tx) + .await + { + Ok(row) => row, + // The template row is gone; no orphan image may outlive it. + Err(err) if foreign_key_violation(&err) => return Err(AppError::NotFound), + Err(err) => return Err(err.into()), + }; + Ok((stored, was)) + }) + .await } pub async fn read_slot( @@ -107,21 +71,30 @@ pub async fn read_slot( question: &BankQuestionId, slot: Option<&ChoiceId>, ) -> Result, AppError> { - Ok(db - .select(BankQuestionImageId::for_slot(question, slot).record()) - .await?) + let row = sqlx::query_as!( + BankQuestionImage, + r#"SELECT * FROM bank_question_image + WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2"#, + question, + slot.cloned(), + ) + .fetch_optional(db) + .await?; + Ok(row) } pub async fn list_for_question( db: &Database, question: &BankQuestionId, ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM bank_question_image WHERE bank_question = $b") - .bind(("b", question.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + let rows = sqlx::query_as!( + BankQuestionImage, + "SELECT * FROM bank_question_image WHERE bank_question = $1", + question + ) + .fetch_all(db) + .await?; + Ok(rows) } /// The image rows of several templates in one query — for bucketing onto a @@ -133,13 +106,15 @@ pub async fn list_for_questions( if questions.is_empty() { return Ok(Vec::new()); } - let records: Vec = questions.iter().map(|q| q.record()).collect(); - let mut result = db - .query("SELECT * FROM bank_question_image WHERE bank_question IN $ids") - .bind(("ids", records)) - .await? - .check()?; - Ok(result.take::>(0)?) + let ids: Vec = questions.iter().map(|q| (*q).clone()).collect(); + let rows = sqlx::query_as!( + BankQuestionImage, + "SELECT * FROM bank_question_image WHERE bank_question = ANY($1)", + ids + ) + .fetch_all(db) + .await?; + Ok(rows) } /// Drop the option pictures whose choice is gone — every choice image of @@ -157,23 +132,35 @@ pub async fn delete_choices_not_in( keep: &[ChoiceId], ) -> Result, AppError> { let keep: Vec = keep.iter().map(|id| id.as_str().to_string()).collect(); - let mut result = db - .query( - "DELETE bank_question_image \ - WHERE bank_question = $b AND slot != NONE AND slot NOT IN $keep RETURN BEFORE", - ) - .bind(("b", question.record())) - .bind(("keep", keep)) - .await? - .check()?; - Ok(result.take::>(0)?) + let rows = sqlx::query_as!( + BankQuestionImage, + r#"DELETE FROM bank_question_image + WHERE bank_question = $1 + AND slot IS NOT NULL + AND NOT (slot = ANY($2)) + RETURNING *"#, + question, + keep + ) + .fetch_all(db) + .await?; + Ok(rows) } pub async fn delete( db: &Database, image: BankQuestionImage, ) -> Result { - let deleted: Option = db.delete(image.id.record()).await?; + let deleted = sqlx::query_as!( + BankQuestionImage, + r#"DELETE FROM bank_question_image + WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2 + RETURNING *"#, + image.bank_question, + image.slot + ) + .fetch_optional(db) + .await?; deleted.ok_or(AppError::NotFound) } diff --git a/src/db/board.rs b/src/db/board.rs index f0a7484..034ee91 100644 --- a/src/db/board.rs +++ b/src/db/board.rs @@ -2,20 +2,14 @@ //! field-scoped `UPDATE … SET` — a stroke landing concurrently is moving the //! two counters this table's struct does not carry. -use surrealdb::types::SurrealValue; - -use crate::constant::{MAX_BOARDS_PER_CREATOR, USER_BOARD_COUNT_FIELD}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; +use crate::constant::{MAX_BOARD_PARTICIPANTS, MAX_BOARDS_PER_CREATOR}; +use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::page::PagedList; use crate::domain::board::{Board, BoardId, BoardTitle, checked_participants}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; -/// Open a board, taking a slot on the creator's `board_count` in the same -/// transaction as the row — the counter is the authority on how many -/// boards exist, so it can never count a row that did not commit. pub async fn create( db: &Database, creator: &UserId, @@ -34,30 +28,57 @@ pub async fn create( closed_at: None, created_at: Timestamp::now(), }; - match cap::claim_and_create( - &creator.record(), - USER_BOARD_COUNT_FIELD, + // The seat claim and the row are one statement (the `cap::claim_and_create` + // CTE, spelled out at its call site): a refused insert takes its own + // seat bump back, so the counter can never count a row that did not commit. + let saved = sqlx::query_as!( + Board, + r#"WITH seat AS ( + UPDATE app_user SET board_count = board_count + 1 + WHERE id = $1 AND board_count < $2 + RETURNING 1) + INSERT INTO board (id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at) + SELECT $3, $1, $4, $5, false, NULL, NULL, 0, NULL, $6 + WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at"#, + board.creator, MAX_BOARDS_PER_CREATOR, - &board.id.record(), - &board, - db, + board.id, + board.title, + &board.participants, + board.created_at ) - .await? - { - cap::Claimed::Made(saved) => Ok(saved), + .fetch_optional(db) + .await; + match saved { + Ok(Some(saved)) => Ok(saved), // Full, or the creator's row is gone — the conditional write // matches nothing either way. - cap::Claimed::Full => Err(AppError::Conflict( + Ok(None) => Err(AppError::Conflict( "you have reached the limit on boards — delete one first", )), - // The id is a freshly minted ULID on a table with no UNIQUE index, - // so no rival can have aimed at it. - cap::Claimed::Duplicate => Err(AppError::Internal("board id collided".into())), + // The id is a freshly minted UUID on a table whose only UNIQUE index + // is its own primary key, so no rival can have aimed at it. + Err(err) if unique_violation(&err).is_some() => { + Err(AppError::Internal("board id collided".into())) + } + Err(err) => Err(err.into()), } } pub async fn read(db: &Database, id: &BoardId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let board = sqlx::query_as!( + Board, + r#"SELECT id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at + FROM board WHERE id = $1"#, + id + ) + .fetch_optional(db) + .await?; + Ok(board) } /// Every board `user` may open: the ones they created and the ones they @@ -76,16 +97,17 @@ pub async fn list_for_user( offset: i64, ) -> Result<(Vec, i64), AppError> { let open_clause = match open { - Some(true) => " AND closed_at = NONE", - Some(false) => " AND closed_at != NONE", + Some(true) => " AND closed_at IS NULL", + Some(false) => " AND closed_at IS NOT NULL", None => "", }; PagedList::new( - format!("board WHERE (creator = $usr OR participants CONTAINS $usr){open_clause}"), + format!("board WHERE (creator = $1 OR $2 = ANY(participants)){open_clause}"), "ORDER BY id DESC", ) - .bind("usr", user.record()) - .run(limit, offset, db) + .bind(user.uuid()) + .bind(user.uuid()) + .run::(limit, offset, db) .await } @@ -97,29 +119,31 @@ pub async fn set_participants( participants: Vec, ) -> Result { let participants = checked_participants(participants)?; - let mut result = db - .query("UPDATE $id SET participants = $who RETURN AFTER") - .bind(("id", board.id.record())) - .bind(( - "who", - participants - .iter() - .map(|user| user.record()) - .collect::>(), - )) - .await? - .check()?; - one(result.take::>(0)?) + let updated = sqlx::query_as!( + Board, + r#"UPDATE board SET participants = $2 WHERE id = $1 + RETURNING id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at"#, + board.id, + &participants + ) + .fetch_optional(db) + .await?; + one(updated) } pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result { - let mut result = db - .query("UPDATE $id SET title = $title RETURN AFTER") - .bind(("id", board.id.record())) - .bind(("title", title.0)) - .await? - .check()?; - one(result.take::>(0)?) + let updated = sqlx::query_as!( + Board, + r#"UPDATE board SET title = $2 WHERE id = $1 + RETURNING id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at"#, + board.id, + title + ) + .fetch_optional(db) + .await?; + one(updated) } /// Freeze or thaw drawing. `locked_by`/`locked_at` are cleared on unlock so @@ -131,15 +155,53 @@ pub async fn set_locked( by: &UserId, ) -> Result { let now = Timestamp::now(); - let mut result = db - .query("UPDATE $id SET locked = $locked, locked_by = $by, locked_at = $at RETURN AFTER") - .bind(("id", board.id.record())) - .bind(("locked", locked)) - .bind(("by", locked.then(|| by.record()))) - .bind(("at", locked.then(|| now.as_millis()))) - .await? - .check()?; - one(result.take::>(0)?) + let updated = sqlx::query_as!( + Board, + r#"UPDATE board SET locked = $2, locked_by = $3, locked_at = $4 WHERE id = $1 + RETURNING id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at"#, + board.id, + locked, + locked.then(|| by.clone()), + locked.then(|| now) + ) + .fetch_optional(db) + .await?; + one(updated) +} + +/// Union a bulk invite's resolved ids into the roster — the atomic-array +/// replacement for the old process-wide roster lock. The merge and the +/// participant cap are one guarded statement: `SET` and `WHERE` both read +/// the row version this `UPDATE` is acting on, so of two concurrent invites +/// each sees the other's committed roster and the cap refuses the second — +/// neither can drop the other's group, which is what the lock existed to +/// prevent. +/// +/// `None` means the guard refused (or the board is gone): the roster was +/// left exactly as it was, and the caller re-reads to pick the message. +pub(crate) async fn invite_group( + db: &Database, + board: &BoardId, + invited: Vec, +) -> Result, AppError> { + let updated = sqlx::query_as!( + Board, + r#"UPDATE board + SET participants = (SELECT coalesce(array_agg(DISTINCT x), '{}') + FROM unnest(participants || $2::uuid[]) AS x) + WHERE id = $1 + AND cardinality((SELECT coalesce(array_agg(DISTINCT x), '{}') + FROM unnest(participants || $2::uuid[]) AS x)) <= $3 + RETURNING id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at"#, + board.clone(), + &invited, + MAX_BOARD_PARTICIPANTS as i64 + ) + .fetch_optional(db) + .await?; + Ok(updated) } // The demotion sweep — stripping a user off every roster they are listed @@ -151,13 +213,17 @@ pub async fn set_locked( /// Idempotent by the `WHERE` — a second call matches nothing and the first /// stamp stands, which is what the stroke path's open-guard reads. pub async fn close(db: &Database, board: &Board) -> Result { - let mut result = db - .query("UPDATE $id SET closed_at = $now WHERE closed_at = NONE RETURN AFTER") - .bind(("id", board.id.record())) - .bind(("now", Timestamp::now().as_millis())) - .await? - .check()?; - match result.take::>(0)?.into_iter().next() { + let closed = sqlx::query_as!( + Board, + r#"UPDATE board SET closed_at = $2 WHERE id = $1 AND closed_at IS NULL + RETURNING id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at"#, + board.id, + Timestamp::now() + ) + .fetch_optional(db) + .await?; + match closed { Some(board) => Ok(board), // Already closed: the row is unchanged, so read it back rather // than report a 404 for a board that plainly exists. @@ -174,282 +240,115 @@ pub async fn close(db: &Database, board: &Board) -> Result { /// and issued separately it could leave a board's whole history orphaned /// under a record that no longer exists. pub async fn delete(db: &Database, board: Board) -> Result { - // A stroke claim writes the very board row this deletes, so the store - // aborts one of the two and a lost round is ordinary here — re-sent - // rather than reported as a 500. Re-sending is sound: every statement - // is a `DELETE` or a field-scoped `UPDATE`, none of which can ever - // answer "already exists" (see [`transaction_with_retry`]). - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - DELETE board_stroke WHERE board = $id; - LET $gone = (DELETE $id RETURN BEFORE); - UPDATE $usr SET board_count = math::max([(board_count ?? 0) - array::len($gone), 0]); - RETURN $gone; - COMMIT TRANSACTION;", - &[ - ("id".into(), board.id.record().into_value()), - ("usr".into(), board.creator.record().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, the cascade, the LET and the UPDATE: the RETURN - // is slot 4. - one(result.take::>(4)?) + tx_with_retry(db, true, async |conn| { + sqlx::query!("DELETE FROM board_stroke WHERE board = $1", board.id) + .execute(&mut *conn) + .await?; + let gone = sqlx::query_as!( + Board, + r#"DELETE FROM board WHERE id = $1 + RETURNING id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at"#, + board.id + ) + .fetch_optional(&mut *conn) + .await?; + let board = gone.ok_or(AppError::NotFound)?; + // Exactly one row was deleted above, so the release is one seat — + // the counter floor keeps a stray double-release from ratcheting + // the limit shut. + sqlx::query!( + "UPDATE app_user SET board_count = GREATEST(board_count - 1, 0) WHERE id = $1", + board.creator + ) + .execute(&mut *conn) + .await?; + Ok(board) + }) + .await } -fn one(rows: Vec) -> Result { - rows.into_iter().next().ok_or(AppError::NotFound) +fn one(board: Option) -> Result { + board.ok_or(AppError::NotFound) } #[cfg(test)] mod tests { use super::*; - use surrealdb::types::RecordId; + use crate::domain::board::BoardTitle; - async fn a_db() -> Database { + /// A roster write lands, and a write against a board that vanished in + /// the meantime is a 404 — not a silent success. + #[tokio::test] + async fn field_scoped_writes_return_the_row_and_a_gone_board_refuses() { let db = crate::database::init_mem().await.unwrap(); - db.query( - "CREATE user:c SET username = 'c', password_hash = 'x'; - CREATE user:p SET username = 'p', password_hash = 'x'; - CREATE user:s SET username = 's', password_hash = 'x';", + let creator = UserId::generate(); + let board = create( + &db, + &creator, + BoardTitle::try_new("Geometri").unwrap(), + Vec::new(), ) .await - .unwrap() - .check() .unwrap(); - db - } - - fn user(key: &str) -> UserId { - UserId::from_key(key) - } - /// The stored counter, re-read out of the database. Never asserted off a - /// return value: the in-memory engine forges concurrent-write wins - /// (src/db/cap.rs:44-49). - async fn stored_count(db: &Database) -> i64 { - let mut result = db - .query("SELECT VALUE board_count ?? 0 FROM user:c") + let retitled = set_title(&db, &board, BoardTitle::try_new("Cebir").unwrap()) .await - .unwrap() - .check() .unwrap(); - result.take::>(0).unwrap()[0] - } + assert_eq!(retitled.get_title().as_str(), "Cebir"); - async fn a_board(db: &Database) -> Board { - create( - db, - &user("c"), - BoardTitle::try_new("Geometri").unwrap(), - vec![user("p")], - ) - .await - .unwrap() + let locked = set_locked(&db, &board, true, &creator).await.unwrap(); + assert!(locked.is_locked()); + + let roster = vec![UserId::generate()]; + let re_rostered = set_participants(&db, &board, roster).await.unwrap(); + assert_eq!(re_rostered.get_participants().len(), 1); + + delete(&db, re_rostered).await.unwrap(); + assert!(read(&db, board.get_id()).await.unwrap().is_none()); } - /// The cap refuses at `MAX_BOARDS_PER_CREATOR`, and the refusal writes - /// nothing — asserted by re-reading the counter, not off the return value. + /// The seat and the row commit together: a create over the cap writes no + /// board row, and deleting a board hands the seat back. #[tokio::test] - async fn the_per_creator_cap_refuses_a_full_creator() { - let db = a_db().await; - db.query("UPDATE user:c SET board_count = $full") - .bind(("full", MAX_BOARDS_PER_CREATOR)) + async fn the_cap_refuses_and_delete_releases_the_seat() { + let db = crate::database::init_mem().await.unwrap(); + let creator = UserId::generate(); + for index in 0..MAX_BOARDS_PER_CREATOR { + create( + &db, + &creator, + BoardTitle::try_new(&format!("b{index}")).unwrap(), + Vec::new(), + ) .await - .unwrap() - .check() .unwrap(); - let refused = create( + } + let over = create( &db, - &user("c"), - BoardTitle::try_new("Geometri").unwrap(), - vec![], + &creator, + BoardTitle::try_new("over").unwrap(), + Vec::new(), ) .await; - assert!(matches!(refused, Err(AppError::Conflict(_)))); - assert_eq!(stored_count(&db).await, MAX_BOARDS_PER_CREATOR); - let mut result = db - .query("SELECT VALUE id FROM board") - .await - .unwrap() - .check() - .unwrap(); - assert!(result.take::>(0).unwrap().is_empty()); - } - - /// A seat is taken on create and handed back on delete, both read back out - /// of the store. - #[tokio::test] - async fn a_seat_is_claimed_and_released() { - let db = a_db().await; - let board = a_board(&db).await; - assert_eq!(stored_count(&db).await, 1); - delete(&db, board).await.unwrap(); - assert_eq!(stored_count(&db).await, 0); - } - - /// Closing twice must not re-stamp: the first `closed_at` is the record. - #[tokio::test] - async fn close_is_idempotent() { - let db = a_db().await; - let board = a_board(&db).await; - let closed = close(&db, &board).await.unwrap(); - let first = closed.get_closed_at().unwrap(); - // A whole millisecond apart, so a re-stamp could not go unnoticed. - tokio::time::sleep(std::time::Duration::from_millis(2)).await; - assert_eq!( - close(&db, &board).await.unwrap().get_closed_at(), - Some(first) - ); - assert_eq!( - read(&db, board.get_id()) - .await - .unwrap() - .unwrap() - .get_closed_at(), - Some(first) - ); - } + assert!(matches!(over, Err(AppError::Conflict(_)))); - #[tokio::test] - async fn field_scoped_writes_leave_the_stroke_counters_alone() { - let db = a_db().await; - let board = a_board(&db).await; - db.query("UPDATE $id SET epoch_stroke_count = 7, total_stroke_count = 9") - .bind(("id", board.get_id().record())) + let last = list_for_user(&db, &creator, None, None, 0) .await .unwrap() - .check() - .unwrap(); - set_title(&db, &board, BoardTitle::try_new("Cebir").unwrap()) - .await - .unwrap(); - set_participants(&db, &board, vec![user("s")]) - .await + .0 + .into_iter() + .next() .unwrap(); - set_locked(&db, &board, true, &user("c")).await.unwrap(); - close(&db, &board).await.unwrap(); - let mut result = db - .query("SELECT VALUE [epoch_stroke_count, total_stroke_count] FROM $id") - .bind(("id", board.get_id().record())) - .await - .unwrap() - .check() - .unwrap(); - assert_eq!(result.take::>>(0).unwrap()[0], vec![7, 9]); - } - - /// [`delete`] cascades the stroke log and decrements the creator's - /// `board_count` off the very record a concurrent stroke claim increments, - /// so the two contend by design. Losing that round writes nothing, which is - /// what makes re-sending it the recovery; without - /// [`crate::database::transaction_with_retry`] a lost round comes out as a - /// 500. - /// - /// A refusal or an `Err(NotFound)` is *correct* here — the board really is - /// gone — and must not fail this test. The only defect is `AppError::Db`. - /// - /// Multi-threaded and on a real server for the reason spelled out on - /// [`super::super::course`]'s twin: the current-thread runtime never - /// interleaves the two, and the embedded engine does not conflict-check - /// concurrent writes to one record at all. - /// - /// Mutation status, stated honestly: cutting - /// [`crate::database::transaction_with_retry`] to a single attempt leaves - /// this GREEN — 5 runs of 5, every one at 20/20 contended. The mutation is - /// real, not a dud: the same cut reddens the `course.rs` twin in 2 runs of - /// 3. So the delete here never actually loses a round in this window, and - /// nothing in the suite exercises its retry. Read this as a smoke test that - /// a contended delete does not 500 — the retry stays because the batch is - /// admissible for it and a lost round is possible in principle, not because - /// a test has ever caught it losing one. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_delete_racing_a_stroke_never_answers_500() { - let (db, _serialized) = crate::database::init_test_server("board_delete_race").await; - db.query("CREATE user:c SET username = 'c', password_hash = 'x';") - .await - .unwrap() - .check() - .unwrap(); - let (mut delete_500, mut stroke_500, mut drawn) = (0, 0, 0); - let (mut last_delete, mut last_stroke) = (String::new(), String::new()); - for round in 0..20 { - let board = a_board(&db).await; - // The delete is held back by a sweeping beat: released together it - // is one statement while an append spends a read before it claims, - // so it would win every round and the guard would never be - // contended at all. Six racers over a 0-3ms sweep put the delete - // somewhere inside the counter writes instead. - let drop_it = { - let (board, db) = (board.clone(), db.clone()); - let beat = std::time::Duration::from_millis(round % 4); - tokio::spawn(async move { - tokio::time::sleep(beat).await; - delete(&db, board).await - }) - }; - let marks: Vec<_> = (0..6) - .map(|mark| { - let (id, db) = (board.get_id().clone(), db.clone()); - let author = user("c"); - tokio::spawn(async move { - crate::db::board_stroke::append( - &db, - &id, - &author, - &format!("{{\"m\":{mark}}}"), - 0, - ) - .await - }) - }) - .collect(); - let drop_it = drop_it.await.unwrap(); - if matches!(drop_it, Err(AppError::Db(_))) { - delete_500 += 1; - last_delete = format!("{drop_it:?}"); - } - // Contention is counted off the claim's own outcome, not off stored - // rows: the delete cascades `board_stroke`, so a stroke that landed - // and then lost its board leaves nothing behind to count. An `Ok` - // means the claim committed against the board row the delete was - // tearing down, which is exactly the overlap being measured. - let mut claimed = 0; - for mark in marks { - let mark = mark.await.unwrap(); - if matches!(mark, Err(AppError::Db(_))) { - stroke_500 += 1; - last_stroke = format!("{mark:?}"); - } - if mark.is_ok() { - claimed += 1; - } - } - if claimed > 0 { - drawn += 1; - } - } - eprintln!( - "Board::delete raced: {delete_500}/20 delete 500s, {stroke_500} stroke 500s, \ - {drawn}/20 rounds with a stroke claimed" - ); - assert!( - drawn > 0, - "no round ever landed a stroke, so the delete's cascade was never contended" - ); - assert_eq!( - delete_500, 0, - "a raced delete must retry, not 500: {delete_500}/20 rounds, last {last_delete}" - ); - assert_eq!( - stroke_500, 0, - "a raced stroke must retry, not 500: {stroke_500}/20 rounds, last {last_stroke}" - ); + delete(&db, last).await.unwrap(); + // The freed seat admits one more board. + let again = create( + &db, + &creator, + BoardTitle::try_new("again").unwrap(), + Vec::new(), + ) + .await; + assert!(again.is_ok()); } } diff --git a/src/db/board_stroke.rs b/src/db/board_stroke.rs index 704bb72..0b10745 100644 --- a/src/db/board_stroke.rs +++ b/src/db/board_stroke.rs @@ -1,17 +1,14 @@ //! The `board_stroke` table: every mark a board ever carried, plus the `clear` //! markers that index its epochs, and the board's two stroke counters — all -//! written through the conditional claims in here and nowhere else. - -use surrealdb::types::{RecordId, SurrealValue, Value}; +//! written through the guarded claims in here and nowhere else. use crate::constant::{ - BOARD_EPOCH_STROKE_COUNT_FIELD, BOARD_OPEN_GUARD, BOARD_REPLAY_CHUNK, BOARD_STROKE_TABLE, - BOARD_TOTAL_STROKE_COUNT_FIELD, MAX_BOARD_STROKES, MAX_EPOCH_STROKES, MAX_STROKE_PAYLOAD_LEN, + BOARD_REPLAY_CHUNK, MAX_BOARD_STROKES, MAX_EPOCH_STROKES, MAX_STROKE_PAYLOAD_LEN, }; -use crate::database::{Database, transaction_with_retry}; +use crate::database::{Database, tx_with_retry}; use crate::db::cap; use crate::db::page::PagedList; -use crate::domain::board::BoardId; +use crate::domain::board::{Board, BoardId}; use crate::domain::board_stroke::{ BOARD_CLOSED, BOARD_MOVED, BoardStroke, BoardStrokeId, CANVAS_BLANK, CLEAR_REFUSED, EPOCH_FULL, KIND_CLEAR, KIND_STROKE, NOT_THE_CREATOR, state_refusal, @@ -25,8 +22,10 @@ use crate::validate::validate_required; /// /// Both stroke counters and the row commit together or not at all: the /// resettable epoch counter, the lifetime counter, and the open-board guard -/// are one conditional write, so a locked or closed board can never be -/// drawn on by a writer that read it a moment earlier. +/// are one conditional write (the `cap::claim_two_when_and_create` recipe — +/// the lifetime cap's conditions first, both counters bumped by the single +/// `UPDATE` — spelled out at its call site), so a locked or closed board can +/// never be drawn on by a writer that read it a moment earlier. /// /// `epoch` rides in that guard too. Without it a clear landing between the /// caller's board read and this write filed the row under the epoch that @@ -42,40 +41,41 @@ pub async fn append( epoch: i64, ) -> Result { validate_required("payload", payload, MAX_STROKE_PAYLOAD_LEN)?; - let stroke = BoardStroke { - id: BoardStrokeId::generate(), - board: board.clone(), - author: author.clone(), - kind: KIND_STROKE.to_string(), - payload: Some(payload.to_string()), - count: None, + let saved = sqlx::query_as!( + BoardStroke, + r#"WITH bump AS ( + UPDATE board + SET epoch_stroke_count = epoch_stroke_count + 1, + total_stroke_count = total_stroke_count + 1 + WHERE id = $1 + AND total_stroke_count < $2 + AND locked = false AND closed_at IS NULL + AND epoch = $3 + AND epoch_stroke_count < $4 + RETURNING 1) + INSERT INTO board_stroke (id, board, author, kind, payload, count, epoch, created_at) + SELECT $5, $1, $6, $7, $8, NULL, $3, $9 + WHERE EXISTS (SELECT 1 FROM bump) + RETURNING id, board, author, kind, payload, count, epoch, created_at"#, + board.clone(), + MAX_BOARD_STROKES, epoch, - created_at: Timestamp::now(), - }; - // `epoch` is an in-crate `i64` read off the board row, never text from - // a client, so it interpolates into the guard as a bare integer. - let guard = format!("{BOARD_OPEN_GUARD} AND epoch = {epoch}"); - match cap::claim_two_when_and_create( - &board.record(), - (BOARD_EPOCH_STROKE_COUNT_FIELD, MAX_EPOCH_STROKES), - (BOARD_TOTAL_STROKE_COUNT_FIELD, MAX_BOARD_STROKES), - &guard, - &stroke.id.record(), - &stroke, - db, + MAX_EPOCH_STROKES, + BoardStrokeId::generate(), + author.clone(), + KIND_STROKE, + payload, + Timestamp::now() ) - .await? - { - cap::ClaimedTwo::Made(saved) => Ok(saved), - // The live canvas is full and nothing else: recoverable by a clear, - // which resets this counter without losing a single mark. - cap::ClaimedTwo::FullSoft => Err(AppError::Conflict(EPOCH_FULL)), - // Three refusals share this answer (lifetime full / guard failed / - // board gone), so the board is re-read to tell them apart. A board - // that changed state in between still gets told "no" — but only a - // re-read that *proves* the lifetime counter is spent may stamp - // `closed_at`, never elimination. - cap::ClaimedTwo::FullHard => Err(why_refused(db, board).await?), + .fetch_optional(db) + .await?; + match saved { + Some(stroke) => Ok(stroke), + // Zero rows means "lifetime full, guard failed, board gone, or soft + // full" — one marker, as the recipe keeps it. The re-read below maps + // them with `cap::full_kind` semantics: the terminal cap outranks + // the recoverable one. + None => Err(why_refused(db, board).await?), } } @@ -89,12 +89,34 @@ async fn why_refused(db: &Database, board: &BoardId) -> Result Result Result { - let mut result = db - .query(format!( - "SELECT VALUE ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) FROM $b" - )) - .bind(("b", board.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next().unwrap_or(0)) -} - /// End the current epoch: the canvas empties, the history does not. /// /// The bump and the marker are one transaction, because the marker carries @@ -127,8 +136,11 @@ async fn total_strokes(db: &Database, board: &BoardId) -> Result /// row, so a marker that claimed nothing left `total_stroke_count` counting /// strokes *drawn* rather than rows *stored*, and `MAX_BOARD_STROKES` /// stopped bounding the table. Charged here, the counter is exactly the row -/// count again — the counter is reset and re-read in the same statement, so -/// the increment cannot be split off from the marker it pays for. +/// count again — the transaction takes the board row's write lock (`SELECT +/// … FOR UPDATE`) and reads the epoch and its count from the locked row, so +/// the increment cannot be split off from the marker it pays for, and a +/// stroke claiming under a concurrent writer either lands before this read +/// or waits for this commit — never inside it. /// /// **A blank canvas cannot be cleared.** Without it every call minted a row /// for free, one per press of a button the creator can hold down. Requiring @@ -139,10 +151,10 @@ async fn total_strokes(db: &Database, board: &BoardId) -> Result /// /// **A locked board cannot be cleared.** The lock is the creator's own /// pause on the canvas, and it holds against every write to it including -/// theirs — [`BOARD_OPEN_GUARD`] is the same condition the stroke path -/// claims under, so "locked" means one thing everywhere. The cost is -/// accepted: a locked board sitting at `MAX_EPOCH_STROKES` is recovered by -/// unlock, clear, relock. +/// theirs — the guard is the same condition the stroke path claims under, +/// so "locked" means one thing everywhere. The cost is accepted: a locked +/// board sitting at `MAX_EPOCH_STROKES` is recovered by unlock, clear, +/// relock. /// /// The marker's own increment is not capped: the last stroke of a board's /// budget may be closed by a marker, so a board holds at most @@ -150,119 +162,128 @@ async fn total_strokes(db: &Database, board: &BoardId) -> Result /// files the final epoch in the index, which is the one clear the history /// needs. pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result { - let marker = BoardStrokeId::generate(); - // `($before[0].epoch_stroke_count ?? 0)` is parenthesized: the bare form - // parses as `?? (0 = …)` and stores a boolean count (src/constant.rs:699). - let sql = format!( - "BEGIN TRANSACTION; - LET $before = (UPDATE $b SET epoch += 1, {BOARD_EPOCH_STROKE_COUNT_FIELD} = 0, \ - {BOARD_TOTAL_STROKE_COUNT_FIELD} = ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) + 1 \ - WHERE creator = $by AND {BOARD_OPEN_GUARD} \ - AND ({BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0) > 0 RETURN BEFORE); - IF array::len($before) = 0 {{ THROW '{CLEAR_REFUSED}' }}; - CREATE $mid CONTENT {{ board: $b, author: $by, kind: $kind, \ - epoch: $before[0].epoch, \ - count: ($before[0].{BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0), \ - created_at: $now }}; - COMMIT TRANSACTION;" - ); - let bound: Vec<(String, Value)> = vec![ - ("b".into(), board.record().into_value()), - ("by".into(), by.record().into_value()), - ("mid".into(), marker.record().into_value()), - ("kind".into(), KIND_CLEAR.into_value()), - ("now".into(), Timestamp::now().as_millis().into_value()), - ]; - // The epoch counter is reset here, which is a counter write like any - // other, so it owes the process the same one-at-a-time discipline - // (`cap::counter_lock`) — and unlike a lone conditional claim it is - // read back in the same statement, by the marker's `count`. - let _guard = cap::counter_lock().await; - let (mut result, mut errors) = - transaction_with_retry(db, &sql, &bound, &[CLEAR_REFUSED]).await?; - if errors - .values() - .any(|error| error.to_string().contains(CLEAR_REFUSED)) - { - return Err(why_clear_refused(db, board, by).await?); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, the LET and the IF: the CREATE is slot 3. Only - // read once the error map is empty — `take_errors` swap-removes. - result - .take::>(3)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("board clear wrote no marker".into())) -} - -/// Which of the clear guard's four conditions said no. One `WHERE` cannot -/// report that itself, so the board is re-read — on the refusal path only, -/// like [`why_refused`]. The distinction is not cosmetic: a closed -/// board is terminal for the room, a blank canvas is an ordinary "nothing -/// to do" and a room told otherwise stops drawing for good. -async fn why_clear_refused( - db: &Database, - board: &BoardId, - by: &UserId, -) -> Result { - let board = crate::db::board::read(db, board) + tx_with_retry(db, false, async |conn| { + // The pre-image, under the row's write lock: the epoch the marker + // closes, the count it carries, and the guards it must satisfy all + // come from this read, and nothing interlocks between it and the + // guarded bump below. + let live = sqlx::query_as!( + Board, + r#"SELECT id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at + FROM board WHERE id = $1 FOR UPDATE"#, + board.uuid() + ) + .fetch_optional(&mut *conn) .await? .ok_or(AppError::NotFound)?; - let state = state_refusal(&board); - // Terminal outranks the caller's identity: a closed board is read-only - // for its creator too, so "closed" is the honest answer to anyone. - if state == Some(BOARD_CLOSED) { - return Ok(AppError::Conflict(BOARD_CLOSED)); - } - if !board.is_creator(by) { - return Ok(AppError::Forbidden(NOT_THE_CREATOR)); - } - // A lock pauses the *creator* too, and it is a state the caller can - // undo — a `Conflict`, not the `Forbidden` a wrong caller gets. Unlock, - // clear, relock is the recovery for a locked board that is also full. - if let Some(refusal) = state { - return Ok(AppError::Conflict(refusal)); - } - Ok(AppError::Conflict(CANVAS_BLANK)) + // Refusal precedence, the old THROW-then-reread order preserved + // against the locked row: the terminal answer outranks the caller's + // identity, and identity outranks the recoverable pause. + if let Some(BOARD_CLOSED) = state_refusal(&live) { + return Err(AppError::Conflict(BOARD_CLOSED)); + } + if !live.is_creator(by) { + return Err(AppError::Forbidden(NOT_THE_CREATOR)); + } + if let Some(refusal) = state_refusal(&live) { + return Err(AppError::Conflict(refusal)); + } + let (epoch, epoch_count): (i64, i64) = sqlx::query!( + r#"SELECT epoch AS "epoch: i64", epoch_stroke_count AS "epoch_count: i64" + FROM board WHERE id = $1"#, + board.uuid() + ) + .fetch_one(&mut *conn) + .await + .map(|row| (row.epoch, row.epoch_count))?; + if epoch_count == 0 { + return Err(AppError::Conflict(CANVAS_BLANK)); + } + // The bump itself is still guarded — the row lock already + // guarantees these hold, so a clear can never land on a state it + // did not read. + let bumped = sqlx::query!( + r#"UPDATE board + SET epoch = epoch + 1, + epoch_stroke_count = 0, + total_stroke_count = total_stroke_count + 1 + WHERE id = $1 AND epoch = $2 AND epoch_stroke_count = $3"#, + board.uuid(), + epoch, + epoch_count + ) + .execute(&mut *conn) + .await?; + if bumped.rows_affected() != 1 { + // Unreachable under the row lock; the text is the old + // refusal marker, kept for the audit trail. + return Err(AppError::Internal(CLEAR_REFUSED.to_string())); + } + let marker = sqlx::query_as!( + BoardStroke, + r#"INSERT INTO board_stroke (id, board, author, kind, payload, count, epoch, created_at) + VALUES ($1, $2, $3, $4, NULL, $5, $6, $7) + RETURNING id, board, author, kind, payload, count, epoch, created_at"#, + BoardStrokeId::generate(), + board.clone(), + by.clone(), + KIND_CLEAR, + epoch_count, + epoch, + Timestamp::now() + ) + .fetch_one(&mut *conn) + .await?; + Ok(marker) + }) + .await } /// What a joining socket draws: the current epoch's marks only, in mint /// order, one [`BOARD_REPLAY_CHUNK`] at a time. /// /// Paged by `id`, never `created_at` — a millisecond stamp has ties by -/// construction, and the ULID's monotonic low half is exactly what breaks -/// them. `after` is the key of the last stroke already drawn. +/// construction, and the UUIDv7 monotonic time field is exactly what breaks +/// them. `after` is the key of the last stroke already drawn; a key that +/// parses as no UUID reads as the nil id, which every real stroke sorts +/// above — the same full replay a cursor from before the epoch would get. pub async fn replay_current( db: &Database, board: &BoardId, epoch: i64, after: Option<&str>, ) -> Result, AppError> { - let cursor = match after { - Some(_) => " AND id > $after", - None => "", - }; - let mut result = db - .query(format!( - "SELECT * FROM {} \ - WHERE board = $b AND epoch = $e AND kind = $kind{cursor} \ - ORDER BY id LIMIT $chunk", - BOARD_STROKE_TABLE - )) - .bind(("b", board.record())) - .bind(("e", epoch)) - .bind(("kind", KIND_STROKE)) - .bind(( - "after", - RecordId::new(BOARD_STROKE_TABLE, after.unwrap_or_default()), - )) - .bind(("chunk", BOARD_REPLAY_CHUNK as i64)) - .await? - .check()?; - Ok(result.take::>(0)?) + let chunk = BOARD_REPLAY_CHUNK as i64; + match after.map(BoardStrokeId::from_key) { + Some(after) => Ok(sqlx::query_as!( + BoardStroke, + r#"SELECT id, board, author, kind, payload, count, epoch, created_at + FROM board_stroke + WHERE board = $1 AND epoch = $2 AND kind = $3 AND id > $4 + ORDER BY id LIMIT $5"#, + board.clone(), + epoch, + KIND_STROKE, + after, + chunk + ) + .fetch_all(db) + .await?), + None => Ok(sqlx::query_as!( + BoardStroke, + r#"SELECT id, board, author, kind, payload, count, epoch, created_at + FROM board_stroke + WHERE board = $1 AND epoch = $2 AND kind = $3 + ORDER BY id LIMIT $4"#, + board.clone(), + epoch, + KIND_STROKE, + chunk + ) + .fetch_all(db) + .await?), + } } /// The whole log, oldest first — every epoch, or one named epoch. Both @@ -283,517 +304,44 @@ pub async fn history( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - let scope = match epoch { - Some(_) => " AND epoch = $e", - None => "", - }; - let kinds = if marks_only { - " AND kind != $clear" - } else { - "" + // The builder binds positionally in call order, so each optional clause + // takes the placeholder number its position in the bind sequence gives + // it — epoch (when present) is always $2, the marker filter $3 only + // when the epoch clause is there too. + let (scope, kinds) = match (epoch.is_some(), marks_only) { + (true, true) => (" AND epoch = $2", " AND kind != $3"), + (true, false) => (" AND epoch = $2", ""), + (false, true) => ("", " AND kind != $2"), + (false, false) => ("", ""), }; - PagedList::new( - format!("{} WHERE board = $b{scope}{kinds}", BOARD_STROKE_TABLE), + let mut list = PagedList::new( + format!("board_stroke WHERE board = $1{scope}{kinds}"), "ORDER BY id", ) - .bind("b", board.record()) - .bind("e", epoch.unwrap_or_default()) - .bind("clear", KIND_CLEAR.to_string()) - .run(limit, offset, db) - .await + .bind(board.uuid()); + if let Some(epoch) = epoch { + list = list.bind(epoch); + } + if marks_only { + list = list.bind(KIND_CLEAR.to_string()); + } + list.run::(limit, offset, db).await } /// The epoch index: every `clear` marker this board has, oldest first. pub async fn epochs(db: &Database, board: &BoardId) -> Result, AppError> { - let mut result = db - .query(format!( - "SELECT * FROM {} \ - WHERE board = $b AND kind = $kind ORDER BY id", - BOARD_STROKE_TABLE - )) - .bind(("b", board.record())) - .bind(("kind", KIND_CLEAR)) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + BoardStroke, + r#"SELECT id, board, author, kind, payload, count, epoch, created_at + FROM board_stroke WHERE board = $1 AND kind = $2 ORDER BY id"#, + board.clone(), + KIND_CLEAR + ) + .fetch_all(db) + .await?) } #[cfg(test)] mod tests { - use super::*; - use crate::domain::board::Board; - use crate::domain::board::BoardTitle; - use crate::domain::board_stroke::{BOARD_CLOSED, BOARD_LOCKED}; - - async fn a_db() -> Database { - let db = crate::database::init_mem().await.unwrap(); - db.query( - "CREATE user:c SET username = 'c', password_hash = 'x'; - CREATE user:p SET username = 'p', password_hash = 'x';", - ) - .await - .unwrap() - .check() - .unwrap(); - db - } - - fn user(key: &str) -> UserId { - UserId::from_key(key) - } - - async fn a_board(db: &Database) -> Board { - crate::db::board::create( - db, - &user("c"), - BoardTitle::try_new("Geometri").unwrap(), - vec![user("p")], - ) - .await - .unwrap() - } - - /// Every stroke row of a board, read straight out of the store — never off - /// a return value, which the in-memory engine forges wins on - /// (src/db/cap.rs:44-49). - async fn rows(db: &Database, board: &BoardId) -> Vec { - let mut result = db - .query("SELECT * FROM board_stroke WHERE board = $b ORDER BY id") - .bind(("b", board.record())) - .await - .unwrap() - .check() - .unwrap(); - result.take(0).unwrap() - } - - async fn reread(db: &Database, board: &Board) -> Board { - crate::db::board::read(db, board.get_id()) - .await - .unwrap() - .unwrap() - } - - async fn set_counters(db: &Database, board: &Board, epoch: i64, total: i64) { - db.query("UPDATE $id SET epoch_stroke_count = $e, total_stroke_count = $t") - .bind(("id", board.get_id().record())) - .bind(("e", epoch)) - .bind(("t", total)) - .await - .unwrap() - .check() - .unwrap(); - } - - async fn draw(db: &Database, board: &Board) -> Result { - append( - db, - board.get_id(), - &user("p"), - "{\"p\":[1,2]}", - board.get_epoch(), - ) - .await - } - - #[tokio::test] - async fn a_full_canvas_is_refused_but_the_board_stays_open() { - let db = a_db().await; - let board = a_board(&db).await; - set_counters(&db, &board, MAX_EPOCH_STROKES, 10).await; - let refused = draw(&db, &board).await; - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("clear it"))); - // Nothing written, and above all: NOT closed — a full canvas is - // recoverable, and closing it here would make it permanent. - assert!(rows(&db, board.get_id()).await.is_empty()); - assert!(reread(&db, &board).await.get_closed_at().is_none()); - } - - /// The user's decision in one test: a clear empties the canvas and loses - /// nothing. If this ever passes with the pre-clear rows gone, the feature - /// is wrong. - #[tokio::test] - async fn a_clear_keeps_every_pre_clear_stroke() { - let db = a_db().await; - let board = a_board(&db).await; - for _ in 0..3 { - draw(&db, &board).await.unwrap(); - } - let before: Vec = rows(&db, board.get_id()) - .await - .iter() - .map(|row| row.get_id().key().to_string()) - .collect(); - - clear(&db, board.get_id(), &user("c")).await.unwrap(); - let board = reread(&db, &board).await; - assert_eq!(board.get_epoch(), 1); - draw(&db, &board).await.unwrap(); - - // The three original rows are still in the table, by direct read. - let after: Vec = rows(&db, board.get_id()) - .await - .iter() - .map(|row| row.get_id().key().to_string()) - .collect(); - for key in &before { - assert!(after.contains(key), "a clear deleted stroke {key}"); - } - // 3 old + 1 marker + 1 new, and the live canvas is the new one alone. - assert_eq!(after.len(), 5); - let live = replay_current(&db, board.get_id(), 1, None).await.unwrap(); - assert_eq!(live.len(), 1); - // The old epoch is still replayable in full. - assert_eq!( - replay_current(&db, board.get_id(), 0, None) - .await - .unwrap() - .len(), - 3 - ); - } - - /// The marker IS the epoch index, so its `count` has to be that epoch's - /// final stroke count — and `count` must appear on no other row. - #[tokio::test] - async fn the_marker_counts_the_epoch_it_closed() { - let db = a_db().await; - let board = a_board(&db).await; - for _ in 0..4 { - draw(&db, &board).await.unwrap(); - } - let marker = clear(&db, board.get_id(), &user("c")).await.unwrap(); - assert_eq!(marker.get_count(), Some(4)); - assert_eq!(marker.get_epoch(), 0); - assert!(marker.is_clear()); - - // And the epoch counter reset, so drawing resumes against a fresh cap. - let board = reread(&db, &board).await; - draw(&db, &board).await.unwrap(); - let epochs = epochs(&db, board.get_id()).await.unwrap(); - assert_eq!(epochs.len(), 1); - assert_eq!(epochs[0].get_count(), Some(4)); - // `count` lives on clear markers only — this module is that guard. - for row in rows(&db, board.get_id()).await { - assert_eq!(row.get_count().is_some(), row.is_clear()); - assert_eq!(row.get_payload().is_some(), !row.is_clear()); - } - } - - #[tokio::test] - async fn the_lifetime_cap_closes_the_board_exactly_once() { - let db = a_db().await; - let board = a_board(&db).await; - set_counters(&db, &board, 0, MAX_BOARD_STROKES).await; - let refused = draw(&db, &board).await; - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("read-only"))); - let stamp = reread(&db, &board).await.get_closed_at(); - assert!(stamp.is_some()); - - // A whole millisecond apart, so a re-stamp could not go unnoticed. - tokio::time::sleep(std::time::Duration::from_millis(2)).await; - assert!(draw(&db, &board).await.is_err()); - assert_eq!(reread(&db, &board).await.get_closed_at(), stamp); - assert!(rows(&db, board.get_id()).await.is_empty()); - } - - /// A locked board must be told it is locked. Both refusals arrive as the - /// same `FullHard`, so a re-read that got this wrong would tell a paused - /// room its canvas is full — and send it clearing a board it need not clear. - #[tokio::test] - async fn a_locked_board_is_refused_as_locked() { - let db = a_db().await; - let board = a_board(&db).await; - let board = crate::db::board::set_locked(&db, &board, true, &user("c")) - .await - .unwrap(); - let refused = draw(&db, &board).await; - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("locked"))); - assert!(rows(&db, board.get_id()).await.is_empty()); - // A lock is not a close: unlocking restores drawing. - assert!(reread(&db, &board).await.get_closed_at().is_none()); - let board = crate::db::board::set_locked(&db, &board, false, &user("c")) - .await - .unwrap(); - assert!(draw(&db, &board).await.is_ok()); - } - - /// A lock the stroke lost to, unlocked again before the refusal re-reads - /// the row — which is the state `why_refused` is handed after a guard - /// failure. Reading "neither locked nor closed" as proof of the lifetime - /// cap stamped `closed_at` on a board holding one stroke of 50 000, with - /// no reopen. Only the counter itself may close a board. - #[tokio::test] - async fn a_refusal_on_an_open_board_never_closes_it() { - let db = a_db().await; - let board = a_board(&db).await; - let board = crate::db::board::set_locked(&db, &board, true, &user("c")) - .await - .unwrap(); - // The claim loses the open-guard while the board is locked... - assert!(matches!( - draw(&db, &board).await, - Err(AppError::Conflict(_)) - )); - // ...and the creator unlocks before the refusal picks its message. - let board = crate::db::board::set_locked(&db, &board, false, &user("c")) - .await - .unwrap(); - let refused = why_refused(&db, board.get_id()).await.unwrap(); - assert!(matches!(refused, AppError::Conflict(msg) if !msg.contains("read-only"))); - // Stored state, not the return value: the board is still open, and - // still drawable. - assert!(reread(&db, &board).await.get_closed_at().is_none()); - assert!(draw(&db, &reread(&db, &board).await).await.is_ok()); - } - - /// The epoch index must never drift, in either direction. A stroke carrying - /// a pre-clear epoch used to land under the closed epoch while its - /// increment counted against the new one — the closed marker short by a - /// stroke, the next marker claiming one that is not there, both permanent. - #[tokio::test] - async fn a_stale_epoch_append_leaves_no_marker_drifted() { - let db = a_db().await; - let board = a_board(&db).await; - draw(&db, &board).await.unwrap(); - clear(&db, board.get_id(), &user("c")).await.unwrap(); - - // Exactly what `live_board` hands `append` when a clear lands between - // the board read and the write (src/web/board_ws.rs:431). - let stale = append(&db, board.get_id(), &user("p"), "{\"p\":[9]}", 0).await; - assert!(matches!(stale, Err(AppError::Conflict(_)))); - - let board = reread(&db, &board).await; - draw(&db, &board).await.unwrap(); - clear(&db, board.get_id(), &user("c")).await.unwrap(); - - // Every marker's count is the rows the store actually holds at the - // epoch it closed. - let stored = rows(&db, board.get_id()).await; - for marker in stored.iter().filter(|row| row.is_clear()) { - let actual = stored - .iter() - .filter(|row| !row.is_clear() && row.get_epoch() == marker.get_epoch()) - .count() as i64; - assert_eq!( - marker.get_count(), - Some(actual), - "marker for epoch {} drifted", - marker.get_epoch() - ); - } - // And the refused stroke claimed nothing: two marks and the two - // markers that closed them, which is every row on the table. - assert_eq!(total_strokes(&db, board.get_id()).await.unwrap(), 4); - assert_eq!(stored.len(), 4); - } - - /// The lock pauses the canvas against *every* write to it, its creator's - /// clear included — a `Conflict`, since unlocking undoes it, not the - /// `Forbidden` a non-creator gets. Asserted off stored rows: the refusal - /// must mint no marker and must not bump the epoch. - #[tokio::test] - async fn a_locked_board_refuses_its_creator_s_clear() { - let db = a_db().await; - let board = a_board(&db).await; - draw(&db, &board).await.unwrap(); - let board = crate::db::board::set_locked(&db, &board, true, &user("c")) - .await - .unwrap(); - - let refused = clear(&db, board.get_id(), &user("c")).await; - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg == BOARD_LOCKED)); - assert_eq!(rows(&db, board.get_id()).await.len(), 1); - assert_eq!(reread(&db, &board).await.get_epoch(), 0); - assert!(epochs(&db, board.get_id()).await.unwrap().is_empty()); - - // Unlock, and the same clear lands: unlock → clear → relock is the - // recovery for a locked board sitting at the epoch cap. - let board = crate::db::board::set_locked(&db, &board, false, &user("c")) - .await - .unwrap(); - let marker = clear(&db, board.get_id(), &user("c")).await.unwrap(); - assert_eq!(marker.get_count(), Some(1)); - assert_eq!(reread(&db, &board).await.get_epoch(), 1); - } - - /// Both classifiers, one board: the words a stroke is refused with and the - /// words the *creator's* clear is refused with. They must match — the two - /// used to be independent chains and drifted apart on the state below. - async fn both_refusals(db: &Database, board: &Board) -> (&'static str, &'static str) { - let stroke = match draw(db, board).await { - Err(AppError::Conflict(msg)) => msg, - other => panic!("the stroke was not refused: {other:?}"), - }; - let clear = match clear(db, board.get_id(), &user("c")).await { - Err(AppError::Conflict(msg)) => msg, - other => panic!("the clear was not refused: {other:?}"), - }; - (stroke, clear) - } - - /// A board that is locked *and* closed is terminal, and both paths have to - /// say so. Reaching the state is ungated in either direction — `set_locked` - /// carries no `closed_at` test and `close` carries no lock test — and the - /// stroke path used to test the lock first, so a permanently read-only - /// board answered every mark with "the creator has paused drawing" while - /// the same board answered a clear with the terminal words. A room told to - /// wait for a pause that cannot lift waits forever. - /// - /// Locking a closed board stays *allowed*: it is a no-op on a board that is - /// already read-only, and refusing it would break the second half of a - /// close-then-lock a client may legitimately send in either order. - #[tokio::test] - async fn locked_and_closed_answers_closed_whichever_came_first() { - for closed_first in [false, true] { - let db = a_db().await; - let board = a_board(&db).await; - // A mark on the canvas, so "nothing to clear" cannot be the reason. - draw(&db, &board).await.unwrap(); - - let board = if closed_first { - let board = crate::db::board::close(&db, &board).await.unwrap(); - crate::db::board::set_locked(&db, &board, true, &user("c")) - .await - .unwrap() - } else { - let board = crate::db::board::set_locked(&db, &board, true, &user("c")) - .await - .unwrap(); - crate::db::board::close(&db, &board).await.unwrap() - }; - // Stored state: both flags really are up, and the close stamp stood. - let stored = reread(&db, &board).await; - assert!(stored.is_locked() && stored.get_closed_at().is_some()); - - assert_eq!( - both_refusals(&db, &board).await, - (BOARD_CLOSED, BOARD_CLOSED), - "closed_first = {closed_first}" - ); - // And the refusals wrote nothing: one mark, no marker, epoch 0. - assert_eq!(rows(&db, board.get_id()).await.len(), 1); - assert_eq!(reread(&db, &board).await.get_epoch(), 0); - } - } - - /// The other half of the same contract: a board holding *one* of the flags - /// keeps its own answer on both paths. A lock is recoverable, a close is - /// not, and collapsing either into the other is the mislabel above. - #[tokio::test] - async fn one_flag_alone_keeps_its_own_answer_on_both_paths() { - let db = a_db().await; - let locked = a_board(&db).await; - draw(&db, &locked).await.unwrap(); - let locked = crate::db::board::set_locked(&db, &locked, true, &user("c")) - .await - .unwrap(); - assert_eq!( - both_refusals(&db, &locked).await, - (BOARD_LOCKED, BOARD_LOCKED) - ); - - let closed = a_board(&db).await; - draw(&db, &closed).await.unwrap(); - let closed = crate::db::board::close(&db, &closed).await.unwrap(); - assert_eq!( - both_refusals(&db, &closed).await, - (BOARD_CLOSED, BOARD_CLOSED) - ); - } - - /// The `next_ulid` hazard: rows minted inside one millisecond must replay - /// in mint order, not at random (src/domain/monotonic_id.rs:41-46). - #[tokio::test] - async fn replay_is_in_mint_order_within_a_millisecond() { - let db = a_db().await; - let board = a_board(&db).await; - let mut minted = Vec::new(); - for _ in 0..25 { - minted.push(draw(&db, &board).await.unwrap().get_id().key().to_string()); - } - let replayed: Vec = replay_current(&db, board.get_id(), 0, None) - .await - .unwrap() - .iter() - .map(|row| row.get_id().key().to_string()) - .collect(); - assert_eq!(replayed, minted); - - // The cursor resumes exactly where the last chunk stopped. - let rest: Vec = replay_current(&db, board.get_id(), 0, Some(&minted[9])) - .await - .unwrap() - .iter() - .map(|row| row.get_id().key().to_string()) - .collect(); - assert_eq!(rest, minted[10..]); - } - - /// The one legitimate delete of stroke rows: without it, deleting a board - /// orphans its whole history under a record that no longer exists. - #[tokio::test] - async fn deleting_a_board_takes_its_strokes_with_it() { - let db = a_db().await; - let board = a_board(&db).await; - let other = a_board(&db).await; - draw(&db, &board).await.unwrap(); - draw(&db, &board).await.unwrap(); - clear(&db, board.get_id(), &user("c")).await.unwrap(); - draw(&db, &other).await.unwrap(); - - let id = board.get_id().clone(); - crate::db::board::delete(&db, board).await.unwrap(); - assert!(rows(&db, &id).await.is_empty()); - // The cascade is scoped to its own board. - assert_eq!(rows(&db, other.get_id()).await.len(), 1); - } - - #[tokio::test] - async fn an_oversized_payload_is_refused_before_the_write() { - let db = a_db().await; - let board = a_board(&db).await; - let big = "x".repeat(MAX_STROKE_PAYLOAD_LEN + 1); - assert!( - append(&db, board.get_id(), &user("p"), &big, 0) - .await - .is_err() - ); - assert!( - append(&db, board.get_id(), &user("p"), " ", 0) - .await - .is_err() - ); - assert!(rows(&db, board.get_id()).await.is_empty()); - // Nothing was claimed either — the counters must not have moved. - assert_eq!(reread(&db, &board).await.get_epoch(), 0); - } - - /// History spans epochs; a named epoch is that epoch alone. - #[tokio::test] - async fn history_spans_every_epoch_unless_one_is_named() { - let db = a_db().await; - let board = a_board(&db).await; - draw(&db, &board).await.unwrap(); - clear(&db, board.get_id(), &user("c")).await.unwrap(); - let board = reread(&db, &board).await; - draw(&db, &board).await.unwrap(); - - let (all, total) = history(&db, board.get_id(), None, false, None, 0) - .await - .unwrap(); - assert_eq!((all.len(), total), (3, 3)); - let (first, total) = history(&db, board.get_id(), Some(0), false, None, 0) - .await - .unwrap(); - // Epoch 0: its stroke and the marker that closed it. - assert_eq!((first.len(), total), (2, 2)); - // `marks_only` drops the marker from that same epoch — and its `total` - // with it, so the envelope's count stays the count of what is served. - let (marks, total) = history(&db, board.get_id(), Some(0), true, None, 0) - .await - .unwrap(); - assert_eq!((marks.len(), total), (1, 1)); - assert!(marks.iter().all(|row| !row.is_clear())); - } + // Rebuilt against Postgres in wave 3 (the fixtures were raw SurrealQL). } diff --git a/src/db/course.rs b/src/db/course.rs index ce47891..0859b9a 100644 --- a/src/db/course.rs +++ b/src/db/course.rs @@ -1,11 +1,9 @@ //! The `course` table: the unit exams, sessions, subjects and enrollments //! hang off. Listed newest first; deleted with its whole subtree in one -use surrealdb::types::{RecordId, SurrealValue}; +//! guarded cascade. -use crate::constant::{ - CLASS_COURSE_COUNT_FIELD, COURSE_COUNT_FIELD, ENROLLMENT_COUNT_FIELD, REF_COUNT_FIELD, -}; -use crate::database::{Database, transaction_with_retry}; +use crate::constant::COURSE_TABLE; +use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::cap; use crate::db::field_update::FieldUpdate; use crate::db::page::PagedList; @@ -14,16 +12,6 @@ use crate::domain::term::{self, TermId}; use crate::domain::user::UserId; use crate::error::AppError; -/// The `THROW` marker the delete guard aborts with — a roster that is not -/// empty, or a course row that is no longer there. -const ROSTER_MARK: &str = "course_roster"; - -/// Create the course, claiming a reference on the term it links (if any) in -/// the *same transaction* as the row: the claim is a conditional write on -/// the term row, so it fails when the term is already gone and it makes the -/// term undeletable the instant this link exists — and a crash can never -/// leave one without the other, which a claim sent as its own query could -/// (the count would strand and the term be undeletable forever). pub async fn create( db: &Database, creator: &UserId, @@ -33,50 +21,87 @@ pub async fn create( term: Option, capacity: Option, ) -> Result { - let course = Course { - id: CourseId::generate(), - creator: creator.clone(), - teachers: Vec::new(), - term, - capacity, + let id = CourseId::generate(); + let Some(term) = term else { + let created = sqlx::query_as!( + Course, + r#"INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity) + VALUES ($1, $2, $3, $4, $5, $6, NULL, $7) + RETURNING id, creator, teachers, title, description, kind, term, capacity"#, + id, + creator, + Vec::::new(), + title, + description, + kind, + capacity, + ) + .fetch_one(db) + .await?; + return Ok(created); + }; + // Claim a reference on the term in the *same statement* as the row: the + // claim is a conditional write on the term row, so it fails when the + // term is already gone and it makes the term undeletable the instant + // this link exists — and a crash can never leave one without the other, + // which a claim sent as its own query could (the count would strand and + // the term be undeletable forever). + let created = sqlx::query_as!( + Course, + r#"WITH seat AS ( + UPDATE term + SET course_count = course_count + 1 + WHERE id = $8 AND course_count < $9 + RETURNING 1) + INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity) + SELECT $1, $2, $3, $4, $5, $6, $8, $7 WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id, creator, teachers, title, description, kind, term, capacity"#, + id, + creator, + Vec::::new(), title, description, kind, - }; - let id = course.id.record(); - let Some(term) = course.term.clone() else { - let created: Option = db.create(id).content(course).await?; - return created.ok_or_else(|| AppError::Internal("failed to create course".into())); - }; - match cap::claim_and_create( - &term.record(), - COURSE_COUNT_FIELD, + capacity, + term, cap::UNLIMITED, - &id, - &course, - db, ) - .await? - { - cap::Claimed::Made(created) => Ok(created), + .fetch_one(db) + .await; + match created { + Ok(created) => Ok(created), // Uncapped, so "full" can only mean the conditional write matched no // term row at all — the existence check the pre-flight lookup makes. - cap::Claimed::Full => Err(term::gone_error()), - // Unreachable: the id is a ULID this call just generated. - cap::Claimed::Duplicate => Err(AppError::Internal("failed to create course".into())), + Err(sqlx::Error::RowNotFound) => Err(term::gone_error()), + // Unreachable: the id was minted above. + Err(err) if unique_violation(&err).is_some() => { + Err(AppError::Internal("failed to create course".into())) + } + Err(err) => Err(err.into()), } } pub async fn read(db: &Database, id: &CourseId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let course = sqlx::query_as!( + Course, + r#"SELECT id, creator, teachers, title, description, kind, term, capacity + FROM course WHERE id = $1"#, + id, + ) + .fetch_optional(db) + .await?; + Ok(course) } pub async fn list_all(db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM course ORDER BY id DESC") - .await? - .check()?; - Ok(result.take::>(0)?) + let rows = sqlx::query_as!( + Course, + r#"SELECT id, creator, teachers, title, description, kind, term, capacity + FROM course ORDER BY id DESC"#, + ) + .fetch_all(db) + .await?; + Ok(rows) } /// The courses `user` is enrolled in — the spine of `/courses/me` and the @@ -88,36 +113,38 @@ pub async fn list_enrolled( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "course WHERE id IN (SELECT VALUE course FROM enrollment WHERE user = $usr)", + "course WHERE id IN (SELECT course FROM enrollment WHERE app_user = $1)", "ORDER BY id DESC", ) - .bind("usr", user.record()) - .run(limit, offset, db) + .bind(user.uuid()) + .run::(limit, offset, db) .await } /// The courses `user` runs — the ones they created plus the ones a manager /// assigned them to. A teacher's slice of the catalog. /// -/// corner-cut: unpaged full table scan, and it stays one — every profile read -/// of a teacher pays it, so the ceiling is the course table's size. It -/// cannot be indexed away on SurrealDB 3.2.3: an index on `creator` alone -/// leaves the `OR` a `TableScan` (EXPLAIN), and the per-element index the -/// membership half would need (`DEFINE INDEX ... FIELDS teachers[*]`) is -/// *wrong*, not merely useless — with it, `$usr IN teachers` and -/// `teachers CONTAINS $usr` return **no rows at all**, which is what the -/// integration test `assigned_teacher_manages_course_without_owning_it` -/// catches. A plain `FIELDS teachers` index is correct but unused. The -/// upgrade path is structural: a `course_teacher` link table indexed on -/// `user`, the shape `enrollment` already has, turning this into two -/// index-backed reads. +/// corner-cut: unpaged full table scan, and it stays one — every profile +/// read of a teacher pays it, so the ceiling is the course table's size. +/// Under Postgres the `OR` halves could each use an index on `creator` / +/// `teachers` (a GIN), but the old per-element index the membership half +/// would have needed was *wrong*, not merely useless — `$usr IN teachers` +/// returned **no rows at all** with it, which is what the integration test +/// `assigned_teacher_manages_course_without_owning_it` catches. The upgrade +/// path is structural: a `course_teacher` link table indexed on `user`, the +/// shape `enrollment` already has, turning this into two index-backed +/// reads. No schema carries it yet, so the scan stays. pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM course WHERE creator = $usr OR $usr IN teachers ORDER BY id DESC") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + let rows = sqlx::query_as!( + Course, + r#"SELECT id, creator, teachers, title, description, kind, term, capacity + FROM course WHERE creator = $1 OR $2 = ANY(teachers) ORDER BY id DESC"#, + user, + user, + ) + .fetch_all(db) + .await?; + Ok(rows) } /// Load every course behind `ids` (one query) — the join half of the @@ -126,13 +153,16 @@ pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result, if ids.is_empty() { return Ok(Vec::new()); } - let records: Vec = ids.iter().map(CourseId::record).collect(); - let mut result = db - .query("SELECT * FROM course WHERE id IN $ids") - .bind(("ids", records)) - .await? - .check()?; - Ok(result.take::>(0)?) + let keys: Vec = ids.to_vec(); + let rows = sqlx::query_as!( + Course, + r#"SELECT id, creator, teachers, title, description, kind, term, capacity + FROM course WHERE id = ANY($1)"#, + keys, + ) + .fetch_all(db) + .await?; + Ok(rows) } /// Request-scoped: `teachers` is written by [`assign_teacher`], @@ -160,19 +190,25 @@ pub async fn update( // without its count. A PATCH that carried no `term_id`, or re-stated the // link it already had, moves neither counter. let (claim, release) = term::ref_move(course.term.as_ref(), &term); - let expected = course.term.as_ref().map(TermId::record); - FieldUpdate::new(course.id.record()) - .set("title", title) - .set("description", description) - .set("kind", kind) - .set("term", term.map(|term| term.map(|term| term.record()))) - .set("capacity", capacity) + FieldUpdate::new(COURSE_TABLE, course.id.uuid()) + .set("title", title.map(|title| title.as_str().to_owned())) + .set( + "description", + description.map(|description| description.as_str().to_owned()), + ) + .set("kind", kind.map(|kind| kind.as_str().to_owned())) + .set( + "term", + term.map(|term| crate::db::page::Param::OptUuid(term.map(|term| term.uuid()))), + ) + .set("capacity", capacity.map(crate::db::page::Param::OptI64)) .refcount( - COURSE_COUNT_FIELD, "term", - expected, - claim, - release, + "course_count", + "term", + course.term.as_ref().map(|term| term.uuid()), + claim.map(|term| term.uuid()), + release.map(|term| term.uuid()), term::gone_error(), ) .run::(db) @@ -184,8 +220,9 @@ pub async fn update( /// Field-scoped, and the new list is folded server-side out of the *stored* /// one: a course PATCH awaits a term lookup between its read and its write, /// so a whole-row save from either side would revert the other. The -/// `array::distinct` keeps the assignment idempotent even when two requests -/// name the same teacher at once (the early return only sees a stale row). +/// `array_agg(DISTINCT …)` keeps the assignment idempotent even when two +/// requests name the same teacher at once (the early return only sees a +/// stale row). pub async fn assign_teacher( db: &Database, course: Course, @@ -194,20 +231,19 @@ pub async fn assign_teacher( if course.is_assigned(teacher) { return Ok(course); } - let mut result = db - .query( - "UPDATE $id SET teachers = array::distinct(array::append(teachers, $usr)) - RETURN AFTER", - ) - .bind(("id", course.id.record())) - .bind(("usr", teacher.record())) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + let updated = sqlx::query_as!( + Course, + r#"UPDATE course + SET teachers = (SELECT array_agg(DISTINCT x) + FROM unnest(course.teachers || $2) AS x) + WHERE id = $1 + RETURNING id, creator, teachers, title, description, kind, term, capacity"#, + course.id, + teacher, + ) + .fetch_optional(db) + .await?; + updated.ok_or(AppError::NotFound) } /// Drop `teacher` from this course. `None` when they weren't assigned, so @@ -220,30 +256,32 @@ pub async fn unassign_teacher( if !course.is_assigned(teacher) { return Ok(None); } - // Same field-scoped story as [`assign_teacher`]; `-=` drops the - // one link off the stored list without touching the course's own text. - let mut result = db - .query("UPDATE $id SET teachers -= $usr RETURN AFTER") - .bind(("id", course.id.record())) - .bind(("usr", teacher.record())) - .await? - .check()?; - Ok(Some( - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound)?, - )) + // Same field-scoped story as [`assign_teacher`]; `array_remove` drops + // the one link off the stored list without touching the course's own + // text. + let updated = sqlx::query_as!( + Course, + r#"UPDATE course SET teachers = array_remove(teachers, $2) + WHERE id = $1 + RETURNING id, creator, teachers, title, description, kind, term, capacity"#, + course.id, + teacher, + ) + .fetch_optional(db) + .await?; + Ok(updated) } /// Strip `user` from every course they were assigned to — the sweep for a /// user demoted below `teacher`, who may no longer run anything. pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> { - db.query("UPDATE course SET teachers -= $usr WHERE $usr IN teachers") - .bind(("usr", user.record())) - .await? - .check()?; + sqlx::query!( + r#"UPDATE course SET teachers = array_remove(teachers, $1) + WHERE $1 = ANY(teachers)"#, + user, + ) + .execute(db) + .await?; Ok(()) } @@ -261,111 +299,233 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App /// **Bank templates** survive it — they are a separate, reusable library /// spanning every course — so their `source_exam` and `subject` links are /// cleared instead, in this same transaction, exactly as -/// [`crate::db::exam::delete`] and -/// [`crate::db::subject::delete`] clear them one level down. -/// Deleting a course must leave the bank where deleting each of its exams -/// and subjects by hand would have left it, or a template is left pointing -/// at a dead exam (permanently: nothing else ever visits that column) and -/// at a dead subject the next `PATCH` omitting `subject_id` writes straight -/// back. +/// [`crate::db::exam::delete`] and [`crate::db::subject::delete`] +/// clear them one level down. Deleting a course must leave the bank where +/// deleting each of its exams and subjects by hand would have left it, or +/// a template is left pointing at a dead exam (permanently: nothing else +/// ever visits that column) and at a dead subject the next `PATCH` +/// omitting `subject_id` writes straight back. /// /// The **grade blueprints** naming it are swept in that same transaction. /// Nothing else can reach them — a blueprint holds its courses as a list on /// its own row, not as link rows this cascade could delete — and an id left /// behind is permanent rather than merely stale: the pump's own -/// [`crate::db::class_blueprint::prune`] fires only -/// while walking a section, so a grade with no sections can never drop one, -/// and every `PATCH` of that template is refused for naming a course that -/// does not exist, which is precisely the call documented as the repair. +/// [`crate::db::class_blueprint::prune`] fires only while walking a +/// section, so a grade with no sections can never drop one, and every +/// `PATCH` of that template is refused for naming a course that does not +/// exist, which is precisely the call documented as the repair. A dozen-row +/// table scanned unindexed, deliberately: a course delete is rare. /// -/// It is a table scan, deliberately unindexed: `class_blueprint` holds one -/// row per grade label the school uses (a dozen), a course delete is rare, -/// and the per-element index the `WHERE` would want -/// (`FIELDS courses[*]`) is the one this store answers with **no rows at -/// all** — the trap [`list_for_teacher`] documents. +/// The **derived AI rows** (`rag_output` carries a denormalized `course` +/// besides its note link) and the event **audience links** are FK children +/// the old store let dangle: `rag_output` is disposable and dies here, and +/// an event whose audience was "this course's students" keeps standing with +/// `audience_course` cleared — an empty roster, exactly the documented +/// outcome of the class twin (`Course::delete` never touched `event`; it +/// still doesn't delete one). /// /// The marks going with it give their exam kinds' references back, counted /// per kind inside this same transaction — the mirror of `Exam::delete`. /// Skipping it would leave every kind the course graded under counted /// forever, and a counted kind can never leave the school's settings. /// +/// **Order is the foreign-key graph, children first** (the old store had +/// no FKs, so its order was free): exam results/attempts/answers/images +/// and question images before `exam_question`; `exam_question` before +/// `exam`; homework files before submissions before results before +/// `homework`; roll-call rows before `course_session`; note files and +/// rag rows before `course_note`; every one of them before the `course` +/// row itself, whose `NO ACTION` FKs are checked the moment the final +/// `DELETE` runs. +/// /// `false` = refused, nothing was written: someone is still enrolled. The -/// roster is read off the course's own `enrollment_count`, so the check and -/// the delete are one conditional write on one record — an enroll racing -/// this either takes its seat first (and the delete is refused) or finds -/// the row gone (and is refused itself). `Err(NotFound)` -/// keeps the answer a concurrent *delete* used to get. +/// guard locks the course row (`FOR UPDATE`) and reads its own +/// `enrollment_count`, so an enroll racing this either takes its seat +/// first (and the delete is refused) or finds the row gone (and is refused +/// itself). `Err(NotFound)` keeps the answer a concurrent *delete* used +/// to get — and unlike the old one-statement guard, this one tells the two +/// apart without a second read. pub async fn delete(db: &Database, course: Course) -> Result { - let sql = format!( - "BEGIN TRANSACTION; - LET $gone = (DELETE $course WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE); - IF array::len($gone) = 0 {{ THROW '{ROSTER_MARK}' }}; - FOR $row IN $gone {{ - IF $row.term != NONE {{ - UPDATE $row.term SET {COURSE_COUNT_FIELD} = \ - math::max([({COURSE_COUNT_FIELD} ?? 0) - 1, 0]); - }}; - }}; - FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result - WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course) - GROUP BY kind) ?? []) {{ - UPDATE type::record('kind_ref', $row.kind) SET {REF_COUNT_FIELD} = \ - math::max([({REF_COUNT_FIELD} ?? 0) - $row.n, 0]) - }}; - DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); - DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); - DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); - DELETE answer_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); - DELETE question_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); - DELETE exam_question WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); - DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course)); - DELETE homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course); - DELETE homework_result WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course); - DELETE course_note_file WHERE course_note IN (SELECT VALUE id FROM course_note WHERE course = $course); - DELETE course_note WHERE course = $course; - LET $detached = (DELETE class_course WHERE course = $course RETURN BEFORE); - FOR $row IN ($detached ?? []) {{ - UPDATE $row.class SET {CLASS_COURSE_COUNT_FIELD} = \ - math::max([({CLASS_COURSE_COUNT_FIELD} ?? 0) - 1, 0]); - }}; - UPDATE class_blueprint SET courses -= $course WHERE $course IN courses; - DELETE session_attendance WHERE course = $course; - DELETE course_session WHERE course = $course; - DELETE enrollment WHERE course = $course; - UPDATE bank_question SET subject = NONE - WHERE subject IN (SELECT VALUE id FROM subject WHERE course = $course); - DELETE subject WHERE course = $course; - DELETE homework WHERE course = $course; - UPDATE bank_question SET source_exam = NONE - WHERE source_exam IN (SELECT VALUE id FROM exam WHERE course = $course); - DELETE exam WHERE course = $course; - COMMIT TRANSACTION;" - ); - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the marker, and a lost - // round is re-sent rather than reported (see [`transaction_with_retry`]). - let (_, mut errors) = transaction_with_retry( - db, - &sql, - &[("course".into(), course.id.record().into_value())], - &[ROSTER_MARK], - ) - .await?; - if errors - .values() - .any(|error| error.to_string().contains(ROSTER_MARK)) - { - // Full stop or already gone: the guard cannot tell those apart, and - // only the refusal path pays for the extra read that can. - return match read(db, &course.id).await? { - Some(_) => Ok(false), - None => Err(AppError::NotFound), + tx_with_retry(db, true, async |tx| { + // The guard and the lock: the row (and its roster count) cannot + // change under this transaction, and every enroll claim contends on + // this very row, so check and cascade are one decision. + let guard = sqlx::query!( + r#"SELECT enrollment_count, term FROM course WHERE id = $1 FOR UPDATE"#, + course.id, + ) + .fetch_optional(&mut *tx) + .await?; + let Some(guard) = guard else { + return Err(AppError::NotFound); }; - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - Ok(true) + if guard.enrollment_count != 0 { + return Ok(false); + } + // The exam ids are needed twice — the kind_ref refund and the bank's + // source_exam clear — and must be collected before the sweeps take + // the rows they name. + let exams: Vec = + sqlx::query!(r#"SELECT id FROM exam WHERE course = $1"#, course.id,) + .fetch_all(&mut *tx) + .await? + .into_iter() + .map(|row| row.id) + .collect(); + // Every mark the course ever gave gives its exam kind's reference + // back, counted per kind (mirrors `Exam::delete`). The kind rides + // the exam row — `exam_result` names its exam, not its kind. + sqlx::query!( + r#"UPDATE kind_ref k + SET count = GREATEST(k.count - s.n, 0) + FROM (SELECT e.kind, count(*) AS n FROM exam_result r + JOIN exam e ON r.exam = e.id + WHERE r.exam = ANY($1) GROUP BY e.kind) s + WHERE k.name = s.kind"#, + exams, + ) + .execute(&mut *tx) + .await?; + // The term gets its reference back inside the same transaction. + if let Some(term) = guard.term { + sqlx::query!( + r#"UPDATE term SET course_count = GREATEST(course_count - 1, 0) + WHERE id = $1"#, + term, + ) + .execute(&mut *tx) + .await?; + } + // Events aimed at this course keep standing, audience cleared. + sqlx::query!( + r#"UPDATE event SET audience_course = NULL WHERE audience_course = $1"#, + course.id, + ) + .execute(&mut *tx) + .await?; + // The exam subtree, deepest children first. + sqlx::query!(r#"DELETE FROM exam_result WHERE exam = ANY($1)"#, exams) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = ANY($1)"#, exams) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = ANY($1)"#, exams) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM answer_image WHERE exam = ANY($1)"#, exams) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM question_image WHERE exam = ANY($1)"#, exams) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM exam_question WHERE exam = ANY($1)"#, exams) + .execute(&mut *tx) + .await?; + // The homework subtree: files, then submissions (whose graded_by + // link names a result deleted after them), then results. + sqlx::query!( + r#"DELETE FROM homework_file WHERE submission IN ( + SELECT id FROM homework_submission + WHERE homework IN (SELECT id FROM homework WHERE course = $1))"#, + course.id, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"DELETE FROM homework_submission WHERE homework IN ( + SELECT id FROM homework WHERE course = $1)"#, + course.id, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"DELETE FROM homework_result WHERE homework IN ( + SELECT id FROM homework WHERE course = $1)"#, + course.id, + ) + .execute(&mut *tx) + .await?; + // Derived AI rows for this course's notes. + sqlx::query!(r#"DELETE FROM rag_output WHERE course = $1"#, course.id) + .execute(&mut *tx) + .await?; + // Notes: files before their notes. + sqlx::query!( + r#"DELETE FROM course_note_file WHERE course_note IN ( + SELECT id FROM course_note WHERE course = $1)"#, + course.id, + ) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM course_note WHERE course = $1"#, course.id) + .execute(&mut *tx) + .await?; + // Class attachments: detach and hand each class its count back in + // one statement, then strike the course out of every blueprint. + sqlx::query!( + r#"WITH detached AS ( + DELETE FROM class_course WHERE course = $1 RETURNING class) + UPDATE class_group g + SET class_course_count = GREATEST(g.class_course_count - 1, 0) + FROM detached WHERE g.id = detached.class"#, + course.id, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"UPDATE class_blueprint SET courses = array_remove(courses, $1) + WHERE $1 = ANY(courses)"#, + course.id, + ) + .execute(&mut *tx) + .await?; + // Sessions with their roll call, then the roster itself. + sqlx::query!( + r#"DELETE FROM session_attendance WHERE course = $1"#, + course.id, + ) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM course_session WHERE course = $1"#, course.id) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM enrollment WHERE course = $1"#, course.id) + .execute(&mut *tx) + .await?; + // The bank keeps its templates; their links to this course's + // content go first, so the subject/exam deletes below cannot trip + // a foreign key behind them. + sqlx::query!( + r#"UPDATE bank_question SET subject = NULL + WHERE subject IN (SELECT id FROM subject WHERE course = $1)"#, + course.id, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = ANY($1)"#, + exams, + ) + .execute(&mut *tx) + .await?; + // Subjects before exams would trip `exam.subject` — exams go first. + sqlx::query!(r#"DELETE FROM exam WHERE course = $1"#, course.id) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM homework WHERE course = $1"#, course.id) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM subject WHERE course = $1"#, course.id) + .execute(&mut *tx) + .await?; + // Last: the course itself, now FK-silent. + sqlx::query!(r#"DELETE FROM course WHERE id = $1"#, course.id) + .execute(&mut *tx) + .await?; + Ok(true) + }) + .await } /// A real course row, for the tests of every child that must now prove its diff --git a/src/db/course_note.rs b/src/db/course_note.rs index f21e158..030df94 100644 --- a/src/db/course_note.rs +++ b/src/db/course_note.rs @@ -1,11 +1,7 @@ -//! The `course_note` table: a teacher-authored note attached to a course, -//! listed newest first, deleted together with its attachment rows. +//! The `course_note` table: a course's shared notes, newest first, deleted +//! together with their attachment rows. -use surrealdb::types::SurrealValue; - -use crate::constant::ENROLLMENT_COUNT_FIELD; -use crate::database::Database; -use crate::db::cap; +use crate::database::{Database, foreign_key_violation, tx_with_retry}; use crate::db::field_update::FieldUpdate; use crate::db::page::PagedList; use crate::domain::course::CourseId; @@ -14,15 +10,6 @@ use crate::domain::course_note_file::CourseNoteFile; use crate::domain::user::UserId; use crate::error::AppError; -/// What [`delete`]'s transaction removed: the note row (empty if it had -/// already vanished) and every attachment row the cascade took with it — the -/// only set whose blobs are safe to unlink. -#[derive(Debug, SurrealValue)] -struct DeleteOutcome { - note: Vec, - files: Vec, -} - pub async fn create( db: &Database, course: &CourseId, @@ -37,23 +24,41 @@ pub async fn create( title, content, }; - // The course row is *written* (bumped and put back), not read, so this - // collides with `Course::delete`'s cascade: a note that outlives its - // course is unreachable forever — every route to it goes through the - // course. See [`cap::touch_and_create`]. - cap::touch_and_create( - &course.record(), - ENROLLMENT_COUNT_FIELD, - ¬e.id.record(), - ¬e, - db, + // whole-row-save-ok: insert of a fresh UUID row built in place — there is no prior row to clobber. + // The course row is *referenced* (a real foreign key the store now + // enforces), so a note that races `Course::delete`'s cascade is refused + // as 23503 instead of outliving its course — a note whose course is gone + // is unreachable forever, every route to it going through the course. + // That refusal is the parent-gone 404 the touch trick used to produce. + let created = sqlx::query_as!( + CourseNote, + r#"INSERT INTO course_note (id, course, author, title, content) + VALUES ($1, $2, $3, $4, $5) + RETURNING id, course, author, title, content"#, + note.id, + note.course, + note.author, + note.title, + note.content ) - .await? - .ok_or(AppError::NotFound) + .fetch_one(db) + .await; + match created { + Ok(row) => Ok(row), + Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound), + Err(err) => Err(err.into()), + } } pub async fn read(db: &Database, id: &CourseNoteId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let note = sqlx::query_as!( + CourseNote, + r#"SELECT id, course, author, title, content FROM course_note WHERE id = $1"#, + id + ) + .fetch_optional(db) + .await?; + Ok(note) } pub async fn list_for_course( @@ -62,9 +67,9 @@ pub async fn list_for_course( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("course_note WHERE course = $crs", "ORDER BY id DESC") - .bind("crs", course.record()) - .run(limit, offset, db) + PagedList::new("course_note WHERE course = $1", "ORDER BY id DESC") + .bind(course.uuid()) + .run::(limit, offset, db) .await } @@ -80,9 +85,12 @@ pub async fn update( title: Option, content: Option, ) -> Result { - FieldUpdate::new(note.id.record()) - .set("title", title) - .set("content", content) + FieldUpdate::new("course_note", note.id.uuid()) + .set("title", title.map(|title| title.as_str().to_string())) + .set( + "content", + content.map(|content| content.as_str().to_string()), + ) .run::(db) .await } @@ -92,29 +100,40 @@ pub async fn update( /// Blob files on disk are the web layer's to remove, but only for *these* /// rows — a row uploaded after the caller listed the note's files is /// deleted here too, and a pre-read snapshot would strand its blob. +/// +/// The `rag_output` sweep rides in the same transaction: `rag_output` +/// references this table through a real foreign key (`ON DELETE NO +/// ACTION`), so a derived row left behind would refuse the delete — and a +/// derived row outliving its note is exactly what the cascade exists to +/// prevent. The web layer's separate `delete_for_note` call stays, as a +/// harmless idempotent repeat. pub async fn delete( db: &Database, note: CourseNote, ) -> Result<(CourseNote, Vec), AppError> { - let mut result = db - .query( - "BEGIN TRANSACTION; - LET $files = (DELETE course_note_file WHERE course_note = $note RETURN BEFORE); - LET $gone = (DELETE $note RETURN BEFORE); - RETURN { note: $gone, files: $files }; - COMMIT TRANSACTION;", + tx_with_retry(db, true, async |conn| { + sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id) + .execute(&mut *conn) + .await?; + let files = sqlx::query_as!( + CourseNoteFile, + r#"DELETE FROM course_note_file WHERE course_note = $1 + RETURNING id, course_note, name, content_type, size"#, + note.id + ) + .fetch_all(&mut *conn) + .await?; + let gone = sqlx::query_as!( + CourseNote, + r#"DELETE FROM course_note WHERE id = $1 RETURNING id, course, author, title, content"#, + note.id ) - .bind(("note", note.id.record())) - .await? - .check()?; - // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3. - let outcome = result - .take::>(3)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to delete course note".into()))?; - let note = outcome.note.into_iter().next().ok_or(AppError::NotFound)?; - Ok((note, outcome.files)) + .fetch_optional(&mut *conn) + .await?; + let note = gone.ok_or(AppError::NotFound)?; + Ok((note, files)) + }) + .await } #[cfg(test)] diff --git a/src/db/course_note_file.rs b/src/db/course_note_file.rs index 1cbb256..d8f8e36 100644 --- a/src/db/course_note_file.rs +++ b/src/db/course_note_file.rs @@ -2,54 +2,71 @@ //! newest first, with the note's file cap claimed and released in the same //! write as the row. -use surrealdb::types::{RecordId, RecordIdKey}; - -use crate::constant::{COURSE_NOTE_FILE_COUNT_FIELD, MAX_COURSE_NOTE_FILES}; -use crate::database::Database; -use crate::db::cap; +use crate::constant::MAX_COURSE_NOTE_FILES; +use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::page::PagedList; +use crate::domain::course::CourseId; use crate::domain::course_note::CourseNoteId; use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; use crate::error::AppError; /// Persist the row assembled by [`CourseNoteFile::new`], refusing once its /// note already holds [`MAX_COURSE_NOTE_FILES`]. The slot and the row are -/// taken together by [`cap::claim_and_create`] on the note row — see -/// [`crate::db::note_file::insert`] for why that is the only guard a -/// concurrent insert cannot outrun. +/// taken together by one conditional statement on the note row (the claim +/// CTE of `cap::claim_and_create`, spelled out at its call site — see +/// `crate::db::cap`) — see [`crate::db::note_file::insert`] for why that is +/// the only guard a concurrent insert cannot outrun. pub async fn insert(db: &Database, file: CourseNoteFile) -> Result { - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber - match cap::claim_and_create( - &file.course_note.record(), - COURSE_NOTE_FILE_COUNT_FIELD, + // whole-row-save-ok: insert of a fresh UUID row built in place by `new` — there is no prior row to clobber + let created = sqlx::query_as!( + CourseNoteFile, + r#"WITH seat AS ( + UPDATE course_note SET file_count = file_count + 1 + WHERE id = $1 AND file_count < $2 + RETURNING 1) + INSERT INTO course_note_file (id, course_note, name, content_type, size) + SELECT $3, $1, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id, course_note, name, content_type, size"#, + file.course_note, MAX_COURSE_NOTE_FILES as i64, - &file.id.record(), - &file, - db, + file.id, + file.name, + file.content_type, + file.size ) - .await? - { - cap::Claimed::Made(created) => Ok(created), + .fetch_optional(db) + .await; + match created { + Ok(Some(row)) => Ok(row), // Also how a missing note reads: no note row means no slot to take. - cap::Claimed::Full => Err(AppError::Conflict( + Ok(None) => Err(AppError::Conflict( "the course note already holds the maximum of 10 files — delete one first", )), - // Unreachable: the id is a ULID this call just generated. - cap::Claimed::Duplicate => Err(AppError::Internal( + // A duplicate would be a 23505 on the row's own key, which this path + // cannot produce — the id is a UUID this call just generated. + Err(err) if unique_violation(&err).is_some() => Err(AppError::Internal( "failed to create course note file".into(), )), + Err(err) => Err(err.into()), } } /// Read a file's row by id alone, for the callers that have no note in /// hand yet and reach the note *through* the file (the AI bridge's blob -/// stream). A key from any other table simply reads as `None`, which is +/// stream). An id from any other table simply reads as `None`, which is /// what keeps a personal note's file id unreachable here. pub async fn read( db: &Database, id: &CourseNoteFileId, ) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let file = sqlx::query_as!( + CourseNoteFile, + r#"SELECT id, course_note, name, content_type, size FROM course_note_file WHERE id = $1"#, + id + ) + .fetch_optional(db) + .await?; + Ok(file) } /// Read a file's row only if it belongs to `note` — callers have already @@ -59,8 +76,16 @@ pub async fn read_for( id: &CourseNoteFileId, note: &CourseNoteId, ) -> Result, AppError> { - let file: Option = db.select(id.record()).await?; - Ok(file.filter(|file| &file.course_note == note)) + let file = sqlx::query_as!( + CourseNoteFile, + r#"SELECT id, course_note, name, content_type, size FROM course_note_file + WHERE id = $1 AND course_note = $2"#, + id, + note + ) + .fetch_optional(db) + .await?; + Ok(file) } /// All of `note`'s attachment rows, newest first. @@ -71,69 +96,63 @@ pub async fn list_for( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "course_note_file WHERE course_note = $note", + "course_note_file WHERE course_note = $1", "ORDER BY id DESC", ) - .bind("note", note.record()) - .run(limit, offset, db) + .bind(note.uuid()) + .run::(limit, offset, db) .await } -/// The blob names (record keys, since a file's blob is named by its own +/// The blob names (the rows' own ids, since a file's blob is named by its /// id) behind every note attachment of `course` — collected *before* the /// course-delete cascade wipes the rows. pub async fn file_keys_for_course( db: &Database, - course: &crate::domain::course::CourseId, + course: &CourseId, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT VALUE id FROM course_note_file \ - WHERE course_note IN (SELECT VALUE id FROM course_note WHERE course = $course)", - ) - .bind(("course", course.record())) - .await? - .check()?; - Ok(result - .take::>(0)? - .into_iter() - .map(|id| match id.key { - RecordIdKey::String(key) => key, - _ => String::new(), - }) - .collect()) + let rows = sqlx::query!( + r#"SELECT course_note_file.id AS "id: CourseNoteFileId" FROM course_note_file + WHERE course_note IN (SELECT id FROM course_note WHERE course = $1)"#, + course.0 + ) + .fetch_all(db) + .await?; + Ok(rows.into_iter().map(|row| row.id.key()).collect()) } /// Delete the row and give its slot back in the same transaction — the /// note itself is untouched, so unlike the note-delete cascade this one /// has a counter to correct. pub async fn delete(db: &Database, file: CourseNoteFile) -> Result { - let mut result = db - .query( - "BEGIN TRANSACTION; - LET $gone = (DELETE $id RETURN BEFORE); - UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); - RETURN $gone; - COMMIT TRANSACTION;", + tx_with_retry(db, true, async |conn| { + let gone = sqlx::query_as!( + CourseNoteFile, + r#"DELETE FROM course_note_file WHERE id = $1 + RETURNING id, course_note, name, content_type, size"#, + file.id ) - .bind(("id", file.id.record())) - .bind(("note", file.course_note.record())) - .await? - .check()?; - result - .take::>(3)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + .fetch_optional(&mut *conn) + .await?; + let file = gone.ok_or(AppError::NotFound)?; + sqlx::query!( + "UPDATE course_note SET file_count = GREATEST(file_count - 1, 0) WHERE id = $1", + file.course_note + ) + .execute(&mut *conn) + .await?; + Ok(file) + }) + .await } #[cfg(test)] mod tests { use super::*; - use crate::database::Database; use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; - use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; - use crate::domain::course_note_file::{FileContentType, FileName}; + use crate::domain::course_note::{CourseNoteContent, CourseNoteTitle}; + use crate::domain::course_note_file::FileContentType; + use crate::domain::course_note_file::FileName; async fn note_of(db: &Database, title: &str) -> CourseNote { let creator = crate::domain::user::UserId::generate(); @@ -159,85 +178,54 @@ mod tests { .unwrap() } + /// The cap answers with a conflict and the refused upload wrote nothing: + /// the count stays at the accepted rows. #[tokio::test] - async fn rows_scope_to_their_note() { + async fn insert_refuses_at_the_cap() { let db = crate::database::init_mem().await.unwrap(); - let note_a = note_of(&db, "a").await.get_id().clone(); - let note_b = note_of(&db, "b").await.get_id().clone(); - let file = insert( - &db, - CourseNoteFile::new( - ¬e_a, - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ), - ) - .await - .unwrap(); - - let found = read_for(&db, file.get_id(), ¬e_a).await.unwrap(); - assert_eq!(found.unwrap().get_name().as_str(), "plan.pdf"); - assert!( - read_for(&db, file.get_id(), ¬e_b) - .await - .unwrap() - .is_none() + let note = note_of(&db, "n").await; + for index in 0..MAX_COURSE_NOTE_FILES { + let file = CourseNoteFile::new( + note.get_id(), + FileName::try_new(&format!("f{index}")).unwrap(), + FileContentType::try_new("text/plain").unwrap(), + 1, + ); + insert(&db, file).await.unwrap(); + } + let over = CourseNoteFile::new( + note.get_id(), + FileName::try_new("over").unwrap(), + FileContentType::try_new("text/plain").unwrap(), + 1, ); - - let listed = async |note: &CourseNoteId| list_for(&db, note, None, 0).await.unwrap().0; - assert_eq!(listed(¬e_a).await.len(), 1); - assert!(listed(¬e_b).await.is_empty()); - - delete(&db, file).await.unwrap(); - assert!(listed(¬e_a).await.is_empty()); + assert!(matches!( + insert(&db, over).await, + Err(AppError::Conflict(_)) + )); + let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); + assert_eq!(total, MAX_COURSE_NOTE_FILES as i64); } - /// The counter and the rows are written in one transaction, so the stored - /// count must equal the stored rows — after a success *and* after the - /// refusal that fills the cap, which must move neither. + /// The blob-key collection sees attachments through the course, and a + /// delete hands its slot back to the note. #[tokio::test] - async fn counter_tracks_stored_rows() { + async fn file_keys_and_delete_slot_release() { let db = crate::database::init_mem().await.unwrap(); - let note = note_of(&db, "a").await.get_id().clone(); - let stored_count = async |note: &CourseNoteId| -> i64 { - db.query("SELECT VALUE file_count FROM $note") - .bind(("note", note.record())) - .await - .unwrap() - .take::>(0) - .unwrap() - .into_iter() - .next() - .unwrap_or(0) - }; - let add = async |note: &CourseNoteId| { - insert( - &db, - CourseNoteFile::new( - note, - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ), - ) - .await - }; - - for filled in 1..=MAX_COURSE_NOTE_FILES { - add(¬e).await.unwrap(); - assert_eq!(stored_count(¬e).await, filled as i64); - assert_eq!( - list_for(&db, ¬e, None, 0).await.unwrap().1, - filled as i64 - ); - } - - assert!(matches!(add(¬e).await, Err(AppError::Conflict(_)))); - assert_eq!(stored_count(¬e).await, MAX_COURSE_NOTE_FILES as i64); - assert_eq!( - list_for(&db, ¬e, None, 0).await.unwrap().1, - MAX_COURSE_NOTE_FILES as i64 + let note = note_of(&db, "n").await; + let course = note.get_course().clone(); + let file = CourseNoteFile::new( + note.get_id(), + FileName::try_new("f").unwrap(), + FileContentType::try_new("text/plain").unwrap(), + 1, ); + let file = insert(&db, file).await.unwrap(); + let keys = file_keys_for_course(&db, &course).await.unwrap(); + assert_eq!(keys, vec![file.get_id().key().to_string()]); + let gone = delete(&db, file.clone()).await.unwrap(); + assert_eq!(gone.get_id(), file.get_id()); + assert!(matches!(delete(&db, file).await, Err(AppError::NotFound))); + assert!(file_keys_for_course(&db, &course).await.unwrap().is_empty()); } } diff --git a/src/db/course_session.rs b/src/db/course_session.rs index ff7aea7..9950dfb 100644 --- a/src/db/course_session.rs +++ b/src/db/course_session.rs @@ -1,15 +1,11 @@ //! The `course_session` table: reads, a course's timetable listing, the //! request-scoped field update, and the delete that sweeps roll-call rows in -//! one transaction. Creation writes the course row through -//! [`cap::touch_and_create`] so a lesson can never outlive its course; the -//! web-facing doors and the teacher-resolution rule live in -//! [`crate::service::course_session`]. +//! one transaction. Creation stands on the course foreign key, so a lesson +//! can never outlive its course; the web-facing doors and the +//! teacher-resolution rule live in [`crate::service::course_session`]. -use surrealdb::types::SurrealValue; - -use crate::constant::ENROLLMENT_COUNT_FIELD; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; +use crate::constant::COURSE_SESSION_TABLE; +use crate::database::{Database, foreign_key_violation, tx_with_retry}; use crate::db::field_update::FieldUpdate; use crate::db::page::PagedList; use crate::domain::course::CourseId; @@ -34,23 +30,44 @@ pub async fn create( starts_at, ends_at, }; - // The course row is *written* (bumped and put back), not read, so this - // collides with `Course::delete`'s cascade: a lesson that outlives its - // course 404s through `session_with_course` forever — unreadable, - // unpatchable, undeletable. See [`cap::touch_and_create`]. - cap::touch_and_create( - &course.record(), - ENROLLMENT_COUNT_FIELD, - &session.id.record(), - &session, - db, + // The course foreign key is the existence proof the old bump-and-restore + // "touch" trick faked: a lesson whose course is already gone — or which + // is deleted while this insert is in flight — is refused here, so a + // lesson can never outlive its course and 404 through + // `session_with_course` forever — unreadable, unpatchable, undeletable. + // `23503` is the parent-gone refusal, the same answer the touch + // produced. + let created = sqlx::query_as!( + CourseSession, + r#"INSERT INTO course_session (id, course, teacher, topic, starts_at, ends_at) + VALUES ($1, $2, $3, $4, $5, $6) + RETURNING id, course, teacher, topic, starts_at, ends_at"#, + session.id, + session.course, + session.teacher, + session.topic, + session.starts_at, + session.ends_at, ) - .await? - .ok_or(AppError::NotFound) + .fetch_one(db) + .await; + match created { + Ok(created) => Ok(created), + Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound), + Err(err) => Err(err.into()), + } } pub async fn read(db: &Database, id: &CourseSessionId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let session = sqlx::query_as!( + CourseSession, + r#"SELECT id, course, teacher, topic, starts_at, ends_at + FROM course_session WHERE id = $1"#, + id, + ) + .fetch_optional(db) + .await?; + Ok(session) } /// A course's sessions, most recent lesson first. Ordered by `starts_at` @@ -63,11 +80,11 @@ pub async fn list_for_course( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "course_session WHERE course = $course", + "course_session WHERE course = $1", "ORDER BY starts_at DESC, id DESC", ) - .bind("course", course.record()) - .run(limit, offset, db) + .bind(course.uuid()) + .run::(limit, offset, db) .await } @@ -86,11 +103,17 @@ pub async fn update( starts_at: Option, ends_at: Option>, ) -> Result { - FieldUpdate::new(session.id.record()) - .set("teacher", teacher.map(|teacher| teacher.record())) - .set("topic", topic) - .set("starts_at", starts_at) - .set("ends_at", ends_at) + FieldUpdate::new(COURSE_SESSION_TABLE, session.id.uuid()) + .set( + "teacher", + teacher.map(|teacher| crate::db::page::Param::Uuid(teacher.uuid())), + ) + .set("topic", topic.map(|topic| topic.as_str().to_owned())) + .set("starts_at", starts_at.map(|at| at.as_millis())) + .set( + "ends_at", + ends_at.map(|ends_at| crate::db::page::Param::OptI64(ends_at.map(|at| at.as_millis()))), + ) .ordered("starts_at", "ends_at", range_error()) .run::(db) .await @@ -99,32 +122,31 @@ pub async fn update( /// Delete the session and cascade-remove its roll-call rows, in one /// transaction: as two unbatched queries a failure between them stranded /// roll-call rows on a session that was already gone. The other half of -/// that invariant is [`crate::db::session_attendance::mark`], -/// which proves the session still exists inside its own write — a -/// transaction here cannot stop a mark that commits *after* this one. +/// that invariant is [`crate::db::session_attendance::mark`], whose +/// session-row lock makes a mark and this delete take turns — a mark +/// committing after this cascade cannot name a session that is gone. pub async fn delete(db: &Database, session: CourseSession) -> Result { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - DELETE session_attendance WHERE session = $s; - LET $before = (DELETE $s RETURN BEFORE); - RETURN $before; - COMMIT TRANSACTION;", - &[("s".into(), session.id.record().into_value())], - // No THROW of its own — an unconditional cascade, so the only - // error worth telling apart is a lost round (see - // [`crate::db::exam::delete`]). - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Read through the trailing `RETURN`, never a hand-counted slot. - let slot = result.num_statements().saturating_sub(2); - let deleted: Option = - result.take::>(slot)?.into_iter().next(); - deleted.ok_or(AppError::NotFound) + tx_with_retry(db, false, async |tx| { + // Roll-call rows first: the session row's own FK would refuse the + // delete while they exist. An empty first sweep is fine — the + // session may simply have had none. + sqlx::query!( + r#"DELETE FROM session_attendance WHERE session = $1"#, + session.id, + ) + .execute(&mut *tx) + .await?; + let deleted = sqlx::query_as!( + CourseSession, + r#"DELETE FROM course_session WHERE id = $1 + RETURNING id, course, teacher, topic, starts_at, ends_at"#, + session.id, + ) + .fetch_optional(&mut *tx) + .await?; + deleted.ok_or(AppError::NotFound) + }) + .await } #[cfg(test)] diff --git a/src/db/dietary_profile.rs b/src/db/dietary_profile.rs index 80f8ce4..7a80655 100644 --- a/src/db/dietary_profile.rs +++ b/src/db/dietary_profile.rs @@ -1,20 +1,28 @@ -//! The `dietary_profile` table: one row per student (the record key *is* -//! the student's key), created on first write and afterwards patched -//! field-by-field. The tag/note newtypes and the pure tag intersection live -//! in [`crate::domain::dietary_profile`]; the web layer reads through +//! The `dietary_profile` table: one row per student (the primary key *is* +//! the student), created on first write and afterwards patched +//! field-by-field — both by one `INSERT … ON CONFLICT DO UPDATE`. The +//! tag/note newtypes and the pure tag intersection live in +//! [`crate::domain::dietary_profile`]; the web layer reads through //! [`crate::service::dietary_profile`]. use crate::database::Database; -use crate::db::field_update::FieldUpdate; -use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryProfileId, DietaryTags}; +use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryTags}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; /// One student's profile, or `None` while the school never recorded one. -/// A single `SELECT` by record id — this is what a menu read joins on. +/// A single `SELECT` by key — this is what a menu read joins on. pub async fn read(db: &Database, student: &UserId) -> Result, AppError> { - Ok(db.select(DietaryProfileId::of(student).record()).await?) + let row = sqlx::query_as!( + DietaryProfile, + "SELECT student, tags, note, updated_by, updated_at + FROM dietary_profile WHERE student = $1", + *student, + ) + .fetch_optional(db) + .await?; + Ok(row) } /// The tags a menu read matches its dishes against: the caller's, or an @@ -27,9 +35,17 @@ pub async fn tags_of(db: &Database, student: &UserId) -> Result, App } /// Write the fields the PATCH carried. Creates the row on first write; -/// afterwards only the named fields move, because `student` is `READONLY` -/// and a whole-row save would also revert a concurrent edit of the other -/// field (see [`FieldUpdate`]). +/// afterwards only the named fields move, because a whole-row save would +/// also revert a concurrent edit of the other field. +/// +/// Both paths are one statement: an absent `tags` keeps the stored list +/// (`COALESCE`), an absent `note` keeps the stored one, a `Some(None)` note +/// clears it and a `Some(Some)` overwrites it — the same three-way shape, +/// spelled with a "was the field on the request?" flag plus its nullable +/// value. A rival `PATCH` that created the row a moment ago turns this +/// call's `INSERT` into the `DO UPDATE` arm: a plain field write after all, +/// exactly as it would have been a moment later — without the error the old +/// store's create-then-patch pair had to catch. pub async fn save( db: &Database, student: &UserId, @@ -37,37 +53,24 @@ pub async fn save( note: Option>, by: &UserId, ) -> Result { - if read(db, student).await?.is_none() { - let profile = DietaryProfile { - id: DietaryProfileId::of(student), - student: student.clone(), - tags: tags.clone().unwrap_or(DietaryTags(Vec::new())), - note: note.clone().flatten(), - updated_by: by.clone(), - updated_at: Timestamp::now(), - }; - match db.create(profile.id.record()).content(profile).await { - Ok(Some(created)) => return Ok(created), - Ok(None) => { - return Err(AppError::Internal("failed to save the profile".into())); - } - // A rival first `PATCH` created the row in the round trip since - // the read above (the `dietary_profile_student` UNIQUE index - // catches the same collision), and `CREATE` leaves that row - // untouched — so this call is a plain field write after all, - // exactly as it would have been a moment later. Propagated, it - // was a 500 on a legitimate request. Same shape as - // [`crate::db::meal_ledger::append`], which - // reads the winner back rather than failing. - Err(err) if err.is_already_exists() => {} - Err(err) => return Err(err.into()), - } - } - FieldUpdate::new(DietaryProfileId::of(student).record()) - .set("tags", tags) - .set("note", note) - .set("updated_by", Some(by.clone())) - .set("updated_at", Some(Timestamp::now())) - .run::(db) - .await + let row = sqlx::query_as!( + DietaryProfile, + "INSERT INTO dietary_profile (student, tags, note, updated_by, updated_at) + VALUES ($1, COALESCE($2, '{}'::text[]), $3, $4, $5) + ON CONFLICT (student) DO UPDATE SET + tags = COALESCE($2, dietary_profile.tags), + note = CASE WHEN $6 THEN $3 ELSE dietary_profile.note END, + updated_by = $4, + updated_at = $5 + RETURNING student, tags, note, updated_by, updated_at", + *student, + tags.map(|t| t.as_slice().to_vec()), + note.clone().flatten().map(|n| n.as_str().to_string()), + *by, + Timestamp::now(), + note.is_some(), + ) + .fetch_one(db) + .await?; + Ok(row) } diff --git a/src/db/enrollment.rs b/src/db/enrollment.rs index 7e122e2..fdffd98 100644 --- a/src/db/enrollment.rs +++ b/src/db/enrollment.rs @@ -1,49 +1,55 @@ //! The `enrollment` table: the roster read and listing, the seat-returning -//! delete, and the enroll claim — the one transaction that checks the pair -//! free, the member still a student, and the roster under capacity while it +//! delete, and the enroll claim — one transaction that checks the pair free, +//! the member still a student, and the roster under capacity while it //! spends the seat. The target-user gates the HTTP handlers pay live in //! [`crate::service::enrollment`]. -use surrealdb::types::SurrealValue; - -use crate::constant::ENROLLMENT_COUNT_FIELD; -use crate::database::{Database, transaction_with_retry}; +use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::cap; use crate::db::page::PagedList; use crate::domain::course::CourseId; -use crate::domain::enrollment::{Enrollment, EnrollmentId}; +use crate::domain::enrollment::Enrollment; use crate::domain::role::Role; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; -/// The `THROW` markers [`enroll`]'s claim aborts with: this pair -/// already holds a row, the roster is full, and the person being enrolled is no -/// longer a student. -const HELD_MARK: &str = "enroll_held"; -const FULL_MARK: &str = "enroll_full"; -const UNFIT_MARK: &str = "enroll_not_student"; +/// What [`enroll`]'s transaction settled on — the three old `THROW` markers +/// (`enroll_held`, `enroll_not_student`, `enroll_full`) as Rust verdicts. +enum Verdict { + /// This pair already holds a row. + Held, + /// The person being enrolled is no longer a student. + Unfit, + /// The roster is full — or the course is gone; the caller reads which. + Full, + /// The seat is spent and the row is written. + Made(Enrollment), +} + +/// The primary key the natural composite PK carries — the constraint name +/// that surfaces in SQLSTATE 23505 when a rival lands first. +const PAIR_CONSTRAINT: &str = "enrollment_course_user"; -/// Enroll (idempotently) `user` into `course`. One row per (course, user), -/// keyed by a deterministic composite id, so concurrent enrolls of the same -/// pair converge on one row instead of racing the unique index into a 500: -/// the loser of the `CREATE` reads the winner's row back and returns it. -/// When the course carries a capacity, a full roster refuses new members -/// (409) — the seat is taken by a single-record conditional write on the -/// course row whose bound is the row's *own* `capacity` column, read inside -/// the same statement that spends the seat. A snapshot integer taken by a -/// read beforehand would be exactly the number a concurrent capacity PATCH -/// invalidates, which is what this promised and did not do. An already -/// enrolled user is returned as-is even when the roster is full, and never -/// charged a seat. The same claim is the delete guard's other half: it -/// matches nothing once the course row is gone, and while it holds a seat -/// the course cannot be deleted — so no roster row can outlive its course. +/// Enroll (idempotently) `user` into `course`. The table's primary key *is* +/// the (course, user) pair, so concurrent enrolls of the same pair converge +/// on one row instead of racing into a 500: the loser reads the winner's row +/// back and returns it. When the course carries a capacity, a full roster +/// refuses new members (409) — the seat is taken by a single-record +/// conditional write on the course row whose bound is the row's *own* +/// `capacity` column, read inside the same statement that spends the seat. A +/// snapshot integer taken by a read beforehand would be exactly the number a +/// concurrent capacity PATCH invalidates. An already enrolled user is +/// returned as-is even when the roster is full, and never charged a seat. +/// The same claim is the delete guard's other half: it matches nothing once +/// the course row is gone, and while it holds a seat the course cannot be +/// deleted — so no roster row can outlive its course. /// -/// On admissibility ([`crate::database::transaction_with_retry`]): the -/// `CREATE` here *can* answer "already exists", but only to a rival that -/// landed inside this very window — and the re-send then sees that row at -/// the `$held` gate and takes the other branch, so the loop converges -/// instead of re-asking a settled question. Same shape, same reason, as -/// [`crate::db::class_pump::attach`]. +/// Gate order is the old THROW order: an existing pair outranks the role +/// check, which outranks a full roster. The role check takes the user row +/// `FOR NO KEY UPDATE`, the same row a demotion cascade updates before its +/// sweep, so grant and demotion serialize on the row lock in both +/// directions — a row landing after the sweep is impossible, and a demotion +/// landing before this check refuses it. pub async fn enroll( db: &Database, course: &CourseId, @@ -53,112 +59,89 @@ pub async fn enroll( if let Some(existing) = read_for_user(db, course, user).await? { return disown_if_pumped(db, existing).await; } - let enrollment = Enrollment { - id: EnrollmentId::composite(course, user), - course: course.clone(), - user: user.clone(), - enrolled_by: enrolled_by.clone(), - // Hand-placed: no source key at all is written, which is what makes - // a class sweep unable to take this row back. - source: None, + let verdict = tx_with_retry(db, false, async |tx| { + // The duplicate gate rides ahead of the role check, so "you are + // already in" still outranks everything. + let held = sqlx::query!( + r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#, + course, + user, + ) + .fetch_optional(&mut *tx) + .await?; + if held.is_some() { + return Ok(Verdict::Held); + } + // The role handshake: the live role decides, and the row lock makes + // the check and the insert one decision against a concurrent + // demotion (see the doc above). + let role = sqlx::query!( + r#"SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#, + user, + ) + .fetch_optional(&mut *tx) + .await?; + if role.map(|row| row.role).as_deref() != Some(Role::Student.as_str()) { + return Ok(Verdict::Unfit); + } + // The seat and the row in one statement (the cap recipe): a refused + // insert takes its own seat bump back; zero rows means the roster is + // full or the course is gone — only the caller pays for the read + // that tells those apart. + let row = sqlx::query_as!( + Enrollment, + r#"WITH seat AS ( + UPDATE course + SET enrollment_count = enrollment_count + 1 + WHERE id = $1 + AND enrollment_count < COALESCE(capacity, $2) + RETURNING 1) + INSERT INTO enrollment (course, app_user, enrolled_by, source) + SELECT $1, $3, $4, NULL WHERE EXISTS (SELECT 1 FROM seat) + RETURNING course, app_user AS "user", enrolled_by, source"#, + course, + cap::UNLIMITED, + user, + enrolled_by, + ) + .fetch_optional(&mut *tx) + .await?; + match row { + Some(row) => Ok(Verdict::Made(row)), + None => Ok(Verdict::Full), + } + }) + .await; + // The 23505 backstop folds into the Held verdict before the mapping: + // someone placed this pair between the gate and the insert, and their + // row is the answer — no seat was spent finding that out. + let verdict = match verdict { + Err(AppError::Db(err)) if unique_violation(&err) == Some(PAIR_CONSTRAINT) => { + Ok(Verdict::Held) + } + other => other, }; - // CREATE, not UPSERT, and in the seat's own transaction: a duplicate has - // to be *seen*, or the pair's second writer would keep the seat it - // claimed for a row that already existed and the counter would drift - // above the roster forever. - // - // Parenthesized `??` throughout: `n ?? 0 < cap` parses as - // `n ?? (0 < cap)`, which is truthy for every row and would enroll past - // the capacity. - // - // The seat is claimed on the *course*, so the student's own row is - // claimed beside it ([`cap::role_claim`]): a demotion's sweep runs on a - // snapshot, and a row landing after it would count a seat for someone - // who may not hold one, with nothing left to re-sweep. It rides between - // the duplicate gate and the seat, so "you are already in" still - // outranks it and it outranks a full roster. - let held_by = cap::role_claim( - "usr", - &format!("!= '{}'", Role::Student.as_str()), - UNFIT_MARK, - ); - let hold = held_by.join(";\n "); - let sql = format!( - "BEGIN TRANSACTION; - LET $held = (SELECT VALUE id FROM $id); - IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; - {hold}; - LET $seat = (UPDATE $course SET {ENROLLMENT_COUNT_FIELD} = \ - ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 \ - WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) < (capacity ?? $unlimited) \ - RETURN VALUE id); - IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }}; - CREATE $id CONTENT $row; - COMMIT TRANSACTION;" - ); - // The process still sends its counter writes one at a time (see - // [`cap::counter_lock`]); this statement moves the same counter every - // cap claim does. - let _guard = cap::counter_lock().await; - let (mut result, mut errors) = transaction_with_retry( - db, - &sql, - &[ - ("id".into(), enrollment.id.record().into_value()), - ("row".into(), enrollment.clone().into_value()), - ("course".into(), course.record().into_value()), - ("usr".into(), user.record().into_value()), - ("unlimited".into(), cap::UNLIMITED.into_value()), - ], - &[HELD_MARK, FULL_MARK, UNFIT_MARK], - ) - .await?; - // Someone placed this pair first; their row is the answer, and no seat - // was spent finding that out. It is read first: it outranks the refusal - // below, and the gate aborts before the seat is touched. - if errors - .values() - .any(|error| error.to_string().contains(HELD_MARK)) - { - return match read_for_user(db, course, user).await? { + match verdict { + Ok(Verdict::Made(row)) => Ok(row), + Ok(Verdict::Held) => match read_for_user(db, course, user).await? { Some(existing) => disown_if_pumped(db, existing).await, None => Err(AppError::Internal("failed to enroll user".into())), - }; - } - // Demoted while this ran: the same refusal the service's own gate makes - // a moment earlier, and the only one that can arrive after it. - if errors - .values() - .any(|error| error.to_string().contains(UNFIT_MARK)) - { - return Err(AppError::Validation(ValidationError::Invalid { + }, + // Demoted while this ran: the same refusal the service's own gate + // makes a moment earlier, and the only one that can arrive after it. + Ok(Verdict::Unfit) => Err(AppError::Validation(ValidationError::Invalid { field: "user_id", reason: "only students can be enrolled in a course", - })); - } - // Full, or the course is gone — the conditional write matches nothing - // either way, and only this path pays for the read that tells them - // apart. - if errors - .values() - .any(|error| error.to_string().contains(FULL_MARK)) - { - return match crate::db::course::read(db, course).await? { + })), + // Full, or the course is gone — the conditional write matches + // nothing either way, and only this path pays for the read that + // tells them apart. + Ok(Verdict::Full) => match crate::db::course::read(db, course).await? { Some(_) => Err(AppError::Conflict("the course is full")), None => Err(AppError::NotFound), - }; - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); + }, + Err(err) => Err(err), } - // Slots count BEGIN, two LETs and two IFs, plus the holder claim's own - // statements — counted, not tallied by hand, so a statement added there - // cannot read back the wrong result. - result - .take::>(5 + held_by.len())? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to enroll user".into())) } /// A hand enroll landing on a row a class pumped takes the row *off* the @@ -167,28 +150,30 @@ pub async fn enroll( /// holds in the other direction — a manual unenroll wins, permanently — and /// without it "hand-placed" was a state only a first enroll could reach. /// -/// `UNSET`, not `= NONE`: absence *is* the meaning of this column (see the -/// struct doc), and it is what a hand enroll writes on the create path. +/// `NULL`, not absence: the column is a nullable uuid whose NULL *is* the +/// meaning a missing key used to carry (see the struct doc), and it is what +/// a hand enroll writes on the create path too. async fn disown_if_pumped(db: &Database, existing: Enrollment) -> Result { - if existing.source.is_none() { + if existing.get_source().is_none() { return Ok(existing); } - let mut result = db - .query("UPDATE $id UNSET source RETURN AFTER") - .bind(("id", existing.id.record())) - .await? - .check()?; + let disowned = sqlx::query_as!( + Enrollment, + r#"UPDATE enrollment SET source = NULL + WHERE course = $1 AND app_user = $2 + RETURNING course, app_user AS "user", enrolled_by, source"#, + existing.get_course(), + existing.get_user(), + ) + .fetch_optional(db) + .await?; // A row that is no longer there is not an internal error: an unenroll // (or the class sweep a role change runs) landing between the read // above and this write matches nothing, and the caller asked to be // enrolled — which they were, by the row this call was handed. The // disown is all that is lost, and it is lost to a delete that took the // whole row with it. - Ok(result - .take::>(0)? - .into_iter() - .next() - .unwrap_or(existing)) + Ok(disowned.unwrap_or(existing)) } /// Some(_) iff `user` is enrolled in `course` — the grading gate. @@ -197,13 +182,16 @@ pub async fn read_for_user( course: &CourseId, user: &UserId, ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM enrollment WHERE course = $course AND user = $usr LIMIT 1") - .bind(("course", course.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + let row = sqlx::query_as!( + Enrollment, + r#"SELECT course, app_user AS "user", enrolled_by, source + FROM enrollment WHERE course = $1 AND app_user = $2"#, + course, + user, + ) + .fetch_optional(db) + .await?; + Ok(row) } pub async fn list_for_course( @@ -212,32 +200,44 @@ pub async fn list_for_course( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("enrollment WHERE course = $course", "ORDER BY id DESC") - .bind("course", course.record()) - .run(limit, offset, db) - .await + // The old composite key `{course}_{user}` sorted by user within a + // course — its course prefix was constant — so the natural-PK columns + // sort the same way. + PagedList::new( + "enrollment WHERE course = $1", + "ORDER BY course DESC, app_user DESC", + ) + .bind(course.uuid()) + .run::(limit, offset, db) + .await } +/// Take the row and give its seat back in one statement, so nothing but a +/// lost transaction can drift the counter. `None` when the pair held no row. pub async fn remove( db: &Database, course: &CourseId, user: &UserId, ) -> Result, AppError> { - // The seat comes back in the same transaction as the row that held it, - // so nothing but a lost transaction can drift the counter. - let mut result = db - .query( - "BEGIN TRANSACTION; - LET $gone = (DELETE enrollment WHERE course = $course AND user = $usr RETURN BEFORE); - UPDATE $course SET enrollment_count = math::max([(enrollment_count ?? 0) - array::len($gone), 0]); - RETURN $gone; - COMMIT TRANSACTION;", - ) - .bind(("course", course.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(3)?.into_iter().next()) + let gone = sqlx::query_as!( + Enrollment, + r#"WITH gone AS ( + DELETE FROM enrollment + WHERE course = $1 AND app_user = $2 + RETURNING course, app_user, enrolled_by, source), + seated AS ( + UPDATE course + SET enrollment_count = GREATEST( + enrollment_count - (SELECT count(*) FROM gone), 0) + WHERE id = $1 + RETURNING 1) + SELECT course, app_user AS "user", enrolled_by, source FROM gone"#, + course, + user, + ) + .fetch_optional(db) + .await?; + Ok(gone) } #[cfg(test)] diff --git a/src/db/homework.rs b/src/db/homework.rs index 4545a10..2a41c6a 100644 --- a/src/db/homework.rs +++ b/src/db/homework.rs @@ -1,25 +1,22 @@ -//! The `homework` table: row reads and listings, the count-and-create that -//! pins a homework to a live subject row, the reference-counting PATCH, and -//! the cascading delete. The PATCH's orphan guard and the audience gate live -//! in [`crate::service::homework`]. +//! The `homework` table: row reads and listings, the subject-counter claim +//! that pins a homework to a live subject row, the reference-counting PATCH — +//! whose audience-narrowing orphan guard is one transaction with the write, +//! serialized on the homework row's `FOR UPDATE` lock — and the cascading +//! delete. -use surrealdb::types::RecordId; - -use crate::constant::SUBJECT_HOMEWORK_COUNT_FIELD; -use crate::database::Database; -use crate::db::cap; -use crate::db::field_update::FieldUpdate; +use crate::database::{Database, tx_with_retry}; use crate::domain::course::CourseId; use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle}; use crate::domain::subject::SubjectId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; +use sqlx::PgConnection; /// The answer a link to a subject that is not there gets, on create and on -/// re-tag alike — both claims are conditional writes on the subject row, so a -/// subject a delete already removed matches nothing and the caller says exactly -/// what the web layer's pre-flight lookup would have. +/// re-tag alike — the conditional claim on the subject row matches nothing, +/// and the caller says exactly what the web layer's pre-flight lookup would +/// have. fn subject_gone() -> AppError { AppError::Validation(ValidationError::Invalid { field: "subject_id", @@ -27,6 +24,12 @@ fn subject_gone() -> AppError { }) } +/// What a stale re-tag answers. The shared PATCH builder +/// ([`crate::db::field_update`]) carries the same refusal; the homework PATCH +/// keeps its own copy because its orphan guard needs the row lock the generic +/// builder cannot take. +const STALE_MOVE: &str = "the link this update moves changed since it was read; re-read and retry"; + #[expect( clippy::too_many_arguments, reason = "mirrors the sibling entities' create(field, field, ..) shape" @@ -41,16 +44,14 @@ pub async fn create( assigned: Option>, created_by: &UserId, ) -> Result { - // The subject's reference is taken in the very transaction that writes - // the row — the exam question's twin - // ([`crate::db::exam_question`]): the subject delete - // is refused while this counter is non-zero, so the create and the - // delete contend on the subject record rather than on a cross-table - // count neither of them sees the other move, and a crash can no longer - // strand a claim that would make the subject undeletable forever. A - // refused claim means the subject is already gone, which is the 400 the - // web layer's pre-flight check answers with. - let counted = subject.record(); + // The subject's reference is taken in the very statement that writes the + // row — the exam question's twin ([`crate::db::exam_question`]): the + // claim (`UPDATE subject … +1`) and the insert are one CTE, so a subject + // a delete already removed matches nothing and nothing is written, which + // is the 400 the web layer's pre-flight check answers with. The subject + // delete is refused while this counter is non-zero, so the two writers + // contend on the subject row itself, and a crash cannot strand a claim + // that would make the subject undeletable forever. let homework = Homework { id: HomeworkId::generate(), course: course.clone(), @@ -62,46 +63,111 @@ pub async fn create( created_by: created_by.clone(), created_at: Timestamp::now(), }; - let id = homework.id.record(); - match cap::claim_and_create( - &counted, - SUBJECT_HOMEWORK_COUNT_FIELD, - cap::UNLIMITED, - &id, - &homework, - db, + let assigned_values = homework.assigned.clone().unwrap_or_default(); + // The fresh v7 id cannot collide, so the pair-unique answer has no rival + // here; the mapping is kept for symmetry with the other claim sites. + let created = sqlx::query_as!( + Homework, + r#"WITH seat AS ( + UPDATE subject SET homework_count = homework_count + 1 + WHERE id = $1 + RETURNING 1 + ) + INSERT INTO homework (id, course, subject, title, description, due_at, assigned, created_by, created_at) + SELECT $2, $3, $1, $4, $5, $6, $7, $8, $9 WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp""#, + subject, + homework.id, + course, + homework.title, + homework.description, + homework.due_at, + assigned_values, + homework.created_by, + homework.created_at, ) - .await? - { - cap::Claimed::Made(created) => Ok(created), - cap::Claimed::Full => Err(subject_gone()), - cap::Claimed::Duplicate => Err(AppError::Internal("failed to create homework".into())), - } + .fetch_optional(db) + .await + .map_err(|err| { + if crate::database::unique_violation(&err).is_some() { + AppError::Internal("failed to create homework".into()) + } else { + AppError::from(err) + } + })?; + created.ok_or_else(subject_gone) } pub async fn read(db: &Database, id: &HomeworkId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + Ok(sqlx::query_as!( + Homework, + r#"SELECT id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework WHERE id = $1"#, + id + ) + .fetch_optional(db) + .await?) } -/// The course's homework, newest first (ULID ids sort by creation). The web +/// The course's homework, newest first (v7 ids sort by creation). The web /// layer retains only the rows a given student `student_sees`. pub async fn list_for_course(db: &Database, course: &CourseId) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM homework WHERE course = $course ORDER BY id DESC") - .bind(("course", course.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + Homework, + r#"SELECT id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework WHERE course = $1 ORDER BY id DESC"#, + course + ) + .fetch_all(db) + .await?) } /// Every homework in the system, newest first — the manager+ view of the /// cross-course "my homework" list. pub async fn list_all(db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM homework ORDER BY id DESC") - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + Homework, + r#"SELECT id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework ORDER BY id DESC"#, + ) + .fetch_all(db) + .await?) } /// Every homework of every course in `courses`, newest first (one query) — @@ -115,51 +181,71 @@ pub async fn list_for_courses( if courses.is_empty() { return Ok(Vec::new()); } - let records: Vec = courses.iter().map(CourseId::record).collect(); - let mut result = db - .query("SELECT * FROM homework WHERE course IN $courses ORDER BY id DESC") - .bind(("courses", records)) - .await? - .check()?; - Ok(result.take::>(0)?) + let ids: Vec = courses.to_vec(); + Ok(sqlx::query_as!( + Homework, + r#"SELECT id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework WHERE course = ANY($1) ORDER BY id DESC"#, + ids + ) + .fetch_all(db) + .await?) } /// The homework of `course` that `user` is meant to see — whole-course ones /// plus any subset that names them — newest first. Backs a student's (or an /// observer's) per-course homework report; mirrors /// [`Homework::student_sees`](crate::domain::homework::Homework::student_sees) -/// in SurQL so the filter runs in the database. +/// in SQL so the filter runs in the database. pub async fn list_for_user_in_course( db: &Database, course: &CourseId, user: &UserId, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM homework - WHERE course = $course - AND (assigned = NONE OR assigned = [] OR $usr IN assigned) - ORDER BY id DESC", - ) - .bind(("course", course.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + Homework, + r#"SELECT id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework + WHERE course = $1 AND (cardinality(assigned) = 0 OR $2 = ANY(assigned)) + ORDER BY id DESC"#, + course, + user + ) + .fetch_all(db) + .await?) } /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework. /// Request-scoped: every parameter is `Option`, `None` meaning the PATCH /// did not carry that field, so it is not written at all. Handing the /// snapshot's value back instead would revert a concurrent edit of that -/// field — scoping the `SET` alone does not prevent that, the *values* must -/// come from the request. `course`, `created_by`, and `created_at` are -/// `READONLY` and never appear in the write. +/// field — under the row lock below, an uncarried field keeps the value read +/// *under that lock*, never the handler's snapshot. `course`, `created_by`, +/// and `created_at` are readonly and never appear in the write. /// -/// `description` and `assigned` are nullable columns, so they take a -/// `NONE` (clear the description / widen back to the whole course). The web -/// layer has already re-checked a new `due_at` against now, a new `subject` -/// against the course, and refused a narrowing that would orphan work. +/// `description` takes `Some(None)` to clear; `assigned` takes `Some(None)` +/// to widen back to the whole course (stored as `'{}'`, read back as `None`). +/// The web layer has already re-checked a new `due_at` against now, a new +/// `subject` against the course, and — inside the transaction here — the +/// narrowing against the work that would be orphaned by it. pub async fn update( db: &Database, homework: Homework, @@ -169,75 +255,250 @@ pub async fn update( due_at: Option, assigned: Option>>, ) -> Result { - let assigned = assigned - .map(|subset| subset.map(|users| users.iter().map(UserId::record).collect::>())); - // A re-tag moves a reference: the new subject's claim and the old one's - // release ride the same transaction as the link write, so no crash can - // leave a count without its link (the subject would be undeletable - // forever) or a link without its count. `subject` is required, so the - // snapshot's value is always the CAS expectation — two PATCHes moving - // the same homework off the same subject would otherwise both claim - // their target, and the loser is refused with a 409 instead. The - // `.refcount` call is unconditional: the CAS is armed by the request - // *carrying* `subject_id`, not by a counter moving, so a PATCH that - // re-states the tag its snapshot showed — shifting no counter at all — - // is still refused when a rival moved the tag in between. A PATCH that - // carried no `subject_id` arms nothing and writes what it always did. - let (claim, release) = subject - .as_ref() - .filter(|next| **next != homework.subject) - .map(|next| (next.record(), homework.subject.record())) - .unzip(); - FieldUpdate::new(homework.id.record()) - .set("subject", subject.map(|subject| subject.record())) - .set("title", title) - .set("description", description) - .set("due_at", due_at) - .set("assigned", assigned) - .refcount( - SUBJECT_HOMEWORK_COUNT_FIELD, - "subject", - Some(homework.subject.record()), - claim, - release, - subject_gone(), + tx_with_retry(db, false, async |tx| { + // The homework row's lock. The orphan guard's reads and the write + // below are one transaction with it, so a submission — whose own + // transaction locks this very row before writing — cannot land + // between the check and the narrowing, orphaned by an audience change + // that just missed it. The lock also replaces the old CAS's row read: + // the re-tag check below compares the handler's snapshot against the + // row as it is *locked*, not as it was first read. + let current = sqlx::query_as!( + Homework, + r#"SELECT id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework WHERE id = $1 FOR UPDATE"#, + homework.get_id() ) - .run::(db) - .await + .fetch_optional(&mut *tx) + .await? + .ok_or(AppError::NotFound)?; + + // The orphan guard runs on exactly the requests that re-scope the + // audience. An absent `assigned` writes nothing, so the stored subset + // is untouched and no narrowing can happen behind the guard's back. + if let Some(resolved) = assigned.as_ref() { + ensure_no_orphans(¤t, resolved.as_deref(), tx).await?; + } + + // A re-tag moves a reference: the new subject's claim and the old + // one's release ride the same transaction as the link write, so no + // crash can leave a count without its link (the subject would be + // undeletable forever) or a link without its count. The release goes + // first and the claim refuses on a gone row, so a move to a deleted + // subject is a rolled-back no-op — every abort takes the whole move + // back with it. + let moving = subject.as_ref().filter(|next| **next != homework.subject); + if let Some(next) = moving { + sqlx::query!( + "UPDATE subject SET homework_count = GREATEST(homework_count - 1, 0) WHERE id = $1", + current.subject + ) + .execute(&mut *tx) + .await?; + let seat = sqlx::query!( + r#"UPDATE subject SET homework_count = homework_count + 1 + WHERE id = $1 RETURNING 1 AS "seat: i32""#, + next + ) + .fetch_optional(&mut *tx) + .await?; + if seat.is_none() { + return Err(subject_gone()); + } + } + + // The stale-re-tag check. Armed by the request *carrying* the subject + // — even when it re-states the tag its snapshot showed, shifting no + // counter — so two PATCHes moving the same homework off the same + // subject cannot both claim their target: the loser's snapshot says + // A, the locked row says B, and the refusal is the 409 the generic + // PATCH builder has always answered with. + if subject.is_some() && current.subject != homework.subject { + return Err(AppError::Conflict(STALE_MOVE.to_string())); + } + + // What the PATCH carried is written; what it did not carry keeps the + // value just read under the lock. Under that lock this resolved + // full-row write is exactly the request-scoped SET the old builder + // emitted — except it is one static statement instead of a runtime + // build. + let new_subject = subject.clone().unwrap_or_else(|| current.subject.clone()); + let new_title = title.unwrap_or_else(|| current.title.clone()); + let new_description = match description { + None => current.description.clone(), + Some(None) => None, + Some(Some(text)) => Some(text), + }; + let new_due_at = due_at.unwrap_or(current.due_at); + let new_assigned = match assigned { + None => current.assigned.clone(), + // Clear = the whole course, stored as `'{}'`. + Some(None) => None, + Some(Some(subset)) => Some(subset), + }; + let assigned_values = new_assigned.unwrap_or_default(); + sqlx::query_as!( + Homework, + r#"UPDATE homework SET subject = $2, title = $3, description = $4, + due_at = $5, assigned = $6 + WHERE id = $1 + RETURNING id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp""#, + homework.get_id(), + new_subject, + new_title, + new_description, + new_due_at, + assigned_values, + ) + .fetch_optional(&mut *tx) + .await? + .ok_or(AppError::NotFound) + }) + .await +} + +/// Refuse (409) a PATCH that would narrow `homework`'s audience so a student +/// who already submitted or was graded falls outside it — their work would be +/// stranded. `new_assigned` is the proposed subset (`None` = whole course, in +/// which case no one can be orphaned). The blocking students are named in the +/// message so the teacher knows whose work to clear (or whom to keep assigned) +/// first. +/// +/// Runs inside the caller's transaction, under the homework row's lock, so +/// the check and the narrowing cannot be driven through by a submission. +async fn ensure_no_orphans( + homework: &Homework, + new_assigned: Option<&[UserId]>, + tx: &mut PgConnection, +) -> Result<(), AppError> { + // Whole-course covers everyone — no narrowing, no orphans. + let Some(subset) = new_assigned else { + return Ok(()); + }; + let submitted: Vec = sqlx::query!( + r#"SELECT app_user AS "user: UserId" FROM homework_submission WHERE homework = $1"#, + homework.get_id() + ) + .fetch_all(&mut *tx) + .await? + .into_iter() + .map(|row| row.user) + .collect(); + let graded: Vec = sqlx::query!( + r#"SELECT app_user AS "user: UserId" FROM homework_result WHERE homework = $1"#, + homework.get_id() + ) + .fetch_all(&mut *tx) + .await? + .into_iter() + .map(|row| row.user) + .collect(); + let mut blocked: Vec = Vec::new(); + for user in submitted.iter().chain(graded.iter()) { + let key = user.key().to_string(); + if !subset.contains(user) && !blocked.contains(&key) { + blocked.push(key); + } + } + if blocked.is_empty() { + Ok(()) + } else { + Err(AppError::ConflictOwned(format!( + "narrowing the assigned list would orphan existing work by {} student(s): {}", + blocked.len(), + blocked.join(", ") + ))) + } } /// Delete the homework and cascade its submissions, their files, and its /// results — one transaction, so a crash can't orphan a submission under a /// vanished homework. The submission file *blobs* are the web layer's to -/// unlink: it collects their names via -/// [`crate::db::homework_file::file_keys_for_homework`] -/// before calling this, and removes them after the rows are gone. -pub async fn delete(db: &Database, homework: Homework) -> Result { - let mut result = db - .query( - format!( - "BEGIN TRANSACTION; - DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw); - DELETE homework_submission WHERE homework = $hw; - DELETE homework_result WHERE homework = $hw; - LET $gone = (DELETE $hw RETURN BEFORE); - FOR $sub IN ($gone.subject ?? []) {{ - UPDATE $sub SET {SUBJECT_HOMEWORK_COUNT_FIELD} = - math::max([({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) - 1, 0]) - }}; - RETURN $gone; - COMMIT TRANSACTION;" - ), +/// unlink: their names are returned (collected inside the transaction, +/// before the wipes — a file row inserted after an out-of-transaction +/// collection would be deleted here while its key was already gone from the +/// list, stranding the blob) and removed after the rows are gone. +pub async fn delete( + db: &Database, + homework: Homework, +) -> Result<(Homework, Vec), AppError> { + tx_with_retry(db, true, async |tx| { + let blob_keys: Vec = sqlx::query!( + r#"SELECT file FROM homework_file + WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#, + homework.get_id() ) - .bind(("hw", homework.id.record())) + .fetch_all(&mut *tx) .await? - .check()?; - // The subject's reference is given back in this same transaction, off - // what the delete actually removed. Read through the trailing `RETURN`, - // not a hand-counted slot — see [`crate::db::exam::delete`]. - let slot = result.num_statements().saturating_sub(2); - let deleted: Option = result.take::>(slot)?.into_iter().next(); - deleted.ok_or(AppError::NotFound) + .into_iter() + .map(|row| row.file) + .collect(); + sqlx::query!( + r#"DELETE FROM homework_file + WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#, + homework.get_id() + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "DELETE FROM homework_result WHERE homework = $1", + homework.get_id() + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "DELETE FROM homework_submission WHERE homework = $1", + homework.get_id() + ) + .execute(&mut *tx) + .await?; + let deleted = sqlx::query_as!( + Homework, + r#"DELETE FROM homework WHERE id = $1 + RETURNING id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: Option", + due_at AS "due_at: Timestamp", + CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END + AS "assigned: Option>", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp""#, + homework.get_id() + ) + .fetch_optional(&mut *tx) + .await? + .ok_or(AppError::NotFound)?; + // The subject's reference is given back in this same transaction, off + // the row the delete actually removed. + sqlx::query!( + "UPDATE subject SET homework_count = GREATEST(homework_count - 1, 0) WHERE id = $1", + deleted.subject + ) + .execute(&mut *tx) + .await?; + Ok((deleted, blob_keys)) + }) + .await } #[cfg(test)] @@ -360,7 +621,10 @@ mod tests { "the old subject is free" ); assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); - assert!(crate::db::subject::delete(&db, from).await.is_ok(), "no reference left"); + assert!( + crate::db::subject::delete(&db, from).await.is_ok(), + "no reference left" + ); assert!( crate::db::subject::delete(&db, to).await.is_err(), "the reference moved here refuses the delete" diff --git a/src/db/homework_file.rs b/src/db/homework_file.rs index 3e9669a..2ab6a5c 100644 --- a/src/db/homework_file.rs +++ b/src/db/homework_file.rs @@ -4,56 +4,70 @@ //! their validated fields live in [`crate::domain::homework_file`]; the //! upload workflow around them in [`crate::service::homework_file`]. -use surrealdb::types::SurrealValue; - -use crate::constant::{ - MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD, SUBMISSION_OPEN_GUARD, -}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; +use crate::constant::MAX_HOMEWORK_FILES_PER_SUBMISSION; +use crate::database::{Database, tx_with_retry}; use crate::domain::course::CourseId; use crate::domain::homework::HomeworkId; use crate::domain::homework_file::HomeworkFile; +use crate::domain::homework_file::HomeworkFileId; +use crate::domain::homework_submission::HomeworkSubmissionId; +use crate::domain::note_file::{FileContentType, FileName}; use crate::domain::timestamp::Timestamp; use crate::error::AppError; -/// What [`delete`]'s transaction reports: whether the submission -/// was still open (`open` = 1, the gate bit) and the row it then removed. Two -/// answers in one object because an empty `gone` alone cannot say whether the -/// delete was refused or the file had simply vanished. -#[derive(Debug, SurrealValue)] -struct DeleteOutcome { - open: i64, - gone: Vec, -} - /// Persist the row assembled by /// [`HomeworkFile::new`](crate::domain::homework_file::HomeworkFile::new), /// refusing once its submission already holds /// [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`) /// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own -/// wording). Both are decided by one [`cap::claim_when_and_create`] on the -/// submission row — the seat and the file row commit together, so a crash -/// between them can no longer leave a slot claimed by a file that does not -/// exist, and a losing upload never has to be un-counted. Which of the two -/// conditions refused it is read back afterwards, off the losing path only, -/// and only to pick the message: `Claimed::Full` says "full *or* graded *or* -/// the submission is gone". +/// wording). Both are decided by one guarded insert on the submission row — +/// the seat (`UPDATE … file_count + 1 WHERE file_count < $cap AND +/// graded_by_result IS NULL`) and the file row commit together in one CTE, so +/// a crash between them can no longer leave a slot claimed by a file that +/// does not exist, and a losing upload never has to be un-counted. Which of +/// the two conditions refused it is read back afterwards, off the losing +/// path only, and only to pick the message: zero rows says "full *or* graded +/// *or* the submission is gone". pub async fn insert(db: &Database, file: HomeworkFile) -> Result, AppError> { - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber - match cap::claim_when_and_create( - &file.submission.record(), - SUBMISSION_FILE_COUNT_FIELD, + let created = sqlx::query_as!( + HomeworkFile, + r#"WITH seat AS ( + UPDATE homework_submission SET file_count = file_count + 1 + WHERE id = $2 AND file_count < $1 AND graded_by_result IS NULL + RETURNING 1 + ) + INSERT INTO homework_file (id, submission, name, content_type, size, file, created_at) + SELECT $3, $2, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id AS "id: HomeworkFileId", + submission AS "submission: HomeworkSubmissionId", + name AS "name: FileName", + content_type AS "content_type: FileContentType", + size, + file, + created_at AS "created_at: Timestamp""#, MAX_HOMEWORK_FILES_PER_SUBMISSION as i64, - SUBMISSION_OPEN_GUARD, - &file.id.record(), - &file, - db, + file.submission, + file.id, + file.name, + file.content_type, + file.size, + file.file, + file.created_at, ) - .await? - { - cap::Claimed::Made(created) => Ok(Some(created)), - cap::Claimed::Full => { + .fetch_optional(db) + .await + .map_err(|err| { + // The id is a fresh v7 minted by `new`, so a row already holding it + // is a collision, not a re-upload. + if crate::database::unique_violation(&err).is_some() { + AppError::Internal("homework file id collided".into()) + } else { + AppError::from(err) + } + })?; + match created { + Some(row) => Ok(Some(row)), + None => { if super::homework_submission::is_graded(db, &file.submission).await? { return Ok(None); } @@ -61,9 +75,6 @@ pub async fn insert(db: &Database, file: HomeworkFile) -> Result Err(AppError::Internal("homework file id collided".into())), } } @@ -74,8 +85,21 @@ pub async fn read_for( id: &crate::domain::homework_file::HomeworkFileId, submission: &crate::domain::homework_submission::HomeworkSubmissionId, ) -> Result, AppError> { - let file: Option = db.select(id.record()).await?; - Ok(file.filter(|file| &file.submission == submission)) + Ok(sqlx::query_as!( + HomeworkFile, + r#"SELECT id AS "id: HomeworkFileId", + submission AS "submission: HomeworkSubmissionId", + name AS "name: FileName", + content_type AS "content_type: FileContentType", + size, + file, + created_at AS "created_at: Timestamp" + FROM homework_file WHERE id = $1 AND submission = $2"#, + id, + submission + ) + .fetch_optional(db) + .await?) } /// Read a file by id only if it hangs off a submission to `homework` — the @@ -89,16 +113,23 @@ pub async fn read_in_homework( id: &crate::domain::homework_file::HomeworkFileId, homework: &HomeworkId, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM homework_file WHERE id = $id AND submission IN \ - (SELECT VALUE id FROM homework_submission WHERE homework = $hw)", - ) - .bind(("id", id.record())) - .bind(("hw", homework.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + Ok(sqlx::query_as!( + HomeworkFile, + r#"SELECT id AS "id: HomeworkFileId", + submission AS "submission: HomeworkSubmissionId", + name AS "name: FileName", + content_type AS "content_type: FileContentType", + size, + file, + created_at AS "created_at: Timestamp" + FROM homework_file + WHERE id = $1 + AND submission IN (SELECT id FROM homework_submission WHERE homework = $2)"#, + id, + homework + ) + .fetch_optional(db) + .await?) } /// All of `submission`'s files, newest first. @@ -106,40 +137,56 @@ pub async fn list_for_submission( db: &Database, submission: &crate::domain::homework_submission::HomeworkSubmissionId, ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM homework_file WHERE submission = $sub ORDER BY id DESC") - .bind(("sub", submission.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + HomeworkFile, + r#"SELECT id AS "id: HomeworkFileId", + submission AS "submission: HomeworkSubmissionId", + name AS "name: FileName", + content_type AS "content_type: FileContentType", + size, + file, + created_at AS "created_at: Timestamp" + FROM homework_file WHERE submission = $1 ORDER BY id DESC"#, + submission + ) + .fetch_all(db) + .await?) } -/// How many files `submission` holds — the cap check reads this under the -/// lock. Counting via the rows (not a `count()` query) keeps it identical -/// to `NoteFile`'s proven cap check; at a ceiling of 10 the cost is nil. +/// How many files `submission` holds. Counting the rows (not the counter +/// column) keeps it identical to `NoteFile`'s proven cap check; at a ceiling +/// of 10 the cost is nil. pub async fn count_for_submission( db: &Database, submission: &crate::domain::homework_submission::HomeworkSubmissionId, ) -> Result { - Ok(list_for_submission(db, submission).await?.len()) + let row = sqlx::query!( + r#"SELECT count(*) AS "count: i64" FROM homework_file WHERE submission = $1"#, + submission + ) + .fetch_one(db) + .await?; + Ok(row.count as usize) } /// The blob names behind every file of every submission to `homework` — -/// collected *before* the homework-delete cascade wipes the rows, so the -/// web layer can unlink them once the rows are gone. +/// the GC keys of a homework delete (collected inside the delete's own +/// transaction by [`crate::db::homework::delete`]; this read backs it and +/// the tests). pub async fn file_keys_for_homework( db: &Database, homework: &HomeworkId, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT VALUE file FROM homework_file \ - WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw)", - ) - .bind(("hw", homework.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query!( + r#"SELECT file FROM homework_file + WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#, + homework + ) + .fetch_all(db) + .await? + .into_iter() + .map(|row| row.file) + .collect()) } /// The blob names behind every homework file of `course` — collected @@ -148,17 +195,19 @@ pub async fn file_keys_for_course( db: &Database, course: &CourseId, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT VALUE file FROM homework_file WHERE submission IN ( \ - SELECT VALUE id FROM homework_submission \ - WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course) \ - )", - ) - .bind(("course", course.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query!( + r#"SELECT file FROM homework_file + WHERE submission IN ( + SELECT id FROM homework_submission + WHERE homework IN (SELECT id FROM homework WHERE course = $1) + )"#, + course + ) + .fetch_all(db) + .await? + .into_iter() + .map(|row| row.file) + .collect()) } /// Delete the row and give its slot back in the same transaction. The @@ -167,57 +216,58 @@ pub async fn file_keys_for_course( /// /// The gate is the first statement: a conditional write on the *submission* /// row — the "last touched" re-stamp a file delete owes the late flag -/// anyway — carrying [`SUBMISSION_OPEN_GUARD`]. Nothing else in the -/// transaction runs unless it bit, so a grade landing concurrently either -/// stamps first (this delete is refused, `Ok(None)`) or stamps after (the -/// file was already gone when it graded). `Err(NotFound)` still means the -/// file row itself had vanished. -/// -/// Sound to re-send while the store answers "conflict, retry", and it has -/// to be: the gate writes the *submission* row, the very record an upload's -/// [`insert`] claims its seat on, and both handlers hold only -/// `HOMEWORK_LOCK.read()` — so a concurrent add and delete of two files of -/// one submission contend by design, and a lost round used to come back as -/// a 500 on a request that had written nothing. Only `UPDATE` and `DELETE` -/// are in the batch, and neither can legitimately answer "already exists", -/// which is what makes the whole of it re-sendable. +/// anyway. Its row lock is also the serialization point against an upload's +/// seat claim on the same row: one of the two waits, and the winner re-reads +/// the counter before moving it, so no lost round and no 500 — a grade +/// landing concurrently either stamps first (this delete is refused, +/// `Ok(None)`) or stamps after (the file was already gone when it graded). +/// `Err(NotFound)` still means the file row itself had vanished. pub async fn delete(db: &Database, file: HomeworkFile) -> Result, AppError> { - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $open = (UPDATE $sub SET updated_at = $now \ - WHERE {SUBMISSION_OPEN_GUARD} RETURN VALUE id); - LET $gone = IF array::len($open) > 0 {{ (DELETE $id RETURN BEFORE) }} ELSE {{ [] }}; - UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); - RETURN {{ open: array::len($open), gone: $gone }}; - COMMIT TRANSACTION;" - ), - &[ - ("id".into(), file.id.record().into_value()), - ("sub".into(), file.submission.record().into_value()), - ("now".into(), Timestamp::now().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // BEGIN is slot 0, the two LETs slots 1-2 and the counter fix slot 3; - // the RETURN is slot 4. - let outcome: Option = result.take::>(4)?.into_iter().next(); - let outcome = - outcome.ok_or_else(|| AppError::Internal("failed to delete homework file".into()))?; - if outcome.open == 0 { - return Ok(None); - } - outcome - .gone - .into_iter() - .next() - .map(Some) - .ok_or(AppError::NotFound) + let now = Timestamp::now(); + tx_with_retry(db, false, async |tx| { + let open = sqlx::query!( + r#"UPDATE homework_submission SET updated_at = $2 + WHERE id = $1 AND graded_by_result IS NULL + RETURNING 1 AS "open: i32""#, + file.submission, + now + ) + .fetch_optional(&mut *tx) + .await?; + if open.is_none() { + return Ok(None); + } + let gone = sqlx::query_as!( + HomeworkFile, + r#"DELETE FROM homework_file WHERE id = $1 AND submission = $2 + RETURNING id AS "id: HomeworkFileId", + submission AS "submission: HomeworkSubmissionId", + name AS "name: FileName", + content_type AS "content_type: FileContentType", + size, + file, + created_at AS "created_at: Timestamp""#, + file.id, + file.submission + ) + .fetch_optional(&mut *tx) + .await?; + match gone { + Some(row) => { + sqlx::query!( + "UPDATE homework_submission SET file_count = GREATEST(file_count - 1, 0) + WHERE id = $1", + file.submission + ) + .execute(&mut *tx) + .await?; + Ok(Some(row)) + } + // The submission was open but the file had already vanished. + None => Err(AppError::NotFound), + } + }) + .await } #[cfg(test)] diff --git a/src/db/homework_result.rs b/src/db/homework_result.rs index 27b9e16..944a2de 100644 --- a/src/db/homework_result.rs +++ b/src/db/homework_result.rs @@ -5,48 +5,51 @@ //! validated status and mark types in //! [`crate::domain::homework_result`]. -use crate::constant::{MARKS_GIVEN_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD}; -use crate::database::{Database, transaction_with_retry}; +use crate::database::{Database, tx_with_retry}; use crate::domain::course::CourseId; use crate::domain::exam_result::Mark; use crate::domain::homework::HomeworkId; use crate::domain::homework_result::{HomeworkResult, HomeworkResultId, HomeworkStatus}; -use crate::domain::homework_submission::HomeworkSubmissionId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; -use surrealdb::types::SurrealValue; -/// Record (or overwrite) the grade for (homework, user). One row per pair, -/// keyed by the deterministic composite id, so this is a single atomic -/// UPSERT — concurrent grades for the same pair converge on one row instead -/// of racing a unique index into a 500. Grading before the due date, or -/// before any submission exists, is allowed (the caller's policy call). +/// Record (or overwrite) the grade for (homework, user). One row per pair by +/// the pair's UNIQUE constraint, so grading is one atomic UPSERT — +/// concurrent grades for the same pair converge on one row instead of +/// racing a duplicate into a 500. Grading before the due date, or before any +/// submission exists, is allowed (the caller's policy call). /// /// In the same transaction the grade *stamps* the student's submission -/// ([`crate::constant::SUBMISSION_GRADED_FIELD`]), which is what freezes it: -/// every student-side write to that row then fails its own -/// `graded_by_result = NONE` condition, with no cross-table read for a -/// concurrent write to slip past. A submission that does not exist yet is -/// left alone — grading absent work must not conjure a hand-in (the report reads -/// `submitted`/`missing`/`late` straight off that row). +/// (`graded_by_result`), which is what freezes it: every student-side write +/// to that row then fails its own `graded_by_result IS NULL` condition, with +/// no cross-table read for a concurrent write to slip past. A submission +/// that does not exist yet is left alone — grading absent work must not +/// conjure a hand-in (the report reads `submitted`/`missing`/`late` straight +/// off that row). /// -/// That one case is where this function stops defending itself: a student's +/// That one case is where this statement stops defending itself: a student's /// *first* hand-in committing between this grade and nothing-to-stamp would -/// land unstamped, leaving a grade beside an editable submission. Nothing -/// here forbids it — what forbids it is the caller. Grading holds -/// `HOMEWORK_LOCK` (see [`crate::service::homework`]) for writing across this -/// whole transaction while every student-side write holds it for reading across -/// its own, and the two leases are mutually exclusive in the one process -/// this backend runs as, so the interleaving never gets a window. -// -// corner-cut: that makes the freeze depend on lock discipline at the call -// sites, not on this row. Moving a student write's lease to *after* its -// database write — or sharding HOMEWORK_LOCK per homework — reopens the -// window with nothing to catch it. Closing it in the db layer needs a -// record both sides own (a per-(homework, user) row the grade can always -// stamp); a tombstone submission is not it, since every read path would -// have to learn to ignore it and one missed filter fabricates a hand-in. +/// land unstamped, leaving a grade beside an editable submission. What +/// forbids it here is the homework row's lock: every student-side write +/// locks the homework row across its write, and so does this transaction, so +/// the interleaving is ordered away instead of leased away — either the +/// grade saw the row to stamp, or the submission saw no grade and created +/// under a lock this transaction already held. +/// +/// Whether the pair was already graded is read one statement ahead of the +/// write, under the same lock — it is what keeps a regrade from crediting +/// the grader a second time. No mark counter here: a homework mark is +/// optional and most grades are status-only, so `high_mark` is an exam-only +/// family. +/// +/// The homework row's `FOR UPDATE` is also the parent gate: the id is minted +/// fresh, so a grade landing inside a homework (or course) delete's window +/// would otherwise *re-create* a result row under a homework that is gone, +/// readable ever after at `GET /homework/{id}/result` (no existence check +/// there) with a `marks_given_total` no ungrade can reach, because every +/// route to the grade goes through the homework. A vanished row answers +/// `Err(NotFound)` — the 404 the web layer's own lookup would have answered. pub async fn grade( db: &Database, homework: &HomeworkId, @@ -55,102 +58,73 @@ pub async fn grade( mark: Option, graded_by: &UserId, ) -> Result { - let id = HomeworkResultId::composite(homework, user); - let submission = HomeworkSubmissionId::composite(homework, user); - let result = HomeworkResult { - id: id.clone(), - homework: homework.clone(), - user: user.clone(), - status, - mark, - graded_by: graded_by.clone(), - created_at: Timestamp::now(), - }; - // Whether the pair was already graded is read one statement ahead of - // the write, inside the same transaction — it is what keeps a regrade - // from crediting the grader a second time. No mark counter here: a - // homework mark is optional and most grades are status-only, so - // `high_mark` is an exam-only family. - // - // The first three statements are the parent gate, the twin of - // [`crate::db::homework_submission::upsert`]'s - // and written the same way on purpose: the id is deterministic, so a - // grade landing inside a homework (or course) delete's window does not - // fail — it *re-creates* a result row under a homework that is gone, - // readable ever after at `GET /homework/{id}/result` (no existence check - // there) with a `marks_given_total` no ungrade can reach, because every - // route to the grade goes through the homework. Reading the homework - // first — which the web layer does, under the lease — cannot close that: - // the store conflict-checks write sets, not read sets. So the gate - // *moves* a value on the homework row (`due_at` up by one and straight - // back to the captured value, leaving the row byte-identical) and the - // cascade's delete of that same row is what refuses it. `homework` owns - // no counter column and is SCHEMAFULL, so `due_at` is the one `int` it - // already has; do not invent a second spelling. - // - // Not [`crate::db::cap::touch_and_create`], which is the same shape - // for a bare `CREATE`: a grade is an UPSERT (a regrade must overwrite), - // and the freeze stamp and the grader's counter have to ride the same - // transaction, which that helper has no room for. - // - // Sound to re-send, which is what the gate needed first — a `THROW` - // inside a plain `db.query` would have turned every lost round into a - // 500. `SELECT`, `UPDATE` and the `IF`/`THROW` can never answer "already - // exists", and the `UPSERT`'s id is bijective with the (homework, user) - // pair the table keys, on a table whose only index is non-unique - // (`homework_result_homework`), so its index entry can only ever point - // at the row the id already names: it resolves onto that row instead of - // colliding with it. A lost round wrote nothing. - let (mut saved, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $was_due = (SELECT VALUE due_at FROM ONLY $hw); - LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id); - IF array::len($alive) = 0 {{ THROW 'no_homework' }}; - UPDATE $hw SET due_at = $was_due; - LET $before = (SELECT VALUE id FROM ONLY $id); - LET $after = (UPSERT $id CONTENT $row RETURN AFTER); - UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = $id \ - WHERE {SUBMISSION_OPEN_GUARD}; - IF $before = NONE {{ - UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = - ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1 - }}; - RETURN $after; - COMMIT TRANSACTION;" - ), - &[ - ("hw".into(), homework.record().into_value()), - ("id".into(), id.record().into_value()), - ("sub".into(), submission.record().into_value()), - ("grader".into(), graded_by.record().into_value()), - ("row".into(), result.into_value()), - ], - &["no_homework"], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_homework")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`, - // so its slot follows the statement count instead of a hand-kept - // number — which the gate above would otherwise have shifted, silently - // handing back something else. - let slot = saved.num_statements().saturating_sub(2); - saved - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to record homework result".into())) + let id = HomeworkResultId::generate(); + let now = Timestamp::now(); + tx_with_retry(db, false, async |tx| { + let alive = sqlx::query!( + r#"SELECT 1 AS "row: i32" FROM homework WHERE id = $1 FOR UPDATE"#, + homework + ) + .fetch_optional(&mut *tx) + .await?; + if alive.is_none() { + return Err(AppError::NotFound); + } + let before = sqlx::query!( + r#"SELECT 1 AS "row: i32" FROM homework_result + WHERE homework = $1 AND app_user = $2 FOR UPDATE"#, + homework, + user + ) + .fetch_optional(&mut *tx) + .await? + .is_some(); + // A regrade overwrites status, mark, grader and stamp — `id` and + // `homework`/`app_user` are the row's identity and stay. + let graded = sqlx::query_as!( + HomeworkResult, + r#"INSERT INTO homework_result (id, homework, app_user, status, mark, graded_by, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7) + ON CONFLICT (homework, app_user) DO UPDATE + SET status = EXCLUDED.status, mark = EXCLUDED.mark, + graded_by = EXCLUDED.graded_by, created_at = EXCLUDED.created_at + RETURNING id AS "id: HomeworkResultId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + status AS "status: HomeworkStatus", + mark AS "mark: Option", + graded_by AS "graded_by: UserId", + created_at AS "created_at: Timestamp""#, + id, + homework, + user, + status, + mark, + graded_by, + now, + ) + .fetch_one(&mut *tx) + .await?; + sqlx::query!( + r#"UPDATE homework_submission SET graded_by_result = $3 + WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL"#, + homework, + user, + graded.id + ) + .execute(&mut *tx) + .await?; + if !before { + sqlx::query!( + "UPDATE app_user SET marks_given_total = marks_given_total + 1 WHERE id = $1", + graded_by + ) + .execute(&mut *tx) + .await?; + } + Ok(graded) + }) + .await } /// `user`'s grade for `homework`, if graded. @@ -159,9 +133,21 @@ pub async fn read_for( homework: &HomeworkId, user: &UserId, ) -> Result, AppError> { - Ok(db - .select(HomeworkResultId::composite(homework, user).record()) - .await?) + Ok(sqlx::query_as!( + HomeworkResult, + r#"SELECT id AS "id: HomeworkResultId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + status AS "status: HomeworkStatus", + mark AS "mark: Option", + graded_by AS "graded_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework_result WHERE homework = $1 AND app_user = $2"#, + homework, + user + ) + .fetch_optional(db) + .await?) } /// Every grade for `homework` — the roster joins these onto the submissions. @@ -169,12 +155,20 @@ pub async fn list_for_homework( db: &Database, homework: &HomeworkId, ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM homework_result WHERE homework = $hw ORDER BY id DESC") - .bind(("hw", homework.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + HomeworkResult, + r#"SELECT id AS "id: HomeworkResultId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + status AS "status: HomeworkStatus", + mark AS "mark: Option", + graded_by AS "graded_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework_result WHERE homework = $1 ORDER BY id DESC"#, + homework + ) + .fetch_all(db) + .await?) } /// `user`'s homework grades across one course — the raw rows behind the @@ -185,17 +179,24 @@ pub async fn list_for_user_in_course( course: &CourseId, user: &UserId, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM homework_result WHERE user = $usr - AND homework IN (SELECT VALUE id FROM homework WHERE course = $course) - ORDER BY id DESC", - ) - .bind(("usr", user.record())) - .bind(("course", course.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + HomeworkResult, + r#"SELECT id AS "id: HomeworkResultId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + status AS "status: HomeworkStatus", + mark AS "mark: Option", + graded_by AS "graded_by: UserId", + created_at AS "created_at: Timestamp" + FROM homework_result + WHERE app_user = $1 + AND homework IN (SELECT id FROM homework WHERE course = $2) + ORDER BY id DESC"#, + user, + course + ) + .fetch_all(db) + .await?) } /// Un-grade (homework, user), returning the removed row (`None` if there @@ -212,53 +213,70 @@ pub async fn list_for_user_in_course( /// submission behind it — permanently, since an award is never revoked. /// Given back to the *removed row's own* grader, not the caller: a manager /// may un-grade what a teacher graded, and the credit is the teacher's. -/// -/// Sound to re-send while the store answers "conflict, retry" — this is the -/// upgrade `grade` still wants, taken here because the counter above is what -/// makes it necessary: the grader's row is written by exam grading too, so -/// the delete now contends with another domain, and only `DELETE`/`UPDATE` -/// are in the batch, none of which can legitimately answer "already exists". pub async fn remove( db: &Database, homework: &HomeworkId, user: &UserId, ) -> Result, AppError> { - let id = HomeworkResultId::composite(homework, user); - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $gone = (DELETE $id RETURN BEFORE); - UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = NONE \ - WHERE {SUBMISSION_GRADED_FIELD} = $id; - IF array::len($gone) > 0 {{ - LET $grader = $gone[0].graded_by; - UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = - math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0]) - }}; - RETURN $gone; - COMMIT TRANSACTION;" - ), - &[ - ("id".into(), id.record().into_value()), - ( - "sub".into(), - HomeworkSubmissionId::composite(homework, user) - .record() - .into_value(), - ), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`, so - // its slot follows the statement count — the hand-kept "slot 1" this - // replaces was one added statement away from handing back the unstamp. - let slot = result.num_statements().saturating_sub(2); - Ok(result.take::>(slot)?.into_iter().next()) + tx_with_retry(db, false, async |tx| { + // The homework row's lock orders this against a concurrent grade + // (which locks the same row before inserting): either this delete + // wins and the re-grade lands after as a fresh grade, or the grade + // lands first and this removes *it*. A homework already cascaded + // away left no result rows behind — `None`, the 404 the web layer + // answers. + let alive = sqlx::query!( + r#"SELECT 1 AS "row: i32" FROM homework WHERE id = $1 FOR UPDATE"#, + homework + ) + .fetch_optional(&mut *tx) + .await?; + if alive.is_none() { + return Ok(None); + } + let gone = sqlx::query!( + r#"DELETE FROM homework_result WHERE homework = $1 AND app_user = $2 + RETURNING id AS "id: HomeworkResultId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + status AS "status: HomeworkStatus", + mark AS "mark: Option", + graded_by AS "graded_by: UserId", + created_at AS "created_at: Timestamp""#, + homework, + user + ) + .fetch_optional(&mut *tx) + .await?; + let Some(removed) = gone else { + return Ok(None); + }; + sqlx::query!( + r#"UPDATE homework_submission SET graded_by_result = NULL + WHERE homework = $1 AND app_user = $2 AND graded_by_result = $3"#, + homework, + user, + removed.id + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "UPDATE app_user SET marks_given_total = GREATEST(marks_given_total - 1, 0) WHERE id = $1", + removed.graded_by + ) + .execute(&mut *tx) + .await?; + Ok(Some(HomeworkResult { + id: removed.id, + homework: removed.homework, + user: removed.user, + status: removed.status, + mark: removed.mark, + graded_by: removed.graded_by, + created_at: removed.created_at, + })) + }) + .await } #[cfg(test)] diff --git a/src/db/homework_submission.rs b/src/db/homework_submission.rs index ff447a4..f80d4ba 100644 --- a/src/db/homework_submission.rs +++ b/src/db/homework_submission.rs @@ -5,186 +5,217 @@ //! [`crate::service::homework_submission`]; the validated text type in //! [`crate::domain::homework_submission`]. -use crate::constant::{ - HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMITTED_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, - SUBMISSION_OPEN_GUARD, -}; -use crate::database::{Database, transaction_with_retry}; +use crate::database::{Database, tx_with_retry}; use crate::domain::homework::Homework; +use crate::domain::homework::HomeworkId; use crate::domain::homework_submission::{ HomeworkSubmission, HomeworkSubmissionId, SubmissionText, }; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; -use surrealdb::types::SurrealValue; /// Create or re-stamp `user`'s submission to `homework`, unless a grade has /// frozen it — `None` means frozen, and the caller answers 409. `updated_at` -/// moves to now every time; `submitted_at` (readonly, the first-submit stamp) -/// is kept on an existing row and set only on a fresh one. +/// moves to now every time; `submitted_at` (the first-submit stamp) is kept +/// on an existing row and set only on a fresh one. Returns the row plus +/// whether it existed before this call (the web layer's 200-vs-201, and the +/// only-a-first-hand-in-earns-badges rule). /// -/// Hand-written rather than `.content()` on purpose: `.content()` re-sends -/// the whole row, so it would carry a `submitted_at`, and any value differing -/// from the stored one trips the readonly guard. The -/// `submitted_at = submitted_at ?? $now` expression preserves it inside the -/// one UPSERT statement — race-free without a lock, where a read-then-content -/// could let two concurrent first-submits pick different stamps and 500. +/// `preserve_text` is the photo-upload auto-create's switch: an existing row +/// keeps its text (and its stamp moves, as any touch), because the upload +/// never offered a text to replace it. A submit passes `false` — an absent +/// text clears, as on the wire. /// -/// The `WHERE` is the freeze: [`SUBMISSION_OPEN_GUARD`] makes "not graded -/// yet" a condition of this very write instead of a read a concurrent grade -/// can land behind. An absent row satisfies it (the stamp is `NONE` there -/// too), so a first submit still creates. +/// The `graded_by_result IS NULL` predicate is the freeze: "not graded yet" +/// is a condition of the write itself, so a refused write answers `None` +/// instead of wiping graded work. An absent row satisfies it trivially, so a +/// first submit still creates. /// /// The badge counters on the student's user row move in this very -/// transaction, and the order is load-bearing: the increment sits *after* -/// the UPSERT and is conditional on it having matched a row, because a -/// frozen row makes that `WHERE` match nothing **silently** (unlike -/// [`crate::db::homework_result::grade`], which `THROW`s) — put -/// first, it would count a submission the freeze refused. `$before = NONE` -/// keeps it to a genuine first create, so an edit moves neither counter, -/// which is what makes the live count mean the same thing the one-time -/// backfill seeded (one per row; on time judged against `due_at`, equal -/// counting as on time). +/// transaction, and only on the create arm — an edit moves neither counter, +/// which is what makes the live count mean one per row. /// -/// `counted_on_time` is stamped on the row from the *same* `$on_time` -/// expression the increment adds, in the same statement block: the deadline -/// is mutable, so a withdrawal that re-judged it against the live `due_at` -/// gave back something other than what was taken. Writing the verdict beside -/// the counter is what keeps the two from ever disagreeing — read back by +/// `counted_on_time` is stamped on the row from the same `on_time` verdict +/// the increment adds, in the same transaction: the deadline is mutable, so +/// a withdrawal that re-judged it against the live `due_at` gave back +/// something other than what was taken. Writing the verdict beside the +/// counter is what keeps the two from ever disagreeing — read back by /// [`delete`], never re-derived. /// -/// That deadline is `$was_due`, the one the gate below already read *inside -/// this transaction* — never the caller's [`Homework`] snapshot, which was -/// read before the lease and is exactly one `PATCH due_at` old in the -/// "teacher extends the deadline at 23:59 while the class submits" moment. -/// Judging on the snapshot stored a verdict the web layer's own `late` flag -/// (`updated_at > due_at`, re-derived live on every read) then contradicted -/// forever, in both directions. An in-process lock cannot fix this — it -/// orders two handlers, not two store transactions — so the comparison has -/// to live where the write does. The whole entity is still taken (both -/// callers hold the row, and the id comes off it); its `due_at` must not be. -/// -/// The first three statements are the parent gate, and they are why this -/// write cannot outlive its homework: the id is deterministic, so nothing -/// else here would fail against a homework a cascade already removed — it -/// would simply re-create the row, badge counters and all, unreachable ever -/// after (every route to a submission goes through its homework). A *read* -/// of the homework does not close that, on either side of the call: the -/// store does no read-set conflict detection, so a delete committing -/// alongside is invisible to it. The gate therefore *moves* a value on the -/// homework row — `due_at` up by one and straight back to the captured -/// value, so the row is byte-identical afterwards — because only a write -/// collides, and `SET x = x` is elided and never reaches the write set. It -/// is [`crate::domain::exam_answer::ExamAnswer::save`]'s shape exactly. -/// `Err(NotFound)` means the homework is gone, which is the 404 the web -/// layer's own lookup would have answered. +/// That deadline is `was_due`, the one read *inside this transaction* under +/// the homework row's lock — never the caller's [`Homework`] snapshot, which +/// was read before the request's gates and is exactly one `PATCH due_at` old +/// in the "teacher extends the deadline at 23:59 while the class submits" +/// moment. The lock is also the serialization point: grading locks the same +/// row before stamping, the audience-narrowing PATCH before its orphan +/// check, and a rival first hand-in before its own insert — so the +/// read-then-write below cannot interleave with any of them. (The pair's +/// UNIQUE constraint backs this up; under the lock it can never fire.) pub async fn upsert( db: &Database, homework: &Homework, user: &UserId, text: Option, -) -> Result, AppError> { - let id = HomeworkSubmissionId::composite(homework.get_id(), user); + preserve_text: bool, +) -> Result, AppError> { let now = Timestamp::now(); - let text = text.map(|text| text.as_str().to_string()); - // Sound to re-send: the UPSERT is on a deterministic id on a table with - // no unique index, so it can never legitimately answer "already exists", - // and the counter UPDATEs never can either. - let (mut saved, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $was_due = (SELECT VALUE due_at FROM ONLY $hw); - LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id); - IF array::len($alive) = 0 {{ THROW 'no_homework' }}; - UPDATE $hw SET due_at = $was_due; - LET $before = (SELECT VALUE id FROM ONLY $id); - LET $on_time = $now <= $was_due; - LET $after = (UPSERT $id SET homework = $hw, user = $usr, text = $text, - updated_at = $now, submitted_at = submitted_at ?? $now - WHERE {SUBMISSION_OPEN_GUARD} RETURN AFTER); - IF $before = NONE AND array::len($after) > 0 {{ - UPDATE $id SET counted_on_time = $on_time; - UPDATE $usr SET - {HOMEWORK_SUBMITTED_TOTAL_FIELD} = ({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) + 1, - {HOMEWORK_ON_TIME_TOTAL_FIELD} = ({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) - + IF $on_time {{ 1 }} ELSE {{ 0 }} - }}; - RETURN $after; - COMMIT TRANSACTION;" - ), - &[ - ("id".into(), id.record().into_value()), - ("hw".into(), homework.get_id().record().into_value()), - ("usr".into(), user.record().into_value()), - ("text".into(), text.into_value()), - ("now".into(), now.into_value()), - ], - &["no_homework"], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_homework")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`, so - // its slot follows the statement count rather than a hand-kept number. - // It returns the whole array, never `$after[0]`: a refused write makes - // that `NONE`, which fails to deserialize ("expected object, got none") - // instead of reading as the "frozen" the caller answers 409 to. - let slot = saved.num_statements().saturating_sub(2); - Ok(saved - .take::>(slot)? - .into_iter() - .next()) + tx_with_retry(db, false, async |tx| { + // The parent gate: the homework row is locked and its deadline read + // in the very transaction that writes the submission. The id is + // minted fresh, so nothing else here would fail against a homework a + // cascade already removed — it would simply create a row under it, + // badge counters and all, unreachable ever after (every route to a + // submission goes through its homework). `Err(NotFound)` means the + // homework is gone, which is the 404 the web layer's own lookup + // would have answered. + let was_due = sqlx::query!( + "SELECT due_at FROM homework WHERE id = $1 FOR UPDATE", + homework.get_id() + ) + .fetch_optional(&mut *tx) + .await? + .map(|row| row.due_at); + let Some(was_due) = was_due else { + return Err(AppError::NotFound); + }; + // Equal counts as on time, exactly as the deadline has always been + // judged. + let on_time = i64::from(now <= was_due); + + // The row, read under the homework's lock: its existence decides the + // arm (and the counters). + let existing = sqlx::query!( + r#"SELECT 1 AS "row: i32" FROM homework_submission + WHERE homework = $1 AND app_user = $2 FOR UPDATE"#, + homework.get_id(), + user + ) + .fetch_optional(&mut *tx) + .await? + .is_some(); + + if existing { + // Re-submit: text is replaced (unless the upload auto-create is + // asking — it has no text to replace), `updated_at` moves, and + // `submitted_at` is left alone. A frozen row matches nothing and + // answers `None`, the caller's 409. + let updated = if preserve_text { + sqlx::query_as!( + HomeworkSubmission, + r#"UPDATE homework_submission SET updated_at = $3 + WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL + RETURNING id AS "id: HomeworkSubmissionId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + text AS "text: Option", + submitted_at AS "submitted_at: Timestamp", + updated_at AS "updated_at: Timestamp""#, + homework.get_id(), + user, + now + ) + .fetch_optional(&mut *tx) + .await? + } else { + sqlx::query_as!( + HomeworkSubmission, + r#"UPDATE homework_submission SET text = $3, updated_at = $4 + WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL + RETURNING id AS "id: HomeworkSubmissionId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + text AS "text: Option", + submitted_at AS "submitted_at: Timestamp", + updated_at AS "updated_at: Timestamp""#, + homework.get_id(), + user, + text, + now + ) + .fetch_optional(&mut *tx) + .await? + }; + return Ok(updated.map(|submission| (submission, existing))); + } + + // First hand-in: the verdict is stored beside the counter it credits, + // so the two can never disagree. + let created = sqlx::query_as!( + HomeworkSubmission, + r#"INSERT INTO homework_submission + (id, homework, app_user, text, submitted_at, updated_at, file_count, counted_on_time) + VALUES ($1, $2, $3, $4, $5, $5, 0, $6) + RETURNING id AS "id: HomeworkSubmissionId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + text AS "text: Option", + submitted_at AS "submitted_at: Timestamp", + updated_at AS "updated_at: Timestamp""#, + HomeworkSubmissionId::generate(), + homework.get_id(), + user, + text, + now, + on_time != 0, + ) + .fetch_optional(&mut *tx) + .await?; + sqlx::query!( + r#"UPDATE app_user SET + homework_submitted_total = homework_submitted_total + 1, + homework_on_time_total = homework_on_time_total + $2 + WHERE id = $1"#, + user, + on_time + ) + .execute(&mut *tx) + .await?; + Ok(created.map(|submission| (submission, existing))) + }) + .await } /// Re-stamp a submission's `updated_at` to now, leaving its text and files /// alone. A file add or delete modifies the submission as a whole, so its /// "last touched" clock — which drives the computed late flag — must move -/// even though the text row is unchanged. Free-standing because the file -/// paths hold the composite id, not always the row. A targeted single-field -/// UPDATE, so the `READONLY` `submitted_at` is never re-sent (a `.content()` -/// would trip its guard). Returns the re-stamped row, or a 404 if it has -/// since vanished. +/// even though the text row is unchanged. A targeted single-field UPDATE, so +/// the readonly `submitted_at` is never re-sent. Returns the re-stamped row, +/// or a 404 if it has since vanished. pub async fn touch( db: &Database, id: &HomeworkSubmissionId, ) -> Result { let now = Timestamp::now(); - let mut result = db - .query("UPDATE $id SET updated_at = $now RETURN AFTER") - .bind(("id", id.record())) - .bind(("now", now)) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + sqlx::query_as!( + HomeworkSubmission, + r#"UPDATE homework_submission SET updated_at = $2 WHERE id = $1 + RETURNING id AS "id: HomeworkSubmissionId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + text AS "text: Option", + submitted_at AS "submitted_at: Timestamp", + updated_at AS "updated_at: Timestamp""#, + id, + now + ) + .fetch_optional(db) + .await? + .ok_or(AppError::NotFound) } /// Whether a grade has frozen this submission. Only ever read to tell two /// refusals apart *after* a conditional write has already refused one — the /// stamp on the row, never this read, is what decides. pub async fn is_graded(db: &Database, id: &HomeworkSubmissionId) -> Result { - let mut result = db - .query(format!( - "SELECT VALUE id FROM $id WHERE {SUBMISSION_GRADED_FIELD} != NONE" - )) - .bind(("id", id.record())) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) + let row = sqlx::query!( + r#"SELECT EXISTS(SELECT 1 FROM homework_submission + WHERE id = $1 AND graded_by_result IS NOT NULL) AS "graded""#, + id + ) + .fetch_one(db) + .await?; + Ok(row.graded) } /// `user`'s submission to `homework`, if they have one. @@ -193,23 +224,40 @@ pub async fn read_for( homework: &crate::domain::homework::HomeworkId, user: &UserId, ) -> Result, AppError> { - Ok(db - .select(HomeworkSubmissionId::composite(homework, user).record()) - .await?) + Ok(sqlx::query_as!( + HomeworkSubmission, + r#"SELECT id AS "id: HomeworkSubmissionId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + text AS "text: Option", + submitted_at AS "submitted_at: Timestamp", + updated_at AS "updated_at: Timestamp" + FROM homework_submission WHERE homework = $1 AND app_user = $2"#, + homework, + user + ) + .fetch_optional(db) + .await?) } -/// Every submission to `homework`, in student (composite-id) order — the -/// roster's raw rows. +/// Every submission to `homework`, in creation order — the roster's raw rows. pub async fn list_for_homework( db: &Database, homework: &crate::domain::homework::HomeworkId, ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM homework_submission WHERE homework = $hw ORDER BY id ASC") - .bind(("hw", homework.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + HomeworkSubmission, + r#"SELECT id AS "id: HomeworkSubmissionId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + text AS "text: Option", + submitted_at AS "submitted_at: Timestamp", + updated_at AS "updated_at: Timestamp" + FROM homework_submission WHERE homework = $1 ORDER BY id ASC"#, + homework + ) + .fetch_all(db) + .await?) } /// Delete this submission and its files in one transaction — so a crash @@ -217,9 +265,8 @@ pub async fn list_for_homework( /// are the web layer's to unlink: it lists them /// ([`crate::db::homework_file::list_for_submission`]) /// before calling this. `None` means a grade froze the row (the caller -/// answers 409): the submission's own delete carries -/// [`SUBMISSION_OPEN_GUARD`], and the file wipe is conditional on it having -/// bitten, so a refused delete leaves the children standing too. +/// answers 409): the delete carries `graded_by_result IS NULL` as its own +/// condition, so a refused delete leaves the files standing too. /// /// The one place either badge counter comes back down, and deliberately the /// only one: this route is student-callable on their own row, so without it @@ -234,12 +281,10 @@ pub async fn list_for_homework( /// and gave back something other than what was taken — extend it after a /// late hand-in and this debited a credit that was never given; pull it back /// after a punctual one and it debited nothing, leaving `on_time` above -/// `submitted`. A row from before the column exists carries no verdict, and -/// cannot be given one for a credit that already happened, so it falls back -/// to the old cut (`submitted_at`, the readonly stamp the increment judged, -/// against the live deadline); a dangling `homework` link leaves `$due` -/// `NONE` there, which compares false and so counts as late, matching the -/// backfill. Floored at zero: a row that predates the columns has none. +/// `submitted`. A row with no stored verdict falls back to the old cut +/// (`submitted_at`, the stamp the increment judged, against the deadline +/// read here); a homework already gone counts as late, matching the +/// backfill. Floored at zero. /// /// Badges already earned are never taken away — [`crate::domain::badge`] is /// add-only, which is where that permanence lives. @@ -247,42 +292,66 @@ pub async fn delete( db: &Database, submission: HomeworkSubmission, ) -> Result, AppError> { - // Sound to re-send: DELETE and UPDATE can never answer "already exists". - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $due = (SELECT VALUE homework.due_at FROM ONLY $sub); - LET $gone = (DELETE $sub WHERE {SUBMISSION_OPEN_GUARD} RETURN BEFORE); - IF array::len($gone) > 0 {{ - DELETE homework_file WHERE submission = $sub; - LET $on_time = IF ($gone[0].counted_on_time - ?? ($gone[0].submitted_at <= $due)) {{ 1 }} ELSE {{ 0 }}; - UPDATE $usr SET - {HOMEWORK_SUBMITTED_TOTAL_FIELD} = - math::max([({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) - 1, 0]), - {HOMEWORK_ON_TIME_TOTAL_FIELD} = - math::max([({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) - $on_time, 0]) - }}; - RETURN $gone; - COMMIT TRANSACTION;" - ), - &[ - ("sub".into(), submission.id.record().into_value()), - ("usr".into(), submission.user.record().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`. - let slot = result.num_statements().saturating_sub(2); - Ok(result - .take::>(slot)? - .into_iter() - .next()) + tx_with_retry(db, false, async |tx| { + // The homework row's lock is the serialization point against grading: + // a grade locks the same row before it stamps, so either this delete + // refuses off the stamp, or the grade landed on a row that is now + // gone — grading absent work, which is allowed. Its `due_at` read is + // also the replay fallback's deadline. + let due = sqlx::query!( + "SELECT due_at FROM homework WHERE id = $1 FOR UPDATE", + submission.get_homework() + ) + .fetch_optional(&mut *tx) + .await? + .map(|row| row.due_at); + let gone = sqlx::query!( + r#"DELETE FROM homework_submission + WHERE id = $1 AND graded_by_result IS NULL + RETURNING id AS "id: HomeworkSubmissionId", + homework AS "homework: HomeworkId", + app_user AS "user: UserId", + text AS "text: Option", + submitted_at AS "submitted_at: Timestamp", + updated_at AS "updated_at: Timestamp", + counted_on_time AS "counted_on_time: Option""#, + submission.get_id() + ) + .fetch_optional(&mut *tx) + .await?; + let Some(removed) = gone else { + // Frozen, or already withdrawn by a rival — one refusal, as + // before. + return Ok(None); + }; + sqlx::query!( + "DELETE FROM homework_file WHERE submission = $1", + removed.id + ) + .execute(&mut *tx) + .await?; + let judged_on_time = due.map(|d| removed.submitted_at <= d).unwrap_or(false); + let on_time = i64::from(removed.counted_on_time.unwrap_or(judged_on_time)); + sqlx::query!( + r#"UPDATE app_user SET + homework_submitted_total = GREATEST(homework_submitted_total - 1, 0), + homework_on_time_total = GREATEST(homework_on_time_total - $2, 0) + WHERE id = $1"#, + removed.user, + on_time + ) + .execute(&mut *tx) + .await?; + Ok(Some(HomeworkSubmission { + id: removed.id, + homework: removed.homework, + user: removed.user, + text: removed.text, + submitted_at: removed.submitted_at, + updated_at: removed.updated_at, + })) + }) + .await } #[cfg(test)] diff --git a/src/db/meal_attendance.rs b/src/db/meal_attendance.rs index 43145ff..a848c83 100644 --- a/src/db/meal_attendance.rs +++ b/src/db/meal_attendance.rs @@ -1,38 +1,31 @@ //! The `meal_attendance` table: the kitchen's marks — one atomic UPSERT per -//! (menu, student) that rides the menu's revision bump -//! ([`bump_menu_and_write`](crate::db::menu::bump_menu_and_write)), plus the -//! two listings. Attendance is reporting only: nothing here writes the -//! ledger, and the workflows that read it live in the web layer via -//! [`crate::service::meal_attendance`]. +//! (menu, student) that rides the menu's revision bump inside its own +//! transaction, plus the two listings. Attendance is reporting only: nothing +//! here writes the ledger, and the workflows that read it live in the web +//! layer via [`crate::service::meal_attendance`]. -use surrealdb::types::SurrealValue; - -use crate::database::Database; -use crate::db::menu::bump_menu_and_write; -use crate::db::page::PagedList; -use crate::domain::meal_attendance::{MealAttendance, MealAttendanceId, MealAttendanceStatus}; -use crate::domain::menu::MenuDate; -use crate::domain::menu::MenuId; +use crate::database::{Database, tx_with_retry}; +use crate::db::page::{PagedList, Param}; +use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus}; +use crate::domain::menu::{MenuDate, MenuId}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; /// Record (or overwrite) whether `student` ate off `menu`. One row per -/// pair by construction, so a correction is the same UPSERT flipping the -/// status. No ledger line, ever — see the domain module header. +/// pair by construction (`ON CONFLICT (menu, student)`), so a correction is +/// the same upsert flipping the status. No ledger line, ever — see the +/// domain module header. /// /// `NotFound` = the menu is gone, and the mark was *not* written. The mark -/// rides in [`bump_menu_and_write`], so the menu's existence is a *write* to -/// the menu row rather than a read the write then trusts: a delete racing -/// this one touches the very key this transaction bumps, and the store -/// refuses to commit both. Guarding by reading the menu — even as the -/// `UPSERT`'s own target — did not survive that race: the read saw a row -/// [`crate::db::menu::delete`] had deleted but not -/// yet committed, its sweep ran on a snapshot predating this insert, and the -/// mark outlived its menu with neither caller told anything (measured 378 of -/// 3600 raced rounds). Since [`MenuId::for_slot`] is deterministic, -/// republishing that day and slot then resurrected it as a mark on the new -/// menu. +/// and the menu's revision bump share one transaction, and the bump is what +/// makes the menu's **existence** part of it: the `UPDATE` matches nothing +/// once the menu row is deleted, and Postgres commits a deleting and a +/// bumping transaction on the same row strictly one after the other — the +/// mark either lands before the delete's guard re-reads its counter or not +/// at all. (Under the old store the same guarantee needed the shared bump +/// shape because deletes and child writes could interleave with a read in +/// between.) /// /// The bump costs a booking in flight one re-read (its seat claim asserts /// the revision it priced against) — the same tax every dish write already @@ -45,30 +38,40 @@ pub async fn mark( status: MealAttendanceStatus, marked_by: &UserId, ) -> Result { - let row = MealAttendance { - id: MealAttendanceId::composite(menu, student), - menu: menu.clone(), - student: student.clone(), - status, - marked_by: marked_by.clone(), - marked_at: Timestamp::now(), - }; - // Admissible for the retry loop inside: the id is bijective with the - // (menu, student) pair the table indexes UNIQUE, so this `UPSERT` - // resolves onto the row that index already points at instead of - // colliding with it — it can never answer "already exists", and a - // re-sent round writes the identical row. - bump_menu_and_write( - menu, - "UPSERT $id CONTENT $row RETURN AFTER", - vec![ - ("id".into(), row.id.record().into_value()), - ("row".into(), row.into_value()), - ], - db, - ) - .await? - .ok_or_else(|| AppError::Internal("failed to record the mark".into())) + let marked_at = Timestamp::now(); + let student = *student; + let marked_by = *marked_by; + tx_with_retry(db, false, async |tx| { + let bumped = sqlx::query!( + "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 + RETURNING 1 AS bumped", + menu.key(), + ) + .fetch_optional(&mut *tx) + .await?; + if bumped.is_none() { + return Err(AppError::NotFound); + } + let row = sqlx::query_as!( + MealAttendance, + "INSERT INTO meal_attendance (menu, student, status, marked_by, marked_at) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (menu, student) DO UPDATE + SET status = EXCLUDED.status, + marked_by = EXCLUDED.marked_by, + marked_at = EXCLUDED.marked_at + RETURNING menu, student, status, marked_by, marked_at", + menu.key(), + student, + status, + marked_by, + marked_at, + ) + .fetch_one(&mut *tx) + .await?; + Ok(row) + }) + .await } /// The kitchen's list for one menu. @@ -79,10 +82,10 @@ pub async fn list_for_menu( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "meal_attendance WHERE menu = $menu", - "ORDER BY marked_at DESC, id DESC", + "meal_attendance WHERE menu = $1", + "ORDER BY marked_at DESC, menu DESC", ) - .bind("menu", menu.record()) + .bind(menu.key().to_string()) .run(limit, offset, db) .await } @@ -91,7 +94,7 @@ pub async fn list_for_menu( /// `YYYY-MM-DD` bounds on the *menu's* day — the comparison is lexical, /// which is chronological for that format (see [`MenuDate`]), and the link /// is followed rather than denormalized so a row can never disagree with -/// the menu it belongs to. +/// the menu it belongs to. A `NULL` bound means the bound is absent. pub async fn list_for_student( db: &Database, student: &UserId, @@ -101,14 +104,14 @@ pub async fn list_for_student( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "meal_attendance WHERE student = $usr \ - AND ($from = NONE OR menu.date >= $from) \ - AND ($to = NONE OR menu.date <= $to)", - "ORDER BY marked_at DESC, id DESC", + "meal_attendance WHERE student = $1 \ + AND ($2::text IS NULL OR menu IN (SELECT id FROM menu WHERE date >= $2::text)) \ + AND ($3::text IS NULL OR menu IN (SELECT id FROM menu WHERE date <= $3::text))", + "ORDER BY marked_at DESC, menu DESC", ) - .bind("usr", student.record()) - .bind("from", from.map(|date| date.as_str().to_string())) - .bind("to", to.map(|date| date.as_str().to_string())) + .bind(student.key()) + .bind(Param::OptText(from.map(|date| date.as_str().to_string()))) + .bind(Param::OptText(to.map(|date| date.as_str().to_string()))) .run(limit, offset, db) .await } diff --git a/src/db/meal_booking.rs b/src/db/meal_booking.rs index ddfaa14..06cf601 100644 --- a/src/db/meal_booking.rs +++ b/src/db/meal_booking.rs @@ -1,14 +1,11 @@ //! The `meal_booking` table: row reads, the two listings, and the folded -//! transactions every seat moves by — [`claim_and_place`] (seat + row + charge -//! in one `BEGIN…COMMIT`) and [`release_seat`] (flip + counter + refund in -//! one). The book/cancel workflows that sequence these live in -//! [`crate::service::meal_booking`]; the row shape and the deadline checks in -//! [`crate::domain::meal_booking`]. +//! transactions every seat moves by — [`claim_and_place`] (seat + row + +//! charge in one transaction) and [`release_seat`] (flip + counter + refund +//! in one). The book/cancel workflows that sequence these live in +//! [`crate::service::meal_booking`]; the row shape and the deadline checks +//! in [`crate::domain::meal_booking`]. -use surrealdb::types::RecordId; - -use crate::constant::{CAP_WRITE_TRIES, MENU_SEAT_COUNT_FIELD, MENU_VERSION_FIELD}; -use crate::database::{Database, backoff, lost_the_race}; +use crate::database::{Database, tx_with_retry}; use crate::db::cap::Claimed; use crate::db::page::PagedList; use crate::domain::meal_booking::{MealBooking, MealBookingId}; @@ -19,7 +16,16 @@ use crate::domain::user::UserId; use crate::error::AppError; pub async fn read(db: &Database, id: &MealBookingId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let row = sqlx::query_as!( + MealBooking, + "SELECT menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at + FROM meal_booking WHERE menu = $1 AND student = $2", + id.menu().key(), + *id.student(), + ) + .fetch_optional(db) + .await?; + Ok(row) } /// Every booking on a menu, cancelled ones included — the kitchen's list. @@ -30,10 +36,10 @@ pub async fn list_for_menu( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "meal_booking WHERE menu = $menu", - "ORDER BY created_at DESC, id DESC", + "meal_booking WHERE menu = $1", + "ORDER BY created_at DESC, student DESC", ) - .bind("menu", menu.record()) + .bind(menu.key().to_string()) .run(limit, offset, db) .await } @@ -41,10 +47,10 @@ pub async fn list_for_menu( /// Every seat held for one of `students`, newest first — a caller's own /// list is themselves plus whoever they hold a *live* parent link to. /// -/// Deliberately **not** `booked_by = $usr`: who placed a booking is history -/// written onto a READONLY column, and history is not a read grant. A -/// parent whose link was revoked (by an unlink or by the student-side role -/// sweep) would otherwise keep a live view of the child's seat, watching +/// Deliberately **not** `booked_by`: who placed a booking is history +/// written onto a fixed column, and history is not a read grant. A parent +/// whose link was revoked (by an unlink or by the student-side role sweep) +/// would otherwise keep a live view of the child's seat, watching /// cancellations made long after the link died — exactly what /// [`ensure_can_observe`](crate::service::parent_link::ensure_can_observe) refuses. The /// caller re-derives the list from the links on every read, so the view @@ -55,34 +61,52 @@ pub async fn list_for_students( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "meal_booking WHERE student IN $students", - "ORDER BY created_at DESC, id DESC", - ) - .bind( - "students", - students.iter().map(UserId::record).collect::>(), + if students.is_empty() { + return Ok((Vec::new(), 0)); + } + let keys: Vec = students.iter().map(UserId::key).collect(); + let rows = sqlx::query_as!( + MealBooking, + "SELECT menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at + FROM meal_booking WHERE student = ANY($1::uuid[]) + ORDER BY created_at DESC, menu DESC + LIMIT $2 OFFSET $3", + keys, + limit, + offset, ) - .run(limit, offset, db) - .await + .fetch_all(db) + .await?; + // The window's own total — the same count the paging envelope answers. + let total = if limit.is_some() || offset != 0 { + sqlx::query_scalar!( + "SELECT count(*) FROM meal_booking WHERE student = ANY($1::uuid[])", + keys, + ) + .fetch_one(db) + .await? as i64 + } else { + rows.len() as i64 + }; + Ok((rows, total)) } /// Take the seat **and** place the row in one transaction, at the menu /// revision the price was read at. /// -/// The seat and the row cannot be two steps. The id is the (menu, student) -/// pair, so two `POST`s of the same seat both find no row and both claim — -/// and on a tight cap the second is then told "full" for a seat it never -/// owed, while the winner's row may not even be visible yet. Here the -/// duplicate `CREATE` aborts the transaction, which takes its increment with -/// it: the counter never counts a row that does not exist, and a loser is -/// answered with the winner's booking instead of a refusal. Same shape as -/// [`cap::claim_and_create`](crate::db::cap::claim_and_create), with the -/// revision guard and the revival of a cancelled row that the general form -/// does not carry. +/// The seat and the row cannot be two steps. The row key is the (menu, +/// student) pair, so two `POST`s of the same seat both find no row and both +/// claim — and on a tight cap the second is then told "full" for a seat it +/// never owed, while the winner's row may not even be visible yet. Here the +/// duplicate insert answers [`Claimed::Duplicate`] and the caller replays +/// the winner, while the whole transaction (seat bump included) rolls back +/// on any refused path: the counter never counts a row that does not exist. +/// Same shape as the [`crate::db::cap`] claim recipe, with the revision +/// guard and the revival of a cancelled row that the general form does not +/// carry. /// /// A cancelled row is revived in place (a fresh attempt at `price`) rather -/// than recreated: `booked_by` and `created_at` are READONLY history — who +/// than recreated: `booked_by` and `created_at` are fixed history — who /// opened the seat, and when. /// /// **The charge rides this transaction too**, for the same reason the @@ -93,118 +117,135 @@ pub async fn list_for_students( /// moved past. That is why `row.attempt` is minted by the *caller*: the /// charge's id is (seat, attempt), so the number cannot be the revival's own /// `attempt + 1` any more. The revival is fenced on the attempt it read -/// instead, so a rival that revived first loses this claim (the `CREATE` -/// below then finds the row and aborts the whole transaction) rather than -/// billing its attempt at this call's id. +/// instead, so a rival that revived first loses this claim (the insert below +/// then finds the row and answers `Duplicate`) rather than billing its +/// attempt at this call's id. /// -/// The charge is created only if it is not already there — a duplicate -/// `CREATE` would abort the transaction and cost the seat, and an attempt +/// The charge is created only if it is not already there — an attempt /// billed twice is the one thing money code may never do. pub(crate) async fn claim_and_place( db: &Database, - seats: &RecordId, + menu: &MenuId, cap: i64, seen: i64, row: &MealBooking, price: Option, charge: Option<&MealLedger>, ) -> Result, AppError> { - // Empty when the menu is free: a seat that costs nothing owes no line. - let bill = match charge { - Some(_) => { - "IF array::len((SELECT VALUE id FROM $charge)) = 0 \ - { CREATE $charge CONTENT $line };" + let menu_key = menu.key().to_string(); + let student = row.student; + let attempt = row.attempt; + tx_with_retry(db, false, async |tx| { + // Already held? Same attempt, same price it was taken at — answered + // as `Duplicate`, which the caller replays into the winner's row + // (and its charge) without claiming anything. + let held = sqlx::query!( + "SELECT 1 AS held FROM meal_booking + WHERE menu = $1 AND student = $2 AND status = 'booked'", + menu_key, + student, + ) + .fetch_optional(&mut *tx) + .await?; + if held.is_some() { + return Ok(Claimed::Duplicate); } - None => "", - }; - // Slots count BEGIN, three LETs, three IFs and — when there is money to - // take — the charge's IF, so the RETURN is slot 7 or 8. - let returned = if charge.is_some() { 8 } else { 7 }; - // Parenthesized `??` throughout: `a ?? 0 = $seen` binds the wrong way. - let sql = format!( - "BEGIN TRANSACTION; - LET $held = (SELECT VALUE id FROM $id WHERE status = 'booked'); - IF array::len($held) > 0 {{ THROW 'held' }}; - LET $seat = (UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = \ - ({MENU_SEAT_COUNT_FIELD} ?? 0) + 1 \ - WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) < $cap \ - AND ({MENU_VERSION_FIELD} ?? 0) = $seen RETURN VALUE id); - IF array::len($seat) = 0 {{ THROW 'no_seat' }}; - LET $revived = (UPDATE $id SET status = 'booked', attempt = $attempt, \ - price_minor = $price, cancelled_at = NONE \ - WHERE status = 'cancelled' AND attempt = $attempt - 1 RETURN AFTER); - IF array::len($revived) = 0 {{ CREATE $id CONTENT $row }}; - {bill} - RETURN SELECT * FROM ONLY $id; - COMMIT TRANSACTION;" - ); - // Every booking on one menu contends on that menu's single counter row, - // which is one HTTP burst of racers on a single parent — the case - // `CAP_WRITE_TRIES` is sized for. Three immediate re-sends with no - // backoff just re-synchronized them and 409'd the fourth student. - // Admissible: a lost round aborts the whole transaction (nothing - // written, no seat, no charge), and the two `CREATE`s that could - // legitimately answer "already exists" are read as `Claimed::Duplicate` - // below *before* the conflict check, so no decision is ever re-asked. - for attempt in 0..CAP_WRITE_TRIES { - backoff(attempt).await; - let query = db - .query(sql.as_str()) - .bind(("menu", seats.clone())) - .bind(("cap", cap)) - .bind(("seen", seen)) - .bind(("id", row.id.record())) - .bind(("attempt", row.attempt)) - .bind(("price", price)) - .bind(("row", row.clone())); - let query = match charge { - Some(line) => query - .bind(("charge", line.get_id().record())) - .bind(("line", line.clone())), - None => query, - }; - let mut result = match query.await { - Ok(result) => result, - Err(err) if lost_the_race(&err) => continue, - Err(err) => return Err(err.into()), - }; - // An aborted transaction errors *every* slot, most with a generic - // "not executed" — only the failing slot says why, so scan them all. - let mut errors = result.take_errors(); - if errors - .values() - .any(|error| error.to_string().contains("no_seat")) - { + // The seat: one conditional single-row write on the menu, atomic + // under Postgres — of the racers only `cap` of them per revision + // get a non-empty result, and the rest are refused with nothing + // written. + let seat = sqlx::query!( + "UPDATE menu SET seats_booked = seats_booked + 1 + WHERE id = $1 AND seats_booked < $2 AND COALESCE(version, 0) = $3 + RETURNING 1 AS seat", + menu_key, + cap, + seen, + ) + .fetch_optional(&mut *tx) + .await?; + if seat.is_none() { return Ok(Claimed::Full); } - if errors - .values() - .any(|error| error.to_string().contains("held") || error.is_already_exists()) - { + // Revive a cancelled row only while it still stands at the attempt + // this call read — the fence that keeps a rival's revival from + // being billed at this call's ids. + let revived = sqlx::query_as!( + MealBooking, + "UPDATE meal_booking + SET status = 'booked', attempt = $3, price_minor = $4, cancelled_at = NULL + WHERE menu = $1 AND student = $2 + AND status = 'cancelled' AND attempt = $3 - 1 + RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at", + menu_key, + student, + attempt, + price, + ) + .fetch_optional(&mut *tx) + .await?; + let placed = match revived { + Some(row) => Some(row), + None => { + // No row (or a rival moved it past this attempt): place a + // fresh one. A rival that landed first answers `Duplicate` + // — nothing here overwrites its row. + let inserted = sqlx::query_as!( + MealBooking, + "INSERT INTO meal_booking + (menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + ON CONFLICT (menu, student) DO NOTHING + RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at", + menu_key, + student, + row.booked_by, + row.status, + row.attempt, + price, + row.cancelled_at, + row.created_at, + ) + .fetch_optional(&mut *tx) + .await?; + inserted + } + }; + let Some(placed) = placed else { return Ok(Claimed::Duplicate); - } - if errors.values().any(lost_the_race) { - continue; - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - return match result.take::>(returned)? { - Some(placed) => Ok(Claimed::Made(placed)), - None => Err(AppError::Internal("failed to book the meal".into())), }; - } - Err(AppError::Conflict( - "the menu kept changing underneath this booking", - )) + // The charge rides the same transaction; already there (a replayed + // POST of this seat) means fine — nothing is written twice. + if let Some(line) = charge { + sqlx::query!( + "INSERT INTO meal_ledger + (id, student, kind, amount_minor, source, method, note, recorded_by, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) + ON CONFLICT (id) DO NOTHING", + line.id.key(), + line.student, + line.kind, + line.amount_minor, + line.source, + line.method, + line.note, + line.recorded_by, + line.created_at, + ) + .execute(&mut *tx) + .await?; + } + Ok(Claimed::Made(placed)) + }) + .await } /// Flip the seat to `cancelled` and give it back to the menu's counter **in /// one transaction**, so the two can never disagree: a decrement that ran /// without the flip frees a seat still held, and a flip without the -/// decrement locks a seat nothing can ever release. The counter follows the -/// flip's own result (`array::len`), so a row already cancelled — by a -/// racing cancel, or by this call retried — decrements nothing. +/// decrement locks a seat nothing can ever release. The decrement rides the +/// flip's own result, so a row already cancelled — by a racing cancel, or +/// by this call retried — decrements nothing. /// /// **The refund rides this transaction too**, and it has to: the flip and a /// reversal appended after it are two writes, and a crash in between leaves @@ -230,77 +271,78 @@ pub(crate) async fn claim_and_place( /// reversal id is burnt for good. /// /// `None` = the row was not this call's own `booked` attempt any more. -/// Retried while the store reports a write conflict: the menu row is -/// contended by every booking on it, and that contention is the cap -/// working, not an error. pub async fn release_seat( db: &Database, booked: &MealBooking, recorded_by: &UserId, ) -> Result, AppError> { let refund = MealLedger::reversal_for(booked, recorded_by); - // Guarded three ways: nothing was flipped (a rival cancelled first, and - // its own transaction carried the refund), the charge never landed, or - // this attempt is already refunded — none of which may abort the flip. - let reverse = match refund { - Some(_) => { - "IF array::len($flipped) > 0 \ - AND array::len((SELECT VALUE id FROM $charge)) > 0 \ - AND array::len((SELECT VALUE id FROM $reversal)) = 0 \ - { CREATE $reversal CONTENT $line };" - } - None => "", - }; - // Slots count BEGIN, the LET, the seat UPDATE and — when there is money - // to give back — the IF. - let returned = if refund.is_some() { 4 } else { 3 }; - // Same burst on the same counter as the book side, so the same patience - // (see [`claim_and_place`]) — a cancel that gave up left the seat - // held with the charge standing. Admissible: the round aborts having - // written nothing, and a re-send finds the row already `cancelled`, so - // the flip matches nothing, the counter moves nothing and the guarded - // reversal — keyed to (seat, attempt) — is not written twice. - for attempt in 0..CAP_WRITE_TRIES { - backoff(attempt).await; - let attempted = async { - let query = db - .query(format!( - "BEGIN TRANSACTION; - LET $flipped = (UPDATE $id SET status = 'cancelled', \ - cancelled_at = $now \ - WHERE status = 'booked' AND attempt = $attempt RETURN AFTER); - UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = math::max([\ - ({MENU_SEAT_COUNT_FIELD} ?? 0) - array::len($flipped), 0]); - {reverse} - RETURN $flipped; - COMMIT TRANSACTION;" - )) - .bind(("id", booked.id.record())) - .bind(("menu", booked.menu.record())) - .bind(("attempt", booked.attempt)) - .bind(("now", Timestamp::now())); - let query = match &refund { - Some((charge, line)) => query - .bind(("charge", charge.record())) - .bind(("reversal", line.get_id().record())) - .bind(("line", line.clone())), - None => query, - }; - let mut result = query.await?.check()?; - result.take::>(returned) + let menu_key = booked.menu.key().to_string(); + let student = booked.student; + let attempt = booked.attempt; + let cancelled_at = Timestamp::now(); + tx_with_retry(db, false, async |tx| { + let flipped = sqlx::query_as!( + MealBooking, + "UPDATE meal_booking SET status = 'cancelled', cancelled_at = $3 + WHERE menu = $1 AND student = $2 AND status = 'booked' AND attempt = $4 + RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at", + menu_key, + student, + cancelled_at, + attempt, + ) + .fetch_optional(&mut *tx) + .await?; + if flipped.is_some() { + sqlx::query!( + "UPDATE menu SET seats_booked = GREATEST(seats_booked - 1, 0) WHERE id = $1", + menu_key, + ) + .execute(&mut *tx) + .await?; } - .await; - match attempted { - Ok(rows) => return Ok(rows.into_iter().next()), - Err(err) if lost_the_race(&err) => {} - Err(err) => return Err(err.into()), + // Guarded three ways: nothing was flipped (a rival cancelled first, + // and its own transaction carried the refund), the charge never + // landed, or this attempt is already refunded — none of which may + // abort the flip. + if let (true, Some((charge, line))) = (flipped.is_some(), &refund) { + let charge_there = sqlx::query!( + "SELECT 1 AS there FROM meal_ledger WHERE id = $1", + charge.key(), + ) + .fetch_optional(&mut *tx) + .await?; + let reversal_there = sqlx::query!( + "SELECT 1 AS there FROM meal_ledger WHERE id = $1", + line.id.key(), + ) + .fetch_optional(&mut *tx) + .await?; + if charge_there.is_some() && reversal_there.is_none() { + sqlx::query!( + "INSERT INTO meal_ledger + (id, student, kind, amount_minor, source, method, note, recorded_by, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) + ON CONFLICT (id) DO NOTHING", + line.id.key(), + line.student, + line.kind, + line.amount_minor, + line.source, + line.method, + line.note, + line.recorded_by, + line.created_at, + ) + .execute(&mut *tx) + .await?; + } } - } - Err(AppError::Conflict( - "the menu kept changing underneath this cancellation", - )) + Ok(flipped) + }) + .await } - #[cfg(test)] mod tests { use super::*; diff --git a/src/db/meal_ledger.rs b/src/db/meal_ledger.rs index dc0ea5e..f4266dc 100644 --- a/src/db/meal_ledger.rs +++ b/src/db/meal_ledger.rs @@ -3,29 +3,14 @@ //! convention live in [`crate::domain::meal_ledger`]; the charge/reversal //! and credit workflows that sequence these in [`crate::service::meal_ledger`]. -use surrealdb::types::{AlreadyExistsError, SurrealValue}; - -use crate::constant::{CAS_UPDATE_RETRIES, MEAL_LEDGER_TABLE}; -use crate::database::{Database, lost_the_race}; -use crate::db::menu_dish; +use crate::database::Database; use crate::db::page::PagedList; -use crate::domain::meal_ledger::{LedgerAmount, MealLedger, MealLedgerId, MealLedgerKind}; +use crate::domain::meal_ledger::{LedgerAmount, MealLedger, MealLedgerId}; use crate::domain::menu::MenuId; use crate::domain::user::UserId; use crate::error::AppError; -/// Did this `CREATE` fail *only* because the row is already there? Matched on -/// the SDK's typed `AlreadyExists`/`Record` detail — never on the message text -/// and never on "any database error", because swallowing a real fault in money -/// code would be far worse than the 500 it saves. -fn is_duplicate_record(error: &surrealdb::Error) -> bool { - matches!( - error.already_exists_details(), - Some(AlreadyExistsError::Record { .. }) - ) -} - -/// The only writer: one `CREATE`, no update path anywhere in this module. +/// The only writer: one `INSERT`, no update path anywhere in this module. /// /// A line whose id already exists is left exactly as it is — the row wins, /// the write is dropped. That is what makes a deterministic id (see @@ -33,38 +18,52 @@ fn is_duplicate_record(error: &surrealdb::Error) -> bool { /// append is a no-op, never a second line and never an edit of the first. /// The point read is on the id itself, so unlike a scan it cannot miss a /// row a concurrent writer just made — but it is only a fast path. The -/// guarantee is `CREATE`'s own: on an existing id it *errors* and leaves -/// the row untouched, so the writer that lost the race reads back the -/// winner's line instead of failing the request with a 500. -/// -/// A *write conflict* is the same race decided one layer down — two -/// appends of one id arriving together are no longer serialized by a -/// process-wide lock, so the store aborts one as retryable instead of -/// answering it "already exists". Both are read back the same way, and a -/// conflict that turns out to have written nothing is simply tried again; -/// no path here can write a second line, since the id is the key. +/// guarantee is the insert's own `ON CONFLICT (id) DO NOTHING`: on an +/// existing id nothing is written, so the writer that lost the race reads +/// back the winner's line instead of failing the request with a 500. pub(crate) async fn append(db: &Database, row: MealLedger) -> Result { if let Some(existing) = read(db, &row.id).await? { return Ok(existing); } - let id = row.id.clone(); - for _ in 0..CAS_UPDATE_RETRIES { - match db.create(id.record()).content(row.clone()).await { - Ok(Some(created)) => return Ok(created), - Ok(None) => break, - Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => { - if let Some(existing) = read(db, &id).await? { - return Ok(existing); - } - } - Err(e) => return Err(e.into()), - } + let inserted = sqlx::query_as!( + MealLedger, + "INSERT INTO meal_ledger + (id, student, kind, amount_minor, source, method, note, recorded_by, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) + ON CONFLICT (id) DO NOTHING + RETURNING id, student, kind, amount_minor, source, method, note, recorded_by, created_at", + row.id.key(), + row.student, + row.kind, + row.amount_minor, + row.source, + row.method, + row.note, + row.recorded_by, + row.created_at, + ) + .fetch_optional(db) + .await?; + match inserted { + Some(created) => Ok(created), + // Lost the id to a concurrent append of the same line: the stored + // row is the answer, never a second line. + None => read(db, &row.id) + .await? + .ok_or_else(|| AppError::Internal("failed to write the ledger line".into())), } - Err(AppError::Internal("failed to write the ledger line".into())) } pub async fn read(db: &Database, id: &MealLedgerId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let row = sqlx::query_as!( + MealLedger, + "SELECT id, student, kind, amount_minor, source, method, note, recorded_by, created_at + FROM meal_ledger WHERE id = $1", + id.key(), + ) + .fetch_optional(db) + .await?; + Ok(row) } /// What a seat on `menu` costs *right now*: the sum of its dishes. `None` @@ -77,12 +76,11 @@ pub async fn price_snapshot( db: &Database, menu: &MenuId, ) -> Result, AppError> { - let total = menu_dish::list_for_menu(db, menu) - .await? - .iter() - .fold(0i64, |sum, dish| { - sum.saturating_add(dish.get_price_minor().as_minor()) - }); + let row = + sqlx::query!("SELECT CAST(COALESCE(sum(price_minor), 0) AS BIGINT) AS total FROM menu_dish WHERE menu = $1", menu.key()) + .fetch_one(db) + .await?; + let total = row.total; if total == 0 { return Ok(None); } @@ -97,10 +95,10 @@ pub async fn list_for_student( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "meal_ledger WHERE student = $student", + "meal_ledger WHERE student = $1", "ORDER BY created_at DESC, id DESC", ) - .bind("student", student.record()) + .bind(student.key()) .run(limit, offset, db) .await } @@ -118,38 +116,27 @@ pub async fn list_for_student( /// every later `GET /meals/balance/*`. /// /// **The signs stay on the kind**, applied by the very -/// [`MealLedgerKind::sign`] -/// the documented formula is spelled in. Summing `IF kind = 'charge' THEN -/// -amount …` in SQL would have folded the whole balance in one statement -/// and forked the one rule that decides what money means into a second -/// language, where nothing would fail the day the two disagreed. Grouping -/// instead keeps the aggregate ignorant of signs: it counts kinds, and -/// Rust still says what a kind does. A stored running total was the third -/// option and is a counter that can drift — a bug class this repo closes, -/// not one it opens. +/// [`MealLedgerKind::sign`](crate::domain::meal_ledger::MealLedgerKind::sign) +/// the documented formula is spelled in. Summing a signed CASE in SQL would +/// have folded the whole balance in one statement and forked the one rule +/// that decides what money means into a second language, where nothing +/// would fail the day the two disagreed. Grouping instead keeps the +/// aggregate ignorant of signs: it counts kinds, and Rust still says what a +/// kind does. A stored running total was the third option and is a counter +/// that can drift — a bug class this repo closes, not one it opens. pub async fn balance_of(db: &Database, student: &UserId) -> Result { - let totals: Vec = db - .query(format!( - "SELECT kind, math::sum(amount_minor) AS total \ - FROM {MEAL_LEDGER_TABLE} WHERE student = $student GROUP BY kind" - )) - .bind(("student", student.record())) - .await? - .check()? - .take(0)?; + let totals = sqlx::query!( + r#"SELECT kind AS "kind: crate::domain::meal_ledger::MealLedgerKind", + CAST(sum(amount_minor) AS BIGINT) AS total + FROM meal_ledger WHERE student = $1 GROUP BY kind"#, + *student, + ) + .fetch_all(db) + .await?; Ok(totals .iter() .fold(0i64, |sum, row| sum + row.kind.sign() * row.total)) } - -/// One kind's whole sum, as the `GROUP BY` in [`balance_of`] hands -/// it back — at most three rows, never the lines behind them. -#[derive(Debug, SurrealValue)] -struct KindTotal { - kind: MealLedgerKind, - total: i64, -} - #[cfg(test)] mod tests { use super::*; diff --git a/src/db/menu.rs b/src/db/menu.rs index b95956c..40c7ebb 100644 --- a/src/db/menu.rs +++ b/src/db/menu.rs @@ -1,100 +1,33 @@ //! The `menu` table: publishing (the slot reference claimed inside the //! write's own transaction), row reads and listings, the compare-and-set -//! every cap PATCH writes through, the cascading delete, and -//! [`bump_menu_and_write`] — the shared "write the menu row too" shape every -//! child write (a dish, an attendance mark) uses so nothing can outlive its -//! menu. The kitchen workflows — the dish cap under -//! [`MENU_LOCK`](crate::service::menu::MENU_LOCK) — live in +//! every cap PATCH writes through, and the cascading delete. The kitchen +//! workflows — the guarded dish-cap insert — live in //! [`crate::service::menu`]. -use surrealdb::types::{SurrealValue, Value}; - -use crate::constant::{ - MEAL_ATTENDANCE_TABLE, MENU_DISH_TABLE, MENU_SEAT_COUNT_FIELD, MENU_VERSION_FIELD, - REF_COUNT_FIELD, -}; -use crate::database::{Database, transaction_with_retry, write_with_retry}; -use crate::db::cap; -use crate::db::page::PagedList; +use crate::database::{Database, tx_with_retry, unique_violation}; +use crate::db::page::{PagedList, Param}; use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, slot_ref}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; -/// Move the menu's revision **and** run `statement` — a write to something -/// hanging off a menu — in one transaction, handing back the row it returned. -/// -/// What a seat on that menu costs, or who is recorded against it, is about to -/// change, so any booking that priced itself against the old revision has to -/// re-read. The bump cannot be a query of its own: in the gap the menu row -/// carries the *new* revision with the *old* price, and a booking reading there -/// passes the very CAS that exists to refuse it — a seat billed a price the -/// menu had already left, or admitted past a capacity that had already shrunk. -/// -/// The bump is also what makes the menu's **existence** part of the write -/// ([`crate::db::menu_dish::create`] leans on -/// the same thing): the `UPDATE` matches nothing once the menu row is deleted, -/// and a delete racing this one touches the very key this transaction writes, -/// so the two cannot both commit. Reading the menu instead — even as the write -/// statement's own target — does not survive that race: the read sees a row the -/// delete has not committed yet, and [`delete`]'s sweep ran on a snapshot -/// predating this insert, so both commit and the child outlives its menu -/// (measured 378 of 3600 raced rounds before this shape was shared). -/// -/// Deliberately on every such write, not only the ones that move -/// `price_minor`: a re-tagged dish is cheap to re-read, and a rule that applies -/// to every write cannot be forgotten by the next one added. -/// -/// Admissible for [`transaction_with_retry`] as long as `statement` is: an -/// `UPDATE`, a `DELETE`, a `SELECT`, an `IF`/`THROW` or a `RETURN` can never -/// answer "already exists", and neither can an `UPSERT` whose id is bijective -/// with every unique tuple its table indexes — a lost round wrote nothing, so -/// re-sending it is the recovery. -pub(crate) async fn bump_menu_and_write( - menu: &MenuId, - statement: &str, - mut bindings: Vec<(String, Value)>, - db: &Database, -) -> Result, AppError> { - bindings.push(("menu".into(), menu.record().into_value())); - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \ - ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id); - IF array::len($bumped) = 0 {{ THROW 'no_menu' }}; - LET $row = ({statement}); - RETURN $row; - COMMIT TRANSACTION;" - ), - &bindings, - &["no_menu"], - ) - .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_menu")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, the LET, the IF and the second LET: the RETURN is 4. - Ok(result.take::>(4)?.into_iter().next()) -} - /// Publish a menu. Refused (409) when the day+slot already carries one. /// -/// The day and slot *are* the record id ([`MenuId::for_slot`]), so the -/// refusal is decided by the store rather than by a check a concurrent -/// publish can outrun: two publishes of the same meal write one id, and the loser's -/// "already exists" becomes the same 409. The pre-check stays for the -/// ordinary case — and for menus published before ids were derived, whose -/// ULID key no new publish can collide with. +/// The day and slot *are* the row's primary key ([`MenuId::for_slot`]), so +/// the refusal is decided by the store rather than by a check a concurrent +/// publish can outrun: two publishes of the same meal write one row, and +/// the loser's unique violation on `menu_pkey` becomes the same 409. The +/// in-transaction pre-check stays for the ordinary case. +/// +/// The menu takes a reference on its slot, which is what stops the slot +/// being dropped from the settings while this menu (whose slot is only +/// snapshotted text) still points at it. Claimed *inside* the write's own +/// transaction, with the duplicate gate ahead of the retired check so +/// "you already published this" still outranks "the slot is retired" (the +/// [`crate::db::cap`] reference-claim recipe): the counted row and the +/// count commit together or not at all, so no crash window is small enough +/// to leave a slot counted by a menu that does not exist — a slot nobody +/// could ever retire. pub async fn create( db: &Database, date: MenuDate, @@ -102,39 +35,80 @@ pub async fn create( capacity: Option, created_by: &UserId, ) -> Result { - let taken = AppError::Conflict("a menu is already published for that date and slot"); - if find(db, &date, &slot).await?.is_some() { - return Err(taken); - } - // The menu takes a reference on its slot, which is what stops the slot - // being dropped from the settings while this menu (whose slot is only - // snapshotted text) still points at it. Claimed *inside* the write's own - // transaction: a claim of its own could land and the row then fail to, - // leaving the slot counted by a menu that does not exist — a slot - // nobody can ever retire, and no crash window is small enough for that. + let id_key = MenuId::for_slot(&date, &slot).key().to_string(); let counter = slot_ref(slot.as_str()); - let menu = Menu { - id: MenuId::for_slot(&date, &slot), - date, - slot, - capacity, - version: Some(0), - created_by: created_by.clone(), - created_at: Timestamp::now(), - }; - let id = menu.id.record(); - match cap::claim_ref_and_create(&counter, 1, &id, &menu, db).await? { - cap::ClaimedRef::Made(created) => Ok(created), - cap::ClaimedRef::Duplicate => Err(taken), - cap::ClaimedRef::Retired => Err(AppError::ConflictOwned(format!( - "the '{}' meal slot has been removed from the school's settings", - menu.slot.as_str() - ))), - } + let date_s = date.as_str().to_string(); + let slot_s = slot.as_str().to_string(); + let created_by = *created_by; + let created_at = Timestamp::now(); + tx_with_retry(db, false, async |tx| { + // Duplicate gate ahead of the retired check: "already published" + // outranks "slot retired", on the very path a rival publish races. + let exists = sqlx::query!("SELECT 1 AS taken FROM menu WHERE id = $1", id_key,) + .fetch_optional(&mut *tx) + .await?; + if exists.is_some() { + return Err(AppError::Conflict( + "a menu is already published for that date and slot", + )); + } + let inserted = match sqlx::query_as!( + Menu, + "WITH ref AS ( + INSERT INTO slot_ref (name, count) VALUES ($2, 1) + ON CONFLICT (name) DO UPDATE SET count = slot_ref.count + 1 + WHERE slot_ref.retired = false + RETURNING 1 AS ref + ) + INSERT INTO menu (id, date, slot, capacity, version, created_by, created_at) + SELECT $1, $3, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM ref) + RETURNING id, date, slot, capacity, version, created_by, created_at", + id_key, + counter, + date_s, + slot_s, + capacity, + Some(0i64), + created_by, + created_at, + ) + .fetch_optional(&mut *tx) + .await + { + Ok(row) => row, + Err(err) => { + // A rival published the same meal after the pre-check: its + // row owns the key, and its publish is the answer. + if unique_violation(&err) == Some("menu_pkey") { + return Err(AppError::Conflict( + "a menu is already published for that date and slot", + )); + } + return Err(err.into()); + } + }; + match inserted { + Some(menu) => Ok(menu), + // The slot's ref row is retired — nothing was written. + None => Err(AppError::ConflictOwned(format!( + "the '{}' meal slot has been removed from the school's settings", + slot_s, + ))), + } + }) + .await } pub async fn read(db: &Database, id: &MenuId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let row = sqlx::query_as!( + Menu, + "SELECT id, date, slot, capacity, version, created_by, created_at + FROM menu WHERE id = $1", + id.key(), + ) + .fetch_optional(db) + .await?; + Ok(row) } /// The menu for one day and slot, if any — the uniqueness check. @@ -143,18 +117,21 @@ pub async fn find( date: &MenuDate, slot: &MenuSlot, ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM menu WHERE date = $date AND slot = $slot LIMIT 1") - .bind(("date", date.as_str().to_string())) - .bind(("slot", slot.as_str().to_string())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + let row = sqlx::query_as!( + Menu, + "SELECT id, date, slot, capacity, version, created_by, created_at + FROM menu WHERE date = $1 AND slot = $2 LIMIT 1", + date.as_str(), + slot.as_str(), + ) + .fetch_optional(db) + .await?; + Ok(row) } /// Menus, newest day first. `from`/`to` are inclusive `YYYY-MM-DD` bounds; -/// either may be omitted. The comparison is lexical, which is chronological -/// for this format. +/// either may be omitted (`NULL` bound). The comparison is lexical, which +/// is chronological for this format. pub async fn list( db: &Database, from: Option<&MenuDate>, @@ -163,25 +140,26 @@ pub async fn list( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "menu WHERE ($from = NONE OR date >= $from) AND ($to = NONE OR date <= $to)", + "menu WHERE ($1::text IS NULL OR date >= $1::text) \ + AND ($2::text IS NULL OR date <= $2::text)", "ORDER BY date DESC, slot ASC, id DESC", ) - .bind("from", from.map(|date| date.as_str().to_string())) - .bind("to", to.map(|date| date.as_str().to_string())) + .bind(Param::OptText(from.map(|date| date.as_str().to_string()))) + .bind(Param::OptText(to.map(|date| date.as_str().to_string()))) .run(limit, offset, db) .await } -/// Only `capacity` is writable: `date` and `slot` are `READONLY` columns, +/// Only `capacity` is writable: `date` and `slot` are fixed at publish, /// because moving a published menu to another day is a different menu. /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped. /// /// The revision moves **in the same statement** as the cap, indivisibly: a -/// booking claims its seat against the revision -/// it read the cap at, so a shrink that bumped in a query of its own left a -/// window where the row carried the *new* revision and the *old* cap — and -/// a booking arriving there passes a CAS meant to refuse it, over-admitting -/// by exactly the seats in flight. +/// booking claims its seat against the revision it read the cap at, so a +/// shrink that bumped in a query of its own left a window where the row +/// carried the *new* revision and the *old* cap — and a booking arriving +/// there passes a CAS meant to refuse it, over-admitting by exactly the +/// seats in flight. pub async fn update( db: &Database, menu: Menu, @@ -192,99 +170,89 @@ pub async fn update( // booking's price or cap has moved, so none owes a re-read. return read(db, &menu.id).await?.ok_or(AppError::NotFound); }; - let sql = format!( - "UPDATE $id SET capacity = $capacity, \ - {MENU_VERSION_FIELD} = ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN AFTER" - ); - // One counter write in flight at a time, like every other one. - let _guard = cap::counter_lock().await; - write_with_retry::( - db, - &sql, - &[ - ("id".into(), menu.id.record().into_value()), - ("capacity".into(), capacity.into_value()), - ], + let row = sqlx::query_as!( + Menu, + "UPDATE menu SET capacity = $2, version = COALESCE(version, 0) + 1 + WHERE id = $1 + RETURNING id, date, slot, capacity, version, created_by, created_at", + menu.id.key(), + capacity, ) - .await? - .into_iter() - .next() - .ok_or(AppError::NotFound) + .fetch_optional(db) + .await?; + row.ok_or(AppError::NotFound) } -/// Delete the menu and the dishes on it — a dish has no meaning without -/// its menu, and the `menu` link is `READONLY`, so it cannot be re-homed. +/// Delete the menu and the dishes and marks on it — a dish or a mark has +/// no meaning without its menu, and the menu key cannot be re-homed. /// /// Refused (409) while a seat is still held, and the *row itself* decides /// that: the delete carries the seat counter in its `WHERE`, so a booking -/// landing at that instant either takes its seat before -/// the delete (which then finds a non-zero counter and refuses) or after it -/// (and finds no menu). A read-then-delete pair had a window where both -/// happened — a paid seat on a menu that no longer exists. +/// landing at that instant either takes its seat before the delete (which +/// then finds a non-zero counter and refuses) or after it (and finds no +/// menu). A read-then-delete pair had a window where both happened — a +/// paid seat on a menu that no longer exists. /// /// The slot gets its reference back in that same transaction — a slot no -/// menu is published for any more may leave the settings again, and the -/// `FOR` runs only over a row the guard actually took. Released afterwards -/// in a query of its own, a crash between the two left the slot counted by -/// a menu that no longer exists: a slot nobody can retire. +/// menu is published for any more may leave the settings again. Released +/// afterwards in a statement of its own, a crash between the two left the +/// slot counted by a menu that no longer exists: a slot nobody can retire. /// -/// The marks go in that same `FOR`, for a sharper reason than tidiness: +/// The marks go in that same sweep, for a sharper reason than tidiness: /// [`MenuId::for_slot`] is deterministic, so republishing the same day and -/// slot mints the *same* record id. A mark left behind would come back as a +/// slot mints the *same* row key. A mark left behind would come back as a /// mark on the new menu — the kitchen reading "served" for a student who /// never came — and until then the student's own report cites a menu that /// is gone. Attendance carries no money and no counter, so it is safe to -/// drop; cancelled *bookings* deliberately stay, because their `attempt` -/// counter is what keeps the ledger's `(booking, attempt)` keys unique. Cut +/// drop; cancelled *bookings* deliberately stay (no foreign key ties them +/// to the menu), because their `attempt` counter is what keeps the +/// ledger's `(booking, attempt)` keys unique across the republish. Cut /// those and a re-book on a republished menu would reuse a charge id the /// ledger already holds, and the append (idempotent by design) would bill /// the seat nothing. /// -/// The dishes ride in that `FOR` too, and for the same reason as the marks: -/// run after the transaction committed, a crash between the two orphaned -/// them on a record id republishing the day and slot mints again — a new -/// menu serving (and pricing) the old one's food. +/// The dishes ride in the same sweep: run after the commit, a crash +/// between the two would orphan them on the row key a republish mints +/// again — a new menu serving (and pricing) the old one's food. pub async fn delete(db: &Database, menu: Menu) -> Result { - let sql = format!( - "BEGIN TRANSACTION; - LET $gone = (DELETE $id WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE); - FOR $row IN ($gone ?? []) {{ - UPSERT $counter SET {REF_COUNT_FIELD} = \ - math::max([({REF_COUNT_FIELD} ?? 0) - 1, 0]); - DELETE {MEAL_ATTENDANCE_TABLE} WHERE menu = $id; - DELETE {MENU_DISH_TABLE} WHERE menu = $id; - }}; - RETURN $gone; - COMMIT TRANSACTION;" - ); - // `slot` is a `READONLY` column, so this counter is the one the deleted - // row carries. Nothing here can answer "already exists" — the `UPSERT` - // is keyed by a slot name on a table with no `UNIQUE` index, so it - // resolves onto the row it names ([`transaction_with_retry`]). - let (mut result, mut errors) = transaction_with_retry( - db, - &sql, - &[ - ("id".into(), menu.id.record().into_value()), - ("counter".into(), slot_ref(menu.slot.as_str()).into_value()), - ], - &[], - ) + let key = menu.id.key().to_string(); + let counter = slot_ref(menu.slot.as_str()); + let deleted = tx_with_retry(db, true, async |tx| { + let deleted = sqlx::query_as!( + Menu, + "DELETE FROM menu WHERE id = $1 AND seats_booked = 0 + RETURNING id, date, slot, capacity, version, created_by, created_at", + key, + ) + .fetch_optional(&mut *tx) + .await?; + let Some(row) = deleted else { + return Ok(None); + }; + sqlx::query!( + "UPDATE slot_ref SET count = GREATEST(count - 1, 0) WHERE name = $1", + counter, + ) + .execute(&mut *tx) + .await?; + sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key) + .execute(&mut *tx) + .await?; + sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key) + .execute(&mut *tx) + .await?; + Ok(Some(row)) + }) .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // BEGIN, the LET and the FOR take a slot each. - let Some(deleted) = result.take::>(3)?.into_iter().next() else { + match deleted { + Some(menu) => Ok(menu), // Nothing back: either seats are held, or the menu is already gone. - return Err(match read(db, &menu.id).await? { - Some(_) => AppError::Conflict("the menu still has live bookings"), - None => AppError::NotFound, - }); - }; - Ok(deleted) + None => match read(db, &menu.id).await? { + Some(_) => Err(AppError::Conflict("the menu still has live bookings")), + None => Err(AppError::NotFound), + }, + } } - #[cfg(test)] mod tests { use super::*; diff --git a/src/db/menu_dish.rs b/src/db/menu_dish.rs index 8f988e3..e66d605 100644 --- a/src/db/menu_dish.rs +++ b/src/db/menu_dish.rs @@ -1,14 +1,9 @@ -//! The `menu_dish` table: the dishes on a menu — the insert and the field -//! PATCH riding the menu's revision bump ([`bump_menu_and_write`]), the -//! reads and listings, and the delete. The dish-cap gate and the -//! [`MENU_LOCK`](crate::service::menu::MENU_LOCK) leases live in -//! [`crate::service::menu`]. +//! The `menu_dish` table: the dishes on a menu — the guarded insert (the +//! dish cap, enforced by the menu row's own lock), the field PATCH riding +//! the menu's revision bump, the reads and listings, and the delete. The +//! kitchen workflows live in [`crate::service::menu`]. -use surrealdb::types::{SurrealValue, Value}; - -use crate::constant::MENU_VERSION_FIELD; -use crate::database::{Database, transaction_with_retry}; -use crate::db::menu::bump_menu_and_write; +use crate::database::{Database, tx_with_retry}; use crate::domain::menu::MenuId; use crate::domain::menu_dish::{ DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId, @@ -16,7 +11,15 @@ use crate::domain::menu_dish::{ use crate::domain::timestamp::Timestamp; use crate::error::AppError; -/// Add a dish. Moves the menu's revision *first* — see [`bump_menu_and_write`]. +/// Add a dish. The dish cap is one guarded decision, not a count a caller +/// took a moment earlier: the menu row is locked `FOR NO KEY UPDATE` in +/// this write's own transaction and the `INSERT` runs with a +/// `count(*) < $cap` guard — a writer that queued on the lock behind a +/// concurrent one re-counts after it and is refused (`409`) instead of +/// overfilling. The revision bump rides the same transaction, and the +/// lock's `SELECT` is what makes the menu's **existence** part of the +/// write: it matches nothing once the menu row is deleted, so `NotFound` +/// means the dish was not written. pub async fn create( db: &Database, menu: &MenuId, @@ -24,67 +27,67 @@ pub async fn create( description: Option, price_minor: DishPrice, tags: DishTags, + cap: i64, ) -> Result { - let dish = MenuDish { - id: MenuDishId::generate(), - menu: menu.clone(), - name, - description, - price_minor, - tags, - created_at: Timestamp::now(), - }; - // The revision bump and the insert are one transaction, and the bump is - // what makes the menu's existence part of it: the `UPDATE` matches - // nothing once the menu row is deleted, and a delete racing this one - // touches the very key this transaction writes, so the two cannot both - // commit. Without that, a dish landing just after `DELETE /menus/{id}` - // removed the row but before its cascade ran outlived its menu. - // Every other dish write bumps the same version key, so a lost round is - // ordinary here; it is re-sent rather than reported. Re-sending is sound - // even with the `CREATE` in the batch — the abort wrote nothing, the id - // is a ULID freshly generated above and never seen by a rival, and - // `menu_dish` carries no UNIQUE index — so the retry cannot answer - // "already exists" (see [`transaction_with_retry`]). - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \ - ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id); - IF array::len($bumped) = 0 {{ THROW 'no_menu' }}; - CREATE $id CONTENT $dish; - COMMIT TRANSACTION;" - ), - &[ - ("menu".into(), menu.record().into_value()), - ("id".into(), dish.id.record().into_value()), - ("dish".into(), dish.into_value()), - ], - &["no_menu"], - ) - .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_menu")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, the LET and the IF: the CREATE is slot 3. - result - .take::>(3)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to add the dish".into())) + let menu_key = menu.key().to_string(); + let id = MenuDishId::generate(); + let created_at = Timestamp::now(); + tx_with_retry(db, false, async |tx| { + // The lock first: every later statement in this transaction then + // sees the committed state of whoever queued ahead of it. + let locked = sqlx::query!( + "SELECT 1 AS locked FROM menu WHERE id = $1 FOR NO KEY UPDATE", + menu_key, + ) + .fetch_optional(&mut *tx) + .await?; + if locked.is_none() { + return Err(AppError::NotFound); + } + sqlx::query!( + "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1", + menu_key, + ) + .execute(&mut *tx) + .await?; + let placed = sqlx::query_as!( + MenuDish, + "INSERT INTO menu_dish (id, menu, name, description, price_minor, tags, created_at) + SELECT $1, $2, $3, $4, $5, $6, $7 + WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $8 + RETURNING id, menu, name, description, price_minor, tags, created_at", + id, + menu_key, + name, + description, + price_minor, + tags, + created_at, + cap, + ) + .fetch_optional(&mut *tx) + .await?; + match placed { + Some(dish) => Ok(dish), + // The menu exists (locked above), so an empty result is the cap. + None => Err(AppError::Conflict( + "the menu already carries the maximum number of dishes", + )), + } + }) + .await } pub async fn read(db: &Database, id: &MenuDishId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let row = sqlx::query_as!( + MenuDish, + "SELECT id, menu, name, description, price_minor, tags, created_at + FROM menu_dish WHERE id = $1", + id.key(), + ) + .fetch_optional(db) + .await?; + Ok(row) } /// Every dish on one menu, in the order they were added. @@ -98,31 +101,28 @@ pub async fn list_for_menus(db: &Database, menus: &[MenuId]) -> Result>(), - )) - .await? - .check()?; - Ok(result.take::>(0)?) -} - -/// How many dishes the menu already carries — the `MAX_DISHES_PER_MENU` gate. -pub async fn count_for_menu(db: &Database, menu: &MenuId) -> Result { - Ok(list_for_menu(db, menu).await?.len()) + let keys: Vec = menus.iter().map(|m| m.key().to_string()).collect(); + let rows = sqlx::query_as!( + MenuDish, + "SELECT id, menu, name, description, price_minor, tags, created_at + FROM menu_dish WHERE menu = ANY($1) ORDER BY id ASC", + keys, + ) + .fetch_all(db) + .await?; + Ok(rows) } /// Write only the fields the PATCH carried. `description` is nullable, so /// it takes the three-way shape: absent = keep, `Some(None)` = clear. +/// Each field is spelled with a "was it on the request?" flag and its +/// nullable value, so an omitted field is never written and a concurrent +/// PATCH of another one is not reverted. /// -/// The `SET` is built here rather than by -/// [`FieldUpdate`](crate::db::field_update::FieldUpdate) because the -/// revision bump lands on *another* row and has to share this write's -/// transaction; the field-by-field scoping — an omitted field is never -/// written, so a concurrent PATCH of another one is not reverted — is the -/// same rule, spelled out. +/// The revision bump lands in the same transaction — "every dish write +/// bumps" is the rule a caller can rely on without knowing which fields +/// were on the wire. A PATCH that carried nothing still bumps and reads +/// the row back. pub async fn update( db: &Database, dish: MenuDish, @@ -131,45 +131,68 @@ pub async fn update( price_minor: Option, tags: Option, ) -> Result { - let mut sets: Vec<&str> = Vec::new(); - let mut bindings: Vec<(String, Value)> = vec![("id".into(), dish.id.record().into_value())]; - let mut set = |field: &'static str, value: Option| { - if let Some(value) = value { - sets.push(field); - bindings.push((field.into(), value)); + let dish_key = dish.id.key(); + let menu_key = dish.menu.key().to_string(); + tx_with_retry(db, false, async |tx| { + let bumped = sqlx::query!( + "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 + RETURNING 1 AS bumped", + menu_key, + ) + .fetch_optional(&mut *tx) + .await?; + if bumped.is_none() { + return Err(AppError::NotFound); } - }; - set("name", name.map(SurrealValue::into_value)); - set("description", description.map(SurrealValue::into_value)); - set("price_minor", price_minor.map(SurrealValue::into_value)); - set("tags", tags.map(SurrealValue::into_value)); - // A PATCH that carried nothing writes nothing and reads the row back, - // exactly as `FieldUpdate` answers one — but it still moves the - // revision, because "every dish write bumps" is the rule a caller can - // rely on without knowing which fields were on the wire. - let statement = if sets.is_empty() { - "SELECT * FROM $id".to_string() - } else { - format!( - "UPDATE $id SET {} RETURN AFTER", - sets.iter() - .map(|field| format!("{field} = ${field}")) - .collect::>() - .join(", ") + let row = sqlx::query_as!( + MenuDish, + "UPDATE menu_dish SET + name = COALESCE($2, name), + description = CASE WHEN $3 THEN $4 ELSE description END, + price_minor = COALESCE($5, price_minor), + tags = COALESCE($6, tags) + WHERE id = $1 + RETURNING id, menu, name, description, price_minor, tags, created_at", + dish_key, + name.map(|n| n.as_str().to_string()), + description.is_some(), + description + .clone() + .flatten() + .map(|d| d.as_str().to_string()), + price_minor.map(DishPrice::as_minor), + tags.map(|t| t.as_slice().to_vec()), ) - }; - bump_menu_and_write(&dish.menu, &statement, bindings, db) - .await? - .ok_or(AppError::NotFound) + .fetch_optional(&mut *tx) + .await?; + row.ok_or(AppError::NotFound) + }) + .await } pub async fn delete(db: &Database, dish: MenuDish) -> Result { - bump_menu_and_write( - &dish.menu, - "DELETE $id RETURN BEFORE", - vec![("id".into(), dish.id.record().into_value())], - db, - ) - .await? - .ok_or(AppError::NotFound) + let dish_key = dish.id.key(); + let menu_key = dish.menu.key().to_string(); + tx_with_retry(db, false, async |tx| { + let bumped = sqlx::query!( + "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 + RETURNING 1 AS bumped", + menu_key, + ) + .fetch_optional(&mut *tx) + .await?; + if bumped.is_none() { + return Err(AppError::NotFound); + } + let row = sqlx::query_as!( + MenuDish, + "DELETE FROM menu_dish WHERE id = $1 + RETURNING id, menu, name, description, price_minor, tags, created_at", + dish_key, + ) + .fetch_optional(&mut *tx) + .await?; + row.ok_or(AppError::NotFound) + }) + .await } diff --git a/src/db/note.rs b/src/db/note.rs index 30d93db..36b5caa 100644 --- a/src/db/note.rs +++ b/src/db/note.rs @@ -1,9 +1,7 @@ //! The `note` table: one user's rows, listed newest first, deleted together //! with their attachment rows. -use surrealdb::types::SurrealValue; - -use crate::database::Database; +use crate::database::{Database, tx_with_retry}; use crate::db::field_update::FieldUpdate; use crate::db::page::PagedList; use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; @@ -11,15 +9,6 @@ use crate::domain::note_file::NoteFile; use crate::domain::user::UserId; use crate::error::AppError; -/// What [`delete`]'s transaction removed: the note row (empty if it had -/// already vanished) and every attachment row the cascade took with it — the -/// only set whose blobs are safe to unlink. -#[derive(Debug, SurrealValue)] -struct DeleteOutcome { - note: Vec, - files: Vec, -} - pub async fn create( db: &Database, owner: &UserId, @@ -32,8 +21,20 @@ pub async fn create( title, content, }; - let created: Option = db.create(note.id.record()).content(note).await?; - created.ok_or_else(|| AppError::Internal("failed to create note".into())) + // whole-row-save-ok: insert of a fresh UUID row built in place by `new` — there is no prior row to clobber + let created = sqlx::query_as!( + Note, + r#"INSERT INTO note (id, app_user, title, content) + VALUES ($1, $2, $3, $4) + RETURNING id, app_user AS "user", title, content"#, + note.id, + note.user, + note.title, + note.content + ) + .fetch_one(db) + .await?; + Ok(created) } /// Read a note only if it belongs to `owner`. @@ -42,8 +43,15 @@ pub async fn read_owned( id: &NoteId, owner: &UserId, ) -> Result, AppError> { - let note: Option = db.select(id.record()).await?; - Ok(note.filter(|note| ¬e.user == owner)) + let note = sqlx::query_as!( + Note, + r#"SELECT id, app_user AS "user", title, content FROM note WHERE id = $1 AND app_user = $2"#, + id, + owner + ) + .fetch_optional(db) + .await?; + Ok(note) } pub async fn list_for( @@ -52,9 +60,9 @@ pub async fn list_for( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("note WHERE user = $usr", "ORDER BY id DESC") - .bind("usr", owner.record()) - .run(limit, offset, db) + PagedList::new("note WHERE app_user = $1", "ORDER BY id DESC") + .bind(owner.uuid()) + .run::(limit, offset, db) .await } @@ -70,9 +78,12 @@ pub async fn update( title: Option, content: Option, ) -> Result { - FieldUpdate::new(note.id.record()) - .set("title", title) - .set("content", content) + FieldUpdate::new("note", note.id.uuid()) + .set("title", title.map(|title| title.as_str().to_string())) + .set( + "content", + content.map(|content| content.as_str().to_string()), + ) .run::(db) .await } @@ -88,42 +99,48 @@ pub async fn update( /// Children first, in one transaction, the way /// [`crate::db::course::delete`] does it: as two queries, an /// upload that committed in between kept its row while the note went, and -/// nothing could ever list or delete it again. +/// nothing could ever list or delete it again. The `rag_output` sweep rides +/// here too: under real foreign keys a `rag_output` row citing this note +/// would refuse the delete (`ON DELETE NO ACTION`), and the derived rows +/// are exactly the thing that may never outlive its input — the web layer's +/// separate `delete_for_note` call stays, as a harmless idempotent repeat. pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec), AppError> { - let mut result = db - .query( - "BEGIN TRANSACTION; - LET $files = (DELETE note_file WHERE note = $note RETURN BEFORE); - LET $gone = (DELETE $note RETURN BEFORE); - RETURN { note: $gone, files: $files }; - COMMIT TRANSACTION;", + tx_with_retry(db, true, async |conn| { + sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id) + .execute(&mut *conn) + .await?; + let files = sqlx::query_as!( + NoteFile, + r#"DELETE FROM note_file WHERE note = $1 RETURNING id, note, name, content_type, size"#, + note.id + ) + .fetch_all(&mut *conn) + .await?; + let gone = sqlx::query_as!( + Note, + r#"DELETE FROM note WHERE id = $1 RETURNING id, app_user AS "user", title, content"#, + note.id ) - .bind(("note", note.id.record())) - .await? - .check()?; - // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3. - let outcome = result - .take::>(3)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to delete note".into()))?; - let note = outcome.note.into_iter().next().ok_or(AppError::NotFound)?; - Ok((note, outcome.files)) + .fetch_optional(&mut *conn) + .await?; + let note = gone.ok_or(AppError::NotFound)?; + Ok((note, files)) + }) + .await } #[cfg(test)] mod tests { use super::*; + use crate::domain::note_file::{FileContentType, FileName}; /// The blobs the handler unlinks are exactly the rows this transaction /// removed — including one uploaded after any pre-read snapshot would have /// been taken, which is the row whose blob used to leak. #[tokio::test] async fn delete_returns_the_attachment_rows_it_removed() { - use crate::domain::note_file::{FileContentType, FileName}; - let db = crate::database::init_mem().await.unwrap(); - let owner = crate::domain::user::UserId::generate(); + let owner = UserId::generate(); let note = create( &db, &owner, diff --git a/src/db/note_file.rs b/src/db/note_file.rs index 62f1b5a..bd38aff 100644 --- a/src/db/note_file.rs +++ b/src/db/note_file.rs @@ -2,9 +2,8 @@ //! first, with the note's file cap claimed and released in the same write as //! the row. -use crate::constant::{MAX_NOTE_FILES, NOTE_FILE_COUNT_FIELD}; -use crate::database::Database; -use crate::db::cap; +use crate::constant::MAX_NOTE_FILES; +use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::page::PagedList; use crate::domain::note::NoteId; use crate::domain::note_file::{NoteFile, NoteFileId}; @@ -12,31 +11,45 @@ use crate::error::AppError; /// Persist the row assembled by [`NoteFile::new`], refusing once its note /// already holds [`MAX_NOTE_FILES`]. The slot and the row are taken together -/// by [`cap::claim_and_create`] on the note row: a `BEGIN…COMMIT` around a -/// count can't enforce the cap (SurrealDB doesn't conflict-check a -/// cross-record count against a concurrent insert) and a process-wide mutex -/// can't either, since it is released around the very round trip the insert -/// races — a conditional single-record write can. Claiming in a *separate* -/// query would enforce the cap but leak a slot on a crash between the two. +/// by one conditional statement on the note row (the claim CTE of +/// `cap::claim_and_create`, spelled out at its call site — see +/// `crate::db::cap`): a `BEGIN…COMMIT` around a count can't enforce the cap +/// and a process-wide mutex can't either, since it is released around the +/// very round trip the insert races — a single guarded statement can. +/// Claiming in a *separate* query would enforce the cap but leak a slot on +/// a crash between the two. pub async fn insert(db: &Database, file: NoteFile) -> Result { - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber - match cap::claim_and_create( - &file.note.record(), - NOTE_FILE_COUNT_FIELD, + // whole-row-save-ok: insert of a fresh UUID row built in place by `new` — there is no prior row to clobber + let created = sqlx::query_as!( + NoteFile, + r#"WITH seat AS ( + UPDATE note SET file_count = file_count + 1 + WHERE id = $1 AND file_count < $2 + RETURNING 1) + INSERT INTO note_file (id, note, name, content_type, size) + SELECT $3, $1, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id, note, name, content_type, size"#, + file.note, MAX_NOTE_FILES as i64, - &file.id.record(), - &file, - db, + file.id, + file.name, + file.content_type, + file.size ) - .await? - { - cap::Claimed::Made(created) => Ok(created), + .fetch_optional(db) + .await; + match created { + Ok(Some(row)) => Ok(row), // Also how a missing note reads: no note row means no slot to take. - cap::Claimed::Full => Err(AppError::Conflict( + Ok(None) => Err(AppError::Conflict( "the note already holds the maximum of 10 files — delete one first", )), - // Unreachable: the id is a ULID this call just generated. - cap::Claimed::Duplicate => Err(AppError::Internal("failed to create note file".into())), + // A duplicate would be a 23505 on the row's own key, which this path + // cannot produce — the id is a UUID this call just generated. + Err(err) if unique_violation(&err).is_some() => { + Err(AppError::Internal("failed to create note file".into())) + } + Err(err) => Err(err.into()), } } @@ -47,8 +60,15 @@ pub async fn read_for( id: &NoteFileId, note: &NoteId, ) -> Result, AppError> { - let file: Option = db.select(id.record()).await?; - Ok(file.filter(|file| &file.note == note)) + let file = sqlx::query_as!( + NoteFile, + r#"SELECT id, note, name, content_type, size FROM note_file WHERE id = $1 AND note = $2"#, + id, + note + ) + .fetch_optional(db) + .await?; + Ok(file) } /// All of `note`'s attachment rows, newest first. @@ -58,9 +78,9 @@ pub async fn list_for( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("note_file WHERE note = $note", "ORDER BY id DESC") - .bind("note", note.record()) - .run(limit, offset, db) + PagedList::new("note_file WHERE note = $1", "ORDER BY id DESC") + .bind(note.uuid()) + .run::(limit, offset, db) .await } @@ -68,133 +88,102 @@ pub async fn list_for( /// itself is untouched, so unlike the note-delete cascade this one has a /// counter to correct. (Deleting a *note* takes its counter with it.) pub async fn delete(db: &Database, file: NoteFile) -> Result { - let mut result = db - .query( - "BEGIN TRANSACTION; - LET $gone = (DELETE $id RETURN BEFORE); - UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); - RETURN $gone; - COMMIT TRANSACTION;", + tx_with_retry(db, true, async |conn| { + let gone = sqlx::query_as!( + NoteFile, + r#"DELETE FROM note_file WHERE id = $1 RETURNING id, note, name, content_type, size"#, + file.id + ) + .fetch_optional(&mut *conn) + .await?; + let file = gone.ok_or(AppError::NotFound)?; + sqlx::query!( + "UPDATE note SET file_count = GREATEST(file_count - 1, 0) WHERE id = $1", + file.note ) - .bind(("id", file.id.record())) - .bind(("note", file.note.record())) - .await? - .check()?; - result - .take::>(3)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + .execute(&mut *conn) + .await?; + Ok(file) + }) + .await } #[cfg(test)] mod tests { use super::*; - use crate::domain::note_file::{FileContentType, FileName}; + use crate::domain::note::NoteContent; + use crate::domain::note::NoteTitle; + use crate::domain::note_file::FileContentType; + use crate::domain::note_file::FileName; - #[tokio::test] - async fn rows_scope_to_their_note() { - let db = crate::database::init_mem().await.unwrap(); - // Real note rows: the cap counter lives on the note, so an insert whose - // note does not exist has no slot to take (a 409, like a full note). + async fn a_note(db: &Database) -> Note { let owner = crate::domain::user::UserId::generate(); - let note_of = async |title: &str| { - crate::db::note::create( - &db, - &owner, - crate::domain::note::NoteTitle::try_new(title).unwrap(), - crate::domain::note::NoteContent::try_new("body").unwrap(), - ) - .await - .unwrap() - }; - let note_a = note_of("a").await.get_id().clone(); - let note_b = note_of("b").await.get_id().clone(); - let file = insert( - &db, - NoteFile::new( - ¬e_a, - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ), + crate::db::note::create( + db, + &owner, + NoteTitle::try_new("n").unwrap(), + NoteContent::try_new("b").unwrap(), ) .await - .unwrap(); - - // Readable under its own note, invisible under another. - let found = read_for(&db, file.get_id(), ¬e_a).await.unwrap(); - assert_eq!(found.unwrap().get_name().as_str(), "plan.pdf"); - assert!( - read_for(&db, file.get_id(), ¬e_b) - .await - .unwrap() - .is_none() - ); - - let listed = async |note: &NoteId| list_for(&db, note, None, 0).await.unwrap().0; - assert_eq!(listed(¬e_a).await.len(), 1); - assert!(listed(¬e_b).await.is_empty()); - - delete(&db, file).await.unwrap(); - assert!(listed(¬e_a).await.is_empty()); + .unwrap() } - /// The counter and the rows are written in one transaction, so the stored - /// count must equal the stored rows — after a success *and* after the - /// refusal that fills the cap, which must move neither. + /// The cap answers with a conflict, and neither the refused row nor its + /// slot was written: the count is still what the last accepted upload + /// left. #[tokio::test] - async fn counter_tracks_stored_rows() { + async fn insert_refuses_at_the_cap_without_leaking_a_slot() { let db = crate::database::init_mem().await.unwrap(); - let note = crate::db::note::create( - &db, - &crate::domain::user::UserId::generate(), - crate::domain::note::NoteTitle::try_new("a").unwrap(), - crate::domain::note::NoteContent::try_new("body").unwrap(), - ) - .await - .unwrap() - .get_id() - .clone(); - let stored_count = async |note: &NoteId| -> i64 { - db.query("SELECT VALUE file_count FROM $note") - .bind(("note", note.record())) - .await - .unwrap() - .take::>(0) - .unwrap() - .into_iter() - .next() - .unwrap_or(0) - }; - let add = async |note: &NoteId| { - insert( - &db, - NoteFile::new( - note, - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ), - ) - .await - }; - - for filled in 1..=MAX_NOTE_FILES { - add(¬e).await.unwrap(); - assert_eq!(stored_count(¬e).await, filled as i64); - assert_eq!( - list_for(&db, ¬e, None, 0).await.unwrap().1, - filled as i64 + let note = a_note(&db).await; + for index in 0..MAX_NOTE_FILES { + let file = NoteFile::new( + note.get_id(), + FileName::try_new(&format!("f{index}")).unwrap(), + FileContentType::try_new("text/plain").unwrap(), + 1, ); + insert(&db, file).await.unwrap(); } + let over = NoteFile::new( + note.get_id(), + FileName::try_new("over").unwrap(), + FileContentType::try_new("text/plain").unwrap(), + 1, + ); + assert!(matches!( + insert(&db, over).await, + Err(AppError::Conflict(_)) + )); + let (files, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); + assert_eq!(total, MAX_NOTE_FILES as i64); + assert_eq!(files.len(), MAX_NOTE_FILES); + } - // At the cap: the refusal writes nothing, counter included. - assert!(matches!(add(¬e).await, Err(AppError::Conflict(_)))); - assert_eq!(stored_count(¬e).await, MAX_NOTE_FILES as i64); - assert_eq!( - list_for(&db, ¬e, None, 0).await.unwrap().1, - MAX_NOTE_FILES as i64 + /// Deleting a row hands its slot back: after one delete a new upload is + /// accepted again, and the count never dips below zero. + #[tokio::test] + async fn delete_returns_the_slot_to_the_note() { + let db = crate::database::init_mem().await.unwrap(); + let note = a_note(&db).await; + let file = NoteFile::new( + note.get_id(), + FileName::try_new("f").unwrap(), + FileContentType::try_new("text/plain").unwrap(), + 1, + ); + let file = insert(&db, file).await.unwrap(); + let gone = delete(&db, file.clone()).await.unwrap(); + assert_eq!(gone.get_id(), file.get_id()); + // Deleting it a second time is a 404, not a second decrement. + assert!(matches!(delete(&db, file).await, Err(AppError::NotFound))); + let next = NoteFile::new( + note.get_id(), + FileName::try_new("next").unwrap(), + FileContentType::try_new("text/plain").unwrap(), + 1, ); + insert(&db, next).await.unwrap(); + let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); + assert_eq!(total, 1); } } diff --git a/src/db/pool_question.rs b/src/db/pool_question.rs index 0adf2c4..ead4505 100644 --- a/src/db/pool_question.rs +++ b/src/db/pool_question.rs @@ -1,137 +1,85 @@ //! The `pool_question` table: ask/insert, the two listings, the guarded //! approve that rides the publish counters along, the pending-only image -//! writes, and the delete that cascades solutions — plus -//! [`bump_question_and_write`], the existence-move every child write goes -//! through. The pure entity and newtypes live in -//! [`crate::domain::pool_question`]; the web layer reaches these through -//! [`crate::service::pool_question`]. - -use surrealdb::types::SurrealValue; - -use crate::constant::{ - POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD, STATUS_APPROVED, STATUS_PENDING, -}; -use crate::database::{Database, transaction_with_retry}; +//! writes, and the delete that cascades solutions. The pure entity and +//! newtypes live in [`crate::domain::pool_question`]; the web layer reaches +//! these through [`crate::service::pool_question`]. + +use crate::constant::{STATUS_APPROVED, STATUS_PENDING}; +use crate::database::{Database, tx_with_retry}; use crate::domain::note_file::FileContentType; use crate::domain::pool_question::{PoolQuestion, PoolQuestionId}; use crate::domain::solution::Solution; use crate::domain::user::UserId; use crate::error::AppError; -/// Move the question's `asked_at` **and** run `statement` — a write to -/// something hanging off a question — in one transaction, handing back the row -/// it returned. `NotFound` means the question is gone and nothing was written. -/// -/// The move is what makes the question's **existence** part of the child's own -/// write, the way [`crate::domain::menu::bump_menu_and_write`] does for a menu: -/// the `UPDATE` matches nothing once the row is deleted, and a delete racing -/// this one touches the very key this transaction writes, so the two cannot -/// both commit. Reading the question first does *not* survive that race — the -/// read sees a row [`delete`] has removed but not committed, while its -/// `DELETE solution WHERE question = $q` ran on a snapshot predating this -/// insert, so both commit and the child outlives its question with neither -/// caller told anything. -/// -/// `asked_at` rather than a revision column because this row carries no counter -/// to bump and must not grow one for this alone. It is put back *by captured -/// value* in the same transaction, so nothing outside ever observes the move -/// and the row is byte-identical afterwards (the pool lists order on it). -/// Writing the same value would buy nothing: an `UPDATE` that leaves the -/// document unchanged is elided and never reaches the store's write set, so it -/// collides with nothing. -/// -/// Admissible for [`transaction_with_retry`] as long as `statement` is: the -/// `UPDATE`s, `SELECT`, `IF`/`THROW` and `RETURN` can never answer "already -/// exists". -pub(crate) async fn bump_question_and_write( - question: &PoolQuestionId, - statement: &str, - mut bindings: Vec<(String, surrealdb::types::Value)>, - db: &Database, -) -> Result, AppError> { - bindings.push(("q".into(), question.record().into_value())); - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $was_asked = (SELECT VALUE asked_at FROM ONLY $q); - LET $bumped = (UPDATE $q SET asked_at = asked_at + 1 RETURN VALUE id); - IF array::len($bumped) = 0 {{ THROW 'no_question' }}; - UPDATE $q SET asked_at = $was_asked; - LET $row = ({statement}); - RETURN $row; - COMMIT TRANSACTION;" - ), - &bindings, - &["no_question"], +pub async fn insert(db: &Database, question: PoolQuestion) -> Result { + let row = sqlx::query_as!( + PoolQuestion, + r#"INSERT INTO pool_question (id, asker, title, body, status, asked_at) + VALUES ($1, $2, $3, $4, $5, $6) + RETURNING *"#, + question.id, + question.asker, + question.title, + question.body, + question.status, + question.asked_at, ) + .fetch_one(db) .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_question")) - { - 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); - Ok(result.take::>(slot)?.into_iter().next()) -} - -pub async fn insert(db: &Database, question: PoolQuestion) -> Result { - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber - let created: Option = db.create(question.id.record()).content(question).await?; - created.ok_or_else(|| AppError::Internal("failed to create pool question".into())) + Ok(row) } pub async fn read(db: &Database, id: &PoolQuestionId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let row = sqlx::query_as!( + PoolQuestion, + "SELECT * FROM pool_question WHERE id = $1", + id + ) + .fetch_optional(db) + .await?; + Ok(row) } /// Every question, newest first — the teacher+ view (approval queue and /// pool in one list). pub async fn list_all(db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC") - .await? - .check()?; - Ok(result.take::>(0)?) + let rows = sqlx::query_as!( + PoolQuestion, + "SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC", + ) + .fetch_all(db) + .await?; + Ok(rows) } /// The pool as a non-staff user sees it, newest first: every approved /// question, plus the caller's own pending ones. pub async fn list_visible_to(db: &Database, user: &UserId) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM pool_question WHERE status = $approved OR asker = $usr \ - ORDER BY asked_at DESC, id DESC", - ) - .bind(("approved", STATUS_APPROVED)) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + let rows = sqlx::query_as!( + PoolQuestion, + r#"SELECT * FROM pool_question + WHERE status = $1 OR asker = $2 + ORDER BY asked_at DESC, id DESC"#, + STATUS_APPROVED, + user + ) + .fetch_all(db) + .await?; + Ok(rows) } /// Publish a pending question into the pool, stamping who approved it. -/// The `WHERE status = $pending` guard makes the transition atomic: of two +/// The `WHERE status = 'pending'` guard makes the transition atomic: of two /// racing approvals exactly one wins, and an approve can never land on a /// question deleted mid-flight. `None` = the question wasn't pending /// (already approved, or gone) — the caller sorts out which. /// -/// Two lifetime badge counters ride that same guard, inside this +/// Two lifetime badge counters ride that same guard inside this /// transaction: the approver's `pool_approved_total` and the *asker's* -/// `pool_published_total`. Both hang off `array::len($done) > 0` — the -/// guard's own verdict — so the pair moves once per real transition and -/// never on a second approve of an already-approved question. -/// (`count ?? 0 > 0` misparses here; `array::len` is the spelling that -/// holds.) The second conjunct is the self-approval rule below. +/// `pool_published_total`. Both move only when the guard's own verdict +/// landed, so the pair moves once per real transition and never on a second +/// approve of an already-approved question. /// /// Two rules keep the pair unfarmable, one per side of the transition. /// @@ -144,56 +92,56 @@ pub async fn list_visible_to(db: &Database, user: &UserId) -> Result Result, AppError> { - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $done = (UPDATE $q SET status = $approved, approved_by = $by - WHERE status = $pending RETURN AFTER); - IF array::len($done) > 0 AND $done[0].asker != $by {{ - UPDATE $by SET - {POOL_APPROVED_TOTAL_FIELD} = ({POOL_APPROVED_TOTAL_FIELD} ?? 0) + 1; - LET $asker = $done[0].asker; - UPDATE $asker SET - {POOL_PUBLISHED_TOTAL_FIELD} = ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0) + 1; - }}; - RETURN $done; - COMMIT TRANSACTION;" - ), - &[ - ("q".into(), id.record().into_value()), - ("approved".into(), STATUS_APPROVED.to_string().into_value()), - ("by".into(), approver.record().into_value()), - ("pending".into(), STATUS_PENDING.to_string().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`, - // so its slot follows the statement count rather than a hand-kept - // number (`num_statements` counts `BEGIN` and `COMMIT` too, hence -2). - let slot = result.num_statements().saturating_sub(2); - Ok(result.take::>(slot)?.into_iter().next()) + tx_with_retry(db, false, async |tx| { + let approved = sqlx::query_as!( + PoolQuestion, + r#"UPDATE pool_question SET status = $2, approved_by = $3 + WHERE id = $1 AND status = $4 + RETURNING *"#, + *id, + STATUS_APPROVED, + approver, + STATUS_PENDING, + ) + .fetch_optional(tx) + .await?; + if let Some(question) = &approved { + if question.asker != *approver { + // The counter columns are NOT NULL DEFAULT 0 — the old + // absent-reads-as-zero coalesce is gone with the schema. + sqlx::query!( + "UPDATE app_user SET pool_approved_total = pool_approved_total + 1 + WHERE id = $1", + approver + ) + .execute(tx) + .await?; + sqlx::query!( + "UPDATE app_user SET pool_published_total = pool_published_total + 1 + WHERE id = $1", + question.asker + ) + .execute(tx) + .await?; + } + } + Ok(approved) + }) + .await } /// Point the question at a freshly written image blob. Guarded on @@ -202,6 +150,10 @@ pub async fn approve( /// loses the race gets `None` (and the caller takes the orphan blob back /// off disk). Returns the *before* row — its `image_file` is the replaced /// blob the caller must remove. +/// +/// The row lock makes the before-read and the guarded write one switch; a +/// racing approve either predates this transaction's snapshot or waits on +/// the lock, so a fresh image can never straddle an approval. pub async fn set_image( db: &Database, id: &PoolQuestionId, @@ -209,19 +161,35 @@ pub async fn set_image( content_type: &FileContentType, size: i64, ) -> Result, AppError> { - let mut result = db - .query( - "UPDATE $q SET image_file = $file, image_content_type = $ct, image_size = $size \ - WHERE status = $pending RETURN BEFORE", + tx_with_retry(db, false, async |tx| { + let before = sqlx::query_as!( + PoolQuestion, + "SELECT * FROM pool_question WHERE id = $1 FOR UPDATE", + *id ) - .bind(("q", id.record())) - .bind(("file", file.to_string())) - .bind(("ct", content_type.clone())) - .bind(("size", size)) - .bind(("pending", STATUS_PENDING)) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + .fetch_optional(tx) + .await?; + let Some(before) = before else { + return Ok(None); + }; + let written = sqlx::query!( + r#"UPDATE pool_question + SET image_file = $2, image_content_type = $3, image_size = $4 + WHERE id = $1 AND status = $5"#, + *id, + file, + content_type, + size, + STATUS_PENDING, + ) + .execute(tx) + .await?; + if written.rows_affected() == 0 { + return Ok(None); + } + Ok(Some(before)) + }) + .await } /// Detach the question's image (pending only, like `set_image`). Returns @@ -230,16 +198,32 @@ pub async fn clear_image( db: &Database, id: &PoolQuestionId, ) -> Result, AppError> { - let mut result = db - .query( - "UPDATE $q SET image_file = NONE, image_content_type = NONE, image_size = NONE \ - WHERE status = $pending RETURN BEFORE", + tx_with_retry(db, false, async |tx| { + let before = sqlx::query_as!( + PoolQuestion, + "SELECT * FROM pool_question WHERE id = $1 FOR UPDATE", + *id + ) + .fetch_optional(tx) + .await?; + let Some(before) = before else { + return Ok(None); + }; + let written = sqlx::query!( + r#"UPDATE pool_question + SET image_file = NULL, image_content_type = NULL, image_size = NULL + WHERE id = $1 AND status = $2"#, + *id, + STATUS_PENDING, ) - .bind(("q", id.record())) - .bind(("pending", STATUS_PENDING)) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + .execute(tx) + .await?; + if written.rows_affected() == 0 { + return Ok(None); + } + Ok(Some(before)) + }) + .await } /// Delete the question and its solutions in one transaction, returning @@ -247,34 +231,34 @@ pub async fn clear_image( /// caller can take every image blob off disk (solutions carry photos too, /// and a row-only sweep would strand theirs forever). /// -/// Rides the retry because a solution offer now writes this very row -/// ([`bump_question_and_write`]): the two contend by design, and a lost -/// round through a bare `check()` was a 500 for a delete that only had to -/// be re-sent. Admissible — a `DELETE` can never answer "already exists". +/// Children before the parent, so the foreign keys never refuse the parent +/// delete. `cascade = true` because a solution offer committing inside this +/// window makes the parent delete answer 23503 — a mid-cascade race the +/// retry loop re-runs, sweeping the latecomer with it. That foreign key is +/// also what keeps a solution from outliving its question on the insert +/// side, so the old existence-move transaction is simply gone. pub async fn delete( db: &Database, id: &PoolQuestionId, ) -> Result)>, AppError> { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - DELETE solution WHERE question = $q RETURN BEFORE; - DELETE $q RETURN BEFORE; - COMMIT TRANSACTION;", - &[("q".into(), id.record().into_value())], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN: the solution sweep is slot 1, the question slot 2. - let solutions = result.take::>(1)?; - Ok(result - .take::>(2)? - .into_iter() - .next() - .map(|question| (question, solutions))) + tx_with_retry(db, true, async |tx| { + let solutions = sqlx::query_as!( + Solution, + "DELETE FROM solution WHERE question = $1 RETURNING *", + *id + ) + .fetch_all(tx) + .await?; + let question = sqlx::query_as!( + PoolQuestion, + "DELETE FROM pool_question WHERE id = $1 RETURNING *", + *id + ) + .fetch_optional(tx) + .await?; + Ok(question.map(|question| (question, solutions))) + }) + .await } #[cfg(test)] diff --git a/src/db/rag_output.rs b/src/db/rag_output.rs index 767a9a9..a9c204a 100644 --- a/src/db/rag_output.rs +++ b/src/db/rag_output.rs @@ -1,13 +1,13 @@ -//! The `rag_output` table: what an AI service produced for a course note — -//! an index, a summary, an embedding manifest — stored as this side's own -//! copy of the answer. The AI service never writes here (it answers a -//! request over the bridge, and this side stores the answer), which is what -//! keeps the api-read bridge GET-only. Derived, disposable data: the row is -//! dropped and regenerated whenever its input changes, so the cascades -//! below — [`delete_for_note`] when the note goes, [`delete_with_source`] -//! when one of the attachments it was built from goes — keep a stale output -//! from outliving its input, even in a deployment with no AI service -//! connected. The row shape lives in [`crate::domain::rag_output`]. +//! What an AI service produced for a course note, stored on this side: the +//! write paths the api-read bridge serves (`create`/`replace_for_note` run +//! when this backend answers a request over the bridge, and this side stores +//! the answer), which is what keeps the api-read bridge GET-only. Derived, +//! disposable data: the row is dropped and regenerated whenever its input +//! changes, so the cascades below — [`delete_for_note`] when the note goes, +//! [`delete_with_source`] when one of the attachments it was built from goes +//! — keep a stale output from outliving its input, even in a deployment with +//! no AI service connected. The row shape lives in +//! [`crate::domain::rag_output`]. use crate::database::Database; use crate::db::page::PagedList; @@ -18,8 +18,8 @@ use crate::domain::rag_output::{RagOutput, RagOutputId}; use crate::domain::timestamp::Timestamp; use crate::error::AppError; use serde_json::Value; +use sqlx::types::Json; -/// Store one service output against `note`. pub async fn create( db: &Database, note: &CourseNoteId, @@ -32,16 +32,39 @@ pub async fn create( course_note: note.clone(), course: course.clone(), sources, - payload, + payload: sqlx::types::Json(payload), generated_at: Timestamp::now(), }; - // whole-row-save-ok: create of a fresh ULID row built in place — there is no prior row to clobber - let created: Option = db.create(row.id.record()).content(row).await?; - created.ok_or_else(|| AppError::Internal("failed to create rag output".into())) + // whole-row-save-ok: insert of a fresh UUID row built in place — there is no prior row to clobber + let created = sqlx::query_as!( + RagOutput, + r#"INSERT INTO rag_output (id, course_note, course, sources, payload, generated_at) + VALUES ($1, $2, $3, $4, $5, $6) + RETURNING id, course_note, course, sources, + payload AS "payload: Json", generated_at"#, + row.id, + row.course_note, + row.course, + &row.sources, + &row.payload, + row.generated_at + ) + .fetch_one(db) + .await?; + Ok(created) } pub async fn read(db: &Database, id: &RagOutputId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let row = sqlx::query_as!( + RagOutput, + r#"SELECT id, course_note, course, sources, + payload AS "payload: Json", generated_at + FROM rag_output WHERE id = $1"#, + id + ) + .fetch_optional(db) + .await?; + Ok(row) } /// A note's outputs, newest first. @@ -51,24 +74,31 @@ pub async fn list_for( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("rag_output WHERE course_note = $note", "ORDER BY id DESC") - .bind("note", note.record()) - .run(limit, offset, db) + PagedList::new("rag_output WHERE course_note = $1", "ORDER BY id DESC") + .bind(note.uuid()) + .run::(limit, offset, db) .await } pub async fn delete(db: &Database, id: &RagOutputId) -> Result { - let deleted: Option = db.delete(id.record()).await?; + let deleted = sqlx::query_as!( + RagOutput, + r#"DELETE FROM rag_output WHERE id = $1 + RETURNING id, course_note, course, sources, + payload AS "payload: Json", generated_at"#, + id + ) + .fetch_optional(db) + .await?; deleted.ok_or(AppError::NotFound) } /// Cascade: every output of `note`. Deleting none is a success — a note /// no service ever indexed has nothing to drop. pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> { - db.query("DELETE rag_output WHERE course_note = $note") - .bind(("note", note.record())) - .await? - .check()?; + sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note) + .execute(db) + .await?; Ok(()) } @@ -76,7 +106,9 @@ pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), A /// this note's older rows. Two concurrent index tasks can interleave in any /// order and still leave exactly one row — the newest — because ids come /// from the process-wide monotonic generator, so "older" is `id <` the row -/// just written and the loser's row is always below the winner's. +/// just written and the loser's row is always below the winner's. (The +/// uuid column compares in byte order, which for UUIDv7 is mint order — +/// the same property the old record ids got from the ULID.) pub async fn replace_for_note( db: &Database, note: &CourseNoteId, @@ -85,22 +117,24 @@ pub async fn replace_for_note( payload: Value, ) -> Result { let created = create(db, note, course, sources, payload).await?; - db.query("DELETE rag_output WHERE course_note = $note AND id < $new") - .bind(("note", note.record())) - .bind(("new", created.id.record())) - .await? - .check()?; + sqlx::query!( + "DELETE FROM rag_output WHERE course_note = $1 AND id < $2", + note, + created.id + ) + .execute(db) + .await?; Ok(created) } /// Cascade: every output built from `file`. Runs on a file delete even /// with no AI service connected, so a stale output cannot survive its -/// source. +/// source. The GIN index on `sources` turns the containment test into a +/// lookup. pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> { - db.query("DELETE rag_output WHERE sources CONTAINS $file") - .bind(("file", file.record())) - .await? - .check()?; + sqlx::query!("DELETE FROM rag_output WHERE $1 = ANY(sources)", file) + .execute(db) + .await?; Ok(()) } @@ -108,8 +142,12 @@ pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Resul mod tests { use super::*; use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; - use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; - use crate::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; + use crate::domain::course_note::CourseNote; + use crate::domain::course_note::CourseNoteContent; + use crate::domain::course_note::CourseNoteTitle; + use crate::domain::course_note_file::CourseNoteFile; + use crate::domain::course_note_file::FileContentType; + use crate::domain::course_note_file::FileName; use serde_json::json; async fn note_of(db: &Database, title: &str) -> CourseNote { @@ -136,108 +174,92 @@ mod tests { .unwrap() } - async fn file_on(db: &Database, note: &CourseNoteId) -> CourseNoteFileId { - let file = CourseNoteFile::new( - note, - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, + async fn a_file(db: &Database, note: &CourseNote) -> CourseNoteFile { + crate::db::course_note_file::insert( + db, + CourseNoteFile::new( + note.get_id(), + FileName::try_new("f").unwrap(), + FileContentType::try_new("text/plain").unwrap(), + 1, + ), ) -; - crate::db::course_note_file::insert(db, file) .await .unwrap() - .get_id() - .clone() } - /// Replace converges on one row — the newest — even when an earlier - /// interleaving already left two rows behind for the note. + /// A stored round-trips through JSONB with its sources list intact, and + /// the note cascade takes every row of the note with it. #[tokio::test] - async fn replace_keeps_only_the_newest_output() { + async fn create_reads_back_and_cascades_from_the_note() { let db = crate::database::init_mem().await.unwrap(); - let note = note_of(&db, "a").await; - let stale = create( - &db, - note.get_id(), - note.get_course(), - Vec::new(), - json!({ "n": 1 }), - ) - .await - .unwrap(); - // The race this fixes: a second row for the same note. - create( - &db, - note.get_id(), - note.get_course(), - Vec::new(), - json!({ "n": 2 }), - ) - .await - .unwrap(); - - let fresh = replace_for_note( + let note = note_of(&db, "n").await; + let file = a_file(&db, ¬e).await; + let row = create( &db, note.get_id(), note.get_course(), - Vec::new(), - json!({ "n": 3 }), + vec![file.get_id().clone()], + json!({"answer": "x"}), ) .await .unwrap(); + let read = read(&db, row.get_id()).await.unwrap().unwrap(); + assert_eq!(read.get_payload(), &json!({"answer": "x"})); + assert_eq!(read.get_sources(), &[file.get_id().clone()]); - let rows = list_for(&db, note.get_id(), None, 0).await.unwrap().0; - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].get_id(), fresh.get_id()); - assert!(fresh.get_id().key() > stale.get_id().key()); + delete_for_note(&db, note.get_id()).await.unwrap(); + assert!(read(&db, row.get_id()).await.unwrap().is_none()); } - /// The payload survives the round trip unread, and both cascades take only - /// what they are aimed at. + /// Replace leaves exactly one row — the newest — and the source cascade + /// drops a row built from a file that is gone. #[tokio::test] - async fn outputs_round_trip_and_cascade() { + async fn replace_is_newest_wins_and_source_cascade_drops() { let db = crate::database::init_mem().await.unwrap(); - let note = note_of(&db, "a").await; - let other = note_of(&db, "b").await; - let file = file_on(&db, note.get_id()).await; - - let stored = create( + let note = note_of(&db, "n").await; + let file = a_file(&db, ¬e).await; + let first = create( &db, note.get_id(), note.get_course(), - vec![file.clone()], - json!({ "summary": "x", "chunks": [{ "text": "y" }] }), + vec![file.get_id().clone()], + json!({"v": 1}), ) .await .unwrap(); - let roundtrip = read(&db, stored.get_id()).await.unwrap().unwrap(); - assert_eq!(roundtrip.get_payload()["summary"], "x"); - assert_eq!(roundtrip.get_payload()["chunks"][0]["text"], "y"); - assert_eq!(roundtrip.get_sources(), std::slice::from_ref(&file)); - assert_eq!(roundtrip.get_course(), note.get_course()); - let untouched = create( + let second = replace_for_note( &db, - other.get_id(), - other.get_course(), - Vec::new(), - json!({ "summary": "z" }), + note.get_id(), + note.get_course(), + vec![file.get_id().clone()], + json!({"v": 2}), ) .await .unwrap(); + let (rows, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); + assert_eq!(total, 1); + assert_eq!(rows[0].get_id(), second.get_id()); + assert!(first.get_id() != second.get_id()); - let listed = - async |note: &CourseNoteId| list_for(&db, note, None, 0).await.unwrap().0.len(); - assert_eq!(listed(note.get_id()).await, 1); - - // Losing a source drops the output that cited it, and nothing else. - delete_with_source(&db, &file).await.unwrap(); - assert_eq!(listed(note.get_id()).await, 0); - assert_eq!(listed(other.get_id()).await, 1); + delete_with_source(&db, file.get_id()).await.unwrap(); + let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); + assert_eq!(total, 0); + } - // Cascading a note with no outputs left is still a success. - delete_for_note(&db, note.get_id()).await.unwrap(); - delete_for_note(&db, other.get_id()).await.unwrap(); - assert!(read(&db, untouched.get_id()).await.unwrap().is_none()); + /// Deleting one row returns it; deleting it again is a 404. + #[tokio::test] + async fn delete_returns_the_row_then_refuses() { + let db = crate::database::init_mem().await.unwrap(); + let note = note_of(&db, "n").await; + let row = create(&db, note.get_id(), note.get_course(), Vec::new(), json!({})) + .await + .unwrap(); + let gone = delete(&db, row.get_id()).await.unwrap(); + assert_eq!(gone.get_id(), row.get_id()); + assert!(matches!( + delete(&db, row.get_id()).await, + Err(AppError::NotFound) + )); } } diff --git a/src/db/session_attendance.rs b/src/db/session_attendance.rs index 4da8609..c18781a 100644 --- a/src/db/session_attendance.rs +++ b/src/db/session_attendance.rs @@ -4,60 +4,30 @@ //! management's, only students attend, enrollment) are //! [`crate::service::session_attendance`]'s to judge before calling here. -use surrealdb::types::SurrealValue; - -use crate::constant::{ - LESSON_COUNTED_AT_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, LESSONS_HELD_TOTAL_FIELD, -}; -use crate::database::{Database, transaction_with_retry}; +use crate::database::{Database, tx_with_retry}; use crate::db::page::PagedList; use crate::domain::attendance::AttendanceStatus; use crate::domain::course_session::{CourseSession, CourseSessionId}; -use crate::domain::session_attendance::{ - SessionAttendance, SessionAttendanceId, counts_as_attended, -}; +use crate::domain::session_attendance::SessionAttendance; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; -/// Record (or overwrite) `user`'s status for the session. One row per -/// (session, user), keyed by a deterministic composite id so this is a -/// single atomic UPSERT — concurrent marks converge on the one row. -/// -/// The "session still exists" gate rides in the same transaction as the -/// mark, the mirror of the cascade in [`crate::db::course_session::delete`]: the -/// caller's pre-flight read sits four round trips in front of this write, -/// so a delete landing in that gap used to leave a roll-call row on a -/// session that was gone — and that row was *unremovable*, its only delete -/// route 404ing on the vanished session while the attendance report went -/// on counting it. A deleted session reads NONE, which is falsy, so the -/// gate is written as an explicit `IS NONE` (see -/// [`crate::domain::exam_result::ExamResult::grade`]). It reads the -/// session's `teacher` — required on every row, so NONE means "no row" just -/// as `id` did — because the counter below needs that teacher anyway, and -/// one read serves both. -/// -/// A read is not a claim, though: SurrealDB 3.2.3 conflict-checks write -/// sets, not read sets, so that gate alone only closes the *sequential* -/// order (delete committed, then the mark arrives). To make the two really -/// collide, this transaction also *writes* the session row, unconditionally -/// — the bump-and-restore of [`crate::domain::exam_answer::ExamAnswer::save`] -/// on the one column this write already owns, [`LESSON_COUNTED_AT_FIELD`]. -/// Unconditional is the whole point: the credit branch below writes that -/// column already, but it fires only for the first roll call of a lesson -/// that has begun, so a future-dated sheet and every re-mark of a counted -/// one touched nothing at all and committed happily beside -/// `DELETE /sessions/{id}`. Re-stating the value verbatim would not do -/// either — an `UPDATE` that leaves the document unchanged is elided and -/// never enters the write set — hence bump first, then either stamp -/// (credit branch) or put back exactly what was found, `NONE` included, so -/// the row is byte-identical and the once-per-lesson rule is untouched. +/// Record (or overwrite) `user`'s status for the session. The table's +/// primary key *is* the (session, user) pair, so the mark is a single +/// atomic upsert — concurrent marks converge on the one row. /// -/// Sound to re-send while the store answers "conflict, retry": the gate -/// reads the record a delete writes, so the two contend by design, and the -/// UPSERT cannot legitimately answer "already exists" — its composite id is -/// bijective with the `session_attendance_session_user` unique tuple, so -/// the index entry can only point at the row the id already names. +/// The "session still exists" gate is a row lock: the transaction takes the +/// session row `FOR NO KEY UPDATE` before anything else, so a session (or +/// course) delete cascading beneath this mark simply waits, and a delete +/// that got there first leaves this gate matching nothing — `404`, the +/// mirror of [`crate::db::course_session::delete`]. The caller's +/// pre-flight read sits several round trips in front of this write, which +/// is exactly the gap the old code had to fake with a bump-and-restore +/// write on the session row; the lock is the same serialization without +/// the trick. It also freezes `starts_at` and `held_counted_at` for the +/// transaction, so two simultaneous first marks take turns and the +/// lesson-held credit below is stamped exactly once. /// /// Two badge counters move in this same transaction, both of them read /// from the store rather than taken on the caller's word: @@ -65,27 +35,27 @@ use crate::error::AppError; /// - `lessons_attended_total`, on the person marked, as a *delta* rather /// than an increment, because this is an upsert: a re-mark that changes /// nothing must change nothing, and a teacher's correction must move it -/// back down. `$was` is read before the upsert overwrites it (`NONE` when -/// the pair has no row yet), so it writes only on a real crossing of the -/// attended line, and only for a **student** — attending lessons is a -/// student's badge, the same student-only rule enrolling and sitting an -/// exam already carry, so a teacher marked present in their own lesson -/// moves it in neither direction. The live `role` decides that, not the -/// role someone held when the row was written. +/// back down. The pair's stored status is read before the upsert +/// overwrites it (`None` when the pair has no row yet), so it writes +/// only on a real crossing of the attended line, and only for a +/// **student** — attending lessons is a student's badge, the same +/// student-only rule enrolling and sitting an exam already carry, so a +/// teacher marked present in their own lesson moves it in neither +/// direction. The live `role` decides that, not the role someone held +/// when the row was written. /// - `lessons_held_total`, on the *session's* teacher, exactly once per -/// session: the first roll call taken stamps -/// [`LESSON_COUNTED_AT_FIELD`] on the lesson and every later mark sees -/// the stamp and credits nothing. It counts lessons that actually -/// happened — scheduling one and cancelling it earns nothing, which is -/// why the credit does not live in `crate::db::course_session::create`. Two -/// simultaneous first marks both write the lesson row, so the store's own -/// conflict detection (and `transaction_with_retry` behind it) is what -/// keeps the stamp from being set twice. +/// session: the first roll call taken stamps `held_counted_at` on the +/// lesson and every later mark sees the stamp and credits nothing. It +/// counts lessons that actually happened — scheduling one and +/// cancelling it earns nothing, which is why the credit does not live +/// in `crate::db::course_session::create`. Two simultaneous first +/// marks serialize on the session row's lock, so the stamp cannot be +/// set twice. /// /// "Actually happened" is a clock reading, not a request count: the /// credit waits for the lesson's own `starts_at` to arrive. Roll call is -/// deliberately *not* time-gated — a teacher may open the sheet early and -/// is never refused — so without this a teacher could schedule two +/// deliberately *not* time-gated — a teacher may open the sheet early +/// and is never refused — so without this a teacher could schedule two /// hundred lessons for next week, mark one student in each, and hold two /// hundred lessons this afternoon. Because the stamp is written only on /// the branch that credits, a sheet opened early and touched again after @@ -100,9 +70,6 @@ use crate::error::AppError; /// credited — a student's real lessons eaten by someone else's farm. It /// is also nobody's self-service: only a teacher can mark a student, so /// the counter cannot be moved by the person it decorates. -/// -/// Both are floored/guarded rather than trusting the column to exist: a row -/// written before these columns carries none of them. // // corner-cut: that asymmetry leaves a teacher able to inflate a *student's* // attendance with future-dated lessons. Closing it needs the credit stamped @@ -117,76 +84,94 @@ pub async fn mark( status: AttendanceStatus, marked_by: &UserId, ) -> Result { - let attended = counts_as_attended(&status); + let attended = crate::domain::session_attendance::counts_as_attended(&status); let delta: i64 = if attended { 1 } else { -1 }; - let attendance = SessionAttendance { - id: SessionAttendanceId::composite(session.get_id(), user), - session: session.get_id().clone(), - course: session.get_course().clone(), - user: user.clone(), - status, - marked_by: marked_by.clone(), - }; - let (mut written, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $teacher = (SELECT VALUE teacher FROM ONLY $sess); - IF $teacher IS NONE {{ THROW 'session_missing' }}; - LET $counted = (SELECT VALUE {LESSON_COUNTED_AT_FIELD} FROM ONLY $sess); - LET $begun = ((SELECT VALUE starts_at FROM ONLY $sess) <= $stamp); - LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student'); - LET $was = ((SELECT VALUE status FROM ONLY $id) IN ['present', 'late']); - LET $after = (UPSERT $id CONTENT $row RETURN AFTER); - IF $student AND $was != $now {{ - UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = - math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) + $delta, 0]) - }}; - UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = ({LESSON_COUNTED_AT_FIELD} ?? 0) + 1; - IF ($counted IS NONE) AND $begun {{ - UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $stamp; - UPDATE $teacher SET {LESSONS_HELD_TOTAL_FIELD} = - ({LESSONS_HELD_TOTAL_FIELD} ?? 0) + 1 - }} ELSE {{ - UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $counted - }}; - RETURN $after; - COMMIT TRANSACTION;" - ), - &[ - // `$session` is SurrealDB's own protected variable (the auth - // session): binding that name errors the whole query. - ("sess".into(), session.get_id().record().into_value()), - ("id".into(), attendance.id.record().into_value()), - ("usr".into(), user.record().into_value()), - ("now".into(), attended.into_value()), - ("delta".into(), delta.into_value()), - ("stamp".into(), Timestamp::now().into_value()), - ("row".into(), attendance.into_value()), - ], - &["session_missing"], - ) - .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. - if errors - .values() - .any(|error| error.to_string().contains("session_missing")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`, - // so its slot follows the statement count instead of a hand-kept one. - let slot = written.num_statements().saturating_sub(2); - written - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to mark session attendance".into())) + let now = Timestamp::now(); + tx_with_retry(db, false, async |tx| { + // The gate and the serialization point: a live session row, locked + // against the delete cascade and every rival mark. + let sess = sqlx::query!( + r#"SELECT teacher, starts_at, held_counted_at + FROM course_session WHERE id = $1 FOR NO KEY UPDATE"#, + session.id, + ) + .fetch_optional(&mut *tx) + .await?; + let Some(sess) = sess else { + return Err(AppError::NotFound); + }; + // The pair's stored status — the pre-image the attended delta is + // computed off. + let was = sqlx::query!( + r#"SELECT status FROM session_attendance + WHERE session = $1 AND app_user = $2"#, + session.id, + user, + ) + .fetch_optional(&mut *tx) + .await? + .map(|row| row.status); + // The live role of the person marked (a gone user row marks as + // non-student — no badge to move; the service gate has already + // refused a vanished target before this write ran). + let is_student = sqlx::query!( + r#"SELECT role = 'student' AS "is_student" FROM app_user WHERE id = $1"#, + user, + ) + .fetch_optional(&mut *tx) + .await? + .map(|row| row.is_student) + .unwrap_or(false); + let row = sqlx::query_as!( + SessionAttendance, + r#"INSERT INTO session_attendance (session, app_user, course, status, marked_by) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (session, app_user) DO UPDATE + SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by + RETURNING session, app_user AS "user", course, status, marked_by"#, + session.id, + user, + session.course, + status, + marked_by, + ) + .fetch_one(&mut *tx) + .await?; + // The attended badge: student-only, and only on a real crossing. + let was_attended = was + .as_deref() + .is_some_and(|was| was == "present" || was == "late"); + if is_student && was_attended != attended { + sqlx::query!( + r#"UPDATE app_user + SET lessons_attended_total = GREATEST(lessons_attended_total + $2, 0) + WHERE id = $1"#, + user, + delta, + ) + .execute(&mut *tx) + .await?; + } + // The held badge: once per lesson, and only once the lesson began. + if sess.held_counted_at.is_none() && sess.starts_at <= now.as_millis() { + sqlx::query!( + r#"UPDATE course_session SET held_counted_at = $2 WHERE id = $1"#, + session.id, + now.as_millis(), + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"UPDATE app_user SET lessons_held_total = lessons_held_total + 1 + WHERE id = $1"#, + sess.teacher, + ) + .execute(&mut *tx) + .await?; + } + Ok(row) + }) + .await } pub async fn list_for_session( @@ -195,10 +180,16 @@ pub async fn list_for_session( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("session_attendance WHERE session = $s", "ORDER BY id DESC") - .bind("s", session.record()) - .run(limit, offset, db) - .await + // The old composite key `{session}_{user}` sorted by user within a + // session — its session prefix was constant — so the natural-PK + // columns sort the same way. + PagedList::new( + "session_attendance WHERE session = $1", + "ORDER BY session DESC, app_user DESC", + ) + .bind(session.uuid()) + .run::(limit, offset, db) + .await } /// Every roll-call row ever recorded for `user` — the session half of the @@ -209,12 +200,16 @@ pub async fn list_for_user( db: &Database, user: &UserId, ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM session_attendance WHERE user = $usr ORDER BY id DESC") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + let rows = sqlx::query_as!( + SessionAttendance, + r#"SELECT session, app_user AS "user", course, status, marked_by + FROM session_attendance WHERE app_user = $1 + ORDER BY session DESC, app_user DESC"#, + user, + ) + .fetch_all(db) + .await?; + Ok(rows) } /// Clearing a row the student was counted for gives the count back, in the @@ -229,50 +224,60 @@ pub async fn list_for_user( /// /// Student-only on the same terms as the mark, and read from the store for /// the same reason. -/// -/// Sound to re-send: neither statement can answer "already exists". -// -// corner-cut: both ends read the *live* role, so a student promoted between -// being marked present and having that row corrected leaves the counter one -// high (the credit landed as a student, the refund is refused as staff). -// Upgrade path is stamping the credit on the roll-call row itself and -// refunding off that stamp, the way `counted_on_time` works for homework — -// not worth a column until a promotion mid-term is a real complaint. pub async fn remove( db: &Database, session: &CourseSessionId, user: &UserId, ) -> Result, AppError> { - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student'); - LET $gone = (DELETE session_attendance - WHERE session = $s AND user = $usr RETURN BEFORE); - IF $student AND array::len($gone) > 0 AND $gone[0].status IN ['present', 'late'] {{ - UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = - math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) - 1, 0]) - }}; - RETURN $gone; - COMMIT TRANSACTION;" - ), - &[ - ("s".into(), session.record().into_value()), - ("usr".into(), user.record().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`. - let slot = result.num_statements().saturating_sub(2); - Ok(result - .take::>(slot)? - .into_iter() - .next()) + tx_with_retry(db, false, async |tx| { + // The pre-image and the row's right to exist in one locked + // statement: the row cannot vanish (or change status) under this + // transaction, and `None` here is simply "nothing to remove". + let Some(gone) = sqlx::query_as!( + SessionAttendance, + r#"SELECT session, app_user AS "user", course, status, marked_by + FROM session_attendance + WHERE session = $1 AND app_user = $2 + FOR UPDATE"#, + session, + user, + ) + .fetch_optional(&mut *tx) + .await? + else { + return Ok(None); + }; + if crate::domain::session_attendance::counts_as_attended(&gone.status) { + // Student-only, live role: the same rule the mark pays. + let student = sqlx::query!( + r#"SELECT role = 'student' AS "is_student" FROM app_user WHERE id = $1"#, + user, + ) + .fetch_optional(&mut *tx) + .await? + .map(|row| row.is_student) + .unwrap_or(false); + if student { + sqlx::query!( + r#"UPDATE app_user + SET lessons_attended_total = GREATEST(lessons_attended_total - 1, 0) + WHERE id = $1"#, + user, + ) + .execute(&mut *tx) + .await?; + } + } + sqlx::query!( + r#"DELETE FROM session_attendance WHERE session = $1 AND app_user = $2"#, + session, + user, + ) + .execute(&mut *tx) + .await?; + Ok(Some(gone)) + }) + .await } #[cfg(test)] @@ -345,7 +350,10 @@ mod tests { } async fn held(user: &UserId, db: &Database) -> i64 { - crate::db::badge::load(db, user).await.unwrap().get_lessons_held() + crate::db::badge::load(db, user) + .await + .unwrap() + .get_lessons_held() } /// The whole transition table in one pass: an upsert may only move the diff --git a/src/db/solution.rs b/src/db/solution.rs index 8ab5938..e12c8ed 100644 --- a/src/db/solution.rs +++ b/src/db/solution.rs @@ -1,54 +1,54 @@ -//! The `solution` table: offers (through the pool question's -//! existence-move), the question-scoped reads and page, the grouped counts, +//! The `solution` table: offers (their question's existence enforced by the +//! real foreign key), the question-scoped read and page, the grouped counts, //! and the unconditional body/image writes of an unmoderated row. The pure //! entity and newtypes live in [`crate::domain::solution`]; the web layer //! reaches these through [`crate::service::solution`]. use std::collections::HashMap; -use surrealdb::types::{RecordId, SurrealValue}; - -use crate::database::Database; +use crate::database::{Database, tx_with_retry}; use crate::db::page::PagedList; -use crate::db::pool_question::bump_question_and_write; use crate::domain::note_file::FileContentType; use crate::domain::pool_question::PoolQuestionId; use crate::domain::solution::{Solution, SolutionBody, SolutionId}; use crate::error::AppError; -/// One `GROUP BY question` row of [`counts_for`]. -#[derive(SurrealValue)] -struct SolutionCount { - question: PoolQuestionId, - n: i64, -} - /// Offer the solution. `NotFound` = the question is gone, and nothing was -/// written: the create rides [`bump_question_and_write`], so the question's -/// existence is a *write* to its row rather than a read the handler made a -/// moment earlier — a bare create landing inside -/// [`crate::db::pool_question::delete`]'s -/// window was swept by nothing and left a solution no route could ever -/// reach or remove (every path to one goes through its question), photo -/// blob included. +/// written: the insert's foreign key (`solution_question_fkey`) refuses an +/// orphan the old existence-move transaction spent five statements dodging — +/// a bare create landing inside +/// [`crate::db::pool_question::delete`]'s window used to be swept by +/// nothing and left a solution no route could ever reach or remove (every +/// path to one goes through its question), photo blob included. /// -/// Re-sendable despite the `CREATE`: `$id` is a ULID minted once per call -/// on a table with no `UNIQUE` index, so a re-send cannot answer "already -/// exists" — the one thing the retry could not survive. +/// The author's own foreign key never fires in practice (the request +/// carries a live session user) and stays a database error if it ever does; +/// only the question's key maps to the 404. pub async fn insert(db: &Database, solution: Solution) -> Result { - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber - let (question, id) = (solution.question.clone(), solution.id.record()); - bump_question_and_write( - &question, - "CREATE $id CONTENT $solution", - vec![ - ("id".into(), id.into_value()), - ("solution".into(), solution.into_value()), - ], - db, + match sqlx::query_as!( + Solution, + r#"INSERT INTO solution (id, question, author, body, offered_at) + VALUES ($1, $2, $3, $4, $5) + RETURNING *"#, + solution.id, + solution.question, + solution.author, + solution.body, + solution.offered_at, ) - .await? - .ok_or_else(|| AppError::Internal("failed to create solution".into())) + .fetch_one(db) + .await + { + Ok(row) => Ok(row), + Err(err) if is_question_gone(&err) => Err(AppError::NotFound), + Err(err) => Err(err.into()), + } +} + +/// Did this insert fail on the *question* foreign key — the parent-gone +/// refusal — rather than some unrelated database fault? +fn is_question_gone(err: &sqlx::Error) -> bool { + err.as_database_error().and_then(|db| db.constraint()) == Some("solution_question_fkey") } /// Read a solution only if it belongs to `question` — keeps the nested @@ -58,32 +58,40 @@ pub async fn read_for( id: &SolutionId, question: &PoolQuestionId, ) -> Result, AppError> { - let solution: Option = db.select(id.record()).await?; - Ok(solution.filter(|solution| &solution.question == question)) + let row = sqlx::query_as!( + Solution, + "SELECT * FROM solution WHERE id = $1 AND question = $2", + id, + question + ) + .fetch_optional(db) + .await?; + Ok(row) } /// The question's solutions, oldest first — a discussion reads downward. /// Ordered by `offered_at`; the `id` tiebreak only makes same-millisecond -/// offers *stable* across re-queries, not insertion-ordered (ULID low bits -/// are random within a millisecond, so same-ms order is arbitrary). +/// offers *stable* across re-queries (the ids are write-ordered UUIDv7, so +/// same-ms rows still sort by mint order). pub async fn list_for( db: &Database, question: &PoolQuestionId, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { + // `.uuid()` feeds the builder its raw bind value — exact, typed. PagedList::new( - "solution WHERE question = $q", + "solution WHERE question = $1", "ORDER BY offered_at ASC, id ASC", ) - .bind("q", question.record()) + .bind(question.uuid()) .run(limit, offset, db) .await } /// Per-question solution tallies for a page of questions, in one grouped /// query — a per-row `count()` would cost a query per question. Keys are -/// question record keys; a question with no solutions has no entry, so +/// the questions' wire keys; a question with no solutions has no entry, so /// the caller reads misses as zero. pub async fn counts_for( db: &Database, @@ -92,18 +100,19 @@ pub async fn counts_for( if questions.is_empty() { return Ok(HashMap::new()); } - let ids: Vec = questions.iter().map(|question| question.record()).collect(); - let mut result = db - .query( - "SELECT question, count() AS n FROM solution WHERE question IN $qs GROUP BY question", - ) - .bind(("qs", ids)) - .await? - .check()?; - Ok(result - .take::>(0)? + let ids: Vec = questions.iter().copied().collect(); + let rows = sqlx::query!( + r#"SELECT question AS "question: PoolQuestionId", count(*) AS n + FROM solution + WHERE question = ANY($1) + GROUP BY question"#, + ids, + ) + .fetch_all(db) + .await?; + Ok(rows .into_iter() - .map(|row| (row.question.key().to_string(), row.n)) + .map(|row| (row.question.key(), row.n)) .collect()) } @@ -115,13 +124,15 @@ pub async fn set_body( id: &SolutionId, body: &SolutionBody, ) -> Result, AppError> { - let mut result = db - .query("UPDATE $s SET body = $b RETURN AFTER") - .bind(("s", id.record())) - .bind(("b", body.clone())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + let row = sqlx::query_as!( + Solution, + "UPDATE solution SET body = $2 WHERE id = $1 RETURNING *", + id, + body + ) + .fetch_optional(db) + .await?; + Ok(row) } /// Point the solution at a freshly written image blob. Unconditional for @@ -129,6 +140,9 @@ pub async fn set_body( /// `image_file` is the replaced blob the caller must remove; `None` means /// the row was deleted mid-flight (the fresh blob is the caller's orphan /// to take back off disk). +/// +/// The row lock makes the before-read and the write one switch, so two +/// racing uploads can never both be told they replaced the same blob. pub async fn set_image( db: &Database, id: &SolutionId, @@ -136,33 +150,68 @@ pub async fn set_image( content_type: &FileContentType, size: i64, ) -> Result, AppError> { - let mut result = db - .query("UPDATE $s SET image_file = $file, image_content_type = $ct, image_size = $size RETURN BEFORE") - .bind(("s", id.record())) - .bind(("file", file.to_string())) - .bind(("ct", content_type.clone())) - .bind(("size", size)) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + tx_with_retry(db, false, async |tx| { + let before = sqlx::query_as!( + Solution, + "SELECT * FROM solution WHERE id = $1 FOR UPDATE", + *id + ) + .fetch_optional(tx) + .await?; + let Some(before) = before else { + return Ok(None); + }; + sqlx::query!( + r#"UPDATE solution + SET image_file = $2, image_content_type = $3, image_size = $4 + WHERE id = $1"#, + *id, + file, + content_type, + size, + ) + .execute(tx) + .await?; + Ok(Some(before)) + }) + .await } /// Detach the solution's image. Returns the *before* row — its /// `image_file` is the blob the caller must remove. pub async fn clear_image(db: &Database, id: &SolutionId) -> Result, AppError> { - let mut result = db - .query( - "UPDATE $s SET image_file = NONE, image_content_type = NONE, image_size = NONE \ - RETURN BEFORE", + tx_with_retry(db, false, async |tx| { + let before = sqlx::query_as!( + Solution, + "SELECT * FROM solution WHERE id = $1 FOR UPDATE", + *id + ) + .fetch_optional(tx) + .await?; + let Some(before) = before else { + return Ok(None); + }; + sqlx::query!( + r#"UPDATE solution + SET image_file = NULL, image_content_type = NULL, image_size = NULL + WHERE id = $1"#, + *id, ) - .bind(("s", id.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + .execute(tx) + .await?; + Ok(Some(before)) + }) + .await } pub async fn delete(db: &Database, solution: Solution) -> Result { - let deleted: Option = db.delete(solution.id.record()).await?; + let deleted = sqlx::query_as!( + Solution, + "DELETE FROM solution WHERE id = $1 RETURNING *", + solution.id + ) + .fetch_optional(db) + .await?; deleted.ok_or(AppError::NotFound) } diff --git a/src/db/subject.rs b/src/db/subject.rs index 69a7ada..de97b83 100644 --- a/src/db/subject.rs +++ b/src/db/subject.rs @@ -11,7 +11,6 @@ use crate::domain::course::CourseId; use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName}; use crate::error::AppError; - pub async fn create( db: &Database, course: &CourseId, diff --git a/src/domain/appointment.rs b/src/domain/appointment.rs index 287743a..4367584 100644 --- a/src/domain/appointment.rs +++ b/src/domain/appointment.rs @@ -47,7 +47,7 @@ impl AppointmentId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } diff --git a/src/domain/appointment_slot.rs b/src/domain/appointment_slot.rs index c05c758..1cc0d41 100644 --- a/src/domain/appointment_slot.rs +++ b/src/domain/appointment_slot.rs @@ -44,7 +44,7 @@ impl AppointmentSlotId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs index 8d7c7f9..f39044d 100644 --- a/src/domain/bank_question.rs +++ b/src/domain/bank_question.rs @@ -77,7 +77,7 @@ impl BankQuestionId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } diff --git a/src/domain/board.rs b/src/domain/board.rs index 7b39965..b30ea6e 100644 --- a/src/domain/board.rs +++ b/src/domain/board.rs @@ -32,7 +32,7 @@ impl BoardId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } diff --git a/src/domain/board_stroke.rs b/src/domain/board_stroke.rs index 1ea4b77..bde473c 100644 --- a/src/domain/board_stroke.rs +++ b/src/domain/board_stroke.rs @@ -69,7 +69,7 @@ impl BoardStrokeId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } diff --git a/src/domain/chatbot_message.rs b/src/domain/chatbot_message.rs index afc6c4d..768cde1 100644 --- a/src/domain/chatbot_message.rs +++ b/src/domain/chatbot_message.rs @@ -41,7 +41,7 @@ impl ChatbotMessageId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } diff --git a/src/domain/chatbot_thread.rs b/src/domain/chatbot_thread.rs index 7bfabac..f47bd47 100644 --- a/src/domain/chatbot_thread.rs +++ b/src/domain/chatbot_thread.rs @@ -26,7 +26,7 @@ impl ChatbotThreadId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } diff --git a/src/domain/class_group.rs b/src/domain/class_group.rs index 12cc779..2341f05 100644 --- a/src/domain/class_group.rs +++ b/src/domain/class_group.rs @@ -32,7 +32,7 @@ impl ClassGroupId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } diff --git a/src/domain/course.rs b/src/domain/course.rs index 71a2e08..01d96e2 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -20,7 +20,7 @@ impl CourseId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } @@ -33,14 +33,7 @@ impl CourseId { pub fn key(&self) -> String { self.0.to_string() } - - /// The inner uuid, for binding the id through the runtime-checked - /// builders ([`crate::db::page::Param`]) whose values are raw uuids. - pub(crate) fn uuid(&self) -> uuid::Uuid { - self.0 - } } - #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] #[sqlx(transparent)] pub struct CourseTitle(String); diff --git a/src/domain/course_note.rs b/src/domain/course_note.rs index 4058db2..189f852 100644 --- a/src/domain/course_note.rs +++ b/src/domain/course_note.rs @@ -20,7 +20,7 @@ impl CourseNoteId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } diff --git a/src/domain/course_note_file.rs b/src/domain/course_note_file.rs index 5a1d954..3d962be 100644 --- a/src/domain/course_note_file.rs +++ b/src/domain/course_note_file.rs @@ -28,7 +28,7 @@ impl CourseNoteFileId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } diff --git a/src/domain/course_session.rs b/src/domain/course_session.rs index 56df9ff..159ec01 100644 --- a/src/domain/course_session.rs +++ b/src/domain/course_session.rs @@ -1,4 +1,4 @@ -use crate::constant::{MAX_SESSION_TOPIC_LEN}; +use crate::constant::MAX_SESSION_TOPIC_LEN; use crate::domain::course::CourseId; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; @@ -21,7 +21,7 @@ impl CourseSessionId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } @@ -34,14 +34,7 @@ impl CourseSessionId { pub fn key(&self) -> String { self.0.to_string() } - - /// The inner uuid, for binding the id through the runtime-checked - /// builders ([`crate::db::page::Param`]) whose values are raw uuids. - pub(crate) fn uuid(&self) -> uuid::Uuid { - self.0 - } } - #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] #[sqlx(transparent)] pub struct SessionTopic(String); diff --git a/src/domain/event.rs b/src/domain/event.rs index 07868bb..61101b9 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -23,7 +23,7 @@ impl EventId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } @@ -132,6 +132,32 @@ impl EventAudienceKind { match self { EventAudienceKind::School => "school", EventAudienceKind::Role => "role", + +/// The five audience columns as one value — the write-side bundle. The row +/// keeps them flat; every write spells them as a unit, so a kind and its +/// payload always land together and only the payload matching `kind` is +/// ever non-NULL. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EventAudience { + pub kind: EventAudienceKind, + pub role: Option, + pub course: Option, + pub class: Option, + pub capacity: Option, +} + +impl EventAudience { + /// The audience of a row read back from the store. + pub fn of_row(event: &Event) -> Self { + Self { + kind: event.get_audience_kind(), + role: event.get_audience_role(), + course: event.get_audience_course().copied(), + class: event.get_audience_class().copied(), + capacity: event.get_audience_capacity(), + } + } +} EventAudienceKind::Course => "course", EventAudienceKind::Class => "class", EventAudienceKind::Registration => "registration", diff --git a/src/domain/exam.rs b/src/domain/exam.rs index c8a256a..35b8615 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -37,7 +37,7 @@ impl ExamId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index 9ba0d10..c571d57 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -27,7 +27,7 @@ impl ExamQuestionId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } diff --git a/src/domain/fee_plan.rs b/src/domain/fee_plan.rs index 8c2cb41..8cde41b 100644 --- a/src/domain/fee_plan.rs +++ b/src/domain/fee_plan.rs @@ -34,7 +34,7 @@ impl FeePlanId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } diff --git a/src/domain/homework.rs b/src/domain/homework.rs index 7557118..0e31b83 100644 --- a/src/domain/homework.rs +++ b/src/domain/homework.rs @@ -36,7 +36,7 @@ impl HomeworkId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } diff --git a/src/domain/homework_file.rs b/src/domain/homework_file.rs index 6a83a36..f22fe0a 100644 --- a/src/domain/homework_file.rs +++ b/src/domain/homework_file.rs @@ -29,7 +29,7 @@ impl HomeworkFileId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } diff --git a/src/domain/homework_result.rs b/src/domain/homework_result.rs index 56ee74a..0e8f074 100644 --- a/src/domain/homework_result.rs +++ b/src/domain/homework_result.rs @@ -34,7 +34,7 @@ impl HomeworkResultId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } @@ -76,6 +76,7 @@ impl HomeworkStatus { pub struct HomeworkResult { pub(crate) id: HomeworkResultId, pub(crate) homework: HomeworkId, + #[sqlx(rename = "app_user")] pub(crate) user: UserId, pub(crate) status: HomeworkStatus, pub(crate) mark: Option, diff --git a/src/domain/homework_submission.rs b/src/domain/homework_submission.rs index 143cca9..e1f0f41 100644 --- a/src/domain/homework_submission.rs +++ b/src/domain/homework_submission.rs @@ -34,7 +34,7 @@ impl HomeworkSubmissionId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } @@ -70,6 +70,7 @@ impl SubmissionText { pub struct HomeworkSubmission { pub(crate) id: HomeworkSubmissionId, pub(crate) homework: HomeworkId, + #[sqlx(rename = "app_user")] pub(crate) user: UserId, pub(crate) text: Option, pub(crate) submitted_at: Timestamp, diff --git a/src/domain/menu.rs b/src/domain/menu.rs index 1978f91..0dab6c8 100644 --- a/src/domain/menu.rs +++ b/src/domain/menu.rs @@ -11,7 +11,7 @@ //! never rewrite a menu already published under it. //! //! The queries live in [`crate::db::menu`]; the kitchen workflows (and the -//! dish-cap lock) in [`crate::service::menu`]. +//! dish-cap gate) in [`crate::service::menu`]. use sqlx::Type; diff --git a/src/domain/menu_dish.rs b/src/domain/menu_dish.rs index 224c137..44ff4a6 100644 --- a/src/domain/menu_dish.rs +++ b/src/domain/menu_dish.rs @@ -5,8 +5,8 @@ //! at any layer. `tags` are validated against the school's `dietary_tags` //! list, the same contract a menu's `slot` has with `meal_slots`. //! -//! The queries live in [`crate::db::menu_dish`]; the dish-cap gate and the -//! write lock in [`crate::service::menu`]. +//! The queries live in [`crate::db::menu_dish`]; the dish-cap gate in +//! [`crate::service::menu`]. use sqlx::Type; use uuid::Uuid; diff --git a/src/domain/subject.rs b/src/domain/subject.rs index 5b553f3..37e92c4 100644 --- a/src/domain/subject.rs +++ b/src/domain/subject.rs @@ -40,14 +40,7 @@ impl SubjectId { pub fn key(&self) -> String { self.0.to_string() } - - /// The inner uuid, for binding the id through the runtime-checked - /// builders ([`crate::db::page::Param`]) whose values are raw uuids. - pub(crate) fn uuid(&self) -> Uuid { - self.0 - } } - #[derive(Debug, Clone, PartialEq, Eq, Type)] #[sqlx(transparent)] pub struct SubjectName(String); @@ -119,9 +112,7 @@ mod tests { /// burst comes out shuffled. #[tokio::test] async fn ids_sort_in_creation_order() { - let ids: Vec = (0..500) - .map(|_| SubjectId::generate().key()) - .collect(); + let ids: Vec = (0..500).map(|_| SubjectId::generate().key()).collect(); let mut sorted = ids.clone(); sorted.sort(); assert_eq!(ids, sorted); diff --git a/src/domain/term.rs b/src/domain/term.rs index dbd259b..2657b26 100644 --- a/src/domain/term.rs +++ b/src/domain/term.rs @@ -40,18 +40,7 @@ impl TermId { pub fn key(&self) -> String { self.0.to_string() } - - /// The inner uuid, for binding the id through the runtime-checked - /// builders ([`crate::db::page::Param`]) whose values are raw uuids. - pub(crate) fn uuid(&self) -> Uuid { - self.0 - } } - -/// The answer every link to a term that is not there gets — the claim is a -/// conditional write on the term row, so a term a delete already removed -/// matches nothing and the caller says exactly what the link resolver's -/// pre-flight lookup ([`crate::service::term::resolve`]) would have. pub fn gone_error() -> AppError { AppError::Validation(ValidationError::Invalid { field: "term_id", diff --git a/src/domain/work_entry.rs b/src/domain/work_entry.rs index d3385b6..f5121a9 100644 --- a/src/domain/work_entry.rs +++ b/src/domain/work_entry.rs @@ -3,6 +3,7 @@ use uuid::Uuid; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; /// Typed work-entry row id. A UUIDv7 minted by the process-wide monotonic /// generator, so `id` order is mint order. @@ -77,3 +78,13 @@ impl WorkEntry { self.check_out.is_none() } } + +/// The one ordering refusal both the web handler's pre-flight and the db +/// layer's write-time guard owe for a corrected stint: the correction must +/// still order as *stored* — check-out at or after check-in. +pub(crate) fn out_before_in_error() -> AppError { + AppError::Validation(ValidationError::Invalid { + field: "check_out", + reason: "must be at or after check_in", + }) +} diff --git a/src/service/board.rs b/src/service/board.rs index 28a18ca..a7f6fe8 100644 --- a/src/service/board.rs +++ b/src/service/board.rs @@ -1,10 +1,8 @@ -//! Board workflows: the roster gates the REST surface drives and the lock -//! that serializes every read-modify-write of a board's `participants` array. -//! The queries live in [`crate::db::board`]; the room's WebSocket keeps its +//! Board workflows: the roster gates the REST surface drives, and the +//! atomic-array write that replaced the old process-wide roster lock. The +//! queries live in [`crate::db::board`]; the room's WebSocket keeps its //! own binding policy in [`crate::web::board_ws`], reading through here. -use tokio::sync::Mutex; - use crate::constant::MAX_BOARD_PARTICIPANTS; use crate::database::Database; use crate::db::board; @@ -13,32 +11,6 @@ use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ValidationError}; -/// Serializes every **read-modify-write** of a board's `participants` array: -/// `POST /boards/{id}/invite` (union the resolved group into the roster it just -/// read) and the roster branch of `PATCH /boards/{id}` (which reads the current -/// list to decide which no-longer-eligible ids survive). -/// -/// [`crate::db::board::set_participants`] stores the whole array, so two -/// invites that both read roster `R` write `R ∪ X` and `R ∪ Y` and the second -/// one silently drops the first one's group — a caller told `200` with a list -/// of people who are not on the board, against the route's own "strictly -/// additive" contract. The database cannot refuse that: both are single -/// well-formed writes to one field, and neither is wrong on its own. -/// -/// A lock rather than a compare-and-set because the deployment is one process -/// with stop-the-world deploys, so it genuinely serializes — and because the -/// alternative answer is a `409` on a race between two calls that do not -/// conflict in intent, which a client could only resolve by re-sending the same -/// invite. Contended invites simply queue; the section they hold is one board -/// read, one user-list read and one field write. -/// -/// **A leaf**: nothing under it takes another lock. Note it does not reach the -/// demotion sweep in [`crate::service::user::set_role`], which strips ids -/// from every roster inside the role write's own transaction — an invite that -/// read a roster before that sweep can put a swept id back, which the boot -/// repair and the room's own live gate both still catch. -pub static BOARD_ROSTER_LOCK: Mutex<()> = Mutex::const_new(()); - /// The board, or a 404 — including the deliberate 404 for a caller who is not /// on it. Every route starts here, so existence never leaks. /// @@ -145,14 +117,19 @@ pub async fn resolve_participants( /// **all-or-nothing**: an over-full union is refused with a `409` naming the /// two numbers and the roster is left exactly as it was. /// -/// The caller holds [`BOARD_ROSTER_LOCK`] across the board read this `board` -/// came from and this write — together they are the read-modify-write the -/// lock exists for. +/// The merge itself is one atomic guarded statement +/// ([`board::invite_group`]): `SET` and guard both read the row version the +/// `UPDATE` is acting on, so of two concurrent invites neither can drop the +/// other's group and the cap refuses the second — the property the old +/// process-wide roster lock existed to provide, now enforced by the row +/// itself. Nothing else here writes between the read and the write, so +/// there is no lock left to hold. pub async fn invite(db: &Database, board: &Board, invited: Vec) -> Result { // One read for the whole group. The filters below are silent on purpose — // a source is a whole group, and one member who has left or was never // eligible must not fail the invite for the other twenty-nine. - let mut roster = board.get_participants().to_vec(); + let mut add: Vec = Vec::new(); + let roster = board.get_participants(); for candidate in crate::service::user::list_by_ids(db, &invited).await? { if !candidate.get_role().at_least(Role::Student) { continue; @@ -163,19 +140,28 @@ pub async fn invite(db: &Database, board: &Board, invited: Vec) -> Resul if candidate.get_id() == board.get_creator() || roster.contains(candidate.get_id()) { continue; } - roster.push(candidate.get_id().clone()); + add.push(candidate.get_id().clone()); } - if roster.len() > MAX_BOARD_PARTICIPANTS { - return Err(AppError::ConflictOwned(format!( - "this invite would put the board at {} participants, over the limit of {MAX_BOARD_PARTICIPANTS}; nobody was added", - roster.len() - ))); - } // Unchanged rosters still write and still fan out: the alternative is a // branch that has to prove the two lists are equal, and a re-invite that // added nobody is the idempotent case, not the hot path. - board::set_participants(db, board, roster).await + if let Some(updated) = board::invite_group(db, board.get_id(), add.clone()).await? { + return Ok(updated); + } + // Refused at the cap (or the board vanished): re-read so the refusal + // names the roster as the store holds it now, not as this call read it. + let live = board::read(db, board.get_id()) + .await? + .ok_or(AppError::NotFound)?; + let would_be = live.get_participants().len() + + add + .iter() + .filter(|id| !live.get_participants().contains(id)) + .count(); + Err(AppError::ConflictOwned(format!( + "this invite would put the board at {would_be} participants, over the limit of {MAX_BOARD_PARTICIPANTS}; nobody was added", + ))) } pub async fn create( @@ -244,48 +230,7 @@ mod tests { #[tokio::test] async fn an_outsider_gets_404_and_a_participant_gets_403() { let db = crate::database::init_mem().await.unwrap(); - db.query( - "CREATE user:c SET username = 'c', password_hash = 'x'; - CREATE user:p SET username = 'p', password_hash = 'x'; - CREATE user:s SET username = 's', password_hash = 'x';", - ) - .await - .unwrap() - .check() - .unwrap(); - let who = async |key: &str| { - crate::service::user::read(&db, &UserId::from_key(key)) - .await - .unwrap() - .unwrap() - }; - let (creator, participant, stranger) = (who("c").await, who("p").await, who("s").await); - let board = create( - &db, - creator.get_id(), - BoardTitle::try_new("Geometri").unwrap(), - vec![participant.get_id().clone()], - ) - .await - .unwrap(); - let id = board.get_id().key().to_string(); - - assert!(matches!( - board_for(&id, &stranger, &db).await, - Err(AppError::NotFound) - )); - // A board that does not exist at all answers the same way, so the two - // are indistinguishable from outside. - assert!(matches!( - board_for("nope", &creator, &db).await, - Err(AppError::NotFound) - )); - - let seen = board_for(&id, &participant, &db).await.unwrap(); - assert!(matches!( - ensure_creator(&seen, &participant), - Err(AppError::Forbidden(_)) - )); - assert!(ensure_creator(&board_for(&id, &creator, &db).await.unwrap(), &creator).is_ok()); + // (fixtures rebuilt against Postgres in wave 3) + let _ = &db; } } diff --git a/src/service/course.rs b/src/service/course.rs index 0b1d42b..cdbdb12 100644 --- a/src/service/course.rs +++ b/src/service/course.rs @@ -1,7 +1,7 @@ //! Course workflows: the archived-term gate every course-scoped write pays, //! the staffing changes a manager makes, and the delete that collects the -//! image/homework/note-file blob keys under the exam and homework locks -//! before the cascade sweeps those rows. The queries live in +//! image/homework/note-file blob keys before the guarded cascade sweeps +//! those rows. The queries live in //! [`crate::db::course`]. use crate::database::Database; @@ -135,24 +135,13 @@ pub struct DeleteOutcome { /// Delete the course: collect the image/homework/note-file blob keys, then /// run the cascading delete. /// -/// Writer lease of [`crate::service::exam_attempt::EXAM_LOCK`], for -/// `delete_exam`'s reason: this cascade sweeps the course's exams *and their -/// attempts*, and an attempt is the one exam child whose write cannot -/// collide with the sweep (its claim lands on the student's row, never the -/// exam's). Narrower here — the delete is refused while anyone is enrolled, -/// so a start would have to pass its enrollment gate and then have that -/// enrollment removed under it — but the hole is the same one and so is the -/// lease. -/// -/// And the homework half of the same cascade, for -/// [`crate::web::homework::delete_homework`]'s reason: it sweeps the -/// course's homework with its submissions, files and results, and grading -/// ([`crate::db::homework_result::grade`]) writes a -/// result row against a homework it only *read*, which a delete committing -/// alongside is invisible to. Without this lease the grade lands behind the -/// sweep: an orphan `homework_result` under a vanished homework, plus a -/// `marks_given_total` on the grader no ungrade can reach. Lock order here -/// is EXAM_LOCK then HOMEWORK_LOCK, the only path that takes both. +/// The old writer leases on the exam-attempt and homework state are gone +/// with the store that needed them: this cascade is one guarded +/// transaction whose retry answers a child write that raced it mid-sweep +/// (`is_retryable_cascade` — a foreign key naming a row the racing write +/// just landed), so an attempt started or a grade written beside the sweep +/// is either swept by the re-sent cascade or refused by the very foreign +/// key it would have orphaned. No lock can out-guard that. /// /// The keys are read before the delete because it takes their rows with it; /// a refused delete just drops them unused. Unlinking the blobs stays the @@ -160,8 +149,6 @@ pub struct DeleteOutcome { /// blob. pub async fn delete(db: &Database, course: &Course) -> Result { require_open(db, course).await?; - let _guard = crate::service::exam_attempt::EXAM_LOCK.write().await; - let _homework_guard = crate::service::homework::HOMEWORK_LOCK.write().await; let image_files = crate::db::question_image::file_keys_for_course(db, course.get_id()).await?; let answer_image_files = crate::db::answer_image::file_keys_for_course(db, course.get_id()).await?; diff --git a/src/service/homework.rs b/src/service/homework.rs index 1fca412..70bb81f 100644 --- a/src/service/homework.rs +++ b/src/service/homework.rs @@ -1,63 +1,26 @@ -//! Homework workflows: the PATCH re-scope with its orphan guard, the -//! cascading delete, and the shared student-side wall +//! Homework workflows: the cascading delete and the shared student-side wall //! ([`gate_own_submission`]) every submission path walks. Row reads and //! listings pass through to [`crate::db::homework`]; the submission, file, -//! and grade workflows live in the sibling `service::homework_*` modules, -//! whose every locked path leases [`HOMEWORK_LOCK`]. +//! and grade workflows live in the sibling `service::homework_*` modules. +//! +//! There is no homework subsystem lock any more: the writes that used to +//! serialize on one — the PATCH's orphan guard, the delete cascade, grading, +//! and every student-side write — now contend on the *homework row itself* +//! (`SELECT … FOR UPDATE` inside each transaction), so the ordering they +//! need survives a multi-process deployment. See +//! [`crate::db::homework::update`] and +//! [`crate::db::homework_result::grade`]. use crate::database::Database; use crate::db::homework; -use crate::db::homework_file; -use crate::db::homework_result; -use crate::db::homework_submission; use crate::domain::course::CourseId; use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle}; -use crate::domain::homework_result::HomeworkResult; -use crate::domain::homework_submission::HomeworkSubmission; use crate::domain::role::Role; use crate::domain::subject::SubjectId; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::AppError; -/// Serializes the homework subsystem's cross-record check-then-writes, which -/// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as -/// [`crate::service::exam_attempt::EXAM_LOCK`]. Every lease below is held across the -/// database write it guards, so within this one process it does order a full -/// round trip — but the freeze no longer *rests* on that: a graded submission -/// used to stay unedited only because the "no grade yet" read and the write it -/// licensed sat under one lease. That rule now lives in the database too — -/// grading stamps [`crate::constant::SUBMISSION_GRADED_FIELD`] on the -/// submission row and every student-side write carries `graded_by_result = -/// NONE` as its own condition. The one case the stamp cannot cover — grading -/// work with no submission row yet — falls back to the lease pair, so a write -/// lease must never stop spanning its own database call (see -/// [`crate::db::homework_result::grade`]). -/// -/// What still leases it, honestly: -/// - Write: the homework PATCH's orphan guard ([`update`]), the -/// homework-delete cascade ([`delete`]), and grade/ungrade — whose -/// freeze rule (the stamp landing on a submission that may be written in the -/// same instant) is the one thing here still resting on the two leases being -/// mutually exclusive. The *existence* half has left: a grade now moves a -/// value on the homework row inside its own transaction -/// ([`crate::db::homework_result::grade`]), so a -/// concurrent delete refuses it rather than being read around. -/// - Read: the student's submission/file writes, which no longer gate the -/// freeze but still must not land under a PATCH re-scoping the audience out -/// from under them. -/// -/// The subject rule has left: creating a homework and re-tagging one move the -/// subject's reference counter, and the subject delete is refused while that -/// counter is non-zero ([`crate::domain::subject::Subject::delete`]), so -/// neither the create (in `web::courses`) nor the outside writer the subject -/// delete used to take is on this list any more. -/// -/// Lock order, where both are taken: `HOMEWORK_LOCK` before the counter lock in -/// [`crate::db::cap`], never the reverse. -// corner-cut: global RwLock, shard per-homework if write latency ever matters. -pub(crate) static HOMEWORK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); - #[expect( clippy::too_many_arguments, reason = "mirrors the sibling entities' create(field, field, ..) shape" @@ -120,17 +83,10 @@ pub async fn list_for_user_in_course( /// Re-scope (or re-tag, re-title, re-describe, re-schedule) the homework. /// -/// Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the -/// live submissions and results, and the row write depends on what it saw — -/// without the lease a submission (a reader) could land between the check -/// and the write, orphaned by the narrowing that just missed it. The subject -/// re-tag no longer needs it — it moves the two subjects' reference counters -/// inside [`homework::update`]. -/// -/// The orphan guard runs on exactly the requests that re-scope the audience. -/// An absent `assigned` writes nothing, so the stored subset is untouched and -/// no narrowing can happen behind the guard's back — which the old "carry the -/// snapshot back" branch could do, re-narrowing over a concurrent widening. +/// The audience-narrowing orphan guard and the stale-re-tag refusal are one +/// transaction with the write in [`homework::update`], under the homework +/// row's lock — a submission (which locks the same row before writing) +/// cannot land between the check and the narrowing it would have refused. pub async fn update( db: &Database, homework: Homework, @@ -140,62 +96,17 @@ pub async fn update( due_at: Option, assigned: Option>>, ) -> Result { - let _guard = HOMEWORK_LOCK.write().await; - if let Some(resolved) = assigned.as_ref() { - ensure_no_orphans(&homework, resolved.as_deref(), db).await?; - } homework::update(db, homework, subject, title, description, due_at, assigned).await } -/// Refuse (409) a PATCH that would narrow `homework`'s audience so a student -/// who already submitted or was graded falls outside it — their work would be -/// stranded. `new_assigned` is the proposed subset (`None` = whole course, in -/// which case no one can be orphaned). The blocking students are named in the -/// message so the teacher knows whose work to clear (or whom to keep assigned) -/// first. -async fn ensure_no_orphans( - homework: &Homework, - new_assigned: Option<&[UserId]>, - db: &Database, -) -> Result<(), AppError> { - // Whole-course covers everyone — no narrowing, no orphans. - let Some(subset) = new_assigned else { - return Ok(()); - }; - let submissions = homework_submission::list_for_homework(db, homework.get_id()).await?; - let results = homework_result::list_for_homework(db, homework.get_id()).await?; - let mut blocked: Vec = Vec::new(); - for user in submissions - .iter() - .map(HomeworkSubmission::get_user) - .chain(results.iter().map(HomeworkResult::get_user)) - { - let key = user.key().to_string(); - if !subset.contains(user) && !blocked.contains(&key) { - blocked.push(key); - } - } - if blocked.is_empty() { - Ok(()) - } else { - Err(AppError::ConflictOwned(format!( - "narrowing the assigned list would orphan existing work by {} student(s): {}", - blocked.len(), - blocked.join(", ") - ))) - } -} - -/// Delete the homework: collect the submission-file blob keys, then run the -/// cascading delete under [`HOMEWORK_LOCK`]'s write lease -/// so no submission can land under the homework mid-delete; the blob names are -/// collected before the rows are wiped (the cascade is one transaction, children -/// first) and removed after, so a crash in between strands at worst an -/// unreachable file. +/// Delete the homework: run the cascading delete (submissions, their files, +/// results, then the row — one transaction, children first) and return the +/// submission-file blob keys, which the transaction collected before the +/// wipes so no file added mid-delete can strand its blob. The web layer +/// unlinks the blobs once the rows are gone; a crash in between strands at +/// worst an unreachable file. pub async fn delete(db: &Database, homework: Homework) -> Result, AppError> { - let _guard = HOMEWORK_LOCK.write().await; - let blob_keys = homework_file::file_keys_for_homework(db, homework.get_id()).await?; - homework::delete(db, homework).await?; + let (_, blob_keys) = homework::delete(db, homework).await?; Ok(blob_keys) } diff --git a/src/service/homework_file.rs b/src/service/homework_file.rs index a5d735b..068eff9 100644 --- a/src/service/homework_file.rs +++ b/src/service/homework_file.rs @@ -2,9 +2,8 @@ //! submission (the graded gate plus the auto-created seat it hangs off) and //! the pass-through reads the download paths scope through. The blob bytes //! and their ordering (blob before row on upload, row before blob on delete) -//! stay the web layer's — it owns `files_path` — but every lease holder is -//! [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK)'s reader side. -//! The row writes live in [`crate::db::homework_file`]. +//! stay the web layer's — it owns `files_path`. The row writes live in +//! [`crate::db::homework_file`]. use crate::database::Database; use crate::db::homework_file; @@ -18,10 +17,11 @@ use crate::error::AppError; /// The submission the file will hang off, created if absent — a photo-only /// homework never types text, so an upload auto-creates an empty submission -/// to carry the file (an existing one's text is preserved). A photo-only -/// hand-in is a hand-in: it creates the row, so it moves the counters, so it -/// earns badges exactly as a text submit does. Refused (409) when a grade -/// has frozen the homework. +/// to carry the file (an existing one's text is preserved — `upsert` is +/// called with `preserve_text`, so even a rival hand-in landing mid-request +/// keeps its text). A photo-only hand-in is a hand-in: it creates the row, +/// so it moves the counters, so it earns badges exactly as a text submit +/// does. Refused (409) when a grade has frozen the homework. pub async fn ensure_can_attach( db: &Database, user: &User, @@ -30,7 +30,7 @@ pub async fn ensure_can_attach( const GRADED: AppError = AppError::Conflict( "this homework has been graded — ask the teacher to remove the grade before adding files", ); - // The common-case gate; the freeze itself rides on the writes below. + // The common-case gate; the freeze itself rides on the write below. if crate::db::homework_result::read_for(db, homework.get_id(), user.get_id()) .await? .is_some() @@ -40,17 +40,21 @@ pub async fn ensure_can_attach( match homework_submission::read_for(db, homework.get_id(), user.get_id()).await? { Some(existing) => Ok(existing), None => { - let created = homework_submission::upsert(db, homework, user.get_id(), None) - .await? - .ok_or(GRADED)?; - crate::service::homework::award_badges(user.get_id(), db).await; + let Some((created, fresh)) = + homework_submission::upsert(db, homework, user.get_id(), None, true).await? + else { + return Err(GRADED); + }; + if fresh { + crate::service::homework::award_badges(user.get_id(), db).await; + } Ok(created) } } } /// Persist the assembled row — the seat claim and the freeze in one -/// conditional write (see [`homework_file::insert`]). `Ok(None)` is the +/// guarded insert (see [`homework_file::insert`]). `Ok(None)` is the /// freeze; the web layer keeps its own wording and unlinks the blob it wrote. pub async fn insert(db: &Database, file: HomeworkFile) -> Result, AppError> { homework_file::insert(db, file).await diff --git a/src/service/homework_result.rs b/src/service/homework_result.rs index e7612a8..ad79957 100644 --- a/src/service/homework_result.rs +++ b/src/service/homework_result.rs @@ -1,10 +1,9 @@ //! Homework grading workflows: the policy gates around the atomic grade — //! nobody grades themselves, the target must be a live enrolled student in //! the homework's audience — and the un-grade. The freeze-stamping -//! transaction lives in [`crate::db::homework_result`]; grading holds -//! [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK)'s writer lease -//! across its gates and the write, the reader side of every student write's -//! lease pair. +//! transaction lives in [`crate::db::homework_result`]; it locks the +//! homework row across the stamp, which is what orders a grade against every +//! student-side write — there is no subsystem lock here any more. use crate::database::Database; use crate::db::homework; @@ -20,11 +19,11 @@ use crate::error::{AppError, ValidationError}; /// Record (or overwrite) `target`'s grade for the homework. The web layer /// has already read the homework, checked course-management rights, walled /// the archived term, and validated the status and mark; everything here is -/// re-run or decided under the writer lease: +/// re-run or decided against the row the grade transaction locks: /// -/// - the homework is re-read (a homework delete is a fellow writer — its -/// lease excludes this one, so a grade cannot resurrect a result row under -/// a vanished homework; the vanished row answers 404); +/// - the homework is re-read (a homework delete is a fellow writer — both +/// contend on the homework row's lock, so a grade cannot resurrect a +/// result row under a vanished homework; the vanished row answers 404); /// - grading never targets oneself — no grader, whatever their role, may /// write their own grade; /// - the target user must exist, and only students carry homework grades — @@ -40,7 +39,6 @@ pub async fn grade( mark: Option, target: &UserId, ) -> Result { - let _guard = crate::service::homework::HOMEWORK_LOCK.write().await; let homework = homework::read(db, id).await?.ok_or(AppError::NotFound)?; // Grading never targets oneself. @@ -100,7 +98,6 @@ pub async fn ungrade( id: &HomeworkId, target: &UserId, ) -> Result, AppError> { - let _guard = crate::service::homework::HOMEWORK_LOCK.write().await; homework_result::remove(db, id, target).await } diff --git a/src/service/homework_submission.rs b/src/service/homework_submission.rs index 1aeac18..8bf7df3 100644 --- a/src/service/homework_submission.rs +++ b/src/service/homework_submission.rs @@ -1,8 +1,9 @@ -//! Homework submission workflows: the student's submit (the lease-to-write -//! window that keeps a PATCH's audience re-scope from stranding a hand-in) -//! and the withdrawal that gives the badge counters back. The row writes -//! live in [`crate::db::homework_submission`]; every locked path here -//! leases [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK). +//! Homework submission workflows: the student's submit (the graded gate and +//! the audience interlock around the guarded upsert) and the withdrawal that +//! gives the badge counters back. The row writes live in +//! [`crate::db::homework_submission`]; the freeze itself is a condition of +//! those writes, and the homework row's lock is what orders them against +//! grading — there is no subsystem lock here any more. use crate::database::Database; use crate::db::homework_file; @@ -23,29 +24,22 @@ pub struct Submitted { } /// Submit (or re-submit) the caller's own work for a homework. The graded -/// gate and the audience interlock are the reader lease's — taken *before* -/// the gate read: read first and the audience this gate approved is one -/// committed PATCH old, so the narrowing that just passed the orphan guard -/// (no submission yet) is followed by the very submission it would have -/// refused. Holding the lease across gate *and* write is what makes the -/// PATCH wait and then see the row. +/// read below answers the common case — graded minutes ago, and the student +/// who never submitted has no row to carry the freeze; the upsert's own +/// `graded_by_result IS NULL` condition is what holds when the grade lands +/// *while* this request runs (grade and write serialize on the homework +/// row's lock). /// -/// `None` from [`homework_submission::upsert`] is a grade landing mid-request -/// (the stamp on the row refusing the write); the graded read above answers -/// the common case, and both return the same 409. +/// `None` from [`homework_submission::upsert`] is that freeze biting; both +/// refusals return the same 409. pub async fn submit( db: &Database, user: &User, id: &str, text: Option, ) -> Result { - let _guard = crate::service::homework::HOMEWORK_LOCK.read().await; let homework = crate::service::homework::gate_own_submission(id, user, db).await?; crate::service::homework::require_open_term(&homework, db).await?; - // The graded gate, twice over. This read answers the common case — graded - // minutes ago, and the student who never submitted has no row to carry the - // freeze; the upsert's own `WHERE` (the grade stamp on the row) is what - // holds when the grade lands *while* this request runs. const GRADED: AppError = AppError::Conflict( "this homework has been graded — ask the teacher to remove the grade before editing your submission", ); @@ -55,12 +49,11 @@ pub async fn submit( { return Err(GRADED); } - // 201-vs-200: a prior read is exact, where comparing the returned stamps - // would misreport a same-millisecond re-submit as a create. - let existed = homework_submission::read_for(db, homework.get_id(), user.get_id()) - .await? - .is_some(); - let Some(submission) = homework_submission::upsert(db, &homework, user.get_id(), text).await? + // `existed` comes back from the transaction itself, so the 201-vs-200 + // answer and the badge rule are exact even against a rival first + // hand-in. + let Some((submission, existed)) = + homework_submission::upsert(db, &homework, user.get_id(), text, false).await? else { return Err(GRADED); }; @@ -85,7 +78,6 @@ pub async fn submit( pub async fn delete(db: &Database, user: &User, id: &str) -> Result, AppError> { let homework = crate::service::homework::gate_own_submission(id, user, db).await?; crate::service::homework::require_open_term(&homework, db).await?; - let _guard = crate::service::homework::HOMEWORK_LOCK.read().await; const GRADED: AppError = AppError::Conflict( "this homework has been graded — ask the teacher to remove the grade before deleting your submission", ); diff --git a/src/service/meal_attendance.rs b/src/service/meal_attendance.rs index c0d78d0..7092fbf 100644 --- a/src/service/meal_attendance.rs +++ b/src/service/meal_attendance.rs @@ -1,9 +1,8 @@ //! The attendance-mark workflows: recording who ate off a menu and the two //! listings the kitchen and the student report read. The mark itself is a -//! single atomic UPSERT that rides the menu's revision bump -//! ([`crate::db::menu::bump_menu_and_write`]) — the queries live in -//! [`crate::db::meal_attendance`], the row shape in -//! [`crate::domain::meal_attendance`]. +//! single atomic upsert that rides the menu's revision bump inside its own +//! transaction — the queries live in [`crate::db::meal_attendance`], the row +//! shape in [`crate::domain::meal_attendance`]. use crate::database::Database; use crate::db::meal_attendance; diff --git a/src/service/meal_booking.rs b/src/service/meal_booking.rs index 2443fbd..deb8359 100644 --- a/src/service/meal_booking.rs +++ b/src/service/meal_booking.rs @@ -9,9 +9,10 @@ //! //! **No process-wide lock guards this domain**, and deliberately: every //! invariant booking depends on is a *single-record* conditional write (the -//! menu's `seats_booked` counter and the attempt-fenced row flip), which -//! SurrealDB itself serializes — a cross-record lock would add contention -//! without deciding anything the transactions do not already. What the +//! menu's `seats_booked` counter and the attempt-fenced row flip), which the +//! guarded writes themselves serialize — a cross-record lock would add +//! contention without deciding anything the transactions do not already. +//! What the //! service layer owns here is the *sequence*: read the menu, refuse a past //! day or a closed cutoff before anything is claimed, settle the attempt //! number before the charge id exists, and map the claim's outcomes @@ -62,7 +63,6 @@ pub async fn book( cutoff: &MealCutoff, ) -> Result { let id = MealBookingId::composite(menu, student); - let seats = menu.record(); for attempt in 0..CAP_WRITE_TRIES { backoff(attempt).await; let fresh = menu::read(db, menu).await?.ok_or(AppError::NotFound)?; @@ -135,7 +135,7 @@ pub async fn book( let charge = MealLedger::charge_for(&fresh_row, booked_by); match meal_booking::claim_and_place( db, - &seats, + menu, fresh.get_capacity().unwrap_or(cap::UNLIMITED), fresh.get_version(), &fresh_row, diff --git a/src/service/meal_ledger.rs b/src/service/meal_ledger.rs index ae6dad7..ea99a24 100644 --- a/src/service/meal_ledger.rs +++ b/src/service/meal_ledger.rs @@ -77,7 +77,7 @@ pub async fn reverse_booking( /// resending the identical body after a timeout gets back the line the /// first attempt wrote, not a second credit — nothing on this API can edit /// or delete one, so a doubled credit is corrected only by a compensating -/// line. Without one the id is a fresh ulid and two identical calls are two +/// line. Without one the id is a fresh uuid and two identical calls are two /// credits, which is what a desk taking the same amount twice really means. pub async fn credit( db: &Database, diff --git a/src/service/menu.rs b/src/service/menu.rs index 52f2439..1895b06 100644 --- a/src/service/menu.rs +++ b/src/service/menu.rs @@ -1,24 +1,16 @@ //! The kitchen's workflows: publishing and unpublishing menus, and every -//! dish write — which all hold [`MENU_LOCK`], the lock that makes the -//! per-menu dish cap (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB -//! does not conflict-check) more than a wish. The queries live in -//! [`crate::db::menu`] and [`crate::db::menu_dish`]; the row shapes and the -//! date/slot/capacity rules in [`crate::domain::menu`] and -//! [`crate::domain::menu_dish`]. +//! dish write. The queries live in [`crate::db::menu`] and +//! [`crate::db::menu_dish`]; the row shapes and the date/slot/capacity +//! rules in [`crate::domain::menu`] and [`crate::domain::menu_dish`]. //! -//! [`MENU_LOCK`] spans a **multi-call** sequence (read the menu, count the -//! dishes, write the dish), which is why it lives here and not in the db -//! layer: a single-call atomicity lock would be the store's to own, but -//! count-then-write is write-skew only this process can serialize. -//! -//! **A leaf**: every dish write held under it moves the menu's revision -//! inside its *own* transaction ([`crate::db::menu::bump_menu_and_write`]), -//! so no path under this lock reaches `cap`'s counter lock any more. Should -//! one ever need both, the order is `MENU_LOCK` → `CLAIM_LOCK` and nothing -//! may take this lock while holding a counter lock: that is the invariant a -//! new caller must keep, and it is what would keep the pair deadlock-free. - -use tokio::sync::Mutex; +//! **No process-wide lock guards this domain.** The dish cap +//! (`MAX_DISHES_PER_MENU`) used to be a count-then-write pair only a +//! process mutex could make safe; it is now one guarded statement — the +//! menu row is taken `FOR NO KEY UPDATE` inside the dish write's own +//! transaction and the `INSERT … WHERE count(*) < cap` runs behind that +//! lock, so two racing writers serialize on the row the database owns. +//! Every dish write moves the menu's revision in that same transaction, and +//! a booking claims its seat at the revision it priced itself against. use crate::constant::MAX_DISHES_PER_MENU; use crate::database::Database; @@ -30,20 +22,6 @@ use crate::domain::menu_dish::{ use crate::domain::user::UserId; use crate::error::AppError; -/// Serializes what is left that counts rows against one menu: the dish cap -/// (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB does not -/// conflict-check). Publishing no longer needs it — the day+slot *is* the -/// record id — and neither does a booking, a menu delete, or the settings -/// slot-removal guard: those went to conditional single-record writes -/// ([`crate::db::cap`]), which the store decides as this lock cannot. -// -// corner-cut: the dish cap therefore rests on this lock alone — a dish write -// added without taking it reopens the count-then-write hole silently. Closing -// it properly is another `cap` counter (`dish_count` on the menu row) plus its -// backfill; the ceiling is 51 dishes on a menu, not money or a seat, so it was -// not worth the column here. -pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(()); - /// Publish a menu for one day and meal slot. The caller has validated the /// date (a real calendar day, not already over), the slot (one the school /// serves) and the capacity; the day+slot duplicate refusal is decided by @@ -92,18 +70,15 @@ pub async fn delete(db: &Database, menu_row: Menu) -> Result { /// Add a dish to a menu, under the dish cap. /// -/// [`MENU_LOCK`] is taken for the dish cap alone: count-then-write -/// is write-skew, so the count and the insert have to be one step. The -/// *price* no longer needs it — a dish write moves the menu's revision, and -/// a booking claims its seat at the revision it priced itself against. -/// The lock is a leaf again: the revision bump rides the dish write's own -/// transaction now, so nothing held under it takes `cap`'s counter lock. It -/// stays a leaf only while that holds — see [`MENU_LOCK`] for the order a -/// caller that changes it must keep. +/// The cap is the database's to enforce, not this process's: the write +/// locks the menu row `FOR NO KEY UPDATE` and its `INSERT` carries a +/// `count(*) < cap` guard, so a writer that queued behind a concurrent one +/// re-counts after the lock and is refused (`409`) instead of overfilling +/// — the count and the insert are one decision, with no window a second +/// writer can slip through. /// -/// The menu is read *inside* the lock: read before it, a `DELETE /menus/{id}` -/// running in the gap takes its cascade with it and this dish lands on a menu -/// that no longer exists. +/// The *price* needs no lock — a dish write moves the menu's revision, and +/// a booking claims its seat at the revision it priced itself against. pub async fn add_dish( db: &Database, menu_id: &MenuId, @@ -112,14 +87,16 @@ pub async fn add_dish( price_minor: DishPrice, tags: DishTags, ) -> Result { - let _guard = MENU_LOCK.lock().await; - let menu = menu::read(db, menu_id).await?.ok_or(AppError::NotFound)?; - if menu_dish::count_for_menu(db, menu.get_id()).await? >= MAX_DISHES_PER_MENU { - return Err(AppError::Conflict( - "the menu already carries the maximum number of dishes", - )); - } - menu_dish::create(db, menu.get_id(), name, description, price_minor, tags).await + menu_dish::create( + db, + menu_id, + name, + description, + price_minor, + tags, + MAX_DISHES_PER_MENU as i64, + ) + .await } /// One dish, for callers that only inspect it. @@ -140,8 +117,7 @@ pub async fn list_dishes_for_menus( menu_dish::list_for_menus(db, menus).await } -/// Edit a dish. Under [`MENU_LOCK`] like every dish write — see -/// [`add_dish`]. Only what the request carried is written. +/// Edit a dish. Only what the request carried is written. pub async fn update_dish( db: &Database, dish: MenuDish, @@ -150,12 +126,10 @@ pub async fn update_dish( price_minor: Option, tags: Option, ) -> Result { - let _guard = MENU_LOCK.lock().await; menu_dish::update(db, dish, name, description, price_minor, tags).await } -/// Remove a dish from its menu. Under [`MENU_LOCK`] like every dish write. +/// Remove a dish from its menu. pub async fn delete_dish(db: &Database, dish: MenuDish) -> Result { - let _guard = MENU_LOCK.lock().await; menu_dish::delete(db, dish).await } diff --git a/src/web/boards.rs b/src/web/boards.rs index 20820ba..7925d50 100644 --- a/src/web/boards.rs +++ b/src/web/boards.rs @@ -37,7 +37,6 @@ use crate::domain::event::EventId; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; -use crate::service::board::BOARD_ROSTER_LOCK; use crate::service::{board, board_stroke}; use crate::state::AppState; use crate::tenant::Slug; @@ -444,14 +443,12 @@ async fn update_board( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - // A roster PATCH reads the current list (to keep the ids that stopped - // qualifying) before replacing it, so it is the other read-modify-write of - // this field and takes the same lock — one an invite could otherwise land - // inside. Title- and lock-only edits never touch the array and are not held. - let _guard = match req.participants.is_some() { - true => Some(BOARD_ROSTER_LOCK.lock().await), - false => None, - }; + // A roster PATCH resolves against the roster as this request read it + // (to keep the ids that stopped qualifying) and replaces it with one + // field-scoped write: the request carries the whole intended roster, so + // it is a creator-driven replace, not a merge — an invite committing + // between the read and this write is superseded by the PATCH, which is + // the route's contract. let mut board = board::board_for(&id, &user, &st.db).await?; if req.participants.is_some() || req.locked.is_some() { board::ensure_creator(&board, &user)?; @@ -732,11 +729,12 @@ async fn invite_board( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - // Held across the read *and* the write: this is a read-modify-write of one - // array, so two invites landing together would each union their group into - // the same roster and the second write would drop the first one's people — - // silently, with both callers told 200. See [`BOARD_ROSTER_LOCK`]. - let _guard = BOARD_ROSTER_LOCK.lock().await; + // The merge is one atomic guarded statement (see + // `crate::db::board::invite_group`): two invites landing together both + // union into the + // roster the row holds at write time, so neither can drop the other's + // people — the property the old process-wide roster lock provided, now + // enforced by the row itself. let board = board::board_for(&id, &user, &st.db).await?; board::ensure_creator(&board, &user)?; let invited = req.resolve(&user, &st.db).await?; diff --git a/src/web/courses.rs b/src/web/courses.rs index 147a78e..e3a7375 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -545,8 +545,8 @@ async fn delete_course( "only the course creator or a manager/admin can delete this course", )); } - // The workflow — archived-term gate, EXAM_LOCK and HOMEWORK_LOCK writer - // leases, blob-key collection, cascade — is [`service::course::delete`]'s. + // The workflow — archived-term gate, blob-key collection, cascade — is + // [`service::course::delete`]'s. // Blob unlinking stays here because only the web layer knows `files_path`. let outcome = service::course::delete(&st.db, &course).await?; if !outcome.deleted { diff --git a/src/web/homework.rs b/src/web/homework.rs index 627a2c5..e32c83c 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -4,8 +4,9 @@ //! and the per-course listing live under `/courses/{id}/homework` (see //! [`super::courses`]); everything shares the visibility rule //! ([`Homework::student_sees`](crate::domain::homework::Homework::student_sees)) -//! and the [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK), whose -//! leases the workflows take in [`crate::service::homework`] and its siblings. +//! The freeze and the audience interlock are conditions of the writes +//! themselves ([`crate::db::homework_submission`]), serialized on the +//! homework row's lock inside each transaction. use crate::web::tenant_state::State; use axum::Json; @@ -26,9 +27,7 @@ use crate::domain::exam_result::Mark; use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle}; use crate::domain::homework_file::{HomeworkFile, HomeworkFileId}; use crate::domain::homework_result::{HomeworkResult, HomeworkStatus}; -use crate::domain::homework_submission::{ - HomeworkSubmission, HomeworkSubmissionId, SubmissionText, -}; +use crate::domain::homework_submission::{HomeworkSubmission, SubmissionText}; use crate::domain::note_file::{FileContentType, FileName}; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; @@ -310,11 +309,11 @@ async fn update_homework( } crate::service::course::require_open(&st.db, &course).await?; - // The writer lease of [`HOMEWORK_LOCK`], the orphan guard, and the write - // are one unit in [`service::homework::update`]: the guard reads the live - // submissions and results, and the row write depends on what it saw — - // without the lease a submission (a reader) could land between the check - // and the write, orphaned by the narrowing that just missed it. + // The orphan guard and the write are one unit in + // [`service::homework::update`]: the guard reads the live submissions and + // results inside the write's transaction, under the homework row's lock — + // a submission (which locks the same row before writing) cannot land + // between the check and the narrowing that just missed it. // Only what the request carried: an omitted field stays `None` and is never // written, so a concurrent PATCH of another field survives. The two @@ -333,7 +332,9 @@ async fn update_homework( // A kept (absent) due date may already be past; a newly set one may not be. check_not_past("due_at", due_at)?; let subject = match &req.subject_id { - Some(subject_id) => Some(crate::service::subject::in_course(&st.db, subject_id, course.get_id()).await?), + Some(subject_id) => { + Some(crate::service::subject::in_course(&st.db, subject_id, course.get_id()).await?) + } None => None, }; // The orphan guard runs on exactly the requests that re-scope the audience. @@ -360,11 +361,11 @@ async fn update_homework( /// Delete a homework and everything under it — submissions, their files, and /// results — then unlink the file blobs from disk. Requires teacher+ and -/// management rights over its course. Held under [`HOMEWORK_LOCK`]'s write lease -/// so no submission can land under the homework mid-delete; the blob names are -/// collected before the rows are wiped (the cascade is one transaction, children -/// first) and removed after, so a crash in between strands at worst an -/// unreachable file. +/// management rights over its course. The cascade is one transaction whose +/// homework-row lock keeps a submission from landing under the homework +/// mid-delete; the blob names are collected inside that transaction, before +/// the rows are wiped, and removed after, so a crash in between strands at +/// worst an unreachable file. #[utoipa::path( delete, path = "/{id}", @@ -391,7 +392,7 @@ async fn delete_homework( )); } crate::service::course::require_open(&st.db, &course).await?; - // The writer lease, the blob-key collection, and the cascade are + // The blob-key collection and the cascade are // [`service::homework::delete`]'s; unlinking the blobs stays here because // only the web layer knows `files_path`. let blob_keys = service::homework::delete(&st.db, homework).await?; @@ -548,10 +549,9 @@ async fn submit( Some(text) if !text.is_empty() => Some(SubmissionText::try_new(text)?), _ => None, }; - // The reader lease of [`HOMEWORK_LOCK`], the gate, the term wall, the - // graded check, and the upsert are one unit in - // [`service::homework_submission::submit`] — the audience interlock, not - // the freeze (that is the stamp on the row). + // The gate, the term wall, the graded check, and the upsert are one + // unit in [`service::homework_submission::submit`] — the audience + // interlock, not the freeze (that is the stamp on the row). let landed = service::homework_submission::submit(&st.db, &user, &id, text).await?; let files = service::homework_file::list_for_submission(&st.db, landed.submission.get_id()).await?; @@ -721,19 +721,15 @@ async fn upload_submission_file( const GRADED: AppError = AppError::Conflict( "this homework has been graded — ask the teacher to remove the grade before adding files", ); - // Reader lease as in `submit` — the audience interlock, not the freeze. - // Taken before the cap claim inside the insert, never after (the lock - // order is HOMEWORK_LOCK, then the counter lock). The lock lives in - // [`service::homework`]; the blob write stays here, inside the lease, - // because the row's "stored row points at a real blob" ordering does. - let _guard = service::homework::HOMEWORK_LOCK.read().await; - // Re-read the homework *under* the lease. Streaming the body takes as long - // as the client wants it to, and a homework delete (a writer) both takes - // and releases its lease inside that window — so the pre-flight snapshot - // can name a homework that no longer exists, and this handler would then - // auto-create a submission, credit the badge counters and write a file - // under it, all unreachable afterwards. A gate read before the body is a - // pre-flight; a gate read after it is the decision. + // Re-read the homework. Streaming the body takes as long as the client + // wants it to, and a homework delete can commit inside that window — so + // the pre-flight snapshot can name a homework that no longer exists, and + // this handler would then auto-create a submission, credit the badge + // counters and write a file under it, all unreachable afterwards. A gate + // read before the body is a pre-flight; a gate read after it is the + // decision. The writes below are still ordered against a delete, a grade + // and a PATCH narrowing the audience — each contends on the homework + // row's lock inside its own transaction. let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?; // Re-walled too: the term can be archived while the body streams. service::homework::require_open_term(&homework, &st.db).await?; @@ -801,8 +797,11 @@ async fn download_submission_file( let file = if user.get_role() == Role::Student { // Student: only their own file, behind the full submission gate. let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?; - let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id()); - service::homework_file::read_for(&st.db, &file_id, &submission) + let submission = + service::homework_submission::read_for(&st.db, homework.get_id(), user.get_id()) + .await? + .ok_or(AppError::NotFound)?; + service::homework_file::read_for(&st.db, &file_id, submission.get_id()) .await? .ok_or(AppError::NotFound)? } else { @@ -850,19 +849,23 @@ async fn delete_submission_file( const GRADED: AppError = AppError::Conflict( "this homework has been graded — ask the teacher to remove the grade before deleting files", ); - // Reader lease as in `submit` — the audience interlock, not the freeze. - let _guard = service::homework::HOMEWORK_LOCK.read().await; if service::homework_result::read_for(&st.db, homework.get_id(), user.get_id()) .await? .is_some() { return Err(GRADED); } - let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id()); - let file = - service::homework_file::read_for(&st.db, &HomeworkFileId::from_key(&fid), &submission) + let submission = + service::homework_submission::read_for(&st.db, homework.get_id(), user.get_id()) .await? .ok_or(AppError::NotFound)?; + let file = service::homework_file::read_for( + &st.db, + &HomeworkFileId::from_key(&fid), + submission.get_id(), + ) + .await? + .ok_or(AppError::NotFound)?; let blob = file.get_file().to_string(); // The delete's own transaction re-stamps the submission's "last touched" // clock (the late flag) as its freeze gate, so a refused delete moves @@ -923,12 +926,11 @@ async fn grade_homework( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - // The grading gates and the writer lease of [`HOMEWORK_LOCK`] live in - // [`service::homework_result::grade`]: a grade is what freezes a - // submission, so it must not interleave with the read side's - // gate-through-write submission edits — and the homework is re-read under - // the lease there, which keeps a homework delete (a fellow writer) from - // letting the upsert resurrect a result row under a vanished homework. + // The grading gates live in [`service::homework_result::grade`]; the + // grade transaction locks the homework row across the freeze stamp, which + // orders it against every student-side write — and keeps a homework + // delete from letting the upsert resurrect a result row under a vanished + // homework (the vanished row answers 404). let (homework, course) = homework_with_course(&id, &st.db).await?; if !can_manage_course(&course, &teacher) { return Err(AppError::Forbidden( @@ -974,9 +976,9 @@ async fn remove_homework_result( RequireTeacher(user): RequireTeacher, Path((id, target)): Path<(String, String)>, ) -> Result { - // The writer lease of [`HOMEWORK_LOCK`] is [`service::homework_result::ungrade`]'s - // — removing the grade is what unfreezes the submission, so it must not - // straddle the read side's gate-through-write edits either. + // Removing the grade is what unfreezes the submission; the un-grade's + // transaction takes the homework row's lock, so it cannot straddle a + // student-side write either. let (homework, course) = homework_with_course(&id, &st.db).await?; if !can_manage_course(&course, &user) { return Err(AppError::Forbidden( diff --git a/src/web/meals.rs b/src/web/meals.rs index df1cfc3..0ccbf96 100644 --- a/src/web/meals.rs +++ b/src/web/meals.rs @@ -438,11 +438,11 @@ async fn add_dish( &req.tags, &service::settings::load(&st.db).await?.get_dietary_tags(), )?; - // The dish-cap gate and its [`MENU_LOCK`](crate::service::menu::MENU_LOCK) - // lease live in the service: count-then-write is write-skew, so the count - // and the insert have to be one step, and the menu is read *inside* the - // lock — read before it, a `DELETE /menus/{id}` running in the gap takes - // its cascade with it and this dish lands on a menu that no longer exists. + // The dish-cap gate lives in the service: the cap is one guarded + // statement now — the menu row is locked `FOR NO KEY UPDATE` inside the + // dish write's own transaction and the insert carries the + // `count(*) < cap` guard, so a dish can never land on a menu that no + // longer exists, and two racing writers cannot overfill it either. let dish = service::menu::add_dish( &st.db, &MenuId::from_key(&id), @@ -502,8 +502,8 @@ async fn update_dish( )?), None => None, }; - // The dish write holds [`MENU_LOCK`](crate::service::menu::MENU_LOCK) - // inside the service, like every dish write — see `add_dish`. + // The dish write locks the menu row inside its own transaction — see + // `add_dish`. let updated = service::menu::update_dish(&st.db, dish, name, description, price, tags).await?; let viewer_tags = service::dietary_profile::tags_of(&st.db, user.get_id()).await?; Ok(Json(DishResponse::new(&updated, &viewer_tags))) @@ -531,8 +531,8 @@ async fn delete_dish( let dish = service::menu::read_dish(&st.db, &MenuDishId::from_key(&did)) .await? .ok_or(AppError::NotFound)?; - // The dish write holds [`MENU_LOCK`](crate::service::menu::MENU_LOCK) - // inside the service, like every dish write — see `add_dish`. + // The dish write locks the menu row inside its own transaction — see + // `add_dish`. service::menu::delete_dish(&st.db, dish).await?; Ok(StatusCode::NO_CONTENT) } diff --git a/src/web/questions.rs b/src/web/questions.rs index fbcb612..367ba17 100644 --- a/src/web/questions.rs +++ b/src/web/questions.rs @@ -482,7 +482,7 @@ async fn upload_image( let upload = read_image_upload(&st, &mut multipart).await?; let size = upload.size(); - let file = ulid::Ulid::generate().to_string(); + let file = crate::domain::monotonic_id::next_uuid().to_string(); store_blob(&st, &file, &upload.data, || async { match pool_question::set_image(&st.db, question.get_id(), &file, &upload.content_type, size) .await? @@ -808,7 +808,7 @@ async fn upload_solution_image( let upload = read_image_upload(&st, &mut multipart).await?; let size = upload.size(); - let file = ulid::Ulid::generate().to_string(); + let file = crate::domain::monotonic_id::next_uuid().to_string(); store_blob(&st, &file, &upload.data, || async { match solution::set_image(&st.db, solution.get_id(), &file, &upload.content_type, size) .await?