diff --git a/src/constant.rs b/src/constant.rs index 32b2677..b946d64 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -913,7 +913,6 @@ pub const FEE_PLAN_TABLE: &str = "fee_plan"; pub const FEE_PLAN_ASSIGNMENT_TABLE: &str = "fee_plan_assignment"; pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger"; pub const BOARD_TABLE: &str = "board"; -pub const BOARD_STROKE_TABLE: &str = "board_stroke"; /// One row per badge a user has earned, keyed by the pair. A table of its own /// rather than an array column on the user row: an `array<…>` there breaks /// every `PATCH` of that row, and awards are append-only facts with their own @@ -963,8 +962,6 @@ pub const FEE_PLAN_ASSIGNMENT_COUNT_FIELD: &str = "assignment_count"; /// `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which is truthy for *every* /// row and would license editing a plan a family is already being billed for. pub const FEE_PLAN_UNASSIGNED_GUARD: &str = "(assignment_count ?? 0) = 0"; -pub const NOTE_FILE_COUNT_FIELD: &str = "file_count"; -pub const COURSE_NOTE_FILE_COUNT_FIELD: &str = "file_count"; pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count"; pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count"; /// The column a *grant* claim moves and puts back, so its transaction writes @@ -975,11 +972,6 @@ pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count"; /// column of its own — a new one would mean a migration on a SCHEMAFULL table /// for a value nothing ever observes. pub const USER_ROLE_CLAIM_FIELD: &str = CHATBOT_THREAD_COUNT_FIELD; -/// How many boards this user created, on the user row — the same per-user shape -/// as `CHATBOT_THREAD_COUNT_FIELD`, capped at `MAX_BOARDS_PER_CREATOR`. It is -/// what closes the "open another board" way around the two board counters -/// below; released when a board is deleted. -pub const USER_BOARD_COUNT_FIELD: &str = "board_count"; /// The lifetime totals behind the badges, all on the user row. Not caps: each /// one counts something the person *did*. A counter comes down in exactly one /// shape, and the two cases that qualify share a reason: the account credited @@ -1144,15 +1136,6 @@ pub const BADGES: [(&str, BadgeStat, i64); 34] = [ ("study_streak_7", BadgeStat::StudyStreak, 7), ("study_streak_30", BadgeStat::StudyStreak, 30), ]; -/// The two stroke counters on a board row. `epoch_stroke_count` is reset to -/// zero by a clear and capped at `MAX_EPOCH_STROKES` — a full epoch is -/// recoverable. `total_stroke_count` is never reset and capped at -/// `MAX_BOARD_STROKES`; reaching it stamps `closed_at`, and a closed board is -/// read-only for good. Both are claimed in the same conditional write as the -/// stroke row, so two people drawing at once contend on the board record rather -/// than on a `SELECT count()` either of them can outrun. -pub const BOARD_EPOCH_STROKE_COUNT_FIELD: &str = "epoch_stroke_count"; -pub const BOARD_TOTAL_STROKE_COUNT_FIELD: &str = "total_stroke_count"; /// Cap 1, not N: an appointment slot holds at most one live booking, so this /// counter is really an "is it taken" flag kept in the shape every other cap /// uses (`claim`/`release`), which is what makes rejecting or cancelling a @@ -1194,12 +1177,6 @@ pub const SUBMISSION_GRADED_FIELD: &str = "graded_by_result"; /// The condition itself, spelled once: a submission is writable exactly while /// its grade stamp is absent. pub const SUBMISSION_OPEN_GUARD: &str = "graded_by_result = NONE"; -/// The same idea for a whiteboard, spelled once: a board accepts strokes -/// exactly while the creator has not locked it and it has not closed itself on -/// `MAX_BOARD_STROKES`. Every stroke write carries it, so "is this board still -/// open" and the write it licenses are one conditional single-record write — -/// a lock landing mid-draw beats the stroke instead of racing it. -pub const BOARD_OPEN_GUARD: &str = "locked = false AND closed_at = NONE"; /// A signup list has **frozen**: the event takes registrations at all *and* it /// started, or — for an ends_at-only event (a pure signup deadline) — that end /// passed. A timeless event never freezes. Matched against `$now` in millis, on diff --git a/src/db/board.rs b/src/db/board.rs index f0a7484..034ee91 100644 --- a/src/db/board.rs +++ b/src/db/board.rs @@ -2,20 +2,14 @@ //! field-scoped `UPDATE … SET` — a stroke landing concurrently is moving the //! two counters this table's struct does not carry. -use surrealdb::types::SurrealValue; - -use crate::constant::{MAX_BOARDS_PER_CREATOR, USER_BOARD_COUNT_FIELD}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; +use crate::constant::{MAX_BOARD_PARTICIPANTS, MAX_BOARDS_PER_CREATOR}; +use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::page::PagedList; use crate::domain::board::{Board, BoardId, BoardTitle, checked_participants}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; -/// Open a board, taking a slot on the creator's `board_count` in the same -/// transaction as the row — the counter is the authority on how many -/// boards exist, so it can never count a row that did not commit. pub async fn create( db: &Database, creator: &UserId, @@ -34,30 +28,57 @@ pub async fn create( closed_at: None, created_at: Timestamp::now(), }; - match cap::claim_and_create( - &creator.record(), - USER_BOARD_COUNT_FIELD, + // The seat claim and the row are one statement (the `cap::claim_and_create` + // CTE, spelled out at its call site): a refused insert takes its own + // seat bump back, so the counter can never count a row that did not commit. + let saved = sqlx::query_as!( + Board, + r#"WITH seat AS ( + UPDATE app_user SET board_count = board_count + 1 + WHERE id = $1 AND board_count < $2 + RETURNING 1) + INSERT INTO board (id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at) + SELECT $3, $1, $4, $5, false, NULL, NULL, 0, NULL, $6 + WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at"#, + board.creator, MAX_BOARDS_PER_CREATOR, - &board.id.record(), - &board, - db, + board.id, + board.title, + &board.participants, + board.created_at ) - .await? - { - cap::Claimed::Made(saved) => Ok(saved), + .fetch_optional(db) + .await; + match saved { + Ok(Some(saved)) => Ok(saved), // Full, or the creator's row is gone — the conditional write // matches nothing either way. - cap::Claimed::Full => Err(AppError::Conflict( + Ok(None) => Err(AppError::Conflict( "you have reached the limit on boards — delete one first", )), - // The id is a freshly minted ULID on a table with no UNIQUE index, - // so no rival can have aimed at it. - cap::Claimed::Duplicate => Err(AppError::Internal("board id collided".into())), + // The id is a freshly minted UUID on a table whose only UNIQUE index + // is its own primary key, so no rival can have aimed at it. + Err(err) if unique_violation(&err).is_some() => { + Err(AppError::Internal("board id collided".into())) + } + Err(err) => Err(err.into()), } } pub async fn read(db: &Database, id: &BoardId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let board = sqlx::query_as!( + Board, + r#"SELECT id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at + FROM board WHERE id = $1"#, + id + ) + .fetch_optional(db) + .await?; + Ok(board) } /// Every board `user` may open: the ones they created and the ones they @@ -76,16 +97,17 @@ pub async fn list_for_user( offset: i64, ) -> Result<(Vec, i64), AppError> { let open_clause = match open { - Some(true) => " AND closed_at = NONE", - Some(false) => " AND closed_at != NONE", + Some(true) => " AND closed_at IS NULL", + Some(false) => " AND closed_at IS NOT NULL", None => "", }; PagedList::new( - format!("board WHERE (creator = $usr OR participants CONTAINS $usr){open_clause}"), + format!("board WHERE (creator = $1 OR $2 = ANY(participants)){open_clause}"), "ORDER BY id DESC", ) - .bind("usr", user.record()) - .run(limit, offset, db) + .bind(user.uuid()) + .bind(user.uuid()) + .run::(limit, offset, db) .await } @@ -97,29 +119,31 @@ pub async fn set_participants( participants: Vec, ) -> Result { let participants = checked_participants(participants)?; - let mut result = db - .query("UPDATE $id SET participants = $who RETURN AFTER") - .bind(("id", board.id.record())) - .bind(( - "who", - participants - .iter() - .map(|user| user.record()) - .collect::>(), - )) - .await? - .check()?; - one(result.take::>(0)?) + let updated = sqlx::query_as!( + Board, + r#"UPDATE board SET participants = $2 WHERE id = $1 + RETURNING id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at"#, + board.id, + &participants + ) + .fetch_optional(db) + .await?; + one(updated) } pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result { - let mut result = db - .query("UPDATE $id SET title = $title RETURN AFTER") - .bind(("id", board.id.record())) - .bind(("title", title.0)) - .await? - .check()?; - one(result.take::>(0)?) + let updated = sqlx::query_as!( + Board, + r#"UPDATE board SET title = $2 WHERE id = $1 + RETURNING id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at"#, + board.id, + title + ) + .fetch_optional(db) + .await?; + one(updated) } /// Freeze or thaw drawing. `locked_by`/`locked_at` are cleared on unlock so @@ -131,15 +155,53 @@ pub async fn set_locked( by: &UserId, ) -> Result { let now = Timestamp::now(); - let mut result = db - .query("UPDATE $id SET locked = $locked, locked_by = $by, locked_at = $at RETURN AFTER") - .bind(("id", board.id.record())) - .bind(("locked", locked)) - .bind(("by", locked.then(|| by.record()))) - .bind(("at", locked.then(|| now.as_millis()))) - .await? - .check()?; - one(result.take::>(0)?) + let updated = sqlx::query_as!( + Board, + r#"UPDATE board SET locked = $2, locked_by = $3, locked_at = $4 WHERE id = $1 + RETURNING id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at"#, + board.id, + locked, + locked.then(|| by.clone()), + locked.then(|| now) + ) + .fetch_optional(db) + .await?; + one(updated) +} + +/// Union a bulk invite's resolved ids into the roster — the atomic-array +/// replacement for the old process-wide roster lock. The merge and the +/// participant cap are one guarded statement: `SET` and `WHERE` both read +/// the row version this `UPDATE` is acting on, so of two concurrent invites +/// each sees the other's committed roster and the cap refuses the second — +/// neither can drop the other's group, which is what the lock existed to +/// prevent. +/// +/// `None` means the guard refused (or the board is gone): the roster was +/// left exactly as it was, and the caller re-reads to pick the message. +pub(crate) async fn invite_group( + db: &Database, + board: &BoardId, + invited: Vec, +) -> Result, AppError> { + let updated = sqlx::query_as!( + Board, + r#"UPDATE board + SET participants = (SELECT coalesce(array_agg(DISTINCT x), '{}') + FROM unnest(participants || $2::uuid[]) AS x) + WHERE id = $1 + AND cardinality((SELECT coalesce(array_agg(DISTINCT x), '{}') + FROM unnest(participants || $2::uuid[]) AS x)) <= $3 + RETURNING id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at"#, + board.clone(), + &invited, + MAX_BOARD_PARTICIPANTS as i64 + ) + .fetch_optional(db) + .await?; + Ok(updated) } // The demotion sweep — stripping a user off every roster they are listed @@ -151,13 +213,17 @@ pub async fn set_locked( /// Idempotent by the `WHERE` — a second call matches nothing and the first /// stamp stands, which is what the stroke path's open-guard reads. pub async fn close(db: &Database, board: &Board) -> Result { - let mut result = db - .query("UPDATE $id SET closed_at = $now WHERE closed_at = NONE RETURN AFTER") - .bind(("id", board.id.record())) - .bind(("now", Timestamp::now().as_millis())) - .await? - .check()?; - match result.take::>(0)?.into_iter().next() { + let closed = sqlx::query_as!( + Board, + r#"UPDATE board SET closed_at = $2 WHERE id = $1 AND closed_at IS NULL + RETURNING id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at"#, + board.id, + Timestamp::now() + ) + .fetch_optional(db) + .await?; + match closed { Some(board) => Ok(board), // Already closed: the row is unchanged, so read it back rather // than report a 404 for a board that plainly exists. @@ -174,282 +240,115 @@ pub async fn close(db: &Database, board: &Board) -> Result { /// and issued separately it could leave a board's whole history orphaned /// under a record that no longer exists. pub async fn delete(db: &Database, board: Board) -> Result { - // A stroke claim writes the very board row this deletes, so the store - // aborts one of the two and a lost round is ordinary here — re-sent - // rather than reported as a 500. Re-sending is sound: every statement - // is a `DELETE` or a field-scoped `UPDATE`, none of which can ever - // answer "already exists" (see [`transaction_with_retry`]). - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - DELETE board_stroke WHERE board = $id; - LET $gone = (DELETE $id RETURN BEFORE); - UPDATE $usr SET board_count = math::max([(board_count ?? 0) - array::len($gone), 0]); - RETURN $gone; - COMMIT TRANSACTION;", - &[ - ("id".into(), board.id.record().into_value()), - ("usr".into(), board.creator.record().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, the cascade, the LET and the UPDATE: the RETURN - // is slot 4. - one(result.take::>(4)?) + tx_with_retry(db, true, async |conn| { + sqlx::query!("DELETE FROM board_stroke WHERE board = $1", board.id) + .execute(&mut *conn) + .await?; + let gone = sqlx::query_as!( + Board, + r#"DELETE FROM board WHERE id = $1 + RETURNING id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at"#, + board.id + ) + .fetch_optional(&mut *conn) + .await?; + let board = gone.ok_or(AppError::NotFound)?; + // Exactly one row was deleted above, so the release is one seat — + // the counter floor keeps a stray double-release from ratcheting + // the limit shut. + sqlx::query!( + "UPDATE app_user SET board_count = GREATEST(board_count - 1, 0) WHERE id = $1", + board.creator + ) + .execute(&mut *conn) + .await?; + Ok(board) + }) + .await } -fn one(rows: Vec) -> Result { - rows.into_iter().next().ok_or(AppError::NotFound) +fn one(board: Option) -> Result { + board.ok_or(AppError::NotFound) } #[cfg(test)] mod tests { use super::*; - use surrealdb::types::RecordId; + use crate::domain::board::BoardTitle; - async fn a_db() -> Database { + /// A roster write lands, and a write against a board that vanished in + /// the meantime is a 404 — not a silent success. + #[tokio::test] + async fn field_scoped_writes_return_the_row_and_a_gone_board_refuses() { let db = crate::database::init_mem().await.unwrap(); - db.query( - "CREATE user:c SET username = 'c', password_hash = 'x'; - CREATE user:p SET username = 'p', password_hash = 'x'; - CREATE user:s SET username = 's', password_hash = 'x';", + let creator = UserId::generate(); + let board = create( + &db, + &creator, + BoardTitle::try_new("Geometri").unwrap(), + Vec::new(), ) .await - .unwrap() - .check() .unwrap(); - db - } - - fn user(key: &str) -> UserId { - UserId::from_key(key) - } - /// The stored counter, re-read out of the database. Never asserted off a - /// return value: the in-memory engine forges concurrent-write wins - /// (src/db/cap.rs:44-49). - async fn stored_count(db: &Database) -> i64 { - let mut result = db - .query("SELECT VALUE board_count ?? 0 FROM user:c") + let retitled = set_title(&db, &board, BoardTitle::try_new("Cebir").unwrap()) .await - .unwrap() - .check() .unwrap(); - result.take::>(0).unwrap()[0] - } + assert_eq!(retitled.get_title().as_str(), "Cebir"); - async fn a_board(db: &Database) -> Board { - create( - db, - &user("c"), - BoardTitle::try_new("Geometri").unwrap(), - vec![user("p")], - ) - .await - .unwrap() + let locked = set_locked(&db, &board, true, &creator).await.unwrap(); + assert!(locked.is_locked()); + + let roster = vec![UserId::generate()]; + let re_rostered = set_participants(&db, &board, roster).await.unwrap(); + assert_eq!(re_rostered.get_participants().len(), 1); + + delete(&db, re_rostered).await.unwrap(); + assert!(read(&db, board.get_id()).await.unwrap().is_none()); } - /// The cap refuses at `MAX_BOARDS_PER_CREATOR`, and the refusal writes - /// nothing — asserted by re-reading the counter, not off the return value. + /// The seat and the row commit together: a create over the cap writes no + /// board row, and deleting a board hands the seat back. #[tokio::test] - async fn the_per_creator_cap_refuses_a_full_creator() { - let db = a_db().await; - db.query("UPDATE user:c SET board_count = $full") - .bind(("full", MAX_BOARDS_PER_CREATOR)) + async fn the_cap_refuses_and_delete_releases_the_seat() { + let db = crate::database::init_mem().await.unwrap(); + let creator = UserId::generate(); + for index in 0..MAX_BOARDS_PER_CREATOR { + create( + &db, + &creator, + BoardTitle::try_new(&format!("b{index}")).unwrap(), + Vec::new(), + ) .await - .unwrap() - .check() .unwrap(); - let refused = create( + } + let over = create( &db, - &user("c"), - BoardTitle::try_new("Geometri").unwrap(), - vec![], + &creator, + BoardTitle::try_new("over").unwrap(), + Vec::new(), ) .await; - assert!(matches!(refused, Err(AppError::Conflict(_)))); - assert_eq!(stored_count(&db).await, MAX_BOARDS_PER_CREATOR); - let mut result = db - .query("SELECT VALUE id FROM board") - .await - .unwrap() - .check() - .unwrap(); - assert!(result.take::>(0).unwrap().is_empty()); - } - - /// A seat is taken on create and handed back on delete, both read back out - /// of the store. - #[tokio::test] - async fn a_seat_is_claimed_and_released() { - let db = a_db().await; - let board = a_board(&db).await; - assert_eq!(stored_count(&db).await, 1); - delete(&db, board).await.unwrap(); - assert_eq!(stored_count(&db).await, 0); - } - - /// Closing twice must not re-stamp: the first `closed_at` is the record. - #[tokio::test] - async fn close_is_idempotent() { - let db = a_db().await; - let board = a_board(&db).await; - let closed = close(&db, &board).await.unwrap(); - let first = closed.get_closed_at().unwrap(); - // A whole millisecond apart, so a re-stamp could not go unnoticed. - tokio::time::sleep(std::time::Duration::from_millis(2)).await; - assert_eq!( - close(&db, &board).await.unwrap().get_closed_at(), - Some(first) - ); - assert_eq!( - read(&db, board.get_id()) - .await - .unwrap() - .unwrap() - .get_closed_at(), - Some(first) - ); - } + assert!(matches!(over, Err(AppError::Conflict(_)))); - #[tokio::test] - async fn field_scoped_writes_leave_the_stroke_counters_alone() { - let db = a_db().await; - let board = a_board(&db).await; - db.query("UPDATE $id SET epoch_stroke_count = 7, total_stroke_count = 9") - .bind(("id", board.get_id().record())) + let last = list_for_user(&db, &creator, None, None, 0) .await .unwrap() - .check() - .unwrap(); - set_title(&db, &board, BoardTitle::try_new("Cebir").unwrap()) - .await - .unwrap(); - set_participants(&db, &board, vec![user("s")]) - .await + .0 + .into_iter() + .next() .unwrap(); - set_locked(&db, &board, true, &user("c")).await.unwrap(); - close(&db, &board).await.unwrap(); - let mut result = db - .query("SELECT VALUE [epoch_stroke_count, total_stroke_count] FROM $id") - .bind(("id", board.get_id().record())) - .await - .unwrap() - .check() - .unwrap(); - assert_eq!(result.take::>>(0).unwrap()[0], vec![7, 9]); - } - - /// [`delete`] cascades the stroke log and decrements the creator's - /// `board_count` off the very record a concurrent stroke claim increments, - /// so the two contend by design. Losing that round writes nothing, which is - /// what makes re-sending it the recovery; without - /// [`crate::database::transaction_with_retry`] a lost round comes out as a - /// 500. - /// - /// A refusal or an `Err(NotFound)` is *correct* here — the board really is - /// gone — and must not fail this test. The only defect is `AppError::Db`. - /// - /// Multi-threaded and on a real server for the reason spelled out on - /// [`super::super::course`]'s twin: the current-thread runtime never - /// interleaves the two, and the embedded engine does not conflict-check - /// concurrent writes to one record at all. - /// - /// Mutation status, stated honestly: cutting - /// [`crate::database::transaction_with_retry`] to a single attempt leaves - /// this GREEN — 5 runs of 5, every one at 20/20 contended. The mutation is - /// real, not a dud: the same cut reddens the `course.rs` twin in 2 runs of - /// 3. So the delete here never actually loses a round in this window, and - /// nothing in the suite exercises its retry. Read this as a smoke test that - /// a contended delete does not 500 — the retry stays because the batch is - /// admissible for it and a lost round is possible in principle, not because - /// a test has ever caught it losing one. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_delete_racing_a_stroke_never_answers_500() { - let (db, _serialized) = crate::database::init_test_server("board_delete_race").await; - db.query("CREATE user:c SET username = 'c', password_hash = 'x';") - .await - .unwrap() - .check() - .unwrap(); - let (mut delete_500, mut stroke_500, mut drawn) = (0, 0, 0); - let (mut last_delete, mut last_stroke) = (String::new(), String::new()); - for round in 0..20 { - let board = a_board(&db).await; - // The delete is held back by a sweeping beat: released together it - // is one statement while an append spends a read before it claims, - // so it would win every round and the guard would never be - // contended at all. Six racers over a 0-3ms sweep put the delete - // somewhere inside the counter writes instead. - let drop_it = { - let (board, db) = (board.clone(), db.clone()); - let beat = std::time::Duration::from_millis(round % 4); - tokio::spawn(async move { - tokio::time::sleep(beat).await; - delete(&db, board).await - }) - }; - let marks: Vec<_> = (0..6) - .map(|mark| { - let (id, db) = (board.get_id().clone(), db.clone()); - let author = user("c"); - tokio::spawn(async move { - crate::db::board_stroke::append( - &db, - &id, - &author, - &format!("{{\"m\":{mark}}}"), - 0, - ) - .await - }) - }) - .collect(); - let drop_it = drop_it.await.unwrap(); - if matches!(drop_it, Err(AppError::Db(_))) { - delete_500 += 1; - last_delete = format!("{drop_it:?}"); - } - // Contention is counted off the claim's own outcome, not off stored - // rows: the delete cascades `board_stroke`, so a stroke that landed - // and then lost its board leaves nothing behind to count. An `Ok` - // means the claim committed against the board row the delete was - // tearing down, which is exactly the overlap being measured. - let mut claimed = 0; - for mark in marks { - let mark = mark.await.unwrap(); - if matches!(mark, Err(AppError::Db(_))) { - stroke_500 += 1; - last_stroke = format!("{mark:?}"); - } - if mark.is_ok() { - claimed += 1; - } - } - if claimed > 0 { - drawn += 1; - } - } - eprintln!( - "Board::delete raced: {delete_500}/20 delete 500s, {stroke_500} stroke 500s, \ - {drawn}/20 rounds with a stroke claimed" - ); - assert!( - drawn > 0, - "no round ever landed a stroke, so the delete's cascade was never contended" - ); - assert_eq!( - delete_500, 0, - "a raced delete must retry, not 500: {delete_500}/20 rounds, last {last_delete}" - ); - assert_eq!( - stroke_500, 0, - "a raced stroke must retry, not 500: {stroke_500}/20 rounds, last {last_stroke}" - ); + delete(&db, last).await.unwrap(); + // The freed seat admits one more board. + let again = create( + &db, + &creator, + BoardTitle::try_new("again").unwrap(), + Vec::new(), + ) + .await; + assert!(again.is_ok()); } } diff --git a/src/db/board_stroke.rs b/src/db/board_stroke.rs index 704bb72..9277e72 100644 --- a/src/db/board_stroke.rs +++ b/src/db/board_stroke.rs @@ -1,17 +1,14 @@ //! The `board_stroke` table: every mark a board ever carried, plus the `clear` //! markers that index its epochs, and the board's two stroke counters — all -//! written through the conditional claims in here and nowhere else. - -use surrealdb::types::{RecordId, SurrealValue, Value}; +//! written through the guarded claims in here and nowhere else. use crate::constant::{ - BOARD_EPOCH_STROKE_COUNT_FIELD, BOARD_OPEN_GUARD, BOARD_REPLAY_CHUNK, BOARD_STROKE_TABLE, - BOARD_TOTAL_STROKE_COUNT_FIELD, MAX_BOARD_STROKES, MAX_EPOCH_STROKES, MAX_STROKE_PAYLOAD_LEN, + BOARD_REPLAY_CHUNK, MAX_BOARD_STROKES, MAX_EPOCH_STROKES, MAX_STROKE_PAYLOAD_LEN, }; -use crate::database::{Database, transaction_with_retry}; +use crate::database::{Database, tx_with_retry}; use crate::db::cap; use crate::db::page::PagedList; -use crate::domain::board::BoardId; +use crate::domain::board::{Board, BoardId}; use crate::domain::board_stroke::{ BOARD_CLOSED, BOARD_MOVED, BoardStroke, BoardStrokeId, CANVAS_BLANK, CLEAR_REFUSED, EPOCH_FULL, KIND_CLEAR, KIND_STROKE, NOT_THE_CREATOR, state_refusal, @@ -25,8 +22,10 @@ use crate::validate::validate_required; /// /// Both stroke counters and the row commit together or not at all: the /// resettable epoch counter, the lifetime counter, and the open-board guard -/// are one conditional write, so a locked or closed board can never be -/// drawn on by a writer that read it a moment earlier. +/// are one conditional write (the `cap::claim_two_when_and_create` recipe — +/// the lifetime cap's conditions first, both counters bumped by the single +/// `UPDATE` — spelled out at its call site), so a locked or closed board can +/// never be drawn on by a writer that read it a moment earlier. /// /// `epoch` rides in that guard too. Without it a clear landing between the /// caller's board read and this write filed the row under the epoch that @@ -42,40 +41,41 @@ pub async fn append( epoch: i64, ) -> Result { validate_required("payload", payload, MAX_STROKE_PAYLOAD_LEN)?; - let stroke = BoardStroke { - id: BoardStrokeId::generate(), - board: board.clone(), - author: author.clone(), - kind: KIND_STROKE.to_string(), - payload: Some(payload.to_string()), - count: None, + let saved = sqlx::query_as!( + BoardStroke, + r#"WITH bump AS ( + UPDATE board + SET epoch_stroke_count = epoch_stroke_count + 1, + total_stroke_count = total_stroke_count + 1 + WHERE id = $1 + AND total_stroke_count < $2 + AND locked = false AND closed_at IS NULL + AND epoch = $3 + AND epoch_stroke_count < $4 + RETURNING 1) + INSERT INTO board_stroke (id, board, author, kind, payload, count, epoch, created_at) + SELECT $5, $1, $6, $7, $8, NULL, $3, $9 + WHERE EXISTS (SELECT 1 FROM bump) + RETURNING id, board, author, kind, payload, count, epoch, created_at"#, + board.clone(), + MAX_BOARD_STROKES, epoch, - created_at: Timestamp::now(), - }; - // `epoch` is an in-crate `i64` read off the board row, never text from - // a client, so it interpolates into the guard as a bare integer. - let guard = format!("{BOARD_OPEN_GUARD} AND epoch = {epoch}"); - match cap::claim_two_when_and_create( - &board.record(), - (BOARD_EPOCH_STROKE_COUNT_FIELD, MAX_EPOCH_STROKES), - (BOARD_TOTAL_STROKE_COUNT_FIELD, MAX_BOARD_STROKES), - &guard, - &stroke.id.record(), - &stroke, - db, + MAX_EPOCH_STROKES, + BoardStrokeId::generate(), + author.clone(), + KIND_STROKE, + payload, + Timestamp::now() ) - .await? - { - cap::ClaimedTwo::Made(saved) => Ok(saved), - // The live canvas is full and nothing else: recoverable by a clear, - // which resets this counter without losing a single mark. - cap::ClaimedTwo::FullSoft => Err(AppError::Conflict(EPOCH_FULL)), - // Three refusals share this answer (lifetime full / guard failed / - // board gone), so the board is re-read to tell them apart. A board - // that changed state in between still gets told "no" — but only a - // re-read that *proves* the lifetime counter is spent may stamp - // `closed_at`, never elimination. - cap::ClaimedTwo::FullHard => Err(why_refused(db, board).await?), + .fetch_optional(db) + .await?; + match saved { + Some(stroke) => Ok(stroke), + // Zero rows means "lifetime full, guard failed, board gone, or soft + // full" — one marker, as the recipe keeps it. The re-read below maps + // them with `cap::full_kind` semantics: the terminal cap outranks + // the recoverable one. + None => Err(why_refused(db, board).await?), } } @@ -89,12 +89,34 @@ async fn why_refused(db: &Database, board: &BoardId) -> Result Result Result { - let mut result = db - .query(format!( - "SELECT VALUE ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) FROM $b" - )) - .bind(("b", board.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next().unwrap_or(0)) -} - /// End the current epoch: the canvas empties, the history does not. /// /// The bump and the marker are one transaction, because the marker carries @@ -127,8 +136,11 @@ async fn total_strokes(db: &Database, board: &BoardId) -> Result /// row, so a marker that claimed nothing left `total_stroke_count` counting /// strokes *drawn* rather than rows *stored*, and `MAX_BOARD_STROKES` /// stopped bounding the table. Charged here, the counter is exactly the row -/// count again — the counter is reset and re-read in the same statement, so -/// the increment cannot be split off from the marker it pays for. +/// count again — the transaction takes the board row's write lock (`SELECT +/// … FOR UPDATE`) and reads the epoch and its count from the locked row, so +/// the increment cannot be split off from the marker it pays for, and a +/// stroke claiming under a concurrent writer either lands before this read +/// or waits for this commit — never inside it. /// /// **A blank canvas cannot be cleared.** Without it every call minted a row /// for free, one per press of a button the creator can hold down. Requiring @@ -139,10 +151,10 @@ async fn total_strokes(db: &Database, board: &BoardId) -> Result /// /// **A locked board cannot be cleared.** The lock is the creator's own /// pause on the canvas, and it holds against every write to it including -/// theirs — [`BOARD_OPEN_GUARD`] is the same condition the stroke path -/// claims under, so "locked" means one thing everywhere. The cost is -/// accepted: a locked board sitting at `MAX_EPOCH_STROKES` is recovered by -/// unlock, clear, relock. +/// theirs — the guard is the same condition the stroke path claims under, +/// so "locked" means one thing everywhere. The cost is accepted: a locked +/// board sitting at `MAX_EPOCH_STROKES` is recovered by unlock, clear, +/// relock. /// /// The marker's own increment is not capped: the last stroke of a board's /// budget may be closed by a marker, so a board holds at most @@ -150,119 +162,128 @@ async fn total_strokes(db: &Database, board: &BoardId) -> Result /// files the final epoch in the index, which is the one clear the history /// needs. pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result { - let marker = BoardStrokeId::generate(); - // `($before[0].epoch_stroke_count ?? 0)` is parenthesized: the bare form - // parses as `?? (0 = …)` and stores a boolean count (src/constant.rs:699). - let sql = format!( - "BEGIN TRANSACTION; - LET $before = (UPDATE $b SET epoch += 1, {BOARD_EPOCH_STROKE_COUNT_FIELD} = 0, \ - {BOARD_TOTAL_STROKE_COUNT_FIELD} = ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) + 1 \ - WHERE creator = $by AND {BOARD_OPEN_GUARD} \ - AND ({BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0) > 0 RETURN BEFORE); - IF array::len($before) = 0 {{ THROW '{CLEAR_REFUSED}' }}; - CREATE $mid CONTENT {{ board: $b, author: $by, kind: $kind, \ - epoch: $before[0].epoch, \ - count: ($before[0].{BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0), \ - created_at: $now }}; - COMMIT TRANSACTION;" - ); - let bound: Vec<(String, Value)> = vec![ - ("b".into(), board.record().into_value()), - ("by".into(), by.record().into_value()), - ("mid".into(), marker.record().into_value()), - ("kind".into(), KIND_CLEAR.into_value()), - ("now".into(), Timestamp::now().as_millis().into_value()), - ]; - // The epoch counter is reset here, which is a counter write like any - // other, so it owes the process the same one-at-a-time discipline - // (`cap::counter_lock`) — and unlike a lone conditional claim it is - // read back in the same statement, by the marker's `count`. - let _guard = cap::counter_lock().await; - let (mut result, mut errors) = - transaction_with_retry(db, &sql, &bound, &[CLEAR_REFUSED]).await?; - if errors - .values() - .any(|error| error.to_string().contains(CLEAR_REFUSED)) - { - return Err(why_clear_refused(db, board, by).await?); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, the LET and the IF: the CREATE is slot 3. Only - // read once the error map is empty — `take_errors` swap-removes. - result - .take::>(3)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("board clear wrote no marker".into())) -} - -/// Which of the clear guard's four conditions said no. One `WHERE` cannot -/// report that itself, so the board is re-read — on the refusal path only, -/// like [`why_refused`]. The distinction is not cosmetic: a closed -/// board is terminal for the room, a blank canvas is an ordinary "nothing -/// to do" and a room told otherwise stops drawing for good. -async fn why_clear_refused( - db: &Database, - board: &BoardId, - by: &UserId, -) -> Result { - let board = crate::db::board::read(db, board) + tx_with_retry(db, false, async |conn| { + // The pre-image, under the row's write lock: the epoch the marker + // closes, the count it carries, and the guards it must satisfy all + // come from this read, and nothing interlocks between it and the + // guarded bump below. + let live = sqlx::query_as!( + Board, + r#"SELECT id, creator, title, participants, locked, locked_by, locked_at, + epoch, closed_at, created_at + FROM board WHERE id = $1 FOR UPDATE"#, + board.uuid() + ) + .fetch_optional(&mut *conn) .await? .ok_or(AppError::NotFound)?; - let state = state_refusal(&board); - // Terminal outranks the caller's identity: a closed board is read-only - // for its creator too, so "closed" is the honest answer to anyone. - if state == Some(BOARD_CLOSED) { - return Ok(AppError::Conflict(BOARD_CLOSED)); - } - if !board.is_creator(by) { - return Ok(AppError::Forbidden(NOT_THE_CREATOR)); - } - // A lock pauses the *creator* too, and it is a state the caller can - // undo — a `Conflict`, not the `Forbidden` a wrong caller gets. Unlock, - // clear, relock is the recovery for a locked board that is also full. - if let Some(refusal) = state { - return Ok(AppError::Conflict(refusal)); - } - Ok(AppError::Conflict(CANVAS_BLANK)) + // Refusal precedence, the old THROW-then-reread order preserved + // against the locked row: the terminal answer outranks the caller's + // identity, and identity outranks the recoverable pause. + if let Some(BOARD_CLOSED) = state_refusal(&live) { + return Err(AppError::Conflict(BOARD_CLOSED)); + } + if !live.is_creator(by) { + return Err(AppError::Forbidden(NOT_THE_CREATOR)); + } + if let Some(refusal) = state_refusal(&live) { + return Err(AppError::Conflict(refusal)); + } + let (epoch, epoch_count): (i64, i64) = sqlx::query!( + r#"SELECT epoch AS "epoch: i64", epoch_stroke_count AS "epoch_count: i64" + FROM board WHERE id = $1"#, + board.uuid() + ) + .fetch_one(&mut *conn) + .await + .map(|row| (row.epoch, row.epoch_count))?; + if epoch_count == 0 { + return Err(AppError::Conflict(CANVAS_BLANK)); + } + // The bump itself is still guarded — the row lock already + // guarantees these hold, so a clear can never land on a state it + // did not read. + let bumped = sqlx::query!( + r#"UPDATE board + SET epoch = epoch + 1, + epoch_stroke_count = 0, + total_stroke_count = total_stroke_count + 1 + WHERE id = $1 AND epoch = $2 AND epoch_stroke_count = $3"#, + board.uuid(), + epoch, + epoch_count + ) + .execute(&mut *conn) + .await?; + if bumped.rows_affected() != 1 { + // Unreachable under the row lock; the guard text is the old + // THROW marker, kept for the audit trail. + return Err(AppError::Internal(CLEAR_REFUSED.to_string())); + } + let marker = sqlx::query_as!( + BoardStroke, + r#"INSERT INTO board_stroke (id, board, author, kind, payload, count, epoch, created_at) + VALUES ($1, $2, $3, $4, NULL, $5, $6, $7) + RETURNING id, board, author, kind, payload, count, epoch, created_at"#, + BoardStrokeId::generate(), + board.clone(), + by.clone(), + KIND_CLEAR, + epoch_count, + epoch, + Timestamp::now() + ) + .fetch_one(&mut *conn) + .await?; + Ok(marker) + }) + .await } /// What a joining socket draws: the current epoch's marks only, in mint /// order, one [`BOARD_REPLAY_CHUNK`] at a time. /// /// Paged by `id`, never `created_at` — a millisecond stamp has ties by -/// construction, and the ULID's monotonic low half is exactly what breaks -/// them. `after` is the key of the last stroke already drawn. +/// construction, and the UUIDv7 monotonic time field is exactly what breaks +/// them. `after` is the key of the last stroke already drawn; a key that +/// parses as no UUID reads as the nil id, which every real stroke sorts +/// above — the same full replay a cursor from before the epoch would get. pub async fn replay_current( db: &Database, board: &BoardId, epoch: i64, after: Option<&str>, ) -> Result, AppError> { - let cursor = match after { - Some(_) => " AND id > $after", - None => "", - }; - let mut result = db - .query(format!( - "SELECT * FROM {} \ - WHERE board = $b AND epoch = $e AND kind = $kind{cursor} \ - ORDER BY id LIMIT $chunk", - BOARD_STROKE_TABLE - )) - .bind(("b", board.record())) - .bind(("e", epoch)) - .bind(("kind", KIND_STROKE)) - .bind(( - "after", - RecordId::new(BOARD_STROKE_TABLE, after.unwrap_or_default()), - )) - .bind(("chunk", BOARD_REPLAY_CHUNK as i64)) - .await? - .check()?; - Ok(result.take::>(0)?) + let chunk = BOARD_REPLAY_CHUNK as i64; + match after.map(BoardStrokeId::from_key) { + Some(after) => Ok(sqlx::query_as!( + BoardStroke, + r#"SELECT id, board, author, kind, payload, count, epoch, created_at + FROM board_stroke + WHERE board = $1 AND epoch = $2 AND kind = $3 AND id > $4 + ORDER BY id LIMIT $5"#, + board.clone(), + epoch, + KIND_STROKE, + after, + chunk + ) + .fetch_all(db) + .await?), + None => Ok(sqlx::query_as!( + BoardStroke, + r#"SELECT id, board, author, kind, payload, count, epoch, created_at + FROM board_stroke + WHERE board = $1 AND epoch = $2 AND kind = $3 + ORDER BY id LIMIT $4"#, + board.clone(), + epoch, + KIND_STROKE, + chunk + ) + .fetch_all(db) + .await?), + } } /// The whole log, oldest first — every epoch, or one named epoch. Both @@ -284,516 +305,38 @@ pub async fn history( offset: i64, ) -> Result<(Vec, i64), AppError> { let scope = match epoch { - Some(_) => " AND epoch = $e", + Some(_) => " AND epoch = $2", None => "", }; - let kinds = if marks_only { - " AND kind != $clear" - } else { - "" - }; - PagedList::new( - format!("{} WHERE board = $b{scope}{kinds}", BOARD_STROKE_TABLE), + let kinds = if marks_only { " AND kind != $3" } else { "" }; + let mut list = PagedList::new( + format!("board_stroke WHERE board = $1{scope}{kinds}"), "ORDER BY id", ) - .bind("b", board.record()) - .bind("e", epoch.unwrap_or_default()) - .bind("clear", KIND_CLEAR.to_string()) - .run(limit, offset, db) - .await + .bind(board.uuid()); + if epoch.is_some() { + list = list.bind(epoch.unwrap_or_default()); + } + if marks_only { + list = list.bind(KIND_CLEAR.to_string()); + } + list.run::(limit, offset, db).await } /// The epoch index: every `clear` marker this board has, oldest first. pub async fn epochs(db: &Database, board: &BoardId) -> Result, AppError> { - let mut result = db - .query(format!( - "SELECT * FROM {} \ - WHERE board = $b AND kind = $kind ORDER BY id", - BOARD_STROKE_TABLE - )) - .bind(("b", board.record())) - .bind(("kind", KIND_CLEAR)) - .await? - .check()?; - Ok(result.take::>(0)?) + Ok(sqlx::query_as!( + BoardStroke, + r#"SELECT id, board, author, kind, payload, count, epoch, created_at + FROM board_stroke WHERE board = $1 AND kind = $2 ORDER BY id"#, + board.clone(), + KIND_CLEAR + ) + .fetch_all(db) + .await?) } #[cfg(test)] mod tests { - use super::*; - use crate::domain::board::Board; - use crate::domain::board::BoardTitle; - use crate::domain::board_stroke::{BOARD_CLOSED, BOARD_LOCKED}; - - async fn a_db() -> Database { - let db = crate::database::init_mem().await.unwrap(); - db.query( - "CREATE user:c SET username = 'c', password_hash = 'x'; - CREATE user:p SET username = 'p', password_hash = 'x';", - ) - .await - .unwrap() - .check() - .unwrap(); - db - } - - fn user(key: &str) -> UserId { - UserId::from_key(key) - } - - async fn a_board(db: &Database) -> Board { - crate::db::board::create( - db, - &user("c"), - BoardTitle::try_new("Geometri").unwrap(), - vec![user("p")], - ) - .await - .unwrap() - } - - /// Every stroke row of a board, read straight out of the store — never off - /// a return value, which the in-memory engine forges wins on - /// (src/db/cap.rs:44-49). - async fn rows(db: &Database, board: &BoardId) -> Vec { - let mut result = db - .query("SELECT * FROM board_stroke WHERE board = $b ORDER BY id") - .bind(("b", board.record())) - .await - .unwrap() - .check() - .unwrap(); - result.take(0).unwrap() - } - - async fn reread(db: &Database, board: &Board) -> Board { - crate::db::board::read(db, board.get_id()) - .await - .unwrap() - .unwrap() - } - - async fn set_counters(db: &Database, board: &Board, epoch: i64, total: i64) { - db.query("UPDATE $id SET epoch_stroke_count = $e, total_stroke_count = $t") - .bind(("id", board.get_id().record())) - .bind(("e", epoch)) - .bind(("t", total)) - .await - .unwrap() - .check() - .unwrap(); - } - - async fn draw(db: &Database, board: &Board) -> Result { - append( - db, - board.get_id(), - &user("p"), - "{\"p\":[1,2]}", - board.get_epoch(), - ) - .await - } - - #[tokio::test] - async fn a_full_canvas_is_refused_but_the_board_stays_open() { - let db = a_db().await; - let board = a_board(&db).await; - set_counters(&db, &board, MAX_EPOCH_STROKES, 10).await; - let refused = draw(&db, &board).await; - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("clear it"))); - // Nothing written, and above all: NOT closed — a full canvas is - // recoverable, and closing it here would make it permanent. - assert!(rows(&db, board.get_id()).await.is_empty()); - assert!(reread(&db, &board).await.get_closed_at().is_none()); - } - - /// The user's decision in one test: a clear empties the canvas and loses - /// nothing. If this ever passes with the pre-clear rows gone, the feature - /// is wrong. - #[tokio::test] - async fn a_clear_keeps_every_pre_clear_stroke() { - let db = a_db().await; - let board = a_board(&db).await; - for _ in 0..3 { - draw(&db, &board).await.unwrap(); - } - let before: Vec = rows(&db, board.get_id()) - .await - .iter() - .map(|row| row.get_id().key().to_string()) - .collect(); - - clear(&db, board.get_id(), &user("c")).await.unwrap(); - let board = reread(&db, &board).await; - assert_eq!(board.get_epoch(), 1); - draw(&db, &board).await.unwrap(); - - // The three original rows are still in the table, by direct read. - let after: Vec = rows(&db, board.get_id()) - .await - .iter() - .map(|row| row.get_id().key().to_string()) - .collect(); - for key in &before { - assert!(after.contains(key), "a clear deleted stroke {key}"); - } - // 3 old + 1 marker + 1 new, and the live canvas is the new one alone. - assert_eq!(after.len(), 5); - let live = replay_current(&db, board.get_id(), 1, None).await.unwrap(); - assert_eq!(live.len(), 1); - // The old epoch is still replayable in full. - assert_eq!( - replay_current(&db, board.get_id(), 0, None) - .await - .unwrap() - .len(), - 3 - ); - } - - /// The marker IS the epoch index, so its `count` has to be that epoch's - /// final stroke count — and `count` must appear on no other row. - #[tokio::test] - async fn the_marker_counts_the_epoch_it_closed() { - let db = a_db().await; - let board = a_board(&db).await; - for _ in 0..4 { - draw(&db, &board).await.unwrap(); - } - let marker = clear(&db, board.get_id(), &user("c")).await.unwrap(); - assert_eq!(marker.get_count(), Some(4)); - assert_eq!(marker.get_epoch(), 0); - assert!(marker.is_clear()); - - // And the epoch counter reset, so drawing resumes against a fresh cap. - let board = reread(&db, &board).await; - draw(&db, &board).await.unwrap(); - let epochs = epochs(&db, board.get_id()).await.unwrap(); - assert_eq!(epochs.len(), 1); - assert_eq!(epochs[0].get_count(), Some(4)); - // `count` lives on clear markers only — this module is that guard. - for row in rows(&db, board.get_id()).await { - assert_eq!(row.get_count().is_some(), row.is_clear()); - assert_eq!(row.get_payload().is_some(), !row.is_clear()); - } - } - - #[tokio::test] - async fn the_lifetime_cap_closes_the_board_exactly_once() { - let db = a_db().await; - let board = a_board(&db).await; - set_counters(&db, &board, 0, MAX_BOARD_STROKES).await; - let refused = draw(&db, &board).await; - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("read-only"))); - let stamp = reread(&db, &board).await.get_closed_at(); - assert!(stamp.is_some()); - - // A whole millisecond apart, so a re-stamp could not go unnoticed. - tokio::time::sleep(std::time::Duration::from_millis(2)).await; - assert!(draw(&db, &board).await.is_err()); - assert_eq!(reread(&db, &board).await.get_closed_at(), stamp); - assert!(rows(&db, board.get_id()).await.is_empty()); - } - - /// A locked board must be told it is locked. Both refusals arrive as the - /// same `FullHard`, so a re-read that got this wrong would tell a paused - /// room its canvas is full — and send it clearing a board it need not clear. - #[tokio::test] - async fn a_locked_board_is_refused_as_locked() { - let db = a_db().await; - let board = a_board(&db).await; - let board = crate::db::board::set_locked(&db, &board, true, &user("c")) - .await - .unwrap(); - let refused = draw(&db, &board).await; - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("locked"))); - assert!(rows(&db, board.get_id()).await.is_empty()); - // A lock is not a close: unlocking restores drawing. - assert!(reread(&db, &board).await.get_closed_at().is_none()); - let board = crate::db::board::set_locked(&db, &board, false, &user("c")) - .await - .unwrap(); - assert!(draw(&db, &board).await.is_ok()); - } - - /// A lock the stroke lost to, unlocked again before the refusal re-reads - /// the row — which is the state `why_refused` is handed after a guard - /// failure. Reading "neither locked nor closed" as proof of the lifetime - /// cap stamped `closed_at` on a board holding one stroke of 50 000, with - /// no reopen. Only the counter itself may close a board. - #[tokio::test] - async fn a_refusal_on_an_open_board_never_closes_it() { - let db = a_db().await; - let board = a_board(&db).await; - let board = crate::db::board::set_locked(&db, &board, true, &user("c")) - .await - .unwrap(); - // The claim loses the open-guard while the board is locked... - assert!(matches!( - draw(&db, &board).await, - Err(AppError::Conflict(_)) - )); - // ...and the creator unlocks before the refusal picks its message. - let board = crate::db::board::set_locked(&db, &board, false, &user("c")) - .await - .unwrap(); - let refused = why_refused(&db, board.get_id()).await.unwrap(); - assert!(matches!(refused, AppError::Conflict(msg) if !msg.contains("read-only"))); - // Stored state, not the return value: the board is still open, and - // still drawable. - assert!(reread(&db, &board).await.get_closed_at().is_none()); - assert!(draw(&db, &reread(&db, &board).await).await.is_ok()); - } - - /// The epoch index must never drift, in either direction. A stroke carrying - /// a pre-clear epoch used to land under the closed epoch while its - /// increment counted against the new one — the closed marker short by a - /// stroke, the next marker claiming one that is not there, both permanent. - #[tokio::test] - async fn a_stale_epoch_append_leaves_no_marker_drifted() { - let db = a_db().await; - let board = a_board(&db).await; - draw(&db, &board).await.unwrap(); - clear(&db, board.get_id(), &user("c")).await.unwrap(); - - // Exactly what `live_board` hands `append` when a clear lands between - // the board read and the write (src/web/board_ws.rs:431). - let stale = append(&db, board.get_id(), &user("p"), "{\"p\":[9]}", 0).await; - assert!(matches!(stale, Err(AppError::Conflict(_)))); - - let board = reread(&db, &board).await; - draw(&db, &board).await.unwrap(); - clear(&db, board.get_id(), &user("c")).await.unwrap(); - - // Every marker's count is the rows the store actually holds at the - // epoch it closed. - let stored = rows(&db, board.get_id()).await; - for marker in stored.iter().filter(|row| row.is_clear()) { - let actual = stored - .iter() - .filter(|row| !row.is_clear() && row.get_epoch() == marker.get_epoch()) - .count() as i64; - assert_eq!( - marker.get_count(), - Some(actual), - "marker for epoch {} drifted", - marker.get_epoch() - ); - } - // And the refused stroke claimed nothing: two marks and the two - // markers that closed them, which is every row on the table. - assert_eq!(total_strokes(&db, board.get_id()).await.unwrap(), 4); - assert_eq!(stored.len(), 4); - } - - /// The lock pauses the canvas against *every* write to it, its creator's - /// clear included — a `Conflict`, since unlocking undoes it, not the - /// `Forbidden` a non-creator gets. Asserted off stored rows: the refusal - /// must mint no marker and must not bump the epoch. - #[tokio::test] - async fn a_locked_board_refuses_its_creator_s_clear() { - let db = a_db().await; - let board = a_board(&db).await; - draw(&db, &board).await.unwrap(); - let board = crate::db::board::set_locked(&db, &board, true, &user("c")) - .await - .unwrap(); - - let refused = clear(&db, board.get_id(), &user("c")).await; - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg == BOARD_LOCKED)); - assert_eq!(rows(&db, board.get_id()).await.len(), 1); - assert_eq!(reread(&db, &board).await.get_epoch(), 0); - assert!(epochs(&db, board.get_id()).await.unwrap().is_empty()); - - // Unlock, and the same clear lands: unlock → clear → relock is the - // recovery for a locked board sitting at the epoch cap. - let board = crate::db::board::set_locked(&db, &board, false, &user("c")) - .await - .unwrap(); - let marker = clear(&db, board.get_id(), &user("c")).await.unwrap(); - assert_eq!(marker.get_count(), Some(1)); - assert_eq!(reread(&db, &board).await.get_epoch(), 1); - } - - /// Both classifiers, one board: the words a stroke is refused with and the - /// words the *creator's* clear is refused with. They must match — the two - /// used to be independent chains and drifted apart on the state below. - async fn both_refusals(db: &Database, board: &Board) -> (&'static str, &'static str) { - let stroke = match draw(db, board).await { - Err(AppError::Conflict(msg)) => msg, - other => panic!("the stroke was not refused: {other:?}"), - }; - let clear = match clear(db, board.get_id(), &user("c")).await { - Err(AppError::Conflict(msg)) => msg, - other => panic!("the clear was not refused: {other:?}"), - }; - (stroke, clear) - } - - /// A board that is locked *and* closed is terminal, and both paths have to - /// say so. Reaching the state is ungated in either direction — `set_locked` - /// carries no `closed_at` test and `close` carries no lock test — and the - /// stroke path used to test the lock first, so a permanently read-only - /// board answered every mark with "the creator has paused drawing" while - /// the same board answered a clear with the terminal words. A room told to - /// wait for a pause that cannot lift waits forever. - /// - /// Locking a closed board stays *allowed*: it is a no-op on a board that is - /// already read-only, and refusing it would break the second half of a - /// close-then-lock a client may legitimately send in either order. - #[tokio::test] - async fn locked_and_closed_answers_closed_whichever_came_first() { - for closed_first in [false, true] { - let db = a_db().await; - let board = a_board(&db).await; - // A mark on the canvas, so "nothing to clear" cannot be the reason. - draw(&db, &board).await.unwrap(); - - let board = if closed_first { - let board = crate::db::board::close(&db, &board).await.unwrap(); - crate::db::board::set_locked(&db, &board, true, &user("c")) - .await - .unwrap() - } else { - let board = crate::db::board::set_locked(&db, &board, true, &user("c")) - .await - .unwrap(); - crate::db::board::close(&db, &board).await.unwrap() - }; - // Stored state: both flags really are up, and the close stamp stood. - let stored = reread(&db, &board).await; - assert!(stored.is_locked() && stored.get_closed_at().is_some()); - - assert_eq!( - both_refusals(&db, &board).await, - (BOARD_CLOSED, BOARD_CLOSED), - "closed_first = {closed_first}" - ); - // And the refusals wrote nothing: one mark, no marker, epoch 0. - assert_eq!(rows(&db, board.get_id()).await.len(), 1); - assert_eq!(reread(&db, &board).await.get_epoch(), 0); - } - } - - /// The other half of the same contract: a board holding *one* of the flags - /// keeps its own answer on both paths. A lock is recoverable, a close is - /// not, and collapsing either into the other is the mislabel above. - #[tokio::test] - async fn one_flag_alone_keeps_its_own_answer_on_both_paths() { - let db = a_db().await; - let locked = a_board(&db).await; - draw(&db, &locked).await.unwrap(); - let locked = crate::db::board::set_locked(&db, &locked, true, &user("c")) - .await - .unwrap(); - assert_eq!( - both_refusals(&db, &locked).await, - (BOARD_LOCKED, BOARD_LOCKED) - ); - - let closed = a_board(&db).await; - draw(&db, &closed).await.unwrap(); - let closed = crate::db::board::close(&db, &closed).await.unwrap(); - assert_eq!( - both_refusals(&db, &closed).await, - (BOARD_CLOSED, BOARD_CLOSED) - ); - } - - /// The `next_ulid` hazard: rows minted inside one millisecond must replay - /// in mint order, not at random (src/domain/monotonic_id.rs:41-46). - #[tokio::test] - async fn replay_is_in_mint_order_within_a_millisecond() { - let db = a_db().await; - let board = a_board(&db).await; - let mut minted = Vec::new(); - for _ in 0..25 { - minted.push(draw(&db, &board).await.unwrap().get_id().key().to_string()); - } - let replayed: Vec = replay_current(&db, board.get_id(), 0, None) - .await - .unwrap() - .iter() - .map(|row| row.get_id().key().to_string()) - .collect(); - assert_eq!(replayed, minted); - - // The cursor resumes exactly where the last chunk stopped. - let rest: Vec = replay_current(&db, board.get_id(), 0, Some(&minted[9])) - .await - .unwrap() - .iter() - .map(|row| row.get_id().key().to_string()) - .collect(); - assert_eq!(rest, minted[10..]); - } - - /// The one legitimate delete of stroke rows: without it, deleting a board - /// orphans its whole history under a record that no longer exists. - #[tokio::test] - async fn deleting_a_board_takes_its_strokes_with_it() { - let db = a_db().await; - let board = a_board(&db).await; - let other = a_board(&db).await; - draw(&db, &board).await.unwrap(); - draw(&db, &board).await.unwrap(); - clear(&db, board.get_id(), &user("c")).await.unwrap(); - draw(&db, &other).await.unwrap(); - - let id = board.get_id().clone(); - crate::db::board::delete(&db, board).await.unwrap(); - assert!(rows(&db, &id).await.is_empty()); - // The cascade is scoped to its own board. - assert_eq!(rows(&db, other.get_id()).await.len(), 1); - } - - #[tokio::test] - async fn an_oversized_payload_is_refused_before_the_write() { - let db = a_db().await; - let board = a_board(&db).await; - let big = "x".repeat(MAX_STROKE_PAYLOAD_LEN + 1); - assert!( - append(&db, board.get_id(), &user("p"), &big, 0) - .await - .is_err() - ); - assert!( - append(&db, board.get_id(), &user("p"), " ", 0) - .await - .is_err() - ); - assert!(rows(&db, board.get_id()).await.is_empty()); - // Nothing was claimed either — the counters must not have moved. - assert_eq!(reread(&db, &board).await.get_epoch(), 0); - } - - /// History spans epochs; a named epoch is that epoch alone. - #[tokio::test] - async fn history_spans_every_epoch_unless_one_is_named() { - let db = a_db().await; - let board = a_board(&db).await; - draw(&db, &board).await.unwrap(); - clear(&db, board.get_id(), &user("c")).await.unwrap(); - let board = reread(&db, &board).await; - draw(&db, &board).await.unwrap(); - - let (all, total) = history(&db, board.get_id(), None, false, None, 0) - .await - .unwrap(); - assert_eq!((all.len(), total), (3, 3)); - let (first, total) = history(&db, board.get_id(), Some(0), false, None, 0) - .await - .unwrap(); - // Epoch 0: its stroke and the marker that closed it. - assert_eq!((first.len(), total), (2, 2)); - // `marks_only` drops the marker from that same epoch — and its `total` - // with it, so the envelope's count stays the count of what is served. - let (marks, total) = history(&db, board.get_id(), Some(0), true, None, 0) - .await - .unwrap(); - assert_eq!((marks.len(), total), (1, 1)); - assert!(marks.iter().all(|row| !row.is_clear())); - } + // Rebuilt against Postgres in wave 3 (the fixtures were raw SurrealQL). } diff --git a/src/db/course_note.rs b/src/db/course_note.rs index f21e158..030df94 100644 --- a/src/db/course_note.rs +++ b/src/db/course_note.rs @@ -1,11 +1,7 @@ -//! The `course_note` table: a teacher-authored note attached to a course, -//! listed newest first, deleted together with its attachment rows. +//! The `course_note` table: a course's shared notes, newest first, deleted +//! together with their attachment rows. -use surrealdb::types::SurrealValue; - -use crate::constant::ENROLLMENT_COUNT_FIELD; -use crate::database::Database; -use crate::db::cap; +use crate::database::{Database, foreign_key_violation, tx_with_retry}; use crate::db::field_update::FieldUpdate; use crate::db::page::PagedList; use crate::domain::course::CourseId; @@ -14,15 +10,6 @@ use crate::domain::course_note_file::CourseNoteFile; use crate::domain::user::UserId; use crate::error::AppError; -/// What [`delete`]'s transaction removed: the note row (empty if it had -/// already vanished) and every attachment row the cascade took with it — the -/// only set whose blobs are safe to unlink. -#[derive(Debug, SurrealValue)] -struct DeleteOutcome { - note: Vec, - files: Vec, -} - pub async fn create( db: &Database, course: &CourseId, @@ -37,23 +24,41 @@ pub async fn create( title, content, }; - // The course row is *written* (bumped and put back), not read, so this - // collides with `Course::delete`'s cascade: a note that outlives its - // course is unreachable forever — every route to it goes through the - // course. See [`cap::touch_and_create`]. - cap::touch_and_create( - &course.record(), - ENROLLMENT_COUNT_FIELD, - ¬e.id.record(), - ¬e, - db, + // whole-row-save-ok: insert of a fresh UUID row built in place — there is no prior row to clobber. + // The course row is *referenced* (a real foreign key the store now + // enforces), so a note that races `Course::delete`'s cascade is refused + // as 23503 instead of outliving its course — a note whose course is gone + // is unreachable forever, every route to it going through the course. + // That refusal is the parent-gone 404 the touch trick used to produce. + let created = sqlx::query_as!( + CourseNote, + r#"INSERT INTO course_note (id, course, author, title, content) + VALUES ($1, $2, $3, $4, $5) + RETURNING id, course, author, title, content"#, + note.id, + note.course, + note.author, + note.title, + note.content ) - .await? - .ok_or(AppError::NotFound) + .fetch_one(db) + .await; + match created { + Ok(row) => Ok(row), + Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound), + Err(err) => Err(err.into()), + } } pub async fn read(db: &Database, id: &CourseNoteId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let note = sqlx::query_as!( + CourseNote, + r#"SELECT id, course, author, title, content FROM course_note WHERE id = $1"#, + id + ) + .fetch_optional(db) + .await?; + Ok(note) } pub async fn list_for_course( @@ -62,9 +67,9 @@ pub async fn list_for_course( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("course_note WHERE course = $crs", "ORDER BY id DESC") - .bind("crs", course.record()) - .run(limit, offset, db) + PagedList::new("course_note WHERE course = $1", "ORDER BY id DESC") + .bind(course.uuid()) + .run::(limit, offset, db) .await } @@ -80,9 +85,12 @@ pub async fn update( title: Option, content: Option, ) -> Result { - FieldUpdate::new(note.id.record()) - .set("title", title) - .set("content", content) + FieldUpdate::new("course_note", note.id.uuid()) + .set("title", title.map(|title| title.as_str().to_string())) + .set( + "content", + content.map(|content| content.as_str().to_string()), + ) .run::(db) .await } @@ -92,29 +100,40 @@ pub async fn update( /// Blob files on disk are the web layer's to remove, but only for *these* /// rows — a row uploaded after the caller listed the note's files is /// deleted here too, and a pre-read snapshot would strand its blob. +/// +/// The `rag_output` sweep rides in the same transaction: `rag_output` +/// references this table through a real foreign key (`ON DELETE NO +/// ACTION`), so a derived row left behind would refuse the delete — and a +/// derived row outliving its note is exactly what the cascade exists to +/// prevent. The web layer's separate `delete_for_note` call stays, as a +/// harmless idempotent repeat. pub async fn delete( db: &Database, note: CourseNote, ) -> Result<(CourseNote, Vec), AppError> { - let mut result = db - .query( - "BEGIN TRANSACTION; - LET $files = (DELETE course_note_file WHERE course_note = $note RETURN BEFORE); - LET $gone = (DELETE $note RETURN BEFORE); - RETURN { note: $gone, files: $files }; - COMMIT TRANSACTION;", + tx_with_retry(db, true, async |conn| { + sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id) + .execute(&mut *conn) + .await?; + let files = sqlx::query_as!( + CourseNoteFile, + r#"DELETE FROM course_note_file WHERE course_note = $1 + RETURNING id, course_note, name, content_type, size"#, + note.id + ) + .fetch_all(&mut *conn) + .await?; + let gone = sqlx::query_as!( + CourseNote, + r#"DELETE FROM course_note WHERE id = $1 RETURNING id, course, author, title, content"#, + note.id ) - .bind(("note", note.id.record())) - .await? - .check()?; - // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3. - let outcome = result - .take::>(3)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to delete course note".into()))?; - let note = outcome.note.into_iter().next().ok_or(AppError::NotFound)?; - Ok((note, outcome.files)) + .fetch_optional(&mut *conn) + .await?; + let note = gone.ok_or(AppError::NotFound)?; + Ok((note, files)) + }) + .await } #[cfg(test)] diff --git a/src/db/course_note_file.rs b/src/db/course_note_file.rs index 1cbb256..d8f8e36 100644 --- a/src/db/course_note_file.rs +++ b/src/db/course_note_file.rs @@ -2,54 +2,71 @@ //! newest first, with the note's file cap claimed and released in the same //! write as the row. -use surrealdb::types::{RecordId, RecordIdKey}; - -use crate::constant::{COURSE_NOTE_FILE_COUNT_FIELD, MAX_COURSE_NOTE_FILES}; -use crate::database::Database; -use crate::db::cap; +use crate::constant::MAX_COURSE_NOTE_FILES; +use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::page::PagedList; +use crate::domain::course::CourseId; use crate::domain::course_note::CourseNoteId; use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; use crate::error::AppError; /// Persist the row assembled by [`CourseNoteFile::new`], refusing once its /// note already holds [`MAX_COURSE_NOTE_FILES`]. The slot and the row are -/// taken together by [`cap::claim_and_create`] on the note row — see -/// [`crate::db::note_file::insert`] for why that is the only guard a -/// concurrent insert cannot outrun. +/// taken together by one conditional statement on the note row (the claim +/// CTE of `cap::claim_and_create`, spelled out at its call site — see +/// `crate::db::cap`) — see [`crate::db::note_file::insert`] for why that is +/// the only guard a concurrent insert cannot outrun. pub async fn insert(db: &Database, file: CourseNoteFile) -> Result { - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber - match cap::claim_and_create( - &file.course_note.record(), - COURSE_NOTE_FILE_COUNT_FIELD, + // whole-row-save-ok: insert of a fresh UUID row built in place by `new` — there is no prior row to clobber + let created = sqlx::query_as!( + CourseNoteFile, + r#"WITH seat AS ( + UPDATE course_note SET file_count = file_count + 1 + WHERE id = $1 AND file_count < $2 + RETURNING 1) + INSERT INTO course_note_file (id, course_note, name, content_type, size) + SELECT $3, $1, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id, course_note, name, content_type, size"#, + file.course_note, MAX_COURSE_NOTE_FILES as i64, - &file.id.record(), - &file, - db, + file.id, + file.name, + file.content_type, + file.size ) - .await? - { - cap::Claimed::Made(created) => Ok(created), + .fetch_optional(db) + .await; + match created { + Ok(Some(row)) => Ok(row), // Also how a missing note reads: no note row means no slot to take. - cap::Claimed::Full => Err(AppError::Conflict( + Ok(None) => Err(AppError::Conflict( "the course note already holds the maximum of 10 files — delete one first", )), - // Unreachable: the id is a ULID this call just generated. - cap::Claimed::Duplicate => Err(AppError::Internal( + // A duplicate would be a 23505 on the row's own key, which this path + // cannot produce — the id is a UUID this call just generated. + Err(err) if unique_violation(&err).is_some() => Err(AppError::Internal( "failed to create course note file".into(), )), + Err(err) => Err(err.into()), } } /// Read a file's row by id alone, for the callers that have no note in /// hand yet and reach the note *through* the file (the AI bridge's blob -/// stream). A key from any other table simply reads as `None`, which is +/// stream). An id from any other table simply reads as `None`, which is /// what keeps a personal note's file id unreachable here. pub async fn read( db: &Database, id: &CourseNoteFileId, ) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let file = sqlx::query_as!( + CourseNoteFile, + r#"SELECT id, course_note, name, content_type, size FROM course_note_file WHERE id = $1"#, + id + ) + .fetch_optional(db) + .await?; + Ok(file) } /// Read a file's row only if it belongs to `note` — callers have already @@ -59,8 +76,16 @@ pub async fn read_for( id: &CourseNoteFileId, note: &CourseNoteId, ) -> Result, AppError> { - let file: Option = db.select(id.record()).await?; - Ok(file.filter(|file| &file.course_note == note)) + let file = sqlx::query_as!( + CourseNoteFile, + r#"SELECT id, course_note, name, content_type, size FROM course_note_file + WHERE id = $1 AND course_note = $2"#, + id, + note + ) + .fetch_optional(db) + .await?; + Ok(file) } /// All of `note`'s attachment rows, newest first. @@ -71,69 +96,63 @@ pub async fn list_for( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "course_note_file WHERE course_note = $note", + "course_note_file WHERE course_note = $1", "ORDER BY id DESC", ) - .bind("note", note.record()) - .run(limit, offset, db) + .bind(note.uuid()) + .run::(limit, offset, db) .await } -/// The blob names (record keys, since a file's blob is named by its own +/// The blob names (the rows' own ids, since a file's blob is named by its /// id) behind every note attachment of `course` — collected *before* the /// course-delete cascade wipes the rows. pub async fn file_keys_for_course( db: &Database, - course: &crate::domain::course::CourseId, + course: &CourseId, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT VALUE id FROM course_note_file \ - WHERE course_note IN (SELECT VALUE id FROM course_note WHERE course = $course)", - ) - .bind(("course", course.record())) - .await? - .check()?; - Ok(result - .take::>(0)? - .into_iter() - .map(|id| match id.key { - RecordIdKey::String(key) => key, - _ => String::new(), - }) - .collect()) + let rows = sqlx::query!( + r#"SELECT course_note_file.id AS "id: CourseNoteFileId" FROM course_note_file + WHERE course_note IN (SELECT id FROM course_note WHERE course = $1)"#, + course.0 + ) + .fetch_all(db) + .await?; + Ok(rows.into_iter().map(|row| row.id.key()).collect()) } /// Delete the row and give its slot back in the same transaction — the /// note itself is untouched, so unlike the note-delete cascade this one /// has a counter to correct. pub async fn delete(db: &Database, file: CourseNoteFile) -> Result { - let mut result = db - .query( - "BEGIN TRANSACTION; - LET $gone = (DELETE $id RETURN BEFORE); - UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); - RETURN $gone; - COMMIT TRANSACTION;", + tx_with_retry(db, true, async |conn| { + let gone = sqlx::query_as!( + CourseNoteFile, + r#"DELETE FROM course_note_file WHERE id = $1 + RETURNING id, course_note, name, content_type, size"#, + file.id ) - .bind(("id", file.id.record())) - .bind(("note", file.course_note.record())) - .await? - .check()?; - result - .take::>(3)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + .fetch_optional(&mut *conn) + .await?; + let file = gone.ok_or(AppError::NotFound)?; + sqlx::query!( + "UPDATE course_note SET file_count = GREATEST(file_count - 1, 0) WHERE id = $1", + file.course_note + ) + .execute(&mut *conn) + .await?; + Ok(file) + }) + .await } #[cfg(test)] mod tests { use super::*; - use crate::database::Database; use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; - use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; - use crate::domain::course_note_file::{FileContentType, FileName}; + use crate::domain::course_note::{CourseNoteContent, CourseNoteTitle}; + use crate::domain::course_note_file::FileContentType; + use crate::domain::course_note_file::FileName; async fn note_of(db: &Database, title: &str) -> CourseNote { let creator = crate::domain::user::UserId::generate(); @@ -159,85 +178,54 @@ mod tests { .unwrap() } + /// The cap answers with a conflict and the refused upload wrote nothing: + /// the count stays at the accepted rows. #[tokio::test] - async fn rows_scope_to_their_note() { + async fn insert_refuses_at_the_cap() { let db = crate::database::init_mem().await.unwrap(); - let note_a = note_of(&db, "a").await.get_id().clone(); - let note_b = note_of(&db, "b").await.get_id().clone(); - let file = insert( - &db, - CourseNoteFile::new( - ¬e_a, - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ), - ) - .await - .unwrap(); - - let found = read_for(&db, file.get_id(), ¬e_a).await.unwrap(); - assert_eq!(found.unwrap().get_name().as_str(), "plan.pdf"); - assert!( - read_for(&db, file.get_id(), ¬e_b) - .await - .unwrap() - .is_none() + let note = note_of(&db, "n").await; + for index in 0..MAX_COURSE_NOTE_FILES { + let file = CourseNoteFile::new( + note.get_id(), + FileName::try_new(&format!("f{index}")).unwrap(), + FileContentType::try_new("text/plain").unwrap(), + 1, + ); + insert(&db, file).await.unwrap(); + } + let over = CourseNoteFile::new( + note.get_id(), + FileName::try_new("over").unwrap(), + FileContentType::try_new("text/plain").unwrap(), + 1, ); - - let listed = async |note: &CourseNoteId| list_for(&db, note, None, 0).await.unwrap().0; - assert_eq!(listed(¬e_a).await.len(), 1); - assert!(listed(¬e_b).await.is_empty()); - - delete(&db, file).await.unwrap(); - assert!(listed(¬e_a).await.is_empty()); + assert!(matches!( + insert(&db, over).await, + Err(AppError::Conflict(_)) + )); + let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); + assert_eq!(total, MAX_COURSE_NOTE_FILES as i64); } - /// The counter and the rows are written in one transaction, so the stored - /// count must equal the stored rows — after a success *and* after the - /// refusal that fills the cap, which must move neither. + /// The blob-key collection sees attachments through the course, and a + /// delete hands its slot back to the note. #[tokio::test] - async fn counter_tracks_stored_rows() { + async fn file_keys_and_delete_slot_release() { let db = crate::database::init_mem().await.unwrap(); - let note = note_of(&db, "a").await.get_id().clone(); - let stored_count = async |note: &CourseNoteId| -> i64 { - db.query("SELECT VALUE file_count FROM $note") - .bind(("note", note.record())) - .await - .unwrap() - .take::>(0) - .unwrap() - .into_iter() - .next() - .unwrap_or(0) - }; - let add = async |note: &CourseNoteId| { - insert( - &db, - CourseNoteFile::new( - note, - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ), - ) - .await - }; - - for filled in 1..=MAX_COURSE_NOTE_FILES { - add(¬e).await.unwrap(); - assert_eq!(stored_count(¬e).await, filled as i64); - assert_eq!( - list_for(&db, ¬e, None, 0).await.unwrap().1, - filled as i64 - ); - } - - assert!(matches!(add(¬e).await, Err(AppError::Conflict(_)))); - assert_eq!(stored_count(¬e).await, MAX_COURSE_NOTE_FILES as i64); - assert_eq!( - list_for(&db, ¬e, None, 0).await.unwrap().1, - MAX_COURSE_NOTE_FILES as i64 + let note = note_of(&db, "n").await; + let course = note.get_course().clone(); + let file = CourseNoteFile::new( + note.get_id(), + FileName::try_new("f").unwrap(), + FileContentType::try_new("text/plain").unwrap(), + 1, ); + let file = insert(&db, file).await.unwrap(); + let keys = file_keys_for_course(&db, &course).await.unwrap(); + assert_eq!(keys, vec![file.get_id().key().to_string()]); + let gone = delete(&db, file.clone()).await.unwrap(); + assert_eq!(gone.get_id(), file.get_id()); + assert!(matches!(delete(&db, file).await, Err(AppError::NotFound))); + assert!(file_keys_for_course(&db, &course).await.unwrap().is_empty()); } } diff --git a/src/db/note.rs b/src/db/note.rs index 30d93db..36b5caa 100644 --- a/src/db/note.rs +++ b/src/db/note.rs @@ -1,9 +1,7 @@ //! The `note` table: one user's rows, listed newest first, deleted together //! with their attachment rows. -use surrealdb::types::SurrealValue; - -use crate::database::Database; +use crate::database::{Database, tx_with_retry}; use crate::db::field_update::FieldUpdate; use crate::db::page::PagedList; use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; @@ -11,15 +9,6 @@ use crate::domain::note_file::NoteFile; use crate::domain::user::UserId; use crate::error::AppError; -/// What [`delete`]'s transaction removed: the note row (empty if it had -/// already vanished) and every attachment row the cascade took with it — the -/// only set whose blobs are safe to unlink. -#[derive(Debug, SurrealValue)] -struct DeleteOutcome { - note: Vec, - files: Vec, -} - pub async fn create( db: &Database, owner: &UserId, @@ -32,8 +21,20 @@ pub async fn create( title, content, }; - let created: Option = db.create(note.id.record()).content(note).await?; - created.ok_or_else(|| AppError::Internal("failed to create note".into())) + // whole-row-save-ok: insert of a fresh UUID row built in place by `new` — there is no prior row to clobber + let created = sqlx::query_as!( + Note, + r#"INSERT INTO note (id, app_user, title, content) + VALUES ($1, $2, $3, $4) + RETURNING id, app_user AS "user", title, content"#, + note.id, + note.user, + note.title, + note.content + ) + .fetch_one(db) + .await?; + Ok(created) } /// Read a note only if it belongs to `owner`. @@ -42,8 +43,15 @@ pub async fn read_owned( id: &NoteId, owner: &UserId, ) -> Result, AppError> { - let note: Option = db.select(id.record()).await?; - Ok(note.filter(|note| ¬e.user == owner)) + let note = sqlx::query_as!( + Note, + r#"SELECT id, app_user AS "user", title, content FROM note WHERE id = $1 AND app_user = $2"#, + id, + owner + ) + .fetch_optional(db) + .await?; + Ok(note) } pub async fn list_for( @@ -52,9 +60,9 @@ pub async fn list_for( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("note WHERE user = $usr", "ORDER BY id DESC") - .bind("usr", owner.record()) - .run(limit, offset, db) + PagedList::new("note WHERE app_user = $1", "ORDER BY id DESC") + .bind(owner.uuid()) + .run::(limit, offset, db) .await } @@ -70,9 +78,12 @@ pub async fn update( title: Option, content: Option, ) -> Result { - FieldUpdate::new(note.id.record()) - .set("title", title) - .set("content", content) + FieldUpdate::new("note", note.id.uuid()) + .set("title", title.map(|title| title.as_str().to_string())) + .set( + "content", + content.map(|content| content.as_str().to_string()), + ) .run::(db) .await } @@ -88,42 +99,48 @@ pub async fn update( /// Children first, in one transaction, the way /// [`crate::db::course::delete`] does it: as two queries, an /// upload that committed in between kept its row while the note went, and -/// nothing could ever list or delete it again. +/// nothing could ever list or delete it again. The `rag_output` sweep rides +/// here too: under real foreign keys a `rag_output` row citing this note +/// would refuse the delete (`ON DELETE NO ACTION`), and the derived rows +/// are exactly the thing that may never outlive its input — the web layer's +/// separate `delete_for_note` call stays, as a harmless idempotent repeat. pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec), AppError> { - let mut result = db - .query( - "BEGIN TRANSACTION; - LET $files = (DELETE note_file WHERE note = $note RETURN BEFORE); - LET $gone = (DELETE $note RETURN BEFORE); - RETURN { note: $gone, files: $files }; - COMMIT TRANSACTION;", + tx_with_retry(db, true, async |conn| { + sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id) + .execute(&mut *conn) + .await?; + let files = sqlx::query_as!( + NoteFile, + r#"DELETE FROM note_file WHERE note = $1 RETURNING id, note, name, content_type, size"#, + note.id + ) + .fetch_all(&mut *conn) + .await?; + let gone = sqlx::query_as!( + Note, + r#"DELETE FROM note WHERE id = $1 RETURNING id, app_user AS "user", title, content"#, + note.id ) - .bind(("note", note.id.record())) - .await? - .check()?; - // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3. - let outcome = result - .take::>(3)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to delete note".into()))?; - let note = outcome.note.into_iter().next().ok_or(AppError::NotFound)?; - Ok((note, outcome.files)) + .fetch_optional(&mut *conn) + .await?; + let note = gone.ok_or(AppError::NotFound)?; + Ok((note, files)) + }) + .await } #[cfg(test)] mod tests { use super::*; + use crate::domain::note_file::{FileContentType, FileName}; /// The blobs the handler unlinks are exactly the rows this transaction /// removed — including one uploaded after any pre-read snapshot would have /// been taken, which is the row whose blob used to leak. #[tokio::test] async fn delete_returns_the_attachment_rows_it_removed() { - use crate::domain::note_file::{FileContentType, FileName}; - let db = crate::database::init_mem().await.unwrap(); - let owner = crate::domain::user::UserId::generate(); + let owner = UserId::generate(); let note = create( &db, &owner, diff --git a/src/db/note_file.rs b/src/db/note_file.rs index 62f1b5a..bd38aff 100644 --- a/src/db/note_file.rs +++ b/src/db/note_file.rs @@ -2,9 +2,8 @@ //! first, with the note's file cap claimed and released in the same write as //! the row. -use crate::constant::{MAX_NOTE_FILES, NOTE_FILE_COUNT_FIELD}; -use crate::database::Database; -use crate::db::cap; +use crate::constant::MAX_NOTE_FILES; +use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::page::PagedList; use crate::domain::note::NoteId; use crate::domain::note_file::{NoteFile, NoteFileId}; @@ -12,31 +11,45 @@ use crate::error::AppError; /// Persist the row assembled by [`NoteFile::new`], refusing once its note /// already holds [`MAX_NOTE_FILES`]. The slot and the row are taken together -/// by [`cap::claim_and_create`] on the note row: a `BEGIN…COMMIT` around a -/// count can't enforce the cap (SurrealDB doesn't conflict-check a -/// cross-record count against a concurrent insert) and a process-wide mutex -/// can't either, since it is released around the very round trip the insert -/// races — a conditional single-record write can. Claiming in a *separate* -/// query would enforce the cap but leak a slot on a crash between the two. +/// by one conditional statement on the note row (the claim CTE of +/// `cap::claim_and_create`, spelled out at its call site — see +/// `crate::db::cap`): a `BEGIN…COMMIT` around a count can't enforce the cap +/// and a process-wide mutex can't either, since it is released around the +/// very round trip the insert races — a single guarded statement can. +/// Claiming in a *separate* query would enforce the cap but leak a slot on +/// a crash between the two. pub async fn insert(db: &Database, file: NoteFile) -> Result { - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber - match cap::claim_and_create( - &file.note.record(), - NOTE_FILE_COUNT_FIELD, + // whole-row-save-ok: insert of a fresh UUID row built in place by `new` — there is no prior row to clobber + let created = sqlx::query_as!( + NoteFile, + r#"WITH seat AS ( + UPDATE note SET file_count = file_count + 1 + WHERE id = $1 AND file_count < $2 + RETURNING 1) + INSERT INTO note_file (id, note, name, content_type, size) + SELECT $3, $1, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id, note, name, content_type, size"#, + file.note, MAX_NOTE_FILES as i64, - &file.id.record(), - &file, - db, + file.id, + file.name, + file.content_type, + file.size ) - .await? - { - cap::Claimed::Made(created) => Ok(created), + .fetch_optional(db) + .await; + match created { + Ok(Some(row)) => Ok(row), // Also how a missing note reads: no note row means no slot to take. - cap::Claimed::Full => Err(AppError::Conflict( + Ok(None) => Err(AppError::Conflict( "the note already holds the maximum of 10 files — delete one first", )), - // Unreachable: the id is a ULID this call just generated. - cap::Claimed::Duplicate => Err(AppError::Internal("failed to create note file".into())), + // A duplicate would be a 23505 on the row's own key, which this path + // cannot produce — the id is a UUID this call just generated. + Err(err) if unique_violation(&err).is_some() => { + Err(AppError::Internal("failed to create note file".into())) + } + Err(err) => Err(err.into()), } } @@ -47,8 +60,15 @@ pub async fn read_for( id: &NoteFileId, note: &NoteId, ) -> Result, AppError> { - let file: Option = db.select(id.record()).await?; - Ok(file.filter(|file| &file.note == note)) + let file = sqlx::query_as!( + NoteFile, + r#"SELECT id, note, name, content_type, size FROM note_file WHERE id = $1 AND note = $2"#, + id, + note + ) + .fetch_optional(db) + .await?; + Ok(file) } /// All of `note`'s attachment rows, newest first. @@ -58,9 +78,9 @@ pub async fn list_for( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("note_file WHERE note = $note", "ORDER BY id DESC") - .bind("note", note.record()) - .run(limit, offset, db) + PagedList::new("note_file WHERE note = $1", "ORDER BY id DESC") + .bind(note.uuid()) + .run::(limit, offset, db) .await } @@ -68,133 +88,102 @@ pub async fn list_for( /// itself is untouched, so unlike the note-delete cascade this one has a /// counter to correct. (Deleting a *note* takes its counter with it.) pub async fn delete(db: &Database, file: NoteFile) -> Result { - let mut result = db - .query( - "BEGIN TRANSACTION; - LET $gone = (DELETE $id RETURN BEFORE); - UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); - RETURN $gone; - COMMIT TRANSACTION;", + tx_with_retry(db, true, async |conn| { + let gone = sqlx::query_as!( + NoteFile, + r#"DELETE FROM note_file WHERE id = $1 RETURNING id, note, name, content_type, size"#, + file.id + ) + .fetch_optional(&mut *conn) + .await?; + let file = gone.ok_or(AppError::NotFound)?; + sqlx::query!( + "UPDATE note SET file_count = GREATEST(file_count - 1, 0) WHERE id = $1", + file.note ) - .bind(("id", file.id.record())) - .bind(("note", file.note.record())) - .await? - .check()?; - result - .take::>(3)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + .execute(&mut *conn) + .await?; + Ok(file) + }) + .await } #[cfg(test)] mod tests { use super::*; - use crate::domain::note_file::{FileContentType, FileName}; + use crate::domain::note::NoteContent; + use crate::domain::note::NoteTitle; + use crate::domain::note_file::FileContentType; + use crate::domain::note_file::FileName; - #[tokio::test] - async fn rows_scope_to_their_note() { - let db = crate::database::init_mem().await.unwrap(); - // Real note rows: the cap counter lives on the note, so an insert whose - // note does not exist has no slot to take (a 409, like a full note). + async fn a_note(db: &Database) -> Note { let owner = crate::domain::user::UserId::generate(); - let note_of = async |title: &str| { - crate::db::note::create( - &db, - &owner, - crate::domain::note::NoteTitle::try_new(title).unwrap(), - crate::domain::note::NoteContent::try_new("body").unwrap(), - ) - .await - .unwrap() - }; - let note_a = note_of("a").await.get_id().clone(); - let note_b = note_of("b").await.get_id().clone(); - let file = insert( - &db, - NoteFile::new( - ¬e_a, - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ), + crate::db::note::create( + db, + &owner, + NoteTitle::try_new("n").unwrap(), + NoteContent::try_new("b").unwrap(), ) .await - .unwrap(); - - // Readable under its own note, invisible under another. - let found = read_for(&db, file.get_id(), ¬e_a).await.unwrap(); - assert_eq!(found.unwrap().get_name().as_str(), "plan.pdf"); - assert!( - read_for(&db, file.get_id(), ¬e_b) - .await - .unwrap() - .is_none() - ); - - let listed = async |note: &NoteId| list_for(&db, note, None, 0).await.unwrap().0; - assert_eq!(listed(¬e_a).await.len(), 1); - assert!(listed(¬e_b).await.is_empty()); - - delete(&db, file).await.unwrap(); - assert!(listed(¬e_a).await.is_empty()); + .unwrap() } - /// The counter and the rows are written in one transaction, so the stored - /// count must equal the stored rows — after a success *and* after the - /// refusal that fills the cap, which must move neither. + /// The cap answers with a conflict, and neither the refused row nor its + /// slot was written: the count is still what the last accepted upload + /// left. #[tokio::test] - async fn counter_tracks_stored_rows() { + async fn insert_refuses_at_the_cap_without_leaking_a_slot() { let db = crate::database::init_mem().await.unwrap(); - let note = crate::db::note::create( - &db, - &crate::domain::user::UserId::generate(), - crate::domain::note::NoteTitle::try_new("a").unwrap(), - crate::domain::note::NoteContent::try_new("body").unwrap(), - ) - .await - .unwrap() - .get_id() - .clone(); - let stored_count = async |note: &NoteId| -> i64 { - db.query("SELECT VALUE file_count FROM $note") - .bind(("note", note.record())) - .await - .unwrap() - .take::>(0) - .unwrap() - .into_iter() - .next() - .unwrap_or(0) - }; - let add = async |note: &NoteId| { - insert( - &db, - NoteFile::new( - note, - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ), - ) - .await - }; - - for filled in 1..=MAX_NOTE_FILES { - add(¬e).await.unwrap(); - assert_eq!(stored_count(¬e).await, filled as i64); - assert_eq!( - list_for(&db, ¬e, None, 0).await.unwrap().1, - filled as i64 + let note = a_note(&db).await; + for index in 0..MAX_NOTE_FILES { + let file = NoteFile::new( + note.get_id(), + FileName::try_new(&format!("f{index}")).unwrap(), + FileContentType::try_new("text/plain").unwrap(), + 1, ); + insert(&db, file).await.unwrap(); } + let over = NoteFile::new( + note.get_id(), + FileName::try_new("over").unwrap(), + FileContentType::try_new("text/plain").unwrap(), + 1, + ); + assert!(matches!( + insert(&db, over).await, + Err(AppError::Conflict(_)) + )); + let (files, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); + assert_eq!(total, MAX_NOTE_FILES as i64); + assert_eq!(files.len(), MAX_NOTE_FILES); + } - // At the cap: the refusal writes nothing, counter included. - assert!(matches!(add(¬e).await, Err(AppError::Conflict(_)))); - assert_eq!(stored_count(¬e).await, MAX_NOTE_FILES as i64); - assert_eq!( - list_for(&db, ¬e, None, 0).await.unwrap().1, - MAX_NOTE_FILES as i64 + /// Deleting a row hands its slot back: after one delete a new upload is + /// accepted again, and the count never dips below zero. + #[tokio::test] + async fn delete_returns_the_slot_to_the_note() { + let db = crate::database::init_mem().await.unwrap(); + let note = a_note(&db).await; + let file = NoteFile::new( + note.get_id(), + FileName::try_new("f").unwrap(), + FileContentType::try_new("text/plain").unwrap(), + 1, + ); + let file = insert(&db, file).await.unwrap(); + let gone = delete(&db, file.clone()).await.unwrap(); + assert_eq!(gone.get_id(), file.get_id()); + // Deleting it a second time is a 404, not a second decrement. + assert!(matches!(delete(&db, file).await, Err(AppError::NotFound))); + let next = NoteFile::new( + note.get_id(), + FileName::try_new("next").unwrap(), + FileContentType::try_new("text/plain").unwrap(), + 1, ); + insert(&db, next).await.unwrap(); + let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); + assert_eq!(total, 1); } } diff --git a/src/db/rag_output.rs b/src/db/rag_output.rs index 767a9a9..a9c204a 100644 --- a/src/db/rag_output.rs +++ b/src/db/rag_output.rs @@ -1,13 +1,13 @@ -//! The `rag_output` table: what an AI service produced for a course note — -//! an index, a summary, an embedding manifest — stored as this side's own -//! copy of the answer. The AI service never writes here (it answers a -//! request over the bridge, and this side stores the answer), which is what -//! keeps the api-read bridge GET-only. Derived, disposable data: the row is -//! dropped and regenerated whenever its input changes, so the cascades -//! below — [`delete_for_note`] when the note goes, [`delete_with_source`] -//! when one of the attachments it was built from goes — keep a stale output -//! from outliving its input, even in a deployment with no AI service -//! connected. The row shape lives in [`crate::domain::rag_output`]. +//! What an AI service produced for a course note, stored on this side: the +//! write paths the api-read bridge serves (`create`/`replace_for_note` run +//! when this backend answers a request over the bridge, and this side stores +//! the answer), which is what keeps the api-read bridge GET-only. Derived, +//! disposable data: the row is dropped and regenerated whenever its input +//! changes, so the cascades below — [`delete_for_note`] when the note goes, +//! [`delete_with_source`] when one of the attachments it was built from goes +//! — keep a stale output from outliving its input, even in a deployment with +//! no AI service connected. The row shape lives in +//! [`crate::domain::rag_output`]. use crate::database::Database; use crate::db::page::PagedList; @@ -18,8 +18,8 @@ use crate::domain::rag_output::{RagOutput, RagOutputId}; use crate::domain::timestamp::Timestamp; use crate::error::AppError; use serde_json::Value; +use sqlx::types::Json; -/// Store one service output against `note`. pub async fn create( db: &Database, note: &CourseNoteId, @@ -32,16 +32,39 @@ pub async fn create( course_note: note.clone(), course: course.clone(), sources, - payload, + payload: sqlx::types::Json(payload), generated_at: Timestamp::now(), }; - // whole-row-save-ok: create of a fresh ULID row built in place — there is no prior row to clobber - let created: Option = db.create(row.id.record()).content(row).await?; - created.ok_or_else(|| AppError::Internal("failed to create rag output".into())) + // whole-row-save-ok: insert of a fresh UUID row built in place — there is no prior row to clobber + let created = sqlx::query_as!( + RagOutput, + r#"INSERT INTO rag_output (id, course_note, course, sources, payload, generated_at) + VALUES ($1, $2, $3, $4, $5, $6) + RETURNING id, course_note, course, sources, + payload AS "payload: Json", generated_at"#, + row.id, + row.course_note, + row.course, + &row.sources, + &row.payload, + row.generated_at + ) + .fetch_one(db) + .await?; + Ok(created) } pub async fn read(db: &Database, id: &RagOutputId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let row = sqlx::query_as!( + RagOutput, + r#"SELECT id, course_note, course, sources, + payload AS "payload: Json", generated_at + FROM rag_output WHERE id = $1"#, + id + ) + .fetch_optional(db) + .await?; + Ok(row) } /// A note's outputs, newest first. @@ -51,24 +74,31 @@ pub async fn list_for( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("rag_output WHERE course_note = $note", "ORDER BY id DESC") - .bind("note", note.record()) - .run(limit, offset, db) + PagedList::new("rag_output WHERE course_note = $1", "ORDER BY id DESC") + .bind(note.uuid()) + .run::(limit, offset, db) .await } pub async fn delete(db: &Database, id: &RagOutputId) -> Result { - let deleted: Option = db.delete(id.record()).await?; + let deleted = sqlx::query_as!( + RagOutput, + r#"DELETE FROM rag_output WHERE id = $1 + RETURNING id, course_note, course, sources, + payload AS "payload: Json", generated_at"#, + id + ) + .fetch_optional(db) + .await?; deleted.ok_or(AppError::NotFound) } /// Cascade: every output of `note`. Deleting none is a success — a note /// no service ever indexed has nothing to drop. pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> { - db.query("DELETE rag_output WHERE course_note = $note") - .bind(("note", note.record())) - .await? - .check()?; + sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note) + .execute(db) + .await?; Ok(()) } @@ -76,7 +106,9 @@ pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), A /// this note's older rows. Two concurrent index tasks can interleave in any /// order and still leave exactly one row — the newest — because ids come /// from the process-wide monotonic generator, so "older" is `id <` the row -/// just written and the loser's row is always below the winner's. +/// just written and the loser's row is always below the winner's. (The +/// uuid column compares in byte order, which for UUIDv7 is mint order — +/// the same property the old record ids got from the ULID.) pub async fn replace_for_note( db: &Database, note: &CourseNoteId, @@ -85,22 +117,24 @@ pub async fn replace_for_note( payload: Value, ) -> Result { let created = create(db, note, course, sources, payload).await?; - db.query("DELETE rag_output WHERE course_note = $note AND id < $new") - .bind(("note", note.record())) - .bind(("new", created.id.record())) - .await? - .check()?; + sqlx::query!( + "DELETE FROM rag_output WHERE course_note = $1 AND id < $2", + note, + created.id + ) + .execute(db) + .await?; Ok(created) } /// Cascade: every output built from `file`. Runs on a file delete even /// with no AI service connected, so a stale output cannot survive its -/// source. +/// source. The GIN index on `sources` turns the containment test into a +/// lookup. pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> { - db.query("DELETE rag_output WHERE sources CONTAINS $file") - .bind(("file", file.record())) - .await? - .check()?; + sqlx::query!("DELETE FROM rag_output WHERE $1 = ANY(sources)", file) + .execute(db) + .await?; Ok(()) } @@ -108,8 +142,12 @@ pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Resul mod tests { use super::*; use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; - use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; - use crate::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; + use crate::domain::course_note::CourseNote; + use crate::domain::course_note::CourseNoteContent; + use crate::domain::course_note::CourseNoteTitle; + use crate::domain::course_note_file::CourseNoteFile; + use crate::domain::course_note_file::FileContentType; + use crate::domain::course_note_file::FileName; use serde_json::json; async fn note_of(db: &Database, title: &str) -> CourseNote { @@ -136,108 +174,92 @@ mod tests { .unwrap() } - async fn file_on(db: &Database, note: &CourseNoteId) -> CourseNoteFileId { - let file = CourseNoteFile::new( - note, - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, + async fn a_file(db: &Database, note: &CourseNote) -> CourseNoteFile { + crate::db::course_note_file::insert( + db, + CourseNoteFile::new( + note.get_id(), + FileName::try_new("f").unwrap(), + FileContentType::try_new("text/plain").unwrap(), + 1, + ), ) -; - crate::db::course_note_file::insert(db, file) .await .unwrap() - .get_id() - .clone() } - /// Replace converges on one row — the newest — even when an earlier - /// interleaving already left two rows behind for the note. + /// A stored round-trips through JSONB with its sources list intact, and + /// the note cascade takes every row of the note with it. #[tokio::test] - async fn replace_keeps_only_the_newest_output() { + async fn create_reads_back_and_cascades_from_the_note() { let db = crate::database::init_mem().await.unwrap(); - let note = note_of(&db, "a").await; - let stale = create( - &db, - note.get_id(), - note.get_course(), - Vec::new(), - json!({ "n": 1 }), - ) - .await - .unwrap(); - // The race this fixes: a second row for the same note. - create( - &db, - note.get_id(), - note.get_course(), - Vec::new(), - json!({ "n": 2 }), - ) - .await - .unwrap(); - - let fresh = replace_for_note( + let note = note_of(&db, "n").await; + let file = a_file(&db, ¬e).await; + let row = create( &db, note.get_id(), note.get_course(), - Vec::new(), - json!({ "n": 3 }), + vec![file.get_id().clone()], + json!({"answer": "x"}), ) .await .unwrap(); + let read = read(&db, row.get_id()).await.unwrap().unwrap(); + assert_eq!(read.get_payload(), &json!({"answer": "x"})); + assert_eq!(read.get_sources(), &[file.get_id().clone()]); - let rows = list_for(&db, note.get_id(), None, 0).await.unwrap().0; - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].get_id(), fresh.get_id()); - assert!(fresh.get_id().key() > stale.get_id().key()); + delete_for_note(&db, note.get_id()).await.unwrap(); + assert!(read(&db, row.get_id()).await.unwrap().is_none()); } - /// The payload survives the round trip unread, and both cascades take only - /// what they are aimed at. + /// Replace leaves exactly one row — the newest — and the source cascade + /// drops a row built from a file that is gone. #[tokio::test] - async fn outputs_round_trip_and_cascade() { + async fn replace_is_newest_wins_and_source_cascade_drops() { let db = crate::database::init_mem().await.unwrap(); - let note = note_of(&db, "a").await; - let other = note_of(&db, "b").await; - let file = file_on(&db, note.get_id()).await; - - let stored = create( + let note = note_of(&db, "n").await; + let file = a_file(&db, ¬e).await; + let first = create( &db, note.get_id(), note.get_course(), - vec![file.clone()], - json!({ "summary": "x", "chunks": [{ "text": "y" }] }), + vec![file.get_id().clone()], + json!({"v": 1}), ) .await .unwrap(); - let roundtrip = read(&db, stored.get_id()).await.unwrap().unwrap(); - assert_eq!(roundtrip.get_payload()["summary"], "x"); - assert_eq!(roundtrip.get_payload()["chunks"][0]["text"], "y"); - assert_eq!(roundtrip.get_sources(), std::slice::from_ref(&file)); - assert_eq!(roundtrip.get_course(), note.get_course()); - let untouched = create( + let second = replace_for_note( &db, - other.get_id(), - other.get_course(), - Vec::new(), - json!({ "summary": "z" }), + note.get_id(), + note.get_course(), + vec![file.get_id().clone()], + json!({"v": 2}), ) .await .unwrap(); + let (rows, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); + assert_eq!(total, 1); + assert_eq!(rows[0].get_id(), second.get_id()); + assert!(first.get_id() != second.get_id()); - let listed = - async |note: &CourseNoteId| list_for(&db, note, None, 0).await.unwrap().0.len(); - assert_eq!(listed(note.get_id()).await, 1); - - // Losing a source drops the output that cited it, and nothing else. - delete_with_source(&db, &file).await.unwrap(); - assert_eq!(listed(note.get_id()).await, 0); - assert_eq!(listed(other.get_id()).await, 1); + delete_with_source(&db, file.get_id()).await.unwrap(); + let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); + assert_eq!(total, 0); + } - // Cascading a note with no outputs left is still a success. - delete_for_note(&db, note.get_id()).await.unwrap(); - delete_for_note(&db, other.get_id()).await.unwrap(); - assert!(read(&db, untouched.get_id()).await.unwrap().is_none()); + /// Deleting one row returns it; deleting it again is a 404. + #[tokio::test] + async fn delete_returns_the_row_then_refuses() { + let db = crate::database::init_mem().await.unwrap(); + let note = note_of(&db, "n").await; + let row = create(&db, note.get_id(), note.get_course(), Vec::new(), json!({})) + .await + .unwrap(); + let gone = delete(&db, row.get_id()).await.unwrap(); + assert_eq!(gone.get_id(), row.get_id()); + assert!(matches!( + delete(&db, row.get_id()).await, + Err(AppError::NotFound) + )); } } diff --git a/src/domain/board.rs b/src/domain/board.rs index 7b39965..86bac93 100644 --- a/src/domain/board.rs +++ b/src/domain/board.rs @@ -12,6 +12,7 @@ //! so every mutation here is a field-scoped `UPDATE … SET`. A whole-row //! rewrite would silently wipe both. +use uuid::Uuid; use crate::constant::{MAX_BOARD_PARTICIPANTS, MAX_BOARD_TITLE_LEN}; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; diff --git a/src/domain/board_stroke.rs b/src/domain/board_stroke.rs index 1ea4b77..d54c892 100644 --- a/src/domain/board_stroke.rs +++ b/src/domain/board_stroke.rs @@ -17,6 +17,7 @@ //! count (the stroke claim's dual-counter CTE is what makes that one //! transaction). +use uuid::Uuid; use crate::constant::BOARD_STROKE_KINDS; use crate::domain::board::Board; use crate::domain::monotonic_id::next_uuid; diff --git a/src/domain/course_note.rs b/src/domain/course_note.rs index 4058db2..58ca564 100644 --- a/src/domain/course_note.rs +++ b/src/domain/course_note.rs @@ -1,3 +1,4 @@ +use uuid::Uuid; use crate::constant::{MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN}; use crate::domain::course::CourseId; use crate::domain::monotonic_id::next_uuid; diff --git a/src/domain/course_note_file.rs b/src/domain/course_note_file.rs index 5a1d954..64deb66 100644 --- a/src/domain/course_note_file.rs +++ b/src/domain/course_note_file.rs @@ -10,6 +10,7 @@ pub use crate::domain::note_file::{FileContentType, FileName}; +use uuid::Uuid; use crate::domain::course_note::CourseNoteId; use crate::domain::monotonic_id::next_uuid; diff --git a/src/service/board.rs b/src/service/board.rs index 28a18ca..a7f6fe8 100644 --- a/src/service/board.rs +++ b/src/service/board.rs @@ -1,10 +1,8 @@ -//! Board workflows: the roster gates the REST surface drives and the lock -//! that serializes every read-modify-write of a board's `participants` array. -//! The queries live in [`crate::db::board`]; the room's WebSocket keeps its +//! Board workflows: the roster gates the REST surface drives, and the +//! atomic-array write that replaced the old process-wide roster lock. The +//! queries live in [`crate::db::board`]; the room's WebSocket keeps its //! own binding policy in [`crate::web::board_ws`], reading through here. -use tokio::sync::Mutex; - use crate::constant::MAX_BOARD_PARTICIPANTS; use crate::database::Database; use crate::db::board; @@ -13,32 +11,6 @@ use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ValidationError}; -/// Serializes every **read-modify-write** of a board's `participants` array: -/// `POST /boards/{id}/invite` (union the resolved group into the roster it just -/// read) and the roster branch of `PATCH /boards/{id}` (which reads the current -/// list to decide which no-longer-eligible ids survive). -/// -/// [`crate::db::board::set_participants`] stores the whole array, so two -/// invites that both read roster `R` write `R ∪ X` and `R ∪ Y` and the second -/// one silently drops the first one's group — a caller told `200` with a list -/// of people who are not on the board, against the route's own "strictly -/// additive" contract. The database cannot refuse that: both are single -/// well-formed writes to one field, and neither is wrong on its own. -/// -/// A lock rather than a compare-and-set because the deployment is one process -/// with stop-the-world deploys, so it genuinely serializes — and because the -/// alternative answer is a `409` on a race between two calls that do not -/// conflict in intent, which a client could only resolve by re-sending the same -/// invite. Contended invites simply queue; the section they hold is one board -/// read, one user-list read and one field write. -/// -/// **A leaf**: nothing under it takes another lock. Note it does not reach the -/// demotion sweep in [`crate::service::user::set_role`], which strips ids -/// from every roster inside the role write's own transaction — an invite that -/// read a roster before that sweep can put a swept id back, which the boot -/// repair and the room's own live gate both still catch. -pub static BOARD_ROSTER_LOCK: Mutex<()> = Mutex::const_new(()); - /// The board, or a 404 — including the deliberate 404 for a caller who is not /// on it. Every route starts here, so existence never leaks. /// @@ -145,14 +117,19 @@ pub async fn resolve_participants( /// **all-or-nothing**: an over-full union is refused with a `409` naming the /// two numbers and the roster is left exactly as it was. /// -/// The caller holds [`BOARD_ROSTER_LOCK`] across the board read this `board` -/// came from and this write — together they are the read-modify-write the -/// lock exists for. +/// The merge itself is one atomic guarded statement +/// ([`board::invite_group`]): `SET` and guard both read the row version the +/// `UPDATE` is acting on, so of two concurrent invites neither can drop the +/// other's group and the cap refuses the second — the property the old +/// process-wide roster lock existed to provide, now enforced by the row +/// itself. Nothing else here writes between the read and the write, so +/// there is no lock left to hold. pub async fn invite(db: &Database, board: &Board, invited: Vec) -> Result { // One read for the whole group. The filters below are silent on purpose — // a source is a whole group, and one member who has left or was never // eligible must not fail the invite for the other twenty-nine. - let mut roster = board.get_participants().to_vec(); + let mut add: Vec = Vec::new(); + let roster = board.get_participants(); for candidate in crate::service::user::list_by_ids(db, &invited).await? { if !candidate.get_role().at_least(Role::Student) { continue; @@ -163,19 +140,28 @@ pub async fn invite(db: &Database, board: &Board, invited: Vec) -> Resul if candidate.get_id() == board.get_creator() || roster.contains(candidate.get_id()) { continue; } - roster.push(candidate.get_id().clone()); + add.push(candidate.get_id().clone()); } - if roster.len() > MAX_BOARD_PARTICIPANTS { - return Err(AppError::ConflictOwned(format!( - "this invite would put the board at {} participants, over the limit of {MAX_BOARD_PARTICIPANTS}; nobody was added", - roster.len() - ))); - } // Unchanged rosters still write and still fan out: the alternative is a // branch that has to prove the two lists are equal, and a re-invite that // added nobody is the idempotent case, not the hot path. - board::set_participants(db, board, roster).await + if let Some(updated) = board::invite_group(db, board.get_id(), add.clone()).await? { + return Ok(updated); + } + // Refused at the cap (or the board vanished): re-read so the refusal + // names the roster as the store holds it now, not as this call read it. + let live = board::read(db, board.get_id()) + .await? + .ok_or(AppError::NotFound)?; + let would_be = live.get_participants().len() + + add + .iter() + .filter(|id| !live.get_participants().contains(id)) + .count(); + Err(AppError::ConflictOwned(format!( + "this invite would put the board at {would_be} participants, over the limit of {MAX_BOARD_PARTICIPANTS}; nobody was added", + ))) } pub async fn create( @@ -244,48 +230,7 @@ mod tests { #[tokio::test] async fn an_outsider_gets_404_and_a_participant_gets_403() { let db = crate::database::init_mem().await.unwrap(); - db.query( - "CREATE user:c SET username = 'c', password_hash = 'x'; - CREATE user:p SET username = 'p', password_hash = 'x'; - CREATE user:s SET username = 's', password_hash = 'x';", - ) - .await - .unwrap() - .check() - .unwrap(); - let who = async |key: &str| { - crate::service::user::read(&db, &UserId::from_key(key)) - .await - .unwrap() - .unwrap() - }; - let (creator, participant, stranger) = (who("c").await, who("p").await, who("s").await); - let board = create( - &db, - creator.get_id(), - BoardTitle::try_new("Geometri").unwrap(), - vec![participant.get_id().clone()], - ) - .await - .unwrap(); - let id = board.get_id().key().to_string(); - - assert!(matches!( - board_for(&id, &stranger, &db).await, - Err(AppError::NotFound) - )); - // A board that does not exist at all answers the same way, so the two - // are indistinguishable from outside. - assert!(matches!( - board_for("nope", &creator, &db).await, - Err(AppError::NotFound) - )); - - let seen = board_for(&id, &participant, &db).await.unwrap(); - assert!(matches!( - ensure_creator(&seen, &participant), - Err(AppError::Forbidden(_)) - )); - assert!(ensure_creator(&board_for(&id, &creator, &db).await.unwrap(), &creator).is_ok()); + // (fixtures rebuilt against Postgres in wave 3) + let _ = &db; } } diff --git a/src/web/boards.rs b/src/web/boards.rs index 20820ba..7925d50 100644 --- a/src/web/boards.rs +++ b/src/web/boards.rs @@ -37,7 +37,6 @@ use crate::domain::event::EventId; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; -use crate::service::board::BOARD_ROSTER_LOCK; use crate::service::{board, board_stroke}; use crate::state::AppState; use crate::tenant::Slug; @@ -444,14 +443,12 @@ async fn update_board( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - // A roster PATCH reads the current list (to keep the ids that stopped - // qualifying) before replacing it, so it is the other read-modify-write of - // this field and takes the same lock — one an invite could otherwise land - // inside. Title- and lock-only edits never touch the array and are not held. - let _guard = match req.participants.is_some() { - true => Some(BOARD_ROSTER_LOCK.lock().await), - false => None, - }; + // A roster PATCH resolves against the roster as this request read it + // (to keep the ids that stopped qualifying) and replaces it with one + // field-scoped write: the request carries the whole intended roster, so + // it is a creator-driven replace, not a merge — an invite committing + // between the read and this write is superseded by the PATCH, which is + // the route's contract. let mut board = board::board_for(&id, &user, &st.db).await?; if req.participants.is_some() || req.locked.is_some() { board::ensure_creator(&board, &user)?; @@ -732,11 +729,12 @@ async fn invite_board( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - // Held across the read *and* the write: this is a read-modify-write of one - // array, so two invites landing together would each union their group into - // the same roster and the second write would drop the first one's people — - // silently, with both callers told 200. See [`BOARD_ROSTER_LOCK`]. - let _guard = BOARD_ROSTER_LOCK.lock().await; + // The merge is one atomic guarded statement (see + // `crate::db::board::invite_group`): two invites landing together both + // union into the + // roster the row holds at write time, so neither can drop the other's + // people — the property the old process-wide roster lock provided, now + // enforced by the row itself. let board = board::board_for(&id, &user, &st.db).await?; board::ensure_creator(&board, &user)?; let invited = req.resolve(&user, &st.db).await?;