🔩 land counter claims with their rows, refuse stale movers
Browse files at this commita8435eea94df7126b74ac8a80b88ae328e709dbdParent: 324b078- fix
- 🔩 land counter claims with their rows, refuse stale movers
9 changed files +905 -149
- src/domain/appointment.rs +66 -24
- src/domain/cap.rs +289 -1
- src/domain/chatbot_thread.rs +92 -15
- src/domain/class_group.rs +18 -3
- src/domain/course.rs +100 -4
- src/domain/exam_result.rs +187 -57
- src/domain/field_update.rs +69 -21
- src/domain/note_file.rs +80 -23
- src/domain/term.rs +4 -1
src/domain/appointment.rsmodified+66 -24
| @@ -5,7 +5,8 @@ | |||
| 5 | //! Two *cross-record* invariants live here, guarded very differently: | 5 | //! Two *cross-record* invariants live here, guarded very differently: |
| 6 | //! | 6 | //! |
| 7 | //! - **One live booking per slot** — the `occupied` counter on the slot row, a | 7 | //! - **One live booking per slot** — the `occupied` counter on the slot row, a |
| 8 | -//! [`cap`](crate::domain::cap) of one. Booking [`claim`](cap::claim)s it; | 8 | +//! [`cap`](crate::domain::cap) of one. Booking claims it *with* the booking |
| 9 | +//! row ([`claim_and_create`](cap::claim_and_create)); | ||
| 9 | //! rejecting or cancelling gives it back in the *same transaction* as the | 10 | //! rejecting or cancelling gives it back in the *same transaction* as the |
| 10 | //! status flip, so the slot frees itself with nothing to sweep. Both are | 11 | //! status flip, so the slot frees itself with nothing to sweep. Both are |
| 11 | //! single-record conditional writes, so the store decides it, not a lock. | 12 | //! single-record conditional writes, so the store decides it, not a lock. |
| @@ -320,10 +321,12 @@ impl Appointment { | |||
| 320 | /// | 321 | /// |
| 321 | /// Refused (409) when the slot's window has already opened, when it is | 322 | /// Refused (409) when the slot's window has already opened, when it is |
| 322 | /// already taken, or when the requester is already committed elsewhere at | 323 | /// already taken, or when the requester is already committed elsewhere at |
| 323 | - /// that time. The slot is taken by [`cap::claim`] on the slot row — a | 324 | + /// that time. The slot is taken by [`cap::claim_and_create`], which writes |
| 324 | - /// conditional single-record write, so two racing requests cannot both find | 325 | + /// the booking in the *same transaction* as the seat — a conditional |
| 325 | - /// it free however they interleave; the requester's own overlap is the | 326 | + /// single-record write, so two racing requests cannot both find it free |
| 326 | - /// lock's part. | 327 | + /// however they interleave, and a crash between the two can no longer leave |
| 328 | + /// the slot occupied by a booking that does not exist. The requester's own | ||
| 329 | + /// overlap is the lock's part. | ||
| 327 | pub async fn book( | 330 | pub async fn book( |
| 328 | slot: &AppointmentSlotId, | 331 | slot: &AppointmentSlotId, |
| 329 | requester: &UserId, | 332 | requester: &UserId, |
| @@ -363,12 +366,6 @@ impl Appointment { | |||
| 363 | // finds no row either way, so the distinction is re-read rather than | 366 | // finds no row either way, so the distinction is re-read rather than |
| 364 | // guessed. | 367 | // guessed. |
| 365 | let seat = slot.record(); | 368 | let seat = slot.record(); |
| 366 | - if !cap::claim(&seat, SLOT_OCCUPIED_FIELD, 1, db).await? { | ||
| 367 | - if AppointmentSlot::read(slot, db).await?.is_none() { | ||
| 368 | - return Err(AppError::NotFound); | ||
| 369 | - } | ||
| 370 | - return Err(AppError::Conflict("the slot is already booked")); | ||
| 371 | - } | ||
| 372 | let appointment = Appointment { | 369 | let appointment = Appointment { |
| 373 | id: AppointmentId::generate(), | 370 | id: AppointmentId::generate(), |
| 374 | slot: slot.clone(), | 371 | slot: slot.clone(), |
| @@ -384,20 +381,26 @@ impl Appointment { | |||
| 384 | reject_reason: None, | 381 | reject_reason: None, |
| 385 | created_at: Timestamp::now(), | 382 | created_at: Timestamp::now(), |
| 386 | }; | 383 | }; |
| 387 | - let created: Result<Option<Appointment>, _> = db | 384 | + match cap::claim_and_create( |
| 388 | - .create(appointment.id.record()) | 385 | + &seat, |
| 389 | - .content(appointment) | 386 | + SLOT_OCCUPIED_FIELD, |
| 390 | - .await; | 387 | + 1, |
| 391 | - match created { | 388 | + &appointment.id.record(), |
| 392 | - Ok(Some(created)) => Ok(created), | 389 | + &appointment, |
| 393 | - // The booking never landed, so the slot it took goes back. | 390 | + db, |
| 394 | - other => { | 391 | + ) |
| 395 | - cap::release(&seat, SLOT_OCCUPIED_FIELD, db).await?; | 392 | + .await? |
| 396 | - Err(match other { | 393 | + { |
| 397 | - Err(err) => err.into(), | 394 | + cap::Claimed::Made(created) => Ok(created), |
| 398 | - _ => AppError::Internal("failed to book the appointment".into()), | 395 | + cap::Claimed::Full => { |
| 399 | - }) | 396 | + if AppointmentSlot::read(slot, db).await?.is_none() { |
| 397 | + return Err(AppError::NotFound); | ||
| 398 | + } | ||
| 399 | + Err(AppError::Conflict("the slot is already booked")) | ||
| 400 | } | 400 | } |
| 401 | + // The id is a freshly minted ULID on a table with no UNIQUE index, | ||
| 402 | + // so no rival can have aimed at it. | ||
| 403 | + cap::Claimed::Duplicate => Err(AppError::Internal("appointment id collided".into())), | ||
| 401 | } | 404 | } |
| 402 | } | 405 | } |
| 403 | 406 | ||
| @@ -1005,6 +1008,45 @@ mod tests { | |||
| 1005 | ); | 1008 | ); |
| 1006 | } | 1009 | } |
| 1007 | 1010 | ||
| 1011 | + /// The seat and the booking row now land in one transaction, so the stored | ||
| 1012 | + /// state must move together: a taken slot refuses the next requester with | ||
| 1013 | + /// the counter *and* the row list untouched — a refusal that had already | ||
| 1014 | + /// bumped the counter would strand the slot forever. | ||
| 1015 | + #[tokio::test] | ||
| 1016 | + async fn a_refused_booking_moves_nothing() { | ||
| 1017 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 1018 | + let teacher = UserId::from_key("t1"); | ||
| 1019 | + let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) | ||
| 1020 | + .await | ||
| 1021 | + .unwrap(); | ||
| 1022 | + let reason = || AppointmentReason::try_new("görüşme").unwrap(); | ||
| 1023 | + | ||
| 1024 | + Appointment::book(slot.get_id(), &UserId::from_key("s1"), reason(), &db) | ||
| 1025 | + .await | ||
| 1026 | + .unwrap(); | ||
| 1027 | + assert_eq!(occupied(slot.get_id(), &db).await, 1); | ||
| 1028 | + | ||
| 1029 | + let refused = | ||
| 1030 | + Appointment::book(slot.get_id(), &UserId::from_key("s2"), reason(), &db).await; | ||
| 1031 | + assert!( | ||
| 1032 | + matches!(refused, Err(AppError::Conflict(_))), | ||
| 1033 | + "the slot is taken" | ||
| 1034 | + ); | ||
| 1035 | + assert_eq!( | ||
| 1036 | + occupied(slot.get_id(), &db).await, | ||
| 1037 | + 1, | ||
| 1038 | + "the refusal took no seat" | ||
| 1039 | + ); | ||
| 1040 | + assert_eq!( | ||
| 1041 | + Appointment::list_for_slot(slot.get_id(), &db) | ||
| 1042 | + .await | ||
| 1043 | + .unwrap() | ||
| 1044 | + .len(), | ||
| 1045 | + 1, | ||
| 1046 | + "and wrote no row" | ||
| 1047 | + ); | ||
| 1048 | + } | ||
| 1049 | + | ||
| 1008 | /// Cancelling gives the seat back in the same transaction as the status | 1050 | /// Cancelling gives the seat back in the same transaction as the status |
| 1009 | /// flip — the counter is the only thing that says a slot is free, so a | 1051 | /// flip — the counter is the only thing that says a slot is free, so a |
| 1010 | /// cancel that moved one without the other would strand the slot forever. | 1052 | /// cancel that moved one without the other would strand the slot forever. |
src/domain/cap.rsmodified+289 -1
| @@ -120,6 +120,11 @@ async fn claim_at( | |||
| 120 | const FULL_MARK: &str = "cap_full"; | 120 | const FULL_MARK: &str = "cap_full"; |
| 121 | const HELD_MARK: &str = "cap_held"; | 121 | const HELD_MARK: &str = "cap_held"; |
| 122 | 122 | ||
| 123 | +/// [`claim_ref_and_create`]'s third answer: the *name* is retired, which is not | ||
| 124 | +/// a count being full — nothing empties it, and only putting the name back in | ||
| 125 | +/// service lets a claim through. | ||
| 126 | +const RETIRED_MARK: &str = "cap_retired"; | ||
| 127 | + | ||
| 123 | /// The two markers [`claim_two_when_and_create`] aborts with, one per counter, | 128 | /// The two markers [`claim_two_when_and_create`] aborts with, one per counter, |
| 124 | /// deliberately *not* shared: its two caps mean opposite things to the person | 129 | /// deliberately *not* shared: its two caps mean opposite things to the person |
| 125 | /// who hit one. The soft cap is a resettable working set (a whiteboard's live | 130 | /// who hit one. The soft cap is a resettable working set (a whiteboard's live |
| @@ -166,12 +171,54 @@ pub(crate) async fn claim_and_create<T: SurrealValue + Clone>( | |||
| 166 | content: &T, | 171 | content: &T, |
| 167 | db: &Database, | 172 | db: &Database, |
| 168 | ) -> Result<Claimed<T>, AppError> { | 173 | ) -> Result<Claimed<T>, AppError> { |
| 174 | + claim_at_and_create(parent, field, cap, "", id, content, db).await | ||
| 175 | +} | ||
| 176 | + | ||
| 177 | +/// [`claim_and_create`], but only while `guard` — an extra predicate on that | ||
| 178 | +/// same parent row — also holds, exactly as [`claim_when`] is to [`claim`]: one | ||
| 179 | +/// conditional write decides the cap *and* the caller's second precondition, so | ||
| 180 | +/// no read a concurrent write can outrun sits between them. | ||
| 181 | +/// | ||
| 182 | +/// The contract that costs the caller something: [`Claimed::Full`] means "full | ||
| 183 | +/// **or** the guard failed **or** the parent row is gone" — one marker for all | ||
| 184 | +/// three, because the seat `UPDATE` matching nothing cannot say which clause | ||
| 185 | +/// refused it. A caller that needs to tell them apart re-reads the parent, and | ||
| 186 | +/// only to pick the message: none of the three is retryable into a success. | ||
| 187 | +/// | ||
| 188 | +/// `guard` is always an in-crate SQL literal or built in-crate out of numbers | ||
| 189 | +/// this crate read back itself — never text from a client. | ||
| 190 | +pub(crate) async fn claim_when_and_create<T: SurrealValue + Clone>( | ||
| 191 | + parent: &RecordId, | ||
| 192 | + field: &str, | ||
| 193 | + cap: i64, | ||
| 194 | + guard: &str, | ||
| 195 | + id: &RecordId, | ||
| 196 | + content: &T, | ||
| 197 | + db: &Database, | ||
| 198 | +) -> Result<Claimed<T>, AppError> { | ||
| 199 | + claim_at_and_create(parent, field, cap, guard, id, content, db).await | ||
| 200 | +} | ||
| 201 | + | ||
| 202 | +async fn claim_at_and_create<T: SurrealValue + Clone>( | ||
| 203 | + parent: &RecordId, | ||
| 204 | + field: &str, | ||
| 205 | + cap: i64, | ||
| 206 | + extra: &str, | ||
| 207 | + id: &RecordId, | ||
| 208 | + content: &T, | ||
| 209 | + db: &Database, | ||
| 210 | +) -> Result<Claimed<T>, AppError> { | ||
| 211 | + let extra = if extra.is_empty() { | ||
| 212 | + String::new() | ||
| 213 | + } else { | ||
| 214 | + format!(" AND ({extra})") | ||
| 215 | + }; | ||
| 169 | let sql = format!( | 216 | let sql = format!( |
| 170 | "BEGIN TRANSACTION; | 217 | "BEGIN TRANSACTION; |
| 171 | LET $held = (SELECT VALUE id FROM $id); | 218 | LET $held = (SELECT VALUE id FROM $id); |
| 172 | IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; | 219 | IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; |
| 173 | LET $seat = (UPDATE $parent SET {field} = ({field} ?? 0) + 1 \ | 220 | LET $seat = (UPDATE $parent SET {field} = ({field} ?? 0) + 1 \ |
| 174 | - WHERE ({field} ?? 0) < $num RETURN VALUE id); | 221 | + WHERE ({field} ?? 0) < $num{extra} RETURN VALUE id); |
| 175 | IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }}; | 222 | IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }}; |
| 176 | CREATE $id CONTENT $row; | 223 | CREATE $id CONTENT $row; |
| 177 | COMMIT TRANSACTION;" | 224 | COMMIT TRANSACTION;" |
| @@ -408,6 +455,111 @@ pub(crate) async fn claim_ref(id: &RecordId, n: i64, db: &Database) -> Result<bo | |||
| 408 | Ok(!write(&sql, id, n, db).await?.is_empty()) | 455 | Ok(!write(&sql, id, n, db).await?.is_empty()) |
| 409 | } | 456 | } |
| 410 | 457 | ||
| 458 | +/// What [`claim_ref_and_create`] settled. | ||
| 459 | +pub(crate) enum ClaimedRef<T> { | ||
| 460 | + /// The reference and the row committed together. | ||
| 461 | + Made(T), | ||
| 462 | + /// The name is retired — nothing was written, and no retry helps until the | ||
| 463 | + /// name is put back in service. | ||
| 464 | + Retired, | ||
| 465 | + /// Another writer placed this very row first, so this caller never owed a | ||
| 466 | + /// reference: nothing was written, and the winner's row is the answer. | ||
| 467 | + Duplicate, | ||
| 468 | +} | ||
| 469 | +// | ||
| 470 | +// A separate enum rather than a `Retired` variant on [`Claimed`]: that enum is | ||
| 471 | +// matched exhaustively by a dozen callers in files this change does not touch, | ||
| 472 | +// and a cap has no retired state to answer for anyway. | ||
| 473 | + | ||
| 474 | +/// Take one reference on `counter` *and* write the row that holds it, in one | ||
| 475 | +/// transaction — [`claim_and_create`] pointed at a name instead of a cap. | ||
| 476 | +/// | ||
| 477 | +/// [`claim_ref`] followed by a separate insert cannot promise this: the claim | ||
| 478 | +/// lands, the insert then fails or the process dies, and the name is counted as | ||
| 479 | +/// used by a row that does not exist — which is a name nobody can ever retire. | ||
| 480 | +/// Here the abort takes the increment with it. | ||
| 481 | +/// | ||
| 482 | +/// The `$held` gate comes first for [`claim_and_create`]'s reason: where the | ||
| 483 | +/// child carries a deterministic id, a rival can place the very row this caller | ||
| 484 | +/// is placing, and "you already have it" is the honest answer — one that must | ||
| 485 | +/// not cost a reference. Which is also why this carries its own retry loop | ||
| 486 | +/// rather than [`crate::database::transaction_with_retry`]'s: the `CREATE` can | ||
| 487 | +/// legitimately answer "already exists", and that loop cannot tell that answer | ||
| 488 | +/// from a lost round. The `UPSERT` cannot answer it — `kind_ref`/`slot_ref` | ||
| 489 | +/// carry no `UNIQUE` index, so a write keyed by id resolves onto the row the id | ||
| 490 | +/// names. | ||
| 491 | +pub(crate) async fn claim_ref_and_create<T: SurrealValue + Clone>( | ||
| 492 | + counter: &RecordId, | ||
| 493 | + n: i64, | ||
| 494 | + id: &RecordId, | ||
| 495 | + content: &T, | ||
| 496 | + db: &Database, | ||
| 497 | +) -> Result<ClaimedRef<T>, AppError> { | ||
| 498 | + let sql = format!( | ||
| 499 | + "BEGIN TRANSACTION; | ||
| 500 | + LET $held = (SELECT VALUE id FROM $id); | ||
| 501 | + IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; | ||
| 502 | + LET $ref = (UPSERT $parent SET {REF_COUNT_FIELD} = ({REF_COUNT_FIELD} ?? 0) + $num \ | ||
| 503 | + WHERE {REF_RETIRED_FIELD} != true RETURN VALUE id); | ||
| 504 | + IF array::len($ref) = 0 {{ THROW '{RETIRED_MARK}' }}; | ||
| 505 | + CREATE $id CONTENT $row; | ||
| 506 | + COMMIT TRANSACTION;" | ||
| 507 | + ); | ||
| 508 | + let _guard = CLAIM_LOCK.lock().await; | ||
| 509 | + let mut last = None; | ||
| 510 | + for attempt in 0..CAP_WRITE_TRIES { | ||
| 511 | + backoff(attempt).await; | ||
| 512 | + let attempted = db | ||
| 513 | + .query(sql.as_str()) | ||
| 514 | + .bind(("parent", counter.clone())) | ||
| 515 | + .bind(("num", n)) | ||
| 516 | + .bind(("id", id.clone())) | ||
| 517 | + .bind(("row", content.clone())) | ||
| 518 | + .await; | ||
| 519 | + let mut result = match attempted { | ||
| 520 | + Ok(result) => result, | ||
| 521 | + Err(err) if lost_the_race(&err) => { | ||
| 522 | + last = Some(err); | ||
| 523 | + continue; | ||
| 524 | + } | ||
| 525 | + Err(err) => return Err(err.into()), | ||
| 526 | + }; | ||
| 527 | + // An aborted transaction errors *every* slot, most with a generic "not | ||
| 528 | + // executed" — only the failing slot says why. The markers are read | ||
| 529 | + // before the conflict check, because a `THROW` is a decision. | ||
| 530 | + let mut errors = result.take_errors(); | ||
| 531 | + if errors | ||
| 532 | + .values() | ||
| 533 | + .any(|error| error.to_string().contains(HELD_MARK) || error.is_already_exists()) | ||
| 534 | + { | ||
| 535 | + return Ok(ClaimedRef::Duplicate); | ||
| 536 | + } | ||
| 537 | + if errors | ||
| 538 | + .values() | ||
| 539 | + .any(|error| error.to_string().contains(RETIRED_MARK)) | ||
| 540 | + { | ||
| 541 | + return Ok(ClaimedRef::Retired); | ||
| 542 | + } | ||
| 543 | + if errors.values().any(lost_the_race) { | ||
| 544 | + last = errors.drain().map(|(_, error)| error).find(lost_the_race); | ||
| 545 | + continue; | ||
| 546 | + } | ||
| 547 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 548 | + return Err(error.into()); | ||
| 549 | + } | ||
| 550 | + // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5. | ||
| 551 | + return result | ||
| 552 | + .take::<Vec<T>>(5)? | ||
| 553 | + .into_iter() | ||
| 554 | + .next() | ||
| 555 | + .map(ClaimedRef::Made) | ||
| 556 | + .ok_or_else(|| AppError::Internal("cap claim wrote no row".into())); | ||
| 557 | + } | ||
| 558 | + Err(last | ||
| 559 | + .map(AppError::from) | ||
| 560 | + .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) | ||
| 561 | +} | ||
| 562 | + | ||
| 411 | /// Give `n` references back — the referencing rows are gone (or never landed). | 563 | /// Give `n` references back — the referencing rows are gone (or never landed). |
| 412 | /// Clamped at zero like [`release`], so a double release cannot push a counter | 564 | /// Clamped at zero like [`release`], so a double release cannot push a counter |
| 413 | /// below the rows it counts and let a used name be retired. | 565 | /// below the rows it counts and let a used name be retired. |
| @@ -625,4 +777,140 @@ mod tests { | |||
| 625 | assert_eq!(stored(&db).await, (0, 0)); | 777 | assert_eq!(stored(&db).await, (0, 0)); |
| 626 | assert_eq!(strokes(&db).await, 0); | 778 | assert_eq!(strokes(&db).await, 0); |
| 627 | } | 779 | } |
| 780 | + | ||
| 781 | + // --- claim_when_and_create ------------------------------------------ | ||
| 782 | + | ||
| 783 | + async fn claim_one(db: &Database, cap: i64, key: &str) -> Claimed<Stroke> { | ||
| 784 | + claim_when_and_create( | ||
| 785 | + &RecordId::new("board", "b"), | ||
| 786 | + BOARD_EPOCH_STROKE_COUNT_FIELD, | ||
| 787 | + cap, | ||
| 788 | + BOARD_OPEN_GUARD, | ||
| 789 | + &RecordId::new("board_stroke", key), | ||
| 790 | + &a_stroke(), | ||
| 791 | + db, | ||
| 792 | + ) | ||
| 793 | + .await | ||
| 794 | + .unwrap() | ||
| 795 | + } | ||
| 796 | + | ||
| 797 | + #[tokio::test] | ||
| 798 | + async fn a_guarded_claim_advances_its_counter_exactly_once() { | ||
| 799 | + let db = a_board(0, 0, false).await; | ||
| 800 | + assert!(matches!(claim_one(&db, 9, "s1").await, Claimed::Made(_))); | ||
| 801 | + assert_eq!(stored(&db).await, (1, 0)); | ||
| 802 | + assert_eq!(strokes(&db).await, 1); | ||
| 803 | + } | ||
| 804 | + | ||
| 805 | + /// A failed guard is refused as `Full` (the one marker covers full, guard | ||
| 806 | + /// and missing parent), and must leave the counter and the table alone. | ||
| 807 | + #[tokio::test] | ||
| 808 | + async fn a_guard_refusal_advances_neither_counter_nor_row() { | ||
| 809 | + let db = a_board(0, 0, true).await; | ||
| 810 | + assert!(matches!(claim_one(&db, 9, "s1").await, Claimed::Full)); | ||
| 811 | + assert_eq!(stored(&db).await, (0, 0)); | ||
| 812 | + assert_eq!(strokes(&db).await, 0); | ||
| 813 | + } | ||
| 814 | + | ||
| 815 | + /// The second writer at the same id owes no seat: the row is already there, | ||
| 816 | + /// so the counter must not move a second time for it. | ||
| 817 | + #[tokio::test] | ||
| 818 | + async fn a_duplicate_row_claims_no_seat() { | ||
| 819 | + let db = a_board(0, 0, false).await; | ||
| 820 | + assert!(matches!(claim_one(&db, 9, "s1").await, Claimed::Made(_))); | ||
| 821 | + assert!(matches!(claim_one(&db, 9, "s1").await, Claimed::Duplicate)); | ||
| 822 | + assert_eq!(stored(&db).await, (1, 0)); | ||
| 823 | + assert_eq!(strokes(&db).await, 1); | ||
| 824 | + } | ||
| 825 | + | ||
| 826 | + // --- claim_ref_and_create ------------------------------------------- | ||
| 827 | + | ||
| 828 | + #[derive(Debug, Clone, SurrealValue)] | ||
| 829 | + struct Menu { | ||
| 830 | + date: String, | ||
| 831 | + slot: String, | ||
| 832 | + created_by: RecordId, | ||
| 833 | + created_at: i64, | ||
| 834 | + } | ||
| 835 | + | ||
| 836 | + async fn a_slot(count: i64, retired: bool) -> Database { | ||
| 837 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 838 | + db.query( | ||
| 839 | + "CREATE user:u SET username = 'u', password_hash = 'x'; | ||
| 840 | + UPSERT slot_ref:lunch SET count = $count, retired = $retired;", | ||
| 841 | + ) | ||
| 842 | + .bind(("count", count)) | ||
| 843 | + .bind(("retired", retired)) | ||
| 844 | + .await | ||
| 845 | + .unwrap() | ||
| 846 | + .check() | ||
| 847 | + .unwrap(); | ||
| 848 | + db | ||
| 849 | + } | ||
| 850 | + | ||
| 851 | + /// The reference count, re-read out of the store — never off a return | ||
| 852 | + /// value, which the in-memory engine forges wins on (see `CLAIM_LOCK`). | ||
| 853 | + async fn refs(db: &Database) -> i64 { | ||
| 854 | + let mut result = db | ||
| 855 | + .query("SELECT VALUE (count ?? 0) FROM slot_ref:lunch") | ||
| 856 | + .await | ||
| 857 | + .unwrap() | ||
| 858 | + .check() | ||
| 859 | + .unwrap(); | ||
| 860 | + result.take::<Vec<i64>>(0).unwrap()[0] | ||
| 861 | + } | ||
| 862 | + | ||
| 863 | + async fn menus(db: &Database) -> usize { | ||
| 864 | + let mut result = db | ||
| 865 | + .query("SELECT VALUE id FROM menu") | ||
| 866 | + .await | ||
| 867 | + .unwrap() | ||
| 868 | + .check() | ||
| 869 | + .unwrap(); | ||
| 870 | + result.take::<Vec<RecordId>>(0).unwrap().len() | ||
| 871 | + } | ||
| 872 | + | ||
| 873 | + async fn claim_slot(db: &Database, key: &str) -> ClaimedRef<Menu> { | ||
| 874 | + claim_ref_and_create( | ||
| 875 | + &RecordId::new(crate::constant::SLOT_REF_TABLE, "lunch"), | ||
| 876 | + 1, | ||
| 877 | + &RecordId::new("menu", key), | ||
| 878 | + &Menu { | ||
| 879 | + date: "2026-08-02".into(), | ||
| 880 | + slot: "lunch".into(), | ||
| 881 | + created_by: RecordId::new("user", "u"), | ||
| 882 | + created_at: 1, | ||
| 883 | + }, | ||
| 884 | + db, | ||
| 885 | + ) | ||
| 886 | + .await | ||
| 887 | + .unwrap() | ||
| 888 | + } | ||
| 889 | + | ||
| 890 | + #[tokio::test] | ||
| 891 | + async fn a_reference_and_its_row_land_together() { | ||
| 892 | + let db = a_slot(0, false).await; | ||
| 893 | + assert!(matches!(claim_slot(&db, "m1").await, ClaimedRef::Made(_))); | ||
| 894 | + assert_eq!(refs(&db).await, 1); | ||
| 895 | + assert_eq!(menus(&db).await, 1); | ||
| 896 | + } | ||
| 897 | + | ||
| 898 | + /// A retired name refuses, and the refusal must cost nothing: no row, no | ||
| 899 | + /// count — a counted row on a retired name is a name nobody can retire. | ||
| 900 | + #[tokio::test] | ||
| 901 | + async fn a_retired_name_refuses_with_no_row_and_no_count() { | ||
| 902 | + let db = a_slot(0, true).await; | ||
| 903 | + assert!(matches!(claim_slot(&db, "m1").await, ClaimedRef::Retired)); | ||
| 904 | + assert_eq!(refs(&db).await, 0); | ||
| 905 | + assert_eq!(menus(&db).await, 0); | ||
| 906 | + } | ||
| 907 | + | ||
| 908 | + #[tokio::test] | ||
| 909 | + async fn a_duplicate_row_claims_no_reference() { | ||
| 910 | + let db = a_slot(0, false).await; | ||
| 911 | + assert!(matches!(claim_slot(&db, "m1").await, ClaimedRef::Made(_))); | ||
| 912 | + assert!(matches!(claim_slot(&db, "m1").await, ClaimedRef::Duplicate)); | ||
| 913 | + assert_eq!(refs(&db).await, 1); | ||
| 914 | + assert_eq!(menus(&db).await, 1); | ||
| 915 | + } | ||
| 628 | } | 916 | } |
src/domain/chatbot_thread.rsmodified+92 -15
| @@ -88,6 +88,10 @@ impl ChatbotThread { | |||
| 88 | self.updated_at | 88 | self.updated_at |
| 89 | } | 89 | } |
| 90 | 90 | ||
| 91 | + /// Write a thread row and nothing else. **Bypasses the cap counter**, so it | ||
| 92 | + /// is only for tests that need a thread without one (`tests/persistence.rs` | ||
| 93 | + /// cascade check); every production path goes through | ||
| 94 | + /// [`ChatbotThread::create_capped`]. | ||
| 91 | pub async fn create( | 95 | pub async fn create( |
| 92 | user: &UserId, | 96 | user: &UserId, |
| 93 | title: Option<ChatbotThreadTitle>, | 97 | title: Option<ChatbotThreadTitle>, |
| @@ -106,28 +110,44 @@ impl ChatbotThread { | |||
| 106 | } | 110 | } |
| 107 | 111 | ||
| 108 | /// Start a thread unless `user` is already at the school's | 112 | /// Start a thread unless `user` is already at the school's |
| 109 | - /// `max_chatbot_threads`. The slot is taken by [`cap::claim`] on the user | 113 | + /// `max_chatbot_threads`. The slot is taken on the user row in the same |
| 110 | - /// row — an atomic single-record write, so two requests racing the same | 114 | + /// transaction as the thread ([`cap::claim_and_create`]) — an atomic |
| 111 | - /// user's last slot cannot both win, and the cap is read fresh so a | 115 | + /// single-record write, so two requests racing the same user's last slot |
| 112 | - /// concurrent settings PATCH is respected. | 116 | + /// cannot both win, the counter can never count a row that did not commit, |
| 117 | + /// and the cap is read fresh so a concurrent settings PATCH is respected. | ||
| 113 | pub async fn create_capped( | 118 | pub async fn create_capped( |
| 114 | user: &UserId, | 119 | user: &UserId, |
| 115 | title: Option<ChatbotThreadTitle>, | 120 | title: Option<ChatbotThreadTitle>, |
| 116 | db: &Database, | 121 | db: &Database, |
| 117 | ) -> Result<ChatbotThread, AppError> { | 122 | ) -> Result<ChatbotThread, AppError> { |
| 118 | let limit = Settings::load(db).await?.get_max_chatbot_threads(); | 123 | let limit = Settings::load(db).await?.get_max_chatbot_threads(); |
| 119 | - let owner = user.record(); | 124 | + let now = Timestamp::now(); |
| 120 | - if !cap::claim(&owner, CHATBOT_THREAD_COUNT_FIELD, limit, db).await? { | 125 | + let thread = ChatbotThread { |
| 121 | - return Err(AppError::Conflict( | 126 | + id: ChatbotThreadId::generate(), |
| 127 | + user_id: user.clone(), | ||
| 128 | + title, | ||
| 129 | + created_at: now, | ||
| 130 | + updated_at: now, | ||
| 131 | + }; | ||
| 132 | + match cap::claim_and_create( | ||
| 133 | + &user.record(), | ||
| 134 | + CHATBOT_THREAD_COUNT_FIELD, | ||
| 135 | + limit, | ||
| 136 | + &thread.id.record(), | ||
| 137 | + &thread, | ||
| 138 | + db, | ||
| 139 | + ) | ||
| 140 | + .await? | ||
| 141 | + { | ||
| 142 | + cap::Claimed::Made(saved) => Ok(saved), | ||
| 143 | + // Full, or the user's row is gone — the conditional write matches | ||
| 144 | + // nothing either way. | ||
| 145 | + cap::Claimed::Full => Err(AppError::Conflict( | ||
| 122 | "you have reached the school's limit on saved threads — delete one first", | 146 | "you have reached the school's limit on saved threads — delete one first", |
| 123 | - )); | 147 | + )), |
| 124 | - } | 148 | + // The id is a freshly minted ULID on a table with no UNIQUE index, |
| 125 | - match Self::create(user, title, db).await { | 149 | + // so no rival can have aimed at it. |
| 126 | - Ok(thread) => Ok(thread), | 150 | + cap::Claimed::Duplicate => Err(AppError::Internal("thread id collided".into())), |
| 127 | - Err(err) => { | ||
| 128 | - cap::release(&owner, CHATBOT_THREAD_COUNT_FIELD, db).await?; | ||
| 129 | - Err(err) | ||
| 130 | - } | ||
| 131 | } | 151 | } |
| 132 | } | 152 | } |
| 133 | 153 | ||
| @@ -238,6 +258,63 @@ impl ChatbotThread { | |||
| 238 | #[cfg(test)] | 258 | #[cfg(test)] |
| 239 | mod tests { | 259 | mod tests { |
| 240 | use super::*; | 260 | use super::*; |
| 261 | + use crate::domain::settings::SettingsParams; | ||
| 262 | + | ||
| 263 | + /// The owner's counter and the threads it counts, both re-read out of the | ||
| 264 | + /// store — never off a return value, which the in-memory engine forges | ||
| 265 | + /// wins on (see [`cap`]). | ||
| 266 | + async fn stored(db: &Database) -> (i64, usize) { | ||
| 267 | + let mut result = db | ||
| 268 | + .query("SELECT VALUE (chatbot_thread_count ?? 0) FROM user:u") | ||
| 269 | + .query("SELECT VALUE id FROM chatbot_thread") | ||
| 270 | + .await | ||
| 271 | + .unwrap() | ||
| 272 | + .check() | ||
| 273 | + .unwrap(); | ||
| 274 | + let counter = result.take::<Vec<i64>>(0).unwrap(); | ||
| 275 | + let rows = result.take::<Vec<RecordId>>(1).unwrap(); | ||
| 276 | + (counter[0], rows.len()) | ||
| 277 | + } | ||
| 278 | + | ||
| 279 | + async fn a_user_capped_at(threads: i64) -> Database { | ||
| 280 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 281 | + db.query("CREATE user:u SET username = 'u', password_hash = 'x';") | ||
| 282 | + .await | ||
| 283 | + .unwrap() | ||
| 284 | + .check() | ||
| 285 | + .unwrap(); | ||
| 286 | + Settings::try_new(SettingsParams { | ||
| 287 | + max_chatbot_threads: threads, | ||
| 288 | + ..Settings::defaults().params() | ||
| 289 | + }) | ||
| 290 | + .unwrap() | ||
| 291 | + .save(&db) | ||
| 292 | + .await | ||
| 293 | + .unwrap(); | ||
| 294 | + db | ||
| 295 | + } | ||
| 296 | + | ||
| 297 | + /// The seat and the row commit together, so the counter the cap reads can | ||
| 298 | + /// never disagree with the threads it counts — and a create refused at the | ||
| 299 | + /// cap advances neither. | ||
| 300 | + #[tokio::test] | ||
| 301 | + async fn a_capped_create_moves_the_counter_with_the_row() { | ||
| 302 | + let db = a_user_capped_at(1).await; | ||
| 303 | + let user = UserId::from_key("u"); | ||
| 304 | + | ||
| 305 | + ChatbotThread::create_capped(&user, None, &db) | ||
| 306 | + .await | ||
| 307 | + .expect("first thread"); | ||
| 308 | + assert_eq!(stored(&db).await, (1, 1)); | ||
| 309 | + | ||
| 310 | + let refused = ChatbotThread::create_capped(&user, None, &db).await; | ||
| 311 | + assert!(matches!(refused, Err(AppError::Conflict(_))), "at the cap"); | ||
| 312 | + assert_eq!( | ||
| 313 | + stored(&db).await, | ||
| 314 | + (1, 1), | ||
| 315 | + "a refused create advances neither" | ||
| 316 | + ); | ||
| 317 | + } | ||
| 241 | 318 | ||
| 242 | #[tokio::test] | 319 | #[tokio::test] |
| 243 | async fn title_is_required_and_bounded() { | 320 | async fn title_is_required_and_bounded() { |
src/domain/class_group.rsmodified+18 -3
| @@ -199,11 +199,19 @@ impl ClassGroup { | |||
| 199 | db: &Database, | 199 | db: &Database, |
| 200 | ) -> Result<ClassGroup, AppError> { | 200 | ) -> Result<ClassGroup, AppError> { |
| 201 | let (claim, release) = term::ref_move(self.term.as_ref(), &term); | 201 | let (claim, release) = term::ref_move(self.term.as_ref(), &term); |
| 202 | + let expected = self.term.as_ref().map(TermId::record); | ||
| 202 | FieldUpdate::new(self.id.record()) | 203 | FieldUpdate::new(self.id.record()) |
| 203 | .set("name", name) | 204 | .set("name", name) |
| 204 | .set("grade", grade) | 205 | .set("grade", grade) |
| 205 | .set("term", term.map(|term| term.map(|term| term.record()))) | 206 | .set("term", term.map(|term| term.map(|term| term.record()))) |
| 206 | - .refcount(TERM_CLASS_COUNT_FIELD, claim, release, term::gone_error()) | 207 | + .refcount( |
| 208 | + TERM_CLASS_COUNT_FIELD, | ||
| 209 | + "term", | ||
| 210 | + expected, | ||
| 211 | + claim, | ||
| 212 | + release, | ||
| 213 | + term::gone_error(), | ||
| 214 | + ) | ||
| 207 | .run::<ClassGroup>(db) | 215 | .run::<ClassGroup>(db) |
| 208 | .await | 216 | .await |
| 209 | } | 217 | } |
| @@ -489,7 +497,10 @@ mod tests { | |||
| 489 | .await | 497 | .await |
| 490 | .expect_err("a term that is gone must not be linkable"); | 498 | .expect_err("a term that is gone must not be linkable"); |
| 491 | assert!(error.to_string().contains("term does not exist")); | 499 | assert!(error.to_string().contains("term does not exist")); |
| 492 | - let stored = ClassGroup::read(class.get_id(), &db).await.unwrap().unwrap(); | 500 | + let stored = ClassGroup::read(class.get_id(), &db) |
| 501 | + .await | ||
| 502 | + .unwrap() | ||
| 503 | + .unwrap(); | ||
| 493 | assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put"); | 504 | 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"); | 505 | assert_eq!(stored.get_name().as_str(), "9-A", "…and so does the row"); |
| 495 | assert_eq!( | 506 | assert_eq!( |
| @@ -503,7 +514,11 @@ mod tests { | |||
| 503 | .await | 514 | .await |
| 504 | .unwrap(); | 515 | .unwrap(); |
| 505 | assert_eq!(moved.get_term(), Some(to.get_id())); | 516 | 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"); | 517 | + assert_eq!( |
| 518 | + count_on(from.get_id(), &db).await, | ||
| 519 | + 0, | ||
| 520 | + "the old term is free" | ||
| 521 | + ); | ||
| 507 | assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); | 522 | assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); |
| 508 | } | 523 | } |
| 509 | 524 | ||
src/domain/course.rsmodified+100 -4
| @@ -290,13 +290,21 @@ impl Course { | |||
| 290 | // without its count. A PATCH that carried no `term_id`, or re-stated the | 290 | // without its count. A PATCH that carried no `term_id`, or re-stated the |
| 291 | // link it already had, moves neither counter. | 291 | // link it already had, moves neither counter. |
| 292 | let (claim, release) = term::ref_move(self.term.as_ref(), &term); | 292 | let (claim, release) = term::ref_move(self.term.as_ref(), &term); |
| 293 | + let expected = self.term.as_ref().map(TermId::record); | ||
| 293 | FieldUpdate::new(self.id.record()) | 294 | FieldUpdate::new(self.id.record()) |
| 294 | .set("title", title) | 295 | .set("title", title) |
| 295 | .set("description", description) | 296 | .set("description", description) |
| 296 | .set("kind", kind) | 297 | .set("kind", kind) |
| 297 | .set("term", term.map(|term| term.map(|term| term.record()))) | 298 | .set("term", term.map(|term| term.map(|term| term.record()))) |
| 298 | .set("capacity", capacity) | 299 | .set("capacity", capacity) |
| 299 | - .refcount(COURSE_COUNT_FIELD, claim, release, term::gone_error()) | 300 | + .refcount( |
| 301 | + COURSE_COUNT_FIELD, | ||
| 302 | + "term", | ||
| 303 | + expected, | ||
| 304 | + claim, | ||
| 305 | + release, | ||
| 306 | + term::gone_error(), | ||
| 307 | + ) | ||
| 300 | .run::<Course>(db) | 308 | .run::<Course>(db) |
| 301 | .await | 309 | .await |
| 302 | } | 310 | } |
| @@ -583,7 +591,9 @@ mod tests { | |||
| 583 | /// The stored `course_count` on one term, absent counting as zero. | 591 | /// The stored `course_count` on one term, absent counting as zero. |
| 584 | async fn count_on(term: &TermId, db: &Database) -> i64 { | 592 | async fn count_on(term: &TermId, db: &Database) -> i64 { |
| 585 | let mut result = db | 593 | let mut result = db |
| 586 | - .query(format!("SELECT VALUE ({COURSE_COUNT_FIELD} ?? 0) FROM $term")) | 594 | + .query(format!( |
| 595 | + "SELECT VALUE ({COURSE_COUNT_FIELD} ?? 0) FROM $term" | ||
| 596 | + )) | ||
| 587 | .bind(("term", term.record())) | 597 | .bind(("term", term.record())) |
| 588 | .await | 598 | .await |
| 589 | .unwrap() | 599 | .unwrap() |
| @@ -661,12 +671,94 @@ mod tests { | |||
| 661 | .await | 671 | .await |
| 662 | .unwrap(); | 672 | .unwrap(); |
| 663 | assert_eq!(moved.get_term(), Some(to.get_id())); | 673 | 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"); | 674 | + assert_eq!( |
| 675 | + count_on(from.get_id(), &db).await, | ||
| 676 | + 0, | ||
| 677 | + "the old term is free" | ||
| 678 | + ); | ||
| 665 | assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); | 679 | assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); |
| 666 | assert!(from.clone().delete(&db).await.unwrap()); | 680 | assert!(from.clone().delete(&db).await.unwrap()); |
| 667 | assert!(!to.clone().delete(&db).await.unwrap()); | 681 | assert!(!to.clone().delete(&db).await.unwrap()); |
| 668 | } | 682 | } |
| 669 | 683 | ||
| 684 | + /// The double-claim guard. Both movers compute their claim and release from | ||
| 685 | + /// the row as *they* read it, so two PATCHes moving the same course off the | ||
| 686 | + /// same term both release it and both claim their target — two counts for | ||
| 687 | + /// one link, and the loser's target is undeletable forever. The second call | ||
| 688 | + /// here runs on the struct read before the first one landed, which is that | ||
| 689 | + /// race with the interleaving pinned: it must be refused outright, and the | ||
| 690 | + /// counts must read as if it never ran. | ||
| 691 | + #[tokio::test] | ||
| 692 | + async fn a_stale_mover_is_refused_and_claims_nothing() { | ||
| 693 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 694 | + let from = a_term("2026", &db).await; | ||
| 695 | + let to = a_term("2027", &db).await; | ||
| 696 | + let other = a_term("2028", &db).await; | ||
| 697 | + let course = course_on(Some(from.get_id().clone()), &db).await; | ||
| 698 | + let stale = course.clone(); | ||
| 699 | + course | ||
| 700 | + .update(None, None, None, Some(Some(to.get_id().clone())), None, &db) | ||
| 701 | + .await | ||
| 702 | + .unwrap(); | ||
| 703 | + | ||
| 704 | + let error = stale | ||
| 705 | + .clone() | ||
| 706 | + .update( | ||
| 707 | + None, | ||
| 708 | + None, | ||
| 709 | + None, | ||
| 710 | + Some(Some(other.get_id().clone())), | ||
| 711 | + None, | ||
| 712 | + &db, | ||
| 713 | + ) | ||
| 714 | + .await | ||
| 715 | + .expect_err("a mover that read a link it no longer holds must be refused"); | ||
| 716 | + assert!( | ||
| 717 | + matches!(error, AppError::Conflict(_)), | ||
| 718 | + "a lost CAS is a conflict, not a 404 or a 500: {error:?}" | ||
| 719 | + ); | ||
| 720 | + let stored = Course::read(stale.get_id(), &db).await.unwrap().unwrap(); | ||
| 721 | + assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link"); | ||
| 722 | + assert_eq!( | ||
| 723 | + count_on(from.get_id(), &db).await, | ||
| 724 | + 0, | ||
| 725 | + "released once, not twice" | ||
| 726 | + ); | ||
| 727 | + assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once"); | ||
| 728 | + assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed"); | ||
| 729 | + | ||
| 730 | + // Same race from the other end: the snapshot says *no* link, so the CAS | ||
| 731 | + // is against an absent column — the shape a bound `NONE` has to match. | ||
| 732 | + let unlinked = course_on(None, &db).await; | ||
| 733 | + let stale = unlinked.clone(); | ||
| 734 | + unlinked | ||
| 735 | + .update(None, None, None, Some(Some(to.get_id().clone())), None, &db) | ||
| 736 | + .await | ||
| 737 | + .unwrap(); | ||
| 738 | + let error = stale | ||
| 739 | + .clone() | ||
| 740 | + .update( | ||
| 741 | + None, | ||
| 742 | + None, | ||
| 743 | + None, | ||
| 744 | + Some(Some(other.get_id().clone())), | ||
| 745 | + None, | ||
| 746 | + &db, | ||
| 747 | + ) | ||
| 748 | + .await | ||
| 749 | + .expect_err("a mover that read an absent link someone else filled must be refused"); | ||
| 750 | + assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); | ||
| 751 | + assert_eq!(count_on(to.get_id(), &db).await, 2, "one claim per link"); | ||
| 752 | + assert_eq!( | ||
| 753 | + count_on(other.get_id(), &db).await, | ||
| 754 | + 0, | ||
| 755 | + "still never claimed" | ||
| 756 | + ); | ||
| 757 | + // …and the unraced set still lands, so the CAS did not just break moves. | ||
| 758 | + let stored = Course::read(stale.get_id(), &db).await.unwrap().unwrap(); | ||
| 759 | + assert_eq!(stored.get_term(), Some(to.get_id())); | ||
| 760 | + } | ||
| 761 | + | ||
| 670 | /// The rollback proof. The transaction releases the old term *before* it | 762 | /// 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 | 763 | /// 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 | 764 | /// decremented when the claim throws — the old count still being 1 is the |
| @@ -697,7 +789,11 @@ mod tests { | |||
| 697 | 789 | ||
| 698 | let stored = Course::read(course.get_id(), &db).await.unwrap().unwrap(); | 790 | 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"); | 791 | 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"); | 792 | + assert_eq!( |
| 793 | + stored.get_title().as_str(), | ||
| 794 | + "algebra", | ||
| 795 | + "…and so does the row" | ||
| 796 | + ); | ||
| 701 | assert_eq!( | 797 | assert_eq!( |
| 702 | count_on(from.get_id(), &db).await, | 798 | count_on(from.get_id(), &db).await, |
| 703 | 1, | 799 | 1, |
src/domain/exam_result.rsmodified+187 -57
| @@ -3,7 +3,7 @@ use std::collections::HashMap; | |||
| 3 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 3 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 4 | 4 | ||
| 5 | use crate::constant::{ | 5 | use crate::constant::{ |
| 6 | - EXAM_RESULT_COUNT_FIELD, EXAM_RESULT_TABLE, KIND_REF_TABLE, REF_COUNT_FIELD, | 6 | + EXAM_RESULT_COUNT_FIELD, EXAM_RESULT_TABLE, KIND_REF_TABLE, REF_COUNT_FIELD, REF_RETIRED_FIELD, |
| 7 | }; | 7 | }; |
| 8 | use crate::database::{Database, transaction_with_retry}; | 8 | use crate::database::{Database, transaction_with_retry}; |
| 9 | use crate::domain::cap; | 9 | use crate::domain::cap; |
| @@ -81,13 +81,9 @@ impl Mark { | |||
| 81 | } | 81 | } |
| 82 | } | 82 | } |
| 83 | 83 | ||
| 84 | -/// What one mark write reports back: the stored row, and whether it replaced a | 84 | +/// The `THROW` marker the in-transaction kind claim aborts with — the mark's |
| 85 | -/// mark that was already there. | 85 | +/// own transaction refusing a name the school has retired. |
| 86 | -#[derive(Debug, Clone, SurrealValue)] | 86 | +const RETIRED_MARK: &str = "kind_retired"; |
| 87 | -struct Written { | ||
| 88 | - existed: bool, | ||
| 89 | - result: ExamResult, | ||
| 90 | -} | ||
| 91 | 87 | ||
| 92 | #[derive(Debug, Clone, SurrealValue)] | 88 | #[derive(Debug, Clone, SurrealValue)] |
| 93 | pub struct ExamResult { | 89 | pub struct ExamResult { |
| @@ -188,17 +184,23 @@ impl ExamResult { | |||
| 188 | /// prior sittings' marks; the latest seq is the grade-of-record. | 184 | /// prior sittings' marks; the latest seq is the grade-of-record. |
| 189 | /// | 185 | /// |
| 190 | /// `kind` is the exam's kind, and this is where a mark takes its reference | 186 | /// `kind` is the exam's kind, and this is where a mark takes its reference |
| 191 | - /// on it — claimed *before* the write, given back when the write turns out | 187 | + /// on it — claimed *inside the mark's own transaction*, and only on the |
| 192 | - /// to have been an overwrite (one mark, one reference) or to have failed. A | 188 | + /// branch that is about to add a row. A kind the school has retired refuses |
| 193 | - /// kind the school has retired refuses the claim, which is the same | 189 | + /// the claim, which is the same invariant the settings guard enforces from |
| 194 | - /// invariant the settings guard enforces from the other side, and the one | 190 | + /// the other side. Claimed before the write and released after, the pair had |
| 195 | - /// crash window left over-counts a kind (refusing a removal) rather than | 191 | + /// two crash windows either side of the write that leaked a reference (a |
| 196 | - /// letting a mark exist under a kind nothing counted. | 192 | + /// kind frozen out of the settings for good) and an exam's `result_count`; |
| 193 | + /// riding the transaction, both counters land exactly when the row does. | ||
| 197 | /// | 194 | /// |
| 198 | /// The exam's own `result_count` is claimed in the same breath, and it is | 195 | /// The exam's own `result_count` is claimed in the same breath, and it is |
| 199 | /// what a kind change is refused against: the exam PATCH pins that counter, | 196 | /// what a kind change is refused against: the exam PATCH pins that counter, |
| 200 | /// so a mark landing while it decides cannot slip past its gate and leave | 197 | /// so a mark landing while it decides cannot slip past its gate and leave |
| 201 | /// itself counted under a kind its exam no longer carries. | 198 | /// itself counted under a kind its exam no longer carries. |
| 199 | + /// | ||
| 200 | + /// An overwrite (a regrade of a sitting already marked) claims *nothing*: | ||
| 201 | + /// one mark, one reference, so the branch that finds a row simply leaves | ||
| 202 | + /// both counters where they are — there is no claim to give back, and so no | ||
| 203 | + /// window in which a crash could fail to give it. | ||
| 202 | pub async fn grade( | 204 | pub async fn grade( |
| 203 | exam: &ExamId, | 205 | exam: &ExamId, |
| 204 | user: &UserId, | 206 | user: &UserId, |
| @@ -208,32 +210,6 @@ impl ExamResult { | |||
| 208 | kind: &str, | 210 | kind: &str, |
| 209 | db: &Database, | 211 | db: &Database, |
| 210 | ) -> Result<ExamResult, AppError> { | 212 | ) -> Result<ExamResult, AppError> { |
| 211 | - let counter = kind_ref(kind); | ||
| 212 | - if !cap::claim_ref(&counter, 1, db).await? { | ||
| 213 | - return Err(retired_kind_error(kind)); | ||
| 214 | - } | ||
| 215 | - cap::claim(&exam.record(), EXAM_RESULT_COUNT_FIELD, cap::UNLIMITED, db).await?; | ||
| 216 | - let written = Self::write_mark(exam, user, seq, mark, graded_by, db).await; | ||
| 217 | - match written { | ||
| 218 | - // An overwrite is not a second mark: both counters go back, or a | ||
| 219 | - // regrade would drift them upward and freeze the kind for good. | ||
| 220 | - Ok(Written { existed: true, .. }) | Err(_) => { | ||
| 221 | - cap::release_ref(&counter, 1, db).await?; | ||
| 222 | - cap::release(&exam.record(), EXAM_RESULT_COUNT_FIELD, db).await?; | ||
| 223 | - } | ||
| 224 | - Ok(_) => {} | ||
| 225 | - } | ||
| 226 | - written.map(|written| written.result) | ||
| 227 | - } | ||
| 228 | - | ||
| 229 | - async fn write_mark( | ||
| 230 | - exam: &ExamId, | ||
| 231 | - user: &UserId, | ||
| 232 | - seq: i64, | ||
| 233 | - mark: Mark, | ||
| 234 | - graded_by: &UserId, | ||
| 235 | - db: &Database, | ||
| 236 | - ) -> Result<Written, AppError> { | ||
| 237 | let result = ExamResult { | 213 | let result = ExamResult { |
| 238 | id: ExamResultId::composite(exam, user, seq), | 214 | id: ExamResultId::composite(exam, user, seq), |
| 239 | exam: exam.clone(), | 215 | exam: exam.clone(), |
| @@ -250,33 +226,52 @@ impl ExamResult { | |||
| 250 | // redundant with the draft one — a deleted exam reads NONE, which is | 226 | // redundant with the draft one — a deleted exam reads NONE, which is |
| 251 | // *falsy*, so the draft gate alone waved a mark onto an exam that no | 227 | // *falsy*, so the draft gate alone waved a mark onto an exam that no |
| 252 | // longer existed. The caller's pre-flight check answers the same 409 | 228 | // longer existed. The caller's pre-flight check answers the same 409 |
| 253 | - // one round trip earlier. | 229 | + // one round trip earlier. It is also what makes a separate "did the |
| 254 | - // Whether the row was already there rides out of the transaction with | 230 | + // exam survive my claim?" check moot: the claim now sits behind this |
| 255 | - // the mark: the answer decides if this grade owes the kind a reference, | 231 | + // gate instead of in front of it. |
| 256 | - // and read anywhere else it would be a guess about a row two graders | 232 | + // |
| 257 | - // may be writing at once. | 233 | + // Whether the row was already there decides both counters, and it is |
| 234 | + // read one statement before them inside the same transaction — read | ||
| 235 | + // anywhere else it would be a guess about a row two graders may be | ||
| 236 | + // writing at once. | ||
| 258 | // | 237 | // |
| 259 | // Re-sent while the store answers "conflict, retry": the gates read a | 238 | // Re-sent while the store answers "conflict, retry": the gates read a |
| 260 | - // column an exam PATCH writes, so the two contend on one record by | 239 | + // column an exam PATCH writes, and the counters are the ones a |
| 261 | - // design. Sound to re-send because the only write is an UPSERT on a | 240 | + // concurrent delete gives back, so this contends on three records by |
| 262 | - // deterministic id — `key::sitting(exam, user, seq)` *is* the | 241 | + // design. Sound to re-send because no statement in it can legitimately |
| 263 | - // `exam_result_exam_user_seq` unique tuple — so it can never answer | 242 | + // answer "already exists": the counter writes are `UPDATE`/`UPSERT` on |
| 264 | - // "already exists", the one thing a retry cannot fix. | 243 | + // ids no rival can collide *into*, and the mark's own UPSERT is on a |
| 244 | + // deterministic id bijective with the `exam_result_exam_user_seq` | ||
| 245 | + // unique tuple — `key::sitting(exam, user, seq)` *is* that tuple, so | ||
| 246 | + // the index entry can only ever point at the row the id already names | ||
| 247 | + // and the write resolves onto it. A lost round aborts having written | ||
| 248 | + // nothing, counters included. | ||
| 249 | + let _guard = cap::counter_lock().await; | ||
| 265 | let (mut written, mut errors) = transaction_with_retry( | 250 | let (mut written, mut errors) = transaction_with_retry( |
| 266 | db, | 251 | db, |
| 267 | - "BEGIN TRANSACTION; | 252 | + &format!( |
| 268 | - IF (SELECT VALUE id FROM ONLY $exam) IS NONE { THROW 'exam_missing' }; | 253 | + "BEGIN TRANSACTION; |
| 269 | - IF (SELECT VALUE draft FROM ONLY $exam) { THROW 'exam_draft' }; | 254 | + IF (SELECT VALUE id FROM ONLY $exam) IS NONE {{ THROW 'exam_missing' }}; |
| 255 | + IF (SELECT VALUE draft FROM ONLY $exam) {{ THROW 'exam_draft' }}; | ||
| 270 | LET $before = (SELECT VALUE id FROM ONLY $id); | 256 | LET $before = (SELECT VALUE id FROM ONLY $id); |
| 257 | + IF $before = NONE {{ | ||
| 258 | + LET $kind = (UPSERT $kref SET {REF_COUNT_FIELD} = ({REF_COUNT_FIELD} ?? 0) + 1 | ||
| 259 | + WHERE {REF_RETIRED_FIELD} != true RETURN VALUE id); | ||
| 260 | + IF array::len($kind) = 0 {{ THROW '{RETIRED_MARK}' }}; | ||
| 261 | + UPDATE $exam SET {EXAM_RESULT_COUNT_FIELD} = | ||
| 262 | + ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1; | ||
| 263 | + }}; | ||
| 271 | LET $after = (UPSERT $id CONTENT $result RETURN AFTER); | 264 | LET $after = (UPSERT $id CONTENT $result RETURN AFTER); |
| 272 | - RETURN { existed: $before != NONE, result: $after[0] }; | 265 | + RETURN $after[0]; |
| 273 | - COMMIT TRANSACTION;", | 266 | + COMMIT TRANSACTION;" |
| 267 | + ), | ||
| 274 | &[ | 268 | &[ |
| 275 | ("exam".into(), exam.record().into_value()), | 269 | ("exam".into(), exam.record().into_value()), |
| 276 | ("id".into(), result.id.record().into_value()), | 270 | ("id".into(), result.id.record().into_value()), |
| 271 | + ("kref".into(), kind_ref(kind).into_value()), | ||
| 277 | ("result".into(), result.into_value()), | 272 | ("result".into(), result.into_value()), |
| 278 | ], | 273 | ], |
| 279 | - &["exam_missing", "exam_draft"], | 274 | + &["exam_missing", "exam_draft", RETIRED_MARK], |
| 280 | ) | 275 | ) |
| 281 | .await?; | 276 | .await?; |
| 282 | // An aborted transaction errors every slot and only the THROW's own | 277 | // An aborted transaction errors every slot and only the THROW's own |
| @@ -293,15 +288,20 @@ impl ExamResult { | |||
| 293 | if thrown("exam_draft") { | 288 | if thrown("exam_draft") { |
| 294 | return Err(draft_error()); | 289 | return Err(draft_error()); |
| 295 | } | 290 | } |
| 291 | + if thrown(RETIRED_MARK) { | ||
| 292 | + return Err(retired_kind_error(kind)); | ||
| 293 | + } | ||
| 296 | if let Some(error) = errors.drain().map(|(_, error)| error).next() { | 294 | if let Some(error) = errors.drain().map(|(_, error)| error).next() { |
| 297 | return Err(error.into()); | 295 | return Err(error.into()); |
| 298 | } | 296 | } |
| 299 | // The trailing `RETURN` is always the last statement before `COMMIT`, | 297 | // The trailing `RETURN` is always the last statement before `COMMIT`, |
| 300 | // so its slot follows the statement count instead of a hand-kept | 298 | // so its slot follows the statement count instead of a hand-kept |
| 301 | // number — see `Exam::delete` for the bug the hand-kept one caused. | 299 | // number — see `Exam::delete` for the bug the hand-kept one caused. |
| 300 | + // Probed on crate 3.2.3: an `IF { … }` block occupies exactly one slot | ||
| 301 | + // however many statements it holds, and one whether or not it is taken. | ||
| 302 | let slot = written.num_statements().saturating_sub(2); | 302 | let slot = written.num_statements().saturating_sub(2); |
| 303 | written | 303 | written |
| 304 | - .take::<Vec<Written>>(slot)? | 304 | + .take::<Vec<ExamResult>>(slot)? |
| 305 | .into_iter() | 305 | .into_iter() |
| 306 | .next() | 306 | .next() |
| 307 | .ok_or_else(|| AppError::Internal("failed to record exam result".into())) | 307 | .ok_or_else(|| AppError::Internal("failed to record exam result".into())) |
| @@ -531,5 +531,135 @@ mod tests { | |||
| 531 | .unwrap() | 531 | .unwrap() |
| 532 | .is_empty() | 532 | .is_empty() |
| 533 | ); | 533 | ); |
| 534 | + assert_eq!(counters(&db, "midterm").await, (0, 0)); | ||
| 535 | + } | ||
| 536 | + | ||
| 537 | + /// The two counters, re-read out of the store — never off a return value, | ||
| 538 | + /// which the in-memory engine forges wins on (see `cap::CLAIM_LOCK`). A | ||
| 539 | + /// missing `kind_ref` row is a zero, which is exactly how the backfill | ||
| 540 | + /// treats it (`tests/persistence.rs` — no zero pass, deliberately). | ||
| 541 | + async fn counters(db: &Database, kind: &str) -> (i64, i64) { | ||
| 542 | + let mut result = db | ||
| 543 | + .query( | ||
| 544 | + "SELECT VALUE count ?? 0 FROM kind_ref WHERE record::id(id) = $kind; | ||
| 545 | + SELECT VALUE result_count ?? 0 FROM exam;", | ||
| 546 | + ) | ||
| 547 | + .bind(("kind", kind.to_string())) | ||
| 548 | + .await | ||
| 549 | + .unwrap() | ||
| 550 | + .check() | ||
| 551 | + .unwrap(); | ||
| 552 | + let kinds: Vec<i64> = result.take(0).unwrap(); | ||
| 553 | + let exams: Vec<i64> = result.take(1).unwrap(); | ||
| 554 | + ( | ||
| 555 | + kinds.into_iter().next().unwrap_or(0), | ||
| 556 | + exams.into_iter().next().unwrap_or(0), | ||
| 557 | + ) | ||
| 558 | + } | ||
| 559 | + | ||
| 560 | + async fn an_exam(db: &Database, exam: &ExamId, kind: &str) { | ||
| 561 | + db.query( | ||
| 562 | + "CREATE $ex SET creator = user:t, course = course:c, title = 't', | ||
| 563 | + description = '', kind = $kind", | ||
| 564 | + ) | ||
| 565 | + .bind(("ex", exam.record())) | ||
| 566 | + .bind(("kind", kind.to_string())) | ||
| 567 | + .await | ||
| 568 | + .unwrap() | ||
| 569 | + .check() | ||
| 570 | + .unwrap(); | ||
| 571 | + } | ||
| 572 | + | ||
| 573 | + async fn grade( | ||
| 574 | + db: &Database, | ||
| 575 | + exam: &ExamId, | ||
| 576 | + seq: i64, | ||
| 577 | + mark: i64, | ||
| 578 | + kind: &str, | ||
| 579 | + ) -> Result<ExamResult, AppError> { | ||
| 580 | + ExamResult::grade( | ||
| 581 | + exam, | ||
| 582 | + &UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"), | ||
| 583 | + seq, | ||
| 584 | + Mark::try_new(mark).unwrap(), | ||
| 585 | + &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), | ||
| 586 | + kind, | ||
| 587 | + db, | ||
| 588 | + ) | ||
| 589 | + .await | ||
| 590 | + } | ||
| 591 | + | ||
| 592 | + /// Both counters ride the mark's own transaction: a new mark claims each | ||
| 593 | + /// exactly once, and a *regrade* of the same sitting claims neither — one | ||
| 594 | + /// mark, one reference. Claimed-then-released around the write, a regrade | ||
| 595 | + /// drifted them upward and froze the kind out of the settings for good. | ||
| 596 | + #[tokio::test] | ||
| 597 | + async fn a_new_mark_moves_both_counters_and_a_regrade_moves_neither() { | ||
| 598 | + let db = init_mem().await.unwrap(); | ||
| 599 | + let exam = ExamId::from_key("01TESTEXAMCOUNTAAAAAAAAAAA"); | ||
| 600 | + an_exam(&db, &exam, "midterm").await; | ||
| 601 | + | ||
| 602 | + grade(&db, &exam, 1, 40, "midterm").await.unwrap(); | ||
| 603 | + assert_eq!(counters(&db, "midterm").await, (1, 1)); | ||
| 604 | + | ||
| 605 | + // Same sitting, new mark: an overwrite, so neither counter moves. | ||
| 606 | + let regraded = grade(&db, &exam, 1, 90, "midterm").await.unwrap(); | ||
| 607 | + assert_eq!(regraded.get_mark().as_i64(), 90); | ||
| 608 | + assert_eq!(counters(&db, "midterm").await, (1, 1)); | ||
| 609 | + | ||
| 610 | + // A retake is a second row, so it does claim. | ||
| 611 | + grade(&db, &exam, 2, 70, "midterm").await.unwrap(); | ||
| 612 | + assert_eq!(counters(&db, "midterm").await, (2, 2)); | ||
| 613 | + } | ||
| 614 | + | ||
| 615 | + /// A retired kind refuses the claim from inside the transaction, which | ||
| 616 | + /// takes the mark and the exam's counter down with it — the settings guard | ||
| 617 | + /// enforcing the same invariant from the other side. | ||
| 618 | + #[tokio::test] | ||
| 619 | + async fn a_retired_kind_refuses_the_mark_and_leaves_both_counters_alone() { | ||
| 620 | + let db = init_mem().await.unwrap(); | ||
| 621 | + let exam = ExamId::from_key("01TESTEXAMRETIREDAAAAAAAAA"); | ||
| 622 | + an_exam(&db, &exam, "midterm").await; | ||
| 623 | + assert!(cap::retire(&kind_ref("midterm"), &db).await.unwrap()); | ||
| 624 | + | ||
| 625 | + let refused = grade(&db, &exam, 1, 40, "midterm").await; | ||
| 626 | + assert!( | ||
| 627 | + matches!(&refused, Err(AppError::ConflictOwned(message)) | ||
| 628 | + if message.contains("has been removed from the school's settings")), | ||
| 629 | + "{refused:?}" | ||
| 630 | + ); | ||
| 631 | + assert!( | ||
| 632 | + ExamResult::list_for_exam(&exam, &db) | ||
| 633 | + .await | ||
| 634 | + .unwrap() | ||
| 635 | + .is_empty(), | ||
| 636 | + "the mark must not have landed" | ||
| 637 | + ); | ||
| 638 | + assert_eq!(counters(&db, "midterm").await, (0, 0)); | ||
| 639 | + } | ||
| 640 | + | ||
| 641 | + /// A draft exam refuses the mark, and the counters stay put — the gate | ||
| 642 | + /// runs before the claim now, so there is nothing to give back. | ||
| 643 | + #[tokio::test] | ||
| 644 | + async fn a_draft_exam_refuses_the_mark_and_leaves_both_counters_alone() { | ||
| 645 | + let db = init_mem().await.unwrap(); | ||
| 646 | + let exam = ExamId::from_key("01TESTEXAMDRAFTAAAAAAAAAAA"); | ||
| 647 | + an_exam(&db, &exam, "midterm").await; | ||
| 648 | + db.query("UPDATE $ex SET draft = true") | ||
| 649 | + .bind(("ex", exam.record())) | ||
| 650 | + .await | ||
| 651 | + .unwrap() | ||
| 652 | + .check() | ||
| 653 | + .unwrap(); | ||
| 654 | + | ||
| 655 | + let refused = grade(&db, &exam, 1, 40, "midterm").await; | ||
| 656 | + assert!(matches!(refused, Err(AppError::Conflict(_))), "{refused:?}"); | ||
| 657 | + assert!( | ||
| 658 | + ExamResult::list_for_exam(&exam, &db) | ||
| 659 | + .await | ||
| 660 | + .unwrap() | ||
| 661 | + .is_empty() | ||
| 662 | + ); | ||
| 663 | + assert_eq!(counters(&db, "midterm").await, (0, 0)); | ||
| 534 | } | 664 | } |
| 535 | } | 665 | } |
src/domain/field_update.rsmodified+69 -21
| @@ -29,10 +29,22 @@ use crate::domain::cap; | |||
| 29 | use crate::error::AppError; | 29 | use crate::error::AppError; |
| 30 | 30 | ||
| 31 | /// The `THROW` markers [`FieldUpdate::refcount`]'s transaction aborts with: the | 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 | 32 | +/// row the reference was to be claimed on is gone, the row being patched is |
| 33 | -/// gone (or its guard bit). | 33 | +/// gone (or its guard bit), and the link this move started from is no longer |
| 34 | +/// the one the handler read. | ||
| 34 | const CLAIM_MARK: &str = "ref_claim_gone"; | 35 | const CLAIM_MARK: &str = "ref_claim_gone"; |
| 35 | const ROW_MARK: &str = "ref_row_gone"; | 36 | const ROW_MARK: &str = "ref_row_gone"; |
| 37 | +const STALE_MARK: &str = "ref_stale_move"; | ||
| 38 | + | ||
| 39 | +/// `(counter field, link column, expected link, claim, release, refusal)`. | ||
| 40 | +type Refcount = ( | ||
| 41 | + &'static str, | ||
| 42 | + &'static str, | ||
| 43 | + Option<RecordId>, | ||
| 44 | + Option<RecordId>, | ||
| 45 | + Option<RecordId>, | ||
| 46 | + AppError, | ||
| 47 | +); | ||
| 36 | 48 | ||
| 37 | pub struct FieldUpdate { | 49 | pub struct FieldUpdate { |
| 38 | id: RecordId, | 50 | id: RecordId, |
| @@ -43,8 +55,9 @@ pub struct FieldUpdate { | |||
| 43 | ordered: Option<(&'static str, &'static str, AppError)>, | 55 | ordered: Option<(&'static str, &'static str, AppError)>, |
| 44 | /// `(condition, refusal)` for [`FieldUpdate::guard`]. | 56 | /// `(condition, refusal)` for [`FieldUpdate::guard`]. |
| 45 | guard: Option<(&'static str, AppError)>, | 57 | guard: Option<(&'static str, AppError)>, |
| 46 | - /// `(counter field, claim, release, refusal)` for [`FieldUpdate::refcount`]. | 58 | + /// `(counter field, link column, expected link, claim, release, refusal)` |
| 47 | - refcount: Option<(&'static str, Option<RecordId>, Option<RecordId>, AppError)>, | 59 | + /// for [`FieldUpdate::refcount`]. |
| 60 | + refcount: Option<Refcount>, | ||
| 48 | } | 61 | } |
| 49 | 62 | ||
| 50 | impl FieldUpdate { | 63 | impl FieldUpdate { |
| @@ -60,8 +73,9 @@ impl FieldUpdate { | |||
| 60 | } | 73 | } |
| 61 | 74 | ||
| 62 | /// Write `field` only when the request carried it. The bind variable is | 75 | /// Write `field` only when the request carried it. The bind variable is |
| 63 | - /// named after the field, so `id` — and `ref_claim`/`ref_release`, which | 76 | + /// named after the field, so `id` — and `ref_claim`/`ref_release`/ |
| 64 | - /// [`FieldUpdate::refcount`] binds — are the names a caller must not use. | 77 | + /// `ref_expected`, which [`FieldUpdate::refcount`] binds — are the names a |
| 78 | + /// caller must not use. | ||
| 65 | #[must_use] | 79 | #[must_use] |
| 66 | pub fn set<T: SurrealValue>(mut self, field: &'static str, value: Option<T>) -> Self { | 80 | pub fn set<T: SurrealValue>(mut self, field: &'static str, value: Option<T>) -> Self { |
| 67 | if let Some(value) = value { | 81 | if let Some(value) = value { |
| @@ -122,16 +136,28 @@ impl FieldUpdate { | |||
| 122 | /// | 136 | /// |
| 123 | /// Only ever called alongside a `.set()` of the very column that carries the | 137 | /// 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. | 138 | /// link, so the empty-request short-circuit below cannot swallow a move. |
| 139 | + /// | ||
| 140 | + /// `link` is that column (never `field`: the counter lives on the *other* | ||
| 141 | + /// row, `course_count` on the term against a `term` link) and `expected` is | ||
| 142 | + /// what the handler's snapshot said it held — `None` for a link that was | ||
| 143 | + /// absent. The pair becomes a CAS on the row write, because claim and | ||
| 144 | + /// release are computed from that snapshot: two PATCHes moving the same link | ||
| 145 | + /// A→B both read A, and both would claim B, leaving B counted twice for one | ||
| 146 | + /// link — a count with no link is exactly what makes a term undeletable | ||
| 147 | + /// forever. The loser's row write matches nothing and the whole transaction | ||
| 148 | + /// aborts, so it claims nothing and answers 409. | ||
| 125 | #[must_use] | 149 | #[must_use] |
| 126 | pub fn refcount( | 150 | pub fn refcount( |
| 127 | mut self, | 151 | mut self, |
| 128 | field: &'static str, | 152 | field: &'static str, |
| 153 | + link: &'static str, | ||
| 154 | + expected: Option<RecordId>, | ||
| 129 | claim: Option<RecordId>, | 155 | claim: Option<RecordId>, |
| 130 | release: Option<RecordId>, | 156 | release: Option<RecordId>, |
| 131 | refused: AppError, | 157 | refused: AppError, |
| 132 | ) -> Self { | 158 | ) -> Self { |
| 133 | if claim.is_some() || release.is_some() { | 159 | if claim.is_some() || release.is_some() { |
| 134 | - self.refcount = Some((field, claim, release, refused)); | 160 | + self.refcount = Some((field, link, expected, claim, release, refused)); |
| 135 | } | 161 | } |
| 136 | self | 162 | self |
| 137 | } | 163 | } |
| @@ -173,7 +199,16 @@ impl FieldUpdate { | |||
| 173 | None => (None, None), | 199 | None => (None, None), |
| 174 | }; | 200 | }; |
| 175 | refused = refused.or(extra_refused); | 201 | refused = refused.or(extra_refused); |
| 176 | - let conditions: Vec<String> = ordered.into_iter().chain(extra).collect(); | 202 | + // Armed only for a move that actually shifts a counter, so a plain PATCH |
| 203 | + // — and a `term` PATCH that re-stated the link it already had — writes | ||
| 204 | + // the same unguarded `UPDATE` it always did. Probed on the mem engine: | ||
| 205 | + // a bound `None` comes through as `NONE` and `link = NONE` matches a row | ||
| 206 | + // whose option column was never set, while failing one that holds a | ||
| 207 | + // record, so the absent-link shape needs no `??`. | ||
| 208 | + let cas = moved | ||
| 209 | + .as_ref() | ||
| 210 | + .map(|(_, link, ..)| format!("{link} = $ref_expected")); | ||
| 211 | + let conditions: Vec<String> = ordered.into_iter().chain(extra).chain(cas).collect(); | ||
| 177 | let guard = if conditions.is_empty() { | 212 | let guard = if conditions.is_empty() { |
| 178 | String::new() | 213 | String::new() |
| 179 | } else { | 214 | } else { |
| @@ -186,10 +221,7 @@ impl FieldUpdate { | |||
| 186 | // its guard reads, and the loser wrote nothing, so re-sending it is the | 221 | // its guard reads, and the loser wrote nothing, so re-sending it is the |
| 187 | // recovery — see [`write_with_retry`]. | 222 | // recovery — see [`write_with_retry`]. |
| 188 | let rows: Vec<T> = match moved { | 223 | let rows: Vec<T> = match moved { |
| 189 | - Some((field, claim, release, ref_refused)) => { | 224 | + Some(moved) => run_with_refcount(db, &sql, self.bindings, moved).await?, |
| 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?, | 225 | None => write_with_retry(db, &sql, &self.bindings).await?, |
| 194 | }; | 226 | }; |
| 195 | // No row back means the guard bit (or, in the window after the handler's | 227 | // No row back means the guard bit (or, in the window after the handler's |
| @@ -212,15 +244,11 @@ impl FieldUpdate { | |||
| 212 | /// Admissible for [`transaction_with_retry`]: every statement is an `UPDATE`, | 244 | /// Admissible for [`transaction_with_retry`]: every statement is an `UPDATE`, |
| 213 | /// an `IF`/`THROW` or a `RETURN`, and none of those can answer "already | 245 | /// 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. | 246 | /// 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>( | 247 | async fn run_with_refcount<T: SurrealValue>( |
| 217 | db: &Database, | 248 | db: &Database, |
| 218 | update: &str, | 249 | update: &str, |
| 219 | mut bindings: Vec<(String, Value)>, | 250 | mut bindings: Vec<(String, Value)>, |
| 220 | - field: &'static str, | 251 | + (field, link, expected, claim, release, refused): Refcount, |
| 221 | - claim: Option<RecordId>, | ||
| 222 | - release: Option<RecordId>, | ||
| 223 | - refused: AppError, | ||
| 224 | ) -> Result<Vec<T>, AppError> { | 252 | ) -> Result<Vec<T>, AppError> { |
| 225 | // Parenthesized `??` throughout: `n ?? 0 + 1` parses as `n ?? (0 + 1)`. | 253 | // Parenthesized `??` throughout: `n ?? 0 + 1` parses as `n ?? (0 + 1)`. |
| 226 | // Both counter writes commit with the row write or neither does, so their | 254 | // Both counter writes commit with the row write or neither does, so their |
| @@ -239,13 +267,25 @@ async fn run_with_refcount<T: SurrealValue>( | |||
| 239 | statements.push(format!( | 267 | statements.push(format!( |
| 240 | "LET $seat = (UPDATE $ref_claim SET {field} = ({field} ?? 0) + 1 RETURN VALUE id)" | 268 | "LET $seat = (UPDATE $ref_claim SET {field} = ({field} ?? 0) + 1 RETURN VALUE id)" |
| 241 | )); | 269 | )); |
| 242 | - statements.push(format!("IF array::len($seat) = 0 {{ THROW '{CLAIM_MARK}' }}")); | 270 | + statements.push(format!( |
| 271 | + "IF array::len($seat) = 0 {{ THROW '{CLAIM_MARK}' }}" | ||
| 272 | + )); | ||
| 243 | bindings.push(("ref_claim".into(), claim.into_value())); | 273 | bindings.push(("ref_claim".into(), claim.into_value())); |
| 244 | } | 274 | } |
| 275 | + bindings.push(("ref_expected".into(), expected.into_value())); | ||
| 245 | statements.push(format!("LET $row = ({update})")); | 276 | statements.push(format!("LET $row = ({update})")); |
| 246 | // Without this the claim would outlive a row write that matched nothing — | 277 | // Without this the claim would outlive a row write that matched nothing — |
| 247 | - // the very leak the transaction exists to close. | 278 | + // the very leak the transaction exists to close. Nothing was written yet |
| 248 | - statements.push(format!("IF array::len($row) = 0 {{ THROW '{ROW_MARK}' }}")); | 279 | + // either way, so the probe that tells the two empty cases apart is free to |
| 280 | + // be another `UPDATE`: it matches only a row that is *there* and whose link | ||
| 281 | + // has moved off what the handler read, which is the CAS having bitten. A | ||
| 282 | + // deleted row and a plain guard refusal both miss it and keep the answer | ||
| 283 | + // they have always got. | ||
| 284 | + statements.push(format!( | ||
| 285 | + "IF array::len($row) = 0 {{ \ | ||
| 286 | + LET $live = (UPDATE $id WHERE {link} != $ref_expected RETURN VALUE id); \ | ||
| 287 | + IF array::len($live) = 0 {{ THROW '{ROW_MARK}' }} ELSE {{ THROW '{STALE_MARK}' }} }}" | ||
| 288 | + )); | ||
| 249 | statements.push("RETURN $row".into()); | 289 | statements.push("RETURN $row".into()); |
| 250 | let sql = format!( | 290 | let sql = format!( |
| 251 | "BEGIN TRANSACTION; {}; COMMIT TRANSACTION;", | 291 | "BEGIN TRANSACTION; {}; COMMIT TRANSACTION;", |
| @@ -257,13 +297,21 @@ async fn run_with_refcount<T: SurrealValue>( | |||
| 257 | // One counter write in flight at a time, like every other counter write. | 297 | // One counter write in flight at a time, like every other counter write. |
| 258 | let _guard = cap::counter_lock().await; | 298 | let _guard = cap::counter_lock().await; |
| 259 | let (mut result, mut errors) = | 299 | let (mut result, mut errors) = |
| 260 | - transaction_with_retry(db, &sql, &bindings, &[CLAIM_MARK, ROW_MARK]).await?; | 300 | + transaction_with_retry(db, &sql, &bindings, &[CLAIM_MARK, ROW_MARK, STALE_MARK]).await?; |
| 261 | if errors | 301 | if errors |
| 262 | .values() | 302 | .values() |
| 263 | .any(|error| error.to_string().contains(CLAIM_MARK)) | 303 | .any(|error| error.to_string().contains(CLAIM_MARK)) |
| 264 | { | 304 | { |
| 265 | return Err(refused); | 305 | return Err(refused); |
| 266 | } | 306 | } |
| 307 | + if errors | ||
| 308 | + .values() | ||
| 309 | + .any(|error| error.to_string().contains(STALE_MARK)) | ||
| 310 | + { | ||
| 311 | + return Err(AppError::Conflict( | ||
| 312 | + "the link this update moves changed since it was read; re-read and retry", | ||
| 313 | + )); | ||
| 314 | + } | ||
| 267 | if errors | 315 | if errors |
| 268 | .values() | 316 | .values() |
| 269 | .any(|error| error.to_string().contains(ROW_MARK)) | 317 | .any(|error| error.to_string().contains(ROW_MARK)) |
src/domain/note_file.rsmodified+80 -23
| @@ -154,31 +154,32 @@ impl NoteFile { | |||
| 154 | } | 154 | } |
| 155 | 155 | ||
| 156 | /// Persist the row assembled by [`Self::new`], refusing once its note | 156 | /// Persist the row assembled by [`Self::new`], refusing once its note |
| 157 | - /// already holds [`MAX_NOTE_FILES`]. The slot is taken by [`cap::claim`] on | 157 | + /// already holds [`MAX_NOTE_FILES`]. The slot and the row are taken together |
| 158 | - /// the note row: a `BEGIN…COMMIT` around a count can't enforce the cap | 158 | + /// by [`cap::claim_and_create`] on the note row: a `BEGIN…COMMIT` around a |
| 159 | - /// (SurrealDB doesn't conflict-check a cross-record count against a | 159 | + /// count can't enforce the cap (SurrealDB doesn't conflict-check a |
| 160 | - /// concurrent insert) and a process-wide mutex can't either, since it is | 160 | + /// cross-record count against a concurrent insert) and a process-wide mutex |
| 161 | - /// released around the very round trip the insert races — a conditional | 161 | + /// can't either, since it is released around the very round trip the insert |
| 162 | - /// single-record write can. | 162 | + /// races — a conditional single-record write can. Claiming in a *separate* |
| 163 | + /// query would enforce the cap but leak a slot on a crash between the two. | ||
| 163 | pub async fn insert(self, db: &Database) -> Result<NoteFile, AppError> { | 164 | pub async fn insert(self, db: &Database) -> Result<NoteFile, AppError> { |
| 164 | - let note = self.note.record(); | ||
| 165 | - if !cap::claim(¬e, NOTE_FILE_COUNT_FIELD, MAX_NOTE_FILES as i64, db).await? { | ||
| 166 | - return Err(AppError::Conflict( | ||
| 167 | - "the note already holds the maximum of 10 files — delete one first", | ||
| 168 | - )); | ||
| 169 | - } | ||
| 170 | // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber | 165 | // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber |
| 171 | - let created: Result<Option<NoteFile>, _> = db.create(self.id.record()).content(self).await; | 166 | + match cap::claim_and_create( |
| 172 | - match created { | 167 | + &self.note.record(), |
| 173 | - Ok(Some(created)) => Ok(created), | 168 | + NOTE_FILE_COUNT_FIELD, |
| 174 | - Ok(None) => { | 169 | + MAX_NOTE_FILES as i64, |
| 175 | - cap::release(¬e, NOTE_FILE_COUNT_FIELD, db).await?; | 170 | + &self.id.record(), |
| 176 | - Err(AppError::Internal("failed to create note file".into())) | 171 | + &self, |
| 177 | - } | 172 | + db, |
| 178 | - Err(err) => { | 173 | + ) |
| 179 | - cap::release(¬e, NOTE_FILE_COUNT_FIELD, db).await?; | 174 | + .await? |
| 180 | - Err(err.into()) | 175 | + { |
| 181 | - } | 176 | + cap::Claimed::Made(created) => Ok(created), |
| 177 | + // Also how a missing note reads: no note row means no slot to take. | ||
| 178 | + cap::Claimed::Full => Err(AppError::Conflict( | ||
| 179 | + "the note already holds the maximum of 10 files — delete one first", | ||
| 180 | + )), | ||
| 181 | + // Unreachable: the id is a ULID this call just generated. | ||
| 182 | + cap::Claimed::Duplicate => Err(AppError::Internal("failed to create note file".into())), | ||
| 182 | } | 183 | } |
| 183 | } | 184 | } |
| 184 | 185 | ||
| @@ -315,4 +316,60 @@ mod tests { | |||
| 315 | file.delete(&db).await.unwrap(); | 316 | file.delete(&db).await.unwrap(); |
| 316 | assert!(listed(¬e_a).await.is_empty()); | 317 | assert!(listed(¬e_a).await.is_empty()); |
| 317 | } | 318 | } |
| 319 | + | ||
| 320 | + /// The counter and the rows are written in one transaction, so the stored | ||
| 321 | + /// count must equal the stored rows — after a success *and* after the | ||
| 322 | + /// refusal that fills the cap, which must move neither. | ||
| 323 | + #[tokio::test] | ||
| 324 | + async fn counter_tracks_stored_rows() { | ||
| 325 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 326 | + let note = crate::domain::note::Note::create( | ||
| 327 | + &crate::domain::user::UserId::generate(), | ||
| 328 | + crate::domain::note::NoteTitle::try_new("a").unwrap(), | ||
| 329 | + crate::domain::note::NoteContent::try_new("body").unwrap(), | ||
| 330 | + &db, | ||
| 331 | + ) | ||
| 332 | + .await | ||
| 333 | + .unwrap() | ||
| 334 | + .get_id() | ||
| 335 | + .clone(); | ||
| 336 | + let stored_count = async |note: &NoteId| -> i64 { | ||
| 337 | + db.query("SELECT VALUE file_count FROM $note") | ||
| 338 | + .bind(("note", note.record())) | ||
| 339 | + .await | ||
| 340 | + .unwrap() | ||
| 341 | + .take::<Vec<i64>>(0) | ||
| 342 | + .unwrap() | ||
| 343 | + .into_iter() | ||
| 344 | + .next() | ||
| 345 | + .unwrap_or(0) | ||
| 346 | + }; | ||
| 347 | + let add = async |note: &NoteId| { | ||
| 348 | + NoteFile::new( | ||
| 349 | + note, | ||
| 350 | + FileName::try_new("plan.pdf").unwrap(), | ||
| 351 | + FileContentType::try_new("application/pdf").unwrap(), | ||
| 352 | + 3, | ||
| 353 | + ) | ||
| 354 | + .insert(&db) | ||
| 355 | + .await | ||
| 356 | + }; | ||
| 357 | + | ||
| 358 | + for filled in 1..=MAX_NOTE_FILES { | ||
| 359 | + add(¬e).await.unwrap(); | ||
| 360 | + assert_eq!(stored_count(¬e).await, filled as i64); | ||
| 361 | + assert_eq!( | ||
| 362 | + NoteFile::list_for(¬e, None, 0, &db).await.unwrap().1, | ||
| 363 | + filled as i64 | ||
| 364 | + ); | ||
| 365 | + } | ||
| 366 | + | ||
| 367 | + // At the cap: the refusal writes nothing, counter included. | ||
| 368 | + assert!(matches!(add(¬e).await, Err(AppError::Conflict(_)))); | ||
| 369 | + assert_eq!(stored_count(¬e).await, MAX_NOTE_FILES as i64); | ||
| 370 | + assert_eq!( | ||
| 371 | + NoteFile::list_for(¬e, None, 0, &db).await.unwrap().1, | ||
| 372 | + MAX_NOTE_FILES as i64 | ||
| 373 | + ); | ||
| 374 | + } | ||
| 318 | } | 375 | } |
src/domain/term.rsmodified+4 -1
| @@ -63,7 +63,10 @@ pub fn ref_move( | |||
| 63 | match patch { | 63 | match patch { |
| 64 | None => (None, None), | 64 | None => (None, None), |
| 65 | Some(next) if next.as_ref() == current => (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)), | 66 | + Some(next) => ( |
| 67 | + next.as_ref().map(TermId::record), | ||
| 68 | + current.map(TermId::record), | ||
| 69 | + ), | ||
| 67 | } | 70 | } |
| 68 | } | 71 | } |
| 69 | 72 | ||