forge
Explore
Log in

Don't you dare go Hollow

Port classes (group/member/course/blueprint/pump) to sqlx/Postgres

Browse files at this commit

dec7a2ac05f35e5140251d7da5045b2825e0563fAhmet Kaan GümüşParent: b3ab76f
  • feat
    • port classes (group/member/course/blueprint/pump) to sqlx/Postgres
Show full message
🗃️ feat!: port classes (group/member/course/blueprint/pump) to sqlx/Postgres

11 changed files +1162 -1011

src/db/class_blueprint.rsmodified+170 -182
@@ -1,14 +1,14 @@
1 //! The `class_blueprint` table: the row keyed by its grade label, the1 //! The `class_blueprint` table: the row keyed by its grade label, the
2 //! compare-and-set writes the edit and the delete go through, and the reads2 //! compare-and-set writes the edit and the delete go through, and the reads
3 //! the sweep and the status screen are built on. The workflows that sequence3 //! the sweep and the status screen are built on. The workflows that sequence
4-//! these under [`crate::service::class_blueprint::BLUEPRINT_LOCK`] live in4+//! these — and the row lock that serializes a delete against the attaches
5-//! [`crate::service::class_blueprint`].5+//! made on the blueprint's behalf — live in [`crate::service::class_blueprint`].
6 6
7-use surrealdb::types::{RecordId, SurrealValue};7+use sqlx::postgres::PgConnection;
8 8
9-use crate::constant::{CLASS_BLUEPRINT_TABLE, CLASS_COURSE_TABLE, ENROLLMENT_COUNT_FIELD};9+use crate::constant::CLASS_BLUEPRINT_TABLE;
10-use crate::database::{Database, transaction_with_retry};10+use crate::database::{Database, tx_with_retry, unique_violation};
11-use crate::db::class_pump::{Axis, detach};11+use crate::db::class_pump;
12 use crate::db::page::PagedList;12 use crate::db::page::PagedList;
13 use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId};13 use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId};
14 use crate::domain::class_group::{ClassGrade, ClassGroupId};14 use crate::domain::class_group::{ClassGrade, ClassGroupId};
@@ -16,50 +16,49 @@ use crate::domain::course::CourseId;
16 use crate::domain::user::UserId;16 use crate::domain::user::UserId;
17 use crate::error::{AppError, ValidationError};17 use crate::error::{AppError, ValidationError};
18 18
19-/// The `THROW` marker a template write aborts with when one of the courses it
20-/// names is gone — the same answer the caller's own pre-flight read gives, made
21-/// inside the transaction that stores the list.
22-const DEAD_MARK: &str = "blueprint_no_course";
23-
24 /// One `class_course` row, projected down to the pair that answers "does this19 /// One `class_course` row, projected down to the pair that answers "does this
25 /// section carry that course". `source` is deliberately not read: a link of any20 /// section carry that course". `source` is deliberately not read: a link of any
26-/// provenance satisfies the template.21+#[derive(Debug, sqlx::FromRow)]
27-#[derive(SurrealValue)]
28 pub struct Held {22 pub struct Held {
29 pub(crate) class: ClassGroupId,23 pub(crate) class: ClassGroupId,
30 pub(crate) course: CourseId,24 pub(crate) course: CourseId,
31 }25 }
32 26
33-/// The statements that prove every course a template is about to name is27+/// Prove every course a template is about to name is still there, *inside* the
34-/// still there, *inside* the transaction that stores the list.28+/// transaction that stores the list.
35 ///29 ///
36 /// The caller's own pre-flight read is not that proof: it is a read of30 /// The caller's own pre-flight read is not that proof: it is a read of
37-/// `course` in a request that then writes `class_blueprint`, and SurrealDB31+/// `course` in a request that then writes `class_blueprint`, and two
38-/// does not conflict-check reads (write skew). `DELETE /courses/{id}` sweeps32+/// transactions that read and write crossed records interleave freely under
39-/// every template naming the course as part of its cascade, so a delete33+/// READ COMMITTED. `DELETE /courses/{id}` sweeps every template naming the
40-/// landing between the read and the write sweeps a row that is not there yet34+/// course as part of its cascade, so a delete landing between the read and the
41-/// and the list keeps an id nothing points at. [`prune`] only fires35+/// write sweeps a row that is not there yet and the list keeps an id nothing
42-/// while walking a section, so at a grade carrying none the id is permanent.36+/// points at. A `FOR KEY SHARE` row lock per course is the proof: it is the
37+/// weakest strength a course `DELETE` cannot take, so the delete waits behind
38+/// this transaction and finds the list that names the course already stored —
39+/// and sweeps it.
43 ///40 ///
44-/// The claim is [`crate::db::class_pump::Axis::pivot_claim`]'s exactly:41+/// One lock per course, the list being at most `MAX_CLASS_COURSES` long —
45-/// the counter is *moved* — bumped, gated, restored to the value this42+/// the same pass-per-course the old in-transaction loop made.
46-/// transaction found, `NONE` included — because an `UPDATE` leaving the43+async fn courses_alive(tx: &mut PgConnection, courses: &[CourseId]) -> Result<(), AppError> {
47-/// document unchanged is elided by 3.2.3 and enters no write set. Moving it44+ for course in courses {
48-/// puts this write on the record the course's delete guard writes.45+ let alive = sqlx::query_scalar!(
49-fn courses_alive() -> String {46+ r#"SELECT 1 AS "one" FROM course WHERE id = $1 FOR KEY SHARE"#,
50- format!(47+ course as _
51- "FOR $course IN ($courses ?? []) {{48+ )
52- LET $was = (SELECT VALUE {ENROLLMENT_COUNT_FIELD} FROM ONLY $course);49+ .fetch_optional(&mut *tx)
53- LET $alive = (UPDATE $course SET {ENROLLMENT_COUNT_FIELD} = \50+ .await?
54- ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id);51+ .is_some();
55- IF array::len($alive) = 0 {{ THROW '{DEAD_MARK}' }};52+ if !alive {
56- UPDATE $course SET {ENROLLMENT_COUNT_FIELD} = $was;53+ return Err(no_such_course());
57- }}"54+ }
58- )55+ }
56+ Ok(())
59 }57 }
60 58
61-/// The refusal a [`DEAD_MARK`] abort is: the same `400` the caller's59+/// The refusal a locked course read answers when the course is gone: the
62-/// pre-flight read raises, since it is the same fact one instant later.60+/// same `400` the caller's pre-flight read raises, since it is the same fact
61+/// one instant later.
63 fn no_such_course() -> AppError {62 fn no_such_course() -> AppError {
64 AppError::Validation(ValidationError::Invalid {63 AppError::Validation(ValidationError::Invalid {
65 field: "course_ids",64 field: "course_ids",
@@ -67,15 +66,10 @@ fn no_such_course() -> AppError {
67 })66 })
68 }67 }
69 68
70-/// Write the blueprint. A second one for the same grade is a 409 the store69+/// Write the blueprint's row. A second one for the same grade is a 409 the
71-/// itself decides — the grade is the record key, so the duplicate is seen70+/// store itself decides — the grade is the primary key, so the duplicate is
72-/// rather than raced.71+/// seen rather than raced (`23505` on `class_blueprint_pkey`, mapped right
73-///72+/// here: a duplicate is a decision, never a retry).
74-/// Not [`transaction_with_retry`]: the `CREATE` here can legitimately answer
75-/// "already exists", which that loop cannot tell from a lost round and would
76-/// re-send until the tries ran out — turning this 409 into a 500. A round
77-/// genuinely lost to a concurrent course delete is therefore an error the
78-/// caller retries, with nothing written.
79 pub async fn create(73 pub async fn create(
80 db: &Database,74 db: &Database,
81 creator: &UserId,75 creator: &UserId,
@@ -84,51 +78,50 @@ pub async fn create(
84 ) -> Result<ClassBlueprint, AppError> {78 ) -> Result<ClassBlueprint, AppError> {
85 let blueprint = ClassBlueprint {79 let blueprint = ClassBlueprint {
86 id: ClassBlueprintId::for_grade(&grade),80 id: ClassBlueprintId::for_grade(&grade),
87- grade,81+ grade: grade.clone(),
88- courses,82+ courses: courses.clone(),
89 creator: creator.clone(),83 creator: creator.clone(),
90 };84 };
91- let named: Vec<RecordId> = blueprint.courses.iter().map(CourseId::record).collect();85+ tx_with_retry(db, false, async |tx| {
92- let mut result = db86+ courses_alive(tx, &courses).await?;
93- .query(format!(87+ let inserted = sqlx::query!(
94- "BEGIN TRANSACTION;88+ r#"INSERT INTO class_blueprint (grade, courses, creator)
95- {};89+ VALUES ($1, $2, $3)"#,
96- CREATE $id CONTENT $row;90+ grade as _,
97- COMMIT TRANSACTION;",91+ courses as _,
98- courses_alive()92+ creator as _
99- ))93+ )
100- .bind(("id", blueprint.id.record()))94+ .execute(&mut *tx)
101- .bind(("row", blueprint))95+ .await;
102- .bind(("courses", named))96+ match inserted {
103- .await?;97+ Ok(_) => Ok(blueprint),
104- let mut errors = result.take_errors();98+ Err(e) if unique_violation(&e) == Some("class_blueprint_pkey") => Err(
105- if errors99+ AppError::Conflict("a blueprint already exists for that grade"),
106- .values()100+ ),
107- .any(|error| error.to_string().contains(DEAD_MARK))101+ Err(e) => Err(e.into()),
108- {102+ }
109- return Err(no_such_course());103+ })
110- }104+ .await
111- if errors.values().any(surrealdb::Error::is_already_exists) {
112- return Err(AppError::Conflict(
113- "a blueprint already exists for that grade",
114- ));
115- }
116- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
117- return Err(error.into());
118- }
119- // Slots count BEGIN and the FOR: the CREATE is slot 2.
120- result
121- .take::<Vec<ClassBlueprint>>(2)?
122- .into_iter()
123- .next()
124- .ok_or_else(|| AppError::Internal("failed to create blueprint".into()))
125 }105 }
126 106
127 pub async fn read(107 pub async fn read(
128 db: &Database,108 db: &Database,
129 id: &ClassBlueprintId,109 id: &ClassBlueprintId,
130 ) -> Result<Option<ClassBlueprint>, AppError> {110 ) -> Result<Option<ClassBlueprint>, AppError> {
131- Ok(db.select(id.record()).await?)111+ let row = sqlx::query!(
112+ r#"SELECT grade AS "id: ClassBlueprintId", grade AS "grade: ClassGrade",
113+ courses AS "courses: Vec<CourseId>", creator AS "creator: UserId"
114+ FROM class_blueprint WHERE grade = $1"#,
115+ id as _
116+ )
117+ .fetch_optional(db)
118+ .await?;
119+ Ok(row.map(|row| ClassBlueprint {
120+ id: row.id,
121+ grade: row.grade,
122+ courses: row.courses,
123+ creator: row.creator,
124+ }))
132 }125 }
133 126
134 /// Every blueprint, by grade label — the id *is* the label, so this is the127 /// Every blueprint, by grade label — the id *is* the label, so this is the
@@ -138,7 +131,7 @@ pub async fn list_all(
138 limit: Option<i64>,131 limit: Option<i64>,
139 offset: i64,132 offset: i64,
140 ) -> Result<(Vec<ClassBlueprint>, i64), AppError> {133 ) -> Result<(Vec<ClassBlueprint>, i64), AppError> {
141- PagedList::new(CLASS_BLUEPRINT_TABLE, "ORDER BY id ASC")134+ PagedList::new(CLASS_BLUEPRINT_TABLE, "ORDER BY grade ASC")
142 .run(limit, offset, db)135 .run(limit, offset, db)
143 .await136 .await
144 }137 }
@@ -150,44 +143,34 @@ pub async fn list_all(
150 /// it, and only the caller can tell those apart (the workflow re-reads and143 /// it, and only the caller can tell those apart (the workflow re-reads and
151 /// answers a `409` or a `404`).144 /// answers a `409` or a `404`).
152 ///145 ///
153-/// A template naming a course that is gone aborts with [`DEAD_MARK`] and is146+/// A template naming a course that is gone refuses inside the transaction
154-/// reported as the caller's own pre-flight `400`.147+/// with the pre-flight `400` ([`courses_alive`]).
155 pub async fn set_courses_if_unchanged(148 pub async fn set_courses_if_unchanged(
156 db: &Database,149 db: &Database,
157 id: &ClassBlueprintId,150 id: &ClassBlueprintId,
158 held: Vec<CourseId>,151 held: Vec<CourseId>,
159 wanted: Vec<CourseId>,152 wanted: Vec<CourseId>,
160 ) -> Result<Option<ClassBlueprint>, AppError> {153 ) -> Result<Option<ClassBlueprint>, AppError> {
161- let named: Vec<RecordId> = wanted.iter().map(CourseId::record).collect();154+ tx_with_retry(db, false, async |tx| {
162- let (mut result, mut errors) = transaction_with_retry(155+ courses_alive(tx, &wanted).await?;
163- db,156+ let updated = sqlx::query!(
164- &format!(157+ r#"UPDATE class_blueprint SET courses = $2
165- "BEGIN TRANSACTION;158+ WHERE grade = $1 AND courses = $3
166- {};159+ RETURNING grade AS "grade: ClassGrade", creator AS "creator: UserId""#,
167- UPDATE $id SET courses = $wanted WHERE courses = $held RETURN AFTER;160+ id as _,
168- COMMIT TRANSACTION;",161+ wanted as _,
169- courses_alive()162+ held as _
170- ),163+ )
171- &[164+ .fetch_optional(&mut *tx)
172- ("id".into(), id.record().into_value()),165+ .await?;
173- ("wanted".into(), wanted.into_value()),166+ Ok(updated.map(|row| ClassBlueprint {
174- ("held".into(), held.into_value()),167+ id: id.clone(),
175- ("courses".into(), named.into_value()),168+ grade: row.grade,
176- ],169+ courses: wanted,
177- &[DEAD_MARK],170+ creator: row.creator,
178- )171+ }))
179- .await?;172+ })
180- if errors173+ .await
181- .values()
182- .any(|error| error.to_string().contains(DEAD_MARK))
183- {
184- return Err(no_such_course());
185- }
186- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
187- return Err(error.into());
188- }
189- // Slots count BEGIN and the FOR: the UPDATE is slot 2.
190- Ok(result.take::<Vec<ClassBlueprint>>(2)?.into_iter().next())
191 }174 }
192 175
193 /// Delete the row, but only while it still carries the list this caller read176 /// Delete the row, but only while it still carries the list this caller read
@@ -195,46 +178,58 @@ pub async fn set_courses_if_unchanged(
195 /// else's additions. `false` means the conditional delete matched nothing:178 /// else's additions. `false` means the conditional delete matched nothing:
196 /// the row is gone, or its list moved since the caller read it, and only the179 /// the row is gone, or its list moved since the caller read it, and only the
197 /// caller can tell those apart.180 /// caller can tell those apart.
181+///
182+/// The `DELETE` is also the whole of the serialization against the attaches
183+/// made on this blueprint's behalf: a sourced attach holds a `FOR KEY SHARE`
184+/// on this row across its transaction ([`class_pump::attach_course`]), so its
185+/// row lands before this delete's sweep runs or not at all — the invariant the
186+/// old process-wide write lease held, now on the row itself.
198 pub async fn delete_if_unchanged(187 pub async fn delete_if_unchanged(
199 db: &Database,188 db: &Database,
200 id: &ClassBlueprintId,189 id: &ClassBlueprintId,
201 held: Vec<CourseId>,190 held: Vec<CourseId>,
202 ) -> Result<bool, AppError> {191 ) -> Result<bool, AppError> {
203- let mut result = db192+ let deleted = sqlx::query!(
204- .query("DELETE $id WHERE courses = $held RETURN BEFORE")193+ r#"DELETE FROM class_blueprint WHERE grade = $1 AND courses = $2"#,
205- .bind(("id", id.record()))194+ id as _,
206- .bind(("held", held))195+ held as _
207- .await?196+ )
208- .check()?;197+ .execute(db)
209- Ok(!result.take::<Vec<ClassBlueprint>>(0)?.is_empty())198+ .await?;
199+ Ok(deleted.rows_affected() > 0)
210 }200 }
211 201
212 /// Every `class_course` row held by any of `classes`, projected down to the202 /// Every `class_course` row held by any of `classes`, projected down to the
213 /// pair — the read [`crate::service::class_blueprint::status`] diffs the203 /// pair — the read [`crate::service::class_blueprint::status`] diffs the
214 /// template against.204 /// template against.
215-pub async fn held_links(db: &Database, classes: Vec<RecordId>) -> Result<Vec<Held>, AppError> {205+pub async fn held_links(db: &Database, classes: Vec<ClassGroupId>) -> Result<Vec<Held>, AppError> {
216- let mut result = db206+ let rows = sqlx::query!(
217- .query(format!(207+ r#"SELECT class AS "class: ClassGroupId", course AS "course: CourseId"
218- "SELECT class, course FROM {CLASS_COURSE_TABLE} WHERE class IN $classes"208+ FROM class_course WHERE class = ANY($1)"#,
219- ))209+ classes as _
220- .bind(("classes", classes))210+ )
221- .await?211+ .fetch_all(db)
222- .check()?;212+ .await?;
223- Ok(result.take::<Vec<Held>>(0)?)213+ Ok(rows
214+ .into_iter()
215+ .map(|row| Held {
216+ class: row.class,
217+ course: row.course,
218+ })
219+ .collect())
224 }220 }
225 221
226 /// Drop a course that no longer exists out of a blueprint's list.222 /// Drop a course that no longer exists out of a blueprint's list.
227 ///223 ///
228-/// The delete does this itself now:224+/// The delete does this itself now: the course's own cascade sweeps
229-/// [`crate::db::course::delete`] sweeps `class_blueprint` in225+/// `class_blueprint` in the same transaction that takes the course's
230-/// the same cascade that takes the course's `class_course` links, so a226+/// `class_course` links, so a template stops naming a course the instant that
231-/// template stops naming a course the instant that course goes. This used227+/// course goes. This used to be the *only* thing that could remove such an id,
232-/// to be the *only* thing that could remove such an id, and that was the228+/// and that was the bug: it fires only while walking a section, so a grade
233-/// bug: it fires only while walking a section, so a grade with no sections229+/// with no sections could never reach it, and the repair every doc surface
234-/// could never reach it, and the repair every doc surface pointed at230+/// pointed at (`PATCH` the list back as it stands) is a `400` for naming a
235-/// (`PATCH` the list back as it stands) is a `400` for naming a course that231+/// course that does not exist. A permanent dangling id, and no call that could
236-/// does not exist. A permanent dangling id, and no call that could clear232+/// clear it.
237-/// it.
238 ///233 ///
239 /// What is left for this to do is the **window** the sweep cannot cover: a234 /// What is left for this to do is the **window** the sweep cannot cover: a
240 /// pump walks a snapshot of the list it read, so a course deleted after235 /// pump walks a snapshot of the list it read, so a course deleted after
@@ -253,21 +248,18 @@ pub async fn held_links(db: &Database, classes: Vec<RecordId>) -> Result<Vec<Hel
253 /// and re-running it changes nothing. No sweep follows it either — the248 /// and re-running it changes nothing. No sweep follows it either — the
254 /// attachments it would sweep are exactly the ones the course's own delete249 /// attachments it would sweep are exactly the ones the course's own delete
255 /// already took.250 /// already took.
256-///
257-/// No [`crate::service::class_blueprint::BLUEPRINT_LOCK`] lease either: an
258-/// `UPDATE` of a record that is gone writes nothing, so this cannot
259-/// resurrect a blueprint a delete took while the pump around it was
260-/// running.
261 pub async fn prune(251 pub async fn prune(
262 db: &Database,252 db: &Database,
263 id: &ClassBlueprintId,253 id: &ClassBlueprintId,
264 course: &CourseId,254 course: &CourseId,
265 ) -> Result<(), AppError> {255 ) -> Result<(), AppError> {
266- db.query("UPDATE $id SET courses = array::complement(courses ?? [], [$course])")256+ sqlx::query!(
267- .bind(("id", id.record()))257+ r#"UPDATE class_blueprint SET courses = array_remove(courses, $2) WHERE grade = $1"#,
268- .bind(("course", course.record()))258+ id as _,
269- .await?259+ course as _
270- .check()?;260+ )
261+ .execute(db)
262+ .await?;
271 Ok(())263 Ok(())
272 }264 }
273 265
@@ -279,7 +271,7 @@ pub async fn prune(
279 /// what makes a repeated call a repair rather than a no-op: whatever a271 /// what makes a repeated call a repair rather than a no-op: whatever a
280 /// half-finished sweep left behind is exactly what the next one finds.272 /// half-finished sweep left behind is exactly what the next one finds.
281 ///273 ///
282-/// `source` is the whole filter, so a row without the key — a hand attach —274+/// `source` is the whole filter, so a row without the tag — a hand attach —
283 /// is never matched, and a class that acquired the same course by hand keeps275 /// is never matched, and a class that acquired the same course by hand keeps
284 /// it. The rows are read rather than derived from the classes at this grade:276 /// it. The rows are read rather than derived from the classes at this grade:
285 /// a class whose grade was edited after the pump still carries this277 /// a class whose grade was edited after the pump still carries this
@@ -288,29 +280,34 @@ pub async fn sourced_links(
288 db: &Database,280 db: &Database,
289 id: &ClassBlueprintId,281 id: &ClassBlueprintId,
290 keep: &[CourseId],282 keep: &[CourseId],
291-) -> Result<Vec<RecordId>, AppError> {283+) -> Result<Vec<Held>, AppError> {
292- let named: Vec<RecordId> = keep.iter().map(CourseId::record).collect();284+ let keep: Vec<CourseId> = keep.to_vec();
293- let mut found = db285+ let rows = sqlx::query!(
294- .query(format!(286+ r#"SELECT class AS "class: ClassGroupId", course AS "course: CourseId"
295- "SELECT VALUE id FROM {CLASS_COURSE_TABLE} \287+ FROM class_course
296- WHERE source = $blueprint AND course NOT IN $keep"288+ WHERE source = $1 AND course <> ALL($2)"#,
297- ))289+ id as _,
298- .bind(("blueprint", id.record()))290+ keep as _
299- .bind(("keep", named))291+ )
300- .await?292+ .fetch_all(db)
301- .check()?;293+ .await?;
302- Ok(found.take::<Vec<RecordId>>(0)?)294+ Ok(rows
295+ .into_iter()
296+ .map(|row| Held {
297+ class: row.class,
298+ course: row.course,
299+ })
300+ .collect())
303 }301 }
304 302
305 /// Detach the link rows [`sourced_links`] named and sweep the enrollments303 /// Detach the link rows [`sourced_links`] named and sweep the enrollments
306 /// they pumped. The sweep underneath is the pump's own, so a student a304 /// they pumped. The sweep underneath is the pump's own, so a student a
307 /// second class still claims is re-tagged rather than unenrolled.305 /// second class still claims is re-tagged rather than unenrolled.
308 ///306 ///
309-/// Each detach re-asserts the tag, because this loop deliberately runs307+/// Each detach re-asserts the tag: the link's identity is the (class, course)
310-/// without the lease: the link's record id is the (class, course) pair and308+/// pair and says nothing about provenance, so a row a *new* blueprint at the
311-/// says nothing about provenance, so a row a *new* blueprint at the same309+/// same grade attached while this ran would otherwise be swept by the old
312-/// grade attached while this ran would otherwise be swept by the old one's310+/// one's tail.
313-/// tail.
314 ///311 ///
315 /// One transaction per *link row*, which is the module note's "one312 /// One transaction per *link row*, which is the module note's "one
316 /// transaction per (class, course)" and the mirror of the pump's313 /// transaction per (class, course)" and the mirror of the pump's
@@ -326,19 +323,10 @@ pub async fn sourced_links(
326 pub async fn drop_links(323 pub async fn drop_links(
327 db: &Database,324 db: &Database,
328 id: &ClassBlueprintId,325 id: &ClassBlueprintId,
329- links: Vec<RecordId>,326+ links: Vec<Held>,
330 ) -> Result<(), AppError> {327 ) -> Result<(), AppError> {
331 for link in links {328 for link in links {
332- detach(329+ class_pump::detach_course(db, &link.class, &link.course, Some(id)).await?;
333- db,
334- "$link WHERE source = $blueprint",
335- Axis::Course,
336- &[
337- ("link".into(), link.into_value()),
338- ("blueprint".into(), id.record().into_value()),
339- ],
340- )
341- .await?;
342 }330 }
343 Ok(())331 Ok(())
344 }332 }
src/db/class_course.rsmodified+10 -28
@@ -1,17 +1,16 @@
1-//! The `class_course` table: the course-axis attach transaction and the1+//! The `class_course` table: the course-axis attach entry point and the
2 //! attachment listing. The refusals-to-errors policy and the detach that turns2 //! attachment listing. The refusals-to-errors policy and the detach that turns
3 //! a zero-row sweep into a 404 live in [`crate::service::class_course`]; the3 //! a zero-row sweep into a 404 live in [`crate::service::class_course`]; the
4 //! transaction itself is the pump's, [`crate::db::class_pump`].4 //! transaction itself is the pump's, [`crate::db::class_pump`].
5 5
6 use crate::constant::CLASS_COURSE_TABLE;6 use crate::constant::CLASS_COURSE_TABLE;
7 use crate::database::Database;7 use crate::database::Database;
8-use crate::db::class_pump::{Attached, Axis};8+use crate::db::class_pump::Attached;
9 use crate::db::page::PagedList;9 use crate::db::page::PagedList;
10 use crate::domain::class_blueprint::ClassBlueprintId;10 use crate::domain::class_blueprint::ClassBlueprintId;
11-use crate::domain::class_course::{ClassCourse, ClassCourseId};11+use crate::domain::class_course::ClassCourse;
12 use crate::domain::class_group::ClassGroupId;12 use crate::domain::class_group::ClassGroupId;
13 use crate::domain::course::CourseId;13 use crate::domain::course::CourseId;
14-use crate::domain::timestamp::Timestamp;
15 use crate::domain::user::UserId;14 use crate::domain::user::UserId;
16 use crate::error::AppError;15 use crate::error::AppError;
17 16
@@ -37,30 +36,13 @@ pub(crate) async fn attach_sourced(
37 attached_by: &UserId,36 attached_by: &UserId,
38 source: Option<&ClassBlueprintId>,37 source: Option<&ClassBlueprintId>,
39 ) -> Result<Attached<ClassCourse>, AppError> {38 ) -> Result<Attached<ClassCourse>, AppError> {
40- let link = ClassCourse {39+ crate::db::class_pump::attach_course(db, class, course, attached_by, source).await
41- id: ClassCourseId::composite(class, course),
42- class: class.clone(),
43- course: course.clone(),
44- attached_by: attached_by.clone(),
45- source: source.cloned(),
46- attached_at: Some(Timestamp::now()),
47- };
48- crate::db::class_pump::attach(
49- db,
50- class,
51- Axis::Course,
52- (&link.id.record(), &link),
53- course.record(),
54- attached_by.record(),
55- source.map(ClassBlueprintId::record),
56- )
57- .await
58 }40 }
59 41
60 /// The courses a class is attached to, newest first — by when they were42 /// The courses a class is attached to, newest first — by when they were
61-/// attached, not by the course's own id, which is what the composite record43+/// attached. The composite primary key is the tiebreaker (class, then course:
62-/// id sorts on. A row older than the column carries no stamp at all, and44+/// the two halves of the id this order used to sort), which makes the order
63-/// NONE sorts last under DESC — the honest place for a row of unknown age.45+/// total.
64 pub async fn list_for_class(46 pub async fn list_for_class(
65 db: &Database,47 db: &Database,
66 class: &ClassGroupId,48 class: &ClassGroupId,
@@ -68,10 +50,10 @@ pub async fn list_for_class(
68 offset: i64,50 offset: i64,
69 ) -> Result<(Vec<ClassCourse>, i64), AppError> {51 ) -> Result<(Vec<ClassCourse>, i64), AppError> {
70 PagedList::new(52 PagedList::new(
71- format!("{CLASS_COURSE_TABLE} WHERE class = $class"),53+ format!("{CLASS_COURSE_TABLE} WHERE class = $1"),
72- "ORDER BY attached_at DESC, id DESC",54+ "ORDER BY attached_at DESC, class DESC, course DESC",
73 )55 )
74- .bind("class", class.record())56+ .bind(class.uuid())
75 .run(limit, offset, db)57 .run(limit, offset, db)
76 .await58 .await
77 }59 }
src/db/class_group.rsmodified+172 -125
@@ -1,13 +1,10 @@
1-//! The `class_group` table: the row, its term reference claimed through1+//! The `class_group` table: the row, its term reference claimed through the
2-//! [`crate::db::cap`] in the same transaction as the link, and the 0/0 delete2+//! [`crate::db::cap`] shapes in the same statement as the link, and the 0/0
3-//! guard. The archived-term guard and the route-facing wrappers live in3+//! delete guard. The archived-term guard and the route-facing wrappers live in
4 //! [`crate::service::class_group`].4 //! [`crate::service::class_group`].
5 5
6-use surrealdb::types::{RecordId, SurrealValue};6+use crate::constant::{CLASS_GROUP_TABLE, TERM_CLASS_COUNT_FIELD};
7-7+use crate::database::{Database, tx_with_retry};
8-use crate::constant::{CLASS_COURSE_COUNT_FIELD, CLASS_MEMBER_COUNT_FIELD, TERM_CLASS_COUNT_FIELD};
9-use crate::database::{Database, transaction_with_retry};
10-use crate::db::cap;
11 use crate::db::field_update::FieldUpdate;8 use crate::db::field_update::FieldUpdate;
12 use crate::db::page::PagedList;9 use crate::db::page::PagedList;
13 use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName};10 use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName};
@@ -15,16 +12,13 @@ use crate::domain::term::{self, TermId};
15 use crate::domain::user::UserId;12 use crate::domain::user::UserId;
16 use crate::error::AppError;13 use crate::error::AppError;
17 14
18-/// The `THROW` marker the delete guard aborts with — a class that still holds
19-/// students or courses, or a class row that is no longer there.
20-const LINKS_MARK: &str = "class_links";
21-
22 /// Create the class, claiming a reference on the term it links (if any) in15 /// Create the class, claiming a reference on the term it links (if any) in
23-/// the *same transaction* as the row, exactly as16+/// the *same statement* as the row, exactly as
24 /// [`crate::db::course::create`] does: the claim is a17 /// [`crate::db::course::create`] does: the claim is a
25 /// conditional write on the term row, so it fails when the term is already18 /// conditional write on the term row, so it fails when the term is already
26-/// gone, it makes the term undeletable the instant this link exists, and no19+/// gone, it makes the term undeletable the instant this link exists, and — the
27-/// crash can leave either half without the other.20+/// claim and the insert being one CTE — no crash and no refused claim can
21+/// leave either half without the other.
28 pub async fn create(22 pub async fn create(
29 db: &Database,23 db: &Database,
30 creator: &UserId,24 creator: &UserId,
@@ -33,40 +27,77 @@ pub async fn create(
33 term: Option<TermId>,27 term: Option<TermId>,
34 teacher: Option<UserId>,28 teacher: Option<UserId>,
35 ) -> Result<ClassGroup, AppError> {29 ) -> Result<ClassGroup, AppError> {
36- let class = ClassGroup {30+ let id = ClassGroupId::generate();
37- id: ClassGroupId::generate(),31+ match &term {
38- creator: creator.clone(),32+ Some(term) => {
39- name,33+ // The claim and the insert are one statement: atomic without an
40- grade,34+ // explicit transaction, exactly like every other
41- term,35+ // single-statement guard.
42- teacher,36+ let written = sqlx::query_as!(
43- };37+ ClassGroup,
44- let id = class.id.record();38+ r#"WITH seat AS (
45- let Some(term) = class.term.clone() else {39+ UPDATE term SET class_count = class_count + 1
46- let created: Option<ClassGroup> = db.create(id).content(class).await?;40+ WHERE id = $1
47- return created.ok_or_else(|| AppError::Internal("failed to create class".into()));41+ RETURNING 1)
48- };42+ INSERT INTO class_group (id, creator, name, grade, term, teacher)
49- match cap::claim_and_create(43+ SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat)
50- &term.record(),44+ RETURNING id, creator, name, grade, term, teacher"#,
51- TERM_CLASS_COUNT_FIELD,45+ term.uuid(),
52- cap::UNLIMITED,46+ id.uuid(),
53- &id,47+ creator.uuid(),
54- &class,48+ name.as_str(),
55- db,49+ grade.as_deref(),
56- )50+ teacher.as_ref()
57- .await?51+ )
58- {52+ .fetch_optional(db)
59- cap::Claimed::Made(created) => Ok(created),53+ .await;
60- // Uncapped, so "full" can only mean the conditional write matched no54+ match written {
61- // term row at all — the claim doubles as the existence check.55+ Ok(Some(created)) => Ok(created),
62- cap::Claimed::Full => Err(term::gone_error()),56+ // Uncapped, so a zero-row claim can only mean the conditional
63- // Unreachable: the id is a ULID this call just generated.57+ // write matched no term row at all — the claim doubles as the
64- cap::Claimed::Duplicate => Err(AppError::Internal("failed to create class".into())),58+ // existence check.
59+ Ok(None) => Err(term::gone_error()),
60+ // The term row is locked by the claim's own UPDATE, so this
61+ // is unreachable; a defensible answer beats a 500.
62+ Err(e) if crate::database::foreign_key_violation(&e) => Err(term::gone_error()),
63+ // Unreachable: the id was minted one line above.
64+ Err(e) if crate::database::unique_violation(&e).is_some() => {
65+ Err(AppError::Internal("failed to create class".into()))
66+ }
67+ Err(e) => Err(e.into()),
68+ }
69+ }
70+ None => {
71+ let created = sqlx::query_as!(
72+ ClassGroup,
73+ r#"INSERT INTO class_group (id, creator, name, grade, term, teacher)
74+ VALUES ($1, $2, $3, $4, $5, $6)
75+ RETURNING id, creator, name, grade, term, teacher"#,
76+ id.uuid(),
77+ creator.uuid(),
78+ name.as_str(),
79+ grade.as_deref(),
80+ term.as_ref(),
81+ teacher.as_ref()
82+ )
83+ .fetch_optional(db)
84+ .await?;
85+ // Unreachable: the id is a v7 uuid this call just generated.
86+ created.ok_or_else(|| AppError::Internal("failed to create class".into()))
87+ }
65 }88 }
66 }89 }
67 90
68 pub async fn read(db: &Database, id: &ClassGroupId) -> Result<Option<ClassGroup>, AppError> {91 pub async fn read(db: &Database, id: &ClassGroupId) -> Result<Option<ClassGroup>, AppError> {
69- Ok(db.select(id.record()).await?)92+ let class = sqlx::query_as!(
93+ ClassGroup,
94+ r#"SELECT id, creator, name, grade, term, teacher
95+ FROM class_group WHERE id = $1"#,
96+ id.uuid()
97+ )
98+ .fetch_optional(db)
99+ .await?;
100+ Ok(class)
70 }101 }
71 102
72 /// Every class, newest first — or one grade's, when `grade` narrows it:103 /// Every class, newest first — or one grade's, when `grade` narrows it:
@@ -84,13 +115,16 @@ pub async fn list_all(
84 offset: i64,115 offset: i64,
85 ) -> Result<(Vec<ClassGroup>, i64), AppError> {116 ) -> Result<(Vec<ClassGroup>, i64), AppError> {
86 let list = match grade {117 let list = match grade {
87- None => PagedList::new("class_group", "ORDER BY id DESC"),118+ None => PagedList::new(CLASS_GROUP_TABLE, "ORDER BY id DESC"),
88- // A gradeless class stores no `grade` key at all (SurrealDB drops a119+ Some(None) => PagedList::new(
89- // key valued NONE), and an absent field reads back as NONE — so the120+ format!("{CLASS_GROUP_TABLE} WHERE grade IS NULL"),
90- // one comparison covers both spellings.121+ "ORDER BY id DESC",
91- Some(None) => PagedList::new("class_group WHERE grade IS NONE", "ORDER BY id DESC"),122+ ),
92- Some(Some(grade)) => PagedList::new("class_group WHERE grade = $grade", "ORDER BY id DESC")123+ Some(Some(grade)) => PagedList::new(
93- .bind("grade", grade.as_str().to_string()),124+ format!("{CLASS_GROUP_TABLE} WHERE grade = $1"),
125+ "ORDER BY id DESC",
126+ )
127+ .bind(grade.as_str().to_string()),
94 };128 };
95 list.run(limit, offset, db).await129 list.run(limit, offset, db).await
96 }130 }
@@ -114,30 +148,34 @@ pub async fn update(
114 teacher: Option<Option<UserId>>,148 teacher: Option<Option<UserId>>,
115 ) -> Result<ClassGroup, AppError> {149 ) -> Result<ClassGroup, AppError> {
116 let (claim, release) = term::ref_move(class.term.as_ref(), &term);150 let (claim, release) = term::ref_move(class.term.as_ref(), &term);
117- let expected = class.term.as_ref().map(TermId::record);151+ let expected = class.term.as_ref().map(TermId::uuid);
118- FieldUpdate::new(class.id.record())152+ FieldUpdate::new(CLASS_GROUP_TABLE, class.id.uuid())
119- .set("name", name)153+ .set("name", name.map(|name| name.as_str().to_string()))
120- .set("grade", grade)154+ .set(
121- .set("term", term.map(|term| term.map(|term| term.record())))155+ "grade",
156+ grade.map(|grade| grade.map(|grade| grade.as_str().to_string())),
157+ )
158+ .set("term", term.map(|term| term.map(|term| term.uuid())))
122 // Not refcounted: a homeroom assignment is a label, so it rides the159 // Not refcounted: a homeroom assignment is a label, so it rides the
123 // plain `set` path and never arms the term CAS.160 // plain `set` path and never arms the term CAS.
124 .set(161 .set(
125 "teacher",162 "teacher",
126- teacher.map(|teacher| teacher.map(|teacher| teacher.record())),163+ teacher.map(|teacher| teacher.map(|teacher| teacher.uuid())),
127 )164 )
128 .refcount(165 .refcount(
166+ "term",
129 TERM_CLASS_COUNT_FIELD,167 TERM_CLASS_COUNT_FIELD,
130 "term",168 "term",
131 expected,169 expected,
132- claim,170+ claim.map(|term| term.uuid()),
133- release,171+ release.map(|term| term.uuid()),
134 term::gone_error(),172 term::gone_error(),
135 )173 )
136 .run::<ClassGroup>(db)174 .run::<ClassGroup>(db)
137 .await175 .await
138 }176 }
139 177
140-/// The classes `ids` names, in no particular order — the join behind178+/// The classes `ids` name, in no particular order — the join behind
141 /// "which class section is this student in", where the ids come from179 /// "which class section is this student in", where the ids come from
142 /// `class_member` rows already paged. Ids that name no row are simply180 /// `class_member` rows already paged. Ids that name no row are simply
143 /// absent.181 /// absent.
@@ -145,13 +183,16 @@ pub async fn list_by_ids(db: &Database, ids: &[ClassGroupId]) -> Result<Vec<Clas
145 if ids.is_empty() {183 if ids.is_empty() {
146 return Ok(Vec::new());184 return Ok(Vec::new());
147 }185 }
148- let records: Vec<RecordId> = ids.iter().map(ClassGroupId::record).collect();186+ let ids: Vec<ClassGroupId> = ids.to_vec();
149- let mut result = db187+ let classes = sqlx::query_as!(
150- .query("SELECT * FROM class_group WHERE id IN $ids")188+ ClassGroup,
151- .bind(("ids", records))189+ r#"SELECT id, creator, name, grade, term, teacher
152- .await?190+ FROM class_group WHERE id = ANY($1)"#,
153- .check()?;191+ ids as _
154- Ok(result.take::<Vec<ClassGroup>>(0)?)192+ )
193+ .fetch_all(db)
194+ .await?;
195+ Ok(classes)
155 }196 }
156 197
157 /// Every class section at one grade label, in no particular order — what a198 /// Every class section at one grade label, in no particular order — what a
@@ -161,23 +202,28 @@ pub async fn list_for_grade(
161 db: &Database,202 db: &Database,
162 grade: &ClassGrade,203 grade: &ClassGrade,
163 ) -> Result<Vec<ClassGroup>, AppError> {204 ) -> Result<Vec<ClassGroup>, AppError> {
164- let mut result = db205+ let classes = sqlx::query_as!(
165- .query("SELECT * FROM class_group WHERE grade = $grade")206+ ClassGroup,
166- .bind(("grade", grade.as_str().to_string()))207+ r#"SELECT id, creator, name, grade, term, teacher
167- .await?208+ FROM class_group WHERE grade = $1"#,
168- .check()?;209+ grade.as_str()
169- Ok(result.take::<Vec<ClassGroup>>(0)?)210+ )
211+ .fetch_all(db)
212+ .await?;
213+ Ok(classes)
170 }214 }
171 215
172-/// Strip `user` from every class they were the homeroom teacher of — the216+/// Clear the homeroom teacher everywhere `user` held one — the
173 /// sweep for a user demoted below `teacher`, who may no longer hold one.217 /// sweep for a user demoted below `teacher`, who may no longer hold one.
174 /// The mirror of [`crate::db::course::unassign_everywhere`];218 /// The mirror of [`crate::db::course::unassign_everywhere`];
175 /// nothing is counted on this column, so there is no reference to give back.219 /// nothing is counted on this column, so there is no reference to give back.
176 pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> {220 pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> {
177- db.query("UPDATE class_group SET teacher = NONE WHERE teacher = $usr")221+ sqlx::query!(
178- .bind(("usr", user.record()))222+ r#"UPDATE class_group SET teacher = NULL WHERE teacher = $1"#,
179- .await?223+ user.uuid()
180- .check()?;224+ )
225+ .execute(db)
226+ .await?;
181 Ok(())227 Ok(())
182 }228 }
183 229
@@ -189,49 +235,48 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App
189 /// `false` = refused, nothing was written. Both counts are read off the235 /// `false` = refused, nothing was written. Both counts are read off the
190 /// class's own row, so the check and the delete are one conditional write on236 /// class's own row, so the check and the delete are one conditional write on
191 /// one record — a member or attach racing this either claims first (and the237 /// one record — a member or attach racing this either claims first (and the
192-/// delete is refused) or finds the row gone (and is refused itself).238+/// delete is refused) or finds the row gone (and is refused itself). The
193 /// `Err(NotFound)` keeps the answer a concurrent *delete* used to get.239 /// `Err(NotFound)` keeps the answer a concurrent *delete* used to get.
194 pub async fn delete(db: &Database, class: ClassGroup) -> Result<bool, AppError> {240 pub async fn delete(db: &Database, class: ClassGroup) -> Result<bool, AppError> {
195- // Parenthesized `??` throughout: `n ?? 0 = 0` parses as `n ?? (0 = 0)`,241+ tx_with_retry(db, false, async |tx| {
196- // which is truthy for every row and would delete a class still in use.242+ let gone = sqlx::query!(
197- let sql = format!(243+ r#"DELETE FROM class_group
198- "BEGIN TRANSACTION;244+ WHERE id = $1
199- LET $gone = (DELETE $class WHERE ({CLASS_MEMBER_COUNT_FIELD} ?? 0) = 0 \245+ AND class_member_count = 0 AND class_course_count = 0
200- AND ({CLASS_COURSE_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE);246+ RETURNING term AS "term: Option<uuid::Uuid>""#,
201- IF array::len($gone) = 0 {{ THROW '{LINKS_MARK}' }};247+ class.id.uuid()
202- FOR $row IN $gone {{248+ )
203- IF $row.term != NONE {{249+ .fetch_optional(&mut *tx)
204- UPDATE $row.term SET {TERM_CLASS_COUNT_FIELD} = \250+ .await?;
205- math::max([({TERM_CLASS_COUNT_FIELD} ?? 0) - 1, 0]);251+ let Some(row) = gone else {
206- }};252+ // Still linked or already gone: the guard cannot tell those
207- }};253+ // apart, and only the refusal path pays for the extra read that
208- COMMIT TRANSACTION;"254+ // can.
209- );255+ let standing = sqlx::query_scalar!(
210- // An aborted transaction errors *every* slot, most with a generic "not256+ r#"SELECT 1 AS "one" FROM class_group WHERE id = $1"#,
211- // executed" — only the THROW's own slot names the marker, and a lost257+ class.id.uuid()
212- // round is re-sent rather than reported (see [`transaction_with_retry`]).258+ )
213- let (_, mut errors) = transaction_with_retry(259+ .fetch_optional(&mut *tx)
214- db,260+ .await?
215- &sql,261+ .is_some();
216- &[("class".into(), class.id.record().into_value())],262+ return if standing {
217- &[LINKS_MARK],263+ Ok(false)
218- )264+ } else {
219- .await?;265+ Err(AppError::NotFound)
220- if errors266+ };
221- .values()
222- .any(|error| error.to_string().contains(LINKS_MARK))
223- {
224- // Still linked or already gone: the guard cannot tell those apart,
225- // and only the refusal path pays for the extra read that can.
226- return match read(db, &class.id).await? {
227- Some(_) => Ok(false),
228- None => Err(AppError::NotFound),
229 };267 };
230- }268+ if let Some(term) = row.term {
231- if let Some(error) = errors.drain().map(|(_, error)| error).next() {269+ sqlx::query!(
232- return Err(error.into());270+ r#"UPDATE term SET class_count = GREATEST(class_count - 1, 0)
233- }271+ WHERE id = $1"#,
234- Ok(true)272+ term
273+ )
274+ .execute(&mut *tx)
275+ .await?;
276+ }
277+ Ok(true)
278+ })
279+ .await
235 }280 }
236 281
237 #[cfg(test)]282 #[cfg(test)]
@@ -547,9 +592,10 @@ mod tests {
547 let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200))592 let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200))
548 .await593 .await
549 .unwrap();594 .unwrap();
550- let dead = crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200))595+ let dead =
551- .await596+ crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200))
552- .unwrap();597+ .await
598+ .unwrap();
553 let dead_id = dead.get_id().clone();599 let dead_id = dead.get_id().clone();
554 assert!(crate::db::term::delete(&db, dead).await.unwrap());600 assert!(crate::db::term::delete(&db, dead).await.unwrap());
555 let class = class_on(Some(from.get_id().clone()), &db).await;601 let class = class_on(Some(from.get_id().clone()), &db).await;
@@ -610,9 +656,10 @@ mod tests {
610 let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200))656 let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200))
611 .await657 .await
612 .unwrap();658 .unwrap();
613- let other = crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200))659+ let other =
614- .await660+ crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200))
615- .unwrap();661+ .await
662+ .unwrap();
616 let class = class_on(Some(from.get_id().clone()), &db).await;663 let class = class_on(Some(from.get_id().clone()), &db).await;
617 let stale = class.clone();664 let stale = class.clone();
618 update(665 update(
src/db/class_member.rsmodified+9 -10
@@ -11,10 +11,9 @@ use crate::domain::class_member::ClassMember;
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-/// The class's roster, newest first — by when the student was added, not by14+/// The class's roster, newest first — by when the student was added. The
15-/// their account id, which is what the composite record id sorts on.15+/// composite primary key is the tiebreaker (class, then user: the two halves
16-/// A row older than the column carries no stamp at all, and NONE sorts last16+/// of the id this order used to sort), which makes the order total.
17-/// under DESC — which is the honest place for a row of unknown age.
18 pub async fn list_for_class(17 pub async fn list_for_class(
19 db: &Database,18 db: &Database,
20 class: &ClassGroupId,19 class: &ClassGroupId,
@@ -22,10 +21,10 @@ pub async fn list_for_class(
22 offset: i64,21 offset: i64,
23 ) -> Result<(Vec<ClassMember>, i64), AppError> {22 ) -> Result<(Vec<ClassMember>, i64), AppError> {
24 PagedList::new(23 PagedList::new(
25- format!("{CLASS_MEMBER_TABLE} WHERE class = $class"),24+ format!("{CLASS_MEMBER_TABLE} WHERE class = $1"),
26- "ORDER BY added_at DESC, id DESC",25+ "ORDER BY added_at DESC, class DESC, app_user DESC",
27 )26 )
28- .bind("class", class.record())27+ .bind(class.uuid())
29 .run(limit, offset, db)28 .run(limit, offset, db)
30 .await29 .await
31 }30 }
@@ -40,10 +39,10 @@ pub async fn list_for_user(
40 offset: i64,39 offset: i64,
41 ) -> Result<(Vec<ClassMember>, i64), AppError> {40 ) -> Result<(Vec<ClassMember>, i64), AppError> {
42 PagedList::new(41 PagedList::new(
43- format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),42+ format!("{CLASS_MEMBER_TABLE} WHERE app_user = $1"),
44- "ORDER BY added_at DESC, id DESC",43+ "ORDER BY added_at DESC, class DESC, app_user DESC",
45 )44 )
46- .bind("usr", user.record())45+ .bind(user.uuid())
47 .run(limit, offset, db)46 .run(limit, offset, db)
48 .await47 .await
49 }48 }
src/db/class_pump.rsmodified+721 -503
@@ -2,91 +2,46 @@
2 //! `enrollment` row that link implies reconciled with it, in one transaction.2 //! `enrollment` row that link implies reconciled with it, in one transaction.
3 //!3 //!
4 //! A class section (şube) has two link tables — `class_member` (a student in4 //! A class section (şube) has two link tables — `class_member` (a student in
5-//! it) and5+//! it) and `class_course` (a course attached to it) — and the *product* of the
6-//! `class_course` (a course attached to it) — and the *product* of the two is6+//! two is the roster it owes: every member is enrolled in every attached
7-//! the roster it owes: every member is enrolled in every attached course, in7+//! course, in real `enrollment` rows tagged [`source`](crate::domain::enrollment)
8-//! real `enrollment` rows tagged [`source`](crate::domain::enrollment) with the8+//! with the class that wrote them. Adding a member and attaching a course are
9-//! class that wrote them. Adding a member and attaching a course are therefore9+//! therefore the same operation seen along its two axes, and so are removing
10-//! the same operation seen along its two axes, and so are removing one and10+//! one and detaching the other.
11-//! detaching the other. That axis is what these two primitives take as a
12-//! parameter, so the four public operations are each a couple of lines.
13 //!11 //!
14 //! What is *not* one primitive is attach and detach. They share no statement:12 //! What is *not* one primitive is attach and detach. They share no statement:
15-//! one gates on "this pair already holds a row" and claims two counters13+//! one gates on "this pair already holds a row" and claims a counter upwards,
16-//! upwards, the other gates on nothing, releases, and has to decide per14+//! the other gates on nothing, releases, and has to decide per enrollment row
17-//! enrollment row whether a *rival* class still claims it. Folding them behind15+//! whether a *rival* class still claims it.
18-//! a direction flag would be one function containing two, so the seam stays
19-//! where the SQL puts it.
20 //!16 //!
21-//! Everything here writes counters the way [`crate::db::cap`] does — a17+//! Every invariant is one Postgres statement or one row lock, in the shapes
22-//! single-record conditional `UPDATE`, never a count-then-write — and every18+//! [`crate::db::cap`] documents: the class counter is claimed by a conditional
23-//! `??` is parenthesized, because `n ?? 0 < $cap` parses as `n ?? (0 < $cap)`19+//! `UPDATE` fused with the link's `INSERT` (one CTE — a refused insert takes
24-//! and is truthy for every row.20+//! its own seat bump back), a duplicate is the link table's natural composite
25-21+//! primary key answering as `23505`, a gone parent is a real `FOREIGN KEY`
26-use surrealdb::types::{RecordId, SurrealValue, Value};22+//! answering as `23503`, and the row locks (`FOR KEY SHARE` / `FOR NO KEY
27-23+//! UPDATE`) put each transaction on the very record a racing writer must
28-use crate::constant::{24+//! touch. A refusal is an early `Err` (or an `Ok` verdict) from the
29- CLASS_COURSE_COUNT_FIELD, CLASS_COURSE_TABLE, CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE,25+//! [`crate::database::tx_with_retry`] closure — a decision, never a retry.
30- ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS,26+
31-};27+use sqlx::postgres::PgConnection;
32-use crate::database::{Database, transaction_with_retry};28+
29+use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
30+use crate::database::{Database, foreign_key_violation, tx_with_retry, unique_violation};
33 use crate::db::cap;31 use crate::db::cap;
34-use crate::db::class_group;32+use crate::domain::class_blueprint::ClassBlueprintId;
33+use crate::domain::class_course::ClassCourse;
35 use crate::domain::class_group::ClassGroupId;34 use crate::domain::class_group::ClassGroupId;
35+use crate::domain::class_member::ClassMember;
36+use crate::domain::course::CourseId;
37+use crate::domain::role::Role;
38+use crate::domain::timestamp::Timestamp;
39+use crate::domain::user::UserId;
36 use crate::error::AppError;40 use crate::error::AppError;
37 41
38-/// The `THROW` markers [`attach`] aborts with. `FULL_MARK` and `MISSING_MARK`42+/// What [`attach_course`]'s attach settled. The caller answers each verdict —
39-/// are *prefixes*: the record id of the course the loop stopped on is appended43+/// a hand attach turns them into this route's errors; a blueprint pump reads
40-/// to them, because neither "the class does not fit" nor "that course is gone"44+/// them and carries on ([`crate::domain::class_blueprint`]).
41-/// is answerable without naming the course, and the loop only learns which one
42-/// at runtime. The whole id and not just the key, so the refusal names
43-/// something a caller can look up without knowing which table it came from.
44-///
45-/// `MISSING_MARK` is deliberately not `FULL_MARK`: a seat claim that matches
46-/// nothing means "full" *or* "no such row", and reporting a class-course link
47-/// left pointing at a deleted course as a full course sends the caller to raise
48-/// a capacity that does not exist, on a class every member add now fails on.
49-///
50-/// `CAP_MARK` is the class counter's claim matching nothing, which is "the
51-/// class is full" *or* "the class is gone" — one conditional write cannot say
52-/// which, so it stays one marker and the read that tells them apart is paid for
53-/// only on that path (the same shape as
54-/// [`crate::db::enrollment::enroll`]). It is not `GONE_MARK`:
55-/// that one is the *pivot* claim, which is a different row.
56-///
57-/// `OVER_MARK` is the *other* axis already standing above its own ceiling —
58-/// which no claim on this axis can see, and which is what bounds this
59-/// transaction's write loop (see [`Axis::cap`]). It is its own marker because
60-/// "this class holds too many courses" is not an answer anyone can act on when
61-/// it is reported as "this class holds too many students".
62-///
63-/// `SOURCE_MARK` is the record that *asked* for this attach — a grade blueprint
64-/// — being gone by the time the transaction runs. It is the only marker a
65-/// caller opts into (only a sourced attach states the claim), and it exists
66-/// because a blueprint's delete sweeps by that tag: a row landing after the
67-/// sweep would carry the name of a template no sweep can ever reach again.
68-const HELD_MARK: &str = "class_held";
69-const GONE_MARK: &str = "class_gone";
70-const CAP_MARK: &str = "class_cap";
71-const OVER_MARK: &str = "class_over";
72-const SOURCE_MARK: &str = "class_no_blueprint";
73-const FULL_MARK: &str = "class_full:";
74-const MISSING_MARK: &str = "class_no_course:";
75-
76-/// An in-transaction existence claim as its own two statements: read `read`
77-/// into `$name`, and abort with `mark` when it matched nothing.
78-///
79-/// Two statements and not one string, because [`attach`] takes the `CREATE`'s
80-/// result slot off the *length* of its statement list — a pair returned as one
81-/// element would count as one slot and silently read the wrong result back.
82-fn claim(name: &str, read: &str, mark: &str) -> Vec<String> {
83- vec![
84- format!("LET ${name} = ({read})"),
85- format!("IF array::len(${name}) = 0 {{ THROW '{mark}' }}"),
86- ]
87-}
88-
89-/// What [`attach`] settled.
90 #[derive(Debug)]45 #[derive(Debug)]
91 pub(crate) enum Attached<T> {46 pub(crate) enum Attached<T> {
92 /// The link row, the counter and every enrollment it implied committed47 /// The link row, the counter and every enrollment it implied committed
@@ -103,11 +58,10 @@ pub(crate) enum Attached<T> {
103 /// between them names the wrong one half the time.58 /// between them names the wrong one half the time.
104 ///59 ///
105 /// On the **member** axis the pivot is the student, and this means their60 /// On the **member** axis the pivot is the student, and this means their
106- /// row is gone *or* their role no longer is `student`61+ /// row is gone *or* their role no longer is `student`. Its one caller
107- /// ([`Axis::pivot_claim`]). Its one caller answers that as the `400` the62+ /// answers that as the `400` the route's own read already answers, never
108- /// route's own read already answers, never as [`Attached::refusal_code`]'s63+ /// as [`Attached::refusal_code`]'s `course_deleted` — which is the course
109- /// `course_deleted` — which is the course axis's word for it and would name64+ /// axis's word for it and would name a record this refusal is not about.
110- /// a record this refusal is not about.
111 PivotGone,65 PivotGone,
112 /// The class is at its own ceiling on this axis. Nothing was written, and66 /// The class is at its own ceiling on this axis. Nothing was written, and
113 /// it is told apart from [`Attached::Gone`] because a full class is a67 /// it is told apart from [`Attached::Gone`] because a full class is a
@@ -147,16 +101,14 @@ impl<T> Attached<T> {
147 /// one cause can never grow two codes.101 /// one cause can never grow two codes.
148 ///102 ///
149 /// Each code names the record that actually failed. The two "gone" answers103 /// Each code names the record that actually failed. The two "gone" answers
150- /// are a *class* delete ([`Attached::Gone`] → `class_deleted`, the class104+ /// are a *class* delete ([`Attached::Gone`] → `class_deleted`) and a
151- /// counter's claim matching nothing on a row a re-read no longer finds) and105+ /// *course* delete ([`Attached::PivotGone`] → `course_deleted`) — and
152- /// a *course* delete ([`Attached::PivotGone`] → `course_deleted`, the106+ /// telling a manager the class vanished when the course did sends them to
153- /// course's own claim matching nothing) — and telling a manager the class107+ /// look at a section that is standing right there. `linked_course_missing`
154- /// vanished when the course did sends them to look at a section that is108+ /// is a third: *another* course already attached to this class no longer
155- /// standing right there. `linked_course_missing` is a third: *another*109+ /// exists, and it must be detached before this attach can be retried.
156- /// course already attached to this class no longer exists, and it must be110+ /// `blueprint_deleted` is a pump losing the template itself mid-run — the
157- /// detached before this attach can be retried. `blueprint_deleted` is a111+ /// only refusal that says nothing about the (class, course) pair it names.
158- /// pump losing the template itself mid-run — the only refusal that says
159- /// nothing about the (class, course) pair it names.
160 ///112 ///
161 /// The `axis` is a parameter because two of these answers name a *different113 /// The `axis` is a parameter because two of these answers name a *different
162 /// ceiling* on each of them: [`Attached::ClassFull`] is the ceiling of the114 /// ceiling* on each of them: [`Attached::ClassFull`] is the ceiling of the
@@ -182,6 +134,7 @@ impl<T> Attached<T> {
182 /// Which way the pump runs: the loop below needs a `(course, user)` pair per134 /// Which way the pump runs: the loop below needs a `(course, user)` pair per
183 /// enrollment, and each caller supplies one side as a constant and reads the135 /// enrollment, and each caller supplies one side as a constant and reads the
184 /// other off the class's *other* link table.136 /// other off the class's *other* link table.
137+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185 pub(crate) enum Axis {138 pub(crate) enum Axis {
186 /// A student joining: the courses come from `class_course`.139 /// A student joining: the courses come from `class_course`.
187 Member,140 Member,
@@ -190,122 +143,36 @@ pub(crate) enum Axis {
190 }143 }
191 144
192 impl Axis {145 impl Axis {
193- /// The `SELECT` that yields this run's `(course, user)` pairs, with `$pivot`
194- /// bound to the fixed side. In-crate text, never client input.
195- fn pairs(&self) -> String {
196- match self {
197- Axis::Member => format!(
198- "SELECT VALUE {{ course: course, user: $pivot }} \
199- FROM {CLASS_COURSE_TABLE} WHERE class = $class"
200- ),
201- Axis::Course => format!(
202- "SELECT VALUE {{ course: $pivot, user: user }} \
203- FROM {CLASS_MEMBER_TABLE} WHERE class = $class"
204- ),
205- }
206- }
207-
208- /// The enrollment rows a *detached* link of this axis is responsible for,
209- /// as a `WHERE` fragment over `enrollment`. Read off the deleted link row
210- /// rather than a bound parameter, so one loop serves a single detach and a
211- /// user's whole membership alike.
212- fn scope(&self) -> &'static str {
213- match self {
214- Axis::Member => "user = $link.user",
215- Axis::Course => "course = $link.course",
216- }
217- }
218-
219- /// The in-transaction proof that this axis's *pivot* row is still there,
220- /// as the statements that claim it.
221- ///
222- /// The class counter's conditional claim covers the class; nothing covered
223- /// the course. With an empty roster the pair loop in [`attach`] touches no
224- /// row at all, so a concurrent `DELETE /courses/{id}` conflicts with
225- /// nothing — SurrealDB does not conflict-check that (write-skew) — and the
226- /// attach commits a `class_course` row pointing at a course that no longer
227- /// exists. A conditional write on the course row *is* the check: it matches
228- /// nothing once the row is gone, and it puts this transaction on the very
229- /// record the course's delete guard writes.
230- ///
231- /// The counter is *moved* — bumped, gated, then restored to the value this
232- /// transaction found — because re-stating it verbatim claims nothing: an
233- /// `UPDATE` that leaves the document unchanged is elided by SurrealDB 3.2.3
234- /// and never enters the write set, so `count = count` sat on no key at all
235- /// and a concurrent `DELETE /courses/{id}` committed beside it with both
236- /// callers told OK (measured on 3.2.3, counter present and absent alike).
237- /// Same shape as [`crate::db::exam_answer::save`]: the
238- /// restore is by captured value, `NONE` included, so the row is
239- /// byte-identical afterwards and the boot backfill still sees the `NONE` it
240- /// seeds off. Both statements are inside the transaction, so an abort
241- /// between them cannot leave a course counting a seat nobody took.
242- ///
243- /// The member axis moves a counter on the *user* row for the same reason in
244- /// a different key ([`cap::role_claim`]): a role change away from `student`
245- /// sweeps this class membership and every enrollment it pumped, on a
246- /// snapshot, so a join landing after that snapshot leaves a non-student on
247- /// a roster — counted against the class's delete guard — with nothing left
248- /// to re-sweep. Its refusal is [`Attached::PivotGone`] like the course
249- /// axis's, because both mean "the row this link hangs off may no longer
250- /// carry it".
251- fn pivot_claim(&self) -> Vec<String> {
252- match self {
253- Axis::Member => cap::role_claim(
254- "pivot",
255- &format!("!= '{}'", crate::domain::role::Role::Student.as_str()),
256- GONE_MARK,
257- ),
258- Axis::Course => {
259- let mut claimed = vec![format!(
260- "LET $was_alive = (SELECT VALUE {ENROLLMENT_COUNT_FIELD} FROM ONLY $pivot)"
261- )];
262- claimed.extend(claim(
263- "alive",
264- &format!(
265- "UPDATE $pivot SET {ENROLLMENT_COUNT_FIELD} = \
266- ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id"
267- ),
268- GONE_MARK,
269- ));
270- claimed.push(format!(
271- "UPDATE $pivot SET {ENROLLMENT_COUNT_FIELD} = $was_alive"
272- ));
273- claimed
274- }
275- }
276- }
277-
278 /// The class counter this axis's link rows are counted on. Taken off the146 /// The class counter this axis's link rows are counted on. Taken off the
279 /// axis rather than passed in beside it, because the two are one fact and a147 /// axis rather than passed in beside it, because the two are one fact and a
280 /// call site that paired the member axis with the course counter would148 /// call site that paired the member axis with the course counter would
281- /// compile, pass every test — both are `&str` — and desync the class delete149+ /// compile, pass every test — both are `&'static str` — and desync the
282- /// guard forever.150+ /// class delete guard forever.
283- fn counter(&self) -> &'static str {151+ fn counter(self) -> &'static str {
284 match self {152 match self {
285- Axis::Member => CLASS_MEMBER_COUNT_FIELD,153+ Axis::Member => "class_member_count",
286- Axis::Course => CLASS_COURSE_COUNT_FIELD,154+ Axis::Course => "class_course_count",
287 }155 }
288 }156 }
289 157
290- /// How many link rows this axis's counter may reach. Taken off the axis158+ /// How many link rows this axis's counter may reach.
291- /// beside the counter it bounds, for the same reason.
292 ///159 ///
293- /// This is what makes the pair loop in [`attach`] finite, and it does it160+ /// This is what makes the pair loop in [`add_member`]/[`attach_course`]
294- /// *crosswise*: the member axis's loop iterates the class's `class_course`161+ /// finite, and it does it *crosswise*: the member axis's loop iterates the
295- /// rows, which the course axis's counter caps, and the course axis's loop162+ /// class's `class_course` rows, which the course axis's counter caps, and
296- /// iterates its `class_member` rows, which the member axis's counter caps.163+ /// the course axis's loop iterates its `class_member` rows, which the
297- /// So bounding the two counters bounds both write loops — one transaction164+ /// member axis's counter caps. So bounding the two counters bounds both
298- /// can never carry more than `MAX_CLASS_MEMBERS`/`MAX_CLASS_COURSES`165+ /// write loops — one transaction can never carry more than
299- /// enrollment writes.166+ /// `MAX_CLASS_MEMBERS`/`MAX_CLASS_COURSES` enrollment writes.
300 ///167 ///
301 /// Crosswise is also why the claim alone is not enough. It bounds the axis168 /// Crosswise is also why the claim alone is not enough. It bounds the axis
302 /// being *added*, and the loop it runs is the length of the *other* one: a169 /// being *added*, and the loop it runs is the length of the *other* one: a
303 /// class that already holds more members than `MAX_CLASS_MEMBERS` — the170 /// class that already holds more members than `MAX_CLASS_MEMBERS` — the
304 /// layer shipped before either ceiling existed, so a real volume can carry171 /// layer shipped before either ceiling existed, so a real volume can carry
305 /// one — could still have a course attached, and that attach writes one172 /// one — could still have a course attached, and that attach writes one
306- /// enrollment per member. So [`attach`] checks the other axis too173+ /// enrollment per member. So the attach checks the other axis too
307 /// ([`Axis::other`]), and the bound holds for stale classes as well.174 /// ([`Axis::other`]), and the bound holds for stale classes as well.
308- fn cap(&self) -> i64 {175+ fn cap(self) -> i64 {
309 match self {176 match self {
310 Axis::Member => MAX_CLASS_MEMBERS,177 Axis::Member => MAX_CLASS_MEMBERS,
311 Axis::Course => MAX_CLASS_COURSES,178 Axis::Course => MAX_CLASS_COURSES,
@@ -315,7 +182,7 @@ impl Axis {
315 /// The refusal code for "the class is *at* this axis's ceiling"182 /// The refusal code for "the class is *at* this axis's ceiling"
316 /// ([`Attached::ClassFull`]), taken off the axis beside the `cap` it183 /// ([`Attached::ClassFull`]), taken off the axis beside the `cap` it
317 /// reports, because that ceiling and its name are one fact.184 /// reports, because that ceiling and its name are one fact.
318- fn at_ceiling_code(&self) -> &'static str {185+ fn at_ceiling_code(self) -> &'static str {
319 match self {186 match self {
320 Axis::Member => "class_at_roster_ceiling",187 Axis::Member => "class_at_roster_ceiling",
321 Axis::Course => "class_at_course_ceiling",188 Axis::Course => "class_at_course_ceiling",
@@ -327,7 +194,7 @@ impl Axis {
327 /// may be ([`Attached::ClassOverloaded`]). Answered off the axis that is194 /// may be ([`Attached::ClassOverloaded`]). Answered off the axis that is
328 /// over, never the one being attached — the two are always different axes,195 /// over, never the one being attached — the two are always different axes,
329 /// which is exactly what the blind version got wrong.196 /// which is exactly what the blind version got wrong.
330- fn over_ceiling_code(&self) -> &'static str {197+ fn over_ceiling_code(self) -> &'static str {
331 match self {198 match self {
332 Axis::Member => "class_roster_too_large",199 Axis::Member => "class_roster_too_large",
333 Axis::Course => "class_course_list_too_large",200 Axis::Course => "class_course_list_too_large",
@@ -337,7 +204,7 @@ impl Axis {
337 /// The axis whose link rows this one's write loop iterates — its counter is204 /// The axis whose link rows this one's write loop iterates — its counter is
338 /// the length of that loop, and its ceiling is therefore the second half of205 /// the length of that loop, and its ceiling is therefore the second half of
339 /// the bound.206 /// the bound.
340- fn other(&self) -> Axis {207+ fn other(self) -> Axis {
341 match self {208 match self {
342 Axis::Member => Axis::Course,209 Axis::Member => Axis::Course,
343 Axis::Course => Axis::Member,210 Axis::Course => Axis::Member,
@@ -345,338 +212,689 @@ impl Axis {
345 }212 }
346 }213 }
347 214
348-// The sweep a role change *off* `student` owes — every class membership (each215+/// The pivot of an attach: the row the link hangs off on its own axis, which
349-// class getting its member count back) and every enrollment row (each course216+/// must still be there — and, on the member axis, still name a `student` —
350-// getting its seat back) — is two of the arms of217+/// when the transaction runs.
351-// [`crate::service::user::set_role`], because it belongs in the same218+enum Pivot<'a> {
352-// transaction as the role write that invalidates them. It stays one fact with219+ User(&'a UserId),
353-// the counters either way: released separately, a failure between the halves220+ Course(&'a CourseId),
354-// left enrollment rows tagged `source = class_group:X` while the class had its221+}
355-// counters back, so the class passed its zero-zero delete guard and the rows
356-// were left pointing at a class no sweep could ever reach again.
357 222
358-/// Write `link` and enroll everything it implies, or write nothing at all.223+/// The verdicts the shared prechecks can settle before any counter moves.
359-///224+enum Early {
360-/// The order is the one [`cap::claim_and_create`] settled on and for the same225+ Duplicate,
361-/// reason: the link is looked for *before* any counter moves, so "you are226+ SourceGone,
362-/// already in" outranks "there is no room" — a caller whose row a rival placed227+ PivotGone,
363-/// a moment ago must not be told a course is full about seats they already228+ Overloaded,
364-/// hold.229+}
365-///230+
366-/// The class counter is claimed by a conditional write rather than a bare231+fn refusal_of<T>(early: Early) -> Attached<T> {
367-/// increment, so a class deleted out from under this run matches nothing and232+ match early {
368-/// the whole cascade aborts: [`Attached::Gone`] instead of a counter on a row233+ Early::Duplicate => Attached::Duplicate,
369-/// that no longer exists. The same write carries the axis's [`Axis::cap`],234+ Early::SourceGone => Attached::SourceGone,
370-/// which is what keeps the pair loop below — and therefore this transaction —235+ Early::PivotGone => Attached::PivotGone,
371-/// finite: [`Attached::ClassFull`] once the class is at its ceiling.236+ Early::Overloaded => Attached::ClassOverloaded,
372-///237+ }
373-/// Every enrollment in the loop is *skipped* when the pair already has a row —238+}
374-/// no seat charged, and the existing row's `source` left exactly as it was, so239+
375-/// a hand-placed student is never quietly adopted by a class. Only the pairs240+/// The gates that run before any counter moves, in the order their answers
376-/// that had no row at all are charged, each against its own course's capacity.241+/// outrank each other:
377-///
378-/// On admissibility ([`crate::database::transaction_with_retry`]): every
379-/// `CREATE` here is preceded by its own in-transaction existence check, so an
380-/// "already exists" can only come from a rival that landed inside that window —
381-/// and re-sending the whole cascade then *sees* the row and takes the other
382-/// branch. The retry converges instead of re-asking a settled question, which
383-/// is the restriction's actual test.
384 ///242 ///
385-/// `source` is the record whose behalf this attach runs on — a grade blueprint243+/// 1. **Duplicate** — "you are already in" outranks "there is no room": a
386-/// — and supplying it adds one more claim: that it is still there when the244+/// caller whose row a rival placed a moment ago must not be told a course
387-/// transaction runs ([`Attached::SourceGone`]). A hand attach owns itself and245+/// is full about seats they already hold. (The link table's own primary key
388-/// passes `None`.246+/// re-answers this below as `23505` for a rival landing inside the window —
389-pub(crate) async fn attach<T: SurrealValue + Clone>(247+/// same verdict, no second seat.)
390- db: &Database,248+/// 2. **Source** — the blueprint that asked for this attach is still there. A
249+/// `FOR KEY SHARE` row lock on the blueprint row: it serializes the attach
250+/// against the blueprint's own delete — the closure the old process-wide
251+/// lease provided, now on the row itself. A concurrent blueprint `DELETE`
252+/// waits behind it and its sweep finds the committed row, while an attach
253+/// starting after the delete finds no row and writes nothing. `KEY SHARE`
254+/// is the weakest strength that blocks the delete, so two sourced attaches
255+/// still run concurrently, exactly as they did under the old shared read
256+/// lease.
257+/// 3. **Pivot** — the member axis takes the [`cap` role-claim
258+/// recipe](crate::db::cap)'s `FOR NO KEY UPDATE` handshake on the user row:
259+/// a role change away from `student` sweeps this membership, and demotion
260+/// and join now serialize on that row lock in both directions. The course
261+/// axis takes a `FOR KEY SHARE` on the course row, which a concurrent
262+/// course delete cannot take — the old bump-and-restore existence proof,
263+/// now a plain lock.
264+/// 4. **Overloaded** — the *other* axis standing above its own ceiling, which
265+/// no claim on this axis can see, and which is what bounds this
266+/// transaction's write loop.
267+async fn early_verdicts(
268+ tx: &mut PgConnection,
391 class: &ClassGroupId,269 class: &ClassGroupId,
392 axis: Axis,270 axis: Axis,
393- new: (&RecordId, &T),271+ pivot: Pivot<'_>,
394- pivot: RecordId,272+ source: Option<&ClassBlueprintId>,
395- by: RecordId,273+) -> Result<Option<Early>, AppError> {
396- source: Option<RecordId>,274+ let held = match pivot {
397-) -> Result<Attached<T>, AppError> {275+ Pivot::User(user) => sqlx::query_scalar!(
398- let (link, row) = new;276+ r#"SELECT 1 AS "one" FROM class_member WHERE class = $1 AND app_user = $2"#,
399- let count_field = axis.counter();277+ class as _,
400- let pairs = axis.pairs();278+ user as _
401- let other = axis.other();279+ )
402- let over_field = other.counter();280+ .fetch_optional(tx)
403- // One statement per element, because the `CREATE`'s result slot is this281+ .await?
404- // list's own length at the moment it is pushed. It used to be a282+ .is_some(),
405- // hand-counted constant with a case per optional claim, and only the path283+ Pivot::Course(course) => sqlx::query_scalar!(
406- // carrying that claim would ever have paid for a miscount.284+ r#"SELECT 1 AS "one" FROM class_course WHERE class = $1 AND course = $2"#,
407- let mut statements = vec![285+ class as _,
408- "BEGIN TRANSACTION".to_string(),286+ course as _
409- "LET $held = (SELECT VALUE id FROM $link)".to_string(),287+ )
410- format!("IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}"),288+ .fetch_optional(tx)
411- ];289+ .await?
412- if source.is_some() {290+ .is_some(),
413- statements.extend(claim("source", "SELECT VALUE id FROM $guard", SOURCE_MARK));291+ };
414- }292+ if held {
415- statements.extend(axis.pivot_claim());293+ return Ok(Some(Early::Duplicate));
416- // Read off the class row inside the transaction that claims it, so the
417- // count this refuses on is the one the pair loop below would iterate.
418- statements.push(format!(
419- "LET $over = (SELECT VALUE id FROM $class WHERE ({over_field} ?? 0) > $other_cap)"
420- ));
421- statements.push(format!(
422- "IF array::len($over) > 0 {{ THROW '{OVER_MARK}' }}"
423- ));
424- statements.push(format!(
425- "LET $counted = (UPDATE $class SET {count_field} = ({count_field} ?? 0) + 1 \
426- WHERE ({count_field} ?? 0) < $class_cap RETURN VALUE id)"
427- ));
428- statements.push(format!(
429- "IF array::len($counted) = 0 {{ THROW '{CAP_MARK}' }}"
430- ));
431- // Taken as it is pushed: this is the slot the link row comes back out of.
432- let made = statements.len();
433- statements.push("CREATE $link CONTENT $row".to_string());
434- statements.push(format!(
435- "FOR $pair IN (({pairs}) ?? []) {{
436- LET $seat_of = type::record('{ENROLLMENT_TABLE}', string::concat(
437- record::id($pair.course), '_', record::id($pair.user)));
438- IF array::len((SELECT VALUE id FROM $seat_of)) = 0 {{
439- IF array::len((SELECT VALUE id FROM $pair.course)) = 0 {{
440- THROW '{MISSING_MARK}' + <string>$pair.course
441- }};
442- LET $seat = (UPDATE $pair.course SET {ENROLLMENT_COUNT_FIELD} = \
443- ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 \
444- WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) < (capacity ?? $unlimited) \
445- RETURN VALUE id);
446- IF array::len($seat) = 0 {{
447- THROW '{FULL_MARK}' + <string>$pair.course
448- }};
449- CREATE $seat_of CONTENT {{ course: $pair.course, user: $pair.user, \
450- enrolled_by: $by, source: $class }};
451- }};
452- }}"
453- ));
454- statements.push("COMMIT TRANSACTION".to_string());
455- let sql = format!("{};", statements.join(";\n"));
456- let mut bindings = vec![
457- ("class".into(), class.record().into_value()),
458- ("link".into(), link.clone().into_value()),
459- ("row".into(), row.clone().into_value()),
460- ("pivot".into(), pivot.into_value()),
461- ("by".into(), by.into_value()),
462- ("unlimited".into(), cap::UNLIMITED.into_value()),
463- ("class_cap".into(), axis.cap().into_value()),
464- ("other_cap".into(), other.cap().into_value()),
465- ];
466- if let Some(guard) = source {
467- bindings.push(("guard".into(), guard.into_value()));
468- }
469- let (mut result, mut errors) = transaction_with_retry(
470- db,
471- &sql,
472- &bindings,
473- &[
474- HELD_MARK,
475- GONE_MARK,
476- OVER_MARK,
477- SOURCE_MARK,
478- CAP_MARK,
479- FULL_MARK,
480- MISSING_MARK,
481- ],
482- )
483- .await?;
484- // "Already linked" is read first: it outranks both refusals below, and the
485- // gate aborts before either could fire.
486- //
487- // Only the `THROW` is read, never an `is_already_exists` off the `CREATE`
488- // itself. A rival landing in the window between the gate and the create
489- // makes the store answer "already exists", which
490- // [`transaction_with_retry`] treats as a lost round and re-sends — and that
491- // re-send is the right answer, because the second pass *sees* the row at
492- // the gate. Reading it here would also mis-file the enrollment `CREATE`'s
493- // version of the same answer as "already in this class".
494- if errors
495- .values()
496- .any(|error| error.to_string().contains(HELD_MARK))
497- {
498- return Ok(Attached::Duplicate);
499- }
500- // The blueprint that asked for this attach is gone, and that outranks every
501- // refusal below it: none of them is an answer anyone can act on once the
502- // template that wanted the row has been deleted — and its claim stands
503- // first in the transaction, so it aborts before they could fire anyway.
504- if errors
505- .values()
506- .any(|error| error.to_string().contains(SOURCE_MARK))
507- {
508- return Ok(Attached::SourceGone);
509- }
510- if errors
511- .values()
512- .any(|error| error.to_string().contains(GONE_MARK))
513- {
514- return Ok(Attached::PivotGone);
515- }
516- // Read before the ceiling below: a class over the *other* axis's ceiling is
517- // refused whether or not this axis has room, and being told it is full on
518- // an axis with places left is an answer nobody can act on.
519- if errors
520- .values()
521- .any(|error| error.to_string().contains(OVER_MARK))
522- {
523- return Ok(Attached::ClassOverloaded);
524- }
525- // Full, or the class is gone — the counter claim matches nothing either
526- // way, and only this path pays for the read that tells them apart.
527- if errors
528- .values()
529- .any(|error| error.to_string().contains(CAP_MARK))
530- {
531- return Ok(match class_group::read(db, class).await? {
532- Some(_) => Attached::ClassFull,
533- None => Attached::Gone,
534- });
535- }
536- // The stale link is read before "full": both come out of the same seat
537- // claim matching nothing, and only one of them is a capacity problem.
538- if let Some(course) = errors
539- .values()
540- .find_map(|error| named_course(&error.to_string(), MISSING_MARK))
541- {
542- return Ok(Attached::CourseGone(course));
543 }294 }
544- if let Some(course) = errors295+ if let Some(source) = source {
545- .values()296+ let alive = sqlx::query_scalar!(
546- .find_map(|error| named_course(&error.to_string(), FULL_MARK))297+ r#"SELECT 1 AS "one" FROM class_blueprint WHERE grade = $1 FOR KEY SHARE"#,
547- {298+ source as _
548- return Ok(Attached::Full(course));299+ )
300+ .fetch_optional(tx)
301+ .await?
302+ .is_some();
303+ if !alive {
304+ return Ok(Some(Early::SourceGone));
305+ }
549 }306 }
550- if let Some(error) = errors.drain().map(|(_, error)| error).next() {307+ match pivot {
551- return Err(error.into());308+ Pivot::User(user) => {
309+ let row = sqlx::query!(
310+ r#"SELECT role AS "role: Role" FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#,
311+ user as _
312+ )
313+ .fetch_optional(tx)
314+ .await?;
315+ if row.map(|row| row.role) != Some(Role::Student) {
316+ return Ok(Some(Early::PivotGone));
317+ }
318+ }
319+ Pivot::Course(course) => {
320+ let alive = sqlx::query_scalar!(
321+ r#"SELECT 1 AS "one" FROM course WHERE id = $1 FOR KEY SHARE"#,
322+ course as _
323+ )
324+ .fetch_optional(tx)
325+ .await?
326+ .is_some();
327+ if !alive {
328+ return Ok(Some(Early::PivotGone));
329+ }
330+ }
552 }331 }
553- result332+ // Read off the class row inside the transaction that claims it, so the
554- .take::<Vec<T>>(made)?333+ // count this refuses on is the one the pair loop below would iterate.
334+ let over = match axis.other() {
335+ Axis::Member => sqlx::query_scalar!(
336+ r#"SELECT 1 AS "one" FROM class_group
337+ WHERE id = $1 AND class_member_count > $2"#,
338+ class as _,
339+ Axis::Member.cap(),
340+ )
341+ .fetch_optional(tx)
342+ .await?
343+ .is_some(),
344+ Axis::Course => sqlx::query_scalar!(
345+ r#"SELECT 1 AS "one" FROM class_group
346+ WHERE id = $1 AND class_course_count > $2"#,
347+ class as _,
348+ Axis::Course.cap(),
349+ )
350+ .fetch_optional(tx)
351+ .await?
352+ .is_some(),
353+ };
354+ Ok(over.then_some(Early::Overloaded))
355+}
356+
357+/// Write the member link and enroll the student into every course the class is
358+/// already attached to, or write nothing at all.
359+///
360+/// A student already enrolled in one of those courses keeps the row they
361+/// have — no seat is charged, and the existing row's `source` is left exactly
362+/// as it was, so a hand-placed student is never quietly adopted by a class.
363+/// A course with no free seat refuses the *whole* join rather than half of it.
364+///
365+/// The class counter is claimed by the conditional half of the CTE below
366+/// rather than a bare increment, so a class deleted out from under this run
367+/// matches nothing and the whole cascade aborts: [`Attached::Gone`] instead of
368+/// a counter on a row that no longer exists. The same write carries
369+/// [`Axis::Member`]'s cap, which is what keeps the pair loop — and therefore
370+/// this transaction — finite: [`Attached::ClassFull`] once the class is at its
371+/// ceiling. Claim and insert are one statement, so a refused insert takes its
372+/// own seat bump back.
373+pub(crate) async fn add_member(
374+ db: &Database,
375+ class: &ClassGroupId,
376+ user: &UserId,
377+ by: &UserId,
378+) -> Result<Attached<ClassMember>, AppError> {
379+ let added_at = Timestamp::now();
380+ tx_with_retry(db, false, async |tx| {
381+ if let Some(early) =
382+ early_verdicts(tx, class, Axis::Member, Pivot::User(user), None).await?
383+ {
384+ return Ok(refusal_of(early));
385+ }
386+ // The claim and the link are one statement (the cap recipe's CTE): the
387+ // conditional `UPDATE` on the class row gates the `INSERT`, so a full
388+ // or gone class writes nothing at all.
389+ let inserted = match sqlx::query_scalar!(
390+ r#"WITH seat AS (
391+ UPDATE class_group SET class_member_count = class_member_count + 1
392+ WHERE id = $1 AND class_member_count < $2
393+ RETURNING 1)
394+ INSERT INTO class_member (class, app_user, added_by, added_at)
395+ SELECT $1, $3, $4, $5 WHERE EXISTS (SELECT 1 FROM seat)
396+ RETURNING 1 AS "one""#,
397+ class as _,
398+ Axis::Member.cap(),
399+ user as _,
400+ by as _,
401+ added_at as _
402+ )
403+ .execute(tx)
404+ .await
405+ {
406+ Ok(result) => result,
407+ // A rival landed in the window between the gate and the insert:
408+ // the link table's own primary key answers, same verdict as the
409+ // gate, no second seat.
410+ Err(e) if unique_violation(&e) == Some("class_member_class_user") => {
411+ return Ok(Attached::Duplicate);
412+ }
413+ // The student row vanished mid-run despite the locked pivot claim.
414+ Err(e) if foreign_key_violation(&e) => return Ok(Attached::PivotGone),
415+ Err(e) => return Err(e.into()),
416+ };
417+ if inserted.rows_affected() == 0 {
418+ // Full, or the class is gone — the claim matches nothing either
419+ // way, and only this path pays for the read that tells them apart.
420+ let standing = sqlx::query_scalar!(
421+ r#"SELECT 1 AS "one" FROM class_group WHERE id = $1"#,
422+ class as _
423+ )
424+ .fetch_optional(&mut *tx)
425+ .await?
426+ .is_some();
427+ return Ok(if standing {
428+ Attached::ClassFull
429+ } else {
430+ Attached::Gone
431+ });
432+ }
433+ let courses: Vec<uuid::Uuid> = sqlx::query_scalar!(
434+ r#"SELECT course AS "course: uuid::Uuid" FROM class_course WHERE class = $1"#,
435+ class as _
436+ )
437+ .fetch_all(&mut *tx)
438+ .await?
555 .into_iter()439 .into_iter()
556- .next()440+ .map(|row| row.course)
557- .map(Attached::Made)441+ .collect();
558- .ok_or_else(|| AppError::Internal("the class pump wrote no link row".into()))442+ let pairs = courses.into_iter().map(|course| (course, user.uuid()));
443+ match enroll_pairs(tx, class, pairs, by).await? {
444+ Sweep::Done => {}
445+ Sweep::CourseGone(course) => return Ok(Attached::CourseGone(course)),
446+ Sweep::Full(course) => return Ok(Attached::Full(course)),
447+ }
448+ Ok(Attached::Made(ClassMember {
449+ class: class.clone(),
450+ user: *user,
451+ added_by: *by,
452+ added_at: Some(added_at),
453+ }))
454+ })
455+ .await
559 }456 }
560 457
561-/// The course id out of a `<mark><table>:<key>` abort. Table names and the458+/// Write the course link and enroll the class's whole roster into it, or
562-/// generated ULID keys here are alphanumeric and `:` joins them, so the id ends459+/// write nothing at all.
563-/// where the store's own wrapping around the thrown text begins.460+///
564-fn named_course(message: &str, mark: &str) -> Option<String> {461+/// Students already in the course keep the rows they have — no seat charged,
565- let id: String = message462+/// `source` untouched — and a roster that does not fit refuses the whole
566- .split_once(mark)?463+/// attach rather than filling the course to its cap and stopping.
567- .1464+///
568- .chars()465+/// `source` is the blueprint whose behalf this attach runs on, and supplying
569- .take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | ':'))466+/// it adds one more claim: that it is still there when the transaction runs
467+/// ([`Attached::SourceGone`]) — the `FOR KEY SHARE` lock that serializes this
468+/// transaction against the blueprint's own delete. A hand attach owns itself
469+/// and passes `None`.
470+pub(crate) async fn attach_course(
471+ db: &Database,
472+ class: &ClassGroupId,
473+ course: &CourseId,
474+ by: &UserId,
475+ source: Option<&ClassBlueprintId>,
476+) -> Result<Attached<ClassCourse>, AppError> {
477+ let attached_at = Timestamp::now();
478+ tx_with_retry(db, false, async |tx| {
479+ if let Some(early) =
480+ early_verdicts(tx, class, Axis::Course, Pivot::Course(course), source).await?
481+ {
482+ return Ok(refusal_of(early));
483+ }
484+ let inserted = match sqlx::query_scalar!(
485+ r#"WITH seat AS (
486+ UPDATE class_group SET class_course_count = class_course_count + 1
487+ WHERE id = $1 AND class_course_count < $2
488+ RETURNING 1)
489+ INSERT INTO class_course (class, course, attached_by, attached_at, source)
490+ SELECT $1, $3, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat)
491+ RETURNING 1 AS "one""#,
492+ class as _,
493+ Axis::Course.cap(),
494+ course as _,
495+ by as _,
496+ attached_at as _,
497+ source as _
498+ )
499+ .execute(tx)
500+ .await
501+ {
502+ Ok(result) => result,
503+ Err(e) if unique_violation(&e) == Some("class_course_class_course") => {
504+ return Ok(Attached::Duplicate);
505+ }
506+ Err(e) if foreign_key_violation(&e) => return Ok(Attached::PivotGone),
507+ Err(e) => return Err(e.into()),
508+ };
509+ if inserted.rows_affected() == 0 {
510+ let standing = sqlx::query_scalar!(
511+ r#"SELECT 1 AS "one" FROM class_group WHERE id = $1"#,
512+ class as _
513+ )
514+ .fetch_optional(&mut *tx)
515+ .await?
516+ .is_some();
517+ return Ok(if standing {
518+ Attached::ClassFull
519+ } else {
520+ Attached::Gone
521+ });
522+ }
523+ let members: Vec<uuid::Uuid> = sqlx::query_scalar!(
524+ r#"SELECT app_user AS "app_user: uuid::Uuid" FROM class_member WHERE class = $1"#,
525+ class as _
526+ )
527+ .fetch_all(&mut *tx)
528+ .await?
529+ .into_iter()
530+ .map(|row| row.app_user)
570 .collect();531 .collect();
571- (!id.is_empty()).then_some(id)532+ let pairs = members.into_iter().map(|user| (course.uuid(), user));
533+ match enroll_pairs(tx, class, pairs, by).await? {
534+ Sweep::Done => {}
535+ Sweep::CourseGone(course) => return Ok(Attached::CourseGone(course)),
536+ Sweep::Full(course) => return Ok(Attached::Full(course)),
537+ }
538+ Ok(Attached::Made(ClassCourse {
539+ class: class.clone(),
540+ course: *course,
541+ attached_by: *by,
542+ source: source.cloned(),
543+ attached_at: Some(attached_at),
544+ }))
545+ })
546+ .await
572 }547 }
573 548
574-/// Drop the link rows `links` names, give each class its counter back, and549+/// What the shared enrollment loop settled for its pairs.
575-/// sweep the enrollment rows those links pumped. Answers how many link rows550+enum Sweep {
576-/// went, so a caller whose link was a single pair can turn zero into a 404.551+ /// Every pair holds the row it owes.
552+ Done,
553+ /// One of the pairs' courses is gone, named by its key: a stale link.
554+ CourseGone(String),
555+ /// One of the pairs' courses has no free seat, named by its key.
556+ Full(String),
557+}
558+
559+/// Enroll every `(course, user)` pair that has no row yet, each against its
560+/// own course's capacity, skipping — never charging — the pairs that do.
577 ///561 ///
578-/// The sweep is *repair-first*: an enrollment this class wrote is only deleted562+/// Per pair, in the order the refusals outrank each other: the pair's own row
579-/// once no other class still claims it. Two classes attached to the same course563+/// answers "already enrolled" (skip, no seat); the course row answers "gone"
580-/// share a student — the second attach skipped the row the first had already564+/// *before* the seat claim, so a stale link is never mis-reported as a
581-/// written, so the row carries only the first class's name — and deleting it on565+/// capacity problem; the seat claim is a conditional `UPDATE` on the course
582-/// the first class's way out would unenroll a student the second class is still566+/// row (live cap — `capacity` as it stands at write time, `NULL` reading as
583-/// responsible for. So the row is re-tagged to that rival instead, and only a567+/// unlimited); and the insert rides the seat it claimed. A rival that lands
584-/// row nobody is left to claim is deleted and its seat given back. The heir is568+/// between the gate and the insert answers `23505`, and the bump is given
585-/// the lowest class id among the claimants: a deterministic pick, so a repeat569+/// back before the skip — the outcome a re-sent transaction used to reach by
586-/// of the same sweep lands on the same class.570+/// seeing the rival's row at its gate.
571+///
572+/// Every abort stops the loop inside the caller's transaction: not one of the
573+/// earlier seats in the same run survives, which is the whole point of doing
574+/// this in a transaction.
575+async fn enroll_pairs(
576+ tx: &mut PgConnection,
577+ class: &ClassGroupId,
578+ pairs: impl Iterator<Item = (uuid::Uuid, uuid::Uuid)>,
579+ by: &UserId,
580+) -> Result<Sweep, AppError> {
581+ for (course, user) in pairs {
582+ let held = sqlx::query_scalar!(
583+ r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#,
584+ course,
585+ user
586+ )
587+ .fetch_optional(&mut *tx)
588+ .await?
589+ .is_some();
590+ if held {
591+ continue;
592+ }
593+ let alive = sqlx::query_scalar!(r#"SELECT 1 AS "one" FROM course WHERE id = $1"#, course)
594+ .fetch_optional(&mut *tx)
595+ .await?
596+ .is_some();
597+ if !alive {
598+ return Ok(Sweep::CourseGone(course.to_string()));
599+ }
600+ let seat = sqlx::query_scalar!(
601+ r#"UPDATE course SET enrollment_count = enrollment_count + 1
602+ WHERE id = $1 AND enrollment_count < COALESCE(capacity, $2)
603+ RETURNING 1 AS "one""#,
604+ course,
605+ cap::UNLIMITED,
606+ )
607+ .fetch_optional(&mut *tx)
608+ .await?
609+ .is_some();
610+ if !seat {
611+ return Ok(Sweep::Full(course.to_string()));
612+ }
613+ let wrote = sqlx::query_scalar!(
614+ r#"INSERT INTO enrollment (course, app_user, enrolled_by, source)
615+ VALUES ($1, $2, $3, $4)
616+ ON CONFLICT (course, app_user) DO NOTHING
617+ RETURNING 1 AS "one""#,
618+ course,
619+ user,
620+ by as _,
621+ class as _
622+ )
623+ .fetch_optional(&mut *tx)
624+ .await;
625+ match wrote {
626+ Ok(Some(_)) => {}
627+ // A rival placed the pair in the window: their row stands, no
628+ // second seat, and the claim this run took is given back — the
629+ // skip wins over the capacity answer, exactly as a re-sent
630+ // transaction found the row at its gate.
631+ Ok(None) => {
632+ sqlx::query!(
633+ r#"UPDATE course SET enrollment_count = enrollment_count - 1
634+ WHERE id = $1"#,
635+ course
636+ )
637+ .execute(&mut *tx)
638+ .await?;
639+ }
640+ Err(e) if unique_violation(&e) == Some("enrollment_course_user") => {
641+ sqlx::query!(
642+ r#"UPDATE course SET enrollment_count = enrollment_count - 1
643+ WHERE id = $1"#,
644+ course
645+ )
646+ .execute(&mut *tx)
647+ .await?;
648+ }
649+ Err(e) => return Err(e.into()),
650+ }
651+ }
652+ Ok(Sweep::Done)
653+}
654+
655+// The sweep a role change *off` `student` owes — every class membership (each
656+// class getting its member count back) and every enrollment row (each course
657+// getting its seat back) — is two of the arms of
658+// [`crate::service::user::set_role`], because it belongs in the same
659+// transaction as the role write that invalidates them. It stays one fact with
660+// the counters either way: released separately, a failure between the halves
661+// left enrollment rows tagged `source = class_group:X` while the class had its
662+// counters back, so the class passed its zero-zero delete guard and the rows
663+// were left pointing at a class no sweep could ever reach again.
664+
665+/// Take a student out of a class and sweep the enrollments the class pumped
666+/// for them. Answers how many link rows went (0 or 1), so the caller can turn
667+/// zero into a 404.
587 ///668 ///
588-/// That pick is then **claimed**, by the bump-and-restore669+/// The sweep is *repair-first*: an enrollment this class wrote is only deleted
589-/// [`Axis::pivot_claim`] documents, before the row is handed over. Both reads670+/// once no other class still claims it. Two classes attached to the same
590-/// behind it are pure, and this sweep is long — one pass per enrollment row the671+/// course share a student — the second attach skipped the row the first had
591-/// link implies — so `DELETE /classes/{heir}/members/{user}` and672+/// already written, so the row carries only the first class's name — and
592-/// `DELETE /classes/{heir}/courses/{course}` could both commit inside it, their673+/// deleting it on the first class's way out would unenroll a student the
593-/// write sets disjoint from this one, and leave the row tagged with a class674+/// second class is still responsible for. So the row is re-tagged to that
594-/// holding neither link: a `class_group` whose own 0/0 delete guard then passes,675+/// rival instead, and only a row nobody is left to claim is deleted and its
595-/// stranding an enrollment nothing can ever sweep (the state the note above676+/// seat given back. The heir is the lowest class id among the claimants: a
596-/// [`attach`] says must not exist). Every one of those writers moves a counter677+/// deterministic pick (uuid order is mint order), so a repeat of the same
597-/// on the heir's own row, so moving it here too puts this transaction on the678+/// sweep lands on the same class.
598-/// record they write and the store settles it. The field is
599-/// `class_member_count` for both axes: what has to collide is the *record*, and
600-/// a class whose membership or course list moved has had one of the two written
601-/// either way.
602 ///679 ///
603-/// A claim that matches nothing is an heir whose class row is gone — a stale680+/// That pick is then **claimed** — a `FOR NO KEY UPDATE` read of the heir's
604-/// link outliving its class — and it takes the release arm rather than tagging681+/// class row, no counter moved — before the row is handed over. Both reads
605-/// the row with a record no route can reach.682+/// behind it are pure, and this sweep is long — one pass per enrollment row
683+/// the link implies — so `DELETE /classes/{heir}/members/{user}` and
684+/// `DELETE /classes/{heir}/courses/{course}` could both commit inside it and
685+/// leave the row tagged with a class holding neither link: a `class_group`
686+/// whose own 0/0 delete guard then passes, stranding an enrollment nothing can
687+/// ever sweep. Every one of those writers moves a counter on the heir's own
688+/// row, so the row lock here puts this transaction on the record they write
689+/// and the two settle in either order. A claim that matches nothing is an
690+/// heir whose class row is gone — a stale link outliving its class — and it
691+/// takes the release arm rather than tagging the row with an id no route can
692+/// reach.
606 ///693 ///
607-/// Sweeps tolerate rows that are already gone. `Course::delete` wipes a694+/// Sweeps tolerate rows that are already gone. A course delete wipes a
608 /// course's enrollments wholesale while the `class_member` rows survive it, so695 /// course's enrollments wholesale while the `class_member` rows survive it, so
609 /// "this class has a member" and "that member has a live pumped row" are696 /// "this class has a member" and "that member has a live pumped row" are
610 /// independent facts and the loop simply finds nothing to sweep.697 /// independent facts and the loop simply finds nothing to sweep.
611-///698+pub(crate) async fn remove_member(
612-/// Admissible by construction: `DELETE` and `UPDATE` only, so no statement in
613-/// the cascade can answer "already exists" and every lost round is a plain
614-/// re-send.
615-pub(crate) async fn detach(
616 db: &Database,699 db: &Database,
617- links: &str,700+ class: &ClassGroupId,
618- axis: Axis,701+ user: &UserId,
619- bindings: &[(String, Value)],
620 ) -> Result<i64, AppError> {702 ) -> Result<i64, AppError> {
621- let count_field = axis.counter();703+ tx_with_retry(db, true, async |tx| {
622- let scope = axis.scope();704+ let gone = sqlx::query_scalar!(
623- // Nobody is left to claim the row: it goes, and its seat with it. Written705+ r#"DELETE FROM class_member WHERE class = $1 AND app_user = $2
624- // once and used from both arms below, because "the heir's claim matched706+ RETURNING 1 AS "one""#,
625- // nothing" is the same answer as "there was no heir".707+ class as _,
626- let release = format!(708+ user as _
627- "DELETE $row.id;709+ )
628- UPDATE $row.course SET {ENROLLMENT_COUNT_FIELD} = \710+ .fetch_optional(tx)
629- math::max([({ENROLLMENT_COUNT_FIELD} ?? 0) - 1, 0]);"711+ .await?;
630- );712+ let Some(_) = gone else {
631- let sweep = format!(713+ return Ok(0);
632- "FOR $row IN ((SELECT id, course, user FROM {ENROLLMENT_TABLE} \714+ };
633- WHERE {scope} AND source = $link.class) ?? []) {{715+ sqlx::query!(
634- LET $rivals = (SELECT VALUE class FROM {CLASS_COURSE_TABLE} \716+ r#"UPDATE class_group
635- WHERE course = $row.course AND class != $link.class);717+ SET class_member_count = GREATEST(class_member_count - 1, 0)
636- LET $heir = array::first(array::sort((SELECT VALUE class \718+ WHERE id = $1"#,
637- FROM {CLASS_MEMBER_TABLE} WHERE user = $row.user AND class IN $rivals)));719+ class as _
638- IF $heir != NONE {{720+ )
639- LET $was_heir = (SELECT VALUE {CLASS_MEMBER_COUNT_FIELD} FROM ONLY $heir);721+ .execute(&mut *tx)
640- LET $claimed = (UPDATE $heir SET {CLASS_MEMBER_COUNT_FIELD} = \722+ .await?;
641- ({CLASS_MEMBER_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id);723+ sweep_enrollments(
642- UPDATE $heir SET {CLASS_MEMBER_COUNT_FIELD} = $was_heir;724+ tx,
643- IF array::len($claimed) > 0 {{725+ class,
644- UPDATE $row.id SET source = $heir;726+ sqlx::query!(
645- }} ELSE {{727+ r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid"
646- {release}728+ FROM enrollment WHERE app_user = $1 AND source = $2"#,
647- }};729+ user as _,
648- }} ELSE {{730+ class as _
649- {release}731+ )
650- }};732+ .fetch_all(&mut *tx)
651- }};"733+ .await?
652- );734+ .into_iter()
653- let sql = format!(735+ .map(|row| (row.course, row.app_user))
654- "BEGIN TRANSACTION;736+ .collect::<Vec<_>>(),
655- LET $gone = (DELETE {links} RETURN BEFORE);737+ )
656- FOR $link IN ($gone ?? []) {{738+ .await?;
657- UPDATE $link.class SET {count_field} = math::max([({count_field} ?? 0) - 1, 0]);739+ Ok(1)
658- {sweep}740+ })
659- }};741+ .await
660- RETURN array::len($gone);742+}
661- COMMIT TRANSACTION;"743+
662- );744+/// Detach `course` from `class` and sweep the enrollments the class pumped
663- let (mut result, mut errors) = transaction_with_retry(db, &sql, bindings, &[]).await?;745+/// into it. `source`, when given, re-asserts the provenance tag on the link's
664- if let Some(error) = errors.drain().map(|(_, error)| error).next() {746+/// own delete — a blueprint sweep may only take back rows its own tag owns.
665- return Err(error.into());747+/// Answers how many link rows went, so a caller whose link was a single pair
666- }748+/// can turn zero into a 404. The sweep underneath is the shared one: a student
667- // Slots count BEGIN, the LET and the FOR: the RETURN is slot 3.749+/// a second class still claims is re-tagged rather than unenrolled.
668- Ok(result.take::<Vec<i64>>(3)?.into_iter().next().unwrap_or(0))750+pub(crate) async fn detach_course(
751+ db: &Database,
752+ class: &ClassGroupId,
753+ course: &CourseId,
754+ source: Option<&ClassBlueprintId>,
755+) -> Result<i64, AppError> {
756+ tx_with_retry(db, true, async |tx| {
757+ let gone = match source {
758+ Some(source) => {
759+ sqlx::query_scalar!(
760+ r#"DELETE FROM class_course WHERE class = $1 AND course = $2 AND source = $3
761+ RETURNING 1 AS "one""#,
762+ class as _,
763+ course as _,
764+ source as _
765+ )
766+ .fetch_optional(tx)
767+ .await?
768+ }
769+ None => {
770+ sqlx::query_scalar!(
771+ r#"DELETE FROM class_course WHERE class = $1 AND course = $2
772+ RETURNING 1 AS "one""#,
773+ class as _,
774+ course as _
775+ )
776+ .fetch_optional(tx)
777+ .await?
778+ }
779+ };
780+ let Some(_) = gone else {
781+ return Ok(0);
782+ };
783+ sqlx::query!(
784+ r#"UPDATE class_group
785+ SET class_course_count = GREATEST(class_course_count - 1, 0)
786+ WHERE id = $1"#,
787+ class as _
788+ )
789+ .execute(&mut *tx)
790+ .await?;
791+ sweep_enrollments(
792+ tx,
793+ class,
794+ sqlx::query!(
795+ r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid"
796+ FROM enrollment WHERE course = $1 AND source = $2"#,
797+ course as _,
798+ class as _
799+ )
800+ .fetch_all(&mut *tx)
801+ .await?
802+ .into_iter()
803+ .map(|row| (row.course, row.app_user))
804+ .collect::<Vec<_>>(),
805+ )
806+ .await?;
807+ Ok(1)
808+ })
809+ .await
669 }810 }
670 811
671-/// A composite id for a `(class, other)` link, the shape812+/// The repair-first tail both detaches share: for every enrollment row the
672-/// [`crate::domain::enrollment::EnrollmentId::composite`] uses: the same pair813+/// deleted link owned, hand it to a rival class that still claims it, or
673-/// always maps to the same record, so one row per pair holds by construction814+/// delete it and give the course its seat back.
674-/// and a duplicate is something the store can *see* rather than something a815+///
675-/// find-then-insert has to race.816+/// The heir is the lowest class id among the rivals that carry both this
676-pub(crate) fn link_id(table: &str, class: &ClassGroupId, other: &str) -> RecordId {817+/// course *and* the student — the same deterministic pick on every repeat. Its
677- RecordId::new(table, format!("{}_{}", class.key(), other))818+/// class row is read `FOR NO KEY UPDATE` (a claim that moves no counter: the
819+/// class_member row already covers the student, and the enrollment is counted
820+/// on the course) so a concurrent member/course write on the heir serializes
821+/// behind this transaction; a claim matching nothing is a gone heir, and the
822+/// row takes the release arm.
823+async fn sweep_enrollments(
824+ tx: &mut PgConnection,
825+ class: &ClassGroupId,
826+ rows: Vec<(uuid::Uuid, uuid::Uuid)>,
827+) -> Result<(), AppError> {
828+ for (course, user) in rows {
829+ let heir = sqlx::query_scalar!(
830+ r#"SELECT cm.class AS "class: uuid::Uuid"
831+ FROM class_member cm
832+ JOIN class_course cc ON cc.class = cm.class AND cc.course = $1
833+ WHERE cm.app_user = $2 AND cm.class <> $3
834+ ORDER BY cm.class
835+ LIMIT 1"#,
836+ course,
837+ user,
838+ class as _
839+ )
840+ .fetch_optional(&mut *tx)
841+ .await?
842+ .map(|row| row.class);
843+ let Some(heir) = heir else {
844+ release(tx, course, user).await?;
845+ continue;
846+ };
847+ let claimed = sqlx::query_scalar!(
848+ r#"SELECT class_member_count AS "heir_count: i64" FROM class_group
849+ WHERE id = $1 FOR NO KEY UPDATE"#,
850+ heir
851+ )
852+ .fetch_optional(&mut *tx)
853+ .await?;
854+ if claimed.is_none() {
855+ release(tx, course, user).await?;
856+ continue;
857+ }
858+ sqlx::query!(
859+ r#"UPDATE enrollment SET source = $1 WHERE course = $2 AND app_user = $3"#,
860+ heir,
861+ course,
862+ user
863+ )
864+ .execute(&mut *tx)
865+ .await?;
866+ }
867+ Ok(())
678 }868 }
679 869
870+/// Nobody is left to claim the row: it goes, and its seat with it. The seat
871+/// is only given back when the delete actually took the row — a course
872+/// delete's wholesale sweep may have taken both while this transaction read
873+/// them, and both halves vanish together there.
874+async fn release(
875+ tx: &mut PgConnection,
876+ course: uuid::Uuid,
877+ user: uuid::Uuid,
878+) -> Result<(), AppError> {
879+ let deleted = sqlx::query!(
880+ r#"DELETE FROM enrollment WHERE course = $1 AND app_user = $2"#,
881+ course,
882+ user
883+ )
884+ .execute(&mut *tx)
885+ .await?
886+ .rows_affected();
887+ if deleted > 0 {
888+ sqlx::query!(
889+ r#"UPDATE course SET enrollment_count = GREATEST(enrollment_count - 1, 0)
890+ WHERE id = $1"#,
891+ course
892+ )
893+ .execute(&mut *tx)
894+ .await?;
895+ }
896+ Ok(())
897+}
680 #[cfg(test)]898 #[cfg(test)]
681 mod tests {899 mod tests {
682 use super::*;900 use super::*;
src/domain/class_blueprint.rsmodified+5 -3
@@ -15,11 +15,10 @@
15 //! shared skip vocabulary ([`skip_reason`]).15 //! shared skip vocabulary ([`skip_reason`]).
16 //!16 //!
17 //! The behavior lives one layer down: the edit-retro-pump, the apply/sweep17 //! The behavior lives one layer down: the edit-retro-pump, the apply/sweep
18-//! engine and its [`crate::service::class_blueprint::BLUEPRINT_LOCK`] lease18+//! engine in [`crate::service::class_blueprint`], the queries in
19-//! in [`crate::service::class_blueprint`], the queries in
20 //! [`crate::db::class_blueprint`].19 //! [`crate::db::class_blueprint`].
21 20
22-use crate::constant::{MAX_CLASS_COURSES};21+use crate::constant::MAX_CLASS_COURSES;
23 use crate::db::class_pump::{Attached, Axis};22 use crate::db::class_pump::{Attached, Axis};
24 use crate::domain::class_course::ClassCourse;23 use crate::domain::class_course::ClassCourse;
25 use crate::domain::class_group::{ClassGrade, ClassGroupId};24 use crate::domain::class_group::{ClassGrade, ClassGroupId};
@@ -53,6 +52,9 @@ impl ClassBlueprintId {
53 /// never has to parse a record id back into a domain value.52 /// never has to parse a record id back into a domain value.
54 #[derive(Debug, Clone, sqlx::FromRow)]53 #[derive(Debug, Clone, sqlx::FromRow)]
55 pub struct ClassBlueprint {54 pub struct ClassBlueprint {
55+ /// The table's `TEXT` primary key column, stored once and read into both
56+ /// this field and `grade` — the key *is* the grade label.
57+ #[sqlx(rename = "grade")]
56 pub(crate) id: ClassBlueprintId,58 pub(crate) id: ClassBlueprintId,
57 pub(crate) grade: ClassGrade,59 pub(crate) grade: ClassGrade,
58 pub(crate) courses: Vec<CourseId>,60 pub(crate) courses: Vec<CourseId>,
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/service/class_blueprint.rsmodified+57 -100
@@ -27,10 +27,6 @@
27 //! repairs before it deletes — and it runs one transaction per pair too, for27 //! repairs before it deletes — and it runs one transaction per pair too, for
28 //! the same reason the pump does.28 //! the same reason the pump does.
29 29
30-use tokio::sync::RwLock;
31-
32-use surrealdb::types::RecordId;
33-
34 use crate::database::Database;30 use crate::database::Database;
35 use crate::db::class_blueprint;31 use crate::db::class_blueprint;
36 use crate::db::class_course;32 use crate::db::class_course;
@@ -39,45 +35,11 @@ use crate::db::class_pump::Attached;
39 use crate::domain::class_blueprint::{35 use crate::domain::class_blueprint::{
40 ClassBlueprint, ClassBlueprintId, Pumped, SectionStatus, Skip, skip_reason,36 ClassBlueprint, ClassBlueprintId, Pumped, SectionStatus, Skip, skip_reason,
41 };37 };
42-use crate::domain::class_group::{ClassGrade, ClassGroup};38+use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId};
43 use crate::domain::course::CourseId;39 use crate::domain::course::CourseId;
44 use crate::domain::user::UserId;40 use crate::domain::user::UserId;
45 use crate::error::AppError;41 use crate::error::AppError;
46 42
47-/// Serializes a blueprint's delete against the attaches made on its behalf.
48-///
49-/// [`delete`] removes the row and then sweeps by the provenance
50-/// tag, and every guarded attach reads that same row *inside* its own
51-/// transaction ([`crate::db::class_pump::attach`]'s `source` claim). Those
52-/// two are a cross-record read-then-write racing a write to the record read,
53-/// which `BEGIN`/`COMMIT` does not serialize (SurrealDB write skew): a pump can
54-/// see the blueprint alive, have the delete commit and sweep past it, and only
55-/// then commit its own `class_course` row — tagged with a record that no longer
56-/// exists and that no sweep can ever reach again, since the grade label *is*
57-/// the id. Delete-first and the in-transaction claim narrow that window; this
58-/// closes it.
59-///
60-/// The delete holds the **write** lease across its compare-and-set and the read
61-/// that fixes the set of rows it will sweep — and no further. That is the whole
62-/// invariant: the sweep's row set must contain every attach this blueprint ever
63-/// committed, and no attach may commit one afterwards. An attach already in
64-/// flight holds the read lease, so the write lease waits for it and its row is
65-/// in the set; an attach starting after the lease is released finds the row
66-/// deleted and answers [`Attached::SourceGone`], writing nothing. The detaching
67-/// itself — one transaction per row, unbounded — therefore runs lease-free,
68-/// because `tokio`'s `RwLock` is *fair*: held across that loop, it parked every
69-/// concurrent `POST /classes` at every other grade behind one grade's delete.
70-/// Each guarded attach holds the **read** lease for the span of its own
71-/// transaction — taken per course in [`apply_to`], never around
72-/// a whole pump, so a delete waits behind one attach rather than an unbounded
73-/// loop.
74-///
75-/// In-process is deployment-wide here: one process by contract, with
76-/// stop-the-world upgrades — the same argument
77-/// [`crate::service::settings::SETTINGS_LOCK`] makes. No other lock is taken
78-/// under it, so it has no ordering rule to break.
79-pub(crate) static BLUEPRINT_LOCK: RwLock<()> = RwLock::const_new(());
80-
81 /// Write the blueprint after settling the course list43 /// Write the blueprint after settling the course list
82 /// ([`ClassBlueprint::course_list`]) — the same validation, in the same44 /// ([`ClassBlueprint::course_list`]) — the same validation, in the same
83 /// order, the single write this replaced did. One blueprint per grade: a45 /// order, the single write this replaced did. One blueprint per grade: a
@@ -137,13 +99,12 @@ pub async fn list_all(
137 /// templated course — what [`status`] reports and the next pump99 /// templated course — what [`status`] reports and the next pump
138 /// repairs — where the diff's failure was a row no call could reach.100 /// repairs — where the diff's failure was a row no call could reach.
139 ///101 ///
140-/// Takes no [`BLUEPRINT_LOCK`] lease, deliberately: holding the write lease102+/// Takes no lease of its own, deliberately: a lease held across its own pump
141-/// across its own pump would deadlock on the read lease that pump takes,103+/// would deadlock on the locks that pump takes, and it would close nothing
142-/// and a lease would close nothing anyway — the pump's claim asks whether104+/// anyway — the attach's claim asks whether the blueprint *exists*, not what
143-/// the blueprint *exists*, not what it holds, so an edit racing a pump is105+/// it holds, so an edit racing a pump is only ever the retro-pump this
144-/// only ever the retro-pump this feature is built on. Rows a racing edit106+/// feature is built on. Rows a racing edit leaves behind stay reachable,
145-/// leaves behind stay reachable, because [`delete`] sweeps the whole107+/// because [`delete`] sweeps the whole tag rather than a list.
146-/// tag rather than a list.
147 pub async fn set_courses(108 pub async fn set_courses(
148 db: &Database,109 db: &Database,
149 blueprint: ClassBlueprint,110 blueprint: ClassBlueprint,
@@ -185,57 +146,55 @@ pub async fn set_courses(
185 /// mirror image of a race: a `PATCH` adding a course and pumping it while146 /// mirror image of a race: a `PATCH` adding a course and pumping it while
186 /// this ran landed rows tagged with a blueprint the delete then removed,147 /// this ran landed rows tagged with a blueprint the delete then removed,
187 /// and nothing could ever sweep them again — the grade label *is* the148 /// and nothing could ever sweep them again — the grade label *is* the
188-/// record id, so only a blueprint recreated at that grade could even name149+/// primary key, so only a blueprint recreated at that grade could even name
189 /// them. Never revert to sweep-first.150 /// them. Never revert to sweep-first.
190 ///151 ///
191-/// Deleting first plus the pump's own in-transaction claim on this row152+/// Deleting first plus the attach's in-transaction claim on this row
192-/// ([`Attached::SourceGone`]) **narrows** that window; it does not close153+/// ([`Attached::SourceGone`]) **closes** that window outright: the claim is
193-/// it. The claim is a read of `class_blueprint` in a transaction that154+/// not a bare read but a `FOR KEY SHARE` row lock on `class_blueprint`, the
194-/// writes `class_course`, racing this delete's write to155+/// one strength a `DELETE` of the row cannot take. A sourced attach that
195-/// `class_blueprint` — a cross-record pair `BEGIN`/`COMMIT` does not156+/// started first holds the row and this delete's `DELETE` waits behind it —
196-/// serialize, so a pump that read the row alive can still commit its link157+/// the row the attach commits is then in the set the sweep reads; an attach
197-/// after the sweep has run. [`BLUEPRINT_LOCK`] is what closes it: the write158+/// starting after the delete finds no row and writes nothing. (Under the
198-/// lease below spans the compare-and-set and the sweep, the read lease in159+/// old engine the claim was a plain read that no `BEGIN`/`COMMIT` pair
199-/// [`apply_to`] spans each attach, and the deployment runs one160+/// serialized against this delete's write, and a process-wide `RwLock` had
200-/// process by contract, which makes an in-process lock the whole answer.161+/// to stand in; the row lock is the same answer without the process.)
201 ///162 ///
202-/// What is left is a **process crash** between the delete and the sweep — a163+/// What is left is a **process crash** between the delete and the sweep.
203-/// lock does not survive the process. That leaves inert `class_course` rows164+/// That leaves inert `class_course` rows tagged with a blueprint that is
204-/// tagged with a blueprint that is gone; they are still detachable one at a165+/// gone; they are still detachable one at a time at
205-/// time at `DELETE /classes/{id}/courses/{course}`, and every counter stays166+/// `DELETE /classes/{id}/courses/{course}`, and every counter stays exact
206-/// exact because each detach is its own transaction.167+/// because each detach is its own transaction.
207 ///168 ///
208 /// The delete is a compare-and-set on the list this caller read, like169 /// The delete is a compare-and-set on the list this caller read, like
209 /// [`set_courses`]: an edit landing in between is a `409` rather than170 /// [`set_courses`]: an edit landing in between is a `409` rather than
210 /// a silent detach of somebody else's additions. Known hole, accepted: the171 /// a silent detach of somebody else's additions. Known hole, accepted: the
211-/// grade label *is* the record id and the comparison is by **content**, so172+/// grade label *is* the primary key and the comparison is by **content**, so
212 /// a blueprint deleted and recreated at the same grade with the same list173 /// a blueprint deleted and recreated at the same grade with the same list
213 /// satisfies `WHERE courses = $held` and this call deletes the *new* row.174 /// satisfies `WHERE courses = $held` and this call deletes the *new* row.
175+///
214 /// Content-equal is intent-equal — the end state is the one the caller176 /// Content-equal is intent-equal — the end state is the one the caller
215 /// asked for — and telling the two apart needs a revision column on the177 /// asked for — and telling the two apart needs a revision column on the
216 /// row, which nothing else here would use.178 /// row, which nothing else here would use.
217 pub async fn delete(db: &Database, blueprint: ClassBlueprint) -> Result<(), AppError> {179 pub async fn delete(db: &Database, blueprint: ClassBlueprint) -> Result<(), AppError> {
218- let doomed = {180+ if !class_blueprint::delete_if_unchanged(db, &blueprint.id, blueprint.courses.clone()).await? {
219- // Held across the delete and the read that fixes the sweep's row181+ // Matched nothing: the row is gone, or its list moved since this
220- // set, and released before the detaching: no attach can commit a row182+ // caller read it. Only this path pays for the read that tells
221- // this read did not see, and none that starts afterwards writes one183+ // them apart.
222- // at all.184+ return match read(db, &blueprint.id).await? {
223- let _lease = BLUEPRINT_LOCK.write().await;185+ Some(_) => Err(AppError::Conflict(
224- if !class_blueprint::delete_if_unchanged(db, &blueprint.id, blueprint.courses.clone())186+ "this blueprint changed since you read it — re-read and retry",
225- .await?187+ )),
226- {188+ None => Err(AppError::NotFound),
227- // Matched nothing: the row is gone, or its list moved since this189+ };
228- // caller read it. Only this path pays for the read that tells190+ }
229- // them apart.191+ // The row set is read after the delete, and the delete itself is what
230- return match read(db, &blueprint.id).await? {192+ // serializes it against the attaches: a sourced attach holds a `FOR KEY
231- Some(_) => Err(AppError::Conflict(193+ // SHARE` on the blueprint row across its transaction, so its row lands
232- "this blueprint changed since you read it — re-read and retry",194+ // before this delete (and is in the set this read then sees) or finds the
233- )),195+ // row gone and writes nothing at all. No attach can commit a row this
234- None => Err(AppError::NotFound),196+ // read did not see, and none that starts afterwards writes one.
235- };197+ let doomed = class_blueprint::sourced_links(db, &blueprint.id, &[]).await?;
236- }
237- class_blueprint::sourced_links(db, &blueprint.id, &[]).await?
238- };
239 class_blueprint::drop_links(db, &blueprint.id, doomed).await198 class_blueprint::drop_links(db, &blueprint.id, doomed).await
240 }199 }
241 200
@@ -246,13 +205,13 @@ pub async fn delete(db: &Database, blueprint: ClassBlueprint) -> Result<(), AppE
246 ///205 ///
247 /// This is the *only* place a sourced attach is made — [`pump`], the206 /// This is the *only* place a sourced attach is made — [`pump`], the
248 /// create-time and per-class pumps in [`crate::web::classes`] all come207 /// create-time and per-class pumps in [`crate::web::classes`] all come
249-/// through here — so it is where each one takes [`BLUEPRINT_LOCK`] for208+/// through here — and each attach's transaction takes a `FOR KEY SHARE`
250-/// reading, one course at a time. A delete landing mid-pump is then clean209+/// lock on the blueprint row itself, one course at a time. A delete landing
251-/// by construction: the attaches that already committed are found by its210+/// mid-pump is then clean by construction: the attaches that already
252-/// tag sweep, and the ones that have not yet started meet the deleted row211+/// committed are found by its tag sweep, and the ones that have not yet
253-/// at their own in-transaction claim and answer `blueprint_deleted`. Per212+/// started meet the deleted row at their own in-transaction claim and
254-/// course rather than per pump, because the pump's loop is unbounded and a213+/// answer `blueprint_deleted`. Per course rather than per pump, because the
255-/// delete may not wait behind all of it.214+/// pump's loop is unbounded and a delete may not wait behind all of it.
256 ///215 ///
257 /// One class, so `blueprint_deleted` is an ordinary skip here: the courses216 /// One class, so `blueprint_deleted` is an ordinary skip here: the courses
258 /// after it are not tried, because the template they would ask for is the217 /// after it are not tried, because the template they would ask for is the
@@ -289,11 +248,9 @@ async fn apply_courses(
289 if dead.contains(course) {248 if dead.contains(course) {
290 continue;249 continue;
291 }250 }
292- let landed = {251+ let landed =
293- let _lease = BLUEPRINT_LOCK.read().await;
294 class_course::attach_sourced(db, class.get_id(), course, by, Some(&blueprint.id))252 class_course::attach_sourced(db, class.get_id(), course, by, Some(&blueprint.id))
295- .await?253+ .await?;
296- };
297 if matches!(landed, Attached::PivotGone) {254 if matches!(landed, Attached::PivotGone) {
298 class_blueprint::prune(db, &blueprint.id, course).await?;255 class_blueprint::prune(db, &blueprint.id, course).await?;
299 dead.push(course.clone());256 dead.push(course.clone());
@@ -321,9 +278,9 @@ async fn apply_courses(
321 /// since a section cannot make either of them untrue. A course that no278 /// since a section cannot make either of them untrue. A course that no
322 /// longer exists is pruned and skipped on the first class that meets it and279 /// longer exists is pruned and skipped on the first class that meets it and
323 /// left out of every class after it. And a `blueprint_deleted` **aborts the280 /// left out of every class after it. And a `blueprint_deleted` **aborts the
324-/// grade loop**: under [`BLUEPRINT_LOCK`] that answer is precisely "a281+/// grade loop**: the attach's `FOR KEY SHARE` row-lock claim makes that
325-/// delete landed mid-pump", so it is reported once and the remaining282+/// answer precisely "a delete landed mid-pump", so it is reported once and
326-/// classes are not walked.283+/// the remaining classes are not walked.
327 ///284 ///
328 /// The abort is still a `Ok(..)`, not an error: the attaches that committed285 /// The abort is still a `Ok(..)`, not an error: the attaches that committed
329 /// before the delete stand (its sweep took the ones it could reach), and a286 /// before the delete stand (its sweep took the ones it could reach), and a
@@ -391,9 +348,9 @@ pub async fn status(
391 if sections.is_empty() {348 if sections.is_empty() {
392 return Ok(Vec::new());349 return Ok(Vec::new());
393 }350 }
394- let classes: Vec<RecordId> = sections351+ let classes: Vec<ClassGroupId> = sections
395 .iter()352 .iter()
396- .map(|class| class.get_id().record())353+ .map(|class| class.get_id().clone())
397 .collect();354 .collect();
398 let held = class_blueprint::held_links(db, classes).await?;355 let held = class_blueprint::held_links(db, classes).await?;
399 Ok(sections356 Ok(sections
src/service/class_course.rsmodified+2 -16
@@ -3,8 +3,6 @@
3 //! The transactions live in [`crate::db::class_pump`] and3 //! The transactions live in [`crate::db::class_pump`] and
4 //! [`crate::db::class_course`].4 //! [`crate::db::class_course`].
5 5
6-use surrealdb::types::SurrealValue;
7-
8 use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};6 use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
9 use crate::database::Database;7 use crate::database::Database;
10 use crate::db::class_course;8 use crate::db::class_course;
@@ -84,25 +82,13 @@ pub async fn attach(
84 /// into it. A course that was not attached is a [`AppError::NotFound`],82 /// into it. A course that was not attached is a [`AppError::NotFound`],
85 /// raised here rather than left to each caller to re-derive from a boolean.83 /// raised here rather than left to each caller to re-derive from a boolean.
86 ///84 ///
87-/// A student another attached class still claims keeps their row, re-tagged85+/// to that class (see [`class_pump::detach_course`]).
88-/// to that class (see [`crate::db::class_pump::detach`]).
89 pub async fn detach(86 pub async fn detach(
90 db: &Database,87 db: &Database,
91 class: &ClassGroupId,88 class: &ClassGroupId,
92 course: &CourseId,89 course: &CourseId,
93 ) -> Result<(), AppError> {90 ) -> Result<(), AppError> {
94- let gone = class_pump::detach(91+ let gone = class_pump::detach_course(db, class, course, None).await?;
95- db,
96- "$link",
97- Axis::Course,
98- &[(
99- "link".into(),
100- crate::domain::class_course::ClassCourseId::composite(class, course)
101- .record()
102- .into_value(),
103- )],
104- )
105- .await?;
106 (gone > 0).then_some(()).ok_or(AppError::NotFound)92 (gone > 0).then_some(()).ok_or(AppError::NotFound)
107 }93 }
108 94
src/service/class_member.rsmodified+4 -32
@@ -4,15 +4,12 @@
4 //! itself lives in [`crate::db::class_pump`]; the table reads in4 //! itself lives in [`crate::db::class_pump`]; the table reads in
5 //! [`crate::db::class_member`].5 //! [`crate::db::class_member`].
6 6
7-use surrealdb::types::SurrealValue;
8-
9 use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};7 use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
10 use crate::database::Database;8 use crate::database::Database;
11 use crate::db::class_member;9 use crate::db::class_member;
12 use crate::db::class_pump::{self, Axis};10 use crate::db::class_pump::{self, Axis};
13 use crate::domain::class_group::ClassGroupId;11 use crate::domain::class_group::ClassGroupId;
14-use crate::domain::class_member::{ClassMember, ClassMemberId};12+use crate::domain::class_member::ClassMember;
15-use crate::domain::timestamp::Timestamp;
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
@@ -29,26 +26,10 @@ pub async fn add(
29 user: &UserId,26 user: &UserId,
30 added_by: &UserId,27 added_by: &UserId,
31 ) -> Result<ClassMember, AppError> {28 ) -> Result<ClassMember, AppError> {
32- let member = ClassMember {
33- id: ClassMemberId::composite(class, user),
34- class: class.clone(),
35- user: user.clone(),
36- added_by: added_by.clone(),
37- added_at: Some(Timestamp::now()),
38- };
39- let landed = class_pump::attach(
40- db,
41- class,
42- Axis::Member,
43- (&member.id.record(), &member),
44- user.record(),
45- added_by.record(),
46- None,
47- )
48- .await?;
49 // Read off the refusal, never respelled here: this route and a29 // Read off the refusal, never respelled here: this route and a
50 // blueprint pump answer one vocabulary. `Made` is the only `None`, and30 // blueprint pump answer one vocabulary. `Made` is the only `None`, and
51 // it takes the `Ok` arm below.31 // it takes the `Ok` arm below.
32+ let landed = class_pump::add_member(db, class, user, added_by).await?;
52 let code = landed.refusal_code(&Axis::Member).unwrap_or_default();33 let code = landed.refusal_code(&Axis::Member).unwrap_or_default();
53 match landed {34 match landed {
54 class_pump::Attached::Made(saved) => Ok(saved),35 class_pump::Attached::Made(saved) => Ok(saved),
@@ -103,18 +84,9 @@ pub async fn add(
103 /// re-derive from a boolean.84 /// re-derive from a boolean.
104 ///85 ///
105 /// An enrollment another attached class still claims is re-tagged to that86 /// An enrollment another attached class still claims is re-tagged to that
106-/// class instead of deleted (see [`crate::db::class_pump::detach`]).87+/// class instead of deleted (see [`class_pump::remove_member`]).
107 pub async fn remove(db: &Database, class: &ClassGroupId, user: &UserId) -> Result<(), AppError> {88 pub async fn remove(db: &Database, class: &ClassGroupId, user: &UserId) -> Result<(), AppError> {
108- let gone = class_pump::detach(89+ let gone = class_pump::remove_member(db, class, user).await?;
109- db,
110- "$link",
111- Axis::Member,
112- &[(
113- "link".into(),
114- ClassMemberId::composite(class, user).record().into_value(),
115- )],
116- )
117- .await?;
118 (gone > 0).then_some(()).ok_or(AppError::NotFound)90 (gone > 0).then_some(()).ok_or(AppError::NotFound)
119 }91 }
120 92
src/web/classes.rsmodified+11 -11
@@ -73,7 +73,7 @@ struct CreateClass {
73 term_id: Option<String>,73 term_id: Option<String>,
74 /// The class's homeroom teacher (sınıf öğretmeni) — a teacher, manager or74 /// The class's homeroom teacher (sınıf öğretmeni) — a teacher, manager or
75 /// admin account. Optional; omit (or send `""`) for a class with none.75 /// admin account. Optional; omit (or send `""`) for a class with none.
76- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]76+ #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")]
77 teacher_id: Option<String>,77 teacher_id: Option<String>,
78 }78 }
79 79
@@ -101,20 +101,20 @@ struct UpdateClass {
101 #[derive(Deserialize, ToSchema)]101 #[derive(Deserialize, ToSchema)]
102 struct AddMember {102 struct AddMember {
103 /// The student to put in the class.103 /// The student to put in the class.
104- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]104+ #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")]
105 user_id: String,105 user_id: String,
106 }106 }
107 107
108 #[derive(Deserialize, ToSchema)]108 #[derive(Deserialize, ToSchema)]
109 struct AttachCourse {109 struct AttachCourse {
110 /// The course the whole class takes.110 /// The course the whole class takes.
111- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]111+ #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")]
112 course_id: String,112 course_id: String,
113 }113 }
114 114
115 #[derive(Serialize, ToSchema)]115 #[derive(Serialize, ToSchema)]
116 struct ClassResponse {116 struct ClassResponse {
117- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]117+ #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")]
118 id: String,118 id: String,
119 /// Who created the class — always a manager or admin, so it is `null` for119 /// Who created the class — always a manager or admin, so it is `null` for
120 /// a caller below teacher+. `GET /classes/me` and a parent's120 /// a caller below teacher+. `GET /classes/me` and a parent's
@@ -184,7 +184,7 @@ struct CreateClassResponse {
184 184
185 /// Every person a [`ClassResponse`] names: its homeroom teacher, plus its185 /// Every person a [`ClassResponse`] names: its homeroom teacher, plus its
186 /// creator when the caller is cleared to see one. Feed this into `person_map` —186 /// creator when the caller is cleared to see one. Feed this into `person_map` —
187-/// an id the map is missing renders as a bare ULID, so a creator left out here187+/// an id the map is missing renders as a bare id, so a creator left out here
188 /// must also be left out of the response.188 /// must also be left out of the response.
189 fn class_people(class: &ClassGroup, with_creator: bool) -> impl Iterator<Item = UserId> + '_ {189 fn class_people(class: &ClassGroup, with_creator: bool) -> impl Iterator<Item = UserId> + '_ {
190 with_creator190 with_creator
@@ -419,7 +419,7 @@ async fn create_class(
419 ///419 ///
420 /// Swallowing that last case is the deliberate one. Every other pump here may420 /// Swallowing that last case is the deliberate one. Every other pump here may
421 /// fail its whole request, because the caller can name what it asked for again —421 /// fail its whole request, because the caller can name what it asked for again —
422-/// a blueprint's id *is* the grade label they sent. A class's id is a ULID this422+/// a blueprint's id *is* the grade label they sent. A class's id is a uuid this
423 /// request is the only place it is ever returned from, so a `500` after the row423 /// request is the only place it is ever returned from, so a `500` after the row
424 /// is written loses a section that exists. Best-effort therefore runs to the end424 /// is written loses a section that exists. Best-effort therefore runs to the end
425 /// of this route: the class is reported, `stocked_from` stays `null`, and the425 /// of this route: the class is reported, `stocked_from` stays `null`, and the
@@ -1041,14 +1041,14 @@ impl BlueprintResponse {
1041 1041
1042 /// One class a pump did *not* stock, and why. The class is named as well as1042 /// One class a pump did *not* stock, and why. The class is named as well as
1043 /// identified: a manager reading a skip list has to know which section is short1043 /// identified: a manager reading a skip list has to know which section is short
1044-/// a course, and a bare ULID is not that.1044+/// a course, and a bare id is not that.
1045 #[derive(Serialize, ToSchema)]1045 #[derive(Serialize, ToSchema)]
1046 struct SkipResponse {1046 struct SkipResponse {
1047- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]1047+ #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")]
1048 class: String,1048 class: String,
1049 #[schema(example = "9-C")]1049 #[schema(example = "9-C")]
1050 class_name: String,1050 class_name: String,
1051- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]1051+ #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")]
1052 course: String,1052 course: String,
1053 /// Why that course could not be attached to that class, as a machine code1053 /// Why that course could not be attached to that class, as a machine code
1054 /// the client words itself — the same id-plus-client-label shape roles and1054 /// the client words itself — the same id-plus-client-label shape roles and
@@ -1118,7 +1118,7 @@ struct BlueprintPumpResponse {
1118 /// One section measured against its grade's template.1118 /// One section measured against its grade's template.
1119 #[derive(Serialize, ToSchema)]1119 #[derive(Serialize, ToSchema)]
1120 struct SectionStatusResponse {1120 struct SectionStatusResponse {
1121- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]1121+ #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")]
1122 class: String,1122 class: String,
1123 #[schema(example = "9-C")]1123 #[schema(example = "9-C")]
1124 class_name: String,1124 class_name: String,
@@ -1521,7 +1521,7 @@ mod tests {
1521 let teacher = make("ada", Role::Teacher).await;1521 let teacher = make("ada", Role::Teacher).await;
1522 1522
1523 for (field, id) in [1523 for (field, id) in [
1524- ("gone", "01J8XZ0K3Q8G7X2M4N5P6R7S8T"),1524+ ("gone", "0198f1a2-3b4c-7d5e-8f90-000000000001"),
1525 ("student", student.get_id().key()),1525 ("student", student.get_id().key()),
1526 ] {1526 ] {
1527 let refused = teacher_or_none(Some(id), &db).await;1527 let refused = teacher_or_none(Some(id), &db).await;