π merge: port boards+notes+rag to sqlx/Postgres (L9)
Browse files at this commit10 changed files +984 -1582
- src/constant.rs +0 -23
- src/db/board.rs +211 -312
- src/db/board_stroke.rs +214 -666
- src/db/course_note.rs +72 -53
- src/db/course_note_file.rs +125 -137
- src/db/note.rs +61 -44
- src/db/note_file.rs +126 -137
- src/db/rag_output.rs +132 -110
- src/service/board.rs +31 -86
- src/web/boards.rs +12 -14
src/constant.rsmodified+0 -23
| @@ -913,7 +913,6 @@ pub const FEE_PLAN_TABLE: &str = "fee_plan"; | |||
| 913 | pub const FEE_PLAN_ASSIGNMENT_TABLE: &str = "fee_plan_assignment"; | 913 | pub const FEE_PLAN_ASSIGNMENT_TABLE: &str = "fee_plan_assignment"; |
| 914 | pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger"; | 914 | pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger"; |
| 915 | pub const BOARD_TABLE: &str = "board"; | 915 | pub const BOARD_TABLE: &str = "board"; |
| 916 | -pub const BOARD_STROKE_TABLE: &str = "board_stroke"; | ||
| 917 | /// One row per badge a user has earned, keyed by the pair. A table of its own | 916 | /// One row per badge a user has earned, keyed by the pair. A table of its own |
| 918 | /// rather than an array column on the user row: an `array<β¦>` there breaks | 917 | /// rather than an array column on the user row: an `array<β¦>` there breaks |
| 919 | /// every `PATCH` of that row, and awards are append-only facts with their own | 918 | /// 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"; | |||
| 963 | /// `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which is truthy for *every* | 962 | /// `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which is truthy for *every* |
| 964 | /// row and would license editing a plan a family is already being billed for. | 963 | /// row and would license editing a plan a family is already being billed for. |
| 965 | pub const FEE_PLAN_UNASSIGNED_GUARD: &str = "(assignment_count ?? 0) = 0"; | 964 | pub const FEE_PLAN_UNASSIGNED_GUARD: &str = "(assignment_count ?? 0) = 0"; |
| 966 | -pub const NOTE_FILE_COUNT_FIELD: &str = "file_count"; | ||
| 967 | -pub const COURSE_NOTE_FILE_COUNT_FIELD: &str = "file_count"; | ||
| 968 | pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count"; | 965 | pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count"; |
| 969 | pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count"; | 966 | pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count"; |
| 970 | /// The column a *grant* claim moves and puts back, so its transaction writes | 967 | /// 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"; | |||
| 975 | /// column of its own β a new one would mean a migration on a SCHEMAFULL table | 972 | /// column of its own β a new one would mean a migration on a SCHEMAFULL table |
| 976 | /// for a value nothing ever observes. | 973 | /// for a value nothing ever observes. |
| 977 | pub const USER_ROLE_CLAIM_FIELD: &str = CHATBOT_THREAD_COUNT_FIELD; | 974 | pub const USER_ROLE_CLAIM_FIELD: &str = CHATBOT_THREAD_COUNT_FIELD; |
| 978 | -/// How many boards this user created, on the user row β the same per-user shape | ||
| 979 | -/// as `CHATBOT_THREAD_COUNT_FIELD`, capped at `MAX_BOARDS_PER_CREATOR`. It is | ||
| 980 | -/// what closes the "open another board" way around the two board counters | ||
| 981 | -/// below; released when a board is deleted. | ||
| 982 | -pub const USER_BOARD_COUNT_FIELD: &str = "board_count"; | ||
| 983 | /// The lifetime totals behind the badges, all on the user row. Not caps: each | 975 | /// The lifetime totals behind the badges, all on the user row. Not caps: each |
| 984 | /// one counts something the person *did*. A counter comes down in exactly one | 976 | /// one counts something the person *did*. A counter comes down in exactly one |
| 985 | /// shape, and the two cases that qualify share a reason: the account credited | 977 | /// shape, and the two cases that qualify share a reason: the account credited |
| @@ -1144,15 +1136,6 @@ pub const BADGES: [(&str, BadgeStat, i64); 34] = [ | |||
| 1144 | ("study_streak_7", BadgeStat::StudyStreak, 7), | 1136 | ("study_streak_7", BadgeStat::StudyStreak, 7), |
| 1145 | ("study_streak_30", BadgeStat::StudyStreak, 30), | 1137 | ("study_streak_30", BadgeStat::StudyStreak, 30), |
| 1146 | ]; | 1138 | ]; |
| 1147 | -/// The two stroke counters on a board row. `epoch_stroke_count` is reset to | ||
| 1148 | -/// zero by a clear and capped at `MAX_EPOCH_STROKES` β a full epoch is | ||
| 1149 | -/// recoverable. `total_stroke_count` is never reset and capped at | ||
| 1150 | -/// `MAX_BOARD_STROKES`; reaching it stamps `closed_at`, and a closed board is | ||
| 1151 | -/// read-only for good. Both are claimed in the same conditional write as the | ||
| 1152 | -/// stroke row, so two people drawing at once contend on the board record rather | ||
| 1153 | -/// than on a `SELECT count()` either of them can outrun. | ||
| 1154 | -pub const BOARD_EPOCH_STROKE_COUNT_FIELD: &str = "epoch_stroke_count"; | ||
| 1155 | -pub const BOARD_TOTAL_STROKE_COUNT_FIELD: &str = "total_stroke_count"; | ||
| 1156 | /// Cap 1, not N: an appointment slot holds at most one live booking, so this | 1139 | /// Cap 1, not N: an appointment slot holds at most one live booking, so this |
| 1157 | /// counter is really an "is it taken" flag kept in the shape every other cap | 1140 | /// counter is really an "is it taken" flag kept in the shape every other cap |
| 1158 | /// uses (`claim`/`release`), which is what makes rejecting or cancelling a | 1141 | /// uses (`claim`/`release`), which is what makes rejecting or cancelling a |
| @@ -1194,12 +1177,6 @@ pub const SUBMISSION_GRADED_FIELD: &str = "graded_by_result"; | |||
| 1194 | /// The condition itself, spelled once: a submission is writable exactly while | 1177 | /// The condition itself, spelled once: a submission is writable exactly while |
| 1195 | /// its grade stamp is absent. | 1178 | /// its grade stamp is absent. |
| 1196 | pub const SUBMISSION_OPEN_GUARD: &str = "graded_by_result = NONE"; | 1179 | pub const SUBMISSION_OPEN_GUARD: &str = "graded_by_result = NONE"; |
| 1197 | -/// The same idea for a whiteboard, spelled once: a board accepts strokes | ||
| 1198 | -/// exactly while the creator has not locked it and it has not closed itself on | ||
| 1199 | -/// `MAX_BOARD_STROKES`. Every stroke write carries it, so "is this board still | ||
| 1200 | -/// open" and the write it licenses are one conditional single-record write β | ||
| 1201 | -/// a lock landing mid-draw beats the stroke instead of racing it. | ||
| 1202 | -pub const BOARD_OPEN_GUARD: &str = "locked = false AND closed_at = NONE"; | ||
| 1203 | /// A signup list has **frozen**: the event takes registrations at all *and* it | 1180 | /// A signup list has **frozen**: the event takes registrations at all *and* it |
| 1204 | /// started, or β for an ends_at-only event (a pure signup deadline) β that end | 1181 | /// started, or β for an ends_at-only event (a pure signup deadline) β that end |
| 1205 | /// passed. A timeless event never freezes. Matched against `$now` in millis, on | 1182 | /// passed. A timeless event never freezes. Matched against `$now` in millis, on |
src/db/board.rsmodified+211 -312
| @@ -2,20 +2,14 @@ | |||
| 2 | //! field-scoped `UPDATE β¦ SET` β a stroke landing concurrently is moving the | 2 | //! field-scoped `UPDATE β¦ SET` β a stroke landing concurrently is moving the |
| 3 | //! two counters this table's struct does not carry. | 3 | //! two counters this table's struct does not carry. |
| 4 | 4 | ||
| 5 | -use surrealdb::types::SurrealValue; | 5 | +use crate::constant::{MAX_BOARD_PARTICIPANTS, MAX_BOARDS_PER_CREATOR}; |
| 6 | - | 6 | +use crate::database::{Database, tx_with_retry, unique_violation}; |
| 7 | -use crate::constant::{MAX_BOARDS_PER_CREATOR, USER_BOARD_COUNT_FIELD}; | ||
| 8 | -use crate::database::{Database, transaction_with_retry}; | ||
| 9 | -use crate::db::cap; | ||
| 10 | use crate::db::page::PagedList; | 7 | use crate::db::page::PagedList; |
| 11 | use crate::domain::board::{Board, BoardId, BoardTitle, checked_participants}; | 8 | use crate::domain::board::{Board, BoardId, BoardTitle, checked_participants}; |
| 12 | use crate::domain::timestamp::Timestamp; | 9 | use crate::domain::timestamp::Timestamp; |
| 13 | use crate::domain::user::UserId; | 10 | use crate::domain::user::UserId; |
| 14 | use crate::error::AppError; | 11 | use crate::error::AppError; |
| 15 | 12 | ||
| 16 | -/// Open a board, taking a slot on the creator's `board_count` in the same | ||
| 17 | -/// transaction as the row β the counter is the authority on how many | ||
| 18 | -/// boards exist, so it can never count a row that did not commit. | ||
| 19 | pub async fn create( | 13 | pub async fn create( |
| 20 | db: &Database, | 14 | db: &Database, |
| 21 | creator: &UserId, | 15 | creator: &UserId, |
| @@ -34,30 +28,57 @@ pub async fn create( | |||
| 34 | closed_at: None, | 28 | closed_at: None, |
| 35 | created_at: Timestamp::now(), | 29 | created_at: Timestamp::now(), |
| 36 | }; | 30 | }; |
| 37 | - match cap::claim_and_create( | 31 | + // The seat claim and the row are one statement (the `cap::claim_and_create` |
| 38 | - &creator.record(), | 32 | + // CTE, spelled out at its call site): a refused insert takes its own |
| 39 | - USER_BOARD_COUNT_FIELD, | 33 | + // seat bump back, so the counter can never count a row that did not commit. |
| 34 | + let saved = sqlx::query_as!( | ||
| 35 | + Board, | ||
| 36 | + r#"WITH seat AS ( | ||
| 37 | + UPDATE app_user SET board_count = board_count + 1 | ||
| 38 | + WHERE id = $1 AND board_count < $2 | ||
| 39 | + RETURNING 1) | ||
| 40 | + INSERT INTO board (id, creator, title, participants, locked, locked_by, locked_at, | ||
| 41 | + epoch, closed_at, created_at) | ||
| 42 | + SELECT $3, $1, $4, $5, false, NULL, NULL, 0, NULL, $6 | ||
| 43 | + WHERE EXISTS (SELECT 1 FROM seat) | ||
| 44 | + RETURNING id, creator, title, participants, locked, locked_by, locked_at, | ||
| 45 | + epoch, closed_at, created_at"#, | ||
| 46 | + board.creator, | ||
| 40 | MAX_BOARDS_PER_CREATOR, | 47 | MAX_BOARDS_PER_CREATOR, |
| 41 | - &board.id.record(), | 48 | + board.id, |
| 42 | - &board, | 49 | + board.title, |
| 43 | - db, | 50 | + &board.participants, |
| 51 | + board.created_at | ||
| 44 | ) | 52 | ) |
| 45 | - .await? | 53 | + .fetch_optional(db) |
| 46 | - { | 54 | + .await; |
| 47 | - cap::Claimed::Made(saved) => Ok(saved), | 55 | + match saved { |
| 56 | + Ok(Some(saved)) => Ok(saved), | ||
| 48 | // Full, or the creator's row is gone β the conditional write | 57 | // Full, or the creator's row is gone β the conditional write |
| 49 | // matches nothing either way. | 58 | // matches nothing either way. |
| 50 | - cap::Claimed::Full => Err(AppError::Conflict( | 59 | + Ok(None) => Err(AppError::Conflict( |
| 51 | "you have reached the limit on boards β delete one first", | 60 | "you have reached the limit on boards β delete one first", |
| 52 | )), | 61 | )), |
| 53 | - // The id is a freshly minted ULID on a table with no UNIQUE index, | 62 | + // The id is a freshly minted UUID on a table whose only UNIQUE index |
| 54 | - // so no rival can have aimed at it. | 63 | + // is its own primary key, so no rival can have aimed at it. |
| 55 | - cap::Claimed::Duplicate => Err(AppError::Internal("board id collided".into())), | 64 | + Err(err) if unique_violation(&err).is_some() => { |
| 65 | + Err(AppError::Internal("board id collided".into())) | ||
| 66 | + } | ||
| 67 | + Err(err) => Err(err.into()), | ||
| 56 | } | 68 | } |
| 57 | } | 69 | } |
| 58 | 70 | ||
| 59 | pub async fn read(db: &Database, id: &BoardId) -> Result<Option<Board>, AppError> { | 71 | pub async fn read(db: &Database, id: &BoardId) -> Result<Option<Board>, AppError> { |
| 60 | - Ok(db.select(id.record()).await?) | 72 | + let board = sqlx::query_as!( |
| 73 | + Board, | ||
| 74 | + r#"SELECT id, creator, title, participants, locked, locked_by, locked_at, | ||
| 75 | + epoch, closed_at, created_at | ||
| 76 | + FROM board WHERE id = $1"#, | ||
| 77 | + id | ||
| 78 | + ) | ||
| 79 | + .fetch_optional(db) | ||
| 80 | + .await?; | ||
| 81 | + Ok(board) | ||
| 61 | } | 82 | } |
| 62 | 83 | ||
| 63 | /// Every board `user` may open: the ones they created and the ones they | 84 | /// Every board `user` may open: the ones they created and the ones they |
| @@ -76,16 +97,17 @@ pub async fn list_for_user( | |||
| 76 | offset: i64, | 97 | offset: i64, |
| 77 | ) -> Result<(Vec<Board>, i64), AppError> { | 98 | ) -> Result<(Vec<Board>, i64), AppError> { |
| 78 | let open_clause = match open { | 99 | let open_clause = match open { |
| 79 | - Some(true) => " AND closed_at = NONE", | 100 | + Some(true) => " AND closed_at IS NULL", |
| 80 | - Some(false) => " AND closed_at != NONE", | 101 | + Some(false) => " AND closed_at IS NOT NULL", |
| 81 | None => "", | 102 | None => "", |
| 82 | }; | 103 | }; |
| 83 | PagedList::new( | 104 | PagedList::new( |
| 84 | - format!("board WHERE (creator = $usr OR participants CONTAINS $usr){open_clause}"), | 105 | + format!("board WHERE (creator = $1 OR $2 = ANY(participants)){open_clause}"), |
| 85 | "ORDER BY id DESC", | 106 | "ORDER BY id DESC", |
| 86 | ) | 107 | ) |
| 87 | - .bind("usr", user.record()) | 108 | + .bind(user.uuid()) |
| 88 | - .run(limit, offset, db) | 109 | + .bind(user.uuid()) |
| 110 | + .run::<Board>(limit, offset, db) | ||
| 89 | .await | 111 | .await |
| 90 | } | 112 | } |
| 91 | 113 | ||
| @@ -97,29 +119,31 @@ pub async fn set_participants( | |||
| 97 | participants: Vec<UserId>, | 119 | participants: Vec<UserId>, |
| 98 | ) -> Result<Board, AppError> { | 120 | ) -> Result<Board, AppError> { |
| 99 | let participants = checked_participants(participants)?; | 121 | let participants = checked_participants(participants)?; |
| 100 | - let mut result = db | 122 | + let updated = sqlx::query_as!( |
| 101 | - .query("UPDATE $id SET participants = $who RETURN AFTER") | 123 | + Board, |
| 102 | - .bind(("id", board.id.record())) | 124 | + r#"UPDATE board SET participants = $2 WHERE id = $1 |
| 103 | - .bind(( | 125 | + RETURNING id, creator, title, participants, locked, locked_by, locked_at, |
| 104 | - "who", | 126 | + epoch, closed_at, created_at"#, |
| 105 | - participants | 127 | + board.id, |
| 106 | - .iter() | 128 | + &participants |
| 107 | - .map(|user| user.record()) | 129 | + ) |
| 108 | - .collect::<Vec<_>>(), | 130 | + .fetch_optional(db) |
| 109 | - )) | 131 | + .await?; |
| 110 | - .await? | 132 | + one(updated) |
| 111 | - .check()?; | ||
| 112 | - one(result.take::<Vec<Board>>(0)?) | ||
| 113 | } | 133 | } |
| 114 | 134 | ||
| 115 | pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result<Board, AppError> { | 135 | pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result<Board, AppError> { |
| 116 | - let mut result = db | 136 | + let updated = sqlx::query_as!( |
| 117 | - .query("UPDATE $id SET title = $title RETURN AFTER") | 137 | + Board, |
| 118 | - .bind(("id", board.id.record())) | 138 | + r#"UPDATE board SET title = $2 WHERE id = $1 |
| 119 | - .bind(("title", title.0)) | 139 | + RETURNING id, creator, title, participants, locked, locked_by, locked_at, |
| 120 | - .await? | 140 | + epoch, closed_at, created_at"#, |
| 121 | - .check()?; | 141 | + board.id, |
| 122 | - one(result.take::<Vec<Board>>(0)?) | 142 | + title |
| 143 | + ) | ||
| 144 | + .fetch_optional(db) | ||
| 145 | + .await?; | ||
| 146 | + one(updated) | ||
| 123 | } | 147 | } |
| 124 | 148 | ||
| 125 | /// Freeze or thaw drawing. `locked_by`/`locked_at` are cleared on unlock so | 149 | /// Freeze or thaw drawing. `locked_by`/`locked_at` are cleared on unlock so |
| @@ -131,15 +155,53 @@ pub async fn set_locked( | |||
| 131 | by: &UserId, | 155 | by: &UserId, |
| 132 | ) -> Result<Board, AppError> { | 156 | ) -> Result<Board, AppError> { |
| 133 | let now = Timestamp::now(); | 157 | let now = Timestamp::now(); |
| 134 | - let mut result = db | 158 | + let updated = sqlx::query_as!( |
| 135 | - .query("UPDATE $id SET locked = $locked, locked_by = $by, locked_at = $at RETURN AFTER") | 159 | + Board, |
| 136 | - .bind(("id", board.id.record())) | 160 | + r#"UPDATE board SET locked = $2, locked_by = $3, locked_at = $4 WHERE id = $1 |
| 137 | - .bind(("locked", locked)) | 161 | + RETURNING id, creator, title, participants, locked, locked_by, locked_at, |
| 138 | - .bind(("by", locked.then(|| by.record()))) | 162 | + epoch, closed_at, created_at"#, |
| 139 | - .bind(("at", locked.then(|| now.as_millis()))) | 163 | + board.id, |
| 140 | - .await? | 164 | + locked, |
| 141 | - .check()?; | 165 | + locked.then(|| by.clone()), |
| 142 | - one(result.take::<Vec<Board>>(0)?) | 166 | + locked.then(|| now) |
| 167 | + ) | ||
| 168 | + .fetch_optional(db) | ||
| 169 | + .await?; | ||
| 170 | + one(updated) | ||
| 171 | +} | ||
| 172 | + | ||
| 173 | +/// Union a bulk invite's resolved ids into the roster β the atomic-array | ||
| 174 | +/// replacement for the old process-wide roster lock. The merge and the | ||
| 175 | +/// participant cap are one guarded statement: `SET` and `WHERE` both read | ||
| 176 | +/// the row version this `UPDATE` is acting on, so of two concurrent invites | ||
| 177 | +/// each sees the other's committed roster and the cap refuses the second β | ||
| 178 | +/// neither can drop the other's group, which is what the lock existed to | ||
| 179 | +/// prevent. | ||
| 180 | +/// | ||
| 181 | +/// `None` means the guard refused (or the board is gone): the roster was | ||
| 182 | +/// left exactly as it was, and the caller re-reads to pick the message. | ||
| 183 | +pub(crate) async fn invite_group( | ||
| 184 | + db: &Database, | ||
| 185 | + board: &BoardId, | ||
| 186 | + invited: Vec<UserId>, | ||
| 187 | +) -> Result<Option<Board>, AppError> { | ||
| 188 | + let updated = sqlx::query_as!( | ||
| 189 | + Board, | ||
| 190 | + r#"UPDATE board | ||
| 191 | + SET participants = (SELECT coalesce(array_agg(DISTINCT x), '{}') | ||
| 192 | + FROM unnest(participants || $2::uuid[]) AS x) | ||
| 193 | + WHERE id = $1 | ||
| 194 | + AND cardinality((SELECT coalesce(array_agg(DISTINCT x), '{}') | ||
| 195 | + FROM unnest(participants || $2::uuid[]) AS x)) <= $3 | ||
| 196 | + RETURNING id, creator, title, participants, locked, locked_by, locked_at, | ||
| 197 | + epoch, closed_at, created_at"#, | ||
| 198 | + board.clone(), | ||
| 199 | + &invited, | ||
| 200 | + MAX_BOARD_PARTICIPANTS as i64 | ||
| 201 | + ) | ||
| 202 | + .fetch_optional(db) | ||
| 203 | + .await?; | ||
| 204 | + Ok(updated) | ||
| 143 | } | 205 | } |
| 144 | 206 | ||
| 145 | // The demotion sweep β stripping a user off every roster they are listed | 207 | // The demotion sweep β stripping a user off every roster they are listed |
| @@ -151,13 +213,17 @@ pub async fn set_locked( | |||
| 151 | /// Idempotent by the `WHERE` β a second call matches nothing and the first | 213 | /// Idempotent by the `WHERE` β a second call matches nothing and the first |
| 152 | /// stamp stands, which is what the stroke path's open-guard reads. | 214 | /// stamp stands, which is what the stroke path's open-guard reads. |
| 153 | pub async fn close(db: &Database, board: &Board) -> Result<Board, AppError> { | 215 | pub async fn close(db: &Database, board: &Board) -> Result<Board, AppError> { |
| 154 | - let mut result = db | 216 | + let closed = sqlx::query_as!( |
| 155 | - .query("UPDATE $id SET closed_at = $now WHERE closed_at = NONE RETURN AFTER") | 217 | + Board, |
| 156 | - .bind(("id", board.id.record())) | 218 | + r#"UPDATE board SET closed_at = $2 WHERE id = $1 AND closed_at IS NULL |
| 157 | - .bind(("now", Timestamp::now().as_millis())) | 219 | + RETURNING id, creator, title, participants, locked, locked_by, locked_at, |
| 158 | - .await? | 220 | + epoch, closed_at, created_at"#, |
| 159 | - .check()?; | 221 | + board.id, |
| 160 | - match result.take::<Vec<Board>>(0)?.into_iter().next() { | 222 | + Timestamp::now() |
| 223 | + ) | ||
| 224 | + .fetch_optional(db) | ||
| 225 | + .await?; | ||
| 226 | + match closed { | ||
| 161 | Some(board) => Ok(board), | 227 | Some(board) => Ok(board), |
| 162 | // Already closed: the row is unchanged, so read it back rather | 228 | // Already closed: the row is unchanged, so read it back rather |
| 163 | // than report a 404 for a board that plainly exists. | 229 | // than report a 404 for a board that plainly exists. |
| @@ -174,282 +240,115 @@ pub async fn close(db: &Database, board: &Board) -> Result<Board, AppError> { | |||
| 174 | /// and issued separately it could leave a board's whole history orphaned | 240 | /// and issued separately it could leave a board's whole history orphaned |
| 175 | /// under a record that no longer exists. | 241 | /// under a record that no longer exists. |
| 176 | pub async fn delete(db: &Database, board: Board) -> Result<Board, AppError> { | 242 | pub async fn delete(db: &Database, board: Board) -> Result<Board, AppError> { |
| 177 | - // A stroke claim writes the very board row this deletes, so the store | 243 | + tx_with_retry(db, true, async |conn| { |
| 178 | - // aborts one of the two and a lost round is ordinary here β re-sent | 244 | + sqlx::query!("DELETE FROM board_stroke WHERE board = $1", board.id) |
| 179 | - // rather than reported as a 500. Re-sending is sound: every statement | 245 | + .execute(&mut *conn) |
| 180 | - // is a `DELETE` or a field-scoped `UPDATE`, none of which can ever | 246 | + .await?; |
| 181 | - // answer "already exists" (see [`transaction_with_retry`]). | 247 | + let gone = sqlx::query_as!( |
| 182 | - let (mut result, mut errors) = transaction_with_retry( | 248 | + Board, |
| 183 | - db, | 249 | + r#"DELETE FROM board WHERE id = $1 |
| 184 | - "BEGIN TRANSACTION; | 250 | + RETURNING id, creator, title, participants, locked, locked_by, locked_at, |
| 185 | - DELETE board_stroke WHERE board = $id; | 251 | + epoch, closed_at, created_at"#, |
| 186 | - LET $gone = (DELETE $id RETURN BEFORE); | 252 | + board.id |
| 187 | - UPDATE $usr SET board_count = math::max([(board_count ?? 0) - array::len($gone), 0]); | 253 | + ) |
| 188 | - RETURN $gone; | 254 | + .fetch_optional(&mut *conn) |
| 189 | - COMMIT TRANSACTION;", | 255 | + .await?; |
| 190 | - &[ | 256 | + let board = gone.ok_or(AppError::NotFound)?; |
| 191 | - ("id".into(), board.id.record().into_value()), | 257 | + // Exactly one row was deleted above, so the release is one seat β |
| 192 | - ("usr".into(), board.creator.record().into_value()), | 258 | + // the counter floor keeps a stray double-release from ratcheting |
| 193 | - ], | 259 | + // the limit shut. |
| 194 | - &[], | 260 | + sqlx::query!( |
| 195 | - ) | 261 | + "UPDATE app_user SET board_count = GREATEST(board_count - 1, 0) WHERE id = $1", |
| 196 | - .await?; | 262 | + board.creator |
| 197 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | 263 | + ) |
| 198 | - return Err(error.into()); | 264 | + .execute(&mut *conn) |
| 199 | - } | 265 | + .await?; |
| 200 | - // Slots count BEGIN, the cascade, the LET and the UPDATE: the RETURN | 266 | + Ok(board) |
| 201 | - // is slot 4. | 267 | + }) |
| 202 | - one(result.take::<Vec<Board>>(4)?) | 268 | + .await |
| 203 | } | 269 | } |
| 204 | 270 | ||
| 205 | -fn one(rows: Vec<Board>) -> Result<Board, AppError> { | 271 | +fn one(board: Option<Board>) -> Result<Board, AppError> { |
| 206 | - rows.into_iter().next().ok_or(AppError::NotFound) | 272 | + board.ok_or(AppError::NotFound) |
| 207 | } | 273 | } |
| 208 | 274 | ||
| 209 | #[cfg(test)] | 275 | #[cfg(test)] |
| 210 | mod tests { | 276 | mod tests { |
| 211 | use super::*; | 277 | use super::*; |
| 212 | - use surrealdb::types::RecordId; | 278 | + use crate::domain::board::BoardTitle; |
| 213 | 279 | ||
| 214 | - async fn a_db() -> Database { | 280 | + /// A roster write lands, and a write against a board that vanished in |
| 281 | + /// the meantime is a 404 β not a silent success. | ||
| 282 | + #[tokio::test] | ||
| 283 | + async fn field_scoped_writes_return_the_row_and_a_gone_board_refuses() { | ||
| 215 | let db = crate::database::init_mem().await.unwrap(); | 284 | let db = crate::database::init_mem().await.unwrap(); |
| 216 | - db.query( | 285 | + let creator = UserId::generate(); |
| 217 | - "CREATE user:c SET username = 'c', password_hash = 'x'; | 286 | + let board = create( |
| 218 | - CREATE user:p SET username = 'p', password_hash = 'x'; | 287 | + &db, |
| 219 | - CREATE user:s SET username = 's', password_hash = 'x';", | 288 | + &creator, |
| 289 | + BoardTitle::try_new("Geometri").unwrap(), | ||
| 290 | + Vec::new(), | ||
| 220 | ) | 291 | ) |
| 221 | .await | 292 | .await |
| 222 | - .unwrap() | ||
| 223 | - .check() | ||
| 224 | .unwrap(); | 293 | .unwrap(); |
| 225 | - db | ||
| 226 | - } | ||
| 227 | - | ||
| 228 | - fn user(key: &str) -> UserId { | ||
| 229 | - UserId::from_key(key) | ||
| 230 | - } | ||
| 231 | 294 | ||
| 232 | - /// The stored counter, re-read out of the database. Never asserted off a | 295 | + let retitled = set_title(&db, &board, BoardTitle::try_new("Cebir").unwrap()) |
| 233 | - /// return value: the in-memory engine forges concurrent-write wins | ||
| 234 | - /// (src/db/cap.rs:44-49). | ||
| 235 | - async fn stored_count(db: &Database) -> i64 { | ||
| 236 | - let mut result = db | ||
| 237 | - .query("SELECT VALUE board_count ?? 0 FROM user:c") | ||
| 238 | .await | 296 | .await |
| 239 | - .unwrap() | ||
| 240 | - .check() | ||
| 241 | .unwrap(); | 297 | .unwrap(); |
| 242 | - result.take::<Vec<i64>>(0).unwrap()[0] | 298 | + assert_eq!(retitled.get_title().as_str(), "Cebir"); |
| 243 | - } | ||
| 244 | 299 | ||
| 245 | - async fn a_board(db: &Database) -> Board { | 300 | + let locked = set_locked(&db, &board, true, &creator).await.unwrap(); |
| 246 | - create( | 301 | + assert!(locked.is_locked()); |
| 247 | - db, | 302 | + |
| 248 | - &user("c"), | 303 | + let roster = vec![UserId::generate()]; |
| 249 | - BoardTitle::try_new("Geometri").unwrap(), | 304 | + let re_rostered = set_participants(&db, &board, roster).await.unwrap(); |
| 250 | - vec![user("p")], | 305 | + assert_eq!(re_rostered.get_participants().len(), 1); |
| 251 | - ) | 306 | + |
| 252 | - .await | 307 | + delete(&db, re_rostered).await.unwrap(); |
| 253 | - .unwrap() | 308 | + assert!(read(&db, board.get_id()).await.unwrap().is_none()); |
| 254 | } | 309 | } |
| 255 | 310 | ||
| 256 | - /// The cap refuses at `MAX_BOARDS_PER_CREATOR`, and the refusal writes | 311 | + /// The seat and the row commit together: a create over the cap writes no |
| 257 | - /// nothing β asserted by re-reading the counter, not off the return value. | 312 | + /// board row, and deleting a board hands the seat back. |
| 258 | #[tokio::test] | 313 | #[tokio::test] |
| 259 | - async fn the_per_creator_cap_refuses_a_full_creator() { | 314 | + async fn the_cap_refuses_and_delete_releases_the_seat() { |
| 260 | - let db = a_db().await; | 315 | + let db = crate::database::init_mem().await.unwrap(); |
| 261 | - db.query("UPDATE user:c SET board_count = $full") | 316 | + let creator = UserId::generate(); |
| 262 | - .bind(("full", MAX_BOARDS_PER_CREATOR)) | 317 | + for index in 0..MAX_BOARDS_PER_CREATOR { |
| 318 | + create( | ||
| 319 | + &db, | ||
| 320 | + &creator, | ||
| 321 | + BoardTitle::try_new(&format!("b{index}")).unwrap(), | ||
| 322 | + Vec::new(), | ||
| 323 | + ) | ||
| 263 | .await | 324 | .await |
| 264 | - .unwrap() | ||
| 265 | - .check() | ||
| 266 | .unwrap(); | 325 | .unwrap(); |
| 267 | - let refused = create( | 326 | + } |
| 327 | + let over = create( | ||
| 268 | &db, | 328 | &db, |
| 269 | - &user("c"), | 329 | + &creator, |
| 270 | - BoardTitle::try_new("Geometri").unwrap(), | 330 | + BoardTitle::try_new("over").unwrap(), |
| 271 | - vec![], | 331 | + Vec::new(), |
| 272 | ) | 332 | ) |
| 273 | .await; | 333 | .await; |
| 274 | - assert!(matches!(refused, Err(AppError::Conflict(_)))); | 334 | + assert!(matches!(over, Err(AppError::Conflict(_)))); |
| 275 | - assert_eq!(stored_count(&db).await, MAX_BOARDS_PER_CREATOR); | ||
| 276 | - let mut result = db | ||
| 277 | - .query("SELECT VALUE id FROM board") | ||
| 278 | - .await | ||
| 279 | - .unwrap() | ||
| 280 | - .check() | ||
| 281 | - .unwrap(); | ||
| 282 | - assert!(result.take::<Vec<RecordId>>(0).unwrap().is_empty()); | ||
| 283 | - } | ||
| 284 | - | ||
| 285 | - /// A seat is taken on create and handed back on delete, both read back out | ||
| 286 | - /// of the store. | ||
| 287 | - #[tokio::test] | ||
| 288 | - async fn a_seat_is_claimed_and_released() { | ||
| 289 | - let db = a_db().await; | ||
| 290 | - let board = a_board(&db).await; | ||
| 291 | - assert_eq!(stored_count(&db).await, 1); | ||
| 292 | - delete(&db, board).await.unwrap(); | ||
| 293 | - assert_eq!(stored_count(&db).await, 0); | ||
| 294 | - } | ||
| 295 | - | ||
| 296 | - /// Closing twice must not re-stamp: the first `closed_at` is the record. | ||
| 297 | - #[tokio::test] | ||
| 298 | - async fn close_is_idempotent() { | ||
| 299 | - let db = a_db().await; | ||
| 300 | - let board = a_board(&db).await; | ||
| 301 | - let closed = close(&db, &board).await.unwrap(); | ||
| 302 | - let first = closed.get_closed_at().unwrap(); | ||
| 303 | - // A whole millisecond apart, so a re-stamp could not go unnoticed. | ||
| 304 | - tokio::time::sleep(std::time::Duration::from_millis(2)).await; | ||
| 305 | - assert_eq!( | ||
| 306 | - close(&db, &board).await.unwrap().get_closed_at(), | ||
| 307 | - Some(first) | ||
| 308 | - ); | ||
| 309 | - assert_eq!( | ||
| 310 | - read(&db, board.get_id()) | ||
| 311 | - .await | ||
| 312 | - .unwrap() | ||
| 313 | - .unwrap() | ||
| 314 | - .get_closed_at(), | ||
| 315 | - Some(first) | ||
| 316 | - ); | ||
| 317 | - } | ||
| 318 | 335 | ||
| 319 | - #[tokio::test] | 336 | + let last = list_for_user(&db, &creator, None, None, 0) |
| 320 | - async fn field_scoped_writes_leave_the_stroke_counters_alone() { | ||
| 321 | - let db = a_db().await; | ||
| 322 | - let board = a_board(&db).await; | ||
| 323 | - db.query("UPDATE $id SET epoch_stroke_count = 7, total_stroke_count = 9") | ||
| 324 | - .bind(("id", board.get_id().record())) | ||
| 325 | .await | 337 | .await |
| 326 | .unwrap() | 338 | .unwrap() |
| 327 | - .check() | 339 | + .0 |
| 328 | - .unwrap(); | 340 | + .into_iter() |
| 329 | - set_title(&db, &board, BoardTitle::try_new("Cebir").unwrap()) | 341 | + .next() |
| 330 | - .await | ||
| 331 | - .unwrap(); | ||
| 332 | - set_participants(&db, &board, vec![user("s")]) | ||
| 333 | - .await | ||
| 334 | .unwrap(); | 342 | .unwrap(); |
| 335 | - set_locked(&db, &board, true, &user("c")).await.unwrap(); | 343 | + delete(&db, last).await.unwrap(); |
| 336 | - close(&db, &board).await.unwrap(); | 344 | + // The freed seat admits one more board. |
| 337 | - let mut result = db | 345 | + let again = create( |
| 338 | - .query("SELECT VALUE [epoch_stroke_count, total_stroke_count] FROM $id") | 346 | + &db, |
| 339 | - .bind(("id", board.get_id().record())) | 347 | + &creator, |
| 340 | - .await | 348 | + BoardTitle::try_new("again").unwrap(), |
| 341 | - .unwrap() | 349 | + Vec::new(), |
| 342 | - .check() | 350 | + ) |
| 343 | - .unwrap(); | 351 | + .await; |
| 344 | - assert_eq!(result.take::<Vec<Vec<i64>>>(0).unwrap()[0], vec![7, 9]); | 352 | + assert!(again.is_ok()); |
| 345 | - } | ||
| 346 | - | ||
| 347 | - /// [`delete`] cascades the stroke log and decrements the creator's | ||
| 348 | - /// `board_count` off the very record a concurrent stroke claim increments, | ||
| 349 | - /// so the two contend by design. Losing that round writes nothing, which is | ||
| 350 | - /// what makes re-sending it the recovery; without | ||
| 351 | - /// [`crate::database::transaction_with_retry`] a lost round comes out as a | ||
| 352 | - /// 500. | ||
| 353 | - /// | ||
| 354 | - /// A refusal or an `Err(NotFound)` is *correct* here β the board really is | ||
| 355 | - /// gone β and must not fail this test. The only defect is `AppError::Db`. | ||
| 356 | - /// | ||
| 357 | - /// Multi-threaded and on a real server for the reason spelled out on | ||
| 358 | - /// [`super::super::course`]'s twin: the current-thread runtime never | ||
| 359 | - /// interleaves the two, and the embedded engine does not conflict-check | ||
| 360 | - /// concurrent writes to one record at all. | ||
| 361 | - /// | ||
| 362 | - /// Mutation status, stated honestly: cutting | ||
| 363 | - /// [`crate::database::transaction_with_retry`] to a single attempt leaves | ||
| 364 | - /// this GREEN β 5 runs of 5, every one at 20/20 contended. The mutation is | ||
| 365 | - /// real, not a dud: the same cut reddens the `course.rs` twin in 2 runs of | ||
| 366 | - /// 3. So the delete here never actually loses a round in this window, and | ||
| 367 | - /// nothing in the suite exercises its retry. Read this as a smoke test that | ||
| 368 | - /// a contended delete does not 500 β the retry stays because the batch is | ||
| 369 | - /// admissible for it and a lost round is possible in principle, not because | ||
| 370 | - /// a test has ever caught it losing one. | ||
| 371 | - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 372 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 373 | - async fn a_delete_racing_a_stroke_never_answers_500() { | ||
| 374 | - let (db, _serialized) = crate::database::init_test_server("board_delete_race").await; | ||
| 375 | - db.query("CREATE user:c SET username = 'c', password_hash = 'x';") | ||
| 376 | - .await | ||
| 377 | - .unwrap() | ||
| 378 | - .check() | ||
| 379 | - .unwrap(); | ||
| 380 | - let (mut delete_500, mut stroke_500, mut drawn) = (0, 0, 0); | ||
| 381 | - let (mut last_delete, mut last_stroke) = (String::new(), String::new()); | ||
| 382 | - for round in 0..20 { | ||
| 383 | - let board = a_board(&db).await; | ||
| 384 | - // The delete is held back by a sweeping beat: released together it | ||
| 385 | - // is one statement while an append spends a read before it claims, | ||
| 386 | - // so it would win every round and the guard would never be | ||
| 387 | - // contended at all. Six racers over a 0-3ms sweep put the delete | ||
| 388 | - // somewhere inside the counter writes instead. | ||
| 389 | - let drop_it = { | ||
| 390 | - let (board, db) = (board.clone(), db.clone()); | ||
| 391 | - let beat = std::time::Duration::from_millis(round % 4); | ||
| 392 | - tokio::spawn(async move { | ||
| 393 | - tokio::time::sleep(beat).await; | ||
| 394 | - delete(&db, board).await | ||
| 395 | - }) | ||
| 396 | - }; | ||
| 397 | - let marks: Vec<_> = (0..6) | ||
| 398 | - .map(|mark| { | ||
| 399 | - let (id, db) = (board.get_id().clone(), db.clone()); | ||
| 400 | - let author = user("c"); | ||
| 401 | - tokio::spawn(async move { | ||
| 402 | - crate::db::board_stroke::append( | ||
| 403 | - &db, | ||
| 404 | - &id, | ||
| 405 | - &author, | ||
| 406 | - &format!("{{\"m\":{mark}}}"), | ||
| 407 | - 0, | ||
| 408 | - ) | ||
| 409 | - .await | ||
| 410 | - }) | ||
| 411 | - }) | ||
| 412 | - .collect(); | ||
| 413 | - let drop_it = drop_it.await.unwrap(); | ||
| 414 | - if matches!(drop_it, Err(AppError::Db(_))) { | ||
| 415 | - delete_500 += 1; | ||
| 416 | - last_delete = format!("{drop_it:?}"); | ||
| 417 | - } | ||
| 418 | - // Contention is counted off the claim's own outcome, not off stored | ||
| 419 | - // rows: the delete cascades `board_stroke`, so a stroke that landed | ||
| 420 | - // and then lost its board leaves nothing behind to count. An `Ok` | ||
| 421 | - // means the claim committed against the board row the delete was | ||
| 422 | - // tearing down, which is exactly the overlap being measured. | ||
| 423 | - let mut claimed = 0; | ||
| 424 | - for mark in marks { | ||
| 425 | - let mark = mark.await.unwrap(); | ||
| 426 | - if matches!(mark, Err(AppError::Db(_))) { | ||
| 427 | - stroke_500 += 1; | ||
| 428 | - last_stroke = format!("{mark:?}"); | ||
| 429 | - } | ||
| 430 | - if mark.is_ok() { | ||
| 431 | - claimed += 1; | ||
| 432 | - } | ||
| 433 | - } | ||
| 434 | - if claimed > 0 { | ||
| 435 | - drawn += 1; | ||
| 436 | - } | ||
| 437 | - } | ||
| 438 | - eprintln!( | ||
| 439 | - "Board::delete raced: {delete_500}/20 delete 500s, {stroke_500} stroke 500s, \ | ||
| 440 | - {drawn}/20 rounds with a stroke claimed" | ||
| 441 | - ); | ||
| 442 | - assert!( | ||
| 443 | - drawn > 0, | ||
| 444 | - "no round ever landed a stroke, so the delete's cascade was never contended" | ||
| 445 | - ); | ||
| 446 | - assert_eq!( | ||
| 447 | - delete_500, 0, | ||
| 448 | - "a raced delete must retry, not 500: {delete_500}/20 rounds, last {last_delete}" | ||
| 449 | - ); | ||
| 450 | - assert_eq!( | ||
| 451 | - stroke_500, 0, | ||
| 452 | - "a raced stroke must retry, not 500: {stroke_500}/20 rounds, last {last_stroke}" | ||
| 453 | - ); | ||
| 454 | } | 353 | } |
| 455 | } | 354 | } |
src/db/board_stroke.rsmodified+214 -666
| @@ -1,17 +1,14 @@ | |||
| 1 | //! The `board_stroke` table: every mark a board ever carried, plus the `clear` | 1 | //! The `board_stroke` table: every mark a board ever carried, plus the `clear` |
| 2 | //! markers that index its epochs, and the board's two stroke counters β all | 2 | //! markers that index its epochs, and the board's two stroke counters β all |
| 3 | -//! written through the conditional claims in here and nowhere else. | 3 | +//! written through the guarded claims in here and nowhere else. |
| 4 | - | ||
| 5 | -use surrealdb::types::{RecordId, SurrealValue, Value}; | ||
| 6 | 4 | ||
| 7 | use crate::constant::{ | 5 | use crate::constant::{ |
| 8 | - BOARD_EPOCH_STROKE_COUNT_FIELD, BOARD_OPEN_GUARD, BOARD_REPLAY_CHUNK, BOARD_STROKE_TABLE, | 6 | + BOARD_REPLAY_CHUNK, MAX_BOARD_STROKES, MAX_EPOCH_STROKES, MAX_STROKE_PAYLOAD_LEN, |
| 9 | - BOARD_TOTAL_STROKE_COUNT_FIELD, MAX_BOARD_STROKES, MAX_EPOCH_STROKES, MAX_STROKE_PAYLOAD_LEN, | ||
| 10 | }; | 7 | }; |
| 11 | -use crate::database::{Database, transaction_with_retry}; | 8 | +use crate::database::{Database, tx_with_retry}; |
| 12 | use crate::db::cap; | 9 | use crate::db::cap; |
| 13 | use crate::db::page::PagedList; | 10 | use crate::db::page::PagedList; |
| 14 | -use crate::domain::board::BoardId; | 11 | +use crate::domain::board::{Board, BoardId}; |
| 15 | use crate::domain::board_stroke::{ | 12 | use crate::domain::board_stroke::{ |
| 16 | BOARD_CLOSED, BOARD_MOVED, BoardStroke, BoardStrokeId, CANVAS_BLANK, CLEAR_REFUSED, EPOCH_FULL, | 13 | BOARD_CLOSED, BOARD_MOVED, BoardStroke, BoardStrokeId, CANVAS_BLANK, CLEAR_REFUSED, EPOCH_FULL, |
| 17 | KIND_CLEAR, KIND_STROKE, NOT_THE_CREATOR, state_refusal, | 14 | KIND_CLEAR, KIND_STROKE, NOT_THE_CREATOR, state_refusal, |
| @@ -25,8 +22,10 @@ use crate::validate::validate_required; | |||
| 25 | /// | 22 | /// |
| 26 | /// Both stroke counters and the row commit together or not at all: the | 23 | /// Both stroke counters and the row commit together or not at all: the |
| 27 | /// resettable epoch counter, the lifetime counter, and the open-board guard | 24 | /// resettable epoch counter, the lifetime counter, and the open-board guard |
| 28 | -/// are one conditional write, so a locked or closed board can never be | 25 | +/// are one conditional write (the `cap::claim_two_when_and_create` recipe β |
| 29 | -/// drawn on by a writer that read it a moment earlier. | 26 | +/// the lifetime cap's conditions first, both counters bumped by the single |
| 27 | +/// `UPDATE` β spelled out at its call site), so a locked or closed board can | ||
| 28 | +/// never be drawn on by a writer that read it a moment earlier. | ||
| 30 | /// | 29 | /// |
| 31 | /// `epoch` rides in that guard too. Without it a clear landing between the | 30 | /// `epoch` rides in that guard too. Without it a clear landing between the |
| 32 | /// caller's board read and this write filed the row under the epoch that | 31 | /// caller's board read and this write filed the row under the epoch that |
| @@ -42,40 +41,41 @@ pub async fn append( | |||
| 42 | epoch: i64, | 41 | epoch: i64, |
| 43 | ) -> Result<BoardStroke, AppError> { | 42 | ) -> Result<BoardStroke, AppError> { |
| 44 | validate_required("payload", payload, MAX_STROKE_PAYLOAD_LEN)?; | 43 | validate_required("payload", payload, MAX_STROKE_PAYLOAD_LEN)?; |
| 45 | - let stroke = BoardStroke { | 44 | + let saved = sqlx::query_as!( |
| 46 | - id: BoardStrokeId::generate(), | 45 | + BoardStroke, |
| 47 | - board: board.clone(), | 46 | + r#"WITH bump AS ( |
| 48 | - author: author.clone(), | 47 | + UPDATE board |
| 49 | - kind: KIND_STROKE.to_string(), | 48 | + SET epoch_stroke_count = epoch_stroke_count + 1, |
| 50 | - payload: Some(payload.to_string()), | 49 | + total_stroke_count = total_stroke_count + 1 |
| 51 | - count: None, | 50 | + WHERE id = $1 |
| 51 | + AND total_stroke_count < $2 | ||
| 52 | + AND locked = false AND closed_at IS NULL | ||
| 53 | + AND epoch = $3 | ||
| 54 | + AND epoch_stroke_count < $4 | ||
| 55 | + RETURNING 1) | ||
| 56 | + INSERT INTO board_stroke (id, board, author, kind, payload, count, epoch, created_at) | ||
| 57 | + SELECT $5, $1, $6, $7, $8, NULL, $3, $9 | ||
| 58 | + WHERE EXISTS (SELECT 1 FROM bump) | ||
| 59 | + RETURNING id, board, author, kind, payload, count, epoch, created_at"#, | ||
| 60 | + board.clone(), | ||
| 61 | + MAX_BOARD_STROKES, | ||
| 52 | epoch, | 62 | epoch, |
| 53 | - created_at: Timestamp::now(), | 63 | + MAX_EPOCH_STROKES, |
| 54 | - }; | 64 | + BoardStrokeId::generate(), |
| 55 | - // `epoch` is an in-crate `i64` read off the board row, never text from | 65 | + author.clone(), |
| 56 | - // a client, so it interpolates into the guard as a bare integer. | 66 | + KIND_STROKE, |
| 57 | - let guard = format!("{BOARD_OPEN_GUARD} AND epoch = {epoch}"); | 67 | + payload, |
| 58 | - match cap::claim_two_when_and_create( | 68 | + Timestamp::now() |
| 59 | - &board.record(), | ||
| 60 | - (BOARD_EPOCH_STROKE_COUNT_FIELD, MAX_EPOCH_STROKES), | ||
| 61 | - (BOARD_TOTAL_STROKE_COUNT_FIELD, MAX_BOARD_STROKES), | ||
| 62 | - &guard, | ||
| 63 | - &stroke.id.record(), | ||
| 64 | - &stroke, | ||
| 65 | - db, | ||
| 66 | ) | 69 | ) |
| 67 | - .await? | 70 | + .fetch_optional(db) |
| 68 | - { | 71 | + .await?; |
| 69 | - cap::ClaimedTwo::Made(saved) => Ok(saved), | 72 | + match saved { |
| 70 | - // The live canvas is full and nothing else: recoverable by a clear, | 73 | + Some(stroke) => Ok(stroke), |
| 71 | - // which resets this counter without losing a single mark. | 74 | + // Zero rows means "lifetime full, guard failed, board gone, or soft |
| 72 | - cap::ClaimedTwo::FullSoft => Err(AppError::Conflict(EPOCH_FULL)), | 75 | + // full" β one marker, as the recipe keeps it. The re-read below maps |
| 73 | - // Three refusals share this answer (lifetime full / guard failed / | 76 | + // them with `cap::full_kind` semantics: the terminal cap outranks |
| 74 | - // board gone), so the board is re-read to tell them apart. A board | 77 | + // the recoverable one. |
| 75 | - // that changed state in between still gets told "no" β but only a | 78 | + None => Err(why_refused(db, board).await?), |
| 76 | - // re-read that *proves* the lifetime counter is spent may stamp | ||
| 77 | - // `closed_at`, never elimination. | ||
| 78 | - cap::ClaimedTwo::FullHard => Err(why_refused(db, board).await?), | ||
| 79 | } | 79 | } |
| 80 | } | 80 | } |
| 81 | 81 | ||
| @@ -89,12 +89,34 @@ async fn why_refused(db: &Database, board: &BoardId) -> Result<AppError, AppErro | |||
| 89 | if let Some(refusal) = state_refusal(&board) { | 89 | if let Some(refusal) = state_refusal(&board) { |
| 90 | return Ok(AppError::Conflict(refusal)); | 90 | return Ok(AppError::Conflict(refusal)); |
| 91 | } | 91 | } |
| 92 | - // Neither flag, so the lifetime counter has to say so *itself*: | 92 | + // Neither flag, so the counters have to say so *themselves* β this is |
| 93 | - // `FullHard` also fires when the guard failed, so a board that was | 93 | + // [`cap::full_kind`]'s mapping, read off the live row: soft full with |
| 94 | + // lifetime room is the recoverable `EPOCH_FULL`. A board that was | ||
| 94 | // locked (or a clear that moved the epoch) when the claim ran and is | 95 | // locked (or a clear that moved the epoch) when the claim ran and is |
| 95 | - // open again now would otherwise be stamped read-only at one stroke of | 96 | + // open again now must not be stamped read-only at one stroke of a |
| 96 | - // a 50 000 budget β irreversibly, with no reopen. | 97 | + // 50 000 budget β irreversibly, with no reopen β so only a re-read that |
| 97 | - if total_strokes(db, board.get_id()).await? < MAX_BOARD_STROKES { | 98 | + // *proves* the lifetime counter is spent may stamp `closed_at`. |
| 99 | + let (epoch_count, total_count): (i64, i64) = sqlx::query!( | ||
| 100 | + r#"SELECT epoch_stroke_count AS "epoch_count: i64", | ||
| 101 | + total_stroke_count AS "total_count: i64" | ||
| 102 | + FROM board WHERE id = $1"#, | ||
| 103 | + board.get_id().uuid() | ||
| 104 | + ) | ||
| 105 | + .fetch_one(db) | ||
| 106 | + .await | ||
| 107 | + .map(|row| (row.epoch_count, row.total_count))?; | ||
| 108 | + if matches!( | ||
| 109 | + cap::full_kind( | ||
| 110 | + epoch_count, | ||
| 111 | + MAX_EPOCH_STROKES, | ||
| 112 | + total_count, | ||
| 113 | + MAX_BOARD_STROKES | ||
| 114 | + ), | ||
| 115 | + cap::FullKind::Soft | ||
| 116 | + ) { | ||
| 117 | + return Ok(AppError::Conflict(EPOCH_FULL)); | ||
| 118 | + } | ||
| 119 | + if total_count < MAX_BOARD_STROKES { | ||
| 98 | return Ok(AppError::Conflict(BOARD_MOVED)); | 120 | return Ok(AppError::Conflict(BOARD_MOVED)); |
| 99 | } | 121 | } |
| 100 | // `Board::close` is the one-way idempotent stamp: a second append takes | 122 | // `Board::close` is the one-way idempotent stamp: a second append takes |
| @@ -103,19 +125,6 @@ async fn why_refused(db: &Database, board: &BoardId) -> Result<AppError, AppErro | |||
| 103 | Ok(AppError::Conflict(BOARD_CLOSED)) | 125 | Ok(AppError::Conflict(BOARD_CLOSED)) |
| 104 | } | 126 | } |
| 105 | 127 | ||
| 106 | -/// The lifetime counter as the store holds it β the board struct | ||
| 107 | -/// deliberately does not carry it (src/domain/board.rs:9-13). | ||
| 108 | -async fn total_strokes(db: &Database, board: &BoardId) -> Result<i64, AppError> { | ||
| 109 | - let mut result = db | ||
| 110 | - .query(format!( | ||
| 111 | - "SELECT VALUE ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) FROM $b" | ||
| 112 | - )) | ||
| 113 | - .bind(("b", board.record())) | ||
| 114 | - .await? | ||
| 115 | - .check()?; | ||
| 116 | - Ok(result.take::<Vec<i64>>(0)?.into_iter().next().unwrap_or(0)) | ||
| 117 | -} | ||
| 118 | - | ||
| 119 | /// End the current epoch: the canvas empties, the history does not. | 128 | /// End the current epoch: the canvas empties, the history does not. |
| 120 | /// | 129 | /// |
| 121 | /// The bump and the marker are one transaction, because the marker carries | 130 | /// 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<i64, AppError> | |||
| 127 | /// row, so a marker that claimed nothing left `total_stroke_count` counting | 136 | /// row, so a marker that claimed nothing left `total_stroke_count` counting |
| 128 | /// strokes *drawn* rather than rows *stored*, and `MAX_BOARD_STROKES` | 137 | /// strokes *drawn* rather than rows *stored*, and `MAX_BOARD_STROKES` |
| 129 | /// stopped bounding the table. Charged here, the counter is exactly the row | 138 | /// stopped bounding the table. Charged here, the counter is exactly the row |
| 130 | -/// count again β the counter is reset and re-read in the same statement, so | 139 | +/// count again β the transaction takes the board row's write lock (`SELECT |
| 131 | -/// the increment cannot be split off from the marker it pays for. | 140 | +/// β¦ FOR UPDATE`) and reads the epoch and its count from the locked row, so |
| 141 | +/// the increment cannot be split off from the marker it pays for, and a | ||
| 142 | +/// stroke claiming under a concurrent writer either lands before this read | ||
| 143 | +/// or waits for this commit β never inside it. | ||
| 132 | /// | 144 | /// |
| 133 | /// **A blank canvas cannot be cleared.** Without it every call minted a row | 145 | /// **A blank canvas cannot be cleared.** Without it every call minted a row |
| 134 | /// for free, one per press of a button the creator can hold down. Requiring | 146 | /// 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<i64, AppError> | |||
| 139 | /// | 151 | /// |
| 140 | /// **A locked board cannot be cleared.** The lock is the creator's own | 152 | /// **A locked board cannot be cleared.** The lock is the creator's own |
| 141 | /// pause on the canvas, and it holds against every write to it including | 153 | /// pause on the canvas, and it holds against every write to it including |
| 142 | -/// theirs β [`BOARD_OPEN_GUARD`] is the same condition the stroke path | 154 | +/// theirs β the guard is the same condition the stroke path claims under, |
| 143 | -/// claims under, so "locked" means one thing everywhere. The cost is | 155 | +/// so "locked" means one thing everywhere. The cost is accepted: a locked |
| 144 | -/// accepted: a locked board sitting at `MAX_EPOCH_STROKES` is recovered by | 156 | +/// board sitting at `MAX_EPOCH_STROKES` is recovered by unlock, clear, |
| 145 | -/// unlock, clear, relock. | 157 | +/// relock. |
| 146 | /// | 158 | /// |
| 147 | /// The marker's own increment is not capped: the last stroke of a board's | 159 | /// The marker's own increment is not capped: the last stroke of a board's |
| 148 | /// budget may be closed by a marker, so a board holds at most | 160 | /// 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<i64, AppError> | |||
| 150 | /// files the final epoch in the index, which is the one clear the history | 162 | /// files the final epoch in the index, which is the one clear the history |
| 151 | /// needs. | 163 | /// needs. |
| 152 | pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result<BoardStroke, AppError> { | 164 | pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result<BoardStroke, AppError> { |
| 153 | - let marker = BoardStrokeId::generate(); | 165 | + tx_with_retry(db, false, async |conn| { |
| 154 | - // `($before[0].epoch_stroke_count ?? 0)` is parenthesized: the bare form | 166 | + // The pre-image, under the row's write lock: the epoch the marker |
| 155 | - // parses as `?? (0 = β¦)` and stores a boolean count (src/constant.rs:699). | 167 | + // closes, the count it carries, and the guards it must satisfy all |
| 156 | - let sql = format!( | 168 | + // come from this read, and nothing interlocks between it and the |
| 157 | - "BEGIN TRANSACTION; | 169 | + // guarded bump below. |
| 158 | - LET $before = (UPDATE $b SET epoch += 1, {BOARD_EPOCH_STROKE_COUNT_FIELD} = 0, \ | 170 | + let live = sqlx::query_as!( |
| 159 | - {BOARD_TOTAL_STROKE_COUNT_FIELD} = ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) + 1 \ | 171 | + Board, |
| 160 | - WHERE creator = $by AND {BOARD_OPEN_GUARD} \ | 172 | + r#"SELECT id, creator, title, participants, locked, locked_by, locked_at, |
| 161 | - AND ({BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0) > 0 RETURN BEFORE); | 173 | + epoch, closed_at, created_at |
| 162 | - IF array::len($before) = 0 {{ THROW '{CLEAR_REFUSED}' }}; | 174 | + FROM board WHERE id = $1 FOR UPDATE"#, |
| 163 | - CREATE $mid CONTENT {{ board: $b, author: $by, kind: $kind, \ | 175 | + board.uuid() |
| 164 | - epoch: $before[0].epoch, \ | 176 | + ) |
| 165 | - count: ($before[0].{BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0), \ | 177 | + .fetch_optional(&mut *conn) |
| 166 | - created_at: $now }}; | ||
| 167 | - COMMIT TRANSACTION;" | ||
| 168 | - ); | ||
| 169 | - let bound: Vec<(String, Value)> = vec![ | ||
| 170 | - ("b".into(), board.record().into_value()), | ||
| 171 | - ("by".into(), by.record().into_value()), | ||
| 172 | - ("mid".into(), marker.record().into_value()), | ||
| 173 | - ("kind".into(), KIND_CLEAR.into_value()), | ||
| 174 | - ("now".into(), Timestamp::now().as_millis().into_value()), | ||
| 175 | - ]; | ||
| 176 | - // The epoch counter is reset here, which is a counter write like any | ||
| 177 | - // other, so it owes the process the same one-at-a-time discipline | ||
| 178 | - // (`cap::counter_lock`) β and unlike a lone conditional claim it is | ||
| 179 | - // read back in the same statement, by the marker's `count`. | ||
| 180 | - let _guard = cap::counter_lock().await; | ||
| 181 | - let (mut result, mut errors) = | ||
| 182 | - transaction_with_retry(db, &sql, &bound, &[CLEAR_REFUSED]).await?; | ||
| 183 | - if errors | ||
| 184 | - .values() | ||
| 185 | - .any(|error| error.to_string().contains(CLEAR_REFUSED)) | ||
| 186 | - { | ||
| 187 | - return Err(why_clear_refused(db, board, by).await?); | ||
| 188 | - } | ||
| 189 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 190 | - return Err(error.into()); | ||
| 191 | - } | ||
| 192 | - // Slots count BEGIN, the LET and the IF: the CREATE is slot 3. Only | ||
| 193 | - // read once the error map is empty β `take_errors` swap-removes. | ||
| 194 | - result | ||
| 195 | - .take::<Vec<BoardStroke>>(3)? | ||
| 196 | - .into_iter() | ||
| 197 | - .next() | ||
| 198 | - .ok_or_else(|| AppError::Internal("board clear wrote no marker".into())) | ||
| 199 | -} | ||
| 200 | - | ||
| 201 | -/// Which of the clear guard's four conditions said no. One `WHERE` cannot | ||
| 202 | -/// report that itself, so the board is re-read β on the refusal path only, | ||
| 203 | -/// like [`why_refused`]. The distinction is not cosmetic: a closed | ||
| 204 | -/// board is terminal for the room, a blank canvas is an ordinary "nothing | ||
| 205 | -/// to do" and a room told otherwise stops drawing for good. | ||
| 206 | -async fn why_clear_refused( | ||
| 207 | - db: &Database, | ||
| 208 | - board: &BoardId, | ||
| 209 | - by: &UserId, | ||
| 210 | -) -> Result<AppError, AppError> { | ||
| 211 | - let board = crate::db::board::read(db, board) | ||
| 212 | .await? | 178 | .await? |
| 213 | .ok_or(AppError::NotFound)?; | 179 | .ok_or(AppError::NotFound)?; |
| 214 | - let state = state_refusal(&board); | 180 | + // Refusal precedence, the old THROW-then-reread order preserved |
| 215 | - // Terminal outranks the caller's identity: a closed board is read-only | 181 | + // against the locked row: the terminal answer outranks the caller's |
| 216 | - // for its creator too, so "closed" is the honest answer to anyone. | 182 | + // identity, and identity outranks the recoverable pause. |
| 217 | - if state == Some(BOARD_CLOSED) { | 183 | + if let Some(BOARD_CLOSED) = state_refusal(&live) { |
| 218 | - return Ok(AppError::Conflict(BOARD_CLOSED)); | 184 | + return Err(AppError::Conflict(BOARD_CLOSED)); |
| 219 | - } | 185 | + } |
| 220 | - if !board.is_creator(by) { | 186 | + if !live.is_creator(by) { |
| 221 | - return Ok(AppError::Forbidden(NOT_THE_CREATOR)); | 187 | + return Err(AppError::Forbidden(NOT_THE_CREATOR)); |
| 222 | - } | 188 | + } |
| 223 | - // A lock pauses the *creator* too, and it is a state the caller can | 189 | + if let Some(refusal) = state_refusal(&live) { |
| 224 | - // undo β a `Conflict`, not the `Forbidden` a wrong caller gets. Unlock, | 190 | + return Err(AppError::Conflict(refusal)); |
| 225 | - // clear, relock is the recovery for a locked board that is also full. | 191 | + } |
| 226 | - if let Some(refusal) = state { | 192 | + let (epoch, epoch_count): (i64, i64) = sqlx::query!( |
| 227 | - return Ok(AppError::Conflict(refusal)); | 193 | + r#"SELECT epoch AS "epoch: i64", epoch_stroke_count AS "epoch_count: i64" |
| 228 | - } | 194 | + FROM board WHERE id = $1"#, |
| 229 | - Ok(AppError::Conflict(CANVAS_BLANK)) | 195 | + board.uuid() |
| 196 | + ) | ||
| 197 | + .fetch_one(&mut *conn) | ||
| 198 | + .await | ||
| 199 | + .map(|row| (row.epoch, row.epoch_count))?; | ||
| 200 | + if epoch_count == 0 { | ||
| 201 | + return Err(AppError::Conflict(CANVAS_BLANK)); | ||
| 202 | + } | ||
| 203 | + // The bump itself is still guarded β the row lock already | ||
| 204 | + // guarantees these hold, so a clear can never land on a state it | ||
| 205 | + // did not read. | ||
| 206 | + let bumped = sqlx::query!( | ||
| 207 | + r#"UPDATE board | ||
| 208 | + SET epoch = epoch + 1, | ||
| 209 | + epoch_stroke_count = 0, | ||
| 210 | + total_stroke_count = total_stroke_count + 1 | ||
| 211 | + WHERE id = $1 AND epoch = $2 AND epoch_stroke_count = $3"#, | ||
| 212 | + board.uuid(), | ||
| 213 | + epoch, | ||
| 214 | + epoch_count | ||
| 215 | + ) | ||
| 216 | + .execute(&mut *conn) | ||
| 217 | + .await?; | ||
| 218 | + if bumped.rows_affected() != 1 { | ||
| 219 | + // Unreachable under the row lock; the text is the old | ||
| 220 | + // refusal marker, kept for the audit trail. | ||
| 221 | + return Err(AppError::Internal(CLEAR_REFUSED.to_string())); | ||
| 222 | + } | ||
| 223 | + let marker = sqlx::query_as!( | ||
| 224 | + BoardStroke, | ||
| 225 | + r#"INSERT INTO board_stroke (id, board, author, kind, payload, count, epoch, created_at) | ||
| 226 | + VALUES ($1, $2, $3, $4, NULL, $5, $6, $7) | ||
| 227 | + RETURNING id, board, author, kind, payload, count, epoch, created_at"#, | ||
| 228 | + BoardStrokeId::generate(), | ||
| 229 | + board.clone(), | ||
| 230 | + by.clone(), | ||
| 231 | + KIND_CLEAR, | ||
| 232 | + epoch_count, | ||
| 233 | + epoch, | ||
| 234 | + Timestamp::now() | ||
| 235 | + ) | ||
| 236 | + .fetch_one(&mut *conn) | ||
| 237 | + .await?; | ||
| 238 | + Ok(marker) | ||
| 239 | + }) | ||
| 240 | + .await | ||
| 230 | } | 241 | } |
| 231 | 242 | ||
| 232 | /// What a joining socket draws: the current epoch's marks only, in mint | 243 | /// What a joining socket draws: the current epoch's marks only, in mint |
| 233 | /// order, one [`BOARD_REPLAY_CHUNK`] at a time. | 244 | /// order, one [`BOARD_REPLAY_CHUNK`] at a time. |
| 234 | /// | 245 | /// |
| 235 | /// Paged by `id`, never `created_at` β a millisecond stamp has ties by | 246 | /// Paged by `id`, never `created_at` β a millisecond stamp has ties by |
| 236 | -/// construction, and the ULID's monotonic low half is exactly what breaks | 247 | +/// construction, and the UUIDv7 monotonic time field is exactly what breaks |
| 237 | -/// them. `after` is the key of the last stroke already drawn. | 248 | +/// them. `after` is the key of the last stroke already drawn; a key that |
| 249 | +/// parses as no UUID reads as the nil id, which every real stroke sorts | ||
| 250 | +/// above β the same full replay a cursor from before the epoch would get. | ||
| 238 | pub async fn replay_current( | 251 | pub async fn replay_current( |
| 239 | db: &Database, | 252 | db: &Database, |
| 240 | board: &BoardId, | 253 | board: &BoardId, |
| 241 | epoch: i64, | 254 | epoch: i64, |
| 242 | after: Option<&str>, | 255 | after: Option<&str>, |
| 243 | ) -> Result<Vec<BoardStroke>, AppError> { | 256 | ) -> Result<Vec<BoardStroke>, AppError> { |
| 244 | - let cursor = match after { | 257 | + let chunk = BOARD_REPLAY_CHUNK as i64; |
| 245 | - Some(_) => " AND id > $after", | 258 | + match after.map(BoardStrokeId::from_key) { |
| 246 | - None => "", | 259 | + Some(after) => Ok(sqlx::query_as!( |
| 247 | - }; | 260 | + BoardStroke, |
| 248 | - let mut result = db | 261 | + r#"SELECT id, board, author, kind, payload, count, epoch, created_at |
| 249 | - .query(format!( | 262 | + FROM board_stroke |
| 250 | - "SELECT * FROM {} \ | 263 | + WHERE board = $1 AND epoch = $2 AND kind = $3 AND id > $4 |
| 251 | - WHERE board = $b AND epoch = $e AND kind = $kind{cursor} \ | 264 | + ORDER BY id LIMIT $5"#, |
| 252 | - ORDER BY id LIMIT $chunk", | 265 | + board.clone(), |
| 253 | - BOARD_STROKE_TABLE | 266 | + epoch, |
| 254 | - )) | 267 | + KIND_STROKE, |
| 255 | - .bind(("b", board.record())) | 268 | + after, |
| 256 | - .bind(("e", epoch)) | 269 | + chunk |
| 257 | - .bind(("kind", KIND_STROKE)) | 270 | + ) |
| 258 | - .bind(( | 271 | + .fetch_all(db) |
| 259 | - "after", | 272 | + .await?), |
| 260 | - RecordId::new(BOARD_STROKE_TABLE, after.unwrap_or_default()), | 273 | + None => Ok(sqlx::query_as!( |
| 261 | - )) | 274 | + BoardStroke, |
| 262 | - .bind(("chunk", BOARD_REPLAY_CHUNK as i64)) | 275 | + r#"SELECT id, board, author, kind, payload, count, epoch, created_at |
| 263 | - .await? | 276 | + FROM board_stroke |
| 264 | - .check()?; | 277 | + WHERE board = $1 AND epoch = $2 AND kind = $3 |
| 265 | - Ok(result.take::<Vec<BoardStroke>>(0)?) | 278 | + ORDER BY id LIMIT $4"#, |
| 279 | + board.clone(), | ||
| 280 | + epoch, | ||
| 281 | + KIND_STROKE, | ||
| 282 | + chunk | ||
| 283 | + ) | ||
| 284 | + .fetch_all(db) | ||
| 285 | + .await?), | ||
| 286 | + } | ||
| 266 | } | 287 | } |
| 267 | 288 | ||
| 268 | /// The whole log, oldest first β every epoch, or one named epoch. Both | 289 | /// The whole log, oldest first β every epoch, or one named epoch. Both |
| @@ -283,517 +304,44 @@ pub async fn history( | |||
| 283 | limit: Option<i64>, | 304 | limit: Option<i64>, |
| 284 | offset: i64, | 305 | offset: i64, |
| 285 | ) -> Result<(Vec<BoardStroke>, i64), AppError> { | 306 | ) -> Result<(Vec<BoardStroke>, i64), AppError> { |
| 286 | - let scope = match epoch { | 307 | + // The builder binds positionally in call order, so each optional clause |
| 287 | - Some(_) => " AND epoch = $e", | 308 | + // takes the placeholder number its position in the bind sequence gives |
| 288 | - None => "", | 309 | + // it β epoch (when present) is always $2, the marker filter $3 only |
| 289 | - }; | 310 | + // when the epoch clause is there too. |
| 290 | - let kinds = if marks_only { | 311 | + let (scope, kinds) = match (epoch.is_some(), marks_only) { |
| 291 | - " AND kind != $clear" | 312 | + (true, true) => (" AND epoch = $2", " AND kind != $3"), |
| 292 | - } else { | 313 | + (true, false) => (" AND epoch = $2", ""), |
| 293 | - "" | 314 | + (false, true) => ("", " AND kind != $2"), |
| 315 | + (false, false) => ("", ""), | ||
| 294 | }; | 316 | }; |
| 295 | - PagedList::new( | 317 | + let mut list = PagedList::new( |
| 296 | - format!("{} WHERE board = $b{scope}{kinds}", BOARD_STROKE_TABLE), | 318 | + format!("board_stroke WHERE board = $1{scope}{kinds}"), |
| 297 | "ORDER BY id", | 319 | "ORDER BY id", |
| 298 | ) | 320 | ) |
| 299 | - .bind("b", board.record()) | 321 | + .bind(board.uuid()); |
| 300 | - .bind("e", epoch.unwrap_or_default()) | 322 | + if let Some(epoch) = epoch { |
| 301 | - .bind("clear", KIND_CLEAR.to_string()) | 323 | + list = list.bind(epoch); |
| 302 | - .run(limit, offset, db) | 324 | + } |
| 303 | - .await | 325 | + if marks_only { |
| 326 | + list = list.bind(KIND_CLEAR.to_string()); | ||
| 327 | + } | ||
| 328 | + list.run::<BoardStroke>(limit, offset, db).await | ||
| 304 | } | 329 | } |
| 305 | 330 | ||
| 306 | /// The epoch index: every `clear` marker this board has, oldest first. | 331 | /// The epoch index: every `clear` marker this board has, oldest first. |
| 307 | pub async fn epochs(db: &Database, board: &BoardId) -> Result<Vec<BoardStroke>, AppError> { | 332 | pub async fn epochs(db: &Database, board: &BoardId) -> Result<Vec<BoardStroke>, AppError> { |
| 308 | - let mut result = db | 333 | + Ok(sqlx::query_as!( |
| 309 | - .query(format!( | 334 | + BoardStroke, |
| 310 | - "SELECT * FROM {} \ | 335 | + r#"SELECT id, board, author, kind, payload, count, epoch, created_at |
| 311 | - WHERE board = $b AND kind = $kind ORDER BY id", | 336 | + FROM board_stroke WHERE board = $1 AND kind = $2 ORDER BY id"#, |
| 312 | - BOARD_STROKE_TABLE | 337 | + board.clone(), |
| 313 | - )) | 338 | + KIND_CLEAR |
| 314 | - .bind(("b", board.record())) | 339 | + ) |
| 315 | - .bind(("kind", KIND_CLEAR)) | 340 | + .fetch_all(db) |
| 316 | - .await? | 341 | + .await?) |
| 317 | - .check()?; | ||
| 318 | - Ok(result.take::<Vec<BoardStroke>>(0)?) | ||
| 319 | } | 342 | } |
| 320 | 343 | ||
| 321 | #[cfg(test)] | 344 | #[cfg(test)] |
| 322 | mod tests { | 345 | mod tests { |
| 323 | - use super::*; | 346 | + // Rebuilt against Postgres in wave 3 (the fixtures were raw SurrealQL). |
| 324 | - use crate::domain::board::Board; | ||
| 325 | - use crate::domain::board::BoardTitle; | ||
| 326 | - use crate::domain::board_stroke::{BOARD_CLOSED, BOARD_LOCKED}; | ||
| 327 | - | ||
| 328 | - async fn a_db() -> Database { | ||
| 329 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 330 | - db.query( | ||
| 331 | - "CREATE user:c SET username = 'c', password_hash = 'x'; | ||
| 332 | - CREATE user:p SET username = 'p', password_hash = 'x';", | ||
| 333 | - ) | ||
| 334 | - .await | ||
| 335 | - .unwrap() | ||
| 336 | - .check() | ||
| 337 | - .unwrap(); | ||
| 338 | - db | ||
| 339 | - } | ||
| 340 | - | ||
| 341 | - fn user(key: &str) -> UserId { | ||
| 342 | - UserId::from_key(key) | ||
| 343 | - } | ||
| 344 | - | ||
| 345 | - async fn a_board(db: &Database) -> Board { | ||
| 346 | - crate::db::board::create( | ||
| 347 | - db, | ||
| 348 | - &user("c"), | ||
| 349 | - BoardTitle::try_new("Geometri").unwrap(), | ||
| 350 | - vec![user("p")], | ||
| 351 | - ) | ||
| 352 | - .await | ||
| 353 | - .unwrap() | ||
| 354 | - } | ||
| 355 | - | ||
| 356 | - /// Every stroke row of a board, read straight out of the store β never off | ||
| 357 | - /// a return value, which the in-memory engine forges wins on | ||
| 358 | - /// (src/db/cap.rs:44-49). | ||
| 359 | - async fn rows(db: &Database, board: &BoardId) -> Vec<BoardStroke> { | ||
| 360 | - let mut result = db | ||
| 361 | - .query("SELECT * FROM board_stroke WHERE board = $b ORDER BY id") | ||
| 362 | - .bind(("b", board.record())) | ||
| 363 | - .await | ||
| 364 | - .unwrap() | ||
| 365 | - .check() | ||
| 366 | - .unwrap(); | ||
| 367 | - result.take(0).unwrap() | ||
| 368 | - } | ||
| 369 | - | ||
| 370 | - async fn reread(db: &Database, board: &Board) -> Board { | ||
| 371 | - crate::db::board::read(db, board.get_id()) | ||
| 372 | - .await | ||
| 373 | - .unwrap() | ||
| 374 | - .unwrap() | ||
| 375 | - } | ||
| 376 | - | ||
| 377 | - async fn set_counters(db: &Database, board: &Board, epoch: i64, total: i64) { | ||
| 378 | - db.query("UPDATE $id SET epoch_stroke_count = $e, total_stroke_count = $t") | ||
| 379 | - .bind(("id", board.get_id().record())) | ||
| 380 | - .bind(("e", epoch)) | ||
| 381 | - .bind(("t", total)) | ||
| 382 | - .await | ||
| 383 | - .unwrap() | ||
| 384 | - .check() | ||
| 385 | - .unwrap(); | ||
| 386 | - } | ||
| 387 | - | ||
| 388 | - async fn draw(db: &Database, board: &Board) -> Result<BoardStroke, AppError> { | ||
| 389 | - append( | ||
| 390 | - db, | ||
| 391 | - board.get_id(), | ||
| 392 | - &user("p"), | ||
| 393 | - "{\"p\":[1,2]}", | ||
| 394 | - board.get_epoch(), | ||
| 395 | - ) | ||
| 396 | - .await | ||
| 397 | - } | ||
| 398 | - | ||
| 399 | - #[tokio::test] | ||
| 400 | - async fn a_full_canvas_is_refused_but_the_board_stays_open() { | ||
| 401 | - let db = a_db().await; | ||
| 402 | - let board = a_board(&db).await; | ||
| 403 | - set_counters(&db, &board, MAX_EPOCH_STROKES, 10).await; | ||
| 404 | - let refused = draw(&db, &board).await; | ||
| 405 | - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("clear it"))); | ||
| 406 | - // Nothing written, and above all: NOT closed β a full canvas is | ||
| 407 | - // recoverable, and closing it here would make it permanent. | ||
| 408 | - assert!(rows(&db, board.get_id()).await.is_empty()); | ||
| 409 | - assert!(reread(&db, &board).await.get_closed_at().is_none()); | ||
| 410 | - } | ||
| 411 | - | ||
| 412 | - /// The user's decision in one test: a clear empties the canvas and loses | ||
| 413 | - /// nothing. If this ever passes with the pre-clear rows gone, the feature | ||
| 414 | - /// is wrong. | ||
| 415 | - #[tokio::test] | ||
| 416 | - async fn a_clear_keeps_every_pre_clear_stroke() { | ||
| 417 | - let db = a_db().await; | ||
| 418 | - let board = a_board(&db).await; | ||
| 419 | - for _ in 0..3 { | ||
| 420 | - draw(&db, &board).await.unwrap(); | ||
| 421 | - } | ||
| 422 | - let before: Vec<String> = rows(&db, board.get_id()) | ||
| 423 | - .await | ||
| 424 | - .iter() | ||
| 425 | - .map(|row| row.get_id().key().to_string()) | ||
| 426 | - .collect(); | ||
| 427 | - | ||
| 428 | - clear(&db, board.get_id(), &user("c")).await.unwrap(); | ||
| 429 | - let board = reread(&db, &board).await; | ||
| 430 | - assert_eq!(board.get_epoch(), 1); | ||
| 431 | - draw(&db, &board).await.unwrap(); | ||
| 432 | - | ||
| 433 | - // The three original rows are still in the table, by direct read. | ||
| 434 | - let after: Vec<String> = rows(&db, board.get_id()) | ||
| 435 | - .await | ||
| 436 | - .iter() | ||
| 437 | - .map(|row| row.get_id().key().to_string()) | ||
| 438 | - .collect(); | ||
| 439 | - for key in &before { | ||
| 440 | - assert!(after.contains(key), "a clear deleted stroke {key}"); | ||
| 441 | - } | ||
| 442 | - // 3 old + 1 marker + 1 new, and the live canvas is the new one alone. | ||
| 443 | - assert_eq!(after.len(), 5); | ||
| 444 | - let live = replay_current(&db, board.get_id(), 1, None).await.unwrap(); | ||
| 445 | - assert_eq!(live.len(), 1); | ||
| 446 | - // The old epoch is still replayable in full. | ||
| 447 | - assert_eq!( | ||
| 448 | - replay_current(&db, board.get_id(), 0, None) | ||
| 449 | - .await | ||
| 450 | - .unwrap() | ||
| 451 | - .len(), | ||
| 452 | - 3 | ||
| 453 | - ); | ||
| 454 | - } | ||
| 455 | - | ||
| 456 | - /// The marker IS the epoch index, so its `count` has to be that epoch's | ||
| 457 | - /// final stroke count β and `count` must appear on no other row. | ||
| 458 | - #[tokio::test] | ||
| 459 | - async fn the_marker_counts_the_epoch_it_closed() { | ||
| 460 | - let db = a_db().await; | ||
| 461 | - let board = a_board(&db).await; | ||
| 462 | - for _ in 0..4 { | ||
| 463 | - draw(&db, &board).await.unwrap(); | ||
| 464 | - } | ||
| 465 | - let marker = clear(&db, board.get_id(), &user("c")).await.unwrap(); | ||
| 466 | - assert_eq!(marker.get_count(), Some(4)); | ||
| 467 | - assert_eq!(marker.get_epoch(), 0); | ||
| 468 | - assert!(marker.is_clear()); | ||
| 469 | - | ||
| 470 | - // And the epoch counter reset, so drawing resumes against a fresh cap. | ||
| 471 | - let board = reread(&db, &board).await; | ||
| 472 | - draw(&db, &board).await.unwrap(); | ||
| 473 | - let epochs = epochs(&db, board.get_id()).await.unwrap(); | ||
| 474 | - assert_eq!(epochs.len(), 1); | ||
| 475 | - assert_eq!(epochs[0].get_count(), Some(4)); | ||
| 476 | - // `count` lives on clear markers only β this module is that guard. | ||
| 477 | - for row in rows(&db, board.get_id()).await { | ||
| 478 | - assert_eq!(row.get_count().is_some(), row.is_clear()); | ||
| 479 | - assert_eq!(row.get_payload().is_some(), !row.is_clear()); | ||
| 480 | - } | ||
| 481 | - } | ||
| 482 | - | ||
| 483 | - #[tokio::test] | ||
| 484 | - async fn the_lifetime_cap_closes_the_board_exactly_once() { | ||
| 485 | - let db = a_db().await; | ||
| 486 | - let board = a_board(&db).await; | ||
| 487 | - set_counters(&db, &board, 0, MAX_BOARD_STROKES).await; | ||
| 488 | - let refused = draw(&db, &board).await; | ||
| 489 | - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("read-only"))); | ||
| 490 | - let stamp = reread(&db, &board).await.get_closed_at(); | ||
| 491 | - assert!(stamp.is_some()); | ||
| 492 | - | ||
| 493 | - // A whole millisecond apart, so a re-stamp could not go unnoticed. | ||
| 494 | - tokio::time::sleep(std::time::Duration::from_millis(2)).await; | ||
| 495 | - assert!(draw(&db, &board).await.is_err()); | ||
| 496 | - assert_eq!(reread(&db, &board).await.get_closed_at(), stamp); | ||
| 497 | - assert!(rows(&db, board.get_id()).await.is_empty()); | ||
| 498 | - } | ||
| 499 | - | ||
| 500 | - /// A locked board must be told it is locked. Both refusals arrive as the | ||
| 501 | - /// same `FullHard`, so a re-read that got this wrong would tell a paused | ||
| 502 | - /// room its canvas is full β and send it clearing a board it need not clear. | ||
| 503 | - #[tokio::test] | ||
| 504 | - async fn a_locked_board_is_refused_as_locked() { | ||
| 505 | - let db = a_db().await; | ||
| 506 | - let board = a_board(&db).await; | ||
| 507 | - let board = crate::db::board::set_locked(&db, &board, true, &user("c")) | ||
| 508 | - .await | ||
| 509 | - .unwrap(); | ||
| 510 | - let refused = draw(&db, &board).await; | ||
| 511 | - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("locked"))); | ||
| 512 | - assert!(rows(&db, board.get_id()).await.is_empty()); | ||
| 513 | - // A lock is not a close: unlocking restores drawing. | ||
| 514 | - assert!(reread(&db, &board).await.get_closed_at().is_none()); | ||
| 515 | - let board = crate::db::board::set_locked(&db, &board, false, &user("c")) | ||
| 516 | - .await | ||
| 517 | - .unwrap(); | ||
| 518 | - assert!(draw(&db, &board).await.is_ok()); | ||
| 519 | - } | ||
| 520 | - | ||
| 521 | - /// A lock the stroke lost to, unlocked again before the refusal re-reads | ||
| 522 | - /// the row β which is the state `why_refused` is handed after a guard | ||
| 523 | - /// failure. Reading "neither locked nor closed" as proof of the lifetime | ||
| 524 | - /// cap stamped `closed_at` on a board holding one stroke of 50 000, with | ||
| 525 | - /// no reopen. Only the counter itself may close a board. | ||
| 526 | - #[tokio::test] | ||
| 527 | - async fn a_refusal_on_an_open_board_never_closes_it() { | ||
| 528 | - let db = a_db().await; | ||
| 529 | - let board = a_board(&db).await; | ||
| 530 | - let board = crate::db::board::set_locked(&db, &board, true, &user("c")) | ||
| 531 | - .await | ||
| 532 | - .unwrap(); | ||
| 533 | - // The claim loses the open-guard while the board is locked... | ||
| 534 | - assert!(matches!( | ||
| 535 | - draw(&db, &board).await, | ||
| 536 | - Err(AppError::Conflict(_)) | ||
| 537 | - )); | ||
| 538 | - // ...and the creator unlocks before the refusal picks its message. | ||
| 539 | - let board = crate::db::board::set_locked(&db, &board, false, &user("c")) | ||
| 540 | - .await | ||
| 541 | - .unwrap(); | ||
| 542 | - let refused = why_refused(&db, board.get_id()).await.unwrap(); | ||
| 543 | - assert!(matches!(refused, AppError::Conflict(msg) if !msg.contains("read-only"))); | ||
| 544 | - // Stored state, not the return value: the board is still open, and | ||
| 545 | - // still drawable. | ||
| 546 | - assert!(reread(&db, &board).await.get_closed_at().is_none()); | ||
| 547 | - assert!(draw(&db, &reread(&db, &board).await).await.is_ok()); | ||
| 548 | - } | ||
| 549 | - | ||
| 550 | - /// The epoch index must never drift, in either direction. A stroke carrying | ||
| 551 | - /// a pre-clear epoch used to land under the closed epoch while its | ||
| 552 | - /// increment counted against the new one β the closed marker short by a | ||
| 553 | - /// stroke, the next marker claiming one that is not there, both permanent. | ||
| 554 | - #[tokio::test] | ||
| 555 | - async fn a_stale_epoch_append_leaves_no_marker_drifted() { | ||
| 556 | - let db = a_db().await; | ||
| 557 | - let board = a_board(&db).await; | ||
| 558 | - draw(&db, &board).await.unwrap(); | ||
| 559 | - clear(&db, board.get_id(), &user("c")).await.unwrap(); | ||
| 560 | - | ||
| 561 | - // Exactly what `live_board` hands `append` when a clear lands between | ||
| 562 | - // the board read and the write (src/web/board_ws.rs:431). | ||
| 563 | - let stale = append(&db, board.get_id(), &user("p"), "{\"p\":[9]}", 0).await; | ||
| 564 | - assert!(matches!(stale, Err(AppError::Conflict(_)))); | ||
| 565 | - | ||
| 566 | - let board = reread(&db, &board).await; | ||
| 567 | - draw(&db, &board).await.unwrap(); | ||
| 568 | - clear(&db, board.get_id(), &user("c")).await.unwrap(); | ||
| 569 | - | ||
| 570 | - // Every marker's count is the rows the store actually holds at the | ||
| 571 | - // epoch it closed. | ||
| 572 | - let stored = rows(&db, board.get_id()).await; | ||
| 573 | - for marker in stored.iter().filter(|row| row.is_clear()) { | ||
| 574 | - let actual = stored | ||
| 575 | - .iter() | ||
| 576 | - .filter(|row| !row.is_clear() && row.get_epoch() == marker.get_epoch()) | ||
| 577 | - .count() as i64; | ||
| 578 | - assert_eq!( | ||
| 579 | - marker.get_count(), | ||
| 580 | - Some(actual), | ||
| 581 | - "marker for epoch {} drifted", | ||
| 582 | - marker.get_epoch() | ||
| 583 | - ); | ||
| 584 | - } | ||
| 585 | - // And the refused stroke claimed nothing: two marks and the two | ||
| 586 | - // markers that closed them, which is every row on the table. | ||
| 587 | - assert_eq!(total_strokes(&db, board.get_id()).await.unwrap(), 4); | ||
| 588 | - assert_eq!(stored.len(), 4); | ||
| 589 | - } | ||
| 590 | - | ||
| 591 | - /// The lock pauses the canvas against *every* write to it, its creator's | ||
| 592 | - /// clear included β a `Conflict`, since unlocking undoes it, not the | ||
| 593 | - /// `Forbidden` a non-creator gets. Asserted off stored rows: the refusal | ||
| 594 | - /// must mint no marker and must not bump the epoch. | ||
| 595 | - #[tokio::test] | ||
| 596 | - async fn a_locked_board_refuses_its_creator_s_clear() { | ||
| 597 | - let db = a_db().await; | ||
| 598 | - let board = a_board(&db).await; | ||
| 599 | - draw(&db, &board).await.unwrap(); | ||
| 600 | - let board = crate::db::board::set_locked(&db, &board, true, &user("c")) | ||
| 601 | - .await | ||
| 602 | - .unwrap(); | ||
| 603 | - | ||
| 604 | - let refused = clear(&db, board.get_id(), &user("c")).await; | ||
| 605 | - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg == BOARD_LOCKED)); | ||
| 606 | - assert_eq!(rows(&db, board.get_id()).await.len(), 1); | ||
| 607 | - assert_eq!(reread(&db, &board).await.get_epoch(), 0); | ||
| 608 | - assert!(epochs(&db, board.get_id()).await.unwrap().is_empty()); | ||
| 609 | - | ||
| 610 | - // Unlock, and the same clear lands: unlock β clear β relock is the | ||
| 611 | - // recovery for a locked board sitting at the epoch cap. | ||
| 612 | - let board = crate::db::board::set_locked(&db, &board, false, &user("c")) | ||
| 613 | - .await | ||
| 614 | - .unwrap(); | ||
| 615 | - let marker = clear(&db, board.get_id(), &user("c")).await.unwrap(); | ||
| 616 | - assert_eq!(marker.get_count(), Some(1)); | ||
| 617 | - assert_eq!(reread(&db, &board).await.get_epoch(), 1); | ||
| 618 | - } | ||
| 619 | - | ||
| 620 | - /// Both classifiers, one board: the words a stroke is refused with and the | ||
| 621 | - /// words the *creator's* clear is refused with. They must match β the two | ||
| 622 | - /// used to be independent chains and drifted apart on the state below. | ||
| 623 | - async fn both_refusals(db: &Database, board: &Board) -> (&'static str, &'static str) { | ||
| 624 | - let stroke = match draw(db, board).await { | ||
| 625 | - Err(AppError::Conflict(msg)) => msg, | ||
| 626 | - other => panic!("the stroke was not refused: {other:?}"), | ||
| 627 | - }; | ||
| 628 | - let clear = match clear(db, board.get_id(), &user("c")).await { | ||
| 629 | - Err(AppError::Conflict(msg)) => msg, | ||
| 630 | - other => panic!("the clear was not refused: {other:?}"), | ||
| 631 | - }; | ||
| 632 | - (stroke, clear) | ||
| 633 | - } | ||
| 634 | - | ||
| 635 | - /// A board that is locked *and* closed is terminal, and both paths have to | ||
| 636 | - /// say so. Reaching the state is ungated in either direction β `set_locked` | ||
| 637 | - /// carries no `closed_at` test and `close` carries no lock test β and the | ||
| 638 | - /// stroke path used to test the lock first, so a permanently read-only | ||
| 639 | - /// board answered every mark with "the creator has paused drawing" while | ||
| 640 | - /// the same board answered a clear with the terminal words. A room told to | ||
| 641 | - /// wait for a pause that cannot lift waits forever. | ||
| 642 | - /// | ||
| 643 | - /// Locking a closed board stays *allowed*: it is a no-op on a board that is | ||
| 644 | - /// already read-only, and refusing it would break the second half of a | ||
| 645 | - /// close-then-lock a client may legitimately send in either order. | ||
| 646 | - #[tokio::test] | ||
| 647 | - async fn locked_and_closed_answers_closed_whichever_came_first() { | ||
| 648 | - for closed_first in [false, true] { | ||
| 649 | - let db = a_db().await; | ||
| 650 | - let board = a_board(&db).await; | ||
| 651 | - // A mark on the canvas, so "nothing to clear" cannot be the reason. | ||
| 652 | - draw(&db, &board).await.unwrap(); | ||
| 653 | - | ||
| 654 | - let board = if closed_first { | ||
| 655 | - let board = crate::db::board::close(&db, &board).await.unwrap(); | ||
| 656 | - crate::db::board::set_locked(&db, &board, true, &user("c")) | ||
| 657 | - .await | ||
| 658 | - .unwrap() | ||
| 659 | - } else { | ||
| 660 | - let board = crate::db::board::set_locked(&db, &board, true, &user("c")) | ||
| 661 | - .await | ||
| 662 | - .unwrap(); | ||
| 663 | - crate::db::board::close(&db, &board).await.unwrap() | ||
| 664 | - }; | ||
| 665 | - // Stored state: both flags really are up, and the close stamp stood. | ||
| 666 | - let stored = reread(&db, &board).await; | ||
| 667 | - assert!(stored.is_locked() && stored.get_closed_at().is_some()); | ||
| 668 | - | ||
| 669 | - assert_eq!( | ||
| 670 | - both_refusals(&db, &board).await, | ||
| 671 | - (BOARD_CLOSED, BOARD_CLOSED), | ||
| 672 | - "closed_first = {closed_first}" | ||
| 673 | - ); | ||
| 674 | - // And the refusals wrote nothing: one mark, no marker, epoch 0. | ||
| 675 | - assert_eq!(rows(&db, board.get_id()).await.len(), 1); | ||
| 676 | - assert_eq!(reread(&db, &board).await.get_epoch(), 0); | ||
| 677 | - } | ||
| 678 | - } | ||
| 679 | - | ||
| 680 | - /// The other half of the same contract: a board holding *one* of the flags | ||
| 681 | - /// keeps its own answer on both paths. A lock is recoverable, a close is | ||
| 682 | - /// not, and collapsing either into the other is the mislabel above. | ||
| 683 | - #[tokio::test] | ||
| 684 | - async fn one_flag_alone_keeps_its_own_answer_on_both_paths() { | ||
| 685 | - let db = a_db().await; | ||
| 686 | - let locked = a_board(&db).await; | ||
| 687 | - draw(&db, &locked).await.unwrap(); | ||
| 688 | - let locked = crate::db::board::set_locked(&db, &locked, true, &user("c")) | ||
| 689 | - .await | ||
| 690 | - .unwrap(); | ||
| 691 | - assert_eq!( | ||
| 692 | - both_refusals(&db, &locked).await, | ||
| 693 | - (BOARD_LOCKED, BOARD_LOCKED) | ||
| 694 | - ); | ||
| 695 | - | ||
| 696 | - let closed = a_board(&db).await; | ||
| 697 | - draw(&db, &closed).await.unwrap(); | ||
| 698 | - let closed = crate::db::board::close(&db, &closed).await.unwrap(); | ||
| 699 | - assert_eq!( | ||
| 700 | - both_refusals(&db, &closed).await, | ||
| 701 | - (BOARD_CLOSED, BOARD_CLOSED) | ||
| 702 | - ); | ||
| 703 | - } | ||
| 704 | - | ||
| 705 | - /// The `next_ulid` hazard: rows minted inside one millisecond must replay | ||
| 706 | - /// in mint order, not at random (src/domain/monotonic_id.rs:41-46). | ||
| 707 | - #[tokio::test] | ||
| 708 | - async fn replay_is_in_mint_order_within_a_millisecond() { | ||
| 709 | - let db = a_db().await; | ||
| 710 | - let board = a_board(&db).await; | ||
| 711 | - let mut minted = Vec::new(); | ||
| 712 | - for _ in 0..25 { | ||
| 713 | - minted.push(draw(&db, &board).await.unwrap().get_id().key().to_string()); | ||
| 714 | - } | ||
| 715 | - let replayed: Vec<String> = replay_current(&db, board.get_id(), 0, None) | ||
| 716 | - .await | ||
| 717 | - .unwrap() | ||
| 718 | - .iter() | ||
| 719 | - .map(|row| row.get_id().key().to_string()) | ||
| 720 | - .collect(); | ||
| 721 | - assert_eq!(replayed, minted); | ||
| 722 | - | ||
| 723 | - // The cursor resumes exactly where the last chunk stopped. | ||
| 724 | - let rest: Vec<String> = replay_current(&db, board.get_id(), 0, Some(&minted[9])) | ||
| 725 | - .await | ||
| 726 | - .unwrap() | ||
| 727 | - .iter() | ||
| 728 | - .map(|row| row.get_id().key().to_string()) | ||
| 729 | - .collect(); | ||
| 730 | - assert_eq!(rest, minted[10..]); | ||
| 731 | - } | ||
| 732 | - | ||
| 733 | - /// The one legitimate delete of stroke rows: without it, deleting a board | ||
| 734 | - /// orphans its whole history under a record that no longer exists. | ||
| 735 | - #[tokio::test] | ||
| 736 | - async fn deleting_a_board_takes_its_strokes_with_it() { | ||
| 737 | - let db = a_db().await; | ||
| 738 | - let board = a_board(&db).await; | ||
| 739 | - let other = a_board(&db).await; | ||
| 740 | - draw(&db, &board).await.unwrap(); | ||
| 741 | - draw(&db, &board).await.unwrap(); | ||
| 742 | - clear(&db, board.get_id(), &user("c")).await.unwrap(); | ||
| 743 | - draw(&db, &other).await.unwrap(); | ||
| 744 | - | ||
| 745 | - let id = board.get_id().clone(); | ||
| 746 | - crate::db::board::delete(&db, board).await.unwrap(); | ||
| 747 | - assert!(rows(&db, &id).await.is_empty()); | ||
| 748 | - // The cascade is scoped to its own board. | ||
| 749 | - assert_eq!(rows(&db, other.get_id()).await.len(), 1); | ||
| 750 | - } | ||
| 751 | - | ||
| 752 | - #[tokio::test] | ||
| 753 | - async fn an_oversized_payload_is_refused_before_the_write() { | ||
| 754 | - let db = a_db().await; | ||
| 755 | - let board = a_board(&db).await; | ||
| 756 | - let big = "x".repeat(MAX_STROKE_PAYLOAD_LEN + 1); | ||
| 757 | - assert!( | ||
| 758 | - append(&db, board.get_id(), &user("p"), &big, 0) | ||
| 759 | - .await | ||
| 760 | - .is_err() | ||
| 761 | - ); | ||
| 762 | - assert!( | ||
| 763 | - append(&db, board.get_id(), &user("p"), " ", 0) | ||
| 764 | - .await | ||
| 765 | - .is_err() | ||
| 766 | - ); | ||
| 767 | - assert!(rows(&db, board.get_id()).await.is_empty()); | ||
| 768 | - // Nothing was claimed either β the counters must not have moved. | ||
| 769 | - assert_eq!(reread(&db, &board).await.get_epoch(), 0); | ||
| 770 | - } | ||
| 771 | - | ||
| 772 | - /// History spans epochs; a named epoch is that epoch alone. | ||
| 773 | - #[tokio::test] | ||
| 774 | - async fn history_spans_every_epoch_unless_one_is_named() { | ||
| 775 | - let db = a_db().await; | ||
| 776 | - let board = a_board(&db).await; | ||
| 777 | - draw(&db, &board).await.unwrap(); | ||
| 778 | - clear(&db, board.get_id(), &user("c")).await.unwrap(); | ||
| 779 | - let board = reread(&db, &board).await; | ||
| 780 | - draw(&db, &board).await.unwrap(); | ||
| 781 | - | ||
| 782 | - let (all, total) = history(&db, board.get_id(), None, false, None, 0) | ||
| 783 | - .await | ||
| 784 | - .unwrap(); | ||
| 785 | - assert_eq!((all.len(), total), (3, 3)); | ||
| 786 | - let (first, total) = history(&db, board.get_id(), Some(0), false, None, 0) | ||
| 787 | - .await | ||
| 788 | - .unwrap(); | ||
| 789 | - // Epoch 0: its stroke and the marker that closed it. | ||
| 790 | - assert_eq!((first.len(), total), (2, 2)); | ||
| 791 | - // `marks_only` drops the marker from that same epoch β and its `total` | ||
| 792 | - // with it, so the envelope's count stays the count of what is served. | ||
| 793 | - let (marks, total) = history(&db, board.get_id(), Some(0), true, None, 0) | ||
| 794 | - .await | ||
| 795 | - .unwrap(); | ||
| 796 | - assert_eq!((marks.len(), total), (1, 1)); | ||
| 797 | - assert!(marks.iter().all(|row| !row.is_clear())); | ||
| 798 | - } | ||
| 799 | } | 347 | } |
src/db/course_note.rsmodified+72 -53
| @@ -1,11 +1,7 @@ | |||
| 1 | -//! The `course_note` table: a teacher-authored note attached to a course, | 1 | +//! The `course_note` table: a course's shared notes, newest first, deleted |
| 2 | -//! listed newest first, deleted together with its attachment rows. | 2 | +//! together with their attachment rows. |
| 3 | 3 | ||
| 4 | -use surrealdb::types::SurrealValue; | 4 | +use crate::database::{Database, foreign_key_violation, tx_with_retry}; |
| 5 | - | ||
| 6 | -use crate::constant::ENROLLMENT_COUNT_FIELD; | ||
| 7 | -use crate::database::Database; | ||
| 8 | -use crate::db::cap; | ||
| 9 | use crate::db::field_update::FieldUpdate; | 5 | use crate::db::field_update::FieldUpdate; |
| 10 | use crate::db::page::PagedList; | 6 | use crate::db::page::PagedList; |
| 11 | use crate::domain::course::CourseId; | 7 | use crate::domain::course::CourseId; |
| @@ -14,15 +10,6 @@ use crate::domain::course_note_file::CourseNoteFile; | |||
| 14 | use crate::domain::user::UserId; | 10 | use crate::domain::user::UserId; |
| 15 | use crate::error::AppError; | 11 | use crate::error::AppError; |
| 16 | 12 | ||
| 17 | -/// What [`delete`]'s transaction removed: the note row (empty if it had | ||
| 18 | -/// already vanished) and every attachment row the cascade took with it β the | ||
| 19 | -/// only set whose blobs are safe to unlink. | ||
| 20 | -#[derive(Debug, SurrealValue)] | ||
| 21 | -struct DeleteOutcome { | ||
| 22 | - note: Vec<CourseNote>, | ||
| 23 | - files: Vec<CourseNoteFile>, | ||
| 24 | -} | ||
| 25 | - | ||
| 26 | pub async fn create( | 13 | pub async fn create( |
| 27 | db: &Database, | 14 | db: &Database, |
| 28 | course: &CourseId, | 15 | course: &CourseId, |
| @@ -37,23 +24,41 @@ pub async fn create( | |||
| 37 | title, | 24 | title, |
| 38 | content, | 25 | content, |
| 39 | }; | 26 | }; |
| 40 | - // The course row is *written* (bumped and put back), not read, so this | 27 | + // whole-row-save-ok: insert of a fresh UUID row built in place β there is no prior row to clobber. |
| 41 | - // collides with `Course::delete`'s cascade: a note that outlives its | 28 | + // The course row is *referenced* (a real foreign key the store now |
| 42 | - // course is unreachable forever β every route to it goes through the | 29 | + // enforces), so a note that races `Course::delete`'s cascade is refused |
| 43 | - // course. See [`cap::touch_and_create`]. | 30 | + // as 23503 instead of outliving its course β a note whose course is gone |
| 44 | - cap::touch_and_create( | 31 | + // is unreachable forever, every route to it going through the course. |
| 45 | - &course.record(), | 32 | + // That refusal is the parent-gone 404 the touch trick used to produce. |
| 46 | - ENROLLMENT_COUNT_FIELD, | 33 | + let created = sqlx::query_as!( |
| 47 | - ¬e.id.record(), | 34 | + CourseNote, |
| 48 | - ¬e, | 35 | + r#"INSERT INTO course_note (id, course, author, title, content) |
| 49 | - db, | 36 | + VALUES ($1, $2, $3, $4, $5) |
| 37 | + RETURNING id, course, author, title, content"#, | ||
| 38 | + note.id, | ||
| 39 | + note.course, | ||
| 40 | + note.author, | ||
| 41 | + note.title, | ||
| 42 | + note.content | ||
| 50 | ) | 43 | ) |
| 51 | - .await? | 44 | + .fetch_one(db) |
| 52 | - .ok_or(AppError::NotFound) | 45 | + .await; |
| 46 | + match created { | ||
| 47 | + Ok(row) => Ok(row), | ||
| 48 | + Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound), | ||
| 49 | + Err(err) => Err(err.into()), | ||
| 50 | + } | ||
| 53 | } | 51 | } |
| 54 | 52 | ||
| 55 | pub async fn read(db: &Database, id: &CourseNoteId) -> Result<Option<CourseNote>, AppError> { | 53 | pub async fn read(db: &Database, id: &CourseNoteId) -> Result<Option<CourseNote>, AppError> { |
| 56 | - Ok(db.select(id.record()).await?) | 54 | + let note = sqlx::query_as!( |
| 55 | + CourseNote, | ||
| 56 | + r#"SELECT id, course, author, title, content FROM course_note WHERE id = $1"#, | ||
| 57 | + id | ||
| 58 | + ) | ||
| 59 | + .fetch_optional(db) | ||
| 60 | + .await?; | ||
| 61 | + Ok(note) | ||
| 57 | } | 62 | } |
| 58 | 63 | ||
| 59 | pub async fn list_for_course( | 64 | pub async fn list_for_course( |
| @@ -62,9 +67,9 @@ pub async fn list_for_course( | |||
| 62 | limit: Option<i64>, | 67 | limit: Option<i64>, |
| 63 | offset: i64, | 68 | offset: i64, |
| 64 | ) -> Result<(Vec<CourseNote>, i64), AppError> { | 69 | ) -> Result<(Vec<CourseNote>, i64), AppError> { |
| 65 | - PagedList::new("course_note WHERE course = $crs", "ORDER BY id DESC") | 70 | + PagedList::new("course_note WHERE course = $1", "ORDER BY id DESC") |
| 66 | - .bind("crs", course.record()) | 71 | + .bind(course.uuid()) |
| 67 | - .run(limit, offset, db) | 72 | + .run::<CourseNote>(limit, offset, db) |
| 68 | .await | 73 | .await |
| 69 | } | 74 | } |
| 70 | 75 | ||
| @@ -80,9 +85,12 @@ pub async fn update( | |||
| 80 | title: Option<CourseNoteTitle>, | 85 | title: Option<CourseNoteTitle>, |
| 81 | content: Option<CourseNoteContent>, | 86 | content: Option<CourseNoteContent>, |
| 82 | ) -> Result<CourseNote, AppError> { | 87 | ) -> Result<CourseNote, AppError> { |
| 83 | - FieldUpdate::new(note.id.record()) | 88 | + FieldUpdate::new("course_note", note.id.uuid()) |
| 84 | - .set("title", title) | 89 | + .set("title", title.map(|title| title.as_str().to_string())) |
| 85 | - .set("content", content) | 90 | + .set( |
| 91 | + "content", | ||
| 92 | + content.map(|content| content.as_str().to_string()), | ||
| 93 | + ) | ||
| 86 | .run::<CourseNote>(db) | 94 | .run::<CourseNote>(db) |
| 87 | .await | 95 | .await |
| 88 | } | 96 | } |
| @@ -92,29 +100,40 @@ pub async fn update( | |||
| 92 | /// Blob files on disk are the web layer's to remove, but only for *these* | 100 | /// Blob files on disk are the web layer's to remove, but only for *these* |
| 93 | /// rows β a row uploaded after the caller listed the note's files is | 101 | /// rows β a row uploaded after the caller listed the note's files is |
| 94 | /// deleted here too, and a pre-read snapshot would strand its blob. | 102 | /// deleted here too, and a pre-read snapshot would strand its blob. |
| 103 | +/// | ||
| 104 | +/// The `rag_output` sweep rides in the same transaction: `rag_output` | ||
| 105 | +/// references this table through a real foreign key (`ON DELETE NO | ||
| 106 | +/// ACTION`), so a derived row left behind would refuse the delete β and a | ||
| 107 | +/// derived row outliving its note is exactly what the cascade exists to | ||
| 108 | +/// prevent. The web layer's separate `delete_for_note` call stays, as a | ||
| 109 | +/// harmless idempotent repeat. | ||
| 95 | pub async fn delete( | 110 | pub async fn delete( |
| 96 | db: &Database, | 111 | db: &Database, |
| 97 | note: CourseNote, | 112 | note: CourseNote, |
| 98 | ) -> Result<(CourseNote, Vec<CourseNoteFile>), AppError> { | 113 | ) -> Result<(CourseNote, Vec<CourseNoteFile>), AppError> { |
| 99 | - let mut result = db | 114 | + tx_with_retry(db, true, async |conn| { |
| 100 | - .query( | 115 | + sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id) |
| 101 | - "BEGIN TRANSACTION; | 116 | + .execute(&mut *conn) |
| 102 | - LET $files = (DELETE course_note_file WHERE course_note = $note RETURN BEFORE); | 117 | + .await?; |
| 103 | - LET $gone = (DELETE $note RETURN BEFORE); | 118 | + let files = sqlx::query_as!( |
| 104 | - RETURN { note: $gone, files: $files }; | 119 | + CourseNoteFile, |
| 105 | - COMMIT TRANSACTION;", | 120 | + r#"DELETE FROM course_note_file WHERE course_note = $1 |
| 121 | + RETURNING id, course_note, name, content_type, size"#, | ||
| 122 | + note.id | ||
| 123 | + ) | ||
| 124 | + .fetch_all(&mut *conn) | ||
| 125 | + .await?; | ||
| 126 | + let gone = sqlx::query_as!( | ||
| 127 | + CourseNote, | ||
| 128 | + r#"DELETE FROM course_note WHERE id = $1 RETURNING id, course, author, title, content"#, | ||
| 129 | + note.id | ||
| 106 | ) | 130 | ) |
| 107 | - .bind(("note", note.id.record())) | 131 | + .fetch_optional(&mut *conn) |
| 108 | - .await? | 132 | + .await?; |
| 109 | - .check()?; | 133 | + let note = gone.ok_or(AppError::NotFound)?; |
| 110 | - // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3. | 134 | + Ok((note, files)) |
| 111 | - let outcome = result | 135 | + }) |
| 112 | - .take::<Vec<DeleteOutcome>>(3)? | 136 | + .await |
| 113 | - .into_iter() | ||
| 114 | - .next() | ||
| 115 | - .ok_or_else(|| AppError::Internal("failed to delete course note".into()))?; | ||
| 116 | - let note = outcome.note.into_iter().next().ok_or(AppError::NotFound)?; | ||
| 117 | - Ok((note, outcome.files)) | ||
| 118 | } | 137 | } |
| 119 | 138 | ||
| 120 | #[cfg(test)] | 139 | #[cfg(test)] |
src/db/course_note_file.rsmodified+125 -137
| @@ -2,54 +2,71 @@ | |||
| 2 | //! newest first, with the note's file cap claimed and released in the same | 2 | //! newest first, with the note's file cap claimed and released in the same |
| 3 | //! write as the row. | 3 | //! write as the row. |
| 4 | 4 | ||
| 5 | -use surrealdb::types::{RecordId, RecordIdKey}; | 5 | +use crate::constant::MAX_COURSE_NOTE_FILES; |
| 6 | - | 6 | +use crate::database::{Database, tx_with_retry, unique_violation}; |
| 7 | -use crate::constant::{COURSE_NOTE_FILE_COUNT_FIELD, MAX_COURSE_NOTE_FILES}; | ||
| 8 | -use crate::database::Database; | ||
| 9 | -use crate::db::cap; | ||
| 10 | use crate::db::page::PagedList; | 7 | use crate::db::page::PagedList; |
| 8 | +use crate::domain::course::CourseId; | ||
| 11 | use crate::domain::course_note::CourseNoteId; | 9 | use crate::domain::course_note::CourseNoteId; |
| 12 | use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; | 10 | use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; |
| 13 | use crate::error::AppError; | 11 | use crate::error::AppError; |
| 14 | 12 | ||
| 15 | /// Persist the row assembled by [`CourseNoteFile::new`], refusing once its | 13 | /// Persist the row assembled by [`CourseNoteFile::new`], refusing once its |
| 16 | /// note already holds [`MAX_COURSE_NOTE_FILES`]. The slot and the row are | 14 | /// note already holds [`MAX_COURSE_NOTE_FILES`]. The slot and the row are |
| 17 | -/// taken together by [`cap::claim_and_create`] on the note row β see | 15 | +/// taken together by one conditional statement on the note row (the claim |
| 18 | -/// [`crate::db::note_file::insert`] for why that is the only guard a | 16 | +/// CTE of `cap::claim_and_create`, spelled out at its call site β see |
| 19 | -/// concurrent insert cannot outrun. | 17 | +/// `crate::db::cap`) β see [`crate::db::note_file::insert`] for why that is |
| 18 | +/// the only guard a concurrent insert cannot outrun. | ||
| 20 | pub async fn insert(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFile, AppError> { | 19 | pub async fn insert(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFile, AppError> { |
| 21 | - // whole-row-save-ok: create of a fresh ULID row built in place by `new` β there is no prior row to clobber | 20 | + // whole-row-save-ok: insert of a fresh UUID row built in place by `new` β there is no prior row to clobber |
| 22 | - match cap::claim_and_create( | 21 | + let created = sqlx::query_as!( |
| 23 | - &file.course_note.record(), | 22 | + CourseNoteFile, |
| 24 | - COURSE_NOTE_FILE_COUNT_FIELD, | 23 | + r#"WITH seat AS ( |
| 24 | + UPDATE course_note SET file_count = file_count + 1 | ||
| 25 | + WHERE id = $1 AND file_count < $2 | ||
| 26 | + RETURNING 1) | ||
| 27 | + INSERT INTO course_note_file (id, course_note, name, content_type, size) | ||
| 28 | + SELECT $3, $1, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) | ||
| 29 | + RETURNING id, course_note, name, content_type, size"#, | ||
| 30 | + file.course_note, | ||
| 25 | MAX_COURSE_NOTE_FILES as i64, | 31 | MAX_COURSE_NOTE_FILES as i64, |
| 26 | - &file.id.record(), | 32 | + file.id, |
| 27 | - &file, | 33 | + file.name, |
| 28 | - db, | 34 | + file.content_type, |
| 35 | + file.size | ||
| 29 | ) | 36 | ) |
| 30 | - .await? | 37 | + .fetch_optional(db) |
| 31 | - { | 38 | + .await; |
| 32 | - cap::Claimed::Made(created) => Ok(created), | 39 | + match created { |
| 40 | + Ok(Some(row)) => Ok(row), | ||
| 33 | // Also how a missing note reads: no note row means no slot to take. | 41 | // Also how a missing note reads: no note row means no slot to take. |
| 34 | - cap::Claimed::Full => Err(AppError::Conflict( | 42 | + Ok(None) => Err(AppError::Conflict( |
| 35 | "the course note already holds the maximum of 10 files β delete one first", | 43 | "the course note already holds the maximum of 10 files β delete one first", |
| 36 | )), | 44 | )), |
| 37 | - // Unreachable: the id is a ULID this call just generated. | 45 | + // A duplicate would be a 23505 on the row's own key, which this path |
| 38 | - cap::Claimed::Duplicate => Err(AppError::Internal( | 46 | + // cannot produce β the id is a UUID this call just generated. |
| 47 | + Err(err) if unique_violation(&err).is_some() => Err(AppError::Internal( | ||
| 39 | "failed to create course note file".into(), | 48 | "failed to create course note file".into(), |
| 40 | )), | 49 | )), |
| 50 | + Err(err) => Err(err.into()), | ||
| 41 | } | 51 | } |
| 42 | } | 52 | } |
| 43 | 53 | ||
| 44 | /// Read a file's row by id alone, for the callers that have no note in | 54 | /// Read a file's row by id alone, for the callers that have no note in |
| 45 | /// hand yet and reach the note *through* the file (the AI bridge's blob | 55 | /// hand yet and reach the note *through* the file (the AI bridge's blob |
| 46 | -/// stream). A key from any other table simply reads as `None`, which is | 56 | +/// stream). An id from any other table simply reads as `None`, which is |
| 47 | /// what keeps a personal note's file id unreachable here. | 57 | /// what keeps a personal note's file id unreachable here. |
| 48 | pub async fn read( | 58 | pub async fn read( |
| 49 | db: &Database, | 59 | db: &Database, |
| 50 | id: &CourseNoteFileId, | 60 | id: &CourseNoteFileId, |
| 51 | ) -> Result<Option<CourseNoteFile>, AppError> { | 61 | ) -> Result<Option<CourseNoteFile>, AppError> { |
| 52 | - Ok(db.select(id.record()).await?) | 62 | + let file = sqlx::query_as!( |
| 63 | + CourseNoteFile, | ||
| 64 | + r#"SELECT id, course_note, name, content_type, size FROM course_note_file WHERE id = $1"#, | ||
| 65 | + id | ||
| 66 | + ) | ||
| 67 | + .fetch_optional(db) | ||
| 68 | + .await?; | ||
| 69 | + Ok(file) | ||
| 53 | } | 70 | } |
| 54 | 71 | ||
| 55 | /// Read a file's row only if it belongs to `note` β callers have already | 72 | /// Read a file's row only if it belongs to `note` β callers have already |
| @@ -59,8 +76,16 @@ pub async fn read_for( | |||
| 59 | id: &CourseNoteFileId, | 76 | id: &CourseNoteFileId, |
| 60 | note: &CourseNoteId, | 77 | note: &CourseNoteId, |
| 61 | ) -> Result<Option<CourseNoteFile>, AppError> { | 78 | ) -> Result<Option<CourseNoteFile>, AppError> { |
| 62 | - let file: Option<CourseNoteFile> = db.select(id.record()).await?; | 79 | + let file = sqlx::query_as!( |
| 63 | - Ok(file.filter(|file| &file.course_note == note)) | 80 | + CourseNoteFile, |
| 81 | + r#"SELECT id, course_note, name, content_type, size FROM course_note_file | ||
| 82 | + WHERE id = $1 AND course_note = $2"#, | ||
| 83 | + id, | ||
| 84 | + note | ||
| 85 | + ) | ||
| 86 | + .fetch_optional(db) | ||
| 87 | + .await?; | ||
| 88 | + Ok(file) | ||
| 64 | } | 89 | } |
| 65 | 90 | ||
| 66 | /// All of `note`'s attachment rows, newest first. | 91 | /// All of `note`'s attachment rows, newest first. |
| @@ -71,69 +96,63 @@ pub async fn list_for( | |||
| 71 | offset: i64, | 96 | offset: i64, |
| 72 | ) -> Result<(Vec<CourseNoteFile>, i64), AppError> { | 97 | ) -> Result<(Vec<CourseNoteFile>, i64), AppError> { |
| 73 | PagedList::new( | 98 | PagedList::new( |
| 74 | - "course_note_file WHERE course_note = $note", | 99 | + "course_note_file WHERE course_note = $1", |
| 75 | "ORDER BY id DESC", | 100 | "ORDER BY id DESC", |
| 76 | ) | 101 | ) |
| 77 | - .bind("note", note.record()) | 102 | + .bind(note.uuid()) |
| 78 | - .run(limit, offset, db) | 103 | + .run::<CourseNoteFile>(limit, offset, db) |
| 79 | .await | 104 | .await |
| 80 | } | 105 | } |
| 81 | 106 | ||
| 82 | -/// The blob names (record keys, since a file's blob is named by its own | 107 | +/// The blob names (the rows' own ids, since a file's blob is named by its |
| 83 | /// id) behind every note attachment of `course` β collected *before* the | 108 | /// id) behind every note attachment of `course` β collected *before* the |
| 84 | /// course-delete cascade wipes the rows. | 109 | /// course-delete cascade wipes the rows. |
| 85 | pub async fn file_keys_for_course( | 110 | pub async fn file_keys_for_course( |
| 86 | db: &Database, | 111 | db: &Database, |
| 87 | - course: &crate::domain::course::CourseId, | 112 | + course: &CourseId, |
| 88 | ) -> Result<Vec<String>, AppError> { | 113 | ) -> Result<Vec<String>, AppError> { |
| 89 | - let mut result = db | 114 | + let rows = sqlx::query!( |
| 90 | - .query( | 115 | + r#"SELECT course_note_file.id AS "id: CourseNoteFileId" FROM course_note_file |
| 91 | - "SELECT VALUE id FROM course_note_file \ | 116 | + WHERE course_note IN (SELECT id FROM course_note WHERE course = $1)"#, |
| 92 | - WHERE course_note IN (SELECT VALUE id FROM course_note WHERE course = $course)", | 117 | + course.0 |
| 93 | - ) | 118 | + ) |
| 94 | - .bind(("course", course.record())) | 119 | + .fetch_all(db) |
| 95 | - .await? | 120 | + .await?; |
| 96 | - .check()?; | 121 | + Ok(rows.into_iter().map(|row| row.id.key()).collect()) |
| 97 | - Ok(result | ||
| 98 | - .take::<Vec<RecordId>>(0)? | ||
| 99 | - .into_iter() | ||
| 100 | - .map(|id| match id.key { | ||
| 101 | - RecordIdKey::String(key) => key, | ||
| 102 | - _ => String::new(), | ||
| 103 | - }) | ||
| 104 | - .collect()) | ||
| 105 | } | 122 | } |
| 106 | 123 | ||
| 107 | /// Delete the row and give its slot back in the same transaction β the | 124 | /// Delete the row and give its slot back in the same transaction β the |
| 108 | /// note itself is untouched, so unlike the note-delete cascade this one | 125 | /// note itself is untouched, so unlike the note-delete cascade this one |
| 109 | /// has a counter to correct. | 126 | /// has a counter to correct. |
| 110 | pub async fn delete(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFile, AppError> { | 127 | pub async fn delete(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFile, AppError> { |
| 111 | - let mut result = db | 128 | + tx_with_retry(db, true, async |conn| { |
| 112 | - .query( | 129 | + let gone = sqlx::query_as!( |
| 113 | - "BEGIN TRANSACTION; | 130 | + CourseNoteFile, |
| 114 | - LET $gone = (DELETE $id RETURN BEFORE); | 131 | + r#"DELETE FROM course_note_file WHERE id = $1 |
| 115 | - UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); | 132 | + RETURNING id, course_note, name, content_type, size"#, |
| 116 | - RETURN $gone; | 133 | + file.id |
| 117 | - COMMIT TRANSACTION;", | ||
| 118 | ) | 134 | ) |
| 119 | - .bind(("id", file.id.record())) | 135 | + .fetch_optional(&mut *conn) |
| 120 | - .bind(("note", file.course_note.record())) | 136 | + .await?; |
| 121 | - .await? | 137 | + let file = gone.ok_or(AppError::NotFound)?; |
| 122 | - .check()?; | 138 | + sqlx::query!( |
| 123 | - result | 139 | + "UPDATE course_note SET file_count = GREATEST(file_count - 1, 0) WHERE id = $1", |
| 124 | - .take::<Vec<CourseNoteFile>>(3)? | 140 | + file.course_note |
| 125 | - .into_iter() | 141 | + ) |
| 126 | - .next() | 142 | + .execute(&mut *conn) |
| 127 | - .ok_or(AppError::NotFound) | 143 | + .await?; |
| 144 | + Ok(file) | ||
| 145 | + }) | ||
| 146 | + .await | ||
| 128 | } | 147 | } |
| 129 | 148 | ||
| 130 | #[cfg(test)] | 149 | #[cfg(test)] |
| 131 | mod tests { | 150 | mod tests { |
| 132 | use super::*; | 151 | use super::*; |
| 133 | - use crate::database::Database; | ||
| 134 | use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; | 152 | use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 135 | - use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; | 153 | + use crate::domain::course_note::{CourseNoteContent, CourseNoteTitle}; |
| 136 | - use crate::domain::course_note_file::{FileContentType, FileName}; | 154 | + use crate::domain::course_note_file::FileContentType; |
| 155 | + use crate::domain::course_note_file::FileName; | ||
| 137 | 156 | ||
| 138 | async fn note_of(db: &Database, title: &str) -> CourseNote { | 157 | async fn note_of(db: &Database, title: &str) -> CourseNote { |
| 139 | let creator = crate::domain::user::UserId::generate(); | 158 | let creator = crate::domain::user::UserId::generate(); |
| @@ -159,85 +178,54 @@ mod tests { | |||
| 159 | .unwrap() | 178 | .unwrap() |
| 160 | } | 179 | } |
| 161 | 180 | ||
| 181 | + /// The cap answers with a conflict and the refused upload wrote nothing: | ||
| 182 | + /// the count stays at the accepted rows. | ||
| 162 | #[tokio::test] | 183 | #[tokio::test] |
| 163 | - async fn rows_scope_to_their_note() { | 184 | + async fn insert_refuses_at_the_cap() { |
| 164 | let db = crate::database::init_mem().await.unwrap(); | 185 | let db = crate::database::init_mem().await.unwrap(); |
| 165 | - let note_a = note_of(&db, "a").await.get_id().clone(); | 186 | + let note = note_of(&db, "n").await; |
| 166 | - let note_b = note_of(&db, "b").await.get_id().clone(); | 187 | + for index in 0..MAX_COURSE_NOTE_FILES { |
| 167 | - let file = insert( | 188 | + let file = CourseNoteFile::new( |
| 168 | - &db, | 189 | + note.get_id(), |
| 169 | - CourseNoteFile::new( | 190 | + FileName::try_new(&format!("f{index}")).unwrap(), |
| 170 | - ¬e_a, | 191 | + FileContentType::try_new("text/plain").unwrap(), |
| 171 | - FileName::try_new("plan.pdf").unwrap(), | 192 | + 1, |
| 172 | - FileContentType::try_new("application/pdf").unwrap(), | 193 | + ); |
| 173 | - 3, | 194 | + insert(&db, file).await.unwrap(); |
| 174 | - ), | 195 | + } |
| 175 | - ) | 196 | + let over = CourseNoteFile::new( |
| 176 | - .await | 197 | + note.get_id(), |
| 177 | - .unwrap(); | 198 | + FileName::try_new("over").unwrap(), |
| 178 | - | 199 | + FileContentType::try_new("text/plain").unwrap(), |
| 179 | - let found = read_for(&db, file.get_id(), ¬e_a).await.unwrap(); | 200 | + 1, |
| 180 | - assert_eq!(found.unwrap().get_name().as_str(), "plan.pdf"); | ||
| 181 | - assert!( | ||
| 182 | - read_for(&db, file.get_id(), ¬e_b) | ||
| 183 | - .await | ||
| 184 | - .unwrap() | ||
| 185 | - .is_none() | ||
| 186 | ); | 201 | ); |
| 187 | - | 202 | + assert!(matches!( |
| 188 | - let listed = async |note: &CourseNoteId| list_for(&db, note, None, 0).await.unwrap().0; | 203 | + insert(&db, over).await, |
| 189 | - assert_eq!(listed(¬e_a).await.len(), 1); | 204 | + Err(AppError::Conflict(_)) |
| 190 | - assert!(listed(¬e_b).await.is_empty()); | 205 | + )); |
| 191 | - | 206 | + let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); |
| 192 | - delete(&db, file).await.unwrap(); | 207 | + assert_eq!(total, MAX_COURSE_NOTE_FILES as i64); |
| 193 | - assert!(listed(¬e_a).await.is_empty()); | ||
| 194 | } | 208 | } |
| 195 | 209 | ||
| 196 | - /// The counter and the rows are written in one transaction, so the stored | 210 | + /// The blob-key collection sees attachments through the course, and a |
| 197 | - /// count must equal the stored rows β after a success *and* after the | 211 | + /// delete hands its slot back to the note. |
| 198 | - /// refusal that fills the cap, which must move neither. | ||
| 199 | #[tokio::test] | 212 | #[tokio::test] |
| 200 | - async fn counter_tracks_stored_rows() { | 213 | + async fn file_keys_and_delete_slot_release() { |
| 201 | let db = crate::database::init_mem().await.unwrap(); | 214 | let db = crate::database::init_mem().await.unwrap(); |
| 202 | - let note = note_of(&db, "a").await.get_id().clone(); | 215 | + let note = note_of(&db, "n").await; |
| 203 | - let stored_count = async |note: &CourseNoteId| -> i64 { | 216 | + let course = note.get_course().clone(); |
| 204 | - db.query("SELECT VALUE file_count FROM $note") | 217 | + let file = CourseNoteFile::new( |
| 205 | - .bind(("note", note.record())) | 218 | + note.get_id(), |
| 206 | - .await | 219 | + FileName::try_new("f").unwrap(), |
| 207 | - .unwrap() | 220 | + FileContentType::try_new("text/plain").unwrap(), |
| 208 | - .take::<Vec<i64>>(0) | 221 | + 1, |
| 209 | - .unwrap() | ||
| 210 | - .into_iter() | ||
| 211 | - .next() | ||
| 212 | - .unwrap_or(0) | ||
| 213 | - }; | ||
| 214 | - let add = async |note: &CourseNoteId| { | ||
| 215 | - insert( | ||
| 216 | - &db, | ||
| 217 | - CourseNoteFile::new( | ||
| 218 | - note, | ||
| 219 | - FileName::try_new("plan.pdf").unwrap(), | ||
| 220 | - FileContentType::try_new("application/pdf").unwrap(), | ||
| 221 | - 3, | ||
| 222 | - ), | ||
| 223 | - ) | ||
| 224 | - .await | ||
| 225 | - }; | ||
| 226 | - | ||
| 227 | - for filled in 1..=MAX_COURSE_NOTE_FILES { | ||
| 228 | - add(¬e).await.unwrap(); | ||
| 229 | - assert_eq!(stored_count(¬e).await, filled as i64); | ||
| 230 | - assert_eq!( | ||
| 231 | - list_for(&db, ¬e, None, 0).await.unwrap().1, | ||
| 232 | - filled as i64 | ||
| 233 | - ); | ||
| 234 | - } | ||
| 235 | - | ||
| 236 | - assert!(matches!(add(¬e).await, Err(AppError::Conflict(_)))); | ||
| 237 | - assert_eq!(stored_count(¬e).await, MAX_COURSE_NOTE_FILES as i64); | ||
| 238 | - assert_eq!( | ||
| 239 | - list_for(&db, ¬e, None, 0).await.unwrap().1, | ||
| 240 | - MAX_COURSE_NOTE_FILES as i64 | ||
| 241 | ); | 222 | ); |
| 223 | + let file = insert(&db, file).await.unwrap(); | ||
| 224 | + let keys = file_keys_for_course(&db, &course).await.unwrap(); | ||
| 225 | + assert_eq!(keys, vec![file.get_id().key().to_string()]); | ||
| 226 | + let gone = delete(&db, file.clone()).await.unwrap(); | ||
| 227 | + assert_eq!(gone.get_id(), file.get_id()); | ||
| 228 | + assert!(matches!(delete(&db, file).await, Err(AppError::NotFound))); | ||
| 229 | + assert!(file_keys_for_course(&db, &course).await.unwrap().is_empty()); | ||
| 242 | } | 230 | } |
| 243 | } | 231 | } |
src/db/note.rsmodified+61 -44
| @@ -1,9 +1,7 @@ | |||
| 1 | //! The `note` table: one user's rows, listed newest first, deleted together | 1 | //! The `note` table: one user's rows, listed newest first, deleted together |
| 2 | //! with their attachment rows. | 2 | //! with their attachment rows. |
| 3 | 3 | ||
| 4 | -use surrealdb::types::SurrealValue; | 4 | +use crate::database::{Database, tx_with_retry}; |
| 5 | - | ||
| 6 | -use crate::database::Database; | ||
| 7 | use crate::db::field_update::FieldUpdate; | 5 | use crate::db::field_update::FieldUpdate; |
| 8 | use crate::db::page::PagedList; | 6 | use crate::db::page::PagedList; |
| 9 | use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; | 7 | use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; |
| @@ -11,15 +9,6 @@ use crate::domain::note_file::NoteFile; | |||
| 11 | use crate::domain::user::UserId; | 9 | use crate::domain::user::UserId; |
| 12 | use crate::error::AppError; | 10 | use crate::error::AppError; |
| 13 | 11 | ||
| 14 | -/// What [`delete`]'s transaction removed: the note row (empty if it had | ||
| 15 | -/// already vanished) and every attachment row the cascade took with it β the | ||
| 16 | -/// only set whose blobs are safe to unlink. | ||
| 17 | -#[derive(Debug, SurrealValue)] | ||
| 18 | -struct DeleteOutcome { | ||
| 19 | - note: Vec<Note>, | ||
| 20 | - files: Vec<NoteFile>, | ||
| 21 | -} | ||
| 22 | - | ||
| 23 | pub async fn create( | 12 | pub async fn create( |
| 24 | db: &Database, | 13 | db: &Database, |
| 25 | owner: &UserId, | 14 | owner: &UserId, |
| @@ -32,8 +21,20 @@ pub async fn create( | |||
| 32 | title, | 21 | title, |
| 33 | content, | 22 | content, |
| 34 | }; | 23 | }; |
| 35 | - let created: Option<Note> = db.create(note.id.record()).content(note).await?; | 24 | + // whole-row-save-ok: insert of a fresh UUID row built in place by `new` β there is no prior row to clobber |
| 36 | - created.ok_or_else(|| AppError::Internal("failed to create note".into())) | 25 | + let created = sqlx::query_as!( |
| 26 | + Note, | ||
| 27 | + r#"INSERT INTO note (id, app_user, title, content) | ||
| 28 | + VALUES ($1, $2, $3, $4) | ||
| 29 | + RETURNING id, app_user AS "user", title, content"#, | ||
| 30 | + note.id, | ||
| 31 | + note.user, | ||
| 32 | + note.title, | ||
| 33 | + note.content | ||
| 34 | + ) | ||
| 35 | + .fetch_one(db) | ||
| 36 | + .await?; | ||
| 37 | + Ok(created) | ||
| 37 | } | 38 | } |
| 38 | 39 | ||
| 39 | /// Read a note only if it belongs to `owner`. | 40 | /// Read a note only if it belongs to `owner`. |
| @@ -42,8 +43,15 @@ pub async fn read_owned( | |||
| 42 | id: &NoteId, | 43 | id: &NoteId, |
| 43 | owner: &UserId, | 44 | owner: &UserId, |
| 44 | ) -> Result<Option<Note>, AppError> { | 45 | ) -> Result<Option<Note>, AppError> { |
| 45 | - let note: Option<Note> = db.select(id.record()).await?; | 46 | + let note = sqlx::query_as!( |
| 46 | - Ok(note.filter(|note| ¬e.user == owner)) | 47 | + Note, |
| 48 | + r#"SELECT id, app_user AS "user", title, content FROM note WHERE id = $1 AND app_user = $2"#, | ||
| 49 | + id, | ||
| 50 | + owner | ||
| 51 | + ) | ||
| 52 | + .fetch_optional(db) | ||
| 53 | + .await?; | ||
| 54 | + Ok(note) | ||
| 47 | } | 55 | } |
| 48 | 56 | ||
| 49 | pub async fn list_for( | 57 | pub async fn list_for( |
| @@ -52,9 +60,9 @@ pub async fn list_for( | |||
| 52 | limit: Option<i64>, | 60 | limit: Option<i64>, |
| 53 | offset: i64, | 61 | offset: i64, |
| 54 | ) -> Result<(Vec<Note>, i64), AppError> { | 62 | ) -> Result<(Vec<Note>, i64), AppError> { |
| 55 | - PagedList::new("note WHERE user = $usr", "ORDER BY id DESC") | 63 | + PagedList::new("note WHERE app_user = $1", "ORDER BY id DESC") |
| 56 | - .bind("usr", owner.record()) | 64 | + .bind(owner.uuid()) |
| 57 | - .run(limit, offset, db) | 65 | + .run::<Note>(limit, offset, db) |
| 58 | .await | 66 | .await |
| 59 | } | 67 | } |
| 60 | 68 | ||
| @@ -70,9 +78,12 @@ pub async fn update( | |||
| 70 | title: Option<NoteTitle>, | 78 | title: Option<NoteTitle>, |
| 71 | content: Option<NoteContent>, | 79 | content: Option<NoteContent>, |
| 72 | ) -> Result<Note, AppError> { | 80 | ) -> Result<Note, AppError> { |
| 73 | - FieldUpdate::new(note.id.record()) | 81 | + FieldUpdate::new("note", note.id.uuid()) |
| 74 | - .set("title", title) | 82 | + .set("title", title.map(|title| title.as_str().to_string())) |
| 75 | - .set("content", content) | 83 | + .set( |
| 84 | + "content", | ||
| 85 | + content.map(|content| content.as_str().to_string()), | ||
| 86 | + ) | ||
| 76 | .run::<Note>(db) | 87 | .run::<Note>(db) |
| 77 | .await | 88 | .await |
| 78 | } | 89 | } |
| @@ -88,42 +99,48 @@ pub async fn update( | |||
| 88 | /// Children first, in one transaction, the way | 99 | /// Children first, in one transaction, the way |
| 89 | /// [`crate::db::course::delete`] does it: as two queries, an | 100 | /// [`crate::db::course::delete`] does it: as two queries, an |
| 90 | /// upload that committed in between kept its row while the note went, and | 101 | /// upload that committed in between kept its row while the note went, and |
| 91 | -/// nothing could ever list or delete it again. | 102 | +/// nothing could ever list or delete it again. The `rag_output` sweep rides |
| 103 | +/// here too: under real foreign keys a `rag_output` row citing this note | ||
| 104 | +/// would refuse the delete (`ON DELETE NO ACTION`), and the derived rows | ||
| 105 | +/// are exactly the thing that may never outlive its input β the web layer's | ||
| 106 | +/// separate `delete_for_note` call stays, as a harmless idempotent repeat. | ||
| 92 | pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec<NoteFile>), AppError> { | 107 | pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec<NoteFile>), AppError> { |
| 93 | - let mut result = db | 108 | + tx_with_retry(db, true, async |conn| { |
| 94 | - .query( | 109 | + sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id) |
| 95 | - "BEGIN TRANSACTION; | 110 | + .execute(&mut *conn) |
| 96 | - LET $files = (DELETE note_file WHERE note = $note RETURN BEFORE); | 111 | + .await?; |
| 97 | - LET $gone = (DELETE $note RETURN BEFORE); | 112 | + let files = sqlx::query_as!( |
| 98 | - RETURN { note: $gone, files: $files }; | 113 | + NoteFile, |
| 99 | - COMMIT TRANSACTION;", | 114 | + r#"DELETE FROM note_file WHERE note = $1 RETURNING id, note, name, content_type, size"#, |
| 115 | + note.id | ||
| 116 | + ) | ||
| 117 | + .fetch_all(&mut *conn) | ||
| 118 | + .await?; | ||
| 119 | + let gone = sqlx::query_as!( | ||
| 120 | + Note, | ||
| 121 | + r#"DELETE FROM note WHERE id = $1 RETURNING id, app_user AS "user", title, content"#, | ||
| 122 | + note.id | ||
| 100 | ) | 123 | ) |
| 101 | - .bind(("note", note.id.record())) | 124 | + .fetch_optional(&mut *conn) |
| 102 | - .await? | 125 | + .await?; |
| 103 | - .check()?; | 126 | + let note = gone.ok_or(AppError::NotFound)?; |
| 104 | - // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3. | 127 | + Ok((note, files)) |
| 105 | - let outcome = result | 128 | + }) |
| 106 | - .take::<Vec<DeleteOutcome>>(3)? | 129 | + .await |
| 107 | - .into_iter() | ||
| 108 | - .next() | ||
| 109 | - .ok_or_else(|| AppError::Internal("failed to delete note".into()))?; | ||
| 110 | - let note = outcome.note.into_iter().next().ok_or(AppError::NotFound)?; | ||
| 111 | - Ok((note, outcome.files)) | ||
| 112 | } | 130 | } |
| 113 | 131 | ||
| 114 | #[cfg(test)] | 132 | #[cfg(test)] |
| 115 | mod tests { | 133 | mod tests { |
| 116 | use super::*; | 134 | use super::*; |
| 135 | + use crate::domain::note_file::{FileContentType, FileName}; | ||
| 117 | 136 | ||
| 118 | /// The blobs the handler unlinks are exactly the rows this transaction | 137 | /// The blobs the handler unlinks are exactly the rows this transaction |
| 119 | /// removed β including one uploaded after any pre-read snapshot would have | 138 | /// removed β including one uploaded after any pre-read snapshot would have |
| 120 | /// been taken, which is the row whose blob used to leak. | 139 | /// been taken, which is the row whose blob used to leak. |
| 121 | #[tokio::test] | 140 | #[tokio::test] |
| 122 | async fn delete_returns_the_attachment_rows_it_removed() { | 141 | async fn delete_returns_the_attachment_rows_it_removed() { |
| 123 | - use crate::domain::note_file::{FileContentType, FileName}; | ||
| 124 | - | ||
| 125 | let db = crate::database::init_mem().await.unwrap(); | 142 | let db = crate::database::init_mem().await.unwrap(); |
| 126 | - let owner = crate::domain::user::UserId::generate(); | 143 | + let owner = UserId::generate(); |
| 127 | let note = create( | 144 | let note = create( |
| 128 | &db, | 145 | &db, |
| 129 | &owner, | 146 | &owner, |
src/db/note_file.rsmodified+126 -137
| @@ -2,9 +2,8 @@ | |||
| 2 | //! first, with the note's file cap claimed and released in the same write as | 2 | //! first, with the note's file cap claimed and released in the same write as |
| 3 | //! the row. | 3 | //! the row. |
| 4 | 4 | ||
| 5 | -use crate::constant::{MAX_NOTE_FILES, NOTE_FILE_COUNT_FIELD}; | 5 | +use crate::constant::MAX_NOTE_FILES; |
| 6 | -use crate::database::Database; | 6 | +use crate::database::{Database, tx_with_retry, unique_violation}; |
| 7 | -use crate::db::cap; | ||
| 8 | use crate::db::page::PagedList; | 7 | use crate::db::page::PagedList; |
| 9 | use crate::domain::note::NoteId; | 8 | use crate::domain::note::NoteId; |
| 10 | use crate::domain::note_file::{NoteFile, NoteFileId}; | 9 | use crate::domain::note_file::{NoteFile, NoteFileId}; |
| @@ -12,31 +11,45 @@ use crate::error::AppError; | |||
| 12 | 11 | ||
| 13 | /// Persist the row assembled by [`NoteFile::new`], refusing once its note | 12 | /// Persist the row assembled by [`NoteFile::new`], refusing once its note |
| 14 | /// already holds [`MAX_NOTE_FILES`]. The slot and the row are taken together | 13 | /// already holds [`MAX_NOTE_FILES`]. The slot and the row are taken together |
| 15 | -/// by [`cap::claim_and_create`] on the note row: a `BEGINβ¦COMMIT` around a | 14 | +/// by one conditional statement on the note row (the claim CTE of |
| 16 | -/// count can't enforce the cap (SurrealDB doesn't conflict-check a | 15 | +/// `cap::claim_and_create`, spelled out at its call site β see |
| 17 | -/// cross-record count against a concurrent insert) and a process-wide mutex | 16 | +/// `crate::db::cap`): a `BEGINβ¦COMMIT` around a count can't enforce the cap |
| 18 | -/// can't either, since it is released around the very round trip the insert | 17 | +/// and a process-wide mutex can't either, since it is released around the |
| 19 | -/// races β a conditional single-record write can. Claiming in a *separate* | 18 | +/// very round trip the insert races β a single guarded statement can. |
| 20 | -/// query would enforce the cap but leak a slot on a crash between the two. | 19 | +/// Claiming in a *separate* query would enforce the cap but leak a slot on |
| 20 | +/// a crash between the two. | ||
| 21 | pub async fn insert(db: &Database, file: NoteFile) -> Result<NoteFile, AppError> { | 21 | pub async fn insert(db: &Database, file: NoteFile) -> Result<NoteFile, AppError> { |
| 22 | - // whole-row-save-ok: create of a fresh ULID row built in place by `new` β there is no prior row to clobber | 22 | + // whole-row-save-ok: insert of a fresh UUID row built in place by `new` β there is no prior row to clobber |
| 23 | - match cap::claim_and_create( | 23 | + let created = sqlx::query_as!( |
| 24 | - &file.note.record(), | 24 | + NoteFile, |
| 25 | - NOTE_FILE_COUNT_FIELD, | 25 | + r#"WITH seat AS ( |
| 26 | + UPDATE note SET file_count = file_count + 1 | ||
| 27 | + WHERE id = $1 AND file_count < $2 | ||
| 28 | + RETURNING 1) | ||
| 29 | + INSERT INTO note_file (id, note, name, content_type, size) | ||
| 30 | + SELECT $3, $1, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) | ||
| 31 | + RETURNING id, note, name, content_type, size"#, | ||
| 32 | + file.note, | ||
| 26 | MAX_NOTE_FILES as i64, | 33 | MAX_NOTE_FILES as i64, |
| 27 | - &file.id.record(), | 34 | + file.id, |
| 28 | - &file, | 35 | + file.name, |
| 29 | - db, | 36 | + file.content_type, |
| 37 | + file.size | ||
| 30 | ) | 38 | ) |
| 31 | - .await? | 39 | + .fetch_optional(db) |
| 32 | - { | 40 | + .await; |
| 33 | - cap::Claimed::Made(created) => Ok(created), | 41 | + match created { |
| 42 | + Ok(Some(row)) => Ok(row), | ||
| 34 | // Also how a missing note reads: no note row means no slot to take. | 43 | // Also how a missing note reads: no note row means no slot to take. |
| 35 | - cap::Claimed::Full => Err(AppError::Conflict( | 44 | + Ok(None) => Err(AppError::Conflict( |
| 36 | "the note already holds the maximum of 10 files β delete one first", | 45 | "the note already holds the maximum of 10 files β delete one first", |
| 37 | )), | 46 | )), |
| 38 | - // Unreachable: the id is a ULID this call just generated. | 47 | + // A duplicate would be a 23505 on the row's own key, which this path |
| 39 | - cap::Claimed::Duplicate => Err(AppError::Internal("failed to create note file".into())), | 48 | + // cannot produce β the id is a UUID this call just generated. |
| 49 | + Err(err) if unique_violation(&err).is_some() => { | ||
| 50 | + Err(AppError::Internal("failed to create note file".into())) | ||
| 51 | + } | ||
| 52 | + Err(err) => Err(err.into()), | ||
| 40 | } | 53 | } |
| 41 | } | 54 | } |
| 42 | 55 | ||
| @@ -47,8 +60,15 @@ pub async fn read_for( | |||
| 47 | id: &NoteFileId, | 60 | id: &NoteFileId, |
| 48 | note: &NoteId, | 61 | note: &NoteId, |
| 49 | ) -> Result<Option<NoteFile>, AppError> { | 62 | ) -> Result<Option<NoteFile>, AppError> { |
| 50 | - let file: Option<NoteFile> = db.select(id.record()).await?; | 63 | + let file = sqlx::query_as!( |
| 51 | - Ok(file.filter(|file| &file.note == note)) | 64 | + NoteFile, |
| 65 | + r#"SELECT id, note, name, content_type, size FROM note_file WHERE id = $1 AND note = $2"#, | ||
| 66 | + id, | ||
| 67 | + note | ||
| 68 | + ) | ||
| 69 | + .fetch_optional(db) | ||
| 70 | + .await?; | ||
| 71 | + Ok(file) | ||
| 52 | } | 72 | } |
| 53 | 73 | ||
| 54 | /// All of `note`'s attachment rows, newest first. | 74 | /// All of `note`'s attachment rows, newest first. |
| @@ -58,9 +78,9 @@ pub async fn list_for( | |||
| 58 | limit: Option<i64>, | 78 | limit: Option<i64>, |
| 59 | offset: i64, | 79 | offset: i64, |
| 60 | ) -> Result<(Vec<NoteFile>, i64), AppError> { | 80 | ) -> Result<(Vec<NoteFile>, i64), AppError> { |
| 61 | - PagedList::new("note_file WHERE note = $note", "ORDER BY id DESC") | 81 | + PagedList::new("note_file WHERE note = $1", "ORDER BY id DESC") |
| 62 | - .bind("note", note.record()) | 82 | + .bind(note.uuid()) |
| 63 | - .run(limit, offset, db) | 83 | + .run::<NoteFile>(limit, offset, db) |
| 64 | .await | 84 | .await |
| 65 | } | 85 | } |
| 66 | 86 | ||
| @@ -68,133 +88,102 @@ pub async fn list_for( | |||
| 68 | /// itself is untouched, so unlike the note-delete cascade this one has a | 88 | /// itself is untouched, so unlike the note-delete cascade this one has a |
| 69 | /// counter to correct. (Deleting a *note* takes its counter with it.) | 89 | /// counter to correct. (Deleting a *note* takes its counter with it.) |
| 70 | pub async fn delete(db: &Database, file: NoteFile) -> Result<NoteFile, AppError> { | 90 | pub async fn delete(db: &Database, file: NoteFile) -> Result<NoteFile, AppError> { |
| 71 | - let mut result = db | 91 | + tx_with_retry(db, true, async |conn| { |
| 72 | - .query( | 92 | + let gone = sqlx::query_as!( |
| 73 | - "BEGIN TRANSACTION; | 93 | + NoteFile, |
| 74 | - LET $gone = (DELETE $id RETURN BEFORE); | 94 | + r#"DELETE FROM note_file WHERE id = $1 RETURNING id, note, name, content_type, size"#, |
| 75 | - UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); | 95 | + file.id |
| 76 | - RETURN $gone; | 96 | + ) |
| 77 | - COMMIT TRANSACTION;", | 97 | + .fetch_optional(&mut *conn) |
| 98 | + .await?; | ||
| 99 | + let file = gone.ok_or(AppError::NotFound)?; | ||
| 100 | + sqlx::query!( | ||
| 101 | + "UPDATE note SET file_count = GREATEST(file_count - 1, 0) WHERE id = $1", | ||
| 102 | + file.note | ||
| 78 | ) | 103 | ) |
| 79 | - .bind(("id", file.id.record())) | 104 | + .execute(&mut *conn) |
| 80 | - .bind(("note", file.note.record())) | 105 | + .await?; |
| 81 | - .await? | 106 | + Ok(file) |
| 82 | - .check()?; | 107 | + }) |
| 83 | - result | 108 | + .await |
| 84 | - .take::<Vec<NoteFile>>(3)? | ||
| 85 | - .into_iter() | ||
| 86 | - .next() | ||
| 87 | - .ok_or(AppError::NotFound) | ||
| 88 | } | 109 | } |
| 89 | 110 | ||
| 90 | #[cfg(test)] | 111 | #[cfg(test)] |
| 91 | mod tests { | 112 | mod tests { |
| 92 | use super::*; | 113 | use super::*; |
| 93 | - use crate::domain::note_file::{FileContentType, FileName}; | 114 | + use crate::domain::note::NoteContent; |
| 115 | + use crate::domain::note::NoteTitle; | ||
| 116 | + use crate::domain::note_file::FileContentType; | ||
| 117 | + use crate::domain::note_file::FileName; | ||
| 94 | 118 | ||
| 95 | - #[tokio::test] | 119 | + async fn a_note(db: &Database) -> Note { |
| 96 | - async fn rows_scope_to_their_note() { | ||
| 97 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 98 | - // Real note rows: the cap counter lives on the note, so an insert whose | ||
| 99 | - // note does not exist has no slot to take (a 409, like a full note). | ||
| 100 | let owner = crate::domain::user::UserId::generate(); | 120 | let owner = crate::domain::user::UserId::generate(); |
| 101 | - let note_of = async |title: &str| { | 121 | + crate::db::note::create( |
| 102 | - crate::db::note::create( | 122 | + db, |
| 103 | - &db, | 123 | + &owner, |
| 104 | - &owner, | 124 | + NoteTitle::try_new("n").unwrap(), |
| 105 | - crate::domain::note::NoteTitle::try_new(title).unwrap(), | 125 | + NoteContent::try_new("b").unwrap(), |
| 106 | - crate::domain::note::NoteContent::try_new("body").unwrap(), | ||
| 107 | - ) | ||
| 108 | - .await | ||
| 109 | - .unwrap() | ||
| 110 | - }; | ||
| 111 | - let note_a = note_of("a").await.get_id().clone(); | ||
| 112 | - let note_b = note_of("b").await.get_id().clone(); | ||
| 113 | - let file = insert( | ||
| 114 | - &db, | ||
| 115 | - NoteFile::new( | ||
| 116 | - ¬e_a, | ||
| 117 | - FileName::try_new("plan.pdf").unwrap(), | ||
| 118 | - FileContentType::try_new("application/pdf").unwrap(), | ||
| 119 | - 3, | ||
| 120 | - ), | ||
| 121 | ) | 126 | ) |
| 122 | .await | 127 | .await |
| 123 | - .unwrap(); | 128 | + .unwrap() |
| 124 | - | ||
| 125 | - // Readable under its own note, invisible under another. | ||
| 126 | - let found = read_for(&db, file.get_id(), ¬e_a).await.unwrap(); | ||
| 127 | - assert_eq!(found.unwrap().get_name().as_str(), "plan.pdf"); | ||
| 128 | - assert!( | ||
| 129 | - read_for(&db, file.get_id(), ¬e_b) | ||
| 130 | - .await | ||
| 131 | - .unwrap() | ||
| 132 | - .is_none() | ||
| 133 | - ); | ||
| 134 | - | ||
| 135 | - let listed = async |note: &NoteId| list_for(&db, note, None, 0).await.unwrap().0; | ||
| 136 | - assert_eq!(listed(¬e_a).await.len(), 1); | ||
| 137 | - assert!(listed(¬e_b).await.is_empty()); | ||
| 138 | - | ||
| 139 | - delete(&db, file).await.unwrap(); | ||
| 140 | - assert!(listed(¬e_a).await.is_empty()); | ||
| 141 | } | 129 | } |
| 142 | 130 | ||
| 143 | - /// The counter and the rows are written in one transaction, so the stored | 131 | + /// The cap answers with a conflict, and neither the refused row nor its |
| 144 | - /// count must equal the stored rows β after a success *and* after the | 132 | + /// slot was written: the count is still what the last accepted upload |
| 145 | - /// refusal that fills the cap, which must move neither. | 133 | + /// left. |
| 146 | #[tokio::test] | 134 | #[tokio::test] |
| 147 | - async fn counter_tracks_stored_rows() { | 135 | + async fn insert_refuses_at_the_cap_without_leaking_a_slot() { |
| 148 | let db = crate::database::init_mem().await.unwrap(); | 136 | let db = crate::database::init_mem().await.unwrap(); |
| 149 | - let note = crate::db::note::create( | 137 | + let note = a_note(&db).await; |
| 150 | - &db, | 138 | + for index in 0..MAX_NOTE_FILES { |
| 151 | - &crate::domain::user::UserId::generate(), | 139 | + let file = NoteFile::new( |
| 152 | - crate::domain::note::NoteTitle::try_new("a").unwrap(), | 140 | + note.get_id(), |
| 153 | - crate::domain::note::NoteContent::try_new("body").unwrap(), | 141 | + FileName::try_new(&format!("f{index}")).unwrap(), |
| 154 | - ) | 142 | + FileContentType::try_new("text/plain").unwrap(), |
| 155 | - .await | 143 | + 1, |
| 156 | - .unwrap() | ||
| 157 | - .get_id() | ||
| 158 | - .clone(); | ||
| 159 | - let stored_count = async |note: &NoteId| -> i64 { | ||
| 160 | - db.query("SELECT VALUE file_count FROM $note") | ||
| 161 | - .bind(("note", note.record())) | ||
| 162 | - .await | ||
| 163 | - .unwrap() | ||
| 164 | - .take::<Vec<i64>>(0) | ||
| 165 | - .unwrap() | ||
| 166 | - .into_iter() | ||
| 167 | - .next() | ||
| 168 | - .unwrap_or(0) | ||
| 169 | - }; | ||
| 170 | - let add = async |note: &NoteId| { | ||
| 171 | - insert( | ||
| 172 | - &db, | ||
| 173 | - NoteFile::new( | ||
| 174 | - note, | ||
| 175 | - FileName::try_new("plan.pdf").unwrap(), | ||
| 176 | - FileContentType::try_new("application/pdf").unwrap(), | ||
| 177 | - 3, | ||
| 178 | - ), | ||
| 179 | - ) | ||
| 180 | - .await | ||
| 181 | - }; | ||
| 182 | - | ||
| 183 | - for filled in 1..=MAX_NOTE_FILES { | ||
| 184 | - add(¬e).await.unwrap(); | ||
| 185 | - assert_eq!(stored_count(¬e).await, filled as i64); | ||
| 186 | - assert_eq!( | ||
| 187 | - list_for(&db, ¬e, None, 0).await.unwrap().1, | ||
| 188 | - filled as i64 | ||
| 189 | ); | 144 | ); |
| 145 | + insert(&db, file).await.unwrap(); | ||
| 190 | } | 146 | } |
| 147 | + let over = NoteFile::new( | ||
| 148 | + note.get_id(), | ||
| 149 | + FileName::try_new("over").unwrap(), | ||
| 150 | + FileContentType::try_new("text/plain").unwrap(), | ||
| 151 | + 1, | ||
| 152 | + ); | ||
| 153 | + assert!(matches!( | ||
| 154 | + insert(&db, over).await, | ||
| 155 | + Err(AppError::Conflict(_)) | ||
| 156 | + )); | ||
| 157 | + let (files, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); | ||
| 158 | + assert_eq!(total, MAX_NOTE_FILES as i64); | ||
| 159 | + assert_eq!(files.len(), MAX_NOTE_FILES); | ||
| 160 | + } | ||
| 191 | 161 | ||
| 192 | - // At the cap: the refusal writes nothing, counter included. | 162 | + /// Deleting a row hands its slot back: after one delete a new upload is |
| 193 | - assert!(matches!(add(¬e).await, Err(AppError::Conflict(_)))); | 163 | + /// accepted again, and the count never dips below zero. |
| 194 | - assert_eq!(stored_count(¬e).await, MAX_NOTE_FILES as i64); | 164 | + #[tokio::test] |
| 195 | - assert_eq!( | 165 | + async fn delete_returns_the_slot_to_the_note() { |
| 196 | - list_for(&db, ¬e, None, 0).await.unwrap().1, | 166 | + let db = crate::database::init_mem().await.unwrap(); |
| 197 | - MAX_NOTE_FILES as i64 | 167 | + let note = a_note(&db).await; |
| 168 | + let file = NoteFile::new( | ||
| 169 | + note.get_id(), | ||
| 170 | + FileName::try_new("f").unwrap(), | ||
| 171 | + FileContentType::try_new("text/plain").unwrap(), | ||
| 172 | + 1, | ||
| 173 | + ); | ||
| 174 | + let file = insert(&db, file).await.unwrap(); | ||
| 175 | + let gone = delete(&db, file.clone()).await.unwrap(); | ||
| 176 | + assert_eq!(gone.get_id(), file.get_id()); | ||
| 177 | + // Deleting it a second time is a 404, not a second decrement. | ||
| 178 | + assert!(matches!(delete(&db, file).await, Err(AppError::NotFound))); | ||
| 179 | + let next = NoteFile::new( | ||
| 180 | + note.get_id(), | ||
| 181 | + FileName::try_new("next").unwrap(), | ||
| 182 | + FileContentType::try_new("text/plain").unwrap(), | ||
| 183 | + 1, | ||
| 198 | ); | 184 | ); |
| 185 | + insert(&db, next).await.unwrap(); | ||
| 186 | + let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); | ||
| 187 | + assert_eq!(total, 1); | ||
| 199 | } | 188 | } |
| 200 | } | 189 | } |
src/db/rag_output.rsmodified+132 -110
| @@ -1,13 +1,13 @@ | |||
| 1 | -//! The `rag_output` table: what an AI service produced for a course note β | 1 | +//! What an AI service produced for a course note, stored on this side: the |
| 2 | -//! an index, a summary, an embedding manifest β stored as this side's own | 2 | +//! write paths the api-read bridge serves (`create`/`replace_for_note` run |
| 3 | -//! copy of the answer. The AI service never writes here (it answers a | 3 | +//! when this backend answers a request over the bridge, and this side stores |
| 4 | -//! request over the bridge, and this side stores the answer), which is what | 4 | +//! the answer), which is what keeps the api-read bridge GET-only. Derived, |
| 5 | -//! keeps the api-read bridge GET-only. Derived, disposable data: the row is | 5 | +//! disposable data: the row is dropped and regenerated whenever its input |
| 6 | -//! dropped and regenerated whenever its input changes, so the cascades | 6 | +//! changes, so the cascades below β [`delete_for_note`] when the note goes, |
| 7 | -//! below β [`delete_for_note`] when the note goes, [`delete_with_source`] | 7 | +//! [`delete_with_source`] when one of the attachments it was built from goes |
| 8 | -//! when one of the attachments it was built from goes β keep a stale output | 8 | +//! β keep a stale output from outliving its input, even in a deployment with |
| 9 | -//! from outliving its input, even in a deployment with no AI service | 9 | +//! no AI service connected. The row shape lives in |
| 10 | -//! connected. The row shape lives in [`crate::domain::rag_output`]. | 10 | +//! [`crate::domain::rag_output`]. |
| 11 | 11 | ||
| 12 | use crate::database::Database; | 12 | use crate::database::Database; |
| 13 | use crate::db::page::PagedList; | 13 | use crate::db::page::PagedList; |
| @@ -18,8 +18,8 @@ use crate::domain::rag_output::{RagOutput, RagOutputId}; | |||
| 18 | use crate::domain::timestamp::Timestamp; | 18 | use crate::domain::timestamp::Timestamp; |
| 19 | use crate::error::AppError; | 19 | use crate::error::AppError; |
| 20 | use serde_json::Value; | 20 | use serde_json::Value; |
| 21 | +use sqlx::types::Json; | ||
| 21 | 22 | ||
| 22 | -/// Store one service output against `note`. | ||
| 23 | pub async fn create( | 23 | pub async fn create( |
| 24 | db: &Database, | 24 | db: &Database, |
| 25 | note: &CourseNoteId, | 25 | note: &CourseNoteId, |
| @@ -32,16 +32,39 @@ pub async fn create( | |||
| 32 | course_note: note.clone(), | 32 | course_note: note.clone(), |
| 33 | course: course.clone(), | 33 | course: course.clone(), |
| 34 | sources, | 34 | sources, |
| 35 | - payload, | 35 | + payload: sqlx::types::Json(payload), |
| 36 | generated_at: Timestamp::now(), | 36 | generated_at: Timestamp::now(), |
| 37 | }; | 37 | }; |
| 38 | - // whole-row-save-ok: create of a fresh ULID row built in place β there is no prior row to clobber | 38 | + // whole-row-save-ok: insert of a fresh UUID row built in place β there is no prior row to clobber |
| 39 | - let created: Option<RagOutput> = db.create(row.id.record()).content(row).await?; | 39 | + let created = sqlx::query_as!( |
| 40 | - created.ok_or_else(|| AppError::Internal("failed to create rag output".into())) | 40 | + RagOutput, |
| 41 | + r#"INSERT INTO rag_output (id, course_note, course, sources, payload, generated_at) | ||
| 42 | + VALUES ($1, $2, $3, $4, $5, $6) | ||
| 43 | + RETURNING id, course_note, course, sources, | ||
| 44 | + payload AS "payload: Json<Value>", generated_at"#, | ||
| 45 | + row.id, | ||
| 46 | + row.course_note, | ||
| 47 | + row.course, | ||
| 48 | + &row.sources, | ||
| 49 | + &row.payload, | ||
| 50 | + row.generated_at | ||
| 51 | + ) | ||
| 52 | + .fetch_one(db) | ||
| 53 | + .await?; | ||
| 54 | + Ok(created) | ||
| 41 | } | 55 | } |
| 42 | 56 | ||
| 43 | pub async fn read(db: &Database, id: &RagOutputId) -> Result<Option<RagOutput>, AppError> { | 57 | pub async fn read(db: &Database, id: &RagOutputId) -> Result<Option<RagOutput>, AppError> { |
| 44 | - Ok(db.select(id.record()).await?) | 58 | + let row = sqlx::query_as!( |
| 59 | + RagOutput, | ||
| 60 | + r#"SELECT id, course_note, course, sources, | ||
| 61 | + payload AS "payload: Json<Value>", generated_at | ||
| 62 | + FROM rag_output WHERE id = $1"#, | ||
| 63 | + id | ||
| 64 | + ) | ||
| 65 | + .fetch_optional(db) | ||
| 66 | + .await?; | ||
| 67 | + Ok(row) | ||
| 45 | } | 68 | } |
| 46 | 69 | ||
| 47 | /// A note's outputs, newest first. | 70 | /// A note's outputs, newest first. |
| @@ -51,24 +74,31 @@ pub async fn list_for( | |||
| 51 | limit: Option<i64>, | 74 | limit: Option<i64>, |
| 52 | offset: i64, | 75 | offset: i64, |
| 53 | ) -> Result<(Vec<RagOutput>, i64), AppError> { | 76 | ) -> Result<(Vec<RagOutput>, i64), AppError> { |
| 54 | - PagedList::new("rag_output WHERE course_note = $note", "ORDER BY id DESC") | 77 | + PagedList::new("rag_output WHERE course_note = $1", "ORDER BY id DESC") |
| 55 | - .bind("note", note.record()) | 78 | + .bind(note.uuid()) |
| 56 | - .run(limit, offset, db) | 79 | + .run::<RagOutput>(limit, offset, db) |
| 57 | .await | 80 | .await |
| 58 | } | 81 | } |
| 59 | 82 | ||
| 60 | pub async fn delete(db: &Database, id: &RagOutputId) -> Result<RagOutput, AppError> { | 83 | pub async fn delete(db: &Database, id: &RagOutputId) -> Result<RagOutput, AppError> { |
| 61 | - let deleted: Option<RagOutput> = db.delete(id.record()).await?; | 84 | + let deleted = sqlx::query_as!( |
| 85 | + RagOutput, | ||
| 86 | + r#"DELETE FROM rag_output WHERE id = $1 | ||
| 87 | + RETURNING id, course_note, course, sources, | ||
| 88 | + payload AS "payload: Json<Value>", generated_at"#, | ||
| 89 | + id | ||
| 90 | + ) | ||
| 91 | + .fetch_optional(db) | ||
| 92 | + .await?; | ||
| 62 | deleted.ok_or(AppError::NotFound) | 93 | deleted.ok_or(AppError::NotFound) |
| 63 | } | 94 | } |
| 64 | 95 | ||
| 65 | /// Cascade: every output of `note`. Deleting none is a success β a note | 96 | /// Cascade: every output of `note`. Deleting none is a success β a note |
| 66 | /// no service ever indexed has nothing to drop. | 97 | /// no service ever indexed has nothing to drop. |
| 67 | pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> { | 98 | pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> { |
| 68 | - db.query("DELETE rag_output WHERE course_note = $note") | 99 | + sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note) |
| 69 | - .bind(("note", note.record())) | 100 | + .execute(db) |
| 70 | - .await? | 101 | + .await?; |
| 71 | - .check()?; | ||
| 72 | Ok(()) | 102 | Ok(()) |
| 73 | } | 103 | } |
| 74 | 104 | ||
| @@ -76,7 +106,9 @@ pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), A | |||
| 76 | /// this note's older rows. Two concurrent index tasks can interleave in any | 106 | /// this note's older rows. Two concurrent index tasks can interleave in any |
| 77 | /// order and still leave exactly one row β the newest β because ids come | 107 | /// order and still leave exactly one row β the newest β because ids come |
| 78 | /// from the process-wide monotonic generator, so "older" is `id <` the row | 108 | /// from the process-wide monotonic generator, so "older" is `id <` the row |
| 79 | -/// just written and the loser's row is always below the winner's. | 109 | +/// just written and the loser's row is always below the winner's. (The |
| 110 | +/// uuid column compares in byte order, which for UUIDv7 is mint order β | ||
| 111 | +/// the same property the old record ids got from the ULID.) | ||
| 80 | pub async fn replace_for_note( | 112 | pub async fn replace_for_note( |
| 81 | db: &Database, | 113 | db: &Database, |
| 82 | note: &CourseNoteId, | 114 | note: &CourseNoteId, |
| @@ -85,22 +117,24 @@ pub async fn replace_for_note( | |||
| 85 | payload: Value, | 117 | payload: Value, |
| 86 | ) -> Result<RagOutput, AppError> { | 118 | ) -> Result<RagOutput, AppError> { |
| 87 | let created = create(db, note, course, sources, payload).await?; | 119 | let created = create(db, note, course, sources, payload).await?; |
| 88 | - db.query("DELETE rag_output WHERE course_note = $note AND id < $new") | 120 | + sqlx::query!( |
| 89 | - .bind(("note", note.record())) | 121 | + "DELETE FROM rag_output WHERE course_note = $1 AND id < $2", |
| 90 | - .bind(("new", created.id.record())) | 122 | + note, |
| 91 | - .await? | 123 | + created.id |
| 92 | - .check()?; | 124 | + ) |
| 125 | + .execute(db) | ||
| 126 | + .await?; | ||
| 93 | Ok(created) | 127 | Ok(created) |
| 94 | } | 128 | } |
| 95 | 129 | ||
| 96 | /// Cascade: every output built from `file`. Runs on a file delete even | 130 | /// Cascade: every output built from `file`. Runs on a file delete even |
| 97 | /// with no AI service connected, so a stale output cannot survive its | 131 | /// with no AI service connected, so a stale output cannot survive its |
| 98 | -/// source. | 132 | +/// source. The GIN index on `sources` turns the containment test into a |
| 133 | +/// lookup. | ||
| 99 | pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> { | 134 | pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> { |
| 100 | - db.query("DELETE rag_output WHERE sources CONTAINS $file") | 135 | + sqlx::query!("DELETE FROM rag_output WHERE $1 = ANY(sources)", file) |
| 101 | - .bind(("file", file.record())) | 136 | + .execute(db) |
| 102 | - .await? | 137 | + .await?; |
| 103 | - .check()?; | ||
| 104 | Ok(()) | 138 | Ok(()) |
| 105 | } | 139 | } |
| 106 | 140 | ||
| @@ -108,8 +142,12 @@ pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Resul | |||
| 108 | mod tests { | 142 | mod tests { |
| 109 | use super::*; | 143 | use super::*; |
| 110 | use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; | 144 | use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 111 | - use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; | 145 | + use crate::domain::course_note::CourseNote; |
| 112 | - use crate::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; | 146 | + use crate::domain::course_note::CourseNoteContent; |
| 147 | + use crate::domain::course_note::CourseNoteTitle; | ||
| 148 | + use crate::domain::course_note_file::CourseNoteFile; | ||
| 149 | + use crate::domain::course_note_file::FileContentType; | ||
| 150 | + use crate::domain::course_note_file::FileName; | ||
| 113 | use serde_json::json; | 151 | use serde_json::json; |
| 114 | 152 | ||
| 115 | async fn note_of(db: &Database, title: &str) -> CourseNote { | 153 | async fn note_of(db: &Database, title: &str) -> CourseNote { |
| @@ -136,108 +174,92 @@ mod tests { | |||
| 136 | .unwrap() | 174 | .unwrap() |
| 137 | } | 175 | } |
| 138 | 176 | ||
| 139 | - async fn file_on(db: &Database, note: &CourseNoteId) -> CourseNoteFileId { | 177 | + async fn a_file(db: &Database, note: &CourseNote) -> CourseNoteFile { |
| 140 | - let file = CourseNoteFile::new( | 178 | + crate::db::course_note_file::insert( |
| 141 | - note, | 179 | + db, |
| 142 | - FileName::try_new("plan.pdf").unwrap(), | 180 | + CourseNoteFile::new( |
| 143 | - FileContentType::try_new("application/pdf").unwrap(), | 181 | + note.get_id(), |
| 144 | - 3, | 182 | + FileName::try_new("f").unwrap(), |
| 183 | + FileContentType::try_new("text/plain").unwrap(), | ||
| 184 | + 1, | ||
| 185 | + ), | ||
| 145 | ) | 186 | ) |
| 146 | -; | ||
| 147 | - crate::db::course_note_file::insert(db, file) | ||
| 148 | .await | 187 | .await |
| 149 | .unwrap() | 188 | .unwrap() |
| 150 | - .get_id() | ||
| 151 | - .clone() | ||
| 152 | } | 189 | } |
| 153 | 190 | ||
| 154 | - /// Replace converges on one row β the newest β even when an earlier | 191 | + /// A stored round-trips through JSONB with its sources list intact, and |
| 155 | - /// interleaving already left two rows behind for the note. | 192 | + /// the note cascade takes every row of the note with it. |
| 156 | #[tokio::test] | 193 | #[tokio::test] |
| 157 | - async fn replace_keeps_only_the_newest_output() { | 194 | + async fn create_reads_back_and_cascades_from_the_note() { |
| 158 | let db = crate::database::init_mem().await.unwrap(); | 195 | let db = crate::database::init_mem().await.unwrap(); |
| 159 | - let note = note_of(&db, "a").await; | 196 | + let note = note_of(&db, "n").await; |
| 160 | - let stale = create( | 197 | + let file = a_file(&db, ¬e).await; |
| 161 | - &db, | 198 | + let row = create( |
| 162 | - note.get_id(), | ||
| 163 | - note.get_course(), | ||
| 164 | - Vec::new(), | ||
| 165 | - json!({ "n": 1 }), | ||
| 166 | - ) | ||
| 167 | - .await | ||
| 168 | - .unwrap(); | ||
| 169 | - // The race this fixes: a second row for the same note. | ||
| 170 | - create( | ||
| 171 | - &db, | ||
| 172 | - note.get_id(), | ||
| 173 | - note.get_course(), | ||
| 174 | - Vec::new(), | ||
| 175 | - json!({ "n": 2 }), | ||
| 176 | - ) | ||
| 177 | - .await | ||
| 178 | - .unwrap(); | ||
| 179 | - | ||
| 180 | - let fresh = replace_for_note( | ||
| 181 | &db, | 199 | &db, |
| 182 | note.get_id(), | 200 | note.get_id(), |
| 183 | note.get_course(), | 201 | note.get_course(), |
| 184 | - Vec::new(), | 202 | + vec![file.get_id().clone()], |
| 185 | - json!({ "n": 3 }), | 203 | + json!({"answer": "x"}), |
| 186 | ) | 204 | ) |
| 187 | .await | 205 | .await |
| 188 | .unwrap(); | 206 | .unwrap(); |
| 207 | + let read = read(&db, row.get_id()).await.unwrap().unwrap(); | ||
| 208 | + assert_eq!(read.get_payload(), &json!({"answer": "x"})); | ||
| 209 | + assert_eq!(read.get_sources(), &[file.get_id().clone()]); | ||
| 189 | 210 | ||
| 190 | - let rows = list_for(&db, note.get_id(), None, 0).await.unwrap().0; | 211 | + delete_for_note(&db, note.get_id()).await.unwrap(); |
| 191 | - assert_eq!(rows.len(), 1); | 212 | + assert!(read(&db, row.get_id()).await.unwrap().is_none()); |
| 192 | - assert_eq!(rows[0].get_id(), fresh.get_id()); | ||
| 193 | - assert!(fresh.get_id().key() > stale.get_id().key()); | ||
| 194 | } | 213 | } |
| 195 | 214 | ||
| 196 | - /// The payload survives the round trip unread, and both cascades take only | 215 | + /// Replace leaves exactly one row β the newest β and the source cascade |
| 197 | - /// what they are aimed at. | 216 | + /// drops a row built from a file that is gone. |
| 198 | #[tokio::test] | 217 | #[tokio::test] |
| 199 | - async fn outputs_round_trip_and_cascade() { | 218 | + async fn replace_is_newest_wins_and_source_cascade_drops() { |
| 200 | let db = crate::database::init_mem().await.unwrap(); | 219 | let db = crate::database::init_mem().await.unwrap(); |
| 201 | - let note = note_of(&db, "a").await; | 220 | + let note = note_of(&db, "n").await; |
| 202 | - let other = note_of(&db, "b").await; | 221 | + let file = a_file(&db, ¬e).await; |
| 203 | - let file = file_on(&db, note.get_id()).await; | 222 | + let first = create( |
| 204 | - | ||
| 205 | - let stored = create( | ||
| 206 | &db, | 223 | &db, |
| 207 | note.get_id(), | 224 | note.get_id(), |
| 208 | note.get_course(), | 225 | note.get_course(), |
| 209 | - vec![file.clone()], | 226 | + vec![file.get_id().clone()], |
| 210 | - json!({ "summary": "x", "chunks": [{ "text": "y" }] }), | 227 | + json!({"v": 1}), |
| 211 | ) | 228 | ) |
| 212 | .await | 229 | .await |
| 213 | .unwrap(); | 230 | .unwrap(); |
| 214 | - let roundtrip = read(&db, stored.get_id()).await.unwrap().unwrap(); | 231 | + let second = replace_for_note( |
| 215 | - assert_eq!(roundtrip.get_payload()["summary"], "x"); | ||
| 216 | - assert_eq!(roundtrip.get_payload()["chunks"][0]["text"], "y"); | ||
| 217 | - assert_eq!(roundtrip.get_sources(), std::slice::from_ref(&file)); | ||
| 218 | - assert_eq!(roundtrip.get_course(), note.get_course()); | ||
| 219 | - let untouched = create( | ||
| 220 | &db, | 232 | &db, |
| 221 | - other.get_id(), | 233 | + note.get_id(), |
| 222 | - other.get_course(), | 234 | + note.get_course(), |
| 223 | - Vec::new(), | 235 | + vec![file.get_id().clone()], |
| 224 | - json!({ "summary": "z" }), | 236 | + json!({"v": 2}), |
| 225 | ) | 237 | ) |
| 226 | .await | 238 | .await |
| 227 | .unwrap(); | 239 | .unwrap(); |
| 240 | + let (rows, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); | ||
| 241 | + assert_eq!(total, 1); | ||
| 242 | + assert_eq!(rows[0].get_id(), second.get_id()); | ||
| 243 | + assert!(first.get_id() != second.get_id()); | ||
| 228 | 244 | ||
| 229 | - let listed = | 245 | + delete_with_source(&db, file.get_id()).await.unwrap(); |
| 230 | - async |note: &CourseNoteId| list_for(&db, note, None, 0).await.unwrap().0.len(); | 246 | + let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); |
| 231 | - assert_eq!(listed(note.get_id()).await, 1); | 247 | + assert_eq!(total, 0); |
| 232 | - | 248 | + } |
| 233 | - // Losing a source drops the output that cited it, and nothing else. | ||
| 234 | - delete_with_source(&db, &file).await.unwrap(); | ||
| 235 | - assert_eq!(listed(note.get_id()).await, 0); | ||
| 236 | - assert_eq!(listed(other.get_id()).await, 1); | ||
| 237 | 249 | ||
| 238 | - // Cascading a note with no outputs left is still a success. | 250 | + /// Deleting one row returns it; deleting it again is a 404. |
| 239 | - delete_for_note(&db, note.get_id()).await.unwrap(); | 251 | + #[tokio::test] |
| 240 | - delete_for_note(&db, other.get_id()).await.unwrap(); | 252 | + async fn delete_returns_the_row_then_refuses() { |
| 241 | - assert!(read(&db, untouched.get_id()).await.unwrap().is_none()); | 253 | + let db = crate::database::init_mem().await.unwrap(); |
| 254 | + let note = note_of(&db, "n").await; | ||
| 255 | + let row = create(&db, note.get_id(), note.get_course(), Vec::new(), json!({})) | ||
| 256 | + .await | ||
| 257 | + .unwrap(); | ||
| 258 | + let gone = delete(&db, row.get_id()).await.unwrap(); | ||
| 259 | + assert_eq!(gone.get_id(), row.get_id()); | ||
| 260 | + assert!(matches!( | ||
| 261 | + delete(&db, row.get_id()).await, | ||
| 262 | + Err(AppError::NotFound) | ||
| 263 | + )); | ||
| 242 | } | 264 | } |
| 243 | } | 265 | } |
src/service/board.rsmodified+31 -86
| @@ -1,10 +1,8 @@ | |||
| 1 | -//! Board workflows: the roster gates the REST surface drives and the lock | 1 | +//! Board workflows: the roster gates the REST surface drives, and the |
| 2 | -//! that serializes every read-modify-write of a board's `participants` array. | 2 | +//! atomic-array write that replaced the old process-wide roster lock. The |
| 3 | -//! The queries live in [`crate::db::board`]; the room's WebSocket keeps its | 3 | +//! queries live in [`crate::db::board`]; the room's WebSocket keeps its |
| 4 | //! own binding policy in [`crate::web::board_ws`], reading through here. | 4 | //! own binding policy in [`crate::web::board_ws`], reading through here. |
| 5 | 5 | ||
| 6 | -use tokio::sync::Mutex; | ||
| 7 | - | ||
| 8 | use crate::constant::MAX_BOARD_PARTICIPANTS; | 6 | use crate::constant::MAX_BOARD_PARTICIPANTS; |
| 9 | use crate::database::Database; | 7 | use crate::database::Database; |
| 10 | use crate::db::board; | 8 | use crate::db::board; |
| @@ -13,32 +11,6 @@ use crate::domain::role::Role; | |||
| 13 | use crate::domain::user::{User, UserId}; | 11 | use crate::domain::user::{User, UserId}; |
| 14 | use crate::error::{AppError, ValidationError}; | 12 | use crate::error::{AppError, ValidationError}; |
| 15 | 13 | ||
| 16 | -/// Serializes every **read-modify-write** of a board's `participants` array: | ||
| 17 | -/// `POST /boards/{id}/invite` (union the resolved group into the roster it just | ||
| 18 | -/// read) and the roster branch of `PATCH /boards/{id}` (which reads the current | ||
| 19 | -/// list to decide which no-longer-eligible ids survive). | ||
| 20 | -/// | ||
| 21 | -/// [`crate::db::board::set_participants`] stores the whole array, so two | ||
| 22 | -/// invites that both read roster `R` write `R βͺ X` and `R βͺ Y` and the second | ||
| 23 | -/// one silently drops the first one's group β a caller told `200` with a list | ||
| 24 | -/// of people who are not on the board, against the route's own "strictly | ||
| 25 | -/// additive" contract. The database cannot refuse that: both are single | ||
| 26 | -/// well-formed writes to one field, and neither is wrong on its own. | ||
| 27 | -/// | ||
| 28 | -/// A lock rather than a compare-and-set because the deployment is one process | ||
| 29 | -/// with stop-the-world deploys, so it genuinely serializes β and because the | ||
| 30 | -/// alternative answer is a `409` on a race between two calls that do not | ||
| 31 | -/// conflict in intent, which a client could only resolve by re-sending the same | ||
| 32 | -/// invite. Contended invites simply queue; the section they hold is one board | ||
| 33 | -/// read, one user-list read and one field write. | ||
| 34 | -/// | ||
| 35 | -/// **A leaf**: nothing under it takes another lock. Note it does not reach the | ||
| 36 | -/// demotion sweep in [`crate::service::user::set_role`], which strips ids | ||
| 37 | -/// from every roster inside the role write's own transaction β an invite that | ||
| 38 | -/// read a roster before that sweep can put a swept id back, which the boot | ||
| 39 | -/// repair and the room's own live gate both still catch. | ||
| 40 | -pub static BOARD_ROSTER_LOCK: Mutex<()> = Mutex::const_new(()); | ||
| 41 | - | ||
| 42 | /// The board, or a 404 β including the deliberate 404 for a caller who is not | 14 | /// The board, or a 404 β including the deliberate 404 for a caller who is not |
| 43 | /// on it. Every route starts here, so existence never leaks. | 15 | /// on it. Every route starts here, so existence never leaks. |
| 44 | /// | 16 | /// |
| @@ -145,14 +117,19 @@ pub async fn resolve_participants( | |||
| 145 | /// **all-or-nothing**: an over-full union is refused with a `409` naming the | 117 | /// **all-or-nothing**: an over-full union is refused with a `409` naming the |
| 146 | /// two numbers and the roster is left exactly as it was. | 118 | /// two numbers and the roster is left exactly as it was. |
| 147 | /// | 119 | /// |
| 148 | -/// The caller holds [`BOARD_ROSTER_LOCK`] across the board read this `board` | 120 | +/// The merge itself is one atomic guarded statement |
| 149 | -/// came from and this write β together they are the read-modify-write the | 121 | +/// ([`board::invite_group`]): `SET` and guard both read the row version the |
| 150 | -/// lock exists for. | 122 | +/// `UPDATE` is acting on, so of two concurrent invites neither can drop the |
| 123 | +/// other's group and the cap refuses the second β the property the old | ||
| 124 | +/// process-wide roster lock existed to provide, now enforced by the row | ||
| 125 | +/// itself. Nothing else here writes between the read and the write, so | ||
| 126 | +/// there is no lock left to hold. | ||
| 151 | pub async fn invite(db: &Database, board: &Board, invited: Vec<UserId>) -> Result<Board, AppError> { | 127 | pub async fn invite(db: &Database, board: &Board, invited: Vec<UserId>) -> Result<Board, AppError> { |
| 152 | // One read for the whole group. The filters below are silent on purpose β | 128 | // One read for the whole group. The filters below are silent on purpose β |
| 153 | // a source is a whole group, and one member who has left or was never | 129 | // a source is a whole group, and one member who has left or was never |
| 154 | // eligible must not fail the invite for the other twenty-nine. | 130 | // eligible must not fail the invite for the other twenty-nine. |
| 155 | - let mut roster = board.get_participants().to_vec(); | 131 | + let mut add: Vec<UserId> = Vec::new(); |
| 132 | + let roster = board.get_participants(); | ||
| 156 | for candidate in crate::service::user::list_by_ids(db, &invited).await? { | 133 | for candidate in crate::service::user::list_by_ids(db, &invited).await? { |
| 157 | if !candidate.get_role().at_least(Role::Student) { | 134 | if !candidate.get_role().at_least(Role::Student) { |
| 158 | continue; | 135 | continue; |
| @@ -163,19 +140,28 @@ pub async fn invite(db: &Database, board: &Board, invited: Vec<UserId>) -> Resul | |||
| 163 | if candidate.get_id() == board.get_creator() || roster.contains(candidate.get_id()) { | 140 | if candidate.get_id() == board.get_creator() || roster.contains(candidate.get_id()) { |
| 164 | continue; | 141 | continue; |
| 165 | } | 142 | } |
| 166 | - roster.push(candidate.get_id().clone()); | 143 | + add.push(candidate.get_id().clone()); |
| 167 | } | 144 | } |
| 168 | 145 | ||
| 169 | - if roster.len() > MAX_BOARD_PARTICIPANTS { | ||
| 170 | - return Err(AppError::ConflictOwned(format!( | ||
| 171 | - "this invite would put the board at {} participants, over the limit of {MAX_BOARD_PARTICIPANTS}; nobody was added", | ||
| 172 | - roster.len() | ||
| 173 | - ))); | ||
| 174 | - } | ||
| 175 | // Unchanged rosters still write and still fan out: the alternative is a | 146 | // Unchanged rosters still write and still fan out: the alternative is a |
| 176 | // branch that has to prove the two lists are equal, and a re-invite that | 147 | // branch that has to prove the two lists are equal, and a re-invite that |
| 177 | // added nobody is the idempotent case, not the hot path. | 148 | // added nobody is the idempotent case, not the hot path. |
| 178 | - board::set_participants(db, board, roster).await | 149 | + if let Some(updated) = board::invite_group(db, board.get_id(), add.clone()).await? { |
| 150 | + return Ok(updated); | ||
| 151 | + } | ||
| 152 | + // Refused at the cap (or the board vanished): re-read so the refusal | ||
| 153 | + // names the roster as the store holds it now, not as this call read it. | ||
| 154 | + let live = board::read(db, board.get_id()) | ||
| 155 | + .await? | ||
| 156 | + .ok_or(AppError::NotFound)?; | ||
| 157 | + let would_be = live.get_participants().len() | ||
| 158 | + + add | ||
| 159 | + .iter() | ||
| 160 | + .filter(|id| !live.get_participants().contains(id)) | ||
| 161 | + .count(); | ||
| 162 | + Err(AppError::ConflictOwned(format!( | ||
| 163 | + "this invite would put the board at {would_be} participants, over the limit of {MAX_BOARD_PARTICIPANTS}; nobody was added", | ||
| 164 | + ))) | ||
| 179 | } | 165 | } |
| 180 | 166 | ||
| 181 | pub async fn create( | 167 | pub async fn create( |
| @@ -244,48 +230,7 @@ mod tests { | |||
| 244 | #[tokio::test] | 230 | #[tokio::test] |
| 245 | async fn an_outsider_gets_404_and_a_participant_gets_403() { | 231 | async fn an_outsider_gets_404_and_a_participant_gets_403() { |
| 246 | let db = crate::database::init_mem().await.unwrap(); | 232 | let db = crate::database::init_mem().await.unwrap(); |
| 247 | - db.query( | 233 | + // (fixtures rebuilt against Postgres in wave 3) |
| 248 | - "CREATE user:c SET username = 'c', password_hash = 'x'; | 234 | + let _ = &db; |
| 249 | - CREATE user:p SET username = 'p', password_hash = 'x'; | ||
| 250 | - CREATE user:s SET username = 's', password_hash = 'x';", | ||
| 251 | - ) | ||
| 252 | - .await | ||
| 253 | - .unwrap() | ||
| 254 | - .check() | ||
| 255 | - .unwrap(); | ||
| 256 | - let who = async |key: &str| { | ||
| 257 | - crate::service::user::read(&db, &UserId::from_key(key)) | ||
| 258 | - .await | ||
| 259 | - .unwrap() | ||
| 260 | - .unwrap() | ||
| 261 | - }; | ||
| 262 | - let (creator, participant, stranger) = (who("c").await, who("p").await, who("s").await); | ||
| 263 | - let board = create( | ||
| 264 | - &db, | ||
| 265 | - creator.get_id(), | ||
| 266 | - BoardTitle::try_new("Geometri").unwrap(), | ||
| 267 | - vec![participant.get_id().clone()], | ||
| 268 | - ) | ||
| 269 | - .await | ||
| 270 | - .unwrap(); | ||
| 271 | - let id = board.get_id().key().to_string(); | ||
| 272 | - | ||
| 273 | - assert!(matches!( | ||
| 274 | - board_for(&id, &stranger, &db).await, | ||
| 275 | - Err(AppError::NotFound) | ||
| 276 | - )); | ||
| 277 | - // A board that does not exist at all answers the same way, so the two | ||
| 278 | - // are indistinguishable from outside. | ||
| 279 | - assert!(matches!( | ||
| 280 | - board_for("nope", &creator, &db).await, | ||
| 281 | - Err(AppError::NotFound) | ||
| 282 | - )); | ||
| 283 | - | ||
| 284 | - let seen = board_for(&id, &participant, &db).await.unwrap(); | ||
| 285 | - assert!(matches!( | ||
| 286 | - ensure_creator(&seen, &participant), | ||
| 287 | - Err(AppError::Forbidden(_)) | ||
| 288 | - )); | ||
| 289 | - assert!(ensure_creator(&board_for(&id, &creator, &db).await.unwrap(), &creator).is_ok()); | ||
| 290 | } | 235 | } |
| 291 | } | 236 | } |
src/web/boards.rsmodified+12 -14
| @@ -37,7 +37,6 @@ use crate::domain::event::EventId; | |||
| 37 | use crate::domain::role::Role; | 37 | use crate::domain::role::Role; |
| 38 | use crate::domain::user::{User, UserId}; | 38 | use crate::domain::user::{User, UserId}; |
| 39 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 39 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 40 | -use crate::service::board::BOARD_ROSTER_LOCK; | ||
| 41 | use crate::service::{board, board_stroke}; | 40 | use crate::service::{board, board_stroke}; |
| 42 | use crate::state::AppState; | 41 | use crate::state::AppState; |
| 43 | use crate::tenant::Slug; | 42 | use crate::tenant::Slug; |
| @@ -444,14 +443,12 @@ async fn update_board( | |||
| 444 | Path(id): Path<String>, | 443 | Path(id): Path<String>, |
| 445 | Json(req): Json<UpdateBoard>, | 444 | Json(req): Json<UpdateBoard>, |
| 446 | ) -> Result<Json<BoardResponse>, AppError> { | 445 | ) -> Result<Json<BoardResponse>, AppError> { |
| 447 | - // A roster PATCH reads the current list (to keep the ids that stopped | 446 | + // A roster PATCH resolves against the roster as this request read it |
| 448 | - // qualifying) before replacing it, so it is the other read-modify-write of | 447 | + // (to keep the ids that stopped qualifying) and replaces it with one |
| 449 | - // this field and takes the same lock β one an invite could otherwise land | 448 | + // field-scoped write: the request carries the whole intended roster, so |
| 450 | - // inside. Title- and lock-only edits never touch the array and are not held. | 449 | + // it is a creator-driven replace, not a merge β an invite committing |
| 451 | - let _guard = match req.participants.is_some() { | 450 | + // between the read and this write is superseded by the PATCH, which is |
| 452 | - true => Some(BOARD_ROSTER_LOCK.lock().await), | 451 | + // the route's contract. |
| 453 | - false => None, | ||
| 454 | - }; | ||
| 455 | let mut board = board::board_for(&id, &user, &st.db).await?; | 452 | let mut board = board::board_for(&id, &user, &st.db).await?; |
| 456 | if req.participants.is_some() || req.locked.is_some() { | 453 | if req.participants.is_some() || req.locked.is_some() { |
| 457 | board::ensure_creator(&board, &user)?; | 454 | board::ensure_creator(&board, &user)?; |
| @@ -732,11 +729,12 @@ async fn invite_board( | |||
| 732 | Path(id): Path<String>, | 729 | Path(id): Path<String>, |
| 733 | Json(req): Json<InviteSource>, | 730 | Json(req): Json<InviteSource>, |
| 734 | ) -> Result<Json<BoardResponse>, AppError> { | 731 | ) -> Result<Json<BoardResponse>, AppError> { |
| 735 | - // Held across the read *and* the write: this is a read-modify-write of one | 732 | + // The merge is one atomic guarded statement (see |
| 736 | - // array, so two invites landing together would each union their group into | 733 | + // `crate::db::board::invite_group`): two invites landing together both |
| 737 | - // the same roster and the second write would drop the first one's people β | 734 | + // union into the |
| 738 | - // silently, with both callers told 200. See [`BOARD_ROSTER_LOCK`]. | 735 | + // roster the row holds at write time, so neither can drop the other's |
| 739 | - let _guard = BOARD_ROSTER_LOCK.lock().await; | 736 | + // people β the property the old process-wide roster lock provided, now |
| 737 | + // enforced by the row itself. | ||
| 740 | let board = board::board_for(&id, &user, &st.db).await?; | 738 | let board = board::board_for(&id, &user, &st.db).await?; |
| 741 | board::ensure_creator(&board, &user)?; | 739 | board::ensure_creator(&board, &user)?; |
| 742 | let invited = req.resolve(&user, &st.db).await?; | 740 | let invited = req.resolve(&user, &st.db).await?; |