From dec7a2ac05f35e5140251d7da5045b2825e0563f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 12 Sep 2026 08:23:46 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=97=83=EF=B8=8F=20feat!:=20port=20classes?= =?UTF-8?q?=20(group/member/course/blueprint/pump)=20to=20sqlx/Postgres?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/db/class_blueprint.rs | 352 +++++---- src/db/class_course.rs | 38 +- src/db/class_group.rs | 297 ++++---- src/db/class_member.rs | 19 +- src/db/class_pump.rs | 1224 +++++++++++++++++++------------- src/domain/class_blueprint.rs | 8 +- src/domain/class_group.rs | 2 +- src/service/class_blueprint.rs | 157 ++-- src/service/class_course.rs | 18 +- src/service/class_member.rs | 36 +- src/web/classes.rs | 22 +- 11 files changed, 1162 insertions(+), 1011 deletions(-) diff --git a/src/db/class_blueprint.rs b/src/db/class_blueprint.rs index 7926f8f..e8053da 100644 --- a/src/db/class_blueprint.rs +++ b/src/db/class_blueprint.rs @@ -1,14 +1,14 @@ //! The `class_blueprint` table: the row keyed by its grade label, the //! compare-and-set writes the edit and the delete go through, and the reads //! the sweep and the status screen are built on. The workflows that sequence -//! these under [`crate::service::class_blueprint::BLUEPRINT_LOCK`] live in -//! [`crate::service::class_blueprint`]. +//! these — and the row lock that serializes a delete against the attaches +//! made on the blueprint's behalf — live in [`crate::service::class_blueprint`]. -use surrealdb::types::{RecordId, SurrealValue}; +use sqlx::postgres::PgConnection; -use crate::constant::{CLASS_BLUEPRINT_TABLE, CLASS_COURSE_TABLE, ENROLLMENT_COUNT_FIELD}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::class_pump::{Axis, detach}; +use crate::constant::CLASS_BLUEPRINT_TABLE; +use crate::database::{Database, tx_with_retry, unique_violation}; +use crate::db::class_pump; use crate::db::page::PagedList; use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId}; use crate::domain::class_group::{ClassGrade, ClassGroupId}; @@ -16,50 +16,49 @@ use crate::domain::course::CourseId; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; -/// The `THROW` marker a template write aborts with when one of the courses it -/// names is gone — the same answer the caller's own pre-flight read gives, made -/// inside the transaction that stores the list. -const DEAD_MARK: &str = "blueprint_no_course"; - /// One `class_course` row, projected down to the pair that answers "does this /// section carry that course". `source` is deliberately not read: a link of any -/// provenance satisfies the template. -#[derive(SurrealValue)] +#[derive(Debug, sqlx::FromRow)] pub struct Held { pub(crate) class: ClassGroupId, pub(crate) course: CourseId, } -/// The statements that prove every course a template is about to name is -/// still there, *inside* the transaction that stores the list. +/// Prove every course a template is about to name is still there, *inside* the +/// transaction that stores the list. /// /// The caller's own pre-flight read is not that proof: it is a read of -/// `course` in a request that then writes `class_blueprint`, and SurrealDB -/// does not conflict-check reads (write skew). `DELETE /courses/{id}` sweeps -/// every template naming the course as part of its cascade, so a delete -/// landing between the read and the write sweeps a row that is not there yet -/// and the list keeps an id nothing points at. [`prune`] only fires -/// while walking a section, so at a grade carrying none the id is permanent. +/// `course` in a request that then writes `class_blueprint`, and two +/// transactions that read and write crossed records interleave freely under +/// READ COMMITTED. `DELETE /courses/{id}` sweeps every template naming the +/// course as part of its cascade, so a delete landing between the read and the +/// write sweeps a row that is not there yet and the list keeps an id nothing +/// points at. A `FOR KEY SHARE` row lock per course is the proof: it is the +/// weakest strength a course `DELETE` cannot take, so the delete waits behind +/// this transaction and finds the list that names the course already stored — +/// and sweeps it. /// -/// The claim is [`crate::db::class_pump::Axis::pivot_claim`]'s exactly: -/// the counter is *moved* — bumped, gated, restored to the value this -/// transaction found, `NONE` included — because an `UPDATE` leaving the -/// document unchanged is elided by 3.2.3 and enters no write set. Moving it -/// puts this write on the record the course's delete guard writes. -fn courses_alive() -> String { - format!( - "FOR $course IN ($courses ?? []) {{ - LET $was = (SELECT VALUE {ENROLLMENT_COUNT_FIELD} FROM ONLY $course); - LET $alive = (UPDATE $course SET {ENROLLMENT_COUNT_FIELD} = \ - ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); - IF array::len($alive) = 0 {{ THROW '{DEAD_MARK}' }}; - UPDATE $course SET {ENROLLMENT_COUNT_FIELD} = $was; - }}" - ) +/// One lock per course, the list being at most `MAX_CLASS_COURSES` long — +/// the same pass-per-course the old in-transaction loop made. +async fn courses_alive(tx: &mut PgConnection, courses: &[CourseId]) -> Result<(), AppError> { + for course in courses { + let alive = sqlx::query_scalar!( + r#"SELECT 1 AS "one" FROM course WHERE id = $1 FOR KEY SHARE"#, + course as _ + ) + .fetch_optional(&mut *tx) + .await? + .is_some(); + if !alive { + return Err(no_such_course()); + } + } + Ok(()) } -/// The refusal a [`DEAD_MARK`] abort is: the same `400` the caller's -/// pre-flight read raises, since it is the same fact one instant later. +/// The refusal a locked course read answers when the course is gone: the +/// same `400` the caller's pre-flight read raises, since it is the same fact +/// one instant later. fn no_such_course() -> AppError { AppError::Validation(ValidationError::Invalid { field: "course_ids", @@ -67,15 +66,10 @@ fn no_such_course() -> AppError { }) } -/// Write the blueprint. A second one for the same grade is a 409 the store -/// itself decides — the grade is the record key, so the duplicate is seen -/// rather than raced. -/// -/// Not [`transaction_with_retry`]: the `CREATE` here can legitimately answer -/// "already exists", which that loop cannot tell from a lost round and would -/// re-send until the tries ran out — turning this 409 into a 500. A round -/// genuinely lost to a concurrent course delete is therefore an error the -/// caller retries, with nothing written. +/// Write the blueprint's row. A second one for the same grade is a 409 the +/// store itself decides — the grade is the primary key, so the duplicate is +/// seen rather than raced (`23505` on `class_blueprint_pkey`, mapped right +/// here: a duplicate is a decision, never a retry). pub async fn create( db: &Database, creator: &UserId, @@ -84,51 +78,50 @@ pub async fn create( ) -> Result { let blueprint = ClassBlueprint { id: ClassBlueprintId::for_grade(&grade), - grade, - courses, + grade: grade.clone(), + courses: courses.clone(), creator: creator.clone(), }; - let named: Vec = blueprint.courses.iter().map(CourseId::record).collect(); - let mut result = db - .query(format!( - "BEGIN TRANSACTION; - {}; - CREATE $id CONTENT $row; - COMMIT TRANSACTION;", - courses_alive() - )) - .bind(("id", blueprint.id.record())) - .bind(("row", blueprint)) - .bind(("courses", named)) - .await?; - let mut errors = result.take_errors(); - if errors - .values() - .any(|error| error.to_string().contains(DEAD_MARK)) - { - return Err(no_such_course()); - } - if errors.values().any(surrealdb::Error::is_already_exists) { - return Err(AppError::Conflict( - "a blueprint already exists for that grade", - )); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN and the FOR: the CREATE is slot 2. - result - .take::>(2)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to create blueprint".into())) + tx_with_retry(db, false, async |tx| { + courses_alive(tx, &courses).await?; + let inserted = sqlx::query!( + r#"INSERT INTO class_blueprint (grade, courses, creator) + VALUES ($1, $2, $3)"#, + grade as _, + courses as _, + creator as _ + ) + .execute(&mut *tx) + .await; + match inserted { + Ok(_) => Ok(blueprint), + Err(e) if unique_violation(&e) == Some("class_blueprint_pkey") => Err( + AppError::Conflict("a blueprint already exists for that grade"), + ), + Err(e) => Err(e.into()), + } + }) + .await } pub async fn read( db: &Database, id: &ClassBlueprintId, ) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let row = sqlx::query!( + r#"SELECT grade AS "id: ClassBlueprintId", grade AS "grade: ClassGrade", + courses AS "courses: Vec", creator AS "creator: UserId" + FROM class_blueprint WHERE grade = $1"#, + id as _ + ) + .fetch_optional(db) + .await?; + Ok(row.map(|row| ClassBlueprint { + id: row.id, + grade: row.grade, + courses: row.courses, + creator: row.creator, + })) } /// Every blueprint, by grade label — the id *is* the label, so this is the @@ -138,7 +131,7 @@ pub async fn list_all( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new(CLASS_BLUEPRINT_TABLE, "ORDER BY id ASC") + PagedList::new(CLASS_BLUEPRINT_TABLE, "ORDER BY grade ASC") .run(limit, offset, db) .await } @@ -150,44 +143,34 @@ pub async fn list_all( /// it, and only the caller can tell those apart (the workflow re-reads and /// answers a `409` or a `404`). /// -/// A template naming a course that is gone aborts with [`DEAD_MARK`] and is -/// reported as the caller's own pre-flight `400`. +/// A template naming a course that is gone refuses inside the transaction +/// with the pre-flight `400` ([`courses_alive`]). pub async fn set_courses_if_unchanged( db: &Database, id: &ClassBlueprintId, held: Vec, wanted: Vec, ) -> Result, AppError> { - let named: Vec = wanted.iter().map(CourseId::record).collect(); - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - {}; - UPDATE $id SET courses = $wanted WHERE courses = $held RETURN AFTER; - COMMIT TRANSACTION;", - courses_alive() - ), - &[ - ("id".into(), id.record().into_value()), - ("wanted".into(), wanted.into_value()), - ("held".into(), held.into_value()), - ("courses".into(), named.into_value()), - ], - &[DEAD_MARK], - ) - .await?; - if errors - .values() - .any(|error| error.to_string().contains(DEAD_MARK)) - { - return Err(no_such_course()); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN and the FOR: the UPDATE is slot 2. - Ok(result.take::>(2)?.into_iter().next()) + tx_with_retry(db, false, async |tx| { + courses_alive(tx, &wanted).await?; + let updated = sqlx::query!( + r#"UPDATE class_blueprint SET courses = $2 + WHERE grade = $1 AND courses = $3 + RETURNING grade AS "grade: ClassGrade", creator AS "creator: UserId""#, + id as _, + wanted as _, + held as _ + ) + .fetch_optional(&mut *tx) + .await?; + Ok(updated.map(|row| ClassBlueprint { + id: id.clone(), + grade: row.grade, + courses: wanted, + creator: row.creator, + })) + }) + .await } /// 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( /// else's additions. `false` means the conditional delete matched nothing: /// the row is gone, or its list moved since the caller read it, and only the /// caller can tell those apart. +/// +/// The `DELETE` is also the whole of the serialization against the attaches +/// made on this blueprint's behalf: a sourced attach holds a `FOR KEY SHARE` +/// on this row across its transaction ([`class_pump::attach_course`]), so its +/// row lands before this delete's sweep runs or not at all — the invariant the +/// old process-wide write lease held, now on the row itself. pub async fn delete_if_unchanged( db: &Database, id: &ClassBlueprintId, held: Vec, ) -> Result { - let mut result = db - .query("DELETE $id WHERE courses = $held RETURN BEFORE") - .bind(("id", id.record())) - .bind(("held", held)) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) + let deleted = sqlx::query!( + r#"DELETE FROM class_blueprint WHERE grade = $1 AND courses = $2"#, + id as _, + held as _ + ) + .execute(db) + .await?; + Ok(deleted.rows_affected() > 0) } /// Every `class_course` row held by any of `classes`, projected down to the /// pair — the read [`crate::service::class_blueprint::status`] diffs the /// template against. -pub async fn held_links(db: &Database, classes: Vec) -> Result, AppError> { - let mut result = db - .query(format!( - "SELECT class, course FROM {CLASS_COURSE_TABLE} WHERE class IN $classes" - )) - .bind(("classes", classes)) - .await? - .check()?; - Ok(result.take::>(0)?) +pub async fn held_links(db: &Database, classes: Vec) -> Result, AppError> { + let rows = sqlx::query!( + r#"SELECT class AS "class: ClassGroupId", course AS "course: CourseId" + FROM class_course WHERE class = ANY($1)"#, + classes as _ + ) + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .map(|row| Held { + class: row.class, + course: row.course, + }) + .collect()) } /// Drop a course that no longer exists out of a blueprint's list. /// -/// The delete does this itself now: -/// [`crate::db::course::delete`] sweeps `class_blueprint` in -/// the same cascade that takes the course's `class_course` links, so a -/// template stops naming a course the instant that course goes. This used -/// to be the *only* thing that could remove such an id, and that was the -/// bug: it fires only while walking a section, so a grade with no sections -/// could never reach it, and the repair every doc surface pointed at -/// (`PATCH` the list back as it stands) is a `400` for naming a course that -/// does not exist. A permanent dangling id, and no call that could clear -/// it. +/// The delete does this itself now: the course's own cascade sweeps +/// `class_blueprint` in the same transaction that takes the course's +/// `class_course` links, so a template stops naming a course the instant that +/// course goes. This used to be the *only* thing that could remove such an id, +/// and that was the bug: it fires only while walking a section, so a grade +/// with no sections could never reach it, and the repair every doc surface +/// pointed at (`PATCH` the list back as it stands) is a `400` for naming a +/// course that does not exist. A permanent dangling id, and no call that could +/// clear it. /// /// What is left for this to do is the **window** the sweep cannot cover: a /// 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) -> Result Result<(), AppError> { - db.query("UPDATE $id SET courses = array::complement(courses ?? [], [$course])") - .bind(("id", id.record())) - .bind(("course", course.record())) - .await? - .check()?; + sqlx::query!( + r#"UPDATE class_blueprint SET courses = array_remove(courses, $2) WHERE grade = $1"#, + id as _, + course as _ + ) + .execute(db) + .await?; Ok(()) } @@ -279,7 +271,7 @@ pub async fn prune( /// what makes a repeated call a repair rather than a no-op: whatever a /// half-finished sweep left behind is exactly what the next one finds. /// -/// `source` is the whole filter, so a row without the key — a hand attach — +/// `source` is the whole filter, so a row without the tag — a hand attach — /// is never matched, and a class that acquired the same course by hand keeps /// it. The rows are read rather than derived from the classes at this grade: /// a class whose grade was edited after the pump still carries this @@ -288,29 +280,34 @@ pub async fn sourced_links( db: &Database, id: &ClassBlueprintId, keep: &[CourseId], -) -> Result, AppError> { - let named: Vec = keep.iter().map(CourseId::record).collect(); - let mut found = db - .query(format!( - "SELECT VALUE id FROM {CLASS_COURSE_TABLE} \ - WHERE source = $blueprint AND course NOT IN $keep" - )) - .bind(("blueprint", id.record())) - .bind(("keep", named)) - .await? - .check()?; - Ok(found.take::>(0)?) +) -> Result, AppError> { + let keep: Vec = keep.to_vec(); + let rows = sqlx::query!( + r#"SELECT class AS "class: ClassGroupId", course AS "course: CourseId" + FROM class_course + WHERE source = $1 AND course <> ALL($2)"#, + id as _, + keep as _ + ) + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .map(|row| Held { + class: row.class, + course: row.course, + }) + .collect()) } /// Detach the link rows [`sourced_links`] named and sweep the enrollments /// they pumped. The sweep underneath is the pump's own, so a student a /// second class still claims is re-tagged rather than unenrolled. /// -/// Each detach re-asserts the tag, because this loop deliberately runs -/// without the lease: the link's record id is the (class, course) pair and -/// says nothing about provenance, so a row a *new* blueprint at the same -/// grade attached while this ran would otherwise be swept by the old one's -/// tail. +/// Each detach re-asserts the tag: the link's identity is the (class, course) +/// pair and says nothing about provenance, so a row a *new* blueprint at the +/// same grade attached while this ran would otherwise be swept by the old +/// one's tail. /// /// One transaction per *link row*, which is the module note's "one /// transaction per (class, course)" and the mirror of the pump's @@ -326,19 +323,10 @@ pub async fn sourced_links( pub async fn drop_links( db: &Database, id: &ClassBlueprintId, - links: Vec, + links: Vec, ) -> Result<(), AppError> { for link in links { - detach( - db, - "$link WHERE source = $blueprint", - Axis::Course, - &[ - ("link".into(), link.into_value()), - ("blueprint".into(), id.record().into_value()), - ], - ) - .await?; + class_pump::detach_course(db, &link.class, &link.course, Some(id)).await?; } Ok(()) } diff --git a/src/db/class_course.rs b/src/db/class_course.rs index 5869e0e..1e0644a 100644 --- a/src/db/class_course.rs +++ b/src/db/class_course.rs @@ -1,17 +1,16 @@ -//! The `class_course` table: the course-axis attach transaction and the +//! The `class_course` table: the course-axis attach entry point and the //! attachment listing. The refusals-to-errors policy and the detach that turns //! a zero-row sweep into a 404 live in [`crate::service::class_course`]; the //! transaction itself is the pump's, [`crate::db::class_pump`]. use crate::constant::CLASS_COURSE_TABLE; use crate::database::Database; -use crate::db::class_pump::{Attached, Axis}; +use crate::db::class_pump::Attached; use crate::db::page::PagedList; use crate::domain::class_blueprint::ClassBlueprintId; -use crate::domain::class_course::{ClassCourse, ClassCourseId}; +use crate::domain::class_course::ClassCourse; use crate::domain::class_group::ClassGroupId; use crate::domain::course::CourseId; -use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -37,30 +36,13 @@ pub(crate) async fn attach_sourced( attached_by: &UserId, source: Option<&ClassBlueprintId>, ) -> Result, AppError> { - let link = ClassCourse { - id: ClassCourseId::composite(class, course), - class: class.clone(), - course: course.clone(), - attached_by: attached_by.clone(), - source: source.cloned(), - attached_at: Some(Timestamp::now()), - }; - crate::db::class_pump::attach( - db, - class, - Axis::Course, - (&link.id.record(), &link), - course.record(), - attached_by.record(), - source.map(ClassBlueprintId::record), - ) - .await + crate::db::class_pump::attach_course(db, class, course, attached_by, source).await } /// The courses a class is attached to, newest first — by when they were -/// attached, not by the course's own id, which is what the composite record -/// id sorts on. A row older than the column carries no stamp at all, and -/// NONE sorts last under DESC — the honest place for a row of unknown age. +/// attached. The composite primary key is the tiebreaker (class, then course: +/// the two halves of the id this order used to sort), which makes the order +/// total. pub async fn list_for_class( db: &Database, class: &ClassGroupId, @@ -68,10 +50,10 @@ pub async fn list_for_class( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - format!("{CLASS_COURSE_TABLE} WHERE class = $class"), - "ORDER BY attached_at DESC, id DESC", + format!("{CLASS_COURSE_TABLE} WHERE class = $1"), + "ORDER BY attached_at DESC, class DESC, course DESC", ) - .bind("class", class.record()) + .bind(class.uuid()) .run(limit, offset, db) .await } diff --git a/src/db/class_group.rs b/src/db/class_group.rs index 9ab31f5..b46de3d 100644 --- a/src/db/class_group.rs +++ b/src/db/class_group.rs @@ -1,13 +1,10 @@ -//! The `class_group` table: the row, its term reference claimed through -//! [`crate::db::cap`] in the same transaction as the link, and the 0/0 delete -//! guard. The archived-term guard and the route-facing wrappers live in +//! The `class_group` table: the row, its term reference claimed through the +//! [`crate::db::cap`] shapes in the same statement as the link, and the 0/0 +//! delete guard. The archived-term guard and the route-facing wrappers live in //! [`crate::service::class_group`]. -use surrealdb::types::{RecordId, SurrealValue}; - -use crate::constant::{CLASS_COURSE_COUNT_FIELD, CLASS_MEMBER_COUNT_FIELD, TERM_CLASS_COUNT_FIELD}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; +use crate::constant::{CLASS_GROUP_TABLE, TERM_CLASS_COUNT_FIELD}; +use crate::database::{Database, tx_with_retry}; use crate::db::field_update::FieldUpdate; use crate::db::page::PagedList; use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName}; @@ -15,16 +12,13 @@ use crate::domain::term::{self, TermId}; use crate::domain::user::UserId; use crate::error::AppError; -/// The `THROW` marker the delete guard aborts with — a class that still holds -/// students or courses, or a class row that is no longer there. -const LINKS_MARK: &str = "class_links"; - /// Create the class, claiming a reference on the term it links (if any) in -/// the *same transaction* as the row, exactly as +/// the *same statement* as the row, exactly as /// [`crate::db::course::create`] does: the claim is a /// conditional write on the term row, so it fails when the term is already -/// gone, it makes the term undeletable the instant this link exists, and no -/// crash can leave either half without the other. +/// gone, it makes the term undeletable the instant this link exists, and — the +/// claim and the insert being one CTE — no crash and no refused claim can +/// leave either half without the other. pub async fn create( db: &Database, creator: &UserId, @@ -33,40 +27,77 @@ pub async fn create( term: Option, teacher: Option, ) -> Result { - let class = ClassGroup { - id: ClassGroupId::generate(), - creator: creator.clone(), - name, - grade, - term, - teacher, - }; - let id = class.id.record(); - let Some(term) = class.term.clone() else { - let created: Option = db.create(id).content(class).await?; - return created.ok_or_else(|| AppError::Internal("failed to create class".into())); - }; - match cap::claim_and_create( - &term.record(), - TERM_CLASS_COUNT_FIELD, - cap::UNLIMITED, - &id, - &class, - db, - ) - .await? - { - cap::Claimed::Made(created) => Ok(created), - // Uncapped, so "full" can only mean the conditional write matched no - // term row at all — the claim doubles as the existence check. - cap::Claimed::Full => Err(term::gone_error()), - // Unreachable: the id is a ULID this call just generated. - cap::Claimed::Duplicate => Err(AppError::Internal("failed to create class".into())), + let id = ClassGroupId::generate(); + match &term { + Some(term) => { + // The claim and the insert are one statement: atomic without an + // explicit transaction, exactly like every other + // single-statement guard. + let written = sqlx::query_as!( + ClassGroup, + r#"WITH seat AS ( + UPDATE term SET class_count = class_count + 1 + WHERE id = $1 + RETURNING 1) + INSERT INTO class_group (id, creator, name, grade, term, teacher) + SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id, creator, name, grade, term, teacher"#, + term.uuid(), + id.uuid(), + creator.uuid(), + name.as_str(), + grade.as_deref(), + teacher.as_ref() + ) + .fetch_optional(db) + .await; + match written { + Ok(Some(created)) => Ok(created), + // Uncapped, so a zero-row claim can only mean the conditional + // write matched no term row at all — the claim doubles as the + // existence check. + Ok(None) => Err(term::gone_error()), + // The term row is locked by the claim's own UPDATE, so this + // is unreachable; a defensible answer beats a 500. + Err(e) if crate::database::foreign_key_violation(&e) => Err(term::gone_error()), + // Unreachable: the id was minted one line above. + Err(e) if crate::database::unique_violation(&e).is_some() => { + Err(AppError::Internal("failed to create class".into())) + } + Err(e) => Err(e.into()), + } + } + None => { + let created = sqlx::query_as!( + ClassGroup, + r#"INSERT INTO class_group (id, creator, name, grade, term, teacher) + VALUES ($1, $2, $3, $4, $5, $6) + RETURNING id, creator, name, grade, term, teacher"#, + id.uuid(), + creator.uuid(), + name.as_str(), + grade.as_deref(), + term.as_ref(), + teacher.as_ref() + ) + .fetch_optional(db) + .await?; + // Unreachable: the id is a v7 uuid this call just generated. + created.ok_or_else(|| AppError::Internal("failed to create class".into())) + } } } pub async fn read(db: &Database, id: &ClassGroupId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let class = sqlx::query_as!( + ClassGroup, + r#"SELECT id, creator, name, grade, term, teacher + FROM class_group WHERE id = $1"#, + id.uuid() + ) + .fetch_optional(db) + .await?; + Ok(class) } /// Every class, newest first — or one grade's, when `grade` narrows it: @@ -84,13 +115,16 @@ pub async fn list_all( offset: i64, ) -> Result<(Vec, i64), AppError> { let list = match grade { - None => PagedList::new("class_group", "ORDER BY id DESC"), - // A gradeless class stores no `grade` key at all (SurrealDB drops a - // key valued NONE), and an absent field reads back as NONE — so the - // one comparison covers both spellings. - Some(None) => PagedList::new("class_group WHERE grade IS NONE", "ORDER BY id DESC"), - Some(Some(grade)) => PagedList::new("class_group WHERE grade = $grade", "ORDER BY id DESC") - .bind("grade", grade.as_str().to_string()), + None => PagedList::new(CLASS_GROUP_TABLE, "ORDER BY id DESC"), + Some(None) => PagedList::new( + format!("{CLASS_GROUP_TABLE} WHERE grade IS NULL"), + "ORDER BY id DESC", + ), + Some(Some(grade)) => PagedList::new( + format!("{CLASS_GROUP_TABLE} WHERE grade = $1"), + "ORDER BY id DESC", + ) + .bind(grade.as_str().to_string()), }; list.run(limit, offset, db).await } @@ -114,30 +148,34 @@ pub async fn update( teacher: Option>, ) -> Result { let (claim, release) = term::ref_move(class.term.as_ref(), &term); - let expected = class.term.as_ref().map(TermId::record); - FieldUpdate::new(class.id.record()) - .set("name", name) - .set("grade", grade) - .set("term", term.map(|term| term.map(|term| term.record()))) + let expected = class.term.as_ref().map(TermId::uuid); + FieldUpdate::new(CLASS_GROUP_TABLE, class.id.uuid()) + .set("name", name.map(|name| name.as_str().to_string())) + .set( + "grade", + grade.map(|grade| grade.map(|grade| grade.as_str().to_string())), + ) + .set("term", term.map(|term| term.map(|term| term.uuid()))) // Not refcounted: a homeroom assignment is a label, so it rides the // plain `set` path and never arms the term CAS. .set( "teacher", - teacher.map(|teacher| teacher.map(|teacher| teacher.record())), + teacher.map(|teacher| teacher.map(|teacher| teacher.uuid())), ) .refcount( + "term", TERM_CLASS_COUNT_FIELD, "term", expected, - claim, - release, + claim.map(|term| term.uuid()), + release.map(|term| term.uuid()), term::gone_error(), ) .run::(db) .await } -/// The classes `ids` names, in no particular order — the join behind +/// The classes `ids` name, in no particular order — the join behind /// "which class section is this student in", where the ids come from /// `class_member` rows already paged. Ids that name no row are simply /// absent. @@ -145,13 +183,16 @@ pub async fn list_by_ids(db: &Database, ids: &[ClassGroupId]) -> Result = ids.iter().map(ClassGroupId::record).collect(); - let mut result = db - .query("SELECT * FROM class_group WHERE id IN $ids") - .bind(("ids", records)) - .await? - .check()?; - Ok(result.take::>(0)?) + let ids: Vec = ids.to_vec(); + let classes = sqlx::query_as!( + ClassGroup, + r#"SELECT id, creator, name, grade, term, teacher + FROM class_group WHERE id = ANY($1)"#, + ids as _ + ) + .fetch_all(db) + .await?; + Ok(classes) } /// Every class section at one grade label, in no particular order — what a @@ -161,23 +202,28 @@ pub async fn list_for_grade( db: &Database, grade: &ClassGrade, ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM class_group WHERE grade = $grade") - .bind(("grade", grade.as_str().to_string())) - .await? - .check()?; - Ok(result.take::>(0)?) + let classes = sqlx::query_as!( + ClassGroup, + r#"SELECT id, creator, name, grade, term, teacher + FROM class_group WHERE grade = $1"#, + grade.as_str() + ) + .fetch_all(db) + .await?; + Ok(classes) } -/// Strip `user` from every class they were the homeroom teacher of — the +/// Clear the homeroom teacher everywhere `user` held one — the /// sweep for a user demoted below `teacher`, who may no longer hold one. /// The mirror of [`crate::db::course::unassign_everywhere`]; /// nothing is counted on this column, so there is no reference to give back. pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> { - db.query("UPDATE class_group SET teacher = NONE WHERE teacher = $usr") - .bind(("usr", user.record())) - .await? - .check()?; + sqlx::query!( + r#"UPDATE class_group SET teacher = NULL WHERE teacher = $1"#, + user.uuid() + ) + .execute(db) + .await?; Ok(()) } @@ -189,49 +235,48 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App /// `false` = refused, nothing was written. Both counts are read off the /// class's own row, so the check and the delete are one conditional write on /// one record — a member or attach racing this either claims first (and the -/// delete is refused) or finds the row gone (and is refused itself). +/// delete is refused) or finds the row gone (and is refused itself). The /// `Err(NotFound)` keeps the answer a concurrent *delete* used to get. pub async fn delete(db: &Database, class: ClassGroup) -> Result { - // Parenthesized `??` throughout: `n ?? 0 = 0` parses as `n ?? (0 = 0)`, - // which is truthy for every row and would delete a class still in use. - let sql = format!( - "BEGIN TRANSACTION; - LET $gone = (DELETE $class WHERE ({CLASS_MEMBER_COUNT_FIELD} ?? 0) = 0 \ - AND ({CLASS_COURSE_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE); - IF array::len($gone) = 0 {{ THROW '{LINKS_MARK}' }}; - FOR $row IN $gone {{ - IF $row.term != NONE {{ - UPDATE $row.term SET {TERM_CLASS_COUNT_FIELD} = \ - math::max([({TERM_CLASS_COUNT_FIELD} ?? 0) - 1, 0]); - }}; - }}; - COMMIT TRANSACTION;" - ); - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the marker, and a lost - // round is re-sent rather than reported (see [`transaction_with_retry`]). - let (_, mut errors) = transaction_with_retry( - db, - &sql, - &[("class".into(), class.id.record().into_value())], - &[LINKS_MARK], - ) - .await?; - if errors - .values() - .any(|error| error.to_string().contains(LINKS_MARK)) - { - // Still linked or already gone: the guard cannot tell those apart, - // and only the refusal path pays for the extra read that can. - return match read(db, &class.id).await? { - Some(_) => Ok(false), - None => Err(AppError::NotFound), + tx_with_retry(db, false, async |tx| { + let gone = sqlx::query!( + r#"DELETE FROM class_group + WHERE id = $1 + AND class_member_count = 0 AND class_course_count = 0 + RETURNING term AS "term: Option""#, + class.id.uuid() + ) + .fetch_optional(&mut *tx) + .await?; + let Some(row) = gone else { + // Still linked or already gone: the guard cannot tell those + // apart, and only the refusal path pays for the extra read that + // can. + let standing = sqlx::query_scalar!( + r#"SELECT 1 AS "one" FROM class_group WHERE id = $1"#, + class.id.uuid() + ) + .fetch_optional(&mut *tx) + .await? + .is_some(); + return if standing { + Ok(false) + } else { + Err(AppError::NotFound) + }; }; - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - Ok(true) + if let Some(term) = row.term { + sqlx::query!( + r#"UPDATE term SET class_count = GREATEST(class_count - 1, 0) + WHERE id = $1"#, + term + ) + .execute(&mut *tx) + .await?; + } + Ok(true) + }) + .await } #[cfg(test)] @@ -547,9 +592,10 @@ mod tests { let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200)) .await .unwrap(); - let dead = crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200)) - .await - .unwrap(); + let dead = + crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200)) + .await + .unwrap(); let dead_id = dead.get_id().clone(); assert!(crate::db::term::delete(&db, dead).await.unwrap()); let class = class_on(Some(from.get_id().clone()), &db).await; @@ -610,9 +656,10 @@ mod tests { let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200)) .await .unwrap(); - let other = crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200)) - .await - .unwrap(); + let other = + crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200)) + .await + .unwrap(); let class = class_on(Some(from.get_id().clone()), &db).await; let stale = class.clone(); update( diff --git a/src/db/class_member.rs b/src/db/class_member.rs index 69ba1db..dfb2d84 100644 --- a/src/db/class_member.rs +++ b/src/db/class_member.rs @@ -11,10 +11,9 @@ use crate::domain::class_member::ClassMember; use crate::domain::user::UserId; use crate::error::AppError; -/// The class's roster, newest first — by when the student was added, not by -/// their account id, which is what the composite record id sorts on. -/// A row older than the column carries no stamp at all, and NONE sorts last -/// under DESC — which is the honest place for a row of unknown age. +/// The class's roster, newest first — by when the student was added. The +/// composite primary key is the tiebreaker (class, then user: the two halves +/// of the id this order used to sort), which makes the order total. pub async fn list_for_class( db: &Database, class: &ClassGroupId, @@ -22,10 +21,10 @@ pub async fn list_for_class( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - format!("{CLASS_MEMBER_TABLE} WHERE class = $class"), - "ORDER BY added_at DESC, id DESC", + format!("{CLASS_MEMBER_TABLE} WHERE class = $1"), + "ORDER BY added_at DESC, class DESC, app_user DESC", ) - .bind("class", class.record()) + .bind(class.uuid()) .run(limit, offset, db) .await } @@ -40,10 +39,10 @@ pub async fn list_for_user( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"), - "ORDER BY added_at DESC, id DESC", + format!("{CLASS_MEMBER_TABLE} WHERE app_user = $1"), + "ORDER BY added_at DESC, class DESC, app_user DESC", ) - .bind("usr", user.record()) + .bind(user.uuid()) .run(limit, offset, db) .await } diff --git a/src/db/class_pump.rs b/src/db/class_pump.rs index ac51124..83f65a8 100644 --- a/src/db/class_pump.rs +++ b/src/db/class_pump.rs @@ -2,91 +2,46 @@ //! `enrollment` row that link implies reconciled with it, in one transaction. //! //! A class section (şube) has two link tables — `class_member` (a student in -//! it) and -//! `class_course` (a course attached to it) — and the *product* of the two is -//! the roster it owes: every member is enrolled in every attached course, in -//! real `enrollment` rows tagged [`source`](crate::domain::enrollment) with the -//! class that wrote them. Adding a member and attaching a course are therefore -//! the same operation seen along its two axes, and so are removing one and -//! detaching the other. That axis is what these two primitives take as a -//! parameter, so the four public operations are each a couple of lines. +//! it) and `class_course` (a course attached to it) — and the *product* of the +//! two is the roster it owes: every member is enrolled in every attached +//! course, in real `enrollment` rows tagged [`source`](crate::domain::enrollment) +//! with the class that wrote them. Adding a member and attaching a course are +//! therefore the same operation seen along its two axes, and so are removing +//! one and detaching the other. //! //! What is *not* one primitive is attach and detach. They share no statement: -//! one gates on "this pair already holds a row" and claims two counters -//! upwards, the other gates on nothing, releases, and has to decide per -//! enrollment row whether a *rival* class still claims it. Folding them behind -//! a direction flag would be one function containing two, so the seam stays -//! where the SQL puts it. +//! one gates on "this pair already holds a row" and claims a counter upwards, +//! the other gates on nothing, releases, and has to decide per enrollment row +//! whether a *rival* class still claims it. //! -//! Everything here writes counters the way [`crate::db::cap`] does — a -//! single-record conditional `UPDATE`, never a count-then-write — and every -//! `??` is parenthesized, because `n ?? 0 < $cap` parses as `n ?? (0 < $cap)` -//! and is truthy for every row. - -use surrealdb::types::{RecordId, SurrealValue, Value}; - -use crate::constant::{ - CLASS_COURSE_COUNT_FIELD, CLASS_COURSE_TABLE, CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE, - ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS, -}; -use crate::database::{Database, transaction_with_retry}; +//! Every invariant is one Postgres statement or one row lock, in the shapes +//! [`crate::db::cap`] documents: the class counter is claimed by a conditional +//! `UPDATE` fused with the link's `INSERT` (one CTE — a refused insert takes +//! its own seat bump back), a duplicate is the link table's natural composite +//! primary key answering as `23505`, a gone parent is a real `FOREIGN KEY` +//! answering as `23503`, and the row locks (`FOR KEY SHARE` / `FOR NO KEY +//! UPDATE`) put each transaction on the very record a racing writer must +//! touch. A refusal is an early `Err` (or an `Ok` verdict) from the +//! [`crate::database::tx_with_retry`] closure — a decision, never a retry. + +use sqlx::postgres::PgConnection; + +use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; +use crate::database::{Database, foreign_key_violation, tx_with_retry, unique_violation}; use crate::db::cap; -use crate::db::class_group; +use crate::domain::class_blueprint::ClassBlueprintId; +use crate::domain::class_course::ClassCourse; use crate::domain::class_group::ClassGroupId; +use crate::domain::class_member::ClassMember; +use crate::domain::course::CourseId; +use crate::domain::role::Role; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; use crate::error::AppError; -/// The `THROW` markers [`attach`] aborts with. `FULL_MARK` and `MISSING_MARK` -/// are *prefixes*: the record id of the course the loop stopped on is appended -/// to them, because neither "the class does not fit" nor "that course is gone" -/// is answerable without naming the course, and the loop only learns which one -/// at runtime. The whole id and not just the key, so the refusal names -/// something a caller can look up without knowing which table it came from. -/// -/// `MISSING_MARK` is deliberately not `FULL_MARK`: a seat claim that matches -/// nothing means "full" *or* "no such row", and reporting a class-course link -/// left pointing at a deleted course as a full course sends the caller to raise -/// a capacity that does not exist, on a class every member add now fails on. -/// -/// `CAP_MARK` is the class counter's claim matching nothing, which is "the -/// class is full" *or* "the class is gone" — one conditional write cannot say -/// which, so it stays one marker and the read that tells them apart is paid for -/// only on that path (the same shape as -/// [`crate::db::enrollment::enroll`]). It is not `GONE_MARK`: -/// that one is the *pivot* claim, which is a different row. -/// -/// `OVER_MARK` is the *other* axis already standing above its own ceiling — -/// which no claim on this axis can see, and which is what bounds this -/// transaction's write loop (see [`Axis::cap`]). It is its own marker because -/// "this class holds too many courses" is not an answer anyone can act on when -/// it is reported as "this class holds too many students". -/// -/// `SOURCE_MARK` is the record that *asked* for this attach — a grade blueprint -/// — being gone by the time the transaction runs. It is the only marker a -/// caller opts into (only a sourced attach states the claim), and it exists -/// because a blueprint's delete sweeps by that tag: a row landing after the -/// sweep would carry the name of a template no sweep can ever reach again. -const HELD_MARK: &str = "class_held"; -const GONE_MARK: &str = "class_gone"; -const CAP_MARK: &str = "class_cap"; -const OVER_MARK: &str = "class_over"; -const SOURCE_MARK: &str = "class_no_blueprint"; -const FULL_MARK: &str = "class_full:"; -const MISSING_MARK: &str = "class_no_course:"; - -/// An in-transaction existence claim as its own two statements: read `read` -/// into `$name`, and abort with `mark` when it matched nothing. -/// -/// Two statements and not one string, because [`attach`] takes the `CREATE`'s -/// result slot off the *length* of its statement list — a pair returned as one -/// element would count as one slot and silently read the wrong result back. -fn claim(name: &str, read: &str, mark: &str) -> Vec { - vec![ - format!("LET ${name} = ({read})"), - format!("IF array::len(${name}) = 0 {{ THROW '{mark}' }}"), - ] -} - -/// What [`attach`] settled. +/// What [`attach_course`]'s attach settled. The caller answers each verdict — +/// a hand attach turns them into this route's errors; a blueprint pump reads +/// them and carries on ([`crate::domain::class_blueprint`]). #[derive(Debug)] pub(crate) enum Attached { /// The link row, the counter and every enrollment it implied committed @@ -103,11 +58,10 @@ pub(crate) enum Attached { /// between them names the wrong one half the time. /// /// On the **member** axis the pivot is the student, and this means their - /// row is gone *or* their role no longer is `student` - /// ([`Axis::pivot_claim`]). Its one caller answers that as the `400` the - /// route's own read already answers, never as [`Attached::refusal_code`]'s - /// `course_deleted` — which is the course axis's word for it and would name - /// a record this refusal is not about. + /// row is gone *or* their role no longer is `student`. Its one caller + /// answers that as the `400` the route's own read already answers, never + /// as [`Attached::refusal_code`]'s `course_deleted` — which is the course + /// axis's word for it and would name a record this refusal is not about. PivotGone, /// The class is at its own ceiling on this axis. Nothing was written, and /// it is told apart from [`Attached::Gone`] because a full class is a @@ -147,16 +101,14 @@ impl Attached { /// one cause can never grow two codes. /// /// Each code names the record that actually failed. The two "gone" answers - /// are a *class* delete ([`Attached::Gone`] → `class_deleted`, the class - /// counter's claim matching nothing on a row a re-read no longer finds) and - /// a *course* delete ([`Attached::PivotGone`] → `course_deleted`, the - /// course's own claim matching nothing) — and telling a manager the class - /// vanished when the course did sends them to look at a section that is - /// standing right there. `linked_course_missing` is a third: *another* - /// course already attached to this class no longer exists, and it must be - /// detached before this attach can be retried. `blueprint_deleted` is a - /// pump losing the template itself mid-run — the only refusal that says - /// nothing about the (class, course) pair it names. + /// are a *class* delete ([`Attached::Gone`] → `class_deleted`) and a + /// *course* delete ([`Attached::PivotGone`] → `course_deleted`) — and + /// telling a manager the class vanished when the course did sends them to + /// look at a section that is standing right there. `linked_course_missing` + /// is a third: *another* course already attached to this class no longer + /// exists, and it must be detached before this attach can be retried. + /// `blueprint_deleted` is a pump losing the template itself mid-run — the + /// only refusal that says nothing about the (class, course) pair it names. /// /// The `axis` is a parameter because two of these answers name a *different /// ceiling* on each of them: [`Attached::ClassFull`] is the ceiling of the @@ -182,6 +134,7 @@ impl Attached { /// Which way the pump runs: the loop below needs a `(course, user)` pair per /// enrollment, and each caller supplies one side as a constant and reads the /// other off the class's *other* link table. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Axis { /// A student joining: the courses come from `class_course`. Member, @@ -190,122 +143,36 @@ pub(crate) enum Axis { } impl Axis { - /// The `SELECT` that yields this run's `(course, user)` pairs, with `$pivot` - /// bound to the fixed side. In-crate text, never client input. - fn pairs(&self) -> String { - match self { - Axis::Member => format!( - "SELECT VALUE {{ course: course, user: $pivot }} \ - FROM {CLASS_COURSE_TABLE} WHERE class = $class" - ), - Axis::Course => format!( - "SELECT VALUE {{ course: $pivot, user: user }} \ - FROM {CLASS_MEMBER_TABLE} WHERE class = $class" - ), - } - } - - /// The enrollment rows a *detached* link of this axis is responsible for, - /// as a `WHERE` fragment over `enrollment`. Read off the deleted link row - /// rather than a bound parameter, so one loop serves a single detach and a - /// user's whole membership alike. - fn scope(&self) -> &'static str { - match self { - Axis::Member => "user = $link.user", - Axis::Course => "course = $link.course", - } - } - - /// The in-transaction proof that this axis's *pivot* row is still there, - /// as the statements that claim it. - /// - /// The class counter's conditional claim covers the class; nothing covered - /// the course. With an empty roster the pair loop in [`attach`] touches no - /// row at all, so a concurrent `DELETE /courses/{id}` conflicts with - /// nothing — SurrealDB does not conflict-check that (write-skew) — and the - /// attach commits a `class_course` row pointing at a course that no longer - /// exists. A conditional write on the course row *is* the check: it matches - /// nothing once the row is gone, and it puts this transaction on the very - /// record the course's delete guard writes. - /// - /// The counter is *moved* — bumped, gated, then restored to the value this - /// transaction found — because re-stating it verbatim claims nothing: an - /// `UPDATE` that leaves the document unchanged is elided by SurrealDB 3.2.3 - /// and never enters the write set, so `count = count` sat on no key at all - /// and a concurrent `DELETE /courses/{id}` committed beside it with both - /// callers told OK (measured on 3.2.3, counter present and absent alike). - /// Same shape as [`crate::db::exam_answer::save`]: the - /// restore is by captured value, `NONE` included, so the row is - /// byte-identical afterwards and the boot backfill still sees the `NONE` it - /// seeds off. Both statements are inside the transaction, so an abort - /// between them cannot leave a course counting a seat nobody took. - /// - /// The member axis moves a counter on the *user* row for the same reason in - /// a different key ([`cap::role_claim`]): a role change away from `student` - /// sweeps this class membership and every enrollment it pumped, on a - /// snapshot, so a join landing after that snapshot leaves a non-student on - /// a roster — counted against the class's delete guard — with nothing left - /// to re-sweep. Its refusal is [`Attached::PivotGone`] like the course - /// axis's, because both mean "the row this link hangs off may no longer - /// carry it". - fn pivot_claim(&self) -> Vec { - match self { - Axis::Member => cap::role_claim( - "pivot", - &format!("!= '{}'", crate::domain::role::Role::Student.as_str()), - GONE_MARK, - ), - Axis::Course => { - let mut claimed = vec![format!( - "LET $was_alive = (SELECT VALUE {ENROLLMENT_COUNT_FIELD} FROM ONLY $pivot)" - )]; - claimed.extend(claim( - "alive", - &format!( - "UPDATE $pivot SET {ENROLLMENT_COUNT_FIELD} = \ - ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id" - ), - GONE_MARK, - )); - claimed.push(format!( - "UPDATE $pivot SET {ENROLLMENT_COUNT_FIELD} = $was_alive" - )); - claimed - } - } - } - /// The class counter this axis's link rows are counted on. Taken off the /// axis rather than passed in beside it, because the two are one fact and a /// call site that paired the member axis with the course counter would - /// compile, pass every test — both are `&str` — and desync the class delete - /// guard forever. - fn counter(&self) -> &'static str { + /// compile, pass every test — both are `&'static str` — and desync the + /// class delete guard forever. + fn counter(self) -> &'static str { match self { - Axis::Member => CLASS_MEMBER_COUNT_FIELD, - Axis::Course => CLASS_COURSE_COUNT_FIELD, + Axis::Member => "class_member_count", + Axis::Course => "class_course_count", } } - /// How many link rows this axis's counter may reach. Taken off the axis - /// beside the counter it bounds, for the same reason. + /// How many link rows this axis's counter may reach. /// - /// This is what makes the pair loop in [`attach`] finite, and it does it - /// *crosswise*: the member axis's loop iterates the class's `class_course` - /// rows, which the course axis's counter caps, and the course axis's loop - /// iterates its `class_member` rows, which the member axis's counter caps. - /// So bounding the two counters bounds both write loops — one transaction - /// can never carry more than `MAX_CLASS_MEMBERS`/`MAX_CLASS_COURSES` - /// enrollment writes. + /// This is what makes the pair loop in [`add_member`]/[`attach_course`] + /// finite, and it does it *crosswise*: the member axis's loop iterates the + /// class's `class_course` rows, which the course axis's counter caps, and + /// the course axis's loop iterates its `class_member` rows, which the + /// member axis's counter caps. So bounding the two counters bounds both + /// write loops — one transaction can never carry more than + /// `MAX_CLASS_MEMBERS`/`MAX_CLASS_COURSES` enrollment writes. /// /// Crosswise is also why the claim alone is not enough. It bounds the axis /// being *added*, and the loop it runs is the length of the *other* one: a /// class that already holds more members than `MAX_CLASS_MEMBERS` — the /// layer shipped before either ceiling existed, so a real volume can carry /// one — could still have a course attached, and that attach writes one - /// enrollment per member. So [`attach`] checks the other axis too + /// enrollment per member. So the attach checks the other axis too /// ([`Axis::other`]), and the bound holds for stale classes as well. - fn cap(&self) -> i64 { + fn cap(self) -> i64 { match self { Axis::Member => MAX_CLASS_MEMBERS, Axis::Course => MAX_CLASS_COURSES, @@ -315,7 +182,7 @@ impl Axis { /// The refusal code for "the class is *at* this axis's ceiling" /// ([`Attached::ClassFull`]), taken off the axis beside the `cap` it /// reports, because that ceiling and its name are one fact. - fn at_ceiling_code(&self) -> &'static str { + fn at_ceiling_code(self) -> &'static str { match self { Axis::Member => "class_at_roster_ceiling", Axis::Course => "class_at_course_ceiling", @@ -327,7 +194,7 @@ impl Axis { /// may be ([`Attached::ClassOverloaded`]). Answered off the axis that is /// over, never the one being attached — the two are always different axes, /// which is exactly what the blind version got wrong. - fn over_ceiling_code(&self) -> &'static str { + fn over_ceiling_code(self) -> &'static str { match self { Axis::Member => "class_roster_too_large", Axis::Course => "class_course_list_too_large", @@ -337,7 +204,7 @@ impl Axis { /// The axis whose link rows this one's write loop iterates — its counter is /// the length of that loop, and its ceiling is therefore the second half of /// the bound. - fn other(&self) -> Axis { + fn other(self) -> Axis { match self { Axis::Member => Axis::Course, Axis::Course => Axis::Member, @@ -345,338 +212,689 @@ impl Axis { } } -// The sweep a role change *off* `student` owes — every class membership (each -// class getting its member count back) and every enrollment row (each course -// getting its seat back) — is two of the arms of -// [`crate::service::user::set_role`], because it belongs in the same -// transaction as the role write that invalidates them. It stays one fact with -// the counters either way: released separately, a failure between the halves -// left enrollment rows tagged `source = class_group:X` while the class had its -// counters back, so the class passed its zero-zero delete guard and the rows -// were left pointing at a class no sweep could ever reach again. +/// The pivot of an attach: the row the link hangs off on its own axis, which +/// must still be there — and, on the member axis, still name a `student` — +/// when the transaction runs. +enum Pivot<'a> { + User(&'a UserId), + Course(&'a CourseId), +} -/// Write `link` and enroll everything it implies, or write nothing at all. -/// -/// The order is the one [`cap::claim_and_create`] settled on and for the same -/// reason: the link is looked for *before* any counter moves, so "you are -/// already in" outranks "there is no room" — a caller whose row a rival placed -/// a moment ago must not be told a course is full about seats they already -/// hold. -/// -/// The class counter is claimed by a conditional write rather than a bare -/// increment, so a class deleted out from under this run matches nothing and -/// the whole cascade aborts: [`Attached::Gone`] instead of a counter on a row -/// that no longer exists. The same write carries the axis's [`Axis::cap`], -/// which is what keeps the pair loop below — and therefore this transaction — -/// finite: [`Attached::ClassFull`] once the class is at its ceiling. -/// -/// Every enrollment in the loop is *skipped* when the pair already has a row — -/// no seat charged, and the existing row's `source` left exactly as it was, so -/// a hand-placed student is never quietly adopted by a class. Only the pairs -/// that had no row at all are charged, each against its own course's capacity. -/// -/// On admissibility ([`crate::database::transaction_with_retry`]): every -/// `CREATE` here is preceded by its own in-transaction existence check, so an -/// "already exists" can only come from a rival that landed inside that window — -/// and re-sending the whole cascade then *sees* the row and takes the other -/// branch. The retry converges instead of re-asking a settled question, which -/// is the restriction's actual test. +/// The verdicts the shared prechecks can settle before any counter moves. +enum Early { + Duplicate, + SourceGone, + PivotGone, + Overloaded, +} + +fn refusal_of(early: Early) -> Attached { + match early { + Early::Duplicate => Attached::Duplicate, + Early::SourceGone => Attached::SourceGone, + Early::PivotGone => Attached::PivotGone, + Early::Overloaded => Attached::ClassOverloaded, + } +} + +/// The gates that run before any counter moves, in the order their answers +/// outrank each other: /// -/// `source` is the record whose behalf this attach runs on — a grade blueprint -/// — and supplying it adds one more claim: that it is still there when the -/// transaction runs ([`Attached::SourceGone`]). A hand attach owns itself and -/// passes `None`. -pub(crate) async fn attach( - db: &Database, +/// 1. **Duplicate** — "you are already in" outranks "there is no room": a +/// caller whose row a rival placed a moment ago must not be told a course +/// is full about seats they already hold. (The link table's own primary key +/// re-answers this below as `23505` for a rival landing inside the window — +/// same verdict, no second seat.) +/// 2. **Source** — the blueprint that asked for this attach is still there. A +/// `FOR KEY SHARE` row lock on the blueprint row: it serializes the attach +/// against the blueprint's own delete — the closure the old process-wide +/// lease provided, now on the row itself. A concurrent blueprint `DELETE` +/// waits behind it and its sweep finds the committed row, while an attach +/// starting after the delete finds no row and writes nothing. `KEY SHARE` +/// is the weakest strength that blocks the delete, so two sourced attaches +/// still run concurrently, exactly as they did under the old shared read +/// lease. +/// 3. **Pivot** — the member axis takes the [`cap` role-claim +/// recipe](crate::db::cap)'s `FOR NO KEY UPDATE` handshake on the user row: +/// a role change away from `student` sweeps this membership, and demotion +/// and join now serialize on that row lock in both directions. The course +/// axis takes a `FOR KEY SHARE` on the course row, which a concurrent +/// course delete cannot take — the old bump-and-restore existence proof, +/// now a plain lock. +/// 4. **Overloaded** — the *other* axis standing above its own ceiling, which +/// no claim on this axis can see, and which is what bounds this +/// transaction's write loop. +async fn early_verdicts( + tx: &mut PgConnection, class: &ClassGroupId, axis: Axis, - new: (&RecordId, &T), - pivot: RecordId, - by: RecordId, - source: Option, -) -> Result, AppError> { - let (link, row) = new; - let count_field = axis.counter(); - let pairs = axis.pairs(); - let other = axis.other(); - let over_field = other.counter(); - // One statement per element, because the `CREATE`'s result slot is this - // list's own length at the moment it is pushed. It used to be a - // hand-counted constant with a case per optional claim, and only the path - // carrying that claim would ever have paid for a miscount. - let mut statements = vec![ - "BEGIN TRANSACTION".to_string(), - "LET $held = (SELECT VALUE id FROM $link)".to_string(), - format!("IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}"), - ]; - if source.is_some() { - statements.extend(claim("source", "SELECT VALUE id FROM $guard", SOURCE_MARK)); - } - statements.extend(axis.pivot_claim()); - // Read off the class row inside the transaction that claims it, so the - // count this refuses on is the one the pair loop below would iterate. - statements.push(format!( - "LET $over = (SELECT VALUE id FROM $class WHERE ({over_field} ?? 0) > $other_cap)" - )); - statements.push(format!( - "IF array::len($over) > 0 {{ THROW '{OVER_MARK}' }}" - )); - statements.push(format!( - "LET $counted = (UPDATE $class SET {count_field} = ({count_field} ?? 0) + 1 \ - WHERE ({count_field} ?? 0) < $class_cap RETURN VALUE id)" - )); - statements.push(format!( - "IF array::len($counted) = 0 {{ THROW '{CAP_MARK}' }}" - )); - // Taken as it is pushed: this is the slot the link row comes back out of. - let made = statements.len(); - statements.push("CREATE $link CONTENT $row".to_string()); - statements.push(format!( - "FOR $pair IN (({pairs}) ?? []) {{ - LET $seat_of = type::record('{ENROLLMENT_TABLE}', string::concat( - record::id($pair.course), '_', record::id($pair.user))); - IF array::len((SELECT VALUE id FROM $seat_of)) = 0 {{ - IF array::len((SELECT VALUE id FROM $pair.course)) = 0 {{ - THROW '{MISSING_MARK}' + $pair.course - }}; - LET $seat = (UPDATE $pair.course SET {ENROLLMENT_COUNT_FIELD} = \ - ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 \ - WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) < (capacity ?? $unlimited) \ - RETURN VALUE id); - IF array::len($seat) = 0 {{ - THROW '{FULL_MARK}' + $pair.course - }}; - CREATE $seat_of CONTENT {{ course: $pair.course, user: $pair.user, \ - enrolled_by: $by, source: $class }}; - }}; - }}" - )); - statements.push("COMMIT TRANSACTION".to_string()); - let sql = format!("{};", statements.join(";\n")); - let mut bindings = vec![ - ("class".into(), class.record().into_value()), - ("link".into(), link.clone().into_value()), - ("row".into(), row.clone().into_value()), - ("pivot".into(), pivot.into_value()), - ("by".into(), by.into_value()), - ("unlimited".into(), cap::UNLIMITED.into_value()), - ("class_cap".into(), axis.cap().into_value()), - ("other_cap".into(), other.cap().into_value()), - ]; - if let Some(guard) = source { - bindings.push(("guard".into(), guard.into_value())); - } - let (mut result, mut errors) = transaction_with_retry( - db, - &sql, - &bindings, - &[ - HELD_MARK, - GONE_MARK, - OVER_MARK, - SOURCE_MARK, - CAP_MARK, - FULL_MARK, - MISSING_MARK, - ], - ) - .await?; - // "Already linked" is read first: it outranks both refusals below, and the - // gate aborts before either could fire. - // - // Only the `THROW` is read, never an `is_already_exists` off the `CREATE` - // itself. A rival landing in the window between the gate and the create - // makes the store answer "already exists", which - // [`transaction_with_retry`] treats as a lost round and re-sends — and that - // re-send is the right answer, because the second pass *sees* the row at - // the gate. Reading it here would also mis-file the enrollment `CREATE`'s - // version of the same answer as "already in this class". - if errors - .values() - .any(|error| error.to_string().contains(HELD_MARK)) - { - return Ok(Attached::Duplicate); - } - // The blueprint that asked for this attach is gone, and that outranks every - // refusal below it: none of them is an answer anyone can act on once the - // template that wanted the row has been deleted — and its claim stands - // first in the transaction, so it aborts before they could fire anyway. - if errors - .values() - .any(|error| error.to_string().contains(SOURCE_MARK)) - { - return Ok(Attached::SourceGone); - } - if errors - .values() - .any(|error| error.to_string().contains(GONE_MARK)) - { - return Ok(Attached::PivotGone); - } - // Read before the ceiling below: a class over the *other* axis's ceiling is - // refused whether or not this axis has room, and being told it is full on - // an axis with places left is an answer nobody can act on. - if errors - .values() - .any(|error| error.to_string().contains(OVER_MARK)) - { - return Ok(Attached::ClassOverloaded); - } - // Full, or the class is gone — the counter claim matches nothing either - // way, and only this path pays for the read that tells them apart. - if errors - .values() - .any(|error| error.to_string().contains(CAP_MARK)) - { - return Ok(match class_group::read(db, class).await? { - Some(_) => Attached::ClassFull, - None => Attached::Gone, - }); - } - // The stale link is read before "full": both come out of the same seat - // claim matching nothing, and only one of them is a capacity problem. - if let Some(course) = errors - .values() - .find_map(|error| named_course(&error.to_string(), MISSING_MARK)) - { - return Ok(Attached::CourseGone(course)); + pivot: Pivot<'_>, + source: Option<&ClassBlueprintId>, +) -> Result, AppError> { + let held = match pivot { + Pivot::User(user) => sqlx::query_scalar!( + r#"SELECT 1 AS "one" FROM class_member WHERE class = $1 AND app_user = $2"#, + class as _, + user as _ + ) + .fetch_optional(tx) + .await? + .is_some(), + Pivot::Course(course) => sqlx::query_scalar!( + r#"SELECT 1 AS "one" FROM class_course WHERE class = $1 AND course = $2"#, + class as _, + course as _ + ) + .fetch_optional(tx) + .await? + .is_some(), + }; + if held { + return Ok(Some(Early::Duplicate)); } - if let Some(course) = errors - .values() - .find_map(|error| named_course(&error.to_string(), FULL_MARK)) - { - return Ok(Attached::Full(course)); + if let Some(source) = source { + let alive = sqlx::query_scalar!( + r#"SELECT 1 AS "one" FROM class_blueprint WHERE grade = $1 FOR KEY SHARE"#, + source as _ + ) + .fetch_optional(tx) + .await? + .is_some(); + if !alive { + return Ok(Some(Early::SourceGone)); + } } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); + match pivot { + Pivot::User(user) => { + let row = sqlx::query!( + r#"SELECT role AS "role: Role" FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#, + user as _ + ) + .fetch_optional(tx) + .await?; + if row.map(|row| row.role) != Some(Role::Student) { + return Ok(Some(Early::PivotGone)); + } + } + Pivot::Course(course) => { + let alive = sqlx::query_scalar!( + r#"SELECT 1 AS "one" FROM course WHERE id = $1 FOR KEY SHARE"#, + course as _ + ) + .fetch_optional(tx) + .await? + .is_some(); + if !alive { + return Ok(Some(Early::PivotGone)); + } + } } - result - .take::>(made)? + // Read off the class row inside the transaction that claims it, so the + // count this refuses on is the one the pair loop below would iterate. + let over = match axis.other() { + Axis::Member => sqlx::query_scalar!( + r#"SELECT 1 AS "one" FROM class_group + WHERE id = $1 AND class_member_count > $2"#, + class as _, + Axis::Member.cap(), + ) + .fetch_optional(tx) + .await? + .is_some(), + Axis::Course => sqlx::query_scalar!( + r#"SELECT 1 AS "one" FROM class_group + WHERE id = $1 AND class_course_count > $2"#, + class as _, + Axis::Course.cap(), + ) + .fetch_optional(tx) + .await? + .is_some(), + }; + Ok(over.then_some(Early::Overloaded)) +} + +/// Write the member link and enroll the student into every course the class is +/// already attached to, or write nothing at all. +/// +/// A student already enrolled in one of those courses keeps the row they +/// have — no seat is charged, and the existing row's `source` is left exactly +/// as it was, so a hand-placed student is never quietly adopted by a class. +/// A course with no free seat refuses the *whole* join rather than half of it. +/// +/// The class counter is claimed by the conditional half of the CTE below +/// rather than a bare increment, so a class deleted out from under this run +/// matches nothing and the whole cascade aborts: [`Attached::Gone`] instead of +/// a counter on a row that no longer exists. The same write carries +/// [`Axis::Member`]'s cap, which is what keeps the pair loop — and therefore +/// this transaction — finite: [`Attached::ClassFull`] once the class is at its +/// ceiling. Claim and insert are one statement, so a refused insert takes its +/// own seat bump back. +pub(crate) async fn add_member( + db: &Database, + class: &ClassGroupId, + user: &UserId, + by: &UserId, +) -> Result, AppError> { + let added_at = Timestamp::now(); + tx_with_retry(db, false, async |tx| { + if let Some(early) = + early_verdicts(tx, class, Axis::Member, Pivot::User(user), None).await? + { + return Ok(refusal_of(early)); + } + // The claim and the link are one statement (the cap recipe's CTE): the + // conditional `UPDATE` on the class row gates the `INSERT`, so a full + // or gone class writes nothing at all. + let inserted = match sqlx::query_scalar!( + r#"WITH seat AS ( + UPDATE class_group SET class_member_count = class_member_count + 1 + WHERE id = $1 AND class_member_count < $2 + RETURNING 1) + INSERT INTO class_member (class, app_user, added_by, added_at) + SELECT $1, $3, $4, $5 WHERE EXISTS (SELECT 1 FROM seat) + RETURNING 1 AS "one""#, + class as _, + Axis::Member.cap(), + user as _, + by as _, + added_at as _ + ) + .execute(tx) + .await + { + Ok(result) => result, + // A rival landed in the window between the gate and the insert: + // the link table's own primary key answers, same verdict as the + // gate, no second seat. + Err(e) if unique_violation(&e) == Some("class_member_class_user") => { + return Ok(Attached::Duplicate); + } + // The student row vanished mid-run despite the locked pivot claim. + Err(e) if foreign_key_violation(&e) => return Ok(Attached::PivotGone), + Err(e) => return Err(e.into()), + }; + if inserted.rows_affected() == 0 { + // Full, or the class is gone — the claim matches nothing either + // way, and only this path pays for the read that tells them apart. + let standing = sqlx::query_scalar!( + r#"SELECT 1 AS "one" FROM class_group WHERE id = $1"#, + class as _ + ) + .fetch_optional(&mut *tx) + .await? + .is_some(); + return Ok(if standing { + Attached::ClassFull + } else { + Attached::Gone + }); + } + let courses: Vec = sqlx::query_scalar!( + r#"SELECT course AS "course: uuid::Uuid" FROM class_course WHERE class = $1"#, + class as _ + ) + .fetch_all(&mut *tx) + .await? .into_iter() - .next() - .map(Attached::Made) - .ok_or_else(|| AppError::Internal("the class pump wrote no link row".into())) + .map(|row| row.course) + .collect(); + let pairs = courses.into_iter().map(|course| (course, user.uuid())); + match enroll_pairs(tx, class, pairs, by).await? { + Sweep::Done => {} + Sweep::CourseGone(course) => return Ok(Attached::CourseGone(course)), + Sweep::Full(course) => return Ok(Attached::Full(course)), + } + Ok(Attached::Made(ClassMember { + class: class.clone(), + user: *user, + added_by: *by, + added_at: Some(added_at), + })) + }) + .await } -/// The course id out of a `:` abort. Table names and the -/// generated ULID keys here are alphanumeric and `:` joins them, so the id ends -/// where the store's own wrapping around the thrown text begins. -fn named_course(message: &str, mark: &str) -> Option { - let id: String = message - .split_once(mark)? - .1 - .chars() - .take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | ':')) +/// Write the course link and enroll the class's whole roster into it, or +/// write nothing at all. +/// +/// Students already in the course keep the rows they have — no seat charged, +/// `source` untouched — and a roster that does not fit refuses the whole +/// attach rather than filling the course to its cap and stopping. +/// +/// `source` is the blueprint whose behalf this attach runs on, and supplying +/// it adds one more claim: that it is still there when the transaction runs +/// ([`Attached::SourceGone`]) — the `FOR KEY SHARE` lock that serializes this +/// transaction against the blueprint's own delete. A hand attach owns itself +/// and passes `None`. +pub(crate) async fn attach_course( + db: &Database, + class: &ClassGroupId, + course: &CourseId, + by: &UserId, + source: Option<&ClassBlueprintId>, +) -> Result, AppError> { + let attached_at = Timestamp::now(); + tx_with_retry(db, false, async |tx| { + if let Some(early) = + early_verdicts(tx, class, Axis::Course, Pivot::Course(course), source).await? + { + return Ok(refusal_of(early)); + } + let inserted = match sqlx::query_scalar!( + r#"WITH seat AS ( + UPDATE class_group SET class_course_count = class_course_count + 1 + WHERE id = $1 AND class_course_count < $2 + RETURNING 1) + INSERT INTO class_course (class, course, attached_by, attached_at, source) + SELECT $1, $3, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) + RETURNING 1 AS "one""#, + class as _, + Axis::Course.cap(), + course as _, + by as _, + attached_at as _, + source as _ + ) + .execute(tx) + .await + { + Ok(result) => result, + Err(e) if unique_violation(&e) == Some("class_course_class_course") => { + return Ok(Attached::Duplicate); + } + Err(e) if foreign_key_violation(&e) => return Ok(Attached::PivotGone), + Err(e) => return Err(e.into()), + }; + if inserted.rows_affected() == 0 { + let standing = sqlx::query_scalar!( + r#"SELECT 1 AS "one" FROM class_group WHERE id = $1"#, + class as _ + ) + .fetch_optional(&mut *tx) + .await? + .is_some(); + return Ok(if standing { + Attached::ClassFull + } else { + Attached::Gone + }); + } + let members: Vec = sqlx::query_scalar!( + r#"SELECT app_user AS "app_user: uuid::Uuid" FROM class_member WHERE class = $1"#, + class as _ + ) + .fetch_all(&mut *tx) + .await? + .into_iter() + .map(|row| row.app_user) .collect(); - (!id.is_empty()).then_some(id) + let pairs = members.into_iter().map(|user| (course.uuid(), user)); + match enroll_pairs(tx, class, pairs, by).await? { + Sweep::Done => {} + Sweep::CourseGone(course) => return Ok(Attached::CourseGone(course)), + Sweep::Full(course) => return Ok(Attached::Full(course)), + } + Ok(Attached::Made(ClassCourse { + class: class.clone(), + course: *course, + attached_by: *by, + source: source.cloned(), + attached_at: Some(attached_at), + })) + }) + .await } -/// Drop the link rows `links` names, give each class its counter back, and -/// sweep the enrollment rows those links pumped. Answers how many link rows -/// went, so a caller whose link was a single pair can turn zero into a 404. +/// What the shared enrollment loop settled for its pairs. +enum Sweep { + /// Every pair holds the row it owes. + Done, + /// One of the pairs' courses is gone, named by its key: a stale link. + CourseGone(String), + /// One of the pairs' courses has no free seat, named by its key. + Full(String), +} + +/// Enroll every `(course, user)` pair that has no row yet, each against its +/// own course's capacity, skipping — never charging — the pairs that do. /// -/// The sweep is *repair-first*: an enrollment this class wrote is only deleted -/// once no other class still claims it. Two classes attached to the same course -/// share a student — the second attach skipped the row the first had already -/// written, so the row carries only the first class's name — and deleting it on -/// the first class's way out would unenroll a student the second class is still -/// responsible for. So the row is re-tagged to that rival instead, and only a -/// row nobody is left to claim is deleted and its seat given back. The heir is -/// the lowest class id among the claimants: a deterministic pick, so a repeat -/// of the same sweep lands on the same class. +/// Per pair, in the order the refusals outrank each other: the pair's own row +/// answers "already enrolled" (skip, no seat); the course row answers "gone" +/// *before* the seat claim, so a stale link is never mis-reported as a +/// capacity problem; the seat claim is a conditional `UPDATE` on the course +/// row (live cap — `capacity` as it stands at write time, `NULL` reading as +/// unlimited); and the insert rides the seat it claimed. A rival that lands +/// between the gate and the insert answers `23505`, and the bump is given +/// back before the skip — the outcome a re-sent transaction used to reach by +/// seeing the rival's row at its gate. +/// +/// Every abort stops the loop inside the caller's transaction: not one of the +/// earlier seats in the same run survives, which is the whole point of doing +/// this in a transaction. +async fn enroll_pairs( + tx: &mut PgConnection, + class: &ClassGroupId, + pairs: impl Iterator, + by: &UserId, +) -> Result { + for (course, user) in pairs { + let held = sqlx::query_scalar!( + r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#, + course, + user + ) + .fetch_optional(&mut *tx) + .await? + .is_some(); + if held { + continue; + } + let alive = sqlx::query_scalar!(r#"SELECT 1 AS "one" FROM course WHERE id = $1"#, course) + .fetch_optional(&mut *tx) + .await? + .is_some(); + if !alive { + return Ok(Sweep::CourseGone(course.to_string())); + } + let seat = sqlx::query_scalar!( + r#"UPDATE course SET enrollment_count = enrollment_count + 1 + WHERE id = $1 AND enrollment_count < COALESCE(capacity, $2) + RETURNING 1 AS "one""#, + course, + cap::UNLIMITED, + ) + .fetch_optional(&mut *tx) + .await? + .is_some(); + if !seat { + return Ok(Sweep::Full(course.to_string())); + } + let wrote = sqlx::query_scalar!( + r#"INSERT INTO enrollment (course, app_user, enrolled_by, source) + VALUES ($1, $2, $3, $4) + ON CONFLICT (course, app_user) DO NOTHING + RETURNING 1 AS "one""#, + course, + user, + by as _, + class as _ + ) + .fetch_optional(&mut *tx) + .await; + match wrote { + Ok(Some(_)) => {} + // A rival placed the pair in the window: their row stands, no + // second seat, and the claim this run took is given back — the + // skip wins over the capacity answer, exactly as a re-sent + // transaction found the row at its gate. + Ok(None) => { + sqlx::query!( + r#"UPDATE course SET enrollment_count = enrollment_count - 1 + WHERE id = $1"#, + course + ) + .execute(&mut *tx) + .await?; + } + Err(e) if unique_violation(&e) == Some("enrollment_course_user") => { + sqlx::query!( + r#"UPDATE course SET enrollment_count = enrollment_count - 1 + WHERE id = $1"#, + course + ) + .execute(&mut *tx) + .await?; + } + Err(e) => return Err(e.into()), + } + } + Ok(Sweep::Done) +} + +// The sweep a role change *off` `student` owes — every class membership (each +// class getting its member count back) and every enrollment row (each course +// getting its seat back) — is two of the arms of +// [`crate::service::user::set_role`], because it belongs in the same +// transaction as the role write that invalidates them. It stays one fact with +// the counters either way: released separately, a failure between the halves +// left enrollment rows tagged `source = class_group:X` while the class had its +// counters back, so the class passed its zero-zero delete guard and the rows +// were left pointing at a class no sweep could ever reach again. + +/// Take a student out of a class and sweep the enrollments the class pumped +/// for them. Answers how many link rows went (0 or 1), so the caller can turn +/// zero into a 404. /// -/// That pick is then **claimed**, by the bump-and-restore -/// [`Axis::pivot_claim`] documents, before the row is handed over. Both reads -/// behind it are pure, and this sweep is long — one pass per enrollment row the -/// link implies — so `DELETE /classes/{heir}/members/{user}` and -/// `DELETE /classes/{heir}/courses/{course}` could both commit inside it, their -/// write sets disjoint from this one, and leave the row tagged with a class -/// holding neither link: a `class_group` whose own 0/0 delete guard then passes, -/// stranding an enrollment nothing can ever sweep (the state the note above -/// [`attach`] says must not exist). Every one of those writers moves a counter -/// on the heir's own row, so moving it here too puts this transaction on the -/// record they write and the store settles it. The field is -/// `class_member_count` for both axes: what has to collide is the *record*, and -/// a class whose membership or course list moved has had one of the two written -/// either way. +/// The sweep is *repair-first*: an enrollment this class wrote is only deleted +/// once no other class still claims it. Two classes attached to the same +/// course share a student — the second attach skipped the row the first had +/// already written, so the row carries only the first class's name — and +/// deleting it on the first class's way out would unenroll a student the +/// second class is still responsible for. So the row is re-tagged to that +/// rival instead, and only a row nobody is left to claim is deleted and its +/// seat given back. The heir is the lowest class id among the claimants: a +/// deterministic pick (uuid order is mint order), so a repeat of the same +/// sweep lands on the same class. /// -/// A claim that matches nothing is an heir whose class row is gone — a stale -/// link outliving its class — and it takes the release arm rather than tagging -/// the row with a record no route can reach. +/// That pick is then **claimed** — a `FOR NO KEY UPDATE` read of the heir's +/// class row, no counter moved — before the row is handed over. Both reads +/// behind it are pure, and this sweep is long — one pass per enrollment row +/// the link implies — so `DELETE /classes/{heir}/members/{user}` and +/// `DELETE /classes/{heir}/courses/{course}` could both commit inside it and +/// leave the row tagged with a class holding neither link: a `class_group` +/// whose own 0/0 delete guard then passes, stranding an enrollment nothing can +/// ever sweep. Every one of those writers moves a counter on the heir's own +/// row, so the row lock here puts this transaction on the record they write +/// and the two settle in either order. A claim that matches nothing is an +/// heir whose class row is gone — a stale link outliving its class — and it +/// takes the release arm rather than tagging the row with an id no route can +/// reach. /// -/// Sweeps tolerate rows that are already gone. `Course::delete` wipes a +/// Sweeps tolerate rows that are already gone. A course delete wipes a /// course's enrollments wholesale while the `class_member` rows survive it, so /// "this class has a member" and "that member has a live pumped row" are /// independent facts and the loop simply finds nothing to sweep. -/// -/// Admissible by construction: `DELETE` and `UPDATE` only, so no statement in -/// the cascade can answer "already exists" and every lost round is a plain -/// re-send. -pub(crate) async fn detach( +pub(crate) async fn remove_member( db: &Database, - links: &str, - axis: Axis, - bindings: &[(String, Value)], + class: &ClassGroupId, + user: &UserId, ) -> Result { - let count_field = axis.counter(); - let scope = axis.scope(); - // Nobody is left to claim the row: it goes, and its seat with it. Written - // once and used from both arms below, because "the heir's claim matched - // nothing" is the same answer as "there was no heir". - let release = format!( - "DELETE $row.id; - UPDATE $row.course SET {ENROLLMENT_COUNT_FIELD} = \ - math::max([({ENROLLMENT_COUNT_FIELD} ?? 0) - 1, 0]);" - ); - let sweep = format!( - "FOR $row IN ((SELECT id, course, user FROM {ENROLLMENT_TABLE} \ - WHERE {scope} AND source = $link.class) ?? []) {{ - LET $rivals = (SELECT VALUE class FROM {CLASS_COURSE_TABLE} \ - WHERE course = $row.course AND class != $link.class); - LET $heir = array::first(array::sort((SELECT VALUE class \ - FROM {CLASS_MEMBER_TABLE} WHERE user = $row.user AND class IN $rivals))); - IF $heir != NONE {{ - LET $was_heir = (SELECT VALUE {CLASS_MEMBER_COUNT_FIELD} FROM ONLY $heir); - LET $claimed = (UPDATE $heir SET {CLASS_MEMBER_COUNT_FIELD} = \ - ({CLASS_MEMBER_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); - UPDATE $heir SET {CLASS_MEMBER_COUNT_FIELD} = $was_heir; - IF array::len($claimed) > 0 {{ - UPDATE $row.id SET source = $heir; - }} ELSE {{ - {release} - }}; - }} ELSE {{ - {release} - }}; - }};" - ); - let sql = format!( - "BEGIN TRANSACTION; - LET $gone = (DELETE {links} RETURN BEFORE); - FOR $link IN ($gone ?? []) {{ - UPDATE $link.class SET {count_field} = math::max([({count_field} ?? 0) - 1, 0]); - {sweep} - }}; - RETURN array::len($gone); - COMMIT TRANSACTION;" - ); - let (mut result, mut errors) = transaction_with_retry(db, &sql, bindings, &[]).await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, the LET and the FOR: the RETURN is slot 3. - Ok(result.take::>(3)?.into_iter().next().unwrap_or(0)) + tx_with_retry(db, true, async |tx| { + let gone = sqlx::query_scalar!( + r#"DELETE FROM class_member WHERE class = $1 AND app_user = $2 + RETURNING 1 AS "one""#, + class as _, + user as _ + ) + .fetch_optional(tx) + .await?; + let Some(_) = gone else { + return Ok(0); + }; + sqlx::query!( + r#"UPDATE class_group + SET class_member_count = GREATEST(class_member_count - 1, 0) + WHERE id = $1"#, + class as _ + ) + .execute(&mut *tx) + .await?; + sweep_enrollments( + tx, + class, + sqlx::query!( + r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid" + FROM enrollment WHERE app_user = $1 AND source = $2"#, + user as _, + class as _ + ) + .fetch_all(&mut *tx) + .await? + .into_iter() + .map(|row| (row.course, row.app_user)) + .collect::>(), + ) + .await?; + Ok(1) + }) + .await +} + +/// Detach `course` from `class` and sweep the enrollments the class pumped +/// into it. `source`, when given, re-asserts the provenance tag on the link's +/// own delete — a blueprint sweep may only take back rows its own tag owns. +/// Answers how many link rows went, so a caller whose link was a single pair +/// can turn zero into a 404. The sweep underneath is the shared one: a student +/// a second class still claims is re-tagged rather than unenrolled. +pub(crate) async fn detach_course( + db: &Database, + class: &ClassGroupId, + course: &CourseId, + source: Option<&ClassBlueprintId>, +) -> Result { + tx_with_retry(db, true, async |tx| { + let gone = match source { + Some(source) => { + sqlx::query_scalar!( + r#"DELETE FROM class_course WHERE class = $1 AND course = $2 AND source = $3 + RETURNING 1 AS "one""#, + class as _, + course as _, + source as _ + ) + .fetch_optional(tx) + .await? + } + None => { + sqlx::query_scalar!( + r#"DELETE FROM class_course WHERE class = $1 AND course = $2 + RETURNING 1 AS "one""#, + class as _, + course as _ + ) + .fetch_optional(tx) + .await? + } + }; + let Some(_) = gone else { + return Ok(0); + }; + sqlx::query!( + r#"UPDATE class_group + SET class_course_count = GREATEST(class_course_count - 1, 0) + WHERE id = $1"#, + class as _ + ) + .execute(&mut *tx) + .await?; + sweep_enrollments( + tx, + class, + sqlx::query!( + r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid" + FROM enrollment WHERE course = $1 AND source = $2"#, + course as _, + class as _ + ) + .fetch_all(&mut *tx) + .await? + .into_iter() + .map(|row| (row.course, row.app_user)) + .collect::>(), + ) + .await?; + Ok(1) + }) + .await } -/// A composite id for a `(class, other)` link, the shape -/// [`crate::domain::enrollment::EnrollmentId::composite`] uses: the same pair -/// always maps to the same record, so one row per pair holds by construction -/// and a duplicate is something the store can *see* rather than something a -/// find-then-insert has to race. -pub(crate) fn link_id(table: &str, class: &ClassGroupId, other: &str) -> RecordId { - RecordId::new(table, format!("{}_{}", class.key(), other)) +/// The repair-first tail both detaches share: for every enrollment row the +/// deleted link owned, hand it to a rival class that still claims it, or +/// delete it and give the course its seat back. +/// +/// The heir is the lowest class id among the rivals that carry both this +/// course *and* the student — the same deterministic pick on every repeat. Its +/// class row is read `FOR NO KEY UPDATE` (a claim that moves no counter: the +/// class_member row already covers the student, and the enrollment is counted +/// on the course) so a concurrent member/course write on the heir serializes +/// behind this transaction; a claim matching nothing is a gone heir, and the +/// row takes the release arm. +async fn sweep_enrollments( + tx: &mut PgConnection, + class: &ClassGroupId, + rows: Vec<(uuid::Uuid, uuid::Uuid)>, +) -> Result<(), AppError> { + for (course, user) in rows { + let heir = sqlx::query_scalar!( + r#"SELECT cm.class AS "class: uuid::Uuid" + FROM class_member cm + JOIN class_course cc ON cc.class = cm.class AND cc.course = $1 + WHERE cm.app_user = $2 AND cm.class <> $3 + ORDER BY cm.class + LIMIT 1"#, + course, + user, + class as _ + ) + .fetch_optional(&mut *tx) + .await? + .map(|row| row.class); + let Some(heir) = heir else { + release(tx, course, user).await?; + continue; + }; + let claimed = sqlx::query_scalar!( + r#"SELECT class_member_count AS "heir_count: i64" FROM class_group + WHERE id = $1 FOR NO KEY UPDATE"#, + heir + ) + .fetch_optional(&mut *tx) + .await?; + if claimed.is_none() { + release(tx, course, user).await?; + continue; + } + sqlx::query!( + r#"UPDATE enrollment SET source = $1 WHERE course = $2 AND app_user = $3"#, + heir, + course, + user + ) + .execute(&mut *tx) + .await?; + } + Ok(()) } +/// Nobody is left to claim the row: it goes, and its seat with it. The seat +/// is only given back when the delete actually took the row — a course +/// delete's wholesale sweep may have taken both while this transaction read +/// them, and both halves vanish together there. +async fn release( + tx: &mut PgConnection, + course: uuid::Uuid, + user: uuid::Uuid, +) -> Result<(), AppError> { + let deleted = sqlx::query!( + r#"DELETE FROM enrollment WHERE course = $1 AND app_user = $2"#, + course, + user + ) + .execute(&mut *tx) + .await? + .rows_affected(); + if deleted > 0 { + sqlx::query!( + r#"UPDATE course SET enrollment_count = GREATEST(enrollment_count - 1, 0) + WHERE id = $1"#, + course + ) + .execute(&mut *tx) + .await?; + } + Ok(()) +} #[cfg(test)] mod tests { use super::*; diff --git a/src/domain/class_blueprint.rs b/src/domain/class_blueprint.rs index 9519ffa..c00abe0 100644 --- a/src/domain/class_blueprint.rs +++ b/src/domain/class_blueprint.rs @@ -15,11 +15,10 @@ //! shared skip vocabulary ([`skip_reason`]). //! //! The behavior lives one layer down: the edit-retro-pump, the apply/sweep -//! engine and its [`crate::service::class_blueprint::BLUEPRINT_LOCK`] lease -//! in [`crate::service::class_blueprint`], the queries in +//! engine in [`crate::service::class_blueprint`], the queries in //! [`crate::db::class_blueprint`]. -use crate::constant::{MAX_CLASS_COURSES}; +use crate::constant::MAX_CLASS_COURSES; use crate::db::class_pump::{Attached, Axis}; use crate::domain::class_course::ClassCourse; use crate::domain::class_group::{ClassGrade, ClassGroupId}; @@ -53,6 +52,9 @@ impl ClassBlueprintId { /// never has to parse a record id back into a domain value. #[derive(Debug, Clone, sqlx::FromRow)] pub struct ClassBlueprint { + /// The table's `TEXT` primary key column, stored once and read into both + /// this field and `grade` — the key *is* the grade label. + #[sqlx(rename = "grade")] pub(crate) id: ClassBlueprintId, pub(crate) grade: ClassGrade, pub(crate) courses: Vec, diff --git a/src/domain/class_group.rs b/src/domain/class_group.rs index 12cc779..2341f05 100644 --- a/src/domain/class_group.rs +++ b/src/domain/class_group.rs @@ -32,7 +32,7 @@ impl ClassGroupId { /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that /// cannot take the newtype. Static `query!` binds take `self` directly. - pub fn uuid(&self) -> Uuid { + pub fn uuid(&self) -> uuid::Uuid { self.0 } diff --git a/src/service/class_blueprint.rs b/src/service/class_blueprint.rs index 99809c4..91b967c 100644 --- a/src/service/class_blueprint.rs +++ b/src/service/class_blueprint.rs @@ -27,10 +27,6 @@ //! repairs before it deletes — and it runs one transaction per pair too, for //! the same reason the pump does. -use tokio::sync::RwLock; - -use surrealdb::types::RecordId; - use crate::database::Database; use crate::db::class_blueprint; use crate::db::class_course; @@ -39,45 +35,11 @@ use crate::db::class_pump::Attached; use crate::domain::class_blueprint::{ ClassBlueprint, ClassBlueprintId, Pumped, SectionStatus, Skip, skip_reason, }; -use crate::domain::class_group::{ClassGrade, ClassGroup}; +use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId}; use crate::domain::course::CourseId; use crate::domain::user::UserId; use crate::error::AppError; -/// Serializes a blueprint's delete against the attaches made on its behalf. -/// -/// [`delete`] removes the row and then sweeps by the provenance -/// tag, and every guarded attach reads that same row *inside* its own -/// transaction ([`crate::db::class_pump::attach`]'s `source` claim). Those -/// two are a cross-record read-then-write racing a write to the record read, -/// which `BEGIN`/`COMMIT` does not serialize (SurrealDB write skew): a pump can -/// see the blueprint alive, have the delete commit and sweep past it, and only -/// then commit its own `class_course` row — tagged with a record that no longer -/// exists and that no sweep can ever reach again, since the grade label *is* -/// the id. Delete-first and the in-transaction claim narrow that window; this -/// closes it. -/// -/// The delete holds the **write** lease across its compare-and-set and the read -/// that fixes the set of rows it will sweep — and no further. That is the whole -/// invariant: the sweep's row set must contain every attach this blueprint ever -/// committed, and no attach may commit one afterwards. An attach already in -/// flight holds the read lease, so the write lease waits for it and its row is -/// in the set; an attach starting after the lease is released finds the row -/// deleted and answers [`Attached::SourceGone`], writing nothing. The detaching -/// itself — one transaction per row, unbounded — therefore runs lease-free, -/// because `tokio`'s `RwLock` is *fair*: held across that loop, it parked every -/// concurrent `POST /classes` at every other grade behind one grade's delete. -/// Each guarded attach holds the **read** lease for the span of its own -/// transaction — taken per course in [`apply_to`], never around -/// a whole pump, so a delete waits behind one attach rather than an unbounded -/// loop. -/// -/// In-process is deployment-wide here: one process by contract, with -/// stop-the-world upgrades — the same argument -/// [`crate::service::settings::SETTINGS_LOCK`] makes. No other lock is taken -/// under it, so it has no ordering rule to break. -pub(crate) static BLUEPRINT_LOCK: RwLock<()> = RwLock::const_new(()); - /// Write the blueprint after settling the course list /// ([`ClassBlueprint::course_list`]) — the same validation, in the same /// order, the single write this replaced did. One blueprint per grade: a @@ -137,13 +99,12 @@ pub async fn list_all( /// templated course — what [`status`] reports and the next pump /// repairs — where the diff's failure was a row no call could reach. /// -/// Takes no [`BLUEPRINT_LOCK`] lease, deliberately: holding the write lease -/// across its own pump would deadlock on the read lease that pump takes, -/// and a lease would close nothing anyway — the pump's claim asks whether -/// the blueprint *exists*, not what it holds, so an edit racing a pump is -/// only ever the retro-pump this feature is built on. Rows a racing edit -/// leaves behind stay reachable, because [`delete`] sweeps the whole -/// tag rather than a list. +/// Takes no lease of its own, deliberately: a lease held across its own pump +/// would deadlock on the locks that pump takes, and it would close nothing +/// anyway — the attach's claim asks whether the blueprint *exists*, not what +/// it holds, so an edit racing a pump is only ever the retro-pump this +/// feature is built on. Rows a racing edit leaves behind stay reachable, +/// because [`delete`] sweeps the whole tag rather than a list. pub async fn set_courses( db: &Database, blueprint: ClassBlueprint, @@ -185,57 +146,55 @@ pub async fn set_courses( /// mirror image of a race: a `PATCH` adding a course and pumping it while /// this ran landed rows tagged with a blueprint the delete then removed, /// and nothing could ever sweep them again — the grade label *is* the -/// record id, so only a blueprint recreated at that grade could even name +/// primary key, so only a blueprint recreated at that grade could even name /// them. Never revert to sweep-first. /// -/// Deleting first plus the pump's own in-transaction claim on this row -/// ([`Attached::SourceGone`]) **narrows** that window; it does not close -/// it. The claim is a read of `class_blueprint` in a transaction that -/// writes `class_course`, racing this delete's write to -/// `class_blueprint` — a cross-record pair `BEGIN`/`COMMIT` does not -/// serialize, so a pump that read the row alive can still commit its link -/// after the sweep has run. [`BLUEPRINT_LOCK`] is what closes it: the write -/// lease below spans the compare-and-set and the sweep, the read lease in -/// [`apply_to`] spans each attach, and the deployment runs one -/// process by contract, which makes an in-process lock the whole answer. +/// Deleting first plus the attach's in-transaction claim on this row +/// ([`Attached::SourceGone`]) **closes** that window outright: the claim is +/// not a bare read but a `FOR KEY SHARE` row lock on `class_blueprint`, the +/// one strength a `DELETE` of the row cannot take. A sourced attach that +/// started first holds the row and this delete's `DELETE` waits behind it — +/// the row the attach commits is then in the set the sweep reads; an attach +/// starting after the delete finds no row and writes nothing. (Under the +/// old engine the claim was a plain read that no `BEGIN`/`COMMIT` pair +/// serialized against this delete's write, and a process-wide `RwLock` had +/// to stand in; the row lock is the same answer without the process.) /// -/// What is left is a **process crash** between the delete and the sweep — a -/// lock does not survive the process. That leaves inert `class_course` rows -/// tagged with a blueprint that is gone; they are still detachable one at a -/// time at `DELETE /classes/{id}/courses/{course}`, and every counter stays -/// exact because each detach is its own transaction. +/// What is left is a **process crash** between the delete and the sweep. +/// That leaves inert `class_course` rows tagged with a blueprint that is +/// gone; they are still detachable one at a time at +/// `DELETE /classes/{id}/courses/{course}`, and every counter stays exact +/// because each detach is its own transaction. /// /// The delete is a compare-and-set on the list this caller read, like /// [`set_courses`]: an edit landing in between is a `409` rather than /// a silent detach of somebody else's additions. Known hole, accepted: the -/// grade label *is* the record id and the comparison is by **content**, so +/// grade label *is* the primary key and the comparison is by **content**, so /// a blueprint deleted and recreated at the same grade with the same list /// satisfies `WHERE courses = $held` and this call deletes the *new* row. +/// /// Content-equal is intent-equal — the end state is the one the caller /// asked for — and telling the two apart needs a revision column on the /// row, which nothing else here would use. pub async fn delete(db: &Database, blueprint: ClassBlueprint) -> Result<(), AppError> { - let doomed = { - // Held across the delete and the read that fixes the sweep's row - // set, and released before the detaching: no attach can commit a row - // this read did not see, and none that starts afterwards writes one - // at all. - let _lease = BLUEPRINT_LOCK.write().await; - if !class_blueprint::delete_if_unchanged(db, &blueprint.id, blueprint.courses.clone()) - .await? - { - // Matched nothing: the row is gone, or its list moved since this - // caller read it. Only this path pays for the read that tells - // them apart. - return match read(db, &blueprint.id).await? { - Some(_) => Err(AppError::Conflict( - "this blueprint changed since you read it — re-read and retry", - )), - None => Err(AppError::NotFound), - }; - } - class_blueprint::sourced_links(db, &blueprint.id, &[]).await? - }; + if !class_blueprint::delete_if_unchanged(db, &blueprint.id, blueprint.courses.clone()).await? { + // Matched nothing: the row is gone, or its list moved since this + // caller read it. Only this path pays for the read that tells + // them apart. + return match read(db, &blueprint.id).await? { + Some(_) => Err(AppError::Conflict( + "this blueprint changed since you read it — re-read and retry", + )), + None => Err(AppError::NotFound), + }; + } + // The row set is read after the delete, and the delete itself is what + // serializes it against the attaches: a sourced attach holds a `FOR KEY + // SHARE` on the blueprint row across its transaction, so its row lands + // before this delete (and is in the set this read then sees) or finds the + // row gone and writes nothing at all. No attach can commit a row this + // read did not see, and none that starts afterwards writes one. + let doomed = class_blueprint::sourced_links(db, &blueprint.id, &[]).await?; class_blueprint::drop_links(db, &blueprint.id, doomed).await } @@ -246,13 +205,13 @@ pub async fn delete(db: &Database, blueprint: ClassBlueprint) -> Result<(), AppE /// /// This is the *only* place a sourced attach is made — [`pump`], the /// create-time and per-class pumps in [`crate::web::classes`] all come -/// through here — so it is where each one takes [`BLUEPRINT_LOCK`] for -/// reading, one course at a time. A delete landing mid-pump is then clean -/// by construction: the attaches that already committed are found by its -/// tag sweep, and the ones that have not yet started meet the deleted row -/// at their own in-transaction claim and answer `blueprint_deleted`. Per -/// course rather than per pump, because the pump's loop is unbounded and a -/// delete may not wait behind all of it. +/// through here — and each attach's transaction takes a `FOR KEY SHARE` +/// lock on the blueprint row itself, one course at a time. A delete landing +/// mid-pump is then clean by construction: the attaches that already +/// committed are found by its tag sweep, and the ones that have not yet +/// started meet the deleted row at their own in-transaction claim and +/// answer `blueprint_deleted`. Per course rather than per pump, because the +/// pump's loop is unbounded and a delete may not wait behind all of it. /// /// One class, so `blueprint_deleted` is an ordinary skip here: the courses /// after it are not tried, because the template they would ask for is the @@ -289,11 +248,9 @@ async fn apply_courses( if dead.contains(course) { continue; } - let landed = { - let _lease = BLUEPRINT_LOCK.read().await; + let landed = class_course::attach_sourced(db, class.get_id(), course, by, Some(&blueprint.id)) - .await? - }; + .await?; if matches!(landed, Attached::PivotGone) { class_blueprint::prune(db, &blueprint.id, course).await?; dead.push(course.clone()); @@ -321,9 +278,9 @@ async fn apply_courses( /// since a section cannot make either of them untrue. A course that no /// longer exists is pruned and skipped on the first class that meets it and /// left out of every class after it. And a `blueprint_deleted` **aborts the -/// grade loop**: under [`BLUEPRINT_LOCK`] that answer is precisely "a -/// delete landed mid-pump", so it is reported once and the remaining -/// classes are not walked. +/// grade loop**: the attach's `FOR KEY SHARE` row-lock claim makes that +/// answer precisely "a delete landed mid-pump", so it is reported once and +/// the remaining classes are not walked. /// /// The abort is still a `Ok(..)`, not an error: the attaches that committed /// before the delete stand (its sweep took the ones it could reach), and a @@ -391,9 +348,9 @@ pub async fn status( if sections.is_empty() { return Ok(Vec::new()); } - let classes: Vec = sections + let classes: Vec = sections .iter() - .map(|class| class.get_id().record()) + .map(|class| class.get_id().clone()) .collect(); let held = class_blueprint::held_links(db, classes).await?; Ok(sections diff --git a/src/service/class_course.rs b/src/service/class_course.rs index de102f9..daf00fe 100644 --- a/src/service/class_course.rs +++ b/src/service/class_course.rs @@ -3,8 +3,6 @@ //! The transactions live in [`crate::db::class_pump`] and //! [`crate::db::class_course`]. -use surrealdb::types::SurrealValue; - use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; use crate::database::Database; use crate::db::class_course; @@ -84,25 +82,13 @@ pub async fn attach( /// into it. A course that was not attached is a [`AppError::NotFound`], /// raised here rather than left to each caller to re-derive from a boolean. /// -/// A student another attached class still claims keeps their row, re-tagged -/// to that class (see [`crate::db::class_pump::detach`]). +/// to that class (see [`class_pump::detach_course`]). pub async fn detach( db: &Database, class: &ClassGroupId, course: &CourseId, ) -> Result<(), AppError> { - let gone = class_pump::detach( - db, - "$link", - Axis::Course, - &[( - "link".into(), - crate::domain::class_course::ClassCourseId::composite(class, course) - .record() - .into_value(), - )], - ) - .await?; + let gone = class_pump::detach_course(db, class, course, None).await?; (gone > 0).then_some(()).ok_or(AppError::NotFound) } diff --git a/src/service/class_member.rs b/src/service/class_member.rs index 3ea4166..8b341ac 100644 --- a/src/service/class_member.rs +++ b/src/service/class_member.rs @@ -4,15 +4,12 @@ //! itself lives in [`crate::db::class_pump`]; the table reads in //! [`crate::db::class_member`]. -use surrealdb::types::SurrealValue; - use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; use crate::database::Database; use crate::db::class_member; use crate::db::class_pump::{self, Axis}; use crate::domain::class_group::ClassGroupId; -use crate::domain::class_member::{ClassMember, ClassMemberId}; -use crate::domain::timestamp::Timestamp; +use crate::domain::class_member::ClassMember; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -29,26 +26,10 @@ pub async fn add( user: &UserId, added_by: &UserId, ) -> Result { - let member = ClassMember { - id: ClassMemberId::composite(class, user), - class: class.clone(), - user: user.clone(), - added_by: added_by.clone(), - added_at: Some(Timestamp::now()), - }; - let landed = class_pump::attach( - db, - class, - Axis::Member, - (&member.id.record(), &member), - user.record(), - added_by.record(), - None, - ) - .await?; // Read off the refusal, never respelled here: this route and a // blueprint pump answer one vocabulary. `Made` is the only `None`, and // it takes the `Ok` arm below. + let landed = class_pump::add_member(db, class, user, added_by).await?; let code = landed.refusal_code(&Axis::Member).unwrap_or_default(); match landed { class_pump::Attached::Made(saved) => Ok(saved), @@ -103,18 +84,9 @@ pub async fn add( /// re-derive from a boolean. /// /// An enrollment another attached class still claims is re-tagged to that -/// class instead of deleted (see [`crate::db::class_pump::detach`]). +/// class instead of deleted (see [`class_pump::remove_member`]). pub async fn remove(db: &Database, class: &ClassGroupId, user: &UserId) -> Result<(), AppError> { - let gone = class_pump::detach( - db, - "$link", - Axis::Member, - &[( - "link".into(), - ClassMemberId::composite(class, user).record().into_value(), - )], - ) - .await?; + let gone = class_pump::remove_member(db, class, user).await?; (gone > 0).then_some(()).ok_or(AppError::NotFound) } diff --git a/src/web/classes.rs b/src/web/classes.rs index 586643a..e0ac1ef 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -73,7 +73,7 @@ struct CreateClass { term_id: Option, /// The class's homeroom teacher (sınıf öğretmeni) — a teacher, manager or /// admin account. Optional; omit (or send `""`) for a class with none. - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")] teacher_id: Option, } @@ -101,20 +101,20 @@ struct UpdateClass { #[derive(Deserialize, ToSchema)] struct AddMember { /// The student to put in the class. - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")] user_id: String, } #[derive(Deserialize, ToSchema)] struct AttachCourse { /// The course the whole class takes. - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")] course_id: String, } #[derive(Serialize, ToSchema)] struct ClassResponse { - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")] id: String, /// Who created the class — always a manager or admin, so it is `null` for /// a caller below teacher+. `GET /classes/me` and a parent's @@ -184,7 +184,7 @@ struct CreateClassResponse { /// Every person a [`ClassResponse`] names: its homeroom teacher, plus its /// creator when the caller is cleared to see one. Feed this into `person_map` — -/// an id the map is missing renders as a bare ULID, so a creator left out here +/// an id the map is missing renders as a bare id, so a creator left out here /// must also be left out of the response. fn class_people(class: &ClassGroup, with_creator: bool) -> impl Iterator + '_ { with_creator @@ -419,7 +419,7 @@ async fn create_class( /// /// Swallowing that last case is the deliberate one. Every other pump here may /// fail its whole request, because the caller can name what it asked for again — -/// a blueprint's id *is* the grade label they sent. A class's id is a ULID this +/// a blueprint's id *is* the grade label they sent. A class's id is a uuid this /// request is the only place it is ever returned from, so a `500` after the row /// is written loses a section that exists. Best-effort therefore runs to the end /// of this route: the class is reported, `stocked_from` stays `null`, and the @@ -1041,14 +1041,14 @@ impl BlueprintResponse { /// One class a pump did *not* stock, and why. The class is named as well as /// identified: a manager reading a skip list has to know which section is short -/// a course, and a bare ULID is not that. +/// a course, and a bare id is not that. #[derive(Serialize, ToSchema)] struct SkipResponse { - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")] class: String, #[schema(example = "9-C")] class_name: String, - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")] course: String, /// Why that course could not be attached to that class, as a machine code /// the client words itself — the same id-plus-client-label shape roles and @@ -1118,7 +1118,7 @@ struct BlueprintPumpResponse { /// One section measured against its grade's template. #[derive(Serialize, ToSchema)] struct SectionStatusResponse { - #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")] class: String, #[schema(example = "9-C")] class_name: String, @@ -1521,7 +1521,7 @@ mod tests { let teacher = make("ada", Role::Teacher).await; for (field, id) in [ - ("gone", "01J8XZ0K3Q8G7X2M4N5P6R7S8T"), + ("gone", "0198f1a2-3b4c-7d5e-8f90-000000000001"), ("student", student.get_id().key()), ] { let refused = teacher_or_none(Some(id), &db).await;