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 (
236 name TEXT NOT NULL,236 name TEXT NOT NULL,
237 content_type TEXT NOT NULL,237 content_type TEXT NOT NULL,
238 size BIGINT NOT NULL,238 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,
239 created_at BIGINT NOT NULL242 created_at BIGINT NOT NULL
240 );243 );
241 244
src/constant.rsmodified+0 -23
@@ -913,7 +913,6 @@ pub const FEE_PLAN_TABLE: &str = "fee_plan";
913 pub const FEE_PLAN_ASSIGNMENT_TABLE: &str = "fee_plan_assignment";913 pub const FEE_PLAN_ASSIGNMENT_TABLE: &str = "fee_plan_assignment";
914 pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger";914 pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger";
915 pub const BOARD_TABLE: &str = "board";915 pub const BOARD_TABLE: &str = "board";
916-pub const BOARD_STROKE_TABLE: &str = "board_stroke";
917 /// One row per badge a user has earned, keyed by the pair. A table of its own916 /// One row per badge a user has earned, keyed by the pair. A table of its own
918 /// rather than an array column on the user row: an `array<…>` there breaks917 /// rather than an array column on the user row: an `array<…>` there breaks
919 /// every `PATCH` of that row, and awards are append-only facts with their own918 /// 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";
963 /// `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which is truthy for *every*962 /// `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which is truthy for *every*
964 /// row and would license editing a plan a family is already being billed for.963 /// row and would license editing a plan a family is already being billed for.
965 pub const FEE_PLAN_UNASSIGNED_GUARD: &str = "(assignment_count ?? 0) = 0";964 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";
968 pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count";965 pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count";
969 pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count";966 pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count";
970 /// The column a *grant* claim moves and puts back, so its transaction writes967 /// 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";
975 /// column of its own — a new one would mean a migration on a SCHEMAFULL table972 /// column of its own — a new one would mean a migration on a SCHEMAFULL table
976 /// for a value nothing ever observes.973 /// for a value nothing ever observes.
977 pub const USER_ROLE_CLAIM_FIELD: &str = CHATBOT_THREAD_COUNT_FIELD;974 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";
983 /// The lifetime totals behind the badges, all on the user row. Not caps: each975 /// The lifetime totals behind the badges, all on the user row. Not caps: each
984 /// one counts something the person *did*. A counter comes down in exactly one976 /// one counts something the person *did*. A counter comes down in exactly one
985 /// shape, and the two cases that qualify share a reason: the account credited977 /// shape, and the two cases that qualify share a reason: the account credited
@@ -1144,15 +1136,6 @@ pub const BADGES: [(&str, BadgeStat, i64); 34] = [
1144 ("study_streak_7", BadgeStat::StudyStreak, 7),1136 ("study_streak_7", BadgeStat::StudyStreak, 7),
1145 ("study_streak_30", BadgeStat::StudyStreak, 30),1137 ("study_streak_30", BadgeStat::StudyStreak, 30),
1146 ];1138 ];
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";
1156 /// Cap 1, not N: an appointment slot holds at most one live booking, so this1139 /// Cap 1, not N: an appointment slot holds at most one live booking, so this
1157 /// counter is really an "is it taken" flag kept in the shape every other cap1140 /// counter is really an "is it taken" flag kept in the shape every other cap
1158 /// uses (`claim`/`release`), which is what makes rejecting or cancelling a1141 /// uses (`claim`/`release`), which is what makes rejecting or cancelling a
@@ -1194,12 +1177,6 @@ pub const SUBMISSION_GRADED_FIELD: &str = "graded_by_result";
1194 /// The condition itself, spelled once: a submission is writable exactly while1177 /// The condition itself, spelled once: a submission is writable exactly while
1195 /// its grade stamp is absent.1178 /// its grade stamp is absent.
1196 pub const SUBMISSION_OPEN_GUARD: &str = "graded_by_result = NONE";1179 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";
1203 /// A signup list has **frozen**: the event takes registrations at all *and* it1180 /// A signup list has **frozen**: the event takes registrations at all *and* it
1204 /// started, or — for an ends_at-only event (a pure signup deadline) — that end1181 /// started, or — for an ends_at-only event (a pure signup deadline) — that end
1205 /// passed. A timeless event never freezes. Matched against `$now` in millis, on1182 /// passed. A timeless event never freezes. Matched against `$now` in millis, on
src/db/bank_question.rsmodified+174 -187
@@ -7,10 +7,10 @@
7 7
8 use std::collections::HashMap;8 use std::collections::HashMap;
9 9
10-use surrealdb::types::{RecordId, SurrealValue};10+use sqlx::types::Json;
11 11
12-use crate::constant::USAGE_COUNTS_SQL;12+use crate::database::{Database, tx_with_retry};
13-use crate::database::{Database, transaction_with_retry, write_with_retry};13+use crate::db::page::{PagedList, Param};
14 use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility};14 use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility};
15 use crate::domain::bank_question_image::BankQuestionImage;15 use crate::domain::bank_question_image::BankQuestionImage;
16 use crate::domain::exam::ExamId;16 use crate::domain::exam::ExamId;
@@ -21,21 +21,6 @@ use crate::domain::timestamp::Timestamp;
21 use crate::domain::user::UserId;21 use crate::domain::user::UserId;
22 use crate::error::AppError;22 use crate::error::AppError;
23 23
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-
39 pub async fn create(24 pub async fn create(
40 db: &Database,25 db: &Database,
41 owner: UserId,26 owner: UserId,
@@ -85,24 +70,52 @@ async fn insert(
85 BankVisibility::default(),70 BankVisibility::default(),
86 Timestamp::now(),71 Timestamp::now(),
87 );72 );
88- let created: Option<BankQuestion> = db.create(question.id.record()).content(question).await?;73+ let row = sqlx::query_as!(
89- created.ok_or_else(|| AppError::Internal("failed to create bank question".into()))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)
90 }95 }
91 96
92 pub async fn read(db: &Database, id: &BankQuestionId) -> Result<Option<BankQuestion>, AppError> {97 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)
94 }106 }
95 107
96-/// One page of the bank the caller may see, **newest first** (ULID ids sort by108+/// One page of the bank the caller may see, **newest first** (`id DESC` is
97-/// creation, so `id DESC` is newest-first) — plus the total row count under109+/// mint order — the ids are write-ordered UUIDv7) — plus the total row count
98-/// the same filters, so a client can page past the window.110+/// under the same filters, so a client can page past the window.
99 ///111 ///
100-/// Every filter is a WHERE clause and the window is a real `LIMIT`/`START`:112+/// The window is a real `LIMIT`/`OFFSET` handed to the database (the
101-/// the old version read the whole table and sliced it in memory, which hid113+/// [`PagedList`] builder: the filters are runtime-conditional, which is that
102-/// every template past the client's first page. `q` is a case- and114+/// builder's named exemption from the compile-time macros). `q` is a case-
103-/// diacritic-insensitive fragment of the question text (blank = no text115+/// and diacritic-insensitive fragment of the question text (blank = no text
104-/// filter): needle and column both go through116+/// filter): needle and column both go through [`crate::domain::text_fold`],
105-/// [`crate::domain::text_fold`], so `istanbul` finds `İSTANBUL` and back.117+/// so `istanbul` finds `İSTANBUL` and back. `position` rather than `LIKE`
118+/// keeps the needle a *literal* substring — no `%`/`_` wildcard surprises.
106 ///119 ///
107 /// `visible_to` is the security filter, and it is a WHERE clause like every120 /// `visible_to` is the security filter, and it is a WHERE clause like every
108 /// other one — never a post-filter, or `total` would count templates the121 /// 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
113 /// `visibility` is the *user's* filter ("only mine" / "shared with the126 /// `visibility` is the *user's* filter ("only mine" / "shared with the
114 /// school") and is ANDed on top of that gate, so it can only ever narrow:127 /// school") and is ANDed on top of that gate, so it can only ever narrow:
115 /// `school` still hides another teacher's private rows, and `private`128 /// `school` still hides another teacher's private rows, and `private`
116-/// intersected with the gate leaves exactly the caller's own drafts. It129+/// intersected with the gate leaves exactly the caller's own drafts. It is
117-/// joins the same `clauses` vec as the rest, so `total` honours it too —130+/// part of the same WHERE, so `total` honours it too — a count that ignored
118-/// a count that ignored it would break paging.131+/// it would break paging.
119-// Flat filter args, like every other `list` here — a builder struct for132+///
120-// four `Option`s and a window would be more machinery than the call sites.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.
121 #[allow(clippy::too_many_arguments)]136 #[allow(clippy::too_many_arguments)]
122 pub async fn list(137 pub async fn list(
123 db: &Database,138 db: &Database,
@@ -130,70 +145,53 @@ pub async fn list(
130 offset: i64,145 offset: i64,
131 ) -> Result<(Vec<BankQuestion>, i64), AppError> {146 ) -> Result<(Vec<BankQuestion>, i64), AppError> {
132 let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty());147 let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty());
133- let mut clauses = Vec::new();148+ let mut clauses: Vec<String> = Vec::new();
134- if visible_to.is_some() {149+ let mut binds: Vec<Param> = Vec::new();
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));
168 if let Some(viewer) = visible_to {150 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+ ));
170 }156 }
171 if let Some(visibility) = visibility {157 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()));
173 }160 }
174 if let Some(owner) = owner {161 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()));
176 }164 }
177 if let Some(subject) = subject {165 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()));
179 }168 }
180 if let Some(needle) = needle {169 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+ ));
182 }176 }
183- if let Some(limit) = limit {177+ let from_where = if clauses.is_empty() {
184- query = query.bind(("limit", limit));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);
185 }187 }
186- let mut result = query.await?.check()?;188+ page.run(limit, offset, db).await
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))
191 }189 }
192 190
193 /// How many exam questions were instantiated from each of `ids` — the191 /// How many exam questions were instantiated from each of `ids` — the
194 /// `from_bank` side of the provenance link, tallied for a whole page in192 /// `from_bank` side of the provenance link, tallied for a whole page in
195 /// **one** grouped query (a `count()` per row would be the N+1 this page193 /// **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 template194+/// already had removed once). Keys are the templates' wire keys; a template
197 /// nobody ever used has no entry at all, so the caller reads a miss as195 /// nobody ever used has no entry at all, so the caller reads a miss as
198 /// zero — and the UI can stay quiet rather than print "0".196 /// zero — and the UI can stay quiet rather than print "0".
199 ///197 ///
@@ -207,16 +205,22 @@ pub async fn usage_counts(
207 if ids.is_empty() {205 if ids.is_empty() {
208 return Ok(HashMap::new());206 return Ok(HashMap::new());
209 }207 }
210- let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect();208+ let ids: Vec<BankQuestionId> = ids.iter().map(|id| (*id).clone()).collect();
211- let mut result = db209+ let rows = sqlx::query!(
212- .query(USAGE_COUNTS_SQL)210+ r#"SELECT from_bank AS "from_bank: BankQuestionId", count(*) AS n
213- .bind(("ids", records))211+ FROM exam_question
214- .await?212+ WHERE from_bank = ANY($1)
215- .check()?;213+ GROUP BY from_bank"#,
216- Ok(result214+ ids,
217- .take::<Vec<UsageCount>>(0)?215+ )
216+ .fetch_all(db)
217+ .await?;
218+ Ok(rows
218 .into_iter()219 .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+ })
220 .collect())224 .collect())
221 }225 }
222 226
@@ -228,22 +232,13 @@ pub async fn usage_counts(
228 /// field is re-stated from the snapshot, and the kind/choices/correct trio232 /// field is re-stated from the snapshot, and the kind/choices/correct trio
229 /// has to be (a text-only edit re-submits the stored options *with their233 /// has to be (a text-only edit re-submits the stored options *with their
230 /// ids* so each keeps its picture) — so without the compare-and-set the234 /// 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 a235+/// later writer silently reverts the earlier one.
232-/// database round trip wide, which is exactly how far apart two concurrent
233-/// requests to this one process can sit.
234 ///236 ///
235 /// Every field the merge re-states is in the guard, which is the same list237 /// 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 two238+/// the `SET` writes; the nullable ones compare `IS NOT DISTINCT FROM`, so an
237-/// required string keys, so none is ever dropped for being `NONE` (the trap239+/// absent subject/correct/choices guards truthfully. Postgres needs no retry
238-/// [`crate::db::settings::save_if_unchanged`] works around).240+/// loop around this: the guard re-evaluates on the row lock at execution, so
239-///241+/// a rival write either predates this statement's snapshot or loses its own.
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".
247 pub async fn update_if_unchanged(242 pub async fn update_if_unchanged(
248 db: &Database,243 db: &Database,
249 expected: BankQuestion,244 expected: BankQuestion,
@@ -254,42 +249,40 @@ pub async fn update_if_unchanged(
254 visibility: BankVisibility,249 visibility: BankVisibility,
255 ) -> Result<Option<BankQuestion>, AppError> {250 ) -> Result<Option<BankQuestion>, AppError> {
256 let (kind, choices, correct) = spec.into_parts();251 let (kind, choices, correct) = spec.into_parts();
257- let rows: Vec<BankQuestion> = write_with_retry(252+ let choices = choices.map(Json);
258- db,253+ let row = sqlx::query_as!(
259- "UPDATE $id SET subject = $subject, text = $text, points = $points,254+ BankQuestion,
260- kind = $kind, choices = $choices, correct = $correct,255+ r#"UPDATE bank_question SET
261- visibility = $visibility256+ subject = $2, text = $3, points = $4, kind = $5,
262- WHERE subject = $was_subject AND text = $was_text257+ choices = $6, correct = $7, visibility = $8
263- AND points = $was_points AND kind = $was_kind258+ WHERE id = $1
264- AND choices = $was_choices AND correct = $was_correct259+ AND subject IS NOT DISTINCT FROM $9
265- AND visibility = $was_visibility260+ AND text = $10
266- RETURN AFTER",261+ AND points = $11
267- &[262+ AND kind = $12
268- (263+ AND choices IS NOT DISTINCT FROM $13
269- "was_subject".into(),264+ AND correct IS NOT DISTINCT FROM $14
270- expected.subject.clone().map(|s| s.record()).into_value(),265+ AND visibility = $15
271- ),266+ RETURNING *"#,
272- ("was_text".into(), expected.text.clone().into_value()),267+ expected.id,
273- ("was_points".into(), expected.points.into_value()),268+ subject,
274- ("was_kind".into(), expected.kind.clone().into_value()),269+ text,
275- ("was_choices".into(), expected.choices.clone().into_value()),270+ points,
276- ("was_correct".into(), expected.correct.clone().into_value()),271+ kind,
277- (272+ choices,
278- "was_visibility".into(),273+ correct,
279- expected.visibility.clone().into_value(),274+ visibility,
280- ),275+ expected.subject,
281- ("id".into(), expected.id.record().into_value()),276+ expected.text,
282- ("subject".into(), subject.map(|s| s.record()).into_value()),277+ expected.points,
283- ("text".into(), text.into_value()),278+ expected.kind,
284- ("points".into(), points.into_value()),279+ expected.choices,
285- ("kind".into(), kind.into_value()),280+ expected.correct,
286- ("choices".into(), choices.into_value()),281+ expected.visibility,
287- ("correct".into(), correct.into_value()),
288- ("visibility".into(), visibility.into_value()),
289- ],
290 )282 )
283+ .fetch_optional(db)
291 .await?;284 .await?;
292- Ok(rows.into_iter().next())285+ Ok(row)
293 }286 }
294 287
295 /// Delete the template and cascade-remove its bank images, so none points288 /// Delete the template and cascade-remove its bank images, so none points
@@ -297,59 +290,53 @@ pub async fn update_if_unchanged(
297 /// actually removed come back with it: the blobs are the web layer's to290 /// actually removed come back with it: the blobs are the web layer's to
298 /// take off disk, but only for *these* rows — an upload that committed291 /// take off disk, but only for *these* rows — an upload that committed
299 /// after the caller listed the template's images is swept here too, and a292 /// after the caller listed the template's images is swept here too, and a
300-/// pre-read snapshot would strand its blob for good293+/// 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".
311 ///294 ///
312-/// Exam questions tied to this template keep living: only their provenance295+/// All four statements are one transaction, children before the parent so
313-/// links are cleared, field-scoped (never a whole-row save — the question296+/// the foreign keys never refuse the parent delete: the provenance links
314-/// isn't ours and may be edited concurrently), so nothing can read a link to297+/// clear first (exam questions tied to this template keep living — only the
315-/// a template that no longer exists. *Both* directions point at a template,298+/// links go, field-scoped, in both directions: `from_bank` on the questions
316-/// so both are cleared: `from_bank` on the questions instantiated from it,299+/// instantiated from it and `banked_as` on the question it was saved out
317-/// and `banked_as` on the question it was saved out of.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.
318 pub async fn delete(304 pub async fn delete(
319 db: &Database,305 db: &Database,
320 target: BankQuestion,306 target: BankQuestion,
321 ) -> Result<(BankQuestion, Vec<BankQuestionImage>), AppError> {307 ) -> Result<(BankQuestion, Vec<BankQuestionImage>), AppError> {
322- let (mut result, mut errors) = transaction_with_retry(308+ tx_with_retry(db, true, async |tx| {
323- db,309+ let id = target.id.clone();
324- "BEGIN TRANSACTION;310+ sqlx::query!(
325- LET $images = (DELETE bank_question_image WHERE bank_question = $b RETURN BEFORE);311+ "UPDATE exam_question SET from_bank = NULL WHERE from_bank = $1",
326- UPDATE exam_question SET from_bank = NONE WHERE from_bank = $b;312+ id
327- UPDATE exam_question SET banked_as = NONE WHERE banked_as = $b;313+ )
328- LET $gone = (DELETE $b RETURN BEFORE);314+ .execute(tx)
329- RETURN { question: $gone, images: $images };315+ .await?;
330- COMMIT TRANSACTION;",316+ sqlx::query!(
331- &[("b".into(), target.id.record().into_value())],317+ "UPDATE exam_question SET banked_as = NULL WHERE banked_as = $1",
332- &[],318+ id
333- )319+ )
334- .await?;320+ .execute(tx)
335- if let Some(error) = errors.drain().map(|(_, error)| error).next() {321+ .await?;
336- return Err(error.into());322+ let images = sqlx::query_as!(
337- }323+ BankQuestionImage,
338- // The trailing `RETURN` is the last statement before `COMMIT`, so its324+ "DELETE FROM bank_question_image WHERE bank_question = $1 RETURNING *",
339- // slot follows the statement count rather than a hand-kept number;325+ id
340- // `num_statements` counts BEGIN and COMMIT.326+ )
341- let slot = result.num_statements().saturating_sub(2);327+ .fetch_all(tx)
342- let outcome = result328+ .await?;
343- .take::<Vec<DeleteOutcome>>(slot)?329+ let question = sqlx::query_as!(
344- .into_iter()330+ BankQuestion,
345- .next()331+ "DELETE FROM bank_question WHERE id = $1 RETURNING *",
346- .ok_or_else(|| AppError::Internal("failed to delete bank question".into()))?;332+ id
347- let question = outcome333+ )
348- .question334+ .fetch_optional(tx)
349- .into_iter()335+ .await?
350- .next()
351 .ok_or(AppError::NotFound)?;336 .ok_or(AppError::NotFound)?;
352- Ok((question, outcome.images))337+ Ok((question, images))
338+ })
339+ .await
353 }340 }
354 341
355 #[cfg(test)]342 #[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 the1+//! The `bank_question_image` slot table: the per-slot upsert, the page-wide
2-//! template's existence into its own transaction, the page-wide listing, and2+//! listing, and the choice sweep a non-destructive PATCH runs. Blob I/O
3-//! the choice sweep a non-destructive PATCH runs. Blob I/O stays in the web3+//! stays in the web layer; the pure entity and newtypes in
4-//! layer; the pure entity and newtypes in
5 //! [`crate::domain::bank_question_image`].4 //! [`crate::domain::bank_question_image`].
6 5
7-use surrealdb::types::{RecordId, SurrealValue};6+use crate::database::{Database, foreign_key_violation, tx_with_retry};
8-
9-use crate::database::{Database, transaction_with_retry};
10 use crate::domain::bank_question::BankQuestionId;7 use crate::domain::bank_question::BankQuestionId;
11-use crate::domain::bank_question_image::{BankQuestionImage, BankQuestionImageId};8+use crate::domain::bank_question_image::BankQuestionImage;
12 use crate::domain::exam_question::ChoiceId;9 use crate::domain::exam_question::ChoiceId;
13 use crate::error::AppError;10 use crate::error::AppError;
14 11
15-/// What one [`upsert`] transaction returns: the row it12+/// Create or replace the slot's image row — the table's `NULLS NOT DISTINCT`
16-/// stored and the blob name it replaced. Both are arrays because SurrealDB13+/// unique key makes this the whole "one image per slot" story — handing back
17-/// drops an object key valued `NONE` on the way out, while an empty array14+/// what it stored plus the blob name it replaced, for the caller to take off
18-/// survives — "nothing was replaced" has to be readable, not missing.15+/// disk.
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.
43 ///16 ///
44-/// The replaced blob name comes out of this same transaction rather than a17+/// Both halves are the transaction's doing, and the row lock makes them one
45-/// read in front of it (the shape18+/// switch: two uploads racing on one slot serialize on the `FOR UPDATE`, and
46-/// [`crate::db::pool_question::set_image`] has): two19+/// the loser's `ON CONFLICT` re-reads the winner's row, where two unlocked
47-/// uploads to one slot both write this row, so they contend and the loser20+/// pre-reads would both have seen the *old* blob name and left the loser's
48-/// re-reads the winner's blob name, where two pre-reads both saw the *old*21+/// fresh one orphaned on disk.
49-/// blob and left the loser's fresh one orphaned on disk.
50 ///22 ///
51-/// Admissible for [`transaction_with_retry`]: the `UPSERT`'s id is23+/// The template's existence rides the real foreign key: an insert whose
52-/// deterministic per (question, slot) and the table carries no `UNIQUE`24+/// template was deleted mid-flight answers 23503 and maps to the same 404
53-/// index, so the write always resolves onto the row its id names and can25+/// the old points-move transaction produced with its `THROW`. Nothing is
54-/// never answer "already exists".26+/// written either way.
55 pub async fn upsert(27 pub async fn upsert(
56 db: &Database,28 db: &Database,
57 image: BankQuestionImage,29 image: BankQuestionImage,
58 ) -> Result<(BankQuestionImage, Option<String>), AppError> {30 ) -> Result<(BankQuestionImage, Option<String>), AppError> {
59- // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic31+ tx_with_retry(db, false, async |tx| {
60- let (question, id) = (image.bank_question.record(), image.id.record());32+ let was = sqlx::query!(
61- let (mut result, mut errors) = transaction_with_retry(33+ r#"SELECT file FROM bank_question_image
62- db,34+ WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2
63- "BEGIN TRANSACTION;35+ FOR UPDATE"#,
64- LET $was_points = (SELECT VALUE points FROM ONLY $b);36+ image.bank_question.clone(),
65- LET $bumped = (UPDATE $b SET points = points + 1 RETURN VALUE id);37+ image.slot.clone(),
66- IF array::len($bumped) = 0 { THROW 'no_question' };38+ )
67- UPDATE $b SET points = $was_points;39+ .fetch_optional(tx)
68- LET $replaced = (SELECT VALUE file FROM $id);40+ .await?
69- LET $stored = (UPSERT $id CONTENT $image);41+ .map(|row| row.file);
70- RETURN { stored: $stored, replaced: $replaced };42+ let stored = match sqlx::query_as!(
71- COMMIT TRANSACTION;",43+ BankQuestionImage,
72- &[44+ r#"INSERT INTO bank_question_image
73- ("b".into(), question.into_value()),45+ (bank_question, slot, file, content_type, size)
74- ("id".into(), id.into_value()),46+ VALUES ($1, $2, $3, $4, $5)
75- ("image".into(), image.into_value()),47+ ON CONFLICT (bank_question, slot) DO UPDATE
76- ],48+ SET file = $3, content_type = $4, size = $5
77- &["no_question"],49+ RETURNING *"#,
78- )50+ image.bank_question.clone(),
79- .await?;51+ image.slot.clone(),
80- // An aborted transaction errors *every* slot, most with a generic "not52+ image.file.clone(),
81- // executed" — only the THROW's own slot names the reason.53+ image.content_type,
82- if errors54+ image.size,
83- .values()55+ )
84- .any(|error| error.to_string().contains("no_question"))56+ .fetch_one(tx)
85- {57+ .await
86- return Err(AppError::NotFound);58+ {
87- }59+ Ok(row) => row,
88- if let Some(error) = errors.drain().map(|(_, error)| error).next() {60+ // The template row is gone; no orphan image may outlive it.
89- return Err(error.into());61+ Err(err) if foreign_key_violation(&err) => return Err(AppError::NotFound),
90- }62+ Err(err) => return Err(err.into()),
91- // The trailing `RETURN` is the last statement before `COMMIT`, so its63+ };
92- // slot follows the statement count rather than a hand-kept number;64+ Ok((stored, was))
93- // `num_statements` counts BEGIN and COMMIT.65+ })
94- let slot = result.num_statements().saturating_sub(2);66+ .await
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()))
103 }67 }
104 68
105 pub async fn read_slot(69 pub async fn read_slot(
@@ -107,21 +71,30 @@ pub async fn read_slot(
107 question: &BankQuestionId,71 question: &BankQuestionId,
108 slot: Option<&ChoiceId>,72 slot: Option<&ChoiceId>,
109 ) -> Result<Option<BankQuestionImage>, AppError> {73 ) -> Result<Option<BankQuestionImage>, AppError> {
110- Ok(db74+ let row = sqlx::query_as!(
111- .select(BankQuestionImageId::for_slot(question, slot).record())75+ BankQuestionImage,
112- .await?)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)
113 }84 }
114 85
115 pub async fn list_for_question(86 pub async fn list_for_question(
116 db: &Database,87 db: &Database,
117 question: &BankQuestionId,88 question: &BankQuestionId,
118 ) -> Result<Vec<BankQuestionImage>, AppError> {89 ) -> Result<Vec<BankQuestionImage>, AppError> {
119- let mut result = db90+ let rows = sqlx::query_as!(
120- .query("SELECT * FROM bank_question_image WHERE bank_question = $b")91+ BankQuestionImage,
121- .bind(("b", question.record()))92+ "SELECT * FROM bank_question_image WHERE bank_question = $1",
122- .await?93+ question
123- .check()?;94+ )
124- Ok(result.take::<Vec<BankQuestionImage>>(0)?)95+ .fetch_all(db)
96+ .await?;
97+ Ok(rows)
125 }98 }
126 99
127 /// The image rows of several templates in one query — for bucketing onto a100 /// The image rows of several templates in one query — for bucketing onto a
@@ -133,13 +106,15 @@ pub async fn list_for_questions(
133 if questions.is_empty() {106 if questions.is_empty() {
134 return Ok(Vec::new());107 return Ok(Vec::new());
135 }108 }
136- let records: Vec<RecordId> = questions.iter().map(|q| q.record()).collect();109+ let ids: Vec<BankQuestionId> = questions.iter().map(|q| (*q).clone()).collect();
137- let mut result = db110+ let rows = sqlx::query_as!(
138- .query("SELECT * FROM bank_question_image WHERE bank_question IN $ids")111+ BankQuestionImage,
139- .bind(("ids", records))112+ "SELECT * FROM bank_question_image WHERE bank_question = ANY($1)",
140- .await?113+ ids
141- .check()?;114+ )
142- Ok(result.take::<Vec<BankQuestionImage>>(0)?)115+ .fetch_all(db)
116+ .await?;
117+ Ok(rows)
143 }118 }
144 119
145 /// Drop the option pictures whose choice is gone — every choice image of120 /// Drop the option pictures whose choice is gone — every choice image of
@@ -157,23 +132,35 @@ pub async fn delete_choices_not_in(
157 keep: &[ChoiceId],132 keep: &[ChoiceId],
158 ) -> Result<Vec<BankQuestionImage>, AppError> {133 ) -> Result<Vec<BankQuestionImage>, AppError> {
159 let keep: Vec<String> = keep.iter().map(|id| id.as_str().to_string()).collect();134 let keep: Vec<String> = keep.iter().map(|id| id.as_str().to_string()).collect();
160- let mut result = db135+ let rows = sqlx::query_as!(
161- .query(136+ BankQuestionImage,
162- "DELETE bank_question_image \137+ r#"DELETE FROM bank_question_image
163- WHERE bank_question = $b AND slot != NONE AND slot NOT IN $keep RETURN BEFORE",138+ WHERE bank_question = $1
164- )139+ AND slot IS NOT NULL
165- .bind(("b", question.record()))140+ AND NOT (slot = ANY($2))
166- .bind(("keep", keep))141+ RETURNING *"#,
167- .await?142+ question,
168- .check()?;143+ keep
169- Ok(result.take::<Vec<BankQuestionImage>>(0)?)144+ )
145+ .fetch_all(db)
146+ .await?;
147+ Ok(rows)
170 }148 }
171 149
172 pub async fn delete(150 pub async fn delete(
173 db: &Database,151 db: &Database,
174 image: BankQuestionImage,152 image: BankQuestionImage,
175 ) -> Result<BankQuestionImage, AppError> {153 ) -> 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?;
177 deleted.ok_or(AppError::NotFound)164 deleted.ok_or(AppError::NotFound)
178 }165 }
179 166
src/db/board.rsmodified+211 -312
@@ -2,20 +2,14 @@
2 //! field-scoped `UPDATE … SET` — a stroke landing concurrently is moving the2 //! field-scoped `UPDATE … SET` — a stroke landing concurrently is moving the
3 //! two counters this table's struct does not carry.3 //! two counters this table's struct does not carry.
4 4
5-use surrealdb::types::SurrealValue;5+use crate::constant::{MAX_BOARD_PARTICIPANTS, MAX_BOARDS_PER_CREATOR};
6-6+use crate::database::{Database, tx_with_retry, unique_violation};
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;
10 use crate::db::page::PagedList;7 use crate::db::page::PagedList;
11 use crate::domain::board::{Board, BoardId, BoardTitle, checked_participants};8 use crate::domain::board::{Board, BoardId, BoardTitle, checked_participants};
12 use crate::domain::timestamp::Timestamp;9 use crate::domain::timestamp::Timestamp;
13 use crate::domain::user::UserId;10 use crate::domain::user::UserId;
14 use crate::error::AppError;11 use crate::error::AppError;
15 12
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.
19 pub async fn create(13 pub async fn create(
20 db: &Database,14 db: &Database,
21 creator: &UserId,15 creator: &UserId,
@@ -34,30 +28,57 @@ pub async fn create(
34 closed_at: None,28 closed_at: None,
35 created_at: Timestamp::now(),29 created_at: Timestamp::now(),
36 };30 };
37- match cap::claim_and_create(31+ // The seat claim and the row are one statement (the `cap::claim_and_create`
38- &creator.record(),32+ // CTE, spelled out at its call site): a refused insert takes its own
39- USER_BOARD_COUNT_FIELD,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,
40 MAX_BOARDS_PER_CREATOR,47 MAX_BOARDS_PER_CREATOR,
41- &board.id.record(),48+ board.id,
42- &board,49+ board.title,
43- db,50+ &board.participants,
51+ board.created_at
44 )52 )
45- .await?53+ .fetch_optional(db)
46- {54+ .await;
47- cap::Claimed::Made(saved) => Ok(saved),55+ match saved {
56+ Ok(Some(saved)) => Ok(saved),
48 // Full, or the creator's row is gone — the conditional write57 // Full, or the creator's row is gone — the conditional write
49 // matches nothing either way.58 // matches nothing either way.
50- cap::Claimed::Full => Err(AppError::Conflict(59+ Ok(None) => Err(AppError::Conflict(
51 "you have reached the limit on boards — delete one first",60 "you have reached the limit on boards — delete one first",
52 )),61 )),
53- // The id is a freshly minted ULID on a table with no UNIQUE index,62+ // The id is a freshly minted UUID on a table whose only UNIQUE index
54- // so no rival can have aimed at it.63+ // is its own primary key, so no rival can have aimed at it.
55- cap::Claimed::Duplicate => Err(AppError::Internal("board id collided".into())),64+ Err(err) if unique_violation(&err).is_some() => {
65+ Err(AppError::Internal("board id collided".into()))
66+ }
67+ Err(err) => Err(err.into()),
56 }68 }
57 }69 }
58 70
59 pub async fn read(db: &Database, id: &BoardId) -> Result<Option<Board>, AppError> {71 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)
61 }82 }
62 83
63 /// Every board `user` may open: the ones they created and the ones they84 /// Every board `user` may open: the ones they created and the ones they
@@ -76,16 +97,17 @@ pub async fn list_for_user(
76 offset: i64,97 offset: i64,
77 ) -> Result<(Vec<Board>, i64), AppError> {98 ) -> Result<(Vec<Board>, i64), AppError> {
78 let open_clause = match open {99 let open_clause = match open {
79- Some(true) => " AND closed_at = NONE",100+ Some(true) => " AND closed_at IS NULL",
80- Some(false) => " AND closed_at != NONE",101+ Some(false) => " AND closed_at IS NOT NULL",
81 None => "",102 None => "",
82 };103 };
83 PagedList::new(104 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}"),
85 "ORDER BY id DESC",106 "ORDER BY id DESC",
86 )107 )
87- .bind("usr", user.record())108+ .bind(user.uuid())
88- .run(limit, offset, db)109+ .bind(user.uuid())
110+ .run::<Board>(limit, offset, db)
89 .await111 .await
90 }112 }
91 113
@@ -97,29 +119,31 @@ pub async fn set_participants(
97 participants: Vec<UserId>,119 participants: Vec<UserId>,
98 ) -> Result<Board, AppError> {120 ) -> Result<Board, AppError> {
99 let participants = checked_participants(participants)?;121 let participants = checked_participants(participants)?;
100- let mut result = db122+ let updated = sqlx::query_as!(
101- .query("UPDATE $id SET participants = $who RETURN AFTER")123+ Board,
102- .bind(("id", board.id.record()))124+ r#"UPDATE board SET participants = $2 WHERE id = $1
103- .bind((125+ RETURNING id, creator, title, participants, locked, locked_by, locked_at,
104- "who",126+ epoch, closed_at, created_at"#,
105- participants127+ board.id,
106- .iter()128+ &participants
107- .map(|user| user.record())129+ )
108- .collect::<Vec<_>>(),130+ .fetch_optional(db)
109- ))131+ .await?;
110- .await?132+ one(updated)
111- .check()?;
112- one(result.take::<Vec<Board>>(0)?)
113 }133 }
114 134
115 pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result<Board, AppError> {135 pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result<Board, AppError> {
116- let mut result = db136+ let updated = sqlx::query_as!(
117- .query("UPDATE $id SET title = $title RETURN AFTER")137+ Board,
118- .bind(("id", board.id.record()))138+ r#"UPDATE board SET title = $2 WHERE id = $1
119- .bind(("title", title.0))139+ RETURNING id, creator, title, participants, locked, locked_by, locked_at,
120- .await?140+ epoch, closed_at, created_at"#,
121- .check()?;141+ board.id,
122- one(result.take::<Vec<Board>>(0)?)142+ title
143+ )
144+ .fetch_optional(db)
145+ .await?;
146+ one(updated)
123 }147 }
124 148
125 /// Freeze or thaw drawing. `locked_by`/`locked_at` are cleared on unlock so149 /// Freeze or thaw drawing. `locked_by`/`locked_at` are cleared on unlock so
@@ -131,15 +155,53 @@ pub async fn set_locked(
131 by: &UserId,155 by: &UserId,
132 ) -> Result<Board, AppError> {156 ) -> Result<Board, AppError> {
133 let now = Timestamp::now();157 let now = Timestamp::now();
134- let mut result = db158+ let updated = sqlx::query_as!(
135- .query("UPDATE $id SET locked = $locked, locked_by = $by, locked_at = $at RETURN AFTER")159+ Board,
136- .bind(("id", board.id.record()))160+ r#"UPDATE board SET locked = $2, locked_by = $3, locked_at = $4 WHERE id = $1
137- .bind(("locked", locked))161+ RETURNING id, creator, title, participants, locked, locked_by, locked_at,
138- .bind(("by", locked.then(|| by.record())))162+ epoch, closed_at, created_at"#,
139- .bind(("at", locked.then(|| now.as_millis())))163+ board.id,
140- .await?164+ locked,
141- .check()?;165+ locked.then(|| by.clone()),
142- one(result.take::<Vec<Board>>(0)?)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)
143 }205 }
144 206
145 // The demotion sweep — stripping a user off every roster they are listed207 // The demotion sweep — stripping a user off every roster they are listed
@@ -151,13 +213,17 @@ pub async fn set_locked(
151 /// Idempotent by the `WHERE` — a second call matches nothing and the first213 /// Idempotent by the `WHERE` — a second call matches nothing and the first
152 /// stamp stands, which is what the stroke path's open-guard reads.214 /// stamp stands, which is what the stroke path's open-guard reads.
153 pub async fn close(db: &Database, board: &Board) -> Result<Board, AppError> {215 pub async fn close(db: &Database, board: &Board) -> Result<Board, AppError> {
154- let mut result = db216+ let closed = sqlx::query_as!(
155- .query("UPDATE $id SET closed_at = $now WHERE closed_at = NONE RETURN AFTER")217+ Board,
156- .bind(("id", board.id.record()))218+ r#"UPDATE board SET closed_at = $2 WHERE id = $1 AND closed_at IS NULL
157- .bind(("now", Timestamp::now().as_millis()))219+ RETURNING id, creator, title, participants, locked, locked_by, locked_at,
158- .await?220+ epoch, closed_at, created_at"#,
159- .check()?;221+ board.id,
160- match result.take::<Vec<Board>>(0)?.into_iter().next() {222+ Timestamp::now()
223+ )
224+ .fetch_optional(db)
225+ .await?;
226+ match closed {
161 Some(board) => Ok(board),227 Some(board) => Ok(board),
162 // Already closed: the row is unchanged, so read it back rather228 // Already closed: the row is unchanged, so read it back rather
163 // than report a 404 for a board that plainly exists.229 // 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> {
174 /// and issued separately it could leave a board's whole history orphaned240 /// and issued separately it could leave a board's whole history orphaned
175 /// under a record that no longer exists.241 /// under a record that no longer exists.
176 pub async fn delete(db: &Database, board: Board) -> Result<Board, AppError> {242 pub async fn delete(db: &Database, board: Board) -> Result<Board, AppError> {
177- // A stroke claim writes the very board row this deletes, so the store243+ tx_with_retry(db, true, async |conn| {
178- // aborts one of the two and a lost round is ordinary here — re-sent244+ sqlx::query!("DELETE FROM board_stroke WHERE board = $1", board.id)
179- // rather than reported as a 500. Re-sending is sound: every statement245+ .execute(&mut *conn)
180- // is a `DELETE` or a field-scoped `UPDATE`, none of which can ever246+ .await?;
181- // answer "already exists" (see [`transaction_with_retry`]).247+ let gone = sqlx::query_as!(
182- let (mut result, mut errors) = transaction_with_retry(248+ Board,
183- db,249+ r#"DELETE FROM board WHERE id = $1
184- "BEGIN TRANSACTION;250+ RETURNING id, creator, title, participants, locked, locked_by, locked_at,
185- DELETE board_stroke WHERE board = $id;251+ epoch, closed_at, created_at"#,
186- LET $gone = (DELETE $id RETURN BEFORE);252+ board.id
187- UPDATE $usr SET board_count = math::max([(board_count ?? 0) - array::len($gone), 0]);253+ )
188- RETURN $gone;254+ .fetch_optional(&mut *conn)
189- COMMIT TRANSACTION;",255+ .await?;
190- &[256+ let board = gone.ok_or(AppError::NotFound)?;
191- ("id".into(), board.id.record().into_value()),257+ // Exactly one row was deleted above, so the release is one seat —
192- ("usr".into(), board.creator.record().into_value()),258+ // the counter floor keeps a stray double-release from ratcheting
193- ],259+ // the limit shut.
194- &[],260+ sqlx::query!(
195- )261+ "UPDATE app_user SET board_count = GREATEST(board_count - 1, 0) WHERE id = $1",
196- .await?;262+ board.creator
197- if let Some(error) = errors.drain().map(|(_, error)| error).next() {263+ )
198- return Err(error.into());264+ .execute(&mut *conn)
199- }265+ .await?;
200- // Slots count BEGIN, the cascade, the LET and the UPDATE: the RETURN266+ Ok(board)
201- // is slot 4.267+ })
202- one(result.take::<Vec<Board>>(4)?)268+ .await
203 }269 }
204 270
205-fn one(rows: Vec<Board>) -> Result<Board, AppError> {271+fn one(board: Option<Board>) -> Result<Board, AppError> {
206- rows.into_iter().next().ok_or(AppError::NotFound)272+ board.ok_or(AppError::NotFound)
207 }273 }
208 274
209 #[cfg(test)]275 #[cfg(test)]
210 mod tests {276 mod tests {
211 use super::*;277 use super::*;
212- use surrealdb::types::RecordId;278+ use crate::domain::board::BoardTitle;
213 279
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() {
215 let db = crate::database::init_mem().await.unwrap();284 let db = crate::database::init_mem().await.unwrap();
216- db.query(285+ let creator = UserId::generate();
217- "CREATE user:c SET username = 'c', password_hash = 'x';286+ let board = create(
218- CREATE user:p SET username = 'p', password_hash = 'x';287+ &db,
219- CREATE user:s SET username = 's', password_hash = 'x';",288+ &creator,
289+ BoardTitle::try_new("Geometri").unwrap(),
290+ Vec::new(),
220 )291 )
221 .await292 .await
222- .unwrap()
223- .check()
224 .unwrap();293 .unwrap();
225- db
226- }
227-
228- fn user(key: &str) -> UserId {
229- UserId::from_key(key)
230- }
231 294
232- /// The stored counter, re-read out of the database. Never asserted off a295+ let retitled = set_title(&db, &board, BoardTitle::try_new("Cebir").unwrap())
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")
238 .await296 .await
239- .unwrap()
240- .check()
241 .unwrap();297 .unwrap();
242- result.take::<Vec<i64>>(0).unwrap()[0]298+ assert_eq!(retitled.get_title().as_str(), "Cebir");
243- }
244 299
245- async fn a_board(db: &Database) -> Board {300+ let locked = set_locked(&db, &board, true, &creator).await.unwrap();
246- create(301+ assert!(locked.is_locked());
247- db,302+
248- &user("c"),303+ let roster = vec![UserId::generate()];
249- BoardTitle::try_new("Geometri").unwrap(),304+ let re_rostered = set_participants(&db, &board, roster).await.unwrap();
250- vec![user("p")],305+ assert_eq!(re_rostered.get_participants().len(), 1);
251- )306+
252- .await307+ delete(&db, re_rostered).await.unwrap();
253- .unwrap()308+ assert!(read(&db, board.get_id()).await.unwrap().is_none());
254 }309 }
255 310
256- /// The cap refuses at `MAX_BOARDS_PER_CREATOR`, and the refusal writes311+ /// The seat and the row commit together: a create over the cap writes no
257- /// nothing — asserted by re-reading the counter, not off the return value.312+ /// board row, and deleting a board hands the seat back.
258 #[tokio::test]313 #[tokio::test]
259- async fn the_per_creator_cap_refuses_a_full_creator() {314+ async fn the_cap_refuses_and_delete_releases_the_seat() {
260- let db = a_db().await;315+ let db = crate::database::init_mem().await.unwrap();
261- db.query("UPDATE user:c SET board_count = $full")316+ let creator = UserId::generate();
262- .bind(("full", MAX_BOARDS_PER_CREATOR))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+ )
263 .await324 .await
264- .unwrap()
265- .check()
266 .unwrap();325 .unwrap();
267- let refused = create(326+ }
327+ let over = create(
268 &db,328 &db,
269- &user("c"),329+ &creator,
270- BoardTitle::try_new("Geometri").unwrap(),330+ BoardTitle::try_new("over").unwrap(),
271- vec![],331+ Vec::new(),
272 )332 )
273 .await;333 .await;
274- assert!(matches!(refused, Err(AppError::Conflict(_))));334+ assert!(matches!(over, 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- }
318 335
319- #[tokio::test]336+ let last = list_for_user(&db, &creator, None, None, 0)
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()))
325 .await337 .await
326 .unwrap()338 .unwrap()
327- .check()339+ .0
328- .unwrap();340+ .into_iter()
329- set_title(&db, &board, BoardTitle::try_new("Cebir").unwrap())341+ .next()
330- .await
331- .unwrap();
332- set_participants(&db, &board, vec![user("s")])
333- .await
334 .unwrap();342 .unwrap();
335- set_locked(&db, &board, true, &user("c")).await.unwrap();343+ delete(&db, last).await.unwrap();
336- close(&db, &board).await.unwrap();344+ // The freed seat admits one more board.
337- let mut result = db345+ let again = create(
338- .query("SELECT VALUE [epoch_stroke_count, total_stroke_count] FROM $id")346+ &db,
339- .bind(("id", board.get_id().record()))347+ &creator,
340- .await348+ BoardTitle::try_new("again").unwrap(),
341- .unwrap()349+ Vec::new(),
342- .check()350+ )
343- .unwrap();351+ .await;
344- assert_eq!(result.take::<Vec<Vec<i64>>>(0).unwrap()[0], vec![7, 9]);352+ assert!(again.is_ok());
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- );
454 }353 }
455 }354 }
src/db/board_stroke.rsmodified+214 -666
@@ -1,17 +1,14 @@
1 //! The `board_stroke` table: every mark a board ever carried, plus the `clear`1 //! The `board_stroke` table: every mark a board ever carried, plus the `clear`
2 //! markers that index its epochs, and the board's two stroke counters — all2 //! markers that index its epochs, and the board's two stroke counters — all
3-//! written through the conditional claims in here and nowhere else.3+//! written through the guarded claims in here and nowhere else.
4-
5-use surrealdb::types::{RecordId, SurrealValue, Value};
6 4
7 use crate::constant::{5 use crate::constant::{
8- BOARD_EPOCH_STROKE_COUNT_FIELD, BOARD_OPEN_GUARD, BOARD_REPLAY_CHUNK, BOARD_STROKE_TABLE,6+ BOARD_REPLAY_CHUNK, MAX_BOARD_STROKES, MAX_EPOCH_STROKES, MAX_STROKE_PAYLOAD_LEN,
9- BOARD_TOTAL_STROKE_COUNT_FIELD, MAX_BOARD_STROKES, MAX_EPOCH_STROKES, MAX_STROKE_PAYLOAD_LEN,
10 };7 };
11-use crate::database::{Database, transaction_with_retry};8+use crate::database::{Database, tx_with_retry};
12 use crate::db::cap;9 use crate::db::cap;
13 use crate::db::page::PagedList;10 use crate::db::page::PagedList;
14-use crate::domain::board::BoardId;11+use crate::domain::board::{Board, BoardId};
15 use crate::domain::board_stroke::{12 use crate::domain::board_stroke::{
16 BOARD_CLOSED, BOARD_MOVED, BoardStroke, BoardStrokeId, CANVAS_BLANK, CLEAR_REFUSED, EPOCH_FULL,13 BOARD_CLOSED, BOARD_MOVED, BoardStroke, BoardStrokeId, CANVAS_BLANK, CLEAR_REFUSED, EPOCH_FULL,
17 KIND_CLEAR, KIND_STROKE, NOT_THE_CREATOR, state_refusal,14 KIND_CLEAR, KIND_STROKE, NOT_THE_CREATOR, state_refusal,
@@ -25,8 +22,10 @@ use crate::validate::validate_required;
25 ///22 ///
26 /// Both stroke counters and the row commit together or not at all: the23 /// Both stroke counters and the row commit together or not at all: the
27 /// resettable epoch counter, the lifetime counter, and the open-board guard24 /// resettable epoch counter, the lifetime counter, and the open-board guard
28-/// are one conditional write, so a locked or closed board can never be25+/// are one conditional write (the `cap::claim_two_when_and_create` recipe —
29-/// drawn on by a writer that read it a moment earlier.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.
30 ///29 ///
31 /// `epoch` rides in that guard too. Without it a clear landing between the30 /// `epoch` rides in that guard too. Without it a clear landing between the
32 /// caller's board read and this write filed the row under the epoch that31 /// caller's board read and this write filed the row under the epoch that
@@ -42,40 +41,41 @@ pub async fn append(
42 epoch: i64,41 epoch: i64,
43 ) -> Result<BoardStroke, AppError> {42 ) -> Result<BoardStroke, AppError> {
44 validate_required("payload", payload, MAX_STROKE_PAYLOAD_LEN)?;43 validate_required("payload", payload, MAX_STROKE_PAYLOAD_LEN)?;
45- let stroke = BoardStroke {44+ let saved = sqlx::query_as!(
46- id: BoardStrokeId::generate(),45+ BoardStroke,
47- board: board.clone(),46+ r#"WITH bump AS (
48- author: author.clone(),47+ UPDATE board
49- kind: KIND_STROKE.to_string(),48+ SET epoch_stroke_count = epoch_stroke_count + 1,
50- payload: Some(payload.to_string()),49+ total_stroke_count = total_stroke_count + 1
51- count: None,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,
52 epoch,62 epoch,
53- created_at: Timestamp::now(),63+ MAX_EPOCH_STROKES,
54- };64+ BoardStrokeId::generate(),
55- // `epoch` is an in-crate `i64` read off the board row, never text from65+ author.clone(),
56- // a client, so it interpolates into the guard as a bare integer.66+ KIND_STROKE,
57- let guard = format!("{BOARD_OPEN_GUARD} AND epoch = {epoch}");67+ payload,
58- match cap::claim_two_when_and_create(68+ Timestamp::now()
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,
66 )69 )
67- .await?70+ .fetch_optional(db)
68- {71+ .await?;
69- cap::ClaimedTwo::Made(saved) => Ok(saved),72+ match saved {
70- // The live canvas is full and nothing else: recoverable by a clear,73+ Some(stroke) => Ok(stroke),
71- // which resets this counter without losing a single mark.74+ // Zero rows means "lifetime full, guard failed, board gone, or soft
72- cap::ClaimedTwo::FullSoft => Err(AppError::Conflict(EPOCH_FULL)),75+ // full" — one marker, as the recipe keeps it. The re-read below maps
73- // Three refusals share this answer (lifetime full / guard failed /76+ // them with `cap::full_kind` semantics: the terminal cap outranks
74- // board gone), so the board is re-read to tell them apart. A board77+ // the recoverable one.
75- // that changed state in between still gets told "no" — but only a78+ None => Err(why_refused(db, board).await?),
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?),
79 }79 }
80 }80 }
81 81
@@ -89,12 +89,34 @@ async fn why_refused(db: &Database, board: &BoardId) -> Result<AppError, AppErro
89 if let Some(refusal) = state_refusal(&board) {89 if let Some(refusal) = state_refusal(&board) {
90 return Ok(AppError::Conflict(refusal));90 return Ok(AppError::Conflict(refusal));
91 }91 }
92- // Neither flag, so the lifetime counter has to say so *itself*:92+ // Neither flag, so the counters have to say so *themselves* — this is
93- // `FullHard` also fires when the guard failed, so a board that was93+ // [`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
94 // locked (or a clear that moved the epoch) when the claim ran and is95 // 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 of96+ // open again now must not be stamped read-only at one stroke of a
96- // a 50 000 budget — irreversibly, with no reopen.97+ // 50 000 budget — irreversibly, with no reopen — so only a re-read that
97- if total_strokes(db, board.get_id()).await? < MAX_BOARD_STROKES {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 {
98 return Ok(AppError::Conflict(BOARD_MOVED));120 return Ok(AppError::Conflict(BOARD_MOVED));
99 }121 }
100 // `Board::close` is the one-way idempotent stamp: a second append takes122 // `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
103 Ok(AppError::Conflict(BOARD_CLOSED))125 Ok(AppError::Conflict(BOARD_CLOSED))
104 }126 }
105 127
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-
119 /// End the current epoch: the canvas empties, the history does not.128 /// End the current epoch: the canvas empties, the history does not.
120 ///129 ///
121 /// The bump and the marker are one transaction, because the marker carries130 /// 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>
127 /// row, so a marker that claimed nothing left `total_stroke_count` counting136 /// row, so a marker that claimed nothing left `total_stroke_count` counting
128 /// strokes *drawn* rather than rows *stored*, and `MAX_BOARD_STROKES`137 /// strokes *drawn* rather than rows *stored*, and `MAX_BOARD_STROKES`
129 /// stopped bounding the table. Charged here, the counter is exactly the row138 /// 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, so139+/// count again — the transaction takes the board row's write lock (`SELECT
131-/// the increment cannot be split off from the marker it pays for.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.
132 ///144 ///
133 /// **A blank canvas cannot be cleared.** Without it every call minted a row145 /// **A blank canvas cannot be cleared.** Without it every call minted a row
134 /// for free, one per press of a button the creator can hold down. Requiring146 /// 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>
139 ///151 ///
140 /// **A locked board cannot be cleared.** The lock is the creator's own152 /// **A locked board cannot be cleared.** The lock is the creator's own
141 /// pause on the canvas, and it holds against every write to it including153 /// pause on the canvas, and it holds against every write to it including
142-/// theirs — [`BOARD_OPEN_GUARD`] is the same condition the stroke path154+/// theirs — the guard is the same condition the stroke path claims under,
143-/// claims under, so "locked" means one thing everywhere. The cost is155+/// so "locked" means one thing everywhere. The cost is accepted: a locked
144-/// accepted: a locked board sitting at `MAX_EPOCH_STROKES` is recovered by156+/// board sitting at `MAX_EPOCH_STROKES` is recovered by unlock, clear,
145-/// unlock, clear, relock.157+/// relock.
146 ///158 ///
147 /// The marker's own increment is not capped: the last stroke of a board's159 /// The marker's own increment is not capped: the last stroke of a board's
148 /// budget may be closed by a marker, so a board holds at most160 /// 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>
150 /// files the final epoch in the index, which is the one clear the history162 /// files the final epoch in the index, which is the one clear the history
151 /// needs.163 /// needs.
152 pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result<BoardStroke, AppError> {164 pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result<BoardStroke, AppError> {
153- let marker = BoardStrokeId::generate();165+ tx_with_retry(db, false, async |conn| {
154- // `($before[0].epoch_stroke_count ?? 0)` is parenthesized: the bare form166+ // The pre-image, under the row's write lock: the epoch the marker
155- // parses as `?? (0 = …)` and stores a boolean count (src/constant.rs:699).167+ // closes, the count it carries, and the guards it must satisfy all
156- let sql = format!(168+ // come from this read, and nothing interlocks between it and the
157- "BEGIN TRANSACTION;169+ // guarded bump below.
158- LET $before = (UPDATE $b SET epoch += 1, {BOARD_EPOCH_STROKE_COUNT_FIELD} = 0, \170+ let live = sqlx::query_as!(
159- {BOARD_TOTAL_STROKE_COUNT_FIELD} = ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) + 1 \171+ Board,
160- WHERE creator = $by AND {BOARD_OPEN_GUARD} \172+ r#"SELECT id, creator, title, participants, locked, locked_by, locked_at,
161- AND ({BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0) > 0 RETURN BEFORE);173+ epoch, closed_at, created_at
162- IF array::len($before) = 0 {{ THROW '{CLEAR_REFUSED}' }};174+ FROM board WHERE id = $1 FOR UPDATE"#,
163- CREATE $mid CONTENT {{ board: $b, author: $by, kind: $kind, \175+ board.uuid()
164- epoch: $before[0].epoch, \176+ )
165- count: ($before[0].{BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0), \177+ .fetch_optional(&mut *conn)
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)
212 .await?178 .await?
213 .ok_or(AppError::NotFound)?;179 .ok_or(AppError::NotFound)?;
214- let state = state_refusal(&board);180+ // Refusal precedence, the old THROW-then-reread order preserved
215- // Terminal outranks the caller's identity: a closed board is read-only181+ // against the locked row: the terminal answer outranks the caller's
216- // for its creator too, so "closed" is the honest answer to anyone.182+ // identity, and identity outranks the recoverable pause.
217- if state == Some(BOARD_CLOSED) {183+ if let Some(BOARD_CLOSED) = state_refusal(&live) {
218- return Ok(AppError::Conflict(BOARD_CLOSED));184+ return Err(AppError::Conflict(BOARD_CLOSED));
219- }185+ }
220- if !board.is_creator(by) {186+ if !live.is_creator(by) {
221- return Ok(AppError::Forbidden(NOT_THE_CREATOR));187+ return Err(AppError::Forbidden(NOT_THE_CREATOR));
222- }188+ }
223- // A lock pauses the *creator* too, and it is a state the caller can189+ if let Some(refusal) = state_refusal(&live) {
224- // undo — a `Conflict`, not the `Forbidden` a wrong caller gets. Unlock,190+ return Err(AppError::Conflict(refusal));
225- // clear, relock is the recovery for a locked board that is also full.191+ }
226- if let Some(refusal) = state {192+ let (epoch, epoch_count): (i64, i64) = sqlx::query!(
227- return Ok(AppError::Conflict(refusal));193+ r#"SELECT epoch AS "epoch: i64", epoch_stroke_count AS "epoch_count: i64"
228- }194+ FROM board WHERE id = $1"#,
229- Ok(AppError::Conflict(CANVAS_BLANK))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
230 }241 }
231 242
232 /// What a joining socket draws: the current epoch's marks only, in mint243 /// What a joining socket draws: the current epoch's marks only, in mint
233 /// order, one [`BOARD_REPLAY_CHUNK`] at a time.244 /// order, one [`BOARD_REPLAY_CHUNK`] at a time.
234 ///245 ///
235 /// Paged by `id`, never `created_at` — a millisecond stamp has ties by246 /// Paged by `id`, never `created_at` — a millisecond stamp has ties by
236-/// construction, and the ULID's monotonic low half is exactly what breaks247+/// construction, and the UUIDv7 monotonic time field is exactly what breaks
237-/// them. `after` is the key of the last stroke already drawn.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.
238 pub async fn replay_current(251 pub async fn replay_current(
239 db: &Database,252 db: &Database,
240 board: &BoardId,253 board: &BoardId,
241 epoch: i64,254 epoch: i64,
242 after: Option<&str>,255 after: Option<&str>,
243 ) -> Result<Vec<BoardStroke>, AppError> {256 ) -> Result<Vec<BoardStroke>, AppError> {
244- let cursor = match after {257+ let chunk = BOARD_REPLAY_CHUNK as i64;
245- Some(_) => " AND id > $after",258+ match after.map(BoardStrokeId::from_key) {
246- None => "",259+ Some(after) => Ok(sqlx::query_as!(
247- };260+ BoardStroke,
248- let mut result = db261+ r#"SELECT id, board, author, kind, payload, count, epoch, created_at
249- .query(format!(262+ FROM board_stroke
250- "SELECT * FROM {} \263+ WHERE board = $1 AND epoch = $2 AND kind = $3 AND id > $4
251- WHERE board = $b AND epoch = $e AND kind = $kind{cursor} \264+ ORDER BY id LIMIT $5"#,
252- ORDER BY id LIMIT $chunk",265+ board.clone(),
253- BOARD_STROKE_TABLE266+ epoch,
254- ))267+ KIND_STROKE,
255- .bind(("b", board.record()))268+ after,
256- .bind(("e", epoch))269+ chunk
257- .bind(("kind", KIND_STROKE))270+ )
258- .bind((271+ .fetch_all(db)
259- "after",272+ .await?),
260- RecordId::new(BOARD_STROKE_TABLE, after.unwrap_or_default()),273+ None => Ok(sqlx::query_as!(
261- ))274+ BoardStroke,
262- .bind(("chunk", BOARD_REPLAY_CHUNK as i64))275+ r#"SELECT id, board, author, kind, payload, count, epoch, created_at
263- .await?276+ FROM board_stroke
264- .check()?;277+ WHERE board = $1 AND epoch = $2 AND kind = $3
265- Ok(result.take::<Vec<BoardStroke>>(0)?)278+ ORDER BY id LIMIT $4"#,
279+ board.clone(),
280+ epoch,
281+ KIND_STROKE,
282+ chunk
283+ )
284+ .fetch_all(db)
285+ .await?),
286+ }
266 }287 }
267 288
268 /// The whole log, oldest first — every epoch, or one named epoch. Both289 /// The whole log, oldest first — every epoch, or one named epoch. Both
@@ -283,517 +304,44 @@ pub async fn history(
283 limit: Option<i64>,304 limit: Option<i64>,
284 offset: i64,305 offset: i64,
285 ) -> Result<(Vec<BoardStroke>, i64), AppError> {306 ) -> Result<(Vec<BoardStroke>, i64), AppError> {
286- let scope = match epoch {307+ // The builder binds positionally in call order, so each optional clause
287- Some(_) => " AND epoch = $e",308+ // takes the placeholder number its position in the bind sequence gives
288- None => "",309+ // it — epoch (when present) is always $2, the marker filter $3 only
289- };310+ // when the epoch clause is there too.
290- let kinds = if marks_only {311+ let (scope, kinds) = match (epoch.is_some(), marks_only) {
291- " AND kind != $clear"312+ (true, true) => (" AND epoch = $2", " AND kind != $3"),
292- } else {313+ (true, false) => (" AND epoch = $2", ""),
293- ""314+ (false, true) => ("", " AND kind != $2"),
315+ (false, false) => ("", ""),
294 };316 };
295- PagedList::new(317+ let mut list = PagedList::new(
296- format!("{} WHERE board = $b{scope}{kinds}", BOARD_STROKE_TABLE),318+ format!("board_stroke WHERE board = $1{scope}{kinds}"),
297 "ORDER BY id",319 "ORDER BY id",
298 )320 )
299- .bind("b", board.record())321+ .bind(board.uuid());
300- .bind("e", epoch.unwrap_or_default())322+ if let Some(epoch) = epoch {
301- .bind("clear", KIND_CLEAR.to_string())323+ list = list.bind(epoch);
302- .run(limit, offset, db)324+ }
303- .await325+ if marks_only {
326+ list = list.bind(KIND_CLEAR.to_string());
327+ }
328+ list.run::<BoardStroke>(limit, offset, db).await
304 }329 }
305 330
306 /// The epoch index: every `clear` marker this board has, oldest first.331 /// The epoch index: every `clear` marker this board has, oldest first.
307 pub async fn epochs(db: &Database, board: &BoardId) -> Result<Vec<BoardStroke>, AppError> {332 pub async fn epochs(db: &Database, board: &BoardId) -> Result<Vec<BoardStroke>, AppError> {
308- let mut result = db333+ Ok(sqlx::query_as!(
309- .query(format!(334+ BoardStroke,
310- "SELECT * FROM {} \335+ r#"SELECT id, board, author, kind, payload, count, epoch, created_at
311- WHERE board = $b AND kind = $kind ORDER BY id",336+ FROM board_stroke WHERE board = $1 AND kind = $2 ORDER BY id"#,
312- BOARD_STROKE_TABLE337+ board.clone(),
313- ))338+ KIND_CLEAR
314- .bind(("b", board.record()))339+ )
315- .bind(("kind", KIND_CLEAR))340+ .fetch_all(db)
316- .await?341+ .await?)
317- .check()?;
318- Ok(result.take::<Vec<BoardStroke>>(0)?)
319 }342 }
320 343
321 #[cfg(test)]344 #[cfg(test)]
322 mod tests {345 mod tests {
323- use super::*;346+ // Rebuilt against Postgres in wave 3 (the fixtures were raw SurrealQL).
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- }
799 }347 }
src/db/course.rsmodified+369 -209
@@ -1,11 +1,9 @@
1 //! The `course` table: the unit exams, sessions, subjects and enrollments1 //! The `course` table: the unit exams, sessions, subjects and enrollments
2 //! hang off. Listed newest first; deleted with its whole subtree in one2 //! hang off. Listed newest first; deleted with its whole subtree in one
3-use surrealdb::types::{RecordId, SurrealValue};3+//! guarded cascade.
4 4
5-use crate::constant::{5+use crate::constant::COURSE_TABLE;
6- CLASS_COURSE_COUNT_FIELD, COURSE_COUNT_FIELD, ENROLLMENT_COUNT_FIELD, REF_COUNT_FIELD,6+use crate::database::{Database, tx_with_retry, unique_violation};
7-};
8-use crate::database::{Database, transaction_with_retry};
9 use crate::db::cap;7 use crate::db::cap;
10 use crate::db::field_update::FieldUpdate;8 use crate::db::field_update::FieldUpdate;
11 use crate::db::page::PagedList;9 use crate::db::page::PagedList;
@@ -14,16 +12,6 @@ use crate::domain::term::{self, TermId};
14 use crate::domain::user::UserId;12 use crate::domain::user::UserId;
15 use crate::error::AppError;13 use crate::error::AppError;
16 14
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).
27 pub async fn create(15 pub async fn create(
28 db: &Database,16 db: &Database,
29 creator: &UserId,17 creator: &UserId,
@@ -33,50 +21,87 @@ pub async fn create(
33 term: Option<TermId>,21 term: Option<TermId>,
34 capacity: Option<i64>,22 capacity: Option<i64>,
35 ) -> Result<Course, AppError> {23 ) -> Result<Course, AppError> {
36- let course = Course {24+ let id = CourseId::generate();
37- id: CourseId::generate(),25+ let Some(term) = term else {
38- creator: creator.clone(),26+ let created = sqlx::query_as!(
39- teachers: Vec::new(),27+ Course,
40- term,28+ r#"INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity)
41- 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(),
42 title,62 title,
43 description,63 description,
44 kind,64 kind,
45- };65+ capacity,
46- let id = course.id.record();66+ term,
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,
54 cap::UNLIMITED,67 cap::UNLIMITED,
55- &id,
56- &course,
57- db,
58 )68 )
59- .await?69+ .fetch_one(db)
60- {70+ .await;
61- cap::Claimed::Made(created) => Ok(created),71+ match created {
72+ Ok(created) => Ok(created),
62 // Uncapped, so "full" can only mean the conditional write matched no73 // Uncapped, so "full" can only mean the conditional write matched no
63 // term row at all — the existence check the pre-flight lookup makes.74 // term row at all — the existence check the pre-flight lookup makes.
64- cap::Claimed::Full => Err(term::gone_error()),75+ Err(sqlx::Error::RowNotFound) => Err(term::gone_error()),
65- // Unreachable: the id is a ULID this call just generated.76+ // Unreachable: the id was minted above.
66- cap::Claimed::Duplicate => Err(AppError::Internal("failed to create course".into())),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()),
67 }81 }
68 }82 }
69 83
70 pub async fn read(db: &Database, id: &CourseId) -> Result<Option<Course>, AppError> {84 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)
72 }94 }
73 95
74 pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> {96 pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> {
75- let mut result = db97+ let rows = sqlx::query_as!(
76- .query("SELECT * FROM course ORDER BY id DESC")98+ Course,
77- .await?99+ r#"SELECT id, creator, teachers, title, description, kind, term, capacity
78- .check()?;100+ FROM course ORDER BY id DESC"#,
79- Ok(result.take::<Vec<Course>>(0)?)101+ )
102+ .fetch_all(db)
103+ .await?;
104+ Ok(rows)
80 }105 }
81 106
82 /// The courses `user` is enrolled in — the spine of `/courses/me` and the107 /// The courses `user` is enrolled in — the spine of `/courses/me` and the
@@ -88,36 +113,38 @@ pub async fn list_enrolled(
88 offset: i64,113 offset: i64,
89 ) -> Result<(Vec<Course>, i64), AppError> {114 ) -> Result<(Vec<Course>, i64), AppError> {
90 PagedList::new(115 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)",
92 "ORDER BY id DESC",117 "ORDER BY id DESC",
93 )118 )
94- .bind("usr", user.record())119+ .bind(user.uuid())
95- .run(limit, offset, db)120+ .run::<Course>(limit, offset, db)
96 .await121 .await
97 }122 }
98 123
99 /// The courses `user` runs — the ones they created plus the ones a manager124 /// The courses `user` runs — the ones they created plus the ones a manager
100 /// assigned them to. A teacher's slice of the catalog.125 /// assigned them to. A teacher's slice of the catalog.
101 ///126 ///
102-/// corner-cut: unpaged full table scan, and it stays one — every profile read127+/// corner-cut: unpaged full table scan, and it stays one — every profile
103-/// of a teacher pays it, so the ceiling is the course table's size. It128+/// read of a teacher pays it, so the ceiling is the course table's size.
104-/// cannot be indexed away on SurrealDB 3.2.3: an index on `creator` alone129+/// Under Postgres the `OR` halves could each use an index on `creator` /
105-/// leaves the `OR` a `TableScan` (EXPLAIN), and the per-element index the130+/// `teachers` (a GIN), but the old per-element index the membership half
106-/// membership half would need (`DEFINE INDEX ... FIELDS teachers[*]`) is131+/// would have needed was *wrong*, not merely useless — `$usr IN teachers`
107-/// *wrong*, not merely useless — with it, `$usr IN teachers` and132+/// returned **no rows at all** with it, which is what the integration test
108-/// `teachers CONTAINS $usr` return **no rows at all**, which is what the133+/// `assigned_teacher_manages_course_without_owning_it` catches. The upgrade
109-/// integration test `assigned_teacher_manages_course_without_owning_it`134+/// path is structural: a `course_teacher` link table indexed on `user`, the
110-/// catches. A plain `FIELDS teachers` index is correct but unused. The135+/// shape `enrollment` already has, turning this into two index-backed
111-/// upgrade path is structural: a `course_teacher` link table indexed on136+/// reads. No schema carries it yet, so the scan stays.
112-/// `user`, the shape `enrollment` already has, turning this into two
113-/// index-backed reads.
114 pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<Course>, AppError> {137 pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<Course>, AppError> {
115- let mut result = db138+ let rows = sqlx::query_as!(
116- .query("SELECT * FROM course WHERE creator = $usr OR $usr IN teachers ORDER BY id DESC")139+ Course,
117- .bind(("usr", user.record()))140+ r#"SELECT id, creator, teachers, title, description, kind, term, capacity
118- .await?141+ FROM course WHERE creator = $1 OR $2 = ANY(teachers) ORDER BY id DESC"#,
119- .check()?;142+ user,
120- Ok(result.take::<Vec<Course>>(0)?)143+ user,
144+ )
145+ .fetch_all(db)
146+ .await?;
147+ Ok(rows)
121 }148 }
122 149
123 /// Load every course behind `ids` (one query) — the join half of the150 /// 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>,
126 if ids.is_empty() {153 if ids.is_empty() {
127 return Ok(Vec::new());154 return Ok(Vec::new());
128 }155 }
129- let records: Vec<RecordId> = ids.iter().map(CourseId::record).collect();156+ let keys: Vec<CourseId> = ids.to_vec();
130- let mut result = db157+ let rows = sqlx::query_as!(
131- .query("SELECT * FROM course WHERE id IN $ids")158+ Course,
132- .bind(("ids", records))159+ r#"SELECT id, creator, teachers, title, description, kind, term, capacity
133- .await?160+ FROM course WHERE id = ANY($1)"#,
134- .check()?;161+ keys,
135- Ok(result.take::<Vec<Course>>(0)?)162+ )
163+ .fetch_all(db)
164+ .await?;
165+ Ok(rows)
136 }166 }
137 167
138 /// Request-scoped: `teachers` is written by [`assign_teacher`],168 /// Request-scoped: `teachers` is written by [`assign_teacher`],
@@ -160,19 +190,25 @@ pub async fn update(
160 // without its count. A PATCH that carried no `term_id`, or re-stated the190 // without its count. A PATCH that carried no `term_id`, or re-stated the
161 // link it already had, moves neither counter.191 // link it already had, moves neither counter.
162 let (claim, release) = term::ref_move(course.term.as_ref(), &term);192 let (claim, release) = term::ref_move(course.term.as_ref(), &term);
163- let expected = course.term.as_ref().map(TermId::record);193+ FieldUpdate::new(COURSE_TABLE, course.id.uuid())
164- FieldUpdate::new(course.id.record())194+ .set("title", title.map(|title| title.as_str().to_owned()))
165- .set("title", title)195+ .set(
166- .set("description", description)196+ "description",
167- .set("kind", kind)197+ description.map(|description| description.as_str().to_owned()),
168- .set("term", term.map(|term| term.map(|term| term.record())))198+ )
169- .set("capacity", capacity)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))
170 .refcount(205 .refcount(
171- COURSE_COUNT_FIELD,
172 "term",206 "term",
173- expected,207+ "course_count",
174- claim,208+ "term",
175- release,209+ course.term.as_ref().map(|term| term.uuid()),
210+ claim.map(|term| term.uuid()),
211+ release.map(|term| term.uuid()),
176 term::gone_error(),212 term::gone_error(),
177 )213 )
178 .run::<Course>(db)214 .run::<Course>(db)
@@ -184,8 +220,9 @@ pub async fn update(
184 /// Field-scoped, and the new list is folded server-side out of the *stored*220 /// Field-scoped, and the new list is folded server-side out of the *stored*
185 /// one: a course PATCH awaits a term lookup between its read and its write,221 /// one: a course PATCH awaits a term lookup between its read and its write,
186 /// so a whole-row save from either side would revert the other. The222 /// so a whole-row save from either side would revert the other. The
187-/// `array::distinct` keeps the assignment idempotent even when two requests223+/// `array_agg(DISTINCT …)` keeps the assignment idempotent even when two
188-/// name the same teacher at once (the early return only sees a stale row).224+/// requests name the same teacher at once (the early return only sees a
225+/// stale row).
189 pub async fn assign_teacher(226 pub async fn assign_teacher(
190 db: &Database,227 db: &Database,
191 course: Course,228 course: Course,
@@ -194,20 +231,19 @@ pub async fn assign_teacher(
194 if course.is_assigned(teacher) {231 if course.is_assigned(teacher) {
195 return Ok(course);232 return Ok(course);
196 }233 }
197- let mut result = db234+ let updated = sqlx::query_as!(
198- .query(235+ Course,
199- "UPDATE $id SET teachers = array::distinct(array::append(teachers, $usr))236+ r#"UPDATE course
200- RETURN AFTER",237+ SET teachers = (SELECT array_agg(DISTINCT x)
201- )238+ FROM unnest(course.teachers || $2) AS x)
202- .bind(("id", course.id.record()))239+ WHERE id = $1
203- .bind(("usr", teacher.record()))240+ RETURNING id, creator, teachers, title, description, kind, term, capacity"#,
204- .await?241+ course.id,
205- .check()?;242+ teacher,
206- result243+ )
207- .take::<Vec<Course>>(0)?244+ .fetch_optional(db)
208- .into_iter()245+ .await?;
209- .next()246+ updated.ok_or(AppError::NotFound)
210- .ok_or(AppError::NotFound)
211 }247 }
212 248
213 /// Drop `teacher` from this course. `None` when they weren't assigned, so249 /// Drop `teacher` from this course. `None` when they weren't assigned, so
@@ -220,30 +256,32 @@ pub async fn unassign_teacher(
220 if !course.is_assigned(teacher) {256 if !course.is_assigned(teacher) {
221 return Ok(None);257 return Ok(None);
222 }258 }
223- // Same field-scoped story as [`assign_teacher`]; `-=` drops the259+ // Same field-scoped story as [`assign_teacher`]; `array_remove` drops
224- // one link off the stored list without touching the course's own text.260+ // the one link off the stored list without touching the course's own
225- let mut result = db261+ // text.
226- .query("UPDATE $id SET teachers -= $usr RETURN AFTER")262+ let updated = sqlx::query_as!(
227- .bind(("id", course.id.record()))263+ Course,
228- .bind(("usr", teacher.record()))264+ r#"UPDATE course SET teachers = array_remove(teachers, $2)
229- .await?265+ WHERE id = $1
230- .check()?;266+ RETURNING id, creator, teachers, title, description, kind, term, capacity"#,
231- Ok(Some(267+ course.id,
232- result268+ teacher,
233- .take::<Vec<Course>>(0)?269+ )
234- .into_iter()270+ .fetch_optional(db)
235- .next()271+ .await?;
236- .ok_or(AppError::NotFound)?,272+ Ok(updated)
237- ))
238 }273 }
239 274
240 /// Strip `user` from every course they were assigned to — the sweep for a275 /// Strip `user` from every course they were assigned to — the sweep for a
241 /// user demoted below `teacher`, who may no longer run anything.276 /// user demoted below `teacher`, who may no longer run anything.
242 pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> {277 pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> {
243- db.query("UPDATE course SET teachers -= $usr WHERE $usr IN teachers")278+ sqlx::query!(
244- .bind(("usr", user.record()))279+ r#"UPDATE course SET teachers = array_remove(teachers, $1)
245- .await?280+ WHERE $1 = ANY(teachers)"#,
246- .check()?;281+ user,
282+ )
283+ .execute(db)
284+ .await?;
247 Ok(())285 Ok(())
248 }286 }
249 287
@@ -261,111 +299,233 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App
261 /// **Bank templates** survive it — they are a separate, reusable library299 /// **Bank templates** survive it — they are a separate, reusable library
262 /// spanning every course — so their `source_exam` and `subject` links are300 /// spanning every course — so their `source_exam` and `subject` links are
263 /// cleared instead, in this same transaction, exactly as301 /// cleared instead, in this same transaction, exactly as
264-/// [`crate::db::exam::delete`] and302+/// [`crate::db::exam::delete`] and [`crate::db::subject::delete`]
265-/// [`crate::db::subject::delete`] clear them one level down.303+/// clear them one level down. Deleting a course must leave the bank where
266-/// Deleting a course must leave the bank where deleting each of its exams304+/// deleting each of its exams and subjects by hand would have left it, or
267-/// and subjects by hand would have left it, or a template is left pointing305+/// a template is left pointing at a dead exam (permanently: nothing else
268-/// at a dead exam (permanently: nothing else ever visits that column) and306+/// ever visits that column) and at a dead subject the next `PATCH`
269-/// at a dead subject the next `PATCH` omitting `subject_id` writes straight307+/// omitting `subject_id` writes straight back.
270-/// back.
271 ///308 ///
272 /// The **grade blueprints** naming it are swept in that same transaction.309 /// The **grade blueprints** naming it are swept in that same transaction.
273 /// Nothing else can reach them — a blueprint holds its courses as a list on310 /// Nothing else can reach them — a blueprint holds its courses as a list on
274 /// its own row, not as link rows this cascade could delete — and an id left311 /// its own row, not as link rows this cascade could delete — and an id left
275 /// behind is permanent rather than merely stale: the pump's own312 /// behind is permanent rather than merely stale: the pump's own
276-/// [`crate::db::class_blueprint::prune`] fires only313+/// [`crate::db::class_blueprint::prune`] fires only while walking a
277-/// while walking a section, so a grade with no sections can never drop one,314+/// section, so a grade with no sections can never drop one, and every
278-/// and every `PATCH` of that template is refused for naming a course that315+/// `PATCH` of that template is refused for naming a course that does not
279-/// does not exist, which is precisely the call documented as the repair.316+/// exist, which is precisely the call documented as the repair. A dozen-row
317+/// table scanned unindexed, deliberately: a course delete is rare.
280 ///318 ///
281-/// It is a table scan, deliberately unindexed: `class_blueprint` holds one319+/// The **derived AI rows** (`rag_output` carries a denormalized `course`
282-/// row per grade label the school uses (a dozen), a course delete is rare,320+/// besides its note link) and the event **audience links** are FK children
283-/// and the per-element index the `WHERE` would want321+/// the old store let dangle: `rag_output` is disposable and dies here, and
284-/// (`FIELDS courses[*]`) is the one this store answers with **no rows at322+/// an event whose audience was "this course's students" keeps standing with
285-/// all** — the trap [`list_for_teacher`] documents.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).
286 ///326 ///
287 /// The marks going with it give their exam kinds' references back, counted327 /// The marks going with it give their exam kinds' references back, counted
288 /// per kind inside this same transaction — the mirror of `Exam::delete`.328 /// per kind inside this same transaction — the mirror of `Exam::delete`.
289 /// Skipping it would leave every kind the course graded under counted329 /// Skipping it would leave every kind the course graded under counted
290 /// forever, and a counted kind can never leave the school's settings.330 /// forever, and a counted kind can never leave the school's settings.
291 ///331 ///
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+///
292 /// `false` = refused, nothing was written: someone is still enrolled. The341 /// `false` = refused, nothing was written: someone is still enrolled. The
293-/// roster is read off the course's own `enrollment_count`, so the check and342+/// guard locks the course row (`FOR UPDATE`) and reads its own
294-/// the delete are one conditional write on one record — an enroll racing343+/// `enrollment_count`, so an enroll racing this either takes its seat
295-/// this either takes its seat first (and the delete is refused) or finds344+/// first (and the delete is refused) or finds the row gone (and is refused
296-/// the row gone (and is refused itself). `Err(NotFound)`345+/// itself). `Err(NotFound)` keeps the answer a concurrent *delete* used
297-/// keeps the answer a concurrent *delete* used to get.346+/// to get — and unlike the old one-statement guard, this one tells the two
347+/// apart without a second read.
298 pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {348 pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {
299- let sql = format!(349+ tx_with_retry(db, true, async |tx| {
300- "BEGIN TRANSACTION;350+ // The guard and the lock: the row (and its roster count) cannot
301- LET $gone = (DELETE $course WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE);351+ // change under this transaction, and every enroll claim contends on
302- IF array::len($gone) = 0 {{ THROW '{ROSTER_MARK}' }};352+ // this very row, so check and cascade are one decision.
303- FOR $row IN $gone {{353+ let guard = sqlx::query!(
304- IF $row.term != NONE {{354+ r#"SELECT enrollment_count, term FROM course WHERE id = $1 FOR UPDATE"#,
305- UPDATE $row.term SET {COURSE_COUNT_FIELD} = \355+ course.id,
306- math::max([({COURSE_COUNT_FIELD} ?? 0) - 1, 0]);356+ )
307- }};357+ .fetch_optional(&mut *tx)
308- }};358+ .await?;
309- FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result359+ let Some(guard) = guard else {
310- WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)360+ return Err(AppError::NotFound);
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),
363 };361 };
364- }362+ if guard.enrollment_count != 0 {
365- if let Some(error) = errors.drain().map(|(_, error)| error).next() {363+ return Ok(false);
366- return Err(error.into());364+ }
367- }365+ // The exam ids are needed twice — the kind_ref refund and the bank's
368- Ok(true)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
369 }529 }
370 530
371 /// A real course row, for the tests of every child that must now prove its531 /// 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,1+//! The `course_note` table: a course's shared notes, newest first, deleted
2-//! listed newest first, deleted together with its attachment rows.2+//! together with their attachment rows.
3 3
4-use surrealdb::types::SurrealValue;4+use crate::database::{Database, foreign_key_violation, tx_with_retry};
5-
6-use crate::constant::ENROLLMENT_COUNT_FIELD;
7-use crate::database::Database;
8-use crate::db::cap;
9 use crate::db::field_update::FieldUpdate;5 use crate::db::field_update::FieldUpdate;
10 use crate::db::page::PagedList;6 use crate::db::page::PagedList;
11 use crate::domain::course::CourseId;7 use crate::domain::course::CourseId;
@@ -14,15 +10,6 @@ use crate::domain::course_note_file::CourseNoteFile;
14 use crate::domain::user::UserId;10 use crate::domain::user::UserId;
15 use crate::error::AppError;11 use crate::error::AppError;
16 12
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-
26 pub async fn create(13 pub async fn create(
27 db: &Database,14 db: &Database,
28 course: &CourseId,15 course: &CourseId,
@@ -37,23 +24,41 @@ pub async fn create(
37 title,24 title,
38 content,25 content,
39 };26 };
40- // The course row is *written* (bumped and put back), not read, so this27+ // whole-row-save-ok: insert of a fresh UUID row built in place — there is no prior row to clobber.
41- // collides with `Course::delete`'s cascade: a note that outlives its28+ // The course row is *referenced* (a real foreign key the store now
42- // course is unreachable forever — every route to it goes through the29+ // enforces), so a note that races `Course::delete`'s cascade is refused
43- // course. See [`cap::touch_and_create`].30+ // as 23503 instead of outliving its course — a note whose course is gone
44- cap::touch_and_create(31+ // is unreachable forever, every route to it going through the course.
45- &course.record(),32+ // That refusal is the parent-gone 404 the touch trick used to produce.
46- ENROLLMENT_COUNT_FIELD,33+ let created = sqlx::query_as!(
47- &note.id.record(),34+ CourseNote,
48- &note,35+ r#"INSERT INTO course_note (id, course, author, title, content)
49- db,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
50 )43 )
51- .await?44+ .fetch_one(db)
52- .ok_or(AppError::NotFound)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+ }
53 }51 }
54 52
55 pub async fn read(db: &Database, id: &CourseNoteId) -> Result<Option<CourseNote>, AppError> {53 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)
57 }62 }
58 63
59 pub async fn list_for_course(64 pub async fn list_for_course(
@@ -62,9 +67,9 @@ pub async fn list_for_course(
62 limit: Option<i64>,67 limit: Option<i64>,
63 offset: i64,68 offset: i64,
64 ) -> Result<(Vec<CourseNote>, i64), AppError> {69 ) -> Result<(Vec<CourseNote>, i64), AppError> {
65- PagedList::new("course_note WHERE course = $crs", "ORDER BY id DESC")70+ PagedList::new("course_note WHERE course = $1", "ORDER BY id DESC")
66- .bind("crs", course.record())71+ .bind(course.uuid())
67- .run(limit, offset, db)72+ .run::<CourseNote>(limit, offset, db)
68 .await73 .await
69 }74 }
70 75
@@ -80,9 +85,12 @@ pub async fn update(
80 title: Option<CourseNoteTitle>,85 title: Option<CourseNoteTitle>,
81 content: Option<CourseNoteContent>,86 content: Option<CourseNoteContent>,
82 ) -> Result<CourseNote, AppError> {87 ) -> Result<CourseNote, AppError> {
83- FieldUpdate::new(note.id.record())88+ FieldUpdate::new("course_note", note.id.uuid())
84- .set("title", title)89+ .set("title", title.map(|title| title.as_str().to_string()))
85- .set("content", content)90+ .set(
91+ "content",
92+ content.map(|content| content.as_str().to_string()),
93+ )
86 .run::<CourseNote>(db)94 .run::<CourseNote>(db)
87 .await95 .await
88 }96 }
@@ -92,29 +100,40 @@ pub async fn update(
92 /// Blob files on disk are the web layer's to remove, but only for *these*100 /// Blob files on disk are the web layer's to remove, but only for *these*
93 /// rows — a row uploaded after the caller listed the note's files is101 /// rows — a row uploaded after the caller listed the note's files is
94 /// deleted here too, and a pre-read snapshot would strand its blob.102 /// 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.
95 pub async fn delete(110 pub async fn delete(
96 db: &Database,111 db: &Database,
97 note: CourseNote,112 note: CourseNote,
98 ) -> Result<(CourseNote, Vec<CourseNoteFile>), AppError> {113 ) -> Result<(CourseNote, Vec<CourseNoteFile>), AppError> {
99- let mut result = db114+ tx_with_retry(db, true, async |conn| {
100- .query(115+ sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id)
101- "BEGIN TRANSACTION;116+ .execute(&mut *conn)
102- LET $files = (DELETE course_note_file WHERE course_note = $note RETURN BEFORE);117+ .await?;
103- LET $gone = (DELETE $note RETURN BEFORE);118+ let files = sqlx::query_as!(
104- RETURN { note: $gone, files: $files };119+ CourseNoteFile,
105- COMMIT TRANSACTION;",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
106 )130 )
107- .bind(("note", note.id.record()))131+ .fetch_optional(&mut *conn)
108- .await?132+ .await?;
109- .check()?;133+ let note = gone.ok_or(AppError::NotFound)?;
110- // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3.134+ Ok((note, files))
111- let outcome = result135+ })
112- .take::<Vec<DeleteOutcome>>(3)?136+ .await
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))
118 }137 }
119 138
120 #[cfg(test)]139 #[cfg(test)]
src/db/course_note_file.rsmodified+125 -137
@@ -2,54 +2,71 @@
2 //! newest first, with the note's file cap claimed and released in the same2 //! newest first, with the note's file cap claimed and released in the same
3 //! write as the row.3 //! write as the row.
4 4
5-use surrealdb::types::{RecordId, RecordIdKey};5+use crate::constant::MAX_COURSE_NOTE_FILES;
6-6+use crate::database::{Database, tx_with_retry, unique_violation};
7-use crate::constant::{COURSE_NOTE_FILE_COUNT_FIELD, MAX_COURSE_NOTE_FILES};
8-use crate::database::Database;
9-use crate::db::cap;
10 use crate::db::page::PagedList;7 use crate::db::page::PagedList;
8+use crate::domain::course::CourseId;
11 use crate::domain::course_note::CourseNoteId;9 use crate::domain::course_note::CourseNoteId;
12 use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId};10 use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId};
13 use crate::error::AppError;11 use crate::error::AppError;
14 12
15 /// Persist the row assembled by [`CourseNoteFile::new`], refusing once its13 /// Persist the row assembled by [`CourseNoteFile::new`], refusing once its
16 /// note already holds [`MAX_COURSE_NOTE_FILES`]. The slot and the row are14 /// 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 — see15+/// taken together by one conditional statement on the note row (the claim
18-/// [`crate::db::note_file::insert`] for why that is the only guard a16+/// CTE of `cap::claim_and_create`, spelled out at its call site — see
19-/// concurrent insert cannot outrun.17+/// `crate::db::cap`) — see [`crate::db::note_file::insert`] for why that is
18+/// the only guard a concurrent insert cannot outrun.
20 pub async fn insert(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFile, AppError> {19 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 clobber20+ // whole-row-save-ok: insert of a fresh UUID row built in place by `new` — there is no prior row to clobber
22- match cap::claim_and_create(21+ let created = sqlx::query_as!(
23- &file.course_note.record(),22+ CourseNoteFile,
24- COURSE_NOTE_FILE_COUNT_FIELD,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,
25 MAX_COURSE_NOTE_FILES as i64,31 MAX_COURSE_NOTE_FILES as i64,
26- &file.id.record(),32+ file.id,
27- &file,33+ file.name,
28- db,34+ file.content_type,
35+ file.size
29 )36 )
30- .await?37+ .fetch_optional(db)
31- {38+ .await;
32- cap::Claimed::Made(created) => Ok(created),39+ match created {
40+ Ok(Some(row)) => Ok(row),
33 // Also how a missing note reads: no note row means no slot to take.41 // 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(
35 "the course note already holds the maximum of 10 files — delete one first",43 "the course note already holds the maximum of 10 files — delete one first",
36 )),44 )),
37- // Unreachable: the id is a ULID this call just generated.45+ // A duplicate would be a 23505 on the row's own key, which this path
38- cap::Claimed::Duplicate => Err(AppError::Internal(46+ // cannot produce — the id is a UUID this call just generated.
47+ Err(err) if unique_violation(&err).is_some() => Err(AppError::Internal(
39 "failed to create course note file".into(),48 "failed to create course note file".into(),
40 )),49 )),
50+ Err(err) => Err(err.into()),
41 }51 }
42 }52 }
43 53
44 /// Read a file's row by id alone, for the callers that have no note in54 /// Read a file's row by id alone, for the callers that have no note in
45 /// hand yet and reach the note *through* the file (the AI bridge's blob55 /// 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 is56+/// stream). An id from any other table simply reads as `None`, which is
47 /// what keeps a personal note's file id unreachable here.57 /// what keeps a personal note's file id unreachable here.
48 pub async fn read(58 pub async fn read(
49 db: &Database,59 db: &Database,
50 id: &CourseNoteFileId,60 id: &CourseNoteFileId,
51 ) -> Result<Option<CourseNoteFile>, AppError> {61 ) -> 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)
53 }70 }
54 71
55 /// Read a file's row only if it belongs to `note` — callers have already72 /// Read a file's row only if it belongs to `note` — callers have already
@@ -59,8 +76,16 @@ pub async fn read_for(
59 id: &CourseNoteFileId,76 id: &CourseNoteFileId,
60 note: &CourseNoteId,77 note: &CourseNoteId,
61 ) -> Result<Option<CourseNoteFile>, AppError> {78 ) -> Result<Option<CourseNoteFile>, AppError> {
62- let file: Option<CourseNoteFile> = db.select(id.record()).await?;79+ let file = sqlx::query_as!(
63- Ok(file.filter(|file| &file.course_note == note))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)
64 }89 }
65 90
66 /// All of `note`'s attachment rows, newest first.91 /// All of `note`'s attachment rows, newest first.
@@ -71,69 +96,63 @@ pub async fn list_for(
71 offset: i64,96 offset: i64,
72 ) -> Result<(Vec<CourseNoteFile>, i64), AppError> {97 ) -> Result<(Vec<CourseNoteFile>, i64), AppError> {
73 PagedList::new(98 PagedList::new(
74- "course_note_file WHERE course_note = $note",99+ "course_note_file WHERE course_note = $1",
75 "ORDER BY id DESC",100 "ORDER BY id DESC",
76 )101 )
77- .bind("note", note.record())102+ .bind(note.uuid())
78- .run(limit, offset, db)103+ .run::<CourseNoteFile>(limit, offset, db)
79 .await104 .await
80 }105 }
81 106
82-/// The blob names (record keys, since a file's blob is named by its own107+/// The blob names (the rows' own ids, since a file's blob is named by its
83 /// id) behind every note attachment of `course` — collected *before* the108 /// id) behind every note attachment of `course` — collected *before* the
84 /// course-delete cascade wipes the rows.109 /// course-delete cascade wipes the rows.
85 pub async fn file_keys_for_course(110 pub async fn file_keys_for_course(
86 db: &Database,111 db: &Database,
87- course: &crate::domain::course::CourseId,112+ course: &CourseId,
88 ) -> Result<Vec<String>, AppError> {113 ) -> Result<Vec<String>, AppError> {
89- let mut result = db114+ let rows = sqlx::query!(
90- .query(115+ r#"SELECT course_note_file.id AS "id: CourseNoteFileId" FROM course_note_file
91- "SELECT VALUE id FROM course_note_file \116+ WHERE course_note IN (SELECT id FROM course_note WHERE course = $1)"#,
92- WHERE course_note IN (SELECT VALUE id FROM course_note WHERE course = $course)",117+ course.0
93- )118+ )
94- .bind(("course", course.record()))119+ .fetch_all(db)
95- .await?120+ .await?;
96- .check()?;121+ Ok(rows.into_iter().map(|row| row.id.key()).collect())
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())
105 }122 }
106 123
107 /// Delete the row and give its slot back in the same transaction — the124 /// Delete the row and give its slot back in the same transaction — the
108 /// note itself is untouched, so unlike the note-delete cascade this one125 /// note itself is untouched, so unlike the note-delete cascade this one
109 /// has a counter to correct.126 /// has a counter to correct.
110 pub async fn delete(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFile, AppError> {127 pub async fn delete(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFile, AppError> {
111- let mut result = db128+ tx_with_retry(db, true, async |conn| {
112- .query(129+ let gone = sqlx::query_as!(
113- "BEGIN TRANSACTION;130+ CourseNoteFile,
114- LET $gone = (DELETE $id RETURN BEFORE);131+ r#"DELETE FROM course_note_file WHERE id = $1
115- UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]);132+ RETURNING id, course_note, name, content_type, size"#,
116- RETURN $gone;133+ file.id
117- COMMIT TRANSACTION;",
118 )134 )
119- .bind(("id", file.id.record()))135+ .fetch_optional(&mut *conn)
120- .bind(("note", file.course_note.record()))136+ .await?;
121- .await?137+ let file = gone.ok_or(AppError::NotFound)?;
122- .check()?;138+ sqlx::query!(
123- result139+ "UPDATE course_note SET file_count = GREATEST(file_count - 1, 0) WHERE id = $1",
124- .take::<Vec<CourseNoteFile>>(3)?140+ file.course_note
125- .into_iter()141+ )
126- .next()142+ .execute(&mut *conn)
127- .ok_or(AppError::NotFound)143+ .await?;
144+ Ok(file)
145+ })
146+ .await
128 }147 }
129 148
130 #[cfg(test)]149 #[cfg(test)]
131 mod tests {150 mod tests {
132 use super::*;151 use super::*;
133- use crate::database::Database;
134 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};152 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
135- use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle};153+ use crate::domain::course_note::{CourseNoteContent, CourseNoteTitle};
136- use crate::domain::course_note_file::{FileContentType, FileName};154+ use crate::domain::course_note_file::FileContentType;
155+ use crate::domain::course_note_file::FileName;
137 156
138 async fn note_of(db: &Database, title: &str) -> CourseNote {157 async fn note_of(db: &Database, title: &str) -> CourseNote {
139 let creator = crate::domain::user::UserId::generate();158 let creator = crate::domain::user::UserId::generate();
@@ -159,85 +178,54 @@ mod tests {
159 .unwrap()178 .unwrap()
160 }179 }
161 180
181+ /// The cap answers with a conflict and the refused upload wrote nothing:
182+ /// the count stays at the accepted rows.
162 #[tokio::test]183 #[tokio::test]
163- async fn rows_scope_to_their_note() {184+ async fn insert_refuses_at_the_cap() {
164 let db = crate::database::init_mem().await.unwrap();185 let db = crate::database::init_mem().await.unwrap();
165- let note_a = note_of(&db, "a").await.get_id().clone();186+ let note = note_of(&db, "n").await;
166- let note_b = note_of(&db, "b").await.get_id().clone();187+ for index in 0..MAX_COURSE_NOTE_FILES {
167- let file = insert(188+ let file = CourseNoteFile::new(
168- &db,189+ note.get_id(),
169- CourseNoteFile::new(190+ FileName::try_new(&format!("f{index}")).unwrap(),
170- &note_a,191+ FileContentType::try_new("text/plain").unwrap(),
171- FileName::try_new("plan.pdf").unwrap(),192+ 1,
172- FileContentType::try_new("application/pdf").unwrap(),193+ );
173- 3,194+ insert(&db, file).await.unwrap();
174- ),195+ }
175- )196+ let over = CourseNoteFile::new(
176- .await197+ note.get_id(),
177- .unwrap();198+ FileName::try_new("over").unwrap(),
178-199+ FileContentType::try_new("text/plain").unwrap(),
179- let found = read_for(&db, file.get_id(), &note_a).await.unwrap();200+ 1,
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 );201 );
187-202+ assert!(matches!(
188- let listed = async |note: &CourseNoteId| list_for(&db, note, None, 0).await.unwrap().0;203+ insert(&db, over).await,
189- assert_eq!(listed(&note_a).await.len(), 1);204+ Err(AppError::Conflict(_))
190- assert!(listed(&note_b).await.is_empty());205+ ));
191-206+ let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap();
192- delete(&db, file).await.unwrap();207+ assert_eq!(total, MAX_COURSE_NOTE_FILES as i64);
193- assert!(listed(&note_a).await.is_empty());
194 }208 }
195 209
196- /// The counter and the rows are written in one transaction, so the stored210+ /// The blob-key collection sees attachments through the course, and a
197- /// count must equal the stored rows — after a success *and* after the211+ /// delete hands its slot back to the note.
198- /// refusal that fills the cap, which must move neither.
199 #[tokio::test]212 #[tokio::test]
200- async fn counter_tracks_stored_rows() {213+ async fn file_keys_and_delete_slot_release() {
201 let db = crate::database::init_mem().await.unwrap();214 let db = crate::database::init_mem().await.unwrap();
202- let note = note_of(&db, "a").await.get_id().clone();215+ let note = note_of(&db, "n").await;
203- let stored_count = async |note: &CourseNoteId| -> i64 {216+ let course = note.get_course().clone();
204- db.query("SELECT VALUE file_count FROM $note")217+ let file = CourseNoteFile::new(
205- .bind(("note", note.record()))218+ note.get_id(),
206- .await219+ FileName::try_new("f").unwrap(),
207- .unwrap()220+ FileContentType::try_new("text/plain").unwrap(),
208- .take::<Vec<i64>>(0)221+ 1,
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
241 );222 );
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());
242 }230 }
243 }231 }
src/db/course_session.rsmodified+77 -55
@@ -1,15 +1,11 @@
1 //! The `course_session` table: reads, a course's timetable listing, the1 //! The `course_session` table: reads, a course's timetable listing, the
2 //! request-scoped field update, and the delete that sweeps roll-call rows in2 //! request-scoped field update, and the delete that sweeps roll-call rows in
3-//! one transaction. Creation writes the course row through3+//! one transaction. Creation stands on the course foreign key, so a lesson
4-//! [`cap::touch_and_create`] so a lesson can never outlive its course; the4+//! can never outlive its course; the web-facing doors and the
5-//! web-facing doors and the teacher-resolution rule live in5+//! teacher-resolution rule live in [`crate::service::course_session`].
6-//! [`crate::service::course_session`].
7 6
8-use surrealdb::types::SurrealValue;7+use crate::constant::COURSE_SESSION_TABLE;
9-8+use crate::database::{Database, foreign_key_violation, tx_with_retry};
10-use crate::constant::ENROLLMENT_COUNT_FIELD;
11-use crate::database::{Database, transaction_with_retry};
12-use crate::db::cap;
13 use crate::db::field_update::FieldUpdate;9 use crate::db::field_update::FieldUpdate;
14 use crate::db::page::PagedList;10 use crate::db::page::PagedList;
15 use crate::domain::course::CourseId;11 use crate::domain::course::CourseId;
@@ -34,23 +30,44 @@ pub async fn create(
34 starts_at,30 starts_at,
35 ends_at,31 ends_at,
36 };32 };
37- // The course row is *written* (bumped and put back), not read, so this33+ // The course foreign key is the existence proof the old bump-and-restore
38- // collides with `Course::delete`'s cascade: a lesson that outlives its34+ // "touch" trick faked: a lesson whose course is already gone — or which
39- // course 404s through `session_with_course` forever — unreadable,35+ // is deleted while this insert is in flight — is refused here, so a
40- // unpatchable, undeletable. See [`cap::touch_and_create`].36+ // lesson can never outlive its course and 404 through
41- cap::touch_and_create(37+ // `session_with_course` forever — unreadable, unpatchable, undeletable.
42- &course.record(),38+ // `23503` is the parent-gone refusal, the same answer the touch
43- ENROLLMENT_COUNT_FIELD,39+ // produced.
44- &session.id.record(),40+ let created = sqlx::query_as!(
45- &session,41+ CourseSession,
46- db,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,
47 )51 )
48- .await?52+ .fetch_one(db)
49- .ok_or(AppError::NotFound)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+ }
50 }59 }
51 60
52 pub async fn read(db: &Database, id: &CourseSessionId) -> Result<Option<CourseSession>, AppError> {61 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)
54 }71 }
55 72
56 /// A course's sessions, most recent lesson first. Ordered by `starts_at`73 /// A course's sessions, most recent lesson first. Ordered by `starts_at`
@@ -63,11 +80,11 @@ pub async fn list_for_course(
63 offset: i64,80 offset: i64,
64 ) -> Result<(Vec<CourseSession>, i64), AppError> {81 ) -> Result<(Vec<CourseSession>, i64), AppError> {
65 PagedList::new(82 PagedList::new(
66- "course_session WHERE course = $course",83+ "course_session WHERE course = $1",
67 "ORDER BY starts_at DESC, id DESC",84 "ORDER BY starts_at DESC, id DESC",
68 )85 )
69- .bind("course", course.record())86+ .bind(course.uuid())
70- .run(limit, offset, db)87+ .run::<CourseSession>(limit, offset, db)
71 .await88 .await
72 }89 }
73 90
@@ -86,11 +103,17 @@ pub async fn update(
86 starts_at: Option<Timestamp>,103 starts_at: Option<Timestamp>,
87 ends_at: Option<Option<Timestamp>>,104 ends_at: Option<Option<Timestamp>>,
88 ) -> Result<CourseSession, AppError> {105 ) -> Result<CourseSession, AppError> {
89- FieldUpdate::new(session.id.record())106+ FieldUpdate::new(COURSE_SESSION_TABLE, session.id.uuid())
90- .set("teacher", teacher.map(|teacher| teacher.record()))107+ .set(
91- .set("topic", topic)108+ "teacher",
92- .set("starts_at", starts_at)109+ teacher.map(|teacher| crate::db::page::Param::Uuid(teacher.uuid())),
93- .set("ends_at", ends_at)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+ )
94 .ordered("starts_at", "ends_at", range_error())117 .ordered("starts_at", "ends_at", range_error())
95 .run::<CourseSession>(db)118 .run::<CourseSession>(db)
96 .await119 .await
@@ -99,32 +122,31 @@ pub async fn update(
99 /// Delete the session and cascade-remove its roll-call rows, in one122 /// Delete the session and cascade-remove its roll-call rows, in one
100 /// transaction: as two unbatched queries a failure between them stranded123 /// transaction: as two unbatched queries a failure between them stranded
101 /// roll-call rows on a session that was already gone. The other half of124 /// roll-call rows on a session that was already gone. The other half of
102-/// that invariant is [`crate::db::session_attendance::mark`],125+/// that invariant is [`crate::db::session_attendance::mark`], whose
103-/// which proves the session still exists inside its own write — a126+/// session-row lock makes a mark and this delete take turns — a mark
104-/// transaction here cannot stop a mark that commits *after* this one.127+/// committing after this cascade cannot name a session that is gone.
105 pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSession, AppError> {128 pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSession, AppError> {
106- let (mut result, mut errors) = transaction_with_retry(129+ tx_with_retry(db, false, async |tx| {
107- db,130+ // Roll-call rows first: the session row's own FK would refuse the
108- "BEGIN TRANSACTION;131+ // delete while they exist. An empty first sweep is fine — the
109- DELETE session_attendance WHERE session = $s;132+ // session may simply have had none.
110- LET $before = (DELETE $s RETURN BEFORE);133+ sqlx::query!(
111- RETURN $before;134+ r#"DELETE FROM session_attendance WHERE session = $1"#,
112- COMMIT TRANSACTION;",135+ session.id,
113- &[("s".into(), session.id.record().into_value())],136+ )
114- // No THROW of its own — an unconditional cascade, so the only137+ .execute(&mut *tx)
115- // error worth telling apart is a lost round (see138+ .await?;
116- // [`crate::db::exam::delete`]).139+ let deleted = sqlx::query_as!(
117- &[],140+ CourseSession,
118- )141+ r#"DELETE FROM course_session WHERE id = $1
119- .await?;142+ RETURNING id, course, teacher, topic, starts_at, ends_at"#,
120- if let Some(error) = errors.drain().map(|(_, error)| error).next() {143+ session.id,
121- return Err(error.into());144+ )
122- }145+ .fetch_optional(&mut *tx)
123- // Read through the trailing `RETURN`, never a hand-counted slot.146+ .await?;
124- let slot = result.num_statements().saturating_sub(2);147+ deleted.ok_or(AppError::NotFound)
125- let deleted: Option<CourseSession> =148+ })
126- result.take::<Vec<CourseSession>>(slot)?.into_iter().next();149+ .await
127- deleted.ok_or(AppError::NotFound)
128 }150 }
129 151
130 #[cfg(test)]152 #[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*1+//! The `dietary_profile` table: one row per student (the primary key *is*
2-//! the student's key), created on first write and afterwards patched2+//! the student), created on first write and afterwards patched
3-//! field-by-field. The tag/note newtypes and the pure tag intersection live3+//! field-by-field — both by one `INSERT … ON CONFLICT DO UPDATE`. The
4-//! in [`crate::domain::dietary_profile`]; the web layer reads through4+//! tag/note newtypes and the pure tag intersection live in
5+//! [`crate::domain::dietary_profile`]; the web layer reads through
5 //! [`crate::service::dietary_profile`].6 //! [`crate::service::dietary_profile`].
6 7
7 use crate::database::Database;8 use crate::database::Database;
8-use crate::db::field_update::FieldUpdate;9+use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryTags};
9-use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryProfileId, DietaryTags};
10 use crate::domain::timestamp::Timestamp;10 use crate::domain::timestamp::Timestamp;
11 use crate::domain::user::UserId;11 use crate::domain::user::UserId;
12 use crate::error::AppError;12 use crate::error::AppError;
13 13
14 /// One student's profile, or `None` while the school never recorded one.14 /// 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.
16 pub async fn read(db: &Database, student: &UserId) -> Result<Option<DietaryProfile>, AppError> {16 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)
18 }26 }
19 27
20 /// The tags a menu read matches its dishes against: the caller's, or an28 /// 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
27 }35 }
28 36
29 /// Write the fields the PATCH carried. Creates the row on first write;37 /// Write the fields the PATCH carried. Creates the row on first write;
30-/// afterwards only the named fields move, because `student` is `READONLY`38+/// afterwards only the named fields move, because a whole-row save would
31-/// and a whole-row save would also revert a concurrent edit of the other39+/// also revert a concurrent edit of the other field.
32-/// field (see [`FieldUpdate`]).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.
33 pub async fn save(49 pub async fn save(
34 db: &Database,50 db: &Database,
35 student: &UserId,51 student: &UserId,
@@ -37,37 +53,24 @@ pub async fn save(
37 note: Option<Option<DietaryNote>>,53 note: Option<Option<DietaryNote>>,
38 by: &UserId,54 by: &UserId,
39 ) -> Result<DietaryProfile, AppError> {55 ) -> Result<DietaryProfile, AppError> {
40- if read(db, student).await?.is_none() {56+ let row = sqlx::query_as!(
41- let profile = DietaryProfile {57+ DietaryProfile,
42- id: DietaryProfileId::of(student),58+ "INSERT INTO dietary_profile (student, tags, note, updated_by, updated_at)
43- student: student.clone(),59+ VALUES ($1, COALESCE($2, '{}'::text[]), $3, $4, $5)
44- tags: tags.clone().unwrap_or(DietaryTags(Vec::new())),60+ ON CONFLICT (student) DO UPDATE SET
45- note: note.clone().flatten(),61+ tags = COALESCE($2, dietary_profile.tags),
46- updated_by: by.clone(),62+ note = CASE WHEN $6 THEN $3 ELSE dietary_profile.note END,
47- updated_at: Timestamp::now(),63+ updated_by = $4,
48- };64+ updated_at = $5
49- match db.create(profile.id.record()).content(profile).await {65+ RETURNING student, tags, note, updated_by, updated_at",
50- Ok(Some(created)) => return Ok(created),66+ *student,
51- Ok(None) => {67+ tags.map(|t| t.as_slice().to_vec()),
52- return Err(AppError::Internal("failed to save the profile".into()));68+ note.clone().flatten().map(|n| n.as_str().to_string()),
53- }69+ *by,
54- // A rival first `PATCH` created the row in the round trip since70+ Timestamp::now(),
55- // the read above (the `dietary_profile_student` UNIQUE index71+ note.is_some(),
56- // catches the same collision), and `CREATE` leaves that row72+ )
57- // untouched — so this call is a plain field write after all,73+ .fetch_one(db)
58- // exactly as it would have been a moment later. Propagated, it74+ .await?;
59- // was a 500 on a legitimate request. Same shape as75+ Ok(row)
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
73 }76 }
src/db/enrollment.rsmodified+170 -170
@@ -1,49 +1,55 @@
1 //! The `enrollment` table: the roster read and listing, the seat-returning1 //! The `enrollment` table: the roster read and listing, the seat-returning
2-//! delete, and the enroll claim — the one transaction that checks the pair2+//! delete, and the enroll claim — one transaction that checks the pair free,
3-//! free, the member still a student, and the roster under capacity while it3+//! the member still a student, and the roster under capacity while it
4 //! spends the seat. The target-user gates the HTTP handlers pay live in4 //! spends the seat. The target-user gates the HTTP handlers pay live in
5 //! [`crate::service::enrollment`].5 //! [`crate::service::enrollment`].
6 6
7-use surrealdb::types::SurrealValue;7+use crate::database::{Database, tx_with_retry, unique_violation};
8-
9-use crate::constant::ENROLLMENT_COUNT_FIELD;
10-use crate::database::{Database, transaction_with_retry};
11 use crate::db::cap;8 use crate::db::cap;
12 use crate::db::page::PagedList;9 use crate::db::page::PagedList;
13 use crate::domain::course::CourseId;10 use crate::domain::course::CourseId;
14-use crate::domain::enrollment::{Enrollment, EnrollmentId};11+use crate::domain::enrollment::Enrollment;
15 use crate::domain::role::Role;12 use crate::domain::role::Role;
16 use crate::domain::user::UserId;13 use crate::domain::user::UserId;
17 use crate::error::{AppError, ValidationError};14 use crate::error::{AppError, ValidationError};
18 15
19-/// The `THROW` markers [`enroll`]'s claim aborts with: this pair16+/// What [`enroll`]'s transaction settled on — the three old `THROW` markers
20-/// already holds a row, the roster is full, and the person being enrolled is no17+/// (`enroll_held`, `enroll_not_student`, `enroll_full`) as Rust verdicts.
21-/// longer a student.18+enum Verdict {
22-const HELD_MARK: &str = "enroll_held";19+ /// This pair already holds a row.
23-const FULL_MARK: &str = "enroll_full";20+ Held,
24-const UNFIT_MARK: &str = "enroll_not_student";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";
25 32
26-/// Enroll (idempotently) `user` into `course`. One row per (course, user),33+/// Enroll (idempotently) `user` into `course`. The table's primary key *is*
27-/// keyed by a deterministic composite id, so concurrent enrolls of the same34+/// the (course, user) pair, so concurrent enrolls of the same pair converge
28-/// pair converge on one row instead of racing the unique index into a 500:35+/// on one row instead of racing into a 500: the loser reads the winner's row
29-/// the loser of the `CREATE` reads the winner's row back and returns it.36+/// back and returns it. When the course carries a capacity, a full roster
30-/// When the course carries a capacity, a full roster refuses new members37+/// refuses new members (409) — the seat is taken by a single-record
31-/// (409) — the seat is taken by a single-record conditional write on the38+/// conditional write on the course row whose bound is the row's *own*
32-/// course row whose bound is the row's *own* `capacity` column, read inside39+/// `capacity` column, read inside the same statement that spends the seat. A
33-/// the same statement that spends the seat. A snapshot integer taken by a40+/// snapshot integer taken by a read beforehand would be exactly the number a
34-/// read beforehand would be exactly the number a concurrent capacity PATCH41+/// concurrent capacity PATCH invalidates. An already enrolled user is
35-/// invalidates, which is what this promised and did not do. An already42+/// returned as-is even when the roster is full, and never charged a seat.
36-/// enrolled user is returned as-is even when the roster is full, and never43+/// The same claim is the delete guard's other half: it matches nothing once
37-/// charged a seat. The same claim is the delete guard's other half: it44+/// the course row is gone, and while it holds a seat the course cannot be
38-/// matches nothing once the course row is gone, and while it holds a seat45+/// deleted — so no roster row can outlive its course.
39-/// the course cannot be deleted — so no roster row can outlive its course.
40 ///46 ///
41-/// On admissibility ([`crate::database::transaction_with_retry`]): the47+/// Gate order is the old THROW order: an existing pair outranks the role
42-/// `CREATE` here *can* answer "already exists", but only to a rival that48+/// check, which outranks a full roster. The role check takes the user row
43-/// landed inside this very window — and the re-send then sees that row at49+/// `FOR NO KEY UPDATE`, the same row a demotion cascade updates before its
44-/// the `$held` gate and takes the other branch, so the loop converges50+/// sweep, so grant and demotion serialize on the row lock in both
45-/// instead of re-asking a settled question. Same shape, same reason, as51+/// directions — a row landing after the sweep is impossible, and a demotion
46-/// [`crate::db::class_pump::attach`].52+/// landing before this check refuses it.
47 pub async fn enroll(53 pub async fn enroll(
48 db: &Database,54 db: &Database,
49 course: &CourseId,55 course: &CourseId,
@@ -53,112 +59,89 @@ pub async fn enroll(
53 if let Some(existing) = read_for_user(db, course, user).await? {59 if let Some(existing) = read_for_user(db, course, user).await? {
54 return disown_if_pumped(db, existing).await;60 return disown_if_pumped(db, existing).await;
55 }61 }
56- let enrollment = Enrollment {62+ let verdict = tx_with_retry(db, false, async |tx| {
57- id: EnrollmentId::composite(course, user),63+ // The duplicate gate rides ahead of the role check, so "you are
58- course: course.clone(),64+ // already in" still outranks everything.
59- user: user.clone(),65+ let held = sqlx::query!(
60- enrolled_by: enrolled_by.clone(),66+ r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#,
61- // Hand-placed: no source key at all is written, which is what makes67+ course,
62- // a class sweep unable to take this row back.68+ user,
63- source: None,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,
64 };123 };
65- // CREATE, not UPSERT, and in the seat's own transaction: a duplicate has124+ match verdict {
66- // to be *seen*, or the pair's second writer would keep the seat it125+ Ok(Verdict::Made(row)) => Ok(row),
67- // claimed for a row that already existed and the counter would drift126+ Ok(Verdict::Held) => match read_for_user(db, course, user).await? {
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 Some(existing) => disown_if_pumped(db, existing).await,127 Some(existing) => disown_if_pumped(db, existing).await,
125 None => Err(AppError::Internal("failed to enroll user".into())),128 None => Err(AppError::Internal("failed to enroll user".into())),
126- };129+ },
127- }130+ // Demoted while this ran: the same refusal the service's own gate
128- // Demoted while this ran: the same refusal the service's own gate makes131+ // makes a moment earlier, and the only one that can arrive after it.
129- // a moment earlier, and the only one that can arrive after it.132+ Ok(Verdict::Unfit) => Err(AppError::Validation(ValidationError::Invalid {
130- if errors
131- .values()
132- .any(|error| error.to_string().contains(UNFIT_MARK))
133- {
134- return Err(AppError::Validation(ValidationError::Invalid {
135 field: "user_id",133 field: "user_id",
136 reason: "only students can be enrolled in a course",134 reason: "only students can be enrolled in a course",
137- }));135+ })),
138- }136+ // Full, or the course is gone — the conditional write matches
139- // Full, or the course is gone — the conditional write matches nothing137+ // nothing either way, and only this path pays for the read that
140- // either way, and only this path pays for the read that tells them138+ // tells them apart.
141- // apart.139+ Ok(Verdict::Full) => match crate::db::course::read(db, course).await? {
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? {
147 Some(_) => Err(AppError::Conflict("the course is full")),140 Some(_) => Err(AppError::Conflict("the course is full")),
148 None => Err(AppError::NotFound),141 None => Err(AppError::NotFound),
149- };142+ },
150- }143+ Err(err) => Err(err),
151- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
152- return Err(error.into());
153 }144 }
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()))
162 }145 }
163 146
164 /// A hand enroll landing on a row a class pumped takes the row *off* the147 /// A hand enroll landing on a row a class pumped takes the row *off* the
@@ -167,28 +150,30 @@ pub async fn enroll(
167 /// holds in the other direction — a manual unenroll wins, permanently — and150 /// holds in the other direction — a manual unenroll wins, permanently — and
168 /// without it "hand-placed" was a state only a first enroll could reach.151 /// without it "hand-placed" was a state only a first enroll could reach.
169 ///152 ///
170-/// `UNSET`, not `= NONE`: absence *is* the meaning of this column (see the153+/// `NULL`, not absence: the column is a nullable uuid whose NULL *is* the
171-/// struct doc), and it is what a hand enroll writes on the create path.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.
172 async fn disown_if_pumped(db: &Database, existing: Enrollment) -> Result<Enrollment, AppError> {156 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() {
174 return Ok(existing);158 return Ok(existing);
175 }159 }
176- let mut result = db160+ let disowned = sqlx::query_as!(
177- .query("UPDATE $id UNSET source RETURN AFTER")161+ Enrollment,
178- .bind(("id", existing.id.record()))162+ r#"UPDATE enrollment SET source = NULL
179- .await?163+ WHERE course = $1 AND app_user = $2
180- .check()?;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?;
181 // A row that is no longer there is not an internal error: an unenroll170 // A row that is no longer there is not an internal error: an unenroll
182 // (or the class sweep a role change runs) landing between the read171 // (or the class sweep a role change runs) landing between the read
183 // above and this write matches nothing, and the caller asked to be172 // above and this write matches nothing, and the caller asked to be
184 // enrolled — which they were, by the row this call was handed. The173 // enrolled — which they were, by the row this call was handed. The
185 // disown is all that is lost, and it is lost to a delete that took the174 // disown is all that is lost, and it is lost to a delete that took the
186 // whole row with it.175 // whole row with it.
187- Ok(result176+ Ok(disowned.unwrap_or(existing))
188- .take::<Vec<Enrollment>>(0)?
189- .into_iter()
190- .next()
191- .unwrap_or(existing))
192 }177 }
193 178
194 /// Some(_) iff `user` is enrolled in `course` — the grading gate.179 /// Some(_) iff `user` is enrolled in `course` — the grading gate.
@@ -197,13 +182,16 @@ pub async fn read_for_user(
197 course: &CourseId,182 course: &CourseId,
198 user: &UserId,183 user: &UserId,
199 ) -> Result<Option<Enrollment>, AppError> {184 ) -> Result<Option<Enrollment>, AppError> {
200- let mut result = db185+ let row = sqlx::query_as!(
201- .query("SELECT * FROM enrollment WHERE course = $course AND user = $usr LIMIT 1")186+ Enrollment,
202- .bind(("course", course.record()))187+ r#"SELECT course, app_user AS "user", enrolled_by, source
203- .bind(("usr", user.record()))188+ FROM enrollment WHERE course = $1 AND app_user = $2"#,
204- .await?189+ course,
205- .check()?;190+ user,
206- Ok(result.take::<Vec<Enrollment>>(0)?.into_iter().next())191+ )
192+ .fetch_optional(db)
193+ .await?;
194+ Ok(row)
207 }195 }
208 196
209 pub async fn list_for_course(197 pub async fn list_for_course(
@@ -212,32 +200,44 @@ pub async fn list_for_course(
212 limit: Option<i64>,200 limit: Option<i64>,
213 offset: i64,201 offset: i64,
214 ) -> Result<(Vec<Enrollment>, i64), AppError> {202 ) -> Result<(Vec<Enrollment>, i64), AppError> {
215- PagedList::new("enrollment WHERE course = $course", "ORDER BY id DESC")203+ // The old composite key `{course}_{user}` sorted by user within a
216- .bind("course", course.record())204+ // course — its course prefix was constant — so the natural-PK columns
217- .run(limit, offset, db)205+ // sort the same way.
218- .await206+ 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
219 }213 }
220 214
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.
221 pub async fn remove(217 pub async fn remove(
222 db: &Database,218 db: &Database,
223 course: &CourseId,219 course: &CourseId,
224 user: &UserId,220 user: &UserId,
225 ) -> Result<Option<Enrollment>, AppError> {221 ) -> Result<Option<Enrollment>, AppError> {
226- // The seat comes back in the same transaction as the row that held it,222+ let gone = sqlx::query_as!(
227- // so nothing but a lost transaction can drift the counter.223+ Enrollment,
228- let mut result = db224+ r#"WITH gone AS (
229- .query(225+ DELETE FROM enrollment
230- "BEGIN TRANSACTION;226+ WHERE course = $1 AND app_user = $2
231- LET $gone = (DELETE enrollment WHERE course = $course AND user = $usr RETURN BEFORE);227+ RETURNING course, app_user, enrolled_by, source),
232- UPDATE $course SET enrollment_count = math::max([(enrollment_count ?? 0) - array::len($gone), 0]);228+ seated AS (
233- RETURN $gone;229+ UPDATE course
234- COMMIT TRANSACTION;",230+ SET enrollment_count = GREATEST(
235- )231+ enrollment_count - (SELECT count(*) FROM gone), 0)
236- .bind(("course", course.record()))232+ WHERE id = $1
237- .bind(("usr", user.record()))233+ RETURNING 1)
238- .await?234+ SELECT course, app_user AS "user", enrolled_by, source FROM gone"#,
239- .check()?;235+ course,
240- Ok(result.take::<Vec<Enrollment>>(3)?.into_iter().next())236+ user,
237+ )
238+ .fetch_optional(db)
239+ .await?;
240+ Ok(gone)
241 }241 }
242 242
243 #[cfg(test)]243 #[cfg(test)]
src/db/homework.rsmodified+403 -139
@@ -1,25 +1,22 @@
1-//! The `homework` table: row reads and listings, the count-and-create that1+//! The `homework` table: row reads and listings, the subject-counter claim
2-//! pins a homework to a live subject row, the reference-counting PATCH, and2+//! that pins a homework to a live subject row, the reference-counting PATCH —
3-//! the cascading delete. The PATCH's orphan guard and the audience gate live3+//! whose audience-narrowing orphan guard is one transaction with the write,
4-//! in [`crate::service::homework`].4+//! serialized on the homework row's `FOR UPDATE` lock — and the cascading
5+//! delete.
5 6
6-use surrealdb::types::RecordId;7+use crate::database::{Database, tx_with_retry};
7-
8-use crate::constant::SUBJECT_HOMEWORK_COUNT_FIELD;
9-use crate::database::Database;
10-use crate::db::cap;
11-use crate::db::field_update::FieldUpdate;
12 use crate::domain::course::CourseId;8 use crate::domain::course::CourseId;
13 use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};9 use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};
14 use crate::domain::subject::SubjectId;10 use crate::domain::subject::SubjectId;
15 use crate::domain::timestamp::Timestamp;11 use crate::domain::timestamp::Timestamp;
16 use crate::domain::user::UserId;12 use crate::domain::user::UserId;
17 use crate::error::{AppError, ValidationError};13 use crate::error::{AppError, ValidationError};
14+use sqlx::PgConnection;
18 15
19 /// The answer a link to a subject that is not there gets, on create and on16 /// 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 a17+/// re-tag alike — the conditional claim on the subject row matches nothing,
21-/// subject a delete already removed matches nothing and the caller says exactly18+/// and the caller says exactly what the web layer's pre-flight lookup would
22-/// what the web layer's pre-flight lookup would have.19+/// have.
23 fn subject_gone() -> AppError {20 fn subject_gone() -> AppError {
24 AppError::Validation(ValidationError::Invalid {21 AppError::Validation(ValidationError::Invalid {
25 field: "subject_id",22 field: "subject_id",
@@ -27,6 +24,12 @@ fn subject_gone() -> AppError {
27 })24 })
28 }25 }
29 26
27+/// What a stale re-tag answers. The shared PATCH builder
28+/// ([`crate::db::field_update`]) carries the same refusal; the homework PATCH
29+/// keeps its own copy because its orphan guard needs the row lock the generic
30+/// builder cannot take.
31+const STALE_MOVE: &str = "the link this update moves changed since it was read; re-read and retry";
32+
30 #[expect(33 #[expect(
31 clippy::too_many_arguments,34 clippy::too_many_arguments,
32 reason = "mirrors the sibling entities' create(field, field, ..) shape"35 reason = "mirrors the sibling entities' create(field, field, ..) shape"
@@ -41,16 +44,14 @@ pub async fn create(
41 assigned: Option<Vec<UserId>>,44 assigned: Option<Vec<UserId>>,
42 created_by: &UserId,45 created_by: &UserId,
43 ) -> Result<Homework, AppError> {46 ) -> Result<Homework, AppError> {
44- // The subject's reference is taken in the very transaction that writes47+ // The subject's reference is taken in the very statement that writes the
45- // the row — the exam question's twin48+ // row — the exam question's twin ([`crate::db::exam_question`]): the
46- // ([`crate::db::exam_question`]): the subject delete49+ // claim (`UPDATE subject … +1`) and the insert are one CTE, so a subject
47- // is refused while this counter is non-zero, so the create and the50+ // a delete already removed matches nothing and nothing is written, which
48- // delete contend on the subject record rather than on a cross-table51+ // is the 400 the web layer's pre-flight check answers with. The subject
49- // count neither of them sees the other move, and a crash can no longer52+ // delete is refused while this counter is non-zero, so the two writers
50- // strand a claim that would make the subject undeletable forever. A53+ // contend on the subject row itself, and a crash cannot strand a claim
51- // refused claim means the subject is already gone, which is the 400 the54+ // that would make the subject undeletable forever.
52- // web layer's pre-flight check answers with.
53- let counted = subject.record();
54 let homework = Homework {55 let homework = Homework {
55 id: HomeworkId::generate(),56 id: HomeworkId::generate(),
56 course: course.clone(),57 course: course.clone(),
@@ -62,46 +63,111 @@ pub async fn create(
62 created_by: created_by.clone(),63 created_by: created_by.clone(),
63 created_at: Timestamp::now(),64 created_at: Timestamp::now(),
64 };65 };
65- let id = homework.id.record();66+ let assigned_values = homework.assigned.clone().unwrap_or_default();
66- match cap::claim_and_create(67+ // The fresh v7 id cannot collide, so the pair-unique answer has no rival
67- &counted,68+ // here; the mapping is kept for symmetry with the other claim sites.
68- SUBJECT_HOMEWORK_COUNT_FIELD,69+ let created = sqlx::query_as!(
69- cap::UNLIMITED,70+ Homework,
70- &id,71+ r#"WITH seat AS (
71- &homework,72+ UPDATE subject SET homework_count = homework_count + 1
72- db,73+ WHERE id = $1
74+ RETURNING 1
75+ )
76+ INSERT INTO homework (id, course, subject, title, description, due_at, assigned, created_by, created_at)
77+ SELECT $2, $3, $1, $4, $5, $6, $7, $8, $9 WHERE EXISTS (SELECT 1 FROM seat)
78+ RETURNING id AS "id: HomeworkId",
79+ course AS "course: CourseId",
80+ subject AS "subject: SubjectId",
81+ title AS "title: HomeworkTitle",
82+ description AS "description: Option<HomeworkDescription>",
83+ due_at AS "due_at: Timestamp",
84+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
85+ AS "assigned: Option<Vec<UserId>>",
86+ created_by AS "created_by: UserId",
87+ created_at AS "created_at: Timestamp""#,
88+ subject,
89+ homework.id,
90+ course,
91+ homework.title,
92+ homework.description,
93+ homework.due_at,
94+ assigned_values,
95+ homework.created_by,
96+ homework.created_at,
73 )97 )
74- .await?98+ .fetch_optional(db)
75- {99+ .await
76- cap::Claimed::Made(created) => Ok(created),100+ .map_err(|err| {
77- cap::Claimed::Full => Err(subject_gone()),101+ if crate::database::unique_violation(&err).is_some() {
78- cap::Claimed::Duplicate => Err(AppError::Internal("failed to create homework".into())),102+ AppError::Internal("failed to create homework".into())
79- }103+ } else {
104+ AppError::from(err)
105+ }
106+ })?;
107+ created.ok_or_else(subject_gone)
80 }108 }
81 109
82 pub async fn read(db: &Database, id: &HomeworkId) -> Result<Option<Homework>, AppError> {110 pub async fn read(db: &Database, id: &HomeworkId) -> Result<Option<Homework>, AppError> {
83- Ok(db.select(id.record()).await?)111+ Ok(sqlx::query_as!(
112+ Homework,
113+ r#"SELECT id AS "id: HomeworkId",
114+ course AS "course: CourseId",
115+ subject AS "subject: SubjectId",
116+ title AS "title: HomeworkTitle",
117+ description AS "description: Option<HomeworkDescription>",
118+ due_at AS "due_at: Timestamp",
119+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
120+ AS "assigned: Option<Vec<UserId>>",
121+ created_by AS "created_by: UserId",
122+ created_at AS "created_at: Timestamp"
123+ FROM homework WHERE id = $1"#,
124+ id
125+ )
126+ .fetch_optional(db)
127+ .await?)
84 }128 }
85 129
86-/// The course's homework, newest first (ULID ids sort by creation). The web130+/// The course's homework, newest first (v7 ids sort by creation). The web
87 /// layer retains only the rows a given student `student_sees`.131 /// layer retains only the rows a given student `student_sees`.
88 pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Homework>, AppError> {132 pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Homework>, AppError> {
89- let mut result = db133+ Ok(sqlx::query_as!(
90- .query("SELECT * FROM homework WHERE course = $course ORDER BY id DESC")134+ Homework,
91- .bind(("course", course.record()))135+ r#"SELECT id AS "id: HomeworkId",
92- .await?136+ course AS "course: CourseId",
93- .check()?;137+ subject AS "subject: SubjectId",
94- Ok(result.take::<Vec<Homework>>(0)?)138+ title AS "title: HomeworkTitle",
139+ description AS "description: Option<HomeworkDescription>",
140+ due_at AS "due_at: Timestamp",
141+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
142+ AS "assigned: Option<Vec<UserId>>",
143+ created_by AS "created_by: UserId",
144+ created_at AS "created_at: Timestamp"
145+ FROM homework WHERE course = $1 ORDER BY id DESC"#,
146+ course
147+ )
148+ .fetch_all(db)
149+ .await?)
95 }150 }
96 151
97 /// Every homework in the system, newest first — the manager+ view of the152 /// Every homework in the system, newest first — the manager+ view of the
98 /// cross-course "my homework" list.153 /// cross-course "my homework" list.
99 pub async fn list_all(db: &Database) -> Result<Vec<Homework>, AppError> {154 pub async fn list_all(db: &Database) -> Result<Vec<Homework>, AppError> {
100- let mut result = db155+ Ok(sqlx::query_as!(
101- .query("SELECT * FROM homework ORDER BY id DESC")156+ Homework,
102- .await?157+ r#"SELECT id AS "id: HomeworkId",
103- .check()?;158+ course AS "course: CourseId",
104- Ok(result.take::<Vec<Homework>>(0)?)159+ subject AS "subject: SubjectId",
160+ title AS "title: HomeworkTitle",
161+ description AS "description: Option<HomeworkDescription>",
162+ due_at AS "due_at: Timestamp",
163+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
164+ AS "assigned: Option<Vec<UserId>>",
165+ created_by AS "created_by: UserId",
166+ created_at AS "created_at: Timestamp"
167+ FROM homework ORDER BY id DESC"#,
168+ )
169+ .fetch_all(db)
170+ .await?)
105 }171 }
106 172
107 /// Every homework of every course in `courses`, newest first (one query) —173 /// Every homework of every course in `courses`, newest first (one query) —
@@ -115,51 +181,71 @@ pub async fn list_for_courses(
115 if courses.is_empty() {181 if courses.is_empty() {
116 return Ok(Vec::new());182 return Ok(Vec::new());
117 }183 }
118- let records: Vec<RecordId> = courses.iter().map(CourseId::record).collect();184+ let ids: Vec<CourseId> = courses.to_vec();
119- let mut result = db185+ Ok(sqlx::query_as!(
120- .query("SELECT * FROM homework WHERE course IN $courses ORDER BY id DESC")186+ Homework,
121- .bind(("courses", records))187+ r#"SELECT id AS "id: HomeworkId",
122- .await?188+ course AS "course: CourseId",
123- .check()?;189+ subject AS "subject: SubjectId",
124- Ok(result.take::<Vec<Homework>>(0)?)190+ title AS "title: HomeworkTitle",
191+ description AS "description: Option<HomeworkDescription>",
192+ due_at AS "due_at: Timestamp",
193+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
194+ AS "assigned: Option<Vec<UserId>>",
195+ created_by AS "created_by: UserId",
196+ created_at AS "created_at: Timestamp"
197+ FROM homework WHERE course = ANY($1) ORDER BY id DESC"#,
198+ ids
199+ )
200+ .fetch_all(db)
201+ .await?)
125 }202 }
126 203
127 /// The homework of `course` that `user` is meant to see — whole-course ones204 /// The homework of `course` that `user` is meant to see — whole-course ones
128 /// plus any subset that names them — newest first. Backs a student's (or an205 /// plus any subset that names them — newest first. Backs a student's (or an
129 /// observer's) per-course homework report; mirrors206 /// observer's) per-course homework report; mirrors
130 /// [`Homework::student_sees`](crate::domain::homework::Homework::student_sees)207 /// [`Homework::student_sees`](crate::domain::homework::Homework::student_sees)
131-/// in SurQL so the filter runs in the database.208+/// in SQL so the filter runs in the database.
132 pub async fn list_for_user_in_course(209 pub async fn list_for_user_in_course(
133 db: &Database,210 db: &Database,
134 course: &CourseId,211 course: &CourseId,
135 user: &UserId,212 user: &UserId,
136 ) -> Result<Vec<Homework>, AppError> {213 ) -> Result<Vec<Homework>, AppError> {
137- let mut result = db214+ Ok(sqlx::query_as!(
138- .query(215+ Homework,
139- "SELECT * FROM homework216+ r#"SELECT id AS "id: HomeworkId",
140- WHERE course = $course217+ course AS "course: CourseId",
141- AND (assigned = NONE OR assigned = [] OR $usr IN assigned)218+ subject AS "subject: SubjectId",
142- ORDER BY id DESC",219+ title AS "title: HomeworkTitle",
143- )220+ description AS "description: Option<HomeworkDescription>",
144- .bind(("course", course.record()))221+ due_at AS "due_at: Timestamp",
145- .bind(("usr", user.record()))222+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
146- .await?223+ AS "assigned: Option<Vec<UserId>>",
147- .check()?;224+ created_by AS "created_by: UserId",
148- Ok(result.take::<Vec<Homework>>(0)?)225+ created_at AS "created_at: Timestamp"
226+ FROM homework
227+ WHERE course = $1 AND (cardinality(assigned) = 0 OR $2 = ANY(assigned))
228+ ORDER BY id DESC"#,
229+ course,
230+ user
231+ )
232+ .fetch_all(db)
233+ .await?)
149 }234 }
150 235
151 /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework.236 /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework.
152 /// Request-scoped: every parameter is `Option`, `None` meaning the PATCH237 /// Request-scoped: every parameter is `Option`, `None` meaning the PATCH
153 /// did not carry that field, so it is not written at all. Handing the238 /// did not carry that field, so it is not written at all. Handing the
154 /// snapshot's value back instead would revert a concurrent edit of that239 /// snapshot's value back instead would revert a concurrent edit of that
155-/// field — scoping the `SET` alone does not prevent that, the *values* must240+/// field — under the row lock below, an uncarried field keeps the value read
156-/// come from the request. `course`, `created_by`, and `created_at` are241+/// *under that lock*, never the handler's snapshot. `course`, `created_by`,
157-/// `READONLY` and never appear in the write.242+/// and `created_at` are readonly and never appear in the write.
158 ///243 ///
159-/// `description` and `assigned` are nullable columns, so they take a244+/// `description` takes `Some(None)` to clear; `assigned` takes `Some(None)`
160-/// `NONE` (clear the description / widen back to the whole course). The web245+/// to widen back to the whole course (stored as `'{}'`, read back as `None`).
161-/// layer has already re-checked a new `due_at` against now, a new `subject`246+/// The web layer has already re-checked a new `due_at` against now, a new
162-/// against the course, and refused a narrowing that would orphan work.247+/// `subject` against the course, and — inside the transaction here — the
248+/// narrowing against the work that would be orphaned by it.
163 pub async fn update(249 pub async fn update(
164 db: &Database,250 db: &Database,
165 homework: Homework,251 homework: Homework,
@@ -169,75 +255,250 @@ pub async fn update(
169 due_at: Option<Timestamp>,255 due_at: Option<Timestamp>,
170 assigned: Option<Option<Vec<UserId>>>,256 assigned: Option<Option<Vec<UserId>>>,
171 ) -> Result<Homework, AppError> {257 ) -> Result<Homework, AppError> {
172- let assigned = assigned258+ tx_with_retry(db, false, async |tx| {
173- .map(|subset| subset.map(|users| users.iter().map(UserId::record).collect::<Vec<_>>()));259+ // The homework row's lock. The orphan guard's reads and the write
174- // A re-tag moves a reference: the new subject's claim and the old one's260+ // below are one transaction with it, so a submission — whose own
175- // release ride the same transaction as the link write, so no crash can261+ // transaction locks this very row before writing — cannot land
176- // leave a count without its link (the subject would be undeletable262+ // between the check and the narrowing, orphaned by an audience change
177- // forever) or a link without its count. `subject` is required, so the263+ // that just missed it. The lock also replaces the old CAS's row read:
178- // snapshot's value is always the CAS expectation — two PATCHes moving264+ // the re-tag check below compares the handler's snapshot against the
179- // the same homework off the same subject would otherwise both claim265+ // row as it is *locked*, not as it was first read.
180- // their target, and the loser is refused with a 409 instead. The266+ let current = sqlx::query_as!(
181- // `.refcount` call is unconditional: the CAS is armed by the request267+ Homework,
182- // *carrying* `subject_id`, not by a counter moving, so a PATCH that268+ r#"SELECT id AS "id: HomeworkId",
183- // re-states the tag its snapshot showed — shifting no counter at all —269+ course AS "course: CourseId",
184- // is still refused when a rival moved the tag in between. A PATCH that270+ subject AS "subject: SubjectId",
185- // carried no `subject_id` arms nothing and writes what it always did.271+ title AS "title: HomeworkTitle",
186- let (claim, release) = subject272+ description AS "description: Option<HomeworkDescription>",
187- .as_ref()273+ due_at AS "due_at: Timestamp",
188- .filter(|next| **next != homework.subject)274+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
189- .map(|next| (next.record(), homework.subject.record()))275+ AS "assigned: Option<Vec<UserId>>",
190- .unzip();276+ created_by AS "created_by: UserId",
191- FieldUpdate::new(homework.id.record())277+ created_at AS "created_at: Timestamp"
192- .set("subject", subject.map(|subject| subject.record()))278+ FROM homework WHERE id = $1 FOR UPDATE"#,
193- .set("title", title)279+ homework.get_id()
194- .set("description", description)
195- .set("due_at", due_at)
196- .set("assigned", assigned)
197- .refcount(
198- SUBJECT_HOMEWORK_COUNT_FIELD,
199- "subject",
200- Some(homework.subject.record()),
201- claim,
202- release,
203- subject_gone(),
204 )280 )
205- .run::<Homework>(db)281+ .fetch_optional(&mut *tx)
206- .await282+ .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+ }
207 }430 }
208 431
209 /// Delete the homework and cascade its submissions, their files, and its432 /// Delete the homework and cascade its submissions, their files, and its
210 /// results — one transaction, so a crash can't orphan a submission under a433 /// results — one transaction, so a crash can't orphan a submission under a
211 /// vanished homework. The submission file *blobs* are the web layer's to434 /// vanished homework. The submission file *blobs* are the web layer's to
212-/// unlink: it collects their names via435+/// unlink: their names are returned (collected inside the transaction,
213-/// [`crate::db::homework_file::file_keys_for_homework`]436+/// before the wipes — a file row inserted after an out-of-transaction
214-/// before calling this, and removes them after the rows are gone.437+/// collection would be deleted here while its key was already gone from the
215-pub async fn delete(db: &Database, homework: Homework) -> Result<Homework, AppError> {438+/// list, stranding the blob) and removed after the rows are gone.
216- let mut result = db439+pub async fn delete(
217- .query(440+ db: &Database,
218- format!(441+ homework: Homework,
219- "BEGIN TRANSACTION;442+) -> Result<(Homework, Vec<String>), AppError> {
220- DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw);443+ tx_with_retry(db, true, async |tx| {
221- DELETE homework_submission WHERE homework = $hw;444+ let blob_keys: Vec<String> = sqlx::query!(
222- DELETE homework_result WHERE homework = $hw;445+ r#"SELECT file FROM homework_file
223- LET $gone = (DELETE $hw RETURN BEFORE);446+ WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#,
224- FOR $sub IN ($gone.subject ?? []) {{447+ homework.get_id()
225- UPDATE $sub SET {SUBJECT_HOMEWORK_COUNT_FIELD} =
226- math::max([({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) - 1, 0])
227- }};
228- RETURN $gone;
229- COMMIT TRANSACTION;"
230- ),
231 )448 )
232- .bind(("hw", homework.id.record()))449+ .fetch_all(&mut *tx)
233 .await?450 .await?
234- .check()?;451+ .into_iter()
235- // The subject's reference is given back in this same transaction, off452+ .map(|row| row.file)
236- // what the delete actually removed. Read through the trailing `RETURN`,453+ .collect();
237- // not a hand-counted slot — see [`crate::db::exam::delete`].454+ sqlx::query!(
238- let slot = result.num_statements().saturating_sub(2);455+ r#"DELETE FROM homework_file
239- let deleted: Option<Homework> = result.take::<Vec<Homework>>(slot)?.into_iter().next();456+ WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#,
240- deleted.ok_or(AppError::NotFound)457+ homework.get_id()
458+ )
459+ .execute(&mut *tx)
460+ .await?;
461+ sqlx::query!(
462+ "DELETE FROM homework_result WHERE homework = $1",
463+ homework.get_id()
464+ )
465+ .execute(&mut *tx)
466+ .await?;
467+ sqlx::query!(
468+ "DELETE FROM homework_submission WHERE homework = $1",
469+ homework.get_id()
470+ )
471+ .execute(&mut *tx)
472+ .await?;
473+ let deleted = sqlx::query_as!(
474+ Homework,
475+ r#"DELETE FROM homework WHERE id = $1
476+ RETURNING id AS "id: HomeworkId",
477+ course AS "course: CourseId",
478+ subject AS "subject: SubjectId",
479+ title AS "title: HomeworkTitle",
480+ description AS "description: Option<HomeworkDescription>",
481+ due_at AS "due_at: Timestamp",
482+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
483+ AS "assigned: Option<Vec<UserId>>",
484+ created_by AS "created_by: UserId",
485+ created_at AS "created_at: Timestamp""#,
486+ homework.get_id()
487+ )
488+ .fetch_optional(&mut *tx)
489+ .await?
490+ .ok_or(AppError::NotFound)?;
491+ // The subject's reference is given back in this same transaction, off
492+ // the row the delete actually removed.
493+ sqlx::query!(
494+ "UPDATE subject SET homework_count = GREATEST(homework_count - 1, 0) WHERE id = $1",
495+ deleted.subject
496+ )
497+ .execute(&mut *tx)
498+ .await?;
499+ Ok((deleted, blob_keys))
500+ })
501+ .await
241 }502 }
242 503
243 #[cfg(test)]504 #[cfg(test)]
@@ -360,7 +621,10 @@ mod tests {
360 "the old subject is free"621 "the old subject is free"
361 );622 );
362 assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not");623 assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not");
363- assert!(crate::db::subject::delete(&db, from).await.is_ok(), "no reference left");624+ assert!(
625+ crate::db::subject::delete(&db, from).await.is_ok(),
626+ "no reference left"
627+ );
364 assert!(628 assert!(
365 crate::db::subject::delete(&db, to).await.is_err(),629 crate::db::subject::delete(&db, to).await.is_err(),
366 "the reference moved here refuses the delete"630 "the reference moved here refuses the delete"
src/db/homework_file.rsmodified+183 -133
@@ -4,56 +4,70 @@
4 //! their validated fields live in [`crate::domain::homework_file`]; the4 //! their validated fields live in [`crate::domain::homework_file`]; the
5 //! upload workflow around them in [`crate::service::homework_file`].5 //! upload workflow around them in [`crate::service::homework_file`].
6 6
7-use surrealdb::types::SurrealValue;7+use crate::constant::MAX_HOMEWORK_FILES_PER_SUBMISSION;
8-8+use crate::database::{Database, tx_with_retry};
9-use crate::constant::{
10- MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD, SUBMISSION_OPEN_GUARD,
11-};
12-use crate::database::{Database, transaction_with_retry};
13-use crate::db::cap;
14 use crate::domain::course::CourseId;9 use crate::domain::course::CourseId;
15 use crate::domain::homework::HomeworkId;10 use crate::domain::homework::HomeworkId;
16 use crate::domain::homework_file::HomeworkFile;11 use crate::domain::homework_file::HomeworkFile;
12+use crate::domain::homework_file::HomeworkFileId;
13+use crate::domain::homework_submission::HomeworkSubmissionId;
14+use crate::domain::note_file::{FileContentType, FileName};
17 use crate::domain::timestamp::Timestamp;15 use crate::domain::timestamp::Timestamp;
18 use crate::error::AppError;16 use crate::error::AppError;
19 17
20-/// What [`delete`]'s transaction reports: whether the submission
21-/// was still open (`open` = 1, the gate bit) and the row it then removed. Two
22-/// answers in one object because an empty `gone` alone cannot say whether the
23-/// delete was refused or the file had simply vanished.
24-#[derive(Debug, SurrealValue)]
25-struct DeleteOutcome {
26- open: i64,
27- gone: Vec<HomeworkFile>,
28-}
29-
30 /// Persist the row assembled by18 /// Persist the row assembled by
31 /// [`HomeworkFile::new`](crate::domain::homework_file::HomeworkFile::new),19 /// [`HomeworkFile::new`](crate::domain::homework_file::HomeworkFile::new),
32 /// refusing once its submission already holds20 /// refusing once its submission already holds
33 /// [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`)21 /// [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`)
34 /// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own22 /// 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 the23+/// wording). Both are decided by one guarded insert on the submission row —
36-/// submission row — the seat and the file row commit together, so a crash24+/// the seat (`UPDATE … file_count + 1 WHERE file_count < $cap AND
37-/// between them can no longer leave a slot claimed by a file that does not25+/// graded_by_result IS NULL`) and the file row commit together in one CTE, so
38-/// exist, and a losing upload never has to be un-counted. Which of the two26+/// a crash between them can no longer leave a slot claimed by a file that
39-/// conditions refused it is read back afterwards, off the losing path only,27+/// does not exist, and a losing upload never has to be un-counted. Which of
40-/// and only to pick the message: `Claimed::Full` says "full *or* graded *or*28+/// the two conditions refused it is read back afterwards, off the losing
41-/// the submission is gone".29+/// path only, and only to pick the message: zero rows says "full *or* graded
30+/// *or* the submission is gone".
42 pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> {31 pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> {
43- // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber32+ let created = sqlx::query_as!(
44- match cap::claim_when_and_create(33+ HomeworkFile,
45- &file.submission.record(),34+ r#"WITH seat AS (
46- SUBMISSION_FILE_COUNT_FIELD,35+ UPDATE homework_submission SET file_count = file_count + 1
36+ WHERE id = $2 AND file_count < $1 AND graded_by_result IS NULL
37+ RETURNING 1
38+ )
39+ INSERT INTO homework_file (id, submission, name, content_type, size, file, created_at)
40+ SELECT $3, $2, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat)
41+ RETURNING id AS "id: HomeworkFileId",
42+ submission AS "submission: HomeworkSubmissionId",
43+ name AS "name: FileName",
44+ content_type AS "content_type: FileContentType",
45+ size,
46+ file,
47+ created_at AS "created_at: Timestamp""#,
47 MAX_HOMEWORK_FILES_PER_SUBMISSION as i64,48 MAX_HOMEWORK_FILES_PER_SUBMISSION as i64,
48- SUBMISSION_OPEN_GUARD,49+ file.submission,
49- &file.id.record(),50+ file.id,
50- &file,51+ file.name,
51- db,52+ file.content_type,
53+ file.size,
54+ file.file,
55+ file.created_at,
52 )56 )
53- .await?57+ .fetch_optional(db)
54- {58+ .await
55- cap::Claimed::Made(created) => Ok(Some(created)),59+ .map_err(|err| {
56- cap::Claimed::Full => {60+ // The id is a fresh v7 minted by `new`, so a row already holding it
61+ // is a collision, not a re-upload.
62+ if crate::database::unique_violation(&err).is_some() {
63+ AppError::Internal("homework file id collided".into())
64+ } else {
65+ AppError::from(err)
66+ }
67+ })?;
68+ match created {
69+ Some(row) => Ok(Some(row)),
70+ None => {
57 if super::homework_submission::is_graded(db, &file.submission).await? {71 if super::homework_submission::is_graded(db, &file.submission).await? {
58 return Ok(None);72 return Ok(None);
59 }73 }
@@ -61,9 +75,6 @@ pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<Homework
61 "the submission already holds the maximum of 10 files — delete one first",75 "the submission already holds the maximum of 10 files — delete one first",
62 ))76 ))
63 }77 }
64- // The id is a fresh ULID minted by `new`, so a row already holding it
65- // is a collision, not a re-upload.
66- cap::Claimed::Duplicate => Err(AppError::Internal("homework file id collided".into())),
67 }78 }
68 }79 }
69 80
@@ -74,8 +85,21 @@ pub async fn read_for(
74 id: &crate::domain::homework_file::HomeworkFileId,85 id: &crate::domain::homework_file::HomeworkFileId,
75 submission: &crate::domain::homework_submission::HomeworkSubmissionId,86 submission: &crate::domain::homework_submission::HomeworkSubmissionId,
76 ) -> Result<Option<HomeworkFile>, AppError> {87 ) -> Result<Option<HomeworkFile>, AppError> {
77- let file: Option<HomeworkFile> = db.select(id.record()).await?;88+ Ok(sqlx::query_as!(
78- Ok(file.filter(|file| &file.submission == submission))89+ HomeworkFile,
90+ r#"SELECT id AS "id: HomeworkFileId",
91+ submission AS "submission: HomeworkSubmissionId",
92+ name AS "name: FileName",
93+ content_type AS "content_type: FileContentType",
94+ size,
95+ file,
96+ created_at AS "created_at: Timestamp"
97+ FROM homework_file WHERE id = $1 AND submission = $2"#,
98+ id,
99+ submission
100+ )
101+ .fetch_optional(db)
102+ .await?)
79 }103 }
80 104
81 /// Read a file by id only if it hangs off a submission to `homework` — the105 /// Read a file by id only if it hangs off a submission to `homework` — the
@@ -89,16 +113,23 @@ pub async fn read_in_homework(
89 id: &crate::domain::homework_file::HomeworkFileId,113 id: &crate::domain::homework_file::HomeworkFileId,
90 homework: &HomeworkId,114 homework: &HomeworkId,
91 ) -> Result<Option<HomeworkFile>, AppError> {115 ) -> Result<Option<HomeworkFile>, AppError> {
92- let mut result = db116+ Ok(sqlx::query_as!(
93- .query(117+ HomeworkFile,
94- "SELECT * FROM homework_file WHERE id = $id AND submission IN \118+ r#"SELECT id AS "id: HomeworkFileId",
95- (SELECT VALUE id FROM homework_submission WHERE homework = $hw)",119+ submission AS "submission: HomeworkSubmissionId",
96- )120+ name AS "name: FileName",
97- .bind(("id", id.record()))121+ content_type AS "content_type: FileContentType",
98- .bind(("hw", homework.record()))122+ size,
99- .await?123+ file,
100- .check()?;124+ created_at AS "created_at: Timestamp"
101- Ok(result.take::<Vec<HomeworkFile>>(0)?.into_iter().next())125+ FROM homework_file
126+ WHERE id = $1
127+ AND submission IN (SELECT id FROM homework_submission WHERE homework = $2)"#,
128+ id,
129+ homework
130+ )
131+ .fetch_optional(db)
132+ .await?)
102 }133 }
103 134
104 /// All of `submission`'s files, newest first.135 /// All of `submission`'s files, newest first.
@@ -106,40 +137,56 @@ pub async fn list_for_submission(
106 db: &Database,137 db: &Database,
107 submission: &crate::domain::homework_submission::HomeworkSubmissionId,138 submission: &crate::domain::homework_submission::HomeworkSubmissionId,
108 ) -> Result<Vec<HomeworkFile>, AppError> {139 ) -> Result<Vec<HomeworkFile>, AppError> {
109- let mut result = db140+ Ok(sqlx::query_as!(
110- .query("SELECT * FROM homework_file WHERE submission = $sub ORDER BY id DESC")141+ HomeworkFile,
111- .bind(("sub", submission.record()))142+ r#"SELECT id AS "id: HomeworkFileId",
112- .await?143+ submission AS "submission: HomeworkSubmissionId",
113- .check()?;144+ name AS "name: FileName",
114- Ok(result.take::<Vec<HomeworkFile>>(0)?)145+ content_type AS "content_type: FileContentType",
146+ size,
147+ file,
148+ created_at AS "created_at: Timestamp"
149+ FROM homework_file WHERE submission = $1 ORDER BY id DESC"#,
150+ submission
151+ )
152+ .fetch_all(db)
153+ .await?)
115 }154 }
116 155
117-/// How many files `submission` holds — the cap check reads this under the156+/// How many files `submission` holds. Counting the rows (not the counter
118-/// lock. Counting via the rows (not a `count()` query) keeps it identical157+/// column) keeps it identical to `NoteFile`'s proven cap check; at a ceiling
119-/// to `NoteFile`'s proven cap check; at a ceiling of 10 the cost is nil.158+/// of 10 the cost is nil.
120 pub async fn count_for_submission(159 pub async fn count_for_submission(
121 db: &Database,160 db: &Database,
122 submission: &crate::domain::homework_submission::HomeworkSubmissionId,161 submission: &crate::domain::homework_submission::HomeworkSubmissionId,
123 ) -> Result<usize, AppError> {162 ) -> Result<usize, AppError> {
124- Ok(list_for_submission(db, submission).await?.len())163+ let row = sqlx::query!(
164+ r#"SELECT count(*) AS "count: i64" FROM homework_file WHERE submission = $1"#,
165+ submission
166+ )
167+ .fetch_one(db)
168+ .await?;
169+ Ok(row.count as usize)
125 }170 }
126 171
127 /// The blob names behind every file of every submission to `homework` —172 /// The blob names behind every file of every submission to `homework` —
128-/// collected *before* the homework-delete cascade wipes the rows, so the173+/// the GC keys of a homework delete (collected inside the delete's own
129-/// web layer can unlink them once the rows are gone.174+/// transaction by [`crate::db::homework::delete`]; this read backs it and
175+/// the tests).
130 pub async fn file_keys_for_homework(176 pub async fn file_keys_for_homework(
131 db: &Database,177 db: &Database,
132 homework: &HomeworkId,178 homework: &HomeworkId,
133 ) -> Result<Vec<String>, AppError> {179 ) -> Result<Vec<String>, AppError> {
134- let mut result = db180+ Ok(sqlx::query!(
135- .query(181+ r#"SELECT file FROM homework_file
136- "SELECT VALUE file FROM homework_file \182+ WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#,
137- WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw)",183+ homework
138- )184+ )
139- .bind(("hw", homework.record()))185+ .fetch_all(db)
140- .await?186+ .await?
141- .check()?;187+ .into_iter()
142- Ok(result.take::<Vec<String>>(0)?)188+ .map(|row| row.file)
189+ .collect())
143 }190 }
144 191
145 /// The blob names behind every homework file of `course` — collected192 /// The blob names behind every homework file of `course` — collected
@@ -148,17 +195,19 @@ pub async fn file_keys_for_course(
148 db: &Database,195 db: &Database,
149 course: &CourseId,196 course: &CourseId,
150 ) -> Result<Vec<String>, AppError> {197 ) -> Result<Vec<String>, AppError> {
151- let mut result = db198+ Ok(sqlx::query!(
152- .query(199+ r#"SELECT file FROM homework_file
153- "SELECT VALUE file FROM homework_file WHERE submission IN ( \200+ WHERE submission IN (
154- SELECT VALUE id FROM homework_submission \201+ SELECT id FROM homework_submission
155- WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course) \202+ WHERE homework IN (SELECT id FROM homework WHERE course = $1)
156- )",203+ )"#,
157- )204+ course
158- .bind(("course", course.record()))205+ )
159- .await?206+ .fetch_all(db)
160- .check()?;207+ .await?
161- Ok(result.take::<Vec<String>>(0)?)208+ .into_iter()
209+ .map(|row| row.file)
210+ .collect())
162 }211 }
163 212
164 /// Delete the row and give its slot back in the same transaction. The213 /// Delete the row and give its slot back in the same transaction. The
@@ -167,57 +216,58 @@ pub async fn file_keys_for_course(
167 ///216 ///
168 /// The gate is the first statement: a conditional write on the *submission*217 /// The gate is the first statement: a conditional write on the *submission*
169 /// row — the "last touched" re-stamp a file delete owes the late flag218 /// row — the "last touched" re-stamp a file delete owes the late flag
170-/// anyway — carrying [`SUBMISSION_OPEN_GUARD`]. Nothing else in the219+/// anyway. Its row lock is also the serialization point against an upload's
171-/// transaction runs unless it bit, so a grade landing concurrently either220+/// seat claim on the same row: one of the two waits, and the winner re-reads
172-/// stamps first (this delete is refused, `Ok(None)`) or stamps after (the221+/// the counter before moving it, so no lost round and no 500 — a grade
173-/// file was already gone when it graded). `Err(NotFound)` still means the222+/// landing concurrently either stamps first (this delete is refused,
174-/// file row itself had vanished.223+/// `Ok(None)`) or stamps after (the file was already gone when it graded).
175-///224+/// `Err(NotFound)` still means the file row itself had vanished.
176-/// Sound to re-send while the store answers "conflict, retry", and it has
177-/// to be: the gate writes the *submission* row, the very record an upload's
178-/// [`insert`] claims its seat on, and both handlers hold only
179-/// `HOMEWORK_LOCK.read()` — so a concurrent add and delete of two files of
180-/// one submission contend by design, and a lost round used to come back as
181-/// a 500 on a request that had written nothing. Only `UPDATE` and `DELETE`
182-/// are in the batch, and neither can legitimately answer "already exists",
183-/// which is what makes the whole of it re-sendable.
184 pub async fn delete(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> {225 pub async fn delete(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> {
185- let (mut result, mut errors) = transaction_with_retry(226+ let now = Timestamp::now();
186- db,227+ tx_with_retry(db, false, async |tx| {
187- &format!(228+ let open = sqlx::query!(
188- "BEGIN TRANSACTION;229+ r#"UPDATE homework_submission SET updated_at = $2
189- LET $open = (UPDATE $sub SET updated_at = $now \230+ WHERE id = $1 AND graded_by_result IS NULL
190- WHERE {SUBMISSION_OPEN_GUARD} RETURN VALUE id);231+ RETURNING 1 AS "open: i32""#,
191- LET $gone = IF array::len($open) > 0 {{ (DELETE $id RETURN BEFORE) }} ELSE {{ [] }};232+ file.submission,
192- UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]);233+ now
193- RETURN {{ open: array::len($open), gone: $gone }};234+ )
194- COMMIT TRANSACTION;"235+ .fetch_optional(&mut *tx)
195- ),236+ .await?;
196- &[237+ if open.is_none() {
197- ("id".into(), file.id.record().into_value()),238+ return Ok(None);
198- ("sub".into(), file.submission.record().into_value()),239+ }
199- ("now".into(), Timestamp::now().into_value()),240+ let gone = sqlx::query_as!(
200- ],241+ HomeworkFile,
201- &[],242+ r#"DELETE FROM homework_file WHERE id = $1 AND submission = $2
202- )243+ RETURNING id AS "id: HomeworkFileId",
203- .await?;244+ submission AS "submission: HomeworkSubmissionId",
204- if let Some(error) = errors.drain().map(|(_, error)| error).next() {245+ name AS "name: FileName",
205- return Err(error.into());246+ content_type AS "content_type: FileContentType",
206- }247+ size,
207- // BEGIN is slot 0, the two LETs slots 1-2 and the counter fix slot 3;248+ file,
208- // the RETURN is slot 4.249+ created_at AS "created_at: Timestamp""#,
209- let outcome: Option<DeleteOutcome> = result.take::<Vec<DeleteOutcome>>(4)?.into_iter().next();250+ file.id,
210- let outcome =251+ file.submission
211- outcome.ok_or_else(|| AppError::Internal("failed to delete homework file".into()))?;252+ )
212- if outcome.open == 0 {253+ .fetch_optional(&mut *tx)
213- return Ok(None);254+ .await?;
214- }255+ match gone {
215- outcome256+ Some(row) => {
216- .gone257+ sqlx::query!(
217- .into_iter()258+ "UPDATE homework_submission SET file_count = GREATEST(file_count - 1, 0)
218- .next()259+ WHERE id = $1",
219- .map(Some)260+ file.submission
220- .ok_or(AppError::NotFound)261+ )
262+ .execute(&mut *tx)
263+ .await?;
264+ Ok(Some(row))
265+ }
266+ // The submission was open but the file had already vanished.
267+ None => Err(AppError::NotFound),
268+ }
269+ })
270+ .await
221 }271 }
222 272
223 #[cfg(test)]273 #[cfg(test)]
src/db/homework_result.rsmodified+206 -188
@@ -5,48 +5,51 @@
5 //! validated status and mark types in5 //! validated status and mark types in
6 //! [`crate::domain::homework_result`].6 //! [`crate::domain::homework_result`].
7 7
8-use crate::constant::{MARKS_GIVEN_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD};8+use crate::database::{Database, tx_with_retry};
9-use crate::database::{Database, transaction_with_retry};
10 use crate::domain::course::CourseId;9 use crate::domain::course::CourseId;
11 use crate::domain::exam_result::Mark;10 use crate::domain::exam_result::Mark;
12 use crate::domain::homework::HomeworkId;11 use crate::domain::homework::HomeworkId;
13 use crate::domain::homework_result::{HomeworkResult, HomeworkResultId, HomeworkStatus};12 use crate::domain::homework_result::{HomeworkResult, HomeworkResultId, HomeworkStatus};
14-use crate::domain::homework_submission::HomeworkSubmissionId;
15 use crate::domain::timestamp::Timestamp;13 use crate::domain::timestamp::Timestamp;
16 use crate::domain::user::UserId;14 use crate::domain::user::UserId;
17 use crate::error::AppError;15 use crate::error::AppError;
18-use surrealdb::types::SurrealValue;
19 16
20-/// Record (or overwrite) the grade for (homework, user). One row per pair,17+/// Record (or overwrite) the grade for (homework, user). One row per pair by
21-/// keyed by the deterministic composite id, so this is a single atomic18+/// the pair's UNIQUE constraint, so grading is one atomic UPSERT —
22-/// UPSERT — concurrent grades for the same pair converge on one row instead19+/// concurrent grades for the same pair converge on one row instead of
23-/// of racing a unique index into a 500. Grading before the due date, or20+/// racing a duplicate into a 500. Grading before the due date, or before any
24-/// before any submission exists, is allowed (the caller's policy call).21+/// submission exists, is allowed (the caller's policy call).
25 ///22 ///
26 /// In the same transaction the grade *stamps* the student's submission23 /// In the same transaction the grade *stamps* the student's submission
27-/// ([`crate::constant::SUBMISSION_GRADED_FIELD`]), which is what freezes it:24+/// (`graded_by_result`), which is what freezes it: every student-side write
28-/// every student-side write to that row then fails its own25+/// to that row then fails its own `graded_by_result IS NULL` condition, with
29-/// `graded_by_result = NONE` condition, with no cross-table read for a26+/// no cross-table read for a concurrent write to slip past. A submission
30-/// concurrent write to slip past. A submission that does not exist yet is27+/// that does not exist yet is left alone — grading absent work must not
31-/// left alone — grading absent work must not conjure a hand-in (the report reads28+/// conjure a hand-in (the report reads `submitted`/`missing`/`late` straight
32-/// `submitted`/`missing`/`late` straight off that row).29+/// off that row).
33 ///30 ///
34-/// That one case is where this function stops defending itself: a student's31+/// That one case is where this statement stops defending itself: a student's
35 /// *first* hand-in committing between this grade and nothing-to-stamp would32 /// *first* hand-in committing between this grade and nothing-to-stamp would
36-/// land unstamped, leaving a grade beside an editable submission. Nothing33+/// land unstamped, leaving a grade beside an editable submission. What
37-/// here forbids it — what forbids it is the caller. Grading holds34+/// forbids it here is the homework row's lock: every student-side write
38-/// `HOMEWORK_LOCK` (see [`crate::service::homework`]) for writing across this35+/// locks the homework row across its write, and so does this transaction, so
39-/// whole transaction while every student-side write holds it for reading across36+/// the interleaving is ordered away instead of leased away — either the
40-/// its own, and the two leases are mutually exclusive in the one process37+/// grade saw the row to stamp, or the submission saw no grade and created
41-/// this backend runs as, so the interleaving never gets a window.38+/// under a lock this transaction already held.
42-//39+///
43-// corner-cut: that makes the freeze depend on lock discipline at the call40+/// Whether the pair was already graded is read one statement ahead of the
44-// sites, not on this row. Moving a student write's lease to *after* its41+/// write, under the same lock — it is what keeps a regrade from crediting
45-// database write — or sharding HOMEWORK_LOCK per homework — reopens the42+/// the grader a second time. No mark counter here: a homework mark is
46-// window with nothing to catch it. Closing it in the db layer needs a43+/// optional and most grades are status-only, so `high_mark` is an exam-only
47-// record both sides own (a per-(homework, user) row the grade can always44+/// family.
48-// stamp); a tombstone submission is not it, since every read path would45+///
49-// have to learn to ignore it and one missed filter fabricates a hand-in.46+/// The homework row's `FOR UPDATE` is also the parent gate: the id is minted
47+/// fresh, so a grade landing inside a homework (or course) delete's window
48+/// would otherwise *re-create* a result row under a homework that is gone,
49+/// readable ever after at `GET /homework/{id}/result` (no existence check
50+/// there) with a `marks_given_total` no ungrade can reach, because every
51+/// route to the grade goes through the homework. A vanished row answers
52+/// `Err(NotFound)` — the 404 the web layer's own lookup would have answered.
50 pub async fn grade(53 pub async fn grade(
51 db: &Database,54 db: &Database,
52 homework: &HomeworkId,55 homework: &HomeworkId,
@@ -55,102 +58,73 @@ pub async fn grade(
55 mark: Option<Mark>,58 mark: Option<Mark>,
56 graded_by: &UserId,59 graded_by: &UserId,
57 ) -> Result<HomeworkResult, AppError> {60 ) -> Result<HomeworkResult, AppError> {
58- let id = HomeworkResultId::composite(homework, user);61+ let id = HomeworkResultId::generate();
59- let submission = HomeworkSubmissionId::composite(homework, user);62+ let now = Timestamp::now();
60- let result = HomeworkResult {63+ tx_with_retry(db, false, async |tx| {
61- id: id.clone(),64+ let alive = sqlx::query!(
62- homework: homework.clone(),65+ r#"SELECT 1 AS "row: i32" FROM homework WHERE id = $1 FOR UPDATE"#,
63- user: user.clone(),66+ homework
64- status,67+ )
65- mark,68+ .fetch_optional(&mut *tx)
66- graded_by: graded_by.clone(),69+ .await?;
67- created_at: Timestamp::now(),70+ if alive.is_none() {
68- };71+ return Err(AppError::NotFound);
69- // Whether the pair was already graded is read one statement ahead of72+ }
70- // the write, inside the same transaction — it is what keeps a regrade73+ let before = sqlx::query!(
71- // from crediting the grader a second time. No mark counter here: a74+ r#"SELECT 1 AS "row: i32" FROM homework_result
72- // homework mark is optional and most grades are status-only, so75+ WHERE homework = $1 AND app_user = $2 FOR UPDATE"#,
73- // `high_mark` is an exam-only family.76+ homework,
74- //77+ user
75- // The first three statements are the parent gate, the twin of78+ )
76- // [`crate::db::homework_submission::upsert`]'s79+ .fetch_optional(&mut *tx)
77- // and written the same way on purpose: the id is deterministic, so a80+ .await?
78- // grade landing inside a homework (or course) delete's window does not81+ .is_some();
79- // fail — it *re-creates* a result row under a homework that is gone,82+ // A regrade overwrites status, mark, grader and stamp — `id` and
80- // readable ever after at `GET /homework/{id}/result` (no existence check83+ // `homework`/`app_user` are the row's identity and stay.
81- // there) with a `marks_given_total` no ungrade can reach, because every84+ let graded = sqlx::query_as!(
82- // route to the grade goes through the homework. Reading the homework85+ HomeworkResult,
83- // first — which the web layer does, under the lease — cannot close that:86+ r#"INSERT INTO homework_result (id, homework, app_user, status, mark, graded_by, created_at)
84- // the store conflict-checks write sets, not read sets. So the gate87+ VALUES ($1, $2, $3, $4, $5, $6, $7)
85- // *moves* a value on the homework row (`due_at` up by one and straight88+ ON CONFLICT (homework, app_user) DO UPDATE
86- // back to the captured value, leaving the row byte-identical) and the89+ SET status = EXCLUDED.status, mark = EXCLUDED.mark,
87- // cascade's delete of that same row is what refuses it. `homework` owns90+ graded_by = EXCLUDED.graded_by, created_at = EXCLUDED.created_at
88- // no counter column and is SCHEMAFULL, so `due_at` is the one `int` it91+ RETURNING id AS "id: HomeworkResultId",
89- // already has; do not invent a second spelling.92+ homework AS "homework: HomeworkId",
90- //93+ app_user AS "user: UserId",
91- // Not [`crate::db::cap::touch_and_create`], which is the same shape94+ status AS "status: HomeworkStatus",
92- // for a bare `CREATE`: a grade is an UPSERT (a regrade must overwrite),95+ mark AS "mark: Option<Mark>",
93- // and the freeze stamp and the grader's counter have to ride the same96+ graded_by AS "graded_by: UserId",
94- // transaction, which that helper has no room for.97+ created_at AS "created_at: Timestamp""#,
95- //98+ id,
96- // Sound to re-send, which is what the gate needed first — a `THROW`99+ homework,
97- // inside a plain `db.query` would have turned every lost round into a100+ user,
98- // 500. `SELECT`, `UPDATE` and the `IF`/`THROW` can never answer "already101+ status,
99- // exists", and the `UPSERT`'s id is bijective with the (homework, user)102+ mark,
100- // pair the table keys, on a table whose only index is non-unique103+ graded_by,
101- // (`homework_result_homework`), so its index entry can only ever point104+ now,
102- // at the row the id already names: it resolves onto that row instead of105+ )
103- // colliding with it. A lost round wrote nothing.106+ .fetch_one(&mut *tx)
104- let (mut saved, mut errors) = transaction_with_retry(107+ .await?;
105- db,108+ sqlx::query!(
106- &format!(109+ r#"UPDATE homework_submission SET graded_by_result = $3
107- "BEGIN TRANSACTION;110+ WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL"#,
108- LET $was_due = (SELECT VALUE due_at FROM ONLY $hw);111+ homework,
109- LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id);112+ user,
110- IF array::len($alive) = 0 {{ THROW 'no_homework' }};113+ graded.id
111- UPDATE $hw SET due_at = $was_due;114+ )
112- LET $before = (SELECT VALUE id FROM ONLY $id);115+ .execute(&mut *tx)
113- LET $after = (UPSERT $id CONTENT $row RETURN AFTER);116+ .await?;
114- UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = $id \117+ if !before {
115- WHERE {SUBMISSION_OPEN_GUARD};118+ sqlx::query!(
116- IF $before = NONE {{119+ "UPDATE app_user SET marks_given_total = marks_given_total + 1 WHERE id = $1",
117- UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} =120+ graded_by
118- ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1121+ )
119- }};122+ .execute(&mut *tx)
120- RETURN $after;123+ .await?;
121- COMMIT TRANSACTION;"124+ }
122- ),125+ Ok(graded)
123- &[126+ })
124- ("hw".into(), homework.record().into_value()),127+ .await
125- ("id".into(), id.record().into_value()),
126- ("sub".into(), submission.record().into_value()),
127- ("grader".into(), graded_by.record().into_value()),
128- ("row".into(), result.into_value()),
129- ],
130- &["no_homework"],
131- )
132- .await?;
133- // An aborted transaction errors *every* slot, most with a generic "not
134- // executed" — only the THROW's own slot names the reason.
135- if errors
136- .values()
137- .any(|error| error.to_string().contains("no_homework"))
138- {
139- return Err(AppError::NotFound);
140- }
141- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
142- return Err(error.into());
143- }
144- // The trailing `RETURN` is always the last statement before `COMMIT`,
145- // so its slot follows the statement count instead of a hand-kept
146- // number — which the gate above would otherwise have shifted, silently
147- // handing back something else.
148- let slot = saved.num_statements().saturating_sub(2);
149- saved
150- .take::<Vec<HomeworkResult>>(slot)?
151- .into_iter()
152- .next()
153- .ok_or_else(|| AppError::Internal("failed to record homework result".into()))
154 }128 }
155 129
156 /// `user`'s grade for `homework`, if graded.130 /// `user`'s grade for `homework`, if graded.
@@ -159,9 +133,21 @@ pub async fn read_for(
159 homework: &HomeworkId,133 homework: &HomeworkId,
160 user: &UserId,134 user: &UserId,
161 ) -> Result<Option<HomeworkResult>, AppError> {135 ) -> Result<Option<HomeworkResult>, AppError> {
162- Ok(db136+ Ok(sqlx::query_as!(
163- .select(HomeworkResultId::composite(homework, user).record())137+ HomeworkResult,
164- .await?)138+ r#"SELECT id AS "id: HomeworkResultId",
139+ homework AS "homework: HomeworkId",
140+ app_user AS "user: UserId",
141+ status AS "status: HomeworkStatus",
142+ mark AS "mark: Option<Mark>",
143+ graded_by AS "graded_by: UserId",
144+ created_at AS "created_at: Timestamp"
145+ FROM homework_result WHERE homework = $1 AND app_user = $2"#,
146+ homework,
147+ user
148+ )
149+ .fetch_optional(db)
150+ .await?)
165 }151 }
166 152
167 /// Every grade for `homework` — the roster joins these onto the submissions.153 /// Every grade for `homework` — the roster joins these onto the submissions.
@@ -169,12 +155,20 @@ pub async fn list_for_homework(
169 db: &Database,155 db: &Database,
170 homework: &HomeworkId,156 homework: &HomeworkId,
171 ) -> Result<Vec<HomeworkResult>, AppError> {157 ) -> Result<Vec<HomeworkResult>, AppError> {
172- let mut result = db158+ Ok(sqlx::query_as!(
173- .query("SELECT * FROM homework_result WHERE homework = $hw ORDER BY id DESC")159+ HomeworkResult,
174- .bind(("hw", homework.record()))160+ r#"SELECT id AS "id: HomeworkResultId",
175- .await?161+ homework AS "homework: HomeworkId",
176- .check()?;162+ app_user AS "user: UserId",
177- Ok(result.take::<Vec<HomeworkResult>>(0)?)163+ status AS "status: HomeworkStatus",
164+ mark AS "mark: Option<Mark>",
165+ graded_by AS "graded_by: UserId",
166+ created_at AS "created_at: Timestamp"
167+ FROM homework_result WHERE homework = $1 ORDER BY id DESC"#,
168+ homework
169+ )
170+ .fetch_all(db)
171+ .await?)
178 }172 }
179 173
180 /// `user`'s homework grades across one course — the raw rows behind the174 /// `user`'s homework grades across one course — the raw rows behind the
@@ -185,17 +179,24 @@ pub async fn list_for_user_in_course(
185 course: &CourseId,179 course: &CourseId,
186 user: &UserId,180 user: &UserId,
187 ) -> Result<Vec<HomeworkResult>, AppError> {181 ) -> Result<Vec<HomeworkResult>, AppError> {
188- let mut result = db182+ Ok(sqlx::query_as!(
189- .query(183+ HomeworkResult,
190- "SELECT * FROM homework_result WHERE user = $usr184+ r#"SELECT id AS "id: HomeworkResultId",
191- AND homework IN (SELECT VALUE id FROM homework WHERE course = $course)185+ homework AS "homework: HomeworkId",
192- ORDER BY id DESC",186+ app_user AS "user: UserId",
193- )187+ status AS "status: HomeworkStatus",
194- .bind(("usr", user.record()))188+ mark AS "mark: Option<Mark>",
195- .bind(("course", course.record()))189+ graded_by AS "graded_by: UserId",
196- .await?190+ created_at AS "created_at: Timestamp"
197- .check()?;191+ FROM homework_result
198- Ok(result.take::<Vec<HomeworkResult>>(0)?)192+ WHERE app_user = $1
193+ AND homework IN (SELECT id FROM homework WHERE course = $2)
194+ ORDER BY id DESC"#,
195+ user,
196+ course
197+ )
198+ .fetch_all(db)
199+ .await?)
199 }200 }
200 201
201 /// Un-grade (homework, user), returning the removed row (`None` if there202 /// Un-grade (homework, user), returning the removed row (`None` if there
@@ -212,53 +213,70 @@ pub async fn list_for_user_in_course(
212 /// submission behind it — permanently, since an award is never revoked.213 /// submission behind it — permanently, since an award is never revoked.
213 /// Given back to the *removed row's own* grader, not the caller: a manager214 /// Given back to the *removed row's own* grader, not the caller: a manager
214 /// may un-grade what a teacher graded, and the credit is the teacher's.215 /// may un-grade what a teacher graded, and the credit is the teacher's.
215-///
216-/// Sound to re-send while the store answers "conflict, retry" — this is the
217-/// upgrade `grade` still wants, taken here because the counter above is what
218-/// makes it necessary: the grader's row is written by exam grading too, so
219-/// the delete now contends with another domain, and only `DELETE`/`UPDATE`
220-/// are in the batch, none of which can legitimately answer "already exists".
221 pub async fn remove(216 pub async fn remove(
222 db: &Database,217 db: &Database,
223 homework: &HomeworkId,218 homework: &HomeworkId,
224 user: &UserId,219 user: &UserId,
225 ) -> Result<Option<HomeworkResult>, AppError> {220 ) -> Result<Option<HomeworkResult>, AppError> {
226- let id = HomeworkResultId::composite(homework, user);221+ tx_with_retry(db, false, async |tx| {
227- let (mut result, mut errors) = transaction_with_retry(222+ // The homework row's lock orders this against a concurrent grade
228- db,223+ // (which locks the same row before inserting): either this delete
229- &format!(224+ // wins and the re-grade lands after as a fresh grade, or the grade
230- "BEGIN TRANSACTION;225+ // lands first and this removes *it*. A homework already cascaded
231- LET $gone = (DELETE $id RETURN BEFORE);226+ // away left no result rows behind — `None`, the 404 the web layer
232- UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = NONE \227+ // answers.
233- WHERE {SUBMISSION_GRADED_FIELD} = $id;228+ let alive = sqlx::query!(
234- IF array::len($gone) > 0 {{229+ r#"SELECT 1 AS "row: i32" FROM homework WHERE id = $1 FOR UPDATE"#,
235- LET $grader = $gone[0].graded_by;230+ homework
236- UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} =231+ )
237- math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0])232+ .fetch_optional(&mut *tx)
238- }};233+ .await?;
239- RETURN $gone;234+ if alive.is_none() {
240- COMMIT TRANSACTION;"235+ return Ok(None);
241- ),236+ }
242- &[237+ let gone = sqlx::query!(
243- ("id".into(), id.record().into_value()),238+ r#"DELETE FROM homework_result WHERE homework = $1 AND app_user = $2
244- (239+ RETURNING id AS "id: HomeworkResultId",
245- "sub".into(),240+ homework AS "homework: HomeworkId",
246- HomeworkSubmissionId::composite(homework, user)241+ app_user AS "user: UserId",
247- .record()242+ status AS "status: HomeworkStatus",
248- .into_value(),243+ mark AS "mark: Option<Mark>",
249- ),244+ graded_by AS "graded_by: UserId",
250- ],245+ created_at AS "created_at: Timestamp""#,
251- &[],246+ homework,
252- )247+ user
253- .await?;248+ )
254- if let Some(error) = errors.drain().map(|(_, error)| error).next() {249+ .fetch_optional(&mut *tx)
255- return Err(error.into());250+ .await?;
256- }251+ let Some(removed) = gone else {
257- // The trailing `RETURN` is always the last statement before `COMMIT`, so252+ return Ok(None);
258- // its slot follows the statement count — the hand-kept "slot 1" this253+ };
259- // replaces was one added statement away from handing back the unstamp.254+ sqlx::query!(
260- let slot = result.num_statements().saturating_sub(2);255+ r#"UPDATE homework_submission SET graded_by_result = NULL
261- Ok(result.take::<Vec<HomeworkResult>>(slot)?.into_iter().next())256+ WHERE homework = $1 AND app_user = $2 AND graded_by_result = $3"#,
257+ homework,
258+ user,
259+ removed.id
260+ )
261+ .execute(&mut *tx)
262+ .await?;
263+ sqlx::query!(
264+ "UPDATE app_user SET marks_given_total = GREATEST(marks_given_total - 1, 0) WHERE id = $1",
265+ removed.graded_by
266+ )
267+ .execute(&mut *tx)
268+ .await?;
269+ Ok(Some(HomeworkResult {
270+ id: removed.id,
271+ homework: removed.homework,
272+ user: removed.user,
273+ status: removed.status,
274+ mark: removed.mark,
275+ graded_by: removed.graded_by,
276+ created_at: removed.created_at,
277+ }))
278+ })
279+ .await
262 }280 }
263 281
264 #[cfg(test)]282 #[cfg(test)]
src/db/homework_submission.rsmodified+266 -197
@@ -5,186 +5,217 @@
5 //! [`crate::service::homework_submission`]; the validated text type in5 //! [`crate::service::homework_submission`]; the validated text type in
6 //! [`crate::domain::homework_submission`].6 //! [`crate::domain::homework_submission`].
7 7
8-use crate::constant::{8+use crate::database::{Database, tx_with_retry};
9- HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMITTED_TOTAL_FIELD, SUBMISSION_GRADED_FIELD,
10- SUBMISSION_OPEN_GUARD,
11-};
12-use crate::database::{Database, transaction_with_retry};
13 use crate::domain::homework::Homework;9 use crate::domain::homework::Homework;
10+use crate::domain::homework::HomeworkId;
14 use crate::domain::homework_submission::{11 use crate::domain::homework_submission::{
15 HomeworkSubmission, HomeworkSubmissionId, SubmissionText,12 HomeworkSubmission, HomeworkSubmissionId, SubmissionText,
16 };13 };
17 use crate::domain::timestamp::Timestamp;14 use crate::domain::timestamp::Timestamp;
18 use crate::domain::user::UserId;15 use crate::domain::user::UserId;
19 use crate::error::AppError;16 use crate::error::AppError;
20-use surrealdb::types::SurrealValue;
21 17
22 /// Create or re-stamp `user`'s submission to `homework`, unless a grade has18 /// Create or re-stamp `user`'s submission to `homework`, unless a grade has
23 /// frozen it — `None` means frozen, and the caller answers 409. `updated_at`19 /// frozen it — `None` means frozen, and the caller answers 409. `updated_at`
24-/// moves to now every time; `submitted_at` (readonly, the first-submit stamp)20+/// moves to now every time; `submitted_at` (the first-submit stamp) is kept
25-/// is kept on an existing row and set only on a fresh one.21+/// on an existing row and set only on a fresh one. Returns the row plus
22+/// whether it existed before this call (the web layer's 200-vs-201, and the
23+/// only-a-first-hand-in-earns-badges rule).
26 ///24 ///
27-/// Hand-written rather than `.content()` on purpose: `.content()` re-sends25+/// `preserve_text` is the photo-upload auto-create's switch: an existing row
28-/// the whole row, so it would carry a `submitted_at`, and any value differing26+/// keeps its text (and its stamp moves, as any touch), because the upload
29-/// from the stored one trips the readonly guard. The27+/// never offered a text to replace it. A submit passes `false` — an absent
30-/// `submitted_at = submitted_at ?? $now` expression preserves it inside the28+/// text clears, as on the wire.
31-/// one UPSERT statement — race-free without a lock, where a read-then-content
32-/// could let two concurrent first-submits pick different stamps and 500.
33 ///29 ///
34-/// The `WHERE` is the freeze: [`SUBMISSION_OPEN_GUARD`] makes "not graded30+/// The `graded_by_result IS NULL` predicate is the freeze: "not graded yet"
35-/// yet" a condition of this very write instead of a read a concurrent grade31+/// is a condition of the write itself, so a refused write answers `None`
36-/// can land behind. An absent row satisfies it (the stamp is `NONE` there32+/// instead of wiping graded work. An absent row satisfies it trivially, so a
37-/// too), so a first submit still creates.33+/// first submit still creates.
38 ///34 ///
39 /// The badge counters on the student's user row move in this very35 /// The badge counters on the student's user row move in this very
40-/// transaction, and the order is load-bearing: the increment sits *after*36+/// transaction, and only on the create arm — an edit moves neither counter,
41-/// the UPSERT and is conditional on it having matched a row, because a37+/// which is what makes the live count mean one per row.
42-/// frozen row makes that `WHERE` match nothing **silently** (unlike
43-/// [`crate::db::homework_result::grade`], which `THROW`s) — put
44-/// first, it would count a submission the freeze refused. `$before = NONE`
45-/// keeps it to a genuine first create, so an edit moves neither counter,
46-/// which is what makes the live count mean the same thing the one-time
47-/// backfill seeded (one per row; on time judged against `due_at`, equal
48-/// counting as on time).
49 ///38 ///
50-/// `counted_on_time` is stamped on the row from the *same* `$on_time`39+/// `counted_on_time` is stamped on the row from the same `on_time` verdict
51-/// expression the increment adds, in the same statement block: the deadline40+/// the increment adds, in the same transaction: the deadline is mutable, so
52-/// is mutable, so a withdrawal that re-judged it against the live `due_at`41+/// a withdrawal that re-judged it against the live `due_at` gave back
53-/// gave back something other than what was taken. Writing the verdict beside42+/// something other than what was taken. Writing the verdict beside the
54-/// the counter is what keeps the two from ever disagreeing — read back by43+/// counter is what keeps the two from ever disagreeing — read back by
55 /// [`delete`], never re-derived.44 /// [`delete`], never re-derived.
56 ///45 ///
57-/// That deadline is `$was_due`, the one the gate below already read *inside46+/// That deadline is `was_due`, the one read *inside this transaction* under
58-/// this transaction* — never the caller's [`Homework`] snapshot, which was47+/// the homework row's lock — never the caller's [`Homework`] snapshot, which
59-/// read before the lease and is exactly one `PATCH due_at` old in the48+/// was read before the request's gates and is exactly one `PATCH due_at` old
60-/// "teacher extends the deadline at 23:59 while the class submits" moment.49+/// in the "teacher extends the deadline at 23:59 while the class submits"
61-/// Judging on the snapshot stored a verdict the web layer's own `late` flag50+/// moment. The lock is also the serialization point: grading locks the same
62-/// (`updated_at > due_at`, re-derived live on every read) then contradicted51+/// row before stamping, the audience-narrowing PATCH before its orphan
63-/// forever, in both directions. An in-process lock cannot fix this — it52+/// check, and a rival first hand-in before its own insert — so the
64-/// orders two handlers, not two store transactions — so the comparison has53+/// read-then-write below cannot interleave with any of them. (The pair's
65-/// to live where the write does. The whole entity is still taken (both54+/// UNIQUE constraint backs this up; under the lock it can never fire.)
66-/// callers hold the row, and the id comes off it); its `due_at` must not be.
67-///
68-/// The first three statements are the parent gate, and they are why this
69-/// write cannot outlive its homework: the id is deterministic, so nothing
70-/// else here would fail against a homework a cascade already removed — it
71-/// would simply re-create the row, badge counters and all, unreachable ever
72-/// after (every route to a submission goes through its homework). A *read*
73-/// of the homework does not close that, on either side of the call: the
74-/// store does no read-set conflict detection, so a delete committing
75-/// alongside is invisible to it. The gate therefore *moves* a value on the
76-/// homework row — `due_at` up by one and straight back to the captured
77-/// value, so the row is byte-identical afterwards — because only a write
78-/// collides, and `SET x = x` is elided and never reaches the write set. It
79-/// is [`crate::domain::exam_answer::ExamAnswer::save`]'s shape exactly.
80-/// `Err(NotFound)` means the homework is gone, which is the 404 the web
81-/// layer's own lookup would have answered.
82 pub async fn upsert(55 pub async fn upsert(
83 db: &Database,56 db: &Database,
84 homework: &Homework,57 homework: &Homework,
85 user: &UserId,58 user: &UserId,
86 text: Option<SubmissionText>,59 text: Option<SubmissionText>,
87-) -> Result<Option<HomeworkSubmission>, AppError> {60+ preserve_text: bool,
88- let id = HomeworkSubmissionId::composite(homework.get_id(), user);61+) -> Result<Option<(HomeworkSubmission, bool)>, AppError> {
89 let now = Timestamp::now();62 let now = Timestamp::now();
90- let text = text.map(|text| text.as_str().to_string());63+ tx_with_retry(db, false, async |tx| {
91- // Sound to re-send: the UPSERT is on a deterministic id on a table with64+ // The parent gate: the homework row is locked and its deadline read
92- // no unique index, so it can never legitimately answer "already exists",65+ // in the very transaction that writes the submission. The id is
93- // and the counter UPDATEs never can either.66+ // minted fresh, so nothing else here would fail against a homework a
94- let (mut saved, mut errors) = transaction_with_retry(67+ // cascade already removed — it would simply create a row under it,
95- db,68+ // badge counters and all, unreachable ever after (every route to a
96- &format!(69+ // submission goes through its homework). `Err(NotFound)` means the
97- "BEGIN TRANSACTION;70+ // homework is gone, which is the 404 the web layer's own lookup
98- LET $was_due = (SELECT VALUE due_at FROM ONLY $hw);71+ // would have answered.
99- LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id);72+ let was_due = sqlx::query!(
100- IF array::len($alive) = 0 {{ THROW 'no_homework' }};73+ "SELECT due_at FROM homework WHERE id = $1 FOR UPDATE",
101- UPDATE $hw SET due_at = $was_due;74+ homework.get_id()
102- LET $before = (SELECT VALUE id FROM ONLY $id);75+ )
103- LET $on_time = $now <= $was_due;76+ .fetch_optional(&mut *tx)
104- LET $after = (UPSERT $id SET homework = $hw, user = $usr, text = $text,77+ .await?
105- updated_at = $now, submitted_at = submitted_at ?? $now78+ .map(|row| row.due_at);
106- WHERE {SUBMISSION_OPEN_GUARD} RETURN AFTER);79+ let Some(was_due) = was_due else {
107- IF $before = NONE AND array::len($after) > 0 {{80+ return Err(AppError::NotFound);
108- UPDATE $id SET counted_on_time = $on_time;81+ };
109- UPDATE $usr SET82+ // Equal counts as on time, exactly as the deadline has always been
110- {HOMEWORK_SUBMITTED_TOTAL_FIELD} = ({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) + 1,83+ // judged.
111- {HOMEWORK_ON_TIME_TOTAL_FIELD} = ({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0)84+ let on_time = i64::from(now <= was_due);
112- + IF $on_time {{ 1 }} ELSE {{ 0 }}85+
113- }};86+ // The row, read under the homework's lock: its existence decides the
114- RETURN $after;87+ // arm (and the counters).
115- COMMIT TRANSACTION;"88+ let existing = sqlx::query!(
116- ),89+ r#"SELECT 1 AS "row: i32" FROM homework_submission
117- &[90+ WHERE homework = $1 AND app_user = $2 FOR UPDATE"#,
118- ("id".into(), id.record().into_value()),91+ homework.get_id(),
119- ("hw".into(), homework.get_id().record().into_value()),92+ user
120- ("usr".into(), user.record().into_value()),93+ )
121- ("text".into(), text.into_value()),94+ .fetch_optional(&mut *tx)
122- ("now".into(), now.into_value()),95+ .await?
123- ],96+ .is_some();
124- &["no_homework"],97+
125- )98+ if existing {
126- .await?;99+ // Re-submit: text is replaced (unless the upload auto-create is
127- // An aborted transaction errors *every* slot, most with a generic "not100+ // asking — it has no text to replace), `updated_at` moves, and
128- // executed" — only the THROW's own slot names the reason.101+ // `submitted_at` is left alone. A frozen row matches nothing and
129- if errors102+ // answers `None`, the caller's 409.
130- .values()103+ let updated = if preserve_text {
131- .any(|error| error.to_string().contains("no_homework"))104+ sqlx::query_as!(
132- {105+ HomeworkSubmission,
133- return Err(AppError::NotFound);106+ r#"UPDATE homework_submission SET updated_at = $3
134- }107+ WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL
135- if let Some(error) = errors.drain().map(|(_, error)| error).next() {108+ RETURNING id AS "id: HomeworkSubmissionId",
136- return Err(error.into());109+ homework AS "homework: HomeworkId",
137- }110+ app_user AS "user: UserId",
138- // The trailing `RETURN` is always the last statement before `COMMIT`, so111+ text AS "text: Option<SubmissionText>",
139- // its slot follows the statement count rather than a hand-kept number.112+ submitted_at AS "submitted_at: Timestamp",
140- // It returns the whole array, never `$after[0]`: a refused write makes113+ updated_at AS "updated_at: Timestamp""#,
141- // that `NONE`, which fails to deserialize ("expected object, got none")114+ homework.get_id(),
142- // instead of reading as the "frozen" the caller answers 409 to.115+ user,
143- let slot = saved.num_statements().saturating_sub(2);116+ now
144- Ok(saved117+ )
145- .take::<Vec<HomeworkSubmission>>(slot)?118+ .fetch_optional(&mut *tx)
146- .into_iter()119+ .await?
147- .next())120+ } else {
121+ sqlx::query_as!(
122+ HomeworkSubmission,
123+ r#"UPDATE homework_submission SET text = $3, updated_at = $4
124+ WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL
125+ RETURNING id AS "id: HomeworkSubmissionId",
126+ homework AS "homework: HomeworkId",
127+ app_user AS "user: UserId",
128+ text AS "text: Option<SubmissionText>",
129+ submitted_at AS "submitted_at: Timestamp",
130+ updated_at AS "updated_at: Timestamp""#,
131+ homework.get_id(),
132+ user,
133+ text,
134+ now
135+ )
136+ .fetch_optional(&mut *tx)
137+ .await?
138+ };
139+ return Ok(updated.map(|submission| (submission, existing)));
140+ }
141+
142+ // First hand-in: the verdict is stored beside the counter it credits,
143+ // so the two can never disagree.
144+ let created = sqlx::query_as!(
145+ HomeworkSubmission,
146+ r#"INSERT INTO homework_submission
147+ (id, homework, app_user, text, submitted_at, updated_at, file_count, counted_on_time)
148+ VALUES ($1, $2, $3, $4, $5, $5, 0, $6)
149+ RETURNING id AS "id: HomeworkSubmissionId",
150+ homework AS "homework: HomeworkId",
151+ app_user AS "user: UserId",
152+ text AS "text: Option<SubmissionText>",
153+ submitted_at AS "submitted_at: Timestamp",
154+ updated_at AS "updated_at: Timestamp""#,
155+ HomeworkSubmissionId::generate(),
156+ homework.get_id(),
157+ user,
158+ text,
159+ now,
160+ on_time != 0,
161+ )
162+ .fetch_optional(&mut *tx)
163+ .await?;
164+ sqlx::query!(
165+ r#"UPDATE app_user SET
166+ homework_submitted_total = homework_submitted_total + 1,
167+ homework_on_time_total = homework_on_time_total + $2
168+ WHERE id = $1"#,
169+ user,
170+ on_time
171+ )
172+ .execute(&mut *tx)
173+ .await?;
174+ Ok(created.map(|submission| (submission, existing)))
175+ })
176+ .await
148 }177 }
149 178
150 /// Re-stamp a submission's `updated_at` to now, leaving its text and files179 /// Re-stamp a submission's `updated_at` to now, leaving its text and files
151 /// alone. A file add or delete modifies the submission as a whole, so its180 /// alone. A file add or delete modifies the submission as a whole, so its
152 /// "last touched" clock — which drives the computed late flag — must move181 /// "last touched" clock — which drives the computed late flag — must move
153-/// even though the text row is unchanged. Free-standing because the file182+/// even though the text row is unchanged. A targeted single-field UPDATE, so
154-/// paths hold the composite id, not always the row. A targeted single-field183+/// the readonly `submitted_at` is never re-sent. Returns the re-stamped row,
155-/// UPDATE, so the `READONLY` `submitted_at` is never re-sent (a `.content()`184+/// or a 404 if it has since vanished.
156-/// would trip its guard). Returns the re-stamped row, or a 404 if it has
157-/// since vanished.
158 pub async fn touch(185 pub async fn touch(
159 db: &Database,186 db: &Database,
160 id: &HomeworkSubmissionId,187 id: &HomeworkSubmissionId,
161 ) -> Result<HomeworkSubmission, AppError> {188 ) -> Result<HomeworkSubmission, AppError> {
162 let now = Timestamp::now();189 let now = Timestamp::now();
163- let mut result = db190+ sqlx::query_as!(
164- .query("UPDATE $id SET updated_at = $now RETURN AFTER")191+ HomeworkSubmission,
165- .bind(("id", id.record()))192+ r#"UPDATE homework_submission SET updated_at = $2 WHERE id = $1
166- .bind(("now", now))193+ RETURNING id AS "id: HomeworkSubmissionId",
167- .await?194+ homework AS "homework: HomeworkId",
168- .check()?;195+ app_user AS "user: UserId",
169- result196+ text AS "text: Option<SubmissionText>",
170- .take::<Vec<HomeworkSubmission>>(0)?197+ submitted_at AS "submitted_at: Timestamp",
171- .into_iter()198+ updated_at AS "updated_at: Timestamp""#,
172- .next()199+ id,
173- .ok_or(AppError::NotFound)200+ now
201+ )
202+ .fetch_optional(db)
203+ .await?
204+ .ok_or(AppError::NotFound)
174 }205 }
175 206
176 /// Whether a grade has frozen this submission. Only ever read to tell two207 /// Whether a grade has frozen this submission. Only ever read to tell two
177 /// refusals apart *after* a conditional write has already refused one — the208 /// refusals apart *after* a conditional write has already refused one — the
178 /// stamp on the row, never this read, is what decides.209 /// stamp on the row, never this read, is what decides.
179 pub async fn is_graded(db: &Database, id: &HomeworkSubmissionId) -> Result<bool, AppError> {210 pub async fn is_graded(db: &Database, id: &HomeworkSubmissionId) -> Result<bool, AppError> {
180- let mut result = db211+ let row = sqlx::query!(
181- .query(format!(212+ r#"SELECT EXISTS(SELECT 1 FROM homework_submission
182- "SELECT VALUE id FROM $id WHERE {SUBMISSION_GRADED_FIELD} != NONE"213+ WHERE id = $1 AND graded_by_result IS NOT NULL) AS "graded""#,
183- ))214+ id
184- .bind(("id", id.record()))215+ )
185- .await?216+ .fetch_one(db)
186- .check()?;217+ .await?;
187- Ok(!result.take::<Vec<HomeworkSubmissionId>>(0)?.is_empty())218+ Ok(row.graded)
188 }219 }
189 220
190 /// `user`'s submission to `homework`, if they have one.221 /// `user`'s submission to `homework`, if they have one.
@@ -193,23 +224,40 @@ pub async fn read_for(
193 homework: &crate::domain::homework::HomeworkId,224 homework: &crate::domain::homework::HomeworkId,
194 user: &UserId,225 user: &UserId,
195 ) -> Result<Option<HomeworkSubmission>, AppError> {226 ) -> Result<Option<HomeworkSubmission>, AppError> {
196- Ok(db227+ Ok(sqlx::query_as!(
197- .select(HomeworkSubmissionId::composite(homework, user).record())228+ HomeworkSubmission,
198- .await?)229+ r#"SELECT id AS "id: HomeworkSubmissionId",
230+ homework AS "homework: HomeworkId",
231+ app_user AS "user: UserId",
232+ text AS "text: Option<SubmissionText>",
233+ submitted_at AS "submitted_at: Timestamp",
234+ updated_at AS "updated_at: Timestamp"
235+ FROM homework_submission WHERE homework = $1 AND app_user = $2"#,
236+ homework,
237+ user
238+ )
239+ .fetch_optional(db)
240+ .await?)
199 }241 }
200 242
201-/// Every submission to `homework`, in student (composite-id) order — the243+/// Every submission to `homework`, in creation order — the roster's raw rows.
202-/// roster's raw rows.
203 pub async fn list_for_homework(244 pub async fn list_for_homework(
204 db: &Database,245 db: &Database,
205 homework: &crate::domain::homework::HomeworkId,246 homework: &crate::domain::homework::HomeworkId,
206 ) -> Result<Vec<HomeworkSubmission>, AppError> {247 ) -> Result<Vec<HomeworkSubmission>, AppError> {
207- let mut result = db248+ Ok(sqlx::query_as!(
208- .query("SELECT * FROM homework_submission WHERE homework = $hw ORDER BY id ASC")249+ HomeworkSubmission,
209- .bind(("hw", homework.record()))250+ r#"SELECT id AS "id: HomeworkSubmissionId",
210- .await?251+ homework AS "homework: HomeworkId",
211- .check()?;252+ app_user AS "user: UserId",
212- Ok(result.take::<Vec<HomeworkSubmission>>(0)?)253+ text AS "text: Option<SubmissionText>",
254+ submitted_at AS "submitted_at: Timestamp",
255+ updated_at AS "updated_at: Timestamp"
256+ FROM homework_submission WHERE homework = $1 ORDER BY id ASC"#,
257+ homework
258+ )
259+ .fetch_all(db)
260+ .await?)
213 }261 }
214 262
215 /// Delete this submission and its files in one transaction — so a crash263 /// Delete this submission and its files in one transaction — so a crash
@@ -217,9 +265,8 @@ pub async fn list_for_homework(
217 /// are the web layer's to unlink: it lists them265 /// are the web layer's to unlink: it lists them
218 /// ([`crate::db::homework_file::list_for_submission`])266 /// ([`crate::db::homework_file::list_for_submission`])
219 /// before calling this. `None` means a grade froze the row (the caller267 /// before calling this. `None` means a grade froze the row (the caller
220-/// answers 409): the submission's own delete carries268+/// answers 409): the delete carries `graded_by_result IS NULL` as its own
221-/// [`SUBMISSION_OPEN_GUARD`], and the file wipe is conditional on it having269+/// condition, so a refused delete leaves the files standing too.
222-/// bitten, so a refused delete leaves the children standing too.
223 ///270 ///
224 /// The one place either badge counter comes back down, and deliberately the271 /// The one place either badge counter comes back down, and deliberately the
225 /// only one: this route is student-callable on their own row, so without it272 /// only one: this route is student-callable on their own row, so without it
@@ -234,12 +281,10 @@ pub async fn list_for_homework(
234 /// and gave back something other than what was taken — extend it after a281 /// and gave back something other than what was taken — extend it after a
235 /// late hand-in and this debited a credit that was never given; pull it back282 /// late hand-in and this debited a credit that was never given; pull it back
236 /// after a punctual one and it debited nothing, leaving `on_time` above283 /// after a punctual one and it debited nothing, leaving `on_time` above
237-/// `submitted`. A row from before the column exists carries no verdict, and284+/// `submitted`. A row with no stored verdict falls back to the old cut
238-/// cannot be given one for a credit that already happened, so it falls back285+/// (`submitted_at`, the stamp the increment judged, against the deadline
239-/// to the old cut (`submitted_at`, the readonly stamp the increment judged,286+/// read here); a homework already gone counts as late, matching the
240-/// against the live deadline); a dangling `homework` link leaves `$due`287+/// backfill. Floored at zero.
241-/// `NONE` there, which compares false and so counts as late, matching the
242-/// backfill. Floored at zero: a row that predates the columns has none.
243 ///288 ///
244 /// Badges already earned are never taken away — [`crate::domain::badge`] is289 /// Badges already earned are never taken away — [`crate::domain::badge`] is
245 /// add-only, which is where that permanence lives.290 /// add-only, which is where that permanence lives.
@@ -247,42 +292,66 @@ pub async fn delete(
247 db: &Database,292 db: &Database,
248 submission: HomeworkSubmission,293 submission: HomeworkSubmission,
249 ) -> Result<Option<HomeworkSubmission>, AppError> {294 ) -> Result<Option<HomeworkSubmission>, AppError> {
250- // Sound to re-send: DELETE and UPDATE can never answer "already exists".295+ tx_with_retry(db, false, async |tx| {
251- let (mut result, mut errors) = transaction_with_retry(296+ // The homework row's lock is the serialization point against grading:
252- db,297+ // a grade locks the same row before it stamps, so either this delete
253- &format!(298+ // refuses off the stamp, or the grade landed on a row that is now
254- "BEGIN TRANSACTION;299+ // gone — grading absent work, which is allowed. Its `due_at` read is
255- LET $due = (SELECT VALUE homework.due_at FROM ONLY $sub);300+ // also the replay fallback's deadline.
256- LET $gone = (DELETE $sub WHERE {SUBMISSION_OPEN_GUARD} RETURN BEFORE);301+ let due = sqlx::query!(
257- IF array::len($gone) > 0 {{302+ "SELECT due_at FROM homework WHERE id = $1 FOR UPDATE",
258- DELETE homework_file WHERE submission = $sub;303+ submission.get_homework()
259- LET $on_time = IF ($gone[0].counted_on_time304+ )
260- ?? ($gone[0].submitted_at <= $due)) {{ 1 }} ELSE {{ 0 }};305+ .fetch_optional(&mut *tx)
261- UPDATE $usr SET306+ .await?
262- {HOMEWORK_SUBMITTED_TOTAL_FIELD} =307+ .map(|row| row.due_at);
263- math::max([({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) - 1, 0]),308+ let gone = sqlx::query!(
264- {HOMEWORK_ON_TIME_TOTAL_FIELD} =309+ r#"DELETE FROM homework_submission
265- math::max([({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) - $on_time, 0])310+ WHERE id = $1 AND graded_by_result IS NULL
266- }};311+ RETURNING id AS "id: HomeworkSubmissionId",
267- RETURN $gone;312+ homework AS "homework: HomeworkId",
268- COMMIT TRANSACTION;"313+ app_user AS "user: UserId",
269- ),314+ text AS "text: Option<SubmissionText>",
270- &[315+ submitted_at AS "submitted_at: Timestamp",
271- ("sub".into(), submission.id.record().into_value()),316+ updated_at AS "updated_at: Timestamp",
272- ("usr".into(), submission.user.record().into_value()),317+ counted_on_time AS "counted_on_time: Option<bool>""#,
273- ],318+ submission.get_id()
274- &[],319+ )
275- )320+ .fetch_optional(&mut *tx)
276- .await?;321+ .await?;
277- if let Some(error) = errors.drain().map(|(_, error)| error).next() {322+ let Some(removed) = gone else {
278- return Err(error.into());323+ // Frozen, or already withdrawn by a rival — one refusal, as
279- }324+ // before.
280- // The trailing `RETURN` is always the last statement before `COMMIT`.325+ return Ok(None);
281- let slot = result.num_statements().saturating_sub(2);326+ };
282- Ok(result327+ sqlx::query!(
283- .take::<Vec<HomeworkSubmission>>(slot)?328+ "DELETE FROM homework_file WHERE submission = $1",
284- .into_iter()329+ removed.id
285- .next())330+ )
331+ .execute(&mut *tx)
332+ .await?;
333+ let judged_on_time = due.map(|d| removed.submitted_at <= d).unwrap_or(false);
334+ let on_time = i64::from(removed.counted_on_time.unwrap_or(judged_on_time));
335+ sqlx::query!(
336+ r#"UPDATE app_user SET
337+ homework_submitted_total = GREATEST(homework_submitted_total - 1, 0),
338+ homework_on_time_total = GREATEST(homework_on_time_total - $2, 0)
339+ WHERE id = $1"#,
340+ removed.user,
341+ on_time
342+ )
343+ .execute(&mut *tx)
344+ .await?;
345+ Ok(Some(HomeworkSubmission {
346+ id: removed.id,
347+ homework: removed.homework,
348+ user: removed.user,
349+ text: removed.text,
350+ submitted_at: removed.submitted_at,
351+ updated_at: removed.updated_at,
352+ }))
353+ })
354+ .await
286 }355 }
287 356
288 #[cfg(test)]357 #[cfg(test)]
src/db/meal_attendance.rsmodified+64 -61
@@ -1,38 +1,31 @@
1 //! The `meal_attendance` table: the kitchen's marks — one atomic UPSERT per1 //! The `meal_attendance` table: the kitchen's marks — one atomic UPSERT per
2-//! (menu, student) that rides the menu's revision bump2+//! (menu, student) that rides the menu's revision bump inside its own
3-//! ([`bump_menu_and_write`](crate::db::menu::bump_menu_and_write)), plus the3+//! transaction, plus the two listings. Attendance is reporting only: nothing
4-//! two listings. Attendance is reporting only: nothing here writes the4+//! here writes the ledger, and the workflows that read it live in the web
5-//! ledger, and the workflows that read it live in the web layer via5+//! layer via [`crate::service::meal_attendance`].
6-//! [`crate::service::meal_attendance`].
7 6
8-use surrealdb::types::SurrealValue;7+use crate::database::{Database, tx_with_retry};
9-8+use crate::db::page::{PagedList, Param};
10-use crate::database::Database;9+use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus};
11-use crate::db::menu::bump_menu_and_write;10+use crate::domain::menu::{MenuDate, MenuId};
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;
16 use crate::domain::timestamp::Timestamp;11 use crate::domain::timestamp::Timestamp;
17 use crate::domain::user::UserId;12 use crate::domain::user::UserId;
18 use crate::error::AppError;13 use crate::error::AppError;
19 14
20 /// Record (or overwrite) whether `student` ate off `menu`. One row per15 /// Record (or overwrite) whether `student` ate off `menu`. One row per
21-/// pair by construction, so a correction is the same UPSERT flipping the16+/// pair by construction (`ON CONFLICT (menu, student)`), so a correction is
22-/// status. No ledger line, ever — see the domain module header.17+/// the same upsert flipping the status. No ledger line, ever — see the
18+/// domain module header.
23 ///19 ///
24 /// `NotFound` = the menu is gone, and the mark was *not* written. The mark20 /// `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* to21+/// and the menu's revision bump share one transaction, and the bump is what
26-/// the menu row rather than a read the write then trusts: a delete racing22+/// makes the menu's **existence** part of it: the `UPDATE` matches nothing
27-/// this one touches the very key this transaction bumps, and the store23+/// once the menu row is deleted, and Postgres commits a deleting and a
28-/// refuses to commit both. Guarding by reading the menu — even as the24+/// bumping transaction on the same row strictly one after the other — the
29-/// `UPSERT`'s own target — did not survive that race: the read saw a row25+/// mark either lands before the delete's guard re-reads its counter or not
30-/// [`crate::db::menu::delete`] had deleted but not26+/// at all. (Under the old store the same guarantee needed the shared bump
31-/// yet committed, its sweep ran on a snapshot predating this insert, and the27+/// shape because deletes and child writes could interleave with a read in
32-/// mark outlived its menu with neither caller told anything (measured 378 of28+/// between.)
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.
36 ///29 ///
37 /// The bump costs a booking in flight one re-read (its seat claim asserts30 /// The bump costs a booking in flight one re-read (its seat claim asserts
38 /// the revision it priced against) — the same tax every dish write already31 /// the revision it priced against) — the same tax every dish write already
@@ -45,30 +38,40 @@ pub async fn mark(
45 status: MealAttendanceStatus,38 status: MealAttendanceStatus,
46 marked_by: &UserId,39 marked_by: &UserId,
47 ) -> Result<MealAttendance, AppError> {40 ) -> Result<MealAttendance, AppError> {
48- let row = MealAttendance {41+ let marked_at = Timestamp::now();
49- id: MealAttendanceId::composite(menu, student),42+ let student = *student;
50- menu: menu.clone(),43+ let marked_by = *marked_by;
51- student: student.clone(),44+ tx_with_retry(db, false, async |tx| {
52- status,45+ let bumped = sqlx::query!(
53- marked_by: marked_by.clone(),46+ "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1
54- marked_at: Timestamp::now(),47+ RETURNING 1 AS bumped",
55- };48+ menu.key(),
56- // Admissible for the retry loop inside: the id is bijective with the49+ )
57- // (menu, student) pair the table indexes UNIQUE, so this `UPSERT`50+ .fetch_optional(&mut *tx)
58- // resolves onto the row that index already points at instead of51+ .await?;
59- // colliding with it — it can never answer "already exists", and a52+ if bumped.is_none() {
60- // re-sent round writes the identical row.53+ return Err(AppError::NotFound);
61- bump_menu_and_write(54+ }
62- menu,55+ let row = sqlx::query_as!(
63- "UPSERT $id CONTENT $row RETURN AFTER",56+ MealAttendance,
64- vec![57+ "INSERT INTO meal_attendance (menu, student, status, marked_by, marked_at)
65- ("id".into(), row.id.record().into_value()),58+ VALUES ($1, $2, $3, $4, $5)
66- ("row".into(), row.into_value()),59+ ON CONFLICT (menu, student) DO UPDATE
67- ],60+ SET status = EXCLUDED.status,
68- db,61+ marked_by = EXCLUDED.marked_by,
69- )62+ marked_at = EXCLUDED.marked_at
70- .await?63+ RETURNING menu, student, status, marked_by, marked_at",
71- .ok_or_else(|| AppError::Internal("failed to record the mark".into()))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
72 }75 }
73 76
74 /// The kitchen's list for one menu.77 /// The kitchen's list for one menu.
@@ -79,10 +82,10 @@ pub async fn list_for_menu(
79 offset: i64,82 offset: i64,
80 ) -> Result<(Vec<MealAttendance>, i64), AppError> {83 ) -> Result<(Vec<MealAttendance>, i64), AppError> {
81 PagedList::new(84 PagedList::new(
82- "meal_attendance WHERE menu = $menu",85+ "meal_attendance WHERE menu = $1",
83- "ORDER BY marked_at DESC, id DESC",86+ "ORDER BY marked_at DESC, menu DESC",
84 )87 )
85- .bind("menu", menu.record())88+ .bind(menu.key().to_string())
86 .run(limit, offset, db)89 .run(limit, offset, db)
87 .await90 .await
88 }91 }
@@ -91,7 +94,7 @@ pub async fn list_for_menu(
91 /// `YYYY-MM-DD` bounds on the *menu's* day — the comparison is lexical,94 /// `YYYY-MM-DD` bounds on the *menu's* day — the comparison is lexical,
92 /// which is chronological for that format (see [`MenuDate`]), and the link95 /// which is chronological for that format (see [`MenuDate`]), and the link
93 /// is followed rather than denormalized so a row can never disagree with96 /// 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.
95 pub async fn list_for_student(98 pub async fn list_for_student(
96 db: &Database,99 db: &Database,
97 student: &UserId,100 student: &UserId,
@@ -101,14 +104,14 @@ pub async fn list_for_student(
101 offset: i64,104 offset: i64,
102 ) -> Result<(Vec<MealAttendance>, i64), AppError> {105 ) -> Result<(Vec<MealAttendance>, i64), AppError> {
103 PagedList::new(106 PagedList::new(
104- "meal_attendance WHERE student = $usr \107+ "meal_attendance WHERE student = $1 \
105- AND ($from = NONE OR menu.date >= $from) \108+ AND ($2::text IS NULL OR menu IN (SELECT id FROM menu WHERE date >= $2::text)) \
106- AND ($to = NONE OR menu.date <= $to)",109+ AND ($3::text IS NULL OR menu IN (SELECT id FROM menu WHERE date <= $3::text))",
107- "ORDER BY marked_at DESC, id DESC",110+ "ORDER BY marked_at DESC, menu DESC",
108 )111 )
109- .bind("usr", student.record())112+ .bind(student.key())
110- .bind("from", from.map(|date| date.as_str().to_string()))113+ .bind(Param::OptText(from.map(|date| date.as_str().to_string())))
111- .bind("to", to.map(|date| date.as_str().to_string()))114+ .bind(Param::OptText(to.map(|date| date.as_str().to_string())))
112 .run(limit, offset, db)115 .run(limit, offset, db)
113 .await116 .await
114 }117 }
src/db/meal_booking.rsmodified+233 -191
@@ -1,14 +1,11 @@
1 //! The `meal_booking` table: row reads, the two listings, and the folded1 //! The `meal_booking` table: row reads, the two listings, and the folded
2-//! transactions every seat moves by — [`claim_and_place`] (seat + row + charge2+//! transactions every seat moves by — [`claim_and_place`] (seat + row +
3-//! in one `BEGIN…COMMIT`) and [`release_seat`] (flip + counter + refund in3+//! charge in one transaction) and [`release_seat`] (flip + counter + refund
4-//! one). The book/cancel workflows that sequence these live in4+//! in one). The book/cancel workflows that sequence these live in
5-//! [`crate::service::meal_booking`]; the row shape and the deadline checks in5+//! [`crate::service::meal_booking`]; the row shape and the deadline checks
6-//! [`crate::domain::meal_booking`].6+//! in [`crate::domain::meal_booking`].
7 7
8-use surrealdb::types::RecordId;8+use crate::database::{Database, tx_with_retry};
9-
10-use crate::constant::{CAP_WRITE_TRIES, MENU_SEAT_COUNT_FIELD, MENU_VERSION_FIELD};
11-use crate::database::{Database, backoff, lost_the_race};
12 use crate::db::cap::Claimed;9 use crate::db::cap::Claimed;
13 use crate::db::page::PagedList;10 use crate::db::page::PagedList;
14 use crate::domain::meal_booking::{MealBooking, MealBookingId};11 use crate::domain::meal_booking::{MealBooking, MealBookingId};
@@ -19,7 +16,16 @@ use crate::domain::user::UserId;
19 use crate::error::AppError;16 use crate::error::AppError;
20 17
21 pub async fn read(db: &Database, id: &MealBookingId) -> Result<Option<MealBooking>, AppError> {18 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)
23 }29 }
24 30
25 /// Every booking on a menu, cancelled ones included — the kitchen's list.31 /// Every booking on a menu, cancelled ones included — the kitchen's list.
@@ -30,10 +36,10 @@ pub async fn list_for_menu(
30 offset: i64,36 offset: i64,
31 ) -> Result<(Vec<MealBooking>, i64), AppError> {37 ) -> Result<(Vec<MealBooking>, i64), AppError> {
32 PagedList::new(38 PagedList::new(
33- "meal_booking WHERE menu = $menu",39+ "meal_booking WHERE menu = $1",
34- "ORDER BY created_at DESC, id DESC",40+ "ORDER BY created_at DESC, student DESC",
35 )41 )
36- .bind("menu", menu.record())42+ .bind(menu.key().to_string())
37 .run(limit, offset, db)43 .run(limit, offset, db)
38 .await44 .await
39 }45 }
@@ -41,10 +47,10 @@ pub async fn list_for_menu(
41 /// Every seat held for one of `students`, newest first — a caller's own47 /// Every seat held for one of `students`, newest first — a caller's own
42 /// list is themselves plus whoever they hold a *live* parent link to.48 /// list is themselves plus whoever they hold a *live* parent link to.
43 ///49 ///
44-/// Deliberately **not** `booked_by = $usr`: who placed a booking is history50+/// Deliberately **not** `booked_by`: who placed a booking is history
45-/// written onto a READONLY column, and history is not a read grant. A51+/// written onto a fixed column, and history is not a read grant. A parent
46-/// parent whose link was revoked (by an unlink or by the student-side role52+/// whose link was revoked (by an unlink or by the student-side role sweep)
47-/// sweep) would otherwise keep a live view of the child's seat, watching53+/// would otherwise keep a live view of the child's seat, watching
48 /// cancellations made long after the link died — exactly what54 /// cancellations made long after the link died — exactly what
49 /// [`ensure_can_observe`](crate::service::parent_link::ensure_can_observe) refuses. The55 /// [`ensure_can_observe`](crate::service::parent_link::ensure_can_observe) refuses. The
50 /// caller re-derives the list from the links on every read, so the view56 /// caller re-derives the list from the links on every read, so the view
@@ -55,34 +61,52 @@ pub async fn list_for_students(
55 limit: Option<i64>,61 limit: Option<i64>,
56 offset: i64,62 offset: i64,
57 ) -> Result<(Vec<MealBooking>, i64), AppError> {63 ) -> Result<(Vec<MealBooking>, i64), AppError> {
58- PagedList::new(64+ if students.is_empty() {
59- "meal_booking WHERE student IN $students",65+ return Ok((Vec::new(), 0));
60- "ORDER BY created_at DESC, id DESC",66+ }
61- )67+ let keys: Vec<String> = students.iter().map(UserId::key).collect();
62- .bind(68+ let rows = sqlx::query_as!(
63- "students",69+ MealBooking,
64- students.iter().map(UserId::record).collect::<Vec<_>>(),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,
65 )77 )
66- .run(limit, offset, db)78+ .fetch_all(db)
67- .await79+ .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))
68 }92 }
69 93
70 /// Take the seat **and** place the row in one transaction, at the menu94 /// Take the seat **and** place the row in one transaction, at the menu
71 /// revision the price was read at.95 /// revision the price was read at.
72 ///96 ///
73-/// The seat and the row cannot be two steps. The id is the (menu, student)97+/// The seat and the row cannot be two steps. The row key is the (menu,
74-/// pair, so two `POST`s of the same seat both find no row and both claim —98+/// student) pair, so two `POST`s of the same seat both find no row and both
75-/// and on a tight cap the second is then told "full" for a seat it never99+/// claim — and on a tight cap the second is then told "full" for a seat it
76-/// owed, while the winner's row may not even be visible yet. Here the100+/// never owed, while the winner's row may not even be visible yet. Here the
77-/// duplicate `CREATE` aborts the transaction, which takes its increment with101+/// duplicate insert answers [`Claimed::Duplicate`] and the caller replays
78-/// it: the counter never counts a row that does not exist, and a loser is102+/// the winner, while the whole transaction (seat bump included) rolls back
79-/// answered with the winner's booking instead of a refusal. Same shape as103+/// on any refused path: the counter never counts a row that does not exist.
80-/// [`cap::claim_and_create`](crate::db::cap::claim_and_create), with the104+/// Same shape as the [`crate::db::cap`] claim recipe, with the revision
81-/// revision guard and the revival of a cancelled row that the general form105+/// guard and the revival of a cancelled row that the general form does not
82-/// does not carry.106+/// carry.
83 ///107 ///
84 /// A cancelled row is revived in place (a fresh attempt at `price`) rather108 /// A cancelled row is revived in place (a fresh attempt at `price`) rather
85-/// than recreated: `booked_by` and `created_at` are READONLY history — who109+/// than recreated: `booked_by` and `created_at` are fixed history — who
86 /// opened the seat, and when.110 /// opened the seat, and when.
87 ///111 ///
88 /// **The charge rides this transaction too**, for the same reason the112 /// **The charge rides this transaction too**, for the same reason the
@@ -93,118 +117,135 @@ pub async fn list_for_students(
93 /// moved past. That is why `row.attempt` is minted by the *caller*: the117 /// moved past. That is why `row.attempt` is minted by the *caller*: the
94 /// charge's id is (seat, attempt), so the number cannot be the revival's own118 /// charge's id is (seat, attempt), so the number cannot be the revival's own
95 /// `attempt + 1` any more. The revival is fenced on the attempt it read119 /// `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`120+/// instead, so a rival that revived first loses this claim (the insert below
97-/// below then finds the row and aborts the whole transaction) rather than121+/// then finds the row and answers `Duplicate`) rather than billing its
98-/// billing its attempt at this call's id.122+/// attempt at this call's id.
99 ///123 ///
100-/// The charge is created only if it is not already there — a duplicate124+/// The charge is created only if it is not already there — an attempt
101-/// `CREATE` would abort the transaction and cost the seat, and an attempt
102 /// billed twice is the one thing money code may never do.125 /// billed twice is the one thing money code may never do.
103 pub(crate) async fn claim_and_place(126 pub(crate) async fn claim_and_place(
104 db: &Database,127 db: &Database,
105- seats: &RecordId,128+ menu: &MenuId,
106 cap: i64,129 cap: i64,
107 seen: i64,130 seen: i64,
108 row: &MealBooking,131 row: &MealBooking,
109 price: Option<LedgerAmount>,132 price: Option<LedgerAmount>,
110 charge: Option<&MealLedger>,133 charge: Option<&MealLedger>,
111 ) -> Result<Claimed<MealBooking>, AppError> {134 ) -> Result<Claimed<MealBooking>, AppError> {
112- // Empty when the menu is free: a seat that costs nothing owes no line.135+ let menu_key = menu.key().to_string();
113- let bill = match charge {136+ let student = row.student;
114- Some(_) => {137+ let attempt = row.attempt;
115- "IF array::len((SELECT VALUE id FROM $charge)) = 0 \138+ tx_with_retry(db, false, async |tx| {
116- { CREATE $charge CONTENT $line };"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);
117 }152 }
118- None => "",153+ // The seat: one conditional single-row write on the menu, atomic
119- };154+ // under Postgres — of the racers only `cap` of them per revision
120- // Slots count BEGIN, three LETs, three IFs and — when there is money to155+ // get a non-empty result, and the rest are refused with nothing
121- // take — the charge's IF, so the RETURN is slot 7 or 8.156+ // written.
122- let returned = if charge.is_some() { 8 } else { 7 };157+ let seat = sqlx::query!(
123- // Parenthesized `??` throughout: `a ?? 0 = $seen` binds the wrong way.158+ "UPDATE menu SET seats_booked = seats_booked + 1
124- let sql = format!(159+ WHERE id = $1 AND seats_booked < $2 AND COALESCE(version, 0) = $3
125- "BEGIN TRANSACTION;160+ RETURNING 1 AS seat",
126- LET $held = (SELECT VALUE id FROM $id WHERE status = 'booked');161+ menu_key,
127- IF array::len($held) > 0 {{ THROW 'held' }};162+ cap,
128- LET $seat = (UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = \163+ seen,
129- ({MENU_SEAT_COUNT_FIELD} ?? 0) + 1 \164+ )
130- WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) < $cap \165+ .fetch_optional(&mut *tx)
131- AND ({MENU_VERSION_FIELD} ?? 0) = $seen RETURN VALUE id);166+ .await?;
132- IF array::len($seat) = 0 {{ THROW 'no_seat' }};167+ if seat.is_none() {
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- {
178 return Ok(Claimed::Full);168 return Ok(Claimed::Full);
179 }169 }
180- if errors170+ // Revive a cancelled row only while it still stands at the attempt
181- .values()171+ // this call read — the fence that keeps a rival's revival from
182- .any(|error| error.to_string().contains("held") || error.is_already_exists())172+ // being billed at this call's ids.
183- {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 {
184 return Ok(Claimed::Duplicate);215 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())),
195 };216 };
196- }217+ // The charge rides the same transaction; already there (a replayed
197- Err(AppError::Conflict(218+ // POST of this seat) means fine — nothing is written twice.
198- "the menu kept changing underneath this booking",219+ if let Some(line) = charge {
199- ))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
200 }241 }
201 242
202 /// Flip the seat to `cancelled` and give it back to the menu's counter **in243 /// Flip the seat to `cancelled` and give it back to the menu's counter **in
203 /// one transaction**, so the two can never disagree: a decrement that ran244 /// one transaction**, so the two can never disagree: a decrement that ran
204 /// without the flip frees a seat still held, and a flip without the245 /// 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 the246+/// decrement locks a seat nothing can ever release. The decrement rides the
206-/// flip's own result (`array::len`), so a row already cancelled — by a247+/// flip's own result, so a row already cancelled — by a racing cancel, or
207-/// racing cancel, or by this call retried — decrements nothing.248+/// by this call retried — decrements nothing.
208 ///249 ///
209 /// **The refund rides this transaction too**, and it has to: the flip and a250 /// **The refund rides this transaction too**, and it has to: the flip and a
210 /// reversal appended after it are two writes, and a crash in between leaves251 /// reversal appended after it are two writes, and a crash in between leaves
@@ -230,77 +271,78 @@ pub(crate) async fn claim_and_place(
230 /// reversal id is burnt for good.271 /// reversal id is burnt for good.
231 ///272 ///
232 /// `None` = the row was not this call's own `booked` attempt any more.273 /// `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.
236 pub async fn release_seat(274 pub async fn release_seat(
237 db: &Database,275 db: &Database,
238 booked: &MealBooking,276 booked: &MealBooking,
239 recorded_by: &UserId,277 recorded_by: &UserId,
240 ) -> Result<Option<MealBooking>, AppError> {278 ) -> Result<Option<MealBooking>, AppError> {
241 let refund = MealLedger::reversal_for(booked, recorded_by);279 let refund = MealLedger::reversal_for(booked, recorded_by);
242- // Guarded three ways: nothing was flipped (a rival cancelled first, and280+ let menu_key = booked.menu.key().to_string();
243- // its own transaction carried the refund), the charge never landed, or281+ let student = booked.student;
244- // this attempt is already refunded — none of which may abort the flip.282+ let attempt = booked.attempt;
245- let reverse = match refund {283+ let cancelled_at = Timestamp::now();
246- Some(_) => {284+ tx_with_retry(db, false, async |tx| {
247- "IF array::len($flipped) > 0 \285+ let flipped = sqlx::query_as!(
248- AND array::len((SELECT VALUE id FROM $charge)) > 0 \286+ MealBooking,
249- AND array::len((SELECT VALUE id FROM $reversal)) = 0 \287+ "UPDATE meal_booking SET status = 'cancelled', cancelled_at = $3
250- { CREATE $reversal CONTENT $line };"288+ WHERE menu = $1 AND student = $2 AND status = 'booked' AND attempt = $4
251- }289+ RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at",
252- None => "",290+ menu_key,
253- };291+ student,
254- // Slots count BEGIN, the LET, the seat UPDATE and — when there is money292+ cancelled_at,
255- // to give back — the IF.293+ attempt,
256- let returned = if refund.is_some() { 4 } else { 3 };294+ )
257- // Same burst on the same counter as the book side, so the same patience295+ .fetch_optional(&mut *tx)
258- // (see [`claim_and_place`]) — a cancel that gave up left the seat296+ .await?;
259- // held with the charge standing. Admissible: the round aborts having297+ if flipped.is_some() {
260- // written nothing, and a re-send finds the row already `cancelled`, so298+ sqlx::query!(
261- // the flip matches nothing, the counter moves nothing and the guarded299+ "UPDATE menu SET seats_booked = GREATEST(seats_booked - 1, 0) WHERE id = $1",
262- // reversal — keyed to (seat, attempt) — is not written twice.300+ menu_key,
263- for attempt in 0..CAP_WRITE_TRIES {301+ )
264- backoff(attempt).await;302+ .execute(&mut *tx)
265- let attempted = async {303+ .await?;
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)
291 }304 }
292- .await;305+ // Guarded three ways: nothing was flipped (a rival cancelled first,
293- match attempted {306+ // and its own transaction carried the refund), the charge never
294- Ok(rows) => return Ok(rows.into_iter().next()),307+ // landed, or this attempt is already refunded — none of which may
295- Err(err) if lost_the_race(&err) => {}308+ // abort the flip.
296- Err(err) => return Err(err.into()),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+ }
297 }341 }
298- }342+ Ok(flipped)
299- Err(AppError::Conflict(343+ })
300- "the menu kept changing underneath this cancellation",344+ .await
301- ))
302 }345 }
303-
304 #[cfg(test)]346 #[cfg(test)]
305 mod tests {347 mod tests {
306 use super::*;348 use super::*;
src/db/meal_ledger.rsmodified+64 -77
@@ -3,29 +3,14 @@
3 //! convention live in [`crate::domain::meal_ledger`]; the charge/reversal3 //! convention live in [`crate::domain::meal_ledger`]; the charge/reversal
4 //! and credit workflows that sequence these in [`crate::service::meal_ledger`].4 //! and credit workflows that sequence these in [`crate::service::meal_ledger`].
5 5
6-use surrealdb::types::{AlreadyExistsError, SurrealValue};6+use crate::database::Database;
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;
11 use crate::db::page::PagedList;7 use crate::db::page::PagedList;
12-use crate::domain::meal_ledger::{LedgerAmount, MealLedger, MealLedgerId, MealLedgerKind};8+use crate::domain::meal_ledger::{LedgerAmount, MealLedger, MealLedgerId};
13 use crate::domain::menu::MenuId;9 use crate::domain::menu::MenuId;
14 use crate::domain::user::UserId;10 use crate::domain::user::UserId;
15 use crate::error::AppError;11 use crate::error::AppError;
16 12
17-/// Did this `CREATE` fail *only* because the row is already there? Matched on13+/// The only writer: one `INSERT`, no update path anywhere in this module.
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.
29 ///14 ///
30 /// A line whose id already exists is left exactly as it is — the row wins,15 /// A line whose id already exists is left exactly as it is — the row wins,
31 /// the write is dropped. That is what makes a deterministic id (see16 /// the write is dropped. That is what makes a deterministic id (see
@@ -33,38 +18,52 @@ fn is_duplicate_record(error: &surrealdb::Error) -> bool {
33 /// append is a no-op, never a second line and never an edit of the first.18 /// append is a no-op, never a second line and never an edit of the first.
34 /// The point read is on the id itself, so unlike a scan it cannot miss a19 /// The point read is on the id itself, so unlike a scan it cannot miss a
35 /// row a concurrent writer just made — but it is only a fast path. The20 /// 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 leaves21+/// guarantee is the insert's own `ON CONFLICT (id) DO NOTHING`: on an
37-/// the row untouched, so the writer that lost the race reads back the22+/// existing id nothing is written, so the writer that lost the race reads
38-/// winner's line instead of failing the request with a 500.23+/// back the 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.
46 pub(crate) async fn append(db: &Database, row: MealLedger) -> Result<MealLedger, AppError> {24 pub(crate) async fn append(db: &Database, row: MealLedger) -> Result<MealLedger, AppError> {
47 if let Some(existing) = read(db, &row.id).await? {25 if let Some(existing) = read(db, &row.id).await? {
48 return Ok(existing);26 return Ok(existing);
49 }27 }
50- let id = row.id.clone();28+ let inserted = sqlx::query_as!(
51- for _ in 0..CAS_UPDATE_RETRIES {29+ MealLedger,
52- match db.create(id.record()).content(row.clone()).await {30+ "INSERT INTO meal_ledger
53- Ok(Some(created)) => return Ok(created),31+ (id, student, kind, amount_minor, source, method, note, recorded_by, created_at)
54- Ok(None) => break,32+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
55- Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => {33+ ON CONFLICT (id) DO NOTHING
56- if let Some(existing) = read(db, &id).await? {34+ RETURNING id, student, kind, amount_minor, source, method, note, recorded_by, created_at",
57- return Ok(existing);35+ row.id.key(),
58- }36+ row.student,
59- }37+ row.kind,
60- Err(e) => return Err(e.into()),38+ row.amount_minor,
61- }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())),
62 }54 }
63- Err(AppError::Internal("failed to write the ledger line".into()))
64 }55 }
65 56
66 pub async fn read(db: &Database, id: &MealLedgerId) -> Result<Option<MealLedger>, AppError> {57 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)
68 }67 }
69 68
70 /// What a seat on `menu` costs *right now*: the sum of its dishes. `None`69 /// What a seat on `menu` costs *right now*: the sum of its dishes. `None`
@@ -77,12 +76,11 @@ pub async fn price_snapshot(
77 db: &Database,76 db: &Database,
78 menu: &MenuId,77 menu: &MenuId,
79 ) -> Result<Option<LedgerAmount>, AppError> {78 ) -> Result<Option<LedgerAmount>, AppError> {
80- let total = menu_dish::list_for_menu(db, menu)79+ let row =
81- .await?80+ sqlx::query!("SELECT CAST(COALESCE(sum(price_minor), 0) AS BIGINT) AS total FROM menu_dish WHERE menu = $1", menu.key())
82- .iter()81+ .fetch_one(db)
83- .fold(0i64, |sum, dish| {82+ .await?;
84- sum.saturating_add(dish.get_price_minor().as_minor())83+ let total = row.total;
85- });
86 if total == 0 {84 if total == 0 {
87 return Ok(None);85 return Ok(None);
88 }86 }
@@ -97,10 +95,10 @@ pub async fn list_for_student(
97 offset: i64,95 offset: i64,
98 ) -> Result<(Vec<MealLedger>, i64), AppError> {96 ) -> Result<(Vec<MealLedger>, i64), AppError> {
99 PagedList::new(97 PagedList::new(
100- "meal_ledger WHERE student = $student",98+ "meal_ledger WHERE student = $1",
101 "ORDER BY created_at DESC, id DESC",99 "ORDER BY created_at DESC, id DESC",
102 )100 )
103- .bind("student", student.record())101+ .bind(student.key())
104 .run(limit, offset, db)102 .run(limit, offset, db)
105 .await103 .await
106 }104 }
@@ -118,38 +116,27 @@ pub async fn list_for_student(
118 /// every later `GET /meals/balance/*`.116 /// every later `GET /meals/balance/*`.
119 ///117 ///
120 /// **The signs stay on the kind**, applied by the very118 /// **The signs stay on the kind**, applied by the very
121-/// [`MealLedgerKind::sign`]119+/// [`MealLedgerKind::sign`](crate::domain::meal_ledger::MealLedgerKind::sign)
122-/// the documented formula is spelled in. Summing `IF kind = 'charge' THEN120+/// the documented formula is spelled in. Summing a signed CASE in SQL would
123-/// -amount …` in SQL would have folded the whole balance in one statement121+/// have folded the whole balance in one statement and forked the one rule
124-/// and forked the one rule that decides what money means into a second122+/// that decides what money means into a second language, where nothing
125-/// language, where nothing would fail the day the two disagreed. Grouping123+/// would fail the day the two disagreed. Grouping instead keeps the
126-/// instead keeps the aggregate ignorant of signs: it counts kinds, and124+/// aggregate ignorant of signs: it counts kinds, and Rust still says what a
127-/// Rust still says what a kind does. A stored running total was the third125+/// kind does. A stored running total was the third option and is a counter
128-/// option and is a counter that can drift — a bug class this repo closes,126+/// that can drift — a bug class this repo closes, not one it opens.
129-/// not one it opens.
130 pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError> {127 pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError> {
131- let totals: Vec<KindTotal> = db128+ let totals = sqlx::query!(
132- .query(format!(129+ r#"SELECT kind AS "kind: crate::domain::meal_ledger::MealLedgerKind",
133- "SELECT kind, math::sum(amount_minor) AS total \130+ CAST(sum(amount_minor) AS BIGINT) AS total
134- FROM {MEAL_LEDGER_TABLE} WHERE student = $student GROUP BY kind"131+ FROM meal_ledger WHERE student = $1 GROUP BY kind"#,
135- ))132+ *student,
136- .bind(("student", student.record()))133+ )
137- .await?134+ .fetch_all(db)
138- .check()?135+ .await?;
139- .take(0)?;
140 Ok(totals136 Ok(totals
141 .iter()137 .iter()
142 .fold(0i64, |sum, row| sum + row.kind.sign() * row.total))138 .fold(0i64, |sum, row| sum + row.kind.sign() * row.total))
143 }139 }
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-
153 #[cfg(test)]140 #[cfg(test)]
154 mod tests {141 mod tests {
155 use super::*;142 use super::*;
src/db/menu.rsmodified+173 -205
@@ -1,100 +1,33 @@
1 //! The `menu` table: publishing (the slot reference claimed inside the1 //! The `menu` table: publishing (the slot reference claimed inside the
2 //! write's own transaction), row reads and listings, the compare-and-set2 //! write's own transaction), row reads and listings, the compare-and-set
3-//! every cap PATCH writes through, the cascading delete, and3+//! every cap PATCH writes through, and the cascading delete. The kitchen
4-//! [`bump_menu_and_write`] — the shared "write the menu row too" shape every4+//! workflows — the guarded dish-cap insert — live in
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
8 //! [`crate::service::menu`].5 //! [`crate::service::menu`].
9 6
10-use surrealdb::types::{SurrealValue, Value};7+use crate::database::{Database, tx_with_retry, unique_violation};
11-8+use crate::db::page::{PagedList, Param};
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;
19 use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, slot_ref};9 use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, slot_ref};
20 use crate::domain::timestamp::Timestamp;10 use crate::domain::timestamp::Timestamp;
21 use crate::domain::user::UserId;11 use crate::domain::user::UserId;
22 use crate::error::AppError;12 use crate::error::AppError;
23 13
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-
90 /// Publish a menu. Refused (409) when the day+slot already carries one.14 /// Publish a menu. Refused (409) when the day+slot already carries one.
91 ///15 ///
92-/// The day and slot *are* the record id ([`MenuId::for_slot`]), so the16+/// The day and slot *are* the row's primary key ([`MenuId::for_slot`]), so
93-/// refusal is decided by the store rather than by a check a concurrent17+/// the 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's18+/// publish can outrun: two publishes of the same meal write one row, and
95-/// "already exists" becomes the same 409. The pre-check stays for the19+/// the loser's unique violation on `menu_pkey` becomes the same 409. The
96-/// ordinary case — and for menus published before ids were derived, whose20+/// in-transaction pre-check stays for the ordinary case.
97-/// ULID key no new publish can collide with.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.
98 pub async fn create(31 pub async fn create(
99 db: &Database,32 db: &Database,
100 date: MenuDate,33 date: MenuDate,
@@ -102,39 +35,80 @@ pub async fn create(
102 capacity: Option<i64>,35 capacity: Option<i64>,
103 created_by: &UserId,36 created_by: &UserId,
104 ) -> Result<Menu, AppError> {37 ) -> Result<Menu, AppError> {
105- let taken = AppError::Conflict("a menu is already published for that date and slot");38+ let id_key = MenuId::for_slot(&date, &slot).key().to_string();
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.
115 let counter = slot_ref(slot.as_str());39 let counter = slot_ref(slot.as_str());
116- let menu = Menu {40+ let date_s = date.as_str().to_string();
117- id: MenuId::for_slot(&date, &slot),41+ let slot_s = slot.as_str().to_string();
118- date,42+ let created_by = *created_by;
119- slot,43+ let created_at = Timestamp::now();
120- capacity,44+ tx_with_retry(db, false, async |tx| {
121- version: Some(0),45+ // Duplicate gate ahead of the retired check: "already published"
122- created_by: created_by.clone(),46+ // outranks "slot retired", on the very path a rival publish races.
123- created_at: Timestamp::now(),47+ let exists = sqlx::query!("SELECT 1 AS taken FROM menu WHERE id = $1", id_key,)
124- };48+ .fetch_optional(&mut *tx)
125- let id = menu.id.record();49+ .await?;
126- match cap::claim_ref_and_create(&counter, 1, &id, &menu, db).await? {50+ if exists.is_some() {
127- cap::ClaimedRef::Made(created) => Ok(created),51+ return Err(AppError::Conflict(
128- cap::ClaimedRef::Duplicate => Err(taken),52+ "a menu is already published for that date and slot",
129- cap::ClaimedRef::Retired => Err(AppError::ConflictOwned(format!(53+ ));
130- "the '{}' meal slot has been removed from the school's settings",54+ }
131- menu.slot.as_str()55+ let inserted = match sqlx::query_as!(
132- ))),56+ Menu,
133- }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
134 }100 }
135 101
136 pub async fn read(db: &Database, id: &MenuId) -> Result<Option<Menu>, AppError> {102 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)
138 }112 }
139 113
140 /// The menu for one day and slot, if any — the uniqueness check.114 /// The menu for one day and slot, if any — the uniqueness check.
@@ -143,18 +117,21 @@ pub async fn find(
143 date: &MenuDate,117 date: &MenuDate,
144 slot: &MenuSlot,118 slot: &MenuSlot,
145 ) -> Result<Option<Menu>, AppError> {119 ) -> Result<Option<Menu>, AppError> {
146- let mut result = db120+ let row = sqlx::query_as!(
147- .query("SELECT * FROM menu WHERE date = $date AND slot = $slot LIMIT 1")121+ Menu,
148- .bind(("date", date.as_str().to_string()))122+ "SELECT id, date, slot, capacity, version, created_by, created_at
149- .bind(("slot", slot.as_str().to_string()))123+ FROM menu WHERE date = $1 AND slot = $2 LIMIT 1",
150- .await?124+ date.as_str(),
151- .check()?;125+ slot.as_str(),
152- Ok(result.take::<Vec<Menu>>(0)?.into_iter().next())126+ )
127+ .fetch_optional(db)
128+ .await?;
129+ Ok(row)
153 }130 }
154 131
155 /// Menus, newest day first. `from`/`to` are inclusive `YYYY-MM-DD` bounds;132 /// Menus, newest day first. `from`/`to` are inclusive `YYYY-MM-DD` bounds;
156-/// either may be omitted. The comparison is lexical, which is chronological133+/// either may be omitted (`NULL` bound). The comparison is lexical, which
157-/// for this format.134+/// is chronological for this format.
158 pub async fn list(135 pub async fn list(
159 db: &Database,136 db: &Database,
160 from: Option<&MenuDate>,137 from: Option<&MenuDate>,
@@ -163,25 +140,26 @@ pub async fn list(
163 offset: i64,140 offset: i64,
164 ) -> Result<(Vec<Menu>, i64), AppError> {141 ) -> Result<(Vec<Menu>, i64), AppError> {
165 PagedList::new(142 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)",
167 "ORDER BY date DESC, slot ASC, id DESC",145 "ORDER BY date DESC, slot ASC, id DESC",
168 )146 )
169- .bind("from", from.map(|date| date.as_str().to_string()))147+ .bind(Param::OptText(from.map(|date| date.as_str().to_string())))
170- .bind("to", to.map(|date| date.as_str().to_string()))148+ .bind(Param::OptText(to.map(|date| date.as_str().to_string())))
171 .run(limit, offset, db)149 .run(limit, offset, db)
172 .await150 .await
173 }151 }
174 152
175-/// Only `capacity` is writable: `date` and `slot` are `READONLY` columns,153+/// Only `capacity` is writable: `date` and `slot` are fixed at publish,
176 /// because moving a published menu to another day is a different menu.154 /// because moving a published menu to another day is a different menu.
177 /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped.155 /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped.
178 ///156 ///
179 /// The revision moves **in the same statement** as the cap, indivisibly: a157 /// The revision moves **in the same statement** as the cap, indivisibly: a
180-/// booking claims its seat against the revision158+/// booking claims its seat against the revision it read the cap at, so a
181-/// it read the cap at, so a shrink that bumped in a query of its own left a159+/// shrink that bumped in a query of its own left a window where the row
182-/// window where the row carried the *new* revision and the *old* cap — and160+/// carried the *new* revision and the *old* cap — and a booking arriving
183-/// a booking arriving there passes a CAS meant to refuse it, over-admitting161+/// there passes a CAS meant to refuse it, over-admitting by exactly the
184-/// by exactly the seats in flight.162+/// seats in flight.
185 pub async fn update(163 pub async fn update(
186 db: &Database,164 db: &Database,
187 menu: Menu,165 menu: Menu,
@@ -192,99 +170,89 @@ pub async fn update(
192 // booking's price or cap has moved, so none owes a re-read.170 // booking's price or cap has moved, so none owes a re-read.
193 return read(db, &menu.id).await?.ok_or(AppError::NotFound);171 return read(db, &menu.id).await?.ok_or(AppError::NotFound);
194 };172 };
195- let sql = format!(173+ let row = sqlx::query_as!(
196- "UPDATE $id SET capacity = $capacity, \174+ Menu,
197- {MENU_VERSION_FIELD} = ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN AFTER"175+ "UPDATE menu SET capacity = $2, version = COALESCE(version, 0) + 1
198- );176+ WHERE id = $1
199- // One counter write in flight at a time, like every other one.177+ RETURNING id, date, slot, capacity, version, created_by, created_at",
200- let _guard = cap::counter_lock().await;178+ menu.id.key(),
201- write_with_retry::<Menu>(179+ capacity,
202- db,
203- &sql,
204- &[
205- ("id".into(), menu.id.record().into_value()),
206- ("capacity".into(), capacity.into_value()),
207- ],
208 )180 )
209- .await?181+ .fetch_optional(db)
210- .into_iter()182+ .await?;
211- .next()183+ row.ok_or(AppError::NotFound)
212- .ok_or(AppError::NotFound)
213 }184 }
214 185
215-/// Delete the menu and the dishes on it — a dish has no meaning without186+/// Delete the menu and the dishes and marks on it — a dish or a mark has
216-/// its menu, and the `menu` link is `READONLY`, so it cannot be re-homed.187+/// no meaning without its menu, and the menu key cannot be re-homed.
217 ///188 ///
218 /// Refused (409) while a seat is still held, and the *row itself* decides189 /// Refused (409) while a seat is still held, and the *row itself* decides
219 /// that: the delete carries the seat counter in its `WHERE`, so a booking190 /// that: the delete carries the seat counter in its `WHERE`, so a booking
220-/// landing at that instant either takes its seat before191+/// landing at that instant either takes its seat before the delete (which
221-/// the delete (which then finds a non-zero counter and refuses) or after it192+/// then finds a non-zero counter and refuses) or after it (and finds no
222-/// (and finds no menu). A read-then-delete pair had a window where both193+/// menu). A read-then-delete pair had a window where both happened — a
223-/// happened — a paid seat on a menu that no longer exists.194+/// paid seat on a menu that no longer exists.
224 ///195 ///
225 /// The slot gets its reference back in that same transaction — a slot no196 /// 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 the197+/// menu is published for any more may leave the settings again. Released
227-/// `FOR` runs only over a row the guard actually took. Released afterwards198+/// afterwards in a statement of its own, a crash between the two left the
228-/// in a query of its own, a crash between the two left the slot counted by199+/// slot counted by a menu that no longer exists: a slot nobody can retire.
229-/// a menu that no longer exists: a slot nobody can retire.
230 ///200 ///
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:
232 /// [`MenuId::for_slot`] is deterministic, so republishing the same day and202 /// [`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 a203+/// slot mints the *same* row key. A mark left behind would come back as a
234 /// mark on the new menu — the kitchen reading "served" for a student who204 /// mark on the new menu — the kitchen reading "served" for a student who
235 /// never came — and until then the student's own report cites a menu that205 /// never came — and until then the student's own report cites a menu that
236 /// is gone. Attendance carries no money and no counter, so it is safe to206 /// is gone. Attendance carries no money and no counter, so it is safe to
237-/// drop; cancelled *bookings* deliberately stay, because their `attempt`207+/// drop; cancelled *bookings* deliberately stay (no foreign key ties them
238-/// counter is what keeps the ledger's `(booking, attempt)` keys unique. Cut208+/// to the menu), because their `attempt` counter is what keeps the
209+/// ledger's `(booking, attempt)` keys unique across the republish. Cut
239 /// those and a re-book on a republished menu would reuse a charge id the210 /// those and a re-book on a republished menu would reuse a charge id the
240 /// ledger already holds, and the append (idempotent by design) would bill211 /// ledger already holds, and the append (idempotent by design) would bill
241 /// the seat nothing.212 /// the seat nothing.
242 ///213 ///
243-/// The dishes ride in that `FOR` too, and for the same reason as the marks:214+/// The dishes ride in the same sweep: run after the commit, a crash
244-/// run after the transaction committed, a crash between the two orphaned215+/// between the two would orphan them on the row key a republish mints
245-/// them on a record id republishing the day and slot mints again — a new216+/// again — a new menu serving (and pricing) the old one's food.
246-/// menu serving (and pricing) the old one's food.
247 pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> {217 pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> {
248- let sql = format!(218+ let key = menu.id.key().to_string();
249- "BEGIN TRANSACTION;219+ let counter = slot_ref(menu.slot.as_str());
250- LET $gone = (DELETE $id WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE);220+ let deleted = tx_with_retry(db, true, async |tx| {
251- FOR $row IN ($gone ?? []) {{221+ let deleted = sqlx::query_as!(
252- UPSERT $counter SET {REF_COUNT_FIELD} = \222+ Menu,
253- math::max([({REF_COUNT_FIELD} ?? 0) - 1, 0]);223+ "DELETE FROM menu WHERE id = $1 AND seats_booked = 0
254- DELETE {MEAL_ATTENDANCE_TABLE} WHERE menu = $id;224+ RETURNING id, date, slot, capacity, version, created_by, created_at",
255- DELETE {MENU_DISH_TABLE} WHERE menu = $id;225+ key,
256- }};226+ )
257- RETURN $gone;227+ .fetch_optional(&mut *tx)
258- COMMIT TRANSACTION;"228+ .await?;
259- );229+ let Some(row) = deleted else {
260- // `slot` is a `READONLY` column, so this counter is the one the deleted230+ return Ok(None);
261- // row carries. Nothing here can answer "already exists" — the `UPSERT`231+ };
262- // is keyed by a slot name on a table with no `UNIQUE` index, so it232+ sqlx::query!(
263- // resolves onto the row it names ([`transaction_with_retry`]).233+ "UPDATE slot_ref SET count = GREATEST(count - 1, 0) WHERE name = $1",
264- let (mut result, mut errors) = transaction_with_retry(234+ counter,
265- db,235+ )
266- &sql,236+ .execute(&mut *tx)
267- &[237+ .await?;
268- ("id".into(), menu.id.record().into_value()),238+ sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key)
269- ("counter".into(), slot_ref(menu.slot.as_str()).into_value()),239+ .execute(&mut *tx)
270- ],240+ .await?;
271- &[],241+ sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key)
272- )242+ .execute(&mut *tx)
243+ .await?;
244+ Ok(Some(row))
245+ })
273 .await?;246 .await?;
274- if let Some(error) = errors.drain().map(|(_, error)| error).next() {247+ match deleted {
275- return Err(error.into());248+ Some(menu) => Ok(menu),
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 {
279 // Nothing back: either seats are held, or the menu is already gone.249 // Nothing back: either seats are held, or the menu is already gone.
280- return Err(match read(db, &menu.id).await? {250+ None => match read(db, &menu.id).await? {
281- Some(_) => AppError::Conflict("the menu still has live bookings"),251+ Some(_) => Err(AppError::Conflict("the menu still has live bookings")),
282- None => AppError::NotFound,252+ None => Err(AppError::NotFound),
283- });253+ },
284- };254+ }
285- Ok(deleted)
286 }255 }
287-
288 #[cfg(test)]256 #[cfg(test)]
289 mod tests {257 mod tests {
290 use super::*;258 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 field1+//! The `menu_dish` table: the dishes on a menu — the guarded insert (the
2-//! PATCH riding the menu's revision bump ([`bump_menu_and_write`]), the2+//! dish cap, enforced by the menu row's own lock), the field PATCH riding
3-//! reads and listings, and the delete. The dish-cap gate and the3+//! the menu's revision bump, the reads and listings, and the delete. The
4-//! [`MENU_LOCK`](crate::service::menu::MENU_LOCK) leases live in4+//! kitchen workflows live in [`crate::service::menu`].
5-//! [`crate::service::menu`].
6 5
7-use surrealdb::types::{SurrealValue, Value};6+use crate::database::{Database, tx_with_retry};
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;
12 use crate::domain::menu::MenuId;7 use crate::domain::menu::MenuId;
13 use crate::domain::menu_dish::{8 use crate::domain::menu_dish::{
14 DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId,9 DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId,
@@ -16,7 +11,15 @@ use crate::domain::menu_dish::{
16 use crate::domain::timestamp::Timestamp;11 use crate::domain::timestamp::Timestamp;
17 use crate::error::AppError;12 use crate::error::AppError;
18 13
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.
20 pub async fn create(23 pub async fn create(
21 db: &Database,24 db: &Database,
22 menu: &MenuId,25 menu: &MenuId,
@@ -24,67 +27,67 @@ pub async fn create(
24 description: Option<DishDescription>,27 description: Option<DishDescription>,
25 price_minor: DishPrice,28 price_minor: DishPrice,
26 tags: DishTags,29 tags: DishTags,
30+ cap: i64,
27 ) -> Result<MenuDish, AppError> {31 ) -> Result<MenuDish, AppError> {
28- let dish = MenuDish {32+ let menu_key = menu.key().to_string();
29- id: MenuDishId::generate(),33+ let id = MenuDishId::generate();
30- menu: menu.clone(),34+ let created_at = Timestamp::now();
31- name,35+ tx_with_retry(db, false, async |tx| {
32- description,36+ // The lock first: every later statement in this transaction then
33- price_minor,37+ // sees the committed state of whoever queued ahead of it.
34- tags,38+ let locked = sqlx::query!(
35- created_at: Timestamp::now(),39+ "SELECT 1 AS locked FROM menu WHERE id = $1 FOR NO KEY UPDATE",
36- };40+ menu_key,
37- // The revision bump and the insert are one transaction, and the bump is41+ )
38- // what makes the menu's existence part of it: the `UPDATE` matches42+ .fetch_optional(&mut *tx)
39- // nothing once the menu row is deleted, and a delete racing this one43+ .await?;
40- // touches the very key this transaction writes, so the two cannot both44+ if locked.is_none() {
41- // commit. Without that, a dish landing just after `DELETE /menus/{id}`45+ return Err(AppError::NotFound);
42- // removed the row but before its cascade ran outlived its menu.46+ }
43- // Every other dish write bumps the same version key, so a lost round is47+ sqlx::query!(
44- // ordinary here; it is re-sent rather than reported. Re-sending is sound48+ "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1",
45- // even with the `CREATE` in the batch — the abort wrote nothing, the id49+ menu_key,
46- // is a ULID freshly generated above and never seen by a rival, and50+ )
47- // `menu_dish` carries no UNIQUE index — so the retry cannot answer51+ .execute(&mut *tx)
48- // "already exists" (see [`transaction_with_retry`]).52+ .await?;
49- let (mut result, mut errors) = transaction_with_retry(53+ let placed = sqlx::query_as!(
50- db,54+ MenuDish,
51- &format!(55+ "INSERT INTO menu_dish (id, menu, name, description, price_minor, tags, created_at)
52- "BEGIN TRANSACTION;56+ SELECT $1, $2, $3, $4, $5, $6, $7
53- LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \57+ WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $8
54- ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id);58+ RETURNING id, menu, name, description, price_minor, tags, created_at",
55- IF array::len($bumped) = 0 {{ THROW 'no_menu' }};59+ id,
56- CREATE $id CONTENT $dish;60+ menu_key,
57- COMMIT TRANSACTION;"61+ name,
58- ),62+ description,
59- &[63+ price_minor,
60- ("menu".into(), menu.record().into_value()),64+ tags,
61- ("id".into(), dish.id.record().into_value()),65+ created_at,
62- ("dish".into(), dish.into_value()),66+ cap,
63- ],67+ )
64- &["no_menu"],68+ .fetch_optional(&mut *tx)
65- )69+ .await?;
66- .await?;70+ match placed {
67- // An aborted transaction errors *every* slot, most with a generic "not71+ Some(dish) => Ok(dish),
68- // executed" — only the THROW's own slot names the reason.72+ // The menu exists (locked above), so an empty result is the cap.
69- if errors73+ None => Err(AppError::Conflict(
70- .values()74+ "the menu already carries the maximum number of dishes",
71- .any(|error| error.to_string().contains("no_menu"))75+ )),
72- {76+ }
73- return Err(AppError::NotFound);77+ })
74- }78+ .await
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()))
84 }79 }
85 80
86 pub async fn read(db: &Database, id: &MenuDishId) -> Result<Option<MenuDish>, AppError> {81 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)
88 }91 }
89 92
90 /// Every dish on one menu, in the order they were added.93 /// 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
98 if menus.is_empty() {101 if menus.is_empty() {
99 return Ok(Vec::new());102 return Ok(Vec::new());
100 }103 }
101- let mut result = db104+ let keys: Vec<String> = menus.iter().map(|m| m.key().to_string()).collect();
102- .query("SELECT * FROM menu_dish WHERE menu IN $menus ORDER BY id ASC")105+ let rows = sqlx::query_as!(
103- .bind((106+ MenuDish,
104- "menus",107+ "SELECT id, menu, name, description, price_minor, tags, created_at
105- menus.iter().map(MenuId::record).collect::<Vec<_>>(),108+ FROM menu_dish WHERE menu = ANY($1) ORDER BY id ASC",
106- ))109+ keys,
107- .await?110+ )
108- .check()?;111+ .fetch_all(db)
109- Ok(result.take::<Vec<MenuDish>>(0)?)112+ .await?;
110-}113+ Ok(rows)
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())
115 }114 }
116 115
117 /// Write only the fields the PATCH carried. `description` is nullable, so116 /// Write only the fields the PATCH carried. `description` is nullable, so
118 /// it takes the three-way shape: absent = keep, `Some(None)` = clear.117 /// 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.
119 ///121 ///
120-/// The `SET` is built here rather than by122+/// The revision bump lands in the same transaction — "every dish write
121-/// [`FieldUpdate`](crate::db::field_update::FieldUpdate) because the123+/// bumps" is the rule a caller can rely on without knowing which fields
122-/// revision bump lands on *another* row and has to share this write's124+/// were on the wire. A PATCH that carried nothing still bumps and reads
123-/// transaction; the field-by-field scoping — an omitted field is never125+/// the row back.
124-/// written, so a concurrent PATCH of another one is not reverted — is the
125-/// same rule, spelled out.
126 pub async fn update(126 pub async fn update(
127 db: &Database,127 db: &Database,
128 dish: MenuDish,128 dish: MenuDish,
@@ -131,45 +131,68 @@ pub async fn update(
131 price_minor: Option<DishPrice>,131 price_minor: Option<DishPrice>,
132 tags: Option<DishTags>,132 tags: Option<DishTags>,
133 ) -> Result<MenuDish, AppError> {133 ) -> Result<MenuDish, AppError> {
134- let mut sets: Vec<&str> = Vec::new();134+ let dish_key = dish.id.key();
135- let mut bindings: Vec<(String, Value)> = vec![("id".into(), dish.id.record().into_value())];135+ let menu_key = dish.menu.key().to_string();
136- let mut set = |field: &'static str, value: Option<Value>| {136+ tx_with_retry(db, false, async |tx| {
137- if let Some(value) = value {137+ let bumped = sqlx::query!(
138- sets.push(field);138+ "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1
139- bindings.push((field.into(), value));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);
140 }146 }
141- };147+ let row = sqlx::query_as!(
142- set("name", name.map(SurrealValue::into_value));148+ MenuDish,
143- set("description", description.map(SurrealValue::into_value));149+ "UPDATE menu_dish SET
144- set("price_minor", price_minor.map(SurrealValue::into_value));150+ name = COALESCE($2, name),
145- set("tags", tags.map(SurrealValue::into_value));151+ description = CASE WHEN $3 THEN $4 ELSE description END,
146- // A PATCH that carried nothing writes nothing and reads the row back,152+ price_minor = COALESCE($5, price_minor),
147- // exactly as `FieldUpdate` answers one — but it still moves the153+ tags = COALESCE($6, tags)
148- // revision, because "every dish write bumps" is the rule a caller can154+ WHERE id = $1
149- // rely on without knowing which fields were on the wire.155+ RETURNING id, menu, name, description, price_minor, tags, created_at",
150- let statement = if sets.is_empty() {156+ dish_key,
151- "SELECT * FROM $id".to_string()157+ name.map(|n| n.as_str().to_string()),
152- } else {158+ description.is_some(),
153- format!(159+ description
154- "UPDATE $id SET {} RETURN AFTER",160+ .clone()
155- sets.iter()161+ .flatten()
156- .map(|field| format!("{field} = ${field}"))162+ .map(|d| d.as_str().to_string()),
157- .collect::<Vec<_>>()163+ price_minor.map(DishPrice::as_minor),
158- .join(", ")164+ tags.map(|t| t.as_slice().to_vec()),
159 )165 )
160- };166+ .fetch_optional(&mut *tx)
161- bump_menu_and_write(&dish.menu, &statement, bindings, db)167+ .await?;
162- .await?168+ row.ok_or(AppError::NotFound)
163- .ok_or(AppError::NotFound)169+ })
170+ .await
164 }171 }
165 172
166 pub async fn delete(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> {173 pub async fn delete(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> {
167- bump_menu_and_write(174+ let dish_key = dish.id.key();
168- &dish.menu,175+ let menu_key = dish.menu.key().to_string();
169- "DELETE $id RETURN BEFORE",176+ tx_with_retry(db, false, async |tx| {
170- vec![("id".into(), dish.id.record().into_value())],177+ let bumped = sqlx::query!(
171- db,178+ "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1
172- )179+ RETURNING 1 AS bumped",
173- .await?180+ menu_key,
174- .ok_or(AppError::NotFound)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
175 }198 }
src/db/note.rsmodified+61 -44
@@ -1,9 +1,7 @@
1 //! The `note` table: one user's rows, listed newest first, deleted together1 //! The `note` table: one user's rows, listed newest first, deleted together
2 //! with their attachment rows.2 //! with their attachment rows.
3 3
4-use surrealdb::types::SurrealValue;4+use crate::database::{Database, tx_with_retry};
5-
6-use crate::database::Database;
7 use crate::db::field_update::FieldUpdate;5 use crate::db::field_update::FieldUpdate;
8 use crate::db::page::PagedList;6 use crate::db::page::PagedList;
9 use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle};7 use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle};
@@ -11,15 +9,6 @@ use crate::domain::note_file::NoteFile;
11 use crate::domain::user::UserId;9 use crate::domain::user::UserId;
12 use crate::error::AppError;10 use crate::error::AppError;
13 11
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-
23 pub async fn create(12 pub async fn create(
24 db: &Database,13 db: &Database,
25 owner: &UserId,14 owner: &UserId,
@@ -32,8 +21,20 @@ pub async fn create(
32 title,21 title,
33 content,22 content,
34 };23 };
35- let created: Option<Note> = db.create(note.id.record()).content(note).await?;24+ // whole-row-save-ok: insert of a fresh UUID row built in place by `new` — there is no prior row to clobber
36- created.ok_or_else(|| AppError::Internal("failed to create note".into()))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)
37 }38 }
38 39
39 /// Read a note only if it belongs to `owner`.40 /// Read a note only if it belongs to `owner`.
@@ -42,8 +43,15 @@ pub async fn read_owned(
42 id: &NoteId,43 id: &NoteId,
43 owner: &UserId,44 owner: &UserId,
44 ) -> Result<Option<Note>, AppError> {45 ) -> Result<Option<Note>, AppError> {
45- let note: Option<Note> = db.select(id.record()).await?;46+ let note = sqlx::query_as!(
46- Ok(note.filter(|note| &note.user == owner))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)
47 }55 }
48 56
49 pub async fn list_for(57 pub async fn list_for(
@@ -52,9 +60,9 @@ pub async fn list_for(
52 limit: Option<i64>,60 limit: Option<i64>,
53 offset: i64,61 offset: i64,
54 ) -> Result<(Vec<Note>, i64), AppError> {62 ) -> Result<(Vec<Note>, i64), AppError> {
55- PagedList::new("note WHERE user = $usr", "ORDER BY id DESC")63+ PagedList::new("note WHERE app_user = $1", "ORDER BY id DESC")
56- .bind("usr", owner.record())64+ .bind(owner.uuid())
57- .run(limit, offset, db)65+ .run::<Note>(limit, offset, db)
58 .await66 .await
59 }67 }
60 68
@@ -70,9 +78,12 @@ pub async fn update(
70 title: Option<NoteTitle>,78 title: Option<NoteTitle>,
71 content: Option<NoteContent>,79 content: Option<NoteContent>,
72 ) -> Result<Note, AppError> {80 ) -> Result<Note, AppError> {
73- FieldUpdate::new(note.id.record())81+ FieldUpdate::new("note", note.id.uuid())
74- .set("title", title)82+ .set("title", title.map(|title| title.as_str().to_string()))
75- .set("content", content)83+ .set(
84+ "content",
85+ content.map(|content| content.as_str().to_string()),
86+ )
76 .run::<Note>(db)87 .run::<Note>(db)
77 .await88 .await
78 }89 }
@@ -88,42 +99,48 @@ pub async fn update(
88 /// Children first, in one transaction, the way99 /// Children first, in one transaction, the way
89 /// [`crate::db::course::delete`] does it: as two queries, an100 /// [`crate::db::course::delete`] does it: as two queries, an
90 /// upload that committed in between kept its row while the note went, and101 /// 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.
92 pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec<NoteFile>), AppError> {107 pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec<NoteFile>), AppError> {
93- let mut result = db108+ tx_with_retry(db, true, async |conn| {
94- .query(109+ sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id)
95- "BEGIN TRANSACTION;110+ .execute(&mut *conn)
96- LET $files = (DELETE note_file WHERE note = $note RETURN BEFORE);111+ .await?;
97- LET $gone = (DELETE $note RETURN BEFORE);112+ let files = sqlx::query_as!(
98- RETURN { note: $gone, files: $files };113+ NoteFile,
99- COMMIT TRANSACTION;",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
100 )123 )
101- .bind(("note", note.id.record()))124+ .fetch_optional(&mut *conn)
102- .await?125+ .await?;
103- .check()?;126+ let note = gone.ok_or(AppError::NotFound)?;
104- // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3.127+ Ok((note, files))
105- let outcome = result128+ })
106- .take::<Vec<DeleteOutcome>>(3)?129+ .await
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))
112 }130 }
113 131
114 #[cfg(test)]132 #[cfg(test)]
115 mod tests {133 mod tests {
116 use super::*;134 use super::*;
135+ use crate::domain::note_file::{FileContentType, FileName};
117 136
118 /// The blobs the handler unlinks are exactly the rows this transaction137 /// The blobs the handler unlinks are exactly the rows this transaction
119 /// removed — including one uploaded after any pre-read snapshot would have138 /// removed — including one uploaded after any pre-read snapshot would have
120 /// been taken, which is the row whose blob used to leak.139 /// been taken, which is the row whose blob used to leak.
121 #[tokio::test]140 #[tokio::test]
122 async fn delete_returns_the_attachment_rows_it_removed() {141 async fn delete_returns_the_attachment_rows_it_removed() {
123- use crate::domain::note_file::{FileContentType, FileName};
124-
125 let db = crate::database::init_mem().await.unwrap();142 let db = crate::database::init_mem().await.unwrap();
126- let owner = crate::domain::user::UserId::generate();143+ let owner = UserId::generate();
127 let note = create(144 let note = create(
128 &db,145 &db,
129 &owner,146 &owner,
src/db/note_file.rsmodified+126 -137
@@ -2,9 +2,8 @@
2 //! first, with the note's file cap claimed and released in the same write as2 //! first, with the note's file cap claimed and released in the same write as
3 //! the row.3 //! the row.
4 4
5-use crate::constant::{MAX_NOTE_FILES, NOTE_FILE_COUNT_FIELD};5+use crate::constant::MAX_NOTE_FILES;
6-use crate::database::Database;6+use crate::database::{Database, tx_with_retry, unique_violation};
7-use crate::db::cap;
8 use crate::db::page::PagedList;7 use crate::db::page::PagedList;
9 use crate::domain::note::NoteId;8 use crate::domain::note::NoteId;
10 use crate::domain::note_file::{NoteFile, NoteFileId};9 use crate::domain::note_file::{NoteFile, NoteFileId};
@@ -12,31 +11,45 @@ use crate::error::AppError;
12 11
13 /// Persist the row assembled by [`NoteFile::new`], refusing once its note12 /// Persist the row assembled by [`NoteFile::new`], refusing once its note
14 /// already holds [`MAX_NOTE_FILES`]. The slot and the row are taken together13 /// 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 a14+/// by one conditional statement on the note row (the claim CTE of
16-/// count can't enforce the cap (SurrealDB doesn't conflict-check a15+/// `cap::claim_and_create`, spelled out at its call site — see
17-/// cross-record count against a concurrent insert) and a process-wide mutex16+/// `crate::db::cap`): a `BEGIN…COMMIT` around a count can't enforce the cap
18-/// can't either, since it is released around the very round trip the insert17+/// and a process-wide mutex can't either, since it is released around the
19-/// races — a conditional single-record write can. Claiming in a *separate*18+/// very round trip the insert races — a single guarded statement can.
20-/// query would enforce the cap but leak a slot on a crash between the two.19+/// Claiming in a *separate* query would enforce the cap but leak a slot on
20+/// a crash between the two.
21 pub async fn insert(db: &Database, file: NoteFile) -> Result<NoteFile, AppError> {21 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 clobber22+ // whole-row-save-ok: insert of a fresh UUID row built in place by `new` — there is no prior row to clobber
23- match cap::claim_and_create(23+ let created = sqlx::query_as!(
24- &file.note.record(),24+ NoteFile,
25- NOTE_FILE_COUNT_FIELD,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,
26 MAX_NOTE_FILES as i64,33 MAX_NOTE_FILES as i64,
27- &file.id.record(),34+ file.id,
28- &file,35+ file.name,
29- db,36+ file.content_type,
37+ file.size
30 )38 )
31- .await?39+ .fetch_optional(db)
32- {40+ .await;
33- cap::Claimed::Made(created) => Ok(created),41+ match created {
42+ Ok(Some(row)) => Ok(row),
34 // Also how a missing note reads: no note row means no slot to take.43 // 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(
36 "the note already holds the maximum of 10 files — delete one first",45 "the note already holds the maximum of 10 files — delete one first",
37 )),46 )),
38- // Unreachable: the id is a ULID this call just generated.47+ // A duplicate would be a 23505 on the row's own key, which this path
39- cap::Claimed::Duplicate => Err(AppError::Internal("failed to create note file".into())),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()),
40 }53 }
41 }54 }
42 55
@@ -47,8 +60,15 @@ pub async fn read_for(
47 id: &NoteFileId,60 id: &NoteFileId,
48 note: &NoteId,61 note: &NoteId,
49 ) -> Result<Option<NoteFile>, AppError> {62 ) -> Result<Option<NoteFile>, AppError> {
50- let file: Option<NoteFile> = db.select(id.record()).await?;63+ let file = sqlx::query_as!(
51- Ok(file.filter(|file| &file.note == note))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)
52 }72 }
53 73
54 /// All of `note`'s attachment rows, newest first.74 /// All of `note`'s attachment rows, newest first.
@@ -58,9 +78,9 @@ pub async fn list_for(
58 limit: Option<i64>,78 limit: Option<i64>,
59 offset: i64,79 offset: i64,
60 ) -> Result<(Vec<NoteFile>, i64), AppError> {80 ) -> Result<(Vec<NoteFile>, i64), AppError> {
61- PagedList::new("note_file WHERE note = $note", "ORDER BY id DESC")81+ PagedList::new("note_file WHERE note = $1", "ORDER BY id DESC")
62- .bind("note", note.record())82+ .bind(note.uuid())
63- .run(limit, offset, db)83+ .run::<NoteFile>(limit, offset, db)
64 .await84 .await
65 }85 }
66 86
@@ -68,133 +88,102 @@ pub async fn list_for(
68 /// itself is untouched, so unlike the note-delete cascade this one has a88 /// itself is untouched, so unlike the note-delete cascade this one has a
69 /// counter to correct. (Deleting a *note* takes its counter with it.)89 /// counter to correct. (Deleting a *note* takes its counter with it.)
70 pub async fn delete(db: &Database, file: NoteFile) -> Result<NoteFile, AppError> {90 pub async fn delete(db: &Database, file: NoteFile) -> Result<NoteFile, AppError> {
71- let mut result = db91+ tx_with_retry(db, true, async |conn| {
72- .query(92+ let gone = sqlx::query_as!(
73- "BEGIN TRANSACTION;93+ NoteFile,
74- LET $gone = (DELETE $id RETURN BEFORE);94+ r#"DELETE FROM note_file WHERE id = $1 RETURNING id, note, name, content_type, size"#,
75- UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]);95+ file.id
76- RETURN $gone;96+ )
77- COMMIT TRANSACTION;",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
78 )103 )
79- .bind(("id", file.id.record()))104+ .execute(&mut *conn)
80- .bind(("note", file.note.record()))105+ .await?;
81- .await?106+ Ok(file)
82- .check()?;107+ })
83- result108+ .await
84- .take::<Vec<NoteFile>>(3)?
85- .into_iter()
86- .next()
87- .ok_or(AppError::NotFound)
88 }109 }
89 110
90 #[cfg(test)]111 #[cfg(test)]
91 mod tests {112 mod tests {
92 use super::*;113 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;
94 118
95- #[tokio::test]119+ async fn a_note(db: &Database) -> Note {
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).
100 let owner = crate::domain::user::UserId::generate();120 let owner = crate::domain::user::UserId::generate();
101- let note_of = async |title: &str| {121+ crate::db::note::create(
102- crate::db::note::create(122+ db,
103- &db,123+ &owner,
104- &owner,124+ NoteTitle::try_new("n").unwrap(),
105- crate::domain::note::NoteTitle::try_new(title).unwrap(),125+ NoteContent::try_new("b").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 )126 )
122 .await127 .await
123- .unwrap();128+ .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());
141 }129 }
142 130
143- /// The counter and the rows are written in one transaction, so the stored131+ /// The cap answers with a conflict, and neither the refused row nor its
144- /// count must equal the stored rows — after a success *and* after the132+ /// slot was written: the count is still what the last accepted upload
145- /// refusal that fills the cap, which must move neither.133+ /// left.
146 #[tokio::test]134 #[tokio::test]
147- async fn counter_tracks_stored_rows() {135+ async fn insert_refuses_at_the_cap_without_leaking_a_slot() {
148 let db = crate::database::init_mem().await.unwrap();136 let db = crate::database::init_mem().await.unwrap();
149- let note = crate::db::note::create(137+ let note = a_note(&db).await;
150- &db,138+ for index in 0..MAX_NOTE_FILES {
151- &crate::domain::user::UserId::generate(),139+ let file = NoteFile::new(
152- crate::domain::note::NoteTitle::try_new("a").unwrap(),140+ note.get_id(),
153- crate::domain::note::NoteContent::try_new("body").unwrap(),141+ FileName::try_new(&format!("f{index}")).unwrap(),
154- )142+ FileContentType::try_new("text/plain").unwrap(),
155- .await143+ 1,
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
189 );144 );
145+ insert(&db, file).await.unwrap();
190 }146 }
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+ }
191 161
192- // At the cap: the refusal writes nothing, counter included.162+ /// Deleting a row hands its slot back: after one delete a new upload is
193- assert!(matches!(add(&note).await, Err(AppError::Conflict(_))));163+ /// accepted again, and the count never dips below zero.
194- assert_eq!(stored_count(&note).await, MAX_NOTE_FILES as i64);164+ #[tokio::test]
195- assert_eq!(165+ async fn delete_returns_the_slot_to_the_note() {
196- list_for(&db, &note, None, 0).await.unwrap().1,166+ let db = crate::database::init_mem().await.unwrap();
197- MAX_NOTE_FILES as i64167+ 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,
198 );184 );
185+ insert(&db, next).await.unwrap();
186+ let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap();
187+ assert_eq!(total, 1);
199 }188 }
200 }189 }
src/db/pool_question.rsmodified+176 -192
@@ -1,137 +1,85 @@
1 //! The `pool_question` table: ask/insert, the two listings, the guarded1 //! The `pool_question` table: ask/insert, the two listings, the guarded
2 //! approve that rides the publish counters along, the pending-only image2 //! approve that rides the publish counters along, the pending-only image
3-//! writes, and the delete that cascades solutions — plus3+//! writes, and the delete that cascades solutions. The pure entity and
4-//! [`bump_question_and_write`], the existence-move every child write goes4+//! newtypes live in [`crate::domain::pool_question`]; the web layer reaches
5-//! through. The pure entity and newtypes live in5+//! these through [`crate::service::pool_question`].
6-//! [`crate::domain::pool_question`]; the web layer reaches these through6+
7-//! [`crate::service::pool_question`].7+use crate::constant::{STATUS_APPROVED, STATUS_PENDING};
8-8+use crate::database::{Database, tx_with_retry};
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};
15 use crate::domain::note_file::FileContentType;9 use crate::domain::note_file::FileContentType;
16 use crate::domain::pool_question::{PoolQuestion, PoolQuestionId};10 use crate::domain::pool_question::{PoolQuestion, PoolQuestionId};
17 use crate::domain::solution::Solution;11 use crate::domain::solution::Solution;
18 use crate::domain::user::UserId;12 use crate::domain::user::UserId;
19 use crate::error::AppError;13 use crate::error::AppError;
20 14
21-/// Move the question's `asked_at` **and** run `statement` — a write to15+pub async fn insert(db: &Database, question: PoolQuestion) -> Result<PoolQuestion, AppError> {
22-/// something hanging off a question — in one transaction, handing back the row16+ let row = sqlx::query_as!(
23-/// it returned. `NotFound` means the question is gone and nothing was written.17+ PoolQuestion,
24-///18+ r#"INSERT INTO pool_question (id, asker, title, body, status, asked_at)
25-/// The move is what makes the question's **existence** part of the child's own19+ VALUES ($1, $2, $3, $4, $5, $6)
26-/// write, the way [`crate::domain::menu::bump_menu_and_write`] does for a menu:20+ RETURNING *"#,
27-/// the `UPDATE` matches nothing once the row is deleted, and a delete racing21+ question.id,
28-/// this one touches the very key this transaction writes, so the two cannot22+ question.asker,
29-/// both commit. Reading the question first does *not* survive that race — the23+ question.title,
30-/// read sees a row [`delete`] has removed but not committed, while its24+ question.body,
31-/// `DELETE solution WHERE question = $q` ran on a snapshot predating this25+ question.status,
32-/// insert, so both commit and the child outlives its question with neither26+ question.asked_at,
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"],
67 )27 )
28+ .fetch_one(db)
68 .await?;29 .await?;
69- // An aborted transaction errors *every* slot, most with a generic "not30+ Ok(row)
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()))
91 }31 }
92 32
93 pub async fn read(db: &Database, id: &PoolQuestionId) -> Result<Option<PoolQuestion>, AppError> {33 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)
95 }42 }
96 43
97 /// Every question, newest first — the teacher+ view (approval queue and44 /// Every question, newest first — the teacher+ view (approval queue and
98 /// pool in one list).45 /// pool in one list).
99 pub async fn list_all(db: &Database) -> Result<Vec<PoolQuestion>, AppError> {46 pub async fn list_all(db: &Database) -> Result<Vec<PoolQuestion>, AppError> {
100- let mut result = db47+ let rows = sqlx::query_as!(
101- .query("SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC")48+ PoolQuestion,
102- .await?49+ "SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC",
103- .check()?;50+ )
104- Ok(result.take::<Vec<PoolQuestion>>(0)?)51+ .fetch_all(db)
52+ .await?;
53+ Ok(rows)
105 }54 }
106 55
107 /// The pool as a non-staff user sees it, newest first: every approved56 /// The pool as a non-staff user sees it, newest first: every approved
108 /// question, plus the caller's own pending ones.57 /// question, plus the caller's own pending ones.
109 pub async fn list_visible_to(db: &Database, user: &UserId) -> Result<Vec<PoolQuestion>, AppError> {58 pub async fn list_visible_to(db: &Database, user: &UserId) -> Result<Vec<PoolQuestion>, AppError> {
110- let mut result = db59+ let rows = sqlx::query_as!(
111- .query(60+ PoolQuestion,
112- "SELECT * FROM pool_question WHERE status = $approved OR asker = $usr \61+ r#"SELECT * FROM pool_question
113- ORDER BY asked_at DESC, id DESC",62+ WHERE status = $1 OR asker = $2
114- )63+ ORDER BY asked_at DESC, id DESC"#,
115- .bind(("approved", STATUS_APPROVED))64+ STATUS_APPROVED,
116- .bind(("usr", user.record()))65+ user
117- .await?66+ )
118- .check()?;67+ .fetch_all(db)
119- Ok(result.take::<Vec<PoolQuestion>>(0)?)68+ .await?;
69+ Ok(rows)
120 }70 }
121 71
122 /// Publish a pending question into the pool, stamping who approved it.72 /// Publish a pending question into the pool, stamping who approved it.
123-/// The `WHERE status = $pending` guard makes the transition atomic: of two73+/// The `WHERE status = 'pending'` guard makes the transition atomic: of two
124 /// racing approvals exactly one wins, and an approve can never land on a74 /// racing approvals exactly one wins, and an approve can never land on a
125 /// question deleted mid-flight. `None` = the question wasn't pending75 /// question deleted mid-flight. `None` = the question wasn't pending
126 /// (already approved, or gone) — the caller sorts out which.76 /// (already approved, or gone) — the caller sorts out which.
127 ///77 ///
128-/// Two lifetime badge counters ride that same guard, inside this78+/// Two lifetime badge counters ride that same guard inside this
129 /// transaction: the approver's `pool_approved_total` and the *asker's*79 /// transaction: the approver's `pool_approved_total` and the *asker's*
130-/// `pool_published_total`. Both hang off `array::len($done) > 0` — the80+/// `pool_published_total`. Both move only when the guard's own verdict
131-/// guard's own verdict — so the pair moves once per real transition and81+/// landed, so the pair moves once per real transition and never on a second
132-/// never on a second approve of an already-approved question.82+/// 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.
135 ///83 ///
136 /// Two rules keep the pair unfarmable, one per side of the transition.84 /// Two rules keep the pair unfarmable, one per side of the transition.
137 ///85 ///
@@ -144,56 +92,56 @@ pub async fn list_visible_to(db: &Database, user: &UserId) -> Result<Vec<PoolQue
144 ///92 ///
145 /// And a *self*-approval — a teacher+ approving a question they asked93 /// And a *self*-approval — a teacher+ approving a question they asked
146 /// themselves, which the route deliberately still allows — moves neither94 /// themselves, which the route deliberately still allows — moves neither
147-/// counter, hence the `$done[0].asker != $by` half of the condition. It is95+/// counter. It is the same farm from the other end (ask, approve, delete,
148-/// the same farm from the other end (ask, approve, delete, repeat, with no96+/// repeat, with no second person involved), and the two together are why a
149-/// second person involved), and the two together are why a counter can only97+/// counter can only move when one person's work was judged by another's.
150-/// move when one person's work was judged by another's. Nothing else about98+/// Nothing else about a self-approval changes: same 200, same freeze, same
151-/// a self-approval changes: same 200, same freeze, same stamp — this skips99+/// stamp — this skips the credit, not the approval.
152-/// the credit, not the approval.
153 ///100 ///
154-/// Re-sent while the store answers "conflict, retry": the guard reads a101+/// Rides the retry loop because the counter bumps lock user rows every
155-/// column a rival approve writes, and both counters sit on user rows every102+/// other counter site writes too; a deadlock between two approvals takes a
156-/// other counter site writes too. Sound to re-send — every statement is an103+/// round and lands the next attempt.
157-/// `UPDATE`, none of which can legitimately answer "already exists" — and a
158-/// lost round aborts having written nothing, increments included.
159 pub async fn approve(104 pub async fn approve(
160 db: &Database,105 db: &Database,
161 id: &PoolQuestionId,106 id: &PoolQuestionId,
162 approver: &UserId,107 approver: &UserId,
163 ) -> Result<Option<PoolQuestion>, AppError> {108 ) -> Result<Option<PoolQuestion>, AppError> {
164- let (mut result, mut errors) = transaction_with_retry(109+ tx_with_retry(db, false, async |tx| {
165- db,110+ let approved = sqlx::query_as!(
166- &format!(111+ PoolQuestion,
167- "BEGIN TRANSACTION;112+ r#"UPDATE pool_question SET status = $2, approved_by = $3
168- LET $done = (UPDATE $q SET status = $approved, approved_by = $by113+ WHERE id = $1 AND status = $4
169- WHERE status = $pending RETURN AFTER);114+ RETURNING *"#,
170- IF array::len($done) > 0 AND $done[0].asker != $by {{115+ *id,
171- UPDATE $by SET116+ STATUS_APPROVED,
172- {POOL_APPROVED_TOTAL_FIELD} = ({POOL_APPROVED_TOTAL_FIELD} ?? 0) + 1;117+ approver,
173- LET $asker = $done[0].asker;118+ STATUS_PENDING,
174- UPDATE $asker SET119+ )
175- {POOL_PUBLISHED_TOTAL_FIELD} = ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0) + 1;120+ .fetch_optional(tx)
176- }};121+ .await?;
177- RETURN $done;122+ if let Some(question) = &approved {
178- COMMIT TRANSACTION;"123+ if question.asker != *approver {
179- ),124+ // The counter columns are NOT NULL DEFAULT 0 — the old
180- &[125+ // absent-reads-as-zero coalesce is gone with the schema.
181- ("q".into(), id.record().into_value()),126+ sqlx::query!(
182- ("approved".into(), STATUS_APPROVED.to_string().into_value()),127+ "UPDATE app_user SET pool_approved_total = pool_approved_total + 1
183- ("by".into(), approver.record().into_value()),128+ WHERE id = $1",
184- ("pending".into(), STATUS_PENDING.to_string().into_value()),129+ approver
185- ],130+ )
186- &[],131+ .execute(tx)
187- )132+ .await?;
188- .await?;133+ sqlx::query!(
189- if let Some(error) = errors.drain().map(|(_, error)| error).next() {134+ "UPDATE app_user SET pool_published_total = pool_published_total + 1
190- return Err(error.into());135+ WHERE id = $1",
191- }136+ question.asker
192- // The trailing `RETURN` is always the last statement before `COMMIT`,137+ )
193- // so its slot follows the statement count rather than a hand-kept138+ .execute(tx)
194- // number (`num_statements` counts `BEGIN` and `COMMIT` too, hence -2).139+ .await?;
195- let slot = result.num_statements().saturating_sub(2);140+ }
196- Ok(result.take::<Vec<PoolQuestion>>(slot)?.into_iter().next())141+ }
142+ Ok(approved)
143+ })
144+ .await
197 }145 }
198 146
199 /// Point the question at a freshly written image blob. Guarded on147 /// Point the question at a freshly written image blob. Guarded on
@@ -202,6 +150,10 @@ pub async fn approve(
202 /// loses the race gets `None` (and the caller takes the orphan blob back150 /// loses the race gets `None` (and the caller takes the orphan blob back
203 /// off disk). Returns the *before* row — its `image_file` is the replaced151 /// off disk). Returns the *before* row — its `image_file` is the replaced
204 /// blob the caller must remove.152 /// 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.
205 pub async fn set_image(157 pub async fn set_image(
206 db: &Database,158 db: &Database,
207 id: &PoolQuestionId,159 id: &PoolQuestionId,
@@ -209,19 +161,35 @@ pub async fn set_image(
209 content_type: &FileContentType,161 content_type: &FileContentType,
210 size: i64,162 size: i64,
211 ) -> Result<Option<PoolQuestion>, AppError> {163 ) -> Result<Option<PoolQuestion>, AppError> {
212- let mut result = db164+ tx_with_retry(db, false, async |tx| {
213- .query(165+ let before = sqlx::query_as!(
214- "UPDATE $q SET image_file = $file, image_content_type = $ct, image_size = $size \166+ PoolQuestion,
215- WHERE status = $pending RETURN BEFORE",167+ "SELECT * FROM pool_question WHERE id = $1 FOR UPDATE",
168+ *id
216 )169 )
217- .bind(("q", id.record()))170+ .fetch_optional(tx)
218- .bind(("file", file.to_string()))171+ .await?;
219- .bind(("ct", content_type.clone()))172+ let Some(before) = before else {
220- .bind(("size", size))173+ return Ok(None);
221- .bind(("pending", STATUS_PENDING))174+ };
222- .await?175+ let written = sqlx::query!(
223- .check()?;176+ r#"UPDATE pool_question
224- Ok(result.take::<Vec<PoolQuestion>>(0)?.into_iter().next())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
225 }193 }
226 194
227 /// Detach the question's image (pending only, like `set_image`). Returns195 /// Detach the question's image (pending only, like `set_image`). Returns
@@ -230,16 +198,32 @@ pub async fn clear_image(
230 db: &Database,198 db: &Database,
231 id: &PoolQuestionId,199 id: &PoolQuestionId,
232 ) -> Result<Option<PoolQuestion>, AppError> {200 ) -> Result<Option<PoolQuestion>, AppError> {
233- let mut result = db201+ tx_with_retry(db, false, async |tx| {
234- .query(202+ let before = sqlx::query_as!(
235- "UPDATE $q SET image_file = NONE, image_content_type = NONE, image_size = NONE \203+ PoolQuestion,
236- WHERE status = $pending RETURN BEFORE",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,
237 )218 )
238- .bind(("q", id.record()))219+ .execute(tx)
239- .bind(("pending", STATUS_PENDING))220+ .await?;
240- .await?221+ if written.rows_affected() == 0 {
241- .check()?;222+ return Ok(None);
242- Ok(result.take::<Vec<PoolQuestion>>(0)?.into_iter().next())223+ }
224+ Ok(Some(before))
225+ })
226+ .await
243 }227 }
244 228
245 /// Delete the question and its solutions in one transaction, returning229 /// Delete the question and its solutions in one transaction, returning
@@ -247,34 +231,34 @@ pub async fn clear_image(
247 /// caller can take every image blob off disk (solutions carry photos too,231 /// caller can take every image blob off disk (solutions carry photos too,
248 /// and a row-only sweep would strand theirs forever).232 /// and a row-only sweep would strand theirs forever).
249 ///233 ///
250-/// Rides the retry because a solution offer now writes this very row234+/// Children before the parent, so the foreign keys never refuse the parent
251-/// ([`bump_question_and_write`]): the two contend by design, and a lost235+/// delete. `cascade = true` because a solution offer committing inside this
252-/// round through a bare `check()` was a 500 for a delete that only had to236+/// window makes the parent delete answer 23503 — a mid-cascade race the
253-/// be re-sent. Admissible — a `DELETE` can never answer "already exists".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.
254 pub async fn delete(240 pub async fn delete(
255 db: &Database,241 db: &Database,
256 id: &PoolQuestionId,242 id: &PoolQuestionId,
257 ) -> Result<Option<(PoolQuestion, Vec<Solution>)>, AppError> {243 ) -> Result<Option<(PoolQuestion, Vec<Solution>)>, AppError> {
258- let (mut result, mut errors) = transaction_with_retry(244+ tx_with_retry(db, true, async |tx| {
259- db,245+ let solutions = sqlx::query_as!(
260- "BEGIN TRANSACTION;246+ Solution,
261- DELETE solution WHERE question = $q RETURN BEFORE;247+ "DELETE FROM solution WHERE question = $1 RETURNING *",
262- DELETE $q RETURN BEFORE;248+ *id
263- COMMIT TRANSACTION;",249+ )
264- &[("q".into(), id.record().into_value())],250+ .fetch_all(tx)
265- &[],251+ .await?;
266- )252+ let question = sqlx::query_as!(
267- .await?;253+ PoolQuestion,
268- if let Some(error) = errors.drain().map(|(_, error)| error).next() {254+ "DELETE FROM pool_question WHERE id = $1 RETURNING *",
269- return Err(error.into());255+ *id
270- }256+ )
271- // Slots count BEGIN: the solution sweep is slot 1, the question slot 2.257+ .fetch_optional(tx)
272- let solutions = result.take::<Vec<Solution>>(1)?;258+ .await?;
273- Ok(result259+ Ok(question.map(|question| (question, solutions)))
274- .take::<Vec<PoolQuestion>>(2)?260+ })
275- .into_iter()261+ .await
276- .next()
277- .map(|question| (question, solutions)))
278 }262 }
279 263
280 #[cfg(test)]264 #[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 —1+//! What an AI service produced for a course note, stored on this side: the
2-//! an index, a summary, an embedding manifest — stored as this side's own2+//! write paths the api-read bridge serves (`create`/`replace_for_note` run
3-//! copy of the answer. The AI service never writes here (it answers a3+//! when this backend answers a request over the bridge, and this side stores
4-//! request over the bridge, and this side stores the answer), which is what4+//! the answer), which is what keeps the api-read bridge GET-only. Derived,
5-//! keeps the api-read bridge GET-only. Derived, disposable data: the row is5+//! disposable data: the row is dropped and regenerated whenever its input
6-//! dropped and regenerated whenever its input changes, so the cascades6+//! changes, so the cascades below — [`delete_for_note`] when the note goes,
7-//! below — [`delete_for_note`] when the note goes, [`delete_with_source`]7+//! [`delete_with_source`] when one of the attachments it was built from goes
8-//! when one of the attachments it was built from goes — keep a stale output8+//! — keep a stale output from outliving its input, even in a deployment with
9-//! from outliving its input, even in a deployment with no AI service9+//! no AI service connected. The row shape lives in
10-//! connected. The row shape lives in [`crate::domain::rag_output`].10+//! [`crate::domain::rag_output`].
11 11
12 use crate::database::Database;12 use crate::database::Database;
13 use crate::db::page::PagedList;13 use crate::db::page::PagedList;
@@ -18,8 +18,8 @@ use crate::domain::rag_output::{RagOutput, RagOutputId};
18 use crate::domain::timestamp::Timestamp;18 use crate::domain::timestamp::Timestamp;
19 use crate::error::AppError;19 use crate::error::AppError;
20 use serde_json::Value;20 use serde_json::Value;
21+use sqlx::types::Json;
21 22
22-/// Store one service output against `note`.
23 pub async fn create(23 pub async fn create(
24 db: &Database,24 db: &Database,
25 note: &CourseNoteId,25 note: &CourseNoteId,
@@ -32,16 +32,39 @@ pub async fn create(
32 course_note: note.clone(),32 course_note: note.clone(),
33 course: course.clone(),33 course: course.clone(),
34 sources,34 sources,
35- payload,35+ payload: sqlx::types::Json(payload),
36 generated_at: Timestamp::now(),36 generated_at: Timestamp::now(),
37 };37 };
38- // whole-row-save-ok: create of a fresh ULID row built in place — there is no prior row to clobber38+ // whole-row-save-ok: insert of a fresh UUID row built in place — there is no prior row to clobber
39- let created: Option<RagOutput> = db.create(row.id.record()).content(row).await?;39+ let created = sqlx::query_as!(
40- created.ok_or_else(|| AppError::Internal("failed to create rag output".into()))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)
41 }55 }
42 56
43 pub async fn read(db: &Database, id: &RagOutputId) -> Result<Option<RagOutput>, AppError> {57 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)
45 }68 }
46 69
47 /// A note's outputs, newest first.70 /// A note's outputs, newest first.
@@ -51,24 +74,31 @@ pub async fn list_for(
51 limit: Option<i64>,74 limit: Option<i64>,
52 offset: i64,75 offset: i64,
53 ) -> Result<(Vec<RagOutput>, i64), AppError> {76 ) -> Result<(Vec<RagOutput>, i64), AppError> {
54- PagedList::new("rag_output WHERE course_note = $note", "ORDER BY id DESC")77+ PagedList::new("rag_output WHERE course_note = $1", "ORDER BY id DESC")
55- .bind("note", note.record())78+ .bind(note.uuid())
56- .run(limit, offset, db)79+ .run::<RagOutput>(limit, offset, db)
57 .await80 .await
58 }81 }
59 82
60 pub async fn delete(db: &Database, id: &RagOutputId) -> Result<RagOutput, AppError> {83 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?;
62 deleted.ok_or(AppError::NotFound)93 deleted.ok_or(AppError::NotFound)
63 }94 }
64 95
65 /// Cascade: every output of `note`. Deleting none is a success — a note96 /// Cascade: every output of `note`. Deleting none is a success — a note
66 /// no service ever indexed has nothing to drop.97 /// no service ever indexed has nothing to drop.
67 pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> {98 pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> {
68- db.query("DELETE rag_output WHERE course_note = $note")99+ sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note)
69- .bind(("note", note.record()))100+ .execute(db)
70- .await?101+ .await?;
71- .check()?;
72 Ok(())102 Ok(())
73 }103 }
74 104
@@ -76,7 +106,9 @@ pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), A
76 /// this note's older rows. Two concurrent index tasks can interleave in any106 /// this note's older rows. Two concurrent index tasks can interleave in any
77 /// order and still leave exactly one row — the newest — because ids come107 /// order and still leave exactly one row — the newest — because ids come
78 /// from the process-wide monotonic generator, so "older" is `id <` the row108 /// 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.)
80 pub async fn replace_for_note(112 pub async fn replace_for_note(
81 db: &Database,113 db: &Database,
82 note: &CourseNoteId,114 note: &CourseNoteId,
@@ -85,22 +117,24 @@ pub async fn replace_for_note(
85 payload: Value,117 payload: Value,
86 ) -> Result<RagOutput, AppError> {118 ) -> Result<RagOutput, AppError> {
87 let created = create(db, note, course, sources, payload).await?;119 let created = create(db, note, course, sources, payload).await?;
88- db.query("DELETE rag_output WHERE course_note = $note AND id < $new")120+ sqlx::query!(
89- .bind(("note", note.record()))121+ "DELETE FROM rag_output WHERE course_note = $1 AND id < $2",
90- .bind(("new", created.id.record()))122+ note,
91- .await?123+ created.id
92- .check()?;124+ )
125+ .execute(db)
126+ .await?;
93 Ok(created)127 Ok(created)
94 }128 }
95 129
96 /// Cascade: every output built from `file`. Runs on a file delete even130 /// Cascade: every output built from `file`. Runs on a file delete even
97 /// with no AI service connected, so a stale output cannot survive its131 /// 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.
99 pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> {134 pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> {
100- db.query("DELETE rag_output WHERE sources CONTAINS $file")135+ sqlx::query!("DELETE FROM rag_output WHERE $1 = ANY(sources)", file)
101- .bind(("file", file.record()))136+ .execute(db)
102- .await?137+ .await?;
103- .check()?;
104 Ok(())138 Ok(())
105 }139 }
106 140
@@ -108,8 +142,12 @@ pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Resul
108 mod tests {142 mod tests {
109 use super::*;143 use super::*;
110 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};144 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
111- use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle};145+ use crate::domain::course_note::CourseNote;
112- use crate::domain::course_note_file::{CourseNoteFile, FileContentType, FileName};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;
113 use serde_json::json;151 use serde_json::json;
114 152
115 async fn note_of(db: &Database, title: &str) -> CourseNote {153 async fn note_of(db: &Database, title: &str) -> CourseNote {
@@ -136,108 +174,92 @@ mod tests {
136 .unwrap()174 .unwrap()
137 }175 }
138 176
139- async fn file_on(db: &Database, note: &CourseNoteId) -> CourseNoteFileId {177+ async fn a_file(db: &Database, note: &CourseNote) -> CourseNoteFile {
140- let file = CourseNoteFile::new(178+ crate::db::course_note_file::insert(
141- note,179+ db,
142- FileName::try_new("plan.pdf").unwrap(),180+ CourseNoteFile::new(
143- FileContentType::try_new("application/pdf").unwrap(),181+ note.get_id(),
144- 3,182+ FileName::try_new("f").unwrap(),
183+ FileContentType::try_new("text/plain").unwrap(),
184+ 1,
185+ ),
145 )186 )
146-;
147- crate::db::course_note_file::insert(db, file)
148 .await187 .await
149 .unwrap()188 .unwrap()
150- .get_id()
151- .clone()
152 }189 }
153 190
154- /// Replace converges on one row — the newest — even when an earlier191+ /// A stored round-trips through JSONB with its sources list intact, and
155- /// interleaving already left two rows behind for the note.192+ /// the note cascade takes every row of the note with it.
156 #[tokio::test]193 #[tokio::test]
157- async fn replace_keeps_only_the_newest_output() {194+ async fn create_reads_back_and_cascades_from_the_note() {
158 let db = crate::database::init_mem().await.unwrap();195 let db = crate::database::init_mem().await.unwrap();
159- let note = note_of(&db, "a").await;196+ let note = note_of(&db, "n").await;
160- let stale = create(197+ let file = a_file(&db, &note).await;
161- &db,198+ let row = create(
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(
181 &db,199 &db,
182 note.get_id(),200 note.get_id(),
183 note.get_course(),201 note.get_course(),
184- Vec::new(),202+ vec![file.get_id().clone()],
185- json!({ "n": 3 }),203+ json!({"answer": "x"}),
186 )204 )
187 .await205 .await
188 .unwrap();206 .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()]);
189 210
190- let rows = list_for(&db, note.get_id(), None, 0).await.unwrap().0;211+ delete_for_note(&db, note.get_id()).await.unwrap();
191- assert_eq!(rows.len(), 1);212+ assert!(read(&db, row.get_id()).await.unwrap().is_none());
192- assert_eq!(rows[0].get_id(), fresh.get_id());
193- assert!(fresh.get_id().key() > stale.get_id().key());
194 }213 }
195 214
196- /// The payload survives the round trip unread, and both cascades take only215+ /// Replace leaves exactly one row — the newest — and the source cascade
197- /// what they are aimed at.216+ /// drops a row built from a file that is gone.
198 #[tokio::test]217 #[tokio::test]
199- async fn outputs_round_trip_and_cascade() {218+ async fn replace_is_newest_wins_and_source_cascade_drops() {
200 let db = crate::database::init_mem().await.unwrap();219 let db = crate::database::init_mem().await.unwrap();
201- let note = note_of(&db, "a").await;220+ let note = note_of(&db, "n").await;
202- let other = note_of(&db, "b").await;221+ let file = a_file(&db, &note).await;
203- let file = file_on(&db, note.get_id()).await;222+ let first = create(
204-
205- let stored = create(
206 &db,223 &db,
207 note.get_id(),224 note.get_id(),
208 note.get_course(),225 note.get_course(),
209- vec![file.clone()],226+ vec![file.get_id().clone()],
210- json!({ "summary": "x", "chunks": [{ "text": "y" }] }),227+ json!({"v": 1}),
211 )228 )
212 .await229 .await
213 .unwrap();230 .unwrap();
214- let roundtrip = read(&db, stored.get_id()).await.unwrap().unwrap();231+ let second = replace_for_note(
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(
220 &db,232 &db,
221- other.get_id(),233+ note.get_id(),
222- other.get_course(),234+ note.get_course(),
223- Vec::new(),235+ vec![file.get_id().clone()],
224- json!({ "summary": "z" }),236+ json!({"v": 2}),
225 )237 )
226 .await238 .await
227 .unwrap();239 .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());
228 244
229- let listed =245+ delete_with_source(&db, file.get_id()).await.unwrap();
230- async |note: &CourseNoteId| list_for(&db, note, None, 0).await.unwrap().0.len();246+ let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap();
231- assert_eq!(listed(note.get_id()).await, 1);247+ assert_eq!(total, 0);
232-248+ }
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);
237 249
238- // Cascading a note with no outputs left is still a success.250+ /// Deleting one row returns it; deleting it again is a 404.
239- delete_for_note(&db, note.get_id()).await.unwrap();251+ #[tokio::test]
240- delete_for_note(&db, other.get_id()).await.unwrap();252+ async fn delete_returns_the_row_then_refuses() {
241- assert!(read(&db, untouched.get_id()).await.unwrap().is_none());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+ ));
242 }264 }
243 }265 }
src/db/session_attendance.rsmodified+193 -185
@@ -4,60 +4,30 @@
4 //! management's, only students attend, enrollment) are4 //! management's, only students attend, enrollment) are
5 //! [`crate::service::session_attendance`]'s to judge before calling here.5 //! [`crate::service::session_attendance`]'s to judge before calling here.
6 6
7-use surrealdb::types::SurrealValue;7+use crate::database::{Database, tx_with_retry};
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};
13 use crate::db::page::PagedList;8 use crate::db::page::PagedList;
14 use crate::domain::attendance::AttendanceStatus;9 use crate::domain::attendance::AttendanceStatus;
15 use crate::domain::course_session::{CourseSession, CourseSessionId};10 use crate::domain::course_session::{CourseSession, CourseSessionId};
16-use crate::domain::session_attendance::{11+use crate::domain::session_attendance::SessionAttendance;
17- SessionAttendance, SessionAttendanceId, counts_as_attended,
18-};
19 use crate::domain::timestamp::Timestamp;12 use crate::domain::timestamp::Timestamp;
20 use crate::domain::user::UserId;13 use crate::domain::user::UserId;
21 use crate::error::AppError;14 use crate::error::AppError;
22 15
23-/// Record (or overwrite) `user`'s status for the session. One row per16+/// Record (or overwrite) `user`'s status for the session. The table's
24-/// (session, user), keyed by a deterministic composite id so this is a17+/// primary key *is* the (session, user) pair, so the mark is a single
25-/// single atomic UPSERT — concurrent marks converge on the one row.18+/// 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.
55 ///19 ///
56-/// Sound to re-send while the store answers "conflict, retry": the gate20+/// The "session still exists" gate is a row lock: the transaction takes the
57-/// reads the record a delete writes, so the two contend by design, and the21+/// session row `FOR NO KEY UPDATE` before anything else, so a session (or
58-/// UPSERT cannot legitimately answer "already exists" — its composite id is22+/// course) delete cascading beneath this mark simply waits, and a delete
59-/// bijective with the `session_attendance_session_user` unique tuple, so23+/// that got there first leaves this gate matching nothing — `404`, the
60-/// the index entry can only point at the row the id already names.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.
61 ///31 ///
62 /// Two badge counters move in this same transaction, both of them read32 /// Two badge counters move in this same transaction, both of them read
63 /// from the store rather than taken on the caller's word:33 /// from the store rather than taken on the caller's word:
@@ -65,27 +35,27 @@ use crate::error::AppError;
65 /// - `lessons_attended_total`, on the person marked, as a *delta* rather35 /// - `lessons_attended_total`, on the person marked, as a *delta* rather
66 /// than an increment, because this is an upsert: a re-mark that changes36 /// than an increment, because this is an upsert: a re-mark that changes
67 /// nothing must change nothing, and a teacher's correction must move it37 /// nothing must change nothing, and a teacher's correction must move it
68-/// back down. `$was` is read before the upsert overwrites it (`NONE` when38+/// back down. The pair's stored status is read before the upsert
69-/// the pair has no row yet), so it writes only on a real crossing of the39+/// overwrites it (`None` when the pair has no row yet), so it writes
70-/// attended line, and only for a **student** — attending lessons is a40+/// only on a real crossing of the attended line, and only for a
71-/// student's badge, the same student-only rule enrolling and sitting an41+/// **student** — attending lessons is a student's badge, the same
72-/// exam already carry, so a teacher marked present in their own lesson42+/// student-only rule enrolling and sitting an exam already carry, so a
73-/// moves it in neither direction. The live `role` decides that, not the43+/// teacher marked present in their own lesson moves it in neither
74-/// role someone held when the row was written.44+/// direction. The live `role` decides that, not the role someone held
45+/// when the row was written.
75 /// - `lessons_held_total`, on the *session's* teacher, exactly once per46 /// - `lessons_held_total`, on the *session's* teacher, exactly once per
76-/// session: the first roll call taken stamps47+/// session: the first roll call taken stamps `held_counted_at` on the
77-/// [`LESSON_COUNTED_AT_FIELD`] on the lesson and every later mark sees48+/// lesson and every later mark sees the stamp and credits nothing. It
78-/// the stamp and credits nothing. It counts lessons that actually49+/// counts lessons that actually happened — scheduling one and
79-/// happened — scheduling one and cancelling it earns nothing, which is50+/// cancelling it earns nothing, which is why the credit does not live
80-/// why the credit does not live in `crate::db::course_session::create`. Two51+/// in `crate::db::course_session::create`. Two simultaneous first
81-/// simultaneous first marks both write the lesson row, so the store's own52+/// marks serialize on the session row's lock, so the stamp cannot be
82-/// conflict detection (and `transaction_with_retry` behind it) is what53+/// set twice.
83-/// keeps the stamp from being set twice.
84 ///54 ///
85 /// "Actually happened" is a clock reading, not a request count: the55 /// "Actually happened" is a clock reading, not a request count: the
86 /// credit waits for the lesson's own `starts_at` to arrive. Roll call is56 /// 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 and57+/// deliberately *not* time-gated — a teacher may open the sheet early
88-/// is never refused — so without this a teacher could schedule two58+/// and is never refused — so without this a teacher could schedule two
89 /// hundred lessons for next week, mark one student in each, and hold two59 /// hundred lessons for next week, mark one student in each, and hold two
90 /// hundred lessons this afternoon. Because the stamp is written only on60 /// hundred lessons this afternoon. Because the stamp is written only on
91 /// the branch that credits, a sheet opened early and touched again after61 /// the branch that credits, a sheet opened early and touched again after
@@ -100,9 +70,6 @@ use crate::error::AppError;
100 /// credited — a student's real lessons eaten by someone else's farm. It70 /// credited — a student's real lessons eaten by someone else's farm. It
101 /// is also nobody's self-service: only a teacher can mark a student, so71 /// is also nobody's self-service: only a teacher can mark a student, so
102 /// the counter cannot be moved by the person it decorates.72 /// 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.
106 //73 //
107 // corner-cut: that asymmetry leaves a teacher able to inflate a *student's*74 // corner-cut: that asymmetry leaves a teacher able to inflate a *student's*
108 // attendance with future-dated lessons. Closing it needs the credit stamped75 // attendance with future-dated lessons. Closing it needs the credit stamped
@@ -117,76 +84,94 @@ pub async fn mark(
117 status: AttendanceStatus,84 status: AttendanceStatus,
118 marked_by: &UserId,85 marked_by: &UserId,
119 ) -> Result<SessionAttendance, AppError> {86 ) -> Result<SessionAttendance, AppError> {
120- let attended = counts_as_attended(&status);87+ let attended = crate::domain::session_attendance::counts_as_attended(&status);
121 let delta: i64 = if attended { 1 } else { -1 };88 let delta: i64 = if attended { 1 } else { -1 };
122- let attendance = SessionAttendance {89+ let now = Timestamp::now();
123- id: SessionAttendanceId::composite(session.get_id(), user),90+ tx_with_retry(db, false, async |tx| {
124- session: session.get_id().clone(),91+ // The gate and the serialization point: a live session row, locked
125- course: session.get_course().clone(),92+ // against the delete cascade and every rival mark.
126- user: user.clone(),93+ let sess = sqlx::query!(
127- status,94+ r#"SELECT teacher, starts_at, held_counted_at
128- marked_by: marked_by.clone(),95+ FROM course_session WHERE id = $1 FOR NO KEY UPDATE"#,
129- };96+ session.id,
130- let (mut written, mut errors) = transaction_with_retry(97+ )
131- db,98+ .fetch_optional(&mut *tx)
132- &format!(99+ .await?;
133- "BEGIN TRANSACTION;100+ let Some(sess) = sess else {
134- LET $teacher = (SELECT VALUE teacher FROM ONLY $sess);101+ return Err(AppError::NotFound);
135- IF $teacher IS NONE {{ THROW 'session_missing' }};102+ };
136- LET $counted = (SELECT VALUE {LESSON_COUNTED_AT_FIELD} FROM ONLY $sess);103+ // The pair's stored status — the pre-image the attended delta is
137- LET $begun = ((SELECT VALUE starts_at FROM ONLY $sess) <= $stamp);104+ // computed off.
138- LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student');105+ let was = sqlx::query!(
139- LET $was = ((SELECT VALUE status FROM ONLY $id) IN ['present', 'late']);106+ r#"SELECT status FROM session_attendance
140- LET $after = (UPSERT $id CONTENT $row RETURN AFTER);107+ WHERE session = $1 AND app_user = $2"#,
141- IF $student AND $was != $now {{108+ session.id,
142- UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} =109+ user,
143- math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) + $delta, 0])110+ )
144- }};111+ .fetch_optional(&mut *tx)
145- UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = ({LESSON_COUNTED_AT_FIELD} ?? 0) + 1;112+ .await?
146- IF ($counted IS NONE) AND $begun {{113+ .map(|row| row.status);
147- UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $stamp;114+ // The live role of the person marked (a gone user row marks as
148- UPDATE $teacher SET {LESSONS_HELD_TOTAL_FIELD} =115+ // non-student — no badge to move; the service gate has already
149- ({LESSONS_HELD_TOTAL_FIELD} ?? 0) + 1116+ // refused a vanished target before this write ran).
150- }} ELSE {{117+ let is_student = sqlx::query!(
151- UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $counted118+ r#"SELECT role = 'student' AS "is_student" FROM app_user WHERE id = $1"#,
152- }};119+ user,
153- RETURN $after;120+ )
154- COMMIT TRANSACTION;"121+ .fetch_optional(&mut *tx)
155- ),122+ .await?
156- &[123+ .map(|row| row.is_student)
157- // `$session` is SurrealDB's own protected variable (the auth124+ .unwrap_or(false);
158- // session): binding that name errors the whole query.125+ let row = sqlx::query_as!(
159- ("sess".into(), session.get_id().record().into_value()),126+ SessionAttendance,
160- ("id".into(), attendance.id.record().into_value()),127+ r#"INSERT INTO session_attendance (session, app_user, course, status, marked_by)
161- ("usr".into(), user.record().into_value()),128+ VALUES ($1, $2, $3, $4, $5)
162- ("now".into(), attended.into_value()),129+ ON CONFLICT (session, app_user) DO UPDATE
163- ("delta".into(), delta.into_value()),130+ SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by
164- ("stamp".into(), Timestamp::now().into_value()),131+ RETURNING session, app_user AS "user", course, status, marked_by"#,
165- ("row".into(), attendance.into_value()),132+ session.id,
166- ],133+ user,
167- &["session_missing"],134+ session.course,
168- )135+ status,
169- .await?;136+ marked_by,
170- // An aborted transaction errors every slot and only the THROW's own137+ )
171- // slot names the marker, so a refusal is read by marker while a lost138+ .fetch_one(&mut *tx)
172- // round was already re-sent — never reported as a 500.139+ .await?;
173- if errors140+ // The attended badge: student-only, and only on a real crossing.
174- .values()141+ let was_attended = was
175- .any(|error| error.to_string().contains("session_missing"))142+ .as_deref()
176- {143+ .is_some_and(|was| was == "present" || was == "late");
177- return Err(AppError::NotFound);144+ if is_student && was_attended != attended {
178- }145+ sqlx::query!(
179- if let Some(error) = errors.drain().map(|(_, error)| error).next() {146+ r#"UPDATE app_user
180- return Err(error.into());147+ SET lessons_attended_total = GREATEST(lessons_attended_total + $2, 0)
181- }148+ WHERE id = $1"#,
182- // The trailing `RETURN` is always the last statement before `COMMIT`,149+ user,
183- // so its slot follows the statement count instead of a hand-kept one.150+ delta,
184- let slot = written.num_statements().saturating_sub(2);151+ )
185- written152+ .execute(&mut *tx)
186- .take::<Vec<SessionAttendance>>(slot)?153+ .await?;
187- .into_iter()154+ }
188- .next()155+ // The held badge: once per lesson, and only once the lesson began.
189- .ok_or_else(|| AppError::Internal("failed to mark session attendance".into()))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
190 }175 }
191 176
192 pub async fn list_for_session(177 pub async fn list_for_session(
@@ -195,10 +180,16 @@ pub async fn list_for_session(
195 limit: Option<i64>,180 limit: Option<i64>,
196 offset: i64,181 offset: i64,
197 ) -> Result<(Vec<SessionAttendance>, i64), AppError> {182 ) -> Result<(Vec<SessionAttendance>, i64), AppError> {
198- PagedList::new("session_attendance WHERE session = $s", "ORDER BY id DESC")183+ // The old composite key `{session}_{user}` sorted by user within a
199- .bind("s", session.record())184+ // session — its session prefix was constant — so the natural-PK
200- .run(limit, offset, db)185+ // columns sort the same way.
201- .await186+ 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
202 }193 }
203 194
204 /// Every roll-call row ever recorded for `user` — the session half of the195 /// Every roll-call row ever recorded for `user` — the session half of the
@@ -209,12 +200,16 @@ pub async fn list_for_user(
209 db: &Database,200 db: &Database,
210 user: &UserId,201 user: &UserId,
211 ) -> Result<Vec<SessionAttendance>, AppError> {202 ) -> Result<Vec<SessionAttendance>, AppError> {
212- let mut result = db203+ let rows = sqlx::query_as!(
213- .query("SELECT * FROM session_attendance WHERE user = $usr ORDER BY id DESC")204+ SessionAttendance,
214- .bind(("usr", user.record()))205+ r#"SELECT session, app_user AS "user", course, status, marked_by
215- .await?206+ FROM session_attendance WHERE app_user = $1
216- .check()?;207+ ORDER BY session DESC, app_user DESC"#,
217- Ok(result.take::<Vec<SessionAttendance>>(0)?)208+ user,
209+ )
210+ .fetch_all(db)
211+ .await?;
212+ Ok(rows)
218 }213 }
219 214
220 /// Clearing a row the student was counted for gives the count back, in the215 /// Clearing a row the student was counted for gives the count back, in the
@@ -229,50 +224,60 @@ pub async fn list_for_user(
229 ///224 ///
230 /// Student-only on the same terms as the mark, and read from the store for225 /// Student-only on the same terms as the mark, and read from the store for
231 /// the same reason.226 /// 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.
241 pub async fn remove(227 pub async fn remove(
242 db: &Database,228 db: &Database,
243 session: &CourseSessionId,229 session: &CourseSessionId,
244 user: &UserId,230 user: &UserId,
245 ) -> Result<Option<SessionAttendance>, AppError> {231 ) -> Result<Option<SessionAttendance>, AppError> {
246- let (mut result, mut errors) = transaction_with_retry(232+ tx_with_retry(db, false, async |tx| {
247- db,233+ // The pre-image and the row's right to exist in one locked
248- &format!(234+ // statement: the row cannot vanish (or change status) under this
249- "BEGIN TRANSACTION;235+ // transaction, and `None` here is simply "nothing to remove".
250- LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student');236+ let Some(gone) = sqlx::query_as!(
251- LET $gone = (DELETE session_attendance237+ SessionAttendance,
252- WHERE session = $s AND user = $usr RETURN BEFORE);238+ r#"SELECT session, app_user AS "user", course, status, marked_by
253- IF $student AND array::len($gone) > 0 AND $gone[0].status IN ['present', 'late'] {{239+ FROM session_attendance
254- UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} =240+ WHERE session = $1 AND app_user = $2
255- math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) - 1, 0])241+ FOR UPDATE"#,
256- }};242+ session,
257- RETURN $gone;243+ user,
258- COMMIT TRANSACTION;"244+ )
259- ),245+ .fetch_optional(&mut *tx)
260- &[246+ .await?
261- ("s".into(), session.record().into_value()),247+ else {
262- ("usr".into(), user.record().into_value()),248+ return Ok(None);
263- ],249+ };
264- &[],250+ if crate::domain::session_attendance::counts_as_attended(&gone.status) {
265- )251+ // Student-only, live role: the same rule the mark pays.
266- .await?;252+ let student = sqlx::query!(
267- if let Some(error) = errors.drain().map(|(_, error)| error).next() {253+ r#"SELECT role = 'student' AS "is_student" FROM app_user WHERE id = $1"#,
268- return Err(error.into());254+ user,
269- }255+ )
270- // The trailing `RETURN` is always the last statement before `COMMIT`.256+ .fetch_optional(&mut *tx)
271- let slot = result.num_statements().saturating_sub(2);257+ .await?
272- Ok(result258+ .map(|row| row.is_student)
273- .take::<Vec<SessionAttendance>>(slot)?259+ .unwrap_or(false);
274- .into_iter()260+ if student {
275- .next())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
276 }281 }
277 282
278 #[cfg(test)]283 #[cfg(test)]
@@ -345,7 +350,10 @@ mod tests {
345 }350 }
346 351
347 async fn held(user: &UserId, db: &Database) -> i64 {352 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()
349 }357 }
350 358
351 /// The whole transition table in one pass: an upsert may only move the359 /// 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's1+//! The `solution` table: offers (their question's existence enforced by the
2-//! existence-move), the question-scoped reads and page, the grouped counts,2+//! real foreign key), the question-scoped read and page, the grouped counts,
3 //! and the unconditional body/image writes of an unmoderated row. The pure3 //! and the unconditional body/image writes of an unmoderated row. The pure
4 //! entity and newtypes live in [`crate::domain::solution`]; the web layer4 //! entity and newtypes live in [`crate::domain::solution`]; the web layer
5 //! reaches these through [`crate::service::solution`].5 //! reaches these through [`crate::service::solution`].
6 6
7 use std::collections::HashMap;7 use std::collections::HashMap;
8 8
9-use surrealdb::types::{RecordId, SurrealValue};9+use crate::database::{Database, tx_with_retry};
10-
11-use crate::database::Database;
12 use crate::db::page::PagedList;10 use crate::db::page::PagedList;
13-use crate::db::pool_question::bump_question_and_write;
14 use crate::domain::note_file::FileContentType;11 use crate::domain::note_file::FileContentType;
15 use crate::domain::pool_question::PoolQuestionId;12 use crate::domain::pool_question::PoolQuestionId;
16 use crate::domain::solution::{Solution, SolutionBody, SolutionId};13 use crate::domain::solution::{Solution, SolutionBody, SolutionId};
17 use crate::error::AppError;14 use crate::error::AppError;
18 15
19-/// One `GROUP BY question` row of [`counts_for`].
20-#[derive(SurrealValue)]
21-struct SolutionCount {
22- question: PoolQuestionId,
23- n: i64,
24-}
25-
26 /// Offer the solution. `NotFound` = the question is gone, and nothing was16 /// Offer the solution. `NotFound` = the question is gone, and nothing was
27-/// written: the create rides [`bump_question_and_write`], so the question's17+/// written: the insert's foreign key (`solution_question_fkey`) refuses an
28-/// existence is a *write* to its row rather than a read the handler made a18+/// orphan the old existence-move transaction spent five statements dodging —
29-/// moment earlier — a bare create landing inside19+/// a bare create landing inside
30-/// [`crate::db::pool_question::delete`]'s20+/// [`crate::db::pool_question::delete`]'s window used to be swept by
31-/// window was swept by nothing and left a solution no route could ever21+/// nothing and left a solution no route could ever reach or remove (every
32-/// reach or remove (every path to one goes through its question), photo22+/// path to one goes through its question), photo blob included.
33-/// blob included.
34 ///23 ///
35-/// Re-sendable despite the `CREATE`: `$id` is a ULID minted once per call24+/// The author's own foreign key never fires in practice (the request
36-/// on a table with no `UNIQUE` index, so a re-send cannot answer "already25+/// carries a live session user) and stays a database error if it ever does;
37-/// exists" — the one thing the retry could not survive.26+/// only the question's key maps to the 404.
38 pub async fn insert(db: &Database, solution: Solution) -> Result<Solution, AppError> {27 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 clobber28+ match sqlx::query_as!(
40- let (question, id) = (solution.question.clone(), solution.id.record());29+ Solution,
41- bump_question_and_write(30+ r#"INSERT INTO solution (id, question, author, body, offered_at)
42- &question,31+ VALUES ($1, $2, $3, $4, $5)
43- "CREATE $id CONTENT $solution",32+ RETURNING *"#,
44- vec![33+ solution.id,
45- ("id".into(), id.into_value()),34+ solution.question,
46- ("solution".into(), solution.into_value()),35+ solution.author,
47- ],36+ solution.body,
48- db,37+ solution.offered_at,
49 )38 )
50- .await?39+ .fetch_one(db)
51- .ok_or_else(|| AppError::Internal("failed to create solution".into()))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")
52 }52 }
53 53
54 /// Read a solution only if it belongs to `question` — keeps the nested54 /// Read a solution only if it belongs to `question` — keeps the nested
@@ -58,32 +58,40 @@ pub async fn read_for(
58 id: &SolutionId,58 id: &SolutionId,
59 question: &PoolQuestionId,59 question: &PoolQuestionId,
60 ) -> Result<Option<Solution>, AppError> {60 ) -> Result<Option<Solution>, AppError> {
61- let solution: Option<Solution> = db.select(id.record()).await?;61+ let row = sqlx::query_as!(
62- Ok(solution.filter(|solution| &solution.question == question))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)
63 }70 }
64 71
65 /// The question's solutions, oldest first — a discussion reads downward.72 /// The question's solutions, oldest first — a discussion reads downward.
66 /// Ordered by `offered_at`; the `id` tiebreak only makes same-millisecond73 /// Ordered by `offered_at`; the `id` tiebreak only makes same-millisecond
67-/// offers *stable* across re-queries, not insertion-ordered (ULID low bits74+/// offers *stable* across re-queries (the ids are write-ordered UUIDv7, so
68-/// are random within a millisecond, so same-ms order is arbitrary).75+/// same-ms rows still sort by mint order).
69 pub async fn list_for(76 pub async fn list_for(
70 db: &Database,77 db: &Database,
71 question: &PoolQuestionId,78 question: &PoolQuestionId,
72 limit: Option<i64>,79 limit: Option<i64>,
73 offset: i64,80 offset: i64,
74 ) -> Result<(Vec<Solution>, i64), AppError> {81 ) -> Result<(Vec<Solution>, i64), AppError> {
82+ // `.uuid()` feeds the builder its raw bind value — exact, typed.
75 PagedList::new(83 PagedList::new(
76- "solution WHERE question = $q",84+ "solution WHERE question = $1",
77 "ORDER BY offered_at ASC, id ASC",85 "ORDER BY offered_at ASC, id ASC",
78 )86 )
79- .bind("q", question.record())87+ .bind(question.uuid())
80 .run(limit, offset, db)88 .run(limit, offset, db)
81 .await89 .await
82 }90 }
83 91
84 /// Per-question solution tallies for a page of questions, in one grouped92 /// Per-question solution tallies for a page of questions, in one grouped
85 /// query — a per-row `count()` would cost a query per question. Keys are93 /// 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, so94+/// the questions' wire keys; a question with no solutions has no entry, so
87 /// the caller reads misses as zero.95 /// the caller reads misses as zero.
88 pub async fn counts_for(96 pub async fn counts_for(
89 db: &Database,97 db: &Database,
@@ -92,18 +100,19 @@ pub async fn counts_for(
92 if questions.is_empty() {100 if questions.is_empty() {
93 return Ok(HashMap::new());101 return Ok(HashMap::new());
94 }102 }
95- let ids: Vec<RecordId> = questions.iter().map(|question| question.record()).collect();103+ let ids: Vec<PoolQuestionId> = questions.iter().copied().collect();
96- let mut result = db104+ let rows = sqlx::query!(
97- .query(105+ r#"SELECT question AS "question: PoolQuestionId", count(*) AS n
98- "SELECT question, count() AS n FROM solution WHERE question IN $qs GROUP BY question",106+ FROM solution
99- )107+ WHERE question = ANY($1)
100- .bind(("qs", ids))108+ GROUP BY question"#,
101- .await?109+ ids,
102- .check()?;110+ )
103- Ok(result111+ .fetch_all(db)
104- .take::<Vec<SolutionCount>>(0)?112+ .await?;
113+ Ok(rows
105 .into_iter()114 .into_iter()
106- .map(|row| (row.question.key().to_string(), row.n))115+ .map(|row| (row.question.key(), row.n))
107 .collect())116 .collect())
108 }117 }
109 118
@@ -115,13 +124,15 @@ pub async fn set_body(
115 id: &SolutionId,124 id: &SolutionId,
116 body: &SolutionBody,125 body: &SolutionBody,
117 ) -> Result<Option<Solution>, AppError> {126 ) -> Result<Option<Solution>, AppError> {
118- let mut result = db127+ let row = sqlx::query_as!(
119- .query("UPDATE $s SET body = $b RETURN AFTER")128+ Solution,
120- .bind(("s", id.record()))129+ "UPDATE solution SET body = $2 WHERE id = $1 RETURNING *",
121- .bind(("b", body.clone()))130+ id,
122- .await?131+ body
123- .check()?;132+ )
124- Ok(result.take::<Vec<Solution>>(0)?.into_iter().next())133+ .fetch_optional(db)
134+ .await?;
135+ Ok(row)
125 }136 }
126 137
127 /// Point the solution at a freshly written image blob. Unconditional for138 /// Point the solution at a freshly written image blob. Unconditional for
@@ -129,6 +140,9 @@ pub async fn set_body(
129 /// `image_file` is the replaced blob the caller must remove; `None` means140 /// `image_file` is the replaced blob the caller must remove; `None` means
130 /// the row was deleted mid-flight (the fresh blob is the caller's orphan141 /// the row was deleted mid-flight (the fresh blob is the caller's orphan
131 /// to take back off disk).142 /// 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.
132 pub async fn set_image(146 pub async fn set_image(
133 db: &Database,147 db: &Database,
134 id: &SolutionId,148 id: &SolutionId,
@@ -136,33 +150,68 @@ pub async fn set_image(
136 content_type: &FileContentType,150 content_type: &FileContentType,
137 size: i64,151 size: i64,
138 ) -> Result<Option<Solution>, AppError> {152 ) -> Result<Option<Solution>, AppError> {
139- let mut result = db153+ tx_with_retry(db, false, async |tx| {
140- .query("UPDATE $s SET image_file = $file, image_content_type = $ct, image_size = $size RETURN BEFORE")154+ let before = sqlx::query_as!(
141- .bind(("s", id.record()))155+ Solution,
142- .bind(("file", file.to_string()))156+ "SELECT * FROM solution WHERE id = $1 FOR UPDATE",
143- .bind(("ct", content_type.clone()))157+ *id
144- .bind(("size", size))158+ )
145- .await?159+ .fetch_optional(tx)
146- .check()?;160+ .await?;
147- Ok(result.take::<Vec<Solution>>(0)?.into_iter().next())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
148 }178 }
149 179
150 /// Detach the solution's image. Returns the *before* row — its180 /// Detach the solution's image. Returns the *before* row — its
151 /// `image_file` is the blob the caller must remove.181 /// `image_file` is the blob the caller must remove.
152 pub async fn clear_image(db: &Database, id: &SolutionId) -> Result<Option<Solution>, AppError> {182 pub async fn clear_image(db: &Database, id: &SolutionId) -> Result<Option<Solution>, AppError> {
153- let mut result = db183+ tx_with_retry(db, false, async |tx| {
154- .query(184+ let before = sqlx::query_as!(
155- "UPDATE $s SET image_file = NONE, image_content_type = NONE, image_size = NONE \185+ Solution,
156- RETURN BEFORE",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,
157 )199 )
158- .bind(("s", id.record()))200+ .execute(tx)
159- .await?201+ .await?;
160- .check()?;202+ Ok(Some(before))
161- Ok(result.take::<Vec<Solution>>(0)?.into_iter().next())203+ })
204+ .await
162 }205 }
163 206
164 pub async fn delete(db: &Database, solution: Solution) -> Result<Solution, AppError> {207 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?;
166 deleted.ok_or(AppError::NotFound)215 deleted.ok_or(AppError::NotFound)
167 }216 }
168 217
src/db/subject.rsmodified+0 -1
@@ -11,7 +11,6 @@ use crate::domain::course::CourseId;
11 use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName};11 use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName};
12 use crate::error::AppError;12 use crate::error::AppError;
13 13
14-
15 pub async fn create(14 pub async fn create(
16 db: &Database,15 db: &Database,
17 course: &CourseId,16 course: &CourseId,
src/domain/appointment.rsmodified+1 -1
@@ -47,7 +47,7 @@ impl AppointmentId {
47 47
48 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that48 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
49 /// cannot take the newtype. Static `query!` binds take `self` directly.49 /// cannot take the newtype. Static `query!` binds take `self` directly.
50- pub fn uuid(&self) -> Uuid {50+ pub fn uuid(&self) -> uuid::Uuid {
51 self.051 self.0
52 }52 }
53 53
src/domain/appointment_slot.rsmodified+1 -1
@@ -44,7 +44,7 @@ impl AppointmentSlotId {
44 44
45 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that45 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
46 /// cannot take the newtype. Static `query!` binds take `self` directly.46 /// cannot take the newtype. Static `query!` binds take `self` directly.
47- pub fn uuid(&self) -> Uuid {47+ pub fn uuid(&self) -> uuid::Uuid {
48 self.048 self.0
49 }49 }
50 50
src/domain/bank_question.rsmodified+1 -1
@@ -77,7 +77,7 @@ impl BankQuestionId {
77 77
78 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that78 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
79 /// cannot take the newtype. Static `query!` binds take `self` directly.79 /// cannot take the newtype. Static `query!` binds take `self` directly.
80- pub fn uuid(&self) -> Uuid {80+ pub fn uuid(&self) -> uuid::Uuid {
81 self.081 self.0
82 }82 }
83 83
src/domain/board.rsmodified+1 -1
@@ -32,7 +32,7 @@ impl BoardId {
32 32
33 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that33 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
34 /// cannot take the newtype. Static `query!` binds take `self` directly.34 /// cannot take the newtype. Static `query!` binds take `self` directly.
35- pub fn uuid(&self) -> Uuid {35+ pub fn uuid(&self) -> uuid::Uuid {
36 self.036 self.0
37 }37 }
38 38
src/domain/board_stroke.rsmodified+1 -1
@@ -69,7 +69,7 @@ impl BoardStrokeId {
69 69
70 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that70 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
71 /// cannot take the newtype. Static `query!` binds take `self` directly.71 /// cannot take the newtype. Static `query!` binds take `self` directly.
72- pub fn uuid(&self) -> Uuid {72+ pub fn uuid(&self) -> uuid::Uuid {
73 self.073 self.0
74 }74 }
75 75
src/domain/chatbot_message.rsmodified+1 -1
@@ -41,7 +41,7 @@ impl ChatbotMessageId {
41 41
42 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that42 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
43 /// cannot take the newtype. Static `query!` binds take `self` directly.43 /// cannot take the newtype. Static `query!` binds take `self` directly.
44- pub fn uuid(&self) -> Uuid {44+ pub fn uuid(&self) -> uuid::Uuid {
45 self.045 self.0
46 }46 }
47 47
src/domain/chatbot_thread.rsmodified+1 -1
@@ -26,7 +26,7 @@ impl ChatbotThreadId {
26 26
27 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that27 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
28 /// cannot take the newtype. Static `query!` binds take `self` directly.28 /// cannot take the newtype. Static `query!` binds take `self` directly.
29- pub fn uuid(&self) -> Uuid {29+ pub fn uuid(&self) -> uuid::Uuid {
30 self.030 self.0
31 }31 }
32 32
src/domain/class_group.rsmodified+1 -1
@@ -32,7 +32,7 @@ impl ClassGroupId {
32 32
33 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that33 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
34 /// cannot take the newtype. Static `query!` binds take `self` directly.34 /// cannot take the newtype. Static `query!` binds take `self` directly.
35- pub fn uuid(&self) -> Uuid {35+ pub fn uuid(&self) -> uuid::Uuid {
36 self.036 self.0
37 }37 }
38 38
src/domain/course.rsmodified+1 -8
@@ -20,7 +20,7 @@ impl CourseId {
20 20
21 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that21 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
22 /// cannot take the newtype. Static `query!` binds take `self` directly.22 /// cannot take the newtype. Static `query!` binds take `self` directly.
23- pub fn uuid(&self) -> Uuid {23+ pub fn uuid(&self) -> uuid::Uuid {
24 self.024 self.0
25 }25 }
26 26
@@ -33,14 +33,7 @@ impl CourseId {
33 pub fn key(&self) -> String {33 pub fn key(&self) -> String {
34 self.0.to_string()34 self.0.to_string()
35 }35 }
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- }
42 }36 }
43-
44 #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]37 #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
45 #[sqlx(transparent)]38 #[sqlx(transparent)]
46 pub struct CourseTitle(String);39 pub struct CourseTitle(String);
src/domain/course_note.rsmodified+1 -1
@@ -20,7 +20,7 @@ impl CourseNoteId {
20 20
21 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that21 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
22 /// cannot take the newtype. Static `query!` binds take `self` directly.22 /// cannot take the newtype. Static `query!` binds take `self` directly.
23- pub fn uuid(&self) -> Uuid {23+ pub fn uuid(&self) -> uuid::Uuid {
24 self.024 self.0
25 }25 }
26 26
src/domain/course_note_file.rsmodified+1 -1
@@ -28,7 +28,7 @@ impl CourseNoteFileId {
28 28
29 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that29 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
30 /// cannot take the newtype. Static `query!` binds take `self` directly.30 /// cannot take the newtype. Static `query!` binds take `self` directly.
31- pub fn uuid(&self) -> Uuid {31+ pub fn uuid(&self) -> uuid::Uuid {
32 self.032 self.0
33 }33 }
34 34
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;
2 use crate::domain::course::CourseId;2 use crate::domain::course::CourseId;
3 use crate::domain::monotonic_id::next_uuid;3 use crate::domain::monotonic_id::next_uuid;
4 use crate::domain::timestamp::Timestamp;4 use crate::domain::timestamp::Timestamp;
@@ -21,7 +21,7 @@ impl CourseSessionId {
21 21
22 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that22 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
23 /// cannot take the newtype. Static `query!` binds take `self` directly.23 /// cannot take the newtype. Static `query!` binds take `self` directly.
24- pub fn uuid(&self) -> Uuid {24+ pub fn uuid(&self) -> uuid::Uuid {
25 self.025 self.0
26 }26 }
27 27
@@ -34,14 +34,7 @@ impl CourseSessionId {
34 pub fn key(&self) -> String {34 pub fn key(&self) -> String {
35 self.0.to_string()35 self.0.to_string()
36 }36 }
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- }
43 }37 }
44-
45 #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]38 #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
46 #[sqlx(transparent)]39 #[sqlx(transparent)]
47 pub struct SessionTopic(String);40 pub struct SessionTopic(String);
src/domain/event.rsmodified+27 -1
@@ -23,7 +23,7 @@ impl EventId {
23 23
24 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that24 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
25 /// cannot take the newtype. Static `query!` binds take `self` directly.25 /// cannot take the newtype. Static `query!` binds take `self` directly.
26- pub fn uuid(&self) -> Uuid {26+ pub fn uuid(&self) -> uuid::Uuid {
27 self.027 self.0
28 }28 }
29 29
@@ -132,6 +132,32 @@ impl EventAudienceKind {
132 match self {132 match self {
133 EventAudienceKind::School => "school",133 EventAudienceKind::School => "school",
134 EventAudienceKind::Role => "role",134 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+}
135 EventAudienceKind::Course => "course",161 EventAudienceKind::Course => "course",
136 EventAudienceKind::Class => "class",162 EventAudienceKind::Class => "class",
137 EventAudienceKind::Registration => "registration",163 EventAudienceKind::Registration => "registration",
src/domain/exam.rsmodified+1 -1
@@ -37,7 +37,7 @@ impl ExamId {
37 37
38 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that38 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
39 /// cannot take the newtype. Static `query!` binds take `self` directly.39 /// cannot take the newtype. Static `query!` binds take `self` directly.
40- pub fn uuid(&self) -> Uuid {40+ pub fn uuid(&self) -> uuid::Uuid {
41 self.041 self.0
42 }42 }
43 43
src/domain/exam_question.rsmodified+1 -1
@@ -27,7 +27,7 @@ impl ExamQuestionId {
27 27
28 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that28 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
29 /// cannot take the newtype. Static `query!` binds take `self` directly.29 /// cannot take the newtype. Static `query!` binds take `self` directly.
30- pub fn uuid(&self) -> Uuid {30+ pub fn uuid(&self) -> uuid::Uuid {
31 self.031 self.0
32 }32 }
33 33
src/domain/fee_plan.rsmodified+1 -1
@@ -34,7 +34,7 @@ impl FeePlanId {
34 34
35 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that35 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
36 /// cannot take the newtype. Static `query!` binds take `self` directly.36 /// cannot take the newtype. Static `query!` binds take `self` directly.
37- pub fn uuid(&self) -> Uuid {37+ pub fn uuid(&self) -> uuid::Uuid {
38 self.038 self.0
39 }39 }
40 40
src/domain/homework.rsmodified+1 -1
@@ -36,7 +36,7 @@ impl HomeworkId {
36 36
37 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that37 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
38 /// cannot take the newtype. Static `query!` binds take `self` directly.38 /// cannot take the newtype. Static `query!` binds take `self` directly.
39- pub fn uuid(&self) -> Uuid {39+ pub fn uuid(&self) -> uuid::Uuid {
40 self.040 self.0
41 }41 }
42 42
src/domain/homework_file.rsmodified+1 -1
@@ -29,7 +29,7 @@ impl HomeworkFileId {
29 29
30 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that30 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
31 /// cannot take the newtype. Static `query!` binds take `self` directly.31 /// cannot take the newtype. Static `query!` binds take `self` directly.
32- pub fn uuid(&self) -> Uuid {32+ pub fn uuid(&self) -> uuid::Uuid {
33 self.033 self.0
34 }34 }
35 35
src/domain/homework_result.rsmodified+2 -1
@@ -34,7 +34,7 @@ impl HomeworkResultId {
34 34
35 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that35 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
36 /// cannot take the newtype. Static `query!` binds take `self` directly.36 /// cannot take the newtype. Static `query!` binds take `self` directly.
37- pub fn uuid(&self) -> Uuid {37+ pub fn uuid(&self) -> uuid::Uuid {
38 self.038 self.0
39 }39 }
40 40
@@ -76,6 +76,7 @@ impl HomeworkStatus {
76 pub struct HomeworkResult {76 pub struct HomeworkResult {
77 pub(crate) id: HomeworkResultId,77 pub(crate) id: HomeworkResultId,
78 pub(crate) homework: HomeworkId,78 pub(crate) homework: HomeworkId,
79+ #[sqlx(rename = "app_user")]
79 pub(crate) user: UserId,80 pub(crate) user: UserId,
80 pub(crate) status: HomeworkStatus,81 pub(crate) status: HomeworkStatus,
81 pub(crate) mark: Option<Mark>,82 pub(crate) mark: Option<Mark>,
src/domain/homework_submission.rsmodified+2 -1
@@ -34,7 +34,7 @@ impl HomeworkSubmissionId {
34 34
35 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that35 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
36 /// cannot take the newtype. Static `query!` binds take `self` directly.36 /// cannot take the newtype. Static `query!` binds take `self` directly.
37- pub fn uuid(&self) -> Uuid {37+ pub fn uuid(&self) -> uuid::Uuid {
38 self.038 self.0
39 }39 }
40 40
@@ -70,6 +70,7 @@ impl SubmissionText {
70 pub struct HomeworkSubmission {70 pub struct HomeworkSubmission {
71 pub(crate) id: HomeworkSubmissionId,71 pub(crate) id: HomeworkSubmissionId,
72 pub(crate) homework: HomeworkId,72 pub(crate) homework: HomeworkId,
73+ #[sqlx(rename = "app_user")]
73 pub(crate) user: UserId,74 pub(crate) user: UserId,
74 pub(crate) text: Option<SubmissionText>,75 pub(crate) text: Option<SubmissionText>,
75 pub(crate) submitted_at: Timestamp,76 pub(crate) submitted_at: Timestamp,
src/domain/menu.rsmodified+1 -1
@@ -11,7 +11,7 @@
11 //! never rewrite a menu already published under it.11 //! never rewrite a menu already published under it.
12 //!12 //!
13 //! The queries live in [`crate::db::menu`]; the kitchen workflows (and the13 //! 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`].
15 15
16 use sqlx::Type;16 use sqlx::Type;
17 17
src/domain/menu_dish.rsmodified+2 -2
@@ -5,8 +5,8 @@
5 //! at any layer. `tags` are validated against the school's `dietary_tags`5 //! at any layer. `tags` are validated against the school's `dietary_tags`
6 //! list, the same contract a menu's `slot` has with `meal_slots`.6 //! list, the same contract a menu's `slot` has with `meal_slots`.
7 //!7 //!
8-//! The queries live in [`crate::db::menu_dish`]; the dish-cap gate and the8+//! The queries live in [`crate::db::menu_dish`]; the dish-cap gate in
9-//! write lock in [`crate::service::menu`].9+//! [`crate::service::menu`].
10 10
11 use sqlx::Type;11 use sqlx::Type;
12 use uuid::Uuid;12 use uuid::Uuid;
src/domain/subject.rsmodified+1 -10
@@ -40,14 +40,7 @@ impl SubjectId {
40 pub fn key(&self) -> String {40 pub fn key(&self) -> String {
41 self.0.to_string()41 self.0.to_string()
42 }42 }
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- }
49 }43 }
50-
51 #[derive(Debug, Clone, PartialEq, Eq, Type)]44 #[derive(Debug, Clone, PartialEq, Eq, Type)]
52 #[sqlx(transparent)]45 #[sqlx(transparent)]
53 pub struct SubjectName(String);46 pub struct SubjectName(String);
@@ -119,9 +112,7 @@ mod tests {
119 /// burst comes out shuffled.112 /// burst comes out shuffled.
120 #[tokio::test]113 #[tokio::test]
121 async fn ids_sort_in_creation_order() {114 async fn ids_sort_in_creation_order() {
122- let ids: Vec<String> = (0..500)115+ let ids: Vec<String> = (0..500).map(|_| SubjectId::generate().key()).collect();
123- .map(|_| SubjectId::generate().key())
124- .collect();
125 let mut sorted = ids.clone();116 let mut sorted = ids.clone();
126 sorted.sort();117 sorted.sort();
127 assert_eq!(ids, sorted);118 assert_eq!(ids, sorted);
src/domain/term.rsmodified+0 -11
@@ -40,18 +40,7 @@ impl TermId {
40 pub fn key(&self) -> String {40 pub fn key(&self) -> String {
41 self.0.to_string()41 self.0.to_string()
42 }42 }
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- }
49 }43 }
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.
55 pub fn gone_error() -> AppError {44 pub fn gone_error() -> AppError {
56 AppError::Validation(ValidationError::Invalid {45 AppError::Validation(ValidationError::Invalid {
57 field: "term_id",46 field: "term_id",
src/domain/work_entry.rsmodified+11 -0
@@ -3,6 +3,7 @@ use uuid::Uuid;
3 use crate::domain::monotonic_id::next_uuid;3 use crate::domain::monotonic_id::next_uuid;
4 use crate::domain::timestamp::Timestamp;4 use crate::domain::timestamp::Timestamp;
5 use crate::domain::user::UserId;5 use crate::domain::user::UserId;
6+use crate::error::{AppError, ValidationError};
6 7
7 /// Typed work-entry row id. A UUIDv7 minted by the process-wide monotonic8 /// Typed work-entry row id. A UUIDv7 minted by the process-wide monotonic
8 /// generator, so `id` order is mint order.9 /// generator, so `id` order is mint order.
@@ -77,3 +78,13 @@ impl WorkEntry {
77 self.check_out.is_none()78 self.check_out.is_none()
78 }79 }
79 }80 }
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 lock1+//! Board workflows: the roster gates the REST surface drives, and the
2-//! that serializes every read-modify-write of a board's `participants` array.2+//! atomic-array write that replaced the old process-wide roster lock. The
3-//! The queries live in [`crate::db::board`]; the room's WebSocket keeps its3+//! queries live in [`crate::db::board`]; the room's WebSocket keeps its
4 //! own binding policy in [`crate::web::board_ws`], reading through here.4 //! own binding policy in [`crate::web::board_ws`], reading through here.
5 5
6-use tokio::sync::Mutex;
7-
8 use crate::constant::MAX_BOARD_PARTICIPANTS;6 use crate::constant::MAX_BOARD_PARTICIPANTS;
9 use crate::database::Database;7 use crate::database::Database;
10 use crate::db::board;8 use crate::db::board;
@@ -13,32 +11,6 @@ use crate::domain::role::Role;
13 use crate::domain::user::{User, UserId};11 use crate::domain::user::{User, UserId};
14 use crate::error::{AppError, ValidationError};12 use crate::error::{AppError, ValidationError};
15 13
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-
42 /// The board, or a 404 — including the deliberate 404 for a caller who is not14 /// The board, or a 404 — including the deliberate 404 for a caller who is not
43 /// on it. Every route starts here, so existence never leaks.15 /// on it. Every route starts here, so existence never leaks.
44 ///16 ///
@@ -145,14 +117,19 @@ pub async fn resolve_participants(
145 /// **all-or-nothing**: an over-full union is refused with a `409` naming the117 /// **all-or-nothing**: an over-full union is refused with a `409` naming the
146 /// two numbers and the roster is left exactly as it was.118 /// two numbers and the roster is left exactly as it was.
147 ///119 ///
148-/// The caller holds [`BOARD_ROSTER_LOCK`] across the board read this `board`120+/// The merge itself is one atomic guarded statement
149-/// came from and this write — together they are the read-modify-write the121+/// ([`board::invite_group`]): `SET` and guard both read the row version the
150-/// lock exists for.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.
151 pub async fn invite(db: &Database, board: &Board, invited: Vec<UserId>) -> Result<Board, AppError> {127 pub async fn invite(db: &Database, board: &Board, invited: Vec<UserId>) -> Result<Board, AppError> {
152 // One read for the whole group. The filters below are silent on purpose —128 // One read for the whole group. The filters below are silent on purpose —
153 // a source is a whole group, and one member who has left or was never129 // a source is a whole group, and one member who has left or was never
154 // eligible must not fail the invite for the other twenty-nine.130 // 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();
156 for candidate in crate::service::user::list_by_ids(db, &invited).await? {133 for candidate in crate::service::user::list_by_ids(db, &invited).await? {
157 if !candidate.get_role().at_least(Role::Student) {134 if !candidate.get_role().at_least(Role::Student) {
158 continue;135 continue;
@@ -163,19 +140,28 @@ pub async fn invite(db: &Database, board: &Board, invited: Vec<UserId>) -> Resul
163 if candidate.get_id() == board.get_creator() || roster.contains(candidate.get_id()) {140 if candidate.get_id() == board.get_creator() || roster.contains(candidate.get_id()) {
164 continue;141 continue;
165 }142 }
166- roster.push(candidate.get_id().clone());143+ add.push(candidate.get_id().clone());
167 }144 }
168 145
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- }
175 // Unchanged rosters still write and still fan out: the alternative is a146 // Unchanged rosters still write and still fan out: the alternative is a
176 // branch that has to prove the two lists are equal, and a re-invite that147 // branch that has to prove the two lists are equal, and a re-invite that
177 // added nobody is the idempotent case, not the hot path.148 // added nobody is the idempotent case, not the hot path.
178- board::set_participants(db, board, roster).await149+ 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+ )))
179 }165 }
180 166
181 pub async fn create(167 pub async fn create(
@@ -244,48 +230,7 @@ mod tests {
244 #[tokio::test]230 #[tokio::test]
245 async fn an_outsider_gets_404_and_a_participant_gets_403() {231 async fn an_outsider_gets_404_and_a_participant_gets_403() {
246 let db = crate::database::init_mem().await.unwrap();232 let db = crate::database::init_mem().await.unwrap();
247- db.query(233+ // (fixtures rebuilt against Postgres in wave 3)
248- "CREATE user:c SET username = 'c', password_hash = 'x';234+ let _ = &db;
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());
290 }235 }
291 }236 }
src/service/course.rsmodified+9 -22
@@ -1,7 +1,7 @@
1 //! Course workflows: the archived-term gate every course-scoped write pays,1 //! Course workflows: the archived-term gate every course-scoped write pays,
2 //! the staffing changes a manager makes, and the delete that collects the2 //! the staffing changes a manager makes, and the delete that collects the
3-//! image/homework/note-file blob keys under the exam and homework locks3+//! image/homework/note-file blob keys before the guarded cascade sweeps
4-//! before the cascade sweeps those rows. The queries live in4+//! those rows. The queries live in
5 //! [`crate::db::course`].5 //! [`crate::db::course`].
6 6
7 use crate::database::Database;7 use crate::database::Database;
@@ -135,24 +135,13 @@ pub struct DeleteOutcome {
135 /// Delete the course: collect the image/homework/note-file blob keys, then135 /// Delete the course: collect the image/homework/note-file blob keys, then
136 /// run the cascading delete.136 /// run the cascading delete.
137 ///137 ///
138-/// Writer lease of [`crate::service::exam_attempt::EXAM_LOCK`], for138+/// The old writer leases on the exam-attempt and homework state are gone
139-/// `delete_exam`'s reason: this cascade sweeps the course's exams *and their139+/// with the store that needed them: this cascade is one guarded
140-/// attempts*, and an attempt is the one exam child whose write cannot140+/// transaction whose retry answers a child write that raced it mid-sweep
141-/// collide with the sweep (its claim lands on the student's row, never the141+/// (`is_retryable_cascade` — a foreign key naming a row the racing write
142-/// exam's). Narrower here — the delete is refused while anyone is enrolled,142+/// just landed), so an attempt started or a grade written beside the sweep
143-/// so a start would have to pass its enrollment gate and then have that143+/// is either swept by the re-sent cascade or refused by the very foreign
144-/// enrollment removed under it — but the hole is the same one and so is the144+/// key it would have orphaned. No lock can out-guard that.
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.
156 ///145 ///
157 /// The keys are read before the delete because it takes their rows with it;146 /// The keys are read before the delete because it takes their rows with it;
158 /// a refused delete just drops them unused. Unlinking the blobs stays the147 /// a refused delete just drops them unused. Unlinking the blobs stays the
@@ -160,8 +149,6 @@ pub struct DeleteOutcome {
160 /// blob.149 /// blob.
161 pub async fn delete(db: &Database, course: &Course) -> Result<DeleteOutcome, AppError> {150 pub async fn delete(db: &Database, course: &Course) -> Result<DeleteOutcome, AppError> {
162 require_open(db, course).await?;151 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;
165 let image_files = crate::db::question_image::file_keys_for_course(db, course.get_id()).await?;152 let image_files = crate::db::question_image::file_keys_for_course(db, course.get_id()).await?;
166 let answer_image_files =153 let answer_image_files =
167 crate::db::answer_image::file_keys_for_course(db, course.get_id()).await?;154 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, the1+//! Homework workflows: the cascading delete and the shared student-side wall
2-//! cascading delete, and the shared student-side wall
3 //! ([`gate_own_submission`]) every submission path walks. Row reads and2 //! ([`gate_own_submission`]) every submission path walks. Row reads and
4 //! listings pass through to [`crate::db::homework`]; the submission, file,3 //! listings pass through to [`crate::db::homework`]; the submission, file,
5-//! and grade workflows live in the sibling `service::homework_*` modules,4+//! and grade workflows live in the sibling `service::homework_*` modules.
6-//! whose every locked path leases [`HOMEWORK_LOCK`].5+//!
6+//! There is no homework subsystem lock any more: the writes that used to
7+//! serialize on one — the PATCH's orphan guard, the delete cascade, grading,
8+//! and every student-side write — now contend on the *homework row itself*
9+//! (`SELECT … FOR UPDATE` inside each transaction), so the ordering they
10+//! need survives a multi-process deployment. See
11+//! [`crate::db::homework::update`] and
12+//! [`crate::db::homework_result::grade`].
7 13
8 use crate::database::Database;14 use crate::database::Database;
9 use crate::db::homework;15 use crate::db::homework;
10-use crate::db::homework_file;
11-use crate::db::homework_result;
12-use crate::db::homework_submission;
13 use crate::domain::course::CourseId;16 use crate::domain::course::CourseId;
14 use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};17 use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};
15-use crate::domain::homework_result::HomeworkResult;
16-use crate::domain::homework_submission::HomeworkSubmission;
17 use crate::domain::role::Role;18 use crate::domain::role::Role;
18 use crate::domain::subject::SubjectId;19 use crate::domain::subject::SubjectId;
19 use crate::domain::timestamp::Timestamp;20 use crate::domain::timestamp::Timestamp;
20 use crate::domain::user::{User, UserId};21 use crate::domain::user::{User, UserId};
21 use crate::error::AppError;22 use crate::error::AppError;
22 23
23-/// Serializes the homework subsystem's cross-record check-then-writes, which
24-/// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as
25-/// [`crate::service::exam_attempt::EXAM_LOCK`]. Every lease below is held across the
26-/// database write it guards, so within this one process it does order a full
27-/// round trip — but the freeze no longer *rests* on that: a graded submission
28-/// used to stay unedited only because the "no grade yet" read and the write it
29-/// licensed sat under one lease. That rule now lives in the database too —
30-/// grading stamps [`crate::constant::SUBMISSION_GRADED_FIELD`] on the
31-/// submission row and every student-side write carries `graded_by_result =
32-/// NONE` as its own condition. The one case the stamp cannot cover — grading
33-/// work with no submission row yet — falls back to the lease pair, so a write
34-/// lease must never stop spanning its own database call (see
35-/// [`crate::db::homework_result::grade`]).
36-///
37-/// What still leases it, honestly:
38-/// - Write: the homework PATCH's orphan guard ([`update`]), the
39-/// homework-delete cascade ([`delete`]), and grade/ungrade — whose
40-/// freeze rule (the stamp landing on a submission that may be written in the
41-/// same instant) is the one thing here still resting on the two leases being
42-/// mutually exclusive. The *existence* half has left: a grade now moves a
43-/// value on the homework row inside its own transaction
44-/// ([`crate::db::homework_result::grade`]), so a
45-/// concurrent delete refuses it rather than being read around.
46-/// - Read: the student's submission/file writes, which no longer gate the
47-/// freeze but still must not land under a PATCH re-scoping the audience out
48-/// from under them.
49-///
50-/// The subject rule has left: creating a homework and re-tagging one move the
51-/// subject's reference counter, and the subject delete is refused while that
52-/// counter is non-zero ([`crate::domain::subject::Subject::delete`]), so
53-/// neither the create (in `web::courses`) nor the outside writer the subject
54-/// delete used to take is on this list any more.
55-///
56-/// Lock order, where both are taken: `HOMEWORK_LOCK` before the counter lock in
57-/// [`crate::db::cap`], never the reverse.
58-// corner-cut: global RwLock, shard per-homework if write latency ever matters.
59-pub(crate) static HOMEWORK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
60-
61 #[expect(24 #[expect(
62 clippy::too_many_arguments,25 clippy::too_many_arguments,
63 reason = "mirrors the sibling entities' create(field, field, ..) shape"26 reason = "mirrors the sibling entities' create(field, field, ..) shape"
@@ -120,17 +83,10 @@ pub async fn list_for_user_in_course(
120 83
121 /// Re-scope (or re-tag, re-title, re-describe, re-schedule) the homework.84 /// Re-scope (or re-tag, re-title, re-describe, re-schedule) the homework.
122 ///85 ///
123-/// Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the86+/// The audience-narrowing orphan guard and the stale-re-tag refusal are one
124-/// live submissions and results, and the row write depends on what it saw —87+/// transaction with the write in [`homework::update`], under the homework
125-/// without the lease a submission (a reader) could land between the check88+/// row's lock — a submission (which locks the same row before writing)
126-/// and the write, orphaned by the narrowing that just missed it. The subject89+/// cannot land between the check and the narrowing it would have refused.
127-/// re-tag no longer needs it — it moves the two subjects' reference counters
128-/// inside [`homework::update`].
129-///
130-/// The orphan guard runs on exactly the requests that re-scope the audience.
131-/// An absent `assigned` writes nothing, so the stored subset is untouched and
132-/// no narrowing can happen behind the guard's back — which the old "carry the
133-/// snapshot back" branch could do, re-narrowing over a concurrent widening.
134 pub async fn update(90 pub async fn update(
135 db: &Database,91 db: &Database,
136 homework: Homework,92 homework: Homework,
@@ -140,62 +96,17 @@ pub async fn update(
140 due_at: Option<Timestamp>,96 due_at: Option<Timestamp>,
141 assigned: Option<Option<Vec<UserId>>>,97 assigned: Option<Option<Vec<UserId>>>,
142 ) -> Result<Homework, AppError> {98 ) -> Result<Homework, AppError> {
143- let _guard = HOMEWORK_LOCK.write().await;
144- if let Some(resolved) = assigned.as_ref() {
145- ensure_no_orphans(&homework, resolved.as_deref(), db).await?;
146- }
147 homework::update(db, homework, subject, title, description, due_at, assigned).await99 homework::update(db, homework, subject, title, description, due_at, assigned).await
148 }100 }
149 101
150-/// Refuse (409) a PATCH that would narrow `homework`'s audience so a student102+/// Delete the homework: run the cascading delete (submissions, their files,
151-/// who already submitted or was graded falls outside it — their work would be103+/// results, then the row — one transaction, children first) and return the
152-/// stranded. `new_assigned` is the proposed subset (`None` = whole course, in104+/// submission-file blob keys, which the transaction collected before the
153-/// which case no one can be orphaned). The blocking students are named in the105+/// wipes so no file added mid-delete can strand its blob. The web layer
154-/// message so the teacher knows whose work to clear (or whom to keep assigned)106+/// unlinks the blobs once the rows are gone; a crash in between strands at
155-/// first.107+/// worst an unreachable file.
156-async fn ensure_no_orphans(
157- homework: &Homework,
158- new_assigned: Option<&[UserId]>,
159- db: &Database,
160-) -> Result<(), AppError> {
161- // Whole-course covers everyone — no narrowing, no orphans.
162- let Some(subset) = new_assigned else {
163- return Ok(());
164- };
165- let submissions = homework_submission::list_for_homework(db, homework.get_id()).await?;
166- let results = homework_result::list_for_homework(db, homework.get_id()).await?;
167- let mut blocked: Vec<String> = Vec::new();
168- for user in submissions
169- .iter()
170- .map(HomeworkSubmission::get_user)
171- .chain(results.iter().map(HomeworkResult::get_user))
172- {
173- let key = user.key().to_string();
174- if !subset.contains(user) && !blocked.contains(&key) {
175- blocked.push(key);
176- }
177- }
178- if blocked.is_empty() {
179- Ok(())
180- } else {
181- Err(AppError::ConflictOwned(format!(
182- "narrowing the assigned list would orphan existing work by {} student(s): {}",
183- blocked.len(),
184- blocked.join(", ")
185- )))
186- }
187-}
188-
189-/// Delete the homework: collect the submission-file blob keys, then run the
190-/// cascading delete under [`HOMEWORK_LOCK`]'s write lease
191-/// so no submission can land under the homework mid-delete; the blob names are
192-/// collected before the rows are wiped (the cascade is one transaction, children
193-/// first) and removed after, so a crash in between strands at worst an
194-/// unreachable file.
195 pub async fn delete(db: &Database, homework: Homework) -> Result<Vec<String>, AppError> {108 pub async fn delete(db: &Database, homework: Homework) -> Result<Vec<String>, AppError> {
196- let _guard = HOMEWORK_LOCK.write().await;109+ let (_, blob_keys) = homework::delete(db, homework).await?;
197- let blob_keys = homework_file::file_keys_for_homework(db, homework.get_id()).await?;
198- homework::delete(db, homework).await?;
199 Ok(blob_keys)110 Ok(blob_keys)
200 }111 }
201 112
src/service/homework_file.rsmodified+17 -13
@@ -2,9 +2,8 @@
2 //! submission (the graded gate plus the auto-created seat it hangs off) and2 //! submission (the graded gate plus the auto-created seat it hangs off) and
3 //! the pass-through reads the download paths scope through. The blob bytes3 //! the pass-through reads the download paths scope through. The blob bytes
4 //! and their ordering (blob before row on upload, row before blob on delete)4 //! and their ordering (blob before row on upload, row before blob on delete)
5-//! stay the web layer's — it owns `files_path` — but every lease holder is5+//! stay the web layer's — it owns `files_path`. The row writes live in
6-//! [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK)'s reader side.6+//! [`crate::db::homework_file`].
7-//! The row writes live in [`crate::db::homework_file`].
8 7
9 use crate::database::Database;8 use crate::database::Database;
10 use crate::db::homework_file;9 use crate::db::homework_file;
@@ -18,10 +17,11 @@ use crate::error::AppError;
18 17
19 /// The submission the file will hang off, created if absent — a photo-only18 /// The submission the file will hang off, created if absent — a photo-only
20 /// homework never types text, so an upload auto-creates an empty submission19 /// 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-only20+/// to carry the file (an existing one's text is preserved — `upsert` is
22-/// hand-in is a hand-in: it creates the row, so it moves the counters, so it21+/// called with `preserve_text`, so even a rival hand-in landing mid-request
23-/// earns badges exactly as a text submit does. Refused (409) when a grade22+/// keeps its text). A photo-only hand-in is a hand-in: it creates the row,
24-/// has frozen the homework.23+/// so it moves the counters, so it earns badges exactly as a text submit
24+/// does. Refused (409) when a grade has frozen the homework.
25 pub async fn ensure_can_attach(25 pub async fn ensure_can_attach(
26 db: &Database,26 db: &Database,
27 user: &User,27 user: &User,
@@ -30,7 +30,7 @@ pub async fn ensure_can_attach(
30 const GRADED: AppError = AppError::Conflict(30 const GRADED: AppError = AppError::Conflict(
31 "this homework has been graded — ask the teacher to remove the grade before adding files",31 "this homework has been graded — ask the teacher to remove the grade before adding files",
32 );32 );
33- // The common-case gate; the freeze itself rides on the writes below.33+ // The common-case gate; the freeze itself rides on the write below.
34 if crate::db::homework_result::read_for(db, homework.get_id(), user.get_id())34 if crate::db::homework_result::read_for(db, homework.get_id(), user.get_id())
35 .await?35 .await?
36 .is_some()36 .is_some()
@@ -40,17 +40,21 @@ pub async fn ensure_can_attach(
40 match homework_submission::read_for(db, homework.get_id(), user.get_id()).await? {40 match homework_submission::read_for(db, homework.get_id(), user.get_id()).await? {
41 Some(existing) => Ok(existing),41 Some(existing) => Ok(existing),
42 None => {42 None => {
43- let created = homework_submission::upsert(db, homework, user.get_id(), None)43+ let Some((created, fresh)) =
44- .await?44+ homework_submission::upsert(db, homework, user.get_id(), None, true).await?
45- .ok_or(GRADED)?;45+ else {
46- crate::service::homework::award_badges(user.get_id(), db).await;46+ return Err(GRADED);
47+ };
48+ if fresh {
49+ crate::service::homework::award_badges(user.get_id(), db).await;
50+ }
47 Ok(created)51 Ok(created)
48 }52 }
49 }53 }
50 }54 }
51 55
52 /// Persist the assembled row — the seat claim and the freeze in one56 /// Persist the assembled row — the seat claim and the freeze in one
53-/// conditional write (see [`homework_file::insert`]). `Ok(None)` is the57+/// guarded insert (see [`homework_file::insert`]). `Ok(None)` is the
54 /// freeze; the web layer keeps its own wording and unlinks the blob it wrote.58 /// freeze; the web layer keeps its own wording and unlinks the blob it wrote.
55 pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> {59 pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> {
56 homework_file::insert(db, file).await60 homework_file::insert(db, file).await
src/service/homework_result.rsmodified+7 -10
@@ -1,10 +1,9 @@
1 //! Homework grading workflows: the policy gates around the atomic grade —1 //! Homework grading workflows: the policy gates around the atomic grade —
2 //! nobody grades themselves, the target must be a live enrolled student in2 //! nobody grades themselves, the target must be a live enrolled student in
3 //! the homework's audience — and the un-grade. The freeze-stamping3 //! the homework's audience — and the un-grade. The freeze-stamping
4-//! transaction lives in [`crate::db::homework_result`]; grading holds4+//! transaction lives in [`crate::db::homework_result`]; it locks the
5-//! [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK)'s writer lease5+//! homework row across the stamp, which is what orders a grade against every
6-//! across its gates and the write, the reader side of every student write's6+//! student-side write — there is no subsystem lock here any more.
7-//! lease pair.
8 7
9 use crate::database::Database;8 use crate::database::Database;
10 use crate::db::homework;9 use crate::db::homework;
@@ -20,11 +19,11 @@ use crate::error::{AppError, ValidationError};
20 /// Record (or overwrite) `target`'s grade for the homework. The web layer19 /// Record (or overwrite) `target`'s grade for the homework. The web layer
21 /// has already read the homework, checked course-management rights, walled20 /// has already read the homework, checked course-management rights, walled
22 /// the archived term, and validated the status and mark; everything here is21 /// the archived term, and validated the status and mark; everything here is
23-/// re-run or decided under the writer lease:22+/// re-run or decided against the row the grade transaction locks:
24 ///23 ///
25-/// - the homework is re-read (a homework delete is a fellow writer — its24+/// - the homework is re-read (a homework delete is a fellow writer — both
26-/// lease excludes this one, so a grade cannot resurrect a result row under25+/// contend on the homework row's lock, so a grade cannot resurrect a
27-/// a vanished homework; the vanished row answers 404);26+/// result row under a vanished homework; the vanished row answers 404);
28 /// - grading never targets oneself — no grader, whatever their role, may27 /// - grading never targets oneself — no grader, whatever their role, may
29 /// write their own grade;28 /// write their own grade;
30 /// - the target user must exist, and only students carry homework grades —29 /// - the target user must exist, and only students carry homework grades —
@@ -40,7 +39,6 @@ pub async fn grade(
40 mark: Option<Mark>,39 mark: Option<Mark>,
41 target: &UserId,40 target: &UserId,
42 ) -> Result<HomeworkResult, AppError> {41 ) -> Result<HomeworkResult, AppError> {
43- let _guard = crate::service::homework::HOMEWORK_LOCK.write().await;
44 let homework = homework::read(db, id).await?.ok_or(AppError::NotFound)?;42 let homework = homework::read(db, id).await?.ok_or(AppError::NotFound)?;
45 43
46 // Grading never targets oneself.44 // Grading never targets oneself.
@@ -100,7 +98,6 @@ pub async fn ungrade(
100 id: &HomeworkId,98 id: &HomeworkId,
101 target: &UserId,99 target: &UserId,
102 ) -> Result<Option<HomeworkResult>, AppError> {100 ) -> Result<Option<HomeworkResult>, AppError> {
103- let _guard = crate::service::homework::HOMEWORK_LOCK.write().await;
104 homework_result::remove(db, id, target).await101 homework_result::remove(db, id, target).await
105 }102 }
106 103
src/service/homework_submission.rsmodified+18 -26
@@ -1,8 +1,9 @@
1-//! Homework submission workflows: the student's submit (the lease-to-write1+//! Homework submission workflows: the student's submit (the graded gate and
2-//! window that keeps a PATCH's audience re-scope from stranding a hand-in)2+//! the audience interlock around the guarded upsert) and the withdrawal that
3-//! and the withdrawal that gives the badge counters back. The row writes3+//! gives the badge counters back. The row writes live in
4-//! live in [`crate::db::homework_submission`]; every locked path here4+//! [`crate::db::homework_submission`]; the freeze itself is a condition of
5-//! leases [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK).5+//! those writes, and the homework row's lock is what orders them against
6+//! grading — there is no subsystem lock here any more.
6 7
7 use crate::database::Database;8 use crate::database::Database;
8 use crate::db::homework_file;9 use crate::db::homework_file;
@@ -23,29 +24,22 @@ pub struct Submitted {
23 }24 }
24 25
25 /// Submit (or re-submit) the caller's own work for a homework. The graded26 /// Submit (or re-submit) the caller's own work for a homework. The graded
26-/// gate and the audience interlock are the reader lease's — taken *before*27+/// read below answers the common case — graded minutes ago, and the student
27-/// the gate read: read first and the audience this gate approved is one28+/// who never submitted has no row to carry the freeze; the upsert's own
28-/// committed PATCH old, so the narrowing that just passed the orphan guard29+/// `graded_by_result IS NULL` condition is what holds when the grade lands
29-/// (no submission yet) is followed by the very submission it would have30+/// *while* this request runs (grade and write serialize on the homework
30-/// refused. Holding the lease across gate *and* write is what makes the31+/// row's lock).
31-/// PATCH wait and then see the row.
32 ///32 ///
33-/// `None` from [`homework_submission::upsert`] is a grade landing mid-request33+/// `None` from [`homework_submission::upsert`] is that freeze biting; both
34-/// (the stamp on the row refusing the write); the graded read above answers34+/// refusals return the same 409.
35-/// the common case, and both return the same 409.
36 pub async fn submit(35 pub async fn submit(
37 db: &Database,36 db: &Database,
38 user: &User,37 user: &User,
39 id: &str,38 id: &str,
40 text: Option<SubmissionText>,39 text: Option<SubmissionText>,
41 ) -> Result<Submitted, AppError> {40 ) -> Result<Submitted, AppError> {
42- let _guard = crate::service::homework::HOMEWORK_LOCK.read().await;
43 let homework = crate::service::homework::gate_own_submission(id, user, db).await?;41 let homework = crate::service::homework::gate_own_submission(id, user, db).await?;
44 crate::service::homework::require_open_term(&homework, db).await?;42 crate::service::homework::require_open_term(&homework, db).await?;
45- // The graded gate, twice over. This read answers the common case — graded
46- // minutes ago, and the student who never submitted has no row to carry the
47- // freeze; the upsert's own `WHERE` (the grade stamp on the row) is what
48- // holds when the grade lands *while* this request runs.
49 const GRADED: AppError = AppError::Conflict(43 const GRADED: AppError = AppError::Conflict(
50 "this homework has been graded — ask the teacher to remove the grade before editing your submission",44 "this homework has been graded — ask the teacher to remove the grade before editing your submission",
51 );45 );
@@ -55,12 +49,11 @@ pub async fn submit(
55 {49 {
56 return Err(GRADED);50 return Err(GRADED);
57 }51 }
58- // 201-vs-200: a prior read is exact, where comparing the returned stamps52+ // `existed` comes back from the transaction itself, so the 201-vs-200
59- // would misreport a same-millisecond re-submit as a create.53+ // answer and the badge rule are exact even against a rival first
60- let existed = homework_submission::read_for(db, homework.get_id(), user.get_id())54+ // hand-in.
61- .await?55+ let Some((submission, existed)) =
62- .is_some();56+ homework_submission::upsert(db, &homework, user.get_id(), text, false).await?
63- let Some(submission) = homework_submission::upsert(db, &homework, user.get_id(), text).await?
64 else {57 else {
65 return Err(GRADED);58 return Err(GRADED);
66 };59 };
@@ -85,7 +78,6 @@ pub async fn submit(
85 pub async fn delete(db: &Database, user: &User, id: &str) -> Result<Vec<HomeworkFile>, AppError> {78 pub async fn delete(db: &Database, user: &User, id: &str) -> Result<Vec<HomeworkFile>, AppError> {
86 let homework = crate::service::homework::gate_own_submission(id, user, db).await?;79 let homework = crate::service::homework::gate_own_submission(id, user, db).await?;
87 crate::service::homework::require_open_term(&homework, db).await?;80 crate::service::homework::require_open_term(&homework, db).await?;
88- let _guard = crate::service::homework::HOMEWORK_LOCK.read().await;
89 const GRADED: AppError = AppError::Conflict(81 const GRADED: AppError = AppError::Conflict(
90 "this homework has been graded — ask the teacher to remove the grade before deleting your submission",82 "this homework has been graded — ask the teacher to remove the grade before deleting your submission",
91 );83 );
src/service/meal_attendance.rsmodified+3 -4
@@ -1,9 +1,8 @@
1 //! The attendance-mark workflows: recording who ate off a menu and the two1 //! The attendance-mark workflows: recording who ate off a menu and the two
2 //! listings the kitchen and the student report read. The mark itself is a2 //! listings the kitchen and the student report read. The mark itself is a
3-//! single atomic UPSERT that rides the menu's revision bump3+//! single atomic upsert that rides the menu's revision bump inside its own
4-//! ([`crate::db::menu::bump_menu_and_write`]) — the queries live in4+//! transaction — the queries live in [`crate::db::meal_attendance`], the row
5-//! [`crate::db::meal_attendance`], the row shape in5+//! shape in [`crate::domain::meal_attendance`].
6-//! [`crate::domain::meal_attendance`].
7 6
8 use crate::database::Database;7 use crate::database::Database;
9 use crate::db::meal_attendance;8 use crate::db::meal_attendance;
src/service/meal_booking.rsmodified+5 -5
@@ -9,9 +9,10 @@
9 //!9 //!
10 //! **No process-wide lock guards this domain**, and deliberately: every10 //! **No process-wide lock guards this domain**, and deliberately: every
11 //! invariant booking depends on is a *single-record* conditional write (the11 //! invariant booking depends on is a *single-record* conditional write (the
12-//! menu's `seats_booked` counter and the attempt-fenced row flip), which12+//! menu's `seats_booked` counter and the attempt-fenced row flip), which the
13-//! SurrealDB itself serializes — a cross-record lock would add contention13+//! guarded writes themselves serialize — a cross-record lock would add
14-//! without deciding anything the transactions do not already. What the14+//! contention without deciding anything the transactions do not already.
15+//! What the
15 //! service layer owns here is the *sequence*: read the menu, refuse a past16 //! service layer owns here is the *sequence*: read the menu, refuse a past
16 //! day or a closed cutoff before anything is claimed, settle the attempt17 //! day or a closed cutoff before anything is claimed, settle the attempt
17 //! number before the charge id exists, and map the claim's outcomes18 //! number before the charge id exists, and map the claim's outcomes
@@ -62,7 +63,6 @@ pub async fn book(
62 cutoff: &MealCutoff,63 cutoff: &MealCutoff,
63 ) -> Result<MealBooking, AppError> {64 ) -> Result<MealBooking, AppError> {
64 let id = MealBookingId::composite(menu, student);65 let id = MealBookingId::composite(menu, student);
65- let seats = menu.record();
66 for attempt in 0..CAP_WRITE_TRIES {66 for attempt in 0..CAP_WRITE_TRIES {
67 backoff(attempt).await;67 backoff(attempt).await;
68 let fresh = menu::read(db, menu).await?.ok_or(AppError::NotFound)?;68 let fresh = menu::read(db, menu).await?.ok_or(AppError::NotFound)?;
@@ -135,7 +135,7 @@ pub async fn book(
135 let charge = MealLedger::charge_for(&fresh_row, booked_by);135 let charge = MealLedger::charge_for(&fresh_row, booked_by);
136 match meal_booking::claim_and_place(136 match meal_booking::claim_and_place(
137 db,137 db,
138- &seats,138+ menu,
139 fresh.get_capacity().unwrap_or(cap::UNLIMITED),139 fresh.get_capacity().unwrap_or(cap::UNLIMITED),
140 fresh.get_version(),140 fresh.get_version(),
141 &fresh_row,141 &fresh_row,
src/service/meal_ledger.rsmodified+1 -1
@@ -77,7 +77,7 @@ pub async fn reverse_booking(
77 /// resending the identical body after a timeout gets back the line the77 /// resending the identical body after a timeout gets back the line the
78 /// first attempt wrote, not a second credit — nothing on this API can edit78 /// first attempt wrote, not a second credit — nothing on this API can edit
79 /// or delete one, so a doubled credit is corrected only by a compensating79 /// 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 two80+/// line. Without one the id is a fresh uuid and two identical calls are two
81 /// credits, which is what a desk taking the same amount twice really means.81 /// credits, which is what a desk taking the same amount twice really means.
82 pub async fn credit(82 pub async fn credit(
83 db: &Database,83 db: &Database,
src/service/menu.rsmodified+31 -57
@@ -1,24 +1,16 @@
1 //! The kitchen's workflows: publishing and unpublishing menus, and every1 //! The kitchen's workflows: publishing and unpublishing menus, and every
2-//! dish write — which all hold [`MENU_LOCK`], the lock that makes the2+//! dish write. The queries live in [`crate::db::menu`] and
3-//! per-menu dish cap (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB3+//! [`crate::db::menu_dish`]; the row shapes and the date/slot/capacity
4-//! does not conflict-check) more than a wish. The queries live in4+//! rules in [`crate::domain::menu`] and [`crate::domain::menu_dish`].
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`].
8 //!5 //!
9-//! [`MENU_LOCK`] spans a **multi-call** sequence (read the menu, count the6+//! **No process-wide lock guards this domain.** The dish cap
10-//! dishes, write the dish), which is why it lives here and not in the db7+//! (`MAX_DISHES_PER_MENU`) used to be a count-then-write pair only a
11-//! layer: a single-call atomicity lock would be the store's to own, but8+//! process mutex could make safe; it is now one guarded statement — the
12-//! count-then-write is write-skew only this process can serialize.9+//! menu row is taken `FOR NO KEY UPDATE` inside the dish write's own
13-//!10+//! transaction and the `INSERT … WHERE count(*) < cap` runs behind that
14-//! **A leaf**: every dish write held under it moves the menu's revision11+//! lock, so two racing writers serialize on the row the database owns.
15-//! inside its *own* transaction ([`crate::db::menu::bump_menu_and_write`]),12+//! Every dish write moves the menu's revision in that same transaction, and
16-//! so no path under this lock reaches `cap`'s counter lock any more. Should13+//! a booking claims its seat at the revision it priced itself against.
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;
22 14
23 use crate::constant::MAX_DISHES_PER_MENU;15 use crate::constant::MAX_DISHES_PER_MENU;
24 use crate::database::Database;16 use crate::database::Database;
@@ -30,20 +22,6 @@ use crate::domain::menu_dish::{
30 use crate::domain::user::UserId;22 use crate::domain::user::UserId;
31 use crate::error::AppError;23 use crate::error::AppError;
32 24
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-
47 /// Publish a menu for one day and meal slot. The caller has validated the25 /// Publish a menu for one day and meal slot. The caller has validated the
48 /// date (a real calendar day, not already over), the slot (one the school26 /// date (a real calendar day, not already over), the slot (one the school
49 /// serves) and the capacity; the day+slot duplicate refusal is decided by27 /// 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> {
92 70
93 /// Add a dish to a menu, under the dish cap.71 /// Add a dish to a menu, under the dish cap.
94 ///72 ///
95-/// [`MENU_LOCK`] is taken for the dish cap alone: count-then-write73+/// The cap is the database's to enforce, not this process's: the write
96-/// is write-skew, so the count and the insert have to be one step. The74+/// locks the menu row `FOR NO KEY UPDATE` and its `INSERT` carries a
97-/// *price* no longer needs it — a dish write moves the menu's revision, and75+/// `count(*) < cap` guard, so a writer that queued behind a concurrent one
98-/// a booking claims its seat at the revision it priced itself against.76+/// re-counts after the lock and is refused (`409`) instead of overfilling
99-/// The lock is a leaf again: the revision bump rides the dish write's own77+/// — the count and the insert are one decision, with no window a second
100-/// transaction now, so nothing held under it takes `cap`'s counter lock. It78+/// writer can slip through.
101-/// stays a leaf only while that holds — see [`MENU_LOCK`] for the order a
102-/// caller that changes it must keep.
103 ///79 ///
104-/// The menu is read *inside* the lock: read before it, a `DELETE /menus/{id}`80+/// The *price* needs no lock — a dish write moves the menu's revision, and
105-/// running in the gap takes its cascade with it and this dish lands on a menu81+/// a booking claims its seat at the revision it priced itself against.
106-/// that no longer exists.
107 pub async fn add_dish(82 pub async fn add_dish(
108 db: &Database,83 db: &Database,
109 menu_id: &MenuId,84 menu_id: &MenuId,
@@ -112,14 +87,16 @@ pub async fn add_dish(
112 price_minor: DishPrice,87 price_minor: DishPrice,
113 tags: DishTags,88 tags: DishTags,
114 ) -> Result<MenuDish, AppError> {89 ) -> Result<MenuDish, AppError> {
115- let _guard = MENU_LOCK.lock().await;90+ menu_dish::create(
116- let menu = menu::read(db, menu_id).await?.ok_or(AppError::NotFound)?;91+ db,
117- if menu_dish::count_for_menu(db, menu.get_id()).await? >= MAX_DISHES_PER_MENU {92+ menu_id,
118- return Err(AppError::Conflict(93+ name,
119- "the menu already carries the maximum number of dishes",94+ description,
120- ));95+ price_minor,
121- }96+ tags,
122- menu_dish::create(db, menu.get_id(), name, description, price_minor, tags).await97+ MAX_DISHES_PER_MENU as i64,
98+ )
99+ .await
123 }100 }
124 101
125 /// One dish, for callers that only inspect it.102 /// One dish, for callers that only inspect it.
@@ -140,8 +117,7 @@ pub async fn list_dishes_for_menus(
140 menu_dish::list_for_menus(db, menus).await117 menu_dish::list_for_menus(db, menus).await
141 }118 }
142 119
143-/// Edit a dish. Under [`MENU_LOCK`] like every dish write — see120+/// Edit a dish. Only what the request carried is written.
144-/// [`add_dish`]. Only what the request carried is written.
145 pub async fn update_dish(121 pub async fn update_dish(
146 db: &Database,122 db: &Database,
147 dish: MenuDish,123 dish: MenuDish,
@@ -150,12 +126,10 @@ pub async fn update_dish(
150 price_minor: Option<DishPrice>,126 price_minor: Option<DishPrice>,
151 tags: Option<DishTags>,127 tags: Option<DishTags>,
152 ) -> Result<MenuDish, AppError> {128 ) -> Result<MenuDish, AppError> {
153- let _guard = MENU_LOCK.lock().await;
154 menu_dish::update(db, dish, name, description, price_minor, tags).await129 menu_dish::update(db, dish, name, description, price_minor, tags).await
155 }130 }
156 131
157-/// Remove a dish from its menu. Under [`MENU_LOCK`] like every dish write.132+/// Remove a dish from its menu.
158 pub async fn delete_dish(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> {133 pub async fn delete_dish(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> {
159- let _guard = MENU_LOCK.lock().await;
160 menu_dish::delete(db, dish).await134 menu_dish::delete(db, dish).await
161 }135 }
src/web/boards.rsmodified+12 -14
@@ -37,7 +37,6 @@ use crate::domain::event::EventId;
37 use crate::domain::role::Role;37 use crate::domain::role::Role;
38 use crate::domain::user::{User, UserId};38 use crate::domain::user::{User, UserId};
39 use crate::error::{AppError, ErrorResponse, ValidationError};39 use crate::error::{AppError, ErrorResponse, ValidationError};
40-use crate::service::board::BOARD_ROSTER_LOCK;
41 use crate::service::{board, board_stroke};40 use crate::service::{board, board_stroke};
42 use crate::state::AppState;41 use crate::state::AppState;
43 use crate::tenant::Slug;42 use crate::tenant::Slug;
@@ -444,14 +443,12 @@ async fn update_board(
444 Path(id): Path<String>,443 Path(id): Path<String>,
445 Json(req): Json<UpdateBoard>,444 Json(req): Json<UpdateBoard>,
446 ) -> Result<Json<BoardResponse>, AppError> {445 ) -> Result<Json<BoardResponse>, AppError> {
447- // A roster PATCH reads the current list (to keep the ids that stopped446+ // A roster PATCH resolves against the roster as this request read it
448- // qualifying) before replacing it, so it is the other read-modify-write of447+ // (to keep the ids that stopped qualifying) and replaces it with one
449- // this field and takes the same lock — one an invite could otherwise land448+ // field-scoped write: the request carries the whole intended roster, so
450- // inside. Title- and lock-only edits never touch the array and are not held.449+ // it is a creator-driven replace, not a merge — an invite committing
451- let _guard = match req.participants.is_some() {450+ // between the read and this write is superseded by the PATCH, which is
452- true => Some(BOARD_ROSTER_LOCK.lock().await),451+ // the route's contract.
453- false => None,
454- };
455 let mut board = board::board_for(&id, &user, &st.db).await?;452 let mut board = board::board_for(&id, &user, &st.db).await?;
456 if req.participants.is_some() || req.locked.is_some() {453 if req.participants.is_some() || req.locked.is_some() {
457 board::ensure_creator(&board, &user)?;454 board::ensure_creator(&board, &user)?;
@@ -732,11 +729,12 @@ async fn invite_board(
732 Path(id): Path<String>,729 Path(id): Path<String>,
733 Json(req): Json<InviteSource>,730 Json(req): Json<InviteSource>,
734 ) -> Result<Json<BoardResponse>, AppError> {731 ) -> Result<Json<BoardResponse>, AppError> {
735- // Held across the read *and* the write: this is a read-modify-write of one732+ // The merge is one atomic guarded statement (see
736- // array, so two invites landing together would each union their group into733+ // `crate::db::board::invite_group`): two invites landing together both
737- // the same roster and the second write would drop the first one's people —734+ // union into the
738- // silently, with both callers told 200. See [`BOARD_ROSTER_LOCK`].735+ // roster the row holds at write time, so neither can drop the other's
739- let _guard = BOARD_ROSTER_LOCK.lock().await;736+ // people — the property the old process-wide roster lock provided, now
737+ // enforced by the row itself.
740 let board = board::board_for(&id, &user, &st.db).await?;738 let board = board::board_for(&id, &user, &st.db).await?;
741 board::ensure_creator(&board, &user)?;739 board::ensure_creator(&board, &user)?;
742 let invited = req.resolve(&user, &st.db).await?;740 let invited = req.resolve(&user, &st.db).await?;
src/web/courses.rsmodified+2 -2
@@ -545,8 +545,8 @@ async fn delete_course(
545 "only the course creator or a manager/admin can delete this course",545 "only the course creator or a manager/admin can delete this course",
546 ));546 ));
547 }547 }
548- // The workflow — archived-term gate, EXAM_LOCK and HOMEWORK_LOCK writer548+ // The workflow — archived-term gate, blob-key collection, cascade — is
549- // leases, blob-key collection, cascade — is [`service::course::delete`]'s.549+ // [`service::course::delete`]'s.
550 // Blob unlinking stays here because only the web layer knows `files_path`.550 // Blob unlinking stays here because only the web layer knows `files_path`.
551 let outcome = service::course::delete(&st.db, &course).await?;551 let outcome = service::course::delete(&st.db, &course).await?;
552 if !outcome.deleted {552 if !outcome.deleted {
src/web/homework.rsmodified+52 -50
@@ -4,8 +4,9 @@
4 //! and the per-course listing live under `/courses/{id}/homework` (see4 //! and the per-course listing live under `/courses/{id}/homework` (see
5 //! [`super::courses`]); everything shares the visibility rule5 //! [`super::courses`]); everything shares the visibility rule
6 //! ([`Homework::student_sees`](crate::domain::homework::Homework::student_sees))6 //! ([`Homework::student_sees`](crate::domain::homework::Homework::student_sees))
7-//! and the [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK), whose7+//! The freeze and the audience interlock are conditions of the writes
8-//! leases the workflows take in [`crate::service::homework`] and its siblings.8+//! themselves ([`crate::db::homework_submission`]), serialized on the
9+//! homework row's lock inside each transaction.
9 10
10 use crate::web::tenant_state::State;11 use crate::web::tenant_state::State;
11 use axum::Json;12 use axum::Json;
@@ -26,9 +27,7 @@ use crate::domain::exam_result::Mark;
26 use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};27 use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};
27 use crate::domain::homework_file::{HomeworkFile, HomeworkFileId};28 use crate::domain::homework_file::{HomeworkFile, HomeworkFileId};
28 use crate::domain::homework_result::{HomeworkResult, HomeworkStatus};29 use crate::domain::homework_result::{HomeworkResult, HomeworkStatus};
29-use crate::domain::homework_submission::{30+use crate::domain::homework_submission::{HomeworkSubmission, SubmissionText};
30- HomeworkSubmission, HomeworkSubmissionId, SubmissionText,
31-};
32 use crate::domain::note_file::{FileContentType, FileName};31 use crate::domain::note_file::{FileContentType, FileName};
33 use crate::domain::role::Role;32 use crate::domain::role::Role;
34 use crate::domain::timestamp::Timestamp;33 use crate::domain::timestamp::Timestamp;
@@ -310,11 +309,11 @@ async fn update_homework(
310 }309 }
311 crate::service::course::require_open(&st.db, &course).await?;310 crate::service::course::require_open(&st.db, &course).await?;
312 311
313- // The writer lease of [`HOMEWORK_LOCK`], the orphan guard, and the write312+ // The orphan guard and the write are one unit in
314- // are one unit in [`service::homework::update`]: the guard reads the live313+ // [`service::homework::update`]: the guard reads the live submissions and
315- // submissions and results, and the row write depends on what it saw —314+ // results inside the write's transaction, under the homework row's lock —
316- // without the lease a submission (a reader) could land between the check315+ // a submission (which locks the same row before writing) cannot land
317- // and the write, orphaned by the narrowing that just missed it.316+ // between the check and the narrowing that just missed it.
318 317
319 // Only what the request carried: an omitted field stays `None` and is never318 // Only what the request carried: an omitted field stays `None` and is never
320 // written, so a concurrent PATCH of another field survives. The two319 // written, so a concurrent PATCH of another field survives. The two
@@ -333,7 +332,9 @@ async fn update_homework(
333 // A kept (absent) due date may already be past; a newly set one may not be.332 // A kept (absent) due date may already be past; a newly set one may not be.
334 check_not_past("due_at", due_at)?;333 check_not_past("due_at", due_at)?;
335 let subject = match &req.subject_id {334 let subject = match &req.subject_id {
336- Some(subject_id) => Some(crate::service::subject::in_course(&st.db, subject_id, course.get_id()).await?),335+ Some(subject_id) => {
336+ Some(crate::service::subject::in_course(&st.db, subject_id, course.get_id()).await?)
337+ }
337 None => None,338 None => None,
338 };339 };
339 // The orphan guard runs on exactly the requests that re-scope the audience.340 // The orphan guard runs on exactly the requests that re-scope the audience.
@@ -360,11 +361,11 @@ async fn update_homework(
360 361
361 /// Delete a homework and everything under it — submissions, their files, and362 /// Delete a homework and everything under it — submissions, their files, and
362 /// results — then unlink the file blobs from disk. Requires teacher+ and363 /// results — then unlink the file blobs from disk. Requires teacher+ and
363-/// management rights over its course. Held under [`HOMEWORK_LOCK`]'s write lease364+/// management rights over its course. The cascade is one transaction whose
364-/// so no submission can land under the homework mid-delete; the blob names are365+/// homework-row lock keeps a submission from landing under the homework
365-/// collected before the rows are wiped (the cascade is one transaction, children366+/// mid-delete; the blob names are collected inside that transaction, before
366-/// first) and removed after, so a crash in between strands at worst an367+/// the rows are wiped, and removed after, so a crash in between strands at
367-/// unreachable file.368+/// worst an unreachable file.
368 #[utoipa::path(369 #[utoipa::path(
369 delete,370 delete,
370 path = "/{id}",371 path = "/{id}",
@@ -391,7 +392,7 @@ async fn delete_homework(
391 ));392 ));
392 }393 }
393 crate::service::course::require_open(&st.db, &course).await?;394 crate::service::course::require_open(&st.db, &course).await?;
394- // The writer lease, the blob-key collection, and the cascade are395+ // The blob-key collection and the cascade are
395 // [`service::homework::delete`]'s; unlinking the blobs stays here because396 // [`service::homework::delete`]'s; unlinking the blobs stays here because
396 // only the web layer knows `files_path`.397 // only the web layer knows `files_path`.
397 let blob_keys = service::homework::delete(&st.db, homework).await?;398 let blob_keys = service::homework::delete(&st.db, homework).await?;
@@ -548,10 +549,9 @@ async fn submit(
548 Some(text) if !text.is_empty() => Some(SubmissionText::try_new(text)?),549 Some(text) if !text.is_empty() => Some(SubmissionText::try_new(text)?),
549 _ => None,550 _ => None,
550 };551 };
551- // The reader lease of [`HOMEWORK_LOCK`], the gate, the term wall, the552+ // The gate, the term wall, the graded check, and the upsert are one
552- // graded check, and the upsert are one unit in553+ // unit in [`service::homework_submission::submit`] — the audience
553- // [`service::homework_submission::submit`] — the audience interlock, not554+ // interlock, not the freeze (that is the stamp on the row).
554- // the freeze (that is the stamp on the row).
555 let landed = service::homework_submission::submit(&st.db, &user, &id, text).await?;555 let landed = service::homework_submission::submit(&st.db, &user, &id, text).await?;
556 let files =556 let files =
557 service::homework_file::list_for_submission(&st.db, landed.submission.get_id()).await?;557 service::homework_file::list_for_submission(&st.db, landed.submission.get_id()).await?;
@@ -721,19 +721,15 @@ async fn upload_submission_file(
721 const GRADED: AppError = AppError::Conflict(721 const GRADED: AppError = AppError::Conflict(
722 "this homework has been graded — ask the teacher to remove the grade before adding files",722 "this homework has been graded — ask the teacher to remove the grade before adding files",
723 );723 );
724- // Reader lease as in `submit` — the audience interlock, not the freeze.724+ // Re-read the homework. Streaming the body takes as long as the client
725- // Taken before the cap claim inside the insert, never after (the lock725+ // wants it to, and a homework delete can commit inside that window — so
726- // order is HOMEWORK_LOCK, then the counter lock). The lock lives in726+ // the pre-flight snapshot can name a homework that no longer exists, and
727- // [`service::homework`]; the blob write stays here, inside the lease,727+ // this handler would then auto-create a submission, credit the badge
728- // because the row's "stored row points at a real blob" ordering does.728+ // counters and write a file under it, all unreachable afterwards. A gate
729- let _guard = service::homework::HOMEWORK_LOCK.read().await;729+ // read before the body is a pre-flight; a gate read after it is the
730- // Re-read the homework *under* the lease. Streaming the body takes as long730+ // decision. The writes below are still ordered against a delete, a grade
731- // as the client wants it to, and a homework delete (a writer) both takes731+ // and a PATCH narrowing the audience — each contends on the homework
732- // and releases its lease inside that window — so the pre-flight snapshot732+ // row's lock inside its own transaction.
733- // can name a homework that no longer exists, and this handler would then
734- // auto-create a submission, credit the badge counters and write a file
735- // under it, all unreachable afterwards. A gate read before the body is a
736- // pre-flight; a gate read after it is the decision.
737 let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?;733 let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?;
738 // Re-walled too: the term can be archived while the body streams.734 // Re-walled too: the term can be archived while the body streams.
739 service::homework::require_open_term(&homework, &st.db).await?;735 service::homework::require_open_term(&homework, &st.db).await?;
@@ -801,8 +797,11 @@ async fn download_submission_file(
801 let file = if user.get_role() == Role::Student {797 let file = if user.get_role() == Role::Student {
802 // Student: only their own file, behind the full submission gate.798 // Student: only their own file, behind the full submission gate.
803 let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?;799 let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?;
804- let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id());800+ let submission =
805- service::homework_file::read_for(&st.db, &file_id, &submission)801+ service::homework_submission::read_for(&st.db, homework.get_id(), user.get_id())
802+ .await?
803+ .ok_or(AppError::NotFound)?;
804+ service::homework_file::read_for(&st.db, &file_id, submission.get_id())
806 .await?805 .await?
807 .ok_or(AppError::NotFound)?806 .ok_or(AppError::NotFound)?
808 } else {807 } else {
@@ -850,19 +849,23 @@ async fn delete_submission_file(
850 const GRADED: AppError = AppError::Conflict(849 const GRADED: AppError = AppError::Conflict(
851 "this homework has been graded — ask the teacher to remove the grade before deleting files",850 "this homework has been graded — ask the teacher to remove the grade before deleting files",
852 );851 );
853- // Reader lease as in `submit` — the audience interlock, not the freeze.
854- let _guard = service::homework::HOMEWORK_LOCK.read().await;
855 if service::homework_result::read_for(&st.db, homework.get_id(), user.get_id())852 if service::homework_result::read_for(&st.db, homework.get_id(), user.get_id())
856 .await?853 .await?
857 .is_some()854 .is_some()
858 {855 {
859 return Err(GRADED);856 return Err(GRADED);
860 }857 }
861- let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id());858+ let submission =
862- let file =859+ service::homework_submission::read_for(&st.db, homework.get_id(), user.get_id())
863- service::homework_file::read_for(&st.db, &HomeworkFileId::from_key(&fid), &submission)
864 .await?860 .await?
865 .ok_or(AppError::NotFound)?;861 .ok_or(AppError::NotFound)?;
862+ let file = service::homework_file::read_for(
863+ &st.db,
864+ &HomeworkFileId::from_key(&fid),
865+ submission.get_id(),
866+ )
867+ .await?
868+ .ok_or(AppError::NotFound)?;
866 let blob = file.get_file().to_string();869 let blob = file.get_file().to_string();
867 // The delete's own transaction re-stamps the submission's "last touched"870 // The delete's own transaction re-stamps the submission's "last touched"
868 // clock (the late flag) as its freeze gate, so a refused delete moves871 // clock (the late flag) as its freeze gate, so a refused delete moves
@@ -923,12 +926,11 @@ async fn grade_homework(
923 Path(id): Path<String>,926 Path(id): Path<String>,
924 Json(req): Json<GradeHomework>,927 Json(req): Json<GradeHomework>,
925 ) -> Result<Json<HomeworkResultResponse>, AppError> {928 ) -> Result<Json<HomeworkResultResponse>, AppError> {
926- // The grading gates and the writer lease of [`HOMEWORK_LOCK`] live in929+ // The grading gates live in [`service::homework_result::grade`]; the
927- // [`service::homework_result::grade`]: a grade is what freezes a930+ // grade transaction locks the homework row across the freeze stamp, which
928- // submission, so it must not interleave with the read side's931+ // orders it against every student-side write — and keeps a homework
929- // gate-through-write submission edits — and the homework is re-read under932+ // delete from letting the upsert resurrect a result row under a vanished
930- // the lease there, which keeps a homework delete (a fellow writer) from933+ // homework (the vanished row answers 404).
931- // letting the upsert resurrect a result row under a vanished homework.
932 let (homework, course) = homework_with_course(&id, &st.db).await?;934 let (homework, course) = homework_with_course(&id, &st.db).await?;
933 if !can_manage_course(&course, &teacher) {935 if !can_manage_course(&course, &teacher) {
934 return Err(AppError::Forbidden(936 return Err(AppError::Forbidden(
@@ -974,9 +976,9 @@ async fn remove_homework_result(
974 RequireTeacher(user): RequireTeacher,976 RequireTeacher(user): RequireTeacher,
975 Path((id, target)): Path<(String, String)>,977 Path((id, target)): Path<(String, String)>,
976 ) -> Result<StatusCode, AppError> {978 ) -> Result<StatusCode, AppError> {
977- // The writer lease of [`HOMEWORK_LOCK`] is [`service::homework_result::ungrade`]'s979+ // Removing the grade is what unfreezes the submission; the un-grade's
978- // — removing the grade is what unfreezes the submission, so it must not980+ // transaction takes the homework row's lock, so it cannot straddle a
979- // straddle the read side's gate-through-write edits either.981+ // student-side write either.
980 let (homework, course) = homework_with_course(&id, &st.db).await?;982 let (homework, course) = homework_with_course(&id, &st.db).await?;
981 if !can_manage_course(&course, &user) {983 if !can_manage_course(&course, &user) {
982 return Err(AppError::Forbidden(984 return Err(AppError::Forbidden(
src/web/meals.rsmodified+9 -9
@@ -438,11 +438,11 @@ async fn add_dish(
438 &req.tags,438 &req.tags,
439 &service::settings::load(&st.db).await?.get_dietary_tags(),439 &service::settings::load(&st.db).await?.get_dietary_tags(),
440 )?;440 )?;
441- // The dish-cap gate and its [`MENU_LOCK`](crate::service::menu::MENU_LOCK)441+ // The dish-cap gate lives in the service: the cap is one guarded
442- // lease live in the service: count-then-write is write-skew, so the count442+ // statement now — the menu row is locked `FOR NO KEY UPDATE` inside the
443- // and the insert have to be one step, and the menu is read *inside* the443+ // dish write's own transaction and the insert carries the
444- // lock — read before it, a `DELETE /menus/{id}` running in the gap takes444+ // `count(*) < cap` guard, so a dish can never land on a menu that no
445- // its cascade with it and this dish lands on a menu that no longer exists.445+ // longer exists, and two racing writers cannot overfill it either.
446 let dish = service::menu::add_dish(446 let dish = service::menu::add_dish(
447 &st.db,447 &st.db,
448 &MenuId::from_key(&id),448 &MenuId::from_key(&id),
@@ -502,8 +502,8 @@ async fn update_dish(
502 )?),502 )?),
503 None => None,503 None => None,
504 };504 };
505- // The dish write holds [`MENU_LOCK`](crate::service::menu::MENU_LOCK)505+ // The dish write locks the menu row inside its own transaction — see
506- // inside the service, like every dish write — see `add_dish`.506+ // `add_dish`.
507 let updated = service::menu::update_dish(&st.db, dish, name, description, price, tags).await?;507 let updated = service::menu::update_dish(&st.db, dish, name, description, price, tags).await?;
508 let viewer_tags = service::dietary_profile::tags_of(&st.db, user.get_id()).await?;508 let viewer_tags = service::dietary_profile::tags_of(&st.db, user.get_id()).await?;
509 Ok(Json(DishResponse::new(&updated, &viewer_tags)))509 Ok(Json(DishResponse::new(&updated, &viewer_tags)))
@@ -531,8 +531,8 @@ async fn delete_dish(
531 let dish = service::menu::read_dish(&st.db, &MenuDishId::from_key(&did))531 let dish = service::menu::read_dish(&st.db, &MenuDishId::from_key(&did))
532 .await?532 .await?
533 .ok_or(AppError::NotFound)?;533 .ok_or(AppError::NotFound)?;
534- // The dish write holds [`MENU_LOCK`](crate::service::menu::MENU_LOCK)534+ // The dish write locks the menu row inside its own transaction — see
535- // inside the service, like every dish write — see `add_dish`.535+ // `add_dish`.
536 service::menu::delete_dish(&st.db, dish).await?;536 service::menu::delete_dish(&st.db, dish).await?;
537 Ok(StatusCode::NO_CONTENT)537 Ok(StatusCode::NO_CONTENT)
538 }538 }
src/web/questions.rsmodified+2 -2
@@ -482,7 +482,7 @@ async fn upload_image(
482 let upload = read_image_upload(&st, &mut multipart).await?;482 let upload = read_image_upload(&st, &mut multipart).await?;
483 let size = upload.size();483 let size = upload.size();
484 484
485- let file = ulid::Ulid::generate().to_string();485+ let file = crate::domain::monotonic_id::next_uuid().to_string();
486 store_blob(&st, &file, &upload.data, || async {486 store_blob(&st, &file, &upload.data, || async {
487 match pool_question::set_image(&st.db, question.get_id(), &file, &upload.content_type, size)487 match pool_question::set_image(&st.db, question.get_id(), &file, &upload.content_type, size)
488 .await?488 .await?
@@ -808,7 +808,7 @@ async fn upload_solution_image(
808 let upload = read_image_upload(&st, &mut multipart).await?;808 let upload = read_image_upload(&st, &mut multipart).await?;
809 let size = upload.size();809 let size = upload.size();
810 810
811- let file = ulid::Ulid::generate().to_string();811+ let file = crate::domain::monotonic_id::next_uuid().to_string();
812 store_blob(&st, &file, &upload.data, || async {812 store_blob(&st, &file, &upload.data, || async {
813 match solution::set_image(&st.db, solution.get_id(), &file, &upload.content_type, size)813 match solution::set_image(&st.db, solution.get_id(), &file, &upload.content_type, size)
814 .await?814 .await?