From 324b078f596e68b1536b9401c310f0faad2b4179 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 2 Aug 2026 00:14:32 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=94=A9=20claim=20term=20refcounts?= =?UTF-8?q?=20inside=20the=20row=20transaction?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/domain/cap.rs | 8 ++ src/domain/class_group.rs | 203 ++++++++++++++++++++----------- src/domain/course.rs | 239 ++++++++++++++++++++++++++----------- src/domain/field_update.rs | 125 ++++++++++++++++++- src/domain/term.rs | 26 ++++ 5 files changed, 460 insertions(+), 141 deletions(-) diff --git a/src/domain/cap.rs b/src/domain/cap.rs index 4fc431b..e4a2c3a 100644 --- a/src/domain/cap.rs +++ b/src/domain/cap.rs @@ -53,6 +53,14 @@ use crate::error::AppError; // only about how many writes a process has in flight. static CLAIM_LOCK: Mutex<()> = Mutex::const_new(()); +/// [`CLAIM_LOCK`], for a counter write that rides someone else's transaction +/// instead of [`write`]'s — [`crate::domain::field_update::FieldUpdate`]'s term +/// move claims and releases inside the very `UPDATE`'s transaction, and still +/// owes the process one counter write at a time. +pub(crate) async fn counter_lock() -> tokio::sync::MutexGuard<'static, ()> { + CLAIM_LOCK.lock().await +} + /// "No cap" as a number, so the guard stays one comparison instead of a /// nullable branch: `NONE`/`NULL` bind ambiguity is a worse trade than a /// sentinel no roster will ever reach. diff --git a/src/domain/class_group.rs b/src/domain/class_group.rs index 0277c69..d53dc74 100644 --- a/src/domain/class_group.rs +++ b/src/domain/class_group.rs @@ -21,7 +21,7 @@ use crate::domain::cap; use crate::domain::field_update::FieldUpdate; use crate::domain::monotonic_id::next_ulid; use crate::domain::page::PagedList; -use crate::domain::term::TermId; +use crate::domain::term::{self, TermId}; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_optional, validate_required}; @@ -122,10 +122,12 @@ impl ClassGroup { &self.creator == user } - /// Create the class, claiming a reference on the term it links (if any) - /// *before* the row is written: the claim is a conditional write on the term - /// row, so it fails when the term is already gone and it makes the term - /// undeletable the instant this link exists. + /// Create the class, claiming a reference on the term it links (if any) in + /// the *same transaction* as the row, exactly as + /// [`crate::domain::course::Course::create`] does: the claim is a + /// conditional write on the term row, so it fails when the term is already + /// gone, it makes the term undeletable the instant this link exists, and no + /// crash can leave either half without the other. pub async fn create( creator: &UserId, name: ClassName, @@ -133,10 +135,6 @@ impl ClassGroup { term: Option, db: &Database, ) -> Result { - if let Some(term) = &term { - claim_term(term, db).await?; - } - let claimed = term.clone(); let class = ClassGroup { id: ClassGroupId::generate(), creator: creator.clone(), @@ -144,20 +142,27 @@ impl ClassGroup { grade, term, }; - let created: Result, _> = - db.create(class.id.record()).content(class).await; - match created { - Ok(Some(created)) => Ok(created), - other => { - // The link never landed, so the reference has to go back. - if let Some(term) = &claimed { - cap::release(&term.record(), TERM_CLASS_COUNT_FIELD, db).await?; - } - match other { - Err(err) => Err(err.into()), - _ => Err(AppError::Internal("failed to create class".into())), - } - } + let id = class.id.record(); + let Some(term) = class.term.clone() else { + let created: Option = db.create(id).content(class).await?; + return created.ok_or_else(|| AppError::Internal("failed to create class".into())); + }; + match cap::claim_and_create( + &term.record(), + TERM_CLASS_COUNT_FIELD, + cap::UNLIMITED, + &id, + &class, + db, + ) + .await? + { + cap::Claimed::Made(created) => Ok(created), + // Uncapped, so "full" can only mean the conditional write matched no + // term row at all — the claim doubles as the existence check. + cap::Claimed::Full => Err(term::gone_error()), + // Unreachable: the id is a ULID this call just generated. + cap::Claimed::Duplicate => Err(AppError::Internal("failed to create class".into())), } } @@ -182,10 +187,10 @@ impl ClassGroup { /// they take the outer/inner `Option>`: `None` = omitted (keep), /// `Some(None)` = clear. /// - /// A term move is claim-then-write-then-release, in that order, exactly as - /// in [`crate::domain::course::Course::update`]: the new term is made - /// undeletable before the link points at it, and the old one is only let go - /// once the link has actually moved off it. + /// A term move claims the new term and releases the old one inside the very + /// transaction that moves the link, exactly as in + /// [`crate::domain::course::Course::update`]: both counters and the link + /// commit together, so no crash can strand a count on a term nothing links. pub async fn update( self, name: Option, @@ -193,37 +198,14 @@ impl ClassGroup { term: Option>, db: &Database, ) -> Result { - let claimed = match &term { - Some(Some(new)) if Some(new) != self.term.as_ref() => { - claim_term(new, db).await?; - Some(new.clone()) - } - _ => None, - }; - let updated = FieldUpdate::new(self.id.record()) + let (claim, release) = term::ref_move(self.term.as_ref(), &term); + FieldUpdate::new(self.id.record()) .set("name", name) .set("grade", grade) .set("term", term.map(|term| term.map(|term| term.record()))) + .refcount(TERM_CLASS_COUNT_FIELD, claim, release, term::gone_error()) .run::(db) - .await; - match updated { - Ok(updated) => { - // The stored row is the authority on where the link ended up — - // a PATCH that carried no `term_id` leaves it untouched. - if let Some(old) = &self.term - && updated.term.as_ref() != Some(old) - { - cap::release(&old.record(), TERM_CLASS_COUNT_FIELD, db).await?; - } - Ok(updated) - } - Err(err) => { - if let Some(new) = &claimed { - cap::release(&new.record(), TERM_CLASS_COUNT_FIELD, db).await?; - } - Err(err) - } - } + .await } /// Delete the class and give its term reference back. Nothing cascades: a @@ -280,19 +262,6 @@ impl ClassGroup { } } -/// Take a reference on `term` for a class about to link it. The conditional -/// write doubles as the existence check — the class half of -/// [`crate::domain::course`]'s `claim_term`, against the class column. -async fn claim_term(term: &TermId, db: &Database) -> Result<(), AppError> { - if cap::claim(&term.record(), TERM_CLASS_COUNT_FIELD, cap::UNLIMITED, db).await? { - return Ok(()); - } - Err(AppError::Validation(ValidationError::Invalid { - field: "term_id", - reason: "term does not exist", - })) -} - #[cfg(test)] mod tests { use super::*; @@ -329,6 +298,25 @@ mod tests { .unwrap() } + /// The stored `class_count` on one term, absent counting as zero. + async fn count_on(term: &TermId, db: &Database) -> i64 { + let mut result = db + .query(format!( + "SELECT VALUE ({TERM_CLASS_COUNT_FIELD} ?? 0) FROM $term" + )) + .bind(("term", term.record())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .first() + .copied() + .unwrap_or(0) + } + /// How many rows `sql` selects ids for. async fn rows(sql: &str, db: &Database) -> usize { let mut result = db.query(sql).await.unwrap().check().unwrap(); @@ -438,6 +426,87 @@ mod tests { } } + /// The class half of the invariant on the create path: a refused create + /// leaves neither the row nor a count stranded on a term (which the term's + /// delete guard reads, so a stray one would make it undeletable forever). + #[tokio::test] + async fn a_refused_create_writes_neither_row_nor_count() { + let db = crate::database::init_mem().await.unwrap(); + let term = a_term(&db).await; + let id = term.get_id().clone(); + assert!(term.delete(&db).await.unwrap()); + + let error = ClassGroup::create( + &UserId::from_key("manager"), + ClassName::try_new("9-A").unwrap(), + None, + Some(id), + &db, + ) + .await + .expect_err("a term that is gone must not be linkable"); + assert!(error.to_string().contains("term does not exist")); + assert_eq!( + rows("SELECT VALUE id FROM class_group", &db).await, + 0, + "a refused create may write no row" + ); + assert_eq!( + rows("SELECT VALUE id FROM term", &db).await, + 0, + "…and least of all a count on a term it just brought back" + ); + } + + /// The class mirror of + /// [`crate::domain::course::Course`]'s move tests: a term move carries both + /// counters with the link, and a move to a term that is gone rolls the + /// release back with the abort (the transaction releases before it claims, + /// so the old count would be 0 if the abort did not undo it). + #[tokio::test] + async fn a_class_term_move_moves_both_counts_or_neither() { + let db = crate::database::init_mem().await.unwrap(); + let at = crate::domain::timestamp::Timestamp::from_millis; + let from = a_term(&db).await; + let to = Term::create(TermName::try_new("2027").unwrap(), at(100), at(200), &db) + .await + .unwrap(); + let dead = Term::create(TermName::try_new("2028").unwrap(), at(100), at(200), &db) + .await + .unwrap(); + let dead_id = dead.get_id().clone(); + assert!(dead.delete(&db).await.unwrap()); + let class = class_on(Some(from.get_id().clone()), &db).await; + + let error = class + .clone() + .update( + Some(ClassName::try_new("9-B").unwrap()), + None, + Some(Some(dead_id)), + &db, + ) + .await + .expect_err("a term that is gone must not be linkable"); + assert!(error.to_string().contains("term does not exist")); + let stored = ClassGroup::read(class.get_id(), &db).await.unwrap().unwrap(); + assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put"); + assert_eq!(stored.get_name().as_str(), "9-A", "…and so does the row"); + assert_eq!( + count_on(from.get_id(), &db).await, + 1, + "the release must roll back with the abort" + ); + + let moved = class + .update(None, None, Some(Some(to.get_id().clone())), &db) + .await + .unwrap(); + assert_eq!(moved.get_term(), Some(to.get_id())); + assert_eq!(count_on(from.get_id(), &db).await, 0, "the old term is free"); + assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); + } + /// [`crate::domain::course::Course::delete`]'s class sweep: deleting a course /// takes its `class_course` attachments with it and gives each class its /// count back, or the classes would be undeletable forever over rows that diff --git a/src/domain/course.rs b/src/domain/course.rs index 12c1e88..2e3f216 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -9,7 +9,7 @@ use crate::database::{Database, transaction_with_retry}; use crate::domain::cap; use crate::domain::field_update::FieldUpdate; use crate::domain::page::PagedList; -use crate::domain::term::TermId; +use crate::domain::term::{self, TermId}; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_course_kind, validate_optional, validate_required}; @@ -161,11 +161,12 @@ impl Course { self.teachers.contains(user) } - /// Create the course, claiming a reference on the term it links (if any) - /// *before* the row is written: the claim is a conditional write on the - /// term row, so it fails when the term is already gone and it makes the - /// term undeletable the instant this link exists, which the count-then-write - /// mutex it replaced could not do. + /// Create the course, claiming a reference on the term it links (if any) in + /// the *same transaction* as the row: the claim is a conditional write on + /// the term row, so it fails when the term is already gone and it makes the + /// term undeletable the instant this link exists — and a crash can never + /// leave one without the other, which a claim sent as its own query could + /// (the count would strand and the term be undeletable forever). pub async fn create( creator: &UserId, title: CourseTitle, @@ -175,10 +176,6 @@ impl Course { capacity: Option, db: &Database, ) -> Result { - if let Some(term) = &term { - claim_term(term, db).await?; - } - let claimed = term.clone(); let course = Course { id: CourseId::generate(), creator: creator.clone(), @@ -189,20 +186,27 @@ impl Course { description, kind, }; - let created: Result, _> = - db.create(course.id.record()).content(course).await; - match created { - Ok(Some(created)) => Ok(created), - other => { - // The link never landed, so the reference has to go back. - if let Some(term) = &claimed { - cap::release(&term.record(), COURSE_COUNT_FIELD, db).await?; - } - match other { - Err(err) => Err(err.into()), - _ => Err(AppError::Internal("failed to create course".into())), - } - } + let id = course.id.record(); + let Some(term) = course.term.clone() else { + let created: Option = db.create(id).content(course).await?; + return created.ok_or_else(|| AppError::Internal("failed to create course".into())); + }; + match cap::claim_and_create( + &term.record(), + COURSE_COUNT_FIELD, + cap::UNLIMITED, + &id, + &course, + db, + ) + .await? + { + cap::Claimed::Made(created) => Ok(created), + // Uncapped, so "full" can only mean the conditional write matched no + // term row at all — the existence check the pre-flight lookup makes. + cap::Claimed::Full => Err(term::gone_error()), + // Unreachable: the id is a ULID this call just generated. + cap::Claimed::Duplicate => Err(AppError::Internal("failed to create course".into())), } } @@ -280,43 +284,21 @@ impl Course { capacity: Option>, db: &Database, ) -> Result { - // A term move is claim-then-write-then-release, in that order: the new - // term is made undeletable before the link points at it, and the old - // one is only let go once the link has actually moved off it. Doing it - // the other way round would open exactly the window this replaced. - let claimed = match &term { - Some(Some(new)) if Some(new) != self.term.as_ref() => { - claim_term(new, db).await?; - Some(new.clone()) - } - _ => None, - }; - let updated = FieldUpdate::new(self.id.record()) + // A term move claims the new term and releases the old one inside the + // very transaction that moves the link, so no crash can leave a count + // without its link (the term would be undeletable forever) or a link + // without its count. A PATCH that carried no `term_id`, or re-stated the + // link it already had, moves neither counter. + let (claim, release) = term::ref_move(self.term.as_ref(), &term); + FieldUpdate::new(self.id.record()) .set("title", title) .set("description", description) .set("kind", kind) .set("term", term.map(|term| term.map(|term| term.record()))) .set("capacity", capacity) + .refcount(COURSE_COUNT_FIELD, claim, release, term::gone_error()) .run::(db) - .await; - match updated { - Ok(updated) => { - // The stored row is the authority on where the link ended up — - // a PATCH that carried no `term_id` leaves it untouched. - if let Some(old) = &self.term - && updated.term.as_ref() != Some(old) - { - cap::release(&old.record(), COURSE_COUNT_FIELD, db).await?; - } - Ok(updated) - } - Err(err) => { - if let Some(new) = &claimed { - cap::release(&new.record(), COURSE_COUNT_FIELD, db).await?; - } - Err(err) - } - } + .await } /// Assign `teacher` to run this course, or return the course untouched if @@ -472,23 +454,10 @@ impl Course { } } -/// Take a reference on `term` for a course about to link it. The conditional -/// write doubles as the existence check: a term that a delete already removed -/// matches nothing, and the caller answers exactly what the pre-flight lookup -/// in `web::terms::resolve_term` would have. -async fn claim_term(term: &TermId, db: &Database) -> Result<(), AppError> { - if cap::claim(&term.record(), COURSE_COUNT_FIELD, cap::UNLIMITED, db).await? { - return Ok(()); - } - Err(AppError::Validation(ValidationError::Invalid { - field: "term_id", - reason: "term does not exist", - })) -} - #[cfg(test)] mod tests { use super::*; + use crate::domain::term::{Term, TermName}; async fn course_on(term: Option, db: &Database) -> Course { Course::create( @@ -557,8 +526,6 @@ mod tests { /// back. Dropping the release in `delete` leaves the term deletable never. #[tokio::test] async fn a_term_is_deletable_only_once_no_course_links_it() { - use crate::domain::term::{Term, TermName}; - let db = crate::database::init_mem().await.unwrap(); let at = crate::domain::timestamp::Timestamp::from_millis; let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db) @@ -613,6 +580,136 @@ mod tests { assert!(error.to_string().contains("term does not exist")); } + /// The stored `course_count` on one term, absent counting as zero. + async fn count_on(term: &TermId, db: &Database) -> i64 { + let mut result = db + .query(format!("SELECT VALUE ({COURSE_COUNT_FIELD} ?? 0) FROM $term")) + .bind(("term", term.record())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .first() + .copied() + .unwrap_or(0) + } + + /// How many rows `sql` selects ids for. + async fn rows(sql: &str, db: &Database) -> usize { + let mut result = db.query(sql).await.unwrap().check().unwrap(); + result.take::>(0).unwrap().len() + } + + async fn a_term(name: &str, db: &Database) -> Term { + let at = crate::domain::timestamp::Timestamp::from_millis; + Term::create(TermName::try_new(name).unwrap(), at(100), at(200), db) + .await + .unwrap() + } + + /// The invariant, on the create path: a claim and the row it accounts for + /// commit together or not at all. A refused create must therefore leave + /// *neither* — no course row, and no count stranded on a term (which is + /// worse than it sounds: the term's delete guard reads that count, so a + /// stray one makes the term undeletable forever). + #[tokio::test] + async fn a_refused_create_writes_neither_row_nor_count() { + let db = crate::database::init_mem().await.unwrap(); + let term = a_term("2026", &db).await; + let id = term.get_id().clone(); + assert!(term.delete(&db).await.unwrap()); + + let error = Course::create( + &UserId::from_key("teacher"), + CourseTitle::try_new("algebra").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + Some(id), + None, + &db, + ) + .await + .expect_err("a term that is gone must not be linkable"); + assert!(error.to_string().contains("term does not exist")); + assert_eq!( + rows("SELECT VALUE id FROM course", &db).await, + 0, + "a refused create may write no row" + ); + assert_eq!( + rows("SELECT VALUE id FROM term", &db).await, + 0, + "…and least of all a count on a term it just brought back" + ); + } + + /// The invariant on the PATCH path, both directions: a move carries the new + /// term's claim and the old term's release with the link itself. + #[tokio::test] + async fn a_term_move_moves_the_count() { + let db = crate::database::init_mem().await.unwrap(); + let from = a_term("2026", &db).await; + let to = a_term("2027", &db).await; + let course = course_on(Some(from.get_id().clone()), &db).await; + assert_eq!(count_on(from.get_id(), &db).await, 1); + + let moved = course + .update(None, None, None, Some(Some(to.get_id().clone())), None, &db) + .await + .unwrap(); + assert_eq!(moved.get_term(), Some(to.get_id())); + assert_eq!(count_on(from.get_id(), &db).await, 0, "the old term is free"); + assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); + assert!(from.clone().delete(&db).await.unwrap()); + assert!(!to.clone().delete(&db).await.unwrap()); + } + + /// The rollback proof. The transaction releases the old term *before* it + /// claims the new one, so a move to a term that is gone has already + /// decremented when the claim throws — the old count still being 1 is the + /// abort undoing a write that really happened, not a branch that never ran. + /// The title moves in the same PATCH, and must not stick either. + #[tokio::test] + async fn a_term_move_to_a_dead_term_leaves_everything_untouched() { + let db = crate::database::init_mem().await.unwrap(); + let from = a_term("2026", &db).await; + let dead = a_term("2027", &db).await; + let dead_id = dead.get_id().clone(); + assert!(dead.delete(&db).await.unwrap()); + let course = course_on(Some(from.get_id().clone()), &db).await; + + let error = course + .clone() + .update( + Some(CourseTitle::try_new("moved").unwrap()), + None, + None, + Some(Some(dead_id)), + None, + &db, + ) + .await + .expect_err("a term that is gone must not be linkable"); + assert!(error.to_string().contains("term does not exist")); + + let stored = Course::read(course.get_id(), &db).await.unwrap().unwrap(); + assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put"); + assert_eq!(stored.get_title().as_str(), "algebra", "…and so does the row"); + assert_eq!( + count_on(from.get_id(), &db).await, + 1, + "the release must roll back with the abort" + ); + assert_eq!( + rows("SELECT VALUE id FROM term", &db).await, + 1, + "the dead term must not be resurrected by the claim" + ); + } + #[tokio::test] async fn title_is_required() { assert!(CourseTitle::try_new("algebra").is_ok()); diff --git a/src/domain/field_update.rs b/src/domain/field_update.rs index fa2ea3a..8ccdec0 100644 --- a/src/domain/field_update.rs +++ b/src/domain/field_update.rs @@ -24,9 +24,16 @@ use surrealdb::types::{RecordId, SurrealValue, Value}; -use crate::database::{Database, write_with_retry}; +use crate::database::{Database, transaction_with_retry, write_with_retry}; +use crate::domain::cap; use crate::error::AppError; +/// The `THROW` markers [`FieldUpdate::refcount`]'s transaction aborts with: the +/// row the reference was to be claimed on is gone, and the row being patched is +/// gone (or its guard bit). +const CLAIM_MARK: &str = "ref_claim_gone"; +const ROW_MARK: &str = "ref_row_gone"; + pub struct FieldUpdate { id: RecordId, /// `field = $field` fragments, in the order they were set. @@ -36,6 +43,8 @@ pub struct FieldUpdate { ordered: Option<(&'static str, &'static str, AppError)>, /// `(condition, refusal)` for [`FieldUpdate::guard`]. guard: Option<(&'static str, AppError)>, + /// `(counter field, claim, release, refusal)` for [`FieldUpdate::refcount`]. + refcount: Option<(&'static str, Option, Option, AppError)>, } impl FieldUpdate { @@ -46,11 +55,13 @@ impl FieldUpdate { bindings: Vec::new(), ordered: None, guard: None, + refcount: None, } } /// Write `field` only when the request carried it. The bind variable is - /// named after the field, so `id` is the one name a caller must not use. + /// named after the field, so `id` — and `ref_claim`/`ref_release`, which + /// [`FieldUpdate::refcount`] binds — are the names a caller must not use. #[must_use] pub fn set(mut self, field: &'static str, value: Option) -> Self { if let Some(value) = value { @@ -97,9 +108,38 @@ impl FieldUpdate { self } + /// Move a reference counter *with* this write: `claim` takes one on the row + /// the link moves to, `release` gives one back on the row it moves off, and + /// both ride the same `BEGIN…COMMIT` as the `UPDATE` that moves the link. + /// + /// That is the whole point. A claim sent as its own query leaves a window + /// where a crash strands a count on a row nothing links any more — and a + /// count is what a delete guard reads, so the stranded one makes its parent + /// undeletable forever. `refused` is the answer when the claimed row is gone + /// (the conditional write doubles as the existence check, as in + /// [`crate::domain::cap`]); the transaction then aborts, so the release and + /// the row write never happened either. + /// + /// Only ever called alongside a `.set()` of the very column that carries the + /// link, so the empty-request short-circuit below cannot swallow a move. + #[must_use] + pub fn refcount( + mut self, + field: &'static str, + claim: Option, + release: Option, + refused: AppError, + ) -> Self { + if claim.is_some() || release.is_some() { + self.refcount = Some((field, claim, release, refused)); + } + self + } + /// Run the update and return the stored row. An empty request writes /// nothing at all and reads the row back unchanged. pub async fn run(mut self, db: &Database) -> Result { + let moved = self.refcount.take(); if self.assignments.is_empty() { let row: Option = db.select(self.id).await?; return row.ok_or(AppError::NotFound); @@ -145,7 +185,13 @@ impl FieldUpdate { // Retried on a write conflict: a guarded PATCH contends on the very row // its guard reads, and the loser wrote nothing, so re-sending it is the // recovery — see [`write_with_retry`]. - let rows: Vec = write_with_retry(db, &sql, &self.bindings).await?; + let rows: Vec = match moved { + Some((field, claim, release, ref_refused)) => { + run_with_refcount(db, &sql, self.bindings, field, claim, release, ref_refused) + .await? + } + None => write_with_retry(db, &sql, &self.bindings).await?, + }; // No row back means the guard bit (or, in the window after the handler's // read, the row was deleted — the guard cannot tell the two apart, and // reports the refusal it was given). @@ -158,3 +204,76 @@ impl FieldUpdate { self.bindings.iter().any(|(name, _)| name == field) } } + +/// Send `update` with its counter move, as one transaction. An empty `Vec` back +/// means the row write matched nothing, exactly as [`write_with_retry`] would +/// have reported it, so the caller's refusal is unchanged. +/// +/// Admissible for [`transaction_with_retry`]: every statement is an `UPDATE`, +/// an `IF`/`THROW` or a `RETURN`, and none of those can answer "already +/// exists" — a lost round writes nothing and re-sending it is the recovery. +#[allow(clippy::too_many_arguments)] +async fn run_with_refcount( + db: &Database, + update: &str, + mut bindings: Vec<(String, Value)>, + field: &'static str, + claim: Option, + release: Option, + refused: AppError, +) -> Result, AppError> { + // Parenthesized `??` throughout: `n ?? 0 + 1` parses as `n ?? (0 + 1)`. + // Both counter writes commit with the row write or neither does, so their + // order is free — the release goes first because that is what makes the + // rollback observable: a move to a term that is gone decrements before the + // claim throws, and the old count still being there proves the abort undid + // it (`a_term_move_to_a_dead_term_leaves_everything_untouched`). + let mut statements: Vec = Vec::new(); + if let Some(release) = release { + statements.push(format!( + "UPDATE $ref_release SET {field} = math::max([({field} ?? 0) - 1, 0])" + )); + bindings.push(("ref_release".into(), release.into_value())); + } + if let Some(claim) = claim { + statements.push(format!( + "LET $seat = (UPDATE $ref_claim SET {field} = ({field} ?? 0) + 1 RETURN VALUE id)" + )); + statements.push(format!("IF array::len($seat) = 0 {{ THROW '{CLAIM_MARK}' }}")); + bindings.push(("ref_claim".into(), claim.into_value())); + } + statements.push(format!("LET $row = ({update})")); + // Without this the claim would outlive a row write that matched nothing — + // the very leak the transaction exists to close. + statements.push(format!("IF array::len($row) = 0 {{ THROW '{ROW_MARK}' }}")); + statements.push("RETURN $row".into()); + let sql = format!( + "BEGIN TRANSACTION; {}; COMMIT TRANSACTION;", + statements.join("; ") + ); + // BEGIN is slot 0, so the trailing RETURN sits at `statements.len()`. + let slot = statements.len(); + + // One counter write in flight at a time, like every other counter write. + let _guard = cap::counter_lock().await; + let (mut result, mut errors) = + transaction_with_retry(db, &sql, &bindings, &[CLAIM_MARK, ROW_MARK]).await?; + if errors + .values() + .any(|error| error.to_string().contains(CLAIM_MARK)) + { + return Err(refused); + } + if errors + .values() + .any(|error| error.to_string().contains(ROW_MARK)) + { + return Ok(Vec::new()); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Sound only because the error map came back empty: `take_errors` swap- + // removes errored slots, which would renumber the rest. + Ok(result.take::>(slot)?) +} diff --git a/src/domain/term.rs b/src/domain/term.rs index 87ebed3..ea9afb3 100644 --- a/src/domain/term.rs +++ b/src/domain/term.rs @@ -41,6 +41,32 @@ impl TermId { } } +/// The answer every link to a term that is not there gets — the claim is a +/// conditional write on the term row, so a term a delete already removed +/// matches nothing and the caller says exactly what `web::terms::resolve_term`'s +/// pre-flight lookup would have. +pub fn gone_error() -> AppError { + AppError::Validation(ValidationError::Invalid { + field: "term_id", + reason: "term does not exist", + }) +} + +/// What a PATCH's `term` field owes the refcounts: the term to claim, and the +/// one to give back. Covers all three moves — set (none→some), move +/// (some→other) and clear (some→none) — and moves nothing for a PATCH that +/// omitted the field or re-stated the link it already had. +pub fn ref_move( + current: Option<&TermId>, + patch: &Option>, +) -> (Option, Option) { + match patch { + None => (None, None), + Some(next) if next.as_ref() == current => (None, None), + Some(next) => (next.as_ref().map(TermId::record), current.map(TermId::record)), + } +} + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct TermName(String);