🔩 claim term refcounts inside the row transaction
Browse files at this commit324b078f596e68b1536b9401c310f0faad2b4179Parent: 0c7403b- fix
- 🔩 claim term refcounts inside the row transaction
5 changed files +460 -141
- src/domain/cap.rs +8 -0
- src/domain/class_group.rs +136 -67
- src/domain/course.rs +168 -71
- src/domain/field_update.rs +122 -3
- src/domain/term.rs +26 -0
src/domain/cap.rsmodified+8 -0
| @@ -53,6 +53,14 @@ use crate::error::AppError; | ||
| 53 | 53 | // only about how many writes a process has in flight. |
| 54 | 54 | static CLAIM_LOCK: Mutex<()> = Mutex::const_new(()); |
| 55 | 55 | |
| 56 | +/// [`CLAIM_LOCK`], for a counter write that rides someone else's transaction | |
| 57 | +/// instead of [`write`]'s — [`crate::domain::field_update::FieldUpdate`]'s term | |
| 58 | +/// move claims and releases inside the very `UPDATE`'s transaction, and still | |
| 59 | +/// owes the process one counter write at a time. | |
| 60 | +pub(crate) async fn counter_lock() -> tokio::sync::MutexGuard<'static, ()> { | |
| 61 | + CLAIM_LOCK.lock().await | |
| 62 | +} | |
| 63 | + | |
| 56 | 64 | /// "No cap" as a number, so the guard stays one comparison instead of a |
| 57 | 65 | /// nullable branch: `NONE`/`NULL` bind ambiguity is a worse trade than a |
| 58 | 66 | /// sentinel no roster will ever reach. |
src/domain/class_group.rsmodified+136 -67
| @@ -21,7 +21,7 @@ use crate::domain::cap; | ||
| 21 | 21 | use crate::domain::field_update::FieldUpdate; |
| 22 | 22 | use crate::domain::monotonic_id::next_ulid; |
| 23 | 23 | use crate::domain::page::PagedList; |
| 24 | -use crate::domain::term::TermId; | |
| 24 | +use crate::domain::term::{self, TermId}; | |
| 25 | 25 | use crate::domain::user::UserId; |
| 26 | 26 | use crate::error::{AppError, ValidationError}; |
| 27 | 27 | use crate::validate::{validate_optional, validate_required}; |
| @@ -122,10 +122,12 @@ impl ClassGroup { | ||
| 122 | 122 | &self.creator == user |
| 123 | 123 | } |
| 124 | 124 | |
| 125 | - /// Create the class, claiming a reference on the term it links (if any) | |
| 126 | - /// *before* the row is written: the claim is a conditional write on the term | |
| 127 | - /// row, so it fails when the term is already gone and it makes the term | |
| 128 | - /// undeletable the instant this link exists. | |
| 125 | + /// Create the class, claiming a reference on the term it links (if any) in | |
| 126 | + /// the *same transaction* as the row, exactly as | |
| 127 | + /// [`crate::domain::course::Course::create`] does: the claim is a | |
| 128 | + /// conditional write on the term row, so it fails when the term is already | |
| 129 | + /// gone, it makes the term undeletable the instant this link exists, and no | |
| 130 | + /// crash can leave either half without the other. | |
| 129 | 131 | pub async fn create( |
| 130 | 132 | creator: &UserId, |
| 131 | 133 | name: ClassName, |
| @@ -133,10 +135,6 @@ impl ClassGroup { | ||
| 133 | 135 | term: Option<TermId>, |
| 134 | 136 | db: &Database, |
| 135 | 137 | ) -> Result<ClassGroup, AppError> { |
| 136 | - if let Some(term) = &term { | |
| 137 | - claim_term(term, db).await?; | |
| 138 | - } | |
| 139 | - let claimed = term.clone(); | |
| 140 | 138 | let class = ClassGroup { |
| 141 | 139 | id: ClassGroupId::generate(), |
| 142 | 140 | creator: creator.clone(), |
| @@ -144,20 +142,27 @@ impl ClassGroup { | ||
| 144 | 142 | grade, |
| 145 | 143 | term, |
| 146 | 144 | }; |
| 147 | - let created: Result<Option<ClassGroup>, _> = | |
| 148 | - db.create(class.id.record()).content(class).await; | |
| 149 | - match created { | |
| 150 | - Ok(Some(created)) => Ok(created), | |
| 151 | - other => { | |
| 152 | - // The link never landed, so the reference has to go back. | |
| 153 | - if let Some(term) = &claimed { | |
| 154 | - cap::release(&term.record(), TERM_CLASS_COUNT_FIELD, db).await?; | |
| 155 | - } | |
| 156 | - match other { | |
| 157 | - Err(err) => Err(err.into()), | |
| 158 | - _ => Err(AppError::Internal("failed to create class".into())), | |
| 159 | - } | |
| 160 | - } | |
| 145 | + let id = class.id.record(); | |
| 146 | + let Some(term) = class.term.clone() else { | |
| 147 | + let created: Option<ClassGroup> = db.create(id).content(class).await?; | |
| 148 | + return created.ok_or_else(|| AppError::Internal("failed to create class".into())); | |
| 149 | + }; | |
| 150 | + match cap::claim_and_create( | |
| 151 | + &term.record(), | |
| 152 | + TERM_CLASS_COUNT_FIELD, | |
| 153 | + cap::UNLIMITED, | |
| 154 | + &id, | |
| 155 | + &class, | |
| 156 | + db, | |
| 157 | + ) | |
| 158 | + .await? | |
| 159 | + { | |
| 160 | + cap::Claimed::Made(created) => Ok(created), | |
| 161 | + // Uncapped, so "full" can only mean the conditional write matched no | |
| 162 | + // term row at all — the claim doubles as the existence check. | |
| 163 | + cap::Claimed::Full => Err(term::gone_error()), | |
| 164 | + // Unreachable: the id is a ULID this call just generated. | |
| 165 | + cap::Claimed::Duplicate => Err(AppError::Internal("failed to create class".into())), | |
| 161 | 166 | } |
| 162 | 167 | } |
| 163 | 168 | |
| @@ -182,10 +187,10 @@ impl ClassGroup { | ||
| 182 | 187 | /// they take the outer/inner `Option<Option<_>>`: `None` = omitted (keep), |
| 183 | 188 | /// `Some(None)` = clear. |
| 184 | 189 | /// |
| 185 | - /// A term move is claim-then-write-then-release, in that order, exactly as | |
| 186 | - /// in [`crate::domain::course::Course::update`]: the new term is made | |
| 187 | - /// undeletable before the link points at it, and the old one is only let go | |
| 188 | - /// once the link has actually moved off it. | |
| 190 | + /// A term move claims the new term and releases the old one inside the very | |
| 191 | + /// transaction that moves the link, exactly as in | |
| 192 | + /// [`crate::domain::course::Course::update`]: both counters and the link | |
| 193 | + /// commit together, so no crash can strand a count on a term nothing links. | |
| 189 | 194 | pub async fn update( |
| 190 | 195 | self, |
| 191 | 196 | name: Option<ClassName>, |
| @@ -193,37 +198,14 @@ impl ClassGroup { | ||
| 193 | 198 | term: Option<Option<TermId>>, |
| 194 | 199 | db: &Database, |
| 195 | 200 | ) -> Result<ClassGroup, AppError> { |
| 196 | - let claimed = match &term { | |
| 197 | - Some(Some(new)) if Some(new) != self.term.as_ref() => { | |
| 198 | - claim_term(new, db).await?; | |
| 199 | - Some(new.clone()) | |
| 200 | - } | |
| 201 | - _ => None, | |
| 202 | - }; | |
| 203 | - let updated = FieldUpdate::new(self.id.record()) | |
| 201 | + let (claim, release) = term::ref_move(self.term.as_ref(), &term); | |
| 202 | + FieldUpdate::new(self.id.record()) | |
| 204 | 203 | .set("name", name) |
| 205 | 204 | .set("grade", grade) |
| 206 | 205 | .set("term", term.map(|term| term.map(|term| term.record()))) |
| 206 | + .refcount(TERM_CLASS_COUNT_FIELD, claim, release, term::gone_error()) | |
| 207 | 207 | .run::<ClassGroup>(db) |
| 208 | - .await; | |
| 209 | - match updated { | |
| 210 | - Ok(updated) => { | |
| 211 | - // The stored row is the authority on where the link ended up — | |
| 212 | - // a PATCH that carried no `term_id` leaves it untouched. | |
| 213 | - if let Some(old) = &self.term | |
| 214 | - && updated.term.as_ref() != Some(old) | |
| 215 | - { | |
| 216 | - cap::release(&old.record(), TERM_CLASS_COUNT_FIELD, db).await?; | |
| 217 | - } | |
| 218 | - Ok(updated) | |
| 219 | - } | |
| 220 | - Err(err) => { | |
| 221 | - if let Some(new) = &claimed { | |
| 222 | - cap::release(&new.record(), TERM_CLASS_COUNT_FIELD, db).await?; | |
| 223 | - } | |
| 224 | - Err(err) | |
| 225 | - } | |
| 226 | - } | |
| 208 | + .await | |
| 227 | 209 | } |
| 228 | 210 | |
| 229 | 211 | /// Delete the class and give its term reference back. Nothing cascades: a |
| @@ -280,19 +262,6 @@ impl ClassGroup { | ||
| 280 | 262 | } |
| 281 | 263 | } |
| 282 | 264 | |
| 283 | -/// Take a reference on `term` for a class about to link it. The conditional | |
| 284 | -/// write doubles as the existence check — the class half of | |
| 285 | -/// [`crate::domain::course`]'s `claim_term`, against the class column. | |
| 286 | -async fn claim_term(term: &TermId, db: &Database) -> Result<(), AppError> { | |
| 287 | - if cap::claim(&term.record(), TERM_CLASS_COUNT_FIELD, cap::UNLIMITED, db).await? { | |
| 288 | - return Ok(()); | |
| 289 | - } | |
| 290 | - Err(AppError::Validation(ValidationError::Invalid { | |
| 291 | - field: "term_id", | |
| 292 | - reason: "term does not exist", | |
| 293 | - })) | |
| 294 | -} | |
| 295 | - | |
| 296 | 265 | #[cfg(test)] |
| 297 | 266 | mod tests { |
| 298 | 267 | use super::*; |
| @@ -329,6 +298,25 @@ mod tests { | ||
| 329 | 298 | .unwrap() |
| 330 | 299 | } |
| 331 | 300 | |
| 301 | + /// The stored `class_count` on one term, absent counting as zero. | |
| 302 | + async fn count_on(term: &TermId, db: &Database) -> i64 { | |
| 303 | + let mut result = db | |
| 304 | + .query(format!( | |
| 305 | + "SELECT VALUE ({TERM_CLASS_COUNT_FIELD} ?? 0) FROM $term" | |
| 306 | + )) | |
| 307 | + .bind(("term", term.record())) | |
| 308 | + .await | |
| 309 | + .unwrap() | |
| 310 | + .check() | |
| 311 | + .unwrap(); | |
| 312 | + result | |
| 313 | + .take::<Vec<i64>>(0) | |
| 314 | + .unwrap() | |
| 315 | + .first() | |
| 316 | + .copied() | |
| 317 | + .unwrap_or(0) | |
| 318 | + } | |
| 319 | + | |
| 332 | 320 | /// How many rows `sql` selects ids for. |
| 333 | 321 | async fn rows(sql: &str, db: &Database) -> usize { |
| 334 | 322 | let mut result = db.query(sql).await.unwrap().check().unwrap(); |
| @@ -438,6 +426,87 @@ mod tests { | ||
| 438 | 426 | } |
| 439 | 427 | } |
| 440 | 428 | |
| 429 | + /// The class half of the invariant on the create path: a refused create | |
| 430 | + /// leaves neither the row nor a count stranded on a term (which the term's | |
| 431 | + /// delete guard reads, so a stray one would make it undeletable forever). | |
| 432 | + #[tokio::test] | |
| 433 | + async fn a_refused_create_writes_neither_row_nor_count() { | |
| 434 | + let db = crate::database::init_mem().await.unwrap(); | |
| 435 | + let term = a_term(&db).await; | |
| 436 | + let id = term.get_id().clone(); | |
| 437 | + assert!(term.delete(&db).await.unwrap()); | |
| 438 | + | |
| 439 | + let error = ClassGroup::create( | |
| 440 | + &UserId::from_key("manager"), | |
| 441 | + ClassName::try_new("9-A").unwrap(), | |
| 442 | + None, | |
| 443 | + Some(id), | |
| 444 | + &db, | |
| 445 | + ) | |
| 446 | + .await | |
| 447 | + .expect_err("a term that is gone must not be linkable"); | |
| 448 | + assert!(error.to_string().contains("term does not exist")); | |
| 449 | + assert_eq!( | |
| 450 | + rows("SELECT VALUE id FROM class_group", &db).await, | |
| 451 | + 0, | |
| 452 | + "a refused create may write no row" | |
| 453 | + ); | |
| 454 | + assert_eq!( | |
| 455 | + rows("SELECT VALUE id FROM term", &db).await, | |
| 456 | + 0, | |
| 457 | + "…and least of all a count on a term it just brought back" | |
| 458 | + ); | |
| 459 | + } | |
| 460 | + | |
| 461 | + /// The class mirror of | |
| 462 | + /// [`crate::domain::course::Course`]'s move tests: a term move carries both | |
| 463 | + /// counters with the link, and a move to a term that is gone rolls the | |
| 464 | + /// release back with the abort (the transaction releases before it claims, | |
| 465 | + /// so the old count would be 0 if the abort did not undo it). | |
| 466 | + #[tokio::test] | |
| 467 | + async fn a_class_term_move_moves_both_counts_or_neither() { | |
| 468 | + let db = crate::database::init_mem().await.unwrap(); | |
| 469 | + let at = crate::domain::timestamp::Timestamp::from_millis; | |
| 470 | + let from = a_term(&db).await; | |
| 471 | + let to = Term::create(TermName::try_new("2027").unwrap(), at(100), at(200), &db) | |
| 472 | + .await | |
| 473 | + .unwrap(); | |
| 474 | + let dead = Term::create(TermName::try_new("2028").unwrap(), at(100), at(200), &db) | |
| 475 | + .await | |
| 476 | + .unwrap(); | |
| 477 | + let dead_id = dead.get_id().clone(); | |
| 478 | + assert!(dead.delete(&db).await.unwrap()); | |
| 479 | + let class = class_on(Some(from.get_id().clone()), &db).await; | |
| 480 | + | |
| 481 | + let error = class | |
| 482 | + .clone() | |
| 483 | + .update( | |
| 484 | + Some(ClassName::try_new("9-B").unwrap()), | |
| 485 | + None, | |
| 486 | + Some(Some(dead_id)), | |
| 487 | + &db, | |
| 488 | + ) | |
| 489 | + .await | |
| 490 | + .expect_err("a term that is gone must not be linkable"); | |
| 491 | + assert!(error.to_string().contains("term does not exist")); | |
| 492 | + let stored = ClassGroup::read(class.get_id(), &db).await.unwrap().unwrap(); | |
| 493 | + assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put"); | |
| 494 | + assert_eq!(stored.get_name().as_str(), "9-A", "…and so does the row"); | |
| 495 | + assert_eq!( | |
| 496 | + count_on(from.get_id(), &db).await, | |
| 497 | + 1, | |
| 498 | + "the release must roll back with the abort" | |
| 499 | + ); | |
| 500 | + | |
| 501 | + let moved = class | |
| 502 | + .update(None, None, Some(Some(to.get_id().clone())), &db) | |
| 503 | + .await | |
| 504 | + .unwrap(); | |
| 505 | + assert_eq!(moved.get_term(), Some(to.get_id())); | |
| 506 | + assert_eq!(count_on(from.get_id(), &db).await, 0, "the old term is free"); | |
| 507 | + assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); | |
| 508 | + } | |
| 509 | + | |
| 441 | 510 | /// [`crate::domain::course::Course::delete`]'s class sweep: deleting a course |
| 442 | 511 | /// takes its `class_course` attachments with it and gives each class its |
| 443 | 512 | /// count back, or the classes would be undeletable forever over rows that |
src/domain/course.rsmodified+168 -71
| @@ -9,7 +9,7 @@ use crate::database::{Database, transaction_with_retry}; | ||
| 9 | 9 | use crate::domain::cap; |
| 10 | 10 | use crate::domain::field_update::FieldUpdate; |
| 11 | 11 | use crate::domain::page::PagedList; |
| 12 | -use crate::domain::term::TermId; | |
| 12 | +use crate::domain::term::{self, TermId}; | |
| 13 | 13 | use crate::domain::user::UserId; |
| 14 | 14 | use crate::error::{AppError, ValidationError}; |
| 15 | 15 | use crate::validate::{validate_course_kind, validate_optional, validate_required}; |
| @@ -161,11 +161,12 @@ impl Course { | ||
| 161 | 161 | self.teachers.contains(user) |
| 162 | 162 | } |
| 163 | 163 | |
| 164 | - /// Create the course, claiming a reference on the term it links (if any) | |
| 165 | - /// *before* the row is written: the claim is a conditional write on the | |
| 166 | - /// term row, so it fails when the term is already gone and it makes the | |
| 167 | - /// term undeletable the instant this link exists, which the count-then-write | |
| 168 | - /// mutex it replaced could not do. | |
| 164 | + /// Create the course, claiming a reference on the term it links (if any) in | |
| 165 | + /// the *same transaction* as the row: the claim is a conditional write on | |
| 166 | + /// the term row, so it fails when the term is already gone and it makes the | |
| 167 | + /// term undeletable the instant this link exists — and a crash can never | |
| 168 | + /// leave one without the other, which a claim sent as its own query could | |
| 169 | + /// (the count would strand and the term be undeletable forever). | |
| 169 | 170 | pub async fn create( |
| 170 | 171 | creator: &UserId, |
| 171 | 172 | title: CourseTitle, |
| @@ -175,10 +176,6 @@ impl Course { | ||
| 175 | 176 | capacity: Option<i64>, |
| 176 | 177 | db: &Database, |
| 177 | 178 | ) -> Result<Course, AppError> { |
| 178 | - if let Some(term) = &term { | |
| 179 | - claim_term(term, db).await?; | |
| 180 | - } | |
| 181 | - let claimed = term.clone(); | |
| 182 | 179 | let course = Course { |
| 183 | 180 | id: CourseId::generate(), |
| 184 | 181 | creator: creator.clone(), |
| @@ -189,20 +186,27 @@ impl Course { | ||
| 189 | 186 | description, |
| 190 | 187 | kind, |
| 191 | 188 | }; |
| 192 | - let created: Result<Option<Course>, _> = | |
| 193 | - db.create(course.id.record()).content(course).await; | |
| 194 | - match created { | |
| 195 | - Ok(Some(created)) => Ok(created), | |
| 196 | - other => { | |
| 197 | - // The link never landed, so the reference has to go back. | |
| 198 | - if let Some(term) = &claimed { | |
| 199 | - cap::release(&term.record(), COURSE_COUNT_FIELD, db).await?; | |
| 200 | - } | |
| 201 | - match other { | |
| 202 | - Err(err) => Err(err.into()), | |
| 203 | - _ => Err(AppError::Internal("failed to create course".into())), | |
| 204 | - } | |
| 205 | - } | |
| 189 | + let id = course.id.record(); | |
| 190 | + let Some(term) = course.term.clone() else { | |
| 191 | + let created: Option<Course> = db.create(id).content(course).await?; | |
| 192 | + return created.ok_or_else(|| AppError::Internal("failed to create course".into())); | |
| 193 | + }; | |
| 194 | + match cap::claim_and_create( | |
| 195 | + &term.record(), | |
| 196 | + COURSE_COUNT_FIELD, | |
| 197 | + cap::UNLIMITED, | |
| 198 | + &id, | |
| 199 | + &course, | |
| 200 | + db, | |
| 201 | + ) | |
| 202 | + .await? | |
| 203 | + { | |
| 204 | + cap::Claimed::Made(created) => Ok(created), | |
| 205 | + // Uncapped, so "full" can only mean the conditional write matched no | |
| 206 | + // term row at all — the existence check the pre-flight lookup makes. | |
| 207 | + cap::Claimed::Full => Err(term::gone_error()), | |
| 208 | + // Unreachable: the id is a ULID this call just generated. | |
| 209 | + cap::Claimed::Duplicate => Err(AppError::Internal("failed to create course".into())), | |
| 206 | 210 | } |
| 207 | 211 | } |
| 208 | 212 | |
| @@ -280,43 +284,21 @@ impl Course { | ||
| 280 | 284 | capacity: Option<Option<i64>>, |
| 281 | 285 | db: &Database, |
| 282 | 286 | ) -> Result<Course, AppError> { |
| 283 | - // A term move is claim-then-write-then-release, in that order: the new | |
| 284 | - // term is made undeletable before the link points at it, and the old | |
| 285 | - // one is only let go once the link has actually moved off it. Doing it | |
| 286 | - // the other way round would open exactly the window this replaced. | |
| 287 | - let claimed = match &term { | |
| 288 | - Some(Some(new)) if Some(new) != self.term.as_ref() => { | |
| 289 | - claim_term(new, db).await?; | |
| 290 | - Some(new.clone()) | |
| 291 | - } | |
| 292 | - _ => None, | |
| 293 | - }; | |
| 294 | - let updated = FieldUpdate::new(self.id.record()) | |
| 287 | + // A term move claims the new term and releases the old one inside the | |
| 288 | + // very transaction that moves the link, so no crash can leave a count | |
| 289 | + // without its link (the term would be undeletable forever) or a link | |
| 290 | + // without its count. A PATCH that carried no `term_id`, or re-stated the | |
| 291 | + // link it already had, moves neither counter. | |
| 292 | + let (claim, release) = term::ref_move(self.term.as_ref(), &term); | |
| 293 | + FieldUpdate::new(self.id.record()) | |
| 295 | 294 | .set("title", title) |
| 296 | 295 | .set("description", description) |
| 297 | 296 | .set("kind", kind) |
| 298 | 297 | .set("term", term.map(|term| term.map(|term| term.record()))) |
| 299 | 298 | .set("capacity", capacity) |
| 299 | + .refcount(COURSE_COUNT_FIELD, claim, release, term::gone_error()) | |
| 300 | 300 | .run::<Course>(db) |
| 301 | - .await; | |
| 302 | - match updated { | |
| 303 | - Ok(updated) => { | |
| 304 | - // The stored row is the authority on where the link ended up — | |
| 305 | - // a PATCH that carried no `term_id` leaves it untouched. | |
| 306 | - if let Some(old) = &self.term | |
| 307 | - && updated.term.as_ref() != Some(old) | |
| 308 | - { | |
| 309 | - cap::release(&old.record(), COURSE_COUNT_FIELD, db).await?; | |
| 310 | - } | |
| 311 | - Ok(updated) | |
| 312 | - } | |
| 313 | - Err(err) => { | |
| 314 | - if let Some(new) = &claimed { | |
| 315 | - cap::release(&new.record(), COURSE_COUNT_FIELD, db).await?; | |
| 316 | - } | |
| 317 | - Err(err) | |
| 318 | - } | |
| 319 | - } | |
| 301 | + .await | |
| 320 | 302 | } |
| 321 | 303 | |
| 322 | 304 | /// Assign `teacher` to run this course, or return the course untouched if |
| @@ -472,23 +454,10 @@ impl Course { | ||
| 472 | 454 | } |
| 473 | 455 | } |
| 474 | 456 | |
| 475 | -/// Take a reference on `term` for a course about to link it. The conditional | |
| 476 | -/// write doubles as the existence check: a term that a delete already removed | |
| 477 | -/// matches nothing, and the caller answers exactly what the pre-flight lookup | |
| 478 | -/// in `web::terms::resolve_term` would have. | |
| 479 | -async fn claim_term(term: &TermId, db: &Database) -> Result<(), AppError> { | |
| 480 | - if cap::claim(&term.record(), COURSE_COUNT_FIELD, cap::UNLIMITED, db).await? { | |
| 481 | - return Ok(()); | |
| 482 | - } | |
| 483 | - Err(AppError::Validation(ValidationError::Invalid { | |
| 484 | - field: "term_id", | |
| 485 | - reason: "term does not exist", | |
| 486 | - })) | |
| 487 | -} | |
| 488 | - | |
| 489 | 457 | #[cfg(test)] |
| 490 | 458 | mod tests { |
| 491 | 459 | use super::*; |
| 460 | + use crate::domain::term::{Term, TermName}; | |
| 492 | 461 | |
| 493 | 462 | async fn course_on(term: Option<TermId>, db: &Database) -> Course { |
| 494 | 463 | Course::create( |
| @@ -557,8 +526,6 @@ mod tests { | ||
| 557 | 526 | /// back. Dropping the release in `delete` leaves the term deletable never. |
| 558 | 527 | #[tokio::test] |
| 559 | 528 | async fn a_term_is_deletable_only_once_no_course_links_it() { |
| 560 | - use crate::domain::term::{Term, TermName}; | |
| 561 | - | |
| 562 | 529 | let db = crate::database::init_mem().await.unwrap(); |
| 563 | 530 | let at = crate::domain::timestamp::Timestamp::from_millis; |
| 564 | 531 | let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db) |
| @@ -613,6 +580,136 @@ mod tests { | ||
| 613 | 580 | assert!(error.to_string().contains("term does not exist")); |
| 614 | 581 | } |
| 615 | 582 | |
| 583 | + /// The stored `course_count` on one term, absent counting as zero. | |
| 584 | + async fn count_on(term: &TermId, db: &Database) -> i64 { | |
| 585 | + let mut result = db | |
| 586 | + .query(format!("SELECT VALUE ({COURSE_COUNT_FIELD} ?? 0) FROM $term")) | |
| 587 | + .bind(("term", term.record())) | |
| 588 | + .await | |
| 589 | + .unwrap() | |
| 590 | + .check() | |
| 591 | + .unwrap(); | |
| 592 | + result | |
| 593 | + .take::<Vec<i64>>(0) | |
| 594 | + .unwrap() | |
| 595 | + .first() | |
| 596 | + .copied() | |
| 597 | + .unwrap_or(0) | |
| 598 | + } | |
| 599 | + | |
| 600 | + /// How many rows `sql` selects ids for. | |
| 601 | + async fn rows(sql: &str, db: &Database) -> usize { | |
| 602 | + let mut result = db.query(sql).await.unwrap().check().unwrap(); | |
| 603 | + result.take::<Vec<RecordId>>(0).unwrap().len() | |
| 604 | + } | |
| 605 | + | |
| 606 | + async fn a_term(name: &str, db: &Database) -> Term { | |
| 607 | + let at = crate::domain::timestamp::Timestamp::from_millis; | |
| 608 | + Term::create(TermName::try_new(name).unwrap(), at(100), at(200), db) | |
| 609 | + .await | |
| 610 | + .unwrap() | |
| 611 | + } | |
| 612 | + | |
| 613 | + /// The invariant, on the create path: a claim and the row it accounts for | |
| 614 | + /// commit together or not at all. A refused create must therefore leave | |
| 615 | + /// *neither* — no course row, and no count stranded on a term (which is | |
| 616 | + /// worse than it sounds: the term's delete guard reads that count, so a | |
| 617 | + /// stray one makes the term undeletable forever). | |
| 618 | + #[tokio::test] | |
| 619 | + async fn a_refused_create_writes_neither_row_nor_count() { | |
| 620 | + let db = crate::database::init_mem().await.unwrap(); | |
| 621 | + let term = a_term("2026", &db).await; | |
| 622 | + let id = term.get_id().clone(); | |
| 623 | + assert!(term.delete(&db).await.unwrap()); | |
| 624 | + | |
| 625 | + let error = Course::create( | |
| 626 | + &UserId::from_key("teacher"), | |
| 627 | + CourseTitle::try_new("algebra").unwrap(), | |
| 628 | + CourseDescription::try_new("").unwrap(), | |
| 629 | + CourseKind::course(), | |
| 630 | + Some(id), | |
| 631 | + None, | |
| 632 | + &db, | |
| 633 | + ) | |
| 634 | + .await | |
| 635 | + .expect_err("a term that is gone must not be linkable"); | |
| 636 | + assert!(error.to_string().contains("term does not exist")); | |
| 637 | + assert_eq!( | |
| 638 | + rows("SELECT VALUE id FROM course", &db).await, | |
| 639 | + 0, | |
| 640 | + "a refused create may write no row" | |
| 641 | + ); | |
| 642 | + assert_eq!( | |
| 643 | + rows("SELECT VALUE id FROM term", &db).await, | |
| 644 | + 0, | |
| 645 | + "…and least of all a count on a term it just brought back" | |
| 646 | + ); | |
| 647 | + } | |
| 648 | + | |
| 649 | + /// The invariant on the PATCH path, both directions: a move carries the new | |
| 650 | + /// term's claim and the old term's release with the link itself. | |
| 651 | + #[tokio::test] | |
| 652 | + async fn a_term_move_moves_the_count() { | |
| 653 | + let db = crate::database::init_mem().await.unwrap(); | |
| 654 | + let from = a_term("2026", &db).await; | |
| 655 | + let to = a_term("2027", &db).await; | |
| 656 | + let course = course_on(Some(from.get_id().clone()), &db).await; | |
| 657 | + assert_eq!(count_on(from.get_id(), &db).await, 1); | |
| 658 | + | |
| 659 | + let moved = course | |
| 660 | + .update(None, None, None, Some(Some(to.get_id().clone())), None, &db) | |
| 661 | + .await | |
| 662 | + .unwrap(); | |
| 663 | + assert_eq!(moved.get_term(), Some(to.get_id())); | |
| 664 | + assert_eq!(count_on(from.get_id(), &db).await, 0, "the old term is free"); | |
| 665 | + assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); | |
| 666 | + assert!(from.clone().delete(&db).await.unwrap()); | |
| 667 | + assert!(!to.clone().delete(&db).await.unwrap()); | |
| 668 | + } | |
| 669 | + | |
| 670 | + /// The rollback proof. The transaction releases the old term *before* it | |
| 671 | + /// claims the new one, so a move to a term that is gone has already | |
| 672 | + /// decremented when the claim throws — the old count still being 1 is the | |
| 673 | + /// abort undoing a write that really happened, not a branch that never ran. | |
| 674 | + /// The title moves in the same PATCH, and must not stick either. | |
| 675 | + #[tokio::test] | |
| 676 | + async fn a_term_move_to_a_dead_term_leaves_everything_untouched() { | |
| 677 | + let db = crate::database::init_mem().await.unwrap(); | |
| 678 | + let from = a_term("2026", &db).await; | |
| 679 | + let dead = a_term("2027", &db).await; | |
| 680 | + let dead_id = dead.get_id().clone(); | |
| 681 | + assert!(dead.delete(&db).await.unwrap()); | |
| 682 | + let course = course_on(Some(from.get_id().clone()), &db).await; | |
| 683 | + | |
| 684 | + let error = course | |
| 685 | + .clone() | |
| 686 | + .update( | |
| 687 | + Some(CourseTitle::try_new("moved").unwrap()), | |
| 688 | + None, | |
| 689 | + None, | |
| 690 | + Some(Some(dead_id)), | |
| 691 | + None, | |
| 692 | + &db, | |
| 693 | + ) | |
| 694 | + .await | |
| 695 | + .expect_err("a term that is gone must not be linkable"); | |
| 696 | + assert!(error.to_string().contains("term does not exist")); | |
| 697 | + | |
| 698 | + let stored = Course::read(course.get_id(), &db).await.unwrap().unwrap(); | |
| 699 | + assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put"); | |
| 700 | + assert_eq!(stored.get_title().as_str(), "algebra", "…and so does the row"); | |
| 701 | + assert_eq!( | |
| 702 | + count_on(from.get_id(), &db).await, | |
| 703 | + 1, | |
| 704 | + "the release must roll back with the abort" | |
| 705 | + ); | |
| 706 | + assert_eq!( | |
| 707 | + rows("SELECT VALUE id FROM term", &db).await, | |
| 708 | + 1, | |
| 709 | + "the dead term must not be resurrected by the claim" | |
| 710 | + ); | |
| 711 | + } | |
| 712 | + | |
| 616 | 713 | #[tokio::test] |
| 617 | 714 | async fn title_is_required() { |
| 618 | 715 | assert!(CourseTitle::try_new("algebra").is_ok()); |
src/domain/field_update.rsmodified+122 -3
| @@ -24,9 +24,16 @@ | ||
| 24 | 24 | |
| 25 | 25 | use surrealdb::types::{RecordId, SurrealValue, Value}; |
| 26 | 26 | |
| 27 | -use crate::database::{Database, write_with_retry}; | |
| 27 | +use crate::database::{Database, transaction_with_retry, write_with_retry}; | |
| 28 | +use crate::domain::cap; | |
| 28 | 29 | use crate::error::AppError; |
| 29 | 30 | |
| 31 | +/// The `THROW` markers [`FieldUpdate::refcount`]'s transaction aborts with: the | |
| 32 | +/// row the reference was to be claimed on is gone, and the row being patched is | |
| 33 | +/// gone (or its guard bit). | |
| 34 | +const CLAIM_MARK: &str = "ref_claim_gone"; | |
| 35 | +const ROW_MARK: &str = "ref_row_gone"; | |
| 36 | + | |
| 30 | 37 | pub struct FieldUpdate { |
| 31 | 38 | id: RecordId, |
| 32 | 39 | /// `field = $field` fragments, in the order they were set. |
| @@ -36,6 +43,8 @@ pub struct FieldUpdate { | ||
| 36 | 43 | ordered: Option<(&'static str, &'static str, AppError)>, |
| 37 | 44 | /// `(condition, refusal)` for [`FieldUpdate::guard`]. |
| 38 | 45 | guard: Option<(&'static str, AppError)>, |
| 46 | + /// `(counter field, claim, release, refusal)` for [`FieldUpdate::refcount`]. | |
| 47 | + refcount: Option<(&'static str, Option<RecordId>, Option<RecordId>, AppError)>, | |
| 39 | 48 | } |
| 40 | 49 | |
| 41 | 50 | impl FieldUpdate { |
| @@ -46,11 +55,13 @@ impl FieldUpdate { | ||
| 46 | 55 | bindings: Vec::new(), |
| 47 | 56 | ordered: None, |
| 48 | 57 | guard: None, |
| 58 | + refcount: None, | |
| 49 | 59 | } |
| 50 | 60 | } |
| 51 | 61 | |
| 52 | 62 | /// Write `field` only when the request carried it. The bind variable is |
| 53 | - /// named after the field, so `id` is the one name a caller must not use. | |
| 63 | + /// named after the field, so `id` — and `ref_claim`/`ref_release`, which | |
| 64 | + /// [`FieldUpdate::refcount`] binds — are the names a caller must not use. | |
| 54 | 65 | #[must_use] |
| 55 | 66 | pub fn set<T: SurrealValue>(mut self, field: &'static str, value: Option<T>) -> Self { |
| 56 | 67 | if let Some(value) = value { |
| @@ -97,9 +108,38 @@ impl FieldUpdate { | ||
| 97 | 108 | self |
| 98 | 109 | } |
| 99 | 110 | |
| 111 | + /// Move a reference counter *with* this write: `claim` takes one on the row | |
| 112 | + /// the link moves to, `release` gives one back on the row it moves off, and | |
| 113 | + /// both ride the same `BEGIN…COMMIT` as the `UPDATE` that moves the link. | |
| 114 | + /// | |
| 115 | + /// That is the whole point. A claim sent as its own query leaves a window | |
| 116 | + /// where a crash strands a count on a row nothing links any more — and a | |
| 117 | + /// count is what a delete guard reads, so the stranded one makes its parent | |
| 118 | + /// undeletable forever. `refused` is the answer when the claimed row is gone | |
| 119 | + /// (the conditional write doubles as the existence check, as in | |
| 120 | + /// [`crate::domain::cap`]); the transaction then aborts, so the release and | |
| 121 | + /// the row write never happened either. | |
| 122 | + /// | |
| 123 | + /// Only ever called alongside a `.set()` of the very column that carries the | |
| 124 | + /// link, so the empty-request short-circuit below cannot swallow a move. | |
| 125 | + #[must_use] | |
| 126 | + pub fn refcount( | |
| 127 | + mut self, | |
| 128 | + field: &'static str, | |
| 129 | + claim: Option<RecordId>, | |
| 130 | + release: Option<RecordId>, | |
| 131 | + refused: AppError, | |
| 132 | + ) -> Self { | |
| 133 | + if claim.is_some() || release.is_some() { | |
| 134 | + self.refcount = Some((field, claim, release, refused)); | |
| 135 | + } | |
| 136 | + self | |
| 137 | + } | |
| 138 | + | |
| 100 | 139 | /// Run the update and return the stored row. An empty request writes |
| 101 | 140 | /// nothing at all and reads the row back unchanged. |
| 102 | 141 | pub async fn run<T: SurrealValue>(mut self, db: &Database) -> Result<T, AppError> { |
| 142 | + let moved = self.refcount.take(); | |
| 103 | 143 | if self.assignments.is_empty() { |
| 104 | 144 | let row: Option<T> = db.select(self.id).await?; |
| 105 | 145 | return row.ok_or(AppError::NotFound); |
| @@ -145,7 +185,13 @@ impl FieldUpdate { | ||
| 145 | 185 | // Retried on a write conflict: a guarded PATCH contends on the very row |
| 146 | 186 | // its guard reads, and the loser wrote nothing, so re-sending it is the |
| 147 | 187 | // recovery — see [`write_with_retry`]. |
| 148 | - let rows: Vec<T> = write_with_retry(db, &sql, &self.bindings).await?; | |
| 188 | + let rows: Vec<T> = match moved { | |
| 189 | + Some((field, claim, release, ref_refused)) => { | |
| 190 | + run_with_refcount(db, &sql, self.bindings, field, claim, release, ref_refused) | |
| 191 | + .await? | |
| 192 | + } | |
| 193 | + None => write_with_retry(db, &sql, &self.bindings).await?, | |
| 194 | + }; | |
| 149 | 195 | // No row back means the guard bit (or, in the window after the handler's |
| 150 | 196 | // read, the row was deleted — the guard cannot tell the two apart, and |
| 151 | 197 | // reports the refusal it was given). |
| @@ -158,3 +204,76 @@ impl FieldUpdate { | ||
| 158 | 204 | self.bindings.iter().any(|(name, _)| name == field) |
| 159 | 205 | } |
| 160 | 206 | } |
| 207 | + | |
| 208 | +/// Send `update` with its counter move, as one transaction. An empty `Vec` back | |
| 209 | +/// means the row write matched nothing, exactly as [`write_with_retry`] would | |
| 210 | +/// have reported it, so the caller's refusal is unchanged. | |
| 211 | +/// | |
| 212 | +/// Admissible for [`transaction_with_retry`]: every statement is an `UPDATE`, | |
| 213 | +/// an `IF`/`THROW` or a `RETURN`, and none of those can answer "already | |
| 214 | +/// exists" — a lost round writes nothing and re-sending it is the recovery. | |
| 215 | +#[allow(clippy::too_many_arguments)] | |
| 216 | +async fn run_with_refcount<T: SurrealValue>( | |
| 217 | + db: &Database, | |
| 218 | + update: &str, | |
| 219 | + mut bindings: Vec<(String, Value)>, | |
| 220 | + field: &'static str, | |
| 221 | + claim: Option<RecordId>, | |
| 222 | + release: Option<RecordId>, | |
| 223 | + refused: AppError, | |
| 224 | +) -> Result<Vec<T>, AppError> { | |
| 225 | + // Parenthesized `??` throughout: `n ?? 0 + 1` parses as `n ?? (0 + 1)`. | |
| 226 | + // Both counter writes commit with the row write or neither does, so their | |
| 227 | + // order is free — the release goes first because that is what makes the | |
| 228 | + // rollback observable: a move to a term that is gone decrements before the | |
| 229 | + // claim throws, and the old count still being there proves the abort undid | |
| 230 | + // it (`a_term_move_to_a_dead_term_leaves_everything_untouched`). | |
| 231 | + let mut statements: Vec<String> = Vec::new(); | |
| 232 | + if let Some(release) = release { | |
| 233 | + statements.push(format!( | |
| 234 | + "UPDATE $ref_release SET {field} = math::max([({field} ?? 0) - 1, 0])" | |
| 235 | + )); | |
| 236 | + bindings.push(("ref_release".into(), release.into_value())); | |
| 237 | + } | |
| 238 | + if let Some(claim) = claim { | |
| 239 | + statements.push(format!( | |
| 240 | + "LET $seat = (UPDATE $ref_claim SET {field} = ({field} ?? 0) + 1 RETURN VALUE id)" | |
| 241 | + )); | |
| 242 | + statements.push(format!("IF array::len($seat) = 0 {{ THROW '{CLAIM_MARK}' }}")); | |
| 243 | + bindings.push(("ref_claim".into(), claim.into_value())); | |
| 244 | + } | |
| 245 | + statements.push(format!("LET $row = ({update})")); | |
| 246 | + // Without this the claim would outlive a row write that matched nothing — | |
| 247 | + // the very leak the transaction exists to close. | |
| 248 | + statements.push(format!("IF array::len($row) = 0 {{ THROW '{ROW_MARK}' }}")); | |
| 249 | + statements.push("RETURN $row".into()); | |
| 250 | + let sql = format!( | |
| 251 | + "BEGIN TRANSACTION; {}; COMMIT TRANSACTION;", | |
| 252 | + statements.join("; ") | |
| 253 | + ); | |
| 254 | + // BEGIN is slot 0, so the trailing RETURN sits at `statements.len()`. | |
| 255 | + let slot = statements.len(); | |
| 256 | + | |
| 257 | + // One counter write in flight at a time, like every other counter write. | |
| 258 | + let _guard = cap::counter_lock().await; | |
| 259 | + let (mut result, mut errors) = | |
| 260 | + transaction_with_retry(db, &sql, &bindings, &[CLAIM_MARK, ROW_MARK]).await?; | |
| 261 | + if errors | |
| 262 | + .values() | |
| 263 | + .any(|error| error.to_string().contains(CLAIM_MARK)) | |
| 264 | + { | |
| 265 | + return Err(refused); | |
| 266 | + } | |
| 267 | + if errors | |
| 268 | + .values() | |
| 269 | + .any(|error| error.to_string().contains(ROW_MARK)) | |
| 270 | + { | |
| 271 | + return Ok(Vec::new()); | |
| 272 | + } | |
| 273 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | |
| 274 | + return Err(error.into()); | |
| 275 | + } | |
| 276 | + // Sound only because the error map came back empty: `take_errors` swap- | |
| 277 | + // removes errored slots, which would renumber the rest. | |
| 278 | + Ok(result.take::<Vec<T>>(slot)?) | |
| 279 | +} |
src/domain/term.rsmodified+26 -0
| @@ -41,6 +41,32 @@ impl TermId { | ||
| 41 | 41 | } |
| 42 | 42 | } |
| 43 | 43 | |
| 44 | +/// The answer every link to a term that is not there gets — the claim is a | |
| 45 | +/// conditional write on the term row, so a term a delete already removed | |
| 46 | +/// matches nothing and the caller says exactly what `web::terms::resolve_term`'s | |
| 47 | +/// pre-flight lookup would have. | |
| 48 | +pub fn gone_error() -> AppError { | |
| 49 | + AppError::Validation(ValidationError::Invalid { | |
| 50 | + field: "term_id", | |
| 51 | + reason: "term does not exist", | |
| 52 | + }) | |
| 53 | +} | |
| 54 | + | |
| 55 | +/// What a PATCH's `term` field owes the refcounts: the term to claim, and the | |
| 56 | +/// one to give back. Covers all three moves — set (none→some), move | |
| 57 | +/// (some→other) and clear (some→none) — and moves nothing for a PATCH that | |
| 58 | +/// omitted the field or re-stated the link it already had. | |
| 59 | +pub fn ref_move( | |
| 60 | + current: Option<&TermId>, | |
| 61 | + patch: &Option<Option<TermId>>, | |
| 62 | +) -> (Option<RecordId>, Option<RecordId>) { | |
| 63 | + match patch { | |
| 64 | + None => (None, None), | |
| 65 | + Some(next) if next.as_ref() == current => (None, None), | |
| 66 | + Some(next) => (next.as_ref().map(TermId::record), current.map(TermId::record)), | |
| 67 | + } | |
| 68 | +} | |
| 69 | + | |
| 44 | 70 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 45 | 71 | pub struct TermName(String); |
| 46 | 72 |