Merge branch 'layer-split/notes_board'
Browse files at this commit33 changed files +2730 -2314
- src/ai/rag.rs +2 -1
- src/ai/server.rs +3 -4
- src/db/board.rs +455 -0
- src/db/board_stroke.rs +800 -0
- src/db/course_note.rs +203 -0
- src/db/course_note_file.rs +243 -0
- src/db/mod.rs +5 -0
- src/db/note.rs +18 -14
- src/db/note_file.rs +200 -0
- src/db/user.rs +4 -4
- src/domain/board.rs +37 -473
- src/domain/board_stroke.rs +36 -820
- src/domain/course_note.rs +9 -196
- src/domain/course_note_file.rs +14 -255
- src/domain/note_file.rs +13 -198
- src/service/board.rs +291 -0
- src/service/board_stroke.rs +58 -0
- src/service/course.rs +2 -2
- src/service/course_note.rs +55 -0
- src/service/course_note_file.rs +48 -0
- src/service/mod.rs +5 -0
- src/service/note_file.rs +39 -0
- src/service/user.rs +47 -31
- src/web/board_ws.rs +29 -34
- src/web/boards.rs +32 -214
- src/web/course_notes.rs +28 -19
- src/web/notes.rs +8 -7
- tests/integration.rs +5 -3
- tests/pagination.rs +4 -4
- tests/persistence.rs +2 -2
- tests/regress_boards.rs +4 -5
- tests/regress_caps.rs +8 -9
- tests/regress_course_child_orphans.rs +23 -19
src/ai/rag.rsmodified+2 -1
| @@ -109,7 +109,8 @@ pub async fn index_course_note(state: &AppState, tenant: &ResolvedTenant, note: | |||
| 109 | // Read the attachments here rather than taking a caller's list: the | 109 | // Read the attachments here rather than taking a caller's list: the |
| 110 | // dispatch runs after the handler answered, so this is the freshest view | 110 | // dispatch runs after the handler answered, so this is the freshest view |
| 111 | // of what the note holds, and the ids it sends are the ids it stores. | 111 | // of what the note holds, and the ids it sends are the ids it stores. |
| 112 | - let files = match CourseNoteFile::list_for(note.get_id(), None, 0, &state.db).await { | 112 | + let files = match crate::db::course_note_file::list_for(&state.db, note.get_id(), None, 0).await |
| 113 | + { | ||
| 113 | Ok((files, _)) => files, | 114 | Ok((files, _)) => files, |
| 114 | Err(err) => { | 115 | Err(err) => { |
| 115 | tracing::warn!("could not load course note files for rag.index: {err}"); | 116 | tracing::warn!("could not load course note files for rag.index: {err}"); |
src/ai/server.rsmodified+3 -4
| @@ -27,8 +27,7 @@ use crate::constant::{ | |||
| 27 | }; | 27 | }; |
| 28 | use crate::database::Database; | 28 | use crate::database::Database; |
| 29 | 29 | ||
| 30 | -use crate::domain::course_note::CourseNote; | 30 | +use crate::domain::course_note_file::CourseNoteFileId; |
| 31 | -use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; | ||
| 32 | use crate::domain::user::{User, UserId}; | 31 | use crate::domain::user::{User, UserId}; |
| 33 | use crate::error::AppError; | 32 | use crate::error::AppError; |
| 34 | use crate::module::Module; | 33 | use crate::module::Module; |
| @@ -631,11 +630,11 @@ async fn open_blob( | |||
| 631 | ) | 630 | ) |
| 632 | }; | 631 | }; |
| 633 | let unavailable = |e: crate::error::AppError| ("unavailable", e.to_string()); | 632 | let unavailable = |e: crate::error::AppError| ("unavailable", e.to_string()); |
| 634 | - let file = CourseNoteFile::read(&CourseNoteFileId::from_key(&request.file), &db) | 633 | + let file = crate::db::course_note_file::read(&db, &CourseNoteFileId::from_key(&request.file)) |
| 635 | .await | 634 | .await |
| 636 | .map_err(unavailable)? | 635 | .map_err(unavailable)? |
| 637 | .ok_or_else(missing)?; | 636 | .ok_or_else(missing)?; |
| 638 | - let note = CourseNote::read(file.get_course_note(), &db) | 637 | + let note = crate::db::course_note::read(&db, file.get_course_note()) |
| 639 | .await | 638 | .await |
| 640 | .map_err(unavailable)? | 639 | .map_err(unavailable)? |
| 641 | .ok_or_else(missing)?; | 640 | .ok_or_else(missing)?; |
src/db/board.rsadded+455 -0
| @@ -0,0 +1,455 @@ | |||
| 1 | +//! The `board` table: whiteboard rooms and their rosters. Every write here is | ||
| 2 | +//! field-scoped `UPDATE … SET` — a stroke landing concurrently is moving the | ||
| 3 | +//! two counters this table's struct does not carry. | ||
| 4 | + | ||
| 5 | +use surrealdb::types::SurrealValue; | ||
| 6 | + | ||
| 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; | ||
| 11 | +use crate::domain::board::{Board, BoardId, BoardTitle, checked_participants}; | ||
| 12 | +use crate::domain::timestamp::Timestamp; | ||
| 13 | +use crate::domain::user::UserId; | ||
| 14 | +use crate::error::AppError; | ||
| 15 | + | ||
| 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( | ||
| 20 | + db: &Database, | ||
| 21 | + creator: &UserId, | ||
| 22 | + title: BoardTitle, | ||
| 23 | + participants: Vec<UserId>, | ||
| 24 | +) -> Result<Board, AppError> { | ||
| 25 | + let board = Board { | ||
| 26 | + id: BoardId::generate(), | ||
| 27 | + creator: creator.clone(), | ||
| 28 | + title, | ||
| 29 | + participants: checked_participants(participants)?, | ||
| 30 | + locked: false, | ||
| 31 | + locked_by: None, | ||
| 32 | + locked_at: None, | ||
| 33 | + epoch: 0, | ||
| 34 | + closed_at: None, | ||
| 35 | + created_at: Timestamp::now(), | ||
| 36 | + }; | ||
| 37 | + match cap::claim_and_create( | ||
| 38 | + &creator.record(), | ||
| 39 | + USER_BOARD_COUNT_FIELD, | ||
| 40 | + MAX_BOARDS_PER_CREATOR, | ||
| 41 | + &board.id.record(), | ||
| 42 | + &board, | ||
| 43 | + db, | ||
| 44 | + ) | ||
| 45 | + .await? | ||
| 46 | + { | ||
| 47 | + cap::Claimed::Made(saved) => Ok(saved), | ||
| 48 | + // Full, or the creator's row is gone — the conditional write | ||
| 49 | + // matches nothing either way. | ||
| 50 | + cap::Claimed::Full => Err(AppError::Conflict( | ||
| 51 | + "you have reached the limit on boards — delete one first", | ||
| 52 | + )), | ||
| 53 | + // The id is a freshly minted ULID on a table with no UNIQUE index, | ||
| 54 | + // so no rival can have aimed at it. | ||
| 55 | + cap::Claimed::Duplicate => Err(AppError::Internal("board id collided".into())), | ||
| 56 | + } | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +pub async fn read(db: &Database, id: &BoardId) -> Result<Option<Board>, AppError> { | ||
| 60 | + Ok(db.select(id.record()).await?) | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +/// Every board `user` may open: the ones they created and the ones they | ||
| 64 | +/// were invited to. Newest first — the ids are monotonic, so `id` is the | ||
| 65 | +/// creation order. | ||
| 66 | +/// | ||
| 67 | +/// `open` narrows by `closed_at`, and it means exactly that flag: a board | ||
| 68 | +/// that is locked, or full at its lifetime cap but never drawn on again, is | ||
| 69 | +/// never stamped and so reads as **open** — because it is. Only a creator's | ||
| 70 | +/// `/close` and the lifetime cap's own refusal ever stamp one. | ||
| 71 | +pub async fn list_for_user( | ||
| 72 | + db: &Database, | ||
| 73 | + user: &UserId, | ||
| 74 | + open: Option<bool>, | ||
| 75 | + limit: Option<i64>, | ||
| 76 | + offset: i64, | ||
| 77 | +) -> Result<(Vec<Board>, i64), AppError> { | ||
| 78 | + let open_clause = match open { | ||
| 79 | + Some(true) => " AND closed_at = NONE", | ||
| 80 | + Some(false) => " AND closed_at != NONE", | ||
| 81 | + None => "", | ||
| 82 | + }; | ||
| 83 | + PagedList::new( | ||
| 84 | + format!("board WHERE (creator = $usr OR participants CONTAINS $usr){open_clause}"), | ||
| 85 | + "ORDER BY id DESC", | ||
| 86 | + ) | ||
| 87 | + .bind("usr", user.record()) | ||
| 88 | + .run(limit, offset, db) | ||
| 89 | + .await | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +/// Re-invite. Field-scoped, like every write here: a stroke landing | ||
| 93 | +/// concurrently is moving the counters this struct does not carry. | ||
| 94 | +pub async fn set_participants( | ||
| 95 | + db: &Database, | ||
| 96 | + board: &Board, | ||
| 97 | + participants: Vec<UserId>, | ||
| 98 | +) -> Result<Board, AppError> { | ||
| 99 | + let participants = checked_participants(participants)?; | ||
| 100 | + let mut result = db | ||
| 101 | + .query("UPDATE $id SET participants = $who RETURN AFTER") | ||
| 102 | + .bind(("id", board.id.record())) | ||
| 103 | + .bind(( | ||
| 104 | + "who", | ||
| 105 | + participants | ||
| 106 | + .iter() | ||
| 107 | + .map(|user| user.record()) | ||
| 108 | + .collect::<Vec<_>>(), | ||
| 109 | + )) | ||
| 110 | + .await? | ||
| 111 | + .check()?; | ||
| 112 | + one(result.take::<Vec<Board>>(0)?) | ||
| 113 | +} | ||
| 114 | + | ||
| 115 | +pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result<Board, AppError> { | ||
| 116 | + let mut result = db | ||
| 117 | + .query("UPDATE $id SET title = $title RETURN AFTER") | ||
| 118 | + .bind(("id", board.id.record())) | ||
| 119 | + .bind(("title", title.0)) | ||
| 120 | + .await? | ||
| 121 | + .check()?; | ||
| 122 | + one(result.take::<Vec<Board>>(0)?) | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +/// Freeze or thaw drawing. `locked_by`/`locked_at` are cleared on unlock so | ||
| 126 | +/// the row never claims a lock that is not held. | ||
| 127 | +pub async fn set_locked( | ||
| 128 | + db: &Database, | ||
| 129 | + board: &Board, | ||
| 130 | + locked: bool, | ||
| 131 | + by: &UserId, | ||
| 132 | +) -> Result<Board, AppError> { | ||
| 133 | + let now = Timestamp::now(); | ||
| 134 | + let mut result = db | ||
| 135 | + .query("UPDATE $id SET locked = $locked, locked_by = $by, locked_at = $at RETURN AFTER") | ||
| 136 | + .bind(("id", board.id.record())) | ||
| 137 | + .bind(("locked", locked)) | ||
| 138 | + .bind(("by", locked.then(|| by.record()))) | ||
| 139 | + .bind(("at", locked.then(|| now.as_millis()))) | ||
| 140 | + .await? | ||
| 141 | + .check()?; | ||
| 142 | + one(result.take::<Vec<Board>>(0)?) | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +// The demotion sweep — stripping a user off every roster they are listed | ||
| 146 | +// on, deleting nothing, and handing the affected rooms back so the caller | ||
| 147 | +// can prompt them — lives in [`crate::service::user::set_role`], where | ||
| 148 | +// it commits with the role write that invalidates the membership. | ||
| 149 | + | ||
| 150 | +/// Retire the board: permanently read-only, history still readable. | ||
| 151 | +/// 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. | ||
| 153 | +pub async fn close(db: &Database, board: &Board) -> Result<Board, AppError> { | ||
| 154 | + let mut result = db | ||
| 155 | + .query("UPDATE $id SET closed_at = $now WHERE closed_at = NONE RETURN AFTER") | ||
| 156 | + .bind(("id", board.id.record())) | ||
| 157 | + .bind(("now", Timestamp::now().as_millis())) | ||
| 158 | + .await? | ||
| 159 | + .check()?; | ||
| 160 | + match result.take::<Vec<Board>>(0)?.into_iter().next() { | ||
| 161 | + Some(board) => Ok(board), | ||
| 162 | + // Already closed: the row is unchanged, so read it back rather | ||
| 163 | + // than report a 404 for a board that plainly exists. | ||
| 164 | + None => read(db, &board.id).await?.ok_or(AppError::NotFound), | ||
| 165 | + } | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +/// Delete the board and give the creator's slot back in the *same* | ||
| 169 | +/// transaction — a release issued afterwards can be lost, and the counter | ||
| 170 | +/// would then ratchet the creator's limit shut forever. | ||
| 171 | +/// | ||
| 172 | +/// The stroke cascade rides in that same transaction: it is the one and | ||
| 173 | +/// only legitimate delete of `board_stroke` rows (a clear deletes nothing), | ||
| 174 | +/// and issued separately it could leave a board's whole history orphaned | ||
| 175 | +/// under a record that no longer exists. | ||
| 176 | +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 | ||
| 178 | + // aborts one of the two and a lost round is ordinary here — re-sent | ||
| 179 | + // rather than reported as a 500. Re-sending is sound: every statement | ||
| 180 | + // is a `DELETE` or a field-scoped `UPDATE`, none of which can ever | ||
| 181 | + // answer "already exists" (see [`transaction_with_retry`]). | ||
| 182 | + let (mut result, mut errors) = transaction_with_retry( | ||
| 183 | + db, | ||
| 184 | + "BEGIN TRANSACTION; | ||
| 185 | + DELETE board_stroke WHERE board = $id; | ||
| 186 | + LET $gone = (DELETE $id RETURN BEFORE); | ||
| 187 | + UPDATE $usr SET board_count = math::max([(board_count ?? 0) - array::len($gone), 0]); | ||
| 188 | + RETURN $gone; | ||
| 189 | + COMMIT TRANSACTION;", | ||
| 190 | + &[ | ||
| 191 | + ("id".into(), board.id.record().into_value()), | ||
| 192 | + ("usr".into(), board.creator.record().into_value()), | ||
| 193 | + ], | ||
| 194 | + &[], | ||
| 195 | + ) | ||
| 196 | + .await?; | ||
| 197 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 198 | + return Err(error.into()); | ||
| 199 | + } | ||
| 200 | + // Slots count BEGIN, the cascade, the LET and the UPDATE: the RETURN | ||
| 201 | + // is slot 4. | ||
| 202 | + one(result.take::<Vec<Board>>(4)?) | ||
| 203 | +} | ||
| 204 | + | ||
| 205 | +fn one(rows: Vec<Board>) -> Result<Board, AppError> { | ||
| 206 | + rows.into_iter().next().ok_or(AppError::NotFound) | ||
| 207 | +} | ||
| 208 | + | ||
| 209 | +#[cfg(test)] | ||
| 210 | +mod tests { | ||
| 211 | + use super::*; | ||
| 212 | + use surrealdb::types::RecordId; | ||
| 213 | + | ||
| 214 | + async fn a_db() -> Database { | ||
| 215 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 216 | + db.query( | ||
| 217 | + "CREATE user:c SET username = 'c', password_hash = 'x'; | ||
| 218 | + CREATE user:p SET username = 'p', password_hash = 'x'; | ||
| 219 | + CREATE user:s SET username = 's', password_hash = 'x';", | ||
| 220 | + ) | ||
| 221 | + .await | ||
| 222 | + .unwrap() | ||
| 223 | + .check() | ||
| 224 | + .unwrap(); | ||
| 225 | + db | ||
| 226 | + } | ||
| 227 | + | ||
| 228 | + fn user(key: &str) -> UserId { | ||
| 229 | + UserId::from_key(key) | ||
| 230 | + } | ||
| 231 | + | ||
| 232 | + /// The stored counter, re-read out of the database. Never asserted off a | ||
| 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 | ||
| 239 | + .unwrap() | ||
| 240 | + .check() | ||
| 241 | + .unwrap(); | ||
| 242 | + result.take::<Vec<i64>>(0).unwrap()[0] | ||
| 243 | + } | ||
| 244 | + | ||
| 245 | + async fn a_board(db: &Database) -> Board { | ||
| 246 | + create( | ||
| 247 | + db, | ||
| 248 | + &user("c"), | ||
| 249 | + BoardTitle::try_new("Geometri").unwrap(), | ||
| 250 | + vec![user("p")], | ||
| 251 | + ) | ||
| 252 | + .await | ||
| 253 | + .unwrap() | ||
| 254 | + } | ||
| 255 | + | ||
| 256 | + /// The cap refuses at `MAX_BOARDS_PER_CREATOR`, and the refusal writes | ||
| 257 | + /// nothing — asserted by re-reading the counter, not off the return value. | ||
| 258 | + #[tokio::test] | ||
| 259 | + async fn the_per_creator_cap_refuses_a_full_creator() { | ||
| 260 | + let db = a_db().await; | ||
| 261 | + db.query("UPDATE user:c SET board_count = $full") | ||
| 262 | + .bind(("full", MAX_BOARDS_PER_CREATOR)) | ||
| 263 | + .await | ||
| 264 | + .unwrap() | ||
| 265 | + .check() | ||
| 266 | + .unwrap(); | ||
| 267 | + let refused = create( | ||
| 268 | + &db, | ||
| 269 | + &user("c"), | ||
| 270 | + BoardTitle::try_new("Geometri").unwrap(), | ||
| 271 | + vec![], | ||
| 272 | + ) | ||
| 273 | + .await; | ||
| 274 | + assert!(matches!(refused, 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 | + | ||
| 319 | + #[tokio::test] | ||
| 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 | ||
| 326 | + .unwrap() | ||
| 327 | + .check() | ||
| 328 | + .unwrap(); | ||
| 329 | + set_title(&db, &board, BoardTitle::try_new("Cebir").unwrap()) | ||
| 330 | + .await | ||
| 331 | + .unwrap(); | ||
| 332 | + set_participants(&db, &board, vec![user("s")]) | ||
| 333 | + .await | ||
| 334 | + .unwrap(); | ||
| 335 | + set_locked(&db, &board, true, &user("c")).await.unwrap(); | ||
| 336 | + close(&db, &board).await.unwrap(); | ||
| 337 | + let mut result = db | ||
| 338 | + .query("SELECT VALUE [epoch_stroke_count, total_stroke_count] FROM $id") | ||
| 339 | + .bind(("id", board.get_id().record())) | ||
| 340 | + .await | ||
| 341 | + .unwrap() | ||
| 342 | + .check() | ||
| 343 | + .unwrap(); | ||
| 344 | + assert_eq!(result.take::<Vec<Vec<i64>>>(0).unwrap()[0], vec![7, 9]); | ||
| 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 | + } | ||
| 455 | +} | ||
src/db/board_stroke.rsadded+800 -0
| @@ -0,0 +1,800 @@ | |||
| 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 | ||
| 3 | +//! written through the conditional claims in here and nowhere else. | ||
| 4 | + | ||
| 5 | +use surrealdb::types::{RecordId, SurrealValue, Value}; | ||
| 6 | + | ||
| 7 | +use crate::constant::{ | ||
| 8 | + BOARD_EPOCH_STROKE_COUNT_FIELD, BOARD_OPEN_GUARD, BOARD_REPLAY_CHUNK, BOARD_STROKE_TABLE, | ||
| 9 | + BOARD_TOTAL_STROKE_COUNT_FIELD, MAX_BOARD_STROKES, MAX_EPOCH_STROKES, MAX_STROKE_PAYLOAD_LEN, | ||
| 10 | +}; | ||
| 11 | +use crate::database::{Database, transaction_with_retry}; | ||
| 12 | +use crate::db::cap; | ||
| 13 | +use crate::db::page::PagedList; | ||
| 14 | +use crate::domain::board::BoardId; | ||
| 15 | +use crate::domain::board_stroke::{ | ||
| 16 | + BOARD_CLOSED, BOARD_MOVED, BoardStroke, BoardStrokeId, CANVAS_BLANK, CLEAR_REFUSED, EPOCH_FULL, | ||
| 17 | + KIND_CLEAR, KIND_STROKE, NOT_THE_CREATOR, state_refusal, | ||
| 18 | +}; | ||
| 19 | +use crate::domain::timestamp::Timestamp; | ||
| 20 | +use crate::domain::user::UserId; | ||
| 21 | +use crate::error::AppError; | ||
| 22 | +use crate::validate::validate_required; | ||
| 23 | + | ||
| 24 | +/// Append one mark to `board`'s current `epoch`. | ||
| 25 | +/// | ||
| 26 | +/// 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 | ||
| 28 | +/// are one conditional write, so a locked or closed board can never be | ||
| 29 | +/// drawn on by a writer that read it a moment earlier. | ||
| 30 | +/// | ||
| 31 | +/// `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 | ||
| 33 | +/// just ended while its increment counted against the *new* epoch's | ||
| 34 | +/// counter — one race, two markers corrupted for good (the closed one short | ||
| 35 | +/// by a stroke, the next one claiming a stroke that is not there), and | ||
| 36 | +/// markers are never rewritten. Now such a stroke is refused instead. | ||
| 37 | +pub async fn append( | ||
| 38 | + db: &Database, | ||
| 39 | + board: &BoardId, | ||
| 40 | + author: &UserId, | ||
| 41 | + payload: &str, | ||
| 42 | + epoch: i64, | ||
| 43 | +) -> Result<BoardStroke, AppError> { | ||
| 44 | + validate_required("payload", payload, MAX_STROKE_PAYLOAD_LEN)?; | ||
| 45 | + let stroke = BoardStroke { | ||
| 46 | + id: BoardStrokeId::generate(), | ||
| 47 | + board: board.clone(), | ||
| 48 | + author: author.clone(), | ||
| 49 | + kind: KIND_STROKE.to_string(), | ||
| 50 | + payload: Some(payload.to_string()), | ||
| 51 | + count: None, | ||
| 52 | + epoch, | ||
| 53 | + created_at: Timestamp::now(), | ||
| 54 | + }; | ||
| 55 | + // `epoch` is an in-crate `i64` read off the board row, never text from | ||
| 56 | + // a client, so it interpolates into the guard as a bare integer. | ||
| 57 | + let guard = format!("{BOARD_OPEN_GUARD} AND epoch = {epoch}"); | ||
| 58 | + match cap::claim_two_when_and_create( | ||
| 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 | + ) | ||
| 67 | + .await? | ||
| 68 | + { | ||
| 69 | + cap::ClaimedTwo::Made(saved) => Ok(saved), | ||
| 70 | + // The live canvas is full and nothing else: recoverable by a clear, | ||
| 71 | + // which resets this counter without losing a single mark. | ||
| 72 | + cap::ClaimedTwo::FullSoft => Err(AppError::Conflict(EPOCH_FULL)), | ||
| 73 | + // Three refusals share this answer (lifetime full / guard failed / | ||
| 74 | + // board gone), so the board is re-read to tell them apart. A board | ||
| 75 | + // that changed state in between still gets told "no" — but only a | ||
| 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 | + } | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +/// The one place `closed` is ordered above `locked` lives in | ||
| 83 | +/// [`state_refusal`]; both refusal paths re-read the board and | ||
| 84 | +/// ask it. | ||
| 85 | + | ||
| 86 | +async fn why_refused(db: &Database, board: &BoardId) -> Result<AppError, AppError> { | ||
| 87 | + let board = crate::db::board::read(db, board) | ||
| 88 | + .await? | ||
| 89 | + .ok_or(AppError::NotFound)?; | ||
| 90 | + if let Some(refusal) = state_refusal(&board) { | ||
| 91 | + return Ok(AppError::Conflict(refusal)); | ||
| 92 | + } | ||
| 93 | + // Neither flag, so the lifetime counter has to say so *itself*: | ||
| 94 | + // `FullHard` also fires when the guard failed, so a board that was | ||
| 95 | + // locked (or a clear that moved the epoch) when the claim ran and is | ||
| 96 | + // open again now would otherwise be stamped read-only at one stroke of | ||
| 97 | + // a 50 000 budget — irreversibly, with no reopen. | ||
| 98 | + if total_strokes(db, board.get_id()).await? < MAX_BOARD_STROKES { | ||
| 99 | + return Ok(AppError::Conflict(BOARD_MOVED)); | ||
| 100 | + } | ||
| 101 | + // `Board::close` is the one-way idempotent stamp: a second append takes | ||
| 102 | + // this branch too and leaves the first `closed_at` standing. | ||
| 103 | + crate::db::board::close(db, &board).await?; | ||
| 104 | + Ok(AppError::Conflict(BOARD_CLOSED)) | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +/// The lifetime counter as the store holds it — the board struct | ||
| 108 | +/// deliberately does not carry it (src/domain/board.rs:9-13). | ||
| 109 | +async fn total_strokes(db: &Database, board: &BoardId) -> Result<i64, AppError> { | ||
| 110 | + let mut result = db | ||
| 111 | + .query(format!( | ||
| 112 | + "SELECT VALUE ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) FROM $b" | ||
| 113 | + )) | ||
| 114 | + .bind(("b", board.record())) | ||
| 115 | + .await? | ||
| 116 | + .check()?; | ||
| 117 | + Ok(result.take::<Vec<i64>>(0)?.into_iter().next().unwrap_or(0)) | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +/// End the current epoch: the canvas empties, the history does not. | ||
| 121 | +/// | ||
| 122 | +/// The bump and the marker are one transaction, because the marker carries | ||
| 123 | +/// the epoch's final count — written apart, a crash between them would | ||
| 124 | +/// leave an epoch no marker indexes, and the playback would silently join | ||
| 125 | +/// two sessions into one. | ||
| 126 | +/// | ||
| 127 | +/// **The marker pays the lifetime counter.** It is a real `board_stroke` | ||
| 128 | +/// row, so a marker that claimed nothing left `total_stroke_count` counting | ||
| 129 | +/// strokes *drawn* rather than rows *stored*, and `MAX_BOARD_STROKES` | ||
| 130 | +/// stopped bounding the table. Charged here, the counter is exactly the row | ||
| 131 | +/// count again — the counter is reset and re-read in the same statement, so | ||
| 132 | +/// the increment cannot be split off from the marker it pays for. | ||
| 133 | +/// | ||
| 134 | +/// **A blank canvas cannot be cleared.** Without it every call minted a row | ||
| 135 | +/// for free, one per press of a button the creator can hold down. Requiring | ||
| 136 | +/// the epoch counter to be non-zero pays for each marker with at least one | ||
| 137 | +/// stroke it closes — and "there is nothing on this canvas to clear" is the | ||
| 138 | +/// honest answer to the call it refuses. The epochs index keeps its meaning | ||
| 139 | +/// too: no zero-stroke epoch can enter it. | ||
| 140 | +/// | ||
| 141 | +/// **A locked board cannot be cleared.** The lock is the creator's own | ||
| 142 | +/// pause on the canvas, and it holds against every write to it including | ||
| 143 | +/// theirs — [`BOARD_OPEN_GUARD`] is the same condition the stroke path | ||
| 144 | +/// claims under, so "locked" means one thing everywhere. The cost is | ||
| 145 | +/// accepted: a locked board sitting at `MAX_EPOCH_STROKES` is recovered by | ||
| 146 | +/// unlock, clear, relock. | ||
| 147 | +/// | ||
| 148 | +/// The marker's own increment is not capped: the last stroke of a board's | ||
| 149 | +/// budget may be closed by a marker, so a board holds at most | ||
| 150 | +/// `MAX_BOARD_STROKES + 1` rows. Capping it would refuse the clear that | ||
| 151 | +/// files the final epoch in the index, which is the one clear the history | ||
| 152 | +/// needs. | ||
| 153 | +pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result<BoardStroke, AppError> { | ||
| 154 | + let marker = BoardStrokeId::generate(); | ||
| 155 | + // `($before[0].epoch_stroke_count ?? 0)` is parenthesized: the bare form | ||
| 156 | + // parses as `?? (0 = …)` and stores a boolean count (src/constant.rs:699). | ||
| 157 | + let sql = format!( | ||
| 158 | + "BEGIN TRANSACTION; | ||
| 159 | + LET $before = (UPDATE $b SET epoch += 1, {BOARD_EPOCH_STROKE_COUNT_FIELD} = 0, \ | ||
| 160 | + {BOARD_TOTAL_STROKE_COUNT_FIELD} = ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) + 1 \ | ||
| 161 | + WHERE creator = $by AND {BOARD_OPEN_GUARD} \ | ||
| 162 | + AND ({BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0) > 0 RETURN BEFORE); | ||
| 163 | + IF array::len($before) = 0 {{ THROW '{CLEAR_REFUSED}' }}; | ||
| 164 | + CREATE $mid CONTENT {{ board: $b, author: $by, kind: $kind, \ | ||
| 165 | + epoch: $before[0].epoch, \ | ||
| 166 | + count: ($before[0].{BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0), \ | ||
| 167 | + created_at: $now }}; | ||
| 168 | + COMMIT TRANSACTION;" | ||
| 169 | + ); | ||
| 170 | + let bound: Vec<(String, Value)> = vec![ | ||
| 171 | + ("b".into(), board.record().into_value()), | ||
| 172 | + ("by".into(), by.record().into_value()), | ||
| 173 | + ("mid".into(), marker.record().into_value()), | ||
| 174 | + ("kind".into(), KIND_CLEAR.into_value()), | ||
| 175 | + ("now".into(), Timestamp::now().as_millis().into_value()), | ||
| 176 | + ]; | ||
| 177 | + // The epoch counter is reset here, which is a counter write like any | ||
| 178 | + // other, so it owes the process the same one-at-a-time discipline | ||
| 179 | + // (`cap::counter_lock`) — and unlike a lone conditional claim it is | ||
| 180 | + // read back in the same statement, by the marker's `count`. | ||
| 181 | + let _guard = cap::counter_lock().await; | ||
| 182 | + let (mut result, mut errors) = | ||
| 183 | + transaction_with_retry(db, &sql, &bound, &[CLEAR_REFUSED]).await?; | ||
| 184 | + if errors | ||
| 185 | + .values() | ||
| 186 | + .any(|error| error.to_string().contains(CLEAR_REFUSED)) | ||
| 187 | + { | ||
| 188 | + return Err(why_clear_refused(db, board, by).await?); | ||
| 189 | + } | ||
| 190 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 191 | + return Err(error.into()); | ||
| 192 | + } | ||
| 193 | + // Slots count BEGIN, the LET and the IF: the CREATE is slot 3. Only | ||
| 194 | + // read once the error map is empty — `take_errors` swap-removes. | ||
| 195 | + result | ||
| 196 | + .take::<Vec<BoardStroke>>(3)? | ||
| 197 | + .into_iter() | ||
| 198 | + .next() | ||
| 199 | + .ok_or_else(|| AppError::Internal("board clear wrote no marker".into())) | ||
| 200 | +} | ||
| 201 | + | ||
| 202 | +/// Which of the clear guard's four conditions said no. One `WHERE` cannot | ||
| 203 | +/// report that itself, so the board is re-read — on the refusal path only, | ||
| 204 | +/// like [`why_refused`]. The distinction is not cosmetic: a closed | ||
| 205 | +/// board is terminal for the room, a blank canvas is an ordinary "nothing | ||
| 206 | +/// to do" and a room told otherwise stops drawing for good. | ||
| 207 | +async fn why_clear_refused( | ||
| 208 | + db: &Database, | ||
| 209 | + board: &BoardId, | ||
| 210 | + by: &UserId, | ||
| 211 | +) -> Result<AppError, AppError> { | ||
| 212 | + let board = crate::db::board::read(db, board) | ||
| 213 | + .await? | ||
| 214 | + .ok_or(AppError::NotFound)?; | ||
| 215 | + let state = state_refusal(&board); | ||
| 216 | + // Terminal outranks the caller's identity: a closed board is read-only | ||
| 217 | + // for its creator too, so "closed" is the honest answer to anyone. | ||
| 218 | + if state == Some(BOARD_CLOSED) { | ||
| 219 | + return Ok(AppError::Conflict(BOARD_CLOSED)); | ||
| 220 | + } | ||
| 221 | + if !board.is_creator(by) { | ||
| 222 | + return Ok(AppError::Forbidden(NOT_THE_CREATOR)); | ||
| 223 | + } | ||
| 224 | + // A lock pauses the *creator* too, and it is a state the caller can | ||
| 225 | + // undo — a `Conflict`, not the `Forbidden` a wrong caller gets. Unlock, | ||
| 226 | + // clear, relock is the recovery for a locked board that is also full. | ||
| 227 | + if let Some(refusal) = state { | ||
| 228 | + return Ok(AppError::Conflict(refusal)); | ||
| 229 | + } | ||
| 230 | + Ok(AppError::Conflict(CANVAS_BLANK)) | ||
| 231 | +} | ||
| 232 | + | ||
| 233 | +/// What a joining socket draws: the current epoch's marks only, in mint | ||
| 234 | +/// order, one [`BOARD_REPLAY_CHUNK`] at a time. | ||
| 235 | +/// | ||
| 236 | +/// Paged by `id`, never `created_at` — a millisecond stamp has ties by | ||
| 237 | +/// construction, and the ULID's monotonic low half is exactly what breaks | ||
| 238 | +/// them. `after` is the key of the last stroke already drawn. | ||
| 239 | +pub async fn replay_current( | ||
| 240 | + db: &Database, | ||
| 241 | + board: &BoardId, | ||
| 242 | + epoch: i64, | ||
| 243 | + after: Option<&str>, | ||
| 244 | +) -> Result<Vec<BoardStroke>, AppError> { | ||
| 245 | + let cursor = match after { | ||
| 246 | + Some(_) => " AND id > $after", | ||
| 247 | + None => "", | ||
| 248 | + }; | ||
| 249 | + let mut result = db | ||
| 250 | + .query(format!( | ||
| 251 | + "SELECT * FROM {} \ | ||
| 252 | + WHERE board = $b AND epoch = $e AND kind = $kind{cursor} \ | ||
| 253 | + ORDER BY id LIMIT $chunk", | ||
| 254 | + BOARD_STROKE_TABLE | ||
| 255 | + )) | ||
| 256 | + .bind(("b", board.record())) | ||
| 257 | + .bind(("e", epoch)) | ||
| 258 | + .bind(("kind", KIND_STROKE)) | ||
| 259 | + .bind(( | ||
| 260 | + "after", | ||
| 261 | + RecordId::new(BOARD_STROKE_TABLE, after.unwrap_or_default()), | ||
| 262 | + )) | ||
| 263 | + .bind(("chunk", BOARD_REPLAY_CHUNK as i64)) | ||
| 264 | + .await? | ||
| 265 | + .check()?; | ||
| 266 | + Ok(result.take::<Vec<BoardStroke>>(0)?) | ||
| 267 | +} | ||
| 268 | + | ||
| 269 | +/// The whole log, oldest first — every epoch, or one named epoch. Both | ||
| 270 | +/// kinds of row come back: the `clear` markers are what tell a reader where | ||
| 271 | +/// one epoch ended and the next began. | ||
| 272 | +/// | ||
| 273 | +/// `marks_only` drops the markers, which is what the *live canvas* wants: | ||
| 274 | +/// the current epoch holds no marker by construction, except in the one | ||
| 275 | +/// race where a clear commits between the board read and this read and | ||
| 276 | +/// files its marker under the epoch just named. The room's replay filters | ||
| 277 | +/// to `kind = 'stroke'` ([`replay_current`]), so without this the two | ||
| 278 | +/// views disagree in exactly that window. | ||
| 279 | +pub async fn history( | ||
| 280 | + db: &Database, | ||
| 281 | + board: &BoardId, | ||
| 282 | + epoch: Option<i64>, | ||
| 283 | + marks_only: bool, | ||
| 284 | + limit: Option<i64>, | ||
| 285 | + offset: i64, | ||
| 286 | +) -> Result<(Vec<BoardStroke>, i64), AppError> { | ||
| 287 | + let scope = match epoch { | ||
| 288 | + Some(_) => " AND epoch = $e", | ||
| 289 | + None => "", | ||
| 290 | + }; | ||
| 291 | + let kinds = if marks_only { | ||
| 292 | + " AND kind != $clear" | ||
| 293 | + } else { | ||
| 294 | + "" | ||
| 295 | + }; | ||
| 296 | + PagedList::new( | ||
| 297 | + format!("{} WHERE board = $b{scope}{kinds}", BOARD_STROKE_TABLE), | ||
| 298 | + "ORDER BY id", | ||
| 299 | + ) | ||
| 300 | + .bind("b", board.record()) | ||
| 301 | + .bind("e", epoch.unwrap_or_default()) | ||
| 302 | + .bind("clear", KIND_CLEAR.to_string()) | ||
| 303 | + .run(limit, offset, db) | ||
| 304 | + .await | ||
| 305 | +} | ||
| 306 | + | ||
| 307 | +/// The epoch index: every `clear` marker this board has, oldest first. | ||
| 308 | +pub async fn epochs(db: &Database, board: &BoardId) -> Result<Vec<BoardStroke>, AppError> { | ||
| 309 | + let mut result = db | ||
| 310 | + .query(format!( | ||
| 311 | + "SELECT * FROM {} \ | ||
| 312 | + WHERE board = $b AND kind = $kind ORDER BY id", | ||
| 313 | + BOARD_STROKE_TABLE | ||
| 314 | + )) | ||
| 315 | + .bind(("b", board.record())) | ||
| 316 | + .bind(("kind", KIND_CLEAR)) | ||
| 317 | + .await? | ||
| 318 | + .check()?; | ||
| 319 | + Ok(result.take::<Vec<BoardStroke>>(0)?) | ||
| 320 | +} | ||
| 321 | + | ||
| 322 | +#[cfg(test)] | ||
| 323 | +mod tests { | ||
| 324 | + use super::*; | ||
| 325 | + use crate::domain::board::Board; | ||
| 326 | + use crate::domain::board::BoardTitle; | ||
| 327 | + use crate::domain::board_stroke::{BOARD_CLOSED, BOARD_LOCKED}; | ||
| 328 | + | ||
| 329 | + async fn a_db() -> Database { | ||
| 330 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 331 | + db.query( | ||
| 332 | + "CREATE user:c SET username = 'c', password_hash = 'x'; | ||
| 333 | + CREATE user:p SET username = 'p', password_hash = 'x';", | ||
| 334 | + ) | ||
| 335 | + .await | ||
| 336 | + .unwrap() | ||
| 337 | + .check() | ||
| 338 | + .unwrap(); | ||
| 339 | + db | ||
| 340 | + } | ||
| 341 | + | ||
| 342 | + fn user(key: &str) -> UserId { | ||
| 343 | + UserId::from_key(key) | ||
| 344 | + } | ||
| 345 | + | ||
| 346 | + async fn a_board(db: &Database) -> Board { | ||
| 347 | + crate::db::board::create( | ||
| 348 | + db, | ||
| 349 | + &user("c"), | ||
| 350 | + BoardTitle::try_new("Geometri").unwrap(), | ||
| 351 | + vec![user("p")], | ||
| 352 | + ) | ||
| 353 | + .await | ||
| 354 | + .unwrap() | ||
| 355 | + } | ||
| 356 | + | ||
| 357 | + /// Every stroke row of a board, read straight out of the store — never off | ||
| 358 | + /// a return value, which the in-memory engine forges wins on | ||
| 359 | + /// (src/db/cap.rs:44-49). | ||
| 360 | + async fn rows(db: &Database, board: &BoardId) -> Vec<BoardStroke> { | ||
| 361 | + let mut result = db | ||
| 362 | + .query("SELECT * FROM board_stroke WHERE board = $b ORDER BY id") | ||
| 363 | + .bind(("b", board.record())) | ||
| 364 | + .await | ||
| 365 | + .unwrap() | ||
| 366 | + .check() | ||
| 367 | + .unwrap(); | ||
| 368 | + result.take(0).unwrap() | ||
| 369 | + } | ||
| 370 | + | ||
| 371 | + async fn reread(db: &Database, board: &Board) -> Board { | ||
| 372 | + crate::db::board::read(db, board.get_id()) | ||
| 373 | + .await | ||
| 374 | + .unwrap() | ||
| 375 | + .unwrap() | ||
| 376 | + } | ||
| 377 | + | ||
| 378 | + async fn set_counters(db: &Database, board: &Board, epoch: i64, total: i64) { | ||
| 379 | + db.query("UPDATE $id SET epoch_stroke_count = $e, total_stroke_count = $t") | ||
| 380 | + .bind(("id", board.get_id().record())) | ||
| 381 | + .bind(("e", epoch)) | ||
| 382 | + .bind(("t", total)) | ||
| 383 | + .await | ||
| 384 | + .unwrap() | ||
| 385 | + .check() | ||
| 386 | + .unwrap(); | ||
| 387 | + } | ||
| 388 | + | ||
| 389 | + async fn draw(db: &Database, board: &Board) -> Result<BoardStroke, AppError> { | ||
| 390 | + append( | ||
| 391 | + db, | ||
| 392 | + board.get_id(), | ||
| 393 | + &user("p"), | ||
| 394 | + "{\"p\":[1,2]}", | ||
| 395 | + board.get_epoch(), | ||
| 396 | + ) | ||
| 397 | + .await | ||
| 398 | + } | ||
| 399 | + | ||
| 400 | + #[tokio::test] | ||
| 401 | + async fn a_full_canvas_is_refused_but_the_board_stays_open() { | ||
| 402 | + let db = a_db().await; | ||
| 403 | + let board = a_board(&db).await; | ||
| 404 | + set_counters(&db, &board, MAX_EPOCH_STROKES, 10).await; | ||
| 405 | + let refused = draw(&db, &board).await; | ||
| 406 | + assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("clear it"))); | ||
| 407 | + // Nothing written, and above all: NOT closed — a full canvas is | ||
| 408 | + // recoverable, and closing it here would make it permanent. | ||
| 409 | + assert!(rows(&db, board.get_id()).await.is_empty()); | ||
| 410 | + assert!(reread(&db, &board).await.get_closed_at().is_none()); | ||
| 411 | + } | ||
| 412 | + | ||
| 413 | + /// The user's decision in one test: a clear empties the canvas and loses | ||
| 414 | + /// nothing. If this ever passes with the pre-clear rows gone, the feature | ||
| 415 | + /// is wrong. | ||
| 416 | + #[tokio::test] | ||
| 417 | + async fn a_clear_keeps_every_pre_clear_stroke() { | ||
| 418 | + let db = a_db().await; | ||
| 419 | + let board = a_board(&db).await; | ||
| 420 | + for _ in 0..3 { | ||
| 421 | + draw(&db, &board).await.unwrap(); | ||
| 422 | + } | ||
| 423 | + let before: Vec<String> = rows(&db, board.get_id()) | ||
| 424 | + .await | ||
| 425 | + .iter() | ||
| 426 | + .map(|row| row.get_id().key().to_string()) | ||
| 427 | + .collect(); | ||
| 428 | + | ||
| 429 | + clear(&db, board.get_id(), &user("c")).await.unwrap(); | ||
| 430 | + let board = reread(&db, &board).await; | ||
| 431 | + assert_eq!(board.get_epoch(), 1); | ||
| 432 | + draw(&db, &board).await.unwrap(); | ||
| 433 | + | ||
| 434 | + // The three original rows are still in the table, by direct read. | ||
| 435 | + let after: Vec<String> = rows(&db, board.get_id()) | ||
| 436 | + .await | ||
| 437 | + .iter() | ||
| 438 | + .map(|row| row.get_id().key().to_string()) | ||
| 439 | + .collect(); | ||
| 440 | + for key in &before { | ||
| 441 | + assert!(after.contains(key), "a clear deleted stroke {key}"); | ||
| 442 | + } | ||
| 443 | + // 3 old + 1 marker + 1 new, and the live canvas is the new one alone. | ||
| 444 | + assert_eq!(after.len(), 5); | ||
| 445 | + let live = replay_current(&db, board.get_id(), 1, None).await.unwrap(); | ||
| 446 | + assert_eq!(live.len(), 1); | ||
| 447 | + // The old epoch is still replayable in full. | ||
| 448 | + assert_eq!( | ||
| 449 | + replay_current(&db, board.get_id(), 0, None) | ||
| 450 | + .await | ||
| 451 | + .unwrap() | ||
| 452 | + .len(), | ||
| 453 | + 3 | ||
| 454 | + ); | ||
| 455 | + } | ||
| 456 | + | ||
| 457 | + /// The marker IS the epoch index, so its `count` has to be that epoch's | ||
| 458 | + /// final stroke count — and `count` must appear on no other row. | ||
| 459 | + #[tokio::test] | ||
| 460 | + async fn the_marker_counts_the_epoch_it_closed() { | ||
| 461 | + let db = a_db().await; | ||
| 462 | + let board = a_board(&db).await; | ||
| 463 | + for _ in 0..4 { | ||
| 464 | + draw(&db, &board).await.unwrap(); | ||
| 465 | + } | ||
| 466 | + let marker = clear(&db, board.get_id(), &user("c")).await.unwrap(); | ||
| 467 | + assert_eq!(marker.get_count(), Some(4)); | ||
| 468 | + assert_eq!(marker.get_epoch(), 0); | ||
| 469 | + assert!(marker.is_clear()); | ||
| 470 | + | ||
| 471 | + // And the epoch counter reset, so drawing resumes against a fresh cap. | ||
| 472 | + let board = reread(&db, &board).await; | ||
| 473 | + draw(&db, &board).await.unwrap(); | ||
| 474 | + let epochs = epochs(&db, board.get_id()).await.unwrap(); | ||
| 475 | + assert_eq!(epochs.len(), 1); | ||
| 476 | + assert_eq!(epochs[0].get_count(), Some(4)); | ||
| 477 | + // `count` lives on clear markers only — this module is that guard. | ||
| 478 | + for row in rows(&db, board.get_id()).await { | ||
| 479 | + assert_eq!(row.get_count().is_some(), row.is_clear()); | ||
| 480 | + assert_eq!(row.get_payload().is_some(), !row.is_clear()); | ||
| 481 | + } | ||
| 482 | + } | ||
| 483 | + | ||
| 484 | + #[tokio::test] | ||
| 485 | + async fn the_lifetime_cap_closes_the_board_exactly_once() { | ||
| 486 | + let db = a_db().await; | ||
| 487 | + let board = a_board(&db).await; | ||
| 488 | + set_counters(&db, &board, 0, MAX_BOARD_STROKES).await; | ||
| 489 | + let refused = draw(&db, &board).await; | ||
| 490 | + assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("read-only"))); | ||
| 491 | + let stamp = reread(&db, &board).await.get_closed_at(); | ||
| 492 | + assert!(stamp.is_some()); | ||
| 493 | + | ||
| 494 | + // A whole millisecond apart, so a re-stamp could not go unnoticed. | ||
| 495 | + tokio::time::sleep(std::time::Duration::from_millis(2)).await; | ||
| 496 | + assert!(draw(&db, &board).await.is_err()); | ||
| 497 | + assert_eq!(reread(&db, &board).await.get_closed_at(), stamp); | ||
| 498 | + assert!(rows(&db, board.get_id()).await.is_empty()); | ||
| 499 | + } | ||
| 500 | + | ||
| 501 | + /// A locked board must be told it is locked. Both refusals arrive as the | ||
| 502 | + /// same `FullHard`, so a re-read that got this wrong would tell a paused | ||
| 503 | + /// room its canvas is full — and send it clearing a board it need not clear. | ||
| 504 | + #[tokio::test] | ||
| 505 | + async fn a_locked_board_is_refused_as_locked() { | ||
| 506 | + let db = a_db().await; | ||
| 507 | + let board = a_board(&db).await; | ||
| 508 | + let board = crate::db::board::set_locked(&db, &board, true, &user("c")) | ||
| 509 | + .await | ||
| 510 | + .unwrap(); | ||
| 511 | + let refused = draw(&db, &board).await; | ||
| 512 | + assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("locked"))); | ||
| 513 | + assert!(rows(&db, board.get_id()).await.is_empty()); | ||
| 514 | + // A lock is not a close: unlocking restores drawing. | ||
| 515 | + assert!(reread(&db, &board).await.get_closed_at().is_none()); | ||
| 516 | + let board = crate::db::board::set_locked(&db, &board, false, &user("c")) | ||
| 517 | + .await | ||
| 518 | + .unwrap(); | ||
| 519 | + assert!(draw(&db, &board).await.is_ok()); | ||
| 520 | + } | ||
| 521 | + | ||
| 522 | + /// A lock the stroke lost to, unlocked again before the refusal re-reads | ||
| 523 | + /// the row — which is the state `why_refused` is handed after a guard | ||
| 524 | + /// failure. Reading "neither locked nor closed" as proof of the lifetime | ||
| 525 | + /// cap stamped `closed_at` on a board holding one stroke of 50 000, with | ||
| 526 | + /// no reopen. Only the counter itself may close a board. | ||
| 527 | + #[tokio::test] | ||
| 528 | + async fn a_refusal_on_an_open_board_never_closes_it() { | ||
| 529 | + let db = a_db().await; | ||
| 530 | + let board = a_board(&db).await; | ||
| 531 | + let board = crate::db::board::set_locked(&db, &board, true, &user("c")) | ||
| 532 | + .await | ||
| 533 | + .unwrap(); | ||
| 534 | + // The claim loses the open-guard while the board is locked... | ||
| 535 | + assert!(matches!( | ||
| 536 | + draw(&db, &board).await, | ||
| 537 | + Err(AppError::Conflict(_)) | ||
| 538 | + )); | ||
| 539 | + // ...and the creator unlocks before the refusal picks its message. | ||
| 540 | + let board = crate::db::board::set_locked(&db, &board, false, &user("c")) | ||
| 541 | + .await | ||
| 542 | + .unwrap(); | ||
| 543 | + let refused = why_refused(&db, board.get_id()).await.unwrap(); | ||
| 544 | + assert!(matches!(refused, AppError::Conflict(msg) if !msg.contains("read-only"))); | ||
| 545 | + // Stored state, not the return value: the board is still open, and | ||
| 546 | + // still drawable. | ||
| 547 | + assert!(reread(&db, &board).await.get_closed_at().is_none()); | ||
| 548 | + assert!(draw(&db, &reread(&db, &board).await).await.is_ok()); | ||
| 549 | + } | ||
| 550 | + | ||
| 551 | + /// The epoch index must never drift, in either direction. A stroke carrying | ||
| 552 | + /// a pre-clear epoch used to land under the closed epoch while its | ||
| 553 | + /// increment counted against the new one — the closed marker short by a | ||
| 554 | + /// stroke, the next marker claiming one that is not there, both permanent. | ||
| 555 | + #[tokio::test] | ||
| 556 | + async fn a_stale_epoch_append_leaves_no_marker_drifted() { | ||
| 557 | + let db = a_db().await; | ||
| 558 | + let board = a_board(&db).await; | ||
| 559 | + draw(&db, &board).await.unwrap(); | ||
| 560 | + clear(&db, board.get_id(), &user("c")).await.unwrap(); | ||
| 561 | + | ||
| 562 | + // Exactly what `live_board` hands `append` when a clear lands between | ||
| 563 | + // the board read and the write (src/web/board_ws.rs:431). | ||
| 564 | + let stale = append(&db, board.get_id(), &user("p"), "{\"p\":[9]}", 0).await; | ||
| 565 | + assert!(matches!(stale, Err(AppError::Conflict(_)))); | ||
| 566 | + | ||
| 567 | + let board = reread(&db, &board).await; | ||
| 568 | + draw(&db, &board).await.unwrap(); | ||
| 569 | + clear(&db, board.get_id(), &user("c")).await.unwrap(); | ||
| 570 | + | ||
| 571 | + // Every marker's count is the rows the store actually holds at the | ||
| 572 | + // epoch it closed. | ||
| 573 | + let stored = rows(&db, board.get_id()).await; | ||
| 574 | + for marker in stored.iter().filter(|row| row.is_clear()) { | ||
| 575 | + let actual = stored | ||
| 576 | + .iter() | ||
| 577 | + .filter(|row| !row.is_clear() && row.get_epoch() == marker.get_epoch()) | ||
| 578 | + .count() as i64; | ||
| 579 | + assert_eq!( | ||
| 580 | + marker.get_count(), | ||
| 581 | + Some(actual), | ||
| 582 | + "marker for epoch {} drifted", | ||
| 583 | + marker.get_epoch() | ||
| 584 | + ); | ||
| 585 | + } | ||
| 586 | + // And the refused stroke claimed nothing: two marks and the two | ||
| 587 | + // markers that closed them, which is every row on the table. | ||
| 588 | + assert_eq!(total_strokes(&db, board.get_id()).await.unwrap(), 4); | ||
| 589 | + assert_eq!(stored.len(), 4); | ||
| 590 | + } | ||
| 591 | + | ||
| 592 | + /// The lock pauses the canvas against *every* write to it, its creator's | ||
| 593 | + /// clear included — a `Conflict`, since unlocking undoes it, not the | ||
| 594 | + /// `Forbidden` a non-creator gets. Asserted off stored rows: the refusal | ||
| 595 | + /// must mint no marker and must not bump the epoch. | ||
| 596 | + #[tokio::test] | ||
| 597 | + async fn a_locked_board_refuses_its_creator_s_clear() { | ||
| 598 | + let db = a_db().await; | ||
| 599 | + let board = a_board(&db).await; | ||
| 600 | + draw(&db, &board).await.unwrap(); | ||
| 601 | + let board = crate::db::board::set_locked(&db, &board, true, &user("c")) | ||
| 602 | + .await | ||
| 603 | + .unwrap(); | ||
| 604 | + | ||
| 605 | + let refused = clear(&db, board.get_id(), &user("c")).await; | ||
| 606 | + assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg == BOARD_LOCKED)); | ||
| 607 | + assert_eq!(rows(&db, board.get_id()).await.len(), 1); | ||
| 608 | + assert_eq!(reread(&db, &board).await.get_epoch(), 0); | ||
| 609 | + assert!(epochs(&db, board.get_id()).await.unwrap().is_empty()); | ||
| 610 | + | ||
| 611 | + // Unlock, and the same clear lands: unlock → clear → relock is the | ||
| 612 | + // recovery for a locked board sitting at the epoch cap. | ||
| 613 | + let board = crate::db::board::set_locked(&db, &board, false, &user("c")) | ||
| 614 | + .await | ||
| 615 | + .unwrap(); | ||
| 616 | + let marker = clear(&db, board.get_id(), &user("c")).await.unwrap(); | ||
| 617 | + assert_eq!(marker.get_count(), Some(1)); | ||
| 618 | + assert_eq!(reread(&db, &board).await.get_epoch(), 1); | ||
| 619 | + } | ||
| 620 | + | ||
| 621 | + /// Both classifiers, one board: the words a stroke is refused with and the | ||
| 622 | + /// words the *creator's* clear is refused with. They must match — the two | ||
| 623 | + /// used to be independent chains and drifted apart on the state below. | ||
| 624 | + async fn both_refusals(db: &Database, board: &Board) -> (&'static str, &'static str) { | ||
| 625 | + let stroke = match draw(db, board).await { | ||
| 626 | + Err(AppError::Conflict(msg)) => msg, | ||
| 627 | + other => panic!("the stroke was not refused: {other:?}"), | ||
| 628 | + }; | ||
| 629 | + let clear = match clear(db, board.get_id(), &user("c")).await { | ||
| 630 | + Err(AppError::Conflict(msg)) => msg, | ||
| 631 | + other => panic!("the clear was not refused: {other:?}"), | ||
| 632 | + }; | ||
| 633 | + (stroke, clear) | ||
| 634 | + } | ||
| 635 | + | ||
| 636 | + /// A board that is locked *and* closed is terminal, and both paths have to | ||
| 637 | + /// say so. Reaching the state is ungated in either direction — `set_locked` | ||
| 638 | + /// carries no `closed_at` test and `close` carries no lock test — and the | ||
| 639 | + /// stroke path used to test the lock first, so a permanently read-only | ||
| 640 | + /// board answered every mark with "the creator has paused drawing" while | ||
| 641 | + /// the same board answered a clear with the terminal words. A room told to | ||
| 642 | + /// wait for a pause that cannot lift waits forever. | ||
| 643 | + /// | ||
| 644 | + /// Locking a closed board stays *allowed*: it is a no-op on a board that is | ||
| 645 | + /// already read-only, and refusing it would break the second half of a | ||
| 646 | + /// close-then-lock a client may legitimately send in either order. | ||
| 647 | + #[tokio::test] | ||
| 648 | + async fn locked_and_closed_answers_closed_whichever_came_first() { | ||
| 649 | + for closed_first in [false, true] { | ||
| 650 | + let db = a_db().await; | ||
| 651 | + let board = a_board(&db).await; | ||
| 652 | + // A mark on the canvas, so "nothing to clear" cannot be the reason. | ||
| 653 | + draw(&db, &board).await.unwrap(); | ||
| 654 | + | ||
| 655 | + let board = if closed_first { | ||
| 656 | + let board = crate::db::board::close(&db, &board).await.unwrap(); | ||
| 657 | + crate::db::board::set_locked(&db, &board, true, &user("c")) | ||
| 658 | + .await | ||
| 659 | + .unwrap() | ||
| 660 | + } else { | ||
| 661 | + let board = crate::db::board::set_locked(&db, &board, true, &user("c")) | ||
| 662 | + .await | ||
| 663 | + .unwrap(); | ||
| 664 | + crate::db::board::close(&db, &board).await.unwrap() | ||
| 665 | + }; | ||
| 666 | + // Stored state: both flags really are up, and the close stamp stood. | ||
| 667 | + let stored = reread(&db, &board).await; | ||
| 668 | + assert!(stored.is_locked() && stored.get_closed_at().is_some()); | ||
| 669 | + | ||
| 670 | + assert_eq!( | ||
| 671 | + both_refusals(&db, &board).await, | ||
| 672 | + (BOARD_CLOSED, BOARD_CLOSED), | ||
| 673 | + "closed_first = {closed_first}" | ||
| 674 | + ); | ||
| 675 | + // And the refusals wrote nothing: one mark, no marker, epoch 0. | ||
| 676 | + assert_eq!(rows(&db, board.get_id()).await.len(), 1); | ||
| 677 | + assert_eq!(reread(&db, &board).await.get_epoch(), 0); | ||
| 678 | + } | ||
| 679 | + } | ||
| 680 | + | ||
| 681 | + /// The other half of the same contract: a board holding *one* of the flags | ||
| 682 | + /// keeps its own answer on both paths. A lock is recoverable, a close is | ||
| 683 | + /// not, and collapsing either into the other is the mislabel above. | ||
| 684 | + #[tokio::test] | ||
| 685 | + async fn one_flag_alone_keeps_its_own_answer_on_both_paths() { | ||
| 686 | + let db = a_db().await; | ||
| 687 | + let locked = a_board(&db).await; | ||
| 688 | + draw(&db, &locked).await.unwrap(); | ||
| 689 | + let locked = crate::db::board::set_locked(&db, &locked, true, &user("c")) | ||
| 690 | + .await | ||
| 691 | + .unwrap(); | ||
| 692 | + assert_eq!( | ||
| 693 | + both_refusals(&db, &locked).await, | ||
| 694 | + (BOARD_LOCKED, BOARD_LOCKED) | ||
| 695 | + ); | ||
| 696 | + | ||
| 697 | + let closed = a_board(&db).await; | ||
| 698 | + draw(&db, &closed).await.unwrap(); | ||
| 699 | + let closed = crate::db::board::close(&db, &closed).await.unwrap(); | ||
| 700 | + assert_eq!( | ||
| 701 | + both_refusals(&db, &closed).await, | ||
| 702 | + (BOARD_CLOSED, BOARD_CLOSED) | ||
| 703 | + ); | ||
| 704 | + } | ||
| 705 | + | ||
| 706 | + /// The `next_ulid` hazard: rows minted inside one millisecond must replay | ||
| 707 | + /// in mint order, not at random (src/domain/monotonic_id.rs:41-46). | ||
| 708 | + #[tokio::test] | ||
| 709 | + async fn replay_is_in_mint_order_within_a_millisecond() { | ||
| 710 | + let db = a_db().await; | ||
| 711 | + let board = a_board(&db).await; | ||
| 712 | + let mut minted = Vec::new(); | ||
| 713 | + for _ in 0..25 { | ||
| 714 | + minted.push(draw(&db, &board).await.unwrap().get_id().key().to_string()); | ||
| 715 | + } | ||
| 716 | + let replayed: Vec<String> = replay_current(&db, board.get_id(), 0, None) | ||
| 717 | + .await | ||
| 718 | + .unwrap() | ||
| 719 | + .iter() | ||
| 720 | + .map(|row| row.get_id().key().to_string()) | ||
| 721 | + .collect(); | ||
| 722 | + assert_eq!(replayed, minted); | ||
| 723 | + | ||
| 724 | + // The cursor resumes exactly where the last chunk stopped. | ||
| 725 | + let rest: Vec<String> = replay_current(&db, board.get_id(), 0, Some(&minted[9])) | ||
| 726 | + .await | ||
| 727 | + .unwrap() | ||
| 728 | + .iter() | ||
| 729 | + .map(|row| row.get_id().key().to_string()) | ||
| 730 | + .collect(); | ||
| 731 | + assert_eq!(rest, minted[10..]); | ||
| 732 | + } | ||
| 733 | + | ||
| 734 | + /// The one legitimate delete of stroke rows: without it, deleting a board | ||
| 735 | + /// orphans its whole history under a record that no longer exists. | ||
| 736 | + #[tokio::test] | ||
| 737 | + async fn deleting_a_board_takes_its_strokes_with_it() { | ||
| 738 | + let db = a_db().await; | ||
| 739 | + let board = a_board(&db).await; | ||
| 740 | + let other = a_board(&db).await; | ||
| 741 | + draw(&db, &board).await.unwrap(); | ||
| 742 | + draw(&db, &board).await.unwrap(); | ||
| 743 | + clear(&db, board.get_id(), &user("c")).await.unwrap(); | ||
| 744 | + draw(&db, &other).await.unwrap(); | ||
| 745 | + | ||
| 746 | + let id = board.get_id().clone(); | ||
| 747 | + crate::db::board::delete(&db, board).await.unwrap(); | ||
| 748 | + assert!(rows(&db, &id).await.is_empty()); | ||
| 749 | + // The cascade is scoped to its own board. | ||
| 750 | + assert_eq!(rows(&db, other.get_id()).await.len(), 1); | ||
| 751 | + } | ||
| 752 | + | ||
| 753 | + #[tokio::test] | ||
| 754 | + async fn an_oversized_payload_is_refused_before_the_write() { | ||
| 755 | + let db = a_db().await; | ||
| 756 | + let board = a_board(&db).await; | ||
| 757 | + let big = "x".repeat(MAX_STROKE_PAYLOAD_LEN + 1); | ||
| 758 | + assert!( | ||
| 759 | + append(&db, board.get_id(), &user("p"), &big, 0) | ||
| 760 | + .await | ||
| 761 | + .is_err() | ||
| 762 | + ); | ||
| 763 | + assert!( | ||
| 764 | + append(&db, board.get_id(), &user("p"), " ", 0) | ||
| 765 | + .await | ||
| 766 | + .is_err() | ||
| 767 | + ); | ||
| 768 | + assert!(rows(&db, board.get_id()).await.is_empty()); | ||
| 769 | + // Nothing was claimed either — the counters must not have moved. | ||
| 770 | + assert_eq!(reread(&db, &board).await.get_epoch(), 0); | ||
| 771 | + } | ||
| 772 | + | ||
| 773 | + /// History spans epochs; a named epoch is that epoch alone. | ||
| 774 | + #[tokio::test] | ||
| 775 | + async fn history_spans_every_epoch_unless_one_is_named() { | ||
| 776 | + let db = a_db().await; | ||
| 777 | + let board = a_board(&db).await; | ||
| 778 | + draw(&db, &board).await.unwrap(); | ||
| 779 | + clear(&db, board.get_id(), &user("c")).await.unwrap(); | ||
| 780 | + let board = reread(&db, &board).await; | ||
| 781 | + draw(&db, &board).await.unwrap(); | ||
| 782 | + | ||
| 783 | + let (all, total) = history(&db, board.get_id(), None, false, None, 0) | ||
| 784 | + .await | ||
| 785 | + .unwrap(); | ||
| 786 | + assert_eq!((all.len(), total), (3, 3)); | ||
| 787 | + let (first, total) = history(&db, board.get_id(), Some(0), false, None, 0) | ||
| 788 | + .await | ||
| 789 | + .unwrap(); | ||
| 790 | + // Epoch 0: its stroke and the marker that closed it. | ||
| 791 | + assert_eq!((first.len(), total), (2, 2)); | ||
| 792 | + // `marks_only` drops the marker from that same epoch — and its `total` | ||
| 793 | + // with it, so the envelope's count stays the count of what is served. | ||
| 794 | + let (marks, total) = history(&db, board.get_id(), Some(0), true, None, 0) | ||
| 795 | + .await | ||
| 796 | + .unwrap(); | ||
| 797 | + assert_eq!((marks.len(), total), (1, 1)); | ||
| 798 | + assert!(marks.iter().all(|row| !row.is_clear())); | ||
| 799 | + } | ||
| 800 | +} | ||
src/db/course_note.rsadded+203 -0
| @@ -0,0 +1,203 @@ | |||
| 1 | +//! The `course_note` table: a teacher-authored note attached to a course, | ||
| 2 | +//! listed newest first, deleted together with its attachment rows. | ||
| 3 | + | ||
| 4 | +use surrealdb::types::SurrealValue; | ||
| 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; | ||
| 10 | +use crate::db::page::PagedList; | ||
| 11 | +use crate::domain::course::CourseId; | ||
| 12 | +use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteId, CourseNoteTitle}; | ||
| 13 | +use crate::domain::course_note_file::CourseNoteFile; | ||
| 14 | +use crate::domain::user::UserId; | ||
| 15 | +use crate::error::AppError; | ||
| 16 | + | ||
| 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( | ||
| 27 | + db: &Database, | ||
| 28 | + course: &CourseId, | ||
| 29 | + author: &UserId, | ||
| 30 | + title: CourseNoteTitle, | ||
| 31 | + content: CourseNoteContent, | ||
| 32 | +) -> Result<CourseNote, AppError> { | ||
| 33 | + let note = CourseNote { | ||
| 34 | + id: CourseNoteId::generate(), | ||
| 35 | + course: course.clone(), | ||
| 36 | + author: author.clone(), | ||
| 37 | + title, | ||
| 38 | + content, | ||
| 39 | + }; | ||
| 40 | + // The course row is *written* (bumped and put back), not read, so this | ||
| 41 | + // collides with `Course::delete`'s cascade: a note that outlives its | ||
| 42 | + // course is unreachable forever — every route to it goes through the | ||
| 43 | + // course. See [`cap::touch_and_create`]. | ||
| 44 | + cap::touch_and_create( | ||
| 45 | + &course.record(), | ||
| 46 | + ENROLLMENT_COUNT_FIELD, | ||
| 47 | + ¬e.id.record(), | ||
| 48 | + ¬e, | ||
| 49 | + db, | ||
| 50 | + ) | ||
| 51 | + .await? | ||
| 52 | + .ok_or(AppError::NotFound) | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +pub async fn read(db: &Database, id: &CourseNoteId) -> Result<Option<CourseNote>, AppError> { | ||
| 56 | + Ok(db.select(id.record()).await?) | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +pub async fn list_for_course( | ||
| 60 | + db: &Database, | ||
| 61 | + course: &CourseId, | ||
| 62 | + limit: Option<i64>, | ||
| 63 | + offset: i64, | ||
| 64 | +) -> Result<(Vec<CourseNote>, i64), AppError> { | ||
| 65 | + PagedList::new("course_note WHERE course = $crs", "ORDER BY id DESC") | ||
| 66 | + .bind("crs", course.record()) | ||
| 67 | + .run(limit, offset, db) | ||
| 68 | + .await | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +/// Request-scoped: no lock spans the handler's read and this write, so an | ||
| 72 | +/// omitted field (`None`) is not written at all. Passing the snapshot's | ||
| 73 | +/// value back instead would revert a concurrent edit of that field — | ||
| 74 | +/// scoping the `SET` alone does not prevent that, the values have to come | ||
| 75 | +/// from the request. Neither column is nullable, so plain `Option` per | ||
| 76 | +/// field says everything there is to say. | ||
| 77 | +pub async fn update( | ||
| 78 | + db: &Database, | ||
| 79 | + note: CourseNote, | ||
| 80 | + title: Option<CourseNoteTitle>, | ||
| 81 | + content: Option<CourseNoteContent>, | ||
| 82 | +) -> Result<CourseNote, AppError> { | ||
| 83 | + FieldUpdate::new(note.id.record()) | ||
| 84 | + .set("title", title) | ||
| 85 | + .set("content", content) | ||
| 86 | + .run::<CourseNote>(db) | ||
| 87 | + .await | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +/// Delete the note and cascade-remove its attachment rows, returning both: | ||
| 91 | +/// the note, and the attachment rows this transaction actually removed. | ||
| 92 | +/// 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 | ||
| 94 | +/// deleted here too, and a pre-read snapshot would strand its blob. | ||
| 95 | +pub async fn delete( | ||
| 96 | + db: &Database, | ||
| 97 | + note: CourseNote, | ||
| 98 | +) -> Result<(CourseNote, Vec<CourseNoteFile>), AppError> { | ||
| 99 | + let mut result = db | ||
| 100 | + .query( | ||
| 101 | + "BEGIN TRANSACTION; | ||
| 102 | + LET $files = (DELETE course_note_file WHERE course_note = $note RETURN BEFORE); | ||
| 103 | + LET $gone = (DELETE $note RETURN BEFORE); | ||
| 104 | + RETURN { note: $gone, files: $files }; | ||
| 105 | + COMMIT TRANSACTION;", | ||
| 106 | + ) | ||
| 107 | + .bind(("note", note.id.record())) | ||
| 108 | + .await? | ||
| 109 | + .check()?; | ||
| 110 | + // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3. | ||
| 111 | + let outcome = result | ||
| 112 | + .take::<Vec<DeleteOutcome>>(3)? | ||
| 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 | +} | ||
| 119 | + | ||
| 120 | +#[cfg(test)] | ||
| 121 | +mod tests { | ||
| 122 | + use super::*; | ||
| 123 | + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; | ||
| 124 | + use crate::domain::course_note_file::{FileContentType, FileName}; | ||
| 125 | + | ||
| 126 | + /// The blobs the handler unlinks are exactly the rows this transaction | ||
| 127 | + /// removed — including one uploaded after any pre-read snapshot would have | ||
| 128 | + /// been taken, which is the row whose blob used to leak. | ||
| 129 | + #[tokio::test] | ||
| 130 | + async fn delete_returns_the_attachment_rows_it_removed() { | ||
| 131 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 132 | + let creator = crate::domain::user::UserId::generate(); | ||
| 133 | + let course = crate::db::course::create( | ||
| 134 | + &db, | ||
| 135 | + &creator, | ||
| 136 | + CourseTitle::try_new("Math").unwrap(), | ||
| 137 | + CourseDescription::try_new("").unwrap(), | ||
| 138 | + CourseKind::try_new("course").unwrap(), | ||
| 139 | + None, | ||
| 140 | + None, | ||
| 141 | + ) | ||
| 142 | + .await | ||
| 143 | + .unwrap(); | ||
| 144 | + let note = create( | ||
| 145 | + &db, | ||
| 146 | + course.get_id(), | ||
| 147 | + &creator, | ||
| 148 | + CourseNoteTitle::try_new("a").unwrap(), | ||
| 149 | + CourseNoteContent::try_new("body").unwrap(), | ||
| 150 | + ) | ||
| 151 | + .await | ||
| 152 | + .unwrap(); | ||
| 153 | + // What a handler snapshot would have seen... | ||
| 154 | + let early = crate::db::course_note_file::insert( | ||
| 155 | + &db, | ||
| 156 | + CourseNoteFile::new( | ||
| 157 | + note.get_id(), | ||
| 158 | + FileName::try_new("early.pdf").unwrap(), | ||
| 159 | + FileContentType::try_new("application/pdf").unwrap(), | ||
| 160 | + 3, | ||
| 161 | + ), | ||
| 162 | + ) | ||
| 163 | + .await | ||
| 164 | + .unwrap(); | ||
| 165 | + let (snapshot, _) = crate::db::course_note_file::list_for(&db, note.get_id(), None, 0) | ||
| 166 | + .await | ||
| 167 | + .unwrap(); | ||
| 168 | + assert_eq!(snapshot.len(), 1); | ||
| 169 | + // ...and the upload that races in after it. | ||
| 170 | + let late = crate::db::course_note_file::insert( | ||
| 171 | + &db, | ||
| 172 | + CourseNoteFile::new( | ||
| 173 | + note.get_id(), | ||
| 174 | + FileName::try_new("late.pdf").unwrap(), | ||
| 175 | + FileContentType::try_new("application/pdf").unwrap(), | ||
| 176 | + 3, | ||
| 177 | + ), | ||
| 178 | + ) | ||
| 179 | + .await | ||
| 180 | + .unwrap(); | ||
| 181 | + | ||
| 182 | + let (gone, files) = delete(&db, note).await.unwrap(); | ||
| 183 | + assert_eq!(gone.get_title().as_str(), "a"); | ||
| 184 | + let mut keys: Vec<_> = files | ||
| 185 | + .iter() | ||
| 186 | + .map(|file| file.get_id().key().to_string()) | ||
| 187 | + .collect(); | ||
| 188 | + keys.sort(); | ||
| 189 | + let mut want = vec![ | ||
| 190 | + early.get_id().key().to_string(), | ||
| 191 | + late.get_id().key().to_string(), | ||
| 192 | + ]; | ||
| 193 | + want.sort(); | ||
| 194 | + assert_eq!(keys, want); | ||
| 195 | + assert!( | ||
| 196 | + crate::db::course_note_file::list_for(&db, gone.get_id(), None, 0) | ||
| 197 | + .await | ||
| 198 | + .unwrap() | ||
| 199 | + .0 | ||
| 200 | + .is_empty() | ||
| 201 | + ); | ||
| 202 | + } | ||
| 203 | +} | ||
src/db/course_note_file.rsadded+243 -0
| @@ -0,0 +1,243 @@ | |||
| 1 | +//! The `course_note_file` table: attachment rows for a course note, listed | ||
| 2 | +//! newest first, with the note's file cap claimed and released in the same | ||
| 3 | +//! write as the row. | ||
| 4 | + | ||
| 5 | +use surrealdb::types::{RecordId, RecordIdKey}; | ||
| 6 | + | ||
| 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; | ||
| 11 | +use crate::domain::course_note::CourseNoteId; | ||
| 12 | +use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; | ||
| 13 | +use crate::error::AppError; | ||
| 14 | + | ||
| 15 | +/// Persist the row assembled by [`CourseNoteFile::new`], refusing once its | ||
| 16 | +/// 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 | ||
| 18 | +/// [`crate::db::note_file::insert`] for why that is the only guard a | ||
| 19 | +/// concurrent insert cannot outrun. | ||
| 20 | +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 | ||
| 22 | + match cap::claim_and_create( | ||
| 23 | + &file.course_note.record(), | ||
| 24 | + COURSE_NOTE_FILE_COUNT_FIELD, | ||
| 25 | + MAX_COURSE_NOTE_FILES as i64, | ||
| 26 | + &file.id.record(), | ||
| 27 | + &file, | ||
| 28 | + db, | ||
| 29 | + ) | ||
| 30 | + .await? | ||
| 31 | + { | ||
| 32 | + cap::Claimed::Made(created) => Ok(created), | ||
| 33 | + // Also how a missing note reads: no note row means no slot to take. | ||
| 34 | + cap::Claimed::Full => Err(AppError::Conflict( | ||
| 35 | + "the course note already holds the maximum of 10 files — delete one first", | ||
| 36 | + )), | ||
| 37 | + // Unreachable: the id is a ULID this call just generated. | ||
| 38 | + cap::Claimed::Duplicate => Err(AppError::Internal( | ||
| 39 | + "failed to create course note file".into(), | ||
| 40 | + )), | ||
| 41 | + } | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +/// 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 | ||
| 46 | +/// stream). A key from any other table simply reads as `None`, which is | ||
| 47 | +/// what keeps a personal note's file id unreachable here. | ||
| 48 | +pub async fn read( | ||
| 49 | + db: &Database, | ||
| 50 | + id: &CourseNoteFileId, | ||
| 51 | +) -> Result<Option<CourseNoteFile>, AppError> { | ||
| 52 | + Ok(db.select(id.record()).await?) | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +/// Read a file's row only if it belongs to `note` — callers have already | ||
| 56 | +/// checked the note belongs to a course the caller may act on. | ||
| 57 | +pub async fn read_for( | ||
| 58 | + db: &Database, | ||
| 59 | + id: &CourseNoteFileId, | ||
| 60 | + note: &CourseNoteId, | ||
| 61 | +) -> Result<Option<CourseNoteFile>, AppError> { | ||
| 62 | + let file: Option<CourseNoteFile> = db.select(id.record()).await?; | ||
| 63 | + Ok(file.filter(|file| &file.course_note == note)) | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +/// All of `note`'s attachment rows, newest first. | ||
| 67 | +pub async fn list_for( | ||
| 68 | + db: &Database, | ||
| 69 | + note: &CourseNoteId, | ||
| 70 | + limit: Option<i64>, | ||
| 71 | + offset: i64, | ||
| 72 | +) -> Result<(Vec<CourseNoteFile>, i64), AppError> { | ||
| 73 | + PagedList::new( | ||
| 74 | + "course_note_file WHERE course_note = $note", | ||
| 75 | + "ORDER BY id DESC", | ||
| 76 | + ) | ||
| 77 | + .bind("note", note.record()) | ||
| 78 | + .run(limit, offset, db) | ||
| 79 | + .await | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +/// The blob names (record keys, since a file's blob is named by its own | ||
| 83 | +/// id) behind every note attachment of `course` — collected *before* the | ||
| 84 | +/// course-delete cascade wipes the rows. | ||
| 85 | +pub async fn file_keys_for_course( | ||
| 86 | + db: &Database, | ||
| 87 | + course: &crate::domain::course::CourseId, | ||
| 88 | +) -> Result<Vec<String>, AppError> { | ||
| 89 | + let mut result = db | ||
| 90 | + .query( | ||
| 91 | + "SELECT VALUE id FROM course_note_file \ | ||
| 92 | + WHERE course_note IN (SELECT VALUE id FROM course_note WHERE course = $course)", | ||
| 93 | + ) | ||
| 94 | + .bind(("course", course.record())) | ||
| 95 | + .await? | ||
| 96 | + .check()?; | ||
| 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 | +} | ||
| 106 | + | ||
| 107 | +/// 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 | ||
| 109 | +/// has a counter to correct. | ||
| 110 | +pub async fn delete(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFile, AppError> { | ||
| 111 | + let mut result = db | ||
| 112 | + .query( | ||
| 113 | + "BEGIN TRANSACTION; | ||
| 114 | + LET $gone = (DELETE $id RETURN BEFORE); | ||
| 115 | + UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); | ||
| 116 | + RETURN $gone; | ||
| 117 | + COMMIT TRANSACTION;", | ||
| 118 | + ) | ||
| 119 | + .bind(("id", file.id.record())) | ||
| 120 | + .bind(("note", file.course_note.record())) | ||
| 121 | + .await? | ||
| 122 | + .check()?; | ||
| 123 | + result | ||
| 124 | + .take::<Vec<CourseNoteFile>>(3)? | ||
| 125 | + .into_iter() | ||
| 126 | + .next() | ||
| 127 | + .ok_or(AppError::NotFound) | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +#[cfg(test)] | ||
| 131 | +mod tests { | ||
| 132 | + use super::*; | ||
| 133 | + use crate::database::Database; | ||
| 134 | + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; | ||
| 135 | + use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; | ||
| 136 | + use crate::domain::course_note_file::{FileContentType, FileName}; | ||
| 137 | + | ||
| 138 | + async fn note_of(db: &Database, title: &str) -> CourseNote { | ||
| 139 | + let creator = crate::domain::user::UserId::generate(); | ||
| 140 | + let course = crate::db::course::create( | ||
| 141 | + db, | ||
| 142 | + &creator, | ||
| 143 | + CourseTitle::try_new("c").unwrap(), | ||
| 144 | + CourseDescription::try_new("").unwrap(), | ||
| 145 | + CourseKind::try_new("course").unwrap(), | ||
| 146 | + None, | ||
| 147 | + None, | ||
| 148 | + ) | ||
| 149 | + .await | ||
| 150 | + .unwrap(); | ||
| 151 | + crate::db::course_note::create( | ||
| 152 | + db, | ||
| 153 | + course.get_id(), | ||
| 154 | + &creator, | ||
| 155 | + CourseNoteTitle::try_new(title).unwrap(), | ||
| 156 | + CourseNoteContent::try_new("body").unwrap(), | ||
| 157 | + ) | ||
| 158 | + .await | ||
| 159 | + .unwrap() | ||
| 160 | + } | ||
| 161 | + | ||
| 162 | + #[tokio::test] | ||
| 163 | + async fn rows_scope_to_their_note() { | ||
| 164 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 165 | + let note_a = note_of(&db, "a").await.get_id().clone(); | ||
| 166 | + let note_b = note_of(&db, "b").await.get_id().clone(); | ||
| 167 | + let file = insert( | ||
| 168 | + &db, | ||
| 169 | + CourseNoteFile::new( | ||
| 170 | + ¬e_a, | ||
| 171 | + FileName::try_new("plan.pdf").unwrap(), | ||
| 172 | + FileContentType::try_new("application/pdf").unwrap(), | ||
| 173 | + 3, | ||
| 174 | + ), | ||
| 175 | + ) | ||
| 176 | + .await | ||
| 177 | + .unwrap(); | ||
| 178 | + | ||
| 179 | + let found = read_for(&db, file.get_id(), ¬e_a).await.unwrap(); | ||
| 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 | + ); | ||
| 187 | + | ||
| 188 | + let listed = async |note: &CourseNoteId| list_for(&db, note, None, 0).await.unwrap().0; | ||
| 189 | + assert_eq!(listed(¬e_a).await.len(), 1); | ||
| 190 | + assert!(listed(¬e_b).await.is_empty()); | ||
| 191 | + | ||
| 192 | + delete(&db, file).await.unwrap(); | ||
| 193 | + assert!(listed(¬e_a).await.is_empty()); | ||
| 194 | + } | ||
| 195 | + | ||
| 196 | + /// The counter and the rows are written in one transaction, so the stored | ||
| 197 | + /// count must equal the stored rows — after a success *and* after the | ||
| 198 | + /// refusal that fills the cap, which must move neither. | ||
| 199 | + #[tokio::test] | ||
| 200 | + async fn counter_tracks_stored_rows() { | ||
| 201 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 202 | + let note = note_of(&db, "a").await.get_id().clone(); | ||
| 203 | + let stored_count = async |note: &CourseNoteId| -> i64 { | ||
| 204 | + db.query("SELECT VALUE file_count FROM $note") | ||
| 205 | + .bind(("note", note.record())) | ||
| 206 | + .await | ||
| 207 | + .unwrap() | ||
| 208 | + .take::<Vec<i64>>(0) | ||
| 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 | + ); | ||
| 242 | + } | ||
| 243 | +} | ||
src/db/mod.rsmodified+5 -0
| @@ -6,6 +6,8 @@ pub mod attendance; | |||
| 6 | pub mod badge; | 6 | pub mod badge; |
| 7 | pub mod bank_question; | 7 | pub mod bank_question; |
| 8 | pub mod bank_question_image; | 8 | pub mod bank_question_image; |
| 9 | +pub mod board; | ||
| 10 | +pub mod board_stroke; | ||
| 9 | pub mod builder; | 11 | pub mod builder; |
| 10 | pub mod cap; | 12 | pub mod cap; |
| 11 | pub mod chatbot_message; | 13 | pub mod chatbot_message; |
| @@ -16,6 +18,8 @@ pub mod class_group; | |||
| 16 | pub mod class_member; | 18 | pub mod class_member; |
| 17 | pub mod class_pump; | 19 | pub mod class_pump; |
| 18 | pub mod course; | 20 | pub mod course; |
| 21 | +pub mod course_note; | ||
| 22 | +pub mod course_note_file; | ||
| 19 | pub mod course_session; | 23 | pub mod course_session; |
| 20 | pub mod dietary_profile; | 24 | pub mod dietary_profile; |
| 21 | pub mod enrollment; | 25 | pub mod enrollment; |
| @@ -39,6 +43,7 @@ pub mod menu; | |||
| 39 | pub mod menu_dish; | 43 | pub mod menu_dish; |
| 40 | pub mod message; | 44 | pub mod message; |
| 41 | pub mod note; | 45 | pub mod note; |
| 46 | +pub mod note_file; | ||
| 42 | pub mod page; | 47 | pub mod page; |
| 43 | pub mod parent_link; | 48 | pub mod parent_link; |
| 44 | pub mod payment_ledger; | 49 | pub mod payment_ledger; |
src/db/note.rsmodified+18 -14
| @@ -133,27 +133,31 @@ mod tests { | |||
| 133 | .await | 133 | .await |
| 134 | .unwrap(); | 134 | .unwrap(); |
| 135 | // What a handler snapshot would have seen... | 135 | // What a handler snapshot would have seen... |
| 136 | - let early = NoteFile::new( | 136 | + let early = crate::db::note_file::insert( |
| 137 | - note.get_id(), | 137 | + &db, |
| 138 | - FileName::try_new("early.pdf").unwrap(), | 138 | + NoteFile::new( |
| 139 | - FileContentType::try_new("application/pdf").unwrap(), | 139 | + note.get_id(), |
| 140 | - 3, | 140 | + FileName::try_new("early.pdf").unwrap(), |
| 141 | + FileContentType::try_new("application/pdf").unwrap(), | ||
| 142 | + 3, | ||
| 143 | + ), | ||
| 141 | ) | 144 | ) |
| 142 | - .insert(&db) | ||
| 143 | .await | 145 | .await |
| 144 | .unwrap(); | 146 | .unwrap(); |
| 145 | - let (snapshot, _) = NoteFile::list_for(note.get_id(), None, 0, &db) | 147 | + let (snapshot, _) = crate::db::note_file::list_for(&db, note.get_id(), None, 0) |
| 146 | .await | 148 | .await |
| 147 | .unwrap(); | 149 | .unwrap(); |
| 148 | assert_eq!(snapshot.len(), 1); | 150 | assert_eq!(snapshot.len(), 1); |
| 149 | // ...and the upload that races in after it. | 151 | // ...and the upload that races in after it. |
| 150 | - let late = NoteFile::new( | 152 | + let late = crate::db::note_file::insert( |
| 151 | - note.get_id(), | 153 | + &db, |
| 152 | - FileName::try_new("late.pdf").unwrap(), | 154 | + NoteFile::new( |
| 153 | - FileContentType::try_new("application/pdf").unwrap(), | 155 | + note.get_id(), |
| 154 | - 3, | 156 | + FileName::try_new("late.pdf").unwrap(), |
| 157 | + FileContentType::try_new("application/pdf").unwrap(), | ||
| 158 | + 3, | ||
| 159 | + ), | ||
| 155 | ) | 160 | ) |
| 156 | - .insert(&db) | ||
| 157 | .await | 161 | .await |
| 158 | .unwrap(); | 162 | .unwrap(); |
| 159 | 163 | ||
| @@ -171,7 +175,7 @@ mod tests { | |||
| 171 | want.sort(); | 175 | want.sort(); |
| 172 | assert_eq!(keys, want); | 176 | assert_eq!(keys, want); |
| 173 | assert!( | 177 | assert!( |
| 174 | - NoteFile::list_for(gone.get_id(), None, 0, &db) | 178 | + crate::db::note_file::list_for(&db, gone.get_id(), None, 0) |
| 175 | .await | 179 | .await |
| 176 | .unwrap() | 180 | .unwrap() |
| 177 | .0 | 181 | .0 |
src/db/note_file.rsadded+200 -0
| @@ -0,0 +1,200 @@ | |||
| 1 | +//! The `note_file` table: attachment rows for a personal note, listed newest | ||
| 2 | +//! first, with the note's file cap claimed and released in the same write as | ||
| 3 | +//! the row. | ||
| 4 | + | ||
| 5 | +use crate::constant::{MAX_NOTE_FILES, NOTE_FILE_COUNT_FIELD}; | ||
| 6 | +use crate::database::Database; | ||
| 7 | +use crate::db::cap; | ||
| 8 | +use crate::db::page::PagedList; | ||
| 9 | +use crate::domain::note::NoteId; | ||
| 10 | +use crate::domain::note_file::{NoteFile, NoteFileId}; | ||
| 11 | +use crate::error::AppError; | ||
| 12 | + | ||
| 13 | +/// 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 | ||
| 15 | +/// by [`cap::claim_and_create`] on the note row: a `BEGIN…COMMIT` around a | ||
| 16 | +/// count can't enforce the cap (SurrealDB doesn't conflict-check a | ||
| 17 | +/// cross-record count against a concurrent insert) and a process-wide mutex | ||
| 18 | +/// can't either, since it is released around the very round trip the insert | ||
| 19 | +/// races — a conditional single-record write can. Claiming in a *separate* | ||
| 20 | +/// query would enforce the cap but leak a slot on a crash between the two. | ||
| 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 | ||
| 23 | + match cap::claim_and_create( | ||
| 24 | + &file.note.record(), | ||
| 25 | + NOTE_FILE_COUNT_FIELD, | ||
| 26 | + MAX_NOTE_FILES as i64, | ||
| 27 | + &file.id.record(), | ||
| 28 | + &file, | ||
| 29 | + db, | ||
| 30 | + ) | ||
| 31 | + .await? | ||
| 32 | + { | ||
| 33 | + cap::Claimed::Made(created) => Ok(created), | ||
| 34 | + // Also how a missing note reads: no note row means no slot to take. | ||
| 35 | + cap::Claimed::Full => Err(AppError::Conflict( | ||
| 36 | + "the note already holds the maximum of 10 files — delete one first", | ||
| 37 | + )), | ||
| 38 | + // Unreachable: the id is a ULID this call just generated. | ||
| 39 | + cap::Claimed::Duplicate => Err(AppError::Internal("failed to create note file".into())), | ||
| 40 | + } | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +/// Read a file's row only if it belongs to `note` — callers have already | ||
| 44 | +/// checked the note belongs to the requesting user. | ||
| 45 | +pub async fn read_for( | ||
| 46 | + db: &Database, | ||
| 47 | + id: &NoteFileId, | ||
| 48 | + note: &NoteId, | ||
| 49 | +) -> Result<Option<NoteFile>, AppError> { | ||
| 50 | + let file: Option<NoteFile> = db.select(id.record()).await?; | ||
| 51 | + Ok(file.filter(|file| &file.note == note)) | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// All of `note`'s attachment rows, newest first. | ||
| 55 | +pub async fn list_for( | ||
| 56 | + db: &Database, | ||
| 57 | + note: &NoteId, | ||
| 58 | + limit: Option<i64>, | ||
| 59 | + offset: i64, | ||
| 60 | +) -> Result<(Vec<NoteFile>, i64), AppError> { | ||
| 61 | + PagedList::new("note_file WHERE note = $note", "ORDER BY id DESC") | ||
| 62 | + .bind("note", note.record()) | ||
| 63 | + .run(limit, offset, db) | ||
| 64 | + .await | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// Delete the row and give its slot back in the same transaction — the note | ||
| 68 | +/// 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.) | ||
| 70 | +pub async fn delete(db: &Database, file: NoteFile) -> Result<NoteFile, AppError> { | ||
| 71 | + let mut result = db | ||
| 72 | + .query( | ||
| 73 | + "BEGIN TRANSACTION; | ||
| 74 | + LET $gone = (DELETE $id RETURN BEFORE); | ||
| 75 | + UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); | ||
| 76 | + RETURN $gone; | ||
| 77 | + COMMIT TRANSACTION;", | ||
| 78 | + ) | ||
| 79 | + .bind(("id", file.id.record())) | ||
| 80 | + .bind(("note", file.note.record())) | ||
| 81 | + .await? | ||
| 82 | + .check()?; | ||
| 83 | + result | ||
| 84 | + .take::<Vec<NoteFile>>(3)? | ||
| 85 | + .into_iter() | ||
| 86 | + .next() | ||
| 87 | + .ok_or(AppError::NotFound) | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +#[cfg(test)] | ||
| 91 | +mod tests { | ||
| 92 | + use super::*; | ||
| 93 | + use crate::domain::note_file::{FileContentType, FileName}; | ||
| 94 | + | ||
| 95 | + #[tokio::test] | ||
| 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(); | ||
| 101 | + let note_of = async |title: &str| { | ||
| 102 | + crate::db::note::create( | ||
| 103 | + &db, | ||
| 104 | + &owner, | ||
| 105 | + crate::domain::note::NoteTitle::try_new(title).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 | + ) | ||
| 122 | + .await | ||
| 123 | + .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 | + } | ||
| 142 | + | ||
| 143 | + /// The counter and the rows are written in one transaction, so the stored | ||
| 144 | + /// count must equal the stored rows — after a success *and* after the | ||
| 145 | + /// refusal that fills the cap, which must move neither. | ||
| 146 | + #[tokio::test] | ||
| 147 | + async fn counter_tracks_stored_rows() { | ||
| 148 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 149 | + let note = crate::db::note::create( | ||
| 150 | + &db, | ||
| 151 | + &crate::domain::user::UserId::generate(), | ||
| 152 | + crate::domain::note::NoteTitle::try_new("a").unwrap(), | ||
| 153 | + crate::domain::note::NoteContent::try_new("body").unwrap(), | ||
| 154 | + ) | ||
| 155 | + .await | ||
| 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 | + ); | ||
| 190 | + } | ||
| 191 | + | ||
| 192 | + // At the cap: the refusal writes nothing, counter included. | ||
| 193 | + assert!(matches!(add(¬e).await, Err(AppError::Conflict(_)))); | ||
| 194 | + assert_eq!(stored_count(¬e).await, MAX_NOTE_FILES as i64); | ||
| 195 | + assert_eq!( | ||
| 196 | + list_for(&db, ¬e, None, 0).await.unwrap().1, | ||
| 197 | + MAX_NOTE_FILES as i64 | ||
| 198 | + ); | ||
| 199 | + } | ||
| 200 | +} | ||
src/db/user.rsmodified+4 -4
| @@ -202,8 +202,8 @@ pub async fn search( | |||
| 202 | } else { | 202 | } else { |
| 203 | clauses.join(" AND ") | 203 | clauses.join(" AND ") |
| 204 | }; | 204 | }; |
| 205 | - let mut list = PagedList::new(format!("user WHERE {where_clause}"), "ORDER BY username") | 205 | + let mut list = |
| 206 | - .bind("q", needle); | 206 | + PagedList::new(format!("user WHERE {where_clause}"), "ORDER BY username").bind("q", needle); |
| 207 | if let Some(role) = role { | 207 | if let Some(role) = role { |
| 208 | list = list.bind("role", role); | 208 | list = list.bind("role", role); |
| 209 | } | 209 | } |
| @@ -330,12 +330,12 @@ pub async fn set_role_cascade( | |||
| 330 | // A room whose *creator* is demoted can never be ended by anyone: | 330 | // A room whose *creator* is demoted can never be ended by anyone: |
| 331 | // the whiteboard is closed to parents outright, so the creator is | 331 | // the whiteboard is closed to parents outright, so the creator is |
| 332 | // 404'd off their own board, `clear`/`lock`/`close`/`delete` are | 332 | // 404'd off their own board, `clear`/`lock`/`close`/`delete` are |
| 333 | - // creator-only for everyone else, and `Board::list_for_user` is the | 333 | + // creator-only for everyone else, and `crate::db::board::list_for_user` is the |
| 334 | // crate's only enumeration — no manager or admin can so much as find | 334 | // crate's only enumeration — no manager or admin can so much as find |
| 335 | // the id. Its participants meanwhile keep drawing (the room re-derives | 335 | // the id. Its participants meanwhile keep drawing (the room re-derives |
| 336 | // membership per frame and they still pass), into a board only the | 336 | // membership per frame and they still pass), into a board only the |
| 337 | // 50 000-stroke lifetime cap could ever retire. So the demotion | 337 | // 50 000-stroke lifetime cap could ever retire. So the demotion |
| 338 | - // retires it, with the same compare-and-set [`Board::close`] uses: an | 338 | + // retires it, with the same compare-and-set [`crate::db::board::close`] uses: an |
| 339 | // already-closed board keeps its first stamp. Closed and not deleted | 339 | // already-closed board keeps its first stamp. Closed and not deleted |
| 340 | // because the marks are the participants' work too — they keep reading | 340 | // because the marks are the participants' work too — they keep reading |
| 341 | // the board and its whole history, and the creator's `board_count` | 341 | // the board and its whole history, and the creator's `board_count` |
src/domain/board.rsmodified+37 -473
| @@ -13,47 +13,14 @@ | |||
| 13 | //! `CONTENT` save would silently wipe both (src/constant.rs:717-722). | 13 | //! `CONTENT` save would silently wipe both (src/constant.rs:717-722). |
| 14 | 14 | ||
| 15 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 15 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 16 | -use tokio::sync::Mutex; | ||
| 17 | 16 | ||
| 18 | -use crate::constant::{ | 17 | +use crate::constant::{BOARD_TABLE, MAX_BOARD_PARTICIPANTS, MAX_BOARD_TITLE_LEN}; |
| 19 | - BOARD_TABLE, MAX_BOARD_PARTICIPANTS, MAX_BOARD_TITLE_LEN, MAX_BOARDS_PER_CREATOR, | ||
| 20 | - USER_BOARD_COUNT_FIELD, | ||
| 21 | -}; | ||
| 22 | -use crate::database::{Database, transaction_with_retry}; | ||
| 23 | -use crate::db::cap; | ||
| 24 | use crate::domain::monotonic_id::next_ulid; | 18 | use crate::domain::monotonic_id::next_ulid; |
| 25 | -use crate::db::page::PagedList; | ||
| 26 | use crate::domain::timestamp::Timestamp; | 19 | use crate::domain::timestamp::Timestamp; |
| 27 | use crate::domain::user::UserId; | 20 | use crate::domain::user::UserId; |
| 28 | -use crate::error::{AppError, ValidationError}; | 21 | +use crate::error::ValidationError; |
| 29 | use crate::validate::validate_required; | 22 | use crate::validate::validate_required; |
| 30 | 23 | ||
| 31 | -/// Serializes every **read-modify-write** of a board's `participants` array: | ||
| 32 | -/// `POST /boards/{id}/invite` (union the resolved group into the roster it just | ||
| 33 | -/// read) and the roster branch of `PATCH /boards/{id}` (which reads the current | ||
| 34 | -/// list to decide which no-longer-eligible ids survive). | ||
| 35 | -/// | ||
| 36 | -/// [`Board::set_participants`] stores the whole array, so two invites that both | ||
| 37 | -/// read roster `R` write `R ∪ X` and `R ∪ Y` and the second one silently drops | ||
| 38 | -/// the first one's group — a caller told `200` with a list of people who are not | ||
| 39 | -/// on the board, against the route's own "strictly additive" contract. The | ||
| 40 | -/// database cannot refuse that: both are single well-formed writes to one field, | ||
| 41 | -/// and neither is wrong on its own. | ||
| 42 | -/// | ||
| 43 | -/// A lock rather than a compare-and-set because the deployment is one process | ||
| 44 | -/// with stop-the-world deploys, so it genuinely serializes — and because the | ||
| 45 | -/// alternative answer is a `409` on a race between two calls that do not | ||
| 46 | -/// conflict in intent, which a client could only resolve by re-sending the same | ||
| 47 | -/// invite. Contended invites simply queue; the section they hold is one board | ||
| 48 | -/// read, one user-list read and one field write. | ||
| 49 | -/// | ||
| 50 | -/// **A leaf**: nothing under it takes another lock. Note it does not reach the | ||
| 51 | -/// demotion sweep in [`crate::service::user::set_role`], which strips ids | ||
| 52 | -/// from every roster inside the role write's own transaction — an invite that | ||
| 53 | -/// read a roster before that sweep can put a swept id back, which the boot | ||
| 54 | -/// repair and the room's own live gate both still catch. | ||
| 55 | -pub(crate) static BOARD_ROSTER_LOCK: Mutex<()> = Mutex::const_new(()); | ||
| 56 | - | ||
| 57 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 24 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 58 | pub struct BoardId(RecordId); | 25 | pub struct BoardId(RecordId); |
| 59 | 26 | ||
| @@ -81,7 +48,7 @@ impl BoardId { | |||
| 81 | } | 48 | } |
| 82 | 49 | ||
| 83 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 50 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 84 | -pub struct BoardTitle(String); | 51 | +pub struct BoardTitle(pub(crate) String); |
| 85 | 52 | ||
| 86 | impl BoardTitle { | 53 | impl BoardTitle { |
| 87 | pub fn try_new(value: &str) -> Result<Self, ValidationError> { | 54 | pub fn try_new(value: &str) -> Result<Self, ValidationError> { |
| @@ -97,7 +64,9 @@ impl BoardTitle { | |||
| 97 | /// The invite list, deduplicated and bounded. The creator is a participant by | 64 | /// The invite list, deduplicated and bounded. The creator is a participant by |
| 98 | /// construction ([`Board::is_participant`]), so their presence in the list is | 65 | /// construction ([`Board::is_participant`]), so their presence in the list is |
| 99 | /// neither required nor rejected. | 66 | /// neither required nor rejected. |
| 100 | -fn checked_participants(participants: Vec<UserId>) -> Result<Vec<UserId>, ValidationError> { | 67 | +pub(crate) fn checked_participants( |
| 68 | + participants: Vec<UserId>, | ||
| 69 | +) -> Result<Vec<UserId>, ValidationError> { | ||
| 101 | let mut unique: Vec<UserId> = Vec::with_capacity(participants.len()); | 70 | let mut unique: Vec<UserId> = Vec::with_capacity(participants.len()); |
| 102 | for user in participants { | 71 | for user in participants { |
| 103 | if !unique.contains(&user) { | 72 | if !unique.contains(&user) { |
| @@ -116,16 +85,16 @@ fn checked_participants(participants: Vec<UserId>) -> Result<Vec<UserId>, Valida | |||
| 116 | 85 | ||
| 117 | #[derive(Debug, Clone, SurrealValue)] | 86 | #[derive(Debug, Clone, SurrealValue)] |
| 118 | pub struct Board { | 87 | pub struct Board { |
| 119 | - id: BoardId, | 88 | + pub(crate) id: BoardId, |
| 120 | - creator: UserId, | 89 | + pub(crate) creator: UserId, |
| 121 | - title: BoardTitle, | 90 | + pub(crate) title: BoardTitle, |
| 122 | - participants: Vec<UserId>, | 91 | + pub(crate) participants: Vec<UserId>, |
| 123 | - locked: bool, | 92 | + pub(crate) locked: bool, |
| 124 | - locked_by: Option<UserId>, | 93 | + pub(crate) locked_by: Option<UserId>, |
| 125 | - locked_at: Option<Timestamp>, | 94 | + pub(crate) locked_at: Option<Timestamp>, |
| 126 | - epoch: i64, | 95 | + pub(crate) epoch: i64, |
| 127 | - closed_at: Option<Timestamp>, | 96 | + pub(crate) closed_at: Option<Timestamp>, |
| 128 | - created_at: Timestamp, | 97 | + pub(crate) created_at: Timestamp, |
| 129 | } | 98 | } |
| 130 | 99 | ||
| 131 | impl Board { | 100 | impl Board { |
| @@ -178,251 +147,37 @@ impl Board { | |||
| 178 | pub fn is_creator(&self, user: &UserId) -> bool { | 147 | pub fn is_creator(&self, user: &UserId) -> bool { |
| 179 | &self.creator == user | 148 | &self.creator == user |
| 180 | } | 149 | } |
| 181 | - | ||
| 182 | - /// Open a board, taking a slot on the creator's `board_count` in the same | ||
| 183 | - /// transaction as the row — the counter is the authority on how many | ||
| 184 | - /// boards exist, so it can never count a row that did not commit. | ||
| 185 | - pub async fn create( | ||
| 186 | - creator: &UserId, | ||
| 187 | - title: BoardTitle, | ||
| 188 | - participants: Vec<UserId>, | ||
| 189 | - db: &Database, | ||
| 190 | - ) -> Result<Board, AppError> { | ||
| 191 | - let board = Board { | ||
| 192 | - id: BoardId::generate(), | ||
| 193 | - creator: creator.clone(), | ||
| 194 | - title, | ||
| 195 | - participants: checked_participants(participants)?, | ||
| 196 | - locked: false, | ||
| 197 | - locked_by: None, | ||
| 198 | - locked_at: None, | ||
| 199 | - epoch: 0, | ||
| 200 | - closed_at: None, | ||
| 201 | - created_at: Timestamp::now(), | ||
| 202 | - }; | ||
| 203 | - match cap::claim_and_create( | ||
| 204 | - &creator.record(), | ||
| 205 | - USER_BOARD_COUNT_FIELD, | ||
| 206 | - MAX_BOARDS_PER_CREATOR, | ||
| 207 | - &board.id.record(), | ||
| 208 | - &board, | ||
| 209 | - db, | ||
| 210 | - ) | ||
| 211 | - .await? | ||
| 212 | - { | ||
| 213 | - cap::Claimed::Made(saved) => Ok(saved), | ||
| 214 | - // Full, or the creator's row is gone — the conditional write | ||
| 215 | - // matches nothing either way. | ||
| 216 | - cap::Claimed::Full => Err(AppError::Conflict( | ||
| 217 | - "you have reached the limit on boards — delete one first", | ||
| 218 | - )), | ||
| 219 | - // The id is a freshly minted ULID on a table with no UNIQUE index, | ||
| 220 | - // so no rival can have aimed at it. | ||
| 221 | - cap::Claimed::Duplicate => Err(AppError::Internal("board id collided".into())), | ||
| 222 | - } | ||
| 223 | - } | ||
| 224 | - | ||
| 225 | - pub async fn read(id: &BoardId, db: &Database) -> Result<Option<Board>, AppError> { | ||
| 226 | - Ok(db.select(id.record()).await?) | ||
| 227 | - } | ||
| 228 | - | ||
| 229 | - /// Every board `user` may open: the ones they created and the ones they | ||
| 230 | - /// were invited to. Newest first — the ids are monotonic, so `id` is the | ||
| 231 | - /// creation order. | ||
| 232 | - /// | ||
| 233 | - /// `open` narrows by `closed_at`, and it means exactly that flag: a board | ||
| 234 | - /// that is locked, or full at its lifetime cap but never drawn on again, is | ||
| 235 | - /// never stamped and so reads as **open** — because it is. Only a creator's | ||
| 236 | - /// `/close` and the lifetime cap's own refusal ever stamp one. | ||
| 237 | - pub async fn list_for_user( | ||
| 238 | - user: &UserId, | ||
| 239 | - open: Option<bool>, | ||
| 240 | - limit: Option<i64>, | ||
| 241 | - offset: i64, | ||
| 242 | - db: &Database, | ||
| 243 | - ) -> Result<(Vec<Board>, i64), AppError> { | ||
| 244 | - let open_clause = match open { | ||
| 245 | - Some(true) => " AND closed_at = NONE", | ||
| 246 | - Some(false) => " AND closed_at != NONE", | ||
| 247 | - None => "", | ||
| 248 | - }; | ||
| 249 | - PagedList::new( | ||
| 250 | - format!("board WHERE (creator = $usr OR participants CONTAINS $usr){open_clause}"), | ||
| 251 | - "ORDER BY id DESC", | ||
| 252 | - ) | ||
| 253 | - .bind("usr", user.record()) | ||
| 254 | - .run(limit, offset, db) | ||
| 255 | - .await | ||
| 256 | - } | ||
| 257 | - | ||
| 258 | - /// Re-invite. Field-scoped, like every write here: a stroke landing | ||
| 259 | - /// concurrently is moving the counters this struct does not carry. | ||
| 260 | - pub async fn set_participants( | ||
| 261 | - &self, | ||
| 262 | - participants: Vec<UserId>, | ||
| 263 | - db: &Database, | ||
| 264 | - ) -> Result<Board, AppError> { | ||
| 265 | - let participants = checked_participants(participants)?; | ||
| 266 | - let mut result = db | ||
| 267 | - .query("UPDATE $id SET participants = $who RETURN AFTER") | ||
| 268 | - .bind(("id", self.id.record())) | ||
| 269 | - .bind(( | ||
| 270 | - "who", | ||
| 271 | - participants | ||
| 272 | - .iter() | ||
| 273 | - .map(|user| user.record()) | ||
| 274 | - .collect::<Vec<_>>(), | ||
| 275 | - )) | ||
| 276 | - .await? | ||
| 277 | - .check()?; | ||
| 278 | - one(result.take::<Vec<Board>>(0)?) | ||
| 279 | - } | ||
| 280 | - | ||
| 281 | - pub async fn set_title(&self, title: BoardTitle, db: &Database) -> Result<Board, AppError> { | ||
| 282 | - let mut result = db | ||
| 283 | - .query("UPDATE $id SET title = $title RETURN AFTER") | ||
| 284 | - .bind(("id", self.id.record())) | ||
| 285 | - .bind(("title", title.0)) | ||
| 286 | - .await? | ||
| 287 | - .check()?; | ||
| 288 | - one(result.take::<Vec<Board>>(0)?) | ||
| 289 | - } | ||
| 290 | - | ||
| 291 | - /// Freeze or thaw drawing. `locked_by`/`locked_at` are cleared on unlock so | ||
| 292 | - /// the row never claims a lock that is not held. | ||
| 293 | - pub async fn set_locked( | ||
| 294 | - &self, | ||
| 295 | - locked: bool, | ||
| 296 | - by: &UserId, | ||
| 297 | - db: &Database, | ||
| 298 | - ) -> Result<Board, AppError> { | ||
| 299 | - let now = Timestamp::now(); | ||
| 300 | - let mut result = db | ||
| 301 | - .query("UPDATE $id SET locked = $locked, locked_by = $by, locked_at = $at RETURN AFTER") | ||
| 302 | - .bind(("id", self.id.record())) | ||
| 303 | - .bind(("locked", locked)) | ||
| 304 | - .bind(("by", locked.then(|| by.record()))) | ||
| 305 | - .bind(("at", locked.then(|| now.as_millis()))) | ||
| 306 | - .await? | ||
| 307 | - .check()?; | ||
| 308 | - one(result.take::<Vec<Board>>(0)?) | ||
| 309 | - } | ||
| 310 | - | ||
| 311 | - // The demotion sweep — stripping a user off every roster they are listed | ||
| 312 | - // on, deleting nothing, and handing the affected rooms back so the caller | ||
| 313 | - // can prompt them — lives in [`crate::service::user::set_role`], where | ||
| 314 | - // it commits with the role write that invalidates the membership. | ||
| 315 | - | ||
| 316 | - /// Retire the board: permanently read-only, history still readable. | ||
| 317 | - /// Idempotent by the `WHERE` — a second call matches nothing and the first | ||
| 318 | - /// stamp stands, which is what the stroke path's open-guard reads. | ||
| 319 | - pub async fn close(&self, db: &Database) -> Result<Board, AppError> { | ||
| 320 | - let mut result = db | ||
| 321 | - .query("UPDATE $id SET closed_at = $now WHERE closed_at = NONE RETURN AFTER") | ||
| 322 | - .bind(("id", self.id.record())) | ||
| 323 | - .bind(("now", Timestamp::now().as_millis())) | ||
| 324 | - .await? | ||
| 325 | - .check()?; | ||
| 326 | - match result.take::<Vec<Board>>(0)?.into_iter().next() { | ||
| 327 | - Some(board) => Ok(board), | ||
| 328 | - // Already closed: the row is unchanged, so read it back rather | ||
| 329 | - // than report a 404 for a board that plainly exists. | ||
| 330 | - None => Self::read(&self.id, db).await?.ok_or(AppError::NotFound), | ||
| 331 | - } | ||
| 332 | - } | ||
| 333 | - | ||
| 334 | - /// Delete the board and give the creator's slot back in the *same* | ||
| 335 | - /// transaction — a release issued afterwards can be lost, and the counter | ||
| 336 | - /// would then ratchet the creator's limit shut forever. | ||
| 337 | - /// | ||
| 338 | - /// The stroke cascade rides in that same transaction: it is the one and | ||
| 339 | - /// only legitimate delete of `board_stroke` rows (a clear deletes nothing), | ||
| 340 | - /// and issued separately it could leave a board's whole history orphaned | ||
| 341 | - /// under a record that no longer exists. | ||
| 342 | - pub async fn delete(self, db: &Database) -> Result<Board, AppError> { | ||
| 343 | - // A stroke claim writes the very board row this deletes, so the store | ||
| 344 | - // aborts one of the two and a lost round is ordinary here — re-sent | ||
| 345 | - // rather than reported as a 500. Re-sending is sound: every statement | ||
| 346 | - // is a `DELETE` or a field-scoped `UPDATE`, none of which can ever | ||
| 347 | - // answer "already exists" (see [`transaction_with_retry`]). | ||
| 348 | - let (mut result, mut errors) = transaction_with_retry( | ||
| 349 | - db, | ||
| 350 | - "BEGIN TRANSACTION; | ||
| 351 | - DELETE board_stroke WHERE board = $id; | ||
| 352 | - LET $gone = (DELETE $id RETURN BEFORE); | ||
| 353 | - UPDATE $usr SET board_count = math::max([(board_count ?? 0) - array::len($gone), 0]); | ||
| 354 | - RETURN $gone; | ||
| 355 | - COMMIT TRANSACTION;", | ||
| 356 | - &[ | ||
| 357 | - ("id".into(), self.id.record().into_value()), | ||
| 358 | - ("usr".into(), self.creator.record().into_value()), | ||
| 359 | - ], | ||
| 360 | - &[], | ||
| 361 | - ) | ||
| 362 | - .await?; | ||
| 363 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 364 | - return Err(error.into()); | ||
| 365 | - } | ||
| 366 | - // Slots count BEGIN, the cascade, the LET and the UPDATE: the RETURN | ||
| 367 | - // is slot 4. | ||
| 368 | - one(result.take::<Vec<Board>>(4)?) | ||
| 369 | - } | ||
| 370 | -} | ||
| 371 | - | ||
| 372 | -fn one(rows: Vec<Board>) -> Result<Board, AppError> { | ||
| 373 | - rows.into_iter().next().ok_or(AppError::NotFound) | ||
| 374 | } | 150 | } |
| 375 | 151 | ||
| 376 | #[cfg(test)] | 152 | #[cfg(test)] |
| 377 | mod tests { | 153 | mod tests { |
| 378 | use super::*; | 154 | use super::*; |
| 379 | - | 155 | + use crate::constant::MAX_BOARD_TITLE_LEN; |
| 380 | - async fn a_db() -> Database { | ||
| 381 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 382 | - db.query( | ||
| 383 | - "CREATE user:c SET username = 'c', password_hash = 'x'; | ||
| 384 | - CREATE user:p SET username = 'p', password_hash = 'x'; | ||
| 385 | - CREATE user:s SET username = 's', password_hash = 'x';", | ||
| 386 | - ) | ||
| 387 | - .await | ||
| 388 | - .unwrap() | ||
| 389 | - .check() | ||
| 390 | - .unwrap(); | ||
| 391 | - db | ||
| 392 | - } | ||
| 393 | 156 | ||
| 394 | fn user(key: &str) -> UserId { | 157 | fn user(key: &str) -> UserId { |
| 395 | UserId::from_key(key) | 158 | UserId::from_key(key) |
| 396 | } | 159 | } |
| 397 | 160 | ||
| 398 | - /// The stored counter, re-read out of the database. Never asserted off a | 161 | + /// A board row assembled in memory — the predicates under test are pure, |
| 399 | - /// return value: the in-memory engine forges concurrent-write wins | 162 | + /// so no store is involved. |
| 400 | - /// (src/domain/cap.rs:44-49). | 163 | + fn a_board() -> Board { |
| 401 | - async fn stored_count(db: &Database) -> i64 { | 164 | + Board { |
| 402 | - let mut result = db | 165 | + id: BoardId::from_key("b"), |
| 403 | - .query("SELECT VALUE board_count ?? 0 FROM user:c") | 166 | + creator: user("c"), |
| 404 | - .await | 167 | + title: BoardTitle::try_new("Geometri").unwrap(), |
| 405 | - .unwrap() | 168 | + participants: vec![user("p")], |
| 406 | - .check() | 169 | + locked: false, |
| 407 | - .unwrap(); | 170 | + locked_by: None, |
| 408 | - result.take::<Vec<i64>>(0).unwrap()[0] | 171 | + locked_at: None, |
| 409 | - } | 172 | + epoch: 0, |
| 410 | - | 173 | + closed_at: None, |
| 411 | - async fn a_board(db: &Database) -> Board { | 174 | + created_at: Timestamp::now(), |
| 412 | - Board::create( | 175 | + } |
| 413 | - &user("c"), | ||
| 414 | - BoardTitle::try_new("Geometri").unwrap(), | ||
| 415 | - vec![user("p")], | ||
| 416 | - db, | ||
| 417 | - ) | ||
| 418 | - .await | ||
| 419 | - .unwrap() | ||
| 420 | } | 176 | } |
| 421 | 177 | ||
| 422 | - #[tokio::test] | 178 | + #[test] |
| 423 | - async fn the_two_predicates_are_the_permission_model() { | 179 | + fn the_two_predicates_are_the_permission_model() { |
| 424 | - let db = a_db().await; | 180 | + let board = a_board(); |
| 425 | - let board = a_board(&db).await; | ||
| 426 | // Creator: draws AND commands. | 181 | // Creator: draws AND commands. |
| 427 | assert!(board.is_participant(&user("c"))); | 182 | assert!(board.is_participant(&user("c"))); |
| 428 | assert!(board.is_creator(&user("c"))); | 183 | assert!(board.is_creator(&user("c"))); |
| @@ -441,8 +196,8 @@ mod tests { | |||
| 441 | assert!(BoardTitle::try_new(&"x".repeat(MAX_BOARD_TITLE_LEN + 1)).is_err()); | 196 | assert!(BoardTitle::try_new(&"x".repeat(MAX_BOARD_TITLE_LEN + 1)).is_err()); |
| 442 | } | 197 | } |
| 443 | 198 | ||
| 444 | - #[tokio::test] | 199 | + #[test] |
| 445 | - async fn participants_are_deduplicated_and_bounded() { | 200 | + fn participants_are_deduplicated_and_bounded() { |
| 446 | assert_eq!( | 201 | assert_eq!( |
| 447 | checked_participants(vec![user("p"), user("p")]) | 202 | checked_participants(vec![user("p"), user("p")]) |
| 448 | .unwrap() | 203 | .unwrap() |
| @@ -454,195 +209,4 @@ mod tests { | |||
| 454 | .collect(); | 209 | .collect(); |
| 455 | assert!(checked_participants(many).is_err()); | 210 | assert!(checked_participants(many).is_err()); |
| 456 | } | 211 | } |
| 457 | - | ||
| 458 | - /// The cap refuses at `MAX_BOARDS_PER_CREATOR`, and the refusal writes | ||
| 459 | - /// nothing — asserted by re-reading the counter, not off the return value. | ||
| 460 | - #[tokio::test] | ||
| 461 | - async fn the_per_creator_cap_refuses_a_full_creator() { | ||
| 462 | - let db = a_db().await; | ||
| 463 | - db.query("UPDATE user:c SET board_count = $full") | ||
| 464 | - .bind(("full", MAX_BOARDS_PER_CREATOR)) | ||
| 465 | - .await | ||
| 466 | - .unwrap() | ||
| 467 | - .check() | ||
| 468 | - .unwrap(); | ||
| 469 | - let refused = Board::create( | ||
| 470 | - &user("c"), | ||
| 471 | - BoardTitle::try_new("Geometri").unwrap(), | ||
| 472 | - vec![], | ||
| 473 | - &db, | ||
| 474 | - ) | ||
| 475 | - .await; | ||
| 476 | - assert!(matches!(refused, Err(AppError::Conflict(_)))); | ||
| 477 | - assert_eq!(stored_count(&db).await, MAX_BOARDS_PER_CREATOR); | ||
| 478 | - let mut result = db | ||
| 479 | - .query("SELECT VALUE id FROM board") | ||
| 480 | - .await | ||
| 481 | - .unwrap() | ||
| 482 | - .check() | ||
| 483 | - .unwrap(); | ||
| 484 | - assert!(result.take::<Vec<RecordId>>(0).unwrap().is_empty()); | ||
| 485 | - } | ||
| 486 | - | ||
| 487 | - /// A seat is taken on create and handed back on delete, both read back out | ||
| 488 | - /// of the store. | ||
| 489 | - #[tokio::test] | ||
| 490 | - async fn a_seat_is_claimed_and_released() { | ||
| 491 | - let db = a_db().await; | ||
| 492 | - let board = a_board(&db).await; | ||
| 493 | - assert_eq!(stored_count(&db).await, 1); | ||
| 494 | - board.delete(&db).await.unwrap(); | ||
| 495 | - assert_eq!(stored_count(&db).await, 0); | ||
| 496 | - } | ||
| 497 | - | ||
| 498 | - /// Closing twice must not re-stamp: the first `closed_at` is the record. | ||
| 499 | - #[tokio::test] | ||
| 500 | - async fn close_is_idempotent() { | ||
| 501 | - let db = a_db().await; | ||
| 502 | - let board = a_board(&db).await; | ||
| 503 | - let closed = board.close(&db).await.unwrap(); | ||
| 504 | - let first = closed.get_closed_at().unwrap(); | ||
| 505 | - // A whole millisecond apart, so a re-stamp could not go unnoticed. | ||
| 506 | - tokio::time::sleep(std::time::Duration::from_millis(2)).await; | ||
| 507 | - assert_eq!(board.close(&db).await.unwrap().get_closed_at(), Some(first)); | ||
| 508 | - assert_eq!( | ||
| 509 | - Board::read(board.get_id(), &db) | ||
| 510 | - .await | ||
| 511 | - .unwrap() | ||
| 512 | - .unwrap() | ||
| 513 | - .get_closed_at(), | ||
| 514 | - Some(first) | ||
| 515 | - ); | ||
| 516 | - } | ||
| 517 | - | ||
| 518 | - #[tokio::test] | ||
| 519 | - async fn field_scoped_writes_leave_the_stroke_counters_alone() { | ||
| 520 | - let db = a_db().await; | ||
| 521 | - let board = a_board(&db).await; | ||
| 522 | - db.query("UPDATE $id SET epoch_stroke_count = 7, total_stroke_count = 9") | ||
| 523 | - .bind(("id", board.get_id().record())) | ||
| 524 | - .await | ||
| 525 | - .unwrap() | ||
| 526 | - .check() | ||
| 527 | - .unwrap(); | ||
| 528 | - board | ||
| 529 | - .set_title(BoardTitle::try_new("Cebir").unwrap(), &db) | ||
| 530 | - .await | ||
| 531 | - .unwrap(); | ||
| 532 | - board.set_participants(vec![user("s")], &db).await.unwrap(); | ||
| 533 | - board.set_locked(true, &user("c"), &db).await.unwrap(); | ||
| 534 | - board.close(&db).await.unwrap(); | ||
| 535 | - let mut result = db | ||
| 536 | - .query("SELECT VALUE [epoch_stroke_count, total_stroke_count] FROM $id") | ||
| 537 | - .bind(("id", board.get_id().record())) | ||
| 538 | - .await | ||
| 539 | - .unwrap() | ||
| 540 | - .check() | ||
| 541 | - .unwrap(); | ||
| 542 | - assert_eq!(result.take::<Vec<Vec<i64>>>(0).unwrap()[0], vec![7, 9]); | ||
| 543 | - } | ||
| 544 | - | ||
| 545 | - /// [`Board::delete`] cascades the stroke log and decrements the creator's | ||
| 546 | - /// `board_count` off the very record a concurrent stroke claim increments, | ||
| 547 | - /// so the two contend by design. Losing that round writes nothing, which is | ||
| 548 | - /// what makes re-sending it the recovery; without | ||
| 549 | - /// [`crate::database::transaction_with_retry`] a lost round comes out as a | ||
| 550 | - /// 500. | ||
| 551 | - /// | ||
| 552 | - /// A refusal or an `Err(NotFound)` is *correct* here — the board really is | ||
| 553 | - /// gone — and must not fail this test. The only defect is `AppError::Db`. | ||
| 554 | - /// | ||
| 555 | - /// Multi-threaded and on a real server for the reason spelled out on | ||
| 556 | - /// [`super::super::course`]'s twin: the current-thread runtime never | ||
| 557 | - /// interleaves the two, and the embedded engine does not conflict-check | ||
| 558 | - /// concurrent writes to one record at all. | ||
| 559 | - /// | ||
| 560 | - /// Mutation status, stated honestly: cutting | ||
| 561 | - /// [`crate::database::transaction_with_retry`] to a single attempt leaves | ||
| 562 | - /// this GREEN — 5 runs of 5, every one at 20/20 contended. The mutation is | ||
| 563 | - /// real, not a dud: the same cut reddens the `course.rs` twin in 2 runs of | ||
| 564 | - /// 3. So the delete here never actually loses a round in this window, and | ||
| 565 | - /// nothing in the suite exercises its retry. Read this as a smoke test that | ||
| 566 | - /// a contended delete does not 500 — the retry stays because the batch is | ||
| 567 | - /// admissible for it and a lost round is possible in principle, not because | ||
| 568 | - /// a test has ever caught it losing one. | ||
| 569 | - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 570 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 571 | - async fn a_delete_racing_a_stroke_never_answers_500() { | ||
| 572 | - use crate::domain::board_stroke::BoardStroke; | ||
| 573 | - let (db, _serialized) = crate::database::init_test_server("board_delete_race").await; | ||
| 574 | - db.query("CREATE user:c SET username = 'c', password_hash = 'x';") | ||
| 575 | - .await | ||
| 576 | - .unwrap() | ||
| 577 | - .check() | ||
| 578 | - .unwrap(); | ||
| 579 | - let (mut delete_500, mut stroke_500, mut drawn) = (0, 0, 0); | ||
| 580 | - let (mut last_delete, mut last_stroke) = (String::new(), String::new()); | ||
| 581 | - for round in 0..20 { | ||
| 582 | - let board = a_board(&db).await; | ||
| 583 | - // The delete is held back by a sweeping beat: released together it | ||
| 584 | - // is one statement while an append spends a read before it claims, | ||
| 585 | - // so it would win every round and the guard would never be | ||
| 586 | - // contended at all. Six racers over a 0-3ms sweep put the delete | ||
| 587 | - // somewhere inside the counter writes instead. | ||
| 588 | - let drop_it = { | ||
| 589 | - let (board, db) = (board.clone(), db.clone()); | ||
| 590 | - let beat = std::time::Duration::from_millis(round % 4); | ||
| 591 | - tokio::spawn(async move { | ||
| 592 | - tokio::time::sleep(beat).await; | ||
| 593 | - board.delete(&db).await | ||
| 594 | - }) | ||
| 595 | - }; | ||
| 596 | - let marks: Vec<_> = (0..6) | ||
| 597 | - .map(|mark| { | ||
| 598 | - let (id, db) = (board.get_id().clone(), db.clone()); | ||
| 599 | - let author = user("c"); | ||
| 600 | - tokio::spawn(async move { | ||
| 601 | - BoardStroke::append(&id, &author, &format!("{{\"m\":{mark}}}"), 0, &db) | ||
| 602 | - .await | ||
| 603 | - }) | ||
| 604 | - }) | ||
| 605 | - .collect(); | ||
| 606 | - let drop_it = drop_it.await.unwrap(); | ||
| 607 | - if matches!(drop_it, Err(AppError::Db(_))) { | ||
| 608 | - delete_500 += 1; | ||
| 609 | - last_delete = format!("{drop_it:?}"); | ||
| 610 | - } | ||
| 611 | - // Contention is counted off the claim's own outcome, not off stored | ||
| 612 | - // rows: the delete cascades `board_stroke`, so a stroke that landed | ||
| 613 | - // and then lost its board leaves nothing behind to count. An `Ok` | ||
| 614 | - // means the claim committed against the board row the delete was | ||
| 615 | - // tearing down, which is exactly the overlap being measured. | ||
| 616 | - let mut claimed = 0; | ||
| 617 | - for mark in marks { | ||
| 618 | - let mark = mark.await.unwrap(); | ||
| 619 | - if matches!(mark, Err(AppError::Db(_))) { | ||
| 620 | - stroke_500 += 1; | ||
| 621 | - last_stroke = format!("{mark:?}"); | ||
| 622 | - } | ||
| 623 | - if mark.is_ok() { | ||
| 624 | - claimed += 1; | ||
| 625 | - } | ||
| 626 | - } | ||
| 627 | - if claimed > 0 { | ||
| 628 | - drawn += 1; | ||
| 629 | - } | ||
| 630 | - } | ||
| 631 | - eprintln!( | ||
| 632 | - "Board::delete raced: {delete_500}/20 delete 500s, {stroke_500} stroke 500s, \ | ||
| 633 | - {drawn}/20 rounds with a stroke claimed" | ||
| 634 | - ); | ||
| 635 | - assert!( | ||
| 636 | - drawn > 0, | ||
| 637 | - "no round ever landed a stroke, so the delete's cascade was never contended" | ||
| 638 | - ); | ||
| 639 | - assert_eq!( | ||
| 640 | - delete_500, 0, | ||
| 641 | - "a raced delete must retry, not 500: {delete_500}/20 rounds, last {last_delete}" | ||
| 642 | - ); | ||
| 643 | - assert_eq!( | ||
| 644 | - stroke_500, 0, | ||
| 645 | - "a raced stroke must retry, not 500: {stroke_500}/20 rounds, last {last_stroke}" | ||
| 646 | - ); | ||
| 647 | - } | ||
| 648 | } | 212 | } |
src/domain/board_stroke.rsmodified+36 -820
| @@ -3,45 +3,37 @@ | |||
| 3 | //! A clear does NOT remove strokes — it bumps the board's `epoch`, so the live | 3 | //! A clear does NOT remove strokes — it bumps the board's `epoch`, so the live |
| 4 | //! canvas empties while every mark the board ever carried stays on the table | 4 | //! canvas empties while every mark the board ever carried stays on the table |
| 5 | //! and stays replayable. That is the whole storage model: the only legitimate | 5 | //! and stays replayable. That is the whole storage model: the only legitimate |
| 6 | -//! delete of a stroke row in the feature is [`crate::domain::board::Board::delete`]'s | 6 | +//! delete of a stroke row in the feature is |
| 7 | -//! cascade, which runs inside the same transaction as the board's own delete. | 7 | +//! [`crate::db::board::delete`]'s cascade, which runs inside the same |
| 8 | +//! transaction as the board's own delete. | ||
| 8 | //! | 9 | //! |
| 9 | //! The `clear` marker row IS the epoch index: it carries the epoch it closed, | 10 | //! The `clear` marker row IS the epoch index: it carries the epoch it closed, |
| 10 | //! that epoch's final stroke count, who cleared and when — so replaying a whole | 11 | //! that epoch's final stroke count, who cleared and when — so replaying a whole |
| 11 | //! session needs no second table and no `GROUP BY` over the history. | 12 | //! session needs no second table and no `GROUP BY` over the history. |
| 12 | //! | 13 | //! |
| 13 | -//! This module is the sole write funnel for `board_stroke`, and for the board's | 14 | +//! Writes funnel through [`crate::db::board_stroke`], and so do the board's |
| 14 | //! two stroke counters. Nothing else may write either, because two invariants | 15 | //! two stroke counters. Nothing else may write either, because two invariants |
| 15 | //! the schema cannot state depend on it: `count` is populated *only* on a | 16 | //! the schema cannot state depend on it: `count` is populated *only* on a |
| 16 | //! `clear` row (SCHEMAFULL types both kinds the same), and the two counters | 17 | //! `clear` row (SCHEMAFULL types both kinds the same), and the two counters |
| 17 | //! must move together with the row they count (`cap::claim_two_when_and_create` | 18 | //! must move together with the row they count (`cap::claim_two_when_and_create` |
| 18 | //! is what makes that one transaction). | 19 | //! is what makes that one transaction). |
| 19 | 20 | ||
| 20 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; | 21 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 21 | 22 | ||
| 22 | -use crate::constant::{ | 23 | +use crate::constant::{BOARD_STROKE_KINDS, BOARD_STROKE_TABLE}; |
| 23 | - BOARD_EPOCH_STROKE_COUNT_FIELD, BOARD_OPEN_GUARD, BOARD_REPLAY_CHUNK, BOARD_STROKE_KINDS, | 24 | +use crate::domain::board::Board; |
| 24 | - BOARD_STROKE_TABLE, BOARD_TOTAL_STROKE_COUNT_FIELD, MAX_BOARD_STROKES, MAX_EPOCH_STROKES, | ||
| 25 | - MAX_STROKE_PAYLOAD_LEN, | ||
| 26 | -}; | ||
| 27 | -use crate::database::{Database, transaction_with_retry}; | ||
| 28 | -use crate::domain::board::{Board, BoardId}; | ||
| 29 | -use crate::db::cap; | ||
| 30 | use crate::domain::monotonic_id::next_ulid; | 25 | use crate::domain::monotonic_id::next_ulid; |
| 31 | -use crate::db::page::PagedList; | ||
| 32 | use crate::domain::timestamp::Timestamp; | 26 | use crate::domain::timestamp::Timestamp; |
| 33 | use crate::domain::user::UserId; | 27 | use crate::domain::user::UserId; |
| 34 | -use crate::error::AppError; | ||
| 35 | -use crate::validate::validate_required; | ||
| 36 | 28 | ||
| 37 | /// A drawn mark, and the marker that ends an epoch. | 29 | /// A drawn mark, and the marker that ends an epoch. |
| 38 | -const KIND_STROKE: &str = BOARD_STROKE_KINDS[0]; | 30 | +pub(crate) const KIND_STROKE: &str = BOARD_STROKE_KINDS[0]; |
| 39 | -const KIND_CLEAR: &str = BOARD_STROKE_KINDS[1]; | 31 | +pub(crate) const KIND_CLEAR: &str = BOARD_STROKE_KINDS[1]; |
| 40 | 32 | ||
| 41 | /// The `THROW` the clear transaction refuses with: a blank canvas, not the | 33 | /// The `THROW` the clear transaction refuses with: a blank canvas, not the |
| 42 | /// creator, or the board is locked or already closed. A decision, so it | 34 | /// creator, or the board is locked or already closed. A decision, so it |
| 43 | /// outranks a lost round. | 35 | /// outranks a lost round. |
| 44 | -const CLEAR_REFUSED: &str = "board_clear_refused"; | 36 | +pub(crate) const CLEAR_REFUSED: &str = "board_clear_refused"; |
| 45 | 37 | ||
| 46 | /// The public words of every refusal this module raises. `pub` because | 38 | /// The public words of every refusal this module raises. `pub` because |
| 47 | /// `src/web/board_ws.rs` turns each into the machine-readable `code` its room | 39 | /// `src/web/board_ws.rs` turns each into the machine-readable `code` its room |
| @@ -91,14 +83,14 @@ impl BoardStrokeId { | |||
| 91 | 83 | ||
| 92 | #[derive(Debug, Clone, SurrealValue)] | 84 | #[derive(Debug, Clone, SurrealValue)] |
| 93 | pub struct BoardStroke { | 85 | pub struct BoardStroke { |
| 94 | - id: BoardStrokeId, | 86 | + pub(crate) id: BoardStrokeId, |
| 95 | - board: BoardId, | 87 | + pub(crate) board: crate::domain::board::BoardId, |
| 96 | - author: UserId, | 88 | + pub(crate) author: UserId, |
| 97 | - kind: String, | 89 | + pub(crate) kind: String, |
| 98 | - payload: Option<String>, | 90 | + pub(crate) payload: Option<String>, |
| 99 | - count: Option<i64>, | 91 | + pub(crate) count: Option<i64>, |
| 100 | - epoch: i64, | 92 | + pub(crate) epoch: i64, |
| 101 | - created_at: Timestamp, | 93 | + pub(crate) created_at: Timestamp, |
| 102 | } | 94 | } |
| 103 | 95 | ||
| 104 | impl BoardStroke { | 96 | impl BoardStroke { |
| @@ -106,7 +98,7 @@ impl BoardStroke { | |||
| 106 | &self.id | 98 | &self.id |
| 107 | } | 99 | } |
| 108 | 100 | ||
| 109 | - pub fn get_board(&self) -> &BoardId { | 101 | + pub fn get_board(&self) -> &crate::domain::board::BoardId { |
| 110 | &self.board | 102 | &self.board |
| 111 | } | 103 | } |
| 112 | 104 | ||
| @@ -138,800 +130,24 @@ impl BoardStroke { | |||
| 138 | pub fn is_clear(&self) -> bool { | 130 | pub fn is_clear(&self) -> bool { |
| 139 | self.kind == KIND_CLEAR | 131 | self.kind == KIND_CLEAR |
| 140 | } | 132 | } |
| 141 | - | ||
| 142 | - /// Append one mark to `board`'s current `epoch`. | ||
| 143 | - /// | ||
| 144 | - /// Both stroke counters and the row commit together or not at all: the | ||
| 145 | - /// resettable epoch counter, the lifetime counter, and the open-board guard | ||
| 146 | - /// are one conditional write, so a locked or closed board can never be | ||
| 147 | - /// drawn on by a writer that read it a moment earlier. | ||
| 148 | - /// | ||
| 149 | - /// `epoch` rides in that guard too. Without it a clear landing between the | ||
| 150 | - /// caller's board read and this write filed the row under the epoch that | ||
| 151 | - /// just ended while its increment counted against the *new* epoch's | ||
| 152 | - /// counter — one race, two markers corrupted for good (the closed one short | ||
| 153 | - /// by a stroke, the next one claiming a stroke that is not there), and | ||
| 154 | - /// markers are never rewritten. Now such a stroke is refused instead. | ||
| 155 | - pub async fn append( | ||
| 156 | - board: &BoardId, | ||
| 157 | - author: &UserId, | ||
| 158 | - payload: &str, | ||
| 159 | - epoch: i64, | ||
| 160 | - db: &Database, | ||
| 161 | - ) -> Result<BoardStroke, AppError> { | ||
| 162 | - validate_required("payload", payload, MAX_STROKE_PAYLOAD_LEN)?; | ||
| 163 | - let stroke = BoardStroke { | ||
| 164 | - id: BoardStrokeId::generate(), | ||
| 165 | - board: board.clone(), | ||
| 166 | - author: author.clone(), | ||
| 167 | - kind: KIND_STROKE.to_string(), | ||
| 168 | - payload: Some(payload.to_string()), | ||
| 169 | - count: None, | ||
| 170 | - epoch, | ||
| 171 | - created_at: Timestamp::now(), | ||
| 172 | - }; | ||
| 173 | - // `epoch` is an in-crate `i64` read off the board row, never text from | ||
| 174 | - // a client, so it interpolates into the guard as a bare integer. | ||
| 175 | - let guard = format!("{BOARD_OPEN_GUARD} AND epoch = {epoch}"); | ||
| 176 | - match cap::claim_two_when_and_create( | ||
| 177 | - &board.record(), | ||
| 178 | - (BOARD_EPOCH_STROKE_COUNT_FIELD, MAX_EPOCH_STROKES), | ||
| 179 | - (BOARD_TOTAL_STROKE_COUNT_FIELD, MAX_BOARD_STROKES), | ||
| 180 | - &guard, | ||
| 181 | - &stroke.id.record(), | ||
| 182 | - &stroke, | ||
| 183 | - db, | ||
| 184 | - ) | ||
| 185 | - .await? | ||
| 186 | - { | ||
| 187 | - cap::ClaimedTwo::Made(saved) => Ok(saved), | ||
| 188 | - // The live canvas is full and nothing else: recoverable by a clear, | ||
| 189 | - // which resets this counter without losing a single mark. | ||
| 190 | - cap::ClaimedTwo::FullSoft => Err(AppError::Conflict(EPOCH_FULL)), | ||
| 191 | - // Three refusals share this answer (lifetime full / guard failed / | ||
| 192 | - // board gone), so the board is re-read to tell them apart. A board | ||
| 193 | - // that changed state in between still gets told "no" — but only a | ||
| 194 | - // re-read that *proves* the lifetime counter is spent may stamp | ||
| 195 | - // `closed_at`, never elimination. | ||
| 196 | - cap::ClaimedTwo::FullHard => Err(Self::why_refused(board, db).await?), | ||
| 197 | - } | ||
| 198 | - } | ||
| 199 | - | ||
| 200 | - /// The one place the module orders `closed` above `locked`, because a board | ||
| 201 | - /// can hold both flags at once (nothing gates `/close` on the lock or the | ||
| 202 | - /// lock on `closed_at`) and **closed outranks locked**: there is no reopen | ||
| 203 | - /// route, so the pause never lifts and only the terminal answer is true. | ||
| 204 | - /// Both classifiers read the precedence from here rather than keeping a | ||
| 205 | - /// copy of it — the copies are what drifted, and a room told "the creator | ||
| 206 | - /// has paused drawing" about a permanently read-only board waits forever. | ||
| 207 | - /// | ||
| 208 | - /// `None` means the board is neither: whatever refused the write, this is | ||
| 209 | - /// not why. | ||
| 210 | - fn state_refusal(board: &Board) -> Option<&'static str> { | ||
| 211 | - if board.get_closed_at().is_some() { | ||
| 212 | - Some(BOARD_CLOSED) | ||
| 213 | - } else if board.is_locked() { | ||
| 214 | - Some(BOARD_LOCKED) | ||
| 215 | - } else { | ||
| 216 | - None | ||
| 217 | - } | ||
| 218 | - } | ||
| 219 | - | ||
| 220 | - async fn why_refused(board: &BoardId, db: &Database) -> Result<AppError, AppError> { | ||
| 221 | - let board = Board::read(board, db).await?.ok_or(AppError::NotFound)?; | ||
| 222 | - if let Some(refusal) = Self::state_refusal(&board) { | ||
| 223 | - return Ok(AppError::Conflict(refusal)); | ||
| 224 | - } | ||
| 225 | - // Neither flag, so the lifetime counter has to say so *itself*: | ||
| 226 | - // `FullHard` also fires when the guard failed, so a board that was | ||
| 227 | - // locked (or a clear that moved the epoch) when the claim ran and is | ||
| 228 | - // open again now would otherwise be stamped read-only at one stroke of | ||
| 229 | - // a 50 000 budget — irreversibly, with no reopen. | ||
| 230 | - if Self::total_strokes(board.get_id(), db).await? < MAX_BOARD_STROKES { | ||
| 231 | - return Ok(AppError::Conflict(BOARD_MOVED)); | ||
| 232 | - } | ||
| 233 | - // `Board::close` is the one-way idempotent stamp: a second append takes | ||
| 234 | - // this branch too and leaves the first `closed_at` standing. | ||
| 235 | - board.close(db).await?; | ||
| 236 | - Ok(AppError::Conflict(BOARD_CLOSED)) | ||
| 237 | - } | ||
| 238 | - | ||
| 239 | - /// The lifetime counter as the store holds it — the board struct | ||
| 240 | - /// deliberately does not carry it (src/domain/board.rs:9-13). | ||
| 241 | - async fn total_strokes(board: &BoardId, db: &Database) -> Result<i64, AppError> { | ||
| 242 | - let mut result = db | ||
| 243 | - .query(format!( | ||
| 244 | - "SELECT VALUE ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) FROM $b" | ||
| 245 | - )) | ||
| 246 | - .bind(("b", board.record())) | ||
| 247 | - .await? | ||
| 248 | - .check()?; | ||
| 249 | - Ok(result.take::<Vec<i64>>(0)?.into_iter().next().unwrap_or(0)) | ||
| 250 | - } | ||
| 251 | - | ||
| 252 | - /// End the current epoch: the canvas empties, the history does not. | ||
| 253 | - /// | ||
| 254 | - /// The bump and the marker are one transaction, because the marker carries | ||
| 255 | - /// the epoch's final count — written apart, a crash between them would | ||
| 256 | - /// leave an epoch no marker indexes, and the playback would silently join | ||
| 257 | - /// two sessions into one. | ||
| 258 | - /// | ||
| 259 | - /// **The marker pays the lifetime counter.** It is a real `board_stroke` | ||
| 260 | - /// row, so a marker that claimed nothing left `total_stroke_count` counting | ||
| 261 | - /// strokes *drawn* rather than rows *stored*, and `MAX_BOARD_STROKES` | ||
| 262 | - /// stopped bounding the table. Charged here, the counter is exactly the row | ||
| 263 | - /// count again — the counter is reset and re-read in the same statement, so | ||
| 264 | - /// the increment cannot be split off from the marker it pays for. | ||
| 265 | - /// | ||
| 266 | - /// **A blank canvas cannot be cleared.** Without it every call minted a row | ||
| 267 | - /// for free, one per press of a button the creator can hold down. Requiring | ||
| 268 | - /// the epoch counter to be non-zero pays for each marker with at least one | ||
| 269 | - /// stroke it closes — and "there is nothing on this canvas to clear" is the | ||
| 270 | - /// honest answer to the call it refuses. The epochs index keeps its meaning | ||
| 271 | - /// too: no zero-stroke epoch can enter it. | ||
| 272 | - /// | ||
| 273 | - /// **A locked board cannot be cleared.** The lock is the creator's own | ||
| 274 | - /// pause on the canvas, and it holds against every write to it including | ||
| 275 | - /// theirs — [`BOARD_OPEN_GUARD`] is the same condition the stroke path | ||
| 276 | - /// claims under, so "locked" means one thing everywhere. The cost is | ||
| 277 | - /// accepted: a locked board sitting at `MAX_EPOCH_STROKES` is recovered by | ||
| 278 | - /// unlock, clear, relock. | ||
| 279 | - /// | ||
| 280 | - /// The marker's own increment is not capped: the last stroke of a board's | ||
| 281 | - /// budget may be closed by a marker, so a board holds at most | ||
| 282 | - /// `MAX_BOARD_STROKES + 1` rows. Capping it would refuse the clear that | ||
| 283 | - /// files the final epoch in the index, which is the one clear the history | ||
| 284 | - /// needs. | ||
| 285 | - pub async fn clear( | ||
| 286 | - board: &BoardId, | ||
| 287 | - by: &UserId, | ||
| 288 | - db: &Database, | ||
| 289 | - ) -> Result<BoardStroke, AppError> { | ||
| 290 | - let marker = BoardStrokeId::generate(); | ||
| 291 | - // `($before[0].epoch_stroke_count ?? 0)` is parenthesized: the bare form | ||
| 292 | - // parses as `?? (0 = …)` and stores a boolean count (src/constant.rs:699). | ||
| 293 | - let sql = format!( | ||
| 294 | - "BEGIN TRANSACTION; | ||
| 295 | - LET $before = (UPDATE $b SET epoch += 1, {BOARD_EPOCH_STROKE_COUNT_FIELD} = 0, \ | ||
| 296 | - {BOARD_TOTAL_STROKE_COUNT_FIELD} = ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) + 1 \ | ||
| 297 | - WHERE creator = $by AND {BOARD_OPEN_GUARD} \ | ||
| 298 | - AND ({BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0) > 0 RETURN BEFORE); | ||
| 299 | - IF array::len($before) = 0 {{ THROW '{CLEAR_REFUSED}' }}; | ||
| 300 | - CREATE $mid CONTENT {{ board: $b, author: $by, kind: $kind, \ | ||
| 301 | - epoch: $before[0].epoch, \ | ||
| 302 | - count: ($before[0].{BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0), \ | ||
| 303 | - created_at: $now }}; | ||
| 304 | - COMMIT TRANSACTION;" | ||
| 305 | - ); | ||
| 306 | - let bound: Vec<(String, Value)> = vec![ | ||
| 307 | - ("b".into(), board.record().into_value()), | ||
| 308 | - ("by".into(), by.record().into_value()), | ||
| 309 | - ("mid".into(), marker.record().into_value()), | ||
| 310 | - ("kind".into(), KIND_CLEAR.into_value()), | ||
| 311 | - ("now".into(), Timestamp::now().as_millis().into_value()), | ||
| 312 | - ]; | ||
| 313 | - // The epoch counter is reset here, which is a counter write like any | ||
| 314 | - // other, so it owes the process the same one-at-a-time discipline | ||
| 315 | - // (`cap::counter_lock`) — and unlike a lone conditional claim it is | ||
| 316 | - // read back in the same statement, by the marker's `count`. | ||
| 317 | - let _guard = cap::counter_lock().await; | ||
| 318 | - let (mut result, mut errors) = | ||
| 319 | - transaction_with_retry(db, &sql, &bound, &[CLEAR_REFUSED]).await?; | ||
| 320 | - if errors | ||
| 321 | - .values() | ||
| 322 | - .any(|error| error.to_string().contains(CLEAR_REFUSED)) | ||
| 323 | - { | ||
| 324 | - return Err(Self::why_clear_refused(board, by, db).await?); | ||
| 325 | - } | ||
| 326 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 327 | - return Err(error.into()); | ||
| 328 | - } | ||
| 329 | - // Slots count BEGIN, the LET and the IF: the CREATE is slot 3. Only | ||
| 330 | - // read once the error map is empty — `take_errors` swap-removes. | ||
| 331 | - result | ||
| 332 | - .take::<Vec<BoardStroke>>(3)? | ||
| 333 | - .into_iter() | ||
| 334 | - .next() | ||
| 335 | - .ok_or_else(|| AppError::Internal("board clear wrote no marker".into())) | ||
| 336 | - } | ||
| 337 | - | ||
| 338 | - /// Which of the clear guard's four conditions said no. One `WHERE` cannot | ||
| 339 | - /// report that itself, so the board is re-read — on the refusal path only, | ||
| 340 | - /// like [`Self::why_refused`]. The distinction is not cosmetic: a closed | ||
| 341 | - /// board is terminal for the room, a blank canvas is an ordinary "nothing | ||
| 342 | - /// to do" and a room told otherwise stops drawing for good. | ||
| 343 | - async fn why_clear_refused( | ||
| 344 | - board: &BoardId, | ||
| 345 | - by: &UserId, | ||
| 346 | - db: &Database, | ||
| 347 | - ) -> Result<AppError, AppError> { | ||
| 348 | - let board = Board::read(board, db).await?.ok_or(AppError::NotFound)?; | ||
| 349 | - let state = Self::state_refusal(&board); | ||
| 350 | - // Terminal outranks the caller's identity: a closed board is read-only | ||
| 351 | - // for its creator too, so "closed" is the honest answer to anyone. | ||
| 352 | - if state == Some(BOARD_CLOSED) { | ||
| 353 | - return Ok(AppError::Conflict(BOARD_CLOSED)); | ||
| 354 | - } | ||
| 355 | - if !board.is_creator(by) { | ||
| 356 | - return Ok(AppError::Forbidden(NOT_THE_CREATOR)); | ||
| 357 | - } | ||
| 358 | - // A lock pauses the *creator* too, and it is a state the caller can | ||
| 359 | - // undo — a `Conflict`, not the `Forbidden` a wrong caller gets. Unlock, | ||
| 360 | - // clear, relock is the recovery for a locked board that is also full. | ||
| 361 | - if let Some(refusal) = state { | ||
| 362 | - return Ok(AppError::Conflict(refusal)); | ||
| 363 | - } | ||
| 364 | - Ok(AppError::Conflict(CANVAS_BLANK)) | ||
| 365 | - } | ||
| 366 | - | ||
| 367 | - /// What a joining socket draws: the current epoch's marks only, in mint | ||
| 368 | - /// order, one [`BOARD_REPLAY_CHUNK`] at a time. | ||
| 369 | - /// | ||
| 370 | - /// Paged by `id`, never `created_at` — a millisecond stamp has ties by | ||
| 371 | - /// construction, and the ULID's monotonic low half is exactly what breaks | ||
| 372 | - /// them. `after` is the key of the last stroke already drawn. | ||
| 373 | - pub async fn replay_current( | ||
| 374 | - board: &BoardId, | ||
| 375 | - epoch: i64, | ||
| 376 | - after: Option<&str>, | ||
| 377 | - db: &Database, | ||
| 378 | - ) -> Result<Vec<BoardStroke>, AppError> { | ||
| 379 | - let cursor = match after { | ||
| 380 | - Some(_) => " AND id > $after", | ||
| 381 | - None => "", | ||
| 382 | - }; | ||
| 383 | - let mut result = db | ||
| 384 | - .query(format!( | ||
| 385 | - "SELECT * FROM {BOARD_STROKE_TABLE} \ | ||
| 386 | - WHERE board = $b AND epoch = $e AND kind = $kind{cursor} \ | ||
| 387 | - ORDER BY id LIMIT $chunk" | ||
| 388 | - )) | ||
| 389 | - .bind(("b", board.record())) | ||
| 390 | - .bind(("e", epoch)) | ||
| 391 | - .bind(("kind", KIND_STROKE)) | ||
| 392 | - .bind(( | ||
| 393 | - "after", | ||
| 394 | - RecordId::new(BOARD_STROKE_TABLE, after.unwrap_or_default()), | ||
| 395 | - )) | ||
| 396 | - .bind(("chunk", BOARD_REPLAY_CHUNK as i64)) | ||
| 397 | - .await? | ||
| 398 | - .check()?; | ||
| 399 | - Ok(result.take::<Vec<BoardStroke>>(0)?) | ||
| 400 | - } | ||
| 401 | - | ||
| 402 | - /// The whole log, oldest first — every epoch, or one named epoch. Both | ||
| 403 | - /// kinds of row come back: the `clear` markers are what tell a reader where | ||
| 404 | - /// one epoch ended and the next began. | ||
| 405 | - /// | ||
| 406 | - /// `marks_only` drops the markers, which is what the *live canvas* wants: | ||
| 407 | - /// the current epoch holds no marker by construction, except in the one | ||
| 408 | - /// race where a clear commits between the board read and this read and | ||
| 409 | - /// files its marker under the epoch just named. The room's replay filters | ||
| 410 | - /// to `kind = 'stroke'` ([`Self::replay_current`]), so without this the two | ||
| 411 | - /// views disagree in exactly that window. | ||
| 412 | - pub async fn history( | ||
| 413 | - board: &BoardId, | ||
| 414 | - epoch: Option<i64>, | ||
| 415 | - marks_only: bool, | ||
| 416 | - limit: Option<i64>, | ||
| 417 | - offset: i64, | ||
| 418 | - db: &Database, | ||
| 419 | - ) -> Result<(Vec<BoardStroke>, i64), AppError> { | ||
| 420 | - let scope = match epoch { | ||
| 421 | - Some(_) => " AND epoch = $e", | ||
| 422 | - None => "", | ||
| 423 | - }; | ||
| 424 | - let kinds = if marks_only { | ||
| 425 | - " AND kind != $clear" | ||
| 426 | - } else { | ||
| 427 | - "" | ||
| 428 | - }; | ||
| 429 | - PagedList::new( | ||
| 430 | - format!("{BOARD_STROKE_TABLE} WHERE board = $b{scope}{kinds}"), | ||
| 431 | - "ORDER BY id", | ||
| 432 | - ) | ||
| 433 | - .bind("b", board.record()) | ||
| 434 | - .bind("e", epoch.unwrap_or_default()) | ||
| 435 | - .bind("clear", KIND_CLEAR.to_string()) | ||
| 436 | - .run(limit, offset, db) | ||
| 437 | - .await | ||
| 438 | - } | ||
| 439 | - | ||
| 440 | - /// The epoch index: every `clear` marker this board has, oldest first. | ||
| 441 | - pub async fn epochs(board: &BoardId, db: &Database) -> Result<Vec<BoardStroke>, AppError> { | ||
| 442 | - let mut result = db | ||
| 443 | - .query(format!( | ||
| 444 | - "SELECT * FROM {BOARD_STROKE_TABLE} \ | ||
| 445 | - WHERE board = $b AND kind = $kind ORDER BY id" | ||
| 446 | - )) | ||
| 447 | - .bind(("b", board.record())) | ||
| 448 | - .bind(("kind", KIND_CLEAR)) | ||
| 449 | - .await? | ||
| 450 | - .check()?; | ||
| 451 | - Ok(result.take::<Vec<BoardStroke>>(0)?) | ||
| 452 | - } | ||
| 453 | } | 133 | } |
| 454 | 134 | ||
| 455 | -#[cfg(test)] | 135 | +/// The one place the module orders `closed` above `locked`, because a board |
| 456 | -mod tests { | 136 | +/// can hold both flags at once (nothing gates `/close` on the lock or the |
| 457 | - use super::*; | 137 | +/// lock on `closed_at`) and **closed outranks locked**: there is no reopen |
| 458 | - use crate::domain::board::BoardTitle; | 138 | +/// route, so the pause never lifts and only the terminal answer is true. |
| 459 | - | 139 | +/// Both classifiers read the precedence from here rather than keeping a |
| 460 | - async fn a_db() -> Database { | 140 | +/// copy of it — the copies are what drifted, and a room told "the creator |
| 461 | - let db = crate::database::init_mem().await.unwrap(); | 141 | +/// has paused drawing" about a permanently read-only board waits forever. |
| 462 | - db.query( | 142 | +/// |
| 463 | - "CREATE user:c SET username = 'c', password_hash = 'x'; | 143 | +/// `None` means the board is neither: whatever refused the write, this is |
| 464 | - CREATE user:p SET username = 'p', password_hash = 'x';", | 144 | +/// not why. |
| 465 | - ) | 145 | +pub(crate) fn state_refusal(board: &Board) -> Option<&'static str> { |
| 466 | - .await | 146 | + if board.get_closed_at().is_some() { |
| 467 | - .unwrap() | 147 | + Some(BOARD_CLOSED) |
| 468 | - .check() | 148 | + } else if board.is_locked() { |
| 469 | - .unwrap(); | 149 | + Some(BOARD_LOCKED) |
| 470 | - db | 150 | + } else { |
| 471 | - } | 151 | + None |
| 472 | - | ||
| 473 | - fn user(key: &str) -> UserId { | ||
| 474 | - UserId::from_key(key) | ||
| 475 | - } | ||
| 476 | - | ||
| 477 | - async fn a_board(db: &Database) -> Board { | ||
| 478 | - Board::create( | ||
| 479 | - &user("c"), | ||
| 480 | - BoardTitle::try_new("Geometri").unwrap(), | ||
| 481 | - vec![user("p")], | ||
| 482 | - db, | ||
| 483 | - ) | ||
| 484 | - .await | ||
| 485 | - .unwrap() | ||
| 486 | - } | ||
| 487 | - | ||
| 488 | - /// Every stroke row of a board, read straight out of the store — never off | ||
| 489 | - /// a return value, which the in-memory engine forges wins on | ||
| 490 | - /// (src/domain/cap.rs:44-49). | ||
| 491 | - async fn rows(board: &BoardId, db: &Database) -> Vec<BoardStroke> { | ||
| 492 | - let mut result = db | ||
| 493 | - .query("SELECT * FROM board_stroke WHERE board = $b ORDER BY id") | ||
| 494 | - .bind(("b", board.record())) | ||
| 495 | - .await | ||
| 496 | - .unwrap() | ||
| 497 | - .check() | ||
| 498 | - .unwrap(); | ||
| 499 | - result.take(0).unwrap() | ||
| 500 | - } | ||
| 501 | - | ||
| 502 | - async fn reread(board: &Board, db: &Database) -> Board { | ||
| 503 | - Board::read(board.get_id(), db).await.unwrap().unwrap() | ||
| 504 | - } | ||
| 505 | - | ||
| 506 | - async fn set_counters(board: &Board, epoch: i64, total: i64, db: &Database) { | ||
| 507 | - db.query("UPDATE $id SET epoch_stroke_count = $e, total_stroke_count = $t") | ||
| 508 | - .bind(("id", board.get_id().record())) | ||
| 509 | - .bind(("e", epoch)) | ||
| 510 | - .bind(("t", total)) | ||
| 511 | - .await | ||
| 512 | - .unwrap() | ||
| 513 | - .check() | ||
| 514 | - .unwrap(); | ||
| 515 | - } | ||
| 516 | - | ||
| 517 | - async fn draw(board: &Board, db: &Database) -> Result<BoardStroke, AppError> { | ||
| 518 | - BoardStroke::append( | ||
| 519 | - board.get_id(), | ||
| 520 | - &user("p"), | ||
| 521 | - "{\"p\":[1,2]}", | ||
| 522 | - board.get_epoch(), | ||
| 523 | - db, | ||
| 524 | - ) | ||
| 525 | - .await | ||
| 526 | - } | ||
| 527 | - | ||
| 528 | - #[tokio::test] | ||
| 529 | - async fn a_full_canvas_is_refused_but_the_board_stays_open() { | ||
| 530 | - let db = a_db().await; | ||
| 531 | - let board = a_board(&db).await; | ||
| 532 | - set_counters(&board, MAX_EPOCH_STROKES, 10, &db).await; | ||
| 533 | - let refused = draw(&board, &db).await; | ||
| 534 | - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("clear it"))); | ||
| 535 | - // Nothing written, and above all: NOT closed — a full canvas is | ||
| 536 | - // recoverable, and closing it here would make it permanent. | ||
| 537 | - assert!(rows(board.get_id(), &db).await.is_empty()); | ||
| 538 | - assert!(reread(&board, &db).await.get_closed_at().is_none()); | ||
| 539 | - } | ||
| 540 | - | ||
| 541 | - /// The user's decision in one test: a clear empties the canvas and loses | ||
| 542 | - /// nothing. If this ever passes with the pre-clear rows gone, the feature | ||
| 543 | - /// is wrong. | ||
| 544 | - #[tokio::test] | ||
| 545 | - async fn a_clear_keeps_every_pre_clear_stroke() { | ||
| 546 | - let db = a_db().await; | ||
| 547 | - let board = a_board(&db).await; | ||
| 548 | - for _ in 0..3 { | ||
| 549 | - draw(&board, &db).await.unwrap(); | ||
| 550 | - } | ||
| 551 | - let before: Vec<String> = rows(board.get_id(), &db) | ||
| 552 | - .await | ||
| 553 | - .iter() | ||
| 554 | - .map(|row| row.get_id().key().to_string()) | ||
| 555 | - .collect(); | ||
| 556 | - | ||
| 557 | - BoardStroke::clear(board.get_id(), &user("c"), &db) | ||
| 558 | - .await | ||
| 559 | - .unwrap(); | ||
| 560 | - let board = reread(&board, &db).await; | ||
| 561 | - assert_eq!(board.get_epoch(), 1); | ||
| 562 | - draw(&board, &db).await.unwrap(); | ||
| 563 | - | ||
| 564 | - // The three original rows are still in the table, by direct read. | ||
| 565 | - let after: Vec<String> = rows(board.get_id(), &db) | ||
| 566 | - .await | ||
| 567 | - .iter() | ||
| 568 | - .map(|row| row.get_id().key().to_string()) | ||
| 569 | - .collect(); | ||
| 570 | - for key in &before { | ||
| 571 | - assert!(after.contains(key), "a clear deleted stroke {key}"); | ||
| 572 | - } | ||
| 573 | - // 3 old + 1 marker + 1 new, and the live canvas is the new one alone. | ||
| 574 | - assert_eq!(after.len(), 5); | ||
| 575 | - let live = BoardStroke::replay_current(board.get_id(), 1, None, &db) | ||
| 576 | - .await | ||
| 577 | - .unwrap(); | ||
| 578 | - assert_eq!(live.len(), 1); | ||
| 579 | - // The old epoch is still replayable in full. | ||
| 580 | - assert_eq!( | ||
| 581 | - BoardStroke::replay_current(board.get_id(), 0, None, &db) | ||
| 582 | - .await | ||
| 583 | - .unwrap() | ||
| 584 | - .len(), | ||
| 585 | - 3 | ||
| 586 | - ); | ||
| 587 | - } | ||
| 588 | - | ||
| 589 | - /// The marker IS the epoch index, so its `count` has to be that epoch's | ||
| 590 | - /// final stroke count — and `count` must appear on no other row. | ||
| 591 | - #[tokio::test] | ||
| 592 | - async fn the_marker_counts_the_epoch_it_closed() { | ||
| 593 | - let db = a_db().await; | ||
| 594 | - let board = a_board(&db).await; | ||
| 595 | - for _ in 0..4 { | ||
| 596 | - draw(&board, &db).await.unwrap(); | ||
| 597 | - } | ||
| 598 | - let marker = BoardStroke::clear(board.get_id(), &user("c"), &db) | ||
| 599 | - .await | ||
| 600 | - .unwrap(); | ||
| 601 | - assert_eq!(marker.get_count(), Some(4)); | ||
| 602 | - assert_eq!(marker.get_epoch(), 0); | ||
| 603 | - assert!(marker.is_clear()); | ||
| 604 | - | ||
| 605 | - // And the epoch counter reset, so drawing resumes against a fresh cap. | ||
| 606 | - let board = reread(&board, &db).await; | ||
| 607 | - draw(&board, &db).await.unwrap(); | ||
| 608 | - let epochs = BoardStroke::epochs(board.get_id(), &db).await.unwrap(); | ||
| 609 | - assert_eq!(epochs.len(), 1); | ||
| 610 | - assert_eq!(epochs[0].get_count(), Some(4)); | ||
| 611 | - // `count` lives on clear markers only — this module is that guard. | ||
| 612 | - for row in rows(board.get_id(), &db).await { | ||
| 613 | - assert_eq!(row.get_count().is_some(), row.is_clear()); | ||
| 614 | - assert_eq!(row.get_payload().is_some(), !row.is_clear()); | ||
| 615 | - } | ||
| 616 | - } | ||
| 617 | - | ||
| 618 | - #[tokio::test] | ||
| 619 | - async fn the_lifetime_cap_closes_the_board_exactly_once() { | ||
| 620 | - let db = a_db().await; | ||
| 621 | - let board = a_board(&db).await; | ||
| 622 | - set_counters(&board, 0, MAX_BOARD_STROKES, &db).await; | ||
| 623 | - let refused = draw(&board, &db).await; | ||
| 624 | - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("read-only"))); | ||
| 625 | - let stamp = reread(&board, &db).await.get_closed_at(); | ||
| 626 | - assert!(stamp.is_some()); | ||
| 627 | - | ||
| 628 | - // A whole millisecond apart, so a re-stamp could not go unnoticed. | ||
| 629 | - tokio::time::sleep(std::time::Duration::from_millis(2)).await; | ||
| 630 | - assert!(draw(&board, &db).await.is_err()); | ||
| 631 | - assert_eq!(reread(&board, &db).await.get_closed_at(), stamp); | ||
| 632 | - assert!(rows(board.get_id(), &db).await.is_empty()); | ||
| 633 | - } | ||
| 634 | - | ||
| 635 | - /// A locked board must be told it is locked. Both refusals arrive as the | ||
| 636 | - /// same `FullHard`, so a re-read that got this wrong would tell a paused | ||
| 637 | - /// room its canvas is full — and send it clearing a board it need not clear. | ||
| 638 | - #[tokio::test] | ||
| 639 | - async fn a_locked_board_is_refused_as_locked() { | ||
| 640 | - let db = a_db().await; | ||
| 641 | - let board = a_board(&db).await; | ||
| 642 | - let board = board.set_locked(true, &user("c"), &db).await.unwrap(); | ||
| 643 | - let refused = draw(&board, &db).await; | ||
| 644 | - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("locked"))); | ||
| 645 | - assert!(rows(board.get_id(), &db).await.is_empty()); | ||
| 646 | - // A lock is not a close: unlocking restores drawing. | ||
| 647 | - assert!(reread(&board, &db).await.get_closed_at().is_none()); | ||
| 648 | - let board = board.set_locked(false, &user("c"), &db).await.unwrap(); | ||
| 649 | - assert!(draw(&board, &db).await.is_ok()); | ||
| 650 | - } | ||
| 651 | - | ||
| 652 | - /// A lock the stroke lost to, unlocked again before the refusal re-reads | ||
| 653 | - /// the row — which is the state `why_refused` is handed after a guard | ||
| 654 | - /// failure. Reading "neither locked nor closed" as proof of the lifetime | ||
| 655 | - /// cap stamped `closed_at` on a board holding one stroke of 50 000, with | ||
| 656 | - /// no reopen. Only the counter itself may close a board. | ||
| 657 | - #[tokio::test] | ||
| 658 | - async fn a_refusal_on_an_open_board_never_closes_it() { | ||
| 659 | - let db = a_db().await; | ||
| 660 | - let board = a_board(&db).await; | ||
| 661 | - let board = board.set_locked(true, &user("c"), &db).await.unwrap(); | ||
| 662 | - // The claim loses the open-guard while the board is locked... | ||
| 663 | - assert!(matches!( | ||
| 664 | - draw(&board, &db).await, | ||
| 665 | - Err(AppError::Conflict(_)) | ||
| 666 | - )); | ||
| 667 | - // ...and the creator unlocks before the refusal picks its message. | ||
| 668 | - let board = board.set_locked(false, &user("c"), &db).await.unwrap(); | ||
| 669 | - let refused = BoardStroke::why_refused(board.get_id(), &db).await.unwrap(); | ||
| 670 | - assert!(matches!(refused, AppError::Conflict(msg) if !msg.contains("read-only"))); | ||
| 671 | - // Stored state, not the return value: the board is still open, and | ||
| 672 | - // still drawable. | ||
| 673 | - assert!(reread(&board, &db).await.get_closed_at().is_none()); | ||
| 674 | - assert!(draw(&reread(&board, &db).await, &db).await.is_ok()); | ||
| 675 | - } | ||
| 676 | - | ||
| 677 | - /// The epoch index must never drift, in either direction. A stroke carrying | ||
| 678 | - /// a pre-clear epoch used to land under the closed epoch while its | ||
| 679 | - /// increment counted against the new one — the closed marker short by a | ||
| 680 | - /// stroke, the next marker claiming one that is not there, both permanent. | ||
| 681 | - #[tokio::test] | ||
| 682 | - async fn a_stale_epoch_append_leaves_no_marker_drifted() { | ||
| 683 | - let db = a_db().await; | ||
| 684 | - let board = a_board(&db).await; | ||
| 685 | - draw(&board, &db).await.unwrap(); | ||
| 686 | - BoardStroke::clear(board.get_id(), &user("c"), &db) | ||
| 687 | - .await | ||
| 688 | - .unwrap(); | ||
| 689 | - | ||
| 690 | - // Exactly what `live_board` hands `append` when a clear lands between | ||
| 691 | - // the board read and the write (src/web/board_ws.rs:431). | ||
| 692 | - let stale = BoardStroke::append(board.get_id(), &user("p"), "{\"p\":[9]}", 0, &db).await; | ||
| 693 | - assert!(matches!(stale, Err(AppError::Conflict(_)))); | ||
| 694 | - | ||
| 695 | - let board = reread(&board, &db).await; | ||
| 696 | - draw(&board, &db).await.unwrap(); | ||
| 697 | - BoardStroke::clear(board.get_id(), &user("c"), &db) | ||
| 698 | - .await | ||
| 699 | - .unwrap(); | ||
| 700 | - | ||
| 701 | - // Every marker's count is the rows the store actually holds at the | ||
| 702 | - // epoch it closed. | ||
| 703 | - let stored = rows(board.get_id(), &db).await; | ||
| 704 | - for marker in stored.iter().filter(|row| row.is_clear()) { | ||
| 705 | - let actual = stored | ||
| 706 | - .iter() | ||
| 707 | - .filter(|row| !row.is_clear() && row.get_epoch() == marker.get_epoch()) | ||
| 708 | - .count() as i64; | ||
| 709 | - assert_eq!( | ||
| 710 | - marker.get_count(), | ||
| 711 | - Some(actual), | ||
| 712 | - "marker for epoch {} drifted", | ||
| 713 | - marker.get_epoch() | ||
| 714 | - ); | ||
| 715 | - } | ||
| 716 | - // And the refused stroke claimed nothing: two marks and the two | ||
| 717 | - // markers that closed them, which is every row on the table. | ||
| 718 | - assert_eq!( | ||
| 719 | - BoardStroke::total_strokes(board.get_id(), &db) | ||
| 720 | - .await | ||
| 721 | - .unwrap(), | ||
| 722 | - 4 | ||
| 723 | - ); | ||
| 724 | - assert_eq!(stored.len(), 4); | ||
| 725 | - } | ||
| 726 | - | ||
| 727 | - /// The lock pauses the canvas against *every* write to it, its creator's | ||
| 728 | - /// clear included — a `Conflict`, since unlocking undoes it, not the | ||
| 729 | - /// `Forbidden` a non-creator gets. Asserted off stored rows: the refusal | ||
| 730 | - /// must mint no marker and must not bump the epoch. | ||
| 731 | - #[tokio::test] | ||
| 732 | - async fn a_locked_board_refuses_its_creator_s_clear() { | ||
| 733 | - let db = a_db().await; | ||
| 734 | - let board = a_board(&db).await; | ||
| 735 | - draw(&board, &db).await.unwrap(); | ||
| 736 | - let board = board.set_locked(true, &user("c"), &db).await.unwrap(); | ||
| 737 | - | ||
| 738 | - let refused = BoardStroke::clear(board.get_id(), &user("c"), &db).await; | ||
| 739 | - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg == BOARD_LOCKED)); | ||
| 740 | - assert_eq!(rows(board.get_id(), &db).await.len(), 1); | ||
| 741 | - assert_eq!(reread(&board, &db).await.get_epoch(), 0); | ||
| 742 | - assert!( | ||
| 743 | - BoardStroke::epochs(board.get_id(), &db) | ||
| 744 | - .await | ||
| 745 | - .unwrap() | ||
| 746 | - .is_empty() | ||
| 747 | - ); | ||
| 748 | - | ||
| 749 | - // Unlock, and the same clear lands: unlock → clear → relock is the | ||
| 750 | - // recovery for a locked board sitting at the epoch cap. | ||
| 751 | - let board = board.set_locked(false, &user("c"), &db).await.unwrap(); | ||
| 752 | - let marker = BoardStroke::clear(board.get_id(), &user("c"), &db) | ||
| 753 | - .await | ||
| 754 | - .unwrap(); | ||
| 755 | - assert_eq!(marker.get_count(), Some(1)); | ||
| 756 | - assert_eq!(reread(&board, &db).await.get_epoch(), 1); | ||
| 757 | - } | ||
| 758 | - | ||
| 759 | - /// Both classifiers, one board: the words a stroke is refused with and the | ||
| 760 | - /// words the *creator's* clear is refused with. They must match — the two | ||
| 761 | - /// used to be independent chains and drifted apart on the state below. | ||
| 762 | - async fn both_refusals(board: &Board, db: &Database) -> (&'static str, &'static str) { | ||
| 763 | - let stroke = match draw(board, db).await { | ||
| 764 | - Err(AppError::Conflict(msg)) => msg, | ||
| 765 | - other => panic!("the stroke was not refused: {other:?}"), | ||
| 766 | - }; | ||
| 767 | - let clear = match BoardStroke::clear(board.get_id(), &user("c"), db).await { | ||
| 768 | - Err(AppError::Conflict(msg)) => msg, | ||
| 769 | - other => panic!("the clear was not refused: {other:?}"), | ||
| 770 | - }; | ||
| 771 | - (stroke, clear) | ||
| 772 | - } | ||
| 773 | - | ||
| 774 | - /// A board that is locked *and* closed is terminal, and both paths have to | ||
| 775 | - /// say so. Reaching the state is ungated in either direction — `set_locked` | ||
| 776 | - /// carries no `closed_at` test and `close` carries no lock test — and the | ||
| 777 | - /// stroke path used to test the lock first, so a permanently read-only | ||
| 778 | - /// board answered every mark with "the creator has paused drawing" while | ||
| 779 | - /// the same board answered a clear with the terminal words. A room told to | ||
| 780 | - /// wait for a pause that cannot lift waits forever. | ||
| 781 | - /// | ||
| 782 | - /// Locking a closed board stays *allowed*: it is a no-op on a board that is | ||
| 783 | - /// already read-only, and refusing it would break the second half of a | ||
| 784 | - /// close-then-lock a client may legitimately send in either order. | ||
| 785 | - #[tokio::test] | ||
| 786 | - async fn locked_and_closed_answers_closed_whichever_came_first() { | ||
| 787 | - for closed_first in [false, true] { | ||
| 788 | - let db = a_db().await; | ||
| 789 | - let board = a_board(&db).await; | ||
| 790 | - // A mark on the canvas, so "nothing to clear" cannot be the reason. | ||
| 791 | - draw(&board, &db).await.unwrap(); | ||
| 792 | - | ||
| 793 | - let board = if closed_first { | ||
| 794 | - let board = board.close(&db).await.unwrap(); | ||
| 795 | - board.set_locked(true, &user("c"), &db).await.unwrap() | ||
| 796 | - } else { | ||
| 797 | - let board = board.set_locked(true, &user("c"), &db).await.unwrap(); | ||
| 798 | - board.close(&db).await.unwrap() | ||
| 799 | - }; | ||
| 800 | - // Stored state: both flags really are up, and the close stamp stood. | ||
| 801 | - let stored = reread(&board, &db).await; | ||
| 802 | - assert!(stored.is_locked() && stored.get_closed_at().is_some()); | ||
| 803 | - | ||
| 804 | - assert_eq!( | ||
| 805 | - both_refusals(&board, &db).await, | ||
| 806 | - (BOARD_CLOSED, BOARD_CLOSED), | ||
| 807 | - "closed_first = {closed_first}" | ||
| 808 | - ); | ||
| 809 | - // And the refusals wrote nothing: one mark, no marker, epoch 0. | ||
| 810 | - assert_eq!(rows(board.get_id(), &db).await.len(), 1); | ||
| 811 | - assert_eq!(reread(&board, &db).await.get_epoch(), 0); | ||
| 812 | - } | ||
| 813 | - } | ||
| 814 | - | ||
| 815 | - /// The other half of the same contract: a board holding *one* of the flags | ||
| 816 | - /// keeps its own answer on both paths. A lock is recoverable, a close is | ||
| 817 | - /// not, and collapsing either into the other is the mislabel above. | ||
| 818 | - #[tokio::test] | ||
| 819 | - async fn one_flag_alone_keeps_its_own_answer_on_both_paths() { | ||
| 820 | - let db = a_db().await; | ||
| 821 | - let locked = a_board(&db).await; | ||
| 822 | - draw(&locked, &db).await.unwrap(); | ||
| 823 | - let locked = locked.set_locked(true, &user("c"), &db).await.unwrap(); | ||
| 824 | - assert_eq!( | ||
| 825 | - both_refusals(&locked, &db).await, | ||
| 826 | - (BOARD_LOCKED, BOARD_LOCKED) | ||
| 827 | - ); | ||
| 828 | - | ||
| 829 | - let closed = a_board(&db).await; | ||
| 830 | - draw(&closed, &db).await.unwrap(); | ||
| 831 | - let closed = closed.close(&db).await.unwrap(); | ||
| 832 | - assert_eq!( | ||
| 833 | - both_refusals(&closed, &db).await, | ||
| 834 | - (BOARD_CLOSED, BOARD_CLOSED) | ||
| 835 | - ); | ||
| 836 | - } | ||
| 837 | - | ||
| 838 | - /// The `next_ulid` hazard: rows minted inside one millisecond must replay | ||
| 839 | - /// in mint order, not at random (src/domain/monotonic_id.rs:41-46). | ||
| 840 | - #[tokio::test] | ||
| 841 | - async fn replay_is_in_mint_order_within_a_millisecond() { | ||
| 842 | - let db = a_db().await; | ||
| 843 | - let board = a_board(&db).await; | ||
| 844 | - let mut minted = Vec::new(); | ||
| 845 | - for _ in 0..25 { | ||
| 846 | - minted.push(draw(&board, &db).await.unwrap().get_id().key().to_string()); | ||
| 847 | - } | ||
| 848 | - let replayed: Vec<String> = BoardStroke::replay_current(board.get_id(), 0, None, &db) | ||
| 849 | - .await | ||
| 850 | - .unwrap() | ||
| 851 | - .iter() | ||
| 852 | - .map(|row| row.get_id().key().to_string()) | ||
| 853 | - .collect(); | ||
| 854 | - assert_eq!(replayed, minted); | ||
| 855 | - | ||
| 856 | - // The cursor resumes exactly where the last chunk stopped. | ||
| 857 | - let rest: Vec<String> = | ||
| 858 | - BoardStroke::replay_current(board.get_id(), 0, Some(&minted[9]), &db) | ||
| 859 | - .await | ||
| 860 | - .unwrap() | ||
| 861 | - .iter() | ||
| 862 | - .map(|row| row.get_id().key().to_string()) | ||
| 863 | - .collect(); | ||
| 864 | - assert_eq!(rest, minted[10..]); | ||
| 865 | - } | ||
| 866 | - | ||
| 867 | - /// The one legitimate delete of stroke rows: without it, deleting a board | ||
| 868 | - /// orphans its whole history under a record that no longer exists. | ||
| 869 | - #[tokio::test] | ||
| 870 | - async fn deleting_a_board_takes_its_strokes_with_it() { | ||
| 871 | - let db = a_db().await; | ||
| 872 | - let board = a_board(&db).await; | ||
| 873 | - let other = a_board(&db).await; | ||
| 874 | - draw(&board, &db).await.unwrap(); | ||
| 875 | - draw(&board, &db).await.unwrap(); | ||
| 876 | - BoardStroke::clear(board.get_id(), &user("c"), &db) | ||
| 877 | - .await | ||
| 878 | - .unwrap(); | ||
| 879 | - draw(&other, &db).await.unwrap(); | ||
| 880 | - | ||
| 881 | - let id = board.get_id().clone(); | ||
| 882 | - board.delete(&db).await.unwrap(); | ||
| 883 | - assert!(rows(&id, &db).await.is_empty()); | ||
| 884 | - // The cascade is scoped to its own board. | ||
| 885 | - assert_eq!(rows(other.get_id(), &db).await.len(), 1); | ||
| 886 | - } | ||
| 887 | - | ||
| 888 | - #[tokio::test] | ||
| 889 | - async fn an_oversized_payload_is_refused_before_the_write() { | ||
| 890 | - let db = a_db().await; | ||
| 891 | - let board = a_board(&db).await; | ||
| 892 | - let big = "x".repeat(MAX_STROKE_PAYLOAD_LEN + 1); | ||
| 893 | - assert!( | ||
| 894 | - BoardStroke::append(board.get_id(), &user("p"), &big, 0, &db) | ||
| 895 | - .await | ||
| 896 | - .is_err() | ||
| 897 | - ); | ||
| 898 | - assert!( | ||
| 899 | - BoardStroke::append(board.get_id(), &user("p"), " ", 0, &db) | ||
| 900 | - .await | ||
| 901 | - .is_err() | ||
| 902 | - ); | ||
| 903 | - assert!(rows(board.get_id(), &db).await.is_empty()); | ||
| 904 | - // Nothing was claimed either — the counters must not have moved. | ||
| 905 | - assert_eq!(reread(&board, &db).await.get_epoch(), 0); | ||
| 906 | - } | ||
| 907 | - | ||
| 908 | - /// History spans epochs; a named epoch is that epoch alone. | ||
| 909 | - #[tokio::test] | ||
| 910 | - async fn history_spans_every_epoch_unless_one_is_named() { | ||
| 911 | - let db = a_db().await; | ||
| 912 | - let board = a_board(&db).await; | ||
| 913 | - draw(&board, &db).await.unwrap(); | ||
| 914 | - BoardStroke::clear(board.get_id(), &user("c"), &db) | ||
| 915 | - .await | ||
| 916 | - .unwrap(); | ||
| 917 | - let board = reread(&board, &db).await; | ||
| 918 | - draw(&board, &db).await.unwrap(); | ||
| 919 | - | ||
| 920 | - let (all, total) = BoardStroke::history(board.get_id(), None, false, None, 0, &db) | ||
| 921 | - .await | ||
| 922 | - .unwrap(); | ||
| 923 | - assert_eq!((all.len(), total), (3, 3)); | ||
| 924 | - let (first, total) = BoardStroke::history(board.get_id(), Some(0), false, None, 0, &db) | ||
| 925 | - .await | ||
| 926 | - .unwrap(); | ||
| 927 | - // Epoch 0: its stroke and the marker that closed it. | ||
| 928 | - assert_eq!((first.len(), total), (2, 2)); | ||
| 929 | - // `marks_only` drops the marker from that same epoch — and its `total` | ||
| 930 | - // with it, so the envelope's count stays the count of what is served. | ||
| 931 | - let (marks, total) = BoardStroke::history(board.get_id(), Some(0), true, None, 0, &db) | ||
| 932 | - .await | ||
| 933 | - .unwrap(); | ||
| 934 | - assert_eq!((marks.len(), total), (1, 1)); | ||
| 935 | - assert!(marks.iter().all(|row| !row.is_clear())); | ||
| 936 | } | 152 | } |
| 937 | } | 153 | } |
src/domain/course_note.rsmodified+9 -196
| @@ -1,17 +1,10 @@ | |||
| 1 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 1 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 2 | 2 | ||
| 3 | -use crate::constant::{ | 3 | +use crate::constant::{COURSE_NOTE_TABLE, MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN}; |
| 4 | - COURSE_NOTE_TABLE, ENROLLMENT_COUNT_FIELD, MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN, | ||
| 5 | -}; | ||
| 6 | -use crate::database::Database; | ||
| 7 | -use crate::db::cap; | ||
| 8 | use crate::domain::course::CourseId; | 4 | use crate::domain::course::CourseId; |
| 9 | -use crate::domain::course_note_file::CourseNoteFile; | ||
| 10 | -use crate::db::field_update::FieldUpdate; | ||
| 11 | use crate::domain::monotonic_id::next_ulid; | 5 | use crate::domain::monotonic_id::next_ulid; |
| 12 | -use crate::db::page::PagedList; | ||
| 13 | use crate::domain::user::UserId; | 6 | use crate::domain::user::UserId; |
| 14 | -use crate::error::{AppError, ValidationError}; | 7 | +use crate::error::ValidationError; |
| 15 | use crate::validate::{validate_optional, validate_required}; | 8 | use crate::validate::{validate_optional, validate_required}; |
| 16 | 9 | ||
| 17 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 10 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| @@ -20,8 +13,8 @@ pub struct CourseNoteId(RecordId); | |||
| 20 | impl CourseNoteId { | 13 | impl CourseNoteId { |
| 21 | /// Minted from the process-wide monotonic generator, not `Ulid::new()`: | 14 | /// Minted from the process-wide monotonic generator, not `Ulid::new()`: |
| 22 | /// a course's notes list `id DESC` (newest first, | 15 | /// a course's notes list `id DESC` (newest first, |
| 23 | - /// [`CourseNote::list_for_course`]), and a random low half scrambles rows | 16 | + /// [`crate::db::course_note::list_for_course`]), and a random low half |
| 24 | - /// minted in the same millisecond. | 17 | + /// scrambles rows minted in the same millisecond. |
| 25 | pub fn generate() -> Self { | 18 | pub fn generate() -> Self { |
| 26 | Self(RecordId::new(COURSE_NOTE_TABLE, next_ulid().to_string())) | 19 | Self(RecordId::new(COURSE_NOTE_TABLE, next_ulid().to_string())) |
| 27 | } | 20 | } |
| @@ -70,22 +63,13 @@ impl CourseNoteContent { | |||
| 70 | } | 63 | } |
| 71 | } | 64 | } |
| 72 | 65 | ||
| 73 | -/// What [`CourseNote::delete`]'s transaction removed: the note row (empty if | ||
| 74 | -/// it had already vanished) and every attachment row the cascade took with | ||
| 75 | -/// it — the only set whose blobs are safe to unlink. | ||
| 76 | -#[derive(Debug, SurrealValue)] | ||
| 77 | -struct DeleteOutcome { | ||
| 78 | - note: Vec<CourseNote>, | ||
| 79 | - files: Vec<CourseNoteFile>, | ||
| 80 | -} | ||
| 81 | - | ||
| 82 | #[derive(Debug, Clone, SurrealValue)] | 66 | #[derive(Debug, Clone, SurrealValue)] |
| 83 | pub struct CourseNote { | 67 | pub struct CourseNote { |
| 84 | - id: CourseNoteId, | 68 | + pub(crate) id: CourseNoteId, |
| 85 | - course: CourseId, | 69 | + pub(crate) course: CourseId, |
| 86 | - author: UserId, | 70 | + pub(crate) author: UserId, |
| 87 | - title: CourseNoteTitle, | 71 | + pub(crate) title: CourseNoteTitle, |
| 88 | - content: CourseNoteContent, | 72 | + pub(crate) content: CourseNoteContent, |
| 89 | } | 73 | } |
| 90 | 74 | ||
| 91 | impl CourseNote { | 75 | impl CourseNote { |
| @@ -108,100 +92,6 @@ impl CourseNote { | |||
| 108 | pub fn get_content(&self) -> &CourseNoteContent { | 92 | pub fn get_content(&self) -> &CourseNoteContent { |
| 109 | &self.content | 93 | &self.content |
| 110 | } | 94 | } |
| 111 | - | ||
| 112 | - pub async fn create( | ||
| 113 | - course: &CourseId, | ||
| 114 | - author: &UserId, | ||
| 115 | - title: CourseNoteTitle, | ||
| 116 | - content: CourseNoteContent, | ||
| 117 | - db: &Database, | ||
| 118 | - ) -> Result<CourseNote, AppError> { | ||
| 119 | - let note = CourseNote { | ||
| 120 | - id: CourseNoteId::generate(), | ||
| 121 | - course: course.clone(), | ||
| 122 | - author: author.clone(), | ||
| 123 | - title, | ||
| 124 | - content, | ||
| 125 | - }; | ||
| 126 | - // The course row is *written* (bumped and put back), not read, so this | ||
| 127 | - // collides with `Course::delete`'s cascade: a note that outlives its | ||
| 128 | - // course is unreachable forever — every route to it goes through the | ||
| 129 | - // course. See [`cap::touch_and_create`]. | ||
| 130 | - cap::touch_and_create( | ||
| 131 | - &course.record(), | ||
| 132 | - ENROLLMENT_COUNT_FIELD, | ||
| 133 | - ¬e.id.record(), | ||
| 134 | - ¬e, | ||
| 135 | - db, | ||
| 136 | - ) | ||
| 137 | - .await? | ||
| 138 | - .ok_or(AppError::NotFound) | ||
| 139 | - } | ||
| 140 | - | ||
| 141 | - pub async fn read(id: &CourseNoteId, db: &Database) -> Result<Option<CourseNote>, AppError> { | ||
| 142 | - Ok(db.select(id.record()).await?) | ||
| 143 | - } | ||
| 144 | - | ||
| 145 | - pub async fn list_for_course( | ||
| 146 | - course: &CourseId, | ||
| 147 | - limit: Option<i64>, | ||
| 148 | - offset: i64, | ||
| 149 | - db: &Database, | ||
| 150 | - ) -> Result<(Vec<CourseNote>, i64), AppError> { | ||
| 151 | - PagedList::new("course_note WHERE course = $crs", "ORDER BY id DESC") | ||
| 152 | - .bind("crs", course.record()) | ||
| 153 | - .run(limit, offset, db) | ||
| 154 | - .await | ||
| 155 | - } | ||
| 156 | - | ||
| 157 | - /// Request-scoped: no lock spans the handler's read and this write, so an | ||
| 158 | - /// omitted field (`None`) is not written at all. Passing the snapshot's | ||
| 159 | - /// value back instead would revert a concurrent edit of that field — | ||
| 160 | - /// scoping the `SET` alone does not prevent that, the values have to come | ||
| 161 | - /// from the request. Neither column is nullable, so plain `Option` per | ||
| 162 | - /// field says everything there is to say. | ||
| 163 | - pub async fn update( | ||
| 164 | - self, | ||
| 165 | - title: Option<CourseNoteTitle>, | ||
| 166 | - content: Option<CourseNoteContent>, | ||
| 167 | - db: &Database, | ||
| 168 | - ) -> Result<CourseNote, AppError> { | ||
| 169 | - FieldUpdate::new(self.id.record()) | ||
| 170 | - .set("title", title) | ||
| 171 | - .set("content", content) | ||
| 172 | - .run::<CourseNote>(db) | ||
| 173 | - .await | ||
| 174 | - } | ||
| 175 | - | ||
| 176 | - /// Delete the note and cascade-remove its attachment rows, returning both: | ||
| 177 | - /// the note, and the attachment rows this transaction actually removed. | ||
| 178 | - /// Blob files on disk are the web layer's to remove, but only for *these* | ||
| 179 | - /// rows — a row uploaded after the caller listed the note's files is | ||
| 180 | - /// deleted here too, and a pre-read snapshot would strand its blob. | ||
| 181 | - pub async fn delete( | ||
| 182 | - self, | ||
| 183 | - db: &Database, | ||
| 184 | - ) -> Result<(CourseNote, Vec<CourseNoteFile>), AppError> { | ||
| 185 | - let mut result = db | ||
| 186 | - .query( | ||
| 187 | - "BEGIN TRANSACTION; | ||
| 188 | - LET $files = (DELETE course_note_file WHERE course_note = $note RETURN BEFORE); | ||
| 189 | - LET $gone = (DELETE $note RETURN BEFORE); | ||
| 190 | - RETURN { note: $gone, files: $files }; | ||
| 191 | - COMMIT TRANSACTION;", | ||
| 192 | - ) | ||
| 193 | - .bind(("note", self.id.record())) | ||
| 194 | - .await? | ||
| 195 | - .check()?; | ||
| 196 | - // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3. | ||
| 197 | - let outcome = result | ||
| 198 | - .take::<Vec<DeleteOutcome>>(3)? | ||
| 199 | - .into_iter() | ||
| 200 | - .next() | ||
| 201 | - .ok_or_else(|| AppError::Internal("failed to delete course note".into()))?; | ||
| 202 | - let note = outcome.note.into_iter().next().ok_or(AppError::NotFound)?; | ||
| 203 | - Ok((note, outcome.files)) | ||
| 204 | - } | ||
| 205 | } | 95 | } |
| 206 | 96 | ||
| 207 | #[cfg(test)] | 97 | #[cfg(test)] |
| @@ -219,81 +109,4 @@ mod tests { | |||
| 219 | assert_eq!(CourseNoteContent::try_new("").unwrap().as_str(), ""); | 109 | assert_eq!(CourseNoteContent::try_new("").unwrap().as_str(), ""); |
| 220 | assert_eq!(CourseNoteContent::try_new("body").unwrap().as_str(), "body"); | 110 | assert_eq!(CourseNoteContent::try_new("body").unwrap().as_str(), "body"); |
| 221 | } | 111 | } |
| 222 | - | ||
| 223 | - /// The blobs the handler unlinks are exactly the rows this transaction | ||
| 224 | - /// removed — including one uploaded after any pre-read snapshot would have | ||
| 225 | - /// been taken, which is the row whose blob used to leak. | ||
| 226 | - #[tokio::test] | ||
| 227 | - async fn delete_returns_the_attachment_rows_it_removed() { | ||
| 228 | - use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; | ||
| 229 | - use crate::domain::course_note_file::{FileContentType, FileName}; | ||
| 230 | - | ||
| 231 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 232 | - let creator = crate::domain::user::UserId::generate(); | ||
| 233 | - let course = crate::db::course::create( | ||
| 234 | - &db, | ||
| 235 | - &creator, | ||
| 236 | - CourseTitle::try_new("Math").unwrap(), | ||
| 237 | - CourseDescription::try_new("").unwrap(), | ||
| 238 | - CourseKind::try_new("course").unwrap(), | ||
| 239 | - None, | ||
| 240 | - None, | ||
| 241 | - ) | ||
| 242 | - .await | ||
| 243 | - .unwrap(); | ||
| 244 | - let note = CourseNote::create( | ||
| 245 | - course.get_id(), | ||
| 246 | - &creator, | ||
| 247 | - CourseNoteTitle::try_new("a").unwrap(), | ||
| 248 | - CourseNoteContent::try_new("body").unwrap(), | ||
| 249 | - &db, | ||
| 250 | - ) | ||
| 251 | - .await | ||
| 252 | - .unwrap(); | ||
| 253 | - // What a handler snapshot would have seen... | ||
| 254 | - let early = CourseNoteFile::new( | ||
| 255 | - note.get_id(), | ||
| 256 | - FileName::try_new("early.pdf").unwrap(), | ||
| 257 | - FileContentType::try_new("application/pdf").unwrap(), | ||
| 258 | - 3, | ||
| 259 | - ) | ||
| 260 | - .insert(&db) | ||
| 261 | - .await | ||
| 262 | - .unwrap(); | ||
| 263 | - let (snapshot, _) = CourseNoteFile::list_for(note.get_id(), None, 0, &db) | ||
| 264 | - .await | ||
| 265 | - .unwrap(); | ||
| 266 | - assert_eq!(snapshot.len(), 1); | ||
| 267 | - // ...and the upload that races in after it. | ||
| 268 | - let late = CourseNoteFile::new( | ||
| 269 | - note.get_id(), | ||
| 270 | - FileName::try_new("late.pdf").unwrap(), | ||
| 271 | - FileContentType::try_new("application/pdf").unwrap(), | ||
| 272 | - 3, | ||
| 273 | - ) | ||
| 274 | - .insert(&db) | ||
| 275 | - .await | ||
| 276 | - .unwrap(); | ||
| 277 | - | ||
| 278 | - let (gone, files) = note.delete(&db).await.unwrap(); | ||
| 279 | - assert_eq!(gone.get_title().as_str(), "a"); | ||
| 280 | - let mut keys: Vec<_> = files | ||
| 281 | - .iter() | ||
| 282 | - .map(|file| file.get_id().key().to_string()) | ||
| 283 | - .collect(); | ||
| 284 | - keys.sort(); | ||
| 285 | - let mut want = vec![ | ||
| 286 | - early.get_id().key().to_string(), | ||
| 287 | - late.get_id().key().to_string(), | ||
| 288 | - ]; | ||
| 289 | - want.sort(); | ||
| 290 | - assert_eq!(keys, want); | ||
| 291 | - assert!( | ||
| 292 | - CourseNoteFile::list_for(gone.get_id(), None, 0, &db) | ||
| 293 | - .await | ||
| 294 | - .unwrap() | ||
| 295 | - .0 | ||
| 296 | - .is_empty() | ||
| 297 | - ); | ||
| 298 | - } | ||
| 299 | } | 112 | } |
src/domain/course_note_file.rsmodified+14 -255
| @@ -3,23 +3,18 @@ | |||
| 3 | //! [`crate::config::Config::files_path`], in a file named by this row's key — | 3 | //! [`crate::config::Config::files_path`], in a file named by this row's key — |
| 4 | //! a server-generated ULID, so no user input ever shapes a disk path. The web | 4 | //! a server-generated ULID, so no user input ever shapes a disk path. The web |
| 5 | //! layer owns the blob I/O and its ordering (blob before row on upload, row | 5 | //! layer owns the blob I/O and its ordering (blob before row on upload, row |
| 6 | -//! before blob on delete); this module owns the rows. `FileName` and | 6 | +//! before blob on delete); persistence lives in |
| 7 | -//! `FileContentType` are shared with [`crate::domain::note_file`] — same | 7 | +//! [`crate::db::course_note_file`]. `FileName` and `FileContentType` are |
| 8 | -//! validation, no reason to duplicate it. | 8 | +//! shared with [`crate::domain::note_file`] — same validation, no reason to |
| 9 | +//! duplicate it. | ||
| 9 | 10 | ||
| 10 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 11 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 11 | 12 | ||
| 12 | pub use crate::domain::note_file::{FileContentType, FileName}; | 13 | pub use crate::domain::note_file::{FileContentType, FileName}; |
| 13 | 14 | ||
| 14 | -use crate::constant::{ | 15 | +use crate::constant::COURSE_NOTE_FILE_TABLE; |
| 15 | - COURSE_NOTE_FILE_COUNT_FIELD, COURSE_NOTE_FILE_TABLE, MAX_COURSE_NOTE_FILES, | ||
| 16 | -}; | ||
| 17 | -use crate::database::Database; | ||
| 18 | -use crate::db::cap; | ||
| 19 | use crate::domain::course_note::CourseNoteId; | 16 | use crate::domain::course_note::CourseNoteId; |
| 20 | use crate::domain::monotonic_id::next_ulid; | 17 | use crate::domain::monotonic_id::next_ulid; |
| 21 | -use crate::db::page::PagedList; | ||
| 22 | -use crate::error::AppError; | ||
| 23 | 18 | ||
| 24 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 19 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 25 | pub struct CourseNoteFileId(RecordId); | 20 | pub struct CourseNoteFileId(RecordId); |
| @@ -27,8 +22,8 @@ pub struct CourseNoteFileId(RecordId); | |||
| 27 | impl CourseNoteFileId { | 22 | impl CourseNoteFileId { |
| 28 | /// Minted from the process-wide monotonic generator, not `Ulid::new()`: | 23 | /// Minted from the process-wide monotonic generator, not `Ulid::new()`: |
| 29 | /// a note's files list `id DESC` (newest first, | 24 | /// a note's files list `id DESC` (newest first, |
| 30 | - /// [`CourseNoteFile::list_for`]), and a random low half scrambles rows | 25 | + /// [`crate::db::course_note_file::list_for`]), and a random low half |
| 31 | - /// minted in the same millisecond. | 26 | + /// scrambles rows minted in the same millisecond. |
| 32 | pub fn generate() -> Self { | 27 | pub fn generate() -> Self { |
| 33 | Self(RecordId::new( | 28 | Self(RecordId::new( |
| 34 | COURSE_NOTE_FILE_TABLE, | 29 | COURSE_NOTE_FILE_TABLE, |
| @@ -54,17 +49,18 @@ impl CourseNoteFileId { | |||
| 54 | 49 | ||
| 55 | #[derive(Debug, Clone, SurrealValue)] | 50 | #[derive(Debug, Clone, SurrealValue)] |
| 56 | pub struct CourseNoteFile { | 51 | pub struct CourseNoteFile { |
| 57 | - id: CourseNoteFileId, | 52 | + pub(crate) id: CourseNoteFileId, |
| 58 | - course_note: CourseNoteId, | 53 | + pub(crate) course_note: CourseNoteId, |
| 59 | - name: FileName, | 54 | + pub(crate) name: FileName, |
| 60 | - content_type: FileContentType, | 55 | + pub(crate) content_type: FileContentType, |
| 61 | - size: i64, | 56 | + pub(crate) size: i64, |
| 62 | } | 57 | } |
| 63 | 58 | ||
| 64 | impl CourseNoteFile { | 59 | impl CourseNoteFile { |
| 65 | /// Assemble a new attachment row (id generated here) without persisting | 60 | /// Assemble a new attachment row (id generated here) without persisting |
| 66 | /// it. The caller writes the blob to disk under the fresh id first, then | 61 | /// it. The caller writes the blob to disk under the fresh id first, then |
| 67 | - /// calls [`Self::insert`] — so a stored row always points at a real blob. | 62 | + /// calls [`crate::db::course_note_file::insert`] — so a stored row always |
| 63 | + /// points at a real blob. | ||
| 68 | pub fn new( | 64 | pub fn new( |
| 69 | note: &CourseNoteId, | 65 | note: &CourseNoteId, |
| 70 | name: FileName, | 66 | name: FileName, |
| @@ -99,241 +95,4 @@ impl CourseNoteFile { | |||
| 99 | pub fn get_size(&self) -> i64 { | 95 | pub fn get_size(&self) -> i64 { |
| 100 | self.size | 96 | self.size |
| 101 | } | 97 | } |
| 102 | - | ||
| 103 | - /// Persist the row assembled by [`Self::new`], refusing once its note | ||
| 104 | - /// already holds [`MAX_COURSE_NOTE_FILES`]. The slot and the row are | ||
| 105 | - /// taken together by [`cap::claim_and_create`] on the note row — see | ||
| 106 | - /// [`crate::domain::note_file::NoteFile::insert`] for why that is the | ||
| 107 | - /// only guard a concurrent insert cannot outrun. | ||
| 108 | - pub async fn insert(self, db: &Database) -> Result<CourseNoteFile, AppError> { | ||
| 109 | - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber | ||
| 110 | - match cap::claim_and_create( | ||
| 111 | - &self.course_note.record(), | ||
| 112 | - COURSE_NOTE_FILE_COUNT_FIELD, | ||
| 113 | - MAX_COURSE_NOTE_FILES as i64, | ||
| 114 | - &self.id.record(), | ||
| 115 | - &self, | ||
| 116 | - db, | ||
| 117 | - ) | ||
| 118 | - .await? | ||
| 119 | - { | ||
| 120 | - cap::Claimed::Made(created) => Ok(created), | ||
| 121 | - // Also how a missing note reads: no note row means no slot to take. | ||
| 122 | - cap::Claimed::Full => Err(AppError::Conflict( | ||
| 123 | - "the course note already holds the maximum of 10 files — delete one first", | ||
| 124 | - )), | ||
| 125 | - // Unreachable: the id is a ULID this call just generated. | ||
| 126 | - cap::Claimed::Duplicate => Err(AppError::Internal( | ||
| 127 | - "failed to create course note file".into(), | ||
| 128 | - )), | ||
| 129 | - } | ||
| 130 | - } | ||
| 131 | - | ||
| 132 | - /// Read a file's row by id alone, for the callers that have no note in | ||
| 133 | - /// hand yet and reach the note *through* the file (the AI bridge's blob | ||
| 134 | - /// stream). A key from any other table simply reads as `None`, which is | ||
| 135 | - /// what keeps a personal note's file id unreachable here. | ||
| 136 | - pub async fn read( | ||
| 137 | - id: &CourseNoteFileId, | ||
| 138 | - db: &Database, | ||
| 139 | - ) -> Result<Option<CourseNoteFile>, AppError> { | ||
| 140 | - Ok(db.select(id.record()).await?) | ||
| 141 | - } | ||
| 142 | - | ||
| 143 | - /// Read a file's row only if it belongs to `note` — callers have already | ||
| 144 | - /// checked the note belongs to a course the caller may act on. | ||
| 145 | - pub async fn read_for( | ||
| 146 | - id: &CourseNoteFileId, | ||
| 147 | - note: &CourseNoteId, | ||
| 148 | - db: &Database, | ||
| 149 | - ) -> Result<Option<CourseNoteFile>, AppError> { | ||
| 150 | - let file: Option<CourseNoteFile> = db.select(id.record()).await?; | ||
| 151 | - Ok(file.filter(|file| &file.course_note == note)) | ||
| 152 | - } | ||
| 153 | - | ||
| 154 | - /// All of `note`'s attachment rows, newest first. | ||
| 155 | - pub async fn list_for( | ||
| 156 | - note: &CourseNoteId, | ||
| 157 | - limit: Option<i64>, | ||
| 158 | - offset: i64, | ||
| 159 | - db: &Database, | ||
| 160 | - ) -> Result<(Vec<CourseNoteFile>, i64), AppError> { | ||
| 161 | - PagedList::new( | ||
| 162 | - "course_note_file WHERE course_note = $note", | ||
| 163 | - "ORDER BY id DESC", | ||
| 164 | - ) | ||
| 165 | - .bind("note", note.record()) | ||
| 166 | - .run(limit, offset, db) | ||
| 167 | - .await | ||
| 168 | - } | ||
| 169 | - | ||
| 170 | - /// The blob names (record keys, since a file's blob is named by its own | ||
| 171 | - /// id) behind every note attachment of `course` — collected *before* the | ||
| 172 | - /// course-delete cascade wipes the rows. | ||
| 173 | - pub async fn file_keys_for_course( | ||
| 174 | - course: &crate::domain::course::CourseId, | ||
| 175 | - db: &Database, | ||
| 176 | - ) -> Result<Vec<String>, AppError> { | ||
| 177 | - let mut result = db | ||
| 178 | - .query( | ||
| 179 | - "SELECT VALUE id FROM course_note_file \ | ||
| 180 | - WHERE course_note IN (SELECT VALUE id FROM course_note WHERE course = $course)", | ||
| 181 | - ) | ||
| 182 | - .bind(("course", course.record())) | ||
| 183 | - .await? | ||
| 184 | - .check()?; | ||
| 185 | - Ok(result | ||
| 186 | - .take::<Vec<RecordId>>(0)? | ||
| 187 | - .into_iter() | ||
| 188 | - .map(|id| match id.key { | ||
| 189 | - RecordIdKey::String(key) => key, | ||
| 190 | - _ => String::new(), | ||
| 191 | - }) | ||
| 192 | - .collect()) | ||
| 193 | - } | ||
| 194 | - | ||
| 195 | - /// Delete the row and give its slot back in the same transaction — the | ||
| 196 | - /// note itself is untouched, so unlike the note-delete cascade this one | ||
| 197 | - /// has a counter to correct. | ||
| 198 | - pub async fn delete(self, db: &Database) -> Result<CourseNoteFile, AppError> { | ||
| 199 | - let mut result = db | ||
| 200 | - .query( | ||
| 201 | - "BEGIN TRANSACTION; | ||
| 202 | - LET $gone = (DELETE $id RETURN BEFORE); | ||
| 203 | - UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); | ||
| 204 | - RETURN $gone; | ||
| 205 | - COMMIT TRANSACTION;", | ||
| 206 | - ) | ||
| 207 | - .bind(("id", self.id.record())) | ||
| 208 | - .bind(("note", self.course_note.record())) | ||
| 209 | - .await? | ||
| 210 | - .check()?; | ||
| 211 | - result | ||
| 212 | - .take::<Vec<CourseNoteFile>>(3)? | ||
| 213 | - .into_iter() | ||
| 214 | - .next() | ||
| 215 | - .ok_or(AppError::NotFound) | ||
| 216 | - } | ||
| 217 | -} | ||
| 218 | - | ||
| 219 | -#[cfg(test)] | ||
| 220 | -mod tests { | ||
| 221 | - use super::*; | ||
| 222 | - use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; | ||
| 223 | - use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; | ||
| 224 | - | ||
| 225 | - async fn note_of(db: &Database, title: &str) -> CourseNote { | ||
| 226 | - let creator = crate::domain::user::UserId::generate(); | ||
| 227 | - let course = crate::db::course::create( | ||
| 228 | - db, | ||
| 229 | - &creator, | ||
| 230 | - CourseTitle::try_new("c").unwrap(), | ||
| 231 | - CourseDescription::try_new("").unwrap(), | ||
| 232 | - CourseKind::try_new("course").unwrap(), | ||
| 233 | - None, | ||
| 234 | - None, | ||
| 235 | - ) | ||
| 236 | - .await | ||
| 237 | - .unwrap(); | ||
| 238 | - CourseNote::create( | ||
| 239 | - course.get_id(), | ||
| 240 | - &creator, | ||
| 241 | - CourseNoteTitle::try_new(title).unwrap(), | ||
| 242 | - CourseNoteContent::try_new("body").unwrap(), | ||
| 243 | - db, | ||
| 244 | - ) | ||
| 245 | - .await | ||
| 246 | - .unwrap() | ||
| 247 | - } | ||
| 248 | - | ||
| 249 | - #[tokio::test] | ||
| 250 | - async fn rows_scope_to_their_note() { | ||
| 251 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 252 | - let note_a = note_of(&db, "a").await.get_id().clone(); | ||
| 253 | - let note_b = note_of(&db, "b").await.get_id().clone(); | ||
| 254 | - let file = CourseNoteFile::new( | ||
| 255 | - ¬e_a, | ||
| 256 | - FileName::try_new("plan.pdf").unwrap(), | ||
| 257 | - FileContentType::try_new("application/pdf").unwrap(), | ||
| 258 | - 3, | ||
| 259 | - ) | ||
| 260 | - .insert(&db) | ||
| 261 | - .await | ||
| 262 | - .unwrap(); | ||
| 263 | - | ||
| 264 | - let found = CourseNoteFile::read_for(file.get_id(), ¬e_a, &db) | ||
| 265 | - .await | ||
| 266 | - .unwrap(); | ||
| 267 | - assert_eq!(found.unwrap().get_name().as_str(), "plan.pdf"); | ||
| 268 | - assert!( | ||
| 269 | - CourseNoteFile::read_for(file.get_id(), ¬e_b, &db) | ||
| 270 | - .await | ||
| 271 | - .unwrap() | ||
| 272 | - .is_none() | ||
| 273 | - ); | ||
| 274 | - | ||
| 275 | - let listed = async |note: &CourseNoteId| { | ||
| 276 | - CourseNoteFile::list_for(note, None, 0, &db) | ||
| 277 | - .await | ||
| 278 | - .unwrap() | ||
| 279 | - .0 | ||
| 280 | - }; | ||
| 281 | - assert_eq!(listed(¬e_a).await.len(), 1); | ||
| 282 | - assert!(listed(¬e_b).await.is_empty()); | ||
| 283 | - | ||
| 284 | - file.delete(&db).await.unwrap(); | ||
| 285 | - assert!(listed(¬e_a).await.is_empty()); | ||
| 286 | - } | ||
| 287 | - | ||
| 288 | - /// The counter and the rows are written in one transaction, so the stored | ||
| 289 | - /// count must equal the stored rows — after a success *and* after the | ||
| 290 | - /// refusal that fills the cap, which must move neither. | ||
| 291 | - #[tokio::test] | ||
| 292 | - async fn counter_tracks_stored_rows() { | ||
| 293 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 294 | - let note = note_of(&db, "a").await.get_id().clone(); | ||
| 295 | - let stored_count = async |note: &CourseNoteId| -> i64 { | ||
| 296 | - db.query("SELECT VALUE file_count FROM $note") | ||
| 297 | - .bind(("note", note.record())) | ||
| 298 | - .await | ||
| 299 | - .unwrap() | ||
| 300 | - .take::<Vec<i64>>(0) | ||
| 301 | - .unwrap() | ||
| 302 | - .into_iter() | ||
| 303 | - .next() | ||
| 304 | - .unwrap_or(0) | ||
| 305 | - }; | ||
| 306 | - let add = async |note: &CourseNoteId| { | ||
| 307 | - CourseNoteFile::new( | ||
| 308 | - note, | ||
| 309 | - FileName::try_new("plan.pdf").unwrap(), | ||
| 310 | - FileContentType::try_new("application/pdf").unwrap(), | ||
| 311 | - 3, | ||
| 312 | - ) | ||
| 313 | - .insert(&db) | ||
| 314 | - .await | ||
| 315 | - }; | ||
| 316 | - | ||
| 317 | - for filled in 1..=MAX_COURSE_NOTE_FILES { | ||
| 318 | - add(¬e).await.unwrap(); | ||
| 319 | - assert_eq!(stored_count(¬e).await, filled as i64); | ||
| 320 | - assert_eq!( | ||
| 321 | - CourseNoteFile::list_for(¬e, None, 0, &db) | ||
| 322 | - .await | ||
| 323 | - .unwrap() | ||
| 324 | - .1, | ||
| 325 | - filled as i64 | ||
| 326 | - ); | ||
| 327 | - } | ||
| 328 | - | ||
| 329 | - assert!(matches!(add(¬e).await, Err(AppError::Conflict(_)))); | ||
| 330 | - assert_eq!(stored_count(¬e).await, MAX_COURSE_NOTE_FILES as i64); | ||
| 331 | - assert_eq!( | ||
| 332 | - CourseNoteFile::list_for(¬e, None, 0, &db) | ||
| 333 | - .await | ||
| 334 | - .unwrap() | ||
| 335 | - .1, | ||
| 336 | - MAX_COURSE_NOTE_FILES as i64 | ||
| 337 | - ); | ||
| 338 | - } | ||
| 339 | } | 98 | } |
src/domain/note_file.rsmodified+13 -198
| @@ -3,28 +3,23 @@ | |||
| 3 | //! [`crate::config::Config::files_path`], in a file named by this row's key — | 3 | //! [`crate::config::Config::files_path`], in a file named by this row's key — |
| 4 | //! a server-generated ULID, so no user input ever shapes a disk path. The web | 4 | //! a server-generated ULID, so no user input ever shapes a disk path. The web |
| 5 | //! layer owns the blob I/O and its ordering (blob before row on upload, row | 5 | //! layer owns the blob I/O and its ordering (blob before row on upload, row |
| 6 | -//! before blob on delete); this module owns the rows. | 6 | +//! before blob on delete); persistence lives in [`crate::db::note_file`]. |
| 7 | 7 | ||
| 8 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 8 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 9 | 9 | ||
| 10 | -use crate::constant::{ | 10 | +use crate::constant::{MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN, NOTE_FILE_TABLE}; |
| 11 | - MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN, MAX_NOTE_FILES, NOTE_FILE_COUNT_FIELD, | ||
| 12 | - NOTE_FILE_TABLE, | ||
| 13 | -}; | ||
| 14 | -use crate::database::Database; | ||
| 15 | -use crate::db::cap; | ||
| 16 | -use crate::db::page::PagedList; | ||
| 17 | use crate::domain::monotonic_id::next_ulid; | 11 | use crate::domain::monotonic_id::next_ulid; |
| 18 | use crate::domain::note::NoteId; | 12 | use crate::domain::note::NoteId; |
| 19 | -use crate::error::{AppError, ValidationError}; | 13 | +use crate::error::ValidationError; |
| 20 | 14 | ||
| 21 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 15 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 22 | pub struct NoteFileId(RecordId); | 16 | pub struct NoteFileId(RecordId); |
| 23 | 17 | ||
| 24 | impl NoteFileId { | 18 | impl NoteFileId { |
| 25 | /// Minted from the process-wide monotonic generator, not `Ulid::new()`: | 19 | /// Minted from the process-wide monotonic generator, not `Ulid::new()`: |
| 26 | - /// a note's files list `id DESC` (newest first, [`NoteFile::list_for_note`]), | 20 | + /// a note's files list `id DESC` (newest first, |
| 27 | - /// and a random low half scrambles rows minted in the same millisecond. | 21 | + /// [`crate::db::note_file::list_for`]), and a random low half scrambles |
| 22 | + /// rows minted in the same millisecond. | ||
| 28 | pub fn generate() -> Self { | 23 | pub fn generate() -> Self { |
| 29 | Self(RecordId::new(NOTE_FILE_TABLE, next_ulid().to_string())) | 24 | Self(RecordId::new(NOTE_FILE_TABLE, next_ulid().to_string())) |
| 30 | } | 25 | } |
| @@ -119,17 +114,18 @@ impl FileContentType { | |||
| 119 | 114 | ||
| 120 | #[derive(Debug, Clone, SurrealValue)] | 115 | #[derive(Debug, Clone, SurrealValue)] |
| 121 | pub struct NoteFile { | 116 | pub struct NoteFile { |
| 122 | - id: NoteFileId, | 117 | + pub(crate) id: NoteFileId, |
| 123 | - note: NoteId, | 118 | + pub(crate) note: NoteId, |
| 124 | - name: FileName, | 119 | + pub(crate) name: FileName, |
| 125 | - content_type: FileContentType, | 120 | + pub(crate) content_type: FileContentType, |
| 126 | - size: i64, | 121 | + pub(crate) size: i64, |
| 127 | } | 122 | } |
| 128 | 123 | ||
| 129 | impl NoteFile { | 124 | impl NoteFile { |
| 130 | /// Assemble a new attachment row (id generated here) without persisting | 125 | /// Assemble a new attachment row (id generated here) without persisting |
| 131 | /// it. The caller writes the blob to disk under the fresh id first, then | 126 | /// it. The caller writes the blob to disk under the fresh id first, then |
| 132 | - /// calls [`Self::insert`] — so a stored row always points at a real blob. | 127 | + /// calls [`crate::db::note_file::insert`] — so a stored row always points |
| 128 | + /// at a real blob. | ||
| 133 | pub fn new(note: &NoteId, name: FileName, content_type: FileContentType, size: i64) -> Self { | 129 | pub fn new(note: &NoteId, name: FileName, content_type: FileContentType, size: i64) -> Self { |
| 134 | Self { | 130 | Self { |
| 135 | id: NoteFileId::generate(), | 131 | id: NoteFileId::generate(), |
| @@ -155,83 +151,6 @@ impl NoteFile { | |||
| 155 | pub fn get_size(&self) -> i64 { | 151 | pub fn get_size(&self) -> i64 { |
| 156 | self.size | 152 | self.size |
| 157 | } | 153 | } |
| 158 | - | ||
| 159 | - /// Persist the row assembled by [`Self::new`], refusing once its note | ||
| 160 | - /// already holds [`MAX_NOTE_FILES`]. The slot and the row are taken together | ||
| 161 | - /// by [`cap::claim_and_create`] on the note row: a `BEGIN…COMMIT` around a | ||
| 162 | - /// count can't enforce the cap (SurrealDB doesn't conflict-check a | ||
| 163 | - /// cross-record count against a concurrent insert) and a process-wide mutex | ||
| 164 | - /// can't either, since it is released around the very round trip the insert | ||
| 165 | - /// races — a conditional single-record write can. Claiming in a *separate* | ||
| 166 | - /// query would enforce the cap but leak a slot on a crash between the two. | ||
| 167 | - pub async fn insert(self, db: &Database) -> Result<NoteFile, AppError> { | ||
| 168 | - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber | ||
| 169 | - match cap::claim_and_create( | ||
| 170 | - &self.note.record(), | ||
| 171 | - NOTE_FILE_COUNT_FIELD, | ||
| 172 | - MAX_NOTE_FILES as i64, | ||
| 173 | - &self.id.record(), | ||
| 174 | - &self, | ||
| 175 | - db, | ||
| 176 | - ) | ||
| 177 | - .await? | ||
| 178 | - { | ||
| 179 | - cap::Claimed::Made(created) => Ok(created), | ||
| 180 | - // Also how a missing note reads: no note row means no slot to take. | ||
| 181 | - cap::Claimed::Full => Err(AppError::Conflict( | ||
| 182 | - "the note already holds the maximum of 10 files — delete one first", | ||
| 183 | - )), | ||
| 184 | - // Unreachable: the id is a ULID this call just generated. | ||
| 185 | - cap::Claimed::Duplicate => Err(AppError::Internal("failed to create note file".into())), | ||
| 186 | - } | ||
| 187 | - } | ||
| 188 | - | ||
| 189 | - /// Read a file's row only if it belongs to `note` — callers have already | ||
| 190 | - /// checked the note belongs to the requesting user. | ||
| 191 | - pub async fn read_for( | ||
| 192 | - id: &NoteFileId, | ||
| 193 | - note: &NoteId, | ||
| 194 | - db: &Database, | ||
| 195 | - ) -> Result<Option<NoteFile>, AppError> { | ||
| 196 | - let file: Option<NoteFile> = db.select(id.record()).await?; | ||
| 197 | - Ok(file.filter(|file| &file.note == note)) | ||
| 198 | - } | ||
| 199 | - | ||
| 200 | - /// All of `note`'s attachment rows, newest first. | ||
| 201 | - pub async fn list_for( | ||
| 202 | - note: &NoteId, | ||
| 203 | - limit: Option<i64>, | ||
| 204 | - offset: i64, | ||
| 205 | - db: &Database, | ||
| 206 | - ) -> Result<(Vec<NoteFile>, i64), AppError> { | ||
| 207 | - PagedList::new("note_file WHERE note = $note", "ORDER BY id DESC") | ||
| 208 | - .bind("note", note.record()) | ||
| 209 | - .run(limit, offset, db) | ||
| 210 | - .await | ||
| 211 | - } | ||
| 212 | - | ||
| 213 | - /// Delete the row and give its slot back in the same transaction — the note | ||
| 214 | - /// itself is untouched, so unlike the note-delete cascade this one has a | ||
| 215 | - /// counter to correct. (Deleting a *note* takes its counter with it.) | ||
| 216 | - pub async fn delete(self, db: &Database) -> Result<NoteFile, AppError> { | ||
| 217 | - let mut result = db | ||
| 218 | - .query( | ||
| 219 | - "BEGIN TRANSACTION; | ||
| 220 | - LET $gone = (DELETE $id RETURN BEFORE); | ||
| 221 | - UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); | ||
| 222 | - RETURN $gone; | ||
| 223 | - COMMIT TRANSACTION;", | ||
| 224 | - ) | ||
| 225 | - .bind(("id", self.id.record())) | ||
| 226 | - .bind(("note", self.note.record())) | ||
| 227 | - .await? | ||
| 228 | - .check()?; | ||
| 229 | - result | ||
| 230 | - .take::<Vec<NoteFile>>(3)? | ||
| 231 | - .into_iter() | ||
| 232 | - .next() | ||
| 233 | - .ok_or(AppError::NotFound) | ||
| 234 | - } | ||
| 235 | } | 154 | } |
| 236 | 155 | ||
| 237 | #[cfg(test)] | 156 | #[cfg(test)] |
| @@ -271,108 +190,4 @@ mod tests { | |||
| 271 | assert!(FileContentType::try_new("appli¢ation/pdf").is_err()); | 190 | assert!(FileContentType::try_new("appli¢ation/pdf").is_err()); |
| 272 | assert!(FileContentType::try_new("a\r\nb").is_err()); | 191 | assert!(FileContentType::try_new("a\r\nb").is_err()); |
| 273 | } | 192 | } |
| 274 | - | ||
| 275 | - #[tokio::test] | ||
| 276 | - async fn rows_scope_to_their_note() { | ||
| 277 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 278 | - // Real note rows: the cap counter lives on the note, so an insert whose | ||
| 279 | - // note does not exist has no slot to take (a 409, like a full note). | ||
| 280 | - let owner = crate::domain::user::UserId::generate(); | ||
| 281 | - let note_of = async |title: &str| { | ||
| 282 | - crate::db::note::create( | ||
| 283 | - &db, | ||
| 284 | - &owner, | ||
| 285 | - crate::domain::note::NoteTitle::try_new(title).unwrap(), | ||
| 286 | - crate::domain::note::NoteContent::try_new("body").unwrap(), | ||
| 287 | - ) | ||
| 288 | - .await | ||
| 289 | - .unwrap() | ||
| 290 | - }; | ||
| 291 | - let note_a = note_of("a").await.get_id().clone(); | ||
| 292 | - let note_b = note_of("b").await.get_id().clone(); | ||
| 293 | - let file = NoteFile::new( | ||
| 294 | - ¬e_a, | ||
| 295 | - FileName::try_new("plan.pdf").unwrap(), | ||
| 296 | - FileContentType::try_new("application/pdf").unwrap(), | ||
| 297 | - 3, | ||
| 298 | - ) | ||
| 299 | - .insert(&db) | ||
| 300 | - .await | ||
| 301 | - .unwrap(); | ||
| 302 | - | ||
| 303 | - // Readable under its own note, invisible under another. | ||
| 304 | - let found = NoteFile::read_for(file.get_id(), ¬e_a, &db) | ||
| 305 | - .await | ||
| 306 | - .unwrap(); | ||
| 307 | - assert_eq!(found.unwrap().get_name().as_str(), "plan.pdf"); | ||
| 308 | - assert!( | ||
| 309 | - NoteFile::read_for(file.get_id(), ¬e_b, &db) | ||
| 310 | - .await | ||
| 311 | - .unwrap() | ||
| 312 | - .is_none() | ||
| 313 | - ); | ||
| 314 | - | ||
| 315 | - let listed = async |note: &NoteId| NoteFile::list_for(note, None, 0, &db).await.unwrap().0; | ||
| 316 | - assert_eq!(listed(¬e_a).await.len(), 1); | ||
| 317 | - assert!(listed(¬e_b).await.is_empty()); | ||
| 318 | - | ||
| 319 | - file.delete(&db).await.unwrap(); | ||
| 320 | - assert!(listed(¬e_a).await.is_empty()); | ||
| 321 | - } | ||
| 322 | - | ||
| 323 | - /// The counter and the rows are written in one transaction, so the stored | ||
| 324 | - /// count must equal the stored rows — after a success *and* after the | ||
| 325 | - /// refusal that fills the cap, which must move neither. | ||
| 326 | - #[tokio::test] | ||
| 327 | - async fn counter_tracks_stored_rows() { | ||
| 328 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 329 | - let note = crate::db::note::create( | ||
| 330 | - &db, | ||
| 331 | - &crate::domain::user::UserId::generate(), | ||
| 332 | - crate::domain::note::NoteTitle::try_new("a").unwrap(), | ||
| 333 | - crate::domain::note::NoteContent::try_new("body").unwrap(), | ||
| 334 | - ) | ||
| 335 | - .await | ||
| 336 | - .unwrap() | ||
| 337 | - .get_id() | ||
| 338 | - .clone(); | ||
| 339 | - let stored_count = async |note: &NoteId| -> i64 { | ||
| 340 | - db.query("SELECT VALUE file_count FROM $note") | ||
| 341 | - .bind(("note", note.record())) | ||
| 342 | - .await | ||
| 343 | - .unwrap() | ||
| 344 | - .take::<Vec<i64>>(0) | ||
| 345 | - .unwrap() | ||
| 346 | - .into_iter() | ||
| 347 | - .next() | ||
| 348 | - .unwrap_or(0) | ||
| 349 | - }; | ||
| 350 | - let add = async |note: &NoteId| { | ||
| 351 | - NoteFile::new( | ||
| 352 | - note, | ||
| 353 | - FileName::try_new("plan.pdf").unwrap(), | ||
| 354 | - FileContentType::try_new("application/pdf").unwrap(), | ||
| 355 | - 3, | ||
| 356 | - ) | ||
| 357 | - .insert(&db) | ||
| 358 | - .await | ||
| 359 | - }; | ||
| 360 | - | ||
| 361 | - for filled in 1..=MAX_NOTE_FILES { | ||
| 362 | - add(¬e).await.unwrap(); | ||
| 363 | - assert_eq!(stored_count(¬e).await, filled as i64); | ||
| 364 | - assert_eq!( | ||
| 365 | - NoteFile::list_for(¬e, None, 0, &db).await.unwrap().1, | ||
| 366 | - filled as i64 | ||
| 367 | - ); | ||
| 368 | - } | ||
| 369 | - | ||
| 370 | - // At the cap: the refusal writes nothing, counter included. | ||
| 371 | - assert!(matches!(add(¬e).await, Err(AppError::Conflict(_)))); | ||
| 372 | - assert_eq!(stored_count(¬e).await, MAX_NOTE_FILES as i64); | ||
| 373 | - assert_eq!( | ||
| 374 | - NoteFile::list_for(¬e, None, 0, &db).await.unwrap().1, | ||
| 375 | - MAX_NOTE_FILES as i64 | ||
| 376 | - ); | ||
| 377 | - } | ||
| 378 | } | 193 | } |
src/service/board.rsadded+291 -0
| @@ -0,0 +1,291 @@ | |||
| 1 | +//! Board workflows: the roster gates the REST surface drives and the lock | ||
| 2 | +//! that serializes every read-modify-write of a board's `participants` array. | ||
| 3 | +//! The queries live in [`crate::db::board`]; the room's WebSocket keeps its | ||
| 4 | +//! own binding policy in [`crate::web::board_ws`], reading through here. | ||
| 5 | + | ||
| 6 | +use tokio::sync::Mutex; | ||
| 7 | + | ||
| 8 | +use crate::constant::MAX_BOARD_PARTICIPANTS; | ||
| 9 | +use crate::database::Database; | ||
| 10 | +use crate::db::board; | ||
| 11 | +use crate::domain::board::{Board, BoardId, BoardTitle}; | ||
| 12 | +use crate::domain::role::Role; | ||
| 13 | +use crate::domain::user::{User, UserId}; | ||
| 14 | +use crate::error::{AppError, ValidationError}; | ||
| 15 | + | ||
| 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 | ||
| 43 | +/// on it. Every route starts here, so existence never leaks. | ||
| 44 | +/// | ||
| 45 | +/// A `parent` is treated as an outsider rather than refused with a 403: the | ||
| 46 | +/// role is barred from the whiteboard entirely, and a 403 would confirm the | ||
| 47 | +/// board exists. [`resolve_participants`] keeps parents off every roster, so | ||
| 48 | +/// this arm only ever fires for a row written before that rule. | ||
| 49 | +pub async fn board_for(id: &str, user: &User, db: &Database) -> Result<Board, AppError> { | ||
| 50 | + let board = board::read(db, &BoardId::from_key(id)) | ||
| 51 | + .await? | ||
| 52 | + .ok_or(AppError::NotFound)?; | ||
| 53 | + if !user.get_role().at_least(Role::Student) || !board.is_participant(user.get_id()) { | ||
| 54 | + return Err(AppError::NotFound); | ||
| 55 | + } | ||
| 56 | + Ok(board) | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// The creator-only gate. A 403, never a 404: the caller reached it through | ||
| 60 | +/// [`board_for`], so they are a participant and the board's existence is | ||
| 61 | +/// already theirs to see. | ||
| 62 | +pub fn ensure_creator(board: &Board, user: &User) -> Result<(), AppError> { | ||
| 63 | + if !board.is_creator(user.get_id()) { | ||
| 64 | + return Err(AppError::Forbidden( | ||
| 65 | + "only the board's creator can clear, lock, close or delete it", | ||
| 66 | + )); | ||
| 67 | + } | ||
| 68 | + Ok(()) | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +/// The invite list off the wire: deduped, capped, and every id resolved against | ||
| 72 | +/// a real user. The cap is applied *before* the lookup (the domain caps too, but | ||
| 73 | +/// only after the read would already have run), and an unknown id is a 400 | ||
| 74 | +/// rather than a silently dropped invitation. | ||
| 75 | +/// | ||
| 76 | +/// The eligible set is fetched in **one** read, not one per id. That was a | ||
| 77 | +/// per-id loop while a roster could only be typed by hand and so was a handful | ||
| 78 | +/// of ids; bulk invite made a full board an ordinary thing to own, and a | ||
| 79 | +/// read-modify-write PATCH of one — read the board, drop a name, send the rest | ||
| 80 | +/// back — is the common client shape, so the loop had become | ||
| 81 | +/// `max_participants` sequential round trips on a routine edit. | ||
| 82 | +/// | ||
| 83 | +/// A `parent` is refused here, and that is the cut that keeps the role off the | ||
| 84 | +/// whiteboard: never on a roster means [`board_for`] and the room's door already | ||
| 85 | +/// answer 404 on every id-scoped route, and no socket can ever open. | ||
| 86 | +/// | ||
| 87 | +/// The creator is a participant by construction, so they are neither injected | ||
| 88 | +/// into the list nor rejected from it. | ||
| 89 | +/// | ||
| 90 | +/// `current` is the board's roster as it stands (empty when a board is being | ||
| 91 | +/// created), and it is what makes a read-modify-write PATCH survive: an id | ||
| 92 | +/// *already* on the board that no longer qualifies — demoted, or deleted | ||
| 93 | +/// outright — is dropped silently instead of failing the whole call, so a | ||
| 94 | +/// creator echoing back the roster they were just served gets a 200 and a | ||
| 95 | +/// cleaned list. An id that is **new** to the board still 400s; without that | ||
| 96 | +/// split the drop would be a hole letting a caller seed a roster with anyone. | ||
| 97 | +pub async fn resolve_participants( | ||
| 98 | + ids: Option<Vec<String>>, | ||
| 99 | + current: &[UserId], | ||
| 100 | + db: &Database, | ||
| 101 | +) -> Result<Vec<UserId>, AppError> { | ||
| 102 | + let Some(mut ids) = ids else { | ||
| 103 | + return Ok(Vec::new()); | ||
| 104 | + }; | ||
| 105 | + ids.sort(); | ||
| 106 | + ids.dedup(); | ||
| 107 | + if ids.len() > MAX_BOARD_PARTICIPANTS { | ||
| 108 | + return Err(AppError::Validation(ValidationError::TooLong { | ||
| 109 | + field: "participants", | ||
| 110 | + max: MAX_BOARD_PARTICIPANTS, | ||
| 111 | + got: ids.len(), | ||
| 112 | + })); | ||
| 113 | + } | ||
| 114 | + let wanted: Vec<UserId> = ids.iter().map(|id| UserId::from_key(id)).collect(); | ||
| 115 | + // Absent from this list means "no such user, or below `student`" — the two | ||
| 116 | + // are one case here, and telling them apart is what the caller must not be | ||
| 117 | + // able to do anyway. | ||
| 118 | + let eligible: Vec<UserId> = crate::service::user::list_by_ids(db, &wanted) | ||
| 119 | + .await? | ||
| 120 | + .iter() | ||
| 121 | + .filter(|found| found.get_role().at_least(Role::Student)) | ||
| 122 | + .map(|found| found.get_id().clone()) | ||
| 123 | + .collect(); | ||
| 124 | + let mut users = Vec::with_capacity(wanted.len()); | ||
| 125 | + for user in wanted { | ||
| 126 | + if !eligible.contains(&user) { | ||
| 127 | + if current.contains(&user) { | ||
| 128 | + continue; | ||
| 129 | + } | ||
| 130 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 131 | + field: "participants", | ||
| 132 | + reason: "every participant must be an existing user of at least the student role", | ||
| 133 | + })); | ||
| 134 | + } | ||
| 135 | + users.push(user); | ||
| 136 | + } | ||
| 137 | + Ok(users) | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +/// Union a bulk-invite source's resolved ids into a board's roster: everyone | ||
| 141 | +/// the source names who still resolves to an eligible user is **added**, | ||
| 142 | +/// nobody is ever removed by it. The filters are silent on purpose — a source | ||
| 143 | +/// is a whole group, and one member who has left or was never eligible must | ||
| 144 | +/// not fail the invite for the other twenty-nine. The cap is | ||
| 145 | +/// **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. | ||
| 147 | +/// | ||
| 148 | +/// The caller holds [`BOARD_ROSTER_LOCK`] across the board read this `board` | ||
| 149 | +/// came from and this write — together they are the read-modify-write the | ||
| 150 | +/// lock exists for. | ||
| 151 | +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 — | ||
| 153 | + // 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. | ||
| 155 | + let mut roster = board.get_participants().to_vec(); | ||
| 156 | + for candidate in crate::service::user::list_by_ids(db, &invited).await? { | ||
| 157 | + if !candidate.get_role().at_least(Role::Student) { | ||
| 158 | + continue; | ||
| 159 | + } | ||
| 160 | + // The creator is a participant by construction and never sits in the | ||
| 161 | + // array; adding them there would spend a seat on someone who already | ||
| 162 | + // has access. | ||
| 163 | + if candidate.get_id() == board.get_creator() || roster.contains(candidate.get_id()) { | ||
| 164 | + continue; | ||
| 165 | + } | ||
| 166 | + roster.push(candidate.get_id().clone()); | ||
| 167 | + } | ||
| 168 | + | ||
| 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 | ||
| 176 | + // 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. | ||
| 178 | + board::set_participants(db, board, roster).await | ||
| 179 | +} | ||
| 180 | + | ||
| 181 | +pub async fn create( | ||
| 182 | + db: &Database, | ||
| 183 | + creator: &UserId, | ||
| 184 | + title: BoardTitle, | ||
| 185 | + participants: Vec<UserId>, | ||
| 186 | +) -> Result<Board, AppError> { | ||
| 187 | + board::create(db, creator, title, participants).await | ||
| 188 | +} | ||
| 189 | + | ||
| 190 | +pub async fn read(db: &Database, id: &BoardId) -> Result<Option<Board>, AppError> { | ||
| 191 | + board::read(db, id).await | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +pub async fn list_for_user( | ||
| 195 | + db: &Database, | ||
| 196 | + user: &UserId, | ||
| 197 | + open: Option<bool>, | ||
| 198 | + limit: Option<i64>, | ||
| 199 | + offset: i64, | ||
| 200 | +) -> Result<(Vec<Board>, i64), AppError> { | ||
| 201 | + board::list_for_user(db, user, open, limit, offset).await | ||
| 202 | +} | ||
| 203 | + | ||
| 204 | +pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result<Board, AppError> { | ||
| 205 | + board::set_title(db, board, title).await | ||
| 206 | +} | ||
| 207 | + | ||
| 208 | +pub async fn set_participants( | ||
| 209 | + db: &Database, | ||
| 210 | + board: &Board, | ||
| 211 | + participants: Vec<UserId>, | ||
| 212 | +) -> Result<Board, AppError> { | ||
| 213 | + board::set_participants(db, board, participants).await | ||
| 214 | +} | ||
| 215 | + | ||
| 216 | +pub async fn set_locked( | ||
| 217 | + db: &Database, | ||
| 218 | + board: &Board, | ||
| 219 | + locked: bool, | ||
| 220 | + by: &UserId, | ||
| 221 | +) -> Result<Board, AppError> { | ||
| 222 | + board::set_locked(db, board, locked, by).await | ||
| 223 | +} | ||
| 224 | + | ||
| 225 | +pub async fn close(db: &Database, board: &Board) -> Result<Board, AppError> { | ||
| 226 | + board::close(db, board).await | ||
| 227 | +} | ||
| 228 | + | ||
| 229 | +/// Delete the board and its whole stroke history; also frees the creator's | ||
| 230 | +/// board seat. | ||
| 231 | +pub async fn delete(db: &Database, board: Board) -> Result<Board, AppError> { | ||
| 232 | + board::delete(db, board).await | ||
| 233 | +} | ||
| 234 | + | ||
| 235 | +#[cfg(test)] | ||
| 236 | +mod tests { | ||
| 237 | + use super::*; | ||
| 238 | + | ||
| 239 | + /// The security boundary of the gates this module owns, in one test: an | ||
| 240 | + /// outsider is told the board does not exist, an insider without rights is | ||
| 241 | + /// told it is not theirs to command. Swapping those two leaks the school's | ||
| 242 | + /// board list on one side and hides a rendered board from its own | ||
| 243 | + /// participant on the other. | ||
| 244 | + #[tokio::test] | ||
| 245 | + async fn an_outsider_gets_404_and_a_participant_gets_403() { | ||
| 246 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 247 | + db.query( | ||
| 248 | + "CREATE user:c SET username = 'c', password_hash = 'x'; | ||
| 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 | + } | ||
| 291 | +} | ||
src/service/board_stroke.rsadded+58 -0
| @@ -0,0 +1,58 @@ | |||
| 1 | +//! Board-stroke workflows: the drawing, clearing and replay paths the REST | ||
| 2 | +//! surface and the board room drive. The queries live in | ||
| 3 | +//! [`crate::db::board_stroke`]; the room's publish ordering stays in | ||
| 4 | +//! [`crate::web::board_ws`]. | ||
| 5 | + | ||
| 6 | +use crate::database::Database; | ||
| 7 | +use crate::db::board_stroke; | ||
| 8 | +use crate::domain::board::BoardId; | ||
| 9 | +use crate::domain::board_stroke::BoardStroke; | ||
| 10 | +use crate::domain::user::UserId; | ||
| 11 | +use crate::error::AppError; | ||
| 12 | + | ||
| 13 | +/// Append one mark to the board's current `epoch`; the conditional claim in | ||
| 14 | +/// the db layer refuses a full canvas, a locked or closed board, and a stale | ||
| 15 | +/// epoch. | ||
| 16 | +pub async fn append( | ||
| 17 | + db: &Database, | ||
| 18 | + board: &BoardId, | ||
| 19 | + author: &UserId, | ||
| 20 | + payload: &str, | ||
| 21 | + epoch: i64, | ||
| 22 | +) -> Result<BoardStroke, AppError> { | ||
| 23 | + board_stroke::append(db, board, author, payload, epoch).await | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +/// End the current epoch — creator-only upstream: the canvas empties, the | ||
| 27 | +/// history does not. | ||
| 28 | +pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result<BoardStroke, AppError> { | ||
| 29 | + board_stroke::clear(db, board, by).await | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +/// The current epoch's marks, in mint order, one chunk at a time (`after` is | ||
| 33 | +/// the last stroke already drawn). | ||
| 34 | +pub async fn replay_current( | ||
| 35 | + db: &Database, | ||
| 36 | + board: &BoardId, | ||
| 37 | + epoch: i64, | ||
| 38 | + after: Option<&str>, | ||
| 39 | +) -> Result<Vec<BoardStroke>, AppError> { | ||
| 40 | + board_stroke::replay_current(db, board, epoch, after).await | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +/// The whole log, oldest first; `marks_only` drops the `clear` markers. | ||
| 44 | +pub async fn history( | ||
| 45 | + db: &Database, | ||
| 46 | + board: &BoardId, | ||
| 47 | + epoch: Option<i64>, | ||
| 48 | + marks_only: bool, | ||
| 49 | + limit: Option<i64>, | ||
| 50 | + offset: i64, | ||
| 51 | +) -> Result<(Vec<BoardStroke>, i64), AppError> { | ||
| 52 | + board_stroke::history(db, board, epoch, marks_only, limit, offset).await | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +/// The epoch index: every `clear` marker this board has, oldest first. | ||
| 56 | +pub async fn epochs(db: &Database, board: &BoardId) -> Result<Vec<BoardStroke>, AppError> { | ||
| 57 | + board_stroke::epochs(db, board).await | ||
| 58 | +} | ||
src/service/course.rsmodified+2 -2
| @@ -7,7 +7,6 @@ | |||
| 7 | use crate::database::Database; | 7 | use crate::database::Database; |
| 8 | use crate::db::course; | 8 | use crate::db::course; |
| 9 | use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; | 9 | use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; |
| 10 | -use crate::domain::course_note_file::CourseNoteFile; | ||
| 11 | use crate::domain::role::Role; | 10 | use crate::domain::role::Role; |
| 12 | use crate::domain::term::TermId; | 11 | use crate::domain::term::TermId; |
| 13 | use crate::domain::user::UserId; | 12 | use crate::domain::user::UserId; |
| @@ -168,7 +167,8 @@ pub async fn delete(db: &Database, course: &Course) -> Result<DeleteOutcome, App | |||
| 168 | crate::db::answer_image::file_keys_for_course(db, course.get_id()).await?; | 167 | crate::db::answer_image::file_keys_for_course(db, course.get_id()).await?; |
| 169 | let homework_files = | 168 | let homework_files = |
| 170 | crate::db::homework_file::file_keys_for_course(db, course.get_id()).await?; | 169 | crate::db::homework_file::file_keys_for_course(db, course.get_id()).await?; |
| 171 | - let course_note_files = CourseNoteFile::file_keys_for_course(course.get_id(), db).await?; | 170 | + let course_note_files = |
| 171 | + crate::db::course_note_file::file_keys_for_course(db, course.get_id()).await?; | ||
| 172 | let deleted = course::delete(db, course.clone()).await?; | 172 | let deleted = course::delete(db, course.clone()).await?; |
| 173 | Ok(DeleteOutcome { | 173 | Ok(DeleteOutcome { |
| 174 | deleted, | 174 | deleted, |
src/service/course_note.rsadded+55 -0
| @@ -0,0 +1,55 @@ | |||
| 1 | +//! Course-note workflows: the create/read/list/update/delete paths the | ||
| 2 | +//! course-notes surface drives. The queries live in | ||
| 3 | +//! [`crate::db::course_note`]; blob unlinking and the AI re-index stay in the | ||
| 4 | +//! web layer. | ||
| 5 | + | ||
| 6 | +use crate::database::Database; | ||
| 7 | +use crate::db::course_note; | ||
| 8 | +use crate::domain::course::CourseId; | ||
| 9 | +use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteId, CourseNoteTitle}; | ||
| 10 | +use crate::domain::course_note_file::CourseNoteFile; | ||
| 11 | +use crate::domain::user::UserId; | ||
| 12 | +use crate::error::AppError; | ||
| 13 | + | ||
| 14 | +pub async fn create( | ||
| 15 | + db: &Database, | ||
| 16 | + course: &CourseId, | ||
| 17 | + author: &UserId, | ||
| 18 | + title: CourseNoteTitle, | ||
| 19 | + content: CourseNoteContent, | ||
| 20 | +) -> Result<CourseNote, AppError> { | ||
| 21 | + course_note::create(db, course, author, title, content).await | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +pub async fn read(db: &Database, id: &CourseNoteId) -> Result<Option<CourseNote>, AppError> { | ||
| 25 | + course_note::read(db, id).await | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +pub async fn list_for_course( | ||
| 29 | + db: &Database, | ||
| 30 | + course: &CourseId, | ||
| 31 | + limit: Option<i64>, | ||
| 32 | + offset: i64, | ||
| 33 | +) -> Result<(Vec<CourseNote>, i64), AppError> { | ||
| 34 | + course_note::list_for_course(db, course, limit, offset).await | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +/// Only what the request carried is written: an omitted field (`None`) is | ||
| 38 | +/// not stored at all, so a concurrent edit of the other field survives. | ||
| 39 | +pub async fn update( | ||
| 40 | + db: &Database, | ||
| 41 | + note: CourseNote, | ||
| 42 | + title: Option<CourseNoteTitle>, | ||
| 43 | + content: Option<CourseNoteContent>, | ||
| 44 | +) -> Result<CourseNote, AppError> { | ||
| 45 | + course_note::update(db, note, title, content).await | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +/// Delete the note and cascade its attachment rows; the returned files are | ||
| 49 | +/// exactly whose blobs the caller may unlink. | ||
| 50 | +pub async fn delete( | ||
| 51 | + db: &Database, | ||
| 52 | + note: CourseNote, | ||
| 53 | +) -> Result<(CourseNote, Vec<CourseNoteFile>), AppError> { | ||
| 54 | + course_note::delete(db, note).await | ||
| 55 | +} | ||
src/service/course_note_file.rsadded+48 -0
| @@ -0,0 +1,48 @@ | |||
| 1 | +//! Course-note-file workflows: the attachment paths the course-notes surface | ||
| 2 | +//! drives. The queries live in [`crate::db::course_note_file`]; blob | ||
| 3 | +//! unlinking and the AI re-index stay in the web layer. | ||
| 4 | + | ||
| 5 | +use crate::database::Database; | ||
| 6 | +use crate::db::course_note_file; | ||
| 7 | +use crate::domain::course_note::CourseNoteId; | ||
| 8 | +use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; | ||
| 9 | +use crate::error::AppError; | ||
| 10 | + | ||
| 11 | +/// Persist a row assembled by [`CourseNoteFile::new`]; refuses with a | ||
| 12 | +/// conflict once the note holds its cap. | ||
| 13 | +pub async fn insert(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFile, AppError> { | ||
| 14 | + course_note_file::insert(db, file).await | ||
| 15 | +} | ||
| 16 | + | ||
| 17 | +/// Read a file's row by id alone — the AI bridge reaches the note *through* | ||
| 18 | +/// the file, so no note scoping happens here. | ||
| 19 | +pub async fn read( | ||
| 20 | + db: &Database, | ||
| 21 | + id: &CourseNoteFileId, | ||
| 22 | +) -> Result<Option<CourseNoteFile>, AppError> { | ||
| 23 | + course_note_file::read(db, id).await | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +/// Read a file's row only if it belongs to `note`. | ||
| 27 | +pub async fn read_for( | ||
| 28 | + db: &Database, | ||
| 29 | + id: &CourseNoteFileId, | ||
| 30 | + note: &CourseNoteId, | ||
| 31 | +) -> Result<Option<CourseNoteFile>, AppError> { | ||
| 32 | + course_note_file::read_for(db, id, note).await | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +pub async fn list_for( | ||
| 36 | + db: &Database, | ||
| 37 | + note: &CourseNoteId, | ||
| 38 | + limit: Option<i64>, | ||
| 39 | + offset: i64, | ||
| 40 | +) -> Result<(Vec<CourseNoteFile>, i64), AppError> { | ||
| 41 | + course_note_file::list_for(db, note, limit, offset).await | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +/// Delete the row and hand its slot back in the same transaction; the | ||
| 45 | +/// returned row is exactly whose blob the caller may unlink. | ||
| 46 | +pub async fn delete(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFile, AppError> { | ||
| 47 | + course_note_file::delete(db, file).await | ||
| 48 | +} | ||
src/service/mod.rsmodified+5 -0
| @@ -7,6 +7,8 @@ pub mod attendance; | |||
| 7 | pub mod badge; | 7 | pub mod badge; |
| 8 | pub mod bank_question; | 8 | pub mod bank_question; |
| 9 | pub mod bank_question_image; | 9 | pub mod bank_question_image; |
| 10 | +pub mod board; | ||
| 11 | +pub mod board_stroke; | ||
| 10 | pub mod builder; | 12 | pub mod builder; |
| 11 | pub mod chatbot_message; | 13 | pub mod chatbot_message; |
| 12 | pub mod chatbot_thread; | 14 | pub mod chatbot_thread; |
| @@ -15,6 +17,8 @@ pub mod class_course; | |||
| 15 | pub mod class_group; | 17 | pub mod class_group; |
| 16 | pub mod class_member; | 18 | pub mod class_member; |
| 17 | pub mod course; | 19 | pub mod course; |
| 20 | +pub mod course_note; | ||
| 21 | +pub mod course_note_file; | ||
| 18 | pub mod course_session; | 22 | pub mod course_session; |
| 19 | pub mod dietary_profile; | 23 | pub mod dietary_profile; |
| 20 | pub mod enrollment; | 24 | pub mod enrollment; |
| @@ -36,6 +40,7 @@ pub mod meal_ledger; | |||
| 36 | pub mod menu; | 40 | pub mod menu; |
| 37 | pub mod message; | 41 | pub mod message; |
| 38 | pub mod note; | 42 | pub mod note; |
| 43 | +pub mod note_file; | ||
| 39 | pub mod parent_link; | 44 | pub mod parent_link; |
| 40 | pub mod payment_ledger; | 45 | pub mod payment_ledger; |
| 41 | pub mod pomodoro; | 46 | pub mod pomodoro; |
src/service/note_file.rsadded+39 -0
| @@ -0,0 +1,39 @@ | |||
| 1 | +//! Note-file workflows: the attachment paths the notes surface drives. The | ||
| 2 | +//! queries live in [`crate::db::note_file`]; blob unlinking stays in the web | ||
| 3 | +//! layer. | ||
| 4 | + | ||
| 5 | +use crate::database::Database; | ||
| 6 | +use crate::db::note_file; | ||
| 7 | +use crate::domain::note::NoteId; | ||
| 8 | +use crate::domain::note_file::{NoteFile, NoteFileId}; | ||
| 9 | +use crate::error::AppError; | ||
| 10 | + | ||
| 11 | +/// Persist a row assembled by [`NoteFile::new`]; refuses with a conflict once | ||
| 12 | +/// the note holds its cap. | ||
| 13 | +pub async fn insert(db: &Database, file: NoteFile) -> Result<NoteFile, AppError> { | ||
| 14 | + note_file::insert(db, file).await | ||
| 15 | +} | ||
| 16 | + | ||
| 17 | +/// Read a file's row only if it belongs to `note`. | ||
| 18 | +pub async fn read_for( | ||
| 19 | + db: &Database, | ||
| 20 | + id: &NoteFileId, | ||
| 21 | + note: &NoteId, | ||
| 22 | +) -> Result<Option<NoteFile>, AppError> { | ||
| 23 | + note_file::read_for(db, id, note).await | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +pub async fn list_for( | ||
| 27 | + db: &Database, | ||
| 28 | + note: &NoteId, | ||
| 29 | + limit: Option<i64>, | ||
| 30 | + offset: i64, | ||
| 31 | +) -> Result<(Vec<NoteFile>, i64), AppError> { | ||
| 32 | + note_file::list_for(db, note, limit, offset).await | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +/// Delete the row and hand its slot back in the same transaction; the returned | ||
| 36 | +/// row is exactly whose blob the caller may unlink. | ||
| 37 | +pub async fn delete(db: &Database, file: NoteFile) -> Result<NoteFile, AppError> { | ||
| 38 | + note_file::delete(db, file).await | ||
| 39 | +} | ||
src/service/user.rsmodified+47 -31
| @@ -64,8 +64,7 @@ pub async fn ensure_admin( | |||
| 64 | // is no marker that could tell such a row apart from a stranger | 64 | // is no marker that could tell such a row apart from a stranger |
| 65 | // who registered the name first, so the hole cannot be healed | 65 | // who registered the name first, so the hole cannot be healed |
| 66 | // later; it has to be impossible to open. | 66 | // later; it has to be impossible to open. |
| 67 | - user::create_with_role(db, username, password.hash_async().await?, Role::Admin) | 67 | + user::create_with_role(db, username, password.hash_async().await?, Role::Admin).await?; |
| 68 | - .await?; | ||
| 69 | // No `username` field: with OTLP on every event is exported as a | 68 | // No `username` field: with OTLP on every event is exported as a |
| 70 | // log record, so an account name here leaves the process. | 69 | // log record, so an account name here leaves the process. |
| 71 | tracing::info!("seeded the admin account named by ADMIN_USERNAME"); | 70 | tracing::info!("seeded the admin account named by ADMIN_USERNAME"); |
| @@ -183,7 +182,18 @@ pub async fn set_profile( | |||
| 183 | display_name: Option<Option<DisplayName>>, | 182 | display_name: Option<Option<DisplayName>>, |
| 184 | bio: Option<Option<Bio>>, | 183 | bio: Option<Option<Bio>>, |
| 185 | ) -> Result<User, AppError> { | 184 | ) -> Result<User, AppError> { |
| 186 | - user::set_profile(db, id, name, surname, email, phone, birth_date, display_name, bio).await | 185 | + user::set_profile( |
| 186 | + db, | ||
| 187 | + id, | ||
| 188 | + name, | ||
| 189 | + surname, | ||
| 190 | + email, | ||
| 191 | + phone, | ||
| 192 | + birth_date, | ||
| 193 | + display_name, | ||
| 194 | + bio, | ||
| 195 | + ) | ||
| 196 | + .await | ||
| 187 | } | 197 | } |
| 188 | 198 | ||
| 189 | /// Persist an avatar upload, handing back the replaced blob's name. | 199 | /// Persist an avatar upload, handing back the replaced blob's name. |
| @@ -249,32 +259,28 @@ mod tests { | |||
| 249 | /// just changed is simply never told. Assert the rows come back. | 259 | /// just changed is simply never told. Assert the rows come back. |
| 250 | #[tokio::test] | 260 | #[tokio::test] |
| 251 | async fn the_cascade_returns_the_boards_it_stripped() { | 261 | async fn the_cascade_returns_the_boards_it_stripped() { |
| 252 | - use crate::domain::board::{Board, BoardTitle}; | 262 | + use crate::domain::board::BoardTitle; |
| 253 | 263 | ||
| 254 | let db = init_mem().await.unwrap(); | 264 | let db = init_mem().await.unwrap(); |
| 255 | let creator = a_user("ogretmen", &db).await; | 265 | let creator = a_user("ogretmen", &db).await; |
| 256 | let guest = a_user("ogrenci", &db).await; | 266 | let guest = a_user("ogrenci", &db).await; |
| 257 | - let board = Board::create( | 267 | + let board = crate::db::board::create( |
| 268 | + &db, | ||
| 258 | creator.get_id(), | 269 | creator.get_id(), |
| 259 | BoardTitle::try_new("Geometri").unwrap(), | 270 | BoardTitle::try_new("Geometri").unwrap(), |
| 260 | vec![guest.get_id().clone()], | 271 | vec![guest.get_id().clone()], |
| 261 | - &db, | ||
| 262 | ) | 272 | ) |
| 263 | .await | 273 | .await |
| 264 | .unwrap(); | 274 | .unwrap(); |
| 265 | 275 | ||
| 266 | // A promotion touches no roster and must report none. | 276 | // A promotion touches no roster and must report none. |
| 267 | - let (guest, boards) = set_role(&db, guest.get_id(), Role::Teacher) | 277 | + let (guest, boards) = set_role(&db, guest.get_id(), Role::Teacher).await.unwrap(); |
| 268 | - .await | ||
| 269 | - .unwrap(); | ||
| 270 | assert!( | 278 | assert!( |
| 271 | boards.is_empty(), | 279 | boards.is_empty(), |
| 272 | "only a demotion to parent strips rosters" | 280 | "only a demotion to parent strips rosters" |
| 273 | ); | 281 | ); |
| 274 | 282 | ||
| 275 | - let (_, boards) = set_role(&db, guest.get_id(), Role::Parent) | 283 | + let (_, boards) = set_role(&db, guest.get_id(), Role::Parent).await.unwrap(); |
| 276 | - .await | ||
| 277 | - .unwrap(); | ||
| 278 | assert_eq!(boards.len(), 1, "the stripped room must be reported back"); | 284 | assert_eq!(boards.len(), 1, "the stripped room must be reported back"); |
| 279 | assert_eq!(boards[0].get_id(), board.get_id()); | 285 | assert_eq!(boards[0].get_id(), board.get_id()); |
| 280 | assert!( | 286 | assert!( |
| @@ -292,36 +298,37 @@ mod tests { | |||
| 292 | /// readable. | 298 | /// readable. |
| 293 | #[tokio::test] | 299 | #[tokio::test] |
| 294 | async fn a_demoted_creator_s_board_is_closed_and_still_readable() { | 300 | async fn a_demoted_creator_s_board_is_closed_and_still_readable() { |
| 295 | - use crate::domain::board::{Board, BoardTitle}; | 301 | + use crate::domain::board::BoardTitle; |
| 296 | - use crate::domain::board_stroke::{BOARD_CLOSED, BoardStroke}; | 302 | + use crate::domain::board_stroke::BOARD_CLOSED; |
| 297 | 303 | ||
| 298 | let db = init_mem().await.unwrap(); | 304 | let db = init_mem().await.unwrap(); |
| 299 | let creator = a_user("ogretmen", &db).await; | 305 | let creator = a_user("ogretmen", &db).await; |
| 300 | let guest = a_user("ogrenci", &db).await; | 306 | let guest = a_user("ogrenci", &db).await; |
| 301 | - let board = Board::create( | 307 | + let board = crate::db::board::create( |
| 308 | + &db, | ||
| 302 | creator.get_id(), | 309 | creator.get_id(), |
| 303 | BoardTitle::try_new("Geometri").unwrap(), | 310 | BoardTitle::try_new("Geometri").unwrap(), |
| 304 | vec![guest.get_id().clone()], | 311 | vec![guest.get_id().clone()], |
| 305 | - &db, | ||
| 306 | ) | 312 | ) |
| 307 | .await | 313 | .await |
| 308 | .unwrap(); | 314 | .unwrap(); |
| 309 | let mark = |epoch| { | 315 | let mark = |epoch| { |
| 310 | let (id, author, db) = (board.get_id().clone(), guest.get_id().clone(), db.clone()); | 316 | let (id, author, db) = (board.get_id().clone(), guest.get_id().clone(), db.clone()); |
| 311 | - async move { BoardStroke::append(&id, &author, "{\"p\":[1]}", epoch, &db).await } | 317 | + async move { crate::db::board_stroke::append(&db, &id, &author, "{\"p\":[1]}", epoch).await } |
| 312 | }; | 318 | }; |
| 313 | mark(0).await.unwrap(); | 319 | mark(0).await.unwrap(); |
| 314 | 320 | ||
| 315 | - let (creator, boards) = set_role(&db, creator.get_id(), Role::Parent) | 321 | + let (creator, boards) = set_role(&db, creator.get_id(), Role::Parent).await.unwrap(); |
| 316 | - .await | ||
| 317 | - .unwrap(); | ||
| 318 | assert_eq!(boards.len(), 1, "the room must be reported back"); | 322 | assert_eq!(boards.len(), 1, "the room must be reported back"); |
| 319 | let stamp = boards[0] | 323 | let stamp = boards[0] |
| 320 | .get_closed_at() | 324 | .get_closed_at() |
| 321 | .expect("and carry the closing stamp the room is told about"); | 325 | .expect("and carry the closing stamp the room is told about"); |
| 322 | 326 | ||
| 323 | // Stored, not merely reported — and nothing else moved. | 327 | // Stored, not merely reported — and nothing else moved. |
| 324 | - let stored = Board::read(board.get_id(), &db).await.unwrap().unwrap(); | 328 | + let stored = crate::db::board::read(&db, board.get_id()) |
| 329 | + .await | ||
| 330 | + .unwrap() | ||
| 331 | + .unwrap(); | ||
| 325 | assert_eq!(stored.get_closed_at(), Some(stamp)); | 332 | assert_eq!(stored.get_closed_at(), Some(stamp)); |
| 326 | assert_eq!( | 333 | assert_eq!( |
| 327 | stored.get_participants(), | 334 | stored.get_participants(), |
| @@ -329,7 +336,7 @@ mod tests { | |||
| 329 | "closing must not empty the roster it did not touch" | 336 | "closing must not empty the roster it did not touch" |
| 330 | ); | 337 | ); |
| 331 | assert_eq!( | 338 | assert_eq!( |
| 332 | - BoardStroke::history(board.get_id(), None, false, None, 0, &db) | 339 | + crate::db::board_stroke::history(&db, board.get_id(), None, false, None, 0) |
| 333 | .await | 340 | .await |
| 334 | .unwrap() | 341 | .unwrap() |
| 335 | .1, | 342 | .1, |
| @@ -345,11 +352,9 @@ mod tests { | |||
| 345 | 352 | ||
| 346 | // The stamp is the record: a re-run of the sweep must not move it. | 353 | // The stamp is the record: a re-run of the sweep must not move it. |
| 347 | tokio::time::sleep(std::time::Duration::from_millis(2)).await; | 354 | tokio::time::sleep(std::time::Duration::from_millis(2)).await; |
| 348 | - set_role(&db, creator.get_id(), Role::Parent) | 355 | + set_role(&db, creator.get_id(), Role::Parent).await.unwrap(); |
| 349 | - .await | ||
| 350 | - .unwrap(); | ||
| 351 | assert_eq!( | 356 | assert_eq!( |
| 352 | - Board::read(board.get_id(), &db) | 357 | + crate::db::board::read(&db, board.get_id()) |
| 353 | .await | 358 | .await |
| 354 | .unwrap() | 359 | .unwrap() |
| 355 | .unwrap() | 360 | .unwrap() |
| @@ -369,8 +374,8 @@ mod tests { | |||
| 369 | #[tokio::test] | 374 | #[tokio::test] |
| 370 | async fn a_demotion_withdraws_the_calendar_and_settles_its_bookings() { | 375 | async fn a_demotion_withdraws_the_calendar_and_settles_its_bookings() { |
| 371 | use crate::domain::appointment::{AppointmentReason, AppointmentStatus}; | 376 | use crate::domain::appointment::{AppointmentReason, AppointmentStatus}; |
| 372 | - use crate::service::appointment; | ||
| 373 | use crate::domain::timestamp::Timestamp; | 377 | use crate::domain::timestamp::Timestamp; |
| 378 | + use crate::service::appointment; | ||
| 374 | 379 | ||
| 375 | let db = init_mem().await.unwrap(); | 380 | let db = init_mem().await.unwrap(); |
| 376 | let staff = |name: &'static str, db: Database| async move { | 381 | let staff = |name: &'static str, db: Database| async move { |
| @@ -388,9 +393,15 @@ mod tests { | |||
| 388 | let slot = |owner: &User, offset: i64, db: Database| { | 393 | let slot = |owner: &User, offset: i64, db: Database| { |
| 389 | let owner = owner.get_id().clone(); | 394 | let owner = owner.get_id().clone(); |
| 390 | async move { | 395 | async move { |
| 391 | - crate::service::appointment_slot::create(&db, &owner, soon(offset), soon(offset + 60_000), None) | 396 | + crate::service::appointment_slot::create( |
| 392 | - .await | 397 | + &db, |
| 393 | - .unwrap() | 398 | + &owner, |
| 399 | + soon(offset), | ||
| 400 | + soon(offset + 60_000), | ||
| 401 | + None, | ||
| 402 | + ) | ||
| 403 | + .await | ||
| 404 | + .unwrap() | ||
| 394 | } | 405 | } |
| 395 | }; | 406 | }; |
| 396 | 407 | ||
| @@ -454,7 +465,12 @@ mod tests { | |||
| 454 | .unwrap() | 465 | .unwrap() |
| 455 | .check() | 466 | .check() |
| 456 | .unwrap(); | 467 | .unwrap(); |
| 457 | - assert!(result.take::<Vec<surrealdb::types::RecordId>>(0).unwrap().is_empty()); | 468 | + assert!( |
| 469 | + result | ||
| 470 | + .take::<Vec<surrealdb::types::RecordId>>(0) | ||
| 471 | + .unwrap() | ||
| 472 | + .is_empty() | ||
| 473 | + ); | ||
| 458 | 474 | ||
| 459 | // Another teacher's calendar is nobody else's business. | 475 | // Another teacher's calendar is nobody else's business. |
| 460 | assert_eq!( | 476 | assert_eq!( |
src/web/board_ws.rsmodified+29 -34
| @@ -9,7 +9,7 @@ | |||
| 9 | //! Two rules shape everything below. | 9 | //! Two rules shape everything below. |
| 10 | //! | 10 | //! |
| 11 | //! **Persist, then publish.** A stroke is fanned out only once | 11 | //! **Persist, then publish.** A stroke is fanned out only once |
| 12 | -//! [`BoardStroke::append`] has returned `Ok`, so the channel can never carry a | 12 | +//! [`board_stroke::append`] has returned `Ok`, so the channel can never carry a |
| 13 | //! mark the database refused (a locked board, a full canvas, a closed board). | 13 | //! mark the database refused (a locked board, a full canvas, a closed board). |
| 14 | //! The database is the canvas; the channel is a notification about it. A | 14 | //! The database is the canvas; the channel is a notification about it. A |
| 15 | //! client still dedupes by stroke `id` — a resync deliberately re-serves marks | 15 | //! client still dedupes by stroke `id` — a resync deliberately re-serves marks |
| @@ -69,11 +69,14 @@ use tokio::sync::broadcast::error::RecvError; | |||
| 69 | use crate::constant::{BOARD_REPLAY_CHUNK, BOARD_WS_TICK_SECS, MAX_BOARD_ID_LEN}; | 69 | use crate::constant::{BOARD_REPLAY_CHUNK, BOARD_WS_TICK_SECS, MAX_BOARD_ID_LEN}; |
| 70 | use crate::database::Database; | 70 | use crate::database::Database; |
| 71 | use crate::domain::board::{Board, BoardId}; | 71 | use crate::domain::board::{Board, BoardId}; |
| 72 | -use crate::domain::board_stroke::{self, BoardStroke}; | 72 | +use crate::domain::board_stroke::{ |
| 73 | + BOARD_CLOSED, BOARD_LOCKED, BoardStroke, CANVAS_BLANK, EPOCH_FULL, | ||
| 74 | +}; | ||
| 73 | use crate::domain::role::Role; | 75 | use crate::domain::role::Role; |
| 74 | use crate::domain::timestamp::Timestamp; | 76 | use crate::domain::timestamp::Timestamp; |
| 75 | use crate::domain::user::UserId; | 77 | use crate::domain::user::UserId; |
| 76 | use crate::error::AppError; | 78 | use crate::error::AppError; |
| 79 | +use crate::service::{board, board_stroke}; | ||
| 77 | use crate::state::AppState; | 80 | use crate::state::AppState; |
| 78 | use crate::tenant::Slug; | 81 | use crate::tenant::Slug; |
| 79 | use crate::web::CurrentUser; | 82 | use crate::web::CurrentUser; |
| @@ -130,7 +133,7 @@ pub async fn board_ws( | |||
| 130 | if id.len() > MAX_BOARD_ID_LEN || !user.get_role().at_least(Role::Student) { | 133 | if id.len() > MAX_BOARD_ID_LEN || !user.get_role().at_least(Role::Student) { |
| 131 | return Err(AppError::NotFound); | 134 | return Err(AppError::NotFound); |
| 132 | } | 135 | } |
| 133 | - let board = Board::read(&BoardId::from_key(&id), &st.db) | 136 | + let board = board::read(&st.db, &BoardId::from_key(&id)) |
| 134 | .await? | 137 | .await? |
| 135 | .ok_or(AppError::NotFound)?; | 138 | .ok_or(AppError::NotFound)?; |
| 136 | if !board.is_participant(user.get_id()) { | 139 | if !board.is_participant(user.get_id()) { |
| @@ -213,7 +216,7 @@ async fn live_board(board: &BoardId, user: &UserId, db: &Database) -> Result<Boa | |||
| 213 | if barred { | 216 | if barred { |
| 214 | return Err(AppError::Forbidden("your role can no longer use boards")); | 217 | return Err(AppError::Forbidden("your role can no longer use boards")); |
| 215 | } | 218 | } |
| 216 | - let board = Board::read(board, db).await?.ok_or(AppError::NotFound)?; | 219 | + let board = board::read(db, board).await?.ok_or(AppError::NotFound)?; |
| 217 | if !board.is_participant(user) { | 220 | if !board.is_participant(user) { |
| 218 | return Err(AppError::Forbidden("you are no longer on this board")); | 221 | return Err(AppError::Forbidden("you are no longer on this board")); |
| 219 | } | 222 | } |
| @@ -359,7 +362,7 @@ async fn replay( | |||
| 359 | ) -> Step { | 362 | ) -> Step { |
| 360 | let mut cursor = after; | 363 | let mut cursor = after; |
| 361 | loop { | 364 | loop { |
| 362 | - let chunk = match BoardStroke::replay_current(board, epoch, cursor.as_deref(), db).await { | 365 | + let chunk = match board_stroke::replay_current(db, board, epoch, cursor.as_deref()).await { |
| 363 | Ok(chunk) => chunk, | 366 | Ok(chunk) => chunk, |
| 364 | Err(err) => return send(socket, error_frame(&err, None)).await, | 367 | Err(err) => return send(socket, error_frame(&err, None)).await, |
| 365 | }; | 368 | }; |
| @@ -460,7 +463,7 @@ async fn handle_message( | |||
| 460 | // cleared since this socket last heard anything. | 463 | // cleared since this socket last heard anything. |
| 461 | let saved = match live_board(board, user, &st.db).await { | 464 | let saved = match live_board(board, user, &st.db).await { |
| 462 | Ok(live) => { | 465 | Ok(live) => { |
| 463 | - BoardStroke::append(board, user, &payload, live.get_epoch(), &st.db).await | 466 | + board_stroke::append(&st.db, board, user, &payload, live.get_epoch()).await |
| 464 | } | 467 | } |
| 465 | Err(err) => Err(err), | 468 | Err(err) => Err(err), |
| 466 | }; | 469 | }; |
| @@ -490,7 +493,7 @@ async fn handle_message( | |||
| 490 | } | 493 | } |
| 491 | ClientMessage::Clear => match creator_board(socket, board, user, &st.db).await? { | 494 | ClientMessage::Clear => match creator_board(socket, board, user, &st.db).await? { |
| 492 | None => Ok(()), | 495 | None => Ok(()), |
| 493 | - Some(live) => match BoardStroke::clear(live.get_id(), user, &st.db).await { | 496 | + Some(live) => match board_stroke::clear(&st.db, live.get_id(), user).await { |
| 494 | // The marker carries the epoch it *closed*; the room's new | 497 | // The marker carries the epoch it *closed*; the room's new |
| 495 | // canvas is the next one. Same shape as `POST /boards/{id}/clear`. | 498 | // canvas is the next one. Same shape as `POST /boards/{id}/clear`. |
| 496 | Ok(marker) => { | 499 | Ok(marker) => { |
| @@ -511,7 +514,7 @@ async fn handle_message( | |||
| 511 | }, | 514 | }, |
| 512 | ClientMessage::Lock { locked } => match creator_board(socket, board, user, &st.db).await? { | 515 | ClientMessage::Lock { locked } => match creator_board(socket, board, user, &st.db).await? { |
| 513 | None => Ok(()), | 516 | None => Ok(()), |
| 514 | - Some(live) => match live.set_locked(locked, user, &st.db).await { | 517 | + Some(live) => match board::set_locked(&st.db, &live, locked, user).await { |
| 515 | Ok(_) => { | 518 | Ok(_) => { |
| 516 | st.board_hub.publish( | 519 | st.board_hub.publish( |
| 517 | slug, | 520 | slug, |
| @@ -570,10 +573,10 @@ async fn creator_board( | |||
| 570 | fn error_frame(err: &AppError, client_seq: Option<u64>) -> Value { | 573 | fn error_frame(err: &AppError, client_seq: Option<u64>) -> Value { |
| 571 | let code = match err { | 574 | let code = match err { |
| 572 | AppError::Forbidden(_) => "forbidden", | 575 | AppError::Forbidden(_) => "forbidden", |
| 573 | - AppError::Conflict(message) if *message == board_stroke::EPOCH_FULL => "epoch_full", | 576 | + AppError::Conflict(message) if *message == EPOCH_FULL => "epoch_full", |
| 574 | - AppError::Conflict(message) if *message == board_stroke::BOARD_LOCKED => "locked", | 577 | + AppError::Conflict(message) if *message == BOARD_LOCKED => "locked", |
| 575 | - AppError::Conflict(message) if *message == board_stroke::BOARD_CLOSED => "board_closed", | 578 | + AppError::Conflict(message) if *message == BOARD_CLOSED => "board_closed", |
| 576 | - AppError::Conflict(message) if *message == board_stroke::CANVAS_BLANK => "canvas_blank", | 579 | + AppError::Conflict(message) if *message == CANVAS_BLANK => "canvas_blank", |
| 577 | // A refusal that already carries its own code keeps it — no board path | 580 | // A refusal that already carries its own code keeps it — no board path |
| 578 | // raises one today, but re-labelling one "conflict" would throw the | 581 | // raises one today, but re-labelling one "conflict" would throw the |
| 579 | // only machine answer it has away. | 582 | // only machine answer it has away. |
| @@ -601,6 +604,7 @@ fn error_frame(err: &AppError, client_seq: Option<u64>) -> Value { | |||
| 601 | #[cfg(test)] | 604 | #[cfg(test)] |
| 602 | mod tests { | 605 | mod tests { |
| 603 | use super::*; | 606 | use super::*; |
| 607 | + use crate::domain::board_stroke::{BOARD_MOVED, REFUSALS}; | ||
| 604 | 608 | ||
| 605 | fn code(err: AppError) -> String { | 609 | fn code(err: AppError) -> String { |
| 606 | error_frame(&err, None)["code"] | 610 | error_frame(&err, None)["code"] |
| @@ -618,26 +622,26 @@ mod tests { | |||
| 618 | /// test that pins the wording rots into a test of a string the code can no | 622 | /// test that pins the wording rots into a test of a string the code can no |
| 619 | /// longer emit, which is exactly how the blank canvas shipped as | 623 | /// longer emit, which is exactly how the blank canvas shipped as |
| 620 | /// `board_closed` through a green suite. The length assertion is the other | 624 | /// `board_closed` through a green suite. The length assertion is the other |
| 621 | - /// half — a refusal added to `board_stroke::REFUSALS` fails here until it | 625 | + /// half — a refusal added to `REFUSALS` fails here until it |
| 622 | /// is given the code its client must act on. | 626 | /// is given the code its client must act on. |
| 623 | #[test] | 627 | #[test] |
| 624 | fn every_refusal_gets_the_code_its_client_must_act_on() { | 628 | fn every_refusal_gets_the_code_its_client_must_act_on() { |
| 625 | let pairs = [ | 629 | let pairs = [ |
| 626 | - (board_stroke::EPOCH_FULL, "epoch_full"), | 630 | + (EPOCH_FULL, "epoch_full"), |
| 627 | - (board_stroke::BOARD_LOCKED, "locked"), | 631 | + (BOARD_LOCKED, "locked"), |
| 628 | - (board_stroke::BOARD_CLOSED, "board_closed"), | 632 | + (BOARD_CLOSED, "board_closed"), |
| 629 | - (board_stroke::CANVAS_BLANK, "canvas_blank"), | 633 | + (CANVAS_BLANK, "canvas_blank"), |
| 630 | // A stroke that lost its epoch to a clear is a plain retryable | 634 | // A stroke that lost its epoch to a clear is a plain retryable |
| 631 | // conflict, and must never be mistaken for terminal. | 635 | // conflict, and must never be mistaken for terminal. |
| 632 | - (board_stroke::BOARD_MOVED, "conflict"), | 636 | + (BOARD_MOVED, "conflict"), |
| 633 | ]; | 637 | ]; |
| 634 | assert_eq!( | 638 | assert_eq!( |
| 635 | pairs.len(), | 639 | pairs.len(), |
| 636 | - board_stroke::REFUSALS.len(), | 640 | + REFUSALS.len(), |
| 637 | "a refusal the room cannot code" | 641 | "a refusal the room cannot code" |
| 638 | ); | 642 | ); |
| 639 | for (message, expected) in pairs { | 643 | for (message, expected) in pairs { |
| 640 | - assert!(board_stroke::REFUSALS.contains(&message)); | 644 | + assert!(REFUSALS.contains(&message)); |
| 641 | assert_eq!(code(AppError::Conflict(message)), expected, "{message}"); | 645 | assert_eq!(code(AppError::Conflict(message)), expected, "{message}"); |
| 642 | } | 646 | } |
| 643 | assert_eq!(code(AppError::Forbidden("nope")), "forbidden"); | 647 | assert_eq!(code(AppError::Forbidden("nope")), "forbidden"); |
| @@ -653,18 +657,9 @@ mod tests { | |||
| 653 | /// the three collapse into one code. | 657 | /// the three collapse into one code. |
| 654 | #[test] | 658 | #[test] |
| 655 | fn a_blank_canvas_is_never_terminal() { | 659 | fn a_blank_canvas_is_never_terminal() { |
| 656 | - assert_eq!( | 660 | + assert_eq!(code(AppError::Conflict(CANVAS_BLANK)), "canvas_blank"); |
| 657 | - code(AppError::Conflict(board_stroke::CANVAS_BLANK)), | 661 | + assert_eq!(code(AppError::Conflict(BOARD_CLOSED)), "board_closed"); |
| 658 | - "canvas_blank" | 662 | + assert_eq!(code(AppError::Conflict(BOARD_LOCKED)), "locked"); |
| 659 | - ); | ||
| 660 | - assert_eq!( | ||
| 661 | - code(AppError::Conflict(board_stroke::BOARD_CLOSED)), | ||
| 662 | - "board_closed" | ||
| 663 | - ); | ||
| 664 | - assert_eq!( | ||
| 665 | - code(AppError::Conflict(board_stroke::BOARD_LOCKED)), | ||
| 666 | - "locked" | ||
| 667 | - ); | ||
| 668 | } | 663 | } |
| 669 | 664 | ||
| 670 | /// The upgrade door's role bar has to hold for the *life* of the socket. | 665 | /// The upgrade door's role bar has to hold for the *life* of the socket. |
| @@ -696,11 +691,11 @@ mod tests { | |||
| 696 | .await | 691 | .await |
| 697 | .unwrap(); | 692 | .unwrap(); |
| 698 | let mate_id = mate.get_id().clone(); | 693 | let mate_id = mate.get_id().clone(); |
| 699 | - let board = Board::create( | 694 | + let board = board::create( |
| 695 | + &db, | ||
| 700 | creator.get_id(), | 696 | creator.get_id(), |
| 701 | BoardTitle::try_new("Tahta").unwrap(), | 697 | BoardTitle::try_new("Tahta").unwrap(), |
| 702 | vec![mate_id.clone()], | 698 | vec![mate_id.clone()], |
| 703 | - &db, | ||
| 704 | ) | 699 | ) |
| 705 | .await | 700 | .await |
| 706 | .unwrap(); | 701 | .unwrap(); |
src/web/boards.rsmodified+32 -214
| @@ -28,9 +28,8 @@ use utoipa::ToSchema; | |||
| 28 | use utoipa_axum::router::OpenApiRouter; | 28 | use utoipa_axum::router::OpenApiRouter; |
| 29 | use utoipa_axum::routes; | 29 | use utoipa_axum::routes; |
| 30 | 30 | ||
| 31 | -use crate::constant::MAX_BOARD_PARTICIPANTS; | ||
| 32 | use crate::database::Database; | 31 | use crate::database::Database; |
| 33 | -use crate::domain::board::{BOARD_ROSTER_LOCK, Board, BoardId, BoardTitle}; | 32 | +use crate::domain::board::{Board, BoardId, BoardTitle}; |
| 34 | use crate::domain::board_stroke::BoardStroke; | 33 | use crate::domain::board_stroke::BoardStroke; |
| 35 | use crate::domain::class_group::ClassGroupId; | 34 | use crate::domain::class_group::ClassGroupId; |
| 36 | use crate::domain::course::CourseId; | 35 | use crate::domain::course::CourseId; |
| @@ -38,6 +37,8 @@ use crate::domain::event::EventId; | |||
| 38 | use crate::domain::role::Role; | 37 | use crate::domain::role::Role; |
| 39 | use crate::domain::user::{User, UserId}; | 38 | use crate::domain::user::{User, UserId}; |
| 40 | 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}; | ||
| 41 | use crate::state::AppState; | 42 | use crate::state::AppState; |
| 42 | use crate::tenant::Slug; | 43 | use crate::tenant::Slug; |
| 43 | 44 | ||
| @@ -60,104 +61,6 @@ pub fn routes() -> OpenApiRouter<AppState> { | |||
| 60 | .routes(routes!(invite_board)) | 61 | .routes(routes!(invite_board)) |
| 61 | } | 62 | } |
| 62 | 63 | ||
| 63 | -/// The board, or a 404 — including the deliberate 404 for a caller who is not | ||
| 64 | -/// on it. Every route starts here, so existence never leaks. | ||
| 65 | -/// | ||
| 66 | -/// A `parent` is treated as an outsider rather than refused with a 403: the | ||
| 67 | -/// role is barred from the whiteboard entirely, and a 403 would confirm the | ||
| 68 | -/// board exists. [`resolve_participants`] keeps parents off every roster, so | ||
| 69 | -/// this arm only ever fires for a row written before that rule. | ||
| 70 | -async fn board_for(id: &str, user: &User, db: &Database) -> Result<Board, AppError> { | ||
| 71 | - let board = Board::read(&BoardId::from_key(id), db) | ||
| 72 | - .await? | ||
| 73 | - .ok_or(AppError::NotFound)?; | ||
| 74 | - if !user.get_role().at_least(Role::Student) || !board.is_participant(user.get_id()) { | ||
| 75 | - return Err(AppError::NotFound); | ||
| 76 | - } | ||
| 77 | - Ok(board) | ||
| 78 | -} | ||
| 79 | - | ||
| 80 | -/// The creator-only gate. A 403, never a 404: the caller reached it through | ||
| 81 | -/// [`board_for`], so they are a participant and the board's existence is | ||
| 82 | -/// already theirs to see. | ||
| 83 | -fn ensure_creator(board: &Board, user: &User) -> Result<(), AppError> { | ||
| 84 | - if !board.is_creator(user.get_id()) { | ||
| 85 | - return Err(AppError::Forbidden( | ||
| 86 | - "only the board's creator can clear, lock, close or delete it", | ||
| 87 | - )); | ||
| 88 | - } | ||
| 89 | - Ok(()) | ||
| 90 | -} | ||
| 91 | - | ||
| 92 | -/// The invite list off the wire: deduped, capped, and every id resolved against | ||
| 93 | -/// a real user. The cap is applied *before* the lookup (the domain caps too, but | ||
| 94 | -/// only after the read would already have run), and an unknown id is a 400 | ||
| 95 | -/// rather than a silently dropped invitation. | ||
| 96 | -/// | ||
| 97 | -/// The eligible set is fetched in **one** read, not one per id. That was a | ||
| 98 | -/// per-id loop while a roster could only be typed by hand and so was a handful | ||
| 99 | -/// of ids; bulk invite made a full board an ordinary thing to own, and a | ||
| 100 | -/// read-modify-write PATCH of one — read the board, drop a name, send the rest | ||
| 101 | -/// back — is the common client shape, so the loop had become | ||
| 102 | -/// `max_participants` sequential round trips on a routine edit. | ||
| 103 | -/// | ||
| 104 | -/// A `parent` is refused here, and that is the cut that keeps the role off the | ||
| 105 | -/// whiteboard: never on a roster means [`board_for`] and the room's door already | ||
| 106 | -/// answer 404 on every id-scoped route, and no socket can ever open. | ||
| 107 | -/// | ||
| 108 | -/// The creator is a participant by construction, so they are neither injected | ||
| 109 | -/// into the list nor rejected from it. | ||
| 110 | -/// | ||
| 111 | -/// `current` is the board's roster as it stands (empty when a board is being | ||
| 112 | -/// created), and it is what makes a read-modify-write PATCH survive: an id | ||
| 113 | -/// *already* on the board that no longer qualifies — demoted, or deleted | ||
| 114 | -/// outright — is dropped silently instead of failing the whole call, so a | ||
| 115 | -/// creator echoing back the roster they were just served gets a 200 and a | ||
| 116 | -/// cleaned list. An id that is **new** to the board still 400s; without that | ||
| 117 | -/// split the drop would be a hole letting a caller seed a roster with anyone. | ||
| 118 | -async fn resolve_participants( | ||
| 119 | - ids: Option<Vec<String>>, | ||
| 120 | - current: &[UserId], | ||
| 121 | - db: &Database, | ||
| 122 | -) -> Result<Vec<UserId>, AppError> { | ||
| 123 | - let Some(mut ids) = ids else { | ||
| 124 | - return Ok(Vec::new()); | ||
| 125 | - }; | ||
| 126 | - ids.sort(); | ||
| 127 | - ids.dedup(); | ||
| 128 | - if ids.len() > MAX_BOARD_PARTICIPANTS { | ||
| 129 | - return Err(AppError::Validation(ValidationError::TooLong { | ||
| 130 | - field: "participants", | ||
| 131 | - max: MAX_BOARD_PARTICIPANTS, | ||
| 132 | - got: ids.len(), | ||
| 133 | - })); | ||
| 134 | - } | ||
| 135 | - let wanted: Vec<UserId> = ids.iter().map(|id| UserId::from_key(id)).collect(); | ||
| 136 | - // Absent from this list means "no such user, or below `student`" — the two | ||
| 137 | - // are one case here, and telling them apart is what the caller must not be | ||
| 138 | - // able to do anyway. | ||
| 139 | - let eligible: Vec<UserId> = crate::service::user::list_by_ids(db, &wanted) | ||
| 140 | - .await? | ||
| 141 | - .iter() | ||
| 142 | - .filter(|found| found.get_role().at_least(Role::Student)) | ||
| 143 | - .map(|found| found.get_id().clone()) | ||
| 144 | - .collect(); | ||
| 145 | - let mut users = Vec::with_capacity(wanted.len()); | ||
| 146 | - for user in wanted { | ||
| 147 | - if !eligible.contains(&user) { | ||
| 148 | - if current.contains(&user) { | ||
| 149 | - continue; | ||
| 150 | - } | ||
| 151 | - return Err(AppError::Validation(ValidationError::Invalid { | ||
| 152 | - field: "participants", | ||
| 153 | - reason: "every participant must be an existing user of at least the student role", | ||
| 154 | - })); | ||
| 155 | - } | ||
| 156 | - users.push(user); | ||
| 157 | - } | ||
| 158 | - Ok(users) | ||
| 159 | -} | ||
| 160 | - | ||
| 161 | /// Push one frame to whoever is in the room right now. An empty room is the | 64 | /// Push one frame to whoever is in the room right now. An empty room is the |
| 162 | /// normal case, not a failure. | 65 | /// normal case, not a failure. |
| 163 | fn fan_out(st: &AppState, slug: &Slug, board: &BoardId, frame: serde_json::Value) { | 66 | fn fan_out(st: &AppState, slug: &Slug, board: &BoardId, frame: serde_json::Value) { |
| @@ -299,8 +202,8 @@ async fn create_board( | |||
| 299 | ) -> Result<(StatusCode, Json<BoardResponse>), AppError> { | 202 | ) -> Result<(StatusCode, Json<BoardResponse>), AppError> { |
| 300 | let title = BoardTitle::try_new(&req.title)?; | 203 | let title = BoardTitle::try_new(&req.title)?; |
| 301 | // No roster yet, so nothing is grandfathered: every id must qualify. | 204 | // No roster yet, so nothing is grandfathered: every id must qualify. |
| 302 | - let participants = resolve_participants(req.participants, &[], &st.db).await?; | 205 | + let participants = board::resolve_participants(req.participants, &[], &st.db).await?; |
| 303 | - let board = Board::create(user.get_id(), title, participants, &st.db).await?; | 206 | + let board = board::create(&st.db, user.get_id(), title, participants).await?; |
| 304 | Ok((StatusCode::CREATED, Json(BoardResponse::new(&board)))) | 207 | Ok((StatusCode::CREATED, Json(BoardResponse::new(&board)))) |
| 305 | } | 208 | } |
| 306 | 209 | ||
| @@ -342,7 +245,7 @@ async fn list_boards( | |||
| 342 | ) -> Result<Json<Page<BoardResponse>>, AppError> { | 245 | ) -> Result<Json<Page<BoardResponse>>, AppError> { |
| 343 | let (limit, offset) = page.resolve()?; | 246 | let (limit, offset) = page.resolve()?; |
| 344 | let (boards, total) = | 247 | let (boards, total) = |
| 345 | - Board::list_for_user(user.get_id(), filter.open, limit, offset, &st.db).await?; | 248 | + board::list_for_user(&st.db, user.get_id(), filter.open, limit, offset).await?; |
| 346 | let items = boards.iter().map(BoardResponse::new).collect(); | 249 | let items = boards.iter().map(BoardResponse::new).collect(); |
| 347 | Ok(Json(Page::new(items, total, limit, offset))) | 250 | Ok(Json(Page::new(items, total, limit, offset))) |
| 348 | } | 251 | } |
| @@ -367,7 +270,7 @@ async fn get_board( | |||
| 367 | CurrentUser(user): CurrentUser, | 270 | CurrentUser(user): CurrentUser, |
| 368 | Path(id): Path<String>, | 271 | Path(id): Path<String>, |
| 369 | ) -> Result<Json<BoardResponse>, AppError> { | 272 | ) -> Result<Json<BoardResponse>, AppError> { |
| 370 | - let board = board_for(&id, &user, &st.db).await?; | 273 | + let board = board::board_for(&id, &user, &st.db).await?; |
| 371 | Ok(Json(BoardResponse::new(&board))) | 274 | Ok(Json(BoardResponse::new(&board))) |
| 372 | } | 275 | } |
| 373 | 276 | ||
| @@ -396,20 +299,20 @@ async fn list_strokes( | |||
| 396 | Query(page): Query<PageParams>, | 299 | Query(page): Query<PageParams>, |
| 397 | ) -> Result<Json<Page<StrokeResponse>>, AppError> { | 300 | ) -> Result<Json<Page<StrokeResponse>>, AppError> { |
| 398 | let (limit, offset) = page.resolve()?; | 301 | let (limit, offset) = page.resolve()?; |
| 399 | - let board = board_for(&id, &user, &st.db).await?; | 302 | + let board = board::board_for(&id, &user, &st.db).await?; |
| 400 | // The current epoch holds no `clear` marker — a marker is written with the | 303 | // The current epoch holds no `clear` marker — a marker is written with the |
| 401 | // epoch it *closed* — so scoping history to it is the live canvas. Markers | 304 | // epoch it *closed* — so scoping history to it is the live canvas. Markers |
| 402 | // are dropped anyway: a clear committing between the board read above and | 305 | // are dropped anyway: a clear committing between the board read above and |
| 403 | // this read files one under the epoch just named, and the room's socket | 306 | // this read files one under the epoch just named, and the room's socket |
| 404 | // never shows it, so without the filter the two views disagree in exactly | 307 | // never shows it, so without the filter the two views disagree in exactly |
| 405 | // that race. | 308 | // that race. |
| 406 | - let (strokes, total) = BoardStroke::history( | 309 | + let (strokes, total) = board_stroke::history( |
| 310 | + &st.db, | ||
| 407 | board.get_id(), | 311 | board.get_id(), |
| 408 | Some(board.get_epoch()), | 312 | Some(board.get_epoch()), |
| 409 | true, | 313 | true, |
| 410 | limit, | 314 | limit, |
| 411 | offset, | 315 | offset, |
| 412 | - &st.db, | ||
| 413 | ) | 316 | ) |
| 414 | .await?; | 317 | .await?; |
| 415 | let items = strokes.iter().map(StrokeResponse::new).collect(); | 318 | let items = strokes.iter().map(StrokeResponse::new).collect(); |
| @@ -447,9 +350,9 @@ async fn list_history( | |||
| 447 | Query(page): Query<PageParams>, | 350 | Query(page): Query<PageParams>, |
| 448 | ) -> Result<Json<Page<StrokeResponse>>, AppError> { | 351 | ) -> Result<Json<Page<StrokeResponse>>, AppError> { |
| 449 | let (limit, offset) = page.resolve()?; | 352 | let (limit, offset) = page.resolve()?; |
| 450 | - let board = board_for(&id, &user, &st.db).await?; | 353 | + let board = board::board_for(&id, &user, &st.db).await?; |
| 451 | let (strokes, total) = | 354 | let (strokes, total) = |
| 452 | - BoardStroke::history(board.get_id(), scope.epoch, false, limit, offset, &st.db).await?; | 355 | + board_stroke::history(&st.db, board.get_id(), scope.epoch, false, limit, offset).await?; |
| 453 | let items = strokes.iter().map(StrokeResponse::new).collect(); | 356 | let items = strokes.iter().map(StrokeResponse::new).collect(); |
| 454 | Ok(Json(Page::new(items, total, limit, offset))) | 357 | Ok(Json(Page::new(items, total, limit, offset))) |
| 455 | } | 358 | } |
| @@ -480,8 +383,8 @@ async fn list_epochs( | |||
| 480 | Query(page): Query<PageParams>, | 383 | Query(page): Query<PageParams>, |
| 481 | ) -> Result<Json<Page<StrokeResponse>>, AppError> { | 384 | ) -> Result<Json<Page<StrokeResponse>>, AppError> { |
| 482 | let (limit, offset) = page.resolve()?; | 385 | let (limit, offset) = page.resolve()?; |
| 483 | - let board = board_for(&id, &user, &st.db).await?; | 386 | + let board = board::board_for(&id, &user, &st.db).await?; |
| 484 | - let markers = BoardStroke::epochs(board.get_id(), &st.db).await?; | 387 | + let markers = board_stroke::epochs(&st.db, board.get_id()).await?; |
| 485 | // Paged in the web layer: the marker list is one bounded read, and a board | 388 | // Paged in the web layer: the marker list is one bounded read, and a board |
| 486 | // has at most one marker per clear. | 389 | // has at most one marker per clear. |
| 487 | let items = paginate(&markers, limit, offset) | 390 | let items = paginate(&markers, limit, offset) |
| @@ -549,22 +452,22 @@ async fn update_board( | |||
| 549 | true => Some(BOARD_ROSTER_LOCK.lock().await), | 452 | true => Some(BOARD_ROSTER_LOCK.lock().await), |
| 550 | false => None, | 453 | false => None, |
| 551 | }; | 454 | }; |
| 552 | - let mut board = board_for(&id, &user, &st.db).await?; | 455 | + let mut board = board::board_for(&id, &user, &st.db).await?; |
| 553 | if req.participants.is_some() || req.locked.is_some() { | 456 | if req.participants.is_some() || req.locked.is_some() { |
| 554 | - ensure_creator(&board, &user)?; | 457 | + board::ensure_creator(&board, &user)?; |
| 555 | } | 458 | } |
| 556 | 459 | ||
| 557 | if let Some(title) = req.title.as_deref() { | 460 | if let Some(title) = req.title.as_deref() { |
| 558 | - board = board.set_title(BoardTitle::try_new(title)?, &st.db).await?; | 461 | + board = board::set_title(&st.db, &board, BoardTitle::try_new(title)?).await?; |
| 559 | } | 462 | } |
| 560 | if let Some(participants) = req.participants { | 463 | if let Some(participants) = req.participants { |
| 561 | let participants = | 464 | let participants = |
| 562 | - resolve_participants(participants, board.get_participants(), &st.db).await?; | 465 | + board::resolve_participants(participants, board.get_participants(), &st.db).await?; |
| 563 | - board = board.set_participants(participants, &st.db).await?; | 466 | + board = board::set_participants(&st.db, &board, participants).await?; |
| 564 | fan_out(&st, &slug, board.get_id(), participants_frame(&board)); | 467 | fan_out(&st, &slug, board.get_id(), participants_frame(&board)); |
| 565 | } | 468 | } |
| 566 | if let Some(locked) = req.locked { | 469 | if let Some(locked) = req.locked { |
| 567 | - board = board.set_locked(locked, user.get_id(), &st.db).await?; | 470 | + board = board::set_locked(&st.db, &board, locked, user.get_id()).await?; |
| 568 | fan_out( | 471 | fan_out( |
| 569 | &st, | 472 | &st, |
| 570 | &slug, | 473 | &slug, |
| @@ -607,9 +510,9 @@ async fn clear_board( | |||
| 607 | CurrentUser(user): CurrentUser, | 510 | CurrentUser(user): CurrentUser, |
| 608 | Path(id): Path<String>, | 511 | Path(id): Path<String>, |
| 609 | ) -> Result<(StatusCode, Json<StrokeResponse>), AppError> { | 512 | ) -> Result<(StatusCode, Json<StrokeResponse>), AppError> { |
| 610 | - let board = board_for(&id, &user, &st.db).await?; | 513 | + let board = board::board_for(&id, &user, &st.db).await?; |
| 611 | - ensure_creator(&board, &user)?; | 514 | + board::ensure_creator(&board, &user)?; |
| 612 | - let marker = BoardStroke::clear(board.get_id(), user.get_id(), &st.db).await?; | 515 | + let marker = board_stroke::clear(&st.db, board.get_id(), user.get_id()).await?; |
| 613 | // The marker carries the epoch it *closed*; the room's new canvas is the | 516 | // The marker carries the epoch it *closed*; the room's new canvas is the |
| 614 | // next one. | 517 | // next one. |
| 615 | fan_out( | 518 | fan_out( |
| @@ -649,9 +552,9 @@ async fn close_board( | |||
| 649 | CurrentUser(user): CurrentUser, | 552 | CurrentUser(user): CurrentUser, |
| 650 | Path(id): Path<String>, | 553 | Path(id): Path<String>, |
| 651 | ) -> Result<Json<BoardResponse>, AppError> { | 554 | ) -> Result<Json<BoardResponse>, AppError> { |
| 652 | - let board = board_for(&id, &user, &st.db).await?; | 555 | + let board = board::board_for(&id, &user, &st.db).await?; |
| 653 | - ensure_creator(&board, &user)?; | 556 | + board::ensure_creator(&board, &user)?; |
| 654 | - let board = board.close(&st.db).await?; | 557 | + let board = board::close(&st.db, &board).await?; |
| 655 | fan_out( | 558 | fan_out( |
| 656 | &st, | 559 | &st, |
| 657 | &slug, | 560 | &slug, |
| @@ -834,37 +737,10 @@ async fn invite_board( | |||
| 834 | // the same roster and the second write would drop the first one's people — | 737 | // the same roster and the second write would drop the first one's people — |
| 835 | // silently, with both callers told 200. See [`BOARD_ROSTER_LOCK`]. | 738 | // silently, with both callers told 200. See [`BOARD_ROSTER_LOCK`]. |
| 836 | let _guard = BOARD_ROSTER_LOCK.lock().await; | 739 | let _guard = BOARD_ROSTER_LOCK.lock().await; |
| 837 | - let board = board_for(&id, &user, &st.db).await?; | 740 | + let board = board::board_for(&id, &user, &st.db).await?; |
| 838 | - ensure_creator(&board, &user)?; | 741 | + board::ensure_creator(&board, &user)?; |
| 839 | let invited = req.resolve(&user, &st.db).await?; | 742 | let invited = req.resolve(&user, &st.db).await?; |
| 840 | - | 743 | + let board = board::invite(&st.db, &board, invited).await?; |
| 841 | - // One read for the whole group. The filters below are silent on purpose — | ||
| 842 | - // a source is a whole group, and one member who has left or was never | ||
| 843 | - // eligible must not fail the invite for the other twenty-nine. | ||
| 844 | - let mut roster = board.get_participants().to_vec(); | ||
| 845 | - for candidate in crate::service::user::list_by_ids(&st.db, &invited).await? { | ||
| 846 | - if !candidate.get_role().at_least(Role::Student) { | ||
| 847 | - continue; | ||
| 848 | - } | ||
| 849 | - // The creator is a participant by construction and never sits in the | ||
| 850 | - // array; adding them there would spend a seat on someone who already | ||
| 851 | - // has access. | ||
| 852 | - if candidate.get_id() == board.get_creator() || roster.contains(candidate.get_id()) { | ||
| 853 | - continue; | ||
| 854 | - } | ||
| 855 | - roster.push(candidate.get_id().clone()); | ||
| 856 | - } | ||
| 857 | - | ||
| 858 | - if roster.len() > MAX_BOARD_PARTICIPANTS { | ||
| 859 | - return Err(AppError::ConflictOwned(format!( | ||
| 860 | - "this invite would put the board at {} participants, over the limit of {MAX_BOARD_PARTICIPANTS}; nobody was added", | ||
| 861 | - roster.len() | ||
| 862 | - ))); | ||
| 863 | - } | ||
| 864 | - // Unchanged rosters still write and still fan out: the alternative is a | ||
| 865 | - // branch that has to prove the two lists are equal, and a re-invite that | ||
| 866 | - // added nobody is the idempotent case, not the hot path. | ||
| 867 | - let board = board.set_participants(roster, &st.db).await?; | ||
| 868 | fan_out(&st, &slug, board.get_id(), participants_frame(&board)); | 744 | fan_out(&st, &slug, board.get_id(), participants_frame(&board)); |
| 869 | Ok(Json(BoardResponse::new(&board))) | 745 | Ok(Json(BoardResponse::new(&board))) |
| 870 | } | 746 | } |
| @@ -892,70 +768,12 @@ async fn delete_board( | |||
| 892 | CurrentUser(user): CurrentUser, | 768 | CurrentUser(user): CurrentUser, |
| 893 | Path(id): Path<String>, | 769 | Path(id): Path<String>, |
| 894 | ) -> Result<StatusCode, AppError> { | 770 | ) -> Result<StatusCode, AppError> { |
| 895 | - let board = board_for(&id, &user, &st.db).await?; | 771 | + let board = board::board_for(&id, &user, &st.db).await?; |
| 896 | - ensure_creator(&board, &user)?; | 772 | + board::ensure_creator(&board, &user)?; |
| 897 | let id = board.get_id().clone(); | 773 | let id = board.get_id().clone(); |
| 898 | - board.delete(&st.db).await?; | 774 | + board::delete(&st.db, board).await?; |
| 899 | // Told after the row is gone: a room that acts on this and then re-reads | 775 | // Told after the row is gone: a room that acts on this and then re-reads |
| 900 | // must find nothing, not a board about to disappear. | 776 | // must find nothing, not a board about to disappear. |
| 901 | fan_out(&st, &slug, &id, json!({"type": "deleted"})); | 777 | fan_out(&st, &slug, &id, json!({"type": "deleted"})); |
| 902 | Ok(StatusCode::NO_CONTENT) | 778 | Ok(StatusCode::NO_CONTENT) |
| 903 | } | 779 | } |
| 904 | - | ||
| 905 | -#[cfg(test)] | ||
| 906 | -mod tests { | ||
| 907 | - use super::*; | ||
| 908 | - | ||
| 909 | - /// The security boundary of this module, in one test: an outsider is told | ||
| 910 | - /// the board does not exist, an insider without rights is told it is not | ||
| 911 | - /// theirs to command. Swapping those two leaks the school's board list on | ||
| 912 | - /// one side and hides a rendered board from its own participant on the | ||
| 913 | - /// other. | ||
| 914 | - #[tokio::test] | ||
| 915 | - async fn an_outsider_gets_404_and_a_participant_gets_403() { | ||
| 916 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 917 | - db.query( | ||
| 918 | - "CREATE user:c SET username = 'c', password_hash = 'x'; | ||
| 919 | - CREATE user:p SET username = 'p', password_hash = 'x'; | ||
| 920 | - CREATE user:s SET username = 's', password_hash = 'x';", | ||
| 921 | - ) | ||
| 922 | - .await | ||
| 923 | - .unwrap() | ||
| 924 | - .check() | ||
| 925 | - .unwrap(); | ||
| 926 | - let who = async |key: &str| { | ||
| 927 | - crate::service::user::read(&db, &UserId::from_key(key)) | ||
| 928 | - .await | ||
| 929 | - .unwrap() | ||
| 930 | - .unwrap() | ||
| 931 | - }; | ||
| 932 | - let (creator, participant, stranger) = (who("c").await, who("p").await, who("s").await); | ||
| 933 | - let board = Board::create( | ||
| 934 | - creator.get_id(), | ||
| 935 | - BoardTitle::try_new("Geometri").unwrap(), | ||
| 936 | - vec![participant.get_id().clone()], | ||
| 937 | - &db, | ||
| 938 | - ) | ||
| 939 | - .await | ||
| 940 | - .unwrap(); | ||
| 941 | - let id = board.get_id().key().to_string(); | ||
| 942 | - | ||
| 943 | - assert!(matches!( | ||
| 944 | - board_for(&id, &stranger, &db).await, | ||
| 945 | - Err(AppError::NotFound) | ||
| 946 | - )); | ||
| 947 | - // A board that does not exist at all answers the same way, so the two | ||
| 948 | - // are indistinguishable from outside. | ||
| 949 | - assert!(matches!( | ||
| 950 | - board_for("nope", &creator, &db).await, | ||
| 951 | - Err(AppError::NotFound) | ||
| 952 | - )); | ||
| 953 | - | ||
| 954 | - let seen = board_for(&id, &participant, &db).await.unwrap(); | ||
| 955 | - assert!(matches!( | ||
| 956 | - ensure_creator(&seen, &participant), | ||
| 957 | - Err(AppError::Forbidden(_)) | ||
| 958 | - )); | ||
| 959 | - assert!(ensure_creator(&board_for(&id, &creator, &db).await.unwrap(), &creator).is_ok()); | ||
| 960 | - } | ||
| 961 | -} | ||
src/web/course_notes.rsmodified+28 -19
| @@ -57,7 +57,7 @@ pub fn routes() -> OpenApiRouter<AppState> { | |||
| 57 | /// The note plus its course, or a 404 — every entity handler here gates on | 57 | /// The note plus its course, or a 404 — every entity handler here gates on |
| 58 | /// the parent course, so they always travel together. | 58 | /// the parent course, so they always travel together. |
| 59 | async fn note_with_course(id: &str, db: &Database) -> Result<(CourseNote, Course), AppError> { | 59 | async fn note_with_course(id: &str, db: &Database) -> Result<(CourseNote, Course), AppError> { |
| 60 | - let note = CourseNote::read(&CourseNoteId::from_key(id), db) | 60 | + let note = service::course_note::read(db, &CourseNoteId::from_key(id)) |
| 61 | .await? | 61 | .await? |
| 62 | .ok_or(AppError::NotFound)?; | 62 | .ok_or(AppError::NotFound)?; |
| 63 | let course = crate::service::course::read(db, note.get_course()) | 63 | let course = crate::service::course::read(db, note.get_course()) |
| @@ -141,7 +141,8 @@ async fn create( | |||
| 141 | crate::service::course::require_open(&st.db, &course).await?; | 141 | crate::service::course::require_open(&st.db, &course).await?; |
| 142 | let title = CourseNoteTitle::try_new(&req.title)?; | 142 | let title = CourseNoteTitle::try_new(&req.title)?; |
| 143 | let content = CourseNoteContent::try_new(&req.content.unwrap_or_default())?; | 143 | let content = CourseNoteContent::try_new(&req.content.unwrap_or_default())?; |
| 144 | - let note = CourseNote::create(course.get_id(), user.get_id(), title, content, &st.db).await?; | 144 | + let note = service::course_note::create(&st.db, course.get_id(), user.get_id(), title, content) |
| 145 | + .await?; | ||
| 145 | // Indexing is a background bonus, never a condition of storing the note: | 146 | // Indexing is a background bonus, never a condition of storing the note: |
| 146 | // the dispatch runs in its own task, so a slow or absent AI service cannot | 147 | // the dispatch runs in its own task, so a slow or absent AI service cannot |
| 147 | // delay or fail this 201. | 148 | // delay or fail this 201. |
| @@ -189,7 +190,7 @@ async fn list( | |||
| 189 | } | 190 | } |
| 190 | let (limit, offset) = page.resolve()?; | 191 | let (limit, offset) = page.resolve()?; |
| 191 | let (notes, total) = | 192 | let (notes, total) = |
| 192 | - CourseNote::list_for_course(course.get_id(), limit, offset, &st.db).await?; | 193 | + service::course_note::list_for_course(&st.db, course.get_id(), limit, offset).await?; |
| 193 | let items = notes.iter().map(CourseNoteResponse::new).collect(); | 194 | let items = notes.iter().map(CourseNoteResponse::new).collect(); |
| 194 | Ok(Json(Page::new(items, total, limit, offset))) | 195 | Ok(Json(Page::new(items, total, limit, offset))) |
| 195 | } | 196 | } |
| @@ -267,7 +268,7 @@ async fn update( | |||
| 267 | .map(CourseNoteContent::try_new) | 268 | .map(CourseNoteContent::try_new) |
| 268 | .transpose()?; | 269 | .transpose()?; |
| 269 | 270 | ||
| 270 | - let updated = note.update(title, content, &st.db).await?; | 271 | + let updated = service::course_note::update(&st.db, note, title, content).await?; |
| 271 | // The stored index describes the old text — refresh it. | 272 | // The stored index describes the old text — refresh it. |
| 272 | spawn_index(&st, &tenant, updated.clone()); | 273 | spawn_index(&st, &tenant, updated.clone()); |
| 273 | Ok(Json(CourseNoteResponse::new(&updated))) | 274 | Ok(Json(CourseNoteResponse::new(&updated))) |
| @@ -310,7 +311,7 @@ async fn delete_one( | |||
| 310 | // between strands at worst an unreachable blob, never a row whose blob is | 311 | // between strands at worst an unreachable blob, never a row whose blob is |
| 311 | // already gone. The files to unlink come from the delete itself, not a | 312 | // already gone. The files to unlink come from the delete itself, not a |
| 312 | // pre-read list — an upload that landed in between is in the cascade too. | 313 | // pre-read list — an upload that landed in between is in the cascade too. |
| 313 | - let (_, files) = note.delete(&st.db).await?; | 314 | + let (_, files) = service::course_note::delete(&st.db, note).await?; |
| 314 | for file in &files { | 315 | for file in &files { |
| 315 | remove_blob(&st.files_path, file.get_id().key()).await; | 316 | remove_blob(&st.files_path, file.get_id().key()).await; |
| 316 | } | 317 | } |
| @@ -379,8 +380,9 @@ async fn upload_file( | |||
| 379 | )); | 380 | )); |
| 380 | } | 381 | } |
| 381 | crate::service::course::require_open(&st.db, &course).await?; | 382 | crate::service::course::require_open(&st.db, &course).await?; |
| 382 | - // The 10-file cap is enforced inside `CourseNoteFile::insert` (count and | 383 | + // The 10-file cap is enforced inside `service::course_note_file::insert` |
| 383 | - // create under one lock) — checking it here too would just race. | 384 | + // (count and create in one conditional write) — checking it here too would |
| 385 | + // just race. | ||
| 384 | let limit = service::settings::load(&st.db).await?.get_max_file_bytes(); | 386 | let limit = service::settings::load(&st.db).await?.get_max_file_bytes(); |
| 385 | 387 | ||
| 386 | let upload = read_upload(&mut multipart, limit).await?; | 388 | let upload = read_upload(&mut multipart, limit).await?; |
| @@ -395,7 +397,7 @@ async fn upload_file( | |||
| 395 | tokio::fs::write(&path, &upload.data) | 397 | tokio::fs::write(&path, &upload.data) |
| 396 | .await | 398 | .await |
| 397 | .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; | 399 | .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; |
| 398 | - match file.insert(&st.db).await { | 400 | + match service::course_note_file::insert(&st.db, file).await { |
| 399 | Ok(created) => { | 401 | Ok(created) => { |
| 400 | // The note now holds one more source than the stored index knows. | 402 | // The note now holds one more source than the stored index knows. |
| 401 | spawn_index(&st, &tenant, note); | 403 | spawn_index(&st, &tenant, note); |
| @@ -440,7 +442,8 @@ async fn list_files( | |||
| 440 | "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note's files", | 442 | "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note's files", |
| 441 | )); | 443 | )); |
| 442 | } | 444 | } |
| 443 | - let (files, total) = CourseNoteFile::list_for(note.get_id(), limit, offset, &st.db).await?; | 445 | + let (files, total) = |
| 446 | + service::course_note_file::list_for(&st.db, note.get_id(), limit, offset).await?; | ||
| 444 | let items = files.iter().map(CourseNoteFileResponse::new).collect(); | 447 | let items = files.iter().map(CourseNoteFileResponse::new).collect(); |
| 445 | Ok(Json(Page::new(items, total, limit, offset))) | 448 | Ok(Json(Page::new(items, total, limit, offset))) |
| 446 | } | 449 | } |
| @@ -474,10 +477,13 @@ async fn download_file( | |||
| 474 | "only enrolled users, the course creator, an assigned teacher, or a manager/admin can download this course note's files", | 477 | "only enrolled users, the course creator, an assigned teacher, or a manager/admin can download this course note's files", |
| 475 | )); | 478 | )); |
| 476 | } | 479 | } |
| 477 | - let file = | 480 | + let file = service::course_note_file::read_for( |
| 478 | - CourseNoteFile::read_for(&CourseNoteFileId::from_key(&file_id), note.get_id(), &st.db) | 481 | + &st.db, |
| 479 | - .await? | 482 | + &CourseNoteFileId::from_key(&file_id), |
| 480 | - .ok_or(AppError::NotFound)?; | 483 | + note.get_id(), |
| 484 | + ) | ||
| 485 | + .await? | ||
| 486 | + .ok_or(AppError::NotFound)?; | ||
| 481 | let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id().key())) | 487 | let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id().key())) |
| 482 | .await | 488 | .await |
| 483 | .map_err(|err| { | 489 | .map_err(|err| { |
| @@ -534,16 +540,19 @@ async fn delete_file( | |||
| 534 | )); | 540 | )); |
| 535 | } | 541 | } |
| 536 | crate::service::course::require_open(&st.db, &course).await?; | 542 | crate::service::course::require_open(&st.db, &course).await?; |
| 537 | - let file = | 543 | + let file = service::course_note_file::read_for( |
| 538 | - CourseNoteFile::read_for(&CourseNoteFileId::from_key(&file_id), note.get_id(), &st.db) | 544 | + &st.db, |
| 539 | - .await? | 545 | + &CourseNoteFileId::from_key(&file_id), |
| 540 | - .ok_or(AppError::NotFound)?; | 546 | + note.get_id(), |
| 547 | + ) | ||
| 548 | + .await? | ||
| 549 | + .ok_or(AppError::NotFound)?; | ||
| 541 | // Drop every output built from this file before the file itself, so a | 550 | // Drop every output built from this file before the file itself, so a |
| 542 | // stale index cannot outlive its source in a deployment with no AI service | 551 | // stale index cannot outlive its source in a deployment with no AI service |
| 543 | // at all, and a failure here leaves the file whole instead of stranding its | 552 | // at all, and a failure here leaves the file whole instead of stranding its |
| 544 | // blob; the re-index rebuilds from what is left, if a service is connected. | 553 | // blob; the re-index rebuilds from what is left, if a service is connected. |
| 545 | service::rag_output::delete_with_source(&st.db, file.get_id()).await?; | 554 | service::rag_output::delete_with_source(&st.db, file.get_id()).await?; |
| 546 | - let file = file.delete(&st.db).await?; | 555 | + let file = service::course_note_file::delete(&st.db, file).await?; |
| 547 | remove_blob(&st.files_path, file.get_id().key()).await; | 556 | remove_blob(&st.files_path, file.get_id().key()).await; |
| 548 | spawn_index(&st, &tenant, note); | 557 | spawn_index(&st, &tenant, note); |
| 549 | Ok(StatusCode::NO_CONTENT) | 558 | Ok(StatusCode::NO_CONTENT) |
| @@ -650,7 +659,7 @@ async fn delete_rag( | |||
| 650 | )); | 659 | )); |
| 651 | } | 660 | } |
| 652 | crate::service::course::require_open(&st.db, &course).await?; | 661 | crate::service::course::require_open(&st.db, &course).await?; |
| 653 | - // Scoped to the note in the path, like `CourseNoteFile::read_for`: an | 662 | + // Scoped to the note in the path, like `service::course_note_file::read_for`: an |
| 654 | // output of another note is a 404 here, never a cross-note delete. | 663 | // output of another note is a 404 here, never a cross-note delete. |
| 655 | let output = service::rag_output::read(&st.db, &RagOutputId::from_key(&output_id)) | 664 | let output = service::rag_output::read(&st.db, &RagOutputId::from_key(&output_id)) |
| 656 | .await? | 665 | .await? |
src/web/notes.rsmodified+8 -7
| @@ -272,8 +272,9 @@ async fn upload_file( | |||
| 272 | let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) | 272 | let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) |
| 273 | .await? | 273 | .await? |
| 274 | .ok_or(AppError::NotFound)?; | 274 | .ok_or(AppError::NotFound)?; |
| 275 | - // The 10-file cap is enforced inside `NoteFile::insert` (count and create | 275 | + // The 10-file cap is enforced inside `service::note_file::insert` (count |
| 276 | - // under one lock) — checking it here too would just race. | 276 | + // and create in one conditional write) — checking it here too would just |
| 277 | + // race. | ||
| 277 | let limit = service::settings::load(&st.db).await?.get_max_file_bytes(); | 278 | let limit = service::settings::load(&st.db).await?.get_max_file_bytes(); |
| 278 | 279 | ||
| 279 | let upload = read_upload(&mut multipart, limit).await?; | 280 | let upload = read_upload(&mut multipart, limit).await?; |
| @@ -288,7 +289,7 @@ async fn upload_file( | |||
| 288 | tokio::fs::write(&path, &upload.data) | 289 | tokio::fs::write(&path, &upload.data) |
| 289 | .await | 290 | .await |
| 290 | .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; | 291 | .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; |
| 291 | - match file.insert(&st.db).await { | 292 | + match service::note_file::insert(&st.db, file).await { |
| 292 | Ok(created) => Ok((StatusCode::CREATED, Json(NoteFileResponse::new(&created)))), | 293 | Ok(created) => Ok((StatusCode::CREATED, Json(NoteFileResponse::new(&created)))), |
| 293 | Err(err) => { | 294 | Err(err) => { |
| 294 | let _ = tokio::fs::remove_file(&path).await; | 295 | let _ = tokio::fs::remove_file(&path).await; |
| @@ -322,7 +323,7 @@ async fn list_files( | |||
| 322 | let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) | 323 | let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) |
| 323 | .await? | 324 | .await? |
| 324 | .ok_or(AppError::NotFound)?; | 325 | .ok_or(AppError::NotFound)?; |
| 325 | - let (files, total) = NoteFile::list_for(note.get_id(), limit, offset, &st.db).await?; | 326 | + let (files, total) = service::note_file::list_for(&st.db, note.get_id(), limit, offset).await?; |
| 326 | let items = files.iter().map(NoteFileResponse::new).collect(); | 327 | let items = files.iter().map(NoteFileResponse::new).collect(); |
| 327 | Ok(Json(Page::new(items, total, limit, offset))) | 328 | Ok(Json(Page::new(items, total, limit, offset))) |
| 328 | } | 329 | } |
| @@ -352,7 +353,7 @@ async fn download_file( | |||
| 352 | let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) | 353 | let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) |
| 353 | .await? | 354 | .await? |
| 354 | .ok_or(AppError::NotFound)?; | 355 | .ok_or(AppError::NotFound)?; |
| 355 | - let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db) | 356 | + let file = service::note_file::read_for(&st.db, &NoteFileId::from_key(&file_id), note.get_id()) |
| 356 | .await? | 357 | .await? |
| 357 | .ok_or(AppError::NotFound)?; | 358 | .ok_or(AppError::NotFound)?; |
| 358 | let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id().key())) | 359 | let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id().key())) |
| @@ -405,10 +406,10 @@ async fn delete_file( | |||
| 405 | let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) | 406 | let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) |
| 406 | .await? | 407 | .await? |
| 407 | .ok_or(AppError::NotFound)?; | 408 | .ok_or(AppError::NotFound)?; |
| 408 | - let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db) | 409 | + let file = service::note_file::read_for(&st.db, &NoteFileId::from_key(&file_id), note.get_id()) |
| 409 | .await? | 410 | .await? |
| 410 | .ok_or(AppError::NotFound)?; | 411 | .ok_or(AppError::NotFound)?; |
| 411 | - let file = file.delete(&st.db).await?; | 412 | + let file = service::note_file::delete(&st.db, file).await?; |
| 412 | remove_blob(&st.files_path, file.get_id().key()).await; | 413 | remove_blob(&st.files_path, file.get_id().key()).await; |
| 413 | Ok(StatusCode::NO_CONTENT) | 414 | Ok(StatusCode::NO_CONTENT) |
| 414 | } | 415 | } |
tests/integration.rsmodified+5 -3
| @@ -24974,12 +24974,12 @@ async fn draw( | |||
| 24974 | epoch: i64, | 24974 | epoch: i64, |
| 24975 | payload: &str, | 24975 | payload: &str, |
| 24976 | ) -> Result<BoardStroke, hezarfen_backend::error::AppError> { | 24976 | ) -> Result<BoardStroke, hezarfen_backend::error::AppError> { |
| 24977 | - BoardStroke::append( | 24977 | + hezarfen_backend::db::board_stroke::append( |
| 24978 | + db, | ||
| 24978 | &BoardId::from_key(board), | 24979 | &BoardId::from_key(board), |
| 24979 | &UserId::from_key(author), | 24980 | &UserId::from_key(author), |
| 24980 | payload, | 24981 | payload, |
| 24981 | epoch, | 24982 | epoch, |
| 24982 | - db, | ||
| 24983 | ) | 24983 | ) |
| 24984 | .await | 24984 | .await |
| 24985 | } | 24985 | } |
| @@ -24987,7 +24987,9 @@ async fn draw( | |||
| 24987 | /// The board row as the store holds it — never the response body, which cannot | 24987 | /// The board row as the store holds it — never the response body, which cannot |
| 24988 | /// prove a counter moved (src/domain/cap.rs:44-49). | 24988 | /// prove a counter moved (src/domain/cap.rs:44-49). |
| 24989 | async fn stored_board(db: &Database, board: &str) -> Option<Board> { | 24989 | async fn stored_board(db: &Database, board: &str) -> Option<Board> { |
| 24990 | - Board::read(&BoardId::from_key(board), db).await.unwrap() | 24990 | + hezarfen_backend::db::board::read(db, &BoardId::from_key(board)) |
| 24991 | + .await | ||
| 24992 | + .unwrap() | ||
| 24991 | } | 24993 | } |
| 24992 | 24994 | ||
| 24993 | /// Every stroke row of a board, oldest first, straight out of the table. | 24995 | /// Every stroke row of a board, oldest first, straight out of the table. |
tests/pagination.rsmodified+4 -4
| @@ -421,12 +421,12 @@ async fn board_lists_are_paged() { | |||
| 421 | // canvas. | 421 | // canvas. |
| 422 | for epoch in 0..2 { | 422 | for epoch in 0..2 { |
| 423 | for n in 0..2 { | 423 | for n in 0..2 { |
| 424 | - hezarfen_backend::domain::board_stroke::BoardStroke::append( | 424 | + hezarfen_backend::db::board_stroke::append( |
| 425 | + &db, | ||
| 425 | &hezarfen_backend::domain::board::BoardId::from_key(&board), | 426 | &hezarfen_backend::domain::board::BoardId::from_key(&board), |
| 426 | &hezarfen_backend::domain::user::UserId::from_key(&ali_id), | 427 | &hezarfen_backend::domain::user::UserId::from_key(&ali_id), |
| 427 | &format!("{{\"p\":[{epoch},{n}]}}"), | 428 | &format!("{{\"p\":[{epoch},{n}]}}"), |
| 428 | epoch, | 429 | epoch, |
| 429 | - &db, | ||
| 430 | ) | 430 | ) |
| 431 | .await | 431 | .await |
| 432 | .expect("append"); | 432 | .expect("append"); |
| @@ -442,12 +442,12 @@ async fn board_lists_are_paged() { | |||
| 442 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | 442 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 443 | } | 443 | } |
| 444 | for n in 0..5 { | 444 | for n in 0..5 { |
| 445 | - hezarfen_backend::domain::board_stroke::BoardStroke::append( | 445 | + hezarfen_backend::db::board_stroke::append( |
| 446 | + &db, | ||
| 446 | &hezarfen_backend::domain::board::BoardId::from_key(&board), | 447 | &hezarfen_backend::domain::board::BoardId::from_key(&board), |
| 447 | &hezarfen_backend::domain::user::UserId::from_key(&ali_id), | 448 | &hezarfen_backend::domain::user::UserId::from_key(&ali_id), |
| 448 | &format!("{{\"p\":[2,{n}]}}"), | 449 | &format!("{{\"p\":[2,{n}]}}"), |
| 449 | 2, | 450 | 2, |
| 450 | - &db, | ||
| 451 | ) | 451 | ) |
| 452 | .await | 452 | .await |
| 453 | .expect("append"); | 453 | .expect("append"); |
tests/persistence.rsmodified+2 -2
| @@ -2134,12 +2134,12 @@ async fn boards_and_their_strokes_survive_remigration() { | |||
| 2134 | 2134 | ||
| 2135 | // Two epochs: two marks cleared away, then one live mark. | 2135 | // Two epochs: two marks cleared away, then one live mark. |
| 2136 | let draw = async |epoch: i64, payload: &str| { | 2136 | let draw = async |epoch: i64, payload: &str| { |
| 2137 | - hezarfen_backend::domain::board_stroke::BoardStroke::append( | 2137 | + hezarfen_backend::db::board_stroke::append( |
| 2138 | + &db, | ||
| 2138 | &hezarfen_backend::domain::board::BoardId::from_key(&board), | 2139 | &hezarfen_backend::domain::board::BoardId::from_key(&board), |
| 2139 | &hezarfen_backend::domain::user::UserId::from_key(&ali_id), | 2140 | &hezarfen_backend::domain::user::UserId::from_key(&ali_id), |
| 2140 | payload, | 2141 | payload, |
| 2141 | epoch, | 2142 | epoch, |
| 2142 | - &db, | ||
| 2143 | ) | 2143 | ) |
| 2144 | .await | 2144 | .await |
| 2145 | .expect("append") | 2145 | .expect("append") |
tests/regress_boards.rsmodified+4 -5
| @@ -7,7 +7,6 @@ mod common; | |||
| 7 | use axum::http::StatusCode; | 7 | use axum::http::StatusCode; |
| 8 | use common::{app_and_db, items, login, me_id, send}; | 8 | use common::{app_and_db, items, login, me_id, send}; |
| 9 | use hezarfen_backend::domain::board::BoardId; | 9 | use hezarfen_backend::domain::board::BoardId; |
| 10 | -use hezarfen_backend::domain::board_stroke::BoardStroke; | ||
| 11 | use hezarfen_backend::domain::user::UserId; | 10 | use hezarfen_backend::domain::user::UserId; |
| 12 | use serde_json::json; | 11 | use serde_json::json; |
| 13 | 12 | ||
| @@ -38,12 +37,12 @@ async fn a_strokes_page_never_carries_a_clear_marker() { | |||
| 38 | let board = a_board(&app, &ali).await; | 37 | let board = a_board(&app, &ali).await; |
| 39 | 38 | ||
| 40 | for n in 0..2 { | 39 | for n in 0..2 { |
| 41 | - BoardStroke::append( | 40 | + hezarfen_backend::db::board_stroke::append( |
| 41 | + &db, | ||
| 42 | &BoardId::from_key(&board), | 42 | &BoardId::from_key(&board), |
| 43 | &UserId::from_key(&ali_id), | 43 | &UserId::from_key(&ali_id), |
| 44 | &format!("{{\"p\":[0,{n}]}}"), | 44 | &format!("{{\"p\":[0,{n}]}}"), |
| 45 | 0, | 45 | 0, |
| 46 | - &db, | ||
| 47 | ) | 46 | ) |
| 48 | .await | 47 | .await |
| 49 | .expect("append"); | 48 | .expect("append"); |
| @@ -120,12 +119,12 @@ async fn a_locked_board_refuses_the_creator_s_clear_with_409() { | |||
| 120 | let ali = login(&app, "ali").await; | 119 | let ali = login(&app, "ali").await; |
| 121 | let ali_id = me_id(&app, &ali).await; | 120 | let ali_id = me_id(&app, &ali).await; |
| 122 | let board = a_board(&app, &ali).await; | 121 | let board = a_board(&app, &ali).await; |
| 123 | - BoardStroke::append( | 122 | + hezarfen_backend::db::board_stroke::append( |
| 123 | + &db, | ||
| 124 | &BoardId::from_key(&board), | 124 | &BoardId::from_key(&board), |
| 125 | &UserId::from_key(&ali_id), | 125 | &UserId::from_key(&ali_id), |
| 126 | "{\"p\":[1,2]}", | 126 | "{\"p\":[1,2]}", |
| 127 | 0, | 127 | 0, |
| 128 | - &db, | ||
| 129 | ) | 128 | ) |
| 130 | .await | 129 | .await |
| 131 | .expect("append"); | 130 | .expect("append"); |
tests/regress_caps.rsmodified+8 -9
| @@ -13,7 +13,6 @@ mod common; | |||
| 13 | use axum::http::StatusCode; | 13 | use axum::http::StatusCode; |
| 14 | use common::{app_and_db, create_course, create_exam, enroll, id_of, login, login_as, me_id, send}; | 14 | use common::{app_and_db, create_course, create_exam, enroll, id_of, login, login_as, me_id, send}; |
| 15 | use hezarfen_backend::domain::board::BoardId; | 15 | use hezarfen_backend::domain::board::BoardId; |
| 16 | -use hezarfen_backend::domain::board_stroke::BoardStroke; | ||
| 17 | use hezarfen_backend::domain::user::UserId; | 16 | use hezarfen_backend::domain::user::UserId; |
| 18 | use serde_json::json; | 17 | use serde_json::json; |
| 19 | 18 | ||
| @@ -281,12 +280,12 @@ async fn a_blank_canvas_cannot_be_cleared_for_a_free_row() { | |||
| 281 | assert_eq!(rows(&db, &board).await, 0, "the refusal minted no marker"); | 280 | assert_eq!(rows(&db, &board).await, 0, "the refusal minted no marker"); |
| 282 | 281 | ||
| 283 | // One mark pays for one marker... | 282 | // One mark pays for one marker... |
| 284 | - BoardStroke::append( | 283 | + hezarfen_backend::db::board_stroke::append( |
| 284 | + &db, | ||
| 285 | &BoardId::from_key(&board), | 285 | &BoardId::from_key(&board), |
| 286 | &UserId::from_key(&ali_id), | 286 | &UserId::from_key(&ali_id), |
| 287 | "{\"p\":[1,2]}", | 287 | "{\"p\":[1,2]}", |
| 288 | 0, | 288 | 0, |
| 289 | - &db, | ||
| 290 | ) | 289 | ) |
| 291 | .await | 290 | .await |
| 292 | .expect("append"); | 291 | .expect("append"); |
| @@ -364,12 +363,12 @@ async fn a_clear_marker_is_charged_to_the_lifetime_counter() { | |||
| 364 | .await; | 363 | .await; |
| 365 | let board = id_of(&res.body); | 364 | let board = id_of(&res.body); |
| 366 | for _ in 0..2 { | 365 | for _ in 0..2 { |
| 367 | - BoardStroke::append( | 366 | + hezarfen_backend::db::board_stroke::append( |
| 367 | + &db, | ||
| 368 | &BoardId::from_key(&board), | 368 | &BoardId::from_key(&board), |
| 369 | &UserId::from_key(&ali_id), | 369 | &UserId::from_key(&ali_id), |
| 370 | "{\"p\":[1,2]}", | 370 | "{\"p\":[1,2]}", |
| 371 | 0, | 371 | 0, |
| 372 | - &db, | ||
| 373 | ) | 372 | ) |
| 374 | .await | 373 | .await |
| 375 | .expect("append"); | 374 | .expect("append"); |
| @@ -384,12 +383,12 @@ async fn a_clear_marker_is_charged_to_the_lifetime_counter() { | |||
| 384 | 383 | ||
| 385 | // The next epoch keeps counting from there — a marker is never re-counted | 384 | // The next epoch keeps counting from there — a marker is never re-counted |
| 386 | // and never uncounted. | 385 | // and never uncounted. |
| 387 | - BoardStroke::append( | 386 | + hezarfen_backend::db::board_stroke::append( |
| 387 | + &db, | ||
| 388 | &BoardId::from_key(&board), | 388 | &BoardId::from_key(&board), |
| 389 | &UserId::from_key(&ali_id), | 389 | &UserId::from_key(&ali_id), |
| 390 | "{\"p\":[3,4]}", | 390 | "{\"p\":[3,4]}", |
| 391 | 1, | 391 | 1, |
| 392 | - &db, | ||
| 393 | ) | 392 | ) |
| 394 | .await | 393 | .await |
| 395 | .expect("append"); | 394 | .expect("append"); |
| @@ -492,12 +491,12 @@ async fn a_boards_lifetime_counter_is_repaired_from_its_rows_on_boot() { | |||
| 492 | ) | 491 | ) |
| 493 | .await; | 492 | .await; |
| 494 | let board = id_of(&res.body); | 493 | let board = id_of(&res.body); |
| 495 | - BoardStroke::append( | 494 | + hezarfen_backend::db::board_stroke::append( |
| 495 | + &db, | ||
| 496 | &BoardId::from_key(&board), | 496 | &BoardId::from_key(&board), |
| 497 | &UserId::from_key(&ali_id), | 497 | &UserId::from_key(&ali_id), |
| 498 | "{\"p\":[1,2]}", | 498 | "{\"p\":[1,2]}", |
| 499 | 0, | 499 | 0, |
| 500 | - &db, | ||
| 501 | ) | 500 | ) |
| 502 | .await | 501 | .await |
| 503 | .expect("append"); | 502 | .expect("append"); |
tests/regress_course_child_orphans.rsmodified+23 -19
| @@ -51,7 +51,7 @@ use hezarfen_backend::database::{self, Database}; | |||
| 51 | use hezarfen_backend::db::course; | 51 | use hezarfen_backend::db::course; |
| 52 | use hezarfen_backend::db::course_session as db_course_session; | 52 | use hezarfen_backend::db::course_session as db_course_session; |
| 53 | use hezarfen_backend::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; | 53 | use hezarfen_backend::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; |
| 54 | -use hezarfen_backend::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; | 54 | +use hezarfen_backend::domain::course_note::{CourseNoteContent, CourseNoteTitle}; |
| 55 | use hezarfen_backend::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; | 55 | use hezarfen_backend::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; |
| 56 | use hezarfen_backend::domain::course_session::SessionTopic; | 56 | use hezarfen_backend::domain::course_session::SessionTopic; |
| 57 | use hezarfen_backend::domain::exam::{ | 57 | use hezarfen_backend::domain::exam::{ |
| @@ -151,12 +151,12 @@ fn make_subject(course: CourseId, db: Database) -> JoinHandle<Result<(), AppErro | |||
| 151 | 151 | ||
| 152 | fn make_note(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> { | 152 | fn make_note(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> { |
| 153 | tokio::spawn(async move { | 153 | tokio::spawn(async move { |
| 154 | - CourseNote::create( | 154 | + hezarfen_backend::db::course_note::create( |
| 155 | + &db, | ||
| 155 | &course, | 156 | &course, |
| 156 | &teacher(), | 157 | &teacher(), |
| 157 | CourseNoteTitle::try_new("plan").unwrap(), | 158 | CourseNoteTitle::try_new("plan").unwrap(), |
| 158 | CourseNoteContent::try_new("").unwrap(), | 159 | CourseNoteContent::try_new("").unwrap(), |
| 159 | - &db, | ||
| 160 | ) | 160 | ) |
| 161 | .await | 161 | .await |
| 162 | .map(|_| ()) | 162 | .map(|_| ()) |
| @@ -264,22 +264,24 @@ async fn the_creates_give_the_courses_roster_counter_back_untouched() { | |||
| 264 | async fn a_course_note_and_its_files_never_outlive_a_course_delete() { | 264 | async fn a_course_note_and_its_files_never_outlive_a_course_delete() { |
| 265 | let db = database::init_mem().await.unwrap(); | 265 | let db = database::init_mem().await.unwrap(); |
| 266 | let course = a_course(&db).await; | 266 | let course = a_course(&db).await; |
| 267 | - let note = CourseNote::create( | 267 | + let note = hezarfen_backend::db::course_note::create( |
| 268 | + &db, | ||
| 268 | &course, | 269 | &course, |
| 269 | &teacher(), | 270 | &teacher(), |
| 270 | CourseNoteTitle::try_new("plan").unwrap(), | 271 | CourseNoteTitle::try_new("plan").unwrap(), |
| 271 | CourseNoteContent::try_new("body").unwrap(), | 272 | CourseNoteContent::try_new("body").unwrap(), |
| 272 | - &db, | ||
| 273 | ) | 273 | ) |
| 274 | .await | 274 | .await |
| 275 | .unwrap(); | 275 | .unwrap(); |
| 276 | - CourseNoteFile::new( | 276 | + hezarfen_backend::db::course_note_file::insert( |
| 277 | - note.get_id(), | 277 | + &db, |
| 278 | - FileName::try_new("plan.pdf").unwrap(), | 278 | + CourseNoteFile::new( |
| 279 | - FileContentType::try_new("application/pdf").unwrap(), | 279 | + note.get_id(), |
| 280 | - 3, | 280 | + FileName::try_new("plan.pdf").unwrap(), |
| 281 | + FileContentType::try_new("application/pdf").unwrap(), | ||
| 282 | + 3, | ||
| 283 | + ), | ||
| 281 | ) | 284 | ) |
| 282 | - .insert(&db) | ||
| 283 | .await | 285 | .await |
| 284 | .unwrap(); | 286 | .unwrap(); |
| 285 | 287 | ||
| @@ -316,12 +318,12 @@ async fn a_course_note_and_its_files_never_outlive_a_course_delete() { | |||
| 316 | async fn a_course_note_file_under_a_deleted_note_is_refused() { | 318 | async fn a_course_note_file_under_a_deleted_note_is_refused() { |
| 317 | let db = database::init_mem().await.unwrap(); | 319 | let db = database::init_mem().await.unwrap(); |
| 318 | let course = a_course(&db).await; | 320 | let course = a_course(&db).await; |
| 319 | - let note = CourseNote::create( | 321 | + let note = hezarfen_backend::db::course_note::create( |
| 322 | + &db, | ||
| 320 | &course, | 323 | &course, |
| 321 | &teacher(), | 324 | &teacher(), |
| 322 | CourseNoteTitle::try_new("plan").unwrap(), | 325 | CourseNoteTitle::try_new("plan").unwrap(), |
| 323 | CourseNoteContent::try_new("").unwrap(), | 326 | CourseNoteContent::try_new("").unwrap(), |
| 324 | - &db, | ||
| 325 | ) | 327 | ) |
| 326 | .await | 328 | .await |
| 327 | .unwrap(); | 329 | .unwrap(); |
| @@ -332,13 +334,15 @@ async fn a_course_note_file_under_a_deleted_note_is_refused() { | |||
| 332 | "the course, and its note with it, goes" | 334 | "the course, and its note with it, goes" |
| 333 | ); | 335 | ); |
| 334 | 336 | ||
| 335 | - let file = CourseNoteFile::new( | 337 | + let file = hezarfen_backend::db::course_note_file::insert( |
| 336 | - note.get_id(), | 338 | + &db, |
| 337 | - FileName::try_new("plan.pdf").unwrap(), | 339 | + CourseNoteFile::new( |
| 338 | - FileContentType::try_new("application/pdf").unwrap(), | 340 | + note.get_id(), |
| 339 | - 3, | 341 | + FileName::try_new("plan.pdf").unwrap(), |
| 342 | + FileContentType::try_new("application/pdf").unwrap(), | ||
| 343 | + 3, | ||
| 344 | + ), | ||
| 340 | ) | 345 | ) |
| 341 | - .insert(&db) | ||
| 342 | .await; | 346 | .await; |
| 343 | assert!( | 347 | assert!( |
| 344 | matches!(file, Err(AppError::Conflict(_))), | 348 | matches!(file, Err(AppError::Conflict(_))), |