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