From 18feaae6081917311395368f47743334d712e8c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 11 Sep 2026 09:47:51 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=B9=20chore:=20split=20class=5Fbluepri?= =?UTF-8?q?nt=20into=20domain/db/service=20layers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/db/class_blueprint.rs | 344 ++++++++++ src/db/course.rs | 2 +- src/db/mod.rs | 1 + src/domain/class_blueprint.rs | 1115 +------------------------------- src/service/class_blueprint.rs | 867 +++++++++++++++++++++++++ src/service/mod.rs | 1 + src/web/classes.rs | 34 +- tests/regress_blueprints.rs | 18 +- 8 files changed, 1261 insertions(+), 1121 deletions(-) create mode 100644 src/db/class_blueprint.rs create mode 100644 src/service/class_blueprint.rs diff --git a/src/db/class_blueprint.rs b/src/db/class_blueprint.rs new file mode 100644 index 0000000..8c64671 --- /dev/null +++ b/src/db/class_blueprint.rs @@ -0,0 +1,344 @@ +//! 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`]. + +use surrealdb::types::{RecordId, SurrealValue}; + +use crate::constant::{CLASS_BLUEPRINT_TABLE, CLASS_COURSE_TABLE, ENROLLMENT_COUNT_FIELD}; +use crate::database::{Database, transaction_with_retry}; +use crate::db::page::PagedList; +use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId}; +use crate::domain::class_group::{ClassGrade, ClassGroupId}; +use crate::domain::class_pump::{Axis, detach}; +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)] +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. +/// +/// 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. +/// +/// The claim is [`crate::domain::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; + }}" + ) +} + +/// 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. +fn no_such_course() -> AppError { + AppError::Validation(ValidationError::Invalid { + field: "course_ids", + reason: "one of these courses does not exist", + }) +} + +/// 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. +pub async fn create( + db: &Database, + creator: &UserId, + grade: ClassGrade, + courses: Vec, +) -> Result { + let blueprint = ClassBlueprint { + id: ClassBlueprintId::for_grade(&grade), + grade, + courses, + 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())) +} + +pub async fn read( + db: &Database, + id: &ClassBlueprintId, +) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// Every blueprint, by grade label — the id *is* the label, so this is the +/// only ordering that means anything here. +pub async fn list_all( + db: &Database, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new(CLASS_BLUEPRINT_TABLE, "ORDER BY id ASC") + .run(limit, offset, db) + .await +} + +/// Write the course list only while the stored row still carries the list +/// this caller read: two managers editing the same grade cannot have one's +/// list silently pump the other's diff. `None` means the conditional write +/// matched nothing — the row is gone, or its list moved since the caller read +/// 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`. +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()) +} + +/// Delete the row, but only while it still carries the list this caller read +/// — the edit race answers the caller, not a silent delete of somebody +/// 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. +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()) +} + +/// 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)?) +} + +/// 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. +/// +/// 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 +/// that read is still attempted, and the delete's sweep has already run +/// past a row it will not visit again. The skip is then reported once for +/// the run that found it (later classes in the same +/// [`crate::service::class_blueprint::pump`] skip it by its dead-course set +/// rather than re-attempting and re-pruning it), and this write is a no-op +/// against a list the cascade already trimmed. It also clears ids written +/// before that cascade existed. +/// +/// Not a compare-and-set, unlike +/// [`crate::service::class_blueprint::set_courses`]: "a course that does +/// not exist is not in this list" holds for every version of the list, so +/// there is nothing a concurrent edit could make this write wrong about, +/// and re-running it changes nothing. No sweep follows it either — the +/// attachments it would sweep are exactly the ones the course's own delete +/// already took. +/// +/// No [`crate::service::class_blueprint::BLUEPRINT_LOCK`] lease either: an +/// `UPDATE` of a record that is gone writes nothing, so this cannot +/// resurrect a blueprint a delete took while the pump around it was +/// running. +pub async fn prune( + db: &Database, + id: &ClassBlueprintId, + course: &CourseId, +) -> Result<(), AppError> { + db.query("UPDATE $id SET courses = array::complement(courses ?? [], [$course])") + .bind(("id", id.record())) + .bind(("course", course.record())) + .await? + .check()?; + Ok(()) +} + +/// A blueprint's attachments that `keep` does not justify: every +/// `class_course` row carrying its tag for a course outside that list. The +/// delete passes `&[]` and so takes all of them. +/// +/// Read off the *stored* list rather than a diff against a handle, which is +/// 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 — +/// 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 +/// blueprint's attachments, and only the tag can find it. +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)?) +} + +/// 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. +/// +/// One transaction per *link row*, which is the module note's "one +/// transaction per (class, course)" and the mirror of the pump's +/// best-effort rule. One statement per course would be shorter, but it puts +/// every section at the grade into a single unbounded transaction: its write +/// loop is one enrollment sweep per (class, member) with no ceiling over the +/// class count, and a failure anywhere in it rolls back the whole grade — +/// so one contended section keeps the other eleven attached to a course the +/// template no longer holds. Per row, a failure leaves the pairs already +/// detached detached, each with its counter released and its enrollments +/// swept, and the rest exactly as they were: a partial removal the next call +/// finishes. +pub async fn drop_links( + db: &Database, + id: &ClassBlueprintId, + links: Vec, +) -> Result<(), AppError> { + for link in links { + detach( + "$link WHERE source = $blueprint", + Axis::Course, + &[ + ("link".into(), link.into_value()), + ("blueprint".into(), id.record().into_value()), + ], + db, + ) + .await?; + } + Ok(()) +} diff --git a/src/db/course.rs b/src/db/course.rs index 4c08f7e..7d75034 100644 --- a/src/db/course.rs +++ b/src/db/course.rs @@ -273,7 +273,7 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App /// Nothing else can reach them — a blueprint holds its courses as a list on /// its own row, not as link rows this cascade could delete — and an id left /// behind is permanent rather than merely stale: the pump's own -/// [`crate::domain::class_blueprint::ClassBlueprint::prune`] fires only +/// [`crate::db::class_blueprint::prune`] fires only /// while walking a section, so a grade with no sections can never drop one, /// and every `PATCH` of that template is refused for naming a course that /// does not exist, which is precisely the call documented as the repair. diff --git a/src/db/mod.rs b/src/db/mod.rs index 1ad9342..4ce6ae0 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -2,6 +2,7 @@ pub mod appointment; pub mod cap; +pub mod class_blueprint; pub mod course; pub mod exam_attempt; pub mod field_update; diff --git a/src/domain/class_blueprint.rs b/src/domain/class_blueprint.rs index 734ebdb..d9b483a 100644 --- a/src/domain/class_blueprint.rs +++ b/src/domain/class_blueprint.rs @@ -9,82 +9,26 @@ //! `enrollment` rows, and an elective (seçmeli) placed by hand next to them is //! still an individual enrollment nothing here can see. //! -//! Two rules shape everything below. +//! This module is the pure shape: the id (the grade label *is* the record +//! key, so "one blueprint per grade" holds by construction), the row, the +//! pump's report types ([`Pumped`], [`Skip`], [`SectionStatus`]) and the +//! shared skip vocabulary ([`skip_reason`]). //! -//! **An edit retro-pumps.** Changing the list reaches every class already at -//! that grade, not just the ones made afterwards. That is an unbounded write -//! loop — one transaction per (class, course), and no ceiling bounds the number -//! of classes — chosen deliberately over a template that only new classes see. -//! -//! **A pump is best-effort.** Each (class, course) pair is one all-or-nothing -//! transaction of the existing pump, and a pair that would breach a limit is -//! *skipped and reported* rather than aborting the other classes' share. So a -//! blueprint edit can leave a partial state — which is the point: one full -//! course must not stop the other eleven sections from being stocked. Every -//! skip is returned, naming the class, the course and the reason. -//! -//! Removal is the mirror, and it is where the provenance tag earns its keep: a -//! `class_course` row this blueprint wrote carries `source`, a row a human -//! attached carries no such key at all, and dropping a course from the -//! blueprint sweeps only the former. The sweep is the pump's own -//! [`crate::domain::class_pump::detach`], so a class losing a course still -//! repairs before it deletes — and it runs one transaction per pair too, for -//! the same reason the pump does. +//! 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 +//! [`crate::db::class_blueprint`]. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use tokio::sync::RwLock; -use crate::constant::{ - CLASS_BLUEPRINT_TABLE, CLASS_COURSE_TABLE, ENROLLMENT_COUNT_FIELD, MAX_CLASS_COURSES, -}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::page::PagedList; +use crate::constant::{CLASS_BLUEPRINT_TABLE, MAX_CLASS_COURSES}; use crate::domain::class_course::ClassCourse; -use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId}; -use crate::domain::class_pump::{Attached, Axis, detach}; +use crate::domain::class_group::{ClassGrade, ClassGroupId}; +use crate::domain::class_pump::{Attached, Axis}; use crate::domain::course::CourseId; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; -/// Serializes a blueprint's delete against the attaches made on its behalf. -/// -/// [`ClassBlueprint::delete`] removes the row and then sweeps by the provenance -/// tag, and every guarded attach reads that same row *inside* its own -/// transaction ([`crate::domain::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 [`ClassBlueprint::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(()); - -/// 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"; - #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ClassBlueprintId(RecordId); @@ -117,10 +61,10 @@ impl ClassBlueprintId { /// never has to parse a record id back into a domain value. #[derive(Debug, Clone, SurrealValue)] pub struct ClassBlueprint { - id: ClassBlueprintId, - grade: ClassGrade, - courses: Vec, - creator: UserId, + pub(crate) id: ClassBlueprintId, + pub(crate) grade: ClassGrade, + pub(crate) courses: Vec, + pub(crate) creator: UserId, } /// One (class, course) pair a pump refused, and why. Precise enough to act on: @@ -137,13 +81,15 @@ pub struct Skip { /// What a pump did: how many sections it reached, and the pairs it refused. /// /// `matched` exists because an empty `skipped` is not success on its own. A -/// grade label is free text ([`ClassGrade`]) and [`ClassGroup::list_for_grade`] +/// grade label is free text ([`ClassGrade`]) and +/// [`crate::domain::class_group::ClassGroup::list_for_grade`] /// matches it exactly, so a blueprint keyed `"9 "` reaches none of the sections /// keyed `"9"` — and with nothing to skip it answers exactly like a pump that /// stocked every one of them. The count is the only thing that tells those /// apart. /// -/// A struct rather than a pair with [`ClassBlueprint::set_courses`]'s: three +/// A struct rather than a pair with +/// [`crate::service::class_blueprint::set_courses`]'s: three /// unlabelled fields off one call is a shape a caller has to remember. #[derive(Debug)] pub struct Pumped { @@ -163,15 +109,6 @@ pub struct SectionStatus { pub missing: Vec, } -/// 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)] -struct Held { - class: ClassGroupId, - course: CourseId, -} - /// Why this attach did not land, or `None` when it did — the shared vocabulary /// of [`Attached::refusal_code`], which is where the codes and the set they /// close over are documented. @@ -185,7 +122,7 @@ struct Held { /// Always the course axis: a pump attaches courses to sections, so the two /// ceiling codes are read on that side ([`Attached::refusal_code`] takes the /// axis because they differ per axis). -fn skip_reason(landed: &Attached) -> Option<&'static str> { +pub(crate) fn skip_reason(landed: &Attached) -> Option<&'static str> { match landed { Attached::Duplicate => None, other => other.refusal_code(&Axis::Course), @@ -236,7 +173,7 @@ impl ClassBlueprint { /// The course list a blueprint may hold: deduplicated, and no longer than /// one class may carry — a blueprint above that ceiling would guarantee a /// skip on every class it ever reached. - fn course_list(courses: Vec) -> Result, AppError> { + pub(crate) fn course_list(courses: Vec) -> Result, AppError> { let mut list: Vec = Vec::new(); for course in courses { if !list.contains(&course) { @@ -252,1021 +189,11 @@ impl ClassBlueprint { } Ok(list) } - - /// The statements that 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. [`Self::prune`] only fires - /// while walking a section, so at a grade carrying none the id is permanent. - /// - /// The claim is [`crate::domain::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; - }}" - ) - } - - /// 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. - fn no_such_course() -> AppError { - AppError::Validation(ValidationError::Invalid { - field: "course_ids", - reason: "one of these courses does not exist", - }) - } - - /// 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. - pub async fn create( - creator: &UserId, - grade: ClassGrade, - courses: Vec, - db: &Database, - ) -> Result { - let blueprint = ClassBlueprint { - id: ClassBlueprintId::for_grade(&grade), - grade, - courses: Self::course_list(courses)?, - 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;", - Self::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(Self::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())) - } - - pub async fn read( - id: &ClassBlueprintId, - db: &Database, - ) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// Every blueprint, by grade label — the id *is* the label, so this is the - /// only ordering that means anything here. - pub async fn list_all( - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new(CLASS_BLUEPRINT_TABLE, "ORDER BY id ASC") - .run(limit, offset, db) - .await - } - - /// Replace the course list, then reconcile every class at this grade with - /// it: the courses this blueprint no longer holds are detached from the - /// classes *it* attached them to, and the ones it holds are pumped into - /// every class that fits. - /// - /// The write is a compare-and-set on the list this caller read, so two - /// managers editing the same grade cannot have one's list silently pump the - /// other's diff — the loser is a 409 and re-reads. - /// - /// Removals run first: a course leaving frees a place under the per-class - /// course ceiling that the same edit's additions can then use. What is swept - /// is derived from the list this write **stored**, never from a diff against - /// the list this handle read ([`Self::sourced_links`]): the sweep is N - /// sequential transactions in one request, and a failure part-way through - /// used to leave sections carrying courses the template no longer holds with - /// no way back — a re-`PATCH` recomputed an empty diff, and the documented - /// self-heal ("send the list it already holds") swept nothing. Derived from - /// the stored list, that same re-`PATCH` finds the rows still tagged and - /// finishes the job. - /// - /// The price is the other direction: a rival edit that lands *and pumps* - /// between this write and this sweep has its new course detached again, - /// because this sweep asks the list it stored. That is a section short a - /// templated course — what [`Self::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 [`Self::delete`] sweeps the whole - /// tag rather than a list. - pub async fn set_courses( - self, - courses: Vec, - by: &UserId, - db: &Database, - ) -> Result<(ClassBlueprint, Pumped), AppError> { - let wanted = Self::course_list(courses)?; - 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;", - Self::courses_alive() - ), - &[ - ("id".into(), self.id.record().into_value()), - ("wanted".into(), wanted.into_value()), - ("held".into(), self.courses.clone().into_value()), - ("courses".into(), named.into_value()), - ], - &[DEAD_MARK], - ) - .await?; - if errors - .values() - .any(|error| error.to_string().contains(DEAD_MARK)) - { - return Err(Self::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. - let Some(mut saved) = result.take::>(2)?.into_iter().next() else { - // The conditional write matched nothing: the row is gone, or its - // list moved since this caller read it. Only this path pays for the - // read that tells those apart. - return match Self::read(&self.id, db).await? { - Some(_) => Err(AppError::Conflict( - "this blueprint changed since you read it — re-read and retry", - )), - None => Err(AppError::NotFound), - }; - }; - saved - .drop_links(saved.sourced_links(&saved.courses, db).await?, db) - .await?; - let pumped = saved.pump(by, db).await?; - Ok((saved, pumped)) - } - - /// Delete the blueprint, taking every attachment it made with it. Courses a - /// human attached to those classes by hand carry no `source` and are left - /// exactly where they are — the same cut a single removal makes, applied to - /// the whole list, because a template that is gone owns nothing. - /// - /// The row goes **first**, and the sweep that follows is by the provenance - /// tag rather than by the list this caller read. Sweeping first was the - /// 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 - /// 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 - /// [`Self::apply_to`] spans each attach, and the deployment runs one - /// process by contract, which makes an in-process lock the whole answer. - /// - /// 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. - /// - /// The delete is a compare-and-set on the list this caller read, like - /// [`Self::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 - /// 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(self, db: &Database) -> 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; - let mut result = db - .query("DELETE $id WHERE courses = $held RETURN BEFORE") - .bind(("id", self.id.record())) - .bind(("held", self.courses.clone())) - .await? - .check()?; - if result.take::>(0)?.is_empty() { - // 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 Self::read(&self.id, db).await? { - Some(_) => Err(AppError::Conflict( - "this blueprint changed since you read it — re-read and retry", - )), - None => Err(AppError::NotFound), - }; - } - self.sourced_links(&[], db).await? - }; - self.drop_links(doomed, db).await - } - - /// Attach every course in this blueprint to `class`, skipping — never - /// aborting on — the ones that do not fit. A course already on the class is - /// a no-op, whoever attached it: this is what makes a pump repeatable, and - /// what stops it re-tagging a hand-attached course as its own. - /// - /// This is the *only* place a sourced attach is made — [`Self::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. - /// - /// 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 - /// one that just went. - pub async fn apply_to( - &self, - class: &ClassGroup, - by: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut skipped = Vec::new(); - self.apply_courses(class, by, &mut Vec::new(), &mut skipped, db) - .await?; - Ok(skipped) - } - - /// One class's share of a pump, and the body both callers above share. - /// - /// `dead` is the courses this run already found deleted: they are not - /// attempted again, so neither the skip nor [`Self::prune`]'s write repeats - /// on the next section. A course newly found gone joins it. - /// - /// Answers `false` when the blueprint itself is gone — a caller looping - /// over classes must stop, because every remaining one would answer exactly - /// the same. - async fn apply_courses( - &self, - class: &ClassGroup, - by: &UserId, - dead: &mut Vec, - skipped: &mut Vec, - db: &Database, - ) -> Result { - for course in &self.courses { - if dead.contains(course) { - continue; - } - let landed = { - let _lease = BLUEPRINT_LOCK.read().await; - ClassCourse::attach_sourced(class.get_id(), course, by, Some(&self.id), db).await? - }; - if matches!(landed, Attached::PivotGone) { - self.prune(course, db).await?; - dead.push(course.clone()); - } - if let Some(reason) = skip_reason(&landed) { - skipped.push(Skip { - class: class.get_id().clone(), - class_name: class.get_name().as_str().to_string(), - course: course.clone(), - reason, - }); - } - if matches!(landed, Attached::SourceGone) { - return Ok(false); - } - } - Ok(true) - } - - /// [`Self::apply_to`] every class at this blueprint's grade. The write loop - /// is one transaction per (class, course) and bounded by neither — see the - /// module note. - /// - /// Two things are said once for the whole run rather than once per section, - /// 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. - /// - /// 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 - /// partial state reported in full is what best-effort means everywhere else - /// here. - /// - /// [`Pumped::matched`] is counted off this loop rather than asked of a - /// second query — the sections the run *walked*, so an abort reports what - /// it did and not what the grade holds. - /// - /// `&mut`, because [`Self::prune`] writes the store and this handle is what - /// both write routes render their response from: a course pruned mid-pump - /// was still listed in the `201`/`200` that pruned it, while the `GET` a - /// moment later did not have it. - pub async fn pump(&mut self, by: &UserId, db: &Database) -> Result { - let mut pumped = Pumped { - matched: 0, - skipped: Vec::new(), - }; - let mut dead = Vec::new(); - for class in ClassGroup::list_for_grade(&self.grade, db).await? { - pumped.matched += 1; - if !self - .apply_courses(&class, by, &mut dead, &mut pumped.skipped, db) - .await? - { - break; - } - } - // Exactly the ids `prune` took out of the stored row, so the handle and - // the store say the same thing. - self.courses.retain(|course| !dead.contains(course)); - Ok(pumped) - } - - /// How far every section at this grade stands from the template: the - /// courses each one does not carry. Writes nothing — a pump's skip list - /// lives only in the response that reported it, and this is the read that - /// answers "which sections are still out of sync" afterwards. - /// - /// **A link of any source counts as satisfied.** A course a human attached - /// by hand fulfils the template exactly as a pumped one does — that is - /// [`Self::apply_to`]'s own idempotence rule, and a status read that - /// disagreed with it would send managers chasing rows no pump will ever - /// write. - /// - /// A course id the blueprint holds but that no longer exists reads as - /// missing from every section. It is the truth about the section, and this - /// read cannot prune it the way a pump does ([`Self::prune`]) without - /// writing — but it is no longer a state a course delete leaves behind: the - /// delete's own cascade takes the id out of every template naming it, so - /// only a row written before that cascade existed, or one the pump's own - /// window ([`Self::prune`]) is about to clear, can still show it. - /// - /// Unpaged, like the [`ClassGroup::list_for_grade`] it is built on: the set - /// is the şube one school runs at one grade, and the caller is asking about - /// all of them. - pub async fn status(&self, db: &Database) -> Result, AppError> { - let sections = ClassGroup::list_for_grade(&self.grade, db).await?; - if sections.is_empty() { - return Ok(Vec::new()); - } - let classes: Vec = sections - .iter() - .map(|class| class.get_id().record()) - .collect(); - let mut result = db - .query(format!( - "SELECT class, course FROM {CLASS_COURSE_TABLE} WHERE class IN $classes" - )) - .bind(("classes", classes)) - .await? - .check()?; - let held = result.take::>(0)?; - Ok(sections - .iter() - .map(|class| SectionStatus { - class: class.get_id().clone(), - class_name: class.get_name().as_str().to_string(), - missing: self - .courses - .iter() - .filter(|course| { - !held - .iter() - .any(|row| &row.class == class.get_id() && &&row.course == course) - }) - .cloned() - .collect(), - }) - .collect()) - } - - /// Drop a course that no longer exists out of this 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. - /// - /// 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 - /// that read is still attempted, and the delete's sweep has already run - /// past a row it will not visit again. The skip is then reported once for - /// the run that found it (later classes in the same [`Self::pump`] skip it - /// by its dead-course set rather than re-attempting and re-pruning it), and - /// this write is a no-op against a list the cascade already trimmed. It - /// also clears ids written before that cascade existed. - /// - /// Not a compare-and-set, unlike [`Self::set_courses`]: "a course that does - /// not exist is not in this list" holds for every version of the list, so - /// there is nothing a concurrent edit could make this write wrong about, - /// and re-running it changes nothing. No sweep follows it either — the - /// attachments it would sweep are exactly the ones the course's own delete - /// already took. - /// - /// No [`BLUEPRINT_LOCK`] lease either: an `UPDATE` of a record that is gone - /// writes nothing, so this cannot resurrect a blueprint a delete took while - /// the pump around it was running. - async fn prune(&self, course: &CourseId, db: &Database) -> Result<(), AppError> { - db.query("UPDATE $id SET courses = array::complement(courses ?? [], [$course])") - .bind(("id", self.id.record())) - .bind(("course", course.record())) - .await? - .check()?; - Ok(()) - } - - /// This blueprint's attachments that `keep` does not justify: every - /// `class_course` row carrying its tag for a course outside that list. The - /// delete passes `&[]` and so takes all of them. - /// - /// Read off the *stored* list rather than a diff against a handle, which is - /// 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 — - /// 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 - /// blueprint's attachments, and only the tag can find it. - async fn sourced_links( - &self, - keep: &[CourseId], - db: &Database, - ) -> 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", self.id.record())) - .bind(("keep", named)) - .await? - .check()?; - Ok(found.take::>(0)?) - } - - /// Detach the link rows [`Self::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. - /// - /// One transaction per *link row*, which is the module note's "one - /// transaction per (class, course)" and the mirror of the pump's - /// best-effort rule. One statement per course would be shorter, but it puts - /// every section at the grade into a single unbounded transaction: its write - /// loop is one enrollment sweep per (class, member) with no ceiling over the - /// class count, and a failure anywhere in it rolls back the whole grade — - /// so one contended section keeps the other eleven attached to a course the - /// template no longer holds. Per row, a failure leaves the pairs already - /// detached detached, each with its counter released and its enrollments - /// swept, and the rest exactly as they were: a partial removal the next call - /// finishes. - async fn drop_links(&self, links: Vec, db: &Database) -> Result<(), AppError> { - for link in links { - detach( - "$link WHERE source = $blueprint", - Axis::Course, - &[ - ("link".into(), link.into_value()), - ("blueprint".into(), self.id.record().into_value()), - ], - db, - ) - .await?; - } - Ok(()) - } } #[cfg(test)] mod tests { use super::*; - use crate::constant::CLASS_COURSE_COUNT_FIELD; - use crate::domain::class_course::ClassCourseId; - use crate::domain::class_group::ClassName; - use crate::domain::class_member::tests::{a_class, a_course, counter, exists, rows}; - - /// A section that a pump's own grade loop can actually find — [`a_class`] - /// carries no grade at all, so `list_for_grade` reaches none of them. - async fn a_section(name: &str, db: &Database) -> ClassGroup { - ClassGroup::create( - &UserId::from_key("manager"), - ClassName::try_new(name).unwrap(), - Some(ClassBlueprint::grade_key("9").unwrap()), - None, - None, - db, - ) - .await - .unwrap() - } - - /// A blueprint holding `courses`, at grade "9". - async fn a_blueprint(courses: Vec, db: &Database) -> ClassBlueprint { - ClassBlueprint::create( - &UserId::from_key("manager"), - ClassBlueprint::grade_key("9").unwrap(), - courses, - db, - ) - .await - .unwrap() - } - - /// Every skip names the record that actually failed. - /// - /// The three refusals a manager can meet come out of two different claims - /// in one transaction, and they used to be reported by one string that - /// guessed: a deleted *course* was announced as a deleted *class*, on a - /// section standing right there. Each is provoked from the state that - /// really produces it, not from the enum. - #[tokio::test] - async fn a_skip_names_what_actually_failed() { - let manager = UserId::from_key("manager"); - - // The course is deleted out from under the pump: the pivot claim - // matches nothing. - let db = crate::database::init_mem().await.unwrap(); - let course = a_course("algebra", None, &db).await; - let class = ClassGroup::read(&a_class("9-A", &db).await, &db) - .await - .unwrap() - .unwrap(); - let blueprint = a_blueprint(vec![course.clone()], &db).await; - db.query("DELETE $c") - .bind(("c", course.record())) - .await - .unwrap() - .check() - .unwrap(); - let skipped = blueprint.apply_to(&class, &manager, &db).await.unwrap(); - assert_eq!(skipped.len(), 1, "{skipped:?}"); - assert_eq!( - skipped[0].reason, "course_deleted", - "the course went, not the class" - ); - // …and the dangling id is taken out of the list, so the skip is - // reported once instead of on every pump forever. - assert!( - ClassBlueprint::read(blueprint.get_id(), &db) - .await - .unwrap() - .unwrap() - .get_courses() - .is_empty(), - "a course that no longer exists is pruned from the blueprint" - ); - - // The class is deleted out from under the pump: the counter claim - // matches nothing and the read that follows finds no row. - let db = crate::database::init_mem().await.unwrap(); - let course = a_course("algebra", None, &db).await; - let class = ClassGroup::read(&a_class("9-A", &db).await, &db) - .await - .unwrap() - .unwrap(); - let blueprint = a_blueprint(vec![course.clone()], &db).await; - db.query("DELETE $c") - .bind(("c", class.get_id().record())) - .await - .unwrap() - .check() - .unwrap(); - let skipped = blueprint.apply_to(&class, &manager, &db).await.unwrap(); - assert_eq!(skipped.len(), 1, "{skipped:?}"); - assert_eq!( - skipped[0].reason, "class_deleted", - "the class went, not the course" - ); - assert_eq!( - ClassBlueprint::read(blueprint.get_id(), &db) - .await - .unwrap() - .unwrap() - .get_courses(), - &[course], - "a live course is not pruned because a class vanished" - ); - - // The class stands at its own ceiling: the same claim matches nothing, - // but the row is there — and that is the one a manager can act on. - let db = crate::database::init_mem().await.unwrap(); - let course = a_course("algebra", None, &db).await; - let class = ClassGroup::read(&a_class("9-A", &db).await, &db) - .await - .unwrap() - .unwrap(); - let blueprint = a_blueprint(vec![course], &db).await; - db.query(format!( - "UPDATE $c SET {} = $cap", - crate::constant::CLASS_COURSE_COUNT_FIELD - )) - .bind(("c", class.get_id().record())) - .bind(("cap", MAX_CLASS_COURSES)) - .await - .unwrap() - .check() - .unwrap(); - let skipped = blueprint.apply_to(&class, &manager, &db).await.unwrap(); - assert_eq!(skipped.len(), 1, "{skipped:?}"); - assert_eq!( - skipped[0].reason, "class_at_course_ceiling", - "a full class is not a deleted one" - ); - } - - /// The delete is a compare-and-set, and it runs *before* the sweep — so a - /// handle whose list moved cannot take the row, and nothing it would have - /// swept is touched either. - /// - /// Provoked with a stale handle rather than a concurrent request, which is - /// exactly the state a `PATCH` landing between the read and the delete puts - /// this caller in, and deterministic where two live requests are not. - #[tokio::test] - async fn a_delete_of_a_list_that_moved_is_a_409_that_writes_nothing() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let algebra = a_course("algebra", None, &db).await; - let physics = a_course("physics", None, &db).await; - let class = ClassGroup::read(&a_class("9-A", &db).await, &db) - .await - .unwrap() - .unwrap(); - let stale = a_blueprint(vec![algebra.clone()], &db).await; - stale.apply_to(&class, &manager, &db).await.unwrap(); - - // The edit this caller did not see: it adds a course and pumps it into - // the section. (The pump is applied by hand because the helper class - // carries no grade for `set_courses`'s own loop to find.) - let (edited, _) = ClassBlueprint::read(stale.get_id(), &db) - .await - .unwrap() - .unwrap() - .set_courses(vec![algebra, physics], &manager, &db) - .await - .unwrap(); - edited.apply_to(&class, &manager, &db).await.unwrap(); - - let refused = stale.delete(&db).await; - assert!( - matches!(refused, Err(AppError::Conflict(_))), - "a list that moved is a 409, not a silent delete: {refused:?}" - ); - assert!( - ClassBlueprint::read(&ClassBlueprintId::from_key("9"), &db) - .await - .unwrap() - .is_some(), - "the row the caller did not read is still there" - ); - assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, - 2, - "and neither attachment was swept — including the one this handle \ - never knew about" - ); - } - - /// The lease is real: a delete cannot start while a guarded attach holds - /// the read side. - /// - /// That is the whole point of the lock — without it a pump could commit its - /// `class_course` row *after* the delete had swept past, stranding a row - /// tagged with a blueprint nothing can reach. Two live requests would be a - /// coin flip the in-memory engine lies about, so the lease is held directly - /// and the delete is watched not-finishing on a timeout. - #[tokio::test] - async fn a_delete_waits_for_an_attach_in_flight() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let algebra = a_course("algebra", None, &db).await; - let class = ClassGroup::read(&a_class("9-A", &db).await, &db) - .await - .unwrap() - .unwrap(); - let blueprint = a_blueprint(vec![algebra], &db).await; - blueprint.apply_to(&class, &manager, &db).await.unwrap(); - - // Stand in for an attach mid-transaction, which is exactly the lease - // `apply_to` holds around one course. - let attaching = BLUEPRINT_LOCK.read().await; - let mut deleting = { - let db = db.clone(); - let blueprint = blueprint.clone(); - tokio::spawn(async move { blueprint.delete(&db).await }) - }; - assert!( - tokio::time::timeout(std::time::Duration::from_millis(150), &mut deleting) - .await - .is_err(), - "the delete must not run while an attach is in flight" - ); - assert_eq!( - rows("SELECT VALUE id FROM class_blueprint", &db).await, - 1, - "…and it must not have swept anything either" - ); - - drop(attaching); - deleting.await.unwrap().unwrap(); - assert_eq!( - rows("SELECT VALUE id FROM class_blueprint", &db).await, - 0, - "once the attach is done the delete goes through" - ); - assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, - 0, - "…taking every row carrying its tag with it" - ); - } - - /// …and the other side of that lease: it is released before the detaching - /// starts, so a pump is *not* parked behind it. - /// - /// The sweep is one transaction per link row and bounded by nothing — - /// sections × courses, each walking up to a full roster — and `tokio`'s - /// `RwLock` is fair, so a lease held across it stalled every concurrent - /// `POST /classes` in the school, at every grade, for the whole delete. What - /// the lease has to cover is only the compare-and-set and the read that - /// fixes the row set, which `a_delete_waits_for_an_attach_in_flight` above - /// still pins from the other direction. - /// - /// The unbounded loop is stood in for by four slow rows: a `DEFINE EVENT` on - /// `class_course` fires inside each detaching transaction, so the delete is - /// provably still sweeping when the lease is asked for. Nothing here is - /// asserted off a fixed delay — the row going is what says the - /// compare-and-set has run, and one *moment* of a free lease while the sweep - /// is unfinished is the whole claim. A sweep that ended first fails the - /// assertion rather than passing it by default. - #[tokio::test] - async fn a_delete_frees_the_lease_before_its_unbounded_sweep() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let courses = vec![ - a_course("algebra", None, &db).await, - a_course("physics", None, &db).await, - ]; - let blueprint = a_blueprint(courses, &db).await; - for name in ["9-A", "9-B"] { - let class = ClassGroup::read(&a_class(name, &db).await, &db) - .await - .unwrap() - .unwrap(); - blueprint.apply_to(&class, &manager, &db).await.unwrap(); - } - db.query( - "DEFINE EVENT slow_sweep ON TABLE class_course WHEN $event = 'DELETE' \ - THEN { SLEEP 300ms; };", - ) - .await - .unwrap() - .check() - .unwrap(); - - let deleting = { - let (db, blueprint) = (db.clone(), blueprint.clone()); - tokio::spawn(async move { blueprint.delete(&db).await }) - }; - let beat = std::time::Duration::from_millis(10); - // The row is gone the instant the compare-and-set commits, which is - // inside the lease this test is about. - while rows("SELECT VALUE id FROM class_blueprint", &db).await > 0 { - tokio::time::sleep(beat).await; - } - let mut freed = false; - while !deleting.is_finished() { - if BLUEPRINT_LOCK.try_read().is_ok() { - freed = true; - break; - } - tokio::time::sleep(beat).await; - } - assert!( - freed, - "a pump may not wait behind a delete's unbounded sweep" - ); - - deleting.await.unwrap().unwrap(); - assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, - 0, - "…and the sweep it ran lease-free still took every row it owned" - ); - } - - /// The other half: a pump holding a handle to a blueprint that has since - /// been deleted writes nothing at all, and says so with its own code. - /// - /// Without the in-transaction claim the attach would land a `class_course` - /// row tagged with a record that no longer exists — the delete's sweep has - /// already run, and the grade label *is* the id, so nothing could ever - /// reach that row again. - #[tokio::test] - async fn a_pump_whose_blueprint_died_attaches_nothing() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let algebra = a_course("algebra", None, &db).await; - let class = ClassGroup::read(&a_class("9-A", &db).await, &db) - .await - .unwrap() - .unwrap(); - let stale = a_blueprint(vec![algebra], &db).await; - ClassBlueprint::read(stale.get_id(), &db) - .await - .unwrap() - .unwrap() - .delete(&db) - .await - .unwrap(); - - let skipped = stale.apply_to(&class, &manager, &db).await.unwrap(); - assert_eq!(skipped.len(), 1, "{skipped:?}"); - assert_eq!( - skipped[0].reason, "blueprint_deleted", - "the template went, not the class or the course" - ); - assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, - 0, - "a row tagged with a deleted blueprint is one nothing can sweep" - ); - assert_eq!( - counter(CLASS_COURSE_COUNT_FIELD, class.get_id().record(), &db).await, - 0, - "…and no counter moved for it" - ); - } - - /// A course that no longer exists is pruned and reported **once for the - /// pump**, not once per section: twelve sections at a grade must not answer - /// one dead course with twelve identical skips and twelve identical prune - /// writes. The live course still reaches every section. - /// - /// Stored state is what is asserted — the in-memory engine forges wins, so - /// the links are re-read rather than counted off the return value. - #[tokio::test] - async fn a_dead_course_is_pruned_and_skipped_once_for_the_whole_grade() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let astronomy = a_course("astronomy", None, &db).await; - let algebra = a_course("algebra", None, &db).await; - let a = a_section("9-A", &db).await; - let b = a_section("9-B", &db).await; - let mut blueprint = a_blueprint(vec![astronomy.clone(), algebra.clone()], &db).await; - db.query("DELETE $c") - .bind(("c", astronomy.record())) - .await - .unwrap() - .check() - .unwrap(); - - let Pumped { matched, skipped } = blueprint.pump(&manager, &db).await.unwrap(); - assert_eq!(matched, 2, "both sections at the grade were walked"); - assert_eq!( - skipped.len(), - 1, - "one dead course is one skip for the grade, not one per section: {skipped:?}" - ); - assert_eq!(skipped[0].reason, "course_deleted"); - assert_eq!( - ClassBlueprint::read(blueprint.get_id(), &db) - .await - .unwrap() - .unwrap() - .get_courses(), - std::slice::from_ref(&algebra), - "and the list is pruned to the course that still exists" - ); - for class in [&a, &b] { - assert!( - exists( - ClassCourseId::composite(class.get_id(), &algebra).record(), - &db - ) - .await, - "the live course still reached {}", - class.get_name().as_str() - ); - } - assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, - 2, - "…and nothing else was attached" - ); - } - - /// A blueprint that is gone ends the whole grade loop: the answer is about - /// the template, so every remaining section would only repeat it. Reported - /// once, and as `Ok` — best-effort, with whatever committed left standing. - /// - /// Provoked with a stale handle rather than a live interleaving, which the - /// in-memory engine cannot be made to produce; it is the same state a - /// delete landing between the read and the pump leaves this caller in. - #[tokio::test] - async fn a_deleted_blueprint_stops_the_grade_loop_after_one_skip() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let algebra = a_course("algebra", None, &db).await; - a_section("9-A", &db).await; - a_section("9-B", &db).await; - let mut stale = a_blueprint(vec![algebra], &db).await; - ClassBlueprint::read(stale.get_id(), &db) - .await - .unwrap() - .unwrap() - .delete(&db) - .await - .unwrap(); - - let Pumped { matched, skipped } = stale.pump(&manager, &db).await.unwrap(); - assert_eq!( - skipped.len(), - 1, - "the template went once, not once per section: {skipped:?}" - ); - assert_eq!(skipped[0].reason, "blueprint_deleted"); - assert_eq!( - matched, 1, - "an abort reports the sections it walked, not the two the grade holds" - ); - assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, - 0, - "…and nothing was attached under a blueprint nothing could sweep" - ); - } #[test] fn a_grade_key_must_be_addressable() { diff --git a/src/service/class_blueprint.rs b/src/service/class_blueprint.rs new file mode 100644 index 0000000..2cc9aa0 --- /dev/null +++ b/src/service/class_blueprint.rs @@ -0,0 +1,867 @@ +//! Grade-blueprint workflows: creating a template and pumping it across a +//! whole grade, the edit that retro-pumps, the delete that takes the +//! attachments it made with it, and the per-class apply they all share. The +//! queries live in [`crate::db::class_blueprint`]; the row shape and the +//! skip vocabulary in [`crate::domain::class_blueprint`]. +//! +//! Two rules shape everything below. +//! +//! **An edit retro-pumps.** Changing the list reaches every class already at +//! that grade, not just the ones made afterwards. That is an unbounded write +//! loop — one transaction per (class, course), and no ceiling bounds the +//! number of classes — chosen deliberately over a template that only new +//! classes see. +//! +//! **A pump is best-effort.** Each (class, course) pair is one all-or-nothing +//! transaction of the existing pump, and a pair that would breach a limit is +//! *skipped and reported* rather than aborting the other classes' share. So a +//! blueprint edit can leave a partial state — which is the point: one full +//! course must not stop the other eleven sections from being stocked. Every +//! skip is returned, naming the class, the course and the reason. +//! +//! Removal is the mirror, and it is where the provenance tag earns its keep: +//! a `class_course` row this blueprint wrote carries `source`, a row a human +//! attached carries no such key at all, and dropping a course from the +//! blueprint sweeps only the former. The sweep is the pump's own +//! [`crate::domain::class_pump::detach`], so a class losing a course still +//! 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::domain::class_blueprint::{ + ClassBlueprint, ClassBlueprintId, Pumped, SectionStatus, Skip, skip_reason, +}; +use crate::domain::class_course::ClassCourse; +use crate::domain::class_group::{ClassGrade, ClassGroup}; +use crate::domain::class_pump::Attached; +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::domain::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 +/// duplicate is a `409` the store itself decides. +pub async fn create( + db: &Database, + creator: &UserId, + grade: ClassGrade, + courses: Vec, +) -> Result { + let courses = ClassBlueprint::course_list(courses)?; + class_blueprint::create(db, creator, grade, courses).await +} + +/// The row, for callers that only inspect it — the web layer's +/// `blueprint_or_404` reads through here. +pub async fn read( + db: &Database, + id: &ClassBlueprintId, +) -> Result, AppError> { + class_blueprint::read(db, id).await +} + +/// Every blueprint, by grade label — the web layer's paged index. +pub async fn list_all( + db: &Database, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + class_blueprint::list_all(db, limit, offset).await +} + +/// Replace the course list, then reconcile every class at this grade with +/// it: the courses this blueprint no longer holds are detached from the +/// classes *it* attached them to, and the ones it holds are pumped into +/// every class that fits. +/// +/// The write is a compare-and-set on the list this caller read +/// ([`class_blueprint::set_courses_if_unchanged`]), so two +/// managers editing the same grade cannot have one's list silently pump the +/// other's diff — the loser is a 409 and re-reads. +/// +/// Removals run first: a course leaving frees a place under the per-class +/// course ceiling that the same edit's additions can then use. What is swept +/// is derived from the list this write **stored**, never from a diff against +/// the list this handle read ([`class_blueprint::sourced_links`]): the sweep is N +/// sequential transactions in one request, and a failure part-way through +/// used to leave sections carrying courses the template no longer holds with +/// no way back — a re-`PATCH` recomputed an empty diff, and the documented +/// self-heal ("send the list it already holds") swept nothing. Derived from +/// the stored list, that same re-`PATCH` finds the rows still tagged and +/// finishes the job. +/// +/// The price is the other direction: a rival edit that lands *and pumps* +/// between this write and this sweep has its new course detached again, +/// because this sweep asks the list it stored. That is a section short a +/// 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. +pub async fn set_courses( + db: &Database, + blueprint: ClassBlueprint, + courses: Vec, + by: &UserId, +) -> Result<(ClassBlueprint, Pumped), AppError> { + let wanted = ClassBlueprint::course_list(courses)?; + let Some(mut saved) = class_blueprint::set_courses_if_unchanged( + db, + &blueprint.id, + blueprint.courses.clone(), + wanted, + ) + .await? + else { + // The conditional write matched nothing: the row is gone, or its + // list moved since this caller read it. Only this path pays for the + // read that tells those 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), + }; + }; + let doomed = class_blueprint::sourced_links(db, saved.get_id(), &saved.courses).await?; + class_blueprint::drop_links(db, saved.get_id(), doomed).await?; + let pumped = pump(db, &mut saved, by).await?; + Ok((saved, pumped)) +} + +/// Delete the blueprint, taking every attachment it made with it. Courses a +/// human attached to those classes by hand carry no `source` and are left +/// exactly where they are — the same cut a single removal makes, applied to +/// the whole list, because a template that is gone owns nothing. +/// +/// The row goes **first**, and the sweep that follows is by the provenance +/// tag rather than by the list this caller read. Sweeping first was the +/// 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 +/// 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. +/// +/// 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. +/// +/// 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 +/// 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? + }; + class_blueprint::drop_links(db, &blueprint.id, doomed).await +} + +/// Attach every course in this blueprint to `class`, skipping — never +/// aborting on — the ones that do not fit. A course already on the class is +/// a no-op, whoever attached it: this is what makes a pump repeatable, and +/// what stops it re-tagging a hand-attached course as its own. +/// +/// 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. +/// +/// 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 +/// one that just went. +pub async fn apply_to( + db: &Database, + blueprint: &ClassBlueprint, + class: &ClassGroup, + by: &UserId, +) -> Result, AppError> { + let mut skipped = Vec::new(); + apply_courses(db, blueprint, class, by, &mut Vec::new(), &mut skipped).await?; + Ok(skipped) +} + +/// One class's share of a pump, and the body both callers above share. +/// +/// `dead` is the courses this run already found deleted: they are not +/// attempted again, so neither the skip nor [`class_blueprint::prune`]'s +/// write repeats on the next section. A course newly found gone joins it. +/// +/// Answers `false` when the blueprint itself is gone — a caller looping +/// over classes must stop, because every remaining one would answer exactly +/// the same. +async fn apply_courses( + db: &Database, + blueprint: &ClassBlueprint, + class: &ClassGroup, + by: &UserId, + dead: &mut Vec, + skipped: &mut Vec, +) -> Result { + for course in &blueprint.courses { + if dead.contains(course) { + continue; + } + let landed = { + let _lease = BLUEPRINT_LOCK.read().await; + ClassCourse::attach_sourced(class.get_id(), course, by, Some(&blueprint.id), db).await? + }; + if matches!(landed, Attached::PivotGone) { + class_blueprint::prune(db, &blueprint.id, course).await?; + dead.push(course.clone()); + } + if let Some(reason) = skip_reason(&landed) { + skipped.push(Skip { + class: class.get_id().clone(), + class_name: class.get_name().as_str().to_string(), + course: course.clone(), + reason, + }); + } + if matches!(landed, Attached::SourceGone) { + return Ok(false); + } + } + Ok(true) +} + +/// [`apply_to`] every class at this blueprint's grade. The write loop +/// is one transaction per (class, course) and bounded by neither — see the +/// module note. +/// +/// Two things are said once for the whole run rather than once per section, +/// 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. +/// +/// 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 +/// partial state reported in full is what best-effort means everywhere else +/// here. +/// +/// [`Pumped::matched`] is counted off this loop rather than asked of a +/// second query — the sections the run *walked*, so an abort reports what +/// it did and not what the grade holds. +/// +/// `&mut`, because [`class_blueprint::prune`] writes the store and this +/// handle is what both write routes render their response from: a course +/// pruned mid-pump was still listed in the `201`/`200` that pruned it, while +/// the `GET` a moment later did not have it. +pub async fn pump( + db: &Database, + blueprint: &mut ClassBlueprint, + by: &UserId, +) -> Result { + let mut pumped = Pumped { + matched: 0, + skipped: Vec::new(), + }; + let mut dead = Vec::new(); + for class in ClassGroup::list_for_grade(&blueprint.grade, db).await? { + pumped.matched += 1; + if !apply_courses(db, blueprint, &class, by, &mut dead, &mut pumped.skipped).await? { + break; + } + } + // Exactly the ids `prune` took out of the stored row, so the handle and + // the store say the same thing. + blueprint.courses.retain(|course| !dead.contains(course)); + Ok(pumped) +} + +/// How far every section at this grade stands from the template: the +/// courses each one does not carry. Writes nothing — a pump's skip list +/// lives only in the response that reported it, and this is the read that +/// answers "which sections are still out of sync" afterwards. +/// +/// **A link of any source counts as satisfied.** A course a human attached +/// by hand fulfils the template exactly as a pumped one does — that is +/// [`apply_to`]'s own idempotence rule, and a status read that +/// disagreed with it would send managers chasing rows no pump will ever +/// write. +/// +/// A course id the blueprint holds but that no longer exists reads as +/// missing from every section. It is the truth about the section, and this +/// read cannot prune it the way a pump does ([`class_blueprint::prune`]) +/// without writing — but it is no longer a state a course delete leaves +/// behind: the delete's own cascade takes the id out of every template +/// naming it, so only a row written before that cascade existed, or one the +/// pump's own window ([`class_blueprint::prune`]) is about to clear, can +/// still show it. +/// +/// Unpaged, like the [`ClassGroup::list_for_grade`] it is built on: the set +/// is the şube one school runs at one grade, and the caller is asking about +/// all of them. +pub async fn status( + db: &Database, + blueprint: &ClassBlueprint, +) -> Result, AppError> { + let sections = ClassGroup::list_for_grade(&blueprint.grade, db).await?; + if sections.is_empty() { + return Ok(Vec::new()); + } + let classes: Vec = sections + .iter() + .map(|class| class.get_id().record()) + .collect(); + let held = class_blueprint::held_links(db, classes).await?; + Ok(sections + .iter() + .map(|class| SectionStatus { + class: class.get_id().clone(), + class_name: class.get_name().as_str().to_string(), + missing: blueprint + .courses + .iter() + .filter(|course| { + !held + .iter() + .any(|row| &row.class == class.get_id() && &&row.course == course) + }) + .cloned() + .collect(), + }) + .collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constant::{CLASS_COURSE_COUNT_FIELD, MAX_CLASS_COURSES}; + use crate::domain::class_course::ClassCourseId; + use crate::domain::class_group::ClassName; + use crate::domain::class_member::tests::{a_class, a_course, counter, exists, rows}; + + /// A section that a pump's own grade loop can actually find — [`a_class`] + /// carries no grade at all, so `list_for_grade` reaches none of them. + async fn a_section(name: &str, db: &Database) -> ClassGroup { + ClassGroup::create( + &UserId::from_key("manager"), + ClassName::try_new(name).unwrap(), + Some(ClassBlueprint::grade_key("9").unwrap()), + None, + None, + db, + ) + .await + .unwrap() + } + + /// A blueprint holding `courses`, at grade "9". + async fn a_blueprint(courses: Vec, db: &Database) -> ClassBlueprint { + create( + db, + &UserId::from_key("manager"), + ClassBlueprint::grade_key("9").unwrap(), + courses, + ) + .await + .unwrap() + } + + /// Every skip names the record that actually failed. + /// + /// The three refusals a manager can meet come out of two different claims + /// in one transaction, and they used to be reported by one string that + /// guessed: a deleted *course* was announced as a deleted *class*, on a + /// section standing right there. Each is provoked from the state that + /// really produces it, not from the enum. + #[tokio::test] + async fn a_skip_names_what_actually_failed() { + let manager = UserId::from_key("manager"); + + // The course is deleted out from under the pump: the pivot claim + // matches nothing. + let db = crate::database::init_mem().await.unwrap(); + let course = a_course("algebra", None, &db).await; + let class = ClassGroup::read(&a_class("9-A", &db).await, &db) + .await + .unwrap() + .unwrap(); + let blueprint = a_blueprint(vec![course.clone()], &db).await; + db.query("DELETE $c") + .bind(("c", course.record())) + .await + .unwrap() + .check() + .unwrap(); + let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap(); + assert_eq!(skipped.len(), 1, "{skipped:?}"); + assert_eq!( + skipped[0].reason, "course_deleted", + "the course went, not the class" + ); + // …and the dangling id is taken out of the list, so the skip is + // reported once instead of on every pump forever. + assert!( + read(&db, blueprint.get_id()) + .await + .unwrap() + .unwrap() + .get_courses() + .is_empty(), + "a course that no longer exists is pruned from the blueprint" + ); + + // The class is deleted out from under the pump: the counter claim + // matches nothing and the read that follows finds no row. + let db = crate::database::init_mem().await.unwrap(); + let course = a_course("algebra", None, &db).await; + let class = ClassGroup::read(&a_class("9-A", &db).await, &db) + .await + .unwrap() + .unwrap(); + let blueprint = a_blueprint(vec![course.clone()], &db).await; + db.query("DELETE $c") + .bind(("c", class.get_id().record())) + .await + .unwrap() + .check() + .unwrap(); + let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap(); + assert_eq!(skipped.len(), 1, "{skipped:?}"); + assert_eq!( + skipped[0].reason, "class_deleted", + "the class went, not the course" + ); + assert_eq!( + read(&db, blueprint.get_id()) + .await + .unwrap() + .unwrap() + .get_courses(), + &[course], + "a live course is not pruned because a class vanished" + ); + + // The class stands at its own ceiling: the same claim matches nothing, + // but the row is there — and that is the one a manager can act on. + let db = crate::database::init_mem().await.unwrap(); + let course = a_course("algebra", None, &db).await; + let class = ClassGroup::read(&a_class("9-A", &db).await, &db) + .await + .unwrap() + .unwrap(); + let blueprint = a_blueprint(vec![course], &db).await; + db.query(format!( + "UPDATE $c SET {} = $cap", + crate::constant::CLASS_COURSE_COUNT_FIELD + )) + .bind(("c", class.get_id().record())) + .bind(("cap", MAX_CLASS_COURSES)) + .await + .unwrap() + .check() + .unwrap(); + let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap(); + assert_eq!(skipped.len(), 1, "{skipped:?}"); + assert_eq!( + skipped[0].reason, "class_at_course_ceiling", + "a full class is not a deleted one" + ); + } + + /// The delete is a compare-and-set, and it runs *before* the sweep — so a + /// handle whose list moved cannot take the row, and nothing it would have + /// swept is touched either. + /// + /// Provoked with a stale handle rather than a concurrent request, which is + /// exactly the state a `PATCH` landing between the read and the delete puts + /// this caller in, and deterministic where two live requests are not. + #[tokio::test] + async fn a_delete_of_a_list_that_moved_is_a_409_that_writes_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let algebra = a_course("algebra", None, &db).await; + let physics = a_course("physics", None, &db).await; + let class = ClassGroup::read(&a_class("9-A", &db).await, &db) + .await + .unwrap() + .unwrap(); + let stale = a_blueprint(vec![algebra.clone()], &db).await; + apply_to(&db, &stale, &class, &manager).await.unwrap(); + + // The edit this caller did not see: it adds a course and pumps it into + // the section. (The pump is applied by hand because the helper class + // carries no grade for `set_courses`'s own loop to find.) + let (edited, _) = set_courses( + &db, + read(&db, stale.get_id()).await.unwrap().unwrap(), + vec![algebra, physics], + &manager, + ) + .await + .unwrap(); + apply_to(&db, &edited, &class, &manager).await.unwrap(); + + let refused = delete(&db, stale).await; + assert!( + matches!(refused, Err(AppError::Conflict(_))), + "a list that moved is a 409, not a silent delete: {refused:?}" + ); + assert!( + read(&db, &ClassBlueprintId::from_key("9")) + .await + .unwrap() + .is_some(), + "the row the caller did not read is still there" + ); + assert_eq!( + rows("SELECT VALUE id FROM class_course", &db).await, + 2, + "and neither attachment was swept — including the one this handle \ + never knew about" + ); + } + + /// The lease is real: a delete cannot start while a guarded attach holds + /// the read side. + /// + /// That is the whole point of the lock — without it a pump could commit its + /// `class_course` row *after* the delete had swept past, stranding a row + /// tagged with a blueprint nothing can reach. Two live requests would be a + /// coin flip the in-memory engine lies about, so the lease is held directly + /// and the delete is watched not-finishing on a timeout. + #[tokio::test] + async fn a_delete_waits_for_an_attach_in_flight() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let algebra = a_course("algebra", None, &db).await; + let class = ClassGroup::read(&a_class("9-A", &db).await, &db) + .await + .unwrap() + .unwrap(); + let blueprint = a_blueprint(vec![algebra], &db).await; + apply_to(&db, &blueprint, &class, &manager).await.unwrap(); + + // Stand in for an attach mid-transaction, which is exactly the lease + // `apply_to` holds around one course. + let attaching = BLUEPRINT_LOCK.read().await; + let mut deleting = { + let db = db.clone(); + let blueprint = blueprint.clone(); + tokio::spawn(async move { delete(&db, blueprint).await }) + }; + assert!( + tokio::time::timeout(std::time::Duration::from_millis(150), &mut deleting) + .await + .is_err(), + "the delete must not run while an attach is in flight" + ); + assert_eq!( + rows("SELECT VALUE id FROM class_blueprint", &db).await, + 1, + "…and it must not have swept anything either" + ); + + drop(attaching); + deleting.await.unwrap().unwrap(); + assert_eq!( + rows("SELECT VALUE id FROM class_blueprint", &db).await, + 0, + "once the attach is done the delete goes through" + ); + assert_eq!( + rows("SELECT VALUE id FROM class_course", &db).await, + 0, + "…taking every row carrying its tag with it" + ); + } + + /// …and the other side of that lease: it is released before the detaching + /// starts, so a pump is *not* parked behind it. + /// + /// The sweep is one transaction per link row and bounded by nothing — + /// sections × courses, each walking up to a full roster — and `tokio`'s + /// `RwLock` is fair, so a lease held across it stalled every concurrent + /// `POST /classes` in the school, at every grade, for the whole delete. What + /// the lease has to cover is only the compare-and-set and the read that + /// fixes the row set, which `a_delete_waits_for_an_attach_in_flight` above + /// still pins from the other direction. + /// + /// The unbounded loop is stood in for by four slow rows: a `DEFINE EVENT` on + /// `class_course` fires inside each detaching transaction, so the delete is + /// provably still sweeping when the lease is asked for. Nothing here is + /// asserted off a fixed delay — the row going is what says the + /// compare-and-set has run, and one *moment* of a free lease while the sweep + /// is unfinished is the whole claim. A sweep that ended first fails the + /// assertion rather than passing it by default. + #[tokio::test] + async fn a_delete_frees_the_lease_before_its_unbounded_sweep() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let courses = vec![ + a_course("algebra", None, &db).await, + a_course("physics", None, &db).await, + ]; + let blueprint = a_blueprint(courses, &db).await; + for name in ["9-A", "9-B"] { + let class = ClassGroup::read(&a_class(name, &db).await, &db) + .await + .unwrap() + .unwrap(); + apply_to(&db, &blueprint, &class, &manager).await.unwrap(); + } + db.query( + "DEFINE EVENT slow_sweep ON TABLE class_course WHEN $event = 'DELETE' \ + THEN { SLEEP 300ms; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let deleting = { + let (db, blueprint) = (db.clone(), blueprint.clone()); + tokio::spawn(async move { delete(&db, blueprint).await }) + }; + let beat = std::time::Duration::from_millis(10); + // The row is gone the instant the compare-and-set commits, which is + // inside the lease this test is about. + while rows("SELECT VALUE id FROM class_blueprint", &db).await > 0 { + tokio::time::sleep(beat).await; + } + let mut freed = false; + while !deleting.is_finished() { + if BLUEPRINT_LOCK.try_read().is_ok() { + freed = true; + break; + } + tokio::time::sleep(beat).await; + } + assert!( + freed, + "a pump may not wait behind a delete's unbounded sweep" + ); + + deleting.await.unwrap().unwrap(); + assert_eq!( + rows("SELECT VALUE id FROM class_course", &db).await, + 0, + "…and the sweep it ran lease-free still took every row it owned" + ); + } + + /// The other half: a pump holding a handle to a blueprint that has since + /// been deleted writes nothing at all, and says so with its own code. + /// + /// Without the in-transaction claim the attach would land a `class_course` + /// row tagged with a record that no longer exists — the delete's sweep has + /// already run, and the grade label *is* the id, so nothing could ever + /// reach that row again. + #[tokio::test] + async fn a_pump_whose_blueprint_died_attaches_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let algebra = a_course("algebra", None, &db).await; + let class = ClassGroup::read(&a_class("9-A", &db).await, &db) + .await + .unwrap() + .unwrap(); + let stale = a_blueprint(vec![algebra], &db).await; + delete(&db, read(&db, stale.get_id()).await.unwrap().unwrap()) + .await + .unwrap(); + + let skipped = apply_to(&db, &stale, &class, &manager).await.unwrap(); + assert_eq!(skipped.len(), 1, "{skipped:?}"); + assert_eq!( + skipped[0].reason, "blueprint_deleted", + "the template went, not the class or the course" + ); + assert_eq!( + rows("SELECT VALUE id FROM class_course", &db).await, + 0, + "a row tagged with a deleted blueprint is one nothing can sweep" + ); + assert_eq!( + counter(CLASS_COURSE_COUNT_FIELD, class.get_id().record(), &db).await, + 0, + "…and no counter moved for it" + ); + } + + /// A course that no longer exists is pruned and reported **once for the + /// pump**, not once per section: twelve sections at a grade must not answer + /// one dead course with twelve identical skips and twelve identical prune + /// writes. The live course still reaches every section. + /// + /// Stored state is what is asserted — the in-memory engine forges wins, so + /// the links are re-read rather than counted off the return value. + #[tokio::test] + async fn a_dead_course_is_pruned_and_skipped_once_for_the_whole_grade() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let astronomy = a_course("astronomy", None, &db).await; + let algebra = a_course("algebra", None, &db).await; + let a = a_section("9-A", &db).await; + let b = a_section("9-B", &db).await; + let mut blueprint = a_blueprint(vec![astronomy.clone(), algebra.clone()], &db).await; + db.query("DELETE $c") + .bind(("c", astronomy.record())) + .await + .unwrap() + .check() + .unwrap(); + + let Pumped { matched, skipped } = pump(&db, &mut blueprint, &manager).await.unwrap(); + assert_eq!(matched, 2, "both sections at the grade were walked"); + assert_eq!( + skipped.len(), + 1, + "one dead course is one skip for the grade, not one per section: {skipped:?}" + ); + assert_eq!(skipped[0].reason, "course_deleted"); + assert_eq!( + read(&db, blueprint.get_id()) + .await + .unwrap() + .unwrap() + .get_courses(), + std::slice::from_ref(&algebra), + "and the list is pruned to the course that still exists" + ); + for class in [&a, &b] { + assert!( + exists( + ClassCourseId::composite(class.get_id(), &algebra).record(), + &db + ) + .await, + "the live course still reached {}", + class.get_name().as_str() + ); + } + assert_eq!( + rows("SELECT VALUE id FROM class_course", &db).await, + 2, + "…and nothing else was attached" + ); + } + + /// A blueprint that is gone ends the whole grade loop: the answer is about + /// the template, so every remaining section would only repeat it. Reported + /// once, and as `Ok` — best-effort, with whatever committed left standing. + /// + /// Provoked with a stale handle rather than a live interleaving, which the + /// in-memory engine cannot be made to produce; it is the same state a + /// delete landing between the read and the pump leaves this caller in. + #[tokio::test] + async fn a_deleted_blueprint_stops_the_grade_loop_after_one_skip() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let algebra = a_course("algebra", None, &db).await; + a_section("9-A", &db).await; + a_section("9-B", &db).await; + let mut stale = a_blueprint(vec![algebra], &db).await; + delete(&db, read(&db, stale.get_id()).await.unwrap().unwrap()) + .await + .unwrap(); + + let Pumped { matched, skipped } = pump(&db, &mut stale, &manager).await.unwrap(); + assert_eq!( + skipped.len(), + 1, + "the template went once, not once per section: {skipped:?}" + ); + assert_eq!(skipped[0].reason, "blueprint_deleted"); + assert_eq!( + matched, 1, + "an abort reports the sections it walked, not the two the grade holds" + ); + assert_eq!( + rows("SELECT VALUE id FROM class_course", &db).await, + 0, + "…and nothing was attached under a blueprint nothing could sweep" + ); + } +} diff --git a/src/service/mod.rs b/src/service/mod.rs index 892e3cd..7fccfc1 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -2,6 +2,7 @@ //! SurrealQL text. pub mod appointment; +pub mod class_blueprint; pub mod course; pub mod exam_attempt; pub mod note; diff --git a/src/web/classes.rs b/src/web/classes.rs index 3208617..5d45413 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -25,6 +25,7 @@ use crate::domain::course::CourseId; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service::class_blueprint; use crate::state::AppState; use super::courses::can_manage_course; @@ -429,10 +430,12 @@ async fn stock_from_blueprint( db: &Database, ) -> Option<(String, Vec)> { let grade = class.get_grade()?; - let blueprint = ClassBlueprint::read(&ClassBlueprintId::for_grade(grade), db) + let blueprint = class_blueprint::read(db, &ClassBlueprintId::for_grade(grade)) .await .ok()??; - let skipped = blueprint.apply_to(class, by, db).await.ok()?; + let skipped = class_blueprint::apply_to(db, &blueprint, class, by) + .await + .ok()?; Some((blueprint.get_grade().as_str().to_string(), skipped)) } @@ -872,8 +875,8 @@ async fn attach_course( Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { let class = class_or_404(&id, &st.db).await?; - let Some(course) = crate::service::course::read(&st.db, &CourseId::from_key(&req.course_id)) - .await? + let Some(course) = + crate::service::course::read(&st.db, &CourseId::from_key(&req.course_id)).await? else { return Err(AppError::Validation(ValidationError::Invalid { field: "course_id", @@ -1165,7 +1168,7 @@ async fn resolve_courses(ids: &[String], db: &Database) -> Result, /// The blueprint a path grade names, or a 404. async fn blueprint_or_404(grade: &str, db: &Database) -> Result { - ClassBlueprint::read(&ClassBlueprintId::from_key(grade), db) + class_blueprint::read(db, &ClassBlueprintId::from_key(grade)) .await? .ok_or(AppError::NotFound) } @@ -1216,8 +1219,8 @@ async fn create_blueprint( ) -> Result<(StatusCode, Json), AppError> { let grade = ClassBlueprint::grade_key(&req.grade)?; let courses = resolve_courses(&req.course_ids, &st.db).await?; - let mut blueprint = ClassBlueprint::create(user.get_id(), grade, courses, &st.db).await?; - let pumped = blueprint.pump(user.get_id(), &st.db).await?; + let mut blueprint = class_blueprint::create(&st.db, user.get_id(), grade, courses).await?; + let pumped = class_blueprint::pump(&st.db, &mut blueprint, user.get_id()).await?; let body = blueprint_body(&blueprint, &pumped, &st.db).await?; Ok((StatusCode::CREATED, Json(body))) } @@ -1243,7 +1246,7 @@ async fn list_blueprints( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let (blueprints, total) = ClassBlueprint::list_all(limit, offset, &st.db).await?; + let (blueprints, total) = class_blueprint::list_all(&st.db, limit, offset).await?; let people = person_map( blueprints .iter() @@ -1322,9 +1325,8 @@ async fn update_blueprint( ) -> Result, AppError> { let blueprint = blueprint_or_404(&grade, &st.db).await?; let courses = resolve_courses(&req.course_ids, &st.db).await?; - let (saved, pumped) = blueprint - .set_courses(courses, user.get_id(), &st.db) - .await?; + let (saved, pumped) = + class_blueprint::set_courses(&st.db, blueprint, courses, user.get_id()).await?; Ok(Json(blueprint_body(&saved, &pumped, &st.db).await?)) } @@ -1354,10 +1356,8 @@ async fn delete_blueprint( RequireManager(_user): RequireManager, Path(grade): Path, ) -> Result { - blueprint_or_404(&grade, &st.db) - .await? - .delete(&st.db) - .await?; + let blueprint = blueprint_or_404(&grade, &st.db).await?; + class_blueprint::delete(&st.db, blueprint).await?; Ok(StatusCode::NO_CONTENT) } @@ -1397,7 +1397,7 @@ async fn blueprint_status( Path(grade): Path, ) -> Result, AppError> { let blueprint = blueprint_or_404(&grade, &st.db).await?; - let sections = blueprint.status(&st.db).await?; + let sections = class_blueprint::status(&st.db, &blueprint).await?; Ok(Json(BlueprintStatusResponse { grade: blueprint.get_grade().as_str().to_string(), courses: blueprint @@ -1460,7 +1460,7 @@ async fn apply_blueprint( crate::service::course::require_open(&st.db, &course).await?; } } - let skipped = blueprint.apply_to(&class, user.get_id(), &st.db).await?; + let skipped = class_blueprint::apply_to(&st.db, &blueprint, &class, user.get_id()).await?; Ok(Json(ApplyResponse { skipped: skipped.iter().map(SkipResponse::new).collect(), })) diff --git a/tests/regress_blueprints.rs b/tests/regress_blueprints.rs index fb9a181..6aa989b 100644 --- a/tests/regress_blueprints.rs +++ b/tests/regress_blueprints.rs @@ -19,6 +19,7 @@ use hezarfen_backend::domain::class_blueprint::ClassBlueprint; use hezarfen_backend::domain::course::CourseId; use hezarfen_backend::domain::user::UserId; use hezarfen_backend::error::AppError; +use hezarfen_backend::service::class_blueprint; use serde_json::{Value, json}; /// One counter, re-read out of the store. @@ -971,7 +972,7 @@ async fn a_row_written_before_the_column_reads_as_hand_attached() { /// The window the lock exists to close, made visible. /// -/// `ClassBlueprint::delete` removes the row and then sweeps by the provenance +/// `service::class_blueprint::delete` removes the row and then sweeps by the provenance /// tag, while a pump reads that row inside the transaction that writes the link /// — a cross-record read-then-write the store does not serialize. A pump that /// passed its liveness claim and then lost the blueprint commits a @@ -983,7 +984,7 @@ async fn a_row_written_before_the_column_reads_as_hand_attached() { /// `class_course` fires *inside* the pump's own transaction, the instant the /// link row lands — which is exactly "after the guard passed, before the /// commit", every single time. This is a below-the-lock probe by construction -/// (the store deletes the row, not `ClassBlueprint::delete`), so it does not +/// (the store deletes the row, not `service::class_blueprint::delete`), so it does not /// test `BLUEPRINT_LOCK`; it pins the end state that lock prevents in-process, /// and the recovery contract that covers the one residue it cannot — a process /// crash between the delete and its sweep. @@ -1625,11 +1626,11 @@ async fn a_template_write_refuses_a_course_that_is_gone() { let algebra = CourseId::from_key(&create_course(&app, &manager, "algebra").await); let ghost = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"); - let refused = ClassBlueprint::create( + let refused = class_blueprint::create( + &db, &by, ClassBlueprint::grade_key("9").unwrap(), vec![ghost.clone()], - &db, ) .await; assert!( @@ -1642,17 +1643,16 @@ async fn a_template_write_refuses_a_course_that_is_gone() { "…and nothing may be stored" ); - let blueprint = ClassBlueprint::create( + let blueprint = class_blueprint::create( + &db, &by, ClassBlueprint::grade_key("9").unwrap(), vec![algebra.clone()], - &db, ) .await .unwrap(); - let refused = blueprint - .set_courses(vec![algebra.clone(), ghost], &by, &db) - .await; + let refused = + class_blueprint::set_courses(&db, blueprint, vec![algebra.clone(), ghost], &by).await; assert!( matches!(refused, Err(AppError::Validation(_))), "the edit carries the same claim: {refused:?}"