forge
Explore
Log in

Don't you dare go Hollow

merge: pick up L5/L6/L9 lane merges from postgres

Browse files at this commit

103e596d0d911866515b187304bc915cd1700067Ahmet Kaan GümüşParent: 29cdff2b88890f

68 changed files +4404 -4505

migrations/school/20260912000003_exams.sqlmodified+3 -0
@@ -236,6 +236,9 @@ CREATE TABLE homework_file (
236236 name TEXT NOT NULL,
237237 content_type TEXT NOT NULL,
238238 size BIGINT NOT NULL,
239+ -- The on-disk blob name (GC key) — READONLY in the old schema, app
240+ -- discipline now.
241+ file TEXT NOT NULL,
239242 created_at BIGINT NOT NULL
240243 );
241244
src/constant.rsmodified+0 -23
@@ -913,7 +913,6 @@ pub const FEE_PLAN_TABLE: &str = "fee_plan";
913913 pub const FEE_PLAN_ASSIGNMENT_TABLE: &str = "fee_plan_assignment";
914914 pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger";
915915 pub const BOARD_TABLE: &str = "board";
916-pub const BOARD_STROKE_TABLE: &str = "board_stroke";
917916 /// One row per badge a user has earned, keyed by the pair. A table of its own
918917 /// rather than an array column on the user row: an `array<…>` there breaks
919918 /// 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";
963962 /// `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which is truthy for *every*
964963 /// row and would license editing a plan a family is already being billed for.
965964 pub const FEE_PLAN_UNASSIGNED_GUARD: &str = "(assignment_count ?? 0) = 0";
966-pub const NOTE_FILE_COUNT_FIELD: &str = "file_count";
967-pub const COURSE_NOTE_FILE_COUNT_FIELD: &str = "file_count";
968965 pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count";
969966 pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count";
970967 /// 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";
975972 /// column of its own — a new one would mean a migration on a SCHEMAFULL table
976973 /// for a value nothing ever observes.
977974 pub const USER_ROLE_CLAIM_FIELD: &str = CHATBOT_THREAD_COUNT_FIELD;
978-/// How many boards this user created, on the user row — the same per-user shape
979-/// as `CHATBOT_THREAD_COUNT_FIELD`, capped at `MAX_BOARDS_PER_CREATOR`. It is
980-/// what closes the "open another board" way around the two board counters
981-/// below; released when a board is deleted.
982-pub const USER_BOARD_COUNT_FIELD: &str = "board_count";
983975 /// The lifetime totals behind the badges, all on the user row. Not caps: each
984976 /// one counts something the person *did*. A counter comes down in exactly one
985977 /// shape, and the two cases that qualify share a reason: the account credited
@@ -1144,15 +1136,6 @@ pub const BADGES: [(&str, BadgeStat, i64); 34] = [
11441136 ("study_streak_7", BadgeStat::StudyStreak, 7),
11451137 ("study_streak_30", BadgeStat::StudyStreak, 30),
11461138 ];
1147-/// The two stroke counters on a board row. `epoch_stroke_count` is reset to
1148-/// zero by a clear and capped at `MAX_EPOCH_STROKES` — a full epoch is
1149-/// recoverable. `total_stroke_count` is never reset and capped at
1150-/// `MAX_BOARD_STROKES`; reaching it stamps `closed_at`, and a closed board is
1151-/// read-only for good. Both are claimed in the same conditional write as the
1152-/// stroke row, so two people drawing at once contend on the board record rather
1153-/// than on a `SELECT count()` either of them can outrun.
1154-pub const BOARD_EPOCH_STROKE_COUNT_FIELD: &str = "epoch_stroke_count";
1155-pub const BOARD_TOTAL_STROKE_COUNT_FIELD: &str = "total_stroke_count";
11561139 /// Cap 1, not N: an appointment slot holds at most one live booking, so this
11571140 /// counter is really an "is it taken" flag kept in the shape every other cap
11581141 /// uses (`claim`/`release`), which is what makes rejecting or cancelling a
@@ -1194,12 +1177,6 @@ pub const SUBMISSION_GRADED_FIELD: &str = "graded_by_result";
11941177 /// The condition itself, spelled once: a submission is writable exactly while
11951178 /// its grade stamp is absent.
11961179 pub const SUBMISSION_OPEN_GUARD: &str = "graded_by_result = NONE";
1197-/// The same idea for a whiteboard, spelled once: a board accepts strokes
1198-/// exactly while the creator has not locked it and it has not closed itself on
1199-/// `MAX_BOARD_STROKES`. Every stroke write carries it, so "is this board still
1200-/// open" and the write it licenses are one conditional single-record write —
1201-/// a lock landing mid-draw beats the stroke instead of racing it.
1202-pub const BOARD_OPEN_GUARD: &str = "locked = false AND closed_at = NONE";
12031180 /// A signup list has **frozen**: the event takes registrations at all *and* it
12041181 /// started, or — for an ends_at-only event (a pure signup deadline) — that end
12051182 /// passed. A timeless event never freezes. Matched against `$now` in millis, on
src/db/bank_question.rsmodified+174 -187
@@ -7,10 +7,10 @@
77
88 use std::collections::HashMap;
99
10-use surrealdb::types::{RecordId, SurrealValue};
10+use sqlx::types::Json;
1111
12-use crate::constant::USAGE_COUNTS_SQL;
13-use crate::database::{Database, transaction_with_retry, write_with_retry};
12+use crate::database::{Database, tx_with_retry};
13+use crate::db::page::{PagedList, Param};
1414 use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility};
1515 use crate::domain::bank_question_image::BankQuestionImage;
1616 use crate::domain::exam::ExamId;
@@ -21,21 +21,6 @@ use crate::domain::timestamp::Timestamp;
2121 use crate::domain::user::UserId;
2222 use crate::error::AppError;
2323
24-/// One `GROUP BY from_bank` row of [`usage_counts`].
25-#[derive(SurrealValue)]
26-struct UsageCount {
27- from_bank: BankQuestionId,
28- n: i64,
29-}
30-
31-/// What one [`delete`] transaction removed — the template (an empty list once
32-/// someone else deleted it first) and the image rows swept with it.
33-#[derive(SurrealValue)]
34-struct DeleteOutcome {
35- question: Vec<BankQuestion>,
36- images: Vec<BankQuestionImage>,
37-}
38-
3924 pub async fn create(
4025 db: &Database,
4126 owner: UserId,
@@ -85,24 +70,52 @@ async fn insert(
8570 BankVisibility::default(),
8671 Timestamp::now(),
8772 );
88- let created: Option<BankQuestion> = db.create(question.id.record()).content(question).await?;
89- created.ok_or_else(|| AppError::Internal("failed to create bank question".into()))
73+ let row = sqlx::query_as!(
74+ BankQuestion,
75+ r#"INSERT INTO bank_question
76+ (id, owner, subject, text, kind, points, choices, correct,
77+ source_exam, visibility, created_at)
78+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
79+ RETURNING *"#,
80+ question.id,
81+ question.owner,
82+ question.subject,
83+ question.text,
84+ question.kind,
85+ question.points,
86+ question.choices,
87+ question.correct,
88+ question.source_exam,
89+ question.visibility,
90+ question.created_at,
91+ )
92+ .fetch_one(db)
93+ .await?;
94+ Ok(row)
9095 }
9196
9297 pub async fn read(db: &Database, id: &BankQuestionId) -> Result<Option<BankQuestion>, AppError> {
93- Ok(db.select(id.record()).await?)
98+ let row = sqlx::query_as!(
99+ BankQuestion,
100+ "SELECT * FROM bank_question WHERE id = $1",
101+ id
102+ )
103+ .fetch_optional(db)
104+ .await?;
105+ Ok(row)
94106 }
95107
96-/// One page of the bank the caller may see, **newest first** (ULID ids sort by
97-/// creation, so `id DESC` is newest-first) — plus the total row count under
98-/// the same filters, so a client can page past the window.
108+/// One page of the bank the caller may see, **newest first** (`id DESC` is
109+/// mint order — the ids are write-ordered UUIDv7) — plus the total row count
110+/// under the same filters, so a client can page past the window.
99111 ///
100-/// Every filter is a WHERE clause and the window is a real `LIMIT`/`START`:
101-/// the old version read the whole table and sliced it in memory, which hid
102-/// every template past the client's first page. `q` is a case- and
103-/// diacritic-insensitive fragment of the question text (blank = no text
104-/// filter): needle and column both go through
105-/// [`crate::domain::text_fold`], so `istanbul` finds `İSTANBUL` and back.
112+/// The window is a real `LIMIT`/`OFFSET` handed to the database (the
113+/// [`PagedList`] builder: the filters are runtime-conditional, which is that
114+/// builder's named exemption from the compile-time macros). `q` is a case-
115+/// and diacritic-insensitive fragment of the question text (blank = no text
116+/// filter): needle and column both go through [`crate::domain::text_fold`],
117+/// so `istanbul` finds `İSTANBUL` and back. `position` rather than `LIKE`
118+/// keeps the needle a *literal* substring — no `%`/`_` wildcard surprises.
106119 ///
107120 /// `visible_to` is the security filter, and it is a WHERE clause like every
108121 /// 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<Option<BankQuest
113126 /// `visibility` is the *user's* filter ("only mine" / "shared with the
114127 /// school") and is ANDed on top of that gate, so it can only ever narrow:
115128 /// `school` still hides another teacher's private rows, and `private`
116-/// intersected with the gate leaves exactly the caller's own drafts. It
117-/// joins the same `clauses` vec as the rest, so `total` honours it too —
118-/// a count that ignored it would break paging.
119-// Flat filter args, like every other `list` here — a builder struct for
120-// four `Option`s and a window would be more machinery than the call sites.
129+/// intersected with the gate leaves exactly the caller's own drafts. It is
130+/// part of the same WHERE, so `total` honours it too — a count that ignored
131+/// it would break paging.
132+///
133+/// The uuid filters bind raw through the id newtypes' [`crate::domain`]
134+/// `uuid()` accessor — [`Param::Uuid`] keeps the comparison exact, typed
135+/// rather than textual.
121136 #[allow(clippy::too_many_arguments)]
122137 pub async fn list(
123138 db: &Database,
@@ -130,70 +145,53 @@ pub async fn list(
130145 offset: i64,
131146 ) -> Result<(Vec<BankQuestion>, i64), AppError> {
132147 let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty());
133- let mut clauses = Vec::new();
134- if visible_to.is_some() {
135- clauses.push("(visibility = 'school' OR owner = $viewer)");
136- }
137- if visibility.is_some() {
138- clauses.push("visibility = $visibility");
139- }
140- if owner.is_some() {
141- clauses.push("owner = $owner");
142- }
143- if subject.is_some() {
144- clauses.push("subject = $subject");
145- }
146- let text_clause = format!("{} CONTAINS $q", search_fold_sql("text"));
147- if needle.is_some() {
148- clauses.push(text_clause.as_str());
149- }
150- let where_clause = if clauses.is_empty() {
151- "true".to_string()
152- } else {
153- clauses.join(" AND ")
154- };
155- // `START` alone (no `LIMIT`) is the unpaged case — `?limit` is opt-in.
156- let window = match limit {
157- Some(_) => "LIMIT $limit START $offset",
158- None => "START $offset",
159- };
160- // The count runs over the *same* WHERE, so `total` can never disagree
161- // with what paging through the list actually yields.
162- let mut query = db
163- .query(format!(
164- "SELECT * FROM bank_question WHERE {where_clause} ORDER BY id DESC {window};
165- SELECT VALUE count() FROM bank_question WHERE {where_clause} GROUP ALL;"
166- ))
167- .bind(("offset", offset));
148+ let mut clauses: Vec<String> = Vec::new();
149+ let mut binds: Vec<Param> = Vec::new();
168150 if let Some(viewer) = visible_to {
169- query = query.bind(("viewer", viewer.record()));
151+ binds.push(Param::Uuid(viewer.uuid()));
152+ clauses.push(format!(
153+ "(visibility = 'school' OR owner = ${})",
154+ binds.len()
155+ ));
170156 }
171157 if let Some(visibility) = visibility {
172- query = query.bind(("visibility", visibility.as_str().to_string()));
158+ binds.push(Param::Text(visibility.as_str().to_string()));
159+ clauses.push(format!("visibility = ${}", binds.len()));
173160 }
174161 if let Some(owner) = owner {
175- query = query.bind(("owner", owner.record()));
162+ binds.push(Param::Uuid(owner.uuid()));
163+ clauses.push(format!("owner = ${}", binds.len()));
176164 }
177165 if let Some(subject) = subject {
178- query = query.bind(("subject", subject.record()));
166+ binds.push(Param::Uuid(subject.uuid()));
167+ clauses.push(format!("subject = ${}", binds.len()));
179168 }
180169 if let Some(needle) = needle {
181- query = query.bind(("q", needle));
170+ binds.push(Param::Text(needle));
171+ clauses.push(format!(
172+ "position(${} in {}) > 0",
173+ binds.len(),
174+ search_fold_sql("text")
175+ ));
182176 }
183- if let Some(limit) = limit {
184- query = query.bind(("limit", limit));
177+ let from_where = if clauses.is_empty() {
178+ "bank_question WHERE true".to_string()
179+ } else {
180+ format!("bank_question WHERE {}", clauses.join(" AND "))
181+ };
182+ // The count runs over the *same* WHERE, so `total` can never disagree
183+ // with what paging through the list actually yields.
184+ let mut page = PagedList::new(from_where, "ORDER BY id DESC");
185+ for bind in binds {
186+ page = page.bind(bind);
185187 }
186- let mut result = query.await?.check()?;
187- let questions = result.take::<Vec<BankQuestion>>(0)?;
188- // `GROUP ALL` yields no row at all when nothing matched.
189- let total = result.take::<Vec<i64>>(1)?.first().copied().unwrap_or(0);
190- Ok((questions, total))
188+ page.run(limit, offset, db).await
191189 }
192190
193191 /// How many exam questions were instantiated from each of `ids` — the
194192 /// `from_bank` side of the provenance link, tallied for a whole page in
195193 /// **one** grouped query (a `count()` per row would be the N+1 this page
196-/// already had removed once). Keys are template record keys; a template
194+/// already had removed once). Keys are the templates' wire keys; a template
197195 /// nobody ever used has no entry at all, so the caller reads a miss as
198196 /// zero — and the UI can stay quiet rather than print "0".
199197 ///
@@ -207,16 +205,22 @@ pub async fn usage_counts(
207205 if ids.is_empty() {
208206 return Ok(HashMap::new());
209207 }
210- let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect();
211- let mut result = db
212- .query(USAGE_COUNTS_SQL)
213- .bind(("ids", records))
214- .await?
215- .check()?;
216- Ok(result
217- .take::<Vec<UsageCount>>(0)?
208+ let ids: Vec<BankQuestionId> = ids.iter().map(|id| (*id).clone()).collect();
209+ let rows = sqlx::query!(
210+ r#"SELECT from_bank AS "from_bank: BankQuestionId", count(*) AS n
211+ FROM exam_question
212+ WHERE from_bank = ANY($1)
213+ GROUP BY from_bank"#,
214+ ids,
215+ )
216+ .fetch_all(db)
217+ .await?;
218+ Ok(rows
218219 .into_iter()
219- .map(|row| (row.from_bank.key().to_string(), row.n))
220+ .filter_map(|row| {
221+ let n = row.n;
222+ row.from_bank.map(|from_bank| (from_bank.key(), n))
223+ })
220224 .collect())
221225 }
222226
@@ -228,22 +232,13 @@ pub async fn usage_counts(
228232 /// field is re-stated from the snapshot, and the kind/choices/correct trio
229233 /// has to be (a text-only edit re-submits the stored options *with their
230234 /// ids* so each keeps its picture) — so without the compare-and-set the
231-/// later writer silently reverts the earlier one — and the window is a
232-/// database round trip wide, which is exactly how far apart two concurrent
233-/// requests to this one process can sit.
235+/// later writer silently reverts the earlier one.
234236 ///
235237 /// Every field the merge re-states is in the guard, which is the same list
236-/// the `SET` writes. `choices` is compared whole: its objects carry two
237-/// required string keys, so none is ever dropped for being `NONE` (the trap
238-/// [`crate::db::settings::save_if_unchanged`] works around).
239-///
240-/// Rides [`write_with_retry`] because an image write now moves this row too
241-/// ([`crate::db::bank_question_image::upsert`]): an upload landing in the
242-/// same instant makes the store answer "conflict, retry", and a bare
243-/// `check()` would turn that into a 500 for an edit that only had to be
244-/// re-sent. A lost round writes nothing, and the guard is re-evaluated on
245-/// the next one, so a genuine stale merge still comes back as `None`.
246-/// Admissible: an `UPDATE` can never answer "already exists".
238+/// the `SET` writes; the nullable ones compare `IS NOT DISTINCT FROM`, so an
239+/// absent subject/correct/choices guards truthfully. Postgres needs no retry
240+/// loop around this: the guard re-evaluates on the row lock at execution, so
241+/// a rival write either predates this statement's snapshot or loses its own.
247242 pub async fn update_if_unchanged(
248243 db: &Database,
249244 expected: BankQuestion,
@@ -254,42 +249,40 @@ pub async fn update_if_unchanged(
254249 visibility: BankVisibility,
255250 ) -> Result<Option<BankQuestion>, AppError> {
256251 let (kind, choices, correct) = spec.into_parts();
257- let rows: Vec<BankQuestion> = write_with_retry(
258- db,
259- "UPDATE $id SET subject = $subject, text = $text, points = $points,
260- kind = $kind, choices = $choices, correct = $correct,
261- visibility = $visibility
262- WHERE subject = $was_subject AND text = $was_text
263- AND points = $was_points AND kind = $was_kind
264- AND choices = $was_choices AND correct = $was_correct
265- AND visibility = $was_visibility
266- RETURN AFTER",
267- &[
268- (
269- "was_subject".into(),
270- expected.subject.clone().map(|s| s.record()).into_value(),
271- ),
272- ("was_text".into(), expected.text.clone().into_value()),
273- ("was_points".into(), expected.points.into_value()),
274- ("was_kind".into(), expected.kind.clone().into_value()),
275- ("was_choices".into(), expected.choices.clone().into_value()),
276- ("was_correct".into(), expected.correct.clone().into_value()),
277- (
278- "was_visibility".into(),
279- expected.visibility.clone().into_value(),
280- ),
281- ("id".into(), expected.id.record().into_value()),
282- ("subject".into(), subject.map(|s| s.record()).into_value()),
283- ("text".into(), text.into_value()),
284- ("points".into(), points.into_value()),
285- ("kind".into(), kind.into_value()),
286- ("choices".into(), choices.into_value()),
287- ("correct".into(), correct.into_value()),
288- ("visibility".into(), visibility.into_value()),
289- ],
252+ let choices = choices.map(Json);
253+ let row = sqlx::query_as!(
254+ BankQuestion,
255+ r#"UPDATE bank_question SET
256+ subject = $2, text = $3, points = $4, kind = $5,
257+ choices = $6, correct = $7, visibility = $8
258+ WHERE id = $1
259+ AND subject IS NOT DISTINCT FROM $9
260+ AND text = $10
261+ AND points = $11
262+ AND kind = $12
263+ AND choices IS NOT DISTINCT FROM $13
264+ AND correct IS NOT DISTINCT FROM $14
265+ AND visibility = $15
266+ RETURNING *"#,
267+ expected.id,
268+ subject,
269+ text,
270+ points,
271+ kind,
272+ choices,
273+ correct,
274+ visibility,
275+ expected.subject,
276+ expected.text,
277+ expected.points,
278+ expected.kind,
279+ expected.choices,
280+ expected.correct,
281+ expected.visibility,
290282 )
283+ .fetch_optional(db)
291284 .await?;
292- Ok(rows.into_iter().next())
285+ Ok(row)
293286 }
294287
295288 /// Delete the template and cascade-remove its bank images, so none points
@@ -297,59 +290,53 @@ pub async fn update_if_unchanged(
297290 /// actually removed come back with it: the blobs are the web layer's to
298291 /// take off disk, but only for *these* rows — an upload that committed
299292 /// after the caller listed the template's images is swept here too, and a
300-/// pre-read snapshot would strand its blob for good
301-/// ([`crate::db::note::delete`]'s story, this domain over).
302-///
303-/// Children first, in one transaction: as two queries, a failure between
304-/// them left image rows swept under a template that survived, or (the other
305-/// order) a template gone with its images still there. Rides the retry
306-/// because an image write now moves this very row
307-/// ([`crate::db::bank_question_image::upsert`]) — the two contend by
308-/// design, and a lost round through a bare `check()` would be a 500 for a
309-/// delete that only had to be re-sent. Admissible: no `UPDATE` or `DELETE`
310-/// in here can answer "already exists".
293+/// pre-read snapshot would strand its blob for good.
311294 ///
312-/// Exam questions tied to this template keep living: only their provenance
313-/// links are cleared, field-scoped (never a whole-row save — the question
314-/// isn't ours and may be edited concurrently), so nothing can read a link to
315-/// a template that no longer exists. *Both* directions point at a template,
316-/// so both are cleared: `from_bank` on the questions instantiated from it,
317-/// and `banked_as` on the question it was saved out of.
295+/// All four statements are one transaction, children before the parent so
296+/// the foreign keys never refuse the parent delete: the provenance links
297+/// clear first (exam questions tied to this template keep living — only the
298+/// links go, field-scoped, in both directions: `from_bank` on the questions
299+/// instantiated from it and `banked_as` on the question it was saved out
300+/// of), then the image sweep, then the row. `cascade = true` because an
301+/// image upsert committing inside this window makes the parent delete
302+/// answer 23503 — a mid-cascade race the retry loop re-runs, sweeping the
303+/// latecomer with it.
318304 pub async fn delete(
319305 db: &Database,
320306 target: BankQuestion,
321307 ) -> Result<(BankQuestion, Vec<BankQuestionImage>), AppError> {
322- let (mut result, mut errors) = transaction_with_retry(
323- db,
324- "BEGIN TRANSACTION;
325- LET $images = (DELETE bank_question_image WHERE bank_question = $b RETURN BEFORE);
326- UPDATE exam_question SET from_bank = NONE WHERE from_bank = $b;
327- UPDATE exam_question SET banked_as = NONE WHERE banked_as = $b;
328- LET $gone = (DELETE $b RETURN BEFORE);
329- RETURN { question: $gone, images: $images };
330- COMMIT TRANSACTION;",
331- &[("b".into(), target.id.record().into_value())],
332- &[],
333- )
334- .await?;
335- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
336- return Err(error.into());
337- }
338- // The trailing `RETURN` is the last statement before `COMMIT`, so its
339- // slot follows the statement count rather than a hand-kept number;
340- // `num_statements` counts BEGIN and COMMIT.
341- let slot = result.num_statements().saturating_sub(2);
342- let outcome = result
343- .take::<Vec<DeleteOutcome>>(slot)?
344- .into_iter()
345- .next()
346- .ok_or_else(|| AppError::Internal("failed to delete bank question".into()))?;
347- let question = outcome
348- .question
349- .into_iter()
350- .next()
308+ tx_with_retry(db, true, async |tx| {
309+ let id = target.id.clone();
310+ sqlx::query!(
311+ "UPDATE exam_question SET from_bank = NULL WHERE from_bank = $1",
312+ id
313+ )
314+ .execute(tx)
315+ .await?;
316+ sqlx::query!(
317+ "UPDATE exam_question SET banked_as = NULL WHERE banked_as = $1",
318+ id
319+ )
320+ .execute(tx)
321+ .await?;
322+ let images = sqlx::query_as!(
323+ BankQuestionImage,
324+ "DELETE FROM bank_question_image WHERE bank_question = $1 RETURNING *",
325+ id
326+ )
327+ .fetch_all(tx)
328+ .await?;
329+ let question = sqlx::query_as!(
330+ BankQuestion,
331+ "DELETE FROM bank_question WHERE id = $1 RETURNING *",
332+ id
333+ )
334+ .fetch_optional(tx)
335+ .await?
351336 .ok_or(AppError::NotFound)?;
352- Ok((question, outcome.images))
337+ Ok((question, images))
338+ })
339+ .await
353340 }
354341
355342 #[cfg(test)]
src/db/bank_question_image.rsmodified+104 -117
@@ -1,105 +1,69 @@
1-//! The `bank_question_image` slot table: the per-slot upsert that pins the
2-//! template's existence into its own transaction, the page-wide listing, and
3-//! the choice sweep a non-destructive PATCH runs. Blob I/O stays in the web
4-//! layer; the pure entity and newtypes in
1+//! The `bank_question_image` slot table: the per-slot upsert, the page-wide
2+//! listing, and the choice sweep a non-destructive PATCH runs. Blob I/O
3+//! stays in the web layer; the pure entity and newtypes in
54 //! [`crate::domain::bank_question_image`].
65
7-use surrealdb::types::{RecordId, SurrealValue};
8-
9-use crate::database::{Database, transaction_with_retry};
6+use crate::database::{Database, foreign_key_violation, tx_with_retry};
107 use crate::domain::bank_question::BankQuestionId;
11-use crate::domain::bank_question_image::{BankQuestionImage, BankQuestionImageId};
8+use crate::domain::bank_question_image::BankQuestionImage;
129 use crate::domain::exam_question::ChoiceId;
1310 use crate::error::AppError;
1411
15-/// What one [`upsert`] transaction returns: the row it
16-/// stored and the blob name it replaced. Both are arrays because SurrealDB
17-/// drops an object key valued `NONE` on the way out, while an empty array
18-/// survives — "nothing was replaced" has to be readable, not missing.
19-#[derive(SurrealValue)]
20-struct UpsertOutcome {
21- stored: Vec<BankQuestionImage>,
22- replaced: Vec<String>,
23-}
24-
25-/// Create or replace the slot's image row — the deterministic id makes this
26-/// the whole "one image per slot" story — handing back what it stored plus
27-/// the blob name it replaced, for the caller to take off disk.
28-///
29-/// Both halves are the transaction's doing. The template's own `points` is
30-/// moved and put straight back inside it, the way
31-/// [`crate::db::pool_question::bump_question_and_write`] moves
32-/// `asked_at` (`created_at` is `READONLY`, so the move goes on the one other
33-/// int column): that makes the template's *existence* part of this write.
34-/// A bare `UPSERT` guarded by having read the template first does not
35-/// survive its delete window — the read sees a row
36-/// [`crate::db::bank_question::delete`] has removed but
37-/// not committed, while that delete's image sweep ran on a snapshot
38-/// predating this row, so both commit and the image outlives the template
39-/// it hangs on. Nothing could ever read, delete, or sweep it afterwards:
40-/// every image route goes through the template. Moving the value makes the
41-/// two transactions touch one key, so the store refuses a side; writing the
42-/// same value back would be elided and collide with nothing.
12+/// Create or replace the slot's image row — the table's `NULLS NOT DISTINCT`
13+/// unique key makes this the whole "one image per slot" story — handing back
14+/// what it stored plus the blob name it replaced, for the caller to take off
15+/// disk.
4316 ///
44-/// The replaced blob name comes out of this same transaction rather than a
45-/// read in front of it (the shape
46-/// [`crate::db::pool_question::set_image`] has): two
47-/// uploads to one slot both write this row, so they contend and the loser
48-/// re-reads the winner's blob name, where two pre-reads both saw the *old*
49-/// blob and left the loser's fresh one orphaned on disk.
17+/// Both halves are the transaction's doing, and the row lock makes them one
18+/// switch: two uploads racing on one slot serialize on the `FOR UPDATE`, and
19+/// the loser's `ON CONFLICT` re-reads the winner's row, where two unlocked
20+/// pre-reads would both have seen the *old* blob name and left the loser's
21+/// fresh one orphaned on disk.
5022 ///
51-/// Admissible for [`transaction_with_retry`]: the `UPSERT`'s id is
52-/// deterministic per (question, slot) and the table carries no `UNIQUE`
53-/// index, so the write always resolves onto the row its id names and can
54-/// never answer "already exists".
23+/// The template's existence rides the real foreign key: an insert whose
24+/// template was deleted mid-flight answers 23503 and maps to the same 404
25+/// the old points-move transaction produced with its `THROW`. Nothing is
26+/// written either way.
5527 pub async fn upsert(
5628 db: &Database,
5729 image: BankQuestionImage,
5830 ) -> Result<(BankQuestionImage, Option<String>), AppError> {
59- // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic
60- let (question, id) = (image.bank_question.record(), image.id.record());
61- let (mut result, mut errors) = transaction_with_retry(
62- db,
63- "BEGIN TRANSACTION;
64- LET $was_points = (SELECT VALUE points FROM ONLY $b);
65- LET $bumped = (UPDATE $b SET points = points + 1 RETURN VALUE id);
66- IF array::len($bumped) = 0 { THROW 'no_question' };
67- UPDATE $b SET points = $was_points;
68- LET $replaced = (SELECT VALUE file FROM $id);
69- LET $stored = (UPSERT $id CONTENT $image);
70- RETURN { stored: $stored, replaced: $replaced };
71- COMMIT TRANSACTION;",
72- &[
73- ("b".into(), question.into_value()),
74- ("id".into(), id.into_value()),
75- ("image".into(), image.into_value()),
76- ],
77- &["no_question"],
78- )
79- .await?;
80- // An aborted transaction errors *every* slot, most with a generic "not
81- // executed" — only the THROW's own slot names the reason.
82- if errors
83- .values()
84- .any(|error| error.to_string().contains("no_question"))
85- {
86- return Err(AppError::NotFound);
87- }
88- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
89- return Err(error.into());
90- }
91- // The trailing `RETURN` is the last statement before `COMMIT`, so its
92- // slot follows the statement count rather than a hand-kept number;
93- // `num_statements` counts BEGIN and COMMIT.
94- let slot = result.num_statements().saturating_sub(2);
95- let failed = || AppError::Internal("failed to store bank question image".into());
96- let outcome = result
97- .take::<Vec<UpsertOutcome>>(slot)?
98- .into_iter()
99- .next()
100- .ok_or_else(failed)?;
101- let stored = outcome.stored.into_iter().next().ok_or_else(failed)?;
102- Ok((stored, outcome.replaced.into_iter().next()))
31+ tx_with_retry(db, false, async |tx| {
32+ let was = sqlx::query!(
33+ r#"SELECT file FROM bank_question_image
34+ WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2
35+ FOR UPDATE"#,
36+ image.bank_question.clone(),
37+ image.slot.clone(),
38+ )
39+ .fetch_optional(tx)
40+ .await?
41+ .map(|row| row.file);
42+ let stored = match sqlx::query_as!(
43+ BankQuestionImage,
44+ r#"INSERT INTO bank_question_image
45+ (bank_question, slot, file, content_type, size)
46+ VALUES ($1, $2, $3, $4, $5)
47+ ON CONFLICT (bank_question, slot) DO UPDATE
48+ SET file = $3, content_type = $4, size = $5
49+ RETURNING *"#,
50+ image.bank_question.clone(),
51+ image.slot.clone(),
52+ image.file.clone(),
53+ image.content_type,
54+ image.size,
55+ )
56+ .fetch_one(tx)
57+ .await
58+ {
59+ Ok(row) => row,
60+ // The template row is gone; no orphan image may outlive it.
61+ Err(err) if foreign_key_violation(&err) => return Err(AppError::NotFound),
62+ Err(err) => return Err(err.into()),
63+ };
64+ Ok((stored, was))
65+ })
66+ .await
10367 }
10468
10569 pub async fn read_slot(
@@ -107,21 +71,30 @@ pub async fn read_slot(
10771 question: &BankQuestionId,
10872 slot: Option<&ChoiceId>,
10973 ) -> Result<Option<BankQuestionImage>, AppError> {
110- Ok(db
111- .select(BankQuestionImageId::for_slot(question, slot).record())
112- .await?)
74+ let row = sqlx::query_as!(
75+ BankQuestionImage,
76+ r#"SELECT * FROM bank_question_image
77+ WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2"#,
78+ question,
79+ slot.cloned(),
80+ )
81+ .fetch_optional(db)
82+ .await?;
83+ Ok(row)
11384 }
11485
11586 pub async fn list_for_question(
11687 db: &Database,
11788 question: &BankQuestionId,
11889 ) -> Result<Vec<BankQuestionImage>, AppError> {
119- let mut result = db
120- .query("SELECT * FROM bank_question_image WHERE bank_question = $b")
121- .bind(("b", question.record()))
122- .await?
123- .check()?;
124- Ok(result.take::<Vec<BankQuestionImage>>(0)?)
90+ let rows = sqlx::query_as!(
91+ BankQuestionImage,
92+ "SELECT * FROM bank_question_image WHERE bank_question = $1",
93+ question
94+ )
95+ .fetch_all(db)
96+ .await?;
97+ Ok(rows)
12598 }
12699
127100 /// The image rows of several templates in one query — for bucketing onto a
@@ -133,13 +106,15 @@ pub async fn list_for_questions(
133106 if questions.is_empty() {
134107 return Ok(Vec::new());
135108 }
136- let records: Vec<RecordId> = questions.iter().map(|q| q.record()).collect();
137- let mut result = db
138- .query("SELECT * FROM bank_question_image WHERE bank_question IN $ids")
139- .bind(("ids", records))
140- .await?
141- .check()?;
142- Ok(result.take::<Vec<BankQuestionImage>>(0)?)
109+ let ids: Vec<BankQuestionId> = questions.iter().map(|q| (*q).clone()).collect();
110+ let rows = sqlx::query_as!(
111+ BankQuestionImage,
112+ "SELECT * FROM bank_question_image WHERE bank_question = ANY($1)",
113+ ids
114+ )
115+ .fetch_all(db)
116+ .await?;
117+ Ok(rows)
143118 }
144119
145120 /// Drop the option pictures whose choice is gone — every choice image of
@@ -157,23 +132,35 @@ pub async fn delete_choices_not_in(
157132 keep: &[ChoiceId],
158133 ) -> Result<Vec<BankQuestionImage>, AppError> {
159134 let keep: Vec<String> = keep.iter().map(|id| id.as_str().to_string()).collect();
160- let mut result = db
161- .query(
162- "DELETE bank_question_image \
163- WHERE bank_question = $b AND slot != NONE AND slot NOT IN $keep RETURN BEFORE",
164- )
165- .bind(("b", question.record()))
166- .bind(("keep", keep))
167- .await?
168- .check()?;
169- Ok(result.take::<Vec<BankQuestionImage>>(0)?)
135+ let rows = sqlx::query_as!(
136+ BankQuestionImage,
137+ r#"DELETE FROM bank_question_image
138+ WHERE bank_question = $1
139+ AND slot IS NOT NULL
140+ AND NOT (slot = ANY($2))
141+ RETURNING *"#,
142+ question,
143+ keep
144+ )
145+ .fetch_all(db)
146+ .await?;
147+ Ok(rows)
170148 }
171149
172150 pub async fn delete(
173151 db: &Database,
174152 image: BankQuestionImage,
175153 ) -> Result<BankQuestionImage, AppError> {
176- let deleted: Option<BankQuestionImage> = db.delete(image.id.record()).await?;
154+ let deleted = sqlx::query_as!(
155+ BankQuestionImage,
156+ r#"DELETE FROM bank_question_image
157+ WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2
158+ RETURNING *"#,
159+ image.bank_question,
160+ image.slot
161+ )
162+ .fetch_optional(db)
163+ .await?;
177164 deleted.ok_or(AppError::NotFound)
178165 }
179166
src/db/board.rsmodified+211 -312
@@ -2,20 +2,14 @@
22 //! field-scoped `UPDATE … SET` — a stroke landing concurrently is moving the
33 //! two counters this table's struct does not carry.
44
5-use surrealdb::types::SurrealValue;
6-
7-use crate::constant::{MAX_BOARDS_PER_CREATOR, USER_BOARD_COUNT_FIELD};
8-use crate::database::{Database, transaction_with_retry};
9-use crate::db::cap;
5+use crate::constant::{MAX_BOARD_PARTICIPANTS, MAX_BOARDS_PER_CREATOR};
6+use crate::database::{Database, tx_with_retry, unique_violation};
107 use crate::db::page::PagedList;
118 use crate::domain::board::{Board, BoardId, BoardTitle, checked_participants};
129 use crate::domain::timestamp::Timestamp;
1310 use crate::domain::user::UserId;
1411 use crate::error::AppError;
1512
16-/// Open a board, taking a slot on the creator's `board_count` in the same
17-/// transaction as the row — the counter is the authority on how many
18-/// boards exist, so it can never count a row that did not commit.
1913 pub async fn create(
2014 db: &Database,
2115 creator: &UserId,
@@ -34,30 +28,57 @@ pub async fn create(
3428 closed_at: None,
3529 created_at: Timestamp::now(),
3630 };
37- match cap::claim_and_create(
38- &creator.record(),
39- USER_BOARD_COUNT_FIELD,
31+ // The seat claim and the row are one statement (the `cap::claim_and_create`
32+ // CTE, spelled out at its call site): a refused insert takes its own
33+ // seat bump back, so the counter can never count a row that did not commit.
34+ let saved = sqlx::query_as!(
35+ Board,
36+ r#"WITH seat AS (
37+ UPDATE app_user SET board_count = board_count + 1
38+ WHERE id = $1 AND board_count < $2
39+ RETURNING 1)
40+ INSERT INTO board (id, creator, title, participants, locked, locked_by, locked_at,
41+ epoch, closed_at, created_at)
42+ SELECT $3, $1, $4, $5, false, NULL, NULL, 0, NULL, $6
43+ WHERE EXISTS (SELECT 1 FROM seat)
44+ RETURNING id, creator, title, participants, locked, locked_by, locked_at,
45+ epoch, closed_at, created_at"#,
46+ board.creator,
4047 MAX_BOARDS_PER_CREATOR,
41- &board.id.record(),
42- &board,
43- db,
48+ board.id,
49+ board.title,
50+ &board.participants,
51+ board.created_at
4452 )
45- .await?
46- {
47- cap::Claimed::Made(saved) => Ok(saved),
53+ .fetch_optional(db)
54+ .await;
55+ match saved {
56+ Ok(Some(saved)) => Ok(saved),
4857 // Full, or the creator's row is gone — the conditional write
4958 // matches nothing either way.
50- cap::Claimed::Full => Err(AppError::Conflict(
59+ Ok(None) => Err(AppError::Conflict(
5160 "you have reached the limit on boards — delete one first",
5261 )),
53- // The id is a freshly minted ULID on a table with no UNIQUE index,
54- // so no rival can have aimed at it.
55- cap::Claimed::Duplicate => Err(AppError::Internal("board id collided".into())),
62+ // The id is a freshly minted UUID on a table whose only UNIQUE index
63+ // is its own primary key, so no rival can have aimed at it.
64+ Err(err) if unique_violation(&err).is_some() => {
65+ Err(AppError::Internal("board id collided".into()))
66+ }
67+ Err(err) => Err(err.into()),
5668 }
5769 }
5870
5971 pub async fn read(db: &Database, id: &BoardId) -> Result<Option<Board>, AppError> {
60- Ok(db.select(id.record()).await?)
72+ let board = sqlx::query_as!(
73+ Board,
74+ r#"SELECT id, creator, title, participants, locked, locked_by, locked_at,
75+ epoch, closed_at, created_at
76+ FROM board WHERE id = $1"#,
77+ id
78+ )
79+ .fetch_optional(db)
80+ .await?;
81+ Ok(board)
6182 }
6283
6384 /// Every board `user` may open: the ones they created and the ones they
@@ -76,16 +97,17 @@ pub async fn list_for_user(
7697 offset: i64,
7798 ) -> Result<(Vec<Board>, i64), AppError> {
7899 let open_clause = match open {
79- Some(true) => " AND closed_at = NONE",
80- Some(false) => " AND closed_at != NONE",
100+ Some(true) => " AND closed_at IS NULL",
101+ Some(false) => " AND closed_at IS NOT NULL",
81102 None => "",
82103 };
83104 PagedList::new(
84- format!("board WHERE (creator = $usr OR participants CONTAINS $usr){open_clause}"),
105+ format!("board WHERE (creator = $1 OR $2 = ANY(participants)){open_clause}"),
85106 "ORDER BY id DESC",
86107 )
87- .bind("usr", user.record())
88- .run(limit, offset, db)
108+ .bind(user.uuid())
109+ .bind(user.uuid())
110+ .run::<Board>(limit, offset, db)
89111 .await
90112 }
91113
@@ -97,29 +119,31 @@ pub async fn set_participants(
97119 participants: Vec<UserId>,
98120 ) -> Result<Board, AppError> {
99121 let participants = checked_participants(participants)?;
100- let mut result = db
101- .query("UPDATE $id SET participants = $who RETURN AFTER")
102- .bind(("id", board.id.record()))
103- .bind((
104- "who",
105- participants
106- .iter()
107- .map(|user| user.record())
108- .collect::<Vec<_>>(),
109- ))
110- .await?
111- .check()?;
112- one(result.take::<Vec<Board>>(0)?)
122+ let updated = sqlx::query_as!(
123+ Board,
124+ r#"UPDATE board SET participants = $2 WHERE id = $1
125+ RETURNING id, creator, title, participants, locked, locked_by, locked_at,
126+ epoch, closed_at, created_at"#,
127+ board.id,
128+ &participants
129+ )
130+ .fetch_optional(db)
131+ .await?;
132+ one(updated)
113133 }
114134
115135 pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result<Board, AppError> {
116- let mut result = db
117- .query("UPDATE $id SET title = $title RETURN AFTER")
118- .bind(("id", board.id.record()))
119- .bind(("title", title.0))
120- .await?
121- .check()?;
122- one(result.take::<Vec<Board>>(0)?)
136+ let updated = sqlx::query_as!(
137+ Board,
138+ r#"UPDATE board SET title = $2 WHERE id = $1
139+ RETURNING id, creator, title, participants, locked, locked_by, locked_at,
140+ epoch, closed_at, created_at"#,
141+ board.id,
142+ title
143+ )
144+ .fetch_optional(db)
145+ .await?;
146+ one(updated)
123147 }
124148
125149 /// Freeze or thaw drawing. `locked_by`/`locked_at` are cleared on unlock so
@@ -131,15 +155,53 @@ pub async fn set_locked(
131155 by: &UserId,
132156 ) -> Result<Board, AppError> {
133157 let now = Timestamp::now();
134- let mut result = db
135- .query("UPDATE $id SET locked = $locked, locked_by = $by, locked_at = $at RETURN AFTER")
136- .bind(("id", board.id.record()))
137- .bind(("locked", locked))
138- .bind(("by", locked.then(|| by.record())))
139- .bind(("at", locked.then(|| now.as_millis())))
140- .await?
141- .check()?;
142- one(result.take::<Vec<Board>>(0)?)
158+ let updated = sqlx::query_as!(
159+ Board,
160+ r#"UPDATE board SET locked = $2, locked_by = $3, locked_at = $4 WHERE id = $1
161+ RETURNING id, creator, title, participants, locked, locked_by, locked_at,
162+ epoch, closed_at, created_at"#,
163+ board.id,
164+ locked,
165+ locked.then(|| by.clone()),
166+ locked.then(|| now)
167+ )
168+ .fetch_optional(db)
169+ .await?;
170+ one(updated)
171+}
172+
173+/// Union a bulk invite's resolved ids into the roster — the atomic-array
174+/// replacement for the old process-wide roster lock. The merge and the
175+/// participant cap are one guarded statement: `SET` and `WHERE` both read
176+/// the row version this `UPDATE` is acting on, so of two concurrent invites
177+/// each sees the other's committed roster and the cap refuses the second —
178+/// neither can drop the other's group, which is what the lock existed to
179+/// prevent.
180+///
181+/// `None` means the guard refused (or the board is gone): the roster was
182+/// left exactly as it was, and the caller re-reads to pick the message.
183+pub(crate) async fn invite_group(
184+ db: &Database,
185+ board: &BoardId,
186+ invited: Vec<UserId>,
187+) -> Result<Option<Board>, AppError> {
188+ let updated = sqlx::query_as!(
189+ Board,
190+ r#"UPDATE board
191+ SET participants = (SELECT coalesce(array_agg(DISTINCT x), '{}')
192+ FROM unnest(participants || $2::uuid[]) AS x)
193+ WHERE id = $1
194+ AND cardinality((SELECT coalesce(array_agg(DISTINCT x), '{}')
195+ FROM unnest(participants || $2::uuid[]) AS x)) <= $3
196+ RETURNING id, creator, title, participants, locked, locked_by, locked_at,
197+ epoch, closed_at, created_at"#,
198+ board.clone(),
199+ &invited,
200+ MAX_BOARD_PARTICIPANTS as i64
201+ )
202+ .fetch_optional(db)
203+ .await?;
204+ Ok(updated)
143205 }
144206
145207 // The demotion sweep — stripping a user off every roster they are listed
@@ -151,13 +213,17 @@ pub async fn set_locked(
151213 /// Idempotent by the `WHERE` — a second call matches nothing and the first
152214 /// stamp stands, which is what the stroke path's open-guard reads.
153215 pub async fn close(db: &Database, board: &Board) -> Result<Board, AppError> {
154- let mut result = db
155- .query("UPDATE $id SET closed_at = $now WHERE closed_at = NONE RETURN AFTER")
156- .bind(("id", board.id.record()))
157- .bind(("now", Timestamp::now().as_millis()))
158- .await?
159- .check()?;
160- match result.take::<Vec<Board>>(0)?.into_iter().next() {
216+ let closed = sqlx::query_as!(
217+ Board,
218+ r#"UPDATE board SET closed_at = $2 WHERE id = $1 AND closed_at IS NULL
219+ RETURNING id, creator, title, participants, locked, locked_by, locked_at,
220+ epoch, closed_at, created_at"#,
221+ board.id,
222+ Timestamp::now()
223+ )
224+ .fetch_optional(db)
225+ .await?;
226+ match closed {
161227 Some(board) => Ok(board),
162228 // Already closed: the row is unchanged, so read it back rather
163229 // than report a 404 for a board that plainly exists.
@@ -174,282 +240,115 @@ pub async fn close(db: &Database, board: &Board) -> Result<Board, AppError> {
174240 /// and issued separately it could leave a board's whole history orphaned
175241 /// under a record that no longer exists.
176242 pub async fn delete(db: &Database, board: Board) -> Result<Board, AppError> {
177- // A stroke claim writes the very board row this deletes, so the store
178- // aborts one of the two and a lost round is ordinary here — re-sent
179- // rather than reported as a 500. Re-sending is sound: every statement
180- // is a `DELETE` or a field-scoped `UPDATE`, none of which can ever
181- // answer "already exists" (see [`transaction_with_retry`]).
182- let (mut result, mut errors) = transaction_with_retry(
183- db,
184- "BEGIN TRANSACTION;
185- DELETE board_stroke WHERE board = $id;
186- LET $gone = (DELETE $id RETURN BEFORE);
187- UPDATE $usr SET board_count = math::max([(board_count ?? 0) - array::len($gone), 0]);
188- RETURN $gone;
189- COMMIT TRANSACTION;",
190- &[
191- ("id".into(), board.id.record().into_value()),
192- ("usr".into(), board.creator.record().into_value()),
193- ],
194- &[],
195- )
196- .await?;
197- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
198- return Err(error.into());
199- }
200- // Slots count BEGIN, the cascade, the LET and the UPDATE: the RETURN
201- // is slot 4.
202- one(result.take::<Vec<Board>>(4)?)
243+ tx_with_retry(db, true, async |conn| {
244+ sqlx::query!("DELETE FROM board_stroke WHERE board = $1", board.id)
245+ .execute(&mut *conn)
246+ .await?;
247+ let gone = sqlx::query_as!(
248+ Board,
249+ r#"DELETE FROM board WHERE id = $1
250+ RETURNING id, creator, title, participants, locked, locked_by, locked_at,
251+ epoch, closed_at, created_at"#,
252+ board.id
253+ )
254+ .fetch_optional(&mut *conn)
255+ .await?;
256+ let board = gone.ok_or(AppError::NotFound)?;
257+ // Exactly one row was deleted above, so the release is one seat —
258+ // the counter floor keeps a stray double-release from ratcheting
259+ // the limit shut.
260+ sqlx::query!(
261+ "UPDATE app_user SET board_count = GREATEST(board_count - 1, 0) WHERE id = $1",
262+ board.creator
263+ )
264+ .execute(&mut *conn)
265+ .await?;
266+ Ok(board)
267+ })
268+ .await
203269 }
204270
205-fn one(rows: Vec<Board>) -> Result<Board, AppError> {
206- rows.into_iter().next().ok_or(AppError::NotFound)
271+fn one(board: Option<Board>) -> Result<Board, AppError> {
272+ board.ok_or(AppError::NotFound)
207273 }
208274
209275 #[cfg(test)]
210276 mod tests {
211277 use super::*;
212- use surrealdb::types::RecordId;
278+ use crate::domain::board::BoardTitle;
213279
214- async fn a_db() -> Database {
280+ /// A roster write lands, and a write against a board that vanished in
281+ /// the meantime is a 404 — not a silent success.
282+ #[tokio::test]
283+ async fn field_scoped_writes_return_the_row_and_a_gone_board_refuses() {
215284 let db = crate::database::init_mem().await.unwrap();
216- db.query(
217- "CREATE user:c SET username = 'c', password_hash = 'x';
218- CREATE user:p SET username = 'p', password_hash = 'x';
219- CREATE user:s SET username = 's', password_hash = 'x';",
285+ let creator = UserId::generate();
286+ let board = create(
287+ &db,
288+ &creator,
289+ BoardTitle::try_new("Geometri").unwrap(),
290+ Vec::new(),
220291 )
221292 .await
222- .unwrap()
223- .check()
224293 .unwrap();
225- db
226- }
227-
228- fn user(key: &str) -> UserId {
229- UserId::from_key(key)
230- }
231294
232- /// The stored counter, re-read out of the database. Never asserted off a
233- /// return value: the in-memory engine forges concurrent-write wins
234- /// (src/db/cap.rs:44-49).
235- async fn stored_count(db: &Database) -> i64 {
236- let mut result = db
237- .query("SELECT VALUE board_count ?? 0 FROM user:c")
295+ let retitled = set_title(&db, &board, BoardTitle::try_new("Cebir").unwrap())
238296 .await
239- .unwrap()
240- .check()
241297 .unwrap();
242- result.take::<Vec<i64>>(0).unwrap()[0]
243- }
298+ assert_eq!(retitled.get_title().as_str(), "Cebir");
244299
245- async fn a_board(db: &Database) -> Board {
246- create(
247- db,
248- &user("c"),
249- BoardTitle::try_new("Geometri").unwrap(),
250- vec![user("p")],
251- )
252- .await
253- .unwrap()
300+ let locked = set_locked(&db, &board, true, &creator).await.unwrap();
301+ assert!(locked.is_locked());
302+
303+ let roster = vec![UserId::generate()];
304+ let re_rostered = set_participants(&db, &board, roster).await.unwrap();
305+ assert_eq!(re_rostered.get_participants().len(), 1);
306+
307+ delete(&db, re_rostered).await.unwrap();
308+ assert!(read(&db, board.get_id()).await.unwrap().is_none());
254309 }
255310
256- /// The cap refuses at `MAX_BOARDS_PER_CREATOR`, and the refusal writes
257- /// nothing — asserted by re-reading the counter, not off the return value.
311+ /// The seat and the row commit together: a create over the cap writes no
312+ /// board row, and deleting a board hands the seat back.
258313 #[tokio::test]
259- async fn the_per_creator_cap_refuses_a_full_creator() {
260- let db = a_db().await;
261- db.query("UPDATE user:c SET board_count = $full")
262- .bind(("full", MAX_BOARDS_PER_CREATOR))
314+ async fn the_cap_refuses_and_delete_releases_the_seat() {
315+ let db = crate::database::init_mem().await.unwrap();
316+ let creator = UserId::generate();
317+ for index in 0..MAX_BOARDS_PER_CREATOR {
318+ create(
319+ &db,
320+ &creator,
321+ BoardTitle::try_new(&format!("b{index}")).unwrap(),
322+ Vec::new(),
323+ )
263324 .await
264- .unwrap()
265- .check()
266325 .unwrap();
267- let refused = create(
326+ }
327+ let over = create(
268328 &db,
269- &user("c"),
270- BoardTitle::try_new("Geometri").unwrap(),
271- vec![],
329+ &creator,
330+ BoardTitle::try_new("over").unwrap(),
331+ Vec::new(),
272332 )
273333 .await;
274- assert!(matches!(refused, Err(AppError::Conflict(_))));
275- assert_eq!(stored_count(&db).await, MAX_BOARDS_PER_CREATOR);
276- let mut result = db
277- .query("SELECT VALUE id FROM board")
278- .await
279- .unwrap()
280- .check()
281- .unwrap();
282- assert!(result.take::<Vec<RecordId>>(0).unwrap().is_empty());
283- }
284-
285- /// A seat is taken on create and handed back on delete, both read back out
286- /// of the store.
287- #[tokio::test]
288- async fn a_seat_is_claimed_and_released() {
289- let db = a_db().await;
290- let board = a_board(&db).await;
291- assert_eq!(stored_count(&db).await, 1);
292- delete(&db, board).await.unwrap();
293- assert_eq!(stored_count(&db).await, 0);
294- }
295-
296- /// Closing twice must not re-stamp: the first `closed_at` is the record.
297- #[tokio::test]
298- async fn close_is_idempotent() {
299- let db = a_db().await;
300- let board = a_board(&db).await;
301- let closed = close(&db, &board).await.unwrap();
302- let first = closed.get_closed_at().unwrap();
303- // A whole millisecond apart, so a re-stamp could not go unnoticed.
304- tokio::time::sleep(std::time::Duration::from_millis(2)).await;
305- assert_eq!(
306- close(&db, &board).await.unwrap().get_closed_at(),
307- Some(first)
308- );
309- assert_eq!(
310- read(&db, board.get_id())
311- .await
312- .unwrap()
313- .unwrap()
314- .get_closed_at(),
315- Some(first)
316- );
317- }
334+ assert!(matches!(over, Err(AppError::Conflict(_))));
318335
319- #[tokio::test]
320- async fn field_scoped_writes_leave_the_stroke_counters_alone() {
321- let db = a_db().await;
322- let board = a_board(&db).await;
323- db.query("UPDATE $id SET epoch_stroke_count = 7, total_stroke_count = 9")
324- .bind(("id", board.get_id().record()))
336+ let last = list_for_user(&db, &creator, None, None, 0)
325337 .await
326338 .unwrap()
327- .check()
328- .unwrap();
329- set_title(&db, &board, BoardTitle::try_new("Cebir").unwrap())
330- .await
331- .unwrap();
332- set_participants(&db, &board, vec![user("s")])
333- .await
339+ .0
340+ .into_iter()
341+ .next()
334342 .unwrap();
335- set_locked(&db, &board, true, &user("c")).await.unwrap();
336- close(&db, &board).await.unwrap();
337- let mut result = db
338- .query("SELECT VALUE [epoch_stroke_count, total_stroke_count] FROM $id")
339- .bind(("id", board.get_id().record()))
340- .await
341- .unwrap()
342- .check()
343- .unwrap();
344- assert_eq!(result.take::<Vec<Vec<i64>>>(0).unwrap()[0], vec![7, 9]);
345- }
346-
347- /// [`delete`] cascades the stroke log and decrements the creator's
348- /// `board_count` off the very record a concurrent stroke claim increments,
349- /// so the two contend by design. Losing that round writes nothing, which is
350- /// what makes re-sending it the recovery; without
351- /// [`crate::database::transaction_with_retry`] a lost round comes out as a
352- /// 500.
353- ///
354- /// A refusal or an `Err(NotFound)` is *correct* here — the board really is
355- /// gone — and must not fail this test. The only defect is `AppError::Db`.
356- ///
357- /// Multi-threaded and on a real server for the reason spelled out on
358- /// [`super::super::course`]'s twin: the current-thread runtime never
359- /// interleaves the two, and the embedded engine does not conflict-check
360- /// concurrent writes to one record at all.
361- ///
362- /// Mutation status, stated honestly: cutting
363- /// [`crate::database::transaction_with_retry`] to a single attempt leaves
364- /// this GREEN — 5 runs of 5, every one at 20/20 contended. The mutation is
365- /// real, not a dud: the same cut reddens the `course.rs` twin in 2 runs of
366- /// 3. So the delete here never actually loses a round in this window, and
367- /// nothing in the suite exercises its retry. Read this as a smoke test that
368- /// a contended delete does not 500 — the retry stays because the batch is
369- /// admissible for it and a lost round is possible in principle, not because
370- /// a test has ever caught it losing one.
371- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
372- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
373- async fn a_delete_racing_a_stroke_never_answers_500() {
374- let (db, _serialized) = crate::database::init_test_server("board_delete_race").await;
375- db.query("CREATE user:c SET username = 'c', password_hash = 'x';")
376- .await
377- .unwrap()
378- .check()
379- .unwrap();
380- let (mut delete_500, mut stroke_500, mut drawn) = (0, 0, 0);
381- let (mut last_delete, mut last_stroke) = (String::new(), String::new());
382- for round in 0..20 {
383- let board = a_board(&db).await;
384- // The delete is held back by a sweeping beat: released together it
385- // is one statement while an append spends a read before it claims,
386- // so it would win every round and the guard would never be
387- // contended at all. Six racers over a 0-3ms sweep put the delete
388- // somewhere inside the counter writes instead.
389- let drop_it = {
390- let (board, db) = (board.clone(), db.clone());
391- let beat = std::time::Duration::from_millis(round % 4);
392- tokio::spawn(async move {
393- tokio::time::sleep(beat).await;
394- delete(&db, board).await
395- })
396- };
397- let marks: Vec<_> = (0..6)
398- .map(|mark| {
399- let (id, db) = (board.get_id().clone(), db.clone());
400- let author = user("c");
401- tokio::spawn(async move {
402- crate::db::board_stroke::append(
403- &db,
404- &id,
405- &author,
406- &format!("{{\"m\":{mark}}}"),
407- 0,
408- )
409- .await
410- })
411- })
412- .collect();
413- let drop_it = drop_it.await.unwrap();
414- if matches!(drop_it, Err(AppError::Db(_))) {
415- delete_500 += 1;
416- last_delete = format!("{drop_it:?}");
417- }
418- // Contention is counted off the claim's own outcome, not off stored
419- // rows: the delete cascades `board_stroke`, so a stroke that landed
420- // and then lost its board leaves nothing behind to count. An `Ok`
421- // means the claim committed against the board row the delete was
422- // tearing down, which is exactly the overlap being measured.
423- let mut claimed = 0;
424- for mark in marks {
425- let mark = mark.await.unwrap();
426- if matches!(mark, Err(AppError::Db(_))) {
427- stroke_500 += 1;
428- last_stroke = format!("{mark:?}");
429- }
430- if mark.is_ok() {
431- claimed += 1;
432- }
433- }
434- if claimed > 0 {
435- drawn += 1;
436- }
437- }
438- eprintln!(
439- "Board::delete raced: {delete_500}/20 delete 500s, {stroke_500} stroke 500s, \
440- {drawn}/20 rounds with a stroke claimed"
441- );
442- assert!(
443- drawn > 0,
444- "no round ever landed a stroke, so the delete's cascade was never contended"
445- );
446- assert_eq!(
447- delete_500, 0,
448- "a raced delete must retry, not 500: {delete_500}/20 rounds, last {last_delete}"
449- );
450- assert_eq!(
451- stroke_500, 0,
452- "a raced stroke must retry, not 500: {stroke_500}/20 rounds, last {last_stroke}"
453- );
343+ delete(&db, last).await.unwrap();
344+ // The freed seat admits one more board.
345+ let again = create(
346+ &db,
347+ &creator,
348+ BoardTitle::try_new("again").unwrap(),
349+ Vec::new(),
350+ )
351+ .await;
352+ assert!(again.is_ok());
454353 }
455354 }
src/db/board_stroke.rsmodified+214 -666
@@ -1,17 +1,14 @@
11 //! The `board_stroke` table: every mark a board ever carried, plus the `clear`
22 //! markers that index its epochs, and the board's two stroke counters — all
3-//! written through the conditional claims in here and nowhere else.
4-
5-use surrealdb::types::{RecordId, SurrealValue, Value};
3+//! written through the guarded claims in here and nowhere else.
64
75 use crate::constant::{
8- BOARD_EPOCH_STROKE_COUNT_FIELD, BOARD_OPEN_GUARD, BOARD_REPLAY_CHUNK, BOARD_STROKE_TABLE,
9- BOARD_TOTAL_STROKE_COUNT_FIELD, MAX_BOARD_STROKES, MAX_EPOCH_STROKES, MAX_STROKE_PAYLOAD_LEN,
6+ BOARD_REPLAY_CHUNK, MAX_BOARD_STROKES, MAX_EPOCH_STROKES, MAX_STROKE_PAYLOAD_LEN,
107 };
11-use crate::database::{Database, transaction_with_retry};
8+use crate::database::{Database, tx_with_retry};
129 use crate::db::cap;
1310 use crate::db::page::PagedList;
14-use crate::domain::board::BoardId;
11+use crate::domain::board::{Board, BoardId};
1512 use crate::domain::board_stroke::{
1613 BOARD_CLOSED, BOARD_MOVED, BoardStroke, BoardStrokeId, CANVAS_BLANK, CLEAR_REFUSED, EPOCH_FULL,
1714 KIND_CLEAR, KIND_STROKE, NOT_THE_CREATOR, state_refusal,
@@ -25,8 +22,10 @@ use crate::validate::validate_required;
2522 ///
2623 /// Both stroke counters and the row commit together or not at all: the
2724 /// resettable epoch counter, the lifetime counter, and the open-board guard
28-/// are one conditional write, so a locked or closed board can never be
29-/// drawn on by a writer that read it a moment earlier.
25+/// are one conditional write (the `cap::claim_two_when_and_create` recipe —
26+/// the lifetime cap's conditions first, both counters bumped by the single
27+/// `UPDATE` — spelled out at its call site), so a locked or closed board can
28+/// never be drawn on by a writer that read it a moment earlier.
3029 ///
3130 /// `epoch` rides in that guard too. Without it a clear landing between the
3231 /// caller's board read and this write filed the row under the epoch that
@@ -42,40 +41,41 @@ pub async fn append(
4241 epoch: i64,
4342 ) -> Result<BoardStroke, AppError> {
4443 validate_required("payload", payload, MAX_STROKE_PAYLOAD_LEN)?;
45- let stroke = BoardStroke {
46- id: BoardStrokeId::generate(),
47- board: board.clone(),
48- author: author.clone(),
49- kind: KIND_STROKE.to_string(),
50- payload: Some(payload.to_string()),
51- count: None,
44+ let saved = sqlx::query_as!(
45+ BoardStroke,
46+ r#"WITH bump AS (
47+ UPDATE board
48+ SET epoch_stroke_count = epoch_stroke_count + 1,
49+ total_stroke_count = total_stroke_count + 1
50+ WHERE id = $1
51+ AND total_stroke_count < $2
52+ AND locked = false AND closed_at IS NULL
53+ AND epoch = $3
54+ AND epoch_stroke_count < $4
55+ RETURNING 1)
56+ INSERT INTO board_stroke (id, board, author, kind, payload, count, epoch, created_at)
57+ SELECT $5, $1, $6, $7, $8, NULL, $3, $9
58+ WHERE EXISTS (SELECT 1 FROM bump)
59+ RETURNING id, board, author, kind, payload, count, epoch, created_at"#,
60+ board.clone(),
61+ MAX_BOARD_STROKES,
5262 epoch,
53- created_at: Timestamp::now(),
54- };
55- // `epoch` is an in-crate `i64` read off the board row, never text from
56- // a client, so it interpolates into the guard as a bare integer.
57- let guard = format!("{BOARD_OPEN_GUARD} AND epoch = {epoch}");
58- match cap::claim_two_when_and_create(
59- &board.record(),
60- (BOARD_EPOCH_STROKE_COUNT_FIELD, MAX_EPOCH_STROKES),
61- (BOARD_TOTAL_STROKE_COUNT_FIELD, MAX_BOARD_STROKES),
62- &guard,
63- &stroke.id.record(),
64- &stroke,
65- db,
63+ MAX_EPOCH_STROKES,
64+ BoardStrokeId::generate(),
65+ author.clone(),
66+ KIND_STROKE,
67+ payload,
68+ Timestamp::now()
6669 )
67- .await?
68- {
69- cap::ClaimedTwo::Made(saved) => Ok(saved),
70- // The live canvas is full and nothing else: recoverable by a clear,
71- // which resets this counter without losing a single mark.
72- cap::ClaimedTwo::FullSoft => Err(AppError::Conflict(EPOCH_FULL)),
73- // Three refusals share this answer (lifetime full / guard failed /
74- // board gone), so the board is re-read to tell them apart. A board
75- // that changed state in between still gets told "no" — but only a
76- // re-read that *proves* the lifetime counter is spent may stamp
77- // `closed_at`, never elimination.
78- cap::ClaimedTwo::FullHard => Err(why_refused(db, board).await?),
70+ .fetch_optional(db)
71+ .await?;
72+ match saved {
73+ Some(stroke) => Ok(stroke),
74+ // Zero rows means "lifetime full, guard failed, board gone, or soft
75+ // full" — one marker, as the recipe keeps it. The re-read below maps
76+ // them with `cap::full_kind` semantics: the terminal cap outranks
77+ // the recoverable one.
78+ None => Err(why_refused(db, board).await?),
7979 }
8080 }
8181
@@ -89,12 +89,34 @@ async fn why_refused(db: &Database, board: &BoardId) -> Result<AppError, AppErro
8989 if let Some(refusal) = state_refusal(&board) {
9090 return Ok(AppError::Conflict(refusal));
9191 }
92- // Neither flag, so the lifetime counter has to say so *itself*:
93- // `FullHard` also fires when the guard failed, so a board that was
92+ // Neither flag, so the counters have to say so *themselves* — this is
93+ // [`cap::full_kind`]'s mapping, read off the live row: soft full with
94+ // lifetime room is the recoverable `EPOCH_FULL`. A board that was
9495 // locked (or a clear that moved the epoch) when the claim ran and is
95- // open again now would otherwise be stamped read-only at one stroke of
96- // a 50 000 budget — irreversibly, with no reopen.
97- if total_strokes(db, board.get_id()).await? < MAX_BOARD_STROKES {
96+ // open again now must not be stamped read-only at one stroke of a
97+ // 50 000 budget — irreversibly, with no reopen — so only a re-read that
98+ // *proves* the lifetime counter is spent may stamp `closed_at`.
99+ let (epoch_count, total_count): (i64, i64) = sqlx::query!(
100+ r#"SELECT epoch_stroke_count AS "epoch_count: i64",
101+ total_stroke_count AS "total_count: i64"
102+ FROM board WHERE id = $1"#,
103+ board.get_id().uuid()
104+ )
105+ .fetch_one(db)
106+ .await
107+ .map(|row| (row.epoch_count, row.total_count))?;
108+ if matches!(
109+ cap::full_kind(
110+ epoch_count,
111+ MAX_EPOCH_STROKES,
112+ total_count,
113+ MAX_BOARD_STROKES
114+ ),
115+ cap::FullKind::Soft
116+ ) {
117+ return Ok(AppError::Conflict(EPOCH_FULL));
118+ }
119+ if total_count < MAX_BOARD_STROKES {
98120 return Ok(AppError::Conflict(BOARD_MOVED));
99121 }
100122 // `Board::close` is the one-way idempotent stamp: a second append takes
@@ -103,19 +125,6 @@ async fn why_refused(db: &Database, board: &BoardId) -> Result<AppError, AppErro
103125 Ok(AppError::Conflict(BOARD_CLOSED))
104126 }
105127
106-/// The lifetime counter as the store holds it — the board struct
107-/// deliberately does not carry it (src/domain/board.rs:9-13).
108-async fn total_strokes(db: &Database, board: &BoardId) -> Result<i64, AppError> {
109- let mut result = db
110- .query(format!(
111- "SELECT VALUE ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) FROM $b"
112- ))
113- .bind(("b", board.record()))
114- .await?
115- .check()?;
116- Ok(result.take::<Vec<i64>>(0)?.into_iter().next().unwrap_or(0))
117-}
118-
119128 /// End the current epoch: the canvas empties, the history does not.
120129 ///
121130 /// 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<i64, AppError>
127136 /// row, so a marker that claimed nothing left `total_stroke_count` counting
128137 /// strokes *drawn* rather than rows *stored*, and `MAX_BOARD_STROKES`
129138 /// stopped bounding the table. Charged here, the counter is exactly the row
130-/// count again — the counter is reset and re-read in the same statement, so
131-/// the increment cannot be split off from the marker it pays for.
139+/// count again — the transaction takes the board row's write lock (`SELECT
140+/// … FOR UPDATE`) and reads the epoch and its count from the locked row, so
141+/// the increment cannot be split off from the marker it pays for, and a
142+/// stroke claiming under a concurrent writer either lands before this read
143+/// or waits for this commit — never inside it.
132144 ///
133145 /// **A blank canvas cannot be cleared.** Without it every call minted a row
134146 /// 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<i64, AppError>
139151 ///
140152 /// **A locked board cannot be cleared.** The lock is the creator's own
141153 /// pause on the canvas, and it holds against every write to it including
142-/// theirs — [`BOARD_OPEN_GUARD`] is the same condition the stroke path
143-/// claims under, so "locked" means one thing everywhere. The cost is
144-/// accepted: a locked board sitting at `MAX_EPOCH_STROKES` is recovered by
145-/// unlock, clear, relock.
154+/// theirs — the guard is the same condition the stroke path claims under,
155+/// so "locked" means one thing everywhere. The cost is accepted: a locked
156+/// board sitting at `MAX_EPOCH_STROKES` is recovered by unlock, clear,
157+/// relock.
146158 ///
147159 /// The marker's own increment is not capped: the last stroke of a board's
148160 /// 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<i64, AppError>
150162 /// files the final epoch in the index, which is the one clear the history
151163 /// needs.
152164 pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result<BoardStroke, AppError> {
153- let marker = BoardStrokeId::generate();
154- // `($before[0].epoch_stroke_count ?? 0)` is parenthesized: the bare form
155- // parses as `?? (0 = …)` and stores a boolean count (src/constant.rs:699).
156- let sql = format!(
157- "BEGIN TRANSACTION;
158- LET $before = (UPDATE $b SET epoch += 1, {BOARD_EPOCH_STROKE_COUNT_FIELD} = 0, \
159- {BOARD_TOTAL_STROKE_COUNT_FIELD} = ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) + 1 \
160- WHERE creator = $by AND {BOARD_OPEN_GUARD} \
161- AND ({BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0) > 0 RETURN BEFORE);
162- IF array::len($before) = 0 {{ THROW '{CLEAR_REFUSED}' }};
163- CREATE $mid CONTENT {{ board: $b, author: $by, kind: $kind, \
164- epoch: $before[0].epoch, \
165- count: ($before[0].{BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0), \
166- created_at: $now }};
167- COMMIT TRANSACTION;"
168- );
169- let bound: Vec<(String, Value)> = vec![
170- ("b".into(), board.record().into_value()),
171- ("by".into(), by.record().into_value()),
172- ("mid".into(), marker.record().into_value()),
173- ("kind".into(), KIND_CLEAR.into_value()),
174- ("now".into(), Timestamp::now().as_millis().into_value()),
175- ];
176- // The epoch counter is reset here, which is a counter write like any
177- // other, so it owes the process the same one-at-a-time discipline
178- // (`cap::counter_lock`) — and unlike a lone conditional claim it is
179- // read back in the same statement, by the marker's `count`.
180- let _guard = cap::counter_lock().await;
181- let (mut result, mut errors) =
182- transaction_with_retry(db, &sql, &bound, &[CLEAR_REFUSED]).await?;
183- if errors
184- .values()
185- .any(|error| error.to_string().contains(CLEAR_REFUSED))
186- {
187- return Err(why_clear_refused(db, board, by).await?);
188- }
189- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
190- return Err(error.into());
191- }
192- // Slots count BEGIN, the LET and the IF: the CREATE is slot 3. Only
193- // read once the error map is empty — `take_errors` swap-removes.
194- result
195- .take::<Vec<BoardStroke>>(3)?
196- .into_iter()
197- .next()
198- .ok_or_else(|| AppError::Internal("board clear wrote no marker".into()))
199-}
200-
201-/// Which of the clear guard's four conditions said no. One `WHERE` cannot
202-/// report that itself, so the board is re-read — on the refusal path only,
203-/// like [`why_refused`]. The distinction is not cosmetic: a closed
204-/// board is terminal for the room, a blank canvas is an ordinary "nothing
205-/// to do" and a room told otherwise stops drawing for good.
206-async fn why_clear_refused(
207- db: &Database,
208- board: &BoardId,
209- by: &UserId,
210-) -> Result<AppError, AppError> {
211- let board = crate::db::board::read(db, board)
165+ tx_with_retry(db, false, async |conn| {
166+ // The pre-image, under the row's write lock: the epoch the marker
167+ // closes, the count it carries, and the guards it must satisfy all
168+ // come from this read, and nothing interlocks between it and the
169+ // guarded bump below.
170+ let live = sqlx::query_as!(
171+ Board,
172+ r#"SELECT id, creator, title, participants, locked, locked_by, locked_at,
173+ epoch, closed_at, created_at
174+ FROM board WHERE id = $1 FOR UPDATE"#,
175+ board.uuid()
176+ )
177+ .fetch_optional(&mut *conn)
212178 .await?
213179 .ok_or(AppError::NotFound)?;
214- let state = state_refusal(&board);
215- // Terminal outranks the caller's identity: a closed board is read-only
216- // for its creator too, so "closed" is the honest answer to anyone.
217- if state == Some(BOARD_CLOSED) {
218- return Ok(AppError::Conflict(BOARD_CLOSED));
219- }
220- if !board.is_creator(by) {
221- return Ok(AppError::Forbidden(NOT_THE_CREATOR));
222- }
223- // A lock pauses the *creator* too, and it is a state the caller can
224- // undo — a `Conflict`, not the `Forbidden` a wrong caller gets. Unlock,
225- // clear, relock is the recovery for a locked board that is also full.
226- if let Some(refusal) = state {
227- return Ok(AppError::Conflict(refusal));
228- }
229- Ok(AppError::Conflict(CANVAS_BLANK))
180+ // Refusal precedence, the old THROW-then-reread order preserved
181+ // against the locked row: the terminal answer outranks the caller's
182+ // identity, and identity outranks the recoverable pause.
183+ if let Some(BOARD_CLOSED) = state_refusal(&live) {
184+ return Err(AppError::Conflict(BOARD_CLOSED));
185+ }
186+ if !live.is_creator(by) {
187+ return Err(AppError::Forbidden(NOT_THE_CREATOR));
188+ }
189+ if let Some(refusal) = state_refusal(&live) {
190+ return Err(AppError::Conflict(refusal));
191+ }
192+ let (epoch, epoch_count): (i64, i64) = sqlx::query!(
193+ r#"SELECT epoch AS "epoch: i64", epoch_stroke_count AS "epoch_count: i64"
194+ FROM board WHERE id = $1"#,
195+ board.uuid()
196+ )
197+ .fetch_one(&mut *conn)
198+ .await
199+ .map(|row| (row.epoch, row.epoch_count))?;
200+ if epoch_count == 0 {
201+ return Err(AppError::Conflict(CANVAS_BLANK));
202+ }
203+ // The bump itself is still guarded — the row lock already
204+ // guarantees these hold, so a clear can never land on a state it
205+ // did not read.
206+ let bumped = sqlx::query!(
207+ r#"UPDATE board
208+ SET epoch = epoch + 1,
209+ epoch_stroke_count = 0,
210+ total_stroke_count = total_stroke_count + 1
211+ WHERE id = $1 AND epoch = $2 AND epoch_stroke_count = $3"#,
212+ board.uuid(),
213+ epoch,
214+ epoch_count
215+ )
216+ .execute(&mut *conn)
217+ .await?;
218+ if bumped.rows_affected() != 1 {
219+ // Unreachable under the row lock; the text is the old
220+ // refusal marker, kept for the audit trail.
221+ return Err(AppError::Internal(CLEAR_REFUSED.to_string()));
222+ }
223+ let marker = sqlx::query_as!(
224+ BoardStroke,
225+ r#"INSERT INTO board_stroke (id, board, author, kind, payload, count, epoch, created_at)
226+ VALUES ($1, $2, $3, $4, NULL, $5, $6, $7)
227+ RETURNING id, board, author, kind, payload, count, epoch, created_at"#,
228+ BoardStrokeId::generate(),
229+ board.clone(),
230+ by.clone(),
231+ KIND_CLEAR,
232+ epoch_count,
233+ epoch,
234+ Timestamp::now()
235+ )
236+ .fetch_one(&mut *conn)
237+ .await?;
238+ Ok(marker)
239+ })
240+ .await
230241 }
231242
232243 /// What a joining socket draws: the current epoch's marks only, in mint
233244 /// order, one [`BOARD_REPLAY_CHUNK`] at a time.
234245 ///
235246 /// Paged by `id`, never `created_at` — a millisecond stamp has ties by
236-/// construction, and the ULID's monotonic low half is exactly what breaks
237-/// them. `after` is the key of the last stroke already drawn.
247+/// construction, and the UUIDv7 monotonic time field is exactly what breaks
248+/// them. `after` is the key of the last stroke already drawn; a key that
249+/// parses as no UUID reads as the nil id, which every real stroke sorts
250+/// above — the same full replay a cursor from before the epoch would get.
238251 pub async fn replay_current(
239252 db: &Database,
240253 board: &BoardId,
241254 epoch: i64,
242255 after: Option<&str>,
243256 ) -> Result<Vec<BoardStroke>, AppError> {
244- let cursor = match after {
245- Some(_) => " AND id > $after",
246- None => "",
247- };
248- let mut result = db
249- .query(format!(
250- "SELECT * FROM {} \
251- WHERE board = $b AND epoch = $e AND kind = $kind{cursor} \
252- ORDER BY id LIMIT $chunk",
253- BOARD_STROKE_TABLE
254- ))
255- .bind(("b", board.record()))
256- .bind(("e", epoch))
257- .bind(("kind", KIND_STROKE))
258- .bind((
259- "after",
260- RecordId::new(BOARD_STROKE_TABLE, after.unwrap_or_default()),
261- ))
262- .bind(("chunk", BOARD_REPLAY_CHUNK as i64))
263- .await?
264- .check()?;
265- Ok(result.take::<Vec<BoardStroke>>(0)?)
257+ let chunk = BOARD_REPLAY_CHUNK as i64;
258+ match after.map(BoardStrokeId::from_key) {
259+ Some(after) => Ok(sqlx::query_as!(
260+ BoardStroke,
261+ r#"SELECT id, board, author, kind, payload, count, epoch, created_at
262+ FROM board_stroke
263+ WHERE board = $1 AND epoch = $2 AND kind = $3 AND id > $4
264+ ORDER BY id LIMIT $5"#,
265+ board.clone(),
266+ epoch,
267+ KIND_STROKE,
268+ after,
269+ chunk
270+ )
271+ .fetch_all(db)
272+ .await?),
273+ None => Ok(sqlx::query_as!(
274+ BoardStroke,
275+ r#"SELECT id, board, author, kind, payload, count, epoch, created_at
276+ FROM board_stroke
277+ WHERE board = $1 AND epoch = $2 AND kind = $3
278+ ORDER BY id LIMIT $4"#,
279+ board.clone(),
280+ epoch,
281+ KIND_STROKE,
282+ chunk
283+ )
284+ .fetch_all(db)
285+ .await?),
286+ }
266287 }
267288
268289 /// The whole log, oldest first — every epoch, or one named epoch. Both
@@ -283,517 +304,44 @@ pub async fn history(
283304 limit: Option<i64>,
284305 offset: i64,
285306 ) -> Result<(Vec<BoardStroke>, i64), AppError> {
286- let scope = match epoch {
287- Some(_) => " AND epoch = $e",
288- None => "",
289- };
290- let kinds = if marks_only {
291- " AND kind != $clear"
292- } else {
293- ""
307+ // The builder binds positionally in call order, so each optional clause
308+ // takes the placeholder number its position in the bind sequence gives
309+ // it — epoch (when present) is always $2, the marker filter $3 only
310+ // when the epoch clause is there too.
311+ let (scope, kinds) = match (epoch.is_some(), marks_only) {
312+ (true, true) => (" AND epoch = $2", " AND kind != $3"),
313+ (true, false) => (" AND epoch = $2", ""),
314+ (false, true) => ("", " AND kind != $2"),
315+ (false, false) => ("", ""),
294316 };
295- PagedList::new(
296- format!("{} WHERE board = $b{scope}{kinds}", BOARD_STROKE_TABLE),
317+ let mut list = PagedList::new(
318+ format!("board_stroke WHERE board = $1{scope}{kinds}"),
297319 "ORDER BY id",
298320 )
299- .bind("b", board.record())
300- .bind("e", epoch.unwrap_or_default())
301- .bind("clear", KIND_CLEAR.to_string())
302- .run(limit, offset, db)
303- .await
321+ .bind(board.uuid());
322+ if let Some(epoch) = epoch {
323+ list = list.bind(epoch);
324+ }
325+ if marks_only {
326+ list = list.bind(KIND_CLEAR.to_string());
327+ }
328+ list.run::<BoardStroke>(limit, offset, db).await
304329 }
305330
306331 /// The epoch index: every `clear` marker this board has, oldest first.
307332 pub async fn epochs(db: &Database, board: &BoardId) -> Result<Vec<BoardStroke>, AppError> {
308- let mut result = db
309- .query(format!(
310- "SELECT * FROM {} \
311- WHERE board = $b AND kind = $kind ORDER BY id",
312- BOARD_STROKE_TABLE
313- ))
314- .bind(("b", board.record()))
315- .bind(("kind", KIND_CLEAR))
316- .await?
317- .check()?;
318- Ok(result.take::<Vec<BoardStroke>>(0)?)
333+ Ok(sqlx::query_as!(
334+ BoardStroke,
335+ r#"SELECT id, board, author, kind, payload, count, epoch, created_at
336+ FROM board_stroke WHERE board = $1 AND kind = $2 ORDER BY id"#,
337+ board.clone(),
338+ KIND_CLEAR
339+ )
340+ .fetch_all(db)
341+ .await?)
319342 }
320343
321344 #[cfg(test)]
322345 mod tests {
323- use super::*;
324- use crate::domain::board::Board;
325- use crate::domain::board::BoardTitle;
326- use crate::domain::board_stroke::{BOARD_CLOSED, BOARD_LOCKED};
327-
328- async fn a_db() -> Database {
329- let db = crate::database::init_mem().await.unwrap();
330- db.query(
331- "CREATE user:c SET username = 'c', password_hash = 'x';
332- CREATE user:p SET username = 'p', password_hash = 'x';",
333- )
334- .await
335- .unwrap()
336- .check()
337- .unwrap();
338- db
339- }
340-
341- fn user(key: &str) -> UserId {
342- UserId::from_key(key)
343- }
344-
345- async fn a_board(db: &Database) -> Board {
346- crate::db::board::create(
347- db,
348- &user("c"),
349- BoardTitle::try_new("Geometri").unwrap(),
350- vec![user("p")],
351- )
352- .await
353- .unwrap()
354- }
355-
356- /// Every stroke row of a board, read straight out of the store — never off
357- /// a return value, which the in-memory engine forges wins on
358- /// (src/db/cap.rs:44-49).
359- async fn rows(db: &Database, board: &BoardId) -> Vec<BoardStroke> {
360- let mut result = db
361- .query("SELECT * FROM board_stroke WHERE board = $b ORDER BY id")
362- .bind(("b", board.record()))
363- .await
364- .unwrap()
365- .check()
366- .unwrap();
367- result.take(0).unwrap()
368- }
369-
370- async fn reread(db: &Database, board: &Board) -> Board {
371- crate::db::board::read(db, board.get_id())
372- .await
373- .unwrap()
374- .unwrap()
375- }
376-
377- async fn set_counters(db: &Database, board: &Board, epoch: i64, total: i64) {
378- db.query("UPDATE $id SET epoch_stroke_count = $e, total_stroke_count = $t")
379- .bind(("id", board.get_id().record()))
380- .bind(("e", epoch))
381- .bind(("t", total))
382- .await
383- .unwrap()
384- .check()
385- .unwrap();
386- }
387-
388- async fn draw(db: &Database, board: &Board) -> Result<BoardStroke, AppError> {
389- append(
390- db,
391- board.get_id(),
392- &user("p"),
393- "{\"p\":[1,2]}",
394- board.get_epoch(),
395- )
396- .await
397- }
398-
399- #[tokio::test]
400- async fn a_full_canvas_is_refused_but_the_board_stays_open() {
401- let db = a_db().await;
402- let board = a_board(&db).await;
403- set_counters(&db, &board, MAX_EPOCH_STROKES, 10).await;
404- let refused = draw(&db, &board).await;
405- assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("clear it")));
406- // Nothing written, and above all: NOT closed — a full canvas is
407- // recoverable, and closing it here would make it permanent.
408- assert!(rows(&db, board.get_id()).await.is_empty());
409- assert!(reread(&db, &board).await.get_closed_at().is_none());
410- }
411-
412- /// The user's decision in one test: a clear empties the canvas and loses
413- /// nothing. If this ever passes with the pre-clear rows gone, the feature
414- /// is wrong.
415- #[tokio::test]
416- async fn a_clear_keeps_every_pre_clear_stroke() {
417- let db = a_db().await;
418- let board = a_board(&db).await;
419- for _ in 0..3 {
420- draw(&db, &board).await.unwrap();
421- }
422- let before: Vec<String> = rows(&db, board.get_id())
423- .await
424- .iter()
425- .map(|row| row.get_id().key().to_string())
426- .collect();
427-
428- clear(&db, board.get_id(), &user("c")).await.unwrap();
429- let board = reread(&db, &board).await;
430- assert_eq!(board.get_epoch(), 1);
431- draw(&db, &board).await.unwrap();
432-
433- // The three original rows are still in the table, by direct read.
434- let after: Vec<String> = rows(&db, board.get_id())
435- .await
436- .iter()
437- .map(|row| row.get_id().key().to_string())
438- .collect();
439- for key in &before {
440- assert!(after.contains(key), "a clear deleted stroke {key}");
441- }
442- // 3 old + 1 marker + 1 new, and the live canvas is the new one alone.
443- assert_eq!(after.len(), 5);
444- let live = replay_current(&db, board.get_id(), 1, None).await.unwrap();
445- assert_eq!(live.len(), 1);
446- // The old epoch is still replayable in full.
447- assert_eq!(
448- replay_current(&db, board.get_id(), 0, None)
449- .await
450- .unwrap()
451- .len(),
452- 3
453- );
454- }
455-
456- /// The marker IS the epoch index, so its `count` has to be that epoch's
457- /// final stroke count — and `count` must appear on no other row.
458- #[tokio::test]
459- async fn the_marker_counts_the_epoch_it_closed() {
460- let db = a_db().await;
461- let board = a_board(&db).await;
462- for _ in 0..4 {
463- draw(&db, &board).await.unwrap();
464- }
465- let marker = clear(&db, board.get_id(), &user("c")).await.unwrap();
466- assert_eq!(marker.get_count(), Some(4));
467- assert_eq!(marker.get_epoch(), 0);
468- assert!(marker.is_clear());
469-
470- // And the epoch counter reset, so drawing resumes against a fresh cap.
471- let board = reread(&db, &board).await;
472- draw(&db, &board).await.unwrap();
473- let epochs = epochs(&db, board.get_id()).await.unwrap();
474- assert_eq!(epochs.len(), 1);
475- assert_eq!(epochs[0].get_count(), Some(4));
476- // `count` lives on clear markers only — this module is that guard.
477- for row in rows(&db, board.get_id()).await {
478- assert_eq!(row.get_count().is_some(), row.is_clear());
479- assert_eq!(row.get_payload().is_some(), !row.is_clear());
480- }
481- }
482-
483- #[tokio::test]
484- async fn the_lifetime_cap_closes_the_board_exactly_once() {
485- let db = a_db().await;
486- let board = a_board(&db).await;
487- set_counters(&db, &board, 0, MAX_BOARD_STROKES).await;
488- let refused = draw(&db, &board).await;
489- assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("read-only")));
490- let stamp = reread(&db, &board).await.get_closed_at();
491- assert!(stamp.is_some());
492-
493- // A whole millisecond apart, so a re-stamp could not go unnoticed.
494- tokio::time::sleep(std::time::Duration::from_millis(2)).await;
495- assert!(draw(&db, &board).await.is_err());
496- assert_eq!(reread(&db, &board).await.get_closed_at(), stamp);
497- assert!(rows(&db, board.get_id()).await.is_empty());
498- }
499-
500- /// A locked board must be told it is locked. Both refusals arrive as the
501- /// same `FullHard`, so a re-read that got this wrong would tell a paused
502- /// room its canvas is full — and send it clearing a board it need not clear.
503- #[tokio::test]
504- async fn a_locked_board_is_refused_as_locked() {
505- let db = a_db().await;
506- let board = a_board(&db).await;
507- let board = crate::db::board::set_locked(&db, &board, true, &user("c"))
508- .await
509- .unwrap();
510- let refused = draw(&db, &board).await;
511- assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("locked")));
512- assert!(rows(&db, board.get_id()).await.is_empty());
513- // A lock is not a close: unlocking restores drawing.
514- assert!(reread(&db, &board).await.get_closed_at().is_none());
515- let board = crate::db::board::set_locked(&db, &board, false, &user("c"))
516- .await
517- .unwrap();
518- assert!(draw(&db, &board).await.is_ok());
519- }
520-
521- /// A lock the stroke lost to, unlocked again before the refusal re-reads
522- /// the row — which is the state `why_refused` is handed after a guard
523- /// failure. Reading "neither locked nor closed" as proof of the lifetime
524- /// cap stamped `closed_at` on a board holding one stroke of 50 000, with
525- /// no reopen. Only the counter itself may close a board.
526- #[tokio::test]
527- async fn a_refusal_on_an_open_board_never_closes_it() {
528- let db = a_db().await;
529- let board = a_board(&db).await;
530- let board = crate::db::board::set_locked(&db, &board, true, &user("c"))
531- .await
532- .unwrap();
533- // The claim loses the open-guard while the board is locked...
534- assert!(matches!(
535- draw(&db, &board).await,
536- Err(AppError::Conflict(_))
537- ));
538- // ...and the creator unlocks before the refusal picks its message.
539- let board = crate::db::board::set_locked(&db, &board, false, &user("c"))
540- .await
541- .unwrap();
542- let refused = why_refused(&db, board.get_id()).await.unwrap();
543- assert!(matches!(refused, AppError::Conflict(msg) if !msg.contains("read-only")));
544- // Stored state, not the return value: the board is still open, and
545- // still drawable.
546- assert!(reread(&db, &board).await.get_closed_at().is_none());
547- assert!(draw(&db, &reread(&db, &board).await).await.is_ok());
548- }
549-
550- /// The epoch index must never drift, in either direction. A stroke carrying
551- /// a pre-clear epoch used to land under the closed epoch while its
552- /// increment counted against the new one — the closed marker short by a
553- /// stroke, the next marker claiming one that is not there, both permanent.
554- #[tokio::test]
555- async fn a_stale_epoch_append_leaves_no_marker_drifted() {
556- let db = a_db().await;
557- let board = a_board(&db).await;
558- draw(&db, &board).await.unwrap();
559- clear(&db, board.get_id(), &user("c")).await.unwrap();
560-
561- // Exactly what `live_board` hands `append` when a clear lands between
562- // the board read and the write (src/web/board_ws.rs:431).
563- let stale = append(&db, board.get_id(), &user("p"), "{\"p\":[9]}", 0).await;
564- assert!(matches!(stale, Err(AppError::Conflict(_))));
565-
566- let board = reread(&db, &board).await;
567- draw(&db, &board).await.unwrap();
568- clear(&db, board.get_id(), &user("c")).await.unwrap();
569-
570- // Every marker's count is the rows the store actually holds at the
571- // epoch it closed.
572- let stored = rows(&db, board.get_id()).await;
573- for marker in stored.iter().filter(|row| row.is_clear()) {
574- let actual = stored
575- .iter()
576- .filter(|row| !row.is_clear() && row.get_epoch() == marker.get_epoch())
577- .count() as i64;
578- assert_eq!(
579- marker.get_count(),
580- Some(actual),
581- "marker for epoch {} drifted",
582- marker.get_epoch()
583- );
584- }
585- // And the refused stroke claimed nothing: two marks and the two
586- // markers that closed them, which is every row on the table.
587- assert_eq!(total_strokes(&db, board.get_id()).await.unwrap(), 4);
588- assert_eq!(stored.len(), 4);
589- }
590-
591- /// The lock pauses the canvas against *every* write to it, its creator's
592- /// clear included — a `Conflict`, since unlocking undoes it, not the
593- /// `Forbidden` a non-creator gets. Asserted off stored rows: the refusal
594- /// must mint no marker and must not bump the epoch.
595- #[tokio::test]
596- async fn a_locked_board_refuses_its_creator_s_clear() {
597- let db = a_db().await;
598- let board = a_board(&db).await;
599- draw(&db, &board).await.unwrap();
600- let board = crate::db::board::set_locked(&db, &board, true, &user("c"))
601- .await
602- .unwrap();
603-
604- let refused = clear(&db, board.get_id(), &user("c")).await;
605- assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg == BOARD_LOCKED));
606- assert_eq!(rows(&db, board.get_id()).await.len(), 1);
607- assert_eq!(reread(&db, &board).await.get_epoch(), 0);
608- assert!(epochs(&db, board.get_id()).await.unwrap().is_empty());
609-
610- // Unlock, and the same clear lands: unlock → clear → relock is the
611- // recovery for a locked board sitting at the epoch cap.
612- let board = crate::db::board::set_locked(&db, &board, false, &user("c"))
613- .await
614- .unwrap();
615- let marker = clear(&db, board.get_id(), &user("c")).await.unwrap();
616- assert_eq!(marker.get_count(), Some(1));
617- assert_eq!(reread(&db, &board).await.get_epoch(), 1);
618- }
619-
620- /// Both classifiers, one board: the words a stroke is refused with and the
621- /// words the *creator's* clear is refused with. They must match — the two
622- /// used to be independent chains and drifted apart on the state below.
623- async fn both_refusals(db: &Database, board: &Board) -> (&'static str, &'static str) {
624- let stroke = match draw(db, board).await {
625- Err(AppError::Conflict(msg)) => msg,
626- other => panic!("the stroke was not refused: {other:?}"),
627- };
628- let clear = match clear(db, board.get_id(), &user("c")).await {
629- Err(AppError::Conflict(msg)) => msg,
630- other => panic!("the clear was not refused: {other:?}"),
631- };
632- (stroke, clear)
633- }
634-
635- /// A board that is locked *and* closed is terminal, and both paths have to
636- /// say so. Reaching the state is ungated in either direction — `set_locked`
637- /// carries no `closed_at` test and `close` carries no lock test — and the
638- /// stroke path used to test the lock first, so a permanently read-only
639- /// board answered every mark with "the creator has paused drawing" while
640- /// the same board answered a clear with the terminal words. A room told to
641- /// wait for a pause that cannot lift waits forever.
642- ///
643- /// Locking a closed board stays *allowed*: it is a no-op on a board that is
644- /// already read-only, and refusing it would break the second half of a
645- /// close-then-lock a client may legitimately send in either order.
646- #[tokio::test]
647- async fn locked_and_closed_answers_closed_whichever_came_first() {
648- for closed_first in [false, true] {
649- let db = a_db().await;
650- let board = a_board(&db).await;
651- // A mark on the canvas, so "nothing to clear" cannot be the reason.
652- draw(&db, &board).await.unwrap();
653-
654- let board = if closed_first {
655- let board = crate::db::board::close(&db, &board).await.unwrap();
656- crate::db::board::set_locked(&db, &board, true, &user("c"))
657- .await
658- .unwrap()
659- } else {
660- let board = crate::db::board::set_locked(&db, &board, true, &user("c"))
661- .await
662- .unwrap();
663- crate::db::board::close(&db, &board).await.unwrap()
664- };
665- // Stored state: both flags really are up, and the close stamp stood.
666- let stored = reread(&db, &board).await;
667- assert!(stored.is_locked() && stored.get_closed_at().is_some());
668-
669- assert_eq!(
670- both_refusals(&db, &board).await,
671- (BOARD_CLOSED, BOARD_CLOSED),
672- "closed_first = {closed_first}"
673- );
674- // And the refusals wrote nothing: one mark, no marker, epoch 0.
675- assert_eq!(rows(&db, board.get_id()).await.len(), 1);
676- assert_eq!(reread(&db, &board).await.get_epoch(), 0);
677- }
678- }
679-
680- /// The other half of the same contract: a board holding *one* of the flags
681- /// keeps its own answer on both paths. A lock is recoverable, a close is
682- /// not, and collapsing either into the other is the mislabel above.
683- #[tokio::test]
684- async fn one_flag_alone_keeps_its_own_answer_on_both_paths() {
685- let db = a_db().await;
686- let locked = a_board(&db).await;
687- draw(&db, &locked).await.unwrap();
688- let locked = crate::db::board::set_locked(&db, &locked, true, &user("c"))
689- .await
690- .unwrap();
691- assert_eq!(
692- both_refusals(&db, &locked).await,
693- (BOARD_LOCKED, BOARD_LOCKED)
694- );
695-
696- let closed = a_board(&db).await;
697- draw(&db, &closed).await.unwrap();
698- let closed = crate::db::board::close(&db, &closed).await.unwrap();
699- assert_eq!(
700- both_refusals(&db, &closed).await,
701- (BOARD_CLOSED, BOARD_CLOSED)
702- );
703- }
704-
705- /// The `next_ulid` hazard: rows minted inside one millisecond must replay
706- /// in mint order, not at random (src/domain/monotonic_id.rs:41-46).
707- #[tokio::test]
708- async fn replay_is_in_mint_order_within_a_millisecond() {
709- let db = a_db().await;
710- let board = a_board(&db).await;
711- let mut minted = Vec::new();
712- for _ in 0..25 {
713- minted.push(draw(&db, &board).await.unwrap().get_id().key().to_string());
714- }
715- let replayed: Vec<String> = replay_current(&db, board.get_id(), 0, None)
716- .await
717- .unwrap()
718- .iter()
719- .map(|row| row.get_id().key().to_string())
720- .collect();
721- assert_eq!(replayed, minted);
722-
723- // The cursor resumes exactly where the last chunk stopped.
724- let rest: Vec<String> = replay_current(&db, board.get_id(), 0, Some(&minted[9]))
725- .await
726- .unwrap()
727- .iter()
728- .map(|row| row.get_id().key().to_string())
729- .collect();
730- assert_eq!(rest, minted[10..]);
731- }
732-
733- /// The one legitimate delete of stroke rows: without it, deleting a board
734- /// orphans its whole history under a record that no longer exists.
735- #[tokio::test]
736- async fn deleting_a_board_takes_its_strokes_with_it() {
737- let db = a_db().await;
738- let board = a_board(&db).await;
739- let other = a_board(&db).await;
740- draw(&db, &board).await.unwrap();
741- draw(&db, &board).await.unwrap();
742- clear(&db, board.get_id(), &user("c")).await.unwrap();
743- draw(&db, &other).await.unwrap();
744-
745- let id = board.get_id().clone();
746- crate::db::board::delete(&db, board).await.unwrap();
747- assert!(rows(&db, &id).await.is_empty());
748- // The cascade is scoped to its own board.
749- assert_eq!(rows(&db, other.get_id()).await.len(), 1);
750- }
751-
752- #[tokio::test]
753- async fn an_oversized_payload_is_refused_before_the_write() {
754- let db = a_db().await;
755- let board = a_board(&db).await;
756- let big = "x".repeat(MAX_STROKE_PAYLOAD_LEN + 1);
757- assert!(
758- append(&db, board.get_id(), &user("p"), &big, 0)
759- .await
760- .is_err()
761- );
762- assert!(
763- append(&db, board.get_id(), &user("p"), " ", 0)
764- .await
765- .is_err()
766- );
767- assert!(rows(&db, board.get_id()).await.is_empty());
768- // Nothing was claimed either — the counters must not have moved.
769- assert_eq!(reread(&db, &board).await.get_epoch(), 0);
770- }
771-
772- /// History spans epochs; a named epoch is that epoch alone.
773- #[tokio::test]
774- async fn history_spans_every_epoch_unless_one_is_named() {
775- let db = a_db().await;
776- let board = a_board(&db).await;
777- draw(&db, &board).await.unwrap();
778- clear(&db, board.get_id(), &user("c")).await.unwrap();
779- let board = reread(&db, &board).await;
780- draw(&db, &board).await.unwrap();
781-
782- let (all, total) = history(&db, board.get_id(), None, false, None, 0)
783- .await
784- .unwrap();
785- assert_eq!((all.len(), total), (3, 3));
786- let (first, total) = history(&db, board.get_id(), Some(0), false, None, 0)
787- .await
788- .unwrap();
789- // Epoch 0: its stroke and the marker that closed it.
790- assert_eq!((first.len(), total), (2, 2));
791- // `marks_only` drops the marker from that same epoch — and its `total`
792- // with it, so the envelope's count stays the count of what is served.
793- let (marks, total) = history(&db, board.get_id(), Some(0), true, None, 0)
794- .await
795- .unwrap();
796- assert_eq!((marks.len(), total), (1, 1));
797- assert!(marks.iter().all(|row| !row.is_clear()));
798- }
346+ // Rebuilt against Postgres in wave 3 (the fixtures were raw SurrealQL).
799347 }
src/db/course.rsmodified+369 -209
@@ -1,11 +1,9 @@
11 //! The `course` table: the unit exams, sessions, subjects and enrollments
22 //! hang off. Listed newest first; deleted with its whole subtree in one
3-use surrealdb::types::{RecordId, SurrealValue};
3+//! guarded cascade.
44
5-use crate::constant::{
6- CLASS_COURSE_COUNT_FIELD, COURSE_COUNT_FIELD, ENROLLMENT_COUNT_FIELD, REF_COUNT_FIELD,
7-};
8-use crate::database::{Database, transaction_with_retry};
5+use crate::constant::COURSE_TABLE;
6+use crate::database::{Database, tx_with_retry, unique_violation};
97 use crate::db::cap;
108 use crate::db::field_update::FieldUpdate;
119 use crate::db::page::PagedList;
@@ -14,16 +12,6 @@ use crate::domain::term::{self, TermId};
1412 use crate::domain::user::UserId;
1513 use crate::error::AppError;
1614
17-/// The `THROW` marker the delete guard aborts with — a roster that is not
18-/// empty, or a course row that is no longer there.
19-const ROSTER_MARK: &str = "course_roster";
20-
21-/// Create the course, claiming a reference on the term it links (if any) in
22-/// the *same transaction* as the row: the claim is a conditional write on
23-/// the term row, so it fails when the term is already gone and it makes the
24-/// term undeletable the instant this link exists — and a crash can never
25-/// leave one without the other, which a claim sent as its own query could
26-/// (the count would strand and the term be undeletable forever).
2715 pub async fn create(
2816 db: &Database,
2917 creator: &UserId,
@@ -33,50 +21,87 @@ pub async fn create(
3321 term: Option<TermId>,
3422 capacity: Option<i64>,
3523 ) -> Result<Course, AppError> {
36- let course = Course {
37- id: CourseId::generate(),
38- creator: creator.clone(),
39- teachers: Vec::new(),
40- term,
41- capacity,
24+ let id = CourseId::generate();
25+ let Some(term) = term else {
26+ let created = sqlx::query_as!(
27+ Course,
28+ r#"INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity)
29+ VALUES ($1, $2, $3, $4, $5, $6, NULL, $7)
30+ RETURNING id, creator, teachers, title, description, kind, term, capacity"#,
31+ id,
32+ creator,
33+ Vec::<UserId>::new(),
34+ title,
35+ description,
36+ kind,
37+ capacity,
38+ )
39+ .fetch_one(db)
40+ .await?;
41+ return Ok(created);
42+ };
43+ // Claim a reference on the term in the *same statement* as the row: the
44+ // claim is a conditional write on the term row, so it fails when the
45+ // term is already gone and it makes the term undeletable the instant
46+ // this link exists — and a crash can never leave one without the other,
47+ // which a claim sent as its own query could (the count would strand and
48+ // the term be undeletable forever).
49+ let created = sqlx::query_as!(
50+ Course,
51+ r#"WITH seat AS (
52+ UPDATE term
53+ SET course_count = course_count + 1
54+ WHERE id = $8 AND course_count < $9
55+ RETURNING 1)
56+ INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity)
57+ SELECT $1, $2, $3, $4, $5, $6, $8, $7 WHERE EXISTS (SELECT 1 FROM seat)
58+ RETURNING id, creator, teachers, title, description, kind, term, capacity"#,
59+ id,
60+ creator,
61+ Vec::<UserId>::new(),
4262 title,
4363 description,
4464 kind,
45- };
46- let id = course.id.record();
47- let Some(term) = course.term.clone() else {
48- let created: Option<Course> = db.create(id).content(course).await?;
49- return created.ok_or_else(|| AppError::Internal("failed to create course".into()));
50- };
51- match cap::claim_and_create(
52- &term.record(),
53- COURSE_COUNT_FIELD,
65+ capacity,
66+ term,
5467 cap::UNLIMITED,
55- &id,
56- &course,
57- db,
5868 )
59- .await?
60- {
61- cap::Claimed::Made(created) => Ok(created),
69+ .fetch_one(db)
70+ .await;
71+ match created {
72+ Ok(created) => Ok(created),
6273 // Uncapped, so "full" can only mean the conditional write matched no
6374 // term row at all — the existence check the pre-flight lookup makes.
64- cap::Claimed::Full => Err(term::gone_error()),
65- // Unreachable: the id is a ULID this call just generated.
66- cap::Claimed::Duplicate => Err(AppError::Internal("failed to create course".into())),
75+ Err(sqlx::Error::RowNotFound) => Err(term::gone_error()),
76+ // Unreachable: the id was minted above.
77+ Err(err) if unique_violation(&err).is_some() => {
78+ Err(AppError::Internal("failed to create course".into()))
79+ }
80+ Err(err) => Err(err.into()),
6781 }
6882 }
6983
7084 pub async fn read(db: &Database, id: &CourseId) -> Result<Option<Course>, AppError> {
71- Ok(db.select(id.record()).await?)
85+ let course = sqlx::query_as!(
86+ Course,
87+ r#"SELECT id, creator, teachers, title, description, kind, term, capacity
88+ FROM course WHERE id = $1"#,
89+ id,
90+ )
91+ .fetch_optional(db)
92+ .await?;
93+ Ok(course)
7294 }
7395
7496 pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> {
75- let mut result = db
76- .query("SELECT * FROM course ORDER BY id DESC")
77- .await?
78- .check()?;
79- Ok(result.take::<Vec<Course>>(0)?)
97+ let rows = sqlx::query_as!(
98+ Course,
99+ r#"SELECT id, creator, teachers, title, description, kind, term, capacity
100+ FROM course ORDER BY id DESC"#,
101+ )
102+ .fetch_all(db)
103+ .await?;
104+ Ok(rows)
80105 }
81106
82107 /// The courses `user` is enrolled in — the spine of `/courses/me` and the
@@ -88,36 +113,38 @@ pub async fn list_enrolled(
88113 offset: i64,
89114 ) -> Result<(Vec<Course>, i64), AppError> {
90115 PagedList::new(
91- "course WHERE id IN (SELECT VALUE course FROM enrollment WHERE user = $usr)",
116+ "course WHERE id IN (SELECT course FROM enrollment WHERE app_user = $1)",
92117 "ORDER BY id DESC",
93118 )
94- .bind("usr", user.record())
95- .run(limit, offset, db)
119+ .bind(user.uuid())
120+ .run::<Course>(limit, offset, db)
96121 .await
97122 }
98123
99124 /// The courses `user` runs — the ones they created plus the ones a manager
100125 /// assigned them to. A teacher's slice of the catalog.
101126 ///
102-/// corner-cut: unpaged full table scan, and it stays one — every profile read
103-/// of a teacher pays it, so the ceiling is the course table's size. It
104-/// cannot be indexed away on SurrealDB 3.2.3: an index on `creator` alone
105-/// leaves the `OR` a `TableScan` (EXPLAIN), and the per-element index the
106-/// membership half would need (`DEFINE INDEX ... FIELDS teachers[*]`) is
107-/// *wrong*, not merely useless — with it, `$usr IN teachers` and
108-/// `teachers CONTAINS $usr` return **no rows at all**, which is what the
109-/// integration test `assigned_teacher_manages_course_without_owning_it`
110-/// catches. A plain `FIELDS teachers` index is correct but unused. The
111-/// upgrade path is structural: a `course_teacher` link table indexed on
112-/// `user`, the shape `enrollment` already has, turning this into two
113-/// index-backed reads.
127+/// corner-cut: unpaged full table scan, and it stays one — every profile
128+/// read of a teacher pays it, so the ceiling is the course table's size.
129+/// Under Postgres the `OR` halves could each use an index on `creator` /
130+/// `teachers` (a GIN), but the old per-element index the membership half
131+/// would have needed was *wrong*, not merely useless — `$usr IN teachers`
132+/// returned **no rows at all** with it, which is what the integration test
133+/// `assigned_teacher_manages_course_without_owning_it` catches. The upgrade
134+/// path is structural: a `course_teacher` link table indexed on `user`, the
135+/// shape `enrollment` already has, turning this into two index-backed
136+/// reads. No schema carries it yet, so the scan stays.
114137 pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<Course>, AppError> {
115- let mut result = db
116- .query("SELECT * FROM course WHERE creator = $usr OR $usr IN teachers ORDER BY id DESC")
117- .bind(("usr", user.record()))
118- .await?
119- .check()?;
120- Ok(result.take::<Vec<Course>>(0)?)
138+ let rows = sqlx::query_as!(
139+ Course,
140+ r#"SELECT id, creator, teachers, title, description, kind, term, capacity
141+ FROM course WHERE creator = $1 OR $2 = ANY(teachers) ORDER BY id DESC"#,
142+ user,
143+ user,
144+ )
145+ .fetch_all(db)
146+ .await?;
147+ Ok(rows)
121148 }
122149
123150 /// 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<Vec<Course>,
126153 if ids.is_empty() {
127154 return Ok(Vec::new());
128155 }
129- let records: Vec<RecordId> = ids.iter().map(CourseId::record).collect();
130- let mut result = db
131- .query("SELECT * FROM course WHERE id IN $ids")
132- .bind(("ids", records))
133- .await?
134- .check()?;
135- Ok(result.take::<Vec<Course>>(0)?)
156+ let keys: Vec<CourseId> = ids.to_vec();
157+ let rows = sqlx::query_as!(
158+ Course,
159+ r#"SELECT id, creator, teachers, title, description, kind, term, capacity
160+ FROM course WHERE id = ANY($1)"#,
161+ keys,
162+ )
163+ .fetch_all(db)
164+ .await?;
165+ Ok(rows)
136166 }
137167
138168 /// Request-scoped: `teachers` is written by [`assign_teacher`],
@@ -160,19 +190,25 @@ pub async fn update(
160190 // without its count. A PATCH that carried no `term_id`, or re-stated the
161191 // link it already had, moves neither counter.
162192 let (claim, release) = term::ref_move(course.term.as_ref(), &term);
163- let expected = course.term.as_ref().map(TermId::record);
164- FieldUpdate::new(course.id.record())
165- .set("title", title)
166- .set("description", description)
167- .set("kind", kind)
168- .set("term", term.map(|term| term.map(|term| term.record())))
169- .set("capacity", capacity)
193+ FieldUpdate::new(COURSE_TABLE, course.id.uuid())
194+ .set("title", title.map(|title| title.as_str().to_owned()))
195+ .set(
196+ "description",
197+ description.map(|description| description.as_str().to_owned()),
198+ )
199+ .set("kind", kind.map(|kind| kind.as_str().to_owned()))
200+ .set(
201+ "term",
202+ term.map(|term| crate::db::page::Param::OptUuid(term.map(|term| term.uuid()))),
203+ )
204+ .set("capacity", capacity.map(crate::db::page::Param::OptI64))
170205 .refcount(
171- COURSE_COUNT_FIELD,
172206 "term",
173- expected,
174- claim,
175- release,
207+ "course_count",
208+ "term",
209+ course.term.as_ref().map(|term| term.uuid()),
210+ claim.map(|term| term.uuid()),
211+ release.map(|term| term.uuid()),
176212 term::gone_error(),
177213 )
178214 .run::<Course>(db)
@@ -184,8 +220,9 @@ pub async fn update(
184220 /// Field-scoped, and the new list is folded server-side out of the *stored*
185221 /// one: a course PATCH awaits a term lookup between its read and its write,
186222 /// so a whole-row save from either side would revert the other. The
187-/// `array::distinct` keeps the assignment idempotent even when two requests
188-/// name the same teacher at once (the early return only sees a stale row).
223+/// `array_agg(DISTINCT …)` keeps the assignment idempotent even when two
224+/// requests name the same teacher at once (the early return only sees a
225+/// stale row).
189226 pub async fn assign_teacher(
190227 db: &Database,
191228 course: Course,
@@ -194,20 +231,19 @@ pub async fn assign_teacher(
194231 if course.is_assigned(teacher) {
195232 return Ok(course);
196233 }
197- let mut result = db
198- .query(
199- "UPDATE $id SET teachers = array::distinct(array::append(teachers, $usr))
200- RETURN AFTER",
201- )
202- .bind(("id", course.id.record()))
203- .bind(("usr", teacher.record()))
204- .await?
205- .check()?;
206- result
207- .take::<Vec<Course>>(0)?
208- .into_iter()
209- .next()
210- .ok_or(AppError::NotFound)
234+ let updated = sqlx::query_as!(
235+ Course,
236+ r#"UPDATE course
237+ SET teachers = (SELECT array_agg(DISTINCT x)
238+ FROM unnest(course.teachers || $2) AS x)
239+ WHERE id = $1
240+ RETURNING id, creator, teachers, title, description, kind, term, capacity"#,
241+ course.id,
242+ teacher,
243+ )
244+ .fetch_optional(db)
245+ .await?;
246+ updated.ok_or(AppError::NotFound)
211247 }
212248
213249 /// Drop `teacher` from this course. `None` when they weren't assigned, so
@@ -220,30 +256,32 @@ pub async fn unassign_teacher(
220256 if !course.is_assigned(teacher) {
221257 return Ok(None);
222258 }
223- // Same field-scoped story as [`assign_teacher`]; `-=` drops the
224- // one link off the stored list without touching the course's own text.
225- let mut result = db
226- .query("UPDATE $id SET teachers -= $usr RETURN AFTER")
227- .bind(("id", course.id.record()))
228- .bind(("usr", teacher.record()))
229- .await?
230- .check()?;
231- Ok(Some(
232- result
233- .take::<Vec<Course>>(0)?
234- .into_iter()
235- .next()
236- .ok_or(AppError::NotFound)?,
237- ))
259+ // Same field-scoped story as [`assign_teacher`]; `array_remove` drops
260+ // the one link off the stored list without touching the course's own
261+ // text.
262+ let updated = sqlx::query_as!(
263+ Course,
264+ r#"UPDATE course SET teachers = array_remove(teachers, $2)
265+ WHERE id = $1
266+ RETURNING id, creator, teachers, title, description, kind, term, capacity"#,
267+ course.id,
268+ teacher,
269+ )
270+ .fetch_optional(db)
271+ .await?;
272+ Ok(updated)
238273 }
239274
240275 /// Strip `user` from every course they were assigned to — the sweep for a
241276 /// user demoted below `teacher`, who may no longer run anything.
242277 pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> {
243- db.query("UPDATE course SET teachers -= $usr WHERE $usr IN teachers")
244- .bind(("usr", user.record()))
245- .await?
246- .check()?;
278+ sqlx::query!(
279+ r#"UPDATE course SET teachers = array_remove(teachers, $1)
280+ WHERE $1 = ANY(teachers)"#,
281+ user,
282+ )
283+ .execute(db)
284+ .await?;
247285 Ok(())
248286 }
249287
@@ -261,111 +299,233 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App
261299 /// **Bank templates** survive it — they are a separate, reusable library
262300 /// spanning every course — so their `source_exam` and `subject` links are
263301 /// cleared instead, in this same transaction, exactly as
264-/// [`crate::db::exam::delete`] and
265-/// [`crate::db::subject::delete`] clear them one level down.
266-/// Deleting a course must leave the bank where deleting each of its exams
267-/// and subjects by hand would have left it, or a template is left pointing
268-/// at a dead exam (permanently: nothing else ever visits that column) and
269-/// at a dead subject the next `PATCH` omitting `subject_id` writes straight
270-/// back.
302+/// [`crate::db::exam::delete`] and [`crate::db::subject::delete`]
303+/// clear them one level down. Deleting a course must leave the bank where
304+/// deleting each of its exams and subjects by hand would have left it, or
305+/// a template is left pointing at a dead exam (permanently: nothing else
306+/// ever visits that column) and at a dead subject the next `PATCH`
307+/// omitting `subject_id` writes straight back.
271308 ///
272309 /// The **grade blueprints** naming it are swept in that same transaction.
273310 /// Nothing else can reach them — a blueprint holds its courses as a list on
274311 /// its own row, not as link rows this cascade could delete — and an id left
275312 /// behind is permanent rather than merely stale: the pump's own
276-/// [`crate::db::class_blueprint::prune`] fires only
277-/// while walking a section, so a grade with no sections can never drop one,
278-/// and every `PATCH` of that template is refused for naming a course that
279-/// does not exist, which is precisely the call documented as the repair.
313+/// [`crate::db::class_blueprint::prune`] fires only while walking a
314+/// section, so a grade with no sections can never drop one, and every
315+/// `PATCH` of that template is refused for naming a course that does not
316+/// exist, which is precisely the call documented as the repair. A dozen-row
317+/// table scanned unindexed, deliberately: a course delete is rare.
280318 ///
281-/// It is a table scan, deliberately unindexed: `class_blueprint` holds one
282-/// row per grade label the school uses (a dozen), a course delete is rare,
283-/// and the per-element index the `WHERE` would want
284-/// (`FIELDS courses[*]`) is the one this store answers with **no rows at
285-/// all** — the trap [`list_for_teacher`] documents.
319+/// The **derived AI rows** (`rag_output` carries a denormalized `course`
320+/// besides its note link) and the event **audience links** are FK children
321+/// the old store let dangle: `rag_output` is disposable and dies here, and
322+/// an event whose audience was "this course's students" keeps standing with
323+/// `audience_course` cleared — an empty roster, exactly the documented
324+/// outcome of the class twin (`Course::delete` never touched `event`; it
325+/// still doesn't delete one).
286326 ///
287327 /// The marks going with it give their exam kinds' references back, counted
288328 /// per kind inside this same transaction — the mirror of `Exam::delete`.
289329 /// Skipping it would leave every kind the course graded under counted
290330 /// forever, and a counted kind can never leave the school's settings.
291331 ///
332+/// **Order is the foreign-key graph, children first** (the old store had
333+/// no FKs, so its order was free): exam results/attempts/answers/images
334+/// and question images before `exam_question`; `exam_question` before
335+/// `exam`; homework files before submissions before results before
336+/// `homework`; roll-call rows before `course_session`; note files and
337+/// rag rows before `course_note`; every one of them before the `course`
338+/// row itself, whose `NO ACTION` FKs are checked the moment the final
339+/// `DELETE` runs.
340+///
292341 /// `false` = refused, nothing was written: someone is still enrolled. The
293-/// roster is read off the course's own `enrollment_count`, so the check and
294-/// the delete are one conditional write on one record — an enroll racing
295-/// this either takes its seat first (and the delete is refused) or finds
296-/// the row gone (and is refused itself). `Err(NotFound)`
297-/// keeps the answer a concurrent *delete* used to get.
342+/// guard locks the course row (`FOR UPDATE`) and reads its own
343+/// `enrollment_count`, so an enroll racing this either takes its seat
344+/// first (and the delete is refused) or finds the row gone (and is refused
345+/// itself). `Err(NotFound)` keeps the answer a concurrent *delete* used
346+/// to get — and unlike the old one-statement guard, this one tells the two
347+/// apart without a second read.
298348 pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {
299- let sql = format!(
300- "BEGIN TRANSACTION;
301- LET $gone = (DELETE $course WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE);
302- IF array::len($gone) = 0 {{ THROW '{ROSTER_MARK}' }};
303- FOR $row IN $gone {{
304- IF $row.term != NONE {{
305- UPDATE $row.term SET {COURSE_COUNT_FIELD} = \
306- math::max([({COURSE_COUNT_FIELD} ?? 0) - 1, 0]);
307- }};
308- }};
309- FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result
310- WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)
311- GROUP BY kind) ?? []) {{
312- UPDATE type::record('kind_ref', $row.kind) SET {REF_COUNT_FIELD} = \
313- math::max([({REF_COUNT_FIELD} ?? 0) - $row.n, 0])
314- }};
315- DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
316- DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
317- DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
318- DELETE answer_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
319- DELETE question_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
320- DELETE exam_question WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
321- DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course));
322- DELETE homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course);
323- DELETE homework_result WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course);
324- DELETE course_note_file WHERE course_note IN (SELECT VALUE id FROM course_note WHERE course = $course);
325- DELETE course_note WHERE course = $course;
326- LET $detached = (DELETE class_course WHERE course = $course RETURN BEFORE);
327- FOR $row IN ($detached ?? []) {{
328- UPDATE $row.class SET {CLASS_COURSE_COUNT_FIELD} = \
329- math::max([({CLASS_COURSE_COUNT_FIELD} ?? 0) - 1, 0]);
330- }};
331- UPDATE class_blueprint SET courses -= $course WHERE $course IN courses;
332- DELETE session_attendance WHERE course = $course;
333- DELETE course_session WHERE course = $course;
334- DELETE enrollment WHERE course = $course;
335- UPDATE bank_question SET subject = NONE
336- WHERE subject IN (SELECT VALUE id FROM subject WHERE course = $course);
337- DELETE subject WHERE course = $course;
338- DELETE homework WHERE course = $course;
339- UPDATE bank_question SET source_exam = NONE
340- WHERE source_exam IN (SELECT VALUE id FROM exam WHERE course = $course);
341- DELETE exam WHERE course = $course;
342- COMMIT TRANSACTION;"
343- );
344- // An aborted transaction errors *every* slot, most with a generic "not
345- // executed" — only the THROW's own slot names the marker, and a lost
346- // round is re-sent rather than reported (see [`transaction_with_retry`]).
347- let (_, mut errors) = transaction_with_retry(
348- db,
349- &sql,
350- &[("course".into(), course.id.record().into_value())],
351- &[ROSTER_MARK],
352- )
353- .await?;
354- if errors
355- .values()
356- .any(|error| error.to_string().contains(ROSTER_MARK))
357- {
358- // Full stop or already gone: the guard cannot tell those apart, and
359- // only the refusal path pays for the extra read that can.
360- return match read(db, &course.id).await? {
361- Some(_) => Ok(false),
362- None => Err(AppError::NotFound),
349+ tx_with_retry(db, true, async |tx| {
350+ // The guard and the lock: the row (and its roster count) cannot
351+ // change under this transaction, and every enroll claim contends on
352+ // this very row, so check and cascade are one decision.
353+ let guard = sqlx::query!(
354+ r#"SELECT enrollment_count, term FROM course WHERE id = $1 FOR UPDATE"#,
355+ course.id,
356+ )
357+ .fetch_optional(&mut *tx)
358+ .await?;
359+ let Some(guard) = guard else {
360+ return Err(AppError::NotFound);
363361 };
364- }
365- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
366- return Err(error.into());
367- }
368- Ok(true)
362+ if guard.enrollment_count != 0 {
363+ return Ok(false);
364+ }
365+ // The exam ids are needed twice — the kind_ref refund and the bank's
366+ // source_exam clear — and must be collected before the sweeps take
367+ // the rows they name.
368+ let exams: Vec<uuid::Uuid> =
369+ sqlx::query!(r#"SELECT id FROM exam WHERE course = $1"#, course.id,)
370+ .fetch_all(&mut *tx)
371+ .await?
372+ .into_iter()
373+ .map(|row| row.id)
374+ .collect();
375+ // Every mark the course ever gave gives its exam kind's reference
376+ // back, counted per kind (mirrors `Exam::delete`). The kind rides
377+ // the exam row — `exam_result` names its exam, not its kind.
378+ sqlx::query!(
379+ r#"UPDATE kind_ref k
380+ SET count = GREATEST(k.count - s.n, 0)
381+ FROM (SELECT e.kind, count(*) AS n FROM exam_result r
382+ JOIN exam e ON r.exam = e.id
383+ WHERE r.exam = ANY($1) GROUP BY e.kind) s
384+ WHERE k.name = s.kind"#,
385+ exams,
386+ )
387+ .execute(&mut *tx)
388+ .await?;
389+ // The term gets its reference back inside the same transaction.
390+ if let Some(term) = guard.term {
391+ sqlx::query!(
392+ r#"UPDATE term SET course_count = GREATEST(course_count - 1, 0)
393+ WHERE id = $1"#,
394+ term,
395+ )
396+ .execute(&mut *tx)
397+ .await?;
398+ }
399+ // Events aimed at this course keep standing, audience cleared.
400+ sqlx::query!(
401+ r#"UPDATE event SET audience_course = NULL WHERE audience_course = $1"#,
402+ course.id,
403+ )
404+ .execute(&mut *tx)
405+ .await?;
406+ // The exam subtree, deepest children first.
407+ sqlx::query!(r#"DELETE FROM exam_result WHERE exam = ANY($1)"#, exams)
408+ .execute(&mut *tx)
409+ .await?;
410+ sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = ANY($1)"#, exams)
411+ .execute(&mut *tx)
412+ .await?;
413+ sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = ANY($1)"#, exams)
414+ .execute(&mut *tx)
415+ .await?;
416+ sqlx::query!(r#"DELETE FROM answer_image WHERE exam = ANY($1)"#, exams)
417+ .execute(&mut *tx)
418+ .await?;
419+ sqlx::query!(r#"DELETE FROM question_image WHERE exam = ANY($1)"#, exams)
420+ .execute(&mut *tx)
421+ .await?;
422+ sqlx::query!(r#"DELETE FROM exam_question WHERE exam = ANY($1)"#, exams)
423+ .execute(&mut *tx)
424+ .await?;
425+ // The homework subtree: files, then submissions (whose graded_by
426+ // link names a result deleted after them), then results.
427+ sqlx::query!(
428+ r#"DELETE FROM homework_file WHERE submission IN (
429+ SELECT id FROM homework_submission
430+ WHERE homework IN (SELECT id FROM homework WHERE course = $1))"#,
431+ course.id,
432+ )
433+ .execute(&mut *tx)
434+ .await?;
435+ sqlx::query!(
436+ r#"DELETE FROM homework_submission WHERE homework IN (
437+ SELECT id FROM homework WHERE course = $1)"#,
438+ course.id,
439+ )
440+ .execute(&mut *tx)
441+ .await?;
442+ sqlx::query!(
443+ r#"DELETE FROM homework_result WHERE homework IN (
444+ SELECT id FROM homework WHERE course = $1)"#,
445+ course.id,
446+ )
447+ .execute(&mut *tx)
448+ .await?;
449+ // Derived AI rows for this course's notes.
450+ sqlx::query!(r#"DELETE FROM rag_output WHERE course = $1"#, course.id)
451+ .execute(&mut *tx)
452+ .await?;
453+ // Notes: files before their notes.
454+ sqlx::query!(
455+ r#"DELETE FROM course_note_file WHERE course_note IN (
456+ SELECT id FROM course_note WHERE course = $1)"#,
457+ course.id,
458+ )
459+ .execute(&mut *tx)
460+ .await?;
461+ sqlx::query!(r#"DELETE FROM course_note WHERE course = $1"#, course.id)
462+ .execute(&mut *tx)
463+ .await?;
464+ // Class attachments: detach and hand each class its count back in
465+ // one statement, then strike the course out of every blueprint.
466+ sqlx::query!(
467+ r#"WITH detached AS (
468+ DELETE FROM class_course WHERE course = $1 RETURNING class)
469+ UPDATE class_group g
470+ SET class_course_count = GREATEST(g.class_course_count - 1, 0)
471+ FROM detached WHERE g.id = detached.class"#,
472+ course.id,
473+ )
474+ .execute(&mut *tx)
475+ .await?;
476+ sqlx::query!(
477+ r#"UPDATE class_blueprint SET courses = array_remove(courses, $1)
478+ WHERE $1 = ANY(courses)"#,
479+ course.id,
480+ )
481+ .execute(&mut *tx)
482+ .await?;
483+ // Sessions with their roll call, then the roster itself.
484+ sqlx::query!(
485+ r#"DELETE FROM session_attendance WHERE course = $1"#,
486+ course.id,
487+ )
488+ .execute(&mut *tx)
489+ .await?;
490+ sqlx::query!(r#"DELETE FROM course_session WHERE course = $1"#, course.id)
491+ .execute(&mut *tx)
492+ .await?;
493+ sqlx::query!(r#"DELETE FROM enrollment WHERE course = $1"#, course.id)
494+ .execute(&mut *tx)
495+ .await?;
496+ // The bank keeps its templates; their links to this course's
497+ // content go first, so the subject/exam deletes below cannot trip
498+ // a foreign key behind them.
499+ sqlx::query!(
500+ r#"UPDATE bank_question SET subject = NULL
501+ WHERE subject IN (SELECT id FROM subject WHERE course = $1)"#,
502+ course.id,
503+ )
504+ .execute(&mut *tx)
505+ .await?;
506+ sqlx::query!(
507+ r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = ANY($1)"#,
508+ exams,
509+ )
510+ .execute(&mut *tx)
511+ .await?;
512+ // Subjects before exams would trip `exam.subject` — exams go first.
513+ sqlx::query!(r#"DELETE FROM exam WHERE course = $1"#, course.id)
514+ .execute(&mut *tx)
515+ .await?;
516+ sqlx::query!(r#"DELETE FROM homework WHERE course = $1"#, course.id)
517+ .execute(&mut *tx)
518+ .await?;
519+ sqlx::query!(r#"DELETE FROM subject WHERE course = $1"#, course.id)
520+ .execute(&mut *tx)
521+ .await?;
522+ // Last: the course itself, now FK-silent.
523+ sqlx::query!(r#"DELETE FROM course WHERE id = $1"#, course.id)
524+ .execute(&mut *tx)
525+ .await?;
526+ Ok(true)
527+ })
528+ .await
369529 }
370530
371531 /// A real course row, for the tests of every child that must now prove its
src/db/course_note.rsmodified+72 -53
@@ -1,11 +1,7 @@
1-//! The `course_note` table: a teacher-authored note attached to a course,
2-//! listed newest first, deleted together with its attachment rows.
1+//! The `course_note` table: a course's shared notes, newest first, deleted
2+//! together with their attachment rows.
33
4-use surrealdb::types::SurrealValue;
5-
6-use crate::constant::ENROLLMENT_COUNT_FIELD;
7-use crate::database::Database;
8-use crate::db::cap;
4+use crate::database::{Database, foreign_key_violation, tx_with_retry};
95 use crate::db::field_update::FieldUpdate;
106 use crate::db::page::PagedList;
117 use crate::domain::course::CourseId;
@@ -14,15 +10,6 @@ use crate::domain::course_note_file::CourseNoteFile;
1410 use crate::domain::user::UserId;
1511 use crate::error::AppError;
1612
17-/// What [`delete`]'s transaction removed: the note row (empty if it had
18-/// already vanished) and every attachment row the cascade took with it — the
19-/// only set whose blobs are safe to unlink.
20-#[derive(Debug, SurrealValue)]
21-struct DeleteOutcome {
22- note: Vec<CourseNote>,
23- files: Vec<CourseNoteFile>,
24-}
25-
2613 pub async fn create(
2714 db: &Database,
2815 course: &CourseId,
@@ -37,23 +24,41 @@ pub async fn create(
3724 title,
3825 content,
3926 };
40- // The course row is *written* (bumped and put back), not read, so this
41- // collides with `Course::delete`'s cascade: a note that outlives its
42- // course is unreachable forever — every route to it goes through the
43- // course. See [`cap::touch_and_create`].
44- cap::touch_and_create(
45- &course.record(),
46- ENROLLMENT_COUNT_FIELD,
47- &note.id.record(),
48- &note,
49- db,
27+ // whole-row-save-ok: insert of a fresh UUID row built in place — there is no prior row to clobber.
28+ // The course row is *referenced* (a real foreign key the store now
29+ // enforces), so a note that races `Course::delete`'s cascade is refused
30+ // as 23503 instead of outliving its course — a note whose course is gone
31+ // is unreachable forever, every route to it going through the course.
32+ // That refusal is the parent-gone 404 the touch trick used to produce.
33+ let created = sqlx::query_as!(
34+ CourseNote,
35+ r#"INSERT INTO course_note (id, course, author, title, content)
36+ VALUES ($1, $2, $3, $4, $5)
37+ RETURNING id, course, author, title, content"#,
38+ note.id,
39+ note.course,
40+ note.author,
41+ note.title,
42+ note.content
5043 )
51- .await?
52- .ok_or(AppError::NotFound)
44+ .fetch_one(db)
45+ .await;
46+ match created {
47+ Ok(row) => Ok(row),
48+ Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound),
49+ Err(err) => Err(err.into()),
50+ }
5351 }
5452
5553 pub async fn read(db: &Database, id: &CourseNoteId) -> Result<Option<CourseNote>, AppError> {
56- Ok(db.select(id.record()).await?)
54+ let note = sqlx::query_as!(
55+ CourseNote,
56+ r#"SELECT id, course, author, title, content FROM course_note WHERE id = $1"#,
57+ id
58+ )
59+ .fetch_optional(db)
60+ .await?;
61+ Ok(note)
5762 }
5863
5964 pub async fn list_for_course(
@@ -62,9 +67,9 @@ pub async fn list_for_course(
6267 limit: Option<i64>,
6368 offset: i64,
6469 ) -> Result<(Vec<CourseNote>, i64), AppError> {
65- PagedList::new("course_note WHERE course = $crs", "ORDER BY id DESC")
66- .bind("crs", course.record())
67- .run(limit, offset, db)
70+ PagedList::new("course_note WHERE course = $1", "ORDER BY id DESC")
71+ .bind(course.uuid())
72+ .run::<CourseNote>(limit, offset, db)
6873 .await
6974 }
7075
@@ -80,9 +85,12 @@ pub async fn update(
8085 title: Option<CourseNoteTitle>,
8186 content: Option<CourseNoteContent>,
8287 ) -> Result<CourseNote, AppError> {
83- FieldUpdate::new(note.id.record())
84- .set("title", title)
85- .set("content", content)
88+ FieldUpdate::new("course_note", note.id.uuid())
89+ .set("title", title.map(|title| title.as_str().to_string()))
90+ .set(
91+ "content",
92+ content.map(|content| content.as_str().to_string()),
93+ )
8694 .run::<CourseNote>(db)
8795 .await
8896 }
@@ -92,29 +100,40 @@ pub async fn update(
92100 /// Blob files on disk are the web layer's to remove, but only for *these*
93101 /// rows — a row uploaded after the caller listed the note's files is
94102 /// deleted here too, and a pre-read snapshot would strand its blob.
103+///
104+/// The `rag_output` sweep rides in the same transaction: `rag_output`
105+/// references this table through a real foreign key (`ON DELETE NO
106+/// ACTION`), so a derived row left behind would refuse the delete — and a
107+/// derived row outliving its note is exactly what the cascade exists to
108+/// prevent. The web layer's separate `delete_for_note` call stays, as a
109+/// harmless idempotent repeat.
95110 pub async fn delete(
96111 db: &Database,
97112 note: CourseNote,
98113 ) -> Result<(CourseNote, Vec<CourseNoteFile>), AppError> {
99- let mut result = db
100- .query(
101- "BEGIN TRANSACTION;
102- LET $files = (DELETE course_note_file WHERE course_note = $note RETURN BEFORE);
103- LET $gone = (DELETE $note RETURN BEFORE);
104- RETURN { note: $gone, files: $files };
105- COMMIT TRANSACTION;",
114+ tx_with_retry(db, true, async |conn| {
115+ sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id)
116+ .execute(&mut *conn)
117+ .await?;
118+ let files = sqlx::query_as!(
119+ CourseNoteFile,
120+ r#"DELETE FROM course_note_file WHERE course_note = $1
121+ RETURNING id, course_note, name, content_type, size"#,
122+ note.id
123+ )
124+ .fetch_all(&mut *conn)
125+ .await?;
126+ let gone = sqlx::query_as!(
127+ CourseNote,
128+ r#"DELETE FROM course_note WHERE id = $1 RETURNING id, course, author, title, content"#,
129+ note.id
106130 )
107- .bind(("note", note.id.record()))
108- .await?
109- .check()?;
110- // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3.
111- let outcome = result
112- .take::<Vec<DeleteOutcome>>(3)?
113- .into_iter()
114- .next()
115- .ok_or_else(|| AppError::Internal("failed to delete course note".into()))?;
116- let note = outcome.note.into_iter().next().ok_or(AppError::NotFound)?;
117- Ok((note, outcome.files))
131+ .fetch_optional(&mut *conn)
132+ .await?;
133+ let note = gone.ok_or(AppError::NotFound)?;
134+ Ok((note, files))
135+ })
136+ .await
118137 }
119138
120139 #[cfg(test)]
src/db/course_note_file.rsmodified+125 -137
@@ -2,54 +2,71 @@
22 //! newest first, with the note's file cap claimed and released in the same
33 //! write as the row.
44
5-use surrealdb::types::{RecordId, RecordIdKey};
6-
7-use crate::constant::{COURSE_NOTE_FILE_COUNT_FIELD, MAX_COURSE_NOTE_FILES};
8-use crate::database::Database;
9-use crate::db::cap;
5+use crate::constant::MAX_COURSE_NOTE_FILES;
6+use crate::database::{Database, tx_with_retry, unique_violation};
107 use crate::db::page::PagedList;
8+use crate::domain::course::CourseId;
119 use crate::domain::course_note::CourseNoteId;
1210 use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId};
1311 use crate::error::AppError;
1412
1513 /// Persist the row assembled by [`CourseNoteFile::new`], refusing once its
1614 /// note already holds [`MAX_COURSE_NOTE_FILES`]. The slot and the row are
17-/// taken together by [`cap::claim_and_create`] on the note row — see
18-/// [`crate::db::note_file::insert`] for why that is the only guard a
19-/// concurrent insert cannot outrun.
15+/// taken together by one conditional statement on the note row (the claim
16+/// CTE of `cap::claim_and_create`, spelled out at its call site — see
17+/// `crate::db::cap`) — see [`crate::db::note_file::insert`] for why that is
18+/// the only guard a concurrent insert cannot outrun.
2019 pub async fn insert(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFile, AppError> {
21- // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber
22- match cap::claim_and_create(
23- &file.course_note.record(),
24- COURSE_NOTE_FILE_COUNT_FIELD,
20+ // whole-row-save-ok: insert of a fresh UUID row built in place by `new` — there is no prior row to clobber
21+ let created = sqlx::query_as!(
22+ CourseNoteFile,
23+ r#"WITH seat AS (
24+ UPDATE course_note SET file_count = file_count + 1
25+ WHERE id = $1 AND file_count < $2
26+ RETURNING 1)
27+ INSERT INTO course_note_file (id, course_note, name, content_type, size)
28+ SELECT $3, $1, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat)
29+ RETURNING id, course_note, name, content_type, size"#,
30+ file.course_note,
2531 MAX_COURSE_NOTE_FILES as i64,
26- &file.id.record(),
27- &file,
28- db,
32+ file.id,
33+ file.name,
34+ file.content_type,
35+ file.size
2936 )
30- .await?
31- {
32- cap::Claimed::Made(created) => Ok(created),
37+ .fetch_optional(db)
38+ .await;
39+ match created {
40+ Ok(Some(row)) => Ok(row),
3341 // Also how a missing note reads: no note row means no slot to take.
34- cap::Claimed::Full => Err(AppError::Conflict(
42+ Ok(None) => Err(AppError::Conflict(
3543 "the course note already holds the maximum of 10 files — delete one first",
3644 )),
37- // Unreachable: the id is a ULID this call just generated.
38- cap::Claimed::Duplicate => Err(AppError::Internal(
45+ // A duplicate would be a 23505 on the row's own key, which this path
46+ // cannot produce — the id is a UUID this call just generated.
47+ Err(err) if unique_violation(&err).is_some() => Err(AppError::Internal(
3948 "failed to create course note file".into(),
4049 )),
50+ Err(err) => Err(err.into()),
4151 }
4252 }
4353
4454 /// Read a file's row by id alone, for the callers that have no note in
4555 /// hand yet and reach the note *through* the file (the AI bridge's blob
46-/// stream). A key from any other table simply reads as `None`, which is
56+/// stream). An id from any other table simply reads as `None`, which is
4757 /// what keeps a personal note's file id unreachable here.
4858 pub async fn read(
4959 db: &Database,
5060 id: &CourseNoteFileId,
5161 ) -> Result<Option<CourseNoteFile>, AppError> {
52- Ok(db.select(id.record()).await?)
62+ let file = sqlx::query_as!(
63+ CourseNoteFile,
64+ r#"SELECT id, course_note, name, content_type, size FROM course_note_file WHERE id = $1"#,
65+ id
66+ )
67+ .fetch_optional(db)
68+ .await?;
69+ Ok(file)
5370 }
5471
5572 /// Read a file's row only if it belongs to `note` — callers have already
@@ -59,8 +76,16 @@ pub async fn read_for(
5976 id: &CourseNoteFileId,
6077 note: &CourseNoteId,
6178 ) -> Result<Option<CourseNoteFile>, AppError> {
62- let file: Option<CourseNoteFile> = db.select(id.record()).await?;
63- Ok(file.filter(|file| &file.course_note == note))
79+ let file = sqlx::query_as!(
80+ CourseNoteFile,
81+ r#"SELECT id, course_note, name, content_type, size FROM course_note_file
82+ WHERE id = $1 AND course_note = $2"#,
83+ id,
84+ note
85+ )
86+ .fetch_optional(db)
87+ .await?;
88+ Ok(file)
6489 }
6590
6691 /// All of `note`'s attachment rows, newest first.
@@ -71,69 +96,63 @@ pub async fn list_for(
7196 offset: i64,
7297 ) -> Result<(Vec<CourseNoteFile>, i64), AppError> {
7398 PagedList::new(
74- "course_note_file WHERE course_note = $note",
99+ "course_note_file WHERE course_note = $1",
75100 "ORDER BY id DESC",
76101 )
77- .bind("note", note.record())
78- .run(limit, offset, db)
102+ .bind(note.uuid())
103+ .run::<CourseNoteFile>(limit, offset, db)
79104 .await
80105 }
81106
82-/// The blob names (record keys, since a file's blob is named by its own
107+/// The blob names (the rows' own ids, since a file's blob is named by its
83108 /// id) behind every note attachment of `course` — collected *before* the
84109 /// course-delete cascade wipes the rows.
85110 pub async fn file_keys_for_course(
86111 db: &Database,
87- course: &crate::domain::course::CourseId,
112+ course: &CourseId,
88113 ) -> Result<Vec<String>, AppError> {
89- let mut result = db
90- .query(
91- "SELECT VALUE id FROM course_note_file \
92- WHERE course_note IN (SELECT VALUE id FROM course_note WHERE course = $course)",
93- )
94- .bind(("course", course.record()))
95- .await?
96- .check()?;
97- Ok(result
98- .take::<Vec<RecordId>>(0)?
99- .into_iter()
100- .map(|id| match id.key {
101- RecordIdKey::String(key) => key,
102- _ => String::new(),
103- })
104- .collect())
114+ let rows = sqlx::query!(
115+ r#"SELECT course_note_file.id AS "id: CourseNoteFileId" FROM course_note_file
116+ WHERE course_note IN (SELECT id FROM course_note WHERE course = $1)"#,
117+ course.0
118+ )
119+ .fetch_all(db)
120+ .await?;
121+ Ok(rows.into_iter().map(|row| row.id.key()).collect())
105122 }
106123
107124 /// Delete the row and give its slot back in the same transaction — the
108125 /// note itself is untouched, so unlike the note-delete cascade this one
109126 /// has a counter to correct.
110127 pub async fn delete(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFile, AppError> {
111- let mut result = db
112- .query(
113- "BEGIN TRANSACTION;
114- LET $gone = (DELETE $id RETURN BEFORE);
115- UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]);
116- RETURN $gone;
117- COMMIT TRANSACTION;",
128+ tx_with_retry(db, true, async |conn| {
129+ let gone = sqlx::query_as!(
130+ CourseNoteFile,
131+ r#"DELETE FROM course_note_file WHERE id = $1
132+ RETURNING id, course_note, name, content_type, size"#,
133+ file.id
118134 )
119- .bind(("id", file.id.record()))
120- .bind(("note", file.course_note.record()))
121- .await?
122- .check()?;
123- result
124- .take::<Vec<CourseNoteFile>>(3)?
125- .into_iter()
126- .next()
127- .ok_or(AppError::NotFound)
135+ .fetch_optional(&mut *conn)
136+ .await?;
137+ let file = gone.ok_or(AppError::NotFound)?;
138+ sqlx::query!(
139+ "UPDATE course_note SET file_count = GREATEST(file_count - 1, 0) WHERE id = $1",
140+ file.course_note
141+ )
142+ .execute(&mut *conn)
143+ .await?;
144+ Ok(file)
145+ })
146+ .await
128147 }
129148
130149 #[cfg(test)]
131150 mod tests {
132151 use super::*;
133- use crate::database::Database;
134152 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
135- use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle};
136- use crate::domain::course_note_file::{FileContentType, FileName};
153+ use crate::domain::course_note::{CourseNoteContent, CourseNoteTitle};
154+ use crate::domain::course_note_file::FileContentType;
155+ use crate::domain::course_note_file::FileName;
137156
138157 async fn note_of(db: &Database, title: &str) -> CourseNote {
139158 let creator = crate::domain::user::UserId::generate();
@@ -159,85 +178,54 @@ mod tests {
159178 .unwrap()
160179 }
161180
181+ /// The cap answers with a conflict and the refused upload wrote nothing:
182+ /// the count stays at the accepted rows.
162183 #[tokio::test]
163- async fn rows_scope_to_their_note() {
184+ async fn insert_refuses_at_the_cap() {
164185 let db = crate::database::init_mem().await.unwrap();
165- let note_a = note_of(&db, "a").await.get_id().clone();
166- let note_b = note_of(&db, "b").await.get_id().clone();
167- let file = insert(
168- &db,
169- CourseNoteFile::new(
170- &note_a,
171- FileName::try_new("plan.pdf").unwrap(),
172- FileContentType::try_new("application/pdf").unwrap(),
173- 3,
174- ),
175- )
176- .await
177- .unwrap();
178-
179- let found = read_for(&db, file.get_id(), &note_a).await.unwrap();
180- assert_eq!(found.unwrap().get_name().as_str(), "plan.pdf");
181- assert!(
182- read_for(&db, file.get_id(), &note_b)
183- .await
184- .unwrap()
185- .is_none()
186+ let note = note_of(&db, "n").await;
187+ for index in 0..MAX_COURSE_NOTE_FILES {
188+ let file = CourseNoteFile::new(
189+ note.get_id(),
190+ FileName::try_new(&format!("f{index}")).unwrap(),
191+ FileContentType::try_new("text/plain").unwrap(),
192+ 1,
193+ );
194+ insert(&db, file).await.unwrap();
195+ }
196+ let over = CourseNoteFile::new(
197+ note.get_id(),
198+ FileName::try_new("over").unwrap(),
199+ FileContentType::try_new("text/plain").unwrap(),
200+ 1,
186201 );
187-
188- let listed = async |note: &CourseNoteId| list_for(&db, note, None, 0).await.unwrap().0;
189- assert_eq!(listed(&note_a).await.len(), 1);
190- assert!(listed(&note_b).await.is_empty());
191-
192- delete(&db, file).await.unwrap();
193- assert!(listed(&note_a).await.is_empty());
202+ assert!(matches!(
203+ insert(&db, over).await,
204+ Err(AppError::Conflict(_))
205+ ));
206+ let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap();
207+ assert_eq!(total, MAX_COURSE_NOTE_FILES as i64);
194208 }
195209
196- /// The counter and the rows are written in one transaction, so the stored
197- /// count must equal the stored rows — after a success *and* after the
198- /// refusal that fills the cap, which must move neither.
210+ /// The blob-key collection sees attachments through the course, and a
211+ /// delete hands its slot back to the note.
199212 #[tokio::test]
200- async fn counter_tracks_stored_rows() {
213+ async fn file_keys_and_delete_slot_release() {
201214 let db = crate::database::init_mem().await.unwrap();
202- let note = note_of(&db, "a").await.get_id().clone();
203- let stored_count = async |note: &CourseNoteId| -> i64 {
204- db.query("SELECT VALUE file_count FROM $note")
205- .bind(("note", note.record()))
206- .await
207- .unwrap()
208- .take::<Vec<i64>>(0)
209- .unwrap()
210- .into_iter()
211- .next()
212- .unwrap_or(0)
213- };
214- let add = async |note: &CourseNoteId| {
215- insert(
216- &db,
217- CourseNoteFile::new(
218- note,
219- FileName::try_new("plan.pdf").unwrap(),
220- FileContentType::try_new("application/pdf").unwrap(),
221- 3,
222- ),
223- )
224- .await
225- };
226-
227- for filled in 1..=MAX_COURSE_NOTE_FILES {
228- add(&note).await.unwrap();
229- assert_eq!(stored_count(&note).await, filled as i64);
230- assert_eq!(
231- list_for(&db, &note, None, 0).await.unwrap().1,
232- filled as i64
233- );
234- }
235-
236- assert!(matches!(add(&note).await, Err(AppError::Conflict(_))));
237- assert_eq!(stored_count(&note).await, MAX_COURSE_NOTE_FILES as i64);
238- assert_eq!(
239- list_for(&db, &note, None, 0).await.unwrap().1,
240- MAX_COURSE_NOTE_FILES as i64
215+ let note = note_of(&db, "n").await;
216+ let course = note.get_course().clone();
217+ let file = CourseNoteFile::new(
218+ note.get_id(),
219+ FileName::try_new("f").unwrap(),
220+ FileContentType::try_new("text/plain").unwrap(),
221+ 1,
241222 );
223+ let file = insert(&db, file).await.unwrap();
224+ let keys = file_keys_for_course(&db, &course).await.unwrap();
225+ assert_eq!(keys, vec![file.get_id().key().to_string()]);
226+ let gone = delete(&db, file.clone()).await.unwrap();
227+ assert_eq!(gone.get_id(), file.get_id());
228+ assert!(matches!(delete(&db, file).await, Err(AppError::NotFound)));
229+ assert!(file_keys_for_course(&db, &course).await.unwrap().is_empty());
242230 }
243231 }
src/db/course_session.rsmodified+77 -55
@@ -1,15 +1,11 @@
11 //! The `course_session` table: reads, a course's timetable listing, the
22 //! request-scoped field update, and the delete that sweeps roll-call rows in
3-//! one transaction. Creation writes the course row through
4-//! [`cap::touch_and_create`] so a lesson can never outlive its course; the
5-//! web-facing doors and the teacher-resolution rule live in
6-//! [`crate::service::course_session`].
3+//! one transaction. Creation stands on the course foreign key, so a lesson
4+//! can never outlive its course; the web-facing doors and the
5+//! teacher-resolution rule live in [`crate::service::course_session`].
76
8-use surrealdb::types::SurrealValue;
9-
10-use crate::constant::ENROLLMENT_COUNT_FIELD;
11-use crate::database::{Database, transaction_with_retry};
12-use crate::db::cap;
7+use crate::constant::COURSE_SESSION_TABLE;
8+use crate::database::{Database, foreign_key_violation, tx_with_retry};
139 use crate::db::field_update::FieldUpdate;
1410 use crate::db::page::PagedList;
1511 use crate::domain::course::CourseId;
@@ -34,23 +30,44 @@ pub async fn create(
3430 starts_at,
3531 ends_at,
3632 };
37- // The course row is *written* (bumped and put back), not read, so this
38- // collides with `Course::delete`'s cascade: a lesson that outlives its
39- // course 404s through `session_with_course` forever — unreadable,
40- // unpatchable, undeletable. See [`cap::touch_and_create`].
41- cap::touch_and_create(
42- &course.record(),
43- ENROLLMENT_COUNT_FIELD,
44- &session.id.record(),
45- &session,
46- db,
33+ // The course foreign key is the existence proof the old bump-and-restore
34+ // "touch" trick faked: a lesson whose course is already gone — or which
35+ // is deleted while this insert is in flight — is refused here, so a
36+ // lesson can never outlive its course and 404 through
37+ // `session_with_course` forever — unreadable, unpatchable, undeletable.
38+ // `23503` is the parent-gone refusal, the same answer the touch
39+ // produced.
40+ let created = sqlx::query_as!(
41+ CourseSession,
42+ r#"INSERT INTO course_session (id, course, teacher, topic, starts_at, ends_at)
43+ VALUES ($1, $2, $3, $4, $5, $6)
44+ RETURNING id, course, teacher, topic, starts_at, ends_at"#,
45+ session.id,
46+ session.course,
47+ session.teacher,
48+ session.topic,
49+ session.starts_at,
50+ session.ends_at,
4751 )
48- .await?
49- .ok_or(AppError::NotFound)
52+ .fetch_one(db)
53+ .await;
54+ match created {
55+ Ok(created) => Ok(created),
56+ Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound),
57+ Err(err) => Err(err.into()),
58+ }
5059 }
5160
5261 pub async fn read(db: &Database, id: &CourseSessionId) -> Result<Option<CourseSession>, AppError> {
53- Ok(db.select(id.record()).await?)
62+ let session = sqlx::query_as!(
63+ CourseSession,
64+ r#"SELECT id, course, teacher, topic, starts_at, ends_at
65+ FROM course_session WHERE id = $1"#,
66+ id,
67+ )
68+ .fetch_optional(db)
69+ .await?;
70+ Ok(session)
5471 }
5572
5673 /// A course's sessions, most recent lesson first. Ordered by `starts_at`
@@ -63,11 +80,11 @@ pub async fn list_for_course(
6380 offset: i64,
6481 ) -> Result<(Vec<CourseSession>, i64), AppError> {
6582 PagedList::new(
66- "course_session WHERE course = $course",
83+ "course_session WHERE course = $1",
6784 "ORDER BY starts_at DESC, id DESC",
6885 )
69- .bind("course", course.record())
70- .run(limit, offset, db)
86+ .bind(course.uuid())
87+ .run::<CourseSession>(limit, offset, db)
7188 .await
7289 }
7390
@@ -86,11 +103,17 @@ pub async fn update(
86103 starts_at: Option<Timestamp>,
87104 ends_at: Option<Option<Timestamp>>,
88105 ) -> Result<CourseSession, AppError> {
89- FieldUpdate::new(session.id.record())
90- .set("teacher", teacher.map(|teacher| teacher.record()))
91- .set("topic", topic)
92- .set("starts_at", starts_at)
93- .set("ends_at", ends_at)
106+ FieldUpdate::new(COURSE_SESSION_TABLE, session.id.uuid())
107+ .set(
108+ "teacher",
109+ teacher.map(|teacher| crate::db::page::Param::Uuid(teacher.uuid())),
110+ )
111+ .set("topic", topic.map(|topic| topic.as_str().to_owned()))
112+ .set("starts_at", starts_at.map(|at| at.as_millis()))
113+ .set(
114+ "ends_at",
115+ ends_at.map(|ends_at| crate::db::page::Param::OptI64(ends_at.map(|at| at.as_millis()))),
116+ )
94117 .ordered("starts_at", "ends_at", range_error())
95118 .run::<CourseSession>(db)
96119 .await
@@ -99,32 +122,31 @@ pub async fn update(
99122 /// Delete the session and cascade-remove its roll-call rows, in one
100123 /// transaction: as two unbatched queries a failure between them stranded
101124 /// roll-call rows on a session that was already gone. The other half of
102-/// that invariant is [`crate::db::session_attendance::mark`],
103-/// which proves the session still exists inside its own write — a
104-/// transaction here cannot stop a mark that commits *after* this one.
125+/// that invariant is [`crate::db::session_attendance::mark`], whose
126+/// session-row lock makes a mark and this delete take turns — a mark
127+/// committing after this cascade cannot name a session that is gone.
105128 pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSession, AppError> {
106- let (mut result, mut errors) = transaction_with_retry(
107- db,
108- "BEGIN TRANSACTION;
109- DELETE session_attendance WHERE session = $s;
110- LET $before = (DELETE $s RETURN BEFORE);
111- RETURN $before;
112- COMMIT TRANSACTION;",
113- &[("s".into(), session.id.record().into_value())],
114- // No THROW of its own — an unconditional cascade, so the only
115- // error worth telling apart is a lost round (see
116- // [`crate::db::exam::delete`]).
117- &[],
118- )
119- .await?;
120- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
121- return Err(error.into());
122- }
123- // Read through the trailing `RETURN`, never a hand-counted slot.
124- let slot = result.num_statements().saturating_sub(2);
125- let deleted: Option<CourseSession> =
126- result.take::<Vec<CourseSession>>(slot)?.into_iter().next();
127- deleted.ok_or(AppError::NotFound)
129+ tx_with_retry(db, false, async |tx| {
130+ // Roll-call rows first: the session row's own FK would refuse the
131+ // delete while they exist. An empty first sweep is fine — the
132+ // session may simply have had none.
133+ sqlx::query!(
134+ r#"DELETE FROM session_attendance WHERE session = $1"#,
135+ session.id,
136+ )
137+ .execute(&mut *tx)
138+ .await?;
139+ let deleted = sqlx::query_as!(
140+ CourseSession,
141+ r#"DELETE FROM course_session WHERE id = $1
142+ RETURNING id, course, teacher, topic, starts_at, ends_at"#,
143+ session.id,
144+ )
145+ .fetch_optional(&mut *tx)
146+ .await?;
147+ deleted.ok_or(AppError::NotFound)
148+ })
149+ .await
128150 }
129151
130152 #[cfg(test)]
src/db/dietary_profile.rsmodified+47 -44
@@ -1,20 +1,28 @@
1-//! The `dietary_profile` table: one row per student (the record key *is*
2-//! the student's key), created on first write and afterwards patched
3-//! field-by-field. The tag/note newtypes and the pure tag intersection live
4-//! in [`crate::domain::dietary_profile`]; the web layer reads through
1+//! The `dietary_profile` table: one row per student (the primary key *is*
2+//! the student), created on first write and afterwards patched
3+//! field-by-field — both by one `INSERT … ON CONFLICT DO UPDATE`. The
4+//! tag/note newtypes and the pure tag intersection live in
5+//! [`crate::domain::dietary_profile`]; the web layer reads through
56 //! [`crate::service::dietary_profile`].
67
78 use crate::database::Database;
8-use crate::db::field_update::FieldUpdate;
9-use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryProfileId, DietaryTags};
9+use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryTags};
1010 use crate::domain::timestamp::Timestamp;
1111 use crate::domain::user::UserId;
1212 use crate::error::AppError;
1313
1414 /// One student's profile, or `None` while the school never recorded one.
15-/// A single `SELECT` by record id — this is what a menu read joins on.
15+/// A single `SELECT` by key — this is what a menu read joins on.
1616 pub async fn read(db: &Database, student: &UserId) -> Result<Option<DietaryProfile>, AppError> {
17- Ok(db.select(DietaryProfileId::of(student).record()).await?)
17+ let row = sqlx::query_as!(
18+ DietaryProfile,
19+ "SELECT student, tags, note, updated_by, updated_at
20+ FROM dietary_profile WHERE student = $1",
21+ *student,
22+ )
23+ .fetch_optional(db)
24+ .await?;
25+ Ok(row)
1826 }
1927
2028 /// 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<Vec<String>, App
2735 }
2836
2937 /// Write the fields the PATCH carried. Creates the row on first write;
30-/// afterwards only the named fields move, because `student` is `READONLY`
31-/// and a whole-row save would also revert a concurrent edit of the other
32-/// field (see [`FieldUpdate`]).
38+/// afterwards only the named fields move, because a whole-row save would
39+/// also revert a concurrent edit of the other field.
40+///
41+/// Both paths are one statement: an absent `tags` keeps the stored list
42+/// (`COALESCE`), an absent `note` keeps the stored one, a `Some(None)` note
43+/// clears it and a `Some(Some)` overwrites it — the same three-way shape,
44+/// spelled with a "was the field on the request?" flag plus its nullable
45+/// value. A rival `PATCH` that created the row a moment ago turns this
46+/// call's `INSERT` into the `DO UPDATE` arm: a plain field write after all,
47+/// exactly as it would have been a moment later — without the error the old
48+/// store's create-then-patch pair had to catch.
3349 pub async fn save(
3450 db: &Database,
3551 student: &UserId,
@@ -37,37 +53,24 @@ pub async fn save(
3753 note: Option<Option<DietaryNote>>,
3854 by: &UserId,
3955 ) -> Result<DietaryProfile, AppError> {
40- if read(db, student).await?.is_none() {
41- let profile = DietaryProfile {
42- id: DietaryProfileId::of(student),
43- student: student.clone(),
44- tags: tags.clone().unwrap_or(DietaryTags(Vec::new())),
45- note: note.clone().flatten(),
46- updated_by: by.clone(),
47- updated_at: Timestamp::now(),
48- };
49- match db.create(profile.id.record()).content(profile).await {
50- Ok(Some(created)) => return Ok(created),
51- Ok(None) => {
52- return Err(AppError::Internal("failed to save the profile".into()));
53- }
54- // A rival first `PATCH` created the row in the round trip since
55- // the read above (the `dietary_profile_student` UNIQUE index
56- // catches the same collision), and `CREATE` leaves that row
57- // untouched — so this call is a plain field write after all,
58- // exactly as it would have been a moment later. Propagated, it
59- // was a 500 on a legitimate request. Same shape as
60- // [`crate::db::meal_ledger::append`], which
61- // reads the winner back rather than failing.
62- Err(err) if err.is_already_exists() => {}
63- Err(err) => return Err(err.into()),
64- }
65- }
66- FieldUpdate::new(DietaryProfileId::of(student).record())
67- .set("tags", tags)
68- .set("note", note)
69- .set("updated_by", Some(by.clone()))
70- .set("updated_at", Some(Timestamp::now()))
71- .run::<DietaryProfile>(db)
72- .await
56+ let row = sqlx::query_as!(
57+ DietaryProfile,
58+ "INSERT INTO dietary_profile (student, tags, note, updated_by, updated_at)
59+ VALUES ($1, COALESCE($2, '{}'::text[]), $3, $4, $5)
60+ ON CONFLICT (student) DO UPDATE SET
61+ tags = COALESCE($2, dietary_profile.tags),
62+ note = CASE WHEN $6 THEN $3 ELSE dietary_profile.note END,
63+ updated_by = $4,
64+ updated_at = $5
65+ RETURNING student, tags, note, updated_by, updated_at",
66+ *student,
67+ tags.map(|t| t.as_slice().to_vec()),
68+ note.clone().flatten().map(|n| n.as_str().to_string()),
69+ *by,
70+ Timestamp::now(),
71+ note.is_some(),
72+ )
73+ .fetch_one(db)
74+ .await?;
75+ Ok(row)
7376 }
src/db/enrollment.rsmodified+170 -170
@@ -1,49 +1,55 @@
11 //! The `enrollment` table: the roster read and listing, the seat-returning
2-//! delete, and the enroll claim — the one transaction that checks the pair
3-//! free, the member still a student, and the roster under capacity while it
2+//! delete, and the enroll claim — one transaction that checks the pair free,
3+//! the member still a student, and the roster under capacity while it
44 //! spends the seat. The target-user gates the HTTP handlers pay live in
55 //! [`crate::service::enrollment`].
66
7-use surrealdb::types::SurrealValue;
8-
9-use crate::constant::ENROLLMENT_COUNT_FIELD;
10-use crate::database::{Database, transaction_with_retry};
7+use crate::database::{Database, tx_with_retry, unique_violation};
118 use crate::db::cap;
129 use crate::db::page::PagedList;
1310 use crate::domain::course::CourseId;
14-use crate::domain::enrollment::{Enrollment, EnrollmentId};
11+use crate::domain::enrollment::Enrollment;
1512 use crate::domain::role::Role;
1613 use crate::domain::user::UserId;
1714 use crate::error::{AppError, ValidationError};
1815
19-/// The `THROW` markers [`enroll`]'s claim aborts with: this pair
20-/// already holds a row, the roster is full, and the person being enrolled is no
21-/// longer a student.
22-const HELD_MARK: &str = "enroll_held";
23-const FULL_MARK: &str = "enroll_full";
24-const UNFIT_MARK: &str = "enroll_not_student";
16+/// What [`enroll`]'s transaction settled on — the three old `THROW` markers
17+/// (`enroll_held`, `enroll_not_student`, `enroll_full`) as Rust verdicts.
18+enum Verdict {
19+ /// This pair already holds a row.
20+ Held,
21+ /// The person being enrolled is no longer a student.
22+ Unfit,
23+ /// The roster is full — or the course is gone; the caller reads which.
24+ Full,
25+ /// The seat is spent and the row is written.
26+ Made(Enrollment),
27+}
28+
29+/// The primary key the natural composite PK carries — the constraint name
30+/// that surfaces in SQLSTATE 23505 when a rival lands first.
31+const PAIR_CONSTRAINT: &str = "enrollment_course_user";
2532
26-/// Enroll (idempotently) `user` into `course`. One row per (course, user),
27-/// keyed by a deterministic composite id, so concurrent enrolls of the same
28-/// pair converge on one row instead of racing the unique index into a 500:
29-/// the loser of the `CREATE` reads the winner's row back and returns it.
30-/// When the course carries a capacity, a full roster refuses new members
31-/// (409) — the seat is taken by a single-record conditional write on the
32-/// course row whose bound is the row's *own* `capacity` column, read inside
33-/// the same statement that spends the seat. A snapshot integer taken by a
34-/// read beforehand would be exactly the number a concurrent capacity PATCH
35-/// invalidates, which is what this promised and did not do. An already
36-/// enrolled user is returned as-is even when the roster is full, and never
37-/// charged a seat. The same claim is the delete guard's other half: it
38-/// matches nothing once the course row is gone, and while it holds a seat
39-/// the course cannot be deleted — so no roster row can outlive its course.
33+/// Enroll (idempotently) `user` into `course`. The table's primary key *is*
34+/// the (course, user) pair, so concurrent enrolls of the same pair converge
35+/// on one row instead of racing into a 500: the loser reads the winner's row
36+/// back and returns it. When the course carries a capacity, a full roster
37+/// refuses new members (409) — the seat is taken by a single-record
38+/// conditional write on the course row whose bound is the row's *own*
39+/// `capacity` column, read inside the same statement that spends the seat. A
40+/// snapshot integer taken by a read beforehand would be exactly the number a
41+/// concurrent capacity PATCH invalidates. An already enrolled user is
42+/// returned as-is even when the roster is full, and never charged a seat.
43+/// The same claim is the delete guard's other half: it matches nothing once
44+/// the course row is gone, and while it holds a seat the course cannot be
45+/// deleted — so no roster row can outlive its course.
4046 ///
41-/// On admissibility ([`crate::database::transaction_with_retry`]): the
42-/// `CREATE` here *can* answer "already exists", but only to a rival that
43-/// landed inside this very window — and the re-send then sees that row at
44-/// the `$held` gate and takes the other branch, so the loop converges
45-/// instead of re-asking a settled question. Same shape, same reason, as
46-/// [`crate::db::class_pump::attach`].
47+/// Gate order is the old THROW order: an existing pair outranks the role
48+/// check, which outranks a full roster. The role check takes the user row
49+/// `FOR NO KEY UPDATE`, the same row a demotion cascade updates before its
50+/// sweep, so grant and demotion serialize on the row lock in both
51+/// directions — a row landing after the sweep is impossible, and a demotion
52+/// landing before this check refuses it.
4753 pub async fn enroll(
4854 db: &Database,
4955 course: &CourseId,
@@ -53,112 +59,89 @@ pub async fn enroll(
5359 if let Some(existing) = read_for_user(db, course, user).await? {
5460 return disown_if_pumped(db, existing).await;
5561 }
56- let enrollment = Enrollment {
57- id: EnrollmentId::composite(course, user),
58- course: course.clone(),
59- user: user.clone(),
60- enrolled_by: enrolled_by.clone(),
61- // Hand-placed: no source key at all is written, which is what makes
62- // a class sweep unable to take this row back.
63- source: None,
62+ let verdict = tx_with_retry(db, false, async |tx| {
63+ // The duplicate gate rides ahead of the role check, so "you are
64+ // already in" still outranks everything.
65+ let held = sqlx::query!(
66+ r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#,
67+ course,
68+ user,
69+ )
70+ .fetch_optional(&mut *tx)
71+ .await?;
72+ if held.is_some() {
73+ return Ok(Verdict::Held);
74+ }
75+ // The role handshake: the live role decides, and the row lock makes
76+ // the check and the insert one decision against a concurrent
77+ // demotion (see the doc above).
78+ let role = sqlx::query!(
79+ r#"SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#,
80+ user,
81+ )
82+ .fetch_optional(&mut *tx)
83+ .await?;
84+ if role.map(|row| row.role).as_deref() != Some(Role::Student.as_str()) {
85+ return Ok(Verdict::Unfit);
86+ }
87+ // The seat and the row in one statement (the cap recipe): a refused
88+ // insert takes its own seat bump back; zero rows means the roster is
89+ // full or the course is gone — only the caller pays for the read
90+ // that tells those apart.
91+ let row = sqlx::query_as!(
92+ Enrollment,
93+ r#"WITH seat AS (
94+ UPDATE course
95+ SET enrollment_count = enrollment_count + 1
96+ WHERE id = $1
97+ AND enrollment_count < COALESCE(capacity, $2)
98+ RETURNING 1)
99+ INSERT INTO enrollment (course, app_user, enrolled_by, source)
100+ SELECT $1, $3, $4, NULL WHERE EXISTS (SELECT 1 FROM seat)
101+ RETURNING course, app_user AS "user", enrolled_by, source"#,
102+ course,
103+ cap::UNLIMITED,
104+ user,
105+ enrolled_by,
106+ )
107+ .fetch_optional(&mut *tx)
108+ .await?;
109+ match row {
110+ Some(row) => Ok(Verdict::Made(row)),
111+ None => Ok(Verdict::Full),
112+ }
113+ })
114+ .await;
115+ // The 23505 backstop folds into the Held verdict before the mapping:
116+ // someone placed this pair between the gate and the insert, and their
117+ // row is the answer — no seat was spent finding that out.
118+ let verdict = match verdict {
119+ Err(AppError::Db(err)) if unique_violation(&err) == Some(PAIR_CONSTRAINT) => {
120+ Ok(Verdict::Held)
121+ }
122+ other => other,
64123 };
65- // CREATE, not UPSERT, and in the seat's own transaction: a duplicate has
66- // to be *seen*, or the pair's second writer would keep the seat it
67- // claimed for a row that already existed and the counter would drift
68- // above the roster forever.
69- //
70- // Parenthesized `??` throughout: `n ?? 0 < cap` parses as
71- // `n ?? (0 < cap)`, which is truthy for every row and would enroll past
72- // the capacity.
73- //
74- // The seat is claimed on the *course*, so the student's own row is
75- // claimed beside it ([`cap::role_claim`]): a demotion's sweep runs on a
76- // snapshot, and a row landing after it would count a seat for someone
77- // who may not hold one, with nothing left to re-sweep. It rides between
78- // the duplicate gate and the seat, so "you are already in" still
79- // outranks it and it outranks a full roster.
80- let held_by = cap::role_claim(
81- "usr",
82- &format!("!= '{}'", Role::Student.as_str()),
83- UNFIT_MARK,
84- );
85- let hold = held_by.join(";\n ");
86- let sql = format!(
87- "BEGIN TRANSACTION;
88- LET $held = (SELECT VALUE id FROM $id);
89- IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }};
90- {hold};
91- LET $seat = (UPDATE $course SET {ENROLLMENT_COUNT_FIELD} = \
92- ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 \
93- WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) < (capacity ?? $unlimited) \
94- RETURN VALUE id);
95- IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }};
96- CREATE $id CONTENT $row;
97- COMMIT TRANSACTION;"
98- );
99- // The process still sends its counter writes one at a time (see
100- // [`cap::counter_lock`]); this statement moves the same counter every
101- // cap claim does.
102- let _guard = cap::counter_lock().await;
103- let (mut result, mut errors) = transaction_with_retry(
104- db,
105- &sql,
106- &[
107- ("id".into(), enrollment.id.record().into_value()),
108- ("row".into(), enrollment.clone().into_value()),
109- ("course".into(), course.record().into_value()),
110- ("usr".into(), user.record().into_value()),
111- ("unlimited".into(), cap::UNLIMITED.into_value()),
112- ],
113- &[HELD_MARK, FULL_MARK, UNFIT_MARK],
114- )
115- .await?;
116- // Someone placed this pair first; their row is the answer, and no seat
117- // was spent finding that out. It is read first: it outranks the refusal
118- // below, and the gate aborts before the seat is touched.
119- if errors
120- .values()
121- .any(|error| error.to_string().contains(HELD_MARK))
122- {
123- return match read_for_user(db, course, user).await? {
124+ match verdict {
125+ Ok(Verdict::Made(row)) => Ok(row),
126+ Ok(Verdict::Held) => match read_for_user(db, course, user).await? {
124127 Some(existing) => disown_if_pumped(db, existing).await,
125128 None => Err(AppError::Internal("failed to enroll user".into())),
126- };
127- }
128- // Demoted while this ran: the same refusal the service's own gate makes
129- // a moment earlier, and the only one that can arrive after it.
130- if errors
131- .values()
132- .any(|error| error.to_string().contains(UNFIT_MARK))
133- {
134- return Err(AppError::Validation(ValidationError::Invalid {
129+ },
130+ // Demoted while this ran: the same refusal the service's own gate
131+ // makes a moment earlier, and the only one that can arrive after it.
132+ Ok(Verdict::Unfit) => Err(AppError::Validation(ValidationError::Invalid {
135133 field: "user_id",
136134 reason: "only students can be enrolled in a course",
137- }));
138- }
139- // Full, or the course is gone — the conditional write matches nothing
140- // either way, and only this path pays for the read that tells them
141- // apart.
142- if errors
143- .values()
144- .any(|error| error.to_string().contains(FULL_MARK))
145- {
146- return match crate::db::course::read(db, course).await? {
135+ })),
136+ // Full, or the course is gone — the conditional write matches
137+ // nothing either way, and only this path pays for the read that
138+ // tells them apart.
139+ Ok(Verdict::Full) => match crate::db::course::read(db, course).await? {
147140 Some(_) => Err(AppError::Conflict("the course is full")),
148141 None => Err(AppError::NotFound),
149- };
150- }
151- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
152- return Err(error.into());
142+ },
143+ Err(err) => Err(err),
153144 }
154- // Slots count BEGIN, two LETs and two IFs, plus the holder claim's own
155- // statements — counted, not tallied by hand, so a statement added there
156- // cannot read back the wrong result.
157- result
158- .take::<Vec<Enrollment>>(5 + held_by.len())?
159- .into_iter()
160- .next()
161- .ok_or_else(|| AppError::Internal("failed to enroll user".into()))
162145 }
163146
164147 /// A hand enroll landing on a row a class pumped takes the row *off* the
@@ -167,28 +150,30 @@ pub async fn enroll(
167150 /// holds in the other direction — a manual unenroll wins, permanently — and
168151 /// without it "hand-placed" was a state only a first enroll could reach.
169152 ///
170-/// `UNSET`, not `= NONE`: absence *is* the meaning of this column (see the
171-/// struct doc), and it is what a hand enroll writes on the create path.
153+/// `NULL`, not absence: the column is a nullable uuid whose NULL *is* the
154+/// meaning a missing key used to carry (see the struct doc), and it is what
155+/// a hand enroll writes on the create path too.
172156 async fn disown_if_pumped(db: &Database, existing: Enrollment) -> Result<Enrollment, AppError> {
173- if existing.source.is_none() {
157+ if existing.get_source().is_none() {
174158 return Ok(existing);
175159 }
176- let mut result = db
177- .query("UPDATE $id UNSET source RETURN AFTER")
178- .bind(("id", existing.id.record()))
179- .await?
180- .check()?;
160+ let disowned = sqlx::query_as!(
161+ Enrollment,
162+ r#"UPDATE enrollment SET source = NULL
163+ WHERE course = $1 AND app_user = $2
164+ RETURNING course, app_user AS "user", enrolled_by, source"#,
165+ existing.get_course(),
166+ existing.get_user(),
167+ )
168+ .fetch_optional(db)
169+ .await?;
181170 // A row that is no longer there is not an internal error: an unenroll
182171 // (or the class sweep a role change runs) landing between the read
183172 // above and this write matches nothing, and the caller asked to be
184173 // enrolled — which they were, by the row this call was handed. The
185174 // disown is all that is lost, and it is lost to a delete that took the
186175 // whole row with it.
187- Ok(result
188- .take::<Vec<Enrollment>>(0)?
189- .into_iter()
190- .next()
191- .unwrap_or(existing))
176+ Ok(disowned.unwrap_or(existing))
192177 }
193178
194179 /// Some(_) iff `user` is enrolled in `course` — the grading gate.
@@ -197,13 +182,16 @@ pub async fn read_for_user(
197182 course: &CourseId,
198183 user: &UserId,
199184 ) -> Result<Option<Enrollment>, AppError> {
200- let mut result = db
201- .query("SELECT * FROM enrollment WHERE course = $course AND user = $usr LIMIT 1")
202- .bind(("course", course.record()))
203- .bind(("usr", user.record()))
204- .await?
205- .check()?;
206- Ok(result.take::<Vec<Enrollment>>(0)?.into_iter().next())
185+ let row = sqlx::query_as!(
186+ Enrollment,
187+ r#"SELECT course, app_user AS "user", enrolled_by, source
188+ FROM enrollment WHERE course = $1 AND app_user = $2"#,
189+ course,
190+ user,
191+ )
192+ .fetch_optional(db)
193+ .await?;
194+ Ok(row)
207195 }
208196
209197 pub async fn list_for_course(
@@ -212,32 +200,44 @@ pub async fn list_for_course(
212200 limit: Option<i64>,
213201 offset: i64,
214202 ) -> Result<(Vec<Enrollment>, i64), AppError> {
215- PagedList::new("enrollment WHERE course = $course", "ORDER BY id DESC")
216- .bind("course", course.record())
217- .run(limit, offset, db)
218- .await
203+ // The old composite key `{course}_{user}` sorted by user within a
204+ // course — its course prefix was constant — so the natural-PK columns
205+ // sort the same way.
206+ PagedList::new(
207+ "enrollment WHERE course = $1",
208+ "ORDER BY course DESC, app_user DESC",
209+ )
210+ .bind(course.uuid())
211+ .run::<Enrollment>(limit, offset, db)
212+ .await
219213 }
220214
215+/// Take the row and give its seat back in one statement, so nothing but a
216+/// lost transaction can drift the counter. `None` when the pair held no row.
221217 pub async fn remove(
222218 db: &Database,
223219 course: &CourseId,
224220 user: &UserId,
225221 ) -> Result<Option<Enrollment>, AppError> {
226- // The seat comes back in the same transaction as the row that held it,
227- // so nothing but a lost transaction can drift the counter.
228- let mut result = db
229- .query(
230- "BEGIN TRANSACTION;
231- LET $gone = (DELETE enrollment WHERE course = $course AND user = $usr RETURN BEFORE);
232- UPDATE $course SET enrollment_count = math::max([(enrollment_count ?? 0) - array::len($gone), 0]);
233- RETURN $gone;
234- COMMIT TRANSACTION;",
235- )
236- .bind(("course", course.record()))
237- .bind(("usr", user.record()))
238- .await?
239- .check()?;
240- Ok(result.take::<Vec<Enrollment>>(3)?.into_iter().next())
222+ let gone = sqlx::query_as!(
223+ Enrollment,
224+ r#"WITH gone AS (
225+ DELETE FROM enrollment
226+ WHERE course = $1 AND app_user = $2
227+ RETURNING course, app_user, enrolled_by, source),
228+ seated AS (
229+ UPDATE course
230+ SET enrollment_count = GREATEST(
231+ enrollment_count - (SELECT count(*) FROM gone), 0)
232+ WHERE id = $1
233+ RETURNING 1)
234+ SELECT course, app_user AS "user", enrolled_by, source FROM gone"#,
235+ course,
236+ user,
237+ )
238+ .fetch_optional(db)
239+ .await?;
240+ Ok(gone)
241241 }
242242
243243 #[cfg(test)]
src/db/homework.rsmodified+403 -139
@@ -1,25 +1,22 @@
1-//! The `homework` table: row reads and listings, the count-and-create that
2-//! pins a homework to a live subject row, the reference-counting PATCH, and
3-//! the cascading delete. The PATCH's orphan guard and the audience gate live
4-//! in [`crate::service::homework`].
1+//! The `homework` table: row reads and listings, the subject-counter claim
2+//! that pins a homework to a live subject row, the reference-counting PATCH —
3+//! whose audience-narrowing orphan guard is one transaction with the write,
4+//! serialized on the homework row's `FOR UPDATE` lock — and the cascading
5+//! delete.
56
6-use surrealdb::types::RecordId;
7-
8-use crate::constant::SUBJECT_HOMEWORK_COUNT_FIELD;
9-use crate::database::Database;
10-use crate::db::cap;
11-use crate::db::field_update::FieldUpdate;
7+use crate::database::{Database, tx_with_retry};
128 use crate::domain::course::CourseId;
139 use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};
1410 use crate::domain::subject::SubjectId;
1511 use crate::domain::timestamp::Timestamp;
1612 use crate::domain::user::UserId;
1713 use crate::error::{AppError, ValidationError};
14+use sqlx::PgConnection;
1815
1916 /// The answer a link to a subject that is not there gets, on create and on
20-/// re-tag alike — both claims are conditional writes on the subject row, so a
21-/// subject a delete already removed matches nothing and the caller says exactly
22-/// what the web layer's pre-flight lookup would have.
17+/// re-tag alike — the conditional claim on the subject row matches nothing,
18+/// and the caller says exactly what the web layer's pre-flight lookup would
19+/// have.
2320 fn subject_gone() -> AppError {
2421 AppError::Validation(ValidationError::Invalid {
2522 field: "subject_id",
@@ -27,6 +24,12 @@ fn subject_gone() -> AppError {
2724 })
2825 }
2926
27+/// What a stale re-tag answers. The shared PATCH builder
28+/// ([`crate::db::field_update`]) carries the same refusal; the homework PATCH
29+/// keeps its own copy because its orphan guard needs the row lock the generic
30+/// builder cannot take.
31+const STALE_MOVE: &str = "the link this update moves changed since it was read; re-read and retry";
32+
3033 #[expect(
3134 clippy::too_many_arguments,
3235 reason = "mirrors the sibling entities' create(field, field, ..) shape"
@@ -41,16 +44,14 @@ pub async fn create(
4144 assigned: Option<Vec<UserId>>,
4245 created_by: &UserId,
4346 ) -> Result<Homework, AppError> {
44- // The subject's reference is taken in the very transaction that writes
45- // the row — the exam question's twin
46- // ([`crate::db::exam_question`]): the subject delete
47- // is refused while this counter is non-zero, so the create and the
48- // delete contend on the subject record rather than on a cross-table
49- // count neither of them sees the other move, and a crash can no longer
50- // strand a claim that would make the subject undeletable forever. A
51- // refused claim means the subject is already gone, which is the 400 the
52- // web layer's pre-flight check answers with.
53- let counted = subject.record();
47+ // The subject's reference is taken in the very statement that writes the
48+ // row — the exam question's twin ([`crate::db::exam_question`]): the
49+ // claim (`UPDATE subject … +1`) and the insert are one CTE, so a subject
50+ // a delete already removed matches nothing and nothing is written, which
51+ // is the 400 the web layer's pre-flight check answers with. The subject
52+ // delete is refused while this counter is non-zero, so the two writers
53+ // contend on the subject row itself, and a crash cannot strand a claim
54+ // that would make the subject undeletable forever.
5455 let homework = Homework {
5556 id: HomeworkId::generate(),
5657 course: course.clone(),
@@ -62,46 +63,111 @@ pub async fn create(
6263 created_by: created_by.clone(),
6364 created_at: Timestamp::now(),
6465 };
65- let id = homework.id.record();
66- match cap::claim_and_create(
67- &counted,
68- SUBJECT_HOMEWORK_COUNT_FIELD,
69- cap::UNLIMITED,
70- &id,
71- &homework,
72- db,
66+ let assigned_values = homework.assigned.clone().unwrap_or_default();
67+ // The fresh v7 id cannot collide, so the pair-unique answer has no rival
68+ // here; the mapping is kept for symmetry with the other claim sites.
69+ let created = sqlx::query_as!(
70+ Homework,
71+ r#"WITH seat AS (
72+ UPDATE subject SET homework_count = homework_count + 1
73+ WHERE id = $1
74+ RETURNING 1
75+ )
76+ INSERT INTO homework (id, course, subject, title, description, due_at, assigned, created_by, created_at)
77+ SELECT $2, $3, $1, $4, $5, $6, $7, $8, $9 WHERE EXISTS (SELECT 1 FROM seat)
78+ RETURNING id AS "id: HomeworkId",
79+ course AS "course: CourseId",
80+ subject AS "subject: SubjectId",
81+ title AS "title: HomeworkTitle",
82+ description AS "description: Option<HomeworkDescription>",
83+ due_at AS "due_at: Timestamp",
84+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
85+ AS "assigned: Option<Vec<UserId>>",
86+ created_by AS "created_by: UserId",
87+ created_at AS "created_at: Timestamp""#,
88+ subject,
89+ homework.id,
90+ course,
91+ homework.title,
92+ homework.description,
93+ homework.due_at,
94+ assigned_values,
95+ homework.created_by,
96+ homework.created_at,
7397 )
74- .await?
75- {
76- cap::Claimed::Made(created) => Ok(created),
77- cap::Claimed::Full => Err(subject_gone()),
78- cap::Claimed::Duplicate => Err(AppError::Internal("failed to create homework".into())),
79- }
98+ .fetch_optional(db)
99+ .await
100+ .map_err(|err| {
101+ if crate::database::unique_violation(&err).is_some() {
102+ AppError::Internal("failed to create homework".into())
103+ } else {
104+ AppError::from(err)
105+ }
106+ })?;
107+ created.ok_or_else(subject_gone)
80108 }
81109
82110 pub async fn read(db: &Database, id: &HomeworkId) -> Result<Option<Homework>, AppError> {
83- Ok(db.select(id.record()).await?)
111+ Ok(sqlx::query_as!(
112+ Homework,
113+ r#"SELECT id AS "id: HomeworkId",
114+ course AS "course: CourseId",
115+ subject AS "subject: SubjectId",
116+ title AS "title: HomeworkTitle",
117+ description AS "description: Option<HomeworkDescription>",
118+ due_at AS "due_at: Timestamp",
119+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
120+ AS "assigned: Option<Vec<UserId>>",
121+ created_by AS "created_by: UserId",
122+ created_at AS "created_at: Timestamp"
123+ FROM homework WHERE id = $1"#,
124+ id
125+ )
126+ .fetch_optional(db)
127+ .await?)
84128 }
85129
86-/// The course's homework, newest first (ULID ids sort by creation). The web
130+/// The course's homework, newest first (v7 ids sort by creation). The web
87131 /// layer retains only the rows a given student `student_sees`.
88132 pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Homework>, AppError> {
89- let mut result = db
90- .query("SELECT * FROM homework WHERE course = $course ORDER BY id DESC")
91- .bind(("course", course.record()))
92- .await?
93- .check()?;
94- Ok(result.take::<Vec<Homework>>(0)?)
133+ Ok(sqlx::query_as!(
134+ Homework,
135+ r#"SELECT id AS "id: HomeworkId",
136+ course AS "course: CourseId",
137+ subject AS "subject: SubjectId",
138+ title AS "title: HomeworkTitle",
139+ description AS "description: Option<HomeworkDescription>",
140+ due_at AS "due_at: Timestamp",
141+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
142+ AS "assigned: Option<Vec<UserId>>",
143+ created_by AS "created_by: UserId",
144+ created_at AS "created_at: Timestamp"
145+ FROM homework WHERE course = $1 ORDER BY id DESC"#,
146+ course
147+ )
148+ .fetch_all(db)
149+ .await?)
95150 }
96151
97152 /// Every homework in the system, newest first — the manager+ view of the
98153 /// cross-course "my homework" list.
99154 pub async fn list_all(db: &Database) -> Result<Vec<Homework>, AppError> {
100- let mut result = db
101- .query("SELECT * FROM homework ORDER BY id DESC")
102- .await?
103- .check()?;
104- Ok(result.take::<Vec<Homework>>(0)?)
155+ Ok(sqlx::query_as!(
156+ Homework,
157+ r#"SELECT id AS "id: HomeworkId",
158+ course AS "course: CourseId",
159+ subject AS "subject: SubjectId",
160+ title AS "title: HomeworkTitle",
161+ description AS "description: Option<HomeworkDescription>",
162+ due_at AS "due_at: Timestamp",
163+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
164+ AS "assigned: Option<Vec<UserId>>",
165+ created_by AS "created_by: UserId",
166+ created_at AS "created_at: Timestamp"
167+ FROM homework ORDER BY id DESC"#,
168+ )
169+ .fetch_all(db)
170+ .await?)
105171 }
106172
107173 /// Every homework of every course in `courses`, newest first (one query) —
@@ -115,51 +181,71 @@ pub async fn list_for_courses(
115181 if courses.is_empty() {
116182 return Ok(Vec::new());
117183 }
118- let records: Vec<RecordId> = courses.iter().map(CourseId::record).collect();
119- let mut result = db
120- .query("SELECT * FROM homework WHERE course IN $courses ORDER BY id DESC")
121- .bind(("courses", records))
122- .await?
123- .check()?;
124- Ok(result.take::<Vec<Homework>>(0)?)
184+ let ids: Vec<CourseId> = courses.to_vec();
185+ Ok(sqlx::query_as!(
186+ Homework,
187+ r#"SELECT id AS "id: HomeworkId",
188+ course AS "course: CourseId",
189+ subject AS "subject: SubjectId",
190+ title AS "title: HomeworkTitle",
191+ description AS "description: Option<HomeworkDescription>",
192+ due_at AS "due_at: Timestamp",
193+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
194+ AS "assigned: Option<Vec<UserId>>",
195+ created_by AS "created_by: UserId",
196+ created_at AS "created_at: Timestamp"
197+ FROM homework WHERE course = ANY($1) ORDER BY id DESC"#,
198+ ids
199+ )
200+ .fetch_all(db)
201+ .await?)
125202 }
126203
127204 /// The homework of `course` that `user` is meant to see — whole-course ones
128205 /// plus any subset that names them — newest first. Backs a student's (or an
129206 /// observer's) per-course homework report; mirrors
130207 /// [`Homework::student_sees`](crate::domain::homework::Homework::student_sees)
131-/// in SurQL so the filter runs in the database.
208+/// in SQL so the filter runs in the database.
132209 pub async fn list_for_user_in_course(
133210 db: &Database,
134211 course: &CourseId,
135212 user: &UserId,
136213 ) -> Result<Vec<Homework>, AppError> {
137- let mut result = db
138- .query(
139- "SELECT * FROM homework
140- WHERE course = $course
141- AND (assigned = NONE OR assigned = [] OR $usr IN assigned)
142- ORDER BY id DESC",
143- )
144- .bind(("course", course.record()))
145- .bind(("usr", user.record()))
146- .await?
147- .check()?;
148- Ok(result.take::<Vec<Homework>>(0)?)
214+ Ok(sqlx::query_as!(
215+ Homework,
216+ r#"SELECT id AS "id: HomeworkId",
217+ course AS "course: CourseId",
218+ subject AS "subject: SubjectId",
219+ title AS "title: HomeworkTitle",
220+ description AS "description: Option<HomeworkDescription>",
221+ due_at AS "due_at: Timestamp",
222+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
223+ AS "assigned: Option<Vec<UserId>>",
224+ created_by AS "created_by: UserId",
225+ created_at AS "created_at: Timestamp"
226+ FROM homework
227+ WHERE course = $1 AND (cardinality(assigned) = 0 OR $2 = ANY(assigned))
228+ ORDER BY id DESC"#,
229+ course,
230+ user
231+ )
232+ .fetch_all(db)
233+ .await?)
149234 }
150235
151236 /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework.
152237 /// Request-scoped: every parameter is `Option`, `None` meaning the PATCH
153238 /// did not carry that field, so it is not written at all. Handing the
154239 /// snapshot's value back instead would revert a concurrent edit of that
155-/// field — scoping the `SET` alone does not prevent that, the *values* must
156-/// come from the request. `course`, `created_by`, and `created_at` are
157-/// `READONLY` and never appear in the write.
240+/// field — under the row lock below, an uncarried field keeps the value read
241+/// *under that lock*, never the handler's snapshot. `course`, `created_by`,
242+/// and `created_at` are readonly and never appear in the write.
158243 ///
159-/// `description` and `assigned` are nullable columns, so they take a
160-/// `NONE` (clear the description / widen back to the whole course). The web
161-/// layer has already re-checked a new `due_at` against now, a new `subject`
162-/// against the course, and refused a narrowing that would orphan work.
244+/// `description` takes `Some(None)` to clear; `assigned` takes `Some(None)`
245+/// to widen back to the whole course (stored as `'{}'`, read back as `None`).
246+/// The web layer has already re-checked a new `due_at` against now, a new
247+/// `subject` against the course, and — inside the transaction here — the
248+/// narrowing against the work that would be orphaned by it.
163249 pub async fn update(
164250 db: &Database,
165251 homework: Homework,
@@ -169,75 +255,250 @@ pub async fn update(
169255 due_at: Option<Timestamp>,
170256 assigned: Option<Option<Vec<UserId>>>,
171257 ) -> Result<Homework, AppError> {
172- let assigned = assigned
173- .map(|subset| subset.map(|users| users.iter().map(UserId::record).collect::<Vec<_>>()));
174- // A re-tag moves a reference: the new subject's claim and the old one's
175- // release ride the same transaction as the link write, so no crash can
176- // leave a count without its link (the subject would be undeletable
177- // forever) or a link without its count. `subject` is required, so the
178- // snapshot's value is always the CAS expectation — two PATCHes moving
179- // the same homework off the same subject would otherwise both claim
180- // their target, and the loser is refused with a 409 instead. The
181- // `.refcount` call is unconditional: the CAS is armed by the request
182- // *carrying* `subject_id`, not by a counter moving, so a PATCH that
183- // re-states the tag its snapshot showed — shifting no counter at all —
184- // is still refused when a rival moved the tag in between. A PATCH that
185- // carried no `subject_id` arms nothing and writes what it always did.
186- let (claim, release) = subject
187- .as_ref()
188- .filter(|next| **next != homework.subject)
189- .map(|next| (next.record(), homework.subject.record()))
190- .unzip();
191- FieldUpdate::new(homework.id.record())
192- .set("subject", subject.map(|subject| subject.record()))
193- .set("title", title)
194- .set("description", description)
195- .set("due_at", due_at)
196- .set("assigned", assigned)
197- .refcount(
198- SUBJECT_HOMEWORK_COUNT_FIELD,
199- "subject",
200- Some(homework.subject.record()),
201- claim,
202- release,
203- subject_gone(),
258+ tx_with_retry(db, false, async |tx| {
259+ // The homework row's lock. The orphan guard's reads and the write
260+ // below are one transaction with it, so a submission — whose own
261+ // transaction locks this very row before writing — cannot land
262+ // between the check and the narrowing, orphaned by an audience change
263+ // that just missed it. The lock also replaces the old CAS's row read:
264+ // the re-tag check below compares the handler's snapshot against the
265+ // row as it is *locked*, not as it was first read.
266+ let current = sqlx::query_as!(
267+ Homework,
268+ r#"SELECT id AS "id: HomeworkId",
269+ course AS "course: CourseId",
270+ subject AS "subject: SubjectId",
271+ title AS "title: HomeworkTitle",
272+ description AS "description: Option<HomeworkDescription>",
273+ due_at AS "due_at: Timestamp",
274+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
275+ AS "assigned: Option<Vec<UserId>>",
276+ created_by AS "created_by: UserId",
277+ created_at AS "created_at: Timestamp"
278+ FROM homework WHERE id = $1 FOR UPDATE"#,
279+ homework.get_id()
204280 )
205- .run::<Homework>(db)
206- .await
281+ .fetch_optional(&mut *tx)
282+ .await?
283+ .ok_or(AppError::NotFound)?;
284+
285+ // The orphan guard runs on exactly the requests that re-scope the
286+ // audience. An absent `assigned` writes nothing, so the stored subset
287+ // is untouched and no narrowing can happen behind the guard's back.
288+ if let Some(resolved) = assigned.as_ref() {
289+ ensure_no_orphans(&current, resolved.as_deref(), tx).await?;
290+ }
291+
292+ // A re-tag moves a reference: the new subject's claim and the old
293+ // one's release ride the same transaction as the link write, so no
294+ // crash can leave a count without its link (the subject would be
295+ // undeletable forever) or a link without its count. The release goes
296+ // first and the claim refuses on a gone row, so a move to a deleted
297+ // subject is a rolled-back no-op — every abort takes the whole move
298+ // back with it.
299+ let moving = subject.as_ref().filter(|next| **next != homework.subject);
300+ if let Some(next) = moving {
301+ sqlx::query!(
302+ "UPDATE subject SET homework_count = GREATEST(homework_count - 1, 0) WHERE id = $1",
303+ current.subject
304+ )
305+ .execute(&mut *tx)
306+ .await?;
307+ let seat = sqlx::query!(
308+ r#"UPDATE subject SET homework_count = homework_count + 1
309+ WHERE id = $1 RETURNING 1 AS "seat: i32""#,
310+ next
311+ )
312+ .fetch_optional(&mut *tx)
313+ .await?;
314+ if seat.is_none() {
315+ return Err(subject_gone());
316+ }
317+ }
318+
319+ // The stale-re-tag check. Armed by the request *carrying* the subject
320+ // — even when it re-states the tag its snapshot showed, shifting no
321+ // counter — so two PATCHes moving the same homework off the same
322+ // subject cannot both claim their target: the loser's snapshot says
323+ // A, the locked row says B, and the refusal is the 409 the generic
324+ // PATCH builder has always answered with.
325+ if subject.is_some() && current.subject != homework.subject {
326+ return Err(AppError::Conflict(STALE_MOVE.to_string()));
327+ }
328+
329+ // What the PATCH carried is written; what it did not carry keeps the
330+ // value just read under the lock. Under that lock this resolved
331+ // full-row write is exactly the request-scoped SET the old builder
332+ // emitted — except it is one static statement instead of a runtime
333+ // build.
334+ let new_subject = subject.clone().unwrap_or_else(|| current.subject.clone());
335+ let new_title = title.unwrap_or_else(|| current.title.clone());
336+ let new_description = match description {
337+ None => current.description.clone(),
338+ Some(None) => None,
339+ Some(Some(text)) => Some(text),
340+ };
341+ let new_due_at = due_at.unwrap_or(current.due_at);
342+ let new_assigned = match assigned {
343+ None => current.assigned.clone(),
344+ // Clear = the whole course, stored as `'{}'`.
345+ Some(None) => None,
346+ Some(Some(subset)) => Some(subset),
347+ };
348+ let assigned_values = new_assigned.unwrap_or_default();
349+ sqlx::query_as!(
350+ Homework,
351+ r#"UPDATE homework SET subject = $2, title = $3, description = $4,
352+ due_at = $5, assigned = $6
353+ WHERE id = $1
354+ RETURNING id AS "id: HomeworkId",
355+ course AS "course: CourseId",
356+ subject AS "subject: SubjectId",
357+ title AS "title: HomeworkTitle",
358+ description AS "description: Option<HomeworkDescription>",
359+ due_at AS "due_at: Timestamp",
360+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
361+ AS "assigned: Option<Vec<UserId>>",
362+ created_by AS "created_by: UserId",
363+ created_at AS "created_at: Timestamp""#,
364+ homework.get_id(),
365+ new_subject,
366+ new_title,
367+ new_description,
368+ new_due_at,
369+ assigned_values,
370+ )
371+ .fetch_optional(&mut *tx)
372+ .await?
373+ .ok_or(AppError::NotFound)
374+ })
375+ .await
376+}
377+
378+/// Refuse (409) a PATCH that would narrow `homework`'s audience so a student
379+/// who already submitted or was graded falls outside it — their work would be
380+/// stranded. `new_assigned` is the proposed subset (`None` = whole course, in
381+/// which case no one can be orphaned). The blocking students are named in the
382+/// message so the teacher knows whose work to clear (or whom to keep assigned)
383+/// first.
384+///
385+/// Runs inside the caller's transaction, under the homework row's lock, so
386+/// the check and the narrowing cannot be driven through by a submission.
387+async fn ensure_no_orphans(
388+ homework: &Homework,
389+ new_assigned: Option<&[UserId]>,
390+ tx: &mut PgConnection,
391+) -> Result<(), AppError> {
392+ // Whole-course covers everyone — no narrowing, no orphans.
393+ let Some(subset) = new_assigned else {
394+ return Ok(());
395+ };
396+ let submitted: Vec<UserId> = sqlx::query!(
397+ r#"SELECT app_user AS "user: UserId" FROM homework_submission WHERE homework = $1"#,
398+ homework.get_id()
399+ )
400+ .fetch_all(&mut *tx)
401+ .await?
402+ .into_iter()
403+ .map(|row| row.user)
404+ .collect();
405+ let graded: Vec<UserId> = sqlx::query!(
406+ r#"SELECT app_user AS "user: UserId" FROM homework_result WHERE homework = $1"#,
407+ homework.get_id()
408+ )
409+ .fetch_all(&mut *tx)
410+ .await?
411+ .into_iter()
412+ .map(|row| row.user)
413+ .collect();
414+ let mut blocked: Vec<String> = Vec::new();
415+ for user in submitted.iter().chain(graded.iter()) {
416+ let key = user.key().to_string();
417+ if !subset.contains(user) && !blocked.contains(&key) {
418+ blocked.push(key);
419+ }
420+ }
421+ if blocked.is_empty() {
422+ Ok(())
423+ } else {
424+ Err(AppError::ConflictOwned(format!(
425+ "narrowing the assigned list would orphan existing work by {} student(s): {}",
426+ blocked.len(),
427+ blocked.join(", ")
428+ )))
429+ }
207430 }
208431
209432 /// Delete the homework and cascade its submissions, their files, and its
210433 /// results — one transaction, so a crash can't orphan a submission under a
211434 /// vanished homework. The submission file *blobs* are the web layer's to
212-/// unlink: it collects their names via
213-/// [`crate::db::homework_file::file_keys_for_homework`]
214-/// before calling this, and removes them after the rows are gone.
215-pub async fn delete(db: &Database, homework: Homework) -> Result<Homework, AppError> {
216- let mut result = db
217- .query(
218- format!(
219- "BEGIN TRANSACTION;
220- DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw);
221- DELETE homework_submission WHERE homework = $hw;
222- DELETE homework_result WHERE homework = $hw;
223- LET $gone = (DELETE $hw RETURN BEFORE);
224- FOR $sub IN ($gone.subject ?? []) {{
225- UPDATE $sub SET {SUBJECT_HOMEWORK_COUNT_FIELD} =
226- math::max([({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) - 1, 0])
227- }};
228- RETURN $gone;
229- COMMIT TRANSACTION;"
230- ),
435+/// unlink: their names are returned (collected inside the transaction,
436+/// before the wipes — a file row inserted after an out-of-transaction
437+/// collection would be deleted here while its key was already gone from the
438+/// list, stranding the blob) and removed after the rows are gone.
439+pub async fn delete(
440+ db: &Database,
441+ homework: Homework,
442+) -> Result<(Homework, Vec<String>), AppError> {
443+ tx_with_retry(db, true, async |tx| {
444+ let blob_keys: Vec<String> = sqlx::query!(
445+ r#"SELECT file FROM homework_file
446+ WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#,
447+ homework.get_id()
231448 )
232- .bind(("hw", homework.id.record()))
449+ .fetch_all(&mut *tx)
233450 .await?
234- .check()?;
235- // The subject's reference is given back in this same transaction, off
236- // what the delete actually removed. Read through the trailing `RETURN`,
237- // not a hand-counted slot — see [`crate::db::exam::delete`].
238- let slot = result.num_statements().saturating_sub(2);
239- let deleted: Option<Homework> = result.take::<Vec<Homework>>(slot)?.into_iter().next();
240- deleted.ok_or(AppError::NotFound)
451+ .into_iter()
452+ .map(|row| row.file)
453+ .collect();
454+ sqlx::query!(
455+ r#"DELETE FROM homework_file
456+ WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#,
457+ homework.get_id()
458+ )
459+ .execute(&mut *tx)
460+ .await?;
461+ sqlx::query!(
462+ "DELETE FROM homework_result WHERE homework = $1",
463+ homework.get_id()
464+ )
465+ .execute(&mut *tx)
466+ .await?;
467+ sqlx::query!(
468+ "DELETE FROM homework_submission WHERE homework = $1",
469+ homework.get_id()
470+ )
471+ .execute(&mut *tx)
472+ .await?;
473+ let deleted = sqlx::query_as!(
474+ Homework,
475+ r#"DELETE FROM homework WHERE id = $1
476+ RETURNING id AS "id: HomeworkId",
477+ course AS "course: CourseId",
478+ subject AS "subject: SubjectId",
479+ title AS "title: HomeworkTitle",
480+ description AS "description: Option<HomeworkDescription>",
481+ due_at AS "due_at: Timestamp",
482+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
483+ AS "assigned: Option<Vec<UserId>>",
484+ created_by AS "created_by: UserId",
485+ created_at AS "created_at: Timestamp""#,
486+ homework.get_id()
487+ )
488+ .fetch_optional(&mut *tx)
489+ .await?
490+ .ok_or(AppError::NotFound)?;
491+ // The subject's reference is given back in this same transaction, off
492+ // the row the delete actually removed.
493+ sqlx::query!(
494+ "UPDATE subject SET homework_count = GREATEST(homework_count - 1, 0) WHERE id = $1",
495+ deleted.subject
496+ )
497+ .execute(&mut *tx)
498+ .await?;
499+ Ok((deleted, blob_keys))
500+ })
501+ .await
241502 }
242503
243504 #[cfg(test)]
@@ -360,7 +621,10 @@ mod tests {
360621 "the old subject is free"
361622 );
362623 assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not");
363- assert!(crate::db::subject::delete(&db, from).await.is_ok(), "no reference left");
624+ assert!(
625+ crate::db::subject::delete(&db, from).await.is_ok(),
626+ "no reference left"
627+ );
364628 assert!(
365629 crate::db::subject::delete(&db, to).await.is_err(),
366630 "the reference moved here refuses the delete"
src/db/homework_file.rsmodified+183 -133
@@ -4,56 +4,70 @@
44 //! their validated fields live in [`crate::domain::homework_file`]; the
55 //! upload workflow around them in [`crate::service::homework_file`].
66
7-use surrealdb::types::SurrealValue;
8-
9-use crate::constant::{
10- MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD, SUBMISSION_OPEN_GUARD,
11-};
12-use crate::database::{Database, transaction_with_retry};
13-use crate::db::cap;
7+use crate::constant::MAX_HOMEWORK_FILES_PER_SUBMISSION;
8+use crate::database::{Database, tx_with_retry};
149 use crate::domain::course::CourseId;
1510 use crate::domain::homework::HomeworkId;
1611 use crate::domain::homework_file::HomeworkFile;
12+use crate::domain::homework_file::HomeworkFileId;
13+use crate::domain::homework_submission::HomeworkSubmissionId;
14+use crate::domain::note_file::{FileContentType, FileName};
1715 use crate::domain::timestamp::Timestamp;
1816 use crate::error::AppError;
1917
20-/// What [`delete`]'s transaction reports: whether the submission
21-/// was still open (`open` = 1, the gate bit) and the row it then removed. Two
22-/// answers in one object because an empty `gone` alone cannot say whether the
23-/// delete was refused or the file had simply vanished.
24-#[derive(Debug, SurrealValue)]
25-struct DeleteOutcome {
26- open: i64,
27- gone: Vec<HomeworkFile>,
28-}
29-
3018 /// Persist the row assembled by
3119 /// [`HomeworkFile::new`](crate::domain::homework_file::HomeworkFile::new),
3220 /// refusing once its submission already holds
3321 /// [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`)
3422 /// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own
35-/// wording). Both are decided by one [`cap::claim_when_and_create`] on the
36-/// submission row — the seat and the file row commit together, so a crash
37-/// between them can no longer leave a slot claimed by a file that does not
38-/// exist, and a losing upload never has to be un-counted. Which of the two
39-/// conditions refused it is read back afterwards, off the losing path only,
40-/// and only to pick the message: `Claimed::Full` says "full *or* graded *or*
41-/// the submission is gone".
23+/// wording). Both are decided by one guarded insert on the submission row —
24+/// the seat (`UPDATE … file_count + 1 WHERE file_count < $cap AND
25+/// graded_by_result IS NULL`) and the file row commit together in one CTE, so
26+/// a crash between them can no longer leave a slot claimed by a file that
27+/// does not exist, and a losing upload never has to be un-counted. Which of
28+/// the two conditions refused it is read back afterwards, off the losing
29+/// path only, and only to pick the message: zero rows says "full *or* graded
30+/// *or* the submission is gone".
4231 pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> {
43- // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber
44- match cap::claim_when_and_create(
45- &file.submission.record(),
46- SUBMISSION_FILE_COUNT_FIELD,
32+ let created = sqlx::query_as!(
33+ HomeworkFile,
34+ r#"WITH seat AS (
35+ UPDATE homework_submission SET file_count = file_count + 1
36+ WHERE id = $2 AND file_count < $1 AND graded_by_result IS NULL
37+ RETURNING 1
38+ )
39+ INSERT INTO homework_file (id, submission, name, content_type, size, file, created_at)
40+ SELECT $3, $2, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat)
41+ RETURNING id AS "id: HomeworkFileId",
42+ submission AS "submission: HomeworkSubmissionId",
43+ name AS "name: FileName",
44+ content_type AS "content_type: FileContentType",
45+ size,
46+ file,
47+ created_at AS "created_at: Timestamp""#,
4748 MAX_HOMEWORK_FILES_PER_SUBMISSION as i64,
48- SUBMISSION_OPEN_GUARD,
49- &file.id.record(),
50- &file,
51- db,
49+ file.submission,
50+ file.id,
51+ file.name,
52+ file.content_type,
53+ file.size,
54+ file.file,
55+ file.created_at,
5256 )
53- .await?
54- {
55- cap::Claimed::Made(created) => Ok(Some(created)),
56- cap::Claimed::Full => {
57+ .fetch_optional(db)
58+ .await
59+ .map_err(|err| {
60+ // The id is a fresh v7 minted by `new`, so a row already holding it
61+ // is a collision, not a re-upload.
62+ if crate::database::unique_violation(&err).is_some() {
63+ AppError::Internal("homework file id collided".into())
64+ } else {
65+ AppError::from(err)
66+ }
67+ })?;
68+ match created {
69+ Some(row) => Ok(Some(row)),
70+ None => {
5771 if super::homework_submission::is_graded(db, &file.submission).await? {
5872 return Ok(None);
5973 }
@@ -61,9 +75,6 @@ pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<Homework
6175 "the submission already holds the maximum of 10 files — delete one first",
6276 ))
6377 }
64- // The id is a fresh ULID minted by `new`, so a row already holding it
65- // is a collision, not a re-upload.
66- cap::Claimed::Duplicate => Err(AppError::Internal("homework file id collided".into())),
6778 }
6879 }
6980
@@ -74,8 +85,21 @@ pub async fn read_for(
7485 id: &crate::domain::homework_file::HomeworkFileId,
7586 submission: &crate::domain::homework_submission::HomeworkSubmissionId,
7687 ) -> Result<Option<HomeworkFile>, AppError> {
77- let file: Option<HomeworkFile> = db.select(id.record()).await?;
78- Ok(file.filter(|file| &file.submission == submission))
88+ Ok(sqlx::query_as!(
89+ HomeworkFile,
90+ r#"SELECT id AS "id: HomeworkFileId",
91+ submission AS "submission: HomeworkSubmissionId",
92+ name AS "name: FileName",
93+ content_type AS "content_type: FileContentType",
94+ size,
95+ file,
96+ created_at AS "created_at: Timestamp"
97+ FROM homework_file WHERE id = $1 AND submission = $2"#,
98+ id,
99+ submission
100+ )
101+ .fetch_optional(db)
102+ .await?)
79103 }
80104
81105 /// 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(
89113 id: &crate::domain::homework_file::HomeworkFileId,
90114 homework: &HomeworkId,
91115 ) -> Result<Option<HomeworkFile>, AppError> {
92- let mut result = db
93- .query(
94- "SELECT * FROM homework_file WHERE id = $id AND submission IN \
95- (SELECT VALUE id FROM homework_submission WHERE homework = $hw)",
96- )
97- .bind(("id", id.record()))
98- .bind(("hw", homework.record()))
99- .await?
100- .check()?;
101- Ok(result.take::<Vec<HomeworkFile>>(0)?.into_iter().next())
116+ Ok(sqlx::query_as!(
117+ HomeworkFile,
118+ r#"SELECT id AS "id: HomeworkFileId",
119+ submission AS "submission: HomeworkSubmissionId",
120+ name AS "name: FileName",
121+ content_type AS "content_type: FileContentType",
122+ size,
123+ file,
124+ created_at AS "created_at: Timestamp"
125+ FROM homework_file
126+ WHERE id = $1
127+ AND submission IN (SELECT id FROM homework_submission WHERE homework = $2)"#,
128+ id,
129+ homework
130+ )
131+ .fetch_optional(db)
132+ .await?)
102133 }
103134
104135 /// All of `submission`'s files, newest first.
@@ -106,40 +137,56 @@ pub async fn list_for_submission(
106137 db: &Database,
107138 submission: &crate::domain::homework_submission::HomeworkSubmissionId,
108139 ) -> Result<Vec<HomeworkFile>, AppError> {
109- let mut result = db
110- .query("SELECT * FROM homework_file WHERE submission = $sub ORDER BY id DESC")
111- .bind(("sub", submission.record()))
112- .await?
113- .check()?;
114- Ok(result.take::<Vec<HomeworkFile>>(0)?)
140+ Ok(sqlx::query_as!(
141+ HomeworkFile,
142+ r#"SELECT id AS "id: HomeworkFileId",
143+ submission AS "submission: HomeworkSubmissionId",
144+ name AS "name: FileName",
145+ content_type AS "content_type: FileContentType",
146+ size,
147+ file,
148+ created_at AS "created_at: Timestamp"
149+ FROM homework_file WHERE submission = $1 ORDER BY id DESC"#,
150+ submission
151+ )
152+ .fetch_all(db)
153+ .await?)
115154 }
116155
117-/// How many files `submission` holds — the cap check reads this under the
118-/// lock. Counting via the rows (not a `count()` query) keeps it identical
119-/// to `NoteFile`'s proven cap check; at a ceiling of 10 the cost is nil.
156+/// How many files `submission` holds. Counting the rows (not the counter
157+/// column) keeps it identical to `NoteFile`'s proven cap check; at a ceiling
158+/// of 10 the cost is nil.
120159 pub async fn count_for_submission(
121160 db: &Database,
122161 submission: &crate::domain::homework_submission::HomeworkSubmissionId,
123162 ) -> Result<usize, AppError> {
124- Ok(list_for_submission(db, submission).await?.len())
163+ let row = sqlx::query!(
164+ r#"SELECT count(*) AS "count: i64" FROM homework_file WHERE submission = $1"#,
165+ submission
166+ )
167+ .fetch_one(db)
168+ .await?;
169+ Ok(row.count as usize)
125170 }
126171
127172 /// The blob names behind every file of every submission to `homework` —
128-/// collected *before* the homework-delete cascade wipes the rows, so the
129-/// web layer can unlink them once the rows are gone.
173+/// the GC keys of a homework delete (collected inside the delete's own
174+/// transaction by [`crate::db::homework::delete`]; this read backs it and
175+/// the tests).
130176 pub async fn file_keys_for_homework(
131177 db: &Database,
132178 homework: &HomeworkId,
133179 ) -> Result<Vec<String>, AppError> {
134- let mut result = db
135- .query(
136- "SELECT VALUE file FROM homework_file \
137- WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw)",
138- )
139- .bind(("hw", homework.record()))
140- .await?
141- .check()?;
142- Ok(result.take::<Vec<String>>(0)?)
180+ Ok(sqlx::query!(
181+ r#"SELECT file FROM homework_file
182+ WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#,
183+ homework
184+ )
185+ .fetch_all(db)
186+ .await?
187+ .into_iter()
188+ .map(|row| row.file)
189+ .collect())
143190 }
144191
145192 /// The blob names behind every homework file of `course` — collected
@@ -148,17 +195,19 @@ pub async fn file_keys_for_course(
148195 db: &Database,
149196 course: &CourseId,
150197 ) -> Result<Vec<String>, AppError> {
151- let mut result = db
152- .query(
153- "SELECT VALUE file FROM homework_file WHERE submission IN ( \
154- SELECT VALUE id FROM homework_submission \
155- WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course) \
156- )",
157- )
158- .bind(("course", course.record()))
159- .await?
160- .check()?;
161- Ok(result.take::<Vec<String>>(0)?)
198+ Ok(sqlx::query!(
199+ r#"SELECT file FROM homework_file
200+ WHERE submission IN (
201+ SELECT id FROM homework_submission
202+ WHERE homework IN (SELECT id FROM homework WHERE course = $1)
203+ )"#,
204+ course
205+ )
206+ .fetch_all(db)
207+ .await?
208+ .into_iter()
209+ .map(|row| row.file)
210+ .collect())
162211 }
163212
164213 /// Delete the row and give its slot back in the same transaction. The
@@ -167,57 +216,58 @@ pub async fn file_keys_for_course(
167216 ///
168217 /// The gate is the first statement: a conditional write on the *submission*
169218 /// row — the "last touched" re-stamp a file delete owes the late flag
170-/// anyway — carrying [`SUBMISSION_OPEN_GUARD`]. Nothing else in the
171-/// transaction runs unless it bit, so a grade landing concurrently either
172-/// stamps first (this delete is refused, `Ok(None)`) or stamps after (the
173-/// file was already gone when it graded). `Err(NotFound)` still means the
174-/// file row itself had vanished.
175-///
176-/// Sound to re-send while the store answers "conflict, retry", and it has
177-/// to be: the gate writes the *submission* row, the very record an upload's
178-/// [`insert`] claims its seat on, and both handlers hold only
179-/// `HOMEWORK_LOCK.read()` — so a concurrent add and delete of two files of
180-/// one submission contend by design, and a lost round used to come back as
181-/// a 500 on a request that had written nothing. Only `UPDATE` and `DELETE`
182-/// are in the batch, and neither can legitimately answer "already exists",
183-/// which is what makes the whole of it re-sendable.
219+/// anyway. Its row lock is also the serialization point against an upload's
220+/// seat claim on the same row: one of the two waits, and the winner re-reads
221+/// the counter before moving it, so no lost round and no 500 — a grade
222+/// landing concurrently either stamps first (this delete is refused,
223+/// `Ok(None)`) or stamps after (the file was already gone when it graded).
224+/// `Err(NotFound)` still means the file row itself had vanished.
184225 pub async fn delete(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> {
185- let (mut result, mut errors) = transaction_with_retry(
186- db,
187- &format!(
188- "BEGIN TRANSACTION;
189- LET $open = (UPDATE $sub SET updated_at = $now \
190- WHERE {SUBMISSION_OPEN_GUARD} RETURN VALUE id);
191- LET $gone = IF array::len($open) > 0 {{ (DELETE $id RETURN BEFORE) }} ELSE {{ [] }};
192- UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]);
193- RETURN {{ open: array::len($open), gone: $gone }};
194- COMMIT TRANSACTION;"
195- ),
196- &[
197- ("id".into(), file.id.record().into_value()),
198- ("sub".into(), file.submission.record().into_value()),
199- ("now".into(), Timestamp::now().into_value()),
200- ],
201- &[],
202- )
203- .await?;
204- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
205- return Err(error.into());
206- }
207- // BEGIN is slot 0, the two LETs slots 1-2 and the counter fix slot 3;
208- // the RETURN is slot 4.
209- let outcome: Option<DeleteOutcome> = result.take::<Vec<DeleteOutcome>>(4)?.into_iter().next();
210- let outcome =
211- outcome.ok_or_else(|| AppError::Internal("failed to delete homework file".into()))?;
212- if outcome.open == 0 {
213- return Ok(None);
214- }
215- outcome
216- .gone
217- .into_iter()
218- .next()
219- .map(Some)
220- .ok_or(AppError::NotFound)
226+ let now = Timestamp::now();
227+ tx_with_retry(db, false, async |tx| {
228+ let open = sqlx::query!(
229+ r#"UPDATE homework_submission SET updated_at = $2
230+ WHERE id = $1 AND graded_by_result IS NULL
231+ RETURNING 1 AS "open: i32""#,
232+ file.submission,
233+ now
234+ )
235+ .fetch_optional(&mut *tx)
236+ .await?;
237+ if open.is_none() {
238+ return Ok(None);
239+ }
240+ let gone = sqlx::query_as!(
241+ HomeworkFile,
242+ r#"DELETE FROM homework_file WHERE id = $1 AND submission = $2
243+ RETURNING id AS "id: HomeworkFileId",
244+ submission AS "submission: HomeworkSubmissionId",
245+ name AS "name: FileName",
246+ content_type AS "content_type: FileContentType",
247+ size,
248+ file,
249+ created_at AS "created_at: Timestamp""#,
250+ file.id,
251+ file.submission
252+ )
253+ .fetch_optional(&mut *tx)
254+ .await?;
255+ match gone {
256+ Some(row) => {
257+ sqlx::query!(
258+ "UPDATE homework_submission SET file_count = GREATEST(file_count - 1, 0)
259+ WHERE id = $1",
260+ file.submission
261+ )
262+ .execute(&mut *tx)
263+ .await?;
264+ Ok(Some(row))
265+ }
266+ // The submission was open but the file had already vanished.
267+ None => Err(AppError::NotFound),
268+ }
269+ })
270+ .await
221271 }
222272
223273 #[cfg(test)]
src/db/homework_result.rsmodified+206 -188
@@ -5,48 +5,51 @@
55 //! validated status and mark types in
66 //! [`crate::domain::homework_result`].
77
8-use crate::constant::{MARKS_GIVEN_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD};
9-use crate::database::{Database, transaction_with_retry};
8+use crate::database::{Database, tx_with_retry};
109 use crate::domain::course::CourseId;
1110 use crate::domain::exam_result::Mark;
1211 use crate::domain::homework::HomeworkId;
1312 use crate::domain::homework_result::{HomeworkResult, HomeworkResultId, HomeworkStatus};
14-use crate::domain::homework_submission::HomeworkSubmissionId;
1513 use crate::domain::timestamp::Timestamp;
1614 use crate::domain::user::UserId;
1715 use crate::error::AppError;
18-use surrealdb::types::SurrealValue;
1916
20-/// Record (or overwrite) the grade for (homework, user). One row per pair,
21-/// keyed by the deterministic composite id, so this is a single atomic
22-/// UPSERT — concurrent grades for the same pair converge on one row instead
23-/// of racing a unique index into a 500. Grading before the due date, or
24-/// before any submission exists, is allowed (the caller's policy call).
17+/// Record (or overwrite) the grade for (homework, user). One row per pair by
18+/// the pair's UNIQUE constraint, so grading is one atomic UPSERT —
19+/// concurrent grades for the same pair converge on one row instead of
20+/// racing a duplicate into a 500. Grading before the due date, or before any
21+/// submission exists, is allowed (the caller's policy call).
2522 ///
2623 /// In the same transaction the grade *stamps* the student's submission
27-/// ([`crate::constant::SUBMISSION_GRADED_FIELD`]), which is what freezes it:
28-/// every student-side write to that row then fails its own
29-/// `graded_by_result = NONE` condition, with no cross-table read for a
30-/// concurrent write to slip past. A submission that does not exist yet is
31-/// left alone — grading absent work must not conjure a hand-in (the report reads
32-/// `submitted`/`missing`/`late` straight off that row).
24+/// (`graded_by_result`), which is what freezes it: every student-side write
25+/// to that row then fails its own `graded_by_result IS NULL` condition, with
26+/// no cross-table read for a concurrent write to slip past. A submission
27+/// that does not exist yet is left alone — grading absent work must not
28+/// conjure a hand-in (the report reads `submitted`/`missing`/`late` straight
29+/// off that row).
3330 ///
34-/// That one case is where this function stops defending itself: a student's
31+/// That one case is where this statement stops defending itself: a student's
3532 /// *first* hand-in committing between this grade and nothing-to-stamp would
36-/// land unstamped, leaving a grade beside an editable submission. Nothing
37-/// here forbids it — what forbids it is the caller. Grading holds
38-/// `HOMEWORK_LOCK` (see [`crate::service::homework`]) for writing across this
39-/// whole transaction while every student-side write holds it for reading across
40-/// its own, and the two leases are mutually exclusive in the one process
41-/// this backend runs as, so the interleaving never gets a window.
42-//
43-// corner-cut: that makes the freeze depend on lock discipline at the call
44-// sites, not on this row. Moving a student write's lease to *after* its
45-// database write — or sharding HOMEWORK_LOCK per homework — reopens the
46-// window with nothing to catch it. Closing it in the db layer needs a
47-// record both sides own (a per-(homework, user) row the grade can always
48-// stamp); a tombstone submission is not it, since every read path would
49-// have to learn to ignore it and one missed filter fabricates a hand-in.
33+/// land unstamped, leaving a grade beside an editable submission. What
34+/// forbids it here is the homework row's lock: every student-side write
35+/// locks the homework row across its write, and so does this transaction, so
36+/// the interleaving is ordered away instead of leased away — either the
37+/// grade saw the row to stamp, or the submission saw no grade and created
38+/// under a lock this transaction already held.
39+///
40+/// Whether the pair was already graded is read one statement ahead of the
41+/// write, under the same lock — it is what keeps a regrade from crediting
42+/// the grader a second time. No mark counter here: a homework mark is
43+/// optional and most grades are status-only, so `high_mark` is an exam-only
44+/// family.
45+///
46+/// The homework row's `FOR UPDATE` is also the parent gate: the id is minted
47+/// fresh, so a grade landing inside a homework (or course) delete's window
48+/// would otherwise *re-create* a result row under a homework that is gone,
49+/// readable ever after at `GET /homework/{id}/result` (no existence check
50+/// there) with a `marks_given_total` no ungrade can reach, because every
51+/// route to the grade goes through the homework. A vanished row answers
52+/// `Err(NotFound)` — the 404 the web layer's own lookup would have answered.
5053 pub async fn grade(
5154 db: &Database,
5255 homework: &HomeworkId,
@@ -55,102 +58,73 @@ pub async fn grade(
5558 mark: Option<Mark>,
5659 graded_by: &UserId,
5760 ) -> Result<HomeworkResult, AppError> {
58- let id = HomeworkResultId::composite(homework, user);
59- let submission = HomeworkSubmissionId::composite(homework, user);
60- let result = HomeworkResult {
61- id: id.clone(),
62- homework: homework.clone(),
63- user: user.clone(),
64- status,
65- mark,
66- graded_by: graded_by.clone(),
67- created_at: Timestamp::now(),
68- };
69- // Whether the pair was already graded is read one statement ahead of
70- // the write, inside the same transaction — it is what keeps a regrade
71- // from crediting the grader a second time. No mark counter here: a
72- // homework mark is optional and most grades are status-only, so
73- // `high_mark` is an exam-only family.
74- //
75- // The first three statements are the parent gate, the twin of
76- // [`crate::db::homework_submission::upsert`]'s
77- // and written the same way on purpose: the id is deterministic, so a
78- // grade landing inside a homework (or course) delete's window does not
79- // fail — it *re-creates* a result row under a homework that is gone,
80- // readable ever after at `GET /homework/{id}/result` (no existence check
81- // there) with a `marks_given_total` no ungrade can reach, because every
82- // route to the grade goes through the homework. Reading the homework
83- // first — which the web layer does, under the lease — cannot close that:
84- // the store conflict-checks write sets, not read sets. So the gate
85- // *moves* a value on the homework row (`due_at` up by one and straight
86- // back to the captured value, leaving the row byte-identical) and the
87- // cascade's delete of that same row is what refuses it. `homework` owns
88- // no counter column and is SCHEMAFULL, so `due_at` is the one `int` it
89- // already has; do not invent a second spelling.
90- //
91- // Not [`crate::db::cap::touch_and_create`], which is the same shape
92- // for a bare `CREATE`: a grade is an UPSERT (a regrade must overwrite),
93- // and the freeze stamp and the grader's counter have to ride the same
94- // transaction, which that helper has no room for.
95- //
96- // Sound to re-send, which is what the gate needed first — a `THROW`
97- // inside a plain `db.query` would have turned every lost round into a
98- // 500. `SELECT`, `UPDATE` and the `IF`/`THROW` can never answer "already
99- // exists", and the `UPSERT`'s id is bijective with the (homework, user)
100- // pair the table keys, on a table whose only index is non-unique
101- // (`homework_result_homework`), so its index entry can only ever point
102- // at the row the id already names: it resolves onto that row instead of
103- // colliding with it. A lost round wrote nothing.
104- let (mut saved, mut errors) = transaction_with_retry(
105- db,
106- &format!(
107- "BEGIN TRANSACTION;
108- LET $was_due = (SELECT VALUE due_at FROM ONLY $hw);
109- LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id);
110- IF array::len($alive) = 0 {{ THROW 'no_homework' }};
111- UPDATE $hw SET due_at = $was_due;
112- LET $before = (SELECT VALUE id FROM ONLY $id);
113- LET $after = (UPSERT $id CONTENT $row RETURN AFTER);
114- UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = $id \
115- WHERE {SUBMISSION_OPEN_GUARD};
116- IF $before = NONE {{
117- UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} =
118- ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1
119- }};
120- RETURN $after;
121- COMMIT TRANSACTION;"
122- ),
123- &[
124- ("hw".into(), homework.record().into_value()),
125- ("id".into(), id.record().into_value()),
126- ("sub".into(), submission.record().into_value()),
127- ("grader".into(), graded_by.record().into_value()),
128- ("row".into(), result.into_value()),
129- ],
130- &["no_homework"],
131- )
132- .await?;
133- // An aborted transaction errors *every* slot, most with a generic "not
134- // executed" — only the THROW's own slot names the reason.
135- if errors
136- .values()
137- .any(|error| error.to_string().contains("no_homework"))
138- {
139- return Err(AppError::NotFound);
140- }
141- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
142- return Err(error.into());
143- }
144- // The trailing `RETURN` is always the last statement before `COMMIT`,
145- // so its slot follows the statement count instead of a hand-kept
146- // number — which the gate above would otherwise have shifted, silently
147- // handing back something else.
148- let slot = saved.num_statements().saturating_sub(2);
149- saved
150- .take::<Vec<HomeworkResult>>(slot)?
151- .into_iter()
152- .next()
153- .ok_or_else(|| AppError::Internal("failed to record homework result".into()))
61+ let id = HomeworkResultId::generate();
62+ let now = Timestamp::now();
63+ tx_with_retry(db, false, async |tx| {
64+ let alive = sqlx::query!(
65+ r#"SELECT 1 AS "row: i32" FROM homework WHERE id = $1 FOR UPDATE"#,
66+ homework
67+ )
68+ .fetch_optional(&mut *tx)
69+ .await?;
70+ if alive.is_none() {
71+ return Err(AppError::NotFound);
72+ }
73+ let before = sqlx::query!(
74+ r#"SELECT 1 AS "row: i32" FROM homework_result
75+ WHERE homework = $1 AND app_user = $2 FOR UPDATE"#,
76+ homework,
77+ user
78+ )
79+ .fetch_optional(&mut *tx)
80+ .await?
81+ .is_some();
82+ // A regrade overwrites status, mark, grader and stamp — `id` and
83+ // `homework`/`app_user` are the row's identity and stay.
84+ let graded = sqlx::query_as!(
85+ HomeworkResult,
86+ r#"INSERT INTO homework_result (id, homework, app_user, status, mark, graded_by, created_at)
87+ VALUES ($1, $2, $3, $4, $5, $6, $7)
88+ ON CONFLICT (homework, app_user) DO UPDATE
89+ SET status = EXCLUDED.status, mark = EXCLUDED.mark,
90+ graded_by = EXCLUDED.graded_by, created_at = EXCLUDED.created_at
91+ RETURNING id AS "id: HomeworkResultId",
92+ homework AS "homework: HomeworkId",
93+ app_user AS "user: UserId",
94+ status AS "status: HomeworkStatus",
95+ mark AS "mark: Option<Mark>",
96+ graded_by AS "graded_by: UserId",
97+ created_at AS "created_at: Timestamp""#,
98+ id,
99+ homework,
100+ user,
101+ status,
102+ mark,
103+ graded_by,
104+ now,
105+ )
106+ .fetch_one(&mut *tx)
107+ .await?;
108+ sqlx::query!(
109+ r#"UPDATE homework_submission SET graded_by_result = $3
110+ WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL"#,
111+ homework,
112+ user,
113+ graded.id
114+ )
115+ .execute(&mut *tx)
116+ .await?;
117+ if !before {
118+ sqlx::query!(
119+ "UPDATE app_user SET marks_given_total = marks_given_total + 1 WHERE id = $1",
120+ graded_by
121+ )
122+ .execute(&mut *tx)
123+ .await?;
124+ }
125+ Ok(graded)
126+ })
127+ .await
154128 }
155129
156130 /// `user`'s grade for `homework`, if graded.
@@ -159,9 +133,21 @@ pub async fn read_for(
159133 homework: &HomeworkId,
160134 user: &UserId,
161135 ) -> Result<Option<HomeworkResult>, AppError> {
162- Ok(db
163- .select(HomeworkResultId::composite(homework, user).record())
164- .await?)
136+ Ok(sqlx::query_as!(
137+ HomeworkResult,
138+ r#"SELECT id AS "id: HomeworkResultId",
139+ homework AS "homework: HomeworkId",
140+ app_user AS "user: UserId",
141+ status AS "status: HomeworkStatus",
142+ mark AS "mark: Option<Mark>",
143+ graded_by AS "graded_by: UserId",
144+ created_at AS "created_at: Timestamp"
145+ FROM homework_result WHERE homework = $1 AND app_user = $2"#,
146+ homework,
147+ user
148+ )
149+ .fetch_optional(db)
150+ .await?)
165151 }
166152
167153 /// Every grade for `homework` — the roster joins these onto the submissions.
@@ -169,12 +155,20 @@ pub async fn list_for_homework(
169155 db: &Database,
170156 homework: &HomeworkId,
171157 ) -> Result<Vec<HomeworkResult>, AppError> {
172- let mut result = db
173- .query("SELECT * FROM homework_result WHERE homework = $hw ORDER BY id DESC")
174- .bind(("hw", homework.record()))
175- .await?
176- .check()?;
177- Ok(result.take::<Vec<HomeworkResult>>(0)?)
158+ Ok(sqlx::query_as!(
159+ HomeworkResult,
160+ r#"SELECT id AS "id: HomeworkResultId",
161+ homework AS "homework: HomeworkId",
162+ app_user AS "user: UserId",
163+ status AS "status: HomeworkStatus",
164+ mark AS "mark: Option<Mark>",
165+ graded_by AS "graded_by: UserId",
166+ created_at AS "created_at: Timestamp"
167+ FROM homework_result WHERE homework = $1 ORDER BY id DESC"#,
168+ homework
169+ )
170+ .fetch_all(db)
171+ .await?)
178172 }
179173
180174 /// `user`'s homework grades across one course — the raw rows behind the
@@ -185,17 +179,24 @@ pub async fn list_for_user_in_course(
185179 course: &CourseId,
186180 user: &UserId,
187181 ) -> Result<Vec<HomeworkResult>, AppError> {
188- let mut result = db
189- .query(
190- "SELECT * FROM homework_result WHERE user = $usr
191- AND homework IN (SELECT VALUE id FROM homework WHERE course = $course)
192- ORDER BY id DESC",
193- )
194- .bind(("usr", user.record()))
195- .bind(("course", course.record()))
196- .await?
197- .check()?;
198- Ok(result.take::<Vec<HomeworkResult>>(0)?)
182+ Ok(sqlx::query_as!(
183+ HomeworkResult,
184+ r#"SELECT id AS "id: HomeworkResultId",
185+ homework AS "homework: HomeworkId",
186+ app_user AS "user: UserId",
187+ status AS "status: HomeworkStatus",
188+ mark AS "mark: Option<Mark>",
189+ graded_by AS "graded_by: UserId",
190+ created_at AS "created_at: Timestamp"
191+ FROM homework_result
192+ WHERE app_user = $1
193+ AND homework IN (SELECT id FROM homework WHERE course = $2)
194+ ORDER BY id DESC"#,
195+ user,
196+ course
197+ )
198+ .fetch_all(db)
199+ .await?)
199200 }
200201
201202 /// Un-grade (homework, user), returning the removed row (`None` if there
@@ -212,53 +213,70 @@ pub async fn list_for_user_in_course(
212213 /// submission behind it — permanently, since an award is never revoked.
213214 /// Given back to the *removed row's own* grader, not the caller: a manager
214215 /// may un-grade what a teacher graded, and the credit is the teacher's.
215-///
216-/// Sound to re-send while the store answers "conflict, retry" — this is the
217-/// upgrade `grade` still wants, taken here because the counter above is what
218-/// makes it necessary: the grader's row is written by exam grading too, so
219-/// the delete now contends with another domain, and only `DELETE`/`UPDATE`
220-/// are in the batch, none of which can legitimately answer "already exists".
221216 pub async fn remove(
222217 db: &Database,
223218 homework: &HomeworkId,
224219 user: &UserId,
225220 ) -> Result<Option<HomeworkResult>, AppError> {
226- let id = HomeworkResultId::composite(homework, user);
227- let (mut result, mut errors) = transaction_with_retry(
228- db,
229- &format!(
230- "BEGIN TRANSACTION;
231- LET $gone = (DELETE $id RETURN BEFORE);
232- UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = NONE \
233- WHERE {SUBMISSION_GRADED_FIELD} = $id;
234- IF array::len($gone) > 0 {{
235- LET $grader = $gone[0].graded_by;
236- UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} =
237- math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0])
238- }};
239- RETURN $gone;
240- COMMIT TRANSACTION;"
241- ),
242- &[
243- ("id".into(), id.record().into_value()),
244- (
245- "sub".into(),
246- HomeworkSubmissionId::composite(homework, user)
247- .record()
248- .into_value(),
249- ),
250- ],
251- &[],
252- )
253- .await?;
254- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
255- return Err(error.into());
256- }
257- // The trailing `RETURN` is always the last statement before `COMMIT`, so
258- // its slot follows the statement count — the hand-kept "slot 1" this
259- // replaces was one added statement away from handing back the unstamp.
260- let slot = result.num_statements().saturating_sub(2);
261- Ok(result.take::<Vec<HomeworkResult>>(slot)?.into_iter().next())
221+ tx_with_retry(db, false, async |tx| {
222+ // The homework row's lock orders this against a concurrent grade
223+ // (which locks the same row before inserting): either this delete
224+ // wins and the re-grade lands after as a fresh grade, or the grade
225+ // lands first and this removes *it*. A homework already cascaded
226+ // away left no result rows behind — `None`, the 404 the web layer
227+ // answers.
228+ let alive = sqlx::query!(
229+ r#"SELECT 1 AS "row: i32" FROM homework WHERE id = $1 FOR UPDATE"#,
230+ homework
231+ )
232+ .fetch_optional(&mut *tx)
233+ .await?;
234+ if alive.is_none() {
235+ return Ok(None);
236+ }
237+ let gone = sqlx::query!(
238+ r#"DELETE FROM homework_result WHERE homework = $1 AND app_user = $2
239+ RETURNING id AS "id: HomeworkResultId",
240+ homework AS "homework: HomeworkId",
241+ app_user AS "user: UserId",
242+ status AS "status: HomeworkStatus",
243+ mark AS "mark: Option<Mark>",
244+ graded_by AS "graded_by: UserId",
245+ created_at AS "created_at: Timestamp""#,
246+ homework,
247+ user
248+ )
249+ .fetch_optional(&mut *tx)
250+ .await?;
251+ let Some(removed) = gone else {
252+ return Ok(None);
253+ };
254+ sqlx::query!(
255+ r#"UPDATE homework_submission SET graded_by_result = NULL
256+ WHERE homework = $1 AND app_user = $2 AND graded_by_result = $3"#,
257+ homework,
258+ user,
259+ removed.id
260+ )
261+ .execute(&mut *tx)
262+ .await?;
263+ sqlx::query!(
264+ "UPDATE app_user SET marks_given_total = GREATEST(marks_given_total - 1, 0) WHERE id = $1",
265+ removed.graded_by
266+ )
267+ .execute(&mut *tx)
268+ .await?;
269+ Ok(Some(HomeworkResult {
270+ id: removed.id,
271+ homework: removed.homework,
272+ user: removed.user,
273+ status: removed.status,
274+ mark: removed.mark,
275+ graded_by: removed.graded_by,
276+ created_at: removed.created_at,
277+ }))
278+ })
279+ .await
262280 }
263281
264282 #[cfg(test)]
src/db/homework_submission.rsmodified+266 -197
@@ -5,186 +5,217 @@
55 //! [`crate::service::homework_submission`]; the validated text type in
66 //! [`crate::domain::homework_submission`].
77
8-use crate::constant::{
9- HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMITTED_TOTAL_FIELD, SUBMISSION_GRADED_FIELD,
10- SUBMISSION_OPEN_GUARD,
11-};
12-use crate::database::{Database, transaction_with_retry};
8+use crate::database::{Database, tx_with_retry};
139 use crate::domain::homework::Homework;
10+use crate::domain::homework::HomeworkId;
1411 use crate::domain::homework_submission::{
1512 HomeworkSubmission, HomeworkSubmissionId, SubmissionText,
1613 };
1714 use crate::domain::timestamp::Timestamp;
1815 use crate::domain::user::UserId;
1916 use crate::error::AppError;
20-use surrealdb::types::SurrealValue;
2117
2218 /// Create or re-stamp `user`'s submission to `homework`, unless a grade has
2319 /// frozen it — `None` means frozen, and the caller answers 409. `updated_at`
24-/// moves to now every time; `submitted_at` (readonly, the first-submit stamp)
25-/// is kept on an existing row and set only on a fresh one.
20+/// moves to now every time; `submitted_at` (the first-submit stamp) is kept
21+/// on an existing row and set only on a fresh one. Returns the row plus
22+/// whether it existed before this call (the web layer's 200-vs-201, and the
23+/// only-a-first-hand-in-earns-badges rule).
2624 ///
27-/// Hand-written rather than `.content()` on purpose: `.content()` re-sends
28-/// the whole row, so it would carry a `submitted_at`, and any value differing
29-/// from the stored one trips the readonly guard. The
30-/// `submitted_at = submitted_at ?? $now` expression preserves it inside the
31-/// one UPSERT statement — race-free without a lock, where a read-then-content
32-/// could let two concurrent first-submits pick different stamps and 500.
25+/// `preserve_text` is the photo-upload auto-create's switch: an existing row
26+/// keeps its text (and its stamp moves, as any touch), because the upload
27+/// never offered a text to replace it. A submit passes `false` — an absent
28+/// text clears, as on the wire.
3329 ///
34-/// The `WHERE` is the freeze: [`SUBMISSION_OPEN_GUARD`] makes "not graded
35-/// yet" a condition of this very write instead of a read a concurrent grade
36-/// can land behind. An absent row satisfies it (the stamp is `NONE` there
37-/// too), so a first submit still creates.
30+/// The `graded_by_result IS NULL` predicate is the freeze: "not graded yet"
31+/// is a condition of the write itself, so a refused write answers `None`
32+/// instead of wiping graded work. An absent row satisfies it trivially, so a
33+/// first submit still creates.
3834 ///
3935 /// The badge counters on the student's user row move in this very
40-/// transaction, and the order is load-bearing: the increment sits *after*
41-/// the UPSERT and is conditional on it having matched a row, because a
42-/// frozen row makes that `WHERE` match nothing **silently** (unlike
43-/// [`crate::db::homework_result::grade`], which `THROW`s) — put
44-/// first, it would count a submission the freeze refused. `$before = NONE`
45-/// keeps it to a genuine first create, so an edit moves neither counter,
46-/// which is what makes the live count mean the same thing the one-time
47-/// backfill seeded (one per row; on time judged against `due_at`, equal
48-/// counting as on time).
36+/// transaction, and only on the create arm — an edit moves neither counter,
37+/// which is what makes the live count mean one per row.
4938 ///
50-/// `counted_on_time` is stamped on the row from the *same* `$on_time`
51-/// expression the increment adds, in the same statement block: the deadline
52-/// is mutable, so a withdrawal that re-judged it against the live `due_at`
53-/// gave back something other than what was taken. Writing the verdict beside
54-/// the counter is what keeps the two from ever disagreeing — read back by
39+/// `counted_on_time` is stamped on the row from the same `on_time` verdict
40+/// the increment adds, in the same transaction: the deadline is mutable, so
41+/// a withdrawal that re-judged it against the live `due_at` gave back
42+/// something other than what was taken. Writing the verdict beside the
43+/// counter is what keeps the two from ever disagreeing — read back by
5544 /// [`delete`], never re-derived.
5645 ///
57-/// That deadline is `$was_due`, the one the gate below already read *inside
58-/// this transaction* — never the caller's [`Homework`] snapshot, which was
59-/// read before the lease and is exactly one `PATCH due_at` old in the
60-/// "teacher extends the deadline at 23:59 while the class submits" moment.
61-/// Judging on the snapshot stored a verdict the web layer's own `late` flag
62-/// (`updated_at > due_at`, re-derived live on every read) then contradicted
63-/// forever, in both directions. An in-process lock cannot fix this — it
64-/// orders two handlers, not two store transactions — so the comparison has
65-/// to live where the write does. The whole entity is still taken (both
66-/// callers hold the row, and the id comes off it); its `due_at` must not be.
67-///
68-/// The first three statements are the parent gate, and they are why this
69-/// write cannot outlive its homework: the id is deterministic, so nothing
70-/// else here would fail against a homework a cascade already removed — it
71-/// would simply re-create the row, badge counters and all, unreachable ever
72-/// after (every route to a submission goes through its homework). A *read*
73-/// of the homework does not close that, on either side of the call: the
74-/// store does no read-set conflict detection, so a delete committing
75-/// alongside is invisible to it. The gate therefore *moves* a value on the
76-/// homework row — `due_at` up by one and straight back to the captured
77-/// value, so the row is byte-identical afterwards — because only a write
78-/// collides, and `SET x = x` is elided and never reaches the write set. It
79-/// is [`crate::domain::exam_answer::ExamAnswer::save`]'s shape exactly.
80-/// `Err(NotFound)` means the homework is gone, which is the 404 the web
81-/// layer's own lookup would have answered.
46+/// That deadline is `was_due`, the one read *inside this transaction* under
47+/// the homework row's lock — never the caller's [`Homework`] snapshot, which
48+/// was read before the request's gates and is exactly one `PATCH due_at` old
49+/// in the "teacher extends the deadline at 23:59 while the class submits"
50+/// moment. The lock is also the serialization point: grading locks the same
51+/// row before stamping, the audience-narrowing PATCH before its orphan
52+/// check, and a rival first hand-in before its own insert — so the
53+/// read-then-write below cannot interleave with any of them. (The pair's
54+/// UNIQUE constraint backs this up; under the lock it can never fire.)
8255 pub async fn upsert(
8356 db: &Database,
8457 homework: &Homework,
8558 user: &UserId,
8659 text: Option<SubmissionText>,
87-) -> Result<Option<HomeworkSubmission>, AppError> {
88- let id = HomeworkSubmissionId::composite(homework.get_id(), user);
60+ preserve_text: bool,
61+) -> Result<Option<(HomeworkSubmission, bool)>, AppError> {
8962 let now = Timestamp::now();
90- let text = text.map(|text| text.as_str().to_string());
91- // Sound to re-send: the UPSERT is on a deterministic id on a table with
92- // no unique index, so it can never legitimately answer "already exists",
93- // and the counter UPDATEs never can either.
94- let (mut saved, mut errors) = transaction_with_retry(
95- db,
96- &format!(
97- "BEGIN TRANSACTION;
98- LET $was_due = (SELECT VALUE due_at FROM ONLY $hw);
99- LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id);
100- IF array::len($alive) = 0 {{ THROW 'no_homework' }};
101- UPDATE $hw SET due_at = $was_due;
102- LET $before = (SELECT VALUE id FROM ONLY $id);
103- LET $on_time = $now <= $was_due;
104- LET $after = (UPSERT $id SET homework = $hw, user = $usr, text = $text,
105- updated_at = $now, submitted_at = submitted_at ?? $now
106- WHERE {SUBMISSION_OPEN_GUARD} RETURN AFTER);
107- IF $before = NONE AND array::len($after) > 0 {{
108- UPDATE $id SET counted_on_time = $on_time;
109- UPDATE $usr SET
110- {HOMEWORK_SUBMITTED_TOTAL_FIELD} = ({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) + 1,
111- {HOMEWORK_ON_TIME_TOTAL_FIELD} = ({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0)
112- + IF $on_time {{ 1 }} ELSE {{ 0 }}
113- }};
114- RETURN $after;
115- COMMIT TRANSACTION;"
116- ),
117- &[
118- ("id".into(), id.record().into_value()),
119- ("hw".into(), homework.get_id().record().into_value()),
120- ("usr".into(), user.record().into_value()),
121- ("text".into(), text.into_value()),
122- ("now".into(), now.into_value()),
123- ],
124- &["no_homework"],
125- )
126- .await?;
127- // An aborted transaction errors *every* slot, most with a generic "not
128- // executed" — only the THROW's own slot names the reason.
129- if errors
130- .values()
131- .any(|error| error.to_string().contains("no_homework"))
132- {
133- return Err(AppError::NotFound);
134- }
135- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
136- return Err(error.into());
137- }
138- // The trailing `RETURN` is always the last statement before `COMMIT`, so
139- // its slot follows the statement count rather than a hand-kept number.
140- // It returns the whole array, never `$after[0]`: a refused write makes
141- // that `NONE`, which fails to deserialize ("expected object, got none")
142- // instead of reading as the "frozen" the caller answers 409 to.
143- let slot = saved.num_statements().saturating_sub(2);
144- Ok(saved
145- .take::<Vec<HomeworkSubmission>>(slot)?
146- .into_iter()
147- .next())
63+ tx_with_retry(db, false, async |tx| {
64+ // The parent gate: the homework row is locked and its deadline read
65+ // in the very transaction that writes the submission. The id is
66+ // minted fresh, so nothing else here would fail against a homework a
67+ // cascade already removed — it would simply create a row under it,
68+ // badge counters and all, unreachable ever after (every route to a
69+ // submission goes through its homework). `Err(NotFound)` means the
70+ // homework is gone, which is the 404 the web layer's own lookup
71+ // would have answered.
72+ let was_due = sqlx::query!(
73+ "SELECT due_at FROM homework WHERE id = $1 FOR UPDATE",
74+ homework.get_id()
75+ )
76+ .fetch_optional(&mut *tx)
77+ .await?
78+ .map(|row| row.due_at);
79+ let Some(was_due) = was_due else {
80+ return Err(AppError::NotFound);
81+ };
82+ // Equal counts as on time, exactly as the deadline has always been
83+ // judged.
84+ let on_time = i64::from(now <= was_due);
85+
86+ // The row, read under the homework's lock: its existence decides the
87+ // arm (and the counters).
88+ let existing = sqlx::query!(
89+ r#"SELECT 1 AS "row: i32" FROM homework_submission
90+ WHERE homework = $1 AND app_user = $2 FOR UPDATE"#,
91+ homework.get_id(),
92+ user
93+ )
94+ .fetch_optional(&mut *tx)
95+ .await?
96+ .is_some();
97+
98+ if existing {
99+ // Re-submit: text is replaced (unless the upload auto-create is
100+ // asking — it has no text to replace), `updated_at` moves, and
101+ // `submitted_at` is left alone. A frozen row matches nothing and
102+ // answers `None`, the caller's 409.
103+ let updated = if preserve_text {
104+ sqlx::query_as!(
105+ HomeworkSubmission,
106+ r#"UPDATE homework_submission SET updated_at = $3
107+ WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL
108+ RETURNING id AS "id: HomeworkSubmissionId",
109+ homework AS "homework: HomeworkId",
110+ app_user AS "user: UserId",
111+ text AS "text: Option<SubmissionText>",
112+ submitted_at AS "submitted_at: Timestamp",
113+ updated_at AS "updated_at: Timestamp""#,
114+ homework.get_id(),
115+ user,
116+ now
117+ )
118+ .fetch_optional(&mut *tx)
119+ .await?
120+ } else {
121+ sqlx::query_as!(
122+ HomeworkSubmission,
123+ r#"UPDATE homework_submission SET text = $3, updated_at = $4
124+ WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL
125+ RETURNING id AS "id: HomeworkSubmissionId",
126+ homework AS "homework: HomeworkId",
127+ app_user AS "user: UserId",
128+ text AS "text: Option<SubmissionText>",
129+ submitted_at AS "submitted_at: Timestamp",
130+ updated_at AS "updated_at: Timestamp""#,
131+ homework.get_id(),
132+ user,
133+ text,
134+ now
135+ )
136+ .fetch_optional(&mut *tx)
137+ .await?
138+ };
139+ return Ok(updated.map(|submission| (submission, existing)));
140+ }
141+
142+ // First hand-in: the verdict is stored beside the counter it credits,
143+ // so the two can never disagree.
144+ let created = sqlx::query_as!(
145+ HomeworkSubmission,
146+ r#"INSERT INTO homework_submission
147+ (id, homework, app_user, text, submitted_at, updated_at, file_count, counted_on_time)
148+ VALUES ($1, $2, $3, $4, $5, $5, 0, $6)
149+ RETURNING id AS "id: HomeworkSubmissionId",
150+ homework AS "homework: HomeworkId",
151+ app_user AS "user: UserId",
152+ text AS "text: Option<SubmissionText>",
153+ submitted_at AS "submitted_at: Timestamp",
154+ updated_at AS "updated_at: Timestamp""#,
155+ HomeworkSubmissionId::generate(),
156+ homework.get_id(),
157+ user,
158+ text,
159+ now,
160+ on_time != 0,
161+ )
162+ .fetch_optional(&mut *tx)
163+ .await?;
164+ sqlx::query!(
165+ r#"UPDATE app_user SET
166+ homework_submitted_total = homework_submitted_total + 1,
167+ homework_on_time_total = homework_on_time_total + $2
168+ WHERE id = $1"#,
169+ user,
170+ on_time
171+ )
172+ .execute(&mut *tx)
173+ .await?;
174+ Ok(created.map(|submission| (submission, existing)))
175+ })
176+ .await
148177 }
149178
150179 /// Re-stamp a submission's `updated_at` to now, leaving its text and files
151180 /// alone. A file add or delete modifies the submission as a whole, so its
152181 /// "last touched" clock — which drives the computed late flag — must move
153-/// even though the text row is unchanged. Free-standing because the file
154-/// paths hold the composite id, not always the row. A targeted single-field
155-/// UPDATE, so the `READONLY` `submitted_at` is never re-sent (a `.content()`
156-/// would trip its guard). Returns the re-stamped row, or a 404 if it has
157-/// since vanished.
182+/// even though the text row is unchanged. A targeted single-field UPDATE, so
183+/// the readonly `submitted_at` is never re-sent. Returns the re-stamped row,
184+/// or a 404 if it has since vanished.
158185 pub async fn touch(
159186 db: &Database,
160187 id: &HomeworkSubmissionId,
161188 ) -> Result<HomeworkSubmission, AppError> {
162189 let now = Timestamp::now();
163- let mut result = db
164- .query("UPDATE $id SET updated_at = $now RETURN AFTER")
165- .bind(("id", id.record()))
166- .bind(("now", now))
167- .await?
168- .check()?;
169- result
170- .take::<Vec<HomeworkSubmission>>(0)?
171- .into_iter()
172- .next()
173- .ok_or(AppError::NotFound)
190+ sqlx::query_as!(
191+ HomeworkSubmission,
192+ r#"UPDATE homework_submission SET updated_at = $2 WHERE id = $1
193+ RETURNING id AS "id: HomeworkSubmissionId",
194+ homework AS "homework: HomeworkId",
195+ app_user AS "user: UserId",
196+ text AS "text: Option<SubmissionText>",
197+ submitted_at AS "submitted_at: Timestamp",
198+ updated_at AS "updated_at: Timestamp""#,
199+ id,
200+ now
201+ )
202+ .fetch_optional(db)
203+ .await?
204+ .ok_or(AppError::NotFound)
174205 }
175206
176207 /// Whether a grade has frozen this submission. Only ever read to tell two
177208 /// refusals apart *after* a conditional write has already refused one — the
178209 /// stamp on the row, never this read, is what decides.
179210 pub async fn is_graded(db: &Database, id: &HomeworkSubmissionId) -> Result<bool, AppError> {
180- let mut result = db
181- .query(format!(
182- "SELECT VALUE id FROM $id WHERE {SUBMISSION_GRADED_FIELD} != NONE"
183- ))
184- .bind(("id", id.record()))
185- .await?
186- .check()?;
187- Ok(!result.take::<Vec<HomeworkSubmissionId>>(0)?.is_empty())
211+ let row = sqlx::query!(
212+ r#"SELECT EXISTS(SELECT 1 FROM homework_submission
213+ WHERE id = $1 AND graded_by_result IS NOT NULL) AS "graded""#,
214+ id
215+ )
216+ .fetch_one(db)
217+ .await?;
218+ Ok(row.graded)
188219 }
189220
190221 /// `user`'s submission to `homework`, if they have one.
@@ -193,23 +224,40 @@ pub async fn read_for(
193224 homework: &crate::domain::homework::HomeworkId,
194225 user: &UserId,
195226 ) -> Result<Option<HomeworkSubmission>, AppError> {
196- Ok(db
197- .select(HomeworkSubmissionId::composite(homework, user).record())
198- .await?)
227+ Ok(sqlx::query_as!(
228+ HomeworkSubmission,
229+ r#"SELECT id AS "id: HomeworkSubmissionId",
230+ homework AS "homework: HomeworkId",
231+ app_user AS "user: UserId",
232+ text AS "text: Option<SubmissionText>",
233+ submitted_at AS "submitted_at: Timestamp",
234+ updated_at AS "updated_at: Timestamp"
235+ FROM homework_submission WHERE homework = $1 AND app_user = $2"#,
236+ homework,
237+ user
238+ )
239+ .fetch_optional(db)
240+ .await?)
199241 }
200242
201-/// Every submission to `homework`, in student (composite-id) order — the
202-/// roster's raw rows.
243+/// Every submission to `homework`, in creation order — the roster's raw rows.
203244 pub async fn list_for_homework(
204245 db: &Database,
205246 homework: &crate::domain::homework::HomeworkId,
206247 ) -> Result<Vec<HomeworkSubmission>, AppError> {
207- let mut result = db
208- .query("SELECT * FROM homework_submission WHERE homework = $hw ORDER BY id ASC")
209- .bind(("hw", homework.record()))
210- .await?
211- .check()?;
212- Ok(result.take::<Vec<HomeworkSubmission>>(0)?)
248+ Ok(sqlx::query_as!(
249+ HomeworkSubmission,
250+ r#"SELECT id AS "id: HomeworkSubmissionId",
251+ homework AS "homework: HomeworkId",
252+ app_user AS "user: UserId",
253+ text AS "text: Option<SubmissionText>",
254+ submitted_at AS "submitted_at: Timestamp",
255+ updated_at AS "updated_at: Timestamp"
256+ FROM homework_submission WHERE homework = $1 ORDER BY id ASC"#,
257+ homework
258+ )
259+ .fetch_all(db)
260+ .await?)
213261 }
214262
215263 /// Delete this submission and its files in one transaction — so a crash
@@ -217,9 +265,8 @@ pub async fn list_for_homework(
217265 /// are the web layer's to unlink: it lists them
218266 /// ([`crate::db::homework_file::list_for_submission`])
219267 /// before calling this. `None` means a grade froze the row (the caller
220-/// answers 409): the submission's own delete carries
221-/// [`SUBMISSION_OPEN_GUARD`], and the file wipe is conditional on it having
222-/// bitten, so a refused delete leaves the children standing too.
268+/// answers 409): the delete carries `graded_by_result IS NULL` as its own
269+/// condition, so a refused delete leaves the files standing too.
223270 ///
224271 /// The one place either badge counter comes back down, and deliberately the
225272 /// only one: this route is student-callable on their own row, so without it
@@ -234,12 +281,10 @@ pub async fn list_for_homework(
234281 /// and gave back something other than what was taken — extend it after a
235282 /// late hand-in and this debited a credit that was never given; pull it back
236283 /// after a punctual one and it debited nothing, leaving `on_time` above
237-/// `submitted`. A row from before the column exists carries no verdict, and
238-/// cannot be given one for a credit that already happened, so it falls back
239-/// to the old cut (`submitted_at`, the readonly stamp the increment judged,
240-/// against the live deadline); a dangling `homework` link leaves `$due`
241-/// `NONE` there, which compares false and so counts as late, matching the
242-/// backfill. Floored at zero: a row that predates the columns has none.
284+/// `submitted`. A row with no stored verdict falls back to the old cut
285+/// (`submitted_at`, the stamp the increment judged, against the deadline
286+/// read here); a homework already gone counts as late, matching the
287+/// backfill. Floored at zero.
243288 ///
244289 /// Badges already earned are never taken away — [`crate::domain::badge`] is
245290 /// add-only, which is where that permanence lives.
@@ -247,42 +292,66 @@ pub async fn delete(
247292 db: &Database,
248293 submission: HomeworkSubmission,
249294 ) -> Result<Option<HomeworkSubmission>, AppError> {
250- // Sound to re-send: DELETE and UPDATE can never answer "already exists".
251- let (mut result, mut errors) = transaction_with_retry(
252- db,
253- &format!(
254- "BEGIN TRANSACTION;
255- LET $due = (SELECT VALUE homework.due_at FROM ONLY $sub);
256- LET $gone = (DELETE $sub WHERE {SUBMISSION_OPEN_GUARD} RETURN BEFORE);
257- IF array::len($gone) > 0 {{
258- DELETE homework_file WHERE submission = $sub;
259- LET $on_time = IF ($gone[0].counted_on_time
260- ?? ($gone[0].submitted_at <= $due)) {{ 1 }} ELSE {{ 0 }};
261- UPDATE $usr SET
262- {HOMEWORK_SUBMITTED_TOTAL_FIELD} =
263- math::max([({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) - 1, 0]),
264- {HOMEWORK_ON_TIME_TOTAL_FIELD} =
265- math::max([({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) - $on_time, 0])
266- }};
267- RETURN $gone;
268- COMMIT TRANSACTION;"
269- ),
270- &[
271- ("sub".into(), submission.id.record().into_value()),
272- ("usr".into(), submission.user.record().into_value()),
273- ],
274- &[],
275- )
276- .await?;
277- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
278- return Err(error.into());
279- }
280- // The trailing `RETURN` is always the last statement before `COMMIT`.
281- let slot = result.num_statements().saturating_sub(2);
282- Ok(result
283- .take::<Vec<HomeworkSubmission>>(slot)?
284- .into_iter()
285- .next())
295+ tx_with_retry(db, false, async |tx| {
296+ // The homework row's lock is the serialization point against grading:
297+ // a grade locks the same row before it stamps, so either this delete
298+ // refuses off the stamp, or the grade landed on a row that is now
299+ // gone — grading absent work, which is allowed. Its `due_at` read is
300+ // also the replay fallback's deadline.
301+ let due = sqlx::query!(
302+ "SELECT due_at FROM homework WHERE id = $1 FOR UPDATE",
303+ submission.get_homework()
304+ )
305+ .fetch_optional(&mut *tx)
306+ .await?
307+ .map(|row| row.due_at);
308+ let gone = sqlx::query!(
309+ r#"DELETE FROM homework_submission
310+ WHERE id = $1 AND graded_by_result IS NULL
311+ RETURNING id AS "id: HomeworkSubmissionId",
312+ homework AS "homework: HomeworkId",
313+ app_user AS "user: UserId",
314+ text AS "text: Option<SubmissionText>",
315+ submitted_at AS "submitted_at: Timestamp",
316+ updated_at AS "updated_at: Timestamp",
317+ counted_on_time AS "counted_on_time: Option<bool>""#,
318+ submission.get_id()
319+ )
320+ .fetch_optional(&mut *tx)
321+ .await?;
322+ let Some(removed) = gone else {
323+ // Frozen, or already withdrawn by a rival — one refusal, as
324+ // before.
325+ return Ok(None);
326+ };
327+ sqlx::query!(
328+ "DELETE FROM homework_file WHERE submission = $1",
329+ removed.id
330+ )
331+ .execute(&mut *tx)
332+ .await?;
333+ let judged_on_time = due.map(|d| removed.submitted_at <= d).unwrap_or(false);
334+ let on_time = i64::from(removed.counted_on_time.unwrap_or(judged_on_time));
335+ sqlx::query!(
336+ r#"UPDATE app_user SET
337+ homework_submitted_total = GREATEST(homework_submitted_total - 1, 0),
338+ homework_on_time_total = GREATEST(homework_on_time_total - $2, 0)
339+ WHERE id = $1"#,
340+ removed.user,
341+ on_time
342+ )
343+ .execute(&mut *tx)
344+ .await?;
345+ Ok(Some(HomeworkSubmission {
346+ id: removed.id,
347+ homework: removed.homework,
348+ user: removed.user,
349+ text: removed.text,
350+ submitted_at: removed.submitted_at,
351+ updated_at: removed.updated_at,
352+ }))
353+ })
354+ .await
286355 }
287356
288357 #[cfg(test)]
src/db/meal_attendance.rsmodified+64 -61
@@ -1,38 +1,31 @@
11 //! The `meal_attendance` table: the kitchen's marks — one atomic UPSERT per
2-//! (menu, student) that rides the menu's revision bump
3-//! ([`bump_menu_and_write`](crate::db::menu::bump_menu_and_write)), plus the
4-//! two listings. Attendance is reporting only: nothing here writes the
5-//! ledger, and the workflows that read it live in the web layer via
6-//! [`crate::service::meal_attendance`].
2+//! (menu, student) that rides the menu's revision bump inside its own
3+//! transaction, plus the two listings. Attendance is reporting only: nothing
4+//! here writes the ledger, and the workflows that read it live in the web
5+//! layer via [`crate::service::meal_attendance`].
76
8-use surrealdb::types::SurrealValue;
9-
10-use crate::database::Database;
11-use crate::db::menu::bump_menu_and_write;
12-use crate::db::page::PagedList;
13-use crate::domain::meal_attendance::{MealAttendance, MealAttendanceId, MealAttendanceStatus};
14-use crate::domain::menu::MenuDate;
15-use crate::domain::menu::MenuId;
7+use crate::database::{Database, tx_with_retry};
8+use crate::db::page::{PagedList, Param};
9+use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus};
10+use crate::domain::menu::{MenuDate, MenuId};
1611 use crate::domain::timestamp::Timestamp;
1712 use crate::domain::user::UserId;
1813 use crate::error::AppError;
1914
2015 /// Record (or overwrite) whether `student` ate off `menu`. One row per
21-/// pair by construction, so a correction is the same UPSERT flipping the
22-/// status. No ledger line, ever — see the domain module header.
16+/// pair by construction (`ON CONFLICT (menu, student)`), so a correction is
17+/// the same upsert flipping the status. No ledger line, ever — see the
18+/// domain module header.
2319 ///
2420 /// `NotFound` = the menu is gone, and the mark was *not* written. The mark
25-/// rides in [`bump_menu_and_write`], so the menu's existence is a *write* to
26-/// the menu row rather than a read the write then trusts: a delete racing
27-/// this one touches the very key this transaction bumps, and the store
28-/// refuses to commit both. Guarding by reading the menu — even as the
29-/// `UPSERT`'s own target — did not survive that race: the read saw a row
30-/// [`crate::db::menu::delete`] had deleted but not
31-/// yet committed, its sweep ran on a snapshot predating this insert, and the
32-/// mark outlived its menu with neither caller told anything (measured 378 of
33-/// 3600 raced rounds). Since [`MenuId::for_slot`] is deterministic,
34-/// republishing that day and slot then resurrected it as a mark on the new
35-/// menu.
21+/// and the menu's revision bump share one transaction, and the bump is what
22+/// makes the menu's **existence** part of it: the `UPDATE` matches nothing
23+/// once the menu row is deleted, and Postgres commits a deleting and a
24+/// bumping transaction on the same row strictly one after the other — the
25+/// mark either lands before the delete's guard re-reads its counter or not
26+/// at all. (Under the old store the same guarantee needed the shared bump
27+/// shape because deletes and child writes could interleave with a read in
28+/// between.)
3629 ///
3730 /// The bump costs a booking in flight one re-read (its seat claim asserts
3831 /// the revision it priced against) — the same tax every dish write already
@@ -45,30 +38,40 @@ pub async fn mark(
4538 status: MealAttendanceStatus,
4639 marked_by: &UserId,
4740 ) -> Result<MealAttendance, AppError> {
48- let row = MealAttendance {
49- id: MealAttendanceId::composite(menu, student),
50- menu: menu.clone(),
51- student: student.clone(),
52- status,
53- marked_by: marked_by.clone(),
54- marked_at: Timestamp::now(),
55- };
56- // Admissible for the retry loop inside: the id is bijective with the
57- // (menu, student) pair the table indexes UNIQUE, so this `UPSERT`
58- // resolves onto the row that index already points at instead of
59- // colliding with it — it can never answer "already exists", and a
60- // re-sent round writes the identical row.
61- bump_menu_and_write(
62- menu,
63- "UPSERT $id CONTENT $row RETURN AFTER",
64- vec![
65- ("id".into(), row.id.record().into_value()),
66- ("row".into(), row.into_value()),
67- ],
68- db,
69- )
70- .await?
71- .ok_or_else(|| AppError::Internal("failed to record the mark".into()))
41+ let marked_at = Timestamp::now();
42+ let student = *student;
43+ let marked_by = *marked_by;
44+ tx_with_retry(db, false, async |tx| {
45+ let bumped = sqlx::query!(
46+ "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1
47+ RETURNING 1 AS bumped",
48+ menu.key(),
49+ )
50+ .fetch_optional(&mut *tx)
51+ .await?;
52+ if bumped.is_none() {
53+ return Err(AppError::NotFound);
54+ }
55+ let row = sqlx::query_as!(
56+ MealAttendance,
57+ "INSERT INTO meal_attendance (menu, student, status, marked_by, marked_at)
58+ VALUES ($1, $2, $3, $4, $5)
59+ ON CONFLICT (menu, student) DO UPDATE
60+ SET status = EXCLUDED.status,
61+ marked_by = EXCLUDED.marked_by,
62+ marked_at = EXCLUDED.marked_at
63+ RETURNING menu, student, status, marked_by, marked_at",
64+ menu.key(),
65+ student,
66+ status,
67+ marked_by,
68+ marked_at,
69+ )
70+ .fetch_one(&mut *tx)
71+ .await?;
72+ Ok(row)
73+ })
74+ .await
7275 }
7376
7477 /// The kitchen's list for one menu.
@@ -79,10 +82,10 @@ pub async fn list_for_menu(
7982 offset: i64,
8083 ) -> Result<(Vec<MealAttendance>, i64), AppError> {
8184 PagedList::new(
82- "meal_attendance WHERE menu = $menu",
83- "ORDER BY marked_at DESC, id DESC",
85+ "meal_attendance WHERE menu = $1",
86+ "ORDER BY marked_at DESC, menu DESC",
8487 )
85- .bind("menu", menu.record())
88+ .bind(menu.key().to_string())
8689 .run(limit, offset, db)
8790 .await
8891 }
@@ -91,7 +94,7 @@ pub async fn list_for_menu(
9194 /// `YYYY-MM-DD` bounds on the *menu's* day — the comparison is lexical,
9295 /// which is chronological for that format (see [`MenuDate`]), and the link
9396 /// is followed rather than denormalized so a row can never disagree with
94-/// the menu it belongs to.
97+/// the menu it belongs to. A `NULL` bound means the bound is absent.
9598 pub async fn list_for_student(
9699 db: &Database,
97100 student: &UserId,
@@ -101,14 +104,14 @@ pub async fn list_for_student(
101104 offset: i64,
102105 ) -> Result<(Vec<MealAttendance>, i64), AppError> {
103106 PagedList::new(
104- "meal_attendance WHERE student = $usr \
105- AND ($from = NONE OR menu.date >= $from) \
106- AND ($to = NONE OR menu.date <= $to)",
107- "ORDER BY marked_at DESC, id DESC",
107+ "meal_attendance WHERE student = $1 \
108+ AND ($2::text IS NULL OR menu IN (SELECT id FROM menu WHERE date >= $2::text)) \
109+ AND ($3::text IS NULL OR menu IN (SELECT id FROM menu WHERE date <= $3::text))",
110+ "ORDER BY marked_at DESC, menu DESC",
108111 )
109- .bind("usr", student.record())
110- .bind("from", from.map(|date| date.as_str().to_string()))
111- .bind("to", to.map(|date| date.as_str().to_string()))
112+ .bind(student.key())
113+ .bind(Param::OptText(from.map(|date| date.as_str().to_string())))
114+ .bind(Param::OptText(to.map(|date| date.as_str().to_string())))
112115 .run(limit, offset, db)
113116 .await
114117 }
src/db/meal_booking.rsmodified+233 -191
@@ -1,14 +1,11 @@
11 //! The `meal_booking` table: row reads, the two listings, and the folded
2-//! transactions every seat moves by — [`claim_and_place`] (seat + row + charge
3-//! in one `BEGIN…COMMIT`) and [`release_seat`] (flip + counter + refund in
4-//! one). The book/cancel workflows that sequence these live in
5-//! [`crate::service::meal_booking`]; the row shape and the deadline checks in
6-//! [`crate::domain::meal_booking`].
2+//! transactions every seat moves by — [`claim_and_place`] (seat + row +
3+//! charge in one transaction) and [`release_seat`] (flip + counter + refund
4+//! in one). The book/cancel workflows that sequence these live in
5+//! [`crate::service::meal_booking`]; the row shape and the deadline checks
6+//! in [`crate::domain::meal_booking`].
77
8-use surrealdb::types::RecordId;
9-
10-use crate::constant::{CAP_WRITE_TRIES, MENU_SEAT_COUNT_FIELD, MENU_VERSION_FIELD};
11-use crate::database::{Database, backoff, lost_the_race};
8+use crate::database::{Database, tx_with_retry};
129 use crate::db::cap::Claimed;
1310 use crate::db::page::PagedList;
1411 use crate::domain::meal_booking::{MealBooking, MealBookingId};
@@ -19,7 +16,16 @@ use crate::domain::user::UserId;
1916 use crate::error::AppError;
2017
2118 pub async fn read(db: &Database, id: &MealBookingId) -> Result<Option<MealBooking>, AppError> {
22- Ok(db.select(id.record()).await?)
19+ let row = sqlx::query_as!(
20+ MealBooking,
21+ "SELECT menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at
22+ FROM meal_booking WHERE menu = $1 AND student = $2",
23+ id.menu().key(),
24+ *id.student(),
25+ )
26+ .fetch_optional(db)
27+ .await?;
28+ Ok(row)
2329 }
2430
2531 /// Every booking on a menu, cancelled ones included — the kitchen's list.
@@ -30,10 +36,10 @@ pub async fn list_for_menu(
3036 offset: i64,
3137 ) -> Result<(Vec<MealBooking>, i64), AppError> {
3238 PagedList::new(
33- "meal_booking WHERE menu = $menu",
34- "ORDER BY created_at DESC, id DESC",
39+ "meal_booking WHERE menu = $1",
40+ "ORDER BY created_at DESC, student DESC",
3541 )
36- .bind("menu", menu.record())
42+ .bind(menu.key().to_string())
3743 .run(limit, offset, db)
3844 .await
3945 }
@@ -41,10 +47,10 @@ pub async fn list_for_menu(
4147 /// Every seat held for one of `students`, newest first — a caller's own
4248 /// list is themselves plus whoever they hold a *live* parent link to.
4349 ///
44-/// Deliberately **not** `booked_by = $usr`: who placed a booking is history
45-/// written onto a READONLY column, and history is not a read grant. A
46-/// parent whose link was revoked (by an unlink or by the student-side role
47-/// sweep) would otherwise keep a live view of the child's seat, watching
50+/// Deliberately **not** `booked_by`: who placed a booking is history
51+/// written onto a fixed column, and history is not a read grant. A parent
52+/// whose link was revoked (by an unlink or by the student-side role sweep)
53+/// would otherwise keep a live view of the child's seat, watching
4854 /// cancellations made long after the link died — exactly what
4955 /// [`ensure_can_observe`](crate::service::parent_link::ensure_can_observe) refuses. The
5056 /// caller re-derives the list from the links on every read, so the view
@@ -55,34 +61,52 @@ pub async fn list_for_students(
5561 limit: Option<i64>,
5662 offset: i64,
5763 ) -> Result<(Vec<MealBooking>, i64), AppError> {
58- PagedList::new(
59- "meal_booking WHERE student IN $students",
60- "ORDER BY created_at DESC, id DESC",
61- )
62- .bind(
63- "students",
64- students.iter().map(UserId::record).collect::<Vec<_>>(),
64+ if students.is_empty() {
65+ return Ok((Vec::new(), 0));
66+ }
67+ let keys: Vec<String> = students.iter().map(UserId::key).collect();
68+ let rows = sqlx::query_as!(
69+ MealBooking,
70+ "SELECT menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at
71+ FROM meal_booking WHERE student = ANY($1::uuid[])
72+ ORDER BY created_at DESC, menu DESC
73+ LIMIT $2 OFFSET $3",
74+ keys,
75+ limit,
76+ offset,
6577 )
66- .run(limit, offset, db)
67- .await
78+ .fetch_all(db)
79+ .await?;
80+ // The window's own total — the same count the paging envelope answers.
81+ let total = if limit.is_some() || offset != 0 {
82+ sqlx::query_scalar!(
83+ "SELECT count(*) FROM meal_booking WHERE student = ANY($1::uuid[])",
84+ keys,
85+ )
86+ .fetch_one(db)
87+ .await? as i64
88+ } else {
89+ rows.len() as i64
90+ };
91+ Ok((rows, total))
6892 }
6993
7094 /// Take the seat **and** place the row in one transaction, at the menu
7195 /// revision the price was read at.
7296 ///
73-/// The seat and the row cannot be two steps. The id is the (menu, student)
74-/// pair, so two `POST`s of the same seat both find no row and both claim —
75-/// and on a tight cap the second is then told "full" for a seat it never
76-/// owed, while the winner's row may not even be visible yet. Here the
77-/// duplicate `CREATE` aborts the transaction, which takes its increment with
78-/// it: the counter never counts a row that does not exist, and a loser is
79-/// answered with the winner's booking instead of a refusal. Same shape as
80-/// [`cap::claim_and_create`](crate::db::cap::claim_and_create), with the
81-/// revision guard and the revival of a cancelled row that the general form
82-/// does not carry.
97+/// The seat and the row cannot be two steps. The row key is the (menu,
98+/// student) pair, so two `POST`s of the same seat both find no row and both
99+/// claim — and on a tight cap the second is then told "full" for a seat it
100+/// never owed, while the winner's row may not even be visible yet. Here the
101+/// duplicate insert answers [`Claimed::Duplicate`] and the caller replays
102+/// the winner, while the whole transaction (seat bump included) rolls back
103+/// on any refused path: the counter never counts a row that does not exist.
104+/// Same shape as the [`crate::db::cap`] claim recipe, with the revision
105+/// guard and the revival of a cancelled row that the general form does not
106+/// carry.
83107 ///
84108 /// A cancelled row is revived in place (a fresh attempt at `price`) rather
85-/// than recreated: `booked_by` and `created_at` are READONLY history — who
109+/// than recreated: `booked_by` and `created_at` are fixed history — who
86110 /// opened the seat, and when.
87111 ///
88112 /// **The charge rides this transaction too**, for the same reason the
@@ -93,118 +117,135 @@ pub async fn list_for_students(
93117 /// moved past. That is why `row.attempt` is minted by the *caller*: the
94118 /// charge's id is (seat, attempt), so the number cannot be the revival's own
95119 /// `attempt + 1` any more. The revival is fenced on the attempt it read
96-/// instead, so a rival that revived first loses this claim (the `CREATE`
97-/// below then finds the row and aborts the whole transaction) rather than
98-/// billing its attempt at this call's id.
120+/// instead, so a rival that revived first loses this claim (the insert below
121+/// then finds the row and answers `Duplicate`) rather than billing its
122+/// attempt at this call's id.
99123 ///
100-/// The charge is created only if it is not already there — a duplicate
101-/// `CREATE` would abort the transaction and cost the seat, and an attempt
124+/// The charge is created only if it is not already there — an attempt
102125 /// billed twice is the one thing money code may never do.
103126 pub(crate) async fn claim_and_place(
104127 db: &Database,
105- seats: &RecordId,
128+ menu: &MenuId,
106129 cap: i64,
107130 seen: i64,
108131 row: &MealBooking,
109132 price: Option<LedgerAmount>,
110133 charge: Option<&MealLedger>,
111134 ) -> Result<Claimed<MealBooking>, AppError> {
112- // Empty when the menu is free: a seat that costs nothing owes no line.
113- let bill = match charge {
114- Some(_) => {
115- "IF array::len((SELECT VALUE id FROM $charge)) = 0 \
116- { CREATE $charge CONTENT $line };"
135+ let menu_key = menu.key().to_string();
136+ let student = row.student;
137+ let attempt = row.attempt;
138+ tx_with_retry(db, false, async |tx| {
139+ // Already held? Same attempt, same price it was taken at — answered
140+ // as `Duplicate`, which the caller replays into the winner's row
141+ // (and its charge) without claiming anything.
142+ let held = sqlx::query!(
143+ "SELECT 1 AS held FROM meal_booking
144+ WHERE menu = $1 AND student = $2 AND status = 'booked'",
145+ menu_key,
146+ student,
147+ )
148+ .fetch_optional(&mut *tx)
149+ .await?;
150+ if held.is_some() {
151+ return Ok(Claimed::Duplicate);
117152 }
118- None => "",
119- };
120- // Slots count BEGIN, three LETs, three IFs and — when there is money to
121- // take — the charge's IF, so the RETURN is slot 7 or 8.
122- let returned = if charge.is_some() { 8 } else { 7 };
123- // Parenthesized `??` throughout: `a ?? 0 = $seen` binds the wrong way.
124- let sql = format!(
125- "BEGIN TRANSACTION;
126- LET $held = (SELECT VALUE id FROM $id WHERE status = 'booked');
127- IF array::len($held) > 0 {{ THROW 'held' }};
128- LET $seat = (UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = \
129- ({MENU_SEAT_COUNT_FIELD} ?? 0) + 1 \
130- WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) < $cap \
131- AND ({MENU_VERSION_FIELD} ?? 0) = $seen RETURN VALUE id);
132- IF array::len($seat) = 0 {{ THROW 'no_seat' }};
133- LET $revived = (UPDATE $id SET status = 'booked', attempt = $attempt, \
134- price_minor = $price, cancelled_at = NONE \
135- WHERE status = 'cancelled' AND attempt = $attempt - 1 RETURN AFTER);
136- IF array::len($revived) = 0 {{ CREATE $id CONTENT $row }};
137- {bill}
138- RETURN SELECT * FROM ONLY $id;
139- COMMIT TRANSACTION;"
140- );
141- // Every booking on one menu contends on that menu's single counter row,
142- // which is one HTTP burst of racers on a single parent — the case
143- // `CAP_WRITE_TRIES` is sized for. Three immediate re-sends with no
144- // backoff just re-synchronized them and 409'd the fourth student.
145- // Admissible: a lost round aborts the whole transaction (nothing
146- // written, no seat, no charge), and the two `CREATE`s that could
147- // legitimately answer "already exists" are read as `Claimed::Duplicate`
148- // below *before* the conflict check, so no decision is ever re-asked.
149- for attempt in 0..CAP_WRITE_TRIES {
150- backoff(attempt).await;
151- let query = db
152- .query(sql.as_str())
153- .bind(("menu", seats.clone()))
154- .bind(("cap", cap))
155- .bind(("seen", seen))
156- .bind(("id", row.id.record()))
157- .bind(("attempt", row.attempt))
158- .bind(("price", price))
159- .bind(("row", row.clone()));
160- let query = match charge {
161- Some(line) => query
162- .bind(("charge", line.get_id().record()))
163- .bind(("line", line.clone())),
164- None => query,
165- };
166- let mut result = match query.await {
167- Ok(result) => result,
168- Err(err) if lost_the_race(&err) => continue,
169- Err(err) => return Err(err.into()),
170- };
171- // An aborted transaction errors *every* slot, most with a generic
172- // "not executed" — only the failing slot says why, so scan them all.
173- let mut errors = result.take_errors();
174- if errors
175- .values()
176- .any(|error| error.to_string().contains("no_seat"))
177- {
153+ // The seat: one conditional single-row write on the menu, atomic
154+ // under Postgres — of the racers only `cap` of them per revision
155+ // get a non-empty result, and the rest are refused with nothing
156+ // written.
157+ let seat = sqlx::query!(
158+ "UPDATE menu SET seats_booked = seats_booked + 1
159+ WHERE id = $1 AND seats_booked < $2 AND COALESCE(version, 0) = $3
160+ RETURNING 1 AS seat",
161+ menu_key,
162+ cap,
163+ seen,
164+ )
165+ .fetch_optional(&mut *tx)
166+ .await?;
167+ if seat.is_none() {
178168 return Ok(Claimed::Full);
179169 }
180- if errors
181- .values()
182- .any(|error| error.to_string().contains("held") || error.is_already_exists())
183- {
170+ // Revive a cancelled row only while it still stands at the attempt
171+ // this call read — the fence that keeps a rival's revival from
172+ // being billed at this call's ids.
173+ let revived = sqlx::query_as!(
174+ MealBooking,
175+ "UPDATE meal_booking
176+ SET status = 'booked', attempt = $3, price_minor = $4, cancelled_at = NULL
177+ WHERE menu = $1 AND student = $2
178+ AND status = 'cancelled' AND attempt = $3 - 1
179+ RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at",
180+ menu_key,
181+ student,
182+ attempt,
183+ price,
184+ )
185+ .fetch_optional(&mut *tx)
186+ .await?;
187+ let placed = match revived {
188+ Some(row) => Some(row),
189+ None => {
190+ // No row (or a rival moved it past this attempt): place a
191+ // fresh one. A rival that landed first answers `Duplicate`
192+ // — nothing here overwrites its row.
193+ let inserted = sqlx::query_as!(
194+ MealBooking,
195+ "INSERT INTO meal_booking
196+ (menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at)
197+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
198+ ON CONFLICT (menu, student) DO NOTHING
199+ RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at",
200+ menu_key,
201+ student,
202+ row.booked_by,
203+ row.status,
204+ row.attempt,
205+ price,
206+ row.cancelled_at,
207+ row.created_at,
208+ )
209+ .fetch_optional(&mut *tx)
210+ .await?;
211+ inserted
212+ }
213+ };
214+ let Some(placed) = placed else {
184215 return Ok(Claimed::Duplicate);
185- }
186- if errors.values().any(lost_the_race) {
187- continue;
188- }
189- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
190- return Err(error.into());
191- }
192- return match result.take::<Option<MealBooking>>(returned)? {
193- Some(placed) => Ok(Claimed::Made(placed)),
194- None => Err(AppError::Internal("failed to book the meal".into())),
195216 };
196- }
197- Err(AppError::Conflict(
198- "the menu kept changing underneath this booking",
199- ))
217+ // The charge rides the same transaction; already there (a replayed
218+ // POST of this seat) means fine — nothing is written twice.
219+ if let Some(line) = charge {
220+ sqlx::query!(
221+ "INSERT INTO meal_ledger
222+ (id, student, kind, amount_minor, source, method, note, recorded_by, created_at)
223+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
224+ ON CONFLICT (id) DO NOTHING",
225+ line.id.key(),
226+ line.student,
227+ line.kind,
228+ line.amount_minor,
229+ line.source,
230+ line.method,
231+ line.note,
232+ line.recorded_by,
233+ line.created_at,
234+ )
235+ .execute(&mut *tx)
236+ .await?;
237+ }
238+ Ok(Claimed::Made(placed))
239+ })
240+ .await
200241 }
201242
202243 /// Flip the seat to `cancelled` and give it back to the menu's counter **in
203244 /// one transaction**, so the two can never disagree: a decrement that ran
204245 /// without the flip frees a seat still held, and a flip without the
205-/// decrement locks a seat nothing can ever release. The counter follows the
206-/// flip's own result (`array::len`), so a row already cancelled — by a
207-/// racing cancel, or by this call retried — decrements nothing.
246+/// decrement locks a seat nothing can ever release. The decrement rides the
247+/// flip's own result, so a row already cancelled — by a racing cancel, or
248+/// by this call retried — decrements nothing.
208249 ///
209250 /// **The refund rides this transaction too**, and it has to: the flip and a
210251 /// reversal appended after it are two writes, and a crash in between leaves
@@ -230,77 +271,78 @@ pub(crate) async fn claim_and_place(
230271 /// reversal id is burnt for good.
231272 ///
232273 /// `None` = the row was not this call's own `booked` attempt any more.
233-/// Retried while the store reports a write conflict: the menu row is
234-/// contended by every booking on it, and that contention is the cap
235-/// working, not an error.
236274 pub async fn release_seat(
237275 db: &Database,
238276 booked: &MealBooking,
239277 recorded_by: &UserId,
240278 ) -> Result<Option<MealBooking>, AppError> {
241279 let refund = MealLedger::reversal_for(booked, recorded_by);
242- // Guarded three ways: nothing was flipped (a rival cancelled first, and
243- // its own transaction carried the refund), the charge never landed, or
244- // this attempt is already refunded — none of which may abort the flip.
245- let reverse = match refund {
246- Some(_) => {
247- "IF array::len($flipped) > 0 \
248- AND array::len((SELECT VALUE id FROM $charge)) > 0 \
249- AND array::len((SELECT VALUE id FROM $reversal)) = 0 \
250- { CREATE $reversal CONTENT $line };"
251- }
252- None => "",
253- };
254- // Slots count BEGIN, the LET, the seat UPDATE and — when there is money
255- // to give back — the IF.
256- let returned = if refund.is_some() { 4 } else { 3 };
257- // Same burst on the same counter as the book side, so the same patience
258- // (see [`claim_and_place`]) — a cancel that gave up left the seat
259- // held with the charge standing. Admissible: the round aborts having
260- // written nothing, and a re-send finds the row already `cancelled`, so
261- // the flip matches nothing, the counter moves nothing and the guarded
262- // reversal — keyed to (seat, attempt) — is not written twice.
263- for attempt in 0..CAP_WRITE_TRIES {
264- backoff(attempt).await;
265- let attempted = async {
266- let query = db
267- .query(format!(
268- "BEGIN TRANSACTION;
269- LET $flipped = (UPDATE $id SET status = 'cancelled', \
270- cancelled_at = $now \
271- WHERE status = 'booked' AND attempt = $attempt RETURN AFTER);
272- UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = math::max([\
273- ({MENU_SEAT_COUNT_FIELD} ?? 0) - array::len($flipped), 0]);
274- {reverse}
275- RETURN $flipped;
276- COMMIT TRANSACTION;"
277- ))
278- .bind(("id", booked.id.record()))
279- .bind(("menu", booked.menu.record()))
280- .bind(("attempt", booked.attempt))
281- .bind(("now", Timestamp::now()));
282- let query = match &refund {
283- Some((charge, line)) => query
284- .bind(("charge", charge.record()))
285- .bind(("reversal", line.get_id().record()))
286- .bind(("line", line.clone())),
287- None => query,
288- };
289- let mut result = query.await?.check()?;
290- result.take::<Vec<MealBooking>>(returned)
280+ let menu_key = booked.menu.key().to_string();
281+ let student = booked.student;
282+ let attempt = booked.attempt;
283+ let cancelled_at = Timestamp::now();
284+ tx_with_retry(db, false, async |tx| {
285+ let flipped = sqlx::query_as!(
286+ MealBooking,
287+ "UPDATE meal_booking SET status = 'cancelled', cancelled_at = $3
288+ WHERE menu = $1 AND student = $2 AND status = 'booked' AND attempt = $4
289+ RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at",
290+ menu_key,
291+ student,
292+ cancelled_at,
293+ attempt,
294+ )
295+ .fetch_optional(&mut *tx)
296+ .await?;
297+ if flipped.is_some() {
298+ sqlx::query!(
299+ "UPDATE menu SET seats_booked = GREATEST(seats_booked - 1, 0) WHERE id = $1",
300+ menu_key,
301+ )
302+ .execute(&mut *tx)
303+ .await?;
291304 }
292- .await;
293- match attempted {
294- Ok(rows) => return Ok(rows.into_iter().next()),
295- Err(err) if lost_the_race(&err) => {}
296- Err(err) => return Err(err.into()),
305+ // Guarded three ways: nothing was flipped (a rival cancelled first,
306+ // and its own transaction carried the refund), the charge never
307+ // landed, or this attempt is already refunded — none of which may
308+ // abort the flip.
309+ if let (true, Some((charge, line))) = (flipped.is_some(), &refund) {
310+ let charge_there = sqlx::query!(
311+ "SELECT 1 AS there FROM meal_ledger WHERE id = $1",
312+ charge.key(),
313+ )
314+ .fetch_optional(&mut *tx)
315+ .await?;
316+ let reversal_there = sqlx::query!(
317+ "SELECT 1 AS there FROM meal_ledger WHERE id = $1",
318+ line.id.key(),
319+ )
320+ .fetch_optional(&mut *tx)
321+ .await?;
322+ if charge_there.is_some() && reversal_there.is_none() {
323+ sqlx::query!(
324+ "INSERT INTO meal_ledger
325+ (id, student, kind, amount_minor, source, method, note, recorded_by, created_at)
326+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
327+ ON CONFLICT (id) DO NOTHING",
328+ line.id.key(),
329+ line.student,
330+ line.kind,
331+ line.amount_minor,
332+ line.source,
333+ line.method,
334+ line.note,
335+ line.recorded_by,
336+ line.created_at,
337+ )
338+ .execute(&mut *tx)
339+ .await?;
340+ }
297341 }
298- }
299- Err(AppError::Conflict(
300- "the menu kept changing underneath this cancellation",
301- ))
342+ Ok(flipped)
343+ })
344+ .await
302345 }
303-
304346 #[cfg(test)]
305347 mod tests {
306348 use super::*;
src/db/meal_ledger.rsmodified+64 -77
@@ -3,29 +3,14 @@
33 //! convention live in [`crate::domain::meal_ledger`]; the charge/reversal
44 //! and credit workflows that sequence these in [`crate::service::meal_ledger`].
55
6-use surrealdb::types::{AlreadyExistsError, SurrealValue};
7-
8-use crate::constant::{CAS_UPDATE_RETRIES, MEAL_LEDGER_TABLE};
9-use crate::database::{Database, lost_the_race};
10-use crate::db::menu_dish;
6+use crate::database::Database;
117 use crate::db::page::PagedList;
12-use crate::domain::meal_ledger::{LedgerAmount, MealLedger, MealLedgerId, MealLedgerKind};
8+use crate::domain::meal_ledger::{LedgerAmount, MealLedger, MealLedgerId};
139 use crate::domain::menu::MenuId;
1410 use crate::domain::user::UserId;
1511 use crate::error::AppError;
1612
17-/// Did this `CREATE` fail *only* because the row is already there? Matched on
18-/// the SDK's typed `AlreadyExists`/`Record` detail — never on the message text
19-/// and never on "any database error", because swallowing a real fault in money
20-/// code would be far worse than the 500 it saves.
21-fn is_duplicate_record(error: &surrealdb::Error) -> bool {
22- matches!(
23- error.already_exists_details(),
24- Some(AlreadyExistsError::Record { .. })
25- )
26-}
27-
28-/// The only writer: one `CREATE`, no update path anywhere in this module.
13+/// The only writer: one `INSERT`, no update path anywhere in this module.
2914 ///
3015 /// A line whose id already exists is left exactly as it is — the row wins,
3116 /// the write is dropped. That is what makes a deterministic id (see
@@ -33,38 +18,52 @@ fn is_duplicate_record(error: &surrealdb::Error) -> bool {
3318 /// append is a no-op, never a second line and never an edit of the first.
3419 /// The point read is on the id itself, so unlike a scan it cannot miss a
3520 /// row a concurrent writer just made — but it is only a fast path. The
36-/// guarantee is `CREATE`'s own: on an existing id it *errors* and leaves
37-/// the row untouched, so the writer that lost the race reads back the
38-/// winner's line instead of failing the request with a 500.
39-///
40-/// A *write conflict* is the same race decided one layer down — two
41-/// appends of one id arriving together are no longer serialized by a
42-/// process-wide lock, so the store aborts one as retryable instead of
43-/// answering it "already exists". Both are read back the same way, and a
44-/// conflict that turns out to have written nothing is simply tried again;
45-/// no path here can write a second line, since the id is the key.
21+/// guarantee is the insert's own `ON CONFLICT (id) DO NOTHING`: on an
22+/// existing id nothing is written, so the writer that lost the race reads
23+/// back the winner's line instead of failing the request with a 500.
4624 pub(crate) async fn append(db: &Database, row: MealLedger) -> Result<MealLedger, AppError> {
4725 if let Some(existing) = read(db, &row.id).await? {
4826 return Ok(existing);
4927 }
50- let id = row.id.clone();
51- for _ in 0..CAS_UPDATE_RETRIES {
52- match db.create(id.record()).content(row.clone()).await {
53- Ok(Some(created)) => return Ok(created),
54- Ok(None) => break,
55- Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => {
56- if let Some(existing) = read(db, &id).await? {
57- return Ok(existing);
58- }
59- }
60- Err(e) => return Err(e.into()),
61- }
28+ let inserted = sqlx::query_as!(
29+ MealLedger,
30+ "INSERT INTO meal_ledger
31+ (id, student, kind, amount_minor, source, method, note, recorded_by, created_at)
32+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
33+ ON CONFLICT (id) DO NOTHING
34+ RETURNING id, student, kind, amount_minor, source, method, note, recorded_by, created_at",
35+ row.id.key(),
36+ row.student,
37+ row.kind,
38+ row.amount_minor,
39+ row.source,
40+ row.method,
41+ row.note,
42+ row.recorded_by,
43+ row.created_at,
44+ )
45+ .fetch_optional(db)
46+ .await?;
47+ match inserted {
48+ Some(created) => Ok(created),
49+ // Lost the id to a concurrent append of the same line: the stored
50+ // row is the answer, never a second line.
51+ None => read(db, &row.id)
52+ .await?
53+ .ok_or_else(|| AppError::Internal("failed to write the ledger line".into())),
6254 }
63- Err(AppError::Internal("failed to write the ledger line".into()))
6455 }
6556
6657 pub async fn read(db: &Database, id: &MealLedgerId) -> Result<Option<MealLedger>, AppError> {
67- Ok(db.select(id.record()).await?)
58+ let row = sqlx::query_as!(
59+ MealLedger,
60+ "SELECT id, student, kind, amount_minor, source, method, note, recorded_by, created_at
61+ FROM meal_ledger WHERE id = $1",
62+ id.key(),
63+ )
64+ .fetch_optional(db)
65+ .await?;
66+ Ok(row)
6867 }
6968
7069 /// What a seat on `menu` costs *right now*: the sum of its dishes. `None`
@@ -77,12 +76,11 @@ pub async fn price_snapshot(
7776 db: &Database,
7877 menu: &MenuId,
7978 ) -> Result<Option<LedgerAmount>, AppError> {
80- let total = menu_dish::list_for_menu(db, menu)
81- .await?
82- .iter()
83- .fold(0i64, |sum, dish| {
84- sum.saturating_add(dish.get_price_minor().as_minor())
85- });
79+ let row =
80+ sqlx::query!("SELECT CAST(COALESCE(sum(price_minor), 0) AS BIGINT) AS total FROM menu_dish WHERE menu = $1", menu.key())
81+ .fetch_one(db)
82+ .await?;
83+ let total = row.total;
8684 if total == 0 {
8785 return Ok(None);
8886 }
@@ -97,10 +95,10 @@ pub async fn list_for_student(
9795 offset: i64,
9896 ) -> Result<(Vec<MealLedger>, i64), AppError> {
9997 PagedList::new(
100- "meal_ledger WHERE student = $student",
98+ "meal_ledger WHERE student = $1",
10199 "ORDER BY created_at DESC, id DESC",
102100 )
103- .bind("student", student.record())
101+ .bind(student.key())
104102 .run(limit, offset, db)
105103 .await
106104 }
@@ -118,38 +116,27 @@ pub async fn list_for_student(
118116 /// every later `GET /meals/balance/*`.
119117 ///
120118 /// **The signs stay on the kind**, applied by the very
121-/// [`MealLedgerKind::sign`]
122-/// the documented formula is spelled in. Summing `IF kind = 'charge' THEN
123-/// -amount …` in SQL would have folded the whole balance in one statement
124-/// and forked the one rule that decides what money means into a second
125-/// language, where nothing would fail the day the two disagreed. Grouping
126-/// instead keeps the aggregate ignorant of signs: it counts kinds, and
127-/// Rust still says what a kind does. A stored running total was the third
128-/// option and is a counter that can drift — a bug class this repo closes,
129-/// not one it opens.
119+/// [`MealLedgerKind::sign`](crate::domain::meal_ledger::MealLedgerKind::sign)
120+/// the documented formula is spelled in. Summing a signed CASE in SQL would
121+/// have folded the whole balance in one statement and forked the one rule
122+/// that decides what money means into a second language, where nothing
123+/// would fail the day the two disagreed. Grouping instead keeps the
124+/// aggregate ignorant of signs: it counts kinds, and Rust still says what a
125+/// kind does. A stored running total was the third option and is a counter
126+/// that can drift — a bug class this repo closes, not one it opens.
130127 pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError> {
131- let totals: Vec<KindTotal> = db
132- .query(format!(
133- "SELECT kind, math::sum(amount_minor) AS total \
134- FROM {MEAL_LEDGER_TABLE} WHERE student = $student GROUP BY kind"
135- ))
136- .bind(("student", student.record()))
137- .await?
138- .check()?
139- .take(0)?;
128+ let totals = sqlx::query!(
129+ r#"SELECT kind AS "kind: crate::domain::meal_ledger::MealLedgerKind",
130+ CAST(sum(amount_minor) AS BIGINT) AS total
131+ FROM meal_ledger WHERE student = $1 GROUP BY kind"#,
132+ *student,
133+ )
134+ .fetch_all(db)
135+ .await?;
140136 Ok(totals
141137 .iter()
142138 .fold(0i64, |sum, row| sum + row.kind.sign() * row.total))
143139 }
144-
145-/// One kind's whole sum, as the `GROUP BY` in [`balance_of`] hands
146-/// it back — at most three rows, never the lines behind them.
147-#[derive(Debug, SurrealValue)]
148-struct KindTotal {
149- kind: MealLedgerKind,
150- total: i64,
151-}
152-
153140 #[cfg(test)]
154141 mod tests {
155142 use super::*;
src/db/menu.rsmodified+173 -205
@@ -1,100 +1,33 @@
11 //! The `menu` table: publishing (the slot reference claimed inside the
22 //! write's own transaction), row reads and listings, the compare-and-set
3-//! every cap PATCH writes through, the cascading delete, and
4-//! [`bump_menu_and_write`] — the shared "write the menu row too" shape every
5-//! child write (a dish, an attendance mark) uses so nothing can outlive its
6-//! menu. The kitchen workflows — the dish cap under
7-//! [`MENU_LOCK`](crate::service::menu::MENU_LOCK) — live in
3+//! every cap PATCH writes through, and the cascading delete. The kitchen
4+//! workflows — the guarded dish-cap insert — live in
85 //! [`crate::service::menu`].
96
10-use surrealdb::types::{SurrealValue, Value};
11-
12-use crate::constant::{
13- MEAL_ATTENDANCE_TABLE, MENU_DISH_TABLE, MENU_SEAT_COUNT_FIELD, MENU_VERSION_FIELD,
14- REF_COUNT_FIELD,
15-};
16-use crate::database::{Database, transaction_with_retry, write_with_retry};
17-use crate::db::cap;
18-use crate::db::page::PagedList;
7+use crate::database::{Database, tx_with_retry, unique_violation};
8+use crate::db::page::{PagedList, Param};
199 use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, slot_ref};
2010 use crate::domain::timestamp::Timestamp;
2111 use crate::domain::user::UserId;
2212 use crate::error::AppError;
2313
24-/// Move the menu's revision **and** run `statement` — a write to something
25-/// hanging off a menu — in one transaction, handing back the row it returned.
26-///
27-/// What a seat on that menu costs, or who is recorded against it, is about to
28-/// change, so any booking that priced itself against the old revision has to
29-/// re-read. The bump cannot be a query of its own: in the gap the menu row
30-/// carries the *new* revision with the *old* price, and a booking reading there
31-/// passes the very CAS that exists to refuse it — a seat billed a price the
32-/// menu had already left, or admitted past a capacity that had already shrunk.
33-///
34-/// The bump is also what makes the menu's **existence** part of the write
35-/// ([`crate::db::menu_dish::create`] leans on
36-/// the same thing): the `UPDATE` matches nothing once the menu row is deleted,
37-/// and a delete racing this one touches the very key this transaction writes,
38-/// so the two cannot both commit. Reading the menu instead — even as the write
39-/// statement's own target — does not survive that race: the read sees a row the
40-/// delete has not committed yet, and [`delete`]'s sweep ran on a snapshot
41-/// predating this insert, so both commit and the child outlives its menu
42-/// (measured 378 of 3600 raced rounds before this shape was shared).
43-///
44-/// Deliberately on every such write, not only the ones that move
45-/// `price_minor`: a re-tagged dish is cheap to re-read, and a rule that applies
46-/// to every write cannot be forgotten by the next one added.
47-///
48-/// Admissible for [`transaction_with_retry`] as long as `statement` is: an
49-/// `UPDATE`, a `DELETE`, a `SELECT`, an `IF`/`THROW` or a `RETURN` can never
50-/// answer "already exists", and neither can an `UPSERT` whose id is bijective
51-/// with every unique tuple its table indexes — a lost round wrote nothing, so
52-/// re-sending it is the recovery.
53-pub(crate) async fn bump_menu_and_write<T: SurrealValue>(
54- menu: &MenuId,
55- statement: &str,
56- mut bindings: Vec<(String, Value)>,
57- db: &Database,
58-) -> Result<Option<T>, AppError> {
59- bindings.push(("menu".into(), menu.record().into_value()));
60- let (mut result, mut errors) = transaction_with_retry(
61- db,
62- &format!(
63- "BEGIN TRANSACTION;
64- LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \
65- ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id);
66- IF array::len($bumped) = 0 {{ THROW 'no_menu' }};
67- LET $row = ({statement});
68- RETURN $row;
69- COMMIT TRANSACTION;"
70- ),
71- &bindings,
72- &["no_menu"],
73- )
74- .await?;
75- // An aborted transaction errors *every* slot, most with a generic "not
76- // executed" — only the THROW's own slot names the reason.
77- if errors
78- .values()
79- .any(|error| error.to_string().contains("no_menu"))
80- {
81- return Err(AppError::NotFound);
82- }
83- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
84- return Err(error.into());
85- }
86- // Slots count BEGIN, the LET, the IF and the second LET: the RETURN is 4.
87- Ok(result.take::<Vec<T>>(4)?.into_iter().next())
88-}
89-
9014 /// Publish a menu. Refused (409) when the day+slot already carries one.
9115 ///
92-/// The day and slot *are* the record id ([`MenuId::for_slot`]), so the
93-/// refusal is decided by the store rather than by a check a concurrent
94-/// publish can outrun: two publishes of the same meal write one id, and the loser's
95-/// "already exists" becomes the same 409. The pre-check stays for the
96-/// ordinary case — and for menus published before ids were derived, whose
97-/// ULID key no new publish can collide with.
16+/// The day and slot *are* the row's primary key ([`MenuId::for_slot`]), so
17+/// the refusal is decided by the store rather than by a check a concurrent
18+/// publish can outrun: two publishes of the same meal write one row, and
19+/// the loser's unique violation on `menu_pkey` becomes the same 409. The
20+/// in-transaction pre-check stays for the ordinary case.
21+///
22+/// The menu takes a reference on its slot, which is what stops the slot
23+/// being dropped from the settings while this menu (whose slot is only
24+/// snapshotted text) still points at it. Claimed *inside* the write's own
25+/// transaction, with the duplicate gate ahead of the retired check so
26+/// "you already published this" still outranks "the slot is retired" (the
27+/// [`crate::db::cap`] reference-claim recipe): the counted row and the
28+/// count commit together or not at all, so no crash window is small enough
29+/// to leave a slot counted by a menu that does not exist — a slot nobody
30+/// could ever retire.
9831 pub async fn create(
9932 db: &Database,
10033 date: MenuDate,
@@ -102,39 +35,80 @@ pub async fn create(
10235 capacity: Option<i64>,
10336 created_by: &UserId,
10437 ) -> Result<Menu, AppError> {
105- let taken = AppError::Conflict("a menu is already published for that date and slot");
106- if find(db, &date, &slot).await?.is_some() {
107- return Err(taken);
108- }
109- // The menu takes a reference on its slot, which is what stops the slot
110- // being dropped from the settings while this menu (whose slot is only
111- // snapshotted text) still points at it. Claimed *inside* the write's own
112- // transaction: a claim of its own could land and the row then fail to,
113- // leaving the slot counted by a menu that does not exist — a slot
114- // nobody can ever retire, and no crash window is small enough for that.
38+ let id_key = MenuId::for_slot(&date, &slot).key().to_string();
11539 let counter = slot_ref(slot.as_str());
116- let menu = Menu {
117- id: MenuId::for_slot(&date, &slot),
118- date,
119- slot,
120- capacity,
121- version: Some(0),
122- created_by: created_by.clone(),
123- created_at: Timestamp::now(),
124- };
125- let id = menu.id.record();
126- match cap::claim_ref_and_create(&counter, 1, &id, &menu, db).await? {
127- cap::ClaimedRef::Made(created) => Ok(created),
128- cap::ClaimedRef::Duplicate => Err(taken),
129- cap::ClaimedRef::Retired => Err(AppError::ConflictOwned(format!(
130- "the '{}' meal slot has been removed from the school's settings",
131- menu.slot.as_str()
132- ))),
133- }
40+ let date_s = date.as_str().to_string();
41+ let slot_s = slot.as_str().to_string();
42+ let created_by = *created_by;
43+ let created_at = Timestamp::now();
44+ tx_with_retry(db, false, async |tx| {
45+ // Duplicate gate ahead of the retired check: "already published"
46+ // outranks "slot retired", on the very path a rival publish races.
47+ let exists = sqlx::query!("SELECT 1 AS taken FROM menu WHERE id = $1", id_key,)
48+ .fetch_optional(&mut *tx)
49+ .await?;
50+ if exists.is_some() {
51+ return Err(AppError::Conflict(
52+ "a menu is already published for that date and slot",
53+ ));
54+ }
55+ let inserted = match sqlx::query_as!(
56+ Menu,
57+ "WITH ref AS (
58+ INSERT INTO slot_ref (name, count) VALUES ($2, 1)
59+ ON CONFLICT (name) DO UPDATE SET count = slot_ref.count + 1
60+ WHERE slot_ref.retired = false
61+ RETURNING 1 AS ref
62+ )
63+ INSERT INTO menu (id, date, slot, capacity, version, created_by, created_at)
64+ SELECT $1, $3, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM ref)
65+ RETURNING id, date, slot, capacity, version, created_by, created_at",
66+ id_key,
67+ counter,
68+ date_s,
69+ slot_s,
70+ capacity,
71+ Some(0i64),
72+ created_by,
73+ created_at,
74+ )
75+ .fetch_optional(&mut *tx)
76+ .await
77+ {
78+ Ok(row) => row,
79+ Err(err) => {
80+ // A rival published the same meal after the pre-check: its
81+ // row owns the key, and its publish is the answer.
82+ if unique_violation(&err) == Some("menu_pkey") {
83+ return Err(AppError::Conflict(
84+ "a menu is already published for that date and slot",
85+ ));
86+ }
87+ return Err(err.into());
88+ }
89+ };
90+ match inserted {
91+ Some(menu) => Ok(menu),
92+ // The slot's ref row is retired — nothing was written.
93+ None => Err(AppError::ConflictOwned(format!(
94+ "the '{}' meal slot has been removed from the school's settings",
95+ slot_s,
96+ ))),
97+ }
98+ })
99+ .await
134100 }
135101
136102 pub async fn read(db: &Database, id: &MenuId) -> Result<Option<Menu>, AppError> {
137- Ok(db.select(id.record()).await?)
103+ let row = sqlx::query_as!(
104+ Menu,
105+ "SELECT id, date, slot, capacity, version, created_by, created_at
106+ FROM menu WHERE id = $1",
107+ id.key(),
108+ )
109+ .fetch_optional(db)
110+ .await?;
111+ Ok(row)
138112 }
139113
140114 /// The menu for one day and slot, if any — the uniqueness check.
@@ -143,18 +117,21 @@ pub async fn find(
143117 date: &MenuDate,
144118 slot: &MenuSlot,
145119 ) -> Result<Option<Menu>, AppError> {
146- let mut result = db
147- .query("SELECT * FROM menu WHERE date = $date AND slot = $slot LIMIT 1")
148- .bind(("date", date.as_str().to_string()))
149- .bind(("slot", slot.as_str().to_string()))
150- .await?
151- .check()?;
152- Ok(result.take::<Vec<Menu>>(0)?.into_iter().next())
120+ let row = sqlx::query_as!(
121+ Menu,
122+ "SELECT id, date, slot, capacity, version, created_by, created_at
123+ FROM menu WHERE date = $1 AND slot = $2 LIMIT 1",
124+ date.as_str(),
125+ slot.as_str(),
126+ )
127+ .fetch_optional(db)
128+ .await?;
129+ Ok(row)
153130 }
154131
155132 /// Menus, newest day first. `from`/`to` are inclusive `YYYY-MM-DD` bounds;
156-/// either may be omitted. The comparison is lexical, which is chronological
157-/// for this format.
133+/// either may be omitted (`NULL` bound). The comparison is lexical, which
134+/// is chronological for this format.
158135 pub async fn list(
159136 db: &Database,
160137 from: Option<&MenuDate>,
@@ -163,25 +140,26 @@ pub async fn list(
163140 offset: i64,
164141 ) -> Result<(Vec<Menu>, i64), AppError> {
165142 PagedList::new(
166- "menu WHERE ($from = NONE OR date >= $from) AND ($to = NONE OR date <= $to)",
143+ "menu WHERE ($1::text IS NULL OR date >= $1::text) \
144+ AND ($2::text IS NULL OR date <= $2::text)",
167145 "ORDER BY date DESC, slot ASC, id DESC",
168146 )
169- .bind("from", from.map(|date| date.as_str().to_string()))
170- .bind("to", to.map(|date| date.as_str().to_string()))
147+ .bind(Param::OptText(from.map(|date| date.as_str().to_string())))
148+ .bind(Param::OptText(to.map(|date| date.as_str().to_string())))
171149 .run(limit, offset, db)
172150 .await
173151 }
174152
175-/// Only `capacity` is writable: `date` and `slot` are `READONLY` columns,
153+/// Only `capacity` is writable: `date` and `slot` are fixed at publish,
176154 /// because moving a published menu to another day is a different menu.
177155 /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped.
178156 ///
179157 /// The revision moves **in the same statement** as the cap, indivisibly: a
180-/// booking claims its seat against the revision
181-/// it read the cap at, so a shrink that bumped in a query of its own left a
182-/// window where the row carried the *new* revision and the *old* cap — and
183-/// a booking arriving there passes a CAS meant to refuse it, over-admitting
184-/// by exactly the seats in flight.
158+/// booking claims its seat against the revision it read the cap at, so a
159+/// shrink that bumped in a query of its own left a window where the row
160+/// carried the *new* revision and the *old* cap — and a booking arriving
161+/// there passes a CAS meant to refuse it, over-admitting by exactly the
162+/// seats in flight.
185163 pub async fn update(
186164 db: &Database,
187165 menu: Menu,
@@ -192,99 +170,89 @@ pub async fn update(
192170 // booking's price or cap has moved, so none owes a re-read.
193171 return read(db, &menu.id).await?.ok_or(AppError::NotFound);
194172 };
195- let sql = format!(
196- "UPDATE $id SET capacity = $capacity, \
197- {MENU_VERSION_FIELD} = ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN AFTER"
198- );
199- // One counter write in flight at a time, like every other one.
200- let _guard = cap::counter_lock().await;
201- write_with_retry::<Menu>(
202- db,
203- &sql,
204- &[
205- ("id".into(), menu.id.record().into_value()),
206- ("capacity".into(), capacity.into_value()),
207- ],
173+ let row = sqlx::query_as!(
174+ Menu,
175+ "UPDATE menu SET capacity = $2, version = COALESCE(version, 0) + 1
176+ WHERE id = $1
177+ RETURNING id, date, slot, capacity, version, created_by, created_at",
178+ menu.id.key(),
179+ capacity,
208180 )
209- .await?
210- .into_iter()
211- .next()
212- .ok_or(AppError::NotFound)
181+ .fetch_optional(db)
182+ .await?;
183+ row.ok_or(AppError::NotFound)
213184 }
214185
215-/// Delete the menu and the dishes on it — a dish has no meaning without
216-/// its menu, and the `menu` link is `READONLY`, so it cannot be re-homed.
186+/// Delete the menu and the dishes and marks on it — a dish or a mark has
187+/// no meaning without its menu, and the menu key cannot be re-homed.
217188 ///
218189 /// Refused (409) while a seat is still held, and the *row itself* decides
219190 /// that: the delete carries the seat counter in its `WHERE`, so a booking
220-/// landing at that instant either takes its seat before
221-/// the delete (which then finds a non-zero counter and refuses) or after it
222-/// (and finds no menu). A read-then-delete pair had a window where both
223-/// happened — a paid seat on a menu that no longer exists.
191+/// landing at that instant either takes its seat before the delete (which
192+/// then finds a non-zero counter and refuses) or after it (and finds no
193+/// menu). A read-then-delete pair had a window where both happened — a
194+/// paid seat on a menu that no longer exists.
224195 ///
225196 /// The slot gets its reference back in that same transaction — a slot no
226-/// menu is published for any more may leave the settings again, and the
227-/// `FOR` runs only over a row the guard actually took. Released afterwards
228-/// in a query of its own, a crash between the two left the slot counted by
229-/// a menu that no longer exists: a slot nobody can retire.
197+/// menu is published for any more may leave the settings again. Released
198+/// afterwards in a statement of its own, a crash between the two left the
199+/// slot counted by a menu that no longer exists: a slot nobody can retire.
230200 ///
231-/// The marks go in that same `FOR`, for a sharper reason than tidiness:
201+/// The marks go in that same sweep, for a sharper reason than tidiness:
232202 /// [`MenuId::for_slot`] is deterministic, so republishing the same day and
233-/// slot mints the *same* record id. A mark left behind would come back as a
203+/// slot mints the *same* row key. A mark left behind would come back as a
234204 /// mark on the new menu — the kitchen reading "served" for a student who
235205 /// never came — and until then the student's own report cites a menu that
236206 /// is gone. Attendance carries no money and no counter, so it is safe to
237-/// drop; cancelled *bookings* deliberately stay, because their `attempt`
238-/// counter is what keeps the ledger's `(booking, attempt)` keys unique. Cut
207+/// drop; cancelled *bookings* deliberately stay (no foreign key ties them
208+/// to the menu), because their `attempt` counter is what keeps the
209+/// ledger's `(booking, attempt)` keys unique across the republish. Cut
239210 /// those and a re-book on a republished menu would reuse a charge id the
240211 /// ledger already holds, and the append (idempotent by design) would bill
241212 /// the seat nothing.
242213 ///
243-/// The dishes ride in that `FOR` too, and for the same reason as the marks:
244-/// run after the transaction committed, a crash between the two orphaned
245-/// them on a record id republishing the day and slot mints again — a new
246-/// menu serving (and pricing) the old one's food.
214+/// The dishes ride in the same sweep: run after the commit, a crash
215+/// between the two would orphan them on the row key a republish mints
216+/// again — a new menu serving (and pricing) the old one's food.
247217 pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> {
248- let sql = format!(
249- "BEGIN TRANSACTION;
250- LET $gone = (DELETE $id WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE);
251- FOR $row IN ($gone ?? []) {{
252- UPSERT $counter SET {REF_COUNT_FIELD} = \
253- math::max([({REF_COUNT_FIELD} ?? 0) - 1, 0]);
254- DELETE {MEAL_ATTENDANCE_TABLE} WHERE menu = $id;
255- DELETE {MENU_DISH_TABLE} WHERE menu = $id;
256- }};
257- RETURN $gone;
258- COMMIT TRANSACTION;"
259- );
260- // `slot` is a `READONLY` column, so this counter is the one the deleted
261- // row carries. Nothing here can answer "already exists" — the `UPSERT`
262- // is keyed by a slot name on a table with no `UNIQUE` index, so it
263- // resolves onto the row it names ([`transaction_with_retry`]).
264- let (mut result, mut errors) = transaction_with_retry(
265- db,
266- &sql,
267- &[
268- ("id".into(), menu.id.record().into_value()),
269- ("counter".into(), slot_ref(menu.slot.as_str()).into_value()),
270- ],
271- &[],
272- )
218+ let key = menu.id.key().to_string();
219+ let counter = slot_ref(menu.slot.as_str());
220+ let deleted = tx_with_retry(db, true, async |tx| {
221+ let deleted = sqlx::query_as!(
222+ Menu,
223+ "DELETE FROM menu WHERE id = $1 AND seats_booked = 0
224+ RETURNING id, date, slot, capacity, version, created_by, created_at",
225+ key,
226+ )
227+ .fetch_optional(&mut *tx)
228+ .await?;
229+ let Some(row) = deleted else {
230+ return Ok(None);
231+ };
232+ sqlx::query!(
233+ "UPDATE slot_ref SET count = GREATEST(count - 1, 0) WHERE name = $1",
234+ counter,
235+ )
236+ .execute(&mut *tx)
237+ .await?;
238+ sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key)
239+ .execute(&mut *tx)
240+ .await?;
241+ sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key)
242+ .execute(&mut *tx)
243+ .await?;
244+ Ok(Some(row))
245+ })
273246 .await?;
274- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
275- return Err(error.into());
276- }
277- // BEGIN, the LET and the FOR take a slot each.
278- let Some(deleted) = result.take::<Vec<Menu>>(3)?.into_iter().next() else {
247+ match deleted {
248+ Some(menu) => Ok(menu),
279249 // Nothing back: either seats are held, or the menu is already gone.
280- return Err(match read(db, &menu.id).await? {
281- Some(_) => AppError::Conflict("the menu still has live bookings"),
282- None => AppError::NotFound,
283- });
284- };
285- Ok(deleted)
250+ None => match read(db, &menu.id).await? {
251+ Some(_) => Err(AppError::Conflict("the menu still has live bookings")),
252+ None => Err(AppError::NotFound),
253+ },
254+ }
286255 }
287-
288256 #[cfg(test)]
289257 mod tests {
290258 use super::*;
src/db/menu_dish.rsmodified+147 -124
@@ -1,14 +1,9 @@
1-//! The `menu_dish` table: the dishes on a menu — the insert and the field
2-//! PATCH riding the menu's revision bump ([`bump_menu_and_write`]), the
3-//! reads and listings, and the delete. The dish-cap gate and the
4-//! [`MENU_LOCK`](crate::service::menu::MENU_LOCK) leases live in
5-//! [`crate::service::menu`].
1+//! The `menu_dish` table: the dishes on a menu — the guarded insert (the
2+//! dish cap, enforced by the menu row's own lock), the field PATCH riding
3+//! the menu's revision bump, the reads and listings, and the delete. The
4+//! kitchen workflows live in [`crate::service::menu`].
65
7-use surrealdb::types::{SurrealValue, Value};
8-
9-use crate::constant::MENU_VERSION_FIELD;
10-use crate::database::{Database, transaction_with_retry};
11-use crate::db::menu::bump_menu_and_write;
6+use crate::database::{Database, tx_with_retry};
127 use crate::domain::menu::MenuId;
138 use crate::domain::menu_dish::{
149 DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId,
@@ -16,7 +11,15 @@ use crate::domain::menu_dish::{
1611 use crate::domain::timestamp::Timestamp;
1712 use crate::error::AppError;
1813
19-/// Add a dish. Moves the menu's revision *first* — see [`bump_menu_and_write`].
14+/// Add a dish. The dish cap is one guarded decision, not a count a caller
15+/// took a moment earlier: the menu row is locked `FOR NO KEY UPDATE` in
16+/// this write's own transaction and the `INSERT` runs with a
17+/// `count(*) < $cap` guard — a writer that queued on the lock behind a
18+/// concurrent one re-counts after it and is refused (`409`) instead of
19+/// overfilling. The revision bump rides the same transaction, and the
20+/// lock's `SELECT` is what makes the menu's **existence** part of the
21+/// write: it matches nothing once the menu row is deleted, so `NotFound`
22+/// means the dish was not written.
2023 pub async fn create(
2124 db: &Database,
2225 menu: &MenuId,
@@ -24,67 +27,67 @@ pub async fn create(
2427 description: Option<DishDescription>,
2528 price_minor: DishPrice,
2629 tags: DishTags,
30+ cap: i64,
2731 ) -> Result<MenuDish, AppError> {
28- let dish = MenuDish {
29- id: MenuDishId::generate(),
30- menu: menu.clone(),
31- name,
32- description,
33- price_minor,
34- tags,
35- created_at: Timestamp::now(),
36- };
37- // The revision bump and the insert are one transaction, and the bump is
38- // what makes the menu's existence part of it: the `UPDATE` matches
39- // nothing once the menu row is deleted, and a delete racing this one
40- // touches the very key this transaction writes, so the two cannot both
41- // commit. Without that, a dish landing just after `DELETE /menus/{id}`
42- // removed the row but before its cascade ran outlived its menu.
43- // Every other dish write bumps the same version key, so a lost round is
44- // ordinary here; it is re-sent rather than reported. Re-sending is sound
45- // even with the `CREATE` in the batch — the abort wrote nothing, the id
46- // is a ULID freshly generated above and never seen by a rival, and
47- // `menu_dish` carries no UNIQUE index — so the retry cannot answer
48- // "already exists" (see [`transaction_with_retry`]).
49- let (mut result, mut errors) = transaction_with_retry(
50- db,
51- &format!(
52- "BEGIN TRANSACTION;
53- LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \
54- ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id);
55- IF array::len($bumped) = 0 {{ THROW 'no_menu' }};
56- CREATE $id CONTENT $dish;
57- COMMIT TRANSACTION;"
58- ),
59- &[
60- ("menu".into(), menu.record().into_value()),
61- ("id".into(), dish.id.record().into_value()),
62- ("dish".into(), dish.into_value()),
63- ],
64- &["no_menu"],
65- )
66- .await?;
67- // An aborted transaction errors *every* slot, most with a generic "not
68- // executed" — only the THROW's own slot names the reason.
69- if errors
70- .values()
71- .any(|error| error.to_string().contains("no_menu"))
72- {
73- return Err(AppError::NotFound);
74- }
75- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
76- return Err(error.into());
77- }
78- // Slots count BEGIN, the LET and the IF: the CREATE is slot 3.
79- result
80- .take::<Vec<MenuDish>>(3)?
81- .into_iter()
82- .next()
83- .ok_or_else(|| AppError::Internal("failed to add the dish".into()))
32+ let menu_key = menu.key().to_string();
33+ let id = MenuDishId::generate();
34+ let created_at = Timestamp::now();
35+ tx_with_retry(db, false, async |tx| {
36+ // The lock first: every later statement in this transaction then
37+ // sees the committed state of whoever queued ahead of it.
38+ let locked = sqlx::query!(
39+ "SELECT 1 AS locked FROM menu WHERE id = $1 FOR NO KEY UPDATE",
40+ menu_key,
41+ )
42+ .fetch_optional(&mut *tx)
43+ .await?;
44+ if locked.is_none() {
45+ return Err(AppError::NotFound);
46+ }
47+ sqlx::query!(
48+ "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1",
49+ menu_key,
50+ )
51+ .execute(&mut *tx)
52+ .await?;
53+ let placed = sqlx::query_as!(
54+ MenuDish,
55+ "INSERT INTO menu_dish (id, menu, name, description, price_minor, tags, created_at)
56+ SELECT $1, $2, $3, $4, $5, $6, $7
57+ WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $8
58+ RETURNING id, menu, name, description, price_minor, tags, created_at",
59+ id,
60+ menu_key,
61+ name,
62+ description,
63+ price_minor,
64+ tags,
65+ created_at,
66+ cap,
67+ )
68+ .fetch_optional(&mut *tx)
69+ .await?;
70+ match placed {
71+ Some(dish) => Ok(dish),
72+ // The menu exists (locked above), so an empty result is the cap.
73+ None => Err(AppError::Conflict(
74+ "the menu already carries the maximum number of dishes",
75+ )),
76+ }
77+ })
78+ .await
8479 }
8580
8681 pub async fn read(db: &Database, id: &MenuDishId) -> Result<Option<MenuDish>, AppError> {
87- Ok(db.select(id.record()).await?)
82+ let row = sqlx::query_as!(
83+ MenuDish,
84+ "SELECT id, menu, name, description, price_minor, tags, created_at
85+ FROM menu_dish WHERE id = $1",
86+ id.key(),
87+ )
88+ .fetch_optional(db)
89+ .await?;
90+ Ok(row)
8891 }
8992
9093 /// 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<Vec<MenuD
98101 if menus.is_empty() {
99102 return Ok(Vec::new());
100103 }
101- let mut result = db
102- .query("SELECT * FROM menu_dish WHERE menu IN $menus ORDER BY id ASC")
103- .bind((
104- "menus",
105- menus.iter().map(MenuId::record).collect::<Vec<_>>(),
106- ))
107- .await?
108- .check()?;
109- Ok(result.take::<Vec<MenuDish>>(0)?)
110-}
111-
112-/// How many dishes the menu already carries — the `MAX_DISHES_PER_MENU` gate.
113-pub async fn count_for_menu(db: &Database, menu: &MenuId) -> Result<usize, AppError> {
114- Ok(list_for_menu(db, menu).await?.len())
104+ let keys: Vec<String> = menus.iter().map(|m| m.key().to_string()).collect();
105+ let rows = sqlx::query_as!(
106+ MenuDish,
107+ "SELECT id, menu, name, description, price_minor, tags, created_at
108+ FROM menu_dish WHERE menu = ANY($1) ORDER BY id ASC",
109+ keys,
110+ )
111+ .fetch_all(db)
112+ .await?;
113+ Ok(rows)
115114 }
116115
117116 /// Write only the fields the PATCH carried. `description` is nullable, so
118117 /// it takes the three-way shape: absent = keep, `Some(None)` = clear.
118+/// Each field is spelled with a "was it on the request?" flag and its
119+/// nullable value, so an omitted field is never written and a concurrent
120+/// PATCH of another one is not reverted.
119121 ///
120-/// The `SET` is built here rather than by
121-/// [`FieldUpdate`](crate::db::field_update::FieldUpdate) because the
122-/// revision bump lands on *another* row and has to share this write's
123-/// transaction; the field-by-field scoping — an omitted field is never
124-/// written, so a concurrent PATCH of another one is not reverted — is the
125-/// same rule, spelled out.
122+/// The revision bump lands in the same transaction — "every dish write
123+/// bumps" is the rule a caller can rely on without knowing which fields
124+/// were on the wire. A PATCH that carried nothing still bumps and reads
125+/// the row back.
126126 pub async fn update(
127127 db: &Database,
128128 dish: MenuDish,
@@ -131,45 +131,68 @@ pub async fn update(
131131 price_minor: Option<DishPrice>,
132132 tags: Option<DishTags>,
133133 ) -> Result<MenuDish, AppError> {
134- let mut sets: Vec<&str> = Vec::new();
135- let mut bindings: Vec<(String, Value)> = vec![("id".into(), dish.id.record().into_value())];
136- let mut set = |field: &'static str, value: Option<Value>| {
137- if let Some(value) = value {
138- sets.push(field);
139- bindings.push((field.into(), value));
134+ let dish_key = dish.id.key();
135+ let menu_key = dish.menu.key().to_string();
136+ tx_with_retry(db, false, async |tx| {
137+ let bumped = sqlx::query!(
138+ "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1
139+ RETURNING 1 AS bumped",
140+ menu_key,
141+ )
142+ .fetch_optional(&mut *tx)
143+ .await?;
144+ if bumped.is_none() {
145+ return Err(AppError::NotFound);
140146 }
141- };
142- set("name", name.map(SurrealValue::into_value));
143- set("description", description.map(SurrealValue::into_value));
144- set("price_minor", price_minor.map(SurrealValue::into_value));
145- set("tags", tags.map(SurrealValue::into_value));
146- // A PATCH that carried nothing writes nothing and reads the row back,
147- // exactly as `FieldUpdate` answers one — but it still moves the
148- // revision, because "every dish write bumps" is the rule a caller can
149- // rely on without knowing which fields were on the wire.
150- let statement = if sets.is_empty() {
151- "SELECT * FROM $id".to_string()
152- } else {
153- format!(
154- "UPDATE $id SET {} RETURN AFTER",
155- sets.iter()
156- .map(|field| format!("{field} = ${field}"))
157- .collect::<Vec<_>>()
158- .join(", ")
147+ let row = sqlx::query_as!(
148+ MenuDish,
149+ "UPDATE menu_dish SET
150+ name = COALESCE($2, name),
151+ description = CASE WHEN $3 THEN $4 ELSE description END,
152+ price_minor = COALESCE($5, price_minor),
153+ tags = COALESCE($6, tags)
154+ WHERE id = $1
155+ RETURNING id, menu, name, description, price_minor, tags, created_at",
156+ dish_key,
157+ name.map(|n| n.as_str().to_string()),
158+ description.is_some(),
159+ description
160+ .clone()
161+ .flatten()
162+ .map(|d| d.as_str().to_string()),
163+ price_minor.map(DishPrice::as_minor),
164+ tags.map(|t| t.as_slice().to_vec()),
159165 )
160- };
161- bump_menu_and_write(&dish.menu, &statement, bindings, db)
162- .await?
163- .ok_or(AppError::NotFound)
166+ .fetch_optional(&mut *tx)
167+ .await?;
168+ row.ok_or(AppError::NotFound)
169+ })
170+ .await
164171 }
165172
166173 pub async fn delete(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> {
167- bump_menu_and_write(
168- &dish.menu,
169- "DELETE $id RETURN BEFORE",
170- vec![("id".into(), dish.id.record().into_value())],
171- db,
172- )
173- .await?
174- .ok_or(AppError::NotFound)
174+ let dish_key = dish.id.key();
175+ let menu_key = dish.menu.key().to_string();
176+ tx_with_retry(db, false, async |tx| {
177+ let bumped = sqlx::query!(
178+ "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1
179+ RETURNING 1 AS bumped",
180+ menu_key,
181+ )
182+ .fetch_optional(&mut *tx)
183+ .await?;
184+ if bumped.is_none() {
185+ return Err(AppError::NotFound);
186+ }
187+ let row = sqlx::query_as!(
188+ MenuDish,
189+ "DELETE FROM menu_dish WHERE id = $1
190+ RETURNING id, menu, name, description, price_minor, tags, created_at",
191+ dish_key,
192+ )
193+ .fetch_optional(&mut *tx)
194+ .await?;
195+ row.ok_or(AppError::NotFound)
196+ })
197+ .await
175198 }
src/db/note.rsmodified+61 -44
@@ -1,9 +1,7 @@
11 //! The `note` table: one user's rows, listed newest first, deleted together
22 //! with their attachment rows.
33
4-use surrealdb::types::SurrealValue;
5-
6-use crate::database::Database;
4+use crate::database::{Database, tx_with_retry};
75 use crate::db::field_update::FieldUpdate;
86 use crate::db::page::PagedList;
97 use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle};
@@ -11,15 +9,6 @@ use crate::domain::note_file::NoteFile;
119 use crate::domain::user::UserId;
1210 use crate::error::AppError;
1311
14-/// What [`delete`]'s transaction removed: the note row (empty if it had
15-/// already vanished) and every attachment row the cascade took with it — the
16-/// only set whose blobs are safe to unlink.
17-#[derive(Debug, SurrealValue)]
18-struct DeleteOutcome {
19- note: Vec<Note>,
20- files: Vec<NoteFile>,
21-}
22-
2312 pub async fn create(
2413 db: &Database,
2514 owner: &UserId,
@@ -32,8 +21,20 @@ pub async fn create(
3221 title,
3322 content,
3423 };
35- let created: Option<Note> = db.create(note.id.record()).content(note).await?;
36- created.ok_or_else(|| AppError::Internal("failed to create note".into()))
24+ // whole-row-save-ok: insert of a fresh UUID row built in place by `new` — there is no prior row to clobber
25+ let created = sqlx::query_as!(
26+ Note,
27+ r#"INSERT INTO note (id, app_user, title, content)
28+ VALUES ($1, $2, $3, $4)
29+ RETURNING id, app_user AS "user", title, content"#,
30+ note.id,
31+ note.user,
32+ note.title,
33+ note.content
34+ )
35+ .fetch_one(db)
36+ .await?;
37+ Ok(created)
3738 }
3839
3940 /// Read a note only if it belongs to `owner`.
@@ -42,8 +43,15 @@ pub async fn read_owned(
4243 id: &NoteId,
4344 owner: &UserId,
4445 ) -> Result<Option<Note>, AppError> {
45- let note: Option<Note> = db.select(id.record()).await?;
46- Ok(note.filter(|note| &note.user == owner))
46+ let note = sqlx::query_as!(
47+ Note,
48+ r#"SELECT id, app_user AS "user", title, content FROM note WHERE id = $1 AND app_user = $2"#,
49+ id,
50+ owner
51+ )
52+ .fetch_optional(db)
53+ .await?;
54+ Ok(note)
4755 }
4856
4957 pub async fn list_for(
@@ -52,9 +60,9 @@ pub async fn list_for(
5260 limit: Option<i64>,
5361 offset: i64,
5462 ) -> Result<(Vec<Note>, i64), AppError> {
55- PagedList::new("note WHERE user = $usr", "ORDER BY id DESC")
56- .bind("usr", owner.record())
57- .run(limit, offset, db)
63+ PagedList::new("note WHERE app_user = $1", "ORDER BY id DESC")
64+ .bind(owner.uuid())
65+ .run::<Note>(limit, offset, db)
5866 .await
5967 }
6068
@@ -70,9 +78,12 @@ pub async fn update(
7078 title: Option<NoteTitle>,
7179 content: Option<NoteContent>,
7280 ) -> Result<Note, AppError> {
73- FieldUpdate::new(note.id.record())
74- .set("title", title)
75- .set("content", content)
81+ FieldUpdate::new("note", note.id.uuid())
82+ .set("title", title.map(|title| title.as_str().to_string()))
83+ .set(
84+ "content",
85+ content.map(|content| content.as_str().to_string()),
86+ )
7687 .run::<Note>(db)
7788 .await
7889 }
@@ -88,42 +99,48 @@ pub async fn update(
8899 /// Children first, in one transaction, the way
89100 /// [`crate::db::course::delete`] does it: as two queries, an
90101 /// upload that committed in between kept its row while the note went, and
91-/// nothing could ever list or delete it again.
102+/// nothing could ever list or delete it again. The `rag_output` sweep rides
103+/// here too: under real foreign keys a `rag_output` row citing this note
104+/// would refuse the delete (`ON DELETE NO ACTION`), and the derived rows
105+/// are exactly the thing that may never outlive its input — the web layer's
106+/// separate `delete_for_note` call stays, as a harmless idempotent repeat.
92107 pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec<NoteFile>), AppError> {
93- let mut result = db
94- .query(
95- "BEGIN TRANSACTION;
96- LET $files = (DELETE note_file WHERE note = $note RETURN BEFORE);
97- LET $gone = (DELETE $note RETURN BEFORE);
98- RETURN { note: $gone, files: $files };
99- COMMIT TRANSACTION;",
108+ tx_with_retry(db, true, async |conn| {
109+ sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id)
110+ .execute(&mut *conn)
111+ .await?;
112+ let files = sqlx::query_as!(
113+ NoteFile,
114+ r#"DELETE FROM note_file WHERE note = $1 RETURNING id, note, name, content_type, size"#,
115+ note.id
116+ )
117+ .fetch_all(&mut *conn)
118+ .await?;
119+ let gone = sqlx::query_as!(
120+ Note,
121+ r#"DELETE FROM note WHERE id = $1 RETURNING id, app_user AS "user", title, content"#,
122+ note.id
100123 )
101- .bind(("note", note.id.record()))
102- .await?
103- .check()?;
104- // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3.
105- let outcome = result
106- .take::<Vec<DeleteOutcome>>(3)?
107- .into_iter()
108- .next()
109- .ok_or_else(|| AppError::Internal("failed to delete note".into()))?;
110- let note = outcome.note.into_iter().next().ok_or(AppError::NotFound)?;
111- Ok((note, outcome.files))
124+ .fetch_optional(&mut *conn)
125+ .await?;
126+ let note = gone.ok_or(AppError::NotFound)?;
127+ Ok((note, files))
128+ })
129+ .await
112130 }
113131
114132 #[cfg(test)]
115133 mod tests {
116134 use super::*;
135+ use crate::domain::note_file::{FileContentType, FileName};
117136
118137 /// The blobs the handler unlinks are exactly the rows this transaction
119138 /// removed — including one uploaded after any pre-read snapshot would have
120139 /// been taken, which is the row whose blob used to leak.
121140 #[tokio::test]
122141 async fn delete_returns_the_attachment_rows_it_removed() {
123- use crate::domain::note_file::{FileContentType, FileName};
124-
125142 let db = crate::database::init_mem().await.unwrap();
126- let owner = crate::domain::user::UserId::generate();
143+ let owner = UserId::generate();
127144 let note = create(
128145 &db,
129146 &owner,
src/db/note_file.rsmodified+126 -137
@@ -2,9 +2,8 @@
22 //! first, with the note's file cap claimed and released in the same write as
33 //! the row.
44
5-use crate::constant::{MAX_NOTE_FILES, NOTE_FILE_COUNT_FIELD};
6-use crate::database::Database;
7-use crate::db::cap;
5+use crate::constant::MAX_NOTE_FILES;
6+use crate::database::{Database, tx_with_retry, unique_violation};
87 use crate::db::page::PagedList;
98 use crate::domain::note::NoteId;
109 use crate::domain::note_file::{NoteFile, NoteFileId};
@@ -12,31 +11,45 @@ use crate::error::AppError;
1211
1312 /// Persist the row assembled by [`NoteFile::new`], refusing once its note
1413 /// already holds [`MAX_NOTE_FILES`]. The slot and the row are taken together
15-/// by [`cap::claim_and_create`] on the note row: a `BEGIN…COMMIT` around a
16-/// count can't enforce the cap (SurrealDB doesn't conflict-check a
17-/// cross-record count against a concurrent insert) and a process-wide mutex
18-/// can't either, since it is released around the very round trip the insert
19-/// races — a conditional single-record write can. Claiming in a *separate*
20-/// query would enforce the cap but leak a slot on a crash between the two.
14+/// by one conditional statement on the note row (the claim CTE of
15+/// `cap::claim_and_create`, spelled out at its call site — see
16+/// `crate::db::cap`): a `BEGIN…COMMIT` around a count can't enforce the cap
17+/// and a process-wide mutex can't either, since it is released around the
18+/// very round trip the insert races — a single guarded statement can.
19+/// Claiming in a *separate* query would enforce the cap but leak a slot on
20+/// a crash between the two.
2121 pub async fn insert(db: &Database, file: NoteFile) -> Result<NoteFile, AppError> {
22- // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber
23- match cap::claim_and_create(
24- &file.note.record(),
25- NOTE_FILE_COUNT_FIELD,
22+ // whole-row-save-ok: insert of a fresh UUID row built in place by `new` — there is no prior row to clobber
23+ let created = sqlx::query_as!(
24+ NoteFile,
25+ r#"WITH seat AS (
26+ UPDATE note SET file_count = file_count + 1
27+ WHERE id = $1 AND file_count < $2
28+ RETURNING 1)
29+ INSERT INTO note_file (id, note, name, content_type, size)
30+ SELECT $3, $1, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat)
31+ RETURNING id, note, name, content_type, size"#,
32+ file.note,
2633 MAX_NOTE_FILES as i64,
27- &file.id.record(),
28- &file,
29- db,
34+ file.id,
35+ file.name,
36+ file.content_type,
37+ file.size
3038 )
31- .await?
32- {
33- cap::Claimed::Made(created) => Ok(created),
39+ .fetch_optional(db)
40+ .await;
41+ match created {
42+ Ok(Some(row)) => Ok(row),
3443 // Also how a missing note reads: no note row means no slot to take.
35- cap::Claimed::Full => Err(AppError::Conflict(
44+ Ok(None) => Err(AppError::Conflict(
3645 "the note already holds the maximum of 10 files — delete one first",
3746 )),
38- // Unreachable: the id is a ULID this call just generated.
39- cap::Claimed::Duplicate => Err(AppError::Internal("failed to create note file".into())),
47+ // A duplicate would be a 23505 on the row's own key, which this path
48+ // cannot produce — the id is a UUID this call just generated.
49+ Err(err) if unique_violation(&err).is_some() => {
50+ Err(AppError::Internal("failed to create note file".into()))
51+ }
52+ Err(err) => Err(err.into()),
4053 }
4154 }
4255
@@ -47,8 +60,15 @@ pub async fn read_for(
4760 id: &NoteFileId,
4861 note: &NoteId,
4962 ) -> Result<Option<NoteFile>, AppError> {
50- let file: Option<NoteFile> = db.select(id.record()).await?;
51- Ok(file.filter(|file| &file.note == note))
63+ let file = sqlx::query_as!(
64+ NoteFile,
65+ r#"SELECT id, note, name, content_type, size FROM note_file WHERE id = $1 AND note = $2"#,
66+ id,
67+ note
68+ )
69+ .fetch_optional(db)
70+ .await?;
71+ Ok(file)
5272 }
5373
5474 /// All of `note`'s attachment rows, newest first.
@@ -58,9 +78,9 @@ pub async fn list_for(
5878 limit: Option<i64>,
5979 offset: i64,
6080 ) -> Result<(Vec<NoteFile>, i64), AppError> {
61- PagedList::new("note_file WHERE note = $note", "ORDER BY id DESC")
62- .bind("note", note.record())
63- .run(limit, offset, db)
81+ PagedList::new("note_file WHERE note = $1", "ORDER BY id DESC")
82+ .bind(note.uuid())
83+ .run::<NoteFile>(limit, offset, db)
6484 .await
6585 }
6686
@@ -68,133 +88,102 @@ pub async fn list_for(
6888 /// itself is untouched, so unlike the note-delete cascade this one has a
6989 /// counter to correct. (Deleting a *note* takes its counter with it.)
7090 pub async fn delete(db: &Database, file: NoteFile) -> Result<NoteFile, AppError> {
71- let mut result = db
72- .query(
73- "BEGIN TRANSACTION;
74- LET $gone = (DELETE $id RETURN BEFORE);
75- UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]);
76- RETURN $gone;
77- COMMIT TRANSACTION;",
91+ tx_with_retry(db, true, async |conn| {
92+ let gone = sqlx::query_as!(
93+ NoteFile,
94+ r#"DELETE FROM note_file WHERE id = $1 RETURNING id, note, name, content_type, size"#,
95+ file.id
96+ )
97+ .fetch_optional(&mut *conn)
98+ .await?;
99+ let file = gone.ok_or(AppError::NotFound)?;
100+ sqlx::query!(
101+ "UPDATE note SET file_count = GREATEST(file_count - 1, 0) WHERE id = $1",
102+ file.note
78103 )
79- .bind(("id", file.id.record()))
80- .bind(("note", file.note.record()))
81- .await?
82- .check()?;
83- result
84- .take::<Vec<NoteFile>>(3)?
85- .into_iter()
86- .next()
87- .ok_or(AppError::NotFound)
104+ .execute(&mut *conn)
105+ .await?;
106+ Ok(file)
107+ })
108+ .await
88109 }
89110
90111 #[cfg(test)]
91112 mod tests {
92113 use super::*;
93- use crate::domain::note_file::{FileContentType, FileName};
114+ use crate::domain::note::NoteContent;
115+ use crate::domain::note::NoteTitle;
116+ use crate::domain::note_file::FileContentType;
117+ use crate::domain::note_file::FileName;
94118
95- #[tokio::test]
96- async fn rows_scope_to_their_note() {
97- let db = crate::database::init_mem().await.unwrap();
98- // Real note rows: the cap counter lives on the note, so an insert whose
99- // note does not exist has no slot to take (a 409, like a full note).
119+ async fn a_note(db: &Database) -> Note {
100120 let owner = crate::domain::user::UserId::generate();
101- let note_of = async |title: &str| {
102- crate::db::note::create(
103- &db,
104- &owner,
105- crate::domain::note::NoteTitle::try_new(title).unwrap(),
106- crate::domain::note::NoteContent::try_new("body").unwrap(),
107- )
108- .await
109- .unwrap()
110- };
111- let note_a = note_of("a").await.get_id().clone();
112- let note_b = note_of("b").await.get_id().clone();
113- let file = insert(
114- &db,
115- NoteFile::new(
116- &note_a,
117- FileName::try_new("plan.pdf").unwrap(),
118- FileContentType::try_new("application/pdf").unwrap(),
119- 3,
120- ),
121+ crate::db::note::create(
122+ db,
123+ &owner,
124+ NoteTitle::try_new("n").unwrap(),
125+ NoteContent::try_new("b").unwrap(),
121126 )
122127 .await
123- .unwrap();
124-
125- // Readable under its own note, invisible under another.
126- let found = read_for(&db, file.get_id(), &note_a).await.unwrap();
127- assert_eq!(found.unwrap().get_name().as_str(), "plan.pdf");
128- assert!(
129- read_for(&db, file.get_id(), &note_b)
130- .await
131- .unwrap()
132- .is_none()
133- );
134-
135- let listed = async |note: &NoteId| list_for(&db, note, None, 0).await.unwrap().0;
136- assert_eq!(listed(&note_a).await.len(), 1);
137- assert!(listed(&note_b).await.is_empty());
138-
139- delete(&db, file).await.unwrap();
140- assert!(listed(&note_a).await.is_empty());
128+ .unwrap()
141129 }
142130
143- /// The counter and the rows are written in one transaction, so the stored
144- /// count must equal the stored rows — after a success *and* after the
145- /// refusal that fills the cap, which must move neither.
131+ /// The cap answers with a conflict, and neither the refused row nor its
132+ /// slot was written: the count is still what the last accepted upload
133+ /// left.
146134 #[tokio::test]
147- async fn counter_tracks_stored_rows() {
135+ async fn insert_refuses_at_the_cap_without_leaking_a_slot() {
148136 let db = crate::database::init_mem().await.unwrap();
149- let note = crate::db::note::create(
150- &db,
151- &crate::domain::user::UserId::generate(),
152- crate::domain::note::NoteTitle::try_new("a").unwrap(),
153- crate::domain::note::NoteContent::try_new("body").unwrap(),
154- )
155- .await
156- .unwrap()
157- .get_id()
158- .clone();
159- let stored_count = async |note: &NoteId| -> i64 {
160- db.query("SELECT VALUE file_count FROM $note")
161- .bind(("note", note.record()))
162- .await
163- .unwrap()
164- .take::<Vec<i64>>(0)
165- .unwrap()
166- .into_iter()
167- .next()
168- .unwrap_or(0)
169- };
170- let add = async |note: &NoteId| {
171- insert(
172- &db,
173- NoteFile::new(
174- note,
175- FileName::try_new("plan.pdf").unwrap(),
176- FileContentType::try_new("application/pdf").unwrap(),
177- 3,
178- ),
179- )
180- .await
181- };
182-
183- for filled in 1..=MAX_NOTE_FILES {
184- add(&note).await.unwrap();
185- assert_eq!(stored_count(&note).await, filled as i64);
186- assert_eq!(
187- list_for(&db, &note, None, 0).await.unwrap().1,
188- filled as i64
137+ let note = a_note(&db).await;
138+ for index in 0..MAX_NOTE_FILES {
139+ let file = NoteFile::new(
140+ note.get_id(),
141+ FileName::try_new(&format!("f{index}")).unwrap(),
142+ FileContentType::try_new("text/plain").unwrap(),
143+ 1,
189144 );
145+ insert(&db, file).await.unwrap();
190146 }
147+ let over = NoteFile::new(
148+ note.get_id(),
149+ FileName::try_new("over").unwrap(),
150+ FileContentType::try_new("text/plain").unwrap(),
151+ 1,
152+ );
153+ assert!(matches!(
154+ insert(&db, over).await,
155+ Err(AppError::Conflict(_))
156+ ));
157+ let (files, total) = list_for(&db, note.get_id(), None, 0).await.unwrap();
158+ assert_eq!(total, MAX_NOTE_FILES as i64);
159+ assert_eq!(files.len(), MAX_NOTE_FILES);
160+ }
191161
192- // At the cap: the refusal writes nothing, counter included.
193- assert!(matches!(add(&note).await, Err(AppError::Conflict(_))));
194- assert_eq!(stored_count(&note).await, MAX_NOTE_FILES as i64);
195- assert_eq!(
196- list_for(&db, &note, None, 0).await.unwrap().1,
197- MAX_NOTE_FILES as i64
162+ /// Deleting a row hands its slot back: after one delete a new upload is
163+ /// accepted again, and the count never dips below zero.
164+ #[tokio::test]
165+ async fn delete_returns_the_slot_to_the_note() {
166+ let db = crate::database::init_mem().await.unwrap();
167+ let note = a_note(&db).await;
168+ let file = NoteFile::new(
169+ note.get_id(),
170+ FileName::try_new("f").unwrap(),
171+ FileContentType::try_new("text/plain").unwrap(),
172+ 1,
173+ );
174+ let file = insert(&db, file).await.unwrap();
175+ let gone = delete(&db, file.clone()).await.unwrap();
176+ assert_eq!(gone.get_id(), file.get_id());
177+ // Deleting it a second time is a 404, not a second decrement.
178+ assert!(matches!(delete(&db, file).await, Err(AppError::NotFound)));
179+ let next = NoteFile::new(
180+ note.get_id(),
181+ FileName::try_new("next").unwrap(),
182+ FileContentType::try_new("text/plain").unwrap(),
183+ 1,
198184 );
185+ insert(&db, next).await.unwrap();
186+ let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap();
187+ assert_eq!(total, 1);
199188 }
200189 }
src/db/pool_question.rsmodified+176 -192
@@ -1,137 +1,85 @@
11 //! The `pool_question` table: ask/insert, the two listings, the guarded
22 //! approve that rides the publish counters along, the pending-only image
3-//! writes, and the delete that cascades solutions — plus
4-//! [`bump_question_and_write`], the existence-move every child write goes
5-//! through. The pure entity and newtypes live in
6-//! [`crate::domain::pool_question`]; the web layer reaches these through
7-//! [`crate::service::pool_question`].
8-
9-use surrealdb::types::SurrealValue;
10-
11-use crate::constant::{
12- POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD, STATUS_APPROVED, STATUS_PENDING,
13-};
14-use crate::database::{Database, transaction_with_retry};
3+//! writes, and the delete that cascades solutions. The pure entity and
4+//! newtypes live in [`crate::domain::pool_question`]; the web layer reaches
5+//! these through [`crate::service::pool_question`].
6+
7+use crate::constant::{STATUS_APPROVED, STATUS_PENDING};
8+use crate::database::{Database, tx_with_retry};
159 use crate::domain::note_file::FileContentType;
1610 use crate::domain::pool_question::{PoolQuestion, PoolQuestionId};
1711 use crate::domain::solution::Solution;
1812 use crate::domain::user::UserId;
1913 use crate::error::AppError;
2014
21-/// Move the question's `asked_at` **and** run `statement` — a write to
22-/// something hanging off a question — in one transaction, handing back the row
23-/// it returned. `NotFound` means the question is gone and nothing was written.
24-///
25-/// The move is what makes the question's **existence** part of the child's own
26-/// write, the way [`crate::domain::menu::bump_menu_and_write`] does for a menu:
27-/// the `UPDATE` matches nothing once the row is deleted, and a delete racing
28-/// this one touches the very key this transaction writes, so the two cannot
29-/// both commit. Reading the question first does *not* survive that race — the
30-/// read sees a row [`delete`] has removed but not committed, while its
31-/// `DELETE solution WHERE question = $q` ran on a snapshot predating this
32-/// insert, so both commit and the child outlives its question with neither
33-/// caller told anything.
34-///
35-/// `asked_at` rather than a revision column because this row carries no counter
36-/// to bump and must not grow one for this alone. It is put back *by captured
37-/// value* in the same transaction, so nothing outside ever observes the move
38-/// and the row is byte-identical afterwards (the pool lists order on it).
39-/// Writing the same value would buy nothing: an `UPDATE` that leaves the
40-/// document unchanged is elided and never reaches the store's write set, so it
41-/// collides with nothing.
42-///
43-/// Admissible for [`transaction_with_retry`] as long as `statement` is: the
44-/// `UPDATE`s, `SELECT`, `IF`/`THROW` and `RETURN` can never answer "already
45-/// exists".
46-pub(crate) async fn bump_question_and_write<T: SurrealValue>(
47- question: &PoolQuestionId,
48- statement: &str,
49- mut bindings: Vec<(String, surrealdb::types::Value)>,
50- db: &Database,
51-) -> Result<Option<T>, AppError> {
52- bindings.push(("q".into(), question.record().into_value()));
53- let (mut result, mut errors) = transaction_with_retry(
54- db,
55- &format!(
56- "BEGIN TRANSACTION;
57- LET $was_asked = (SELECT VALUE asked_at FROM ONLY $q);
58- LET $bumped = (UPDATE $q SET asked_at = asked_at + 1 RETURN VALUE id);
59- IF array::len($bumped) = 0 {{ THROW 'no_question' }};
60- UPDATE $q SET asked_at = $was_asked;
61- LET $row = ({statement});
62- RETURN $row;
63- COMMIT TRANSACTION;"
64- ),
65- &bindings,
66- &["no_question"],
15+pub async fn insert(db: &Database, question: PoolQuestion) -> Result<PoolQuestion, AppError> {
16+ let row = sqlx::query_as!(
17+ PoolQuestion,
18+ r#"INSERT INTO pool_question (id, asker, title, body, status, asked_at)
19+ VALUES ($1, $2, $3, $4, $5, $6)
20+ RETURNING *"#,
21+ question.id,
22+ question.asker,
23+ question.title,
24+ question.body,
25+ question.status,
26+ question.asked_at,
6727 )
28+ .fetch_one(db)
6829 .await?;
69- // An aborted transaction errors *every* slot, most with a generic "not
70- // executed" — only the THROW's own slot names the reason.
71- if errors
72- .values()
73- .any(|error| error.to_string().contains("no_question"))
74- {
75- return Err(AppError::NotFound);
76- }
77- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
78- return Err(error.into());
79- }
80- // The trailing `RETURN` is the last statement before `COMMIT`, so its slot
81- // follows the statement count rather than a hand-kept number;
82- // `num_statements` counts BEGIN and COMMIT.
83- let slot = result.num_statements().saturating_sub(2);
84- Ok(result.take::<Vec<T>>(slot)?.into_iter().next())
85-}
86-
87-pub async fn insert(db: &Database, question: PoolQuestion) -> Result<PoolQuestion, AppError> {
88- // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber
89- let created: Option<PoolQuestion> = db.create(question.id.record()).content(question).await?;
90- created.ok_or_else(|| AppError::Internal("failed to create pool question".into()))
30+ Ok(row)
9131 }
9232
9333 pub async fn read(db: &Database, id: &PoolQuestionId) -> Result<Option<PoolQuestion>, AppError> {
94- Ok(db.select(id.record()).await?)
34+ let row = sqlx::query_as!(
35+ PoolQuestion,
36+ "SELECT * FROM pool_question WHERE id = $1",
37+ id
38+ )
39+ .fetch_optional(db)
40+ .await?;
41+ Ok(row)
9542 }
9643
9744 /// Every question, newest first — the teacher+ view (approval queue and
9845 /// pool in one list).
9946 pub async fn list_all(db: &Database) -> Result<Vec<PoolQuestion>, AppError> {
100- let mut result = db
101- .query("SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC")
102- .await?
103- .check()?;
104- Ok(result.take::<Vec<PoolQuestion>>(0)?)
47+ let rows = sqlx::query_as!(
48+ PoolQuestion,
49+ "SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC",
50+ )
51+ .fetch_all(db)
52+ .await?;
53+ Ok(rows)
10554 }
10655
10756 /// The pool as a non-staff user sees it, newest first: every approved
10857 /// question, plus the caller's own pending ones.
10958 pub async fn list_visible_to(db: &Database, user: &UserId) -> Result<Vec<PoolQuestion>, AppError> {
110- let mut result = db
111- .query(
112- "SELECT * FROM pool_question WHERE status = $approved OR asker = $usr \
113- ORDER BY asked_at DESC, id DESC",
114- )
115- .bind(("approved", STATUS_APPROVED))
116- .bind(("usr", user.record()))
117- .await?
118- .check()?;
119- Ok(result.take::<Vec<PoolQuestion>>(0)?)
59+ let rows = sqlx::query_as!(
60+ PoolQuestion,
61+ r#"SELECT * FROM pool_question
62+ WHERE status = $1 OR asker = $2
63+ ORDER BY asked_at DESC, id DESC"#,
64+ STATUS_APPROVED,
65+ user
66+ )
67+ .fetch_all(db)
68+ .await?;
69+ Ok(rows)
12070 }
12171
12272 /// Publish a pending question into the pool, stamping who approved it.
123-/// The `WHERE status = $pending` guard makes the transition atomic: of two
73+/// The `WHERE status = 'pending'` guard makes the transition atomic: of two
12474 /// racing approvals exactly one wins, and an approve can never land on a
12575 /// question deleted mid-flight. `None` = the question wasn't pending
12676 /// (already approved, or gone) — the caller sorts out which.
12777 ///
128-/// Two lifetime badge counters ride that same guard, inside this
78+/// Two lifetime badge counters ride that same guard inside this
12979 /// transaction: the approver's `pool_approved_total` and the *asker's*
130-/// `pool_published_total`. Both hang off `array::len($done) > 0` — the
131-/// guard's own verdict — so the pair moves once per real transition and
132-/// never on a second approve of an already-approved question.
133-/// (`count ?? 0 > 0` misparses here; `array::len` is the spelling that
134-/// holds.) The second conjunct is the self-approval rule below.
80+/// `pool_published_total`. Both move only when the guard's own verdict
81+/// landed, so the pair moves once per real transition and never on a second
82+/// approve of an already-approved question.
13583 ///
13684 /// Two rules keep the pair unfarmable, one per side of the transition.
13785 ///
@@ -144,56 +92,56 @@ pub async fn list_visible_to(db: &Database, user: &UserId) -> Result<Vec<PoolQue
14492 ///
14593 /// And a *self*-approval — a teacher+ approving a question they asked
14694 /// themselves, which the route deliberately still allows — moves neither
147-/// counter, hence the `$done[0].asker != $by` half of the condition. It is
148-/// the same farm from the other end (ask, approve, delete, repeat, with no
149-/// second person involved), and the two together are why a counter can only
150-/// move when one person's work was judged by another's. Nothing else about
151-/// a self-approval changes: same 200, same freeze, same stamp — this skips
152-/// the credit, not the approval.
95+/// counter. It is the same farm from the other end (ask, approve, delete,
96+/// repeat, with no second person involved), and the two together are why a
97+/// counter can only move when one person's work was judged by another's.
98+/// Nothing else about a self-approval changes: same 200, same freeze, same
99+/// stamp — this skips the credit, not the approval.
153100 ///
154-/// Re-sent while the store answers "conflict, retry": the guard reads a
155-/// column a rival approve writes, and both counters sit on user rows every
156-/// other counter site writes too. Sound to re-send — every statement is an
157-/// `UPDATE`, none of which can legitimately answer "already exists" — and a
158-/// lost round aborts having written nothing, increments included.
101+/// Rides the retry loop because the counter bumps lock user rows every
102+/// other counter site writes too; a deadlock between two approvals takes a
103+/// round and lands the next attempt.
159104 pub async fn approve(
160105 db: &Database,
161106 id: &PoolQuestionId,
162107 approver: &UserId,
163108 ) -> Result<Option<PoolQuestion>, AppError> {
164- let (mut result, mut errors) = transaction_with_retry(
165- db,
166- &format!(
167- "BEGIN TRANSACTION;
168- LET $done = (UPDATE $q SET status = $approved, approved_by = $by
169- WHERE status = $pending RETURN AFTER);
170- IF array::len($done) > 0 AND $done[0].asker != $by {{
171- UPDATE $by SET
172- {POOL_APPROVED_TOTAL_FIELD} = ({POOL_APPROVED_TOTAL_FIELD} ?? 0) + 1;
173- LET $asker = $done[0].asker;
174- UPDATE $asker SET
175- {POOL_PUBLISHED_TOTAL_FIELD} = ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0) + 1;
176- }};
177- RETURN $done;
178- COMMIT TRANSACTION;"
179- ),
180- &[
181- ("q".into(), id.record().into_value()),
182- ("approved".into(), STATUS_APPROVED.to_string().into_value()),
183- ("by".into(), approver.record().into_value()),
184- ("pending".into(), STATUS_PENDING.to_string().into_value()),
185- ],
186- &[],
187- )
188- .await?;
189- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
190- return Err(error.into());
191- }
192- // The trailing `RETURN` is always the last statement before `COMMIT`,
193- // so its slot follows the statement count rather than a hand-kept
194- // number (`num_statements` counts `BEGIN` and `COMMIT` too, hence -2).
195- let slot = result.num_statements().saturating_sub(2);
196- Ok(result.take::<Vec<PoolQuestion>>(slot)?.into_iter().next())
109+ tx_with_retry(db, false, async |tx| {
110+ let approved = sqlx::query_as!(
111+ PoolQuestion,
112+ r#"UPDATE pool_question SET status = $2, approved_by = $3
113+ WHERE id = $1 AND status = $4
114+ RETURNING *"#,
115+ *id,
116+ STATUS_APPROVED,
117+ approver,
118+ STATUS_PENDING,
119+ )
120+ .fetch_optional(tx)
121+ .await?;
122+ if let Some(question) = &approved {
123+ if question.asker != *approver {
124+ // The counter columns are NOT NULL DEFAULT 0 — the old
125+ // absent-reads-as-zero coalesce is gone with the schema.
126+ sqlx::query!(
127+ "UPDATE app_user SET pool_approved_total = pool_approved_total + 1
128+ WHERE id = $1",
129+ approver
130+ )
131+ .execute(tx)
132+ .await?;
133+ sqlx::query!(
134+ "UPDATE app_user SET pool_published_total = pool_published_total + 1
135+ WHERE id = $1",
136+ question.asker
137+ )
138+ .execute(tx)
139+ .await?;
140+ }
141+ }
142+ Ok(approved)
143+ })
144+ .await
197145 }
198146
199147 /// Point the question at a freshly written image blob. Guarded on
@@ -202,6 +150,10 @@ pub async fn approve(
202150 /// loses the race gets `None` (and the caller takes the orphan blob back
203151 /// off disk). Returns the *before* row — its `image_file` is the replaced
204152 /// blob the caller must remove.
153+///
154+/// The row lock makes the before-read and the guarded write one switch; a
155+/// racing approve either predates this transaction's snapshot or waits on
156+/// the lock, so a fresh image can never straddle an approval.
205157 pub async fn set_image(
206158 db: &Database,
207159 id: &PoolQuestionId,
@@ -209,19 +161,35 @@ pub async fn set_image(
209161 content_type: &FileContentType,
210162 size: i64,
211163 ) -> Result<Option<PoolQuestion>, AppError> {
212- let mut result = db
213- .query(
214- "UPDATE $q SET image_file = $file, image_content_type = $ct, image_size = $size \
215- WHERE status = $pending RETURN BEFORE",
164+ tx_with_retry(db, false, async |tx| {
165+ let before = sqlx::query_as!(
166+ PoolQuestion,
167+ "SELECT * FROM pool_question WHERE id = $1 FOR UPDATE",
168+ *id
216169 )
217- .bind(("q", id.record()))
218- .bind(("file", file.to_string()))
219- .bind(("ct", content_type.clone()))
220- .bind(("size", size))
221- .bind(("pending", STATUS_PENDING))
222- .await?
223- .check()?;
224- Ok(result.take::<Vec<PoolQuestion>>(0)?.into_iter().next())
170+ .fetch_optional(tx)
171+ .await?;
172+ let Some(before) = before else {
173+ return Ok(None);
174+ };
175+ let written = sqlx::query!(
176+ r#"UPDATE pool_question
177+ SET image_file = $2, image_content_type = $3, image_size = $4
178+ WHERE id = $1 AND status = $5"#,
179+ *id,
180+ file,
181+ content_type,
182+ size,
183+ STATUS_PENDING,
184+ )
185+ .execute(tx)
186+ .await?;
187+ if written.rows_affected() == 0 {
188+ return Ok(None);
189+ }
190+ Ok(Some(before))
191+ })
192+ .await
225193 }
226194
227195 /// Detach the question's image (pending only, like `set_image`). Returns
@@ -230,16 +198,32 @@ pub async fn clear_image(
230198 db: &Database,
231199 id: &PoolQuestionId,
232200 ) -> Result<Option<PoolQuestion>, AppError> {
233- let mut result = db
234- .query(
235- "UPDATE $q SET image_file = NONE, image_content_type = NONE, image_size = NONE \
236- WHERE status = $pending RETURN BEFORE",
201+ tx_with_retry(db, false, async |tx| {
202+ let before = sqlx::query_as!(
203+ PoolQuestion,
204+ "SELECT * FROM pool_question WHERE id = $1 FOR UPDATE",
205+ *id
206+ )
207+ .fetch_optional(tx)
208+ .await?;
209+ let Some(before) = before else {
210+ return Ok(None);
211+ };
212+ let written = sqlx::query!(
213+ r#"UPDATE pool_question
214+ SET image_file = NULL, image_content_type = NULL, image_size = NULL
215+ WHERE id = $1 AND status = $2"#,
216+ *id,
217+ STATUS_PENDING,
237218 )
238- .bind(("q", id.record()))
239- .bind(("pending", STATUS_PENDING))
240- .await?
241- .check()?;
242- Ok(result.take::<Vec<PoolQuestion>>(0)?.into_iter().next())
219+ .execute(tx)
220+ .await?;
221+ if written.rows_affected() == 0 {
222+ return Ok(None);
223+ }
224+ Ok(Some(before))
225+ })
226+ .await
243227 }
244228
245229 /// Delete the question and its solutions in one transaction, returning
@@ -247,34 +231,34 @@ pub async fn clear_image(
247231 /// caller can take every image blob off disk (solutions carry photos too,
248232 /// and a row-only sweep would strand theirs forever).
249233 ///
250-/// Rides the retry because a solution offer now writes this very row
251-/// ([`bump_question_and_write`]): the two contend by design, and a lost
252-/// round through a bare `check()` was a 500 for a delete that only had to
253-/// be re-sent. Admissible — a `DELETE` can never answer "already exists".
234+/// Children before the parent, so the foreign keys never refuse the parent
235+/// delete. `cascade = true` because a solution offer committing inside this
236+/// window makes the parent delete answer 23503 — a mid-cascade race the
237+/// retry loop re-runs, sweeping the latecomer with it. That foreign key is
238+/// also what keeps a solution from outliving its question on the insert
239+/// side, so the old existence-move transaction is simply gone.
254240 pub async fn delete(
255241 db: &Database,
256242 id: &PoolQuestionId,
257243 ) -> Result<Option<(PoolQuestion, Vec<Solution>)>, AppError> {
258- let (mut result, mut errors) = transaction_with_retry(
259- db,
260- "BEGIN TRANSACTION;
261- DELETE solution WHERE question = $q RETURN BEFORE;
262- DELETE $q RETURN BEFORE;
263- COMMIT TRANSACTION;",
264- &[("q".into(), id.record().into_value())],
265- &[],
266- )
267- .await?;
268- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
269- return Err(error.into());
270- }
271- // Slots count BEGIN: the solution sweep is slot 1, the question slot 2.
272- let solutions = result.take::<Vec<Solution>>(1)?;
273- Ok(result
274- .take::<Vec<PoolQuestion>>(2)?
275- .into_iter()
276- .next()
277- .map(|question| (question, solutions)))
244+ tx_with_retry(db, true, async |tx| {
245+ let solutions = sqlx::query_as!(
246+ Solution,
247+ "DELETE FROM solution WHERE question = $1 RETURNING *",
248+ *id
249+ )
250+ .fetch_all(tx)
251+ .await?;
252+ let question = sqlx::query_as!(
253+ PoolQuestion,
254+ "DELETE FROM pool_question WHERE id = $1 RETURNING *",
255+ *id
256+ )
257+ .fetch_optional(tx)
258+ .await?;
259+ Ok(question.map(|question| (question, solutions)))
260+ })
261+ .await
278262 }
279263
280264 #[cfg(test)]
src/db/rag_output.rsmodified+132 -110
@@ -1,13 +1,13 @@
1-//! The `rag_output` table: what an AI service produced for a course note —
2-//! an index, a summary, an embedding manifest — stored as this side's own
3-//! copy of the answer. The AI service never writes here (it answers a
4-//! request over the bridge, and this side stores the answer), which is what
5-//! keeps the api-read bridge GET-only. Derived, disposable data: the row is
6-//! dropped and regenerated whenever its input changes, so the cascades
7-//! below — [`delete_for_note`] when the note goes, [`delete_with_source`]
8-//! when one of the attachments it was built from goes — keep a stale output
9-//! from outliving its input, even in a deployment with no AI service
10-//! connected. The row shape lives in [`crate::domain::rag_output`].
1+//! What an AI service produced for a course note, stored on this side: the
2+//! write paths the api-read bridge serves (`create`/`replace_for_note` run
3+//! when this backend answers a request over the bridge, and this side stores
4+//! the answer), which is what keeps the api-read bridge GET-only. Derived,
5+//! disposable data: the row is dropped and regenerated whenever its input
6+//! changes, so the cascades below — [`delete_for_note`] when the note goes,
7+//! [`delete_with_source`] when one of the attachments it was built from goes
8+//! — keep a stale output from outliving its input, even in a deployment with
9+//! no AI service connected. The row shape lives in
10+//! [`crate::domain::rag_output`].
1111
1212 use crate::database::Database;
1313 use crate::db::page::PagedList;
@@ -18,8 +18,8 @@ use crate::domain::rag_output::{RagOutput, RagOutputId};
1818 use crate::domain::timestamp::Timestamp;
1919 use crate::error::AppError;
2020 use serde_json::Value;
21+use sqlx::types::Json;
2122
22-/// Store one service output against `note`.
2323 pub async fn create(
2424 db: &Database,
2525 note: &CourseNoteId,
@@ -32,16 +32,39 @@ pub async fn create(
3232 course_note: note.clone(),
3333 course: course.clone(),
3434 sources,
35- payload,
35+ payload: sqlx::types::Json(payload),
3636 generated_at: Timestamp::now(),
3737 };
38- // whole-row-save-ok: create of a fresh ULID row built in place — there is no prior row to clobber
39- let created: Option<RagOutput> = db.create(row.id.record()).content(row).await?;
40- created.ok_or_else(|| AppError::Internal("failed to create rag output".into()))
38+ // whole-row-save-ok: insert of a fresh UUID row built in place — there is no prior row to clobber
39+ let created = sqlx::query_as!(
40+ RagOutput,
41+ r#"INSERT INTO rag_output (id, course_note, course, sources, payload, generated_at)
42+ VALUES ($1, $2, $3, $4, $5, $6)
43+ RETURNING id, course_note, course, sources,
44+ payload AS "payload: Json<Value>", generated_at"#,
45+ row.id,
46+ row.course_note,
47+ row.course,
48+ &row.sources,
49+ &row.payload,
50+ row.generated_at
51+ )
52+ .fetch_one(db)
53+ .await?;
54+ Ok(created)
4155 }
4256
4357 pub async fn read(db: &Database, id: &RagOutputId) -> Result<Option<RagOutput>, AppError> {
44- Ok(db.select(id.record()).await?)
58+ let row = sqlx::query_as!(
59+ RagOutput,
60+ r#"SELECT id, course_note, course, sources,
61+ payload AS "payload: Json<Value>", generated_at
62+ FROM rag_output WHERE id = $1"#,
63+ id
64+ )
65+ .fetch_optional(db)
66+ .await?;
67+ Ok(row)
4568 }
4669
4770 /// A note's outputs, newest first.
@@ -51,24 +74,31 @@ pub async fn list_for(
5174 limit: Option<i64>,
5275 offset: i64,
5376 ) -> Result<(Vec<RagOutput>, i64), AppError> {
54- PagedList::new("rag_output WHERE course_note = $note", "ORDER BY id DESC")
55- .bind("note", note.record())
56- .run(limit, offset, db)
77+ PagedList::new("rag_output WHERE course_note = $1", "ORDER BY id DESC")
78+ .bind(note.uuid())
79+ .run::<RagOutput>(limit, offset, db)
5780 .await
5881 }
5982
6083 pub async fn delete(db: &Database, id: &RagOutputId) -> Result<RagOutput, AppError> {
61- let deleted: Option<RagOutput> = db.delete(id.record()).await?;
84+ let deleted = sqlx::query_as!(
85+ RagOutput,
86+ r#"DELETE FROM rag_output WHERE id = $1
87+ RETURNING id, course_note, course, sources,
88+ payload AS "payload: Json<Value>", generated_at"#,
89+ id
90+ )
91+ .fetch_optional(db)
92+ .await?;
6293 deleted.ok_or(AppError::NotFound)
6394 }
6495
6596 /// Cascade: every output of `note`. Deleting none is a success — a note
6697 /// no service ever indexed has nothing to drop.
6798 pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> {
68- db.query("DELETE rag_output WHERE course_note = $note")
69- .bind(("note", note.record()))
70- .await?
71- .check()?;
99+ sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note)
100+ .execute(db)
101+ .await?;
72102 Ok(())
73103 }
74104
@@ -76,7 +106,9 @@ pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), A
76106 /// this note's older rows. Two concurrent index tasks can interleave in any
77107 /// order and still leave exactly one row — the newest — because ids come
78108 /// from the process-wide monotonic generator, so "older" is `id <` the row
79-/// just written and the loser's row is always below the winner's.
109+/// just written and the loser's row is always below the winner's. (The
110+/// uuid column compares in byte order, which for UUIDv7 is mint order —
111+/// the same property the old record ids got from the ULID.)
80112 pub async fn replace_for_note(
81113 db: &Database,
82114 note: &CourseNoteId,
@@ -85,22 +117,24 @@ pub async fn replace_for_note(
85117 payload: Value,
86118 ) -> Result<RagOutput, AppError> {
87119 let created = create(db, note, course, sources, payload).await?;
88- db.query("DELETE rag_output WHERE course_note = $note AND id < $new")
89- .bind(("note", note.record()))
90- .bind(("new", created.id.record()))
91- .await?
92- .check()?;
120+ sqlx::query!(
121+ "DELETE FROM rag_output WHERE course_note = $1 AND id < $2",
122+ note,
123+ created.id
124+ )
125+ .execute(db)
126+ .await?;
93127 Ok(created)
94128 }
95129
96130 /// Cascade: every output built from `file`. Runs on a file delete even
97131 /// with no AI service connected, so a stale output cannot survive its
98-/// source.
132+/// source. The GIN index on `sources` turns the containment test into a
133+/// lookup.
99134 pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> {
100- db.query("DELETE rag_output WHERE sources CONTAINS $file")
101- .bind(("file", file.record()))
102- .await?
103- .check()?;
135+ sqlx::query!("DELETE FROM rag_output WHERE $1 = ANY(sources)", file)
136+ .execute(db)
137+ .await?;
104138 Ok(())
105139 }
106140
@@ -108,8 +142,12 @@ pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Resul
108142 mod tests {
109143 use super::*;
110144 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
111- use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle};
112- use crate::domain::course_note_file::{CourseNoteFile, FileContentType, FileName};
145+ use crate::domain::course_note::CourseNote;
146+ use crate::domain::course_note::CourseNoteContent;
147+ use crate::domain::course_note::CourseNoteTitle;
148+ use crate::domain::course_note_file::CourseNoteFile;
149+ use crate::domain::course_note_file::FileContentType;
150+ use crate::domain::course_note_file::FileName;
113151 use serde_json::json;
114152
115153 async fn note_of(db: &Database, title: &str) -> CourseNote {
@@ -136,108 +174,92 @@ mod tests {
136174 .unwrap()
137175 }
138176
139- async fn file_on(db: &Database, note: &CourseNoteId) -> CourseNoteFileId {
140- let file = CourseNoteFile::new(
141- note,
142- FileName::try_new("plan.pdf").unwrap(),
143- FileContentType::try_new("application/pdf").unwrap(),
144- 3,
177+ async fn a_file(db: &Database, note: &CourseNote) -> CourseNoteFile {
178+ crate::db::course_note_file::insert(
179+ db,
180+ CourseNoteFile::new(
181+ note.get_id(),
182+ FileName::try_new("f").unwrap(),
183+ FileContentType::try_new("text/plain").unwrap(),
184+ 1,
185+ ),
145186 )
146-;
147- crate::db::course_note_file::insert(db, file)
148187 .await
149188 .unwrap()
150- .get_id()
151- .clone()
152189 }
153190
154- /// Replace converges on one row — the newest — even when an earlier
155- /// interleaving already left two rows behind for the note.
191+ /// A stored round-trips through JSONB with its sources list intact, and
192+ /// the note cascade takes every row of the note with it.
156193 #[tokio::test]
157- async fn replace_keeps_only_the_newest_output() {
194+ async fn create_reads_back_and_cascades_from_the_note() {
158195 let db = crate::database::init_mem().await.unwrap();
159- let note = note_of(&db, "a").await;
160- let stale = create(
161- &db,
162- note.get_id(),
163- note.get_course(),
164- Vec::new(),
165- json!({ "n": 1 }),
166- )
167- .await
168- .unwrap();
169- // The race this fixes: a second row for the same note.
170- create(
171- &db,
172- note.get_id(),
173- note.get_course(),
174- Vec::new(),
175- json!({ "n": 2 }),
176- )
177- .await
178- .unwrap();
179-
180- let fresh = replace_for_note(
196+ let note = note_of(&db, "n").await;
197+ let file = a_file(&db, &note).await;
198+ let row = create(
181199 &db,
182200 note.get_id(),
183201 note.get_course(),
184- Vec::new(),
185- json!({ "n": 3 }),
202+ vec![file.get_id().clone()],
203+ json!({"answer": "x"}),
186204 )
187205 .await
188206 .unwrap();
207+ let read = read(&db, row.get_id()).await.unwrap().unwrap();
208+ assert_eq!(read.get_payload(), &json!({"answer": "x"}));
209+ assert_eq!(read.get_sources(), &[file.get_id().clone()]);
189210
190- let rows = list_for(&db, note.get_id(), None, 0).await.unwrap().0;
191- assert_eq!(rows.len(), 1);
192- assert_eq!(rows[0].get_id(), fresh.get_id());
193- assert!(fresh.get_id().key() > stale.get_id().key());
211+ delete_for_note(&db, note.get_id()).await.unwrap();
212+ assert!(read(&db, row.get_id()).await.unwrap().is_none());
194213 }
195214
196- /// The payload survives the round trip unread, and both cascades take only
197- /// what they are aimed at.
215+ /// Replace leaves exactly one row — the newest — and the source cascade
216+ /// drops a row built from a file that is gone.
198217 #[tokio::test]
199- async fn outputs_round_trip_and_cascade() {
218+ async fn replace_is_newest_wins_and_source_cascade_drops() {
200219 let db = crate::database::init_mem().await.unwrap();
201- let note = note_of(&db, "a").await;
202- let other = note_of(&db, "b").await;
203- let file = file_on(&db, note.get_id()).await;
204-
205- let stored = create(
220+ let note = note_of(&db, "n").await;
221+ let file = a_file(&db, &note).await;
222+ let first = create(
206223 &db,
207224 note.get_id(),
208225 note.get_course(),
209- vec![file.clone()],
210- json!({ "summary": "x", "chunks": [{ "text": "y" }] }),
226+ vec![file.get_id().clone()],
227+ json!({"v": 1}),
211228 )
212229 .await
213230 .unwrap();
214- let roundtrip = read(&db, stored.get_id()).await.unwrap().unwrap();
215- assert_eq!(roundtrip.get_payload()["summary"], "x");
216- assert_eq!(roundtrip.get_payload()["chunks"][0]["text"], "y");
217- assert_eq!(roundtrip.get_sources(), std::slice::from_ref(&file));
218- assert_eq!(roundtrip.get_course(), note.get_course());
219- let untouched = create(
231+ let second = replace_for_note(
220232 &db,
221- other.get_id(),
222- other.get_course(),
223- Vec::new(),
224- json!({ "summary": "z" }),
233+ note.get_id(),
234+ note.get_course(),
235+ vec![file.get_id().clone()],
236+ json!({"v": 2}),
225237 )
226238 .await
227239 .unwrap();
240+ let (rows, total) = list_for(&db, note.get_id(), None, 0).await.unwrap();
241+ assert_eq!(total, 1);
242+ assert_eq!(rows[0].get_id(), second.get_id());
243+ assert!(first.get_id() != second.get_id());
228244
229- let listed =
230- async |note: &CourseNoteId| list_for(&db, note, None, 0).await.unwrap().0.len();
231- assert_eq!(listed(note.get_id()).await, 1);
232-
233- // Losing a source drops the output that cited it, and nothing else.
234- delete_with_source(&db, &file).await.unwrap();
235- assert_eq!(listed(note.get_id()).await, 0);
236- assert_eq!(listed(other.get_id()).await, 1);
245+ delete_with_source(&db, file.get_id()).await.unwrap();
246+ let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap();
247+ assert_eq!(total, 0);
248+ }
237249
238- // Cascading a note with no outputs left is still a success.
239- delete_for_note(&db, note.get_id()).await.unwrap();
240- delete_for_note(&db, other.get_id()).await.unwrap();
241- assert!(read(&db, untouched.get_id()).await.unwrap().is_none());
250+ /// Deleting one row returns it; deleting it again is a 404.
251+ #[tokio::test]
252+ async fn delete_returns_the_row_then_refuses() {
253+ let db = crate::database::init_mem().await.unwrap();
254+ let note = note_of(&db, "n").await;
255+ let row = create(&db, note.get_id(), note.get_course(), Vec::new(), json!({}))
256+ .await
257+ .unwrap();
258+ let gone = delete(&db, row.get_id()).await.unwrap();
259+ assert_eq!(gone.get_id(), row.get_id());
260+ assert!(matches!(
261+ delete(&db, row.get_id()).await,
262+ Err(AppError::NotFound)
263+ ));
242264 }
243265 }
src/db/session_attendance.rsmodified+193 -185
@@ -4,60 +4,30 @@
44 //! management's, only students attend, enrollment) are
55 //! [`crate::service::session_attendance`]'s to judge before calling here.
66
7-use surrealdb::types::SurrealValue;
8-
9-use crate::constant::{
10- LESSON_COUNTED_AT_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, LESSONS_HELD_TOTAL_FIELD,
11-};
12-use crate::database::{Database, transaction_with_retry};
7+use crate::database::{Database, tx_with_retry};
138 use crate::db::page::PagedList;
149 use crate::domain::attendance::AttendanceStatus;
1510 use crate::domain::course_session::{CourseSession, CourseSessionId};
16-use crate::domain::session_attendance::{
17- SessionAttendance, SessionAttendanceId, counts_as_attended,
18-};
11+use crate::domain::session_attendance::SessionAttendance;
1912 use crate::domain::timestamp::Timestamp;
2013 use crate::domain::user::UserId;
2114 use crate::error::AppError;
2215
23-/// Record (or overwrite) `user`'s status for the session. One row per
24-/// (session, user), keyed by a deterministic composite id so this is a
25-/// single atomic UPSERT — concurrent marks converge on the one row.
26-///
27-/// The "session still exists" gate rides in the same transaction as the
28-/// mark, the mirror of the cascade in [`crate::db::course_session::delete`]: the
29-/// caller's pre-flight read sits four round trips in front of this write,
30-/// so a delete landing in that gap used to leave a roll-call row on a
31-/// session that was gone — and that row was *unremovable*, its only delete
32-/// route 404ing on the vanished session while the attendance report went
33-/// on counting it. A deleted session reads NONE, which is falsy, so the
34-/// gate is written as an explicit `IS NONE` (see
35-/// [`crate::domain::exam_result::ExamResult::grade`]). It reads the
36-/// session's `teacher` — required on every row, so NONE means "no row" just
37-/// as `id` did — because the counter below needs that teacher anyway, and
38-/// one read serves both.
39-///
40-/// A read is not a claim, though: SurrealDB 3.2.3 conflict-checks write
41-/// sets, not read sets, so that gate alone only closes the *sequential*
42-/// order (delete committed, then the mark arrives). To make the two really
43-/// collide, this transaction also *writes* the session row, unconditionally
44-/// — the bump-and-restore of [`crate::domain::exam_answer::ExamAnswer::save`]
45-/// on the one column this write already owns, [`LESSON_COUNTED_AT_FIELD`].
46-/// Unconditional is the whole point: the credit branch below writes that
47-/// column already, but it fires only for the first roll call of a lesson
48-/// that has begun, so a future-dated sheet and every re-mark of a counted
49-/// one touched nothing at all and committed happily beside
50-/// `DELETE /sessions/{id}`. Re-stating the value verbatim would not do
51-/// either — an `UPDATE` that leaves the document unchanged is elided and
52-/// never enters the write set — hence bump first, then either stamp
53-/// (credit branch) or put back exactly what was found, `NONE` included, so
54-/// the row is byte-identical and the once-per-lesson rule is untouched.
16+/// Record (or overwrite) `user`'s status for the session. The table's
17+/// primary key *is* the (session, user) pair, so the mark is a single
18+/// atomic upsert — concurrent marks converge on the one row.
5519 ///
56-/// Sound to re-send while the store answers "conflict, retry": the gate
57-/// reads the record a delete writes, so the two contend by design, and the
58-/// UPSERT cannot legitimately answer "already exists" — its composite id is
59-/// bijective with the `session_attendance_session_user` unique tuple, so
60-/// the index entry can only point at the row the id already names.
20+/// The "session still exists" gate is a row lock: the transaction takes the
21+/// session row `FOR NO KEY UPDATE` before anything else, so a session (or
22+/// course) delete cascading beneath this mark simply waits, and a delete
23+/// that got there first leaves this gate matching nothing — `404`, the
24+/// mirror of [`crate::db::course_session::delete`]. The caller's
25+/// pre-flight read sits several round trips in front of this write, which
26+/// is exactly the gap the old code had to fake with a bump-and-restore
27+/// write on the session row; the lock is the same serialization without
28+/// the trick. It also freezes `starts_at` and `held_counted_at` for the
29+/// transaction, so two simultaneous first marks take turns and the
30+/// lesson-held credit below is stamped exactly once.
6131 ///
6232 /// Two badge counters move in this same transaction, both of them read
6333 /// from the store rather than taken on the caller's word:
@@ -65,27 +35,27 @@ use crate::error::AppError;
6535 /// - `lessons_attended_total`, on the person marked, as a *delta* rather
6636 /// than an increment, because this is an upsert: a re-mark that changes
6737 /// nothing must change nothing, and a teacher's correction must move it
68-/// back down. `$was` is read before the upsert overwrites it (`NONE` when
69-/// the pair has no row yet), so it writes only on a real crossing of the
70-/// attended line, and only for a **student** — attending lessons is a
71-/// student's badge, the same student-only rule enrolling and sitting an
72-/// exam already carry, so a teacher marked present in their own lesson
73-/// moves it in neither direction. The live `role` decides that, not the
74-/// role someone held when the row was written.
38+/// back down. The pair's stored status is read before the upsert
39+/// overwrites it (`None` when the pair has no row yet), so it writes
40+/// only on a real crossing of the attended line, and only for a
41+/// **student** — attending lessons is a student's badge, the same
42+/// student-only rule enrolling and sitting an exam already carry, so a
43+/// teacher marked present in their own lesson moves it in neither
44+/// direction. The live `role` decides that, not the role someone held
45+/// when the row was written.
7546 /// - `lessons_held_total`, on the *session's* teacher, exactly once per
76-/// session: the first roll call taken stamps
77-/// [`LESSON_COUNTED_AT_FIELD`] on the lesson and every later mark sees
78-/// the stamp and credits nothing. It counts lessons that actually
79-/// happened — scheduling one and cancelling it earns nothing, which is
80-/// why the credit does not live in `crate::db::course_session::create`. Two
81-/// simultaneous first marks both write the lesson row, so the store's own
82-/// conflict detection (and `transaction_with_retry` behind it) is what
83-/// keeps the stamp from being set twice.
47+/// session: the first roll call taken stamps `held_counted_at` on the
48+/// lesson and every later mark sees the stamp and credits nothing. It
49+/// counts lessons that actually happened — scheduling one and
50+/// cancelling it earns nothing, which is why the credit does not live
51+/// in `crate::db::course_session::create`. Two simultaneous first
52+/// marks serialize on the session row's lock, so the stamp cannot be
53+/// set twice.
8454 ///
8555 /// "Actually happened" is a clock reading, not a request count: the
8656 /// credit waits for the lesson's own `starts_at` to arrive. Roll call is
87-/// deliberately *not* time-gated — a teacher may open the sheet early and
88-/// is never refused — so without this a teacher could schedule two
57+/// deliberately *not* time-gated — a teacher may open the sheet early
58+/// and is never refused — so without this a teacher could schedule two
8959 /// hundred lessons for next week, mark one student in each, and hold two
9060 /// hundred lessons this afternoon. Because the stamp is written only on
9161 /// the branch that credits, a sheet opened early and touched again after
@@ -100,9 +70,6 @@ use crate::error::AppError;
10070 /// credited — a student's real lessons eaten by someone else's farm. It
10171 /// is also nobody's self-service: only a teacher can mark a student, so
10272 /// the counter cannot be moved by the person it decorates.
103-///
104-/// Both are floored/guarded rather than trusting the column to exist: a row
105-/// written before these columns carries none of them.
10673 //
10774 // corner-cut: that asymmetry leaves a teacher able to inflate a *student's*
10875 // attendance with future-dated lessons. Closing it needs the credit stamped
@@ -117,76 +84,94 @@ pub async fn mark(
11784 status: AttendanceStatus,
11885 marked_by: &UserId,
11986 ) -> Result<SessionAttendance, AppError> {
120- let attended = counts_as_attended(&status);
87+ let attended = crate::domain::session_attendance::counts_as_attended(&status);
12188 let delta: i64 = if attended { 1 } else { -1 };
122- let attendance = SessionAttendance {
123- id: SessionAttendanceId::composite(session.get_id(), user),
124- session: session.get_id().clone(),
125- course: session.get_course().clone(),
126- user: user.clone(),
127- status,
128- marked_by: marked_by.clone(),
129- };
130- let (mut written, mut errors) = transaction_with_retry(
131- db,
132- &format!(
133- "BEGIN TRANSACTION;
134- LET $teacher = (SELECT VALUE teacher FROM ONLY $sess);
135- IF $teacher IS NONE {{ THROW 'session_missing' }};
136- LET $counted = (SELECT VALUE {LESSON_COUNTED_AT_FIELD} FROM ONLY $sess);
137- LET $begun = ((SELECT VALUE starts_at FROM ONLY $sess) <= $stamp);
138- LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student');
139- LET $was = ((SELECT VALUE status FROM ONLY $id) IN ['present', 'late']);
140- LET $after = (UPSERT $id CONTENT $row RETURN AFTER);
141- IF $student AND $was != $now {{
142- UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} =
143- math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) + $delta, 0])
144- }};
145- UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = ({LESSON_COUNTED_AT_FIELD} ?? 0) + 1;
146- IF ($counted IS NONE) AND $begun {{
147- UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $stamp;
148- UPDATE $teacher SET {LESSONS_HELD_TOTAL_FIELD} =
149- ({LESSONS_HELD_TOTAL_FIELD} ?? 0) + 1
150- }} ELSE {{
151- UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $counted
152- }};
153- RETURN $after;
154- COMMIT TRANSACTION;"
155- ),
156- &[
157- // `$session` is SurrealDB's own protected variable (the auth
158- // session): binding that name errors the whole query.
159- ("sess".into(), session.get_id().record().into_value()),
160- ("id".into(), attendance.id.record().into_value()),
161- ("usr".into(), user.record().into_value()),
162- ("now".into(), attended.into_value()),
163- ("delta".into(), delta.into_value()),
164- ("stamp".into(), Timestamp::now().into_value()),
165- ("row".into(), attendance.into_value()),
166- ],
167- &["session_missing"],
168- )
169- .await?;
170- // An aborted transaction errors every slot and only the THROW's own
171- // slot names the marker, so a refusal is read by marker while a lost
172- // round was already re-sent — never reported as a 500.
173- if errors
174- .values()
175- .any(|error| error.to_string().contains("session_missing"))
176- {
177- return Err(AppError::NotFound);
178- }
179- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
180- return Err(error.into());
181- }
182- // The trailing `RETURN` is always the last statement before `COMMIT`,
183- // so its slot follows the statement count instead of a hand-kept one.
184- let slot = written.num_statements().saturating_sub(2);
185- written
186- .take::<Vec<SessionAttendance>>(slot)?
187- .into_iter()
188- .next()
189- .ok_or_else(|| AppError::Internal("failed to mark session attendance".into()))
89+ let now = Timestamp::now();
90+ tx_with_retry(db, false, async |tx| {
91+ // The gate and the serialization point: a live session row, locked
92+ // against the delete cascade and every rival mark.
93+ let sess = sqlx::query!(
94+ r#"SELECT teacher, starts_at, held_counted_at
95+ FROM course_session WHERE id = $1 FOR NO KEY UPDATE"#,
96+ session.id,
97+ )
98+ .fetch_optional(&mut *tx)
99+ .await?;
100+ let Some(sess) = sess else {
101+ return Err(AppError::NotFound);
102+ };
103+ // The pair's stored status — the pre-image the attended delta is
104+ // computed off.
105+ let was = sqlx::query!(
106+ r#"SELECT status FROM session_attendance
107+ WHERE session = $1 AND app_user = $2"#,
108+ session.id,
109+ user,
110+ )
111+ .fetch_optional(&mut *tx)
112+ .await?
113+ .map(|row| row.status);
114+ // The live role of the person marked (a gone user row marks as
115+ // non-student — no badge to move; the service gate has already
116+ // refused a vanished target before this write ran).
117+ let is_student = sqlx::query!(
118+ r#"SELECT role = 'student' AS "is_student" FROM app_user WHERE id = $1"#,
119+ user,
120+ )
121+ .fetch_optional(&mut *tx)
122+ .await?
123+ .map(|row| row.is_student)
124+ .unwrap_or(false);
125+ let row = sqlx::query_as!(
126+ SessionAttendance,
127+ r#"INSERT INTO session_attendance (session, app_user, course, status, marked_by)
128+ VALUES ($1, $2, $3, $4, $5)
129+ ON CONFLICT (session, app_user) DO UPDATE
130+ SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by
131+ RETURNING session, app_user AS "user", course, status, marked_by"#,
132+ session.id,
133+ user,
134+ session.course,
135+ status,
136+ marked_by,
137+ )
138+ .fetch_one(&mut *tx)
139+ .await?;
140+ // The attended badge: student-only, and only on a real crossing.
141+ let was_attended = was
142+ .as_deref()
143+ .is_some_and(|was| was == "present" || was == "late");
144+ if is_student && was_attended != attended {
145+ sqlx::query!(
146+ r#"UPDATE app_user
147+ SET lessons_attended_total = GREATEST(lessons_attended_total + $2, 0)
148+ WHERE id = $1"#,
149+ user,
150+ delta,
151+ )
152+ .execute(&mut *tx)
153+ .await?;
154+ }
155+ // The held badge: once per lesson, and only once the lesson began.
156+ if sess.held_counted_at.is_none() && sess.starts_at <= now.as_millis() {
157+ sqlx::query!(
158+ r#"UPDATE course_session SET held_counted_at = $2 WHERE id = $1"#,
159+ session.id,
160+ now.as_millis(),
161+ )
162+ .execute(&mut *tx)
163+ .await?;
164+ sqlx::query!(
165+ r#"UPDATE app_user SET lessons_held_total = lessons_held_total + 1
166+ WHERE id = $1"#,
167+ sess.teacher,
168+ )
169+ .execute(&mut *tx)
170+ .await?;
171+ }
172+ Ok(row)
173+ })
174+ .await
190175 }
191176
192177 pub async fn list_for_session(
@@ -195,10 +180,16 @@ pub async fn list_for_session(
195180 limit: Option<i64>,
196181 offset: i64,
197182 ) -> Result<(Vec<SessionAttendance>, i64), AppError> {
198- PagedList::new("session_attendance WHERE session = $s", "ORDER BY id DESC")
199- .bind("s", session.record())
200- .run(limit, offset, db)
201- .await
183+ // The old composite key `{session}_{user}` sorted by user within a
184+ // session — its session prefix was constant — so the natural-PK
185+ // columns sort the same way.
186+ PagedList::new(
187+ "session_attendance WHERE session = $1",
188+ "ORDER BY session DESC, app_user DESC",
189+ )
190+ .bind(session.uuid())
191+ .run::<SessionAttendance>(limit, offset, db)
192+ .await
202193 }
203194
204195 /// Every roll-call row ever recorded for `user` — the session half of the
@@ -209,12 +200,16 @@ pub async fn list_for_user(
209200 db: &Database,
210201 user: &UserId,
211202 ) -> Result<Vec<SessionAttendance>, AppError> {
212- let mut result = db
213- .query("SELECT * FROM session_attendance WHERE user = $usr ORDER BY id DESC")
214- .bind(("usr", user.record()))
215- .await?
216- .check()?;
217- Ok(result.take::<Vec<SessionAttendance>>(0)?)
203+ let rows = sqlx::query_as!(
204+ SessionAttendance,
205+ r#"SELECT session, app_user AS "user", course, status, marked_by
206+ FROM session_attendance WHERE app_user = $1
207+ ORDER BY session DESC, app_user DESC"#,
208+ user,
209+ )
210+ .fetch_all(db)
211+ .await?;
212+ Ok(rows)
218213 }
219214
220215 /// Clearing a row the student was counted for gives the count back, in the
@@ -229,50 +224,60 @@ pub async fn list_for_user(
229224 ///
230225 /// Student-only on the same terms as the mark, and read from the store for
231226 /// the same reason.
232-///
233-/// Sound to re-send: neither statement can answer "already exists".
234-//
235-// corner-cut: both ends read the *live* role, so a student promoted between
236-// being marked present and having that row corrected leaves the counter one
237-// high (the credit landed as a student, the refund is refused as staff).
238-// Upgrade path is stamping the credit on the roll-call row itself and
239-// refunding off that stamp, the way `counted_on_time` works for homework —
240-// not worth a column until a promotion mid-term is a real complaint.
241227 pub async fn remove(
242228 db: &Database,
243229 session: &CourseSessionId,
244230 user: &UserId,
245231 ) -> Result<Option<SessionAttendance>, AppError> {
246- let (mut result, mut errors) = transaction_with_retry(
247- db,
248- &format!(
249- "BEGIN TRANSACTION;
250- LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student');
251- LET $gone = (DELETE session_attendance
252- WHERE session = $s AND user = $usr RETURN BEFORE);
253- IF $student AND array::len($gone) > 0 AND $gone[0].status IN ['present', 'late'] {{
254- UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} =
255- math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) - 1, 0])
256- }};
257- RETURN $gone;
258- COMMIT TRANSACTION;"
259- ),
260- &[
261- ("s".into(), session.record().into_value()),
262- ("usr".into(), user.record().into_value()),
263- ],
264- &[],
265- )
266- .await?;
267- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
268- return Err(error.into());
269- }
270- // The trailing `RETURN` is always the last statement before `COMMIT`.
271- let slot = result.num_statements().saturating_sub(2);
272- Ok(result
273- .take::<Vec<SessionAttendance>>(slot)?
274- .into_iter()
275- .next())
232+ tx_with_retry(db, false, async |tx| {
233+ // The pre-image and the row's right to exist in one locked
234+ // statement: the row cannot vanish (or change status) under this
235+ // transaction, and `None` here is simply "nothing to remove".
236+ let Some(gone) = sqlx::query_as!(
237+ SessionAttendance,
238+ r#"SELECT session, app_user AS "user", course, status, marked_by
239+ FROM session_attendance
240+ WHERE session = $1 AND app_user = $2
241+ FOR UPDATE"#,
242+ session,
243+ user,
244+ )
245+ .fetch_optional(&mut *tx)
246+ .await?
247+ else {
248+ return Ok(None);
249+ };
250+ if crate::domain::session_attendance::counts_as_attended(&gone.status) {
251+ // Student-only, live role: the same rule the mark pays.
252+ let student = sqlx::query!(
253+ r#"SELECT role = 'student' AS "is_student" FROM app_user WHERE id = $1"#,
254+ user,
255+ )
256+ .fetch_optional(&mut *tx)
257+ .await?
258+ .map(|row| row.is_student)
259+ .unwrap_or(false);
260+ if student {
261+ sqlx::query!(
262+ r#"UPDATE app_user
263+ SET lessons_attended_total = GREATEST(lessons_attended_total - 1, 0)
264+ WHERE id = $1"#,
265+ user,
266+ )
267+ .execute(&mut *tx)
268+ .await?;
269+ }
270+ }
271+ sqlx::query!(
272+ r#"DELETE FROM session_attendance WHERE session = $1 AND app_user = $2"#,
273+ session,
274+ user,
275+ )
276+ .execute(&mut *tx)
277+ .await?;
278+ Ok(Some(gone))
279+ })
280+ .await
276281 }
277282
278283 #[cfg(test)]
@@ -345,7 +350,10 @@ mod tests {
345350 }
346351
347352 async fn held(user: &UserId, db: &Database) -> i64 {
348- crate::db::badge::load(db, user).await.unwrap().get_lessons_held()
353+ crate::db::badge::load(db, user)
354+ .await
355+ .unwrap()
356+ .get_lessons_held()
349357 }
350358
351359 /// The whole transition table in one pass: an upsert may only move the
src/db/solution.rsmodified+127 -78
@@ -1,54 +1,54 @@
1-//! The `solution` table: offers (through the pool question's
2-//! existence-move), the question-scoped reads and page, the grouped counts,
1+//! The `solution` table: offers (their question's existence enforced by the
2+//! real foreign key), the question-scoped read and page, the grouped counts,
33 //! and the unconditional body/image writes of an unmoderated row. The pure
44 //! entity and newtypes live in [`crate::domain::solution`]; the web layer
55 //! reaches these through [`crate::service::solution`].
66
77 use std::collections::HashMap;
88
9-use surrealdb::types::{RecordId, SurrealValue};
10-
11-use crate::database::Database;
9+use crate::database::{Database, tx_with_retry};
1210 use crate::db::page::PagedList;
13-use crate::db::pool_question::bump_question_and_write;
1411 use crate::domain::note_file::FileContentType;
1512 use crate::domain::pool_question::PoolQuestionId;
1613 use crate::domain::solution::{Solution, SolutionBody, SolutionId};
1714 use crate::error::AppError;
1815
19-/// One `GROUP BY question` row of [`counts_for`].
20-#[derive(SurrealValue)]
21-struct SolutionCount {
22- question: PoolQuestionId,
23- n: i64,
24-}
25-
2616 /// Offer the solution. `NotFound` = the question is gone, and nothing was
27-/// written: the create rides [`bump_question_and_write`], so the question's
28-/// existence is a *write* to its row rather than a read the handler made a
29-/// moment earlier — a bare create landing inside
30-/// [`crate::db::pool_question::delete`]'s
31-/// window was swept by nothing and left a solution no route could ever
32-/// reach or remove (every path to one goes through its question), photo
33-/// blob included.
17+/// written: the insert's foreign key (`solution_question_fkey`) refuses an
18+/// orphan the old existence-move transaction spent five statements dodging —
19+/// a bare create landing inside
20+/// [`crate::db::pool_question::delete`]'s window used to be swept by
21+/// nothing and left a solution no route could ever reach or remove (every
22+/// path to one goes through its question), photo blob included.
3423 ///
35-/// Re-sendable despite the `CREATE`: `$id` is a ULID minted once per call
36-/// on a table with no `UNIQUE` index, so a re-send cannot answer "already
37-/// exists" — the one thing the retry could not survive.
24+/// The author's own foreign key never fires in practice (the request
25+/// carries a live session user) and stays a database error if it ever does;
26+/// only the question's key maps to the 404.
3827 pub async fn insert(db: &Database, solution: Solution) -> Result<Solution, AppError> {
39- // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber
40- let (question, id) = (solution.question.clone(), solution.id.record());
41- bump_question_and_write(
42- &question,
43- "CREATE $id CONTENT $solution",
44- vec![
45- ("id".into(), id.into_value()),
46- ("solution".into(), solution.into_value()),
47- ],
48- db,
28+ match sqlx::query_as!(
29+ Solution,
30+ r#"INSERT INTO solution (id, question, author, body, offered_at)
31+ VALUES ($1, $2, $3, $4, $5)
32+ RETURNING *"#,
33+ solution.id,
34+ solution.question,
35+ solution.author,
36+ solution.body,
37+ solution.offered_at,
4938 )
50- .await?
51- .ok_or_else(|| AppError::Internal("failed to create solution".into()))
39+ .fetch_one(db)
40+ .await
41+ {
42+ Ok(row) => Ok(row),
43+ Err(err) if is_question_gone(&err) => Err(AppError::NotFound),
44+ Err(err) => Err(err.into()),
45+ }
46+}
47+
48+/// Did this insert fail on the *question* foreign key — the parent-gone
49+/// refusal — rather than some unrelated database fault?
50+fn is_question_gone(err: &sqlx::Error) -> bool {
51+ err.as_database_error().and_then(|db| db.constraint()) == Some("solution_question_fkey")
5252 }
5353
5454 /// Read a solution only if it belongs to `question` — keeps the nested
@@ -58,32 +58,40 @@ pub async fn read_for(
5858 id: &SolutionId,
5959 question: &PoolQuestionId,
6060 ) -> Result<Option<Solution>, AppError> {
61- let solution: Option<Solution> = db.select(id.record()).await?;
62- Ok(solution.filter(|solution| &solution.question == question))
61+ let row = sqlx::query_as!(
62+ Solution,
63+ "SELECT * FROM solution WHERE id = $1 AND question = $2",
64+ id,
65+ question
66+ )
67+ .fetch_optional(db)
68+ .await?;
69+ Ok(row)
6370 }
6471
6572 /// The question's solutions, oldest first — a discussion reads downward.
6673 /// Ordered by `offered_at`; the `id` tiebreak only makes same-millisecond
67-/// offers *stable* across re-queries, not insertion-ordered (ULID low bits
68-/// are random within a millisecond, so same-ms order is arbitrary).
74+/// offers *stable* across re-queries (the ids are write-ordered UUIDv7, so
75+/// same-ms rows still sort by mint order).
6976 pub async fn list_for(
7077 db: &Database,
7178 question: &PoolQuestionId,
7279 limit: Option<i64>,
7380 offset: i64,
7481 ) -> Result<(Vec<Solution>, i64), AppError> {
82+ // `.uuid()` feeds the builder its raw bind value — exact, typed.
7583 PagedList::new(
76- "solution WHERE question = $q",
84+ "solution WHERE question = $1",
7785 "ORDER BY offered_at ASC, id ASC",
7886 )
79- .bind("q", question.record())
87+ .bind(question.uuid())
8088 .run(limit, offset, db)
8189 .await
8290 }
8391
8492 /// Per-question solution tallies for a page of questions, in one grouped
8593 /// query — a per-row `count()` would cost a query per question. Keys are
86-/// question record keys; a question with no solutions has no entry, so
94+/// the questions' wire keys; a question with no solutions has no entry, so
8795 /// the caller reads misses as zero.
8896 pub async fn counts_for(
8997 db: &Database,
@@ -92,18 +100,19 @@ pub async fn counts_for(
92100 if questions.is_empty() {
93101 return Ok(HashMap::new());
94102 }
95- let ids: Vec<RecordId> = questions.iter().map(|question| question.record()).collect();
96- let mut result = db
97- .query(
98- "SELECT question, count() AS n FROM solution WHERE question IN $qs GROUP BY question",
99- )
100- .bind(("qs", ids))
101- .await?
102- .check()?;
103- Ok(result
104- .take::<Vec<SolutionCount>>(0)?
103+ let ids: Vec<PoolQuestionId> = questions.iter().copied().collect();
104+ let rows = sqlx::query!(
105+ r#"SELECT question AS "question: PoolQuestionId", count(*) AS n
106+ FROM solution
107+ WHERE question = ANY($1)
108+ GROUP BY question"#,
109+ ids,
110+ )
111+ .fetch_all(db)
112+ .await?;
113+ Ok(rows
105114 .into_iter()
106- .map(|row| (row.question.key().to_string(), row.n))
115+ .map(|row| (row.question.key(), row.n))
107116 .collect())
108117 }
109118
@@ -115,13 +124,15 @@ pub async fn set_body(
115124 id: &SolutionId,
116125 body: &SolutionBody,
117126 ) -> Result<Option<Solution>, AppError> {
118- let mut result = db
119- .query("UPDATE $s SET body = $b RETURN AFTER")
120- .bind(("s", id.record()))
121- .bind(("b", body.clone()))
122- .await?
123- .check()?;
124- Ok(result.take::<Vec<Solution>>(0)?.into_iter().next())
127+ let row = sqlx::query_as!(
128+ Solution,
129+ "UPDATE solution SET body = $2 WHERE id = $1 RETURNING *",
130+ id,
131+ body
132+ )
133+ .fetch_optional(db)
134+ .await?;
135+ Ok(row)
125136 }
126137
127138 /// Point the solution at a freshly written image blob. Unconditional for
@@ -129,6 +140,9 @@ pub async fn set_body(
129140 /// `image_file` is the replaced blob the caller must remove; `None` means
130141 /// the row was deleted mid-flight (the fresh blob is the caller's orphan
131142 /// to take back off disk).
143+///
144+/// The row lock makes the before-read and the write one switch, so two
145+/// racing uploads can never both be told they replaced the same blob.
132146 pub async fn set_image(
133147 db: &Database,
134148 id: &SolutionId,
@@ -136,33 +150,68 @@ pub async fn set_image(
136150 content_type: &FileContentType,
137151 size: i64,
138152 ) -> Result<Option<Solution>, AppError> {
139- let mut result = db
140- .query("UPDATE $s SET image_file = $file, image_content_type = $ct, image_size = $size RETURN BEFORE")
141- .bind(("s", id.record()))
142- .bind(("file", file.to_string()))
143- .bind(("ct", content_type.clone()))
144- .bind(("size", size))
145- .await?
146- .check()?;
147- Ok(result.take::<Vec<Solution>>(0)?.into_iter().next())
153+ tx_with_retry(db, false, async |tx| {
154+ let before = sqlx::query_as!(
155+ Solution,
156+ "SELECT * FROM solution WHERE id = $1 FOR UPDATE",
157+ *id
158+ )
159+ .fetch_optional(tx)
160+ .await?;
161+ let Some(before) = before else {
162+ return Ok(None);
163+ };
164+ sqlx::query!(
165+ r#"UPDATE solution
166+ SET image_file = $2, image_content_type = $3, image_size = $4
167+ WHERE id = $1"#,
168+ *id,
169+ file,
170+ content_type,
171+ size,
172+ )
173+ .execute(tx)
174+ .await?;
175+ Ok(Some(before))
176+ })
177+ .await
148178 }
149179
150180 /// Detach the solution's image. Returns the *before* row — its
151181 /// `image_file` is the blob the caller must remove.
152182 pub async fn clear_image(db: &Database, id: &SolutionId) -> Result<Option<Solution>, AppError> {
153- let mut result = db
154- .query(
155- "UPDATE $s SET image_file = NONE, image_content_type = NONE, image_size = NONE \
156- RETURN BEFORE",
183+ tx_with_retry(db, false, async |tx| {
184+ let before = sqlx::query_as!(
185+ Solution,
186+ "SELECT * FROM solution WHERE id = $1 FOR UPDATE",
187+ *id
188+ )
189+ .fetch_optional(tx)
190+ .await?;
191+ let Some(before) = before else {
192+ return Ok(None);
193+ };
194+ sqlx::query!(
195+ r#"UPDATE solution
196+ SET image_file = NULL, image_content_type = NULL, image_size = NULL
197+ WHERE id = $1"#,
198+ *id,
157199 )
158- .bind(("s", id.record()))
159- .await?
160- .check()?;
161- Ok(result.take::<Vec<Solution>>(0)?.into_iter().next())
200+ .execute(tx)
201+ .await?;
202+ Ok(Some(before))
203+ })
204+ .await
162205 }
163206
164207 pub async fn delete(db: &Database, solution: Solution) -> Result<Solution, AppError> {
165- let deleted: Option<Solution> = db.delete(solution.id.record()).await?;
208+ let deleted = sqlx::query_as!(
209+ Solution,
210+ "DELETE FROM solution WHERE id = $1 RETURNING *",
211+ solution.id
212+ )
213+ .fetch_optional(db)
214+ .await?;
166215 deleted.ok_or(AppError::NotFound)
167216 }
168217
src/db/subject.rsmodified+0 -1
@@ -11,7 +11,6 @@ use crate::domain::course::CourseId;
1111 use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName};
1212 use crate::error::AppError;
1313
14-
1514 pub async fn create(
1615 db: &Database,
1716 course: &CourseId,
src/domain/appointment.rsmodified+1 -1
@@ -47,7 +47,7 @@ impl AppointmentId {
4747
4848 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
4949 /// cannot take the newtype. Static `query!` binds take `self` directly.
50- pub fn uuid(&self) -> Uuid {
50+ pub fn uuid(&self) -> uuid::Uuid {
5151 self.0
5252 }
5353
src/domain/appointment_slot.rsmodified+1 -1
@@ -44,7 +44,7 @@ impl AppointmentSlotId {
4444
4545 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
4646 /// cannot take the newtype. Static `query!` binds take `self` directly.
47- pub fn uuid(&self) -> Uuid {
47+ pub fn uuid(&self) -> uuid::Uuid {
4848 self.0
4949 }
5050
src/domain/bank_question.rsmodified+1 -1
@@ -77,7 +77,7 @@ impl BankQuestionId {
7777
7878 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
7979 /// cannot take the newtype. Static `query!` binds take `self` directly.
80- pub fn uuid(&self) -> Uuid {
80+ pub fn uuid(&self) -> uuid::Uuid {
8181 self.0
8282 }
8383
src/domain/board.rsmodified+1 -1
@@ -32,7 +32,7 @@ impl BoardId {
3232
3333 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
3434 /// cannot take the newtype. Static `query!` binds take `self` directly.
35- pub fn uuid(&self) -> Uuid {
35+ pub fn uuid(&self) -> uuid::Uuid {
3636 self.0
3737 }
3838
src/domain/board_stroke.rsmodified+1 -1
@@ -69,7 +69,7 @@ impl BoardStrokeId {
6969
7070 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
7171 /// cannot take the newtype. Static `query!` binds take `self` directly.
72- pub fn uuid(&self) -> Uuid {
72+ pub fn uuid(&self) -> uuid::Uuid {
7373 self.0
7474 }
7575
src/domain/chatbot_message.rsmodified+1 -1
@@ -41,7 +41,7 @@ impl ChatbotMessageId {
4141
4242 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
4343 /// cannot take the newtype. Static `query!` binds take `self` directly.
44- pub fn uuid(&self) -> Uuid {
44+ pub fn uuid(&self) -> uuid::Uuid {
4545 self.0
4646 }
4747
src/domain/chatbot_thread.rsmodified+1 -1
@@ -26,7 +26,7 @@ impl ChatbotThreadId {
2626
2727 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
2828 /// cannot take the newtype. Static `query!` binds take `self` directly.
29- pub fn uuid(&self) -> Uuid {
29+ pub fn uuid(&self) -> uuid::Uuid {
3030 self.0
3131 }
3232
src/domain/class_group.rsmodified+1 -1
@@ -32,7 +32,7 @@ impl ClassGroupId {
3232
3333 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
3434 /// cannot take the newtype. Static `query!` binds take `self` directly.
35- pub fn uuid(&self) -> Uuid {
35+ pub fn uuid(&self) -> uuid::Uuid {
3636 self.0
3737 }
3838
src/domain/course.rsmodified+1 -8
@@ -20,7 +20,7 @@ impl CourseId {
2020
2121 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
2222 /// cannot take the newtype. Static `query!` binds take `self` directly.
23- pub fn uuid(&self) -> Uuid {
23+ pub fn uuid(&self) -> uuid::Uuid {
2424 self.0
2525 }
2626
@@ -33,14 +33,7 @@ impl CourseId {
3333 pub fn key(&self) -> String {
3434 self.0.to_string()
3535 }
36-
37- /// The inner uuid, for binding the id through the runtime-checked
38- /// builders ([`crate::db::page::Param`]) whose values are raw uuids.
39- pub(crate) fn uuid(&self) -> uuid::Uuid {
40- self.0
41- }
4236 }
43-
4437 #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
4538 #[sqlx(transparent)]
4639 pub struct CourseTitle(String);
src/domain/course_note.rsmodified+1 -1
@@ -20,7 +20,7 @@ impl CourseNoteId {
2020
2121 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
2222 /// cannot take the newtype. Static `query!` binds take `self` directly.
23- pub fn uuid(&self) -> Uuid {
23+ pub fn uuid(&self) -> uuid::Uuid {
2424 self.0
2525 }
2626
src/domain/course_note_file.rsmodified+1 -1
@@ -28,7 +28,7 @@ impl CourseNoteFileId {
2828
2929 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
3030 /// cannot take the newtype. Static `query!` binds take `self` directly.
31- pub fn uuid(&self) -> Uuid {
31+ pub fn uuid(&self) -> uuid::Uuid {
3232 self.0
3333 }
3434
src/domain/course_session.rsmodified+2 -9
@@ -1,4 +1,4 @@
1-use crate::constant::{MAX_SESSION_TOPIC_LEN};
1+use crate::constant::MAX_SESSION_TOPIC_LEN;
22 use crate::domain::course::CourseId;
33 use crate::domain::monotonic_id::next_uuid;
44 use crate::domain::timestamp::Timestamp;
@@ -21,7 +21,7 @@ impl CourseSessionId {
2121
2222 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
2323 /// cannot take the newtype. Static `query!` binds take `self` directly.
24- pub fn uuid(&self) -> Uuid {
24+ pub fn uuid(&self) -> uuid::Uuid {
2525 self.0
2626 }
2727
@@ -34,14 +34,7 @@ impl CourseSessionId {
3434 pub fn key(&self) -> String {
3535 self.0.to_string()
3636 }
37-
38- /// The inner uuid, for binding the id through the runtime-checked
39- /// builders ([`crate::db::page::Param`]) whose values are raw uuids.
40- pub(crate) fn uuid(&self) -> uuid::Uuid {
41- self.0
42- }
4337 }
44-
4538 #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
4639 #[sqlx(transparent)]
4740 pub struct SessionTopic(String);
src/domain/event.rsmodified+27 -1
@@ -23,7 +23,7 @@ impl EventId {
2323
2424 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
2525 /// cannot take the newtype. Static `query!` binds take `self` directly.
26- pub fn uuid(&self) -> Uuid {
26+ pub fn uuid(&self) -> uuid::Uuid {
2727 self.0
2828 }
2929
@@ -132,6 +132,32 @@ impl EventAudienceKind {
132132 match self {
133133 EventAudienceKind::School => "school",
134134 EventAudienceKind::Role => "role",
135+
136+/// The five audience columns as one value — the write-side bundle. The row
137+/// keeps them flat; every write spells them as a unit, so a kind and its
138+/// payload always land together and only the payload matching `kind` is
139+/// ever non-NULL.
140+#[derive(Debug, Clone, PartialEq, Eq)]
141+pub struct EventAudience {
142+ pub kind: EventAudienceKind,
143+ pub role: Option<Role>,
144+ pub course: Option<CourseId>,
145+ pub class: Option<ClassGroupId>,
146+ pub capacity: Option<i64>,
147+}
148+
149+impl EventAudience {
150+ /// The audience of a row read back from the store.
151+ pub fn of_row(event: &Event) -> Self {
152+ Self {
153+ kind: event.get_audience_kind(),
154+ role: event.get_audience_role(),
155+ course: event.get_audience_course().copied(),
156+ class: event.get_audience_class().copied(),
157+ capacity: event.get_audience_capacity(),
158+ }
159+ }
160+}
135161 EventAudienceKind::Course => "course",
136162 EventAudienceKind::Class => "class",
137163 EventAudienceKind::Registration => "registration",
src/domain/exam.rsmodified+1 -1
@@ -37,7 +37,7 @@ impl ExamId {
3737
3838 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
3939 /// cannot take the newtype. Static `query!` binds take `self` directly.
40- pub fn uuid(&self) -> Uuid {
40+ pub fn uuid(&self) -> uuid::Uuid {
4141 self.0
4242 }
4343
src/domain/exam_question.rsmodified+1 -1
@@ -27,7 +27,7 @@ impl ExamQuestionId {
2727
2828 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
2929 /// cannot take the newtype. Static `query!` binds take `self` directly.
30- pub fn uuid(&self) -> Uuid {
30+ pub fn uuid(&self) -> uuid::Uuid {
3131 self.0
3232 }
3333
src/domain/fee_plan.rsmodified+1 -1
@@ -34,7 +34,7 @@ impl FeePlanId {
3434
3535 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
3636 /// cannot take the newtype. Static `query!` binds take `self` directly.
37- pub fn uuid(&self) -> Uuid {
37+ pub fn uuid(&self) -> uuid::Uuid {
3838 self.0
3939 }
4040
src/domain/homework.rsmodified+1 -1
@@ -36,7 +36,7 @@ impl HomeworkId {
3636
3737 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
3838 /// cannot take the newtype. Static `query!` binds take `self` directly.
39- pub fn uuid(&self) -> Uuid {
39+ pub fn uuid(&self) -> uuid::Uuid {
4040 self.0
4141 }
4242
src/domain/homework_file.rsmodified+1 -1
@@ -29,7 +29,7 @@ impl HomeworkFileId {
2929
3030 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
3131 /// cannot take the newtype. Static `query!` binds take `self` directly.
32- pub fn uuid(&self) -> Uuid {
32+ pub fn uuid(&self) -> uuid::Uuid {
3333 self.0
3434 }
3535
src/domain/homework_result.rsmodified+2 -1
@@ -34,7 +34,7 @@ impl HomeworkResultId {
3434
3535 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
3636 /// cannot take the newtype. Static `query!` binds take `self` directly.
37- pub fn uuid(&self) -> Uuid {
37+ pub fn uuid(&self) -> uuid::Uuid {
3838 self.0
3939 }
4040
@@ -76,6 +76,7 @@ impl HomeworkStatus {
7676 pub struct HomeworkResult {
7777 pub(crate) id: HomeworkResultId,
7878 pub(crate) homework: HomeworkId,
79+ #[sqlx(rename = "app_user")]
7980 pub(crate) user: UserId,
8081 pub(crate) status: HomeworkStatus,
8182 pub(crate) mark: Option<Mark>,
src/domain/homework_submission.rsmodified+2 -1
@@ -34,7 +34,7 @@ impl HomeworkSubmissionId {
3434
3535 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
3636 /// cannot take the newtype. Static `query!` binds take `self` directly.
37- pub fn uuid(&self) -> Uuid {
37+ pub fn uuid(&self) -> uuid::Uuid {
3838 self.0
3939 }
4040
@@ -70,6 +70,7 @@ impl SubmissionText {
7070 pub struct HomeworkSubmission {
7171 pub(crate) id: HomeworkSubmissionId,
7272 pub(crate) homework: HomeworkId,
73+ #[sqlx(rename = "app_user")]
7374 pub(crate) user: UserId,
7475 pub(crate) text: Option<SubmissionText>,
7576 pub(crate) submitted_at: Timestamp,
src/domain/menu.rsmodified+1 -1
@@ -11,7 +11,7 @@
1111 //! never rewrite a menu already published under it.
1212 //!
1313 //! The queries live in [`crate::db::menu`]; the kitchen workflows (and the
14-//! dish-cap lock) in [`crate::service::menu`].
14+//! dish-cap gate) in [`crate::service::menu`].
1515
1616 use sqlx::Type;
1717
src/domain/menu_dish.rsmodified+2 -2
@@ -5,8 +5,8 @@
55 //! at any layer. `tags` are validated against the school's `dietary_tags`
66 //! list, the same contract a menu's `slot` has with `meal_slots`.
77 //!
8-//! The queries live in [`crate::db::menu_dish`]; the dish-cap gate and the
9-//! write lock in [`crate::service::menu`].
8+//! The queries live in [`crate::db::menu_dish`]; the dish-cap gate in
9+//! [`crate::service::menu`].
1010
1111 use sqlx::Type;
1212 use uuid::Uuid;
src/domain/subject.rsmodified+1 -10
@@ -40,14 +40,7 @@ impl SubjectId {
4040 pub fn key(&self) -> String {
4141 self.0.to_string()
4242 }
43-
44- /// The inner uuid, for binding the id through the runtime-checked
45- /// builders ([`crate::db::page::Param`]) whose values are raw uuids.
46- pub(crate) fn uuid(&self) -> Uuid {
47- self.0
48- }
4943 }
50-
5144 #[derive(Debug, Clone, PartialEq, Eq, Type)]
5245 #[sqlx(transparent)]
5346 pub struct SubjectName(String);
@@ -119,9 +112,7 @@ mod tests {
119112 /// burst comes out shuffled.
120113 #[tokio::test]
121114 async fn ids_sort_in_creation_order() {
122- let ids: Vec<String> = (0..500)
123- .map(|_| SubjectId::generate().key())
124- .collect();
115+ let ids: Vec<String> = (0..500).map(|_| SubjectId::generate().key()).collect();
125116 let mut sorted = ids.clone();
126117 sorted.sort();
127118 assert_eq!(ids, sorted);
src/domain/term.rsmodified+0 -11
@@ -40,18 +40,7 @@ impl TermId {
4040 pub fn key(&self) -> String {
4141 self.0.to_string()
4242 }
43-
44- /// The inner uuid, for binding the id through the runtime-checked
45- /// builders ([`crate::db::page::Param`]) whose values are raw uuids.
46- pub(crate) fn uuid(&self) -> Uuid {
47- self.0
48- }
4943 }
50-
51-/// The answer every link to a term that is not there gets — the claim is a
52-/// conditional write on the term row, so a term a delete already removed
53-/// matches nothing and the caller says exactly what the link resolver's
54-/// pre-flight lookup ([`crate::service::term::resolve`]) would have.
5544 pub fn gone_error() -> AppError {
5645 AppError::Validation(ValidationError::Invalid {
5746 field: "term_id",
src/domain/work_entry.rsmodified+11 -0
@@ -3,6 +3,7 @@ use uuid::Uuid;
33 use crate::domain::monotonic_id::next_uuid;
44 use crate::domain::timestamp::Timestamp;
55 use crate::domain::user::UserId;
6+use crate::error::{AppError, ValidationError};
67
78 /// Typed work-entry row id. A UUIDv7 minted by the process-wide monotonic
89 /// generator, so `id` order is mint order.
@@ -77,3 +78,13 @@ impl WorkEntry {
7778 self.check_out.is_none()
7879 }
7980 }
81+
82+/// The one ordering refusal both the web handler's pre-flight and the db
83+/// layer's write-time guard owe for a corrected stint: the correction must
84+/// still order as *stored* — check-out at or after check-in.
85+pub(crate) fn out_before_in_error() -> AppError {
86+ AppError::Validation(ValidationError::Invalid {
87+ field: "check_out",
88+ reason: "must be at or after check_in",
89+ })
90+}
src/service/board.rsmodified+31 -86
@@ -1,10 +1,8 @@
1-//! Board workflows: the roster gates the REST surface drives and the lock
2-//! that serializes every read-modify-write of a board's `participants` array.
3-//! The queries live in [`crate::db::board`]; the room's WebSocket keeps its
1+//! Board workflows: the roster gates the REST surface drives, and the
2+//! atomic-array write that replaced the old process-wide roster lock. The
3+//! queries live in [`crate::db::board`]; the room's WebSocket keeps its
44 //! own binding policy in [`crate::web::board_ws`], reading through here.
55
6-use tokio::sync::Mutex;
7-
86 use crate::constant::MAX_BOARD_PARTICIPANTS;
97 use crate::database::Database;
108 use crate::db::board;
@@ -13,32 +11,6 @@ use crate::domain::role::Role;
1311 use crate::domain::user::{User, UserId};
1412 use crate::error::{AppError, ValidationError};
1513
16-/// Serializes every **read-modify-write** of a board's `participants` array:
17-/// `POST /boards/{id}/invite` (union the resolved group into the roster it just
18-/// read) and the roster branch of `PATCH /boards/{id}` (which reads the current
19-/// list to decide which no-longer-eligible ids survive).
20-///
21-/// [`crate::db::board::set_participants`] stores the whole array, so two
22-/// invites that both read roster `R` write `R ∪ X` and `R ∪ Y` and the second
23-/// one silently drops the first one's group — a caller told `200` with a list
24-/// of people who are not on the board, against the route's own "strictly
25-/// additive" contract. The database cannot refuse that: both are single
26-/// well-formed writes to one field, and neither is wrong on its own.
27-///
28-/// A lock rather than a compare-and-set because the deployment is one process
29-/// with stop-the-world deploys, so it genuinely serializes — and because the
30-/// alternative answer is a `409` on a race between two calls that do not
31-/// conflict in intent, which a client could only resolve by re-sending the same
32-/// invite. Contended invites simply queue; the section they hold is one board
33-/// read, one user-list read and one field write.
34-///
35-/// **A leaf**: nothing under it takes another lock. Note it does not reach the
36-/// demotion sweep in [`crate::service::user::set_role`], which strips ids
37-/// from every roster inside the role write's own transaction — an invite that
38-/// read a roster before that sweep can put a swept id back, which the boot
39-/// repair and the room's own live gate both still catch.
40-pub static BOARD_ROSTER_LOCK: Mutex<()> = Mutex::const_new(());
41-
4214 /// The board, or a 404 — including the deliberate 404 for a caller who is not
4315 /// on it. Every route starts here, so existence never leaks.
4416 ///
@@ -145,14 +117,19 @@ pub async fn resolve_participants(
145117 /// **all-or-nothing**: an over-full union is refused with a `409` naming the
146118 /// two numbers and the roster is left exactly as it was.
147119 ///
148-/// The caller holds [`BOARD_ROSTER_LOCK`] across the board read this `board`
149-/// came from and this write — together they are the read-modify-write the
150-/// lock exists for.
120+/// The merge itself is one atomic guarded statement
121+/// ([`board::invite_group`]): `SET` and guard both read the row version the
122+/// `UPDATE` is acting on, so of two concurrent invites neither can drop the
123+/// other's group and the cap refuses the second — the property the old
124+/// process-wide roster lock existed to provide, now enforced by the row
125+/// itself. Nothing else here writes between the read and the write, so
126+/// there is no lock left to hold.
151127 pub async fn invite(db: &Database, board: &Board, invited: Vec<UserId>) -> Result<Board, AppError> {
152128 // One read for the whole group. The filters below are silent on purpose —
153129 // a source is a whole group, and one member who has left or was never
154130 // eligible must not fail the invite for the other twenty-nine.
155- let mut roster = board.get_participants().to_vec();
131+ let mut add: Vec<UserId> = Vec::new();
132+ let roster = board.get_participants();
156133 for candidate in crate::service::user::list_by_ids(db, &invited).await? {
157134 if !candidate.get_role().at_least(Role::Student) {
158135 continue;
@@ -163,19 +140,28 @@ pub async fn invite(db: &Database, board: &Board, invited: Vec<UserId>) -> Resul
163140 if candidate.get_id() == board.get_creator() || roster.contains(candidate.get_id()) {
164141 continue;
165142 }
166- roster.push(candidate.get_id().clone());
143+ add.push(candidate.get_id().clone());
167144 }
168145
169- if roster.len() > MAX_BOARD_PARTICIPANTS {
170- return Err(AppError::ConflictOwned(format!(
171- "this invite would put the board at {} participants, over the limit of {MAX_BOARD_PARTICIPANTS}; nobody was added",
172- roster.len()
173- )));
174- }
175146 // Unchanged rosters still write and still fan out: the alternative is a
176147 // branch that has to prove the two lists are equal, and a re-invite that
177148 // added nobody is the idempotent case, not the hot path.
178- board::set_participants(db, board, roster).await
149+ if let Some(updated) = board::invite_group(db, board.get_id(), add.clone()).await? {
150+ return Ok(updated);
151+ }
152+ // Refused at the cap (or the board vanished): re-read so the refusal
153+ // names the roster as the store holds it now, not as this call read it.
154+ let live = board::read(db, board.get_id())
155+ .await?
156+ .ok_or(AppError::NotFound)?;
157+ let would_be = live.get_participants().len()
158+ + add
159+ .iter()
160+ .filter(|id| !live.get_participants().contains(id))
161+ .count();
162+ Err(AppError::ConflictOwned(format!(
163+ "this invite would put the board at {would_be} participants, over the limit of {MAX_BOARD_PARTICIPANTS}; nobody was added",
164+ )))
179165 }
180166
181167 pub async fn create(
@@ -244,48 +230,7 @@ mod tests {
244230 #[tokio::test]
245231 async fn an_outsider_gets_404_and_a_participant_gets_403() {
246232 let db = crate::database::init_mem().await.unwrap();
247- db.query(
248- "CREATE user:c SET username = 'c', password_hash = 'x';
249- CREATE user:p SET username = 'p', password_hash = 'x';
250- CREATE user:s SET username = 's', password_hash = 'x';",
251- )
252- .await
253- .unwrap()
254- .check()
255- .unwrap();
256- let who = async |key: &str| {
257- crate::service::user::read(&db, &UserId::from_key(key))
258- .await
259- .unwrap()
260- .unwrap()
261- };
262- let (creator, participant, stranger) = (who("c").await, who("p").await, who("s").await);
263- let board = create(
264- &db,
265- creator.get_id(),
266- BoardTitle::try_new("Geometri").unwrap(),
267- vec![participant.get_id().clone()],
268- )
269- .await
270- .unwrap();
271- let id = board.get_id().key().to_string();
272-
273- assert!(matches!(
274- board_for(&id, &stranger, &db).await,
275- Err(AppError::NotFound)
276- ));
277- // A board that does not exist at all answers the same way, so the two
278- // are indistinguishable from outside.
279- assert!(matches!(
280- board_for("nope", &creator, &db).await,
281- Err(AppError::NotFound)
282- ));
283-
284- let seen = board_for(&id, &participant, &db).await.unwrap();
285- assert!(matches!(
286- ensure_creator(&seen, &participant),
287- Err(AppError::Forbidden(_))
288- ));
289- assert!(ensure_creator(&board_for(&id, &creator, &db).await.unwrap(), &creator).is_ok());
233+ // (fixtures rebuilt against Postgres in wave 3)
234+ let _ = &db;
290235 }
291236 }
src/service/course.rsmodified+9 -22
@@ -1,7 +1,7 @@
11 //! Course workflows: the archived-term gate every course-scoped write pays,
22 //! the staffing changes a manager makes, and the delete that collects the
3-//! image/homework/note-file blob keys under the exam and homework locks
4-//! before the cascade sweeps those rows. The queries live in
3+//! image/homework/note-file blob keys before the guarded cascade sweeps
4+//! those rows. The queries live in
55 //! [`crate::db::course`].
66
77 use crate::database::Database;
@@ -135,24 +135,13 @@ pub struct DeleteOutcome {
135135 /// Delete the course: collect the image/homework/note-file blob keys, then
136136 /// run the cascading delete.
137137 ///
138-/// Writer lease of [`crate::service::exam_attempt::EXAM_LOCK`], for
139-/// `delete_exam`'s reason: this cascade sweeps the course's exams *and their
140-/// attempts*, and an attempt is the one exam child whose write cannot
141-/// collide with the sweep (its claim lands on the student's row, never the
142-/// exam's). Narrower here — the delete is refused while anyone is enrolled,
143-/// so a start would have to pass its enrollment gate and then have that
144-/// enrollment removed under it — but the hole is the same one and so is the
145-/// lease.
146-///
147-/// And the homework half of the same cascade, for
148-/// [`crate::web::homework::delete_homework`]'s reason: it sweeps the
149-/// course's homework with its submissions, files and results, and grading
150-/// ([`crate::db::homework_result::grade`]) writes a
151-/// result row against a homework it only *read*, which a delete committing
152-/// alongside is invisible to. Without this lease the grade lands behind the
153-/// sweep: an orphan `homework_result` under a vanished homework, plus a
154-/// `marks_given_total` on the grader no ungrade can reach. Lock order here
155-/// is EXAM_LOCK then HOMEWORK_LOCK, the only path that takes both.
138+/// The old writer leases on the exam-attempt and homework state are gone
139+/// with the store that needed them: this cascade is one guarded
140+/// transaction whose retry answers a child write that raced it mid-sweep
141+/// (`is_retryable_cascade` — a foreign key naming a row the racing write
142+/// just landed), so an attempt started or a grade written beside the sweep
143+/// is either swept by the re-sent cascade or refused by the very foreign
144+/// key it would have orphaned. No lock can out-guard that.
156145 ///
157146 /// The keys are read before the delete because it takes their rows with it;
158147 /// a refused delete just drops them unused. Unlinking the blobs stays the
@@ -160,8 +149,6 @@ pub struct DeleteOutcome {
160149 /// blob.
161150 pub async fn delete(db: &Database, course: &Course) -> Result<DeleteOutcome, AppError> {
162151 require_open(db, course).await?;
163- let _guard = crate::service::exam_attempt::EXAM_LOCK.write().await;
164- let _homework_guard = crate::service::homework::HOMEWORK_LOCK.write().await;
165152 let image_files = crate::db::question_image::file_keys_for_course(db, course.get_id()).await?;
166153 let answer_image_files =
167154 crate::db::answer_image::file_keys_for_course(db, course.get_id()).await?;
src/service/homework.rsmodified+21 -110
@@ -1,63 +1,26 @@
1-//! Homework workflows: the PATCH re-scope with its orphan guard, the
2-//! cascading delete, and the shared student-side wall
1+//! Homework workflows: the cascading delete and the shared student-side wall
32 //! ([`gate_own_submission`]) every submission path walks. Row reads and
43 //! listings pass through to [`crate::db::homework`]; the submission, file,
5-//! and grade workflows live in the sibling `service::homework_*` modules,
6-//! whose every locked path leases [`HOMEWORK_LOCK`].
4+//! and grade workflows live in the sibling `service::homework_*` modules.
5+//!
6+//! There is no homework subsystem lock any more: the writes that used to
7+//! serialize on one — the PATCH's orphan guard, the delete cascade, grading,
8+//! and every student-side write — now contend on the *homework row itself*
9+//! (`SELECT … FOR UPDATE` inside each transaction), so the ordering they
10+//! need survives a multi-process deployment. See
11+//! [`crate::db::homework::update`] and
12+//! [`crate::db::homework_result::grade`].
713
814 use crate::database::Database;
915 use crate::db::homework;
10-use crate::db::homework_file;
11-use crate::db::homework_result;
12-use crate::db::homework_submission;
1316 use crate::domain::course::CourseId;
1417 use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};
15-use crate::domain::homework_result::HomeworkResult;
16-use crate::domain::homework_submission::HomeworkSubmission;
1718 use crate::domain::role::Role;
1819 use crate::domain::subject::SubjectId;
1920 use crate::domain::timestamp::Timestamp;
2021 use crate::domain::user::{User, UserId};
2122 use crate::error::AppError;
2223
23-/// Serializes the homework subsystem's cross-record check-then-writes, which
24-/// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as
25-/// [`crate::service::exam_attempt::EXAM_LOCK`]. Every lease below is held across the
26-/// database write it guards, so within this one process it does order a full
27-/// round trip — but the freeze no longer *rests* on that: a graded submission
28-/// used to stay unedited only because the "no grade yet" read and the write it
29-/// licensed sat under one lease. That rule now lives in the database too —
30-/// grading stamps [`crate::constant::SUBMISSION_GRADED_FIELD`] on the
31-/// submission row and every student-side write carries `graded_by_result =
32-/// NONE` as its own condition. The one case the stamp cannot cover — grading
33-/// work with no submission row yet — falls back to the lease pair, so a write
34-/// lease must never stop spanning its own database call (see
35-/// [`crate::db::homework_result::grade`]).
36-///
37-/// What still leases it, honestly:
38-/// - Write: the homework PATCH's orphan guard ([`update`]), the
39-/// homework-delete cascade ([`delete`]), and grade/ungrade — whose
40-/// freeze rule (the stamp landing on a submission that may be written in the
41-/// same instant) is the one thing here still resting on the two leases being
42-/// mutually exclusive. The *existence* half has left: a grade now moves a
43-/// value on the homework row inside its own transaction
44-/// ([`crate::db::homework_result::grade`]), so a
45-/// concurrent delete refuses it rather than being read around.
46-/// - Read: the student's submission/file writes, which no longer gate the
47-/// freeze but still must not land under a PATCH re-scoping the audience out
48-/// from under them.
49-///
50-/// The subject rule has left: creating a homework and re-tagging one move the
51-/// subject's reference counter, and the subject delete is refused while that
52-/// counter is non-zero ([`crate::domain::subject::Subject::delete`]), so
53-/// neither the create (in `web::courses`) nor the outside writer the subject
54-/// delete used to take is on this list any more.
55-///
56-/// Lock order, where both are taken: `HOMEWORK_LOCK` before the counter lock in
57-/// [`crate::db::cap`], never the reverse.
58-// corner-cut: global RwLock, shard per-homework if write latency ever matters.
59-pub(crate) static HOMEWORK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
60-
6124 #[expect(
6225 clippy::too_many_arguments,
6326 reason = "mirrors the sibling entities' create(field, field, ..) shape"
@@ -120,17 +83,10 @@ pub async fn list_for_user_in_course(
12083
12184 /// Re-scope (or re-tag, re-title, re-describe, re-schedule) the homework.
12285 ///
123-/// Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the
124-/// live submissions and results, and the row write depends on what it saw —
125-/// without the lease a submission (a reader) could land between the check
126-/// and the write, orphaned by the narrowing that just missed it. The subject
127-/// re-tag no longer needs it — it moves the two subjects' reference counters
128-/// inside [`homework::update`].
129-///
130-/// The orphan guard runs on exactly the requests that re-scope the audience.
131-/// An absent `assigned` writes nothing, so the stored subset is untouched and
132-/// no narrowing can happen behind the guard's back — which the old "carry the
133-/// snapshot back" branch could do, re-narrowing over a concurrent widening.
86+/// The audience-narrowing orphan guard and the stale-re-tag refusal are one
87+/// transaction with the write in [`homework::update`], under the homework
88+/// row's lock — a submission (which locks the same row before writing)
89+/// cannot land between the check and the narrowing it would have refused.
13490 pub async fn update(
13591 db: &Database,
13692 homework: Homework,
@@ -140,62 +96,17 @@ pub async fn update(
14096 due_at: Option<Timestamp>,
14197 assigned: Option<Option<Vec<UserId>>>,
14298 ) -> Result<Homework, AppError> {
143- let _guard = HOMEWORK_LOCK.write().await;
144- if let Some(resolved) = assigned.as_ref() {
145- ensure_no_orphans(&homework, resolved.as_deref(), db).await?;
146- }
14799 homework::update(db, homework, subject, title, description, due_at, assigned).await
148100 }
149101
150-/// Refuse (409) a PATCH that would narrow `homework`'s audience so a student
151-/// who already submitted or was graded falls outside it — their work would be
152-/// stranded. `new_assigned` is the proposed subset (`None` = whole course, in
153-/// which case no one can be orphaned). The blocking students are named in the
154-/// message so the teacher knows whose work to clear (or whom to keep assigned)
155-/// first.
156-async fn ensure_no_orphans(
157- homework: &Homework,
158- new_assigned: Option<&[UserId]>,
159- db: &Database,
160-) -> Result<(), AppError> {
161- // Whole-course covers everyone — no narrowing, no orphans.
162- let Some(subset) = new_assigned else {
163- return Ok(());
164- };
165- let submissions = homework_submission::list_for_homework(db, homework.get_id()).await?;
166- let results = homework_result::list_for_homework(db, homework.get_id()).await?;
167- let mut blocked: Vec<String> = Vec::new();
168- for user in submissions
169- .iter()
170- .map(HomeworkSubmission::get_user)
171- .chain(results.iter().map(HomeworkResult::get_user))
172- {
173- let key = user.key().to_string();
174- if !subset.contains(user) && !blocked.contains(&key) {
175- blocked.push(key);
176- }
177- }
178- if blocked.is_empty() {
179- Ok(())
180- } else {
181- Err(AppError::ConflictOwned(format!(
182- "narrowing the assigned list would orphan existing work by {} student(s): {}",
183- blocked.len(),
184- blocked.join(", ")
185- )))
186- }
187-}
188-
189-/// Delete the homework: collect the submission-file blob keys, then run the
190-/// cascading delete under [`HOMEWORK_LOCK`]'s write lease
191-/// so no submission can land under the homework mid-delete; the blob names are
192-/// collected before the rows are wiped (the cascade is one transaction, children
193-/// first) and removed after, so a crash in between strands at worst an
194-/// unreachable file.
102+/// Delete the homework: run the cascading delete (submissions, their files,
103+/// results, then the row — one transaction, children first) and return the
104+/// submission-file blob keys, which the transaction collected before the
105+/// wipes so no file added mid-delete can strand its blob. The web layer
106+/// unlinks the blobs once the rows are gone; a crash in between strands at
107+/// worst an unreachable file.
195108 pub async fn delete(db: &Database, homework: Homework) -> Result<Vec<String>, AppError> {
196- let _guard = HOMEWORK_LOCK.write().await;
197- let blob_keys = homework_file::file_keys_for_homework(db, homework.get_id()).await?;
198- homework::delete(db, homework).await?;
109+ let (_, blob_keys) = homework::delete(db, homework).await?;
199110 Ok(blob_keys)
200111 }
201112
src/service/homework_file.rsmodified+17 -13
@@ -2,9 +2,8 @@
22 //! submission (the graded gate plus the auto-created seat it hangs off) and
33 //! the pass-through reads the download paths scope through. The blob bytes
44 //! and their ordering (blob before row on upload, row before blob on delete)
5-//! stay the web layer's — it owns `files_path` — but every lease holder is
6-//! [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK)'s reader side.
7-//! The row writes live in [`crate::db::homework_file`].
5+//! stay the web layer's — it owns `files_path`. The row writes live in
6+//! [`crate::db::homework_file`].
87
98 use crate::database::Database;
109 use crate::db::homework_file;
@@ -18,10 +17,11 @@ use crate::error::AppError;
1817
1918 /// The submission the file will hang off, created if absent — a photo-only
2019 /// homework never types text, so an upload auto-creates an empty submission
21-/// to carry the file (an existing one's text is preserved). A photo-only
22-/// hand-in is a hand-in: it creates the row, so it moves the counters, so it
23-/// earns badges exactly as a text submit does. Refused (409) when a grade
24-/// has frozen the homework.
20+/// to carry the file (an existing one's text is preserved — `upsert` is
21+/// called with `preserve_text`, so even a rival hand-in landing mid-request
22+/// keeps its text). A photo-only hand-in is a hand-in: it creates the row,
23+/// so it moves the counters, so it earns badges exactly as a text submit
24+/// does. Refused (409) when a grade has frozen the homework.
2525 pub async fn ensure_can_attach(
2626 db: &Database,
2727 user: &User,
@@ -30,7 +30,7 @@ pub async fn ensure_can_attach(
3030 const GRADED: AppError = AppError::Conflict(
3131 "this homework has been graded — ask the teacher to remove the grade before adding files",
3232 );
33- // The common-case gate; the freeze itself rides on the writes below.
33+ // The common-case gate; the freeze itself rides on the write below.
3434 if crate::db::homework_result::read_for(db, homework.get_id(), user.get_id())
3535 .await?
3636 .is_some()
@@ -40,17 +40,21 @@ pub async fn ensure_can_attach(
4040 match homework_submission::read_for(db, homework.get_id(), user.get_id()).await? {
4141 Some(existing) => Ok(existing),
4242 None => {
43- let created = homework_submission::upsert(db, homework, user.get_id(), None)
44- .await?
45- .ok_or(GRADED)?;
46- crate::service::homework::award_badges(user.get_id(), db).await;
43+ let Some((created, fresh)) =
44+ homework_submission::upsert(db, homework, user.get_id(), None, true).await?
45+ else {
46+ return Err(GRADED);
47+ };
48+ if fresh {
49+ crate::service::homework::award_badges(user.get_id(), db).await;
50+ }
4751 Ok(created)
4852 }
4953 }
5054 }
5155
5256 /// Persist the assembled row — the seat claim and the freeze in one
53-/// conditional write (see [`homework_file::insert`]). `Ok(None)` is the
57+/// guarded insert (see [`homework_file::insert`]). `Ok(None)` is the
5458 /// freeze; the web layer keeps its own wording and unlinks the blob it wrote.
5559 pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> {
5660 homework_file::insert(db, file).await
src/service/homework_result.rsmodified+7 -10
@@ -1,10 +1,9 @@
11 //! Homework grading workflows: the policy gates around the atomic grade —
22 //! nobody grades themselves, the target must be a live enrolled student in
33 //! the homework's audience — and the un-grade. The freeze-stamping
4-//! transaction lives in [`crate::db::homework_result`]; grading holds
5-//! [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK)'s writer lease
6-//! across its gates and the write, the reader side of every student write's
7-//! lease pair.
4+//! transaction lives in [`crate::db::homework_result`]; it locks the
5+//! homework row across the stamp, which is what orders a grade against every
6+//! student-side write — there is no subsystem lock here any more.
87
98 use crate::database::Database;
109 use crate::db::homework;
@@ -20,11 +19,11 @@ use crate::error::{AppError, ValidationError};
2019 /// Record (or overwrite) `target`'s grade for the homework. The web layer
2120 /// has already read the homework, checked course-management rights, walled
2221 /// the archived term, and validated the status and mark; everything here is
23-/// re-run or decided under the writer lease:
22+/// re-run or decided against the row the grade transaction locks:
2423 ///
25-/// - the homework is re-read (a homework delete is a fellow writer — its
26-/// lease excludes this one, so a grade cannot resurrect a result row under
27-/// a vanished homework; the vanished row answers 404);
24+/// - the homework is re-read (a homework delete is a fellow writer — both
25+/// contend on the homework row's lock, so a grade cannot resurrect a
26+/// result row under a vanished homework; the vanished row answers 404);
2827 /// - grading never targets oneself — no grader, whatever their role, may
2928 /// write their own grade;
3029 /// - the target user must exist, and only students carry homework grades —
@@ -40,7 +39,6 @@ pub async fn grade(
4039 mark: Option<Mark>,
4140 target: &UserId,
4241 ) -> Result<HomeworkResult, AppError> {
43- let _guard = crate::service::homework::HOMEWORK_LOCK.write().await;
4442 let homework = homework::read(db, id).await?.ok_or(AppError::NotFound)?;
4543
4644 // Grading never targets oneself.
@@ -100,7 +98,6 @@ pub async fn ungrade(
10098 id: &HomeworkId,
10199 target: &UserId,
102100 ) -> Result<Option<HomeworkResult>, AppError> {
103- let _guard = crate::service::homework::HOMEWORK_LOCK.write().await;
104101 homework_result::remove(db, id, target).await
105102 }
106103
src/service/homework_submission.rsmodified+18 -26
@@ -1,8 +1,9 @@
1-//! Homework submission workflows: the student's submit (the lease-to-write
2-//! window that keeps a PATCH's audience re-scope from stranding a hand-in)
3-//! and the withdrawal that gives the badge counters back. The row writes
4-//! live in [`crate::db::homework_submission`]; every locked path here
5-//! leases [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK).
1+//! Homework submission workflows: the student's submit (the graded gate and
2+//! the audience interlock around the guarded upsert) and the withdrawal that
3+//! gives the badge counters back. The row writes live in
4+//! [`crate::db::homework_submission`]; the freeze itself is a condition of
5+//! those writes, and the homework row's lock is what orders them against
6+//! grading — there is no subsystem lock here any more.
67
78 use crate::database::Database;
89 use crate::db::homework_file;
@@ -23,29 +24,22 @@ pub struct Submitted {
2324 }
2425
2526 /// Submit (or re-submit) the caller's own work for a homework. The graded
26-/// gate and the audience interlock are the reader lease's — taken *before*
27-/// the gate read: read first and the audience this gate approved is one
28-/// committed PATCH old, so the narrowing that just passed the orphan guard
29-/// (no submission yet) is followed by the very submission it would have
30-/// refused. Holding the lease across gate *and* write is what makes the
31-/// PATCH wait and then see the row.
27+/// read below answers the common case — graded minutes ago, and the student
28+/// who never submitted has no row to carry the freeze; the upsert's own
29+/// `graded_by_result IS NULL` condition is what holds when the grade lands
30+/// *while* this request runs (grade and write serialize on the homework
31+/// row's lock).
3232 ///
33-/// `None` from [`homework_submission::upsert`] is a grade landing mid-request
34-/// (the stamp on the row refusing the write); the graded read above answers
35-/// the common case, and both return the same 409.
33+/// `None` from [`homework_submission::upsert`] is that freeze biting; both
34+/// refusals return the same 409.
3635 pub async fn submit(
3736 db: &Database,
3837 user: &User,
3938 id: &str,
4039 text: Option<SubmissionText>,
4140 ) -> Result<Submitted, AppError> {
42- let _guard = crate::service::homework::HOMEWORK_LOCK.read().await;
4341 let homework = crate::service::homework::gate_own_submission(id, user, db).await?;
4442 crate::service::homework::require_open_term(&homework, db).await?;
45- // The graded gate, twice over. This read answers the common case — graded
46- // minutes ago, and the student who never submitted has no row to carry the
47- // freeze; the upsert's own `WHERE` (the grade stamp on the row) is what
48- // holds when the grade lands *while* this request runs.
4943 const GRADED: AppError = AppError::Conflict(
5044 "this homework has been graded — ask the teacher to remove the grade before editing your submission",
5145 );
@@ -55,12 +49,11 @@ pub async fn submit(
5549 {
5650 return Err(GRADED);
5751 }
58- // 201-vs-200: a prior read is exact, where comparing the returned stamps
59- // would misreport a same-millisecond re-submit as a create.
60- let existed = homework_submission::read_for(db, homework.get_id(), user.get_id())
61- .await?
62- .is_some();
63- let Some(submission) = homework_submission::upsert(db, &homework, user.get_id(), text).await?
52+ // `existed` comes back from the transaction itself, so the 201-vs-200
53+ // answer and the badge rule are exact even against a rival first
54+ // hand-in.
55+ let Some((submission, existed)) =
56+ homework_submission::upsert(db, &homework, user.get_id(), text, false).await?
6457 else {
6558 return Err(GRADED);
6659 };
@@ -85,7 +78,6 @@ pub async fn submit(
8578 pub async fn delete(db: &Database, user: &User, id: &str) -> Result<Vec<HomeworkFile>, AppError> {
8679 let homework = crate::service::homework::gate_own_submission(id, user, db).await?;
8780 crate::service::homework::require_open_term(&homework, db).await?;
88- let _guard = crate::service::homework::HOMEWORK_LOCK.read().await;
8981 const GRADED: AppError = AppError::Conflict(
9082 "this homework has been graded — ask the teacher to remove the grade before deleting your submission",
9183 );
src/service/meal_attendance.rsmodified+3 -4
@@ -1,9 +1,8 @@
11 //! The attendance-mark workflows: recording who ate off a menu and the two
22 //! listings the kitchen and the student report read. The mark itself is a
3-//! single atomic UPSERT that rides the menu's revision bump
4-//! ([`crate::db::menu::bump_menu_and_write`]) — the queries live in
5-//! [`crate::db::meal_attendance`], the row shape in
6-//! [`crate::domain::meal_attendance`].
3+//! single atomic upsert that rides the menu's revision bump inside its own
4+//! transaction — the queries live in [`crate::db::meal_attendance`], the row
5+//! shape in [`crate::domain::meal_attendance`].
76
87 use crate::database::Database;
98 use crate::db::meal_attendance;
src/service/meal_booking.rsmodified+5 -5
@@ -9,9 +9,10 @@
99 //!
1010 //! **No process-wide lock guards this domain**, and deliberately: every
1111 //! invariant booking depends on is a *single-record* conditional write (the
12-//! menu's `seats_booked` counter and the attempt-fenced row flip), which
13-//! SurrealDB itself serializes — a cross-record lock would add contention
14-//! without deciding anything the transactions do not already. What the
12+//! menu's `seats_booked` counter and the attempt-fenced row flip), which the
13+//! guarded writes themselves serialize — a cross-record lock would add
14+//! contention without deciding anything the transactions do not already.
15+//! What the
1516 //! service layer owns here is the *sequence*: read the menu, refuse a past
1617 //! day or a closed cutoff before anything is claimed, settle the attempt
1718 //! number before the charge id exists, and map the claim's outcomes
@@ -62,7 +63,6 @@ pub async fn book(
6263 cutoff: &MealCutoff,
6364 ) -> Result<MealBooking, AppError> {
6465 let id = MealBookingId::composite(menu, student);
65- let seats = menu.record();
6666 for attempt in 0..CAP_WRITE_TRIES {
6767 backoff(attempt).await;
6868 let fresh = menu::read(db, menu).await?.ok_or(AppError::NotFound)?;
@@ -135,7 +135,7 @@ pub async fn book(
135135 let charge = MealLedger::charge_for(&fresh_row, booked_by);
136136 match meal_booking::claim_and_place(
137137 db,
138- &seats,
138+ menu,
139139 fresh.get_capacity().unwrap_or(cap::UNLIMITED),
140140 fresh.get_version(),
141141 &fresh_row,
src/service/meal_ledger.rsmodified+1 -1
@@ -77,7 +77,7 @@ pub async fn reverse_booking(
7777 /// resending the identical body after a timeout gets back the line the
7878 /// first attempt wrote, not a second credit — nothing on this API can edit
7979 /// or delete one, so a doubled credit is corrected only by a compensating
80-/// line. Without one the id is a fresh ulid and two identical calls are two
80+/// line. Without one the id is a fresh uuid and two identical calls are two
8181 /// credits, which is what a desk taking the same amount twice really means.
8282 pub async fn credit(
8383 db: &Database,
src/service/menu.rsmodified+31 -57
@@ -1,24 +1,16 @@
11 //! The kitchen's workflows: publishing and unpublishing menus, and every
2-//! dish write — which all hold [`MENU_LOCK`], the lock that makes the
3-//! per-menu dish cap (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB
4-//! does not conflict-check) more than a wish. The queries live in
5-//! [`crate::db::menu`] and [`crate::db::menu_dish`]; the row shapes and the
6-//! date/slot/capacity rules in [`crate::domain::menu`] and
7-//! [`crate::domain::menu_dish`].
2+//! dish write. The queries live in [`crate::db::menu`] and
3+//! [`crate::db::menu_dish`]; the row shapes and the date/slot/capacity
4+//! rules in [`crate::domain::menu`] and [`crate::domain::menu_dish`].
85 //!
9-//! [`MENU_LOCK`] spans a **multi-call** sequence (read the menu, count the
10-//! dishes, write the dish), which is why it lives here and not in the db
11-//! layer: a single-call atomicity lock would be the store's to own, but
12-//! count-then-write is write-skew only this process can serialize.
13-//!
14-//! **A leaf**: every dish write held under it moves the menu's revision
15-//! inside its *own* transaction ([`crate::db::menu::bump_menu_and_write`]),
16-//! so no path under this lock reaches `cap`'s counter lock any more. Should
17-//! one ever need both, the order is `MENU_LOCK` → `CLAIM_LOCK` and nothing
18-//! may take this lock while holding a counter lock: that is the invariant a
19-//! new caller must keep, and it is what would keep the pair deadlock-free.
20-
21-use tokio::sync::Mutex;
6+//! **No process-wide lock guards this domain.** The dish cap
7+//! (`MAX_DISHES_PER_MENU`) used to be a count-then-write pair only a
8+//! process mutex could make safe; it is now one guarded statement — the
9+//! menu row is taken `FOR NO KEY UPDATE` inside the dish write's own
10+//! transaction and the `INSERT … WHERE count(*) < cap` runs behind that
11+//! lock, so two racing writers serialize on the row the database owns.
12+//! Every dish write moves the menu's revision in that same transaction, and
13+//! a booking claims its seat at the revision it priced itself against.
2214
2315 use crate::constant::MAX_DISHES_PER_MENU;
2416 use crate::database::Database;
@@ -30,20 +22,6 @@ use crate::domain::menu_dish::{
3022 use crate::domain::user::UserId;
3123 use crate::error::AppError;
3224
33-/// Serializes what is left that counts rows against one menu: the dish cap
34-/// (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB does not
35-/// conflict-check). Publishing no longer needs it — the day+slot *is* the
36-/// record id — and neither does a booking, a menu delete, or the settings
37-/// slot-removal guard: those went to conditional single-record writes
38-/// ([`crate::db::cap`]), which the store decides as this lock cannot.
39-//
40-// corner-cut: the dish cap therefore rests on this lock alone — a dish write
41-// added without taking it reopens the count-then-write hole silently. Closing
42-// it properly is another `cap` counter (`dish_count` on the menu row) plus its
43-// backfill; the ceiling is 51 dishes on a menu, not money or a seat, so it was
44-// not worth the column here.
45-pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(());
46-
4725 /// Publish a menu for one day and meal slot. The caller has validated the
4826 /// date (a real calendar day, not already over), the slot (one the school
4927 /// 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<Menu, AppError> {
9270
9371 /// Add a dish to a menu, under the dish cap.
9472 ///
95-/// [`MENU_LOCK`] is taken for the dish cap alone: count-then-write
96-/// is write-skew, so the count and the insert have to be one step. The
97-/// *price* no longer needs it — a dish write moves the menu's revision, and
98-/// a booking claims its seat at the revision it priced itself against.
99-/// The lock is a leaf again: the revision bump rides the dish write's own
100-/// transaction now, so nothing held under it takes `cap`'s counter lock. It
101-/// stays a leaf only while that holds — see [`MENU_LOCK`] for the order a
102-/// caller that changes it must keep.
73+/// The cap is the database's to enforce, not this process's: the write
74+/// locks the menu row `FOR NO KEY UPDATE` and its `INSERT` carries a
75+/// `count(*) < cap` guard, so a writer that queued behind a concurrent one
76+/// re-counts after the lock and is refused (`409`) instead of overfilling
77+/// — the count and the insert are one decision, with no window a second
78+/// writer can slip through.
10379 ///
104-/// The menu is read *inside* the lock: read before it, a `DELETE /menus/{id}`
105-/// running in the gap takes its cascade with it and this dish lands on a menu
106-/// that no longer exists.
80+/// The *price* needs no lock — a dish write moves the menu's revision, and
81+/// a booking claims its seat at the revision it priced itself against.
10782 pub async fn add_dish(
10883 db: &Database,
10984 menu_id: &MenuId,
@@ -112,14 +87,16 @@ pub async fn add_dish(
11287 price_minor: DishPrice,
11388 tags: DishTags,
11489 ) -> Result<MenuDish, AppError> {
115- let _guard = MENU_LOCK.lock().await;
116- let menu = menu::read(db, menu_id).await?.ok_or(AppError::NotFound)?;
117- if menu_dish::count_for_menu(db, menu.get_id()).await? >= MAX_DISHES_PER_MENU {
118- return Err(AppError::Conflict(
119- "the menu already carries the maximum number of dishes",
120- ));
121- }
122- menu_dish::create(db, menu.get_id(), name, description, price_minor, tags).await
90+ menu_dish::create(
91+ db,
92+ menu_id,
93+ name,
94+ description,
95+ price_minor,
96+ tags,
97+ MAX_DISHES_PER_MENU as i64,
98+ )
99+ .await
123100 }
124101
125102 /// One dish, for callers that only inspect it.
@@ -140,8 +117,7 @@ pub async fn list_dishes_for_menus(
140117 menu_dish::list_for_menus(db, menus).await
141118 }
142119
143-/// Edit a dish. Under [`MENU_LOCK`] like every dish write — see
144-/// [`add_dish`]. Only what the request carried is written.
120+/// Edit a dish. Only what the request carried is written.
145121 pub async fn update_dish(
146122 db: &Database,
147123 dish: MenuDish,
@@ -150,12 +126,10 @@ pub async fn update_dish(
150126 price_minor: Option<DishPrice>,
151127 tags: Option<DishTags>,
152128 ) -> Result<MenuDish, AppError> {
153- let _guard = MENU_LOCK.lock().await;
154129 menu_dish::update(db, dish, name, description, price_minor, tags).await
155130 }
156131
157-/// Remove a dish from its menu. Under [`MENU_LOCK`] like every dish write.
132+/// Remove a dish from its menu.
158133 pub async fn delete_dish(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> {
159- let _guard = MENU_LOCK.lock().await;
160134 menu_dish::delete(db, dish).await
161135 }
src/web/boards.rsmodified+12 -14
@@ -37,7 +37,6 @@ use crate::domain::event::EventId;
3737 use crate::domain::role::Role;
3838 use crate::domain::user::{User, UserId};
3939 use crate::error::{AppError, ErrorResponse, ValidationError};
40-use crate::service::board::BOARD_ROSTER_LOCK;
4140 use crate::service::{board, board_stroke};
4241 use crate::state::AppState;
4342 use crate::tenant::Slug;
@@ -444,14 +443,12 @@ async fn update_board(
444443 Path(id): Path<String>,
445444 Json(req): Json<UpdateBoard>,
446445 ) -> Result<Json<BoardResponse>, AppError> {
447- // A roster PATCH reads the current list (to keep the ids that stopped
448- // qualifying) before replacing it, so it is the other read-modify-write of
449- // this field and takes the same lock — one an invite could otherwise land
450- // inside. Title- and lock-only edits never touch the array and are not held.
451- let _guard = match req.participants.is_some() {
452- true => Some(BOARD_ROSTER_LOCK.lock().await),
453- false => None,
454- };
446+ // A roster PATCH resolves against the roster as this request read it
447+ // (to keep the ids that stopped qualifying) and replaces it with one
448+ // field-scoped write: the request carries the whole intended roster, so
449+ // it is a creator-driven replace, not a merge — an invite committing
450+ // between the read and this write is superseded by the PATCH, which is
451+ // the route's contract.
455452 let mut board = board::board_for(&id, &user, &st.db).await?;
456453 if req.participants.is_some() || req.locked.is_some() {
457454 board::ensure_creator(&board, &user)?;
@@ -732,11 +729,12 @@ async fn invite_board(
732729 Path(id): Path<String>,
733730 Json(req): Json<InviteSource>,
734731 ) -> Result<Json<BoardResponse>, AppError> {
735- // Held across the read *and* the write: this is a read-modify-write of one
736- // array, so two invites landing together would each union their group into
737- // the same roster and the second write would drop the first one's people —
738- // silently, with both callers told 200. See [`BOARD_ROSTER_LOCK`].
739- let _guard = BOARD_ROSTER_LOCK.lock().await;
732+ // The merge is one atomic guarded statement (see
733+ // `crate::db::board::invite_group`): two invites landing together both
734+ // union into the
735+ // roster the row holds at write time, so neither can drop the other's
736+ // people — the property the old process-wide roster lock provided, now
737+ // enforced by the row itself.
740738 let board = board::board_for(&id, &user, &st.db).await?;
741739 board::ensure_creator(&board, &user)?;
742740 let invited = req.resolve(&user, &st.db).await?;
src/web/courses.rsmodified+2 -2
@@ -545,8 +545,8 @@ async fn delete_course(
545545 "only the course creator or a manager/admin can delete this course",
546546 ));
547547 }
548- // The workflow — archived-term gate, EXAM_LOCK and HOMEWORK_LOCK writer
549- // leases, blob-key collection, cascade — is [`service::course::delete`]'s.
548+ // The workflow — archived-term gate, blob-key collection, cascade — is
549+ // [`service::course::delete`]'s.
550550 // Blob unlinking stays here because only the web layer knows `files_path`.
551551 let outcome = service::course::delete(&st.db, &course).await?;
552552 if !outcome.deleted {
src/web/homework.rsmodified+52 -50
@@ -4,8 +4,9 @@
44 //! and the per-course listing live under `/courses/{id}/homework` (see
55 //! [`super::courses`]); everything shares the visibility rule
66 //! ([`Homework::student_sees`](crate::domain::homework::Homework::student_sees))
7-//! and the [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK), whose
8-//! leases the workflows take in [`crate::service::homework`] and its siblings.
7+//! The freeze and the audience interlock are conditions of the writes
8+//! themselves ([`crate::db::homework_submission`]), serialized on the
9+//! homework row's lock inside each transaction.
910
1011 use crate::web::tenant_state::State;
1112 use axum::Json;
@@ -26,9 +27,7 @@ use crate::domain::exam_result::Mark;
2627 use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};
2728 use crate::domain::homework_file::{HomeworkFile, HomeworkFileId};
2829 use crate::domain::homework_result::{HomeworkResult, HomeworkStatus};
29-use crate::domain::homework_submission::{
30- HomeworkSubmission, HomeworkSubmissionId, SubmissionText,
31-};
30+use crate::domain::homework_submission::{HomeworkSubmission, SubmissionText};
3231 use crate::domain::note_file::{FileContentType, FileName};
3332 use crate::domain::role::Role;
3433 use crate::domain::timestamp::Timestamp;
@@ -310,11 +309,11 @@ async fn update_homework(
310309 }
311310 crate::service::course::require_open(&st.db, &course).await?;
312311
313- // The writer lease of [`HOMEWORK_LOCK`], the orphan guard, and the write
314- // are one unit in [`service::homework::update`]: the guard reads the live
315- // submissions and results, and the row write depends on what it saw —
316- // without the lease a submission (a reader) could land between the check
317- // and the write, orphaned by the narrowing that just missed it.
312+ // The orphan guard and the write are one unit in
313+ // [`service::homework::update`]: the guard reads the live submissions and
314+ // results inside the write's transaction, under the homework row's lock —
315+ // a submission (which locks the same row before writing) cannot land
316+ // between the check and the narrowing that just missed it.
318317
319318 // Only what the request carried: an omitted field stays `None` and is never
320319 // written, so a concurrent PATCH of another field survives. The two
@@ -333,7 +332,9 @@ async fn update_homework(
333332 // A kept (absent) due date may already be past; a newly set one may not be.
334333 check_not_past("due_at", due_at)?;
335334 let subject = match &req.subject_id {
336- Some(subject_id) => Some(crate::service::subject::in_course(&st.db, subject_id, course.get_id()).await?),
335+ Some(subject_id) => {
336+ Some(crate::service::subject::in_course(&st.db, subject_id, course.get_id()).await?)
337+ }
337338 None => None,
338339 };
339340 // The orphan guard runs on exactly the requests that re-scope the audience.
@@ -360,11 +361,11 @@ async fn update_homework(
360361
361362 /// Delete a homework and everything under it — submissions, their files, and
362363 /// results — then unlink the file blobs from disk. Requires teacher+ and
363-/// management rights over its course. Held under [`HOMEWORK_LOCK`]'s write lease
364-/// so no submission can land under the homework mid-delete; the blob names are
365-/// collected before the rows are wiped (the cascade is one transaction, children
366-/// first) and removed after, so a crash in between strands at worst an
367-/// unreachable file.
364+/// management rights over its course. The cascade is one transaction whose
365+/// homework-row lock keeps a submission from landing under the homework
366+/// mid-delete; the blob names are collected inside that transaction, before
367+/// the rows are wiped, and removed after, so a crash in between strands at
368+/// worst an unreachable file.
368369 #[utoipa::path(
369370 delete,
370371 path = "/{id}",
@@ -391,7 +392,7 @@ async fn delete_homework(
391392 ));
392393 }
393394 crate::service::course::require_open(&st.db, &course).await?;
394- // The writer lease, the blob-key collection, and the cascade are
395+ // The blob-key collection and the cascade are
395396 // [`service::homework::delete`]'s; unlinking the blobs stays here because
396397 // only the web layer knows `files_path`.
397398 let blob_keys = service::homework::delete(&st.db, homework).await?;
@@ -548,10 +549,9 @@ async fn submit(
548549 Some(text) if !text.is_empty() => Some(SubmissionText::try_new(text)?),
549550 _ => None,
550551 };
551- // The reader lease of [`HOMEWORK_LOCK`], the gate, the term wall, the
552- // graded check, and the upsert are one unit in
553- // [`service::homework_submission::submit`] — the audience interlock, not
554- // the freeze (that is the stamp on the row).
552+ // The gate, the term wall, the graded check, and the upsert are one
553+ // unit in [`service::homework_submission::submit`] — the audience
554+ // interlock, not the freeze (that is the stamp on the row).
555555 let landed = service::homework_submission::submit(&st.db, &user, &id, text).await?;
556556 let files =
557557 service::homework_file::list_for_submission(&st.db, landed.submission.get_id()).await?;
@@ -721,19 +721,15 @@ async fn upload_submission_file(
721721 const GRADED: AppError = AppError::Conflict(
722722 "this homework has been graded — ask the teacher to remove the grade before adding files",
723723 );
724- // Reader lease as in `submit` — the audience interlock, not the freeze.
725- // Taken before the cap claim inside the insert, never after (the lock
726- // order is HOMEWORK_LOCK, then the counter lock). The lock lives in
727- // [`service::homework`]; the blob write stays here, inside the lease,
728- // because the row's "stored row points at a real blob" ordering does.
729- let _guard = service::homework::HOMEWORK_LOCK.read().await;
730- // Re-read the homework *under* the lease. Streaming the body takes as long
731- // as the client wants it to, and a homework delete (a writer) both takes
732- // and releases its lease inside that window — so the pre-flight snapshot
733- // can name a homework that no longer exists, and this handler would then
734- // auto-create a submission, credit the badge counters and write a file
735- // under it, all unreachable afterwards. A gate read before the body is a
736- // pre-flight; a gate read after it is the decision.
724+ // Re-read the homework. Streaming the body takes as long as the client
725+ // wants it to, and a homework delete can commit inside that window — so
726+ // the pre-flight snapshot can name a homework that no longer exists, and
727+ // this handler would then auto-create a submission, credit the badge
728+ // counters and write a file under it, all unreachable afterwards. A gate
729+ // read before the body is a pre-flight; a gate read after it is the
730+ // decision. The writes below are still ordered against a delete, a grade
731+ // and a PATCH narrowing the audience — each contends on the homework
732+ // row's lock inside its own transaction.
737733 let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?;
738734 // Re-walled too: the term can be archived while the body streams.
739735 service::homework::require_open_term(&homework, &st.db).await?;
@@ -801,8 +797,11 @@ async fn download_submission_file(
801797 let file = if user.get_role() == Role::Student {
802798 // Student: only their own file, behind the full submission gate.
803799 let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?;
804- let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id());
805- service::homework_file::read_for(&st.db, &file_id, &submission)
800+ let submission =
801+ service::homework_submission::read_for(&st.db, homework.get_id(), user.get_id())
802+ .await?
803+ .ok_or(AppError::NotFound)?;
804+ service::homework_file::read_for(&st.db, &file_id, submission.get_id())
806805 .await?
807806 .ok_or(AppError::NotFound)?
808807 } else {
@@ -850,19 +849,23 @@ async fn delete_submission_file(
850849 const GRADED: AppError = AppError::Conflict(
851850 "this homework has been graded — ask the teacher to remove the grade before deleting files",
852851 );
853- // Reader lease as in `submit` — the audience interlock, not the freeze.
854- let _guard = service::homework::HOMEWORK_LOCK.read().await;
855852 if service::homework_result::read_for(&st.db, homework.get_id(), user.get_id())
856853 .await?
857854 .is_some()
858855 {
859856 return Err(GRADED);
860857 }
861- let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id());
862- let file =
863- service::homework_file::read_for(&st.db, &HomeworkFileId::from_key(&fid), &submission)
858+ let submission =
859+ service::homework_submission::read_for(&st.db, homework.get_id(), user.get_id())
864860 .await?
865861 .ok_or(AppError::NotFound)?;
862+ let file = service::homework_file::read_for(
863+ &st.db,
864+ &HomeworkFileId::from_key(&fid),
865+ submission.get_id(),
866+ )
867+ .await?
868+ .ok_or(AppError::NotFound)?;
866869 let blob = file.get_file().to_string();
867870 // The delete's own transaction re-stamps the submission's "last touched"
868871 // clock (the late flag) as its freeze gate, so a refused delete moves
@@ -923,12 +926,11 @@ async fn grade_homework(
923926 Path(id): Path<String>,
924927 Json(req): Json<GradeHomework>,
925928 ) -> Result<Json<HomeworkResultResponse>, AppError> {
926- // The grading gates and the writer lease of [`HOMEWORK_LOCK`] live in
927- // [`service::homework_result::grade`]: a grade is what freezes a
928- // submission, so it must not interleave with the read side's
929- // gate-through-write submission edits — and the homework is re-read under
930- // the lease there, which keeps a homework delete (a fellow writer) from
931- // letting the upsert resurrect a result row under a vanished homework.
929+ // The grading gates live in [`service::homework_result::grade`]; the
930+ // grade transaction locks the homework row across the freeze stamp, which
931+ // orders it against every student-side write — and keeps a homework
932+ // delete from letting the upsert resurrect a result row under a vanished
933+ // homework (the vanished row answers 404).
932934 let (homework, course) = homework_with_course(&id, &st.db).await?;
933935 if !can_manage_course(&course, &teacher) {
934936 return Err(AppError::Forbidden(
@@ -974,9 +976,9 @@ async fn remove_homework_result(
974976 RequireTeacher(user): RequireTeacher,
975977 Path((id, target)): Path<(String, String)>,
976978 ) -> Result<StatusCode, AppError> {
977- // The writer lease of [`HOMEWORK_LOCK`] is [`service::homework_result::ungrade`]'s
978- // — removing the grade is what unfreezes the submission, so it must not
979- // straddle the read side's gate-through-write edits either.
979+ // Removing the grade is what unfreezes the submission; the un-grade's
980+ // transaction takes the homework row's lock, so it cannot straddle a
981+ // student-side write either.
980982 let (homework, course) = homework_with_course(&id, &st.db).await?;
981983 if !can_manage_course(&course, &user) {
982984 return Err(AppError::Forbidden(
src/web/meals.rsmodified+9 -9
@@ -438,11 +438,11 @@ async fn add_dish(
438438 &req.tags,
439439 &service::settings::load(&st.db).await?.get_dietary_tags(),
440440 )?;
441- // The dish-cap gate and its [`MENU_LOCK`](crate::service::menu::MENU_LOCK)
442- // lease live in the service: count-then-write is write-skew, so the count
443- // and the insert have to be one step, and the menu is read *inside* the
444- // lock — read before it, a `DELETE /menus/{id}` running in the gap takes
445- // its cascade with it and this dish lands on a menu that no longer exists.
441+ // The dish-cap gate lives in the service: the cap is one guarded
442+ // statement now — the menu row is locked `FOR NO KEY UPDATE` inside the
443+ // dish write's own transaction and the insert carries the
444+ // `count(*) < cap` guard, so a dish can never land on a menu that no
445+ // longer exists, and two racing writers cannot overfill it either.
446446 let dish = service::menu::add_dish(
447447 &st.db,
448448 &MenuId::from_key(&id),
@@ -502,8 +502,8 @@ async fn update_dish(
502502 )?),
503503 None => None,
504504 };
505- // The dish write holds [`MENU_LOCK`](crate::service::menu::MENU_LOCK)
506- // inside the service, like every dish write — see `add_dish`.
505+ // The dish write locks the menu row inside its own transaction — see
506+ // `add_dish`.
507507 let updated = service::menu::update_dish(&st.db, dish, name, description, price, tags).await?;
508508 let viewer_tags = service::dietary_profile::tags_of(&st.db, user.get_id()).await?;
509509 Ok(Json(DishResponse::new(&updated, &viewer_tags)))
@@ -531,8 +531,8 @@ async fn delete_dish(
531531 let dish = service::menu::read_dish(&st.db, &MenuDishId::from_key(&did))
532532 .await?
533533 .ok_or(AppError::NotFound)?;
534- // The dish write holds [`MENU_LOCK`](crate::service::menu::MENU_LOCK)
535- // inside the service, like every dish write — see `add_dish`.
534+ // The dish write locks the menu row inside its own transaction — see
535+ // `add_dish`.
536536 service::menu::delete_dish(&st.db, dish).await?;
537537 Ok(StatusCode::NO_CONTENT)
538538 }
src/web/questions.rsmodified+2 -2
@@ -482,7 +482,7 @@ async fn upload_image(
482482 let upload = read_image_upload(&st, &mut multipart).await?;
483483 let size = upload.size();
484484
485- let file = ulid::Ulid::generate().to_string();
485+ let file = crate::domain::monotonic_id::next_uuid().to_string();
486486 store_blob(&st, &file, &upload.data, || async {
487487 match pool_question::set_image(&st.db, question.get_id(), &file, &upload.content_type, size)
488488 .await?
@@ -808,7 +808,7 @@ async fn upload_solution_image(
808808 let upload = read_image_upload(&st, &mut multipart).await?;
809809 let size = upload.size();
810810
811- let file = ulid::Ulid::generate().to_string();
811+ let file = crate::domain::monotonic_id::next_uuid().to_string();
812812 store_blob(&st, &file, &upload.data, || async {
813813 match solution::set_image(&st.db, solution.get_id(), &file, &upload.content_type, size)
814814 .await?