diff --git a/src/ai/rag.rs b/src/ai/rag.rs index cc35d4e..a73f2ad 100644 --- a/src/ai/rag.rs +++ b/src/ai/rag.rs @@ -110,7 +110,8 @@ pub async fn index_course_note(state: &AppState, tenant: &ResolvedTenant, note: // Read the attachments here rather than taking a caller's list: the // dispatch runs after the handler answered, so this is the freshest view // of what the note holds, and the ids it sends are the ids it stores. - let files = match CourseNoteFile::list_for(note.get_id(), None, 0, &state.db).await { + let files = match crate::db::course_note_file::list_for(&state.db, note.get_id(), None, 0).await + { Ok((files, _)) => files, Err(err) => { tracing::warn!("could not load course note files for rag.index: {err}"); diff --git a/src/ai/server.rs b/src/ai/server.rs index 086afb5..95ba0f0 100644 --- a/src/ai/server.rs +++ b/src/ai/server.rs @@ -27,8 +27,7 @@ use crate::constant::{ }; use crate::database::Database; -use crate::domain::course_note::CourseNote; -use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; +use crate::domain::course_note_file::CourseNoteFileId; use crate::domain::user::{User, UserId}; use crate::error::AppError; use crate::module::Module; @@ -631,11 +630,11 @@ async fn open_blob( ) }; let unavailable = |e: crate::error::AppError| ("unavailable", e.to_string()); - let file = CourseNoteFile::read(&CourseNoteFileId::from_key(&request.file), &db) + let file = crate::db::course_note_file::read(&db, &CourseNoteFileId::from_key(&request.file)) .await .map_err(unavailable)? .ok_or_else(missing)?; - let note = CourseNote::read(file.get_course_note(), &db) + let note = crate::db::course_note::read(&db, file.get_course_note()) .await .map_err(unavailable)? .ok_or_else(missing)?; diff --git a/src/db/board.rs b/src/db/board.rs new file mode 100644 index 0000000..f0a7484 --- /dev/null +++ b/src/db/board.rs @@ -0,0 +1,455 @@ +//! The `board` table: whiteboard rooms and their rosters. Every write here is +//! field-scoped `UPDATE … SET` — a stroke landing concurrently is moving the +//! two counters this table's struct does not carry. + +use surrealdb::types::SurrealValue; + +use crate::constant::{MAX_BOARDS_PER_CREATOR, USER_BOARD_COUNT_FIELD}; +use crate::database::{Database, transaction_with_retry}; +use crate::db::cap; +use crate::db::page::PagedList; +use crate::domain::board::{Board, BoardId, BoardTitle, checked_participants}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Open a board, taking a slot on the creator's `board_count` in the same +/// transaction as the row — the counter is the authority on how many +/// boards exist, so it can never count a row that did not commit. +pub async fn create( + db: &Database, + creator: &UserId, + title: BoardTitle, + participants: Vec, +) -> Result { + let board = Board { + id: BoardId::generate(), + creator: creator.clone(), + title, + participants: checked_participants(participants)?, + locked: false, + locked_by: None, + locked_at: None, + epoch: 0, + closed_at: None, + created_at: Timestamp::now(), + }; + match cap::claim_and_create( + &creator.record(), + USER_BOARD_COUNT_FIELD, + MAX_BOARDS_PER_CREATOR, + &board.id.record(), + &board, + db, + ) + .await? + { + cap::Claimed::Made(saved) => Ok(saved), + // Full, or the creator's row is gone — the conditional write + // matches nothing either way. + cap::Claimed::Full => Err(AppError::Conflict( + "you have reached the limit on boards — delete one first", + )), + // The id is a freshly minted ULID on a table with no UNIQUE index, + // so no rival can have aimed at it. + cap::Claimed::Duplicate => Err(AppError::Internal("board id collided".into())), + } +} + +pub async fn read(db: &Database, id: &BoardId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// Every board `user` may open: the ones they created and the ones they +/// were invited to. Newest first — the ids are monotonic, so `id` is the +/// creation order. +/// +/// `open` narrows by `closed_at`, and it means exactly that flag: a board +/// that is locked, or full at its lifetime cap but never drawn on again, is +/// never stamped and so reads as **open** — because it is. Only a creator's +/// `/close` and the lifetime cap's own refusal ever stamp one. +pub async fn list_for_user( + db: &Database, + user: &UserId, + open: Option, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + let open_clause = match open { + Some(true) => " AND closed_at = NONE", + Some(false) => " AND closed_at != NONE", + None => "", + }; + PagedList::new( + format!("board WHERE (creator = $usr OR participants CONTAINS $usr){open_clause}"), + "ORDER BY id DESC", + ) + .bind("usr", user.record()) + .run(limit, offset, db) + .await +} + +/// Re-invite. Field-scoped, like every write here: a stroke landing +/// concurrently is moving the counters this struct does not carry. +pub async fn set_participants( + db: &Database, + board: &Board, + participants: Vec, +) -> Result { + let participants = checked_participants(participants)?; + let mut result = db + .query("UPDATE $id SET participants = $who RETURN AFTER") + .bind(("id", board.id.record())) + .bind(( + "who", + participants + .iter() + .map(|user| user.record()) + .collect::>(), + )) + .await? + .check()?; + one(result.take::>(0)?) +} + +pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result { + let mut result = db + .query("UPDATE $id SET title = $title RETURN AFTER") + .bind(("id", board.id.record())) + .bind(("title", title.0)) + .await? + .check()?; + one(result.take::>(0)?) +} + +/// Freeze or thaw drawing. `locked_by`/`locked_at` are cleared on unlock so +/// the row never claims a lock that is not held. +pub async fn set_locked( + db: &Database, + board: &Board, + locked: bool, + by: &UserId, +) -> Result { + let now = Timestamp::now(); + let mut result = db + .query("UPDATE $id SET locked = $locked, locked_by = $by, locked_at = $at RETURN AFTER") + .bind(("id", board.id.record())) + .bind(("locked", locked)) + .bind(("by", locked.then(|| by.record()))) + .bind(("at", locked.then(|| now.as_millis()))) + .await? + .check()?; + one(result.take::>(0)?) +} + +// The demotion sweep — stripping a user off every roster they are listed +// on, deleting nothing, and handing the affected rooms back so the caller +// can prompt them — lives in [`crate::service::user::set_role`], where +// it commits with the role write that invalidates the membership. + +/// Retire the board: permanently read-only, history still readable. +/// Idempotent by the `WHERE` — a second call matches nothing and the first +/// stamp stands, which is what the stroke path's open-guard reads. +pub async fn close(db: &Database, board: &Board) -> Result { + let mut result = db + .query("UPDATE $id SET closed_at = $now WHERE closed_at = NONE RETURN AFTER") + .bind(("id", board.id.record())) + .bind(("now", Timestamp::now().as_millis())) + .await? + .check()?; + match result.take::>(0)?.into_iter().next() { + Some(board) => Ok(board), + // Already closed: the row is unchanged, so read it back rather + // than report a 404 for a board that plainly exists. + None => read(db, &board.id).await?.ok_or(AppError::NotFound), + } +} + +/// Delete the board and give the creator's slot back in the *same* +/// transaction — a release issued afterwards can be lost, and the counter +/// would then ratchet the creator's limit shut forever. +/// +/// The stroke cascade rides in that same transaction: it is the one and +/// only legitimate delete of `board_stroke` rows (a clear deletes nothing), +/// and issued separately it could leave a board's whole history orphaned +/// under a record that no longer exists. +pub async fn delete(db: &Database, board: Board) -> Result { + // A stroke claim writes the very board row this deletes, so the store + // aborts one of the two and a lost round is ordinary here — re-sent + // rather than reported as a 500. Re-sending is sound: every statement + // is a `DELETE` or a field-scoped `UPDATE`, none of which can ever + // answer "already exists" (see [`transaction_with_retry`]). + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; + DELETE board_stroke WHERE board = $id; + LET $gone = (DELETE $id RETURN BEFORE); + UPDATE $usr SET board_count = math::max([(board_count ?? 0) - array::len($gone), 0]); + RETURN $gone; + COMMIT TRANSACTION;", + &[ + ("id".into(), board.id.record().into_value()), + ("usr".into(), board.creator.record().into_value()), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Slots count BEGIN, the cascade, the LET and the UPDATE: the RETURN + // is slot 4. + one(result.take::>(4)?) +} + +fn one(rows: Vec) -> Result { + rows.into_iter().next().ok_or(AppError::NotFound) +} + +#[cfg(test)] +mod tests { + use super::*; + use surrealdb::types::RecordId; + + async fn a_db() -> Database { + let db = crate::database::init_mem().await.unwrap(); + db.query( + "CREATE user:c SET username = 'c', password_hash = 'x'; + CREATE user:p SET username = 'p', password_hash = 'x'; + CREATE user:s SET username = 's', password_hash = 'x';", + ) + .await + .unwrap() + .check() + .unwrap(); + db + } + + fn user(key: &str) -> UserId { + UserId::from_key(key) + } + + /// The stored counter, re-read out of the database. Never asserted off a + /// return value: the in-memory engine forges concurrent-write wins + /// (src/db/cap.rs:44-49). + async fn stored_count(db: &Database) -> i64 { + let mut result = db + .query("SELECT VALUE board_count ?? 0 FROM user:c") + .await + .unwrap() + .check() + .unwrap(); + result.take::>(0).unwrap()[0] + } + + async fn a_board(db: &Database) -> Board { + create( + db, + &user("c"), + BoardTitle::try_new("Geometri").unwrap(), + vec![user("p")], + ) + .await + .unwrap() + } + + /// The cap refuses at `MAX_BOARDS_PER_CREATOR`, and the refusal writes + /// nothing — asserted by re-reading the counter, not off the return value. + #[tokio::test] + async fn the_per_creator_cap_refuses_a_full_creator() { + let db = a_db().await; + db.query("UPDATE user:c SET board_count = $full") + .bind(("full", MAX_BOARDS_PER_CREATOR)) + .await + .unwrap() + .check() + .unwrap(); + let refused = create( + &db, + &user("c"), + BoardTitle::try_new("Geometri").unwrap(), + vec![], + ) + .await; + assert!(matches!(refused, Err(AppError::Conflict(_)))); + assert_eq!(stored_count(&db).await, MAX_BOARDS_PER_CREATOR); + let mut result = db + .query("SELECT VALUE id FROM board") + .await + .unwrap() + .check() + .unwrap(); + assert!(result.take::>(0).unwrap().is_empty()); + } + + /// A seat is taken on create and handed back on delete, both read back out + /// of the store. + #[tokio::test] + async fn a_seat_is_claimed_and_released() { + let db = a_db().await; + let board = a_board(&db).await; + assert_eq!(stored_count(&db).await, 1); + delete(&db, board).await.unwrap(); + assert_eq!(stored_count(&db).await, 0); + } + + /// Closing twice must not re-stamp: the first `closed_at` is the record. + #[tokio::test] + async fn close_is_idempotent() { + let db = a_db().await; + let board = a_board(&db).await; + let closed = close(&db, &board).await.unwrap(); + let first = closed.get_closed_at().unwrap(); + // A whole millisecond apart, so a re-stamp could not go unnoticed. + tokio::time::sleep(std::time::Duration::from_millis(2)).await; + assert_eq!( + close(&db, &board).await.unwrap().get_closed_at(), + Some(first) + ); + assert_eq!( + read(&db, board.get_id()) + .await + .unwrap() + .unwrap() + .get_closed_at(), + Some(first) + ); + } + + #[tokio::test] + async fn field_scoped_writes_leave_the_stroke_counters_alone() { + let db = a_db().await; + let board = a_board(&db).await; + db.query("UPDATE $id SET epoch_stroke_count = 7, total_stroke_count = 9") + .bind(("id", board.get_id().record())) + .await + .unwrap() + .check() + .unwrap(); + set_title(&db, &board, BoardTitle::try_new("Cebir").unwrap()) + .await + .unwrap(); + set_participants(&db, &board, vec![user("s")]) + .await + .unwrap(); + set_locked(&db, &board, true, &user("c")).await.unwrap(); + close(&db, &board).await.unwrap(); + let mut result = db + .query("SELECT VALUE [epoch_stroke_count, total_stroke_count] FROM $id") + .bind(("id", board.get_id().record())) + .await + .unwrap() + .check() + .unwrap(); + assert_eq!(result.take::>>(0).unwrap()[0], vec![7, 9]); + } + + /// [`delete`] cascades the stroke log and decrements the creator's + /// `board_count` off the very record a concurrent stroke claim increments, + /// so the two contend by design. Losing that round writes nothing, which is + /// what makes re-sending it the recovery; without + /// [`crate::database::transaction_with_retry`] a lost round comes out as a + /// 500. + /// + /// A refusal or an `Err(NotFound)` is *correct* here — the board really is + /// gone — and must not fail this test. The only defect is `AppError::Db`. + /// + /// Multi-threaded and on a real server for the reason spelled out on + /// [`super::super::course`]'s twin: the current-thread runtime never + /// interleaves the two, and the embedded engine does not conflict-check + /// concurrent writes to one record at all. + /// + /// Mutation status, stated honestly: cutting + /// [`crate::database::transaction_with_retry`] to a single attempt leaves + /// this GREEN — 5 runs of 5, every one at 20/20 contended. The mutation is + /// real, not a dud: the same cut reddens the `course.rs` twin in 2 runs of + /// 3. So the delete here never actually loses a round in this window, and + /// nothing in the suite exercises its retry. Read this as a smoke test that + /// a contended delete does not 500 — the retry stays because the batch is + /// admissible for it and a lost round is possible in principle, not because + /// a test has ever caught it losing one. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_delete_racing_a_stroke_never_answers_500() { + let (db, _serialized) = crate::database::init_test_server("board_delete_race").await; + db.query("CREATE user:c SET username = 'c', password_hash = 'x';") + .await + .unwrap() + .check() + .unwrap(); + let (mut delete_500, mut stroke_500, mut drawn) = (0, 0, 0); + let (mut last_delete, mut last_stroke) = (String::new(), String::new()); + for round in 0..20 { + let board = a_board(&db).await; + // The delete is held back by a sweeping beat: released together it + // is one statement while an append spends a read before it claims, + // so it would win every round and the guard would never be + // contended at all. Six racers over a 0-3ms sweep put the delete + // somewhere inside the counter writes instead. + let drop_it = { + let (board, db) = (board.clone(), db.clone()); + let beat = std::time::Duration::from_millis(round % 4); + tokio::spawn(async move { + tokio::time::sleep(beat).await; + delete(&db, board).await + }) + }; + let marks: Vec<_> = (0..6) + .map(|mark| { + let (id, db) = (board.get_id().clone(), db.clone()); + let author = user("c"); + tokio::spawn(async move { + crate::db::board_stroke::append( + &db, + &id, + &author, + &format!("{{\"m\":{mark}}}"), + 0, + ) + .await + }) + }) + .collect(); + let drop_it = drop_it.await.unwrap(); + if matches!(drop_it, Err(AppError::Db(_))) { + delete_500 += 1; + last_delete = format!("{drop_it:?}"); + } + // Contention is counted off the claim's own outcome, not off stored + // rows: the delete cascades `board_stroke`, so a stroke that landed + // and then lost its board leaves nothing behind to count. An `Ok` + // means the claim committed against the board row the delete was + // tearing down, which is exactly the overlap being measured. + let mut claimed = 0; + for mark in marks { + let mark = mark.await.unwrap(); + if matches!(mark, Err(AppError::Db(_))) { + stroke_500 += 1; + last_stroke = format!("{mark:?}"); + } + if mark.is_ok() { + claimed += 1; + } + } + if claimed > 0 { + drawn += 1; + } + } + eprintln!( + "Board::delete raced: {delete_500}/20 delete 500s, {stroke_500} stroke 500s, \ + {drawn}/20 rounds with a stroke claimed" + ); + assert!( + drawn > 0, + "no round ever landed a stroke, so the delete's cascade was never contended" + ); + assert_eq!( + delete_500, 0, + "a raced delete must retry, not 500: {delete_500}/20 rounds, last {last_delete}" + ); + assert_eq!( + stroke_500, 0, + "a raced stroke must retry, not 500: {stroke_500}/20 rounds, last {last_stroke}" + ); + } +} diff --git a/src/db/board_stroke.rs b/src/db/board_stroke.rs new file mode 100644 index 0000000..1904bf2 --- /dev/null +++ b/src/db/board_stroke.rs @@ -0,0 +1,800 @@ +//! The `board_stroke` table: every mark a board ever carried, plus the `clear` +//! markers that index its epochs, and the board's two stroke counters — all +//! written through the conditional claims in here and nowhere else. + +use surrealdb::types::{RecordId, SurrealValue, Value}; + +use crate::constant::{ + BOARD_EPOCH_STROKE_COUNT_FIELD, BOARD_OPEN_GUARD, BOARD_REPLAY_CHUNK, BOARD_STROKE_TABLE, + BOARD_TOTAL_STROKE_COUNT_FIELD, MAX_BOARD_STROKES, MAX_EPOCH_STROKES, MAX_STROKE_PAYLOAD_LEN, +}; +use crate::database::{Database, transaction_with_retry}; +use crate::db::cap; +use crate::db::page::PagedList; +use crate::domain::board::BoardId; +use crate::domain::board_stroke::{ + BOARD_CLOSED, BOARD_MOVED, BoardStroke, BoardStrokeId, CANVAS_BLANK, CLEAR_REFUSED, EPOCH_FULL, + KIND_CLEAR, KIND_STROKE, NOT_THE_CREATOR, state_refusal, +}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; +use crate::validate::validate_required; + +/// Append one mark to `board`'s current `epoch`. +/// +/// Both stroke counters and the row commit together or not at all: the +/// resettable epoch counter, the lifetime counter, and the open-board guard +/// are one conditional write, so a locked or closed board can never be +/// drawn on by a writer that read it a moment earlier. +/// +/// `epoch` rides in that guard too. Without it a clear landing between the +/// caller's board read and this write filed the row under the epoch that +/// just ended while its increment counted against the *new* epoch's +/// counter — one race, two markers corrupted for good (the closed one short +/// by a stroke, the next one claiming a stroke that is not there), and +/// markers are never rewritten. Now such a stroke is refused instead. +pub async fn append( + db: &Database, + board: &BoardId, + author: &UserId, + payload: &str, + epoch: i64, +) -> Result { + validate_required("payload", payload, MAX_STROKE_PAYLOAD_LEN)?; + let stroke = BoardStroke { + id: BoardStrokeId::generate(), + board: board.clone(), + author: author.clone(), + kind: KIND_STROKE.to_string(), + payload: Some(payload.to_string()), + count: None, + epoch, + created_at: Timestamp::now(), + }; + // `epoch` is an in-crate `i64` read off the board row, never text from + // a client, so it interpolates into the guard as a bare integer. + let guard = format!("{BOARD_OPEN_GUARD} AND epoch = {epoch}"); + match cap::claim_two_when_and_create( + &board.record(), + (BOARD_EPOCH_STROKE_COUNT_FIELD, MAX_EPOCH_STROKES), + (BOARD_TOTAL_STROKE_COUNT_FIELD, MAX_BOARD_STROKES), + &guard, + &stroke.id.record(), + &stroke, + db, + ) + .await? + { + cap::ClaimedTwo::Made(saved) => Ok(saved), + // The live canvas is full and nothing else: recoverable by a clear, + // which resets this counter without losing a single mark. + cap::ClaimedTwo::FullSoft => Err(AppError::Conflict(EPOCH_FULL)), + // Three refusals share this answer (lifetime full / guard failed / + // board gone), so the board is re-read to tell them apart. A board + // that changed state in between still gets told "no" — but only a + // re-read that *proves* the lifetime counter is spent may stamp + // `closed_at`, never elimination. + cap::ClaimedTwo::FullHard => Err(why_refused(db, board).await?), + } +} + +/// The one place `closed` is ordered above `locked` lives in +/// [`state_refusal`]; both refusal paths re-read the board and +/// ask it. + +async fn why_refused(db: &Database, board: &BoardId) -> Result { + let board = crate::db::board::read(db, board) + .await? + .ok_or(AppError::NotFound)?; + if let Some(refusal) = state_refusal(&board) { + return Ok(AppError::Conflict(refusal)); + } + // Neither flag, so the lifetime counter has to say so *itself*: + // `FullHard` also fires when the guard failed, so a board that was + // locked (or a clear that moved the epoch) when the claim ran and is + // open again now would otherwise be stamped read-only at one stroke of + // a 50 000 budget — irreversibly, with no reopen. + if total_strokes(db, board.get_id()).await? < MAX_BOARD_STROKES { + return Ok(AppError::Conflict(BOARD_MOVED)); + } + // `Board::close` is the one-way idempotent stamp: a second append takes + // this branch too and leaves the first `closed_at` standing. + crate::db::board::close(db, &board).await?; + Ok(AppError::Conflict(BOARD_CLOSED)) +} + +/// The lifetime counter as the store holds it — the board struct +/// deliberately does not carry it (src/domain/board.rs:9-13). +async fn total_strokes(db: &Database, board: &BoardId) -> Result { + let mut result = db + .query(format!( + "SELECT VALUE ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) FROM $b" + )) + .bind(("b", board.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next().unwrap_or(0)) +} + +/// End the current epoch: the canvas empties, the history does not. +/// +/// The bump and the marker are one transaction, because the marker carries +/// the epoch's final count — written apart, a crash between them would +/// leave an epoch no marker indexes, and the playback would silently join +/// two sessions into one. +/// +/// **The marker pays the lifetime counter.** It is a real `board_stroke` +/// row, so a marker that claimed nothing left `total_stroke_count` counting +/// strokes *drawn* rather than rows *stored*, and `MAX_BOARD_STROKES` +/// stopped bounding the table. Charged here, the counter is exactly the row +/// count again — the counter is reset and re-read in the same statement, so +/// the increment cannot be split off from the marker it pays for. +/// +/// **A blank canvas cannot be cleared.** Without it every call minted a row +/// for free, one per press of a button the creator can hold down. Requiring +/// the epoch counter to be non-zero pays for each marker with at least one +/// stroke it closes — and "there is nothing on this canvas to clear" is the +/// honest answer to the call it refuses. The epochs index keeps its meaning +/// too: no zero-stroke epoch can enter it. +/// +/// **A locked board cannot be cleared.** The lock is the creator's own +/// pause on the canvas, and it holds against every write to it including +/// theirs — [`BOARD_OPEN_GUARD`] is the same condition the stroke path +/// claims under, so "locked" means one thing everywhere. The cost is +/// accepted: a locked board sitting at `MAX_EPOCH_STROKES` is recovered by +/// unlock, clear, relock. +/// +/// The marker's own increment is not capped: the last stroke of a board's +/// budget may be closed by a marker, so a board holds at most +/// `MAX_BOARD_STROKES + 1` rows. Capping it would refuse the clear that +/// files the final epoch in the index, which is the one clear the history +/// needs. +pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result { + let marker = BoardStrokeId::generate(); + // `($before[0].epoch_stroke_count ?? 0)` is parenthesized: the bare form + // parses as `?? (0 = …)` and stores a boolean count (src/constant.rs:699). + let sql = format!( + "BEGIN TRANSACTION; + LET $before = (UPDATE $b SET epoch += 1, {BOARD_EPOCH_STROKE_COUNT_FIELD} = 0, \ + {BOARD_TOTAL_STROKE_COUNT_FIELD} = ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) + 1 \ + WHERE creator = $by AND {BOARD_OPEN_GUARD} \ + AND ({BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0) > 0 RETURN BEFORE); + IF array::len($before) = 0 {{ THROW '{CLEAR_REFUSED}' }}; + CREATE $mid CONTENT {{ board: $b, author: $by, kind: $kind, \ + epoch: $before[0].epoch, \ + count: ($before[0].{BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0), \ + created_at: $now }}; + COMMIT TRANSACTION;" + ); + let bound: Vec<(String, Value)> = vec![ + ("b".into(), board.record().into_value()), + ("by".into(), by.record().into_value()), + ("mid".into(), marker.record().into_value()), + ("kind".into(), KIND_CLEAR.into_value()), + ("now".into(), Timestamp::now().as_millis().into_value()), + ]; + // The epoch counter is reset here, which is a counter write like any + // other, so it owes the process the same one-at-a-time discipline + // (`cap::counter_lock`) — and unlike a lone conditional claim it is + // read back in the same statement, by the marker's `count`. + let _guard = cap::counter_lock().await; + let (mut result, mut errors) = + transaction_with_retry(db, &sql, &bound, &[CLEAR_REFUSED]).await?; + if errors + .values() + .any(|error| error.to_string().contains(CLEAR_REFUSED)) + { + return Err(why_clear_refused(db, board, by).await?); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Slots count BEGIN, the LET and the IF: the CREATE is slot 3. Only + // read once the error map is empty — `take_errors` swap-removes. + result + .take::>(3)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("board clear wrote no marker".into())) +} + +/// Which of the clear guard's four conditions said no. One `WHERE` cannot +/// report that itself, so the board is re-read — on the refusal path only, +/// like [`why_refused`]. The distinction is not cosmetic: a closed +/// board is terminal for the room, a blank canvas is an ordinary "nothing +/// to do" and a room told otherwise stops drawing for good. +async fn why_clear_refused( + db: &Database, + board: &BoardId, + by: &UserId, +) -> Result { + let board = crate::db::board::read(db, board) + .await? + .ok_or(AppError::NotFound)?; + let state = state_refusal(&board); + // Terminal outranks the caller's identity: a closed board is read-only + // for its creator too, so "closed" is the honest answer to anyone. + if state == Some(BOARD_CLOSED) { + return Ok(AppError::Conflict(BOARD_CLOSED)); + } + if !board.is_creator(by) { + return Ok(AppError::Forbidden(NOT_THE_CREATOR)); + } + // A lock pauses the *creator* too, and it is a state the caller can + // undo — a `Conflict`, not the `Forbidden` a wrong caller gets. Unlock, + // clear, relock is the recovery for a locked board that is also full. + if let Some(refusal) = state { + return Ok(AppError::Conflict(refusal)); + } + Ok(AppError::Conflict(CANVAS_BLANK)) +} + +/// What a joining socket draws: the current epoch's marks only, in mint +/// order, one [`BOARD_REPLAY_CHUNK`] at a time. +/// +/// Paged by `id`, never `created_at` — a millisecond stamp has ties by +/// construction, and the ULID's monotonic low half is exactly what breaks +/// them. `after` is the key of the last stroke already drawn. +pub async fn replay_current( + db: &Database, + board: &BoardId, + epoch: i64, + after: Option<&str>, +) -> Result, AppError> { + let cursor = match after { + Some(_) => " AND id > $after", + None => "", + }; + let mut result = db + .query(format!( + "SELECT * FROM {} \ + WHERE board = $b AND epoch = $e AND kind = $kind{cursor} \ + ORDER BY id LIMIT $chunk", + BOARD_STROKE_TABLE + )) + .bind(("b", board.record())) + .bind(("e", epoch)) + .bind(("kind", KIND_STROKE)) + .bind(( + "after", + RecordId::new(BOARD_STROKE_TABLE, after.unwrap_or_default()), + )) + .bind(("chunk", BOARD_REPLAY_CHUNK as i64)) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// The whole log, oldest first — every epoch, or one named epoch. Both +/// kinds of row come back: the `clear` markers are what tell a reader where +/// one epoch ended and the next began. +/// +/// `marks_only` drops the markers, which is what the *live canvas* wants: +/// the current epoch holds no marker by construction, except in the one +/// race where a clear commits between the board read and this read and +/// files its marker under the epoch just named. The room's replay filters +/// to `kind = 'stroke'` ([`replay_current`]), so without this the two +/// views disagree in exactly that window. +pub async fn history( + db: &Database, + board: &BoardId, + epoch: Option, + marks_only: bool, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + let scope = match epoch { + Some(_) => " AND epoch = $e", + None => "", + }; + let kinds = if marks_only { + " AND kind != $clear" + } else { + "" + }; + PagedList::new( + format!("{} WHERE board = $b{scope}{kinds}", BOARD_STROKE_TABLE), + "ORDER BY id", + ) + .bind("b", board.record()) + .bind("e", epoch.unwrap_or_default()) + .bind("clear", KIND_CLEAR.to_string()) + .run(limit, offset, db) + .await +} + +/// The epoch index: every `clear` marker this board has, oldest first. +pub async fn epochs(db: &Database, board: &BoardId) -> Result, AppError> { + let mut result = db + .query(format!( + "SELECT * FROM {} \ + WHERE board = $b AND kind = $kind ORDER BY id", + BOARD_STROKE_TABLE + )) + .bind(("b", board.record())) + .bind(("kind", KIND_CLEAR)) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::board::Board; + use crate::domain::board::BoardTitle; + use crate::domain::board_stroke::{BOARD_CLOSED, BOARD_LOCKED}; + + async fn a_db() -> Database { + let db = crate::database::init_mem().await.unwrap(); + db.query( + "CREATE user:c SET username = 'c', password_hash = 'x'; + CREATE user:p SET username = 'p', password_hash = 'x';", + ) + .await + .unwrap() + .check() + .unwrap(); + db + } + + fn user(key: &str) -> UserId { + UserId::from_key(key) + } + + async fn a_board(db: &Database) -> Board { + crate::db::board::create( + db, + &user("c"), + BoardTitle::try_new("Geometri").unwrap(), + vec![user("p")], + ) + .await + .unwrap() + } + + /// Every stroke row of a board, read straight out of the store — never off + /// a return value, which the in-memory engine forges wins on + /// (src/db/cap.rs:44-49). + async fn rows(db: &Database, board: &BoardId) -> Vec { + let mut result = db + .query("SELECT * FROM board_stroke WHERE board = $b ORDER BY id") + .bind(("b", board.record())) + .await + .unwrap() + .check() + .unwrap(); + result.take(0).unwrap() + } + + async fn reread(db: &Database, board: &Board) -> Board { + crate::db::board::read(db, board.get_id()) + .await + .unwrap() + .unwrap() + } + + async fn set_counters(db: &Database, board: &Board, epoch: i64, total: i64) { + db.query("UPDATE $id SET epoch_stroke_count = $e, total_stroke_count = $t") + .bind(("id", board.get_id().record())) + .bind(("e", epoch)) + .bind(("t", total)) + .await + .unwrap() + .check() + .unwrap(); + } + + async fn draw(db: &Database, board: &Board) -> Result { + append( + db, + board.get_id(), + &user("p"), + "{\"p\":[1,2]}", + board.get_epoch(), + ) + .await + } + + #[tokio::test] + async fn a_full_canvas_is_refused_but_the_board_stays_open() { + let db = a_db().await; + let board = a_board(&db).await; + set_counters(&db, &board, MAX_EPOCH_STROKES, 10).await; + let refused = draw(&db, &board).await; + assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("clear it"))); + // Nothing written, and above all: NOT closed — a full canvas is + // recoverable, and closing it here would make it permanent. + assert!(rows(&db, board.get_id()).await.is_empty()); + assert!(reread(&db, &board).await.get_closed_at().is_none()); + } + + /// The user's decision in one test: a clear empties the canvas and loses + /// nothing. If this ever passes with the pre-clear rows gone, the feature + /// is wrong. + #[tokio::test] + async fn a_clear_keeps_every_pre_clear_stroke() { + let db = a_db().await; + let board = a_board(&db).await; + for _ in 0..3 { + draw(&db, &board).await.unwrap(); + } + let before: Vec = rows(&db, board.get_id()) + .await + .iter() + .map(|row| row.get_id().key().to_string()) + .collect(); + + clear(&db, board.get_id(), &user("c")).await.unwrap(); + let board = reread(&db, &board).await; + assert_eq!(board.get_epoch(), 1); + draw(&db, &board).await.unwrap(); + + // The three original rows are still in the table, by direct read. + let after: Vec = rows(&db, board.get_id()) + .await + .iter() + .map(|row| row.get_id().key().to_string()) + .collect(); + for key in &before { + assert!(after.contains(key), "a clear deleted stroke {key}"); + } + // 3 old + 1 marker + 1 new, and the live canvas is the new one alone. + assert_eq!(after.len(), 5); + let live = replay_current(&db, board.get_id(), 1, None).await.unwrap(); + assert_eq!(live.len(), 1); + // The old epoch is still replayable in full. + assert_eq!( + replay_current(&db, board.get_id(), 0, None) + .await + .unwrap() + .len(), + 3 + ); + } + + /// The marker IS the epoch index, so its `count` has to be that epoch's + /// final stroke count — and `count` must appear on no other row. + #[tokio::test] + async fn the_marker_counts_the_epoch_it_closed() { + let db = a_db().await; + let board = a_board(&db).await; + for _ in 0..4 { + draw(&db, &board).await.unwrap(); + } + let marker = clear(&db, board.get_id(), &user("c")).await.unwrap(); + assert_eq!(marker.get_count(), Some(4)); + assert_eq!(marker.get_epoch(), 0); + assert!(marker.is_clear()); + + // And the epoch counter reset, so drawing resumes against a fresh cap. + let board = reread(&db, &board).await; + draw(&db, &board).await.unwrap(); + let epochs = epochs(&db, board.get_id()).await.unwrap(); + assert_eq!(epochs.len(), 1); + assert_eq!(epochs[0].get_count(), Some(4)); + // `count` lives on clear markers only — this module is that guard. + for row in rows(&db, board.get_id()).await { + assert_eq!(row.get_count().is_some(), row.is_clear()); + assert_eq!(row.get_payload().is_some(), !row.is_clear()); + } + } + + #[tokio::test] + async fn the_lifetime_cap_closes_the_board_exactly_once() { + let db = a_db().await; + let board = a_board(&db).await; + set_counters(&db, &board, 0, MAX_BOARD_STROKES).await; + let refused = draw(&db, &board).await; + assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("read-only"))); + let stamp = reread(&db, &board).await.get_closed_at(); + assert!(stamp.is_some()); + + // A whole millisecond apart, so a re-stamp could not go unnoticed. + tokio::time::sleep(std::time::Duration::from_millis(2)).await; + assert!(draw(&db, &board).await.is_err()); + assert_eq!(reread(&db, &board).await.get_closed_at(), stamp); + assert!(rows(&db, board.get_id()).await.is_empty()); + } + + /// A locked board must be told it is locked. Both refusals arrive as the + /// same `FullHard`, so a re-read that got this wrong would tell a paused + /// room its canvas is full — and send it clearing a board it need not clear. + #[tokio::test] + async fn a_locked_board_is_refused_as_locked() { + let db = a_db().await; + let board = a_board(&db).await; + let board = crate::db::board::set_locked(&db, &board, true, &user("c")) + .await + .unwrap(); + let refused = draw(&db, &board).await; + assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("locked"))); + assert!(rows(&db, board.get_id()).await.is_empty()); + // A lock is not a close: unlocking restores drawing. + assert!(reread(&db, &board).await.get_closed_at().is_none()); + let board = crate::db::board::set_locked(&db, &board, false, &user("c")) + .await + .unwrap(); + assert!(draw(&db, &board).await.is_ok()); + } + + /// A lock the stroke lost to, unlocked again before the refusal re-reads + /// the row — which is the state `why_refused` is handed after a guard + /// failure. Reading "neither locked nor closed" as proof of the lifetime + /// cap stamped `closed_at` on a board holding one stroke of 50 000, with + /// no reopen. Only the counter itself may close a board. + #[tokio::test] + async fn a_refusal_on_an_open_board_never_closes_it() { + let db = a_db().await; + let board = a_board(&db).await; + let board = crate::db::board::set_locked(&db, &board, true, &user("c")) + .await + .unwrap(); + // The claim loses the open-guard while the board is locked... + assert!(matches!( + draw(&db, &board).await, + Err(AppError::Conflict(_)) + )); + // ...and the creator unlocks before the refusal picks its message. + let board = crate::db::board::set_locked(&db, &board, false, &user("c")) + .await + .unwrap(); + let refused = why_refused(&db, board.get_id()).await.unwrap(); + assert!(matches!(refused, AppError::Conflict(msg) if !msg.contains("read-only"))); + // Stored state, not the return value: the board is still open, and + // still drawable. + assert!(reread(&db, &board).await.get_closed_at().is_none()); + assert!(draw(&db, &reread(&db, &board).await).await.is_ok()); + } + + /// The epoch index must never drift, in either direction. A stroke carrying + /// a pre-clear epoch used to land under the closed epoch while its + /// increment counted against the new one — the closed marker short by a + /// stroke, the next marker claiming one that is not there, both permanent. + #[tokio::test] + async fn a_stale_epoch_append_leaves_no_marker_drifted() { + let db = a_db().await; + let board = a_board(&db).await; + draw(&db, &board).await.unwrap(); + clear(&db, board.get_id(), &user("c")).await.unwrap(); + + // Exactly what `live_board` hands `append` when a clear lands between + // the board read and the write (src/web/board_ws.rs:431). + let stale = append(&db, board.get_id(), &user("p"), "{\"p\":[9]}", 0).await; + assert!(matches!(stale, Err(AppError::Conflict(_)))); + + let board = reread(&db, &board).await; + draw(&db, &board).await.unwrap(); + clear(&db, board.get_id(), &user("c")).await.unwrap(); + + // Every marker's count is the rows the store actually holds at the + // epoch it closed. + let stored = rows(&db, board.get_id()).await; + for marker in stored.iter().filter(|row| row.is_clear()) { + let actual = stored + .iter() + .filter(|row| !row.is_clear() && row.get_epoch() == marker.get_epoch()) + .count() as i64; + assert_eq!( + marker.get_count(), + Some(actual), + "marker for epoch {} drifted", + marker.get_epoch() + ); + } + // And the refused stroke claimed nothing: two marks and the two + // markers that closed them, which is every row on the table. + assert_eq!(total_strokes(&db, board.get_id()).await.unwrap(), 4); + assert_eq!(stored.len(), 4); + } + + /// The lock pauses the canvas against *every* write to it, its creator's + /// clear included — a `Conflict`, since unlocking undoes it, not the + /// `Forbidden` a non-creator gets. Asserted off stored rows: the refusal + /// must mint no marker and must not bump the epoch. + #[tokio::test] + async fn a_locked_board_refuses_its_creator_s_clear() { + let db = a_db().await; + let board = a_board(&db).await; + draw(&db, &board).await.unwrap(); + let board = crate::db::board::set_locked(&db, &board, true, &user("c")) + .await + .unwrap(); + + let refused = clear(&db, board.get_id(), &user("c")).await; + assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg == BOARD_LOCKED)); + assert_eq!(rows(&db, board.get_id()).await.len(), 1); + assert_eq!(reread(&db, &board).await.get_epoch(), 0); + assert!(epochs(&db, board.get_id()).await.unwrap().is_empty()); + + // Unlock, and the same clear lands: unlock → clear → relock is the + // recovery for a locked board sitting at the epoch cap. + let board = crate::db::board::set_locked(&db, &board, false, &user("c")) + .await + .unwrap(); + let marker = clear(&db, board.get_id(), &user("c")).await.unwrap(); + assert_eq!(marker.get_count(), Some(1)); + assert_eq!(reread(&db, &board).await.get_epoch(), 1); + } + + /// Both classifiers, one board: the words a stroke is refused with and the + /// words the *creator's* clear is refused with. They must match — the two + /// used to be independent chains and drifted apart on the state below. + async fn both_refusals(db: &Database, board: &Board) -> (&'static str, &'static str) { + let stroke = match draw(db, board).await { + Err(AppError::Conflict(msg)) => msg, + other => panic!("the stroke was not refused: {other:?}"), + }; + let clear = match clear(db, board.get_id(), &user("c")).await { + Err(AppError::Conflict(msg)) => msg, + other => panic!("the clear was not refused: {other:?}"), + }; + (stroke, clear) + } + + /// A board that is locked *and* closed is terminal, and both paths have to + /// say so. Reaching the state is ungated in either direction — `set_locked` + /// carries no `closed_at` test and `close` carries no lock test — and the + /// stroke path used to test the lock first, so a permanently read-only + /// board answered every mark with "the creator has paused drawing" while + /// the same board answered a clear with the terminal words. A room told to + /// wait for a pause that cannot lift waits forever. + /// + /// Locking a closed board stays *allowed*: it is a no-op on a board that is + /// already read-only, and refusing it would break the second half of a + /// close-then-lock a client may legitimately send in either order. + #[tokio::test] + async fn locked_and_closed_answers_closed_whichever_came_first() { + for closed_first in [false, true] { + let db = a_db().await; + let board = a_board(&db).await; + // A mark on the canvas, so "nothing to clear" cannot be the reason. + draw(&db, &board).await.unwrap(); + + let board = if closed_first { + let board = crate::db::board::close(&db, &board).await.unwrap(); + crate::db::board::set_locked(&db, &board, true, &user("c")) + .await + .unwrap() + } else { + let board = crate::db::board::set_locked(&db, &board, true, &user("c")) + .await + .unwrap(); + crate::db::board::close(&db, &board).await.unwrap() + }; + // Stored state: both flags really are up, and the close stamp stood. + let stored = reread(&db, &board).await; + assert!(stored.is_locked() && stored.get_closed_at().is_some()); + + assert_eq!( + both_refusals(&db, &board).await, + (BOARD_CLOSED, BOARD_CLOSED), + "closed_first = {closed_first}" + ); + // And the refusals wrote nothing: one mark, no marker, epoch 0. + assert_eq!(rows(&db, board.get_id()).await.len(), 1); + assert_eq!(reread(&db, &board).await.get_epoch(), 0); + } + } + + /// The other half of the same contract: a board holding *one* of the flags + /// keeps its own answer on both paths. A lock is recoverable, a close is + /// not, and collapsing either into the other is the mislabel above. + #[tokio::test] + async fn one_flag_alone_keeps_its_own_answer_on_both_paths() { + let db = a_db().await; + let locked = a_board(&db).await; + draw(&db, &locked).await.unwrap(); + let locked = crate::db::board::set_locked(&db, &locked, true, &user("c")) + .await + .unwrap(); + assert_eq!( + both_refusals(&db, &locked).await, + (BOARD_LOCKED, BOARD_LOCKED) + ); + + let closed = a_board(&db).await; + draw(&db, &closed).await.unwrap(); + let closed = crate::db::board::close(&db, &closed).await.unwrap(); + assert_eq!( + both_refusals(&db, &closed).await, + (BOARD_CLOSED, BOARD_CLOSED) + ); + } + + /// The `next_ulid` hazard: rows minted inside one millisecond must replay + /// in mint order, not at random (src/domain/monotonic_id.rs:41-46). + #[tokio::test] + async fn replay_is_in_mint_order_within_a_millisecond() { + let db = a_db().await; + let board = a_board(&db).await; + let mut minted = Vec::new(); + for _ in 0..25 { + minted.push(draw(&db, &board).await.unwrap().get_id().key().to_string()); + } + let replayed: Vec = replay_current(&db, board.get_id(), 0, None) + .await + .unwrap() + .iter() + .map(|row| row.get_id().key().to_string()) + .collect(); + assert_eq!(replayed, minted); + + // The cursor resumes exactly where the last chunk stopped. + let rest: Vec = replay_current(&db, board.get_id(), 0, Some(&minted[9])) + .await + .unwrap() + .iter() + .map(|row| row.get_id().key().to_string()) + .collect(); + assert_eq!(rest, minted[10..]); + } + + /// The one legitimate delete of stroke rows: without it, deleting a board + /// orphans its whole history under a record that no longer exists. + #[tokio::test] + async fn deleting_a_board_takes_its_strokes_with_it() { + let db = a_db().await; + let board = a_board(&db).await; + let other = a_board(&db).await; + draw(&db, &board).await.unwrap(); + draw(&db, &board).await.unwrap(); + clear(&db, board.get_id(), &user("c")).await.unwrap(); + draw(&db, &other).await.unwrap(); + + let id = board.get_id().clone(); + crate::db::board::delete(&db, board).await.unwrap(); + assert!(rows(&db, &id).await.is_empty()); + // The cascade is scoped to its own board. + assert_eq!(rows(&db, other.get_id()).await.len(), 1); + } + + #[tokio::test] + async fn an_oversized_payload_is_refused_before_the_write() { + let db = a_db().await; + let board = a_board(&db).await; + let big = "x".repeat(MAX_STROKE_PAYLOAD_LEN + 1); + assert!( + append(&db, board.get_id(), &user("p"), &big, 0) + .await + .is_err() + ); + assert!( + append(&db, board.get_id(), &user("p"), " ", 0) + .await + .is_err() + ); + assert!(rows(&db, board.get_id()).await.is_empty()); + // Nothing was claimed either — the counters must not have moved. + assert_eq!(reread(&db, &board).await.get_epoch(), 0); + } + + /// History spans epochs; a named epoch is that epoch alone. + #[tokio::test] + async fn history_spans_every_epoch_unless_one_is_named() { + let db = a_db().await; + let board = a_board(&db).await; + draw(&db, &board).await.unwrap(); + clear(&db, board.get_id(), &user("c")).await.unwrap(); + let board = reread(&db, &board).await; + draw(&db, &board).await.unwrap(); + + let (all, total) = history(&db, board.get_id(), None, false, None, 0) + .await + .unwrap(); + assert_eq!((all.len(), total), (3, 3)); + let (first, total) = history(&db, board.get_id(), Some(0), false, None, 0) + .await + .unwrap(); + // Epoch 0: its stroke and the marker that closed it. + assert_eq!((first.len(), total), (2, 2)); + // `marks_only` drops the marker from that same epoch — and its `total` + // with it, so the envelope's count stays the count of what is served. + let (marks, total) = history(&db, board.get_id(), Some(0), true, None, 0) + .await + .unwrap(); + assert_eq!((marks.len(), total), (1, 1)); + assert!(marks.iter().all(|row| !row.is_clear())); + } +} diff --git a/src/db/course_note.rs b/src/db/course_note.rs new file mode 100644 index 0000000..f21e158 --- /dev/null +++ b/src/db/course_note.rs @@ -0,0 +1,203 @@ +//! The `course_note` table: a teacher-authored note attached to a course, +//! listed newest first, deleted together with its attachment rows. + +use surrealdb::types::SurrealValue; + +use crate::constant::ENROLLMENT_COUNT_FIELD; +use crate::database::Database; +use crate::db::cap; +use crate::db::field_update::FieldUpdate; +use crate::db::page::PagedList; +use crate::domain::course::CourseId; +use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteId, CourseNoteTitle}; +use crate::domain::course_note_file::CourseNoteFile; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// What [`delete`]'s transaction removed: the note row (empty if it had +/// already vanished) and every attachment row the cascade took with it — the +/// only set whose blobs are safe to unlink. +#[derive(Debug, SurrealValue)] +struct DeleteOutcome { + note: Vec, + files: Vec, +} + +pub async fn create( + db: &Database, + course: &CourseId, + author: &UserId, + title: CourseNoteTitle, + content: CourseNoteContent, +) -> Result { + let note = CourseNote { + id: CourseNoteId::generate(), + course: course.clone(), + author: author.clone(), + title, + content, + }; + // The course row is *written* (bumped and put back), not read, so this + // collides with `Course::delete`'s cascade: a note that outlives its + // course is unreachable forever — every route to it goes through the + // course. See [`cap::touch_and_create`]. + cap::touch_and_create( + &course.record(), + ENROLLMENT_COUNT_FIELD, + ¬e.id.record(), + ¬e, + db, + ) + .await? + .ok_or(AppError::NotFound) +} + +pub async fn read(db: &Database, id: &CourseNoteId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +pub async fn list_for_course( + db: &Database, + course: &CourseId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new("course_note WHERE course = $crs", "ORDER BY id DESC") + .bind("crs", course.record()) + .run(limit, offset, db) + .await +} + +/// Request-scoped: no lock spans the handler's read and this write, so an +/// omitted field (`None`) is not written at all. Passing the snapshot's +/// value back instead would revert a concurrent edit of that field — +/// scoping the `SET` alone does not prevent that, the values have to come +/// from the request. Neither column is nullable, so plain `Option` per +/// field says everything there is to say. +pub async fn update( + db: &Database, + note: CourseNote, + title: Option, + content: Option, +) -> Result { + FieldUpdate::new(note.id.record()) + .set("title", title) + .set("content", content) + .run::(db) + .await +} + +/// Delete the note and cascade-remove its attachment rows, returning both: +/// the note, and the attachment rows this transaction actually removed. +/// Blob files on disk are the web layer's to remove, but only for *these* +/// rows — a row uploaded after the caller listed the note's files is +/// deleted here too, and a pre-read snapshot would strand its blob. +pub async fn delete( + db: &Database, + note: CourseNote, +) -> Result<(CourseNote, Vec), AppError> { + let mut result = db + .query( + "BEGIN TRANSACTION; + LET $files = (DELETE course_note_file WHERE course_note = $note RETURN BEFORE); + LET $gone = (DELETE $note RETURN BEFORE); + RETURN { note: $gone, files: $files }; + COMMIT TRANSACTION;", + ) + .bind(("note", note.id.record())) + .await? + .check()?; + // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3. + let outcome = result + .take::>(3)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to delete course note".into()))?; + let note = outcome.note.into_iter().next().ok_or(AppError::NotFound)?; + Ok((note, outcome.files)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; + use crate::domain::course_note_file::{FileContentType, FileName}; + + /// The blobs the handler unlinks are exactly the rows this transaction + /// removed — including one uploaded after any pre-read snapshot would have + /// been taken, which is the row whose blob used to leak. + #[tokio::test] + async fn delete_returns_the_attachment_rows_it_removed() { + let db = crate::database::init_mem().await.unwrap(); + let creator = crate::domain::user::UserId::generate(); + let course = crate::db::course::create( + &db, + &creator, + CourseTitle::try_new("Math").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::try_new("course").unwrap(), + None, + None, + ) + .await + .unwrap(); + let note = create( + &db, + course.get_id(), + &creator, + CourseNoteTitle::try_new("a").unwrap(), + CourseNoteContent::try_new("body").unwrap(), + ) + .await + .unwrap(); + // What a handler snapshot would have seen... + let early = crate::db::course_note_file::insert( + &db, + CourseNoteFile::new( + note.get_id(), + FileName::try_new("early.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ), + ) + .await + .unwrap(); + let (snapshot, _) = crate::db::course_note_file::list_for(&db, note.get_id(), None, 0) + .await + .unwrap(); + assert_eq!(snapshot.len(), 1); + // ...and the upload that races in after it. + let late = crate::db::course_note_file::insert( + &db, + CourseNoteFile::new( + note.get_id(), + FileName::try_new("late.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ), + ) + .await + .unwrap(); + + let (gone, files) = delete(&db, note).await.unwrap(); + assert_eq!(gone.get_title().as_str(), "a"); + let mut keys: Vec<_> = files + .iter() + .map(|file| file.get_id().key().to_string()) + .collect(); + keys.sort(); + let mut want = vec![ + early.get_id().key().to_string(), + late.get_id().key().to_string(), + ]; + want.sort(); + assert_eq!(keys, want); + assert!( + crate::db::course_note_file::list_for(&db, gone.get_id(), None, 0) + .await + .unwrap() + .0 + .is_empty() + ); + } +} diff --git a/src/db/course_note_file.rs b/src/db/course_note_file.rs new file mode 100644 index 0000000..1cbb256 --- /dev/null +++ b/src/db/course_note_file.rs @@ -0,0 +1,243 @@ +//! The `course_note_file` table: attachment rows for a course note, listed +//! newest first, with the note's file cap claimed and released in the same +//! write as the row. + +use surrealdb::types::{RecordId, RecordIdKey}; + +use crate::constant::{COURSE_NOTE_FILE_COUNT_FIELD, MAX_COURSE_NOTE_FILES}; +use crate::database::Database; +use crate::db::cap; +use crate::db::page::PagedList; +use crate::domain::course_note::CourseNoteId; +use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; +use crate::error::AppError; + +/// Persist the row assembled by [`CourseNoteFile::new`], refusing once its +/// note already holds [`MAX_COURSE_NOTE_FILES`]. The slot and the row are +/// taken together by [`cap::claim_and_create`] on the note row — see +/// [`crate::db::note_file::insert`] for why that is the only guard a +/// concurrent insert cannot outrun. +pub async fn insert(db: &Database, file: CourseNoteFile) -> Result { + // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber + match cap::claim_and_create( + &file.course_note.record(), + COURSE_NOTE_FILE_COUNT_FIELD, + MAX_COURSE_NOTE_FILES as i64, + &file.id.record(), + &file, + db, + ) + .await? + { + cap::Claimed::Made(created) => Ok(created), + // Also how a missing note reads: no note row means no slot to take. + cap::Claimed::Full => Err(AppError::Conflict( + "the course note already holds the maximum of 10 files — delete one first", + )), + // Unreachable: the id is a ULID this call just generated. + cap::Claimed::Duplicate => Err(AppError::Internal( + "failed to create course note file".into(), + )), + } +} + +/// Read a file's row by id alone, for the callers that have no note in +/// hand yet and reach the note *through* the file (the AI bridge's blob +/// stream). A key from any other table simply reads as `None`, which is +/// what keeps a personal note's file id unreachable here. +pub async fn read( + db: &Database, + id: &CourseNoteFileId, +) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// Read a file's row only if it belongs to `note` — callers have already +/// checked the note belongs to a course the caller may act on. +pub async fn read_for( + db: &Database, + id: &CourseNoteFileId, + note: &CourseNoteId, +) -> Result, AppError> { + let file: Option = db.select(id.record()).await?; + Ok(file.filter(|file| &file.course_note == note)) +} + +/// All of `note`'s attachment rows, newest first. +pub async fn list_for( + db: &Database, + note: &CourseNoteId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + "course_note_file WHERE course_note = $note", + "ORDER BY id DESC", + ) + .bind("note", note.record()) + .run(limit, offset, db) + .await +} + +/// The blob names (record keys, since a file's blob is named by its own +/// id) behind every note attachment of `course` — collected *before* the +/// course-delete cascade wipes the rows. +pub async fn file_keys_for_course( + db: &Database, + course: &crate::domain::course::CourseId, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT VALUE id FROM course_note_file \ + WHERE course_note IN (SELECT VALUE id FROM course_note WHERE course = $course)", + ) + .bind(("course", course.record())) + .await? + .check()?; + Ok(result + .take::>(0)? + .into_iter() + .map(|id| match id.key { + RecordIdKey::String(key) => key, + _ => String::new(), + }) + .collect()) +} + +/// Delete the row and give its slot back in the same transaction — the +/// note itself is untouched, so unlike the note-delete cascade this one +/// has a counter to correct. +pub async fn delete(db: &Database, file: CourseNoteFile) -> Result { + let mut result = db + .query( + "BEGIN TRANSACTION; + LET $gone = (DELETE $id RETURN BEFORE); + UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); + RETURN $gone; + COMMIT TRANSACTION;", + ) + .bind(("id", file.id.record())) + .bind(("note", file.course_note.record())) + .await? + .check()?; + result + .take::>(3)? + .into_iter() + .next() + .ok_or(AppError::NotFound) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database::Database; + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; + use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; + use crate::domain::course_note_file::{FileContentType, FileName}; + + async fn note_of(db: &Database, title: &str) -> CourseNote { + let creator = crate::domain::user::UserId::generate(); + let course = crate::db::course::create( + db, + &creator, + CourseTitle::try_new("c").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::try_new("course").unwrap(), + None, + None, + ) + .await + .unwrap(); + crate::db::course_note::create( + db, + course.get_id(), + &creator, + CourseNoteTitle::try_new(title).unwrap(), + CourseNoteContent::try_new("body").unwrap(), + ) + .await + .unwrap() + } + + #[tokio::test] + async fn rows_scope_to_their_note() { + let db = crate::database::init_mem().await.unwrap(); + let note_a = note_of(&db, "a").await.get_id().clone(); + let note_b = note_of(&db, "b").await.get_id().clone(); + let file = insert( + &db, + CourseNoteFile::new( + ¬e_a, + FileName::try_new("plan.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ), + ) + .await + .unwrap(); + + let found = read_for(&db, file.get_id(), ¬e_a).await.unwrap(); + assert_eq!(found.unwrap().get_name().as_str(), "plan.pdf"); + assert!( + read_for(&db, file.get_id(), ¬e_b) + .await + .unwrap() + .is_none() + ); + + let listed = async |note: &CourseNoteId| list_for(&db, note, None, 0).await.unwrap().0; + assert_eq!(listed(¬e_a).await.len(), 1); + assert!(listed(¬e_b).await.is_empty()); + + delete(&db, file).await.unwrap(); + assert!(listed(¬e_a).await.is_empty()); + } + + /// The counter and the rows are written in one transaction, so the stored + /// count must equal the stored rows — after a success *and* after the + /// refusal that fills the cap, which must move neither. + #[tokio::test] + async fn counter_tracks_stored_rows() { + let db = crate::database::init_mem().await.unwrap(); + let note = note_of(&db, "a").await.get_id().clone(); + let stored_count = async |note: &CourseNoteId| -> i64 { + db.query("SELECT VALUE file_count FROM $note") + .bind(("note", note.record())) + .await + .unwrap() + .take::>(0) + .unwrap() + .into_iter() + .next() + .unwrap_or(0) + }; + let add = async |note: &CourseNoteId| { + insert( + &db, + CourseNoteFile::new( + note, + FileName::try_new("plan.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ), + ) + .await + }; + + for filled in 1..=MAX_COURSE_NOTE_FILES { + add(¬e).await.unwrap(); + assert_eq!(stored_count(¬e).await, filled as i64); + assert_eq!( + list_for(&db, ¬e, None, 0).await.unwrap().1, + filled as i64 + ); + } + + assert!(matches!(add(¬e).await, Err(AppError::Conflict(_)))); + assert_eq!(stored_count(¬e).await, MAX_COURSE_NOTE_FILES as i64); + assert_eq!( + list_for(&db, ¬e, None, 0).await.unwrap().1, + MAX_COURSE_NOTE_FILES as i64 + ); + } +} diff --git a/src/db/mod.rs b/src/db/mod.rs index e164f1b..ea39bd9 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -2,9 +2,13 @@ pub mod appointment; pub mod appointment_slot; +pub mod board; +pub mod board_stroke; pub mod cap; pub mod class_blueprint; pub mod course; +pub mod course_note; +pub mod course_note_file; pub mod course_session; pub mod enrollment; pub mod exam; @@ -13,6 +17,7 @@ pub mod exam_question; pub mod field_update; pub mod meal_booking; pub mod note; +pub mod note_file; pub mod page; pub mod payment_ledger; pub mod session; diff --git a/src/db/note.rs b/src/db/note.rs index eb1f0f1..30d93db 100644 --- a/src/db/note.rs +++ b/src/db/note.rs @@ -133,27 +133,31 @@ mod tests { .await .unwrap(); // What a handler snapshot would have seen... - let early = NoteFile::new( - note.get_id(), - FileName::try_new("early.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, + let early = crate::db::note_file::insert( + &db, + NoteFile::new( + note.get_id(), + FileName::try_new("early.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ), ) - .insert(&db) .await .unwrap(); - let (snapshot, _) = NoteFile::list_for(note.get_id(), None, 0, &db) + let (snapshot, _) = crate::db::note_file::list_for(&db, note.get_id(), None, 0) .await .unwrap(); assert_eq!(snapshot.len(), 1); // ...and the upload that races in after it. - let late = NoteFile::new( - note.get_id(), - FileName::try_new("late.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, + let late = crate::db::note_file::insert( + &db, + NoteFile::new( + note.get_id(), + FileName::try_new("late.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ), ) - .insert(&db) .await .unwrap(); @@ -171,7 +175,7 @@ mod tests { want.sort(); assert_eq!(keys, want); assert!( - NoteFile::list_for(gone.get_id(), None, 0, &db) + crate::db::note_file::list_for(&db, gone.get_id(), None, 0) .await .unwrap() .0 diff --git a/src/db/note_file.rs b/src/db/note_file.rs new file mode 100644 index 0000000..62f1b5a --- /dev/null +++ b/src/db/note_file.rs @@ -0,0 +1,200 @@ +//! The `note_file` table: attachment rows for a personal note, listed newest +//! first, with the note's file cap claimed and released in the same write as +//! the row. + +use crate::constant::{MAX_NOTE_FILES, NOTE_FILE_COUNT_FIELD}; +use crate::database::Database; +use crate::db::cap; +use crate::db::page::PagedList; +use crate::domain::note::NoteId; +use crate::domain::note_file::{NoteFile, NoteFileId}; +use crate::error::AppError; + +/// Persist the row assembled by [`NoteFile::new`], refusing once its note +/// already holds [`MAX_NOTE_FILES`]. The slot and the row are taken together +/// by [`cap::claim_and_create`] on the note row: a `BEGIN…COMMIT` around a +/// count can't enforce the cap (SurrealDB doesn't conflict-check a +/// cross-record count against a concurrent insert) and a process-wide mutex +/// can't either, since it is released around the very round trip the insert +/// races — a conditional single-record write can. Claiming in a *separate* +/// query would enforce the cap but leak a slot on a crash between the two. +pub async fn insert(db: &Database, file: NoteFile) -> Result { + // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber + match cap::claim_and_create( + &file.note.record(), + NOTE_FILE_COUNT_FIELD, + MAX_NOTE_FILES as i64, + &file.id.record(), + &file, + db, + ) + .await? + { + cap::Claimed::Made(created) => Ok(created), + // Also how a missing note reads: no note row means no slot to take. + cap::Claimed::Full => Err(AppError::Conflict( + "the note already holds the maximum of 10 files — delete one first", + )), + // Unreachable: the id is a ULID this call just generated. + cap::Claimed::Duplicate => Err(AppError::Internal("failed to create note file".into())), + } +} + +/// Read a file's row only if it belongs to `note` — callers have already +/// checked the note belongs to the requesting user. +pub async fn read_for( + db: &Database, + id: &NoteFileId, + note: &NoteId, +) -> Result, AppError> { + let file: Option = db.select(id.record()).await?; + Ok(file.filter(|file| &file.note == note)) +} + +/// All of `note`'s attachment rows, newest first. +pub async fn list_for( + db: &Database, + note: &NoteId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new("note_file WHERE note = $note", "ORDER BY id DESC") + .bind("note", note.record()) + .run(limit, offset, db) + .await +} + +/// Delete the row and give its slot back in the same transaction — the note +/// itself is untouched, so unlike the note-delete cascade this one has a +/// counter to correct. (Deleting a *note* takes its counter with it.) +pub async fn delete(db: &Database, file: NoteFile) -> Result { + let mut result = db + .query( + "BEGIN TRANSACTION; + LET $gone = (DELETE $id RETURN BEFORE); + UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); + RETURN $gone; + COMMIT TRANSACTION;", + ) + .bind(("id", file.id.record())) + .bind(("note", file.note.record())) + .await? + .check()?; + result + .take::>(3)? + .into_iter() + .next() + .ok_or(AppError::NotFound) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::note_file::{FileContentType, FileName}; + + #[tokio::test] + async fn rows_scope_to_their_note() { + let db = crate::database::init_mem().await.unwrap(); + // Real note rows: the cap counter lives on the note, so an insert whose + // note does not exist has no slot to take (a 409, like a full note). + let owner = crate::domain::user::UserId::generate(); + let note_of = async |title: &str| { + crate::db::note::create( + &db, + &owner, + crate::domain::note::NoteTitle::try_new(title).unwrap(), + crate::domain::note::NoteContent::try_new("body").unwrap(), + ) + .await + .unwrap() + }; + let note_a = note_of("a").await.get_id().clone(); + let note_b = note_of("b").await.get_id().clone(); + let file = insert( + &db, + NoteFile::new( + ¬e_a, + FileName::try_new("plan.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ), + ) + .await + .unwrap(); + + // Readable under its own note, invisible under another. + let found = read_for(&db, file.get_id(), ¬e_a).await.unwrap(); + assert_eq!(found.unwrap().get_name().as_str(), "plan.pdf"); + assert!( + read_for(&db, file.get_id(), ¬e_b) + .await + .unwrap() + .is_none() + ); + + let listed = async |note: &NoteId| list_for(&db, note, None, 0).await.unwrap().0; + assert_eq!(listed(¬e_a).await.len(), 1); + assert!(listed(¬e_b).await.is_empty()); + + delete(&db, file).await.unwrap(); + assert!(listed(¬e_a).await.is_empty()); + } + + /// The counter and the rows are written in one transaction, so the stored + /// count must equal the stored rows — after a success *and* after the + /// refusal that fills the cap, which must move neither. + #[tokio::test] + async fn counter_tracks_stored_rows() { + let db = crate::database::init_mem().await.unwrap(); + let note = crate::db::note::create( + &db, + &crate::domain::user::UserId::generate(), + crate::domain::note::NoteTitle::try_new("a").unwrap(), + crate::domain::note::NoteContent::try_new("body").unwrap(), + ) + .await + .unwrap() + .get_id() + .clone(); + let stored_count = async |note: &NoteId| -> i64 { + db.query("SELECT VALUE file_count FROM $note") + .bind(("note", note.record())) + .await + .unwrap() + .take::>(0) + .unwrap() + .into_iter() + .next() + .unwrap_or(0) + }; + let add = async |note: &NoteId| { + insert( + &db, + NoteFile::new( + note, + FileName::try_new("plan.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ), + ) + .await + }; + + for filled in 1..=MAX_NOTE_FILES { + add(¬e).await.unwrap(); + assert_eq!(stored_count(¬e).await, filled as i64); + assert_eq!( + list_for(&db, ¬e, None, 0).await.unwrap().1, + filled as i64 + ); + } + + // At the cap: the refusal writes nothing, counter included. + assert!(matches!(add(¬e).await, Err(AppError::Conflict(_)))); + assert_eq!(stored_count(¬e).await, MAX_NOTE_FILES as i64); + assert_eq!( + list_for(&db, ¬e, None, 0).await.unwrap().1, + MAX_NOTE_FILES as i64 + ); + } +} diff --git a/src/db/user.rs b/src/db/user.rs index fcbe36f..b85f5bd 100644 --- a/src/db/user.rs +++ b/src/db/user.rs @@ -202,8 +202,8 @@ pub async fn search( } else { clauses.join(" AND ") }; - let mut list = PagedList::new(format!("user WHERE {where_clause}"), "ORDER BY username") - .bind("q", needle); + let mut list = + PagedList::new(format!("user WHERE {where_clause}"), "ORDER BY username").bind("q", needle); if let Some(role) = role { list = list.bind("role", role); } @@ -330,12 +330,12 @@ pub async fn set_role_cascade( // A room whose *creator* is demoted can never be ended by anyone: // the whiteboard is closed to parents outright, so the creator is // 404'd off their own board, `clear`/`lock`/`close`/`delete` are - // creator-only for everyone else, and `Board::list_for_user` is the + // creator-only for everyone else, and `crate::db::board::list_for_user` is the // crate's only enumeration — no manager or admin can so much as find // the id. Its participants meanwhile keep drawing (the room re-derives // membership per frame and they still pass), into a board only the // 50 000-stroke lifetime cap could ever retire. So the demotion - // retires it, with the same compare-and-set [`Board::close`] uses: an + // retires it, with the same compare-and-set [`crate::db::board::close`] uses: an // already-closed board keeps its first stamp. Closed and not deleted // because the marks are the participants' work too — they keep reading // the board and its whole history, and the creator's `board_count` diff --git a/src/domain/board.rs b/src/domain/board.rs index c28477e..6c9ccdc 100644 --- a/src/domain/board.rs +++ b/src/domain/board.rs @@ -13,47 +13,14 @@ //! `CONTENT` save would silently wipe both (src/constant.rs:717-722). use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use tokio::sync::Mutex; -use crate::constant::{ - BOARD_TABLE, MAX_BOARD_PARTICIPANTS, MAX_BOARD_TITLE_LEN, MAX_BOARDS_PER_CREATOR, - USER_BOARD_COUNT_FIELD, -}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; +use crate::constant::{BOARD_TABLE, MAX_BOARD_PARTICIPANTS, MAX_BOARD_TITLE_LEN}; use crate::domain::monotonic_id::next_ulid; -use crate::db::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::validate_required; -/// Serializes every **read-modify-write** of a board's `participants` array: -/// `POST /boards/{id}/invite` (union the resolved group into the roster it just -/// read) and the roster branch of `PATCH /boards/{id}` (which reads the current -/// list to decide which no-longer-eligible ids survive). -/// -/// [`Board::set_participants`] stores the whole array, so two invites that both -/// read roster `R` write `R ∪ X` and `R ∪ Y` and the second one silently drops -/// the first one's group — a caller told `200` with a list of people who are not -/// on the board, against the route's own "strictly additive" contract. The -/// database cannot refuse that: both are single well-formed writes to one field, -/// and neither is wrong on its own. -/// -/// A lock rather than a compare-and-set because the deployment is one process -/// with stop-the-world deploys, so it genuinely serializes — and because the -/// alternative answer is a `409` on a race between two calls that do not -/// conflict in intent, which a client could only resolve by re-sending the same -/// invite. Contended invites simply queue; the section they hold is one board -/// read, one user-list read and one field write. -/// -/// **A leaf**: nothing under it takes another lock. Note it does not reach the -/// demotion sweep in [`crate::service::user::set_role`], which strips ids -/// from every roster inside the role write's own transaction — an invite that -/// read a roster before that sweep can put a swept id back, which the boot -/// repair and the room's own live gate both still catch. -pub(crate) static BOARD_ROSTER_LOCK: Mutex<()> = Mutex::const_new(()); - #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct BoardId(RecordId); @@ -81,7 +48,7 @@ impl BoardId { } #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct BoardTitle(String); +pub struct BoardTitle(pub(crate) String); impl BoardTitle { pub fn try_new(value: &str) -> Result { @@ -97,7 +64,9 @@ impl BoardTitle { /// The invite list, deduplicated and bounded. The creator is a participant by /// construction ([`Board::is_participant`]), so their presence in the list is /// neither required nor rejected. -fn checked_participants(participants: Vec) -> Result, ValidationError> { +pub(crate) fn checked_participants( + participants: Vec, +) -> Result, ValidationError> { let mut unique: Vec = Vec::with_capacity(participants.len()); for user in participants { if !unique.contains(&user) { @@ -116,16 +85,16 @@ fn checked_participants(participants: Vec) -> Result, Valida #[derive(Debug, Clone, SurrealValue)] pub struct Board { - id: BoardId, - creator: UserId, - title: BoardTitle, - participants: Vec, - locked: bool, - locked_by: Option, - locked_at: Option, - epoch: i64, - closed_at: Option, - created_at: Timestamp, + pub(crate) id: BoardId, + pub(crate) creator: UserId, + pub(crate) title: BoardTitle, + pub(crate) participants: Vec, + pub(crate) locked: bool, + pub(crate) locked_by: Option, + pub(crate) locked_at: Option, + pub(crate) epoch: i64, + pub(crate) closed_at: Option, + pub(crate) created_at: Timestamp, } impl Board { @@ -178,251 +147,37 @@ impl Board { pub fn is_creator(&self, user: &UserId) -> bool { &self.creator == user } - - /// Open a board, taking a slot on the creator's `board_count` in the same - /// transaction as the row — the counter is the authority on how many - /// boards exist, so it can never count a row that did not commit. - pub async fn create( - creator: &UserId, - title: BoardTitle, - participants: Vec, - db: &Database, - ) -> Result { - let board = Board { - id: BoardId::generate(), - creator: creator.clone(), - title, - participants: checked_participants(participants)?, - locked: false, - locked_by: None, - locked_at: None, - epoch: 0, - closed_at: None, - created_at: Timestamp::now(), - }; - match cap::claim_and_create( - &creator.record(), - USER_BOARD_COUNT_FIELD, - MAX_BOARDS_PER_CREATOR, - &board.id.record(), - &board, - db, - ) - .await? - { - cap::Claimed::Made(saved) => Ok(saved), - // Full, or the creator's row is gone — the conditional write - // matches nothing either way. - cap::Claimed::Full => Err(AppError::Conflict( - "you have reached the limit on boards — delete one first", - )), - // The id is a freshly minted ULID on a table with no UNIQUE index, - // so no rival can have aimed at it. - cap::Claimed::Duplicate => Err(AppError::Internal("board id collided".into())), - } - } - - pub async fn read(id: &BoardId, db: &Database) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// Every board `user` may open: the ones they created and the ones they - /// were invited to. Newest first — the ids are monotonic, so `id` is the - /// creation order. - /// - /// `open` narrows by `closed_at`, and it means exactly that flag: a board - /// that is locked, or full at its lifetime cap but never drawn on again, is - /// never stamped and so reads as **open** — because it is. Only a creator's - /// `/close` and the lifetime cap's own refusal ever stamp one. - pub async fn list_for_user( - user: &UserId, - open: Option, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - let open_clause = match open { - Some(true) => " AND closed_at = NONE", - Some(false) => " AND closed_at != NONE", - None => "", - }; - PagedList::new( - format!("board WHERE (creator = $usr OR participants CONTAINS $usr){open_clause}"), - "ORDER BY id DESC", - ) - .bind("usr", user.record()) - .run(limit, offset, db) - .await - } - - /// Re-invite. Field-scoped, like every write here: a stroke landing - /// concurrently is moving the counters this struct does not carry. - pub async fn set_participants( - &self, - participants: Vec, - db: &Database, - ) -> Result { - let participants = checked_participants(participants)?; - let mut result = db - .query("UPDATE $id SET participants = $who RETURN AFTER") - .bind(("id", self.id.record())) - .bind(( - "who", - participants - .iter() - .map(|user| user.record()) - .collect::>(), - )) - .await? - .check()?; - one(result.take::>(0)?) - } - - pub async fn set_title(&self, title: BoardTitle, db: &Database) -> Result { - let mut result = db - .query("UPDATE $id SET title = $title RETURN AFTER") - .bind(("id", self.id.record())) - .bind(("title", title.0)) - .await? - .check()?; - one(result.take::>(0)?) - } - - /// Freeze or thaw drawing. `locked_by`/`locked_at` are cleared on unlock so - /// the row never claims a lock that is not held. - pub async fn set_locked( - &self, - locked: bool, - by: &UserId, - db: &Database, - ) -> Result { - let now = Timestamp::now(); - let mut result = db - .query("UPDATE $id SET locked = $locked, locked_by = $by, locked_at = $at RETURN AFTER") - .bind(("id", self.id.record())) - .bind(("locked", locked)) - .bind(("by", locked.then(|| by.record()))) - .bind(("at", locked.then(|| now.as_millis()))) - .await? - .check()?; - one(result.take::>(0)?) - } - - // The demotion sweep — stripping a user off every roster they are listed - // on, deleting nothing, and handing the affected rooms back so the caller - // can prompt them — lives in [`crate::service::user::set_role`], where - // it commits with the role write that invalidates the membership. - - /// Retire the board: permanently read-only, history still readable. - /// Idempotent by the `WHERE` — a second call matches nothing and the first - /// stamp stands, which is what the stroke path's open-guard reads. - pub async fn close(&self, db: &Database) -> Result { - let mut result = db - .query("UPDATE $id SET closed_at = $now WHERE closed_at = NONE RETURN AFTER") - .bind(("id", self.id.record())) - .bind(("now", Timestamp::now().as_millis())) - .await? - .check()?; - match result.take::>(0)?.into_iter().next() { - Some(board) => Ok(board), - // Already closed: the row is unchanged, so read it back rather - // than report a 404 for a board that plainly exists. - None => Self::read(&self.id, db).await?.ok_or(AppError::NotFound), - } - } - - /// Delete the board and give the creator's slot back in the *same* - /// transaction — a release issued afterwards can be lost, and the counter - /// would then ratchet the creator's limit shut forever. - /// - /// The stroke cascade rides in that same transaction: it is the one and - /// only legitimate delete of `board_stroke` rows (a clear deletes nothing), - /// and issued separately it could leave a board's whole history orphaned - /// under a record that no longer exists. - pub async fn delete(self, db: &Database) -> Result { - // A stroke claim writes the very board row this deletes, so the store - // aborts one of the two and a lost round is ordinary here — re-sent - // rather than reported as a 500. Re-sending is sound: every statement - // is a `DELETE` or a field-scoped `UPDATE`, none of which can ever - // answer "already exists" (see [`transaction_with_retry`]). - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - DELETE board_stroke WHERE board = $id; - LET $gone = (DELETE $id RETURN BEFORE); - UPDATE $usr SET board_count = math::max([(board_count ?? 0) - array::len($gone), 0]); - RETURN $gone; - COMMIT TRANSACTION;", - &[ - ("id".into(), self.id.record().into_value()), - ("usr".into(), self.creator.record().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, the cascade, the LET and the UPDATE: the RETURN - // is slot 4. - one(result.take::>(4)?) - } -} - -fn one(rows: Vec) -> Result { - rows.into_iter().next().ok_or(AppError::NotFound) } #[cfg(test)] mod tests { use super::*; - - async fn a_db() -> Database { - let db = crate::database::init_mem().await.unwrap(); - db.query( - "CREATE user:c SET username = 'c', password_hash = 'x'; - CREATE user:p SET username = 'p', password_hash = 'x'; - CREATE user:s SET username = 's', password_hash = 'x';", - ) - .await - .unwrap() - .check() - .unwrap(); - db - } + use crate::constant::MAX_BOARD_TITLE_LEN; fn user(key: &str) -> UserId { UserId::from_key(key) } - /// The stored counter, re-read out of the database. Never asserted off a - /// return value: the in-memory engine forges concurrent-write wins - /// (src/domain/cap.rs:44-49). - async fn stored_count(db: &Database) -> i64 { - let mut result = db - .query("SELECT VALUE board_count ?? 0 FROM user:c") - .await - .unwrap() - .check() - .unwrap(); - result.take::>(0).unwrap()[0] - } - - async fn a_board(db: &Database) -> Board { - Board::create( - &user("c"), - BoardTitle::try_new("Geometri").unwrap(), - vec![user("p")], - db, - ) - .await - .unwrap() + /// A board row assembled in memory — the predicates under test are pure, + /// so no store is involved. + fn a_board() -> Board { + Board { + id: BoardId::from_key("b"), + creator: user("c"), + title: BoardTitle::try_new("Geometri").unwrap(), + participants: vec![user("p")], + locked: false, + locked_by: None, + locked_at: None, + epoch: 0, + closed_at: None, + created_at: Timestamp::now(), + } } - #[tokio::test] - async fn the_two_predicates_are_the_permission_model() { - let db = a_db().await; - let board = a_board(&db).await; + #[test] + fn the_two_predicates_are_the_permission_model() { + let board = a_board(); // Creator: draws AND commands. assert!(board.is_participant(&user("c"))); assert!(board.is_creator(&user("c"))); @@ -441,8 +196,8 @@ mod tests { assert!(BoardTitle::try_new(&"x".repeat(MAX_BOARD_TITLE_LEN + 1)).is_err()); } - #[tokio::test] - async fn participants_are_deduplicated_and_bounded() { + #[test] + fn participants_are_deduplicated_and_bounded() { assert_eq!( checked_participants(vec![user("p"), user("p")]) .unwrap() @@ -454,195 +209,4 @@ mod tests { .collect(); assert!(checked_participants(many).is_err()); } - - /// The cap refuses at `MAX_BOARDS_PER_CREATOR`, and the refusal writes - /// nothing — asserted by re-reading the counter, not off the return value. - #[tokio::test] - async fn the_per_creator_cap_refuses_a_full_creator() { - let db = a_db().await; - db.query("UPDATE user:c SET board_count = $full") - .bind(("full", MAX_BOARDS_PER_CREATOR)) - .await - .unwrap() - .check() - .unwrap(); - let refused = Board::create( - &user("c"), - BoardTitle::try_new("Geometri").unwrap(), - vec![], - &db, - ) - .await; - assert!(matches!(refused, Err(AppError::Conflict(_)))); - assert_eq!(stored_count(&db).await, MAX_BOARDS_PER_CREATOR); - let mut result = db - .query("SELECT VALUE id FROM board") - .await - .unwrap() - .check() - .unwrap(); - assert!(result.take::>(0).unwrap().is_empty()); - } - - /// A seat is taken on create and handed back on delete, both read back out - /// of the store. - #[tokio::test] - async fn a_seat_is_claimed_and_released() { - let db = a_db().await; - let board = a_board(&db).await; - assert_eq!(stored_count(&db).await, 1); - board.delete(&db).await.unwrap(); - assert_eq!(stored_count(&db).await, 0); - } - - /// Closing twice must not re-stamp: the first `closed_at` is the record. - #[tokio::test] - async fn close_is_idempotent() { - let db = a_db().await; - let board = a_board(&db).await; - let closed = board.close(&db).await.unwrap(); - let first = closed.get_closed_at().unwrap(); - // A whole millisecond apart, so a re-stamp could not go unnoticed. - tokio::time::sleep(std::time::Duration::from_millis(2)).await; - assert_eq!(board.close(&db).await.unwrap().get_closed_at(), Some(first)); - assert_eq!( - Board::read(board.get_id(), &db) - .await - .unwrap() - .unwrap() - .get_closed_at(), - Some(first) - ); - } - - #[tokio::test] - async fn field_scoped_writes_leave_the_stroke_counters_alone() { - let db = a_db().await; - let board = a_board(&db).await; - db.query("UPDATE $id SET epoch_stroke_count = 7, total_stroke_count = 9") - .bind(("id", board.get_id().record())) - .await - .unwrap() - .check() - .unwrap(); - board - .set_title(BoardTitle::try_new("Cebir").unwrap(), &db) - .await - .unwrap(); - board.set_participants(vec![user("s")], &db).await.unwrap(); - board.set_locked(true, &user("c"), &db).await.unwrap(); - board.close(&db).await.unwrap(); - let mut result = db - .query("SELECT VALUE [epoch_stroke_count, total_stroke_count] FROM $id") - .bind(("id", board.get_id().record())) - .await - .unwrap() - .check() - .unwrap(); - assert_eq!(result.take::>>(0).unwrap()[0], vec![7, 9]); - } - - /// [`Board::delete`] cascades the stroke log and decrements the creator's - /// `board_count` off the very record a concurrent stroke claim increments, - /// so the two contend by design. Losing that round writes nothing, which is - /// what makes re-sending it the recovery; without - /// [`crate::database::transaction_with_retry`] a lost round comes out as a - /// 500. - /// - /// A refusal or an `Err(NotFound)` is *correct* here — the board really is - /// gone — and must not fail this test. The only defect is `AppError::Db`. - /// - /// Multi-threaded and on a real server for the reason spelled out on - /// [`super::super::course`]'s twin: the current-thread runtime never - /// interleaves the two, and the embedded engine does not conflict-check - /// concurrent writes to one record at all. - /// - /// Mutation status, stated honestly: cutting - /// [`crate::database::transaction_with_retry`] to a single attempt leaves - /// this GREEN — 5 runs of 5, every one at 20/20 contended. The mutation is - /// real, not a dud: the same cut reddens the `course.rs` twin in 2 runs of - /// 3. So the delete here never actually loses a round in this window, and - /// nothing in the suite exercises its retry. Read this as a smoke test that - /// a contended delete does not 500 — the retry stays because the batch is - /// admissible for it and a lost round is possible in principle, not because - /// a test has ever caught it losing one. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_delete_racing_a_stroke_never_answers_500() { - use crate::domain::board_stroke::BoardStroke; - let (db, _serialized) = crate::database::init_test_server("board_delete_race").await; - db.query("CREATE user:c SET username = 'c', password_hash = 'x';") - .await - .unwrap() - .check() - .unwrap(); - let (mut delete_500, mut stroke_500, mut drawn) = (0, 0, 0); - let (mut last_delete, mut last_stroke) = (String::new(), String::new()); - for round in 0..20 { - let board = a_board(&db).await; - // The delete is held back by a sweeping beat: released together it - // is one statement while an append spends a read before it claims, - // so it would win every round and the guard would never be - // contended at all. Six racers over a 0-3ms sweep put the delete - // somewhere inside the counter writes instead. - let drop_it = { - let (board, db) = (board.clone(), db.clone()); - let beat = std::time::Duration::from_millis(round % 4); - tokio::spawn(async move { - tokio::time::sleep(beat).await; - board.delete(&db).await - }) - }; - let marks: Vec<_> = (0..6) - .map(|mark| { - let (id, db) = (board.get_id().clone(), db.clone()); - let author = user("c"); - tokio::spawn(async move { - BoardStroke::append(&id, &author, &format!("{{\"m\":{mark}}}"), 0, &db) - .await - }) - }) - .collect(); - let drop_it = drop_it.await.unwrap(); - if matches!(drop_it, Err(AppError::Db(_))) { - delete_500 += 1; - last_delete = format!("{drop_it:?}"); - } - // Contention is counted off the claim's own outcome, not off stored - // rows: the delete cascades `board_stroke`, so a stroke that landed - // and then lost its board leaves nothing behind to count. An `Ok` - // means the claim committed against the board row the delete was - // tearing down, which is exactly the overlap being measured. - let mut claimed = 0; - for mark in marks { - let mark = mark.await.unwrap(); - if matches!(mark, Err(AppError::Db(_))) { - stroke_500 += 1; - last_stroke = format!("{mark:?}"); - } - if mark.is_ok() { - claimed += 1; - } - } - if claimed > 0 { - drawn += 1; - } - } - eprintln!( - "Board::delete raced: {delete_500}/20 delete 500s, {stroke_500} stroke 500s, \ - {drawn}/20 rounds with a stroke claimed" - ); - assert!( - drawn > 0, - "no round ever landed a stroke, so the delete's cascade was never contended" - ); - assert_eq!( - delete_500, 0, - "a raced delete must retry, not 500: {delete_500}/20 rounds, last {last_delete}" - ); - assert_eq!( - stroke_500, 0, - "a raced stroke must retry, not 500: {stroke_500}/20 rounds, last {last_stroke}" - ); - } } diff --git a/src/domain/board_stroke.rs b/src/domain/board_stroke.rs index fcdf10f..d88fb39 100644 --- a/src/domain/board_stroke.rs +++ b/src/domain/board_stroke.rs @@ -3,45 +3,37 @@ //! A clear does NOT remove strokes — it bumps the board's `epoch`, so the live //! canvas empties while every mark the board ever carried stays on the table //! and stays replayable. That is the whole storage model: the only legitimate -//! delete of a stroke row in the feature is [`crate::domain::board::Board::delete`]'s -//! cascade, which runs inside the same transaction as the board's own delete. +//! delete of a stroke row in the feature is +//! [`crate::db::board::delete`]'s cascade, which runs inside the same +//! transaction as the board's own delete. //! //! The `clear` marker row IS the epoch index: it carries the epoch it closed, //! that epoch's final stroke count, who cleared and when — so replaying a whole //! session needs no second table and no `GROUP BY` over the history. //! -//! This module is the sole write funnel for `board_stroke`, and for the board's +//! Writes funnel through [`crate::db::board_stroke`], and so do the board's //! two stroke counters. Nothing else may write either, because two invariants //! the schema cannot state depend on it: `count` is populated *only* on a //! `clear` row (SCHEMAFULL types both kinds the same), and the two counters //! must move together with the row they count (`cap::claim_two_when_and_create` //! is what makes that one transaction). -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ - BOARD_EPOCH_STROKE_COUNT_FIELD, BOARD_OPEN_GUARD, BOARD_REPLAY_CHUNK, BOARD_STROKE_KINDS, - BOARD_STROKE_TABLE, BOARD_TOTAL_STROKE_COUNT_FIELD, MAX_BOARD_STROKES, MAX_EPOCH_STROKES, - MAX_STROKE_PAYLOAD_LEN, -}; -use crate::database::{Database, transaction_with_retry}; -use crate::domain::board::{Board, BoardId}; -use crate::db::cap; +use crate::constant::{BOARD_STROKE_KINDS, BOARD_STROKE_TABLE}; +use crate::domain::board::Board; use crate::domain::monotonic_id::next_ulid; -use crate::db::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::AppError; -use crate::validate::validate_required; /// A drawn mark, and the marker that ends an epoch. -const KIND_STROKE: &str = BOARD_STROKE_KINDS[0]; -const KIND_CLEAR: &str = BOARD_STROKE_KINDS[1]; +pub(crate) const KIND_STROKE: &str = BOARD_STROKE_KINDS[0]; +pub(crate) const KIND_CLEAR: &str = BOARD_STROKE_KINDS[1]; /// The `THROW` the clear transaction refuses with: a blank canvas, not the /// creator, or the board is locked or already closed. A decision, so it /// outranks a lost round. -const CLEAR_REFUSED: &str = "board_clear_refused"; +pub(crate) const CLEAR_REFUSED: &str = "board_clear_refused"; /// The public words of every refusal this module raises. `pub` because /// `src/web/board_ws.rs` turns each into the machine-readable `code` its room @@ -91,14 +83,14 @@ impl BoardStrokeId { #[derive(Debug, Clone, SurrealValue)] pub struct BoardStroke { - id: BoardStrokeId, - board: BoardId, - author: UserId, - kind: String, - payload: Option, - count: Option, - epoch: i64, - created_at: Timestamp, + pub(crate) id: BoardStrokeId, + pub(crate) board: crate::domain::board::BoardId, + pub(crate) author: UserId, + pub(crate) kind: String, + pub(crate) payload: Option, + pub(crate) count: Option, + pub(crate) epoch: i64, + pub(crate) created_at: Timestamp, } impl BoardStroke { @@ -106,7 +98,7 @@ impl BoardStroke { &self.id } - pub fn get_board(&self) -> &BoardId { + pub fn get_board(&self) -> &crate::domain::board::BoardId { &self.board } @@ -138,800 +130,24 @@ impl BoardStroke { pub fn is_clear(&self) -> bool { self.kind == KIND_CLEAR } - - /// Append one mark to `board`'s current `epoch`. - /// - /// Both stroke counters and the row commit together or not at all: the - /// resettable epoch counter, the lifetime counter, and the open-board guard - /// are one conditional write, so a locked or closed board can never be - /// drawn on by a writer that read it a moment earlier. - /// - /// `epoch` rides in that guard too. Without it a clear landing between the - /// caller's board read and this write filed the row under the epoch that - /// just ended while its increment counted against the *new* epoch's - /// counter — one race, two markers corrupted for good (the closed one short - /// by a stroke, the next one claiming a stroke that is not there), and - /// markers are never rewritten. Now such a stroke is refused instead. - pub async fn append( - board: &BoardId, - author: &UserId, - payload: &str, - epoch: i64, - db: &Database, - ) -> Result { - validate_required("payload", payload, MAX_STROKE_PAYLOAD_LEN)?; - let stroke = BoardStroke { - id: BoardStrokeId::generate(), - board: board.clone(), - author: author.clone(), - kind: KIND_STROKE.to_string(), - payload: Some(payload.to_string()), - count: None, - epoch, - created_at: Timestamp::now(), - }; - // `epoch` is an in-crate `i64` read off the board row, never text from - // a client, so it interpolates into the guard as a bare integer. - let guard = format!("{BOARD_OPEN_GUARD} AND epoch = {epoch}"); - match cap::claim_two_when_and_create( - &board.record(), - (BOARD_EPOCH_STROKE_COUNT_FIELD, MAX_EPOCH_STROKES), - (BOARD_TOTAL_STROKE_COUNT_FIELD, MAX_BOARD_STROKES), - &guard, - &stroke.id.record(), - &stroke, - db, - ) - .await? - { - cap::ClaimedTwo::Made(saved) => Ok(saved), - // The live canvas is full and nothing else: recoverable by a clear, - // which resets this counter without losing a single mark. - cap::ClaimedTwo::FullSoft => Err(AppError::Conflict(EPOCH_FULL)), - // Three refusals share this answer (lifetime full / guard failed / - // board gone), so the board is re-read to tell them apart. A board - // that changed state in between still gets told "no" — but only a - // re-read that *proves* the lifetime counter is spent may stamp - // `closed_at`, never elimination. - cap::ClaimedTwo::FullHard => Err(Self::why_refused(board, db).await?), - } - } - - /// The one place the module orders `closed` above `locked`, because a board - /// can hold both flags at once (nothing gates `/close` on the lock or the - /// lock on `closed_at`) and **closed outranks locked**: there is no reopen - /// route, so the pause never lifts and only the terminal answer is true. - /// Both classifiers read the precedence from here rather than keeping a - /// copy of it — the copies are what drifted, and a room told "the creator - /// has paused drawing" about a permanently read-only board waits forever. - /// - /// `None` means the board is neither: whatever refused the write, this is - /// not why. - fn state_refusal(board: &Board) -> Option<&'static str> { - if board.get_closed_at().is_some() { - Some(BOARD_CLOSED) - } else if board.is_locked() { - Some(BOARD_LOCKED) - } else { - None - } - } - - async fn why_refused(board: &BoardId, db: &Database) -> Result { - let board = Board::read(board, db).await?.ok_or(AppError::NotFound)?; - if let Some(refusal) = Self::state_refusal(&board) { - return Ok(AppError::Conflict(refusal)); - } - // Neither flag, so the lifetime counter has to say so *itself*: - // `FullHard` also fires when the guard failed, so a board that was - // locked (or a clear that moved the epoch) when the claim ran and is - // open again now would otherwise be stamped read-only at one stroke of - // a 50 000 budget — irreversibly, with no reopen. - if Self::total_strokes(board.get_id(), db).await? < MAX_BOARD_STROKES { - return Ok(AppError::Conflict(BOARD_MOVED)); - } - // `Board::close` is the one-way idempotent stamp: a second append takes - // this branch too and leaves the first `closed_at` standing. - board.close(db).await?; - Ok(AppError::Conflict(BOARD_CLOSED)) - } - - /// The lifetime counter as the store holds it — the board struct - /// deliberately does not carry it (src/domain/board.rs:9-13). - async fn total_strokes(board: &BoardId, db: &Database) -> Result { - let mut result = db - .query(format!( - "SELECT VALUE ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) FROM $b" - )) - .bind(("b", board.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next().unwrap_or(0)) - } - - /// End the current epoch: the canvas empties, the history does not. - /// - /// The bump and the marker are one transaction, because the marker carries - /// the epoch's final count — written apart, a crash between them would - /// leave an epoch no marker indexes, and the playback would silently join - /// two sessions into one. - /// - /// **The marker pays the lifetime counter.** It is a real `board_stroke` - /// row, so a marker that claimed nothing left `total_stroke_count` counting - /// strokes *drawn* rather than rows *stored*, and `MAX_BOARD_STROKES` - /// stopped bounding the table. Charged here, the counter is exactly the row - /// count again — the counter is reset and re-read in the same statement, so - /// the increment cannot be split off from the marker it pays for. - /// - /// **A blank canvas cannot be cleared.** Without it every call minted a row - /// for free, one per press of a button the creator can hold down. Requiring - /// the epoch counter to be non-zero pays for each marker with at least one - /// stroke it closes — and "there is nothing on this canvas to clear" is the - /// honest answer to the call it refuses. The epochs index keeps its meaning - /// too: no zero-stroke epoch can enter it. - /// - /// **A locked board cannot be cleared.** The lock is the creator's own - /// pause on the canvas, and it holds against every write to it including - /// theirs — [`BOARD_OPEN_GUARD`] is the same condition the stroke path - /// claims under, so "locked" means one thing everywhere. The cost is - /// accepted: a locked board sitting at `MAX_EPOCH_STROKES` is recovered by - /// unlock, clear, relock. - /// - /// The marker's own increment is not capped: the last stroke of a board's - /// budget may be closed by a marker, so a board holds at most - /// `MAX_BOARD_STROKES + 1` rows. Capping it would refuse the clear that - /// files the final epoch in the index, which is the one clear the history - /// needs. - pub async fn clear( - board: &BoardId, - by: &UserId, - db: &Database, - ) -> Result { - let marker = BoardStrokeId::generate(); - // `($before[0].epoch_stroke_count ?? 0)` is parenthesized: the bare form - // parses as `?? (0 = …)` and stores a boolean count (src/constant.rs:699). - let sql = format!( - "BEGIN TRANSACTION; - LET $before = (UPDATE $b SET epoch += 1, {BOARD_EPOCH_STROKE_COUNT_FIELD} = 0, \ - {BOARD_TOTAL_STROKE_COUNT_FIELD} = ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) + 1 \ - WHERE creator = $by AND {BOARD_OPEN_GUARD} \ - AND ({BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0) > 0 RETURN BEFORE); - IF array::len($before) = 0 {{ THROW '{CLEAR_REFUSED}' }}; - CREATE $mid CONTENT {{ board: $b, author: $by, kind: $kind, \ - epoch: $before[0].epoch, \ - count: ($before[0].{BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0), \ - created_at: $now }}; - COMMIT TRANSACTION;" - ); - let bound: Vec<(String, Value)> = vec![ - ("b".into(), board.record().into_value()), - ("by".into(), by.record().into_value()), - ("mid".into(), marker.record().into_value()), - ("kind".into(), KIND_CLEAR.into_value()), - ("now".into(), Timestamp::now().as_millis().into_value()), - ]; - // The epoch counter is reset here, which is a counter write like any - // other, so it owes the process the same one-at-a-time discipline - // (`cap::counter_lock`) — and unlike a lone conditional claim it is - // read back in the same statement, by the marker's `count`. - let _guard = cap::counter_lock().await; - let (mut result, mut errors) = - transaction_with_retry(db, &sql, &bound, &[CLEAR_REFUSED]).await?; - if errors - .values() - .any(|error| error.to_string().contains(CLEAR_REFUSED)) - { - return Err(Self::why_clear_refused(board, by, db).await?); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, the LET and the IF: the CREATE is slot 3. Only - // read once the error map is empty — `take_errors` swap-removes. - result - .take::>(3)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("board clear wrote no marker".into())) - } - - /// Which of the clear guard's four conditions said no. One `WHERE` cannot - /// report that itself, so the board is re-read — on the refusal path only, - /// like [`Self::why_refused`]. The distinction is not cosmetic: a closed - /// board is terminal for the room, a blank canvas is an ordinary "nothing - /// to do" and a room told otherwise stops drawing for good. - async fn why_clear_refused( - board: &BoardId, - by: &UserId, - db: &Database, - ) -> Result { - let board = Board::read(board, db).await?.ok_or(AppError::NotFound)?; - let state = Self::state_refusal(&board); - // Terminal outranks the caller's identity: a closed board is read-only - // for its creator too, so "closed" is the honest answer to anyone. - if state == Some(BOARD_CLOSED) { - return Ok(AppError::Conflict(BOARD_CLOSED)); - } - if !board.is_creator(by) { - return Ok(AppError::Forbidden(NOT_THE_CREATOR)); - } - // A lock pauses the *creator* too, and it is a state the caller can - // undo — a `Conflict`, not the `Forbidden` a wrong caller gets. Unlock, - // clear, relock is the recovery for a locked board that is also full. - if let Some(refusal) = state { - return Ok(AppError::Conflict(refusal)); - } - Ok(AppError::Conflict(CANVAS_BLANK)) - } - - /// What a joining socket draws: the current epoch's marks only, in mint - /// order, one [`BOARD_REPLAY_CHUNK`] at a time. - /// - /// Paged by `id`, never `created_at` — a millisecond stamp has ties by - /// construction, and the ULID's monotonic low half is exactly what breaks - /// them. `after` is the key of the last stroke already drawn. - pub async fn replay_current( - board: &BoardId, - epoch: i64, - after: Option<&str>, - db: &Database, - ) -> Result, AppError> { - let cursor = match after { - Some(_) => " AND id > $after", - None => "", - }; - let mut result = db - .query(format!( - "SELECT * FROM {BOARD_STROKE_TABLE} \ - WHERE board = $b AND epoch = $e AND kind = $kind{cursor} \ - ORDER BY id LIMIT $chunk" - )) - .bind(("b", board.record())) - .bind(("e", epoch)) - .bind(("kind", KIND_STROKE)) - .bind(( - "after", - RecordId::new(BOARD_STROKE_TABLE, after.unwrap_or_default()), - )) - .bind(("chunk", BOARD_REPLAY_CHUNK as i64)) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// The whole log, oldest first — every epoch, or one named epoch. Both - /// kinds of row come back: the `clear` markers are what tell a reader where - /// one epoch ended and the next began. - /// - /// `marks_only` drops the markers, which is what the *live canvas* wants: - /// the current epoch holds no marker by construction, except in the one - /// race where a clear commits between the board read and this read and - /// files its marker under the epoch just named. The room's replay filters - /// to `kind = 'stroke'` ([`Self::replay_current`]), so without this the two - /// views disagree in exactly that window. - pub async fn history( - board: &BoardId, - epoch: Option, - marks_only: bool, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - let scope = match epoch { - Some(_) => " AND epoch = $e", - None => "", - }; - let kinds = if marks_only { - " AND kind != $clear" - } else { - "" - }; - PagedList::new( - format!("{BOARD_STROKE_TABLE} WHERE board = $b{scope}{kinds}"), - "ORDER BY id", - ) - .bind("b", board.record()) - .bind("e", epoch.unwrap_or_default()) - .bind("clear", KIND_CLEAR.to_string()) - .run(limit, offset, db) - .await - } - - /// The epoch index: every `clear` marker this board has, oldest first. - pub async fn epochs(board: &BoardId, db: &Database) -> Result, AppError> { - let mut result = db - .query(format!( - "SELECT * FROM {BOARD_STROKE_TABLE} \ - WHERE board = $b AND kind = $kind ORDER BY id" - )) - .bind(("b", board.record())) - .bind(("kind", KIND_CLEAR)) - .await? - .check()?; - Ok(result.take::>(0)?) - } } -#[cfg(test)] -mod tests { - use super::*; - use crate::domain::board::BoardTitle; - - async fn a_db() -> Database { - let db = crate::database::init_mem().await.unwrap(); - db.query( - "CREATE user:c SET username = 'c', password_hash = 'x'; - CREATE user:p SET username = 'p', password_hash = 'x';", - ) - .await - .unwrap() - .check() - .unwrap(); - db - } - - fn user(key: &str) -> UserId { - UserId::from_key(key) - } - - async fn a_board(db: &Database) -> Board { - Board::create( - &user("c"), - BoardTitle::try_new("Geometri").unwrap(), - vec![user("p")], - db, - ) - .await - .unwrap() - } - - /// Every stroke row of a board, read straight out of the store — never off - /// a return value, which the in-memory engine forges wins on - /// (src/domain/cap.rs:44-49). - async fn rows(board: &BoardId, db: &Database) -> Vec { - let mut result = db - .query("SELECT * FROM board_stroke WHERE board = $b ORDER BY id") - .bind(("b", board.record())) - .await - .unwrap() - .check() - .unwrap(); - result.take(0).unwrap() - } - - async fn reread(board: &Board, db: &Database) -> Board { - Board::read(board.get_id(), db).await.unwrap().unwrap() - } - - async fn set_counters(board: &Board, epoch: i64, total: i64, db: &Database) { - db.query("UPDATE $id SET epoch_stroke_count = $e, total_stroke_count = $t") - .bind(("id", board.get_id().record())) - .bind(("e", epoch)) - .bind(("t", total)) - .await - .unwrap() - .check() - .unwrap(); - } - - async fn draw(board: &Board, db: &Database) -> Result { - BoardStroke::append( - board.get_id(), - &user("p"), - "{\"p\":[1,2]}", - board.get_epoch(), - db, - ) - .await - } - - #[tokio::test] - async fn a_full_canvas_is_refused_but_the_board_stays_open() { - let db = a_db().await; - let board = a_board(&db).await; - set_counters(&board, MAX_EPOCH_STROKES, 10, &db).await; - let refused = draw(&board, &db).await; - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("clear it"))); - // Nothing written, and above all: NOT closed — a full canvas is - // recoverable, and closing it here would make it permanent. - assert!(rows(board.get_id(), &db).await.is_empty()); - assert!(reread(&board, &db).await.get_closed_at().is_none()); - } - - /// The user's decision in one test: a clear empties the canvas and loses - /// nothing. If this ever passes with the pre-clear rows gone, the feature - /// is wrong. - #[tokio::test] - async fn a_clear_keeps_every_pre_clear_stroke() { - let db = a_db().await; - let board = a_board(&db).await; - for _ in 0..3 { - draw(&board, &db).await.unwrap(); - } - let before: Vec = rows(board.get_id(), &db) - .await - .iter() - .map(|row| row.get_id().key().to_string()) - .collect(); - - BoardStroke::clear(board.get_id(), &user("c"), &db) - .await - .unwrap(); - let board = reread(&board, &db).await; - assert_eq!(board.get_epoch(), 1); - draw(&board, &db).await.unwrap(); - - // The three original rows are still in the table, by direct read. - let after: Vec = rows(board.get_id(), &db) - .await - .iter() - .map(|row| row.get_id().key().to_string()) - .collect(); - for key in &before { - assert!(after.contains(key), "a clear deleted stroke {key}"); - } - // 3 old + 1 marker + 1 new, and the live canvas is the new one alone. - assert_eq!(after.len(), 5); - let live = BoardStroke::replay_current(board.get_id(), 1, None, &db) - .await - .unwrap(); - assert_eq!(live.len(), 1); - // The old epoch is still replayable in full. - assert_eq!( - BoardStroke::replay_current(board.get_id(), 0, None, &db) - .await - .unwrap() - .len(), - 3 - ); - } - - /// The marker IS the epoch index, so its `count` has to be that epoch's - /// final stroke count — and `count` must appear on no other row. - #[tokio::test] - async fn the_marker_counts_the_epoch_it_closed() { - let db = a_db().await; - let board = a_board(&db).await; - for _ in 0..4 { - draw(&board, &db).await.unwrap(); - } - let marker = BoardStroke::clear(board.get_id(), &user("c"), &db) - .await - .unwrap(); - assert_eq!(marker.get_count(), Some(4)); - assert_eq!(marker.get_epoch(), 0); - assert!(marker.is_clear()); - - // And the epoch counter reset, so drawing resumes against a fresh cap. - let board = reread(&board, &db).await; - draw(&board, &db).await.unwrap(); - let epochs = BoardStroke::epochs(board.get_id(), &db).await.unwrap(); - assert_eq!(epochs.len(), 1); - assert_eq!(epochs[0].get_count(), Some(4)); - // `count` lives on clear markers only — this module is that guard. - for row in rows(board.get_id(), &db).await { - assert_eq!(row.get_count().is_some(), row.is_clear()); - assert_eq!(row.get_payload().is_some(), !row.is_clear()); - } - } - - #[tokio::test] - async fn the_lifetime_cap_closes_the_board_exactly_once() { - let db = a_db().await; - let board = a_board(&db).await; - set_counters(&board, 0, MAX_BOARD_STROKES, &db).await; - let refused = draw(&board, &db).await; - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("read-only"))); - let stamp = reread(&board, &db).await.get_closed_at(); - assert!(stamp.is_some()); - - // A whole millisecond apart, so a re-stamp could not go unnoticed. - tokio::time::sleep(std::time::Duration::from_millis(2)).await; - assert!(draw(&board, &db).await.is_err()); - assert_eq!(reread(&board, &db).await.get_closed_at(), stamp); - assert!(rows(board.get_id(), &db).await.is_empty()); - } - - /// A locked board must be told it is locked. Both refusals arrive as the - /// same `FullHard`, so a re-read that got this wrong would tell a paused - /// room its canvas is full — and send it clearing a board it need not clear. - #[tokio::test] - async fn a_locked_board_is_refused_as_locked() { - let db = a_db().await; - let board = a_board(&db).await; - let board = board.set_locked(true, &user("c"), &db).await.unwrap(); - let refused = draw(&board, &db).await; - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("locked"))); - assert!(rows(board.get_id(), &db).await.is_empty()); - // A lock is not a close: unlocking restores drawing. - assert!(reread(&board, &db).await.get_closed_at().is_none()); - let board = board.set_locked(false, &user("c"), &db).await.unwrap(); - assert!(draw(&board, &db).await.is_ok()); - } - - /// A lock the stroke lost to, unlocked again before the refusal re-reads - /// the row — which is the state `why_refused` is handed after a guard - /// failure. Reading "neither locked nor closed" as proof of the lifetime - /// cap stamped `closed_at` on a board holding one stroke of 50 000, with - /// no reopen. Only the counter itself may close a board. - #[tokio::test] - async fn a_refusal_on_an_open_board_never_closes_it() { - let db = a_db().await; - let board = a_board(&db).await; - let board = board.set_locked(true, &user("c"), &db).await.unwrap(); - // The claim loses the open-guard while the board is locked... - assert!(matches!( - draw(&board, &db).await, - Err(AppError::Conflict(_)) - )); - // ...and the creator unlocks before the refusal picks its message. - let board = board.set_locked(false, &user("c"), &db).await.unwrap(); - let refused = BoardStroke::why_refused(board.get_id(), &db).await.unwrap(); - assert!(matches!(refused, AppError::Conflict(msg) if !msg.contains("read-only"))); - // Stored state, not the return value: the board is still open, and - // still drawable. - assert!(reread(&board, &db).await.get_closed_at().is_none()); - assert!(draw(&reread(&board, &db).await, &db).await.is_ok()); - } - - /// The epoch index must never drift, in either direction. A stroke carrying - /// a pre-clear epoch used to land under the closed epoch while its - /// increment counted against the new one — the closed marker short by a - /// stroke, the next marker claiming one that is not there, both permanent. - #[tokio::test] - async fn a_stale_epoch_append_leaves_no_marker_drifted() { - let db = a_db().await; - let board = a_board(&db).await; - draw(&board, &db).await.unwrap(); - BoardStroke::clear(board.get_id(), &user("c"), &db) - .await - .unwrap(); - - // Exactly what `live_board` hands `append` when a clear lands between - // the board read and the write (src/web/board_ws.rs:431). - let stale = BoardStroke::append(board.get_id(), &user("p"), "{\"p\":[9]}", 0, &db).await; - assert!(matches!(stale, Err(AppError::Conflict(_)))); - - let board = reread(&board, &db).await; - draw(&board, &db).await.unwrap(); - BoardStroke::clear(board.get_id(), &user("c"), &db) - .await - .unwrap(); - - // Every marker's count is the rows the store actually holds at the - // epoch it closed. - let stored = rows(board.get_id(), &db).await; - for marker in stored.iter().filter(|row| row.is_clear()) { - let actual = stored - .iter() - .filter(|row| !row.is_clear() && row.get_epoch() == marker.get_epoch()) - .count() as i64; - assert_eq!( - marker.get_count(), - Some(actual), - "marker for epoch {} drifted", - marker.get_epoch() - ); - } - // And the refused stroke claimed nothing: two marks and the two - // markers that closed them, which is every row on the table. - assert_eq!( - BoardStroke::total_strokes(board.get_id(), &db) - .await - .unwrap(), - 4 - ); - assert_eq!(stored.len(), 4); - } - - /// The lock pauses the canvas against *every* write to it, its creator's - /// clear included — a `Conflict`, since unlocking undoes it, not the - /// `Forbidden` a non-creator gets. Asserted off stored rows: the refusal - /// must mint no marker and must not bump the epoch. - #[tokio::test] - async fn a_locked_board_refuses_its_creator_s_clear() { - let db = a_db().await; - let board = a_board(&db).await; - draw(&board, &db).await.unwrap(); - let board = board.set_locked(true, &user("c"), &db).await.unwrap(); - - let refused = BoardStroke::clear(board.get_id(), &user("c"), &db).await; - assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg == BOARD_LOCKED)); - assert_eq!(rows(board.get_id(), &db).await.len(), 1); - assert_eq!(reread(&board, &db).await.get_epoch(), 0); - assert!( - BoardStroke::epochs(board.get_id(), &db) - .await - .unwrap() - .is_empty() - ); - - // Unlock, and the same clear lands: unlock → clear → relock is the - // recovery for a locked board sitting at the epoch cap. - let board = board.set_locked(false, &user("c"), &db).await.unwrap(); - let marker = BoardStroke::clear(board.get_id(), &user("c"), &db) - .await - .unwrap(); - assert_eq!(marker.get_count(), Some(1)); - assert_eq!(reread(&board, &db).await.get_epoch(), 1); - } - - /// Both classifiers, one board: the words a stroke is refused with and the - /// words the *creator's* clear is refused with. They must match — the two - /// used to be independent chains and drifted apart on the state below. - async fn both_refusals(board: &Board, db: &Database) -> (&'static str, &'static str) { - let stroke = match draw(board, db).await { - Err(AppError::Conflict(msg)) => msg, - other => panic!("the stroke was not refused: {other:?}"), - }; - let clear = match BoardStroke::clear(board.get_id(), &user("c"), db).await { - Err(AppError::Conflict(msg)) => msg, - other => panic!("the clear was not refused: {other:?}"), - }; - (stroke, clear) - } - - /// A board that is locked *and* closed is terminal, and both paths have to - /// say so. Reaching the state is ungated in either direction — `set_locked` - /// carries no `closed_at` test and `close` carries no lock test — and the - /// stroke path used to test the lock first, so a permanently read-only - /// board answered every mark with "the creator has paused drawing" while - /// the same board answered a clear with the terminal words. A room told to - /// wait for a pause that cannot lift waits forever. - /// - /// Locking a closed board stays *allowed*: it is a no-op on a board that is - /// already read-only, and refusing it would break the second half of a - /// close-then-lock a client may legitimately send in either order. - #[tokio::test] - async fn locked_and_closed_answers_closed_whichever_came_first() { - for closed_first in [false, true] { - let db = a_db().await; - let board = a_board(&db).await; - // A mark on the canvas, so "nothing to clear" cannot be the reason. - draw(&board, &db).await.unwrap(); - - let board = if closed_first { - let board = board.close(&db).await.unwrap(); - board.set_locked(true, &user("c"), &db).await.unwrap() - } else { - let board = board.set_locked(true, &user("c"), &db).await.unwrap(); - board.close(&db).await.unwrap() - }; - // Stored state: both flags really are up, and the close stamp stood. - let stored = reread(&board, &db).await; - assert!(stored.is_locked() && stored.get_closed_at().is_some()); - - assert_eq!( - both_refusals(&board, &db).await, - (BOARD_CLOSED, BOARD_CLOSED), - "closed_first = {closed_first}" - ); - // And the refusals wrote nothing: one mark, no marker, epoch 0. - assert_eq!(rows(board.get_id(), &db).await.len(), 1); - assert_eq!(reread(&board, &db).await.get_epoch(), 0); - } - } - - /// The other half of the same contract: a board holding *one* of the flags - /// keeps its own answer on both paths. A lock is recoverable, a close is - /// not, and collapsing either into the other is the mislabel above. - #[tokio::test] - async fn one_flag_alone_keeps_its_own_answer_on_both_paths() { - let db = a_db().await; - let locked = a_board(&db).await; - draw(&locked, &db).await.unwrap(); - let locked = locked.set_locked(true, &user("c"), &db).await.unwrap(); - assert_eq!( - both_refusals(&locked, &db).await, - (BOARD_LOCKED, BOARD_LOCKED) - ); - - let closed = a_board(&db).await; - draw(&closed, &db).await.unwrap(); - let closed = closed.close(&db).await.unwrap(); - assert_eq!( - both_refusals(&closed, &db).await, - (BOARD_CLOSED, BOARD_CLOSED) - ); - } - - /// The `next_ulid` hazard: rows minted inside one millisecond must replay - /// in mint order, not at random (src/domain/monotonic_id.rs:41-46). - #[tokio::test] - async fn replay_is_in_mint_order_within_a_millisecond() { - let db = a_db().await; - let board = a_board(&db).await; - let mut minted = Vec::new(); - for _ in 0..25 { - minted.push(draw(&board, &db).await.unwrap().get_id().key().to_string()); - } - let replayed: Vec = BoardStroke::replay_current(board.get_id(), 0, None, &db) - .await - .unwrap() - .iter() - .map(|row| row.get_id().key().to_string()) - .collect(); - assert_eq!(replayed, minted); - - // The cursor resumes exactly where the last chunk stopped. - let rest: Vec = - BoardStroke::replay_current(board.get_id(), 0, Some(&minted[9]), &db) - .await - .unwrap() - .iter() - .map(|row| row.get_id().key().to_string()) - .collect(); - assert_eq!(rest, minted[10..]); - } - - /// The one legitimate delete of stroke rows: without it, deleting a board - /// orphans its whole history under a record that no longer exists. - #[tokio::test] - async fn deleting_a_board_takes_its_strokes_with_it() { - let db = a_db().await; - let board = a_board(&db).await; - let other = a_board(&db).await; - draw(&board, &db).await.unwrap(); - draw(&board, &db).await.unwrap(); - BoardStroke::clear(board.get_id(), &user("c"), &db) - .await - .unwrap(); - draw(&other, &db).await.unwrap(); - - let id = board.get_id().clone(); - board.delete(&db).await.unwrap(); - assert!(rows(&id, &db).await.is_empty()); - // The cascade is scoped to its own board. - assert_eq!(rows(other.get_id(), &db).await.len(), 1); - } - - #[tokio::test] - async fn an_oversized_payload_is_refused_before_the_write() { - let db = a_db().await; - let board = a_board(&db).await; - let big = "x".repeat(MAX_STROKE_PAYLOAD_LEN + 1); - assert!( - BoardStroke::append(board.get_id(), &user("p"), &big, 0, &db) - .await - .is_err() - ); - assert!( - BoardStroke::append(board.get_id(), &user("p"), " ", 0, &db) - .await - .is_err() - ); - assert!(rows(board.get_id(), &db).await.is_empty()); - // Nothing was claimed either — the counters must not have moved. - assert_eq!(reread(&board, &db).await.get_epoch(), 0); - } - - /// History spans epochs; a named epoch is that epoch alone. - #[tokio::test] - async fn history_spans_every_epoch_unless_one_is_named() { - let db = a_db().await; - let board = a_board(&db).await; - draw(&board, &db).await.unwrap(); - BoardStroke::clear(board.get_id(), &user("c"), &db) - .await - .unwrap(); - let board = reread(&board, &db).await; - draw(&board, &db).await.unwrap(); - - let (all, total) = BoardStroke::history(board.get_id(), None, false, None, 0, &db) - .await - .unwrap(); - assert_eq!((all.len(), total), (3, 3)); - let (first, total) = BoardStroke::history(board.get_id(), Some(0), false, None, 0, &db) - .await - .unwrap(); - // Epoch 0: its stroke and the marker that closed it. - assert_eq!((first.len(), total), (2, 2)); - // `marks_only` drops the marker from that same epoch — and its `total` - // with it, so the envelope's count stays the count of what is served. - let (marks, total) = BoardStroke::history(board.get_id(), Some(0), true, None, 0, &db) - .await - .unwrap(); - assert_eq!((marks.len(), total), (1, 1)); - assert!(marks.iter().all(|row| !row.is_clear())); +/// The one place the module orders `closed` above `locked`, because a board +/// can hold both flags at once (nothing gates `/close` on the lock or the +/// lock on `closed_at`) and **closed outranks locked**: there is no reopen +/// route, so the pause never lifts and only the terminal answer is true. +/// Both classifiers read the precedence from here rather than keeping a +/// copy of it — the copies are what drifted, and a room told "the creator +/// has paused drawing" about a permanently read-only board waits forever. +/// +/// `None` means the board is neither: whatever refused the write, this is +/// not why. +pub(crate) fn state_refusal(board: &Board) -> Option<&'static str> { + if board.get_closed_at().is_some() { + Some(BOARD_CLOSED) + } else if board.is_locked() { + Some(BOARD_LOCKED) + } else { + None } } diff --git a/src/domain/course_note.rs b/src/domain/course_note.rs index d1bcfbf..f24f5f6 100644 --- a/src/domain/course_note.rs +++ b/src/domain/course_note.rs @@ -1,17 +1,10 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ - COURSE_NOTE_TABLE, ENROLLMENT_COUNT_FIELD, MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN, -}; -use crate::database::Database; -use crate::db::cap; +use crate::constant::{COURSE_NOTE_TABLE, MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN}; use crate::domain::course::CourseId; -use crate::domain::course_note_file::CourseNoteFile; -use crate::db::field_update::FieldUpdate; use crate::domain::monotonic_id::next_ulid; -use crate::db::page::PagedList; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::{validate_optional, validate_required}; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -20,8 +13,8 @@ pub struct CourseNoteId(RecordId); impl CourseNoteId { /// Minted from the process-wide monotonic generator, not `Ulid::new()`: /// a course's notes list `id DESC` (newest first, - /// [`CourseNote::list_for_course`]), and a random low half scrambles rows - /// minted in the same millisecond. + /// [`crate::db::course_note::list_for_course`]), and a random low half + /// scrambles rows minted in the same millisecond. pub fn generate() -> Self { Self(RecordId::new(COURSE_NOTE_TABLE, next_ulid().to_string())) } @@ -70,22 +63,13 @@ impl CourseNoteContent { } } -/// What [`CourseNote::delete`]'s transaction removed: the note row (empty if -/// it had already vanished) and every attachment row the cascade took with -/// it — the only set whose blobs are safe to unlink. -#[derive(Debug, SurrealValue)] -struct DeleteOutcome { - note: Vec, - files: Vec, -} - #[derive(Debug, Clone, SurrealValue)] pub struct CourseNote { - id: CourseNoteId, - course: CourseId, - author: UserId, - title: CourseNoteTitle, - content: CourseNoteContent, + pub(crate) id: CourseNoteId, + pub(crate) course: CourseId, + pub(crate) author: UserId, + pub(crate) title: CourseNoteTitle, + pub(crate) content: CourseNoteContent, } impl CourseNote { @@ -108,100 +92,6 @@ impl CourseNote { pub fn get_content(&self) -> &CourseNoteContent { &self.content } - - pub async fn create( - course: &CourseId, - author: &UserId, - title: CourseNoteTitle, - content: CourseNoteContent, - db: &Database, - ) -> Result { - let note = CourseNote { - id: CourseNoteId::generate(), - course: course.clone(), - author: author.clone(), - title, - content, - }; - // The course row is *written* (bumped and put back), not read, so this - // collides with `Course::delete`'s cascade: a note that outlives its - // course is unreachable forever — every route to it goes through the - // course. See [`cap::touch_and_create`]. - cap::touch_and_create( - &course.record(), - ENROLLMENT_COUNT_FIELD, - ¬e.id.record(), - ¬e, - db, - ) - .await? - .ok_or(AppError::NotFound) - } - - pub async fn read(id: &CourseNoteId, db: &Database) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - pub async fn list_for_course( - course: &CourseId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new("course_note WHERE course = $crs", "ORDER BY id DESC") - .bind("crs", course.record()) - .run(limit, offset, db) - .await - } - - /// Request-scoped: no lock spans the handler's read and this write, so an - /// omitted field (`None`) is not written at all. Passing the snapshot's - /// value back instead would revert a concurrent edit of that field — - /// scoping the `SET` alone does not prevent that, the values have to come - /// from the request. Neither column is nullable, so plain `Option` per - /// field says everything there is to say. - pub async fn update( - self, - title: Option, - content: Option, - db: &Database, - ) -> Result { - FieldUpdate::new(self.id.record()) - .set("title", title) - .set("content", content) - .run::(db) - .await - } - - /// Delete the note and cascade-remove its attachment rows, returning both: - /// the note, and the attachment rows this transaction actually removed. - /// Blob files on disk are the web layer's to remove, but only for *these* - /// rows — a row uploaded after the caller listed the note's files is - /// deleted here too, and a pre-read snapshot would strand its blob. - pub async fn delete( - self, - db: &Database, - ) -> Result<(CourseNote, Vec), AppError> { - let mut result = db - .query( - "BEGIN TRANSACTION; - LET $files = (DELETE course_note_file WHERE course_note = $note RETURN BEFORE); - LET $gone = (DELETE $note RETURN BEFORE); - RETURN { note: $gone, files: $files }; - COMMIT TRANSACTION;", - ) - .bind(("note", self.id.record())) - .await? - .check()?; - // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3. - let outcome = result - .take::>(3)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to delete course note".into()))?; - let note = outcome.note.into_iter().next().ok_or(AppError::NotFound)?; - Ok((note, outcome.files)) - } } #[cfg(test)] @@ -219,81 +109,4 @@ mod tests { assert_eq!(CourseNoteContent::try_new("").unwrap().as_str(), ""); assert_eq!(CourseNoteContent::try_new("body").unwrap().as_str(), "body"); } - - /// The blobs the handler unlinks are exactly the rows this transaction - /// removed — including one uploaded after any pre-read snapshot would have - /// been taken, which is the row whose blob used to leak. - #[tokio::test] - async fn delete_returns_the_attachment_rows_it_removed() { - use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; - use crate::domain::course_note_file::{FileContentType, FileName}; - - let db = crate::database::init_mem().await.unwrap(); - let creator = crate::domain::user::UserId::generate(); - let course = crate::db::course::create( - &db, - &creator, - CourseTitle::try_new("Math").unwrap(), - CourseDescription::try_new("").unwrap(), - CourseKind::try_new("course").unwrap(), - None, - None, - ) - .await - .unwrap(); - let note = CourseNote::create( - course.get_id(), - &creator, - CourseNoteTitle::try_new("a").unwrap(), - CourseNoteContent::try_new("body").unwrap(), - &db, - ) - .await - .unwrap(); - // What a handler snapshot would have seen... - let early = CourseNoteFile::new( - note.get_id(), - FileName::try_new("early.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ) - .insert(&db) - .await - .unwrap(); - let (snapshot, _) = CourseNoteFile::list_for(note.get_id(), None, 0, &db) - .await - .unwrap(); - assert_eq!(snapshot.len(), 1); - // ...and the upload that races in after it. - let late = CourseNoteFile::new( - note.get_id(), - FileName::try_new("late.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ) - .insert(&db) - .await - .unwrap(); - - let (gone, files) = note.delete(&db).await.unwrap(); - assert_eq!(gone.get_title().as_str(), "a"); - let mut keys: Vec<_> = files - .iter() - .map(|file| file.get_id().key().to_string()) - .collect(); - keys.sort(); - let mut want = vec![ - early.get_id().key().to_string(), - late.get_id().key().to_string(), - ]; - want.sort(); - assert_eq!(keys, want); - assert!( - CourseNoteFile::list_for(gone.get_id(), None, 0, &db) - .await - .unwrap() - .0 - .is_empty() - ); - } } diff --git a/src/domain/course_note_file.rs b/src/domain/course_note_file.rs index d3b2a6a..629adf0 100644 --- a/src/domain/course_note_file.rs +++ b/src/domain/course_note_file.rs @@ -3,23 +3,18 @@ //! [`crate::config::Config::files_path`], in a file named by this row's key — //! a server-generated ULID, so no user input ever shapes a disk path. The web //! layer owns the blob I/O and its ordering (blob before row on upload, row -//! before blob on delete); this module owns the rows. `FileName` and -//! `FileContentType` are shared with [`crate::domain::note_file`] — same -//! validation, no reason to duplicate it. +//! before blob on delete); persistence lives in +//! [`crate::db::course_note_file`]. `FileName` and `FileContentType` are +//! shared with [`crate::domain::note_file`] — same validation, no reason to +//! duplicate it. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; pub use crate::domain::note_file::{FileContentType, FileName}; -use crate::constant::{ - COURSE_NOTE_FILE_COUNT_FIELD, COURSE_NOTE_FILE_TABLE, MAX_COURSE_NOTE_FILES, -}; -use crate::database::Database; -use crate::db::cap; +use crate::constant::COURSE_NOTE_FILE_TABLE; use crate::domain::course_note::CourseNoteId; use crate::domain::monotonic_id::next_ulid; -use crate::db::page::PagedList; -use crate::error::AppError; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct CourseNoteFileId(RecordId); @@ -27,8 +22,8 @@ pub struct CourseNoteFileId(RecordId); impl CourseNoteFileId { /// Minted from the process-wide monotonic generator, not `Ulid::new()`: /// a note's files list `id DESC` (newest first, - /// [`CourseNoteFile::list_for`]), and a random low half scrambles rows - /// minted in the same millisecond. + /// [`crate::db::course_note_file::list_for`]), and a random low half + /// scrambles rows minted in the same millisecond. pub fn generate() -> Self { Self(RecordId::new( COURSE_NOTE_FILE_TABLE, @@ -54,17 +49,18 @@ impl CourseNoteFileId { #[derive(Debug, Clone, SurrealValue)] pub struct CourseNoteFile { - id: CourseNoteFileId, - course_note: CourseNoteId, - name: FileName, - content_type: FileContentType, - size: i64, + pub(crate) id: CourseNoteFileId, + pub(crate) course_note: CourseNoteId, + pub(crate) name: FileName, + pub(crate) content_type: FileContentType, + pub(crate) size: i64, } impl CourseNoteFile { /// Assemble a new attachment row (id generated here) without persisting /// it. The caller writes the blob to disk under the fresh id first, then - /// calls [`Self::insert`] — so a stored row always points at a real blob. + /// calls [`crate::db::course_note_file::insert`] — so a stored row always + /// points at a real blob. pub fn new( note: &CourseNoteId, name: FileName, @@ -99,241 +95,4 @@ impl CourseNoteFile { pub fn get_size(&self) -> i64 { self.size } - - /// Persist the row assembled by [`Self::new`], refusing once its note - /// already holds [`MAX_COURSE_NOTE_FILES`]. The slot and the row are - /// taken together by [`cap::claim_and_create`] on the note row — see - /// [`crate::domain::note_file::NoteFile::insert`] for why that is the - /// only guard a concurrent insert cannot outrun. - pub async fn insert(self, db: &Database) -> Result { - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber - match cap::claim_and_create( - &self.course_note.record(), - COURSE_NOTE_FILE_COUNT_FIELD, - MAX_COURSE_NOTE_FILES as i64, - &self.id.record(), - &self, - db, - ) - .await? - { - cap::Claimed::Made(created) => Ok(created), - // Also how a missing note reads: no note row means no slot to take. - cap::Claimed::Full => Err(AppError::Conflict( - "the course note already holds the maximum of 10 files — delete one first", - )), - // Unreachable: the id is a ULID this call just generated. - cap::Claimed::Duplicate => Err(AppError::Internal( - "failed to create course note file".into(), - )), - } - } - - /// Read a file's row by id alone, for the callers that have no note in - /// hand yet and reach the note *through* the file (the AI bridge's blob - /// stream). A key from any other table simply reads as `None`, which is - /// what keeps a personal note's file id unreachable here. - pub async fn read( - id: &CourseNoteFileId, - db: &Database, - ) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// Read a file's row only if it belongs to `note` — callers have already - /// checked the note belongs to a course the caller may act on. - pub async fn read_for( - id: &CourseNoteFileId, - note: &CourseNoteId, - db: &Database, - ) -> Result, AppError> { - let file: Option = db.select(id.record()).await?; - Ok(file.filter(|file| &file.course_note == note)) - } - - /// All of `note`'s attachment rows, newest first. - pub async fn list_for( - note: &CourseNoteId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "course_note_file WHERE course_note = $note", - "ORDER BY id DESC", - ) - .bind("note", note.record()) - .run(limit, offset, db) - .await - } - - /// The blob names (record keys, since a file's blob is named by its own - /// id) behind every note attachment of `course` — collected *before* the - /// course-delete cascade wipes the rows. - pub async fn file_keys_for_course( - course: &crate::domain::course::CourseId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT VALUE id FROM course_note_file \ - WHERE course_note IN (SELECT VALUE id FROM course_note WHERE course = $course)", - ) - .bind(("course", course.record())) - .await? - .check()?; - Ok(result - .take::>(0)? - .into_iter() - .map(|id| match id.key { - RecordIdKey::String(key) => key, - _ => String::new(), - }) - .collect()) - } - - /// Delete the row and give its slot back in the same transaction — the - /// note itself is untouched, so unlike the note-delete cascade this one - /// has a counter to correct. - pub async fn delete(self, db: &Database) -> Result { - let mut result = db - .query( - "BEGIN TRANSACTION; - LET $gone = (DELETE $id RETURN BEFORE); - UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); - RETURN $gone; - COMMIT TRANSACTION;", - ) - .bind(("id", self.id.record())) - .bind(("note", self.course_note.record())) - .await? - .check()?; - result - .take::>(3)? - .into_iter() - .next() - .ok_or(AppError::NotFound) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; - use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; - - async fn note_of(db: &Database, title: &str) -> CourseNote { - let creator = crate::domain::user::UserId::generate(); - let course = crate::db::course::create( - db, - &creator, - CourseTitle::try_new("c").unwrap(), - CourseDescription::try_new("").unwrap(), - CourseKind::try_new("course").unwrap(), - None, - None, - ) - .await - .unwrap(); - CourseNote::create( - course.get_id(), - &creator, - CourseNoteTitle::try_new(title).unwrap(), - CourseNoteContent::try_new("body").unwrap(), - db, - ) - .await - .unwrap() - } - - #[tokio::test] - async fn rows_scope_to_their_note() { - let db = crate::database::init_mem().await.unwrap(); - let note_a = note_of(&db, "a").await.get_id().clone(); - let note_b = note_of(&db, "b").await.get_id().clone(); - let file = CourseNoteFile::new( - ¬e_a, - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ) - .insert(&db) - .await - .unwrap(); - - let found = CourseNoteFile::read_for(file.get_id(), ¬e_a, &db) - .await - .unwrap(); - assert_eq!(found.unwrap().get_name().as_str(), "plan.pdf"); - assert!( - CourseNoteFile::read_for(file.get_id(), ¬e_b, &db) - .await - .unwrap() - .is_none() - ); - - let listed = async |note: &CourseNoteId| { - CourseNoteFile::list_for(note, None, 0, &db) - .await - .unwrap() - .0 - }; - assert_eq!(listed(¬e_a).await.len(), 1); - assert!(listed(¬e_b).await.is_empty()); - - file.delete(&db).await.unwrap(); - assert!(listed(¬e_a).await.is_empty()); - } - - /// The counter and the rows are written in one transaction, so the stored - /// count must equal the stored rows — after a success *and* after the - /// refusal that fills the cap, which must move neither. - #[tokio::test] - async fn counter_tracks_stored_rows() { - let db = crate::database::init_mem().await.unwrap(); - let note = note_of(&db, "a").await.get_id().clone(); - let stored_count = async |note: &CourseNoteId| -> i64 { - db.query("SELECT VALUE file_count FROM $note") - .bind(("note", note.record())) - .await - .unwrap() - .take::>(0) - .unwrap() - .into_iter() - .next() - .unwrap_or(0) - }; - let add = async |note: &CourseNoteId| { - CourseNoteFile::new( - note, - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ) - .insert(&db) - .await - }; - - for filled in 1..=MAX_COURSE_NOTE_FILES { - add(¬e).await.unwrap(); - assert_eq!(stored_count(¬e).await, filled as i64); - assert_eq!( - CourseNoteFile::list_for(¬e, None, 0, &db) - .await - .unwrap() - .1, - filled as i64 - ); - } - - assert!(matches!(add(¬e).await, Err(AppError::Conflict(_)))); - assert_eq!(stored_count(¬e).await, MAX_COURSE_NOTE_FILES as i64); - assert_eq!( - CourseNoteFile::list_for(¬e, None, 0, &db) - .await - .unwrap() - .1, - MAX_COURSE_NOTE_FILES as i64 - ); - } } diff --git a/src/domain/note_file.rs b/src/domain/note_file.rs index 06703ad..729d724 100644 --- a/src/domain/note_file.rs +++ b/src/domain/note_file.rs @@ -3,28 +3,23 @@ //! [`crate::config::Config::files_path`], in a file named by this row's key — //! a server-generated ULID, so no user input ever shapes a disk path. The web //! layer owns the blob I/O and its ordering (blob before row on upload, row -//! before blob on delete); this module owns the rows. +//! before blob on delete); persistence lives in [`crate::db::note_file`]. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ - MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN, MAX_NOTE_FILES, NOTE_FILE_COUNT_FIELD, - NOTE_FILE_TABLE, -}; -use crate::database::Database; -use crate::db::cap; -use crate::db::page::PagedList; +use crate::constant::{MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN, NOTE_FILE_TABLE}; use crate::domain::monotonic_id::next_ulid; use crate::domain::note::NoteId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct NoteFileId(RecordId); impl NoteFileId { /// Minted from the process-wide monotonic generator, not `Ulid::new()`: - /// a note's files list `id DESC` (newest first, [`NoteFile::list_for_note`]), - /// and a random low half scrambles rows minted in the same millisecond. + /// a note's files list `id DESC` (newest first, + /// [`crate::db::note_file::list_for`]), and a random low half scrambles + /// rows minted in the same millisecond. pub fn generate() -> Self { Self(RecordId::new(NOTE_FILE_TABLE, next_ulid().to_string())) } @@ -119,17 +114,18 @@ impl FileContentType { #[derive(Debug, Clone, SurrealValue)] pub struct NoteFile { - id: NoteFileId, - note: NoteId, - name: FileName, - content_type: FileContentType, - size: i64, + pub(crate) id: NoteFileId, + pub(crate) note: NoteId, + pub(crate) name: FileName, + pub(crate) content_type: FileContentType, + pub(crate) size: i64, } impl NoteFile { /// Assemble a new attachment row (id generated here) without persisting /// it. The caller writes the blob to disk under the fresh id first, then - /// calls [`Self::insert`] — so a stored row always points at a real blob. + /// calls [`crate::db::note_file::insert`] — so a stored row always points + /// at a real blob. pub fn new(note: &NoteId, name: FileName, content_type: FileContentType, size: i64) -> Self { Self { id: NoteFileId::generate(), @@ -155,83 +151,6 @@ impl NoteFile { pub fn get_size(&self) -> i64 { self.size } - - /// Persist the row assembled by [`Self::new`], refusing once its note - /// already holds [`MAX_NOTE_FILES`]. The slot and the row are taken together - /// by [`cap::claim_and_create`] on the note row: a `BEGIN…COMMIT` around a - /// count can't enforce the cap (SurrealDB doesn't conflict-check a - /// cross-record count against a concurrent insert) and a process-wide mutex - /// can't either, since it is released around the very round trip the insert - /// races — a conditional single-record write can. Claiming in a *separate* - /// query would enforce the cap but leak a slot on a crash between the two. - pub async fn insert(self, db: &Database) -> Result { - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber - match cap::claim_and_create( - &self.note.record(), - NOTE_FILE_COUNT_FIELD, - MAX_NOTE_FILES as i64, - &self.id.record(), - &self, - db, - ) - .await? - { - cap::Claimed::Made(created) => Ok(created), - // Also how a missing note reads: no note row means no slot to take. - cap::Claimed::Full => Err(AppError::Conflict( - "the note already holds the maximum of 10 files — delete one first", - )), - // Unreachable: the id is a ULID this call just generated. - cap::Claimed::Duplicate => Err(AppError::Internal("failed to create note file".into())), - } - } - - /// Read a file's row only if it belongs to `note` — callers have already - /// checked the note belongs to the requesting user. - pub async fn read_for( - id: &NoteFileId, - note: &NoteId, - db: &Database, - ) -> Result, AppError> { - let file: Option = db.select(id.record()).await?; - Ok(file.filter(|file| &file.note == note)) - } - - /// All of `note`'s attachment rows, newest first. - pub async fn list_for( - note: &NoteId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new("note_file WHERE note = $note", "ORDER BY id DESC") - .bind("note", note.record()) - .run(limit, offset, db) - .await - } - - /// Delete the row and give its slot back in the same transaction — the note - /// itself is untouched, so unlike the note-delete cascade this one has a - /// counter to correct. (Deleting a *note* takes its counter with it.) - pub async fn delete(self, db: &Database) -> Result { - let mut result = db - .query( - "BEGIN TRANSACTION; - LET $gone = (DELETE $id RETURN BEFORE); - UPDATE $note SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); - RETURN $gone; - COMMIT TRANSACTION;", - ) - .bind(("id", self.id.record())) - .bind(("note", self.note.record())) - .await? - .check()?; - result - .take::>(3)? - .into_iter() - .next() - .ok_or(AppError::NotFound) - } } #[cfg(test)] @@ -271,108 +190,4 @@ mod tests { assert!(FileContentType::try_new("appli¢ation/pdf").is_err()); assert!(FileContentType::try_new("a\r\nb").is_err()); } - - #[tokio::test] - async fn rows_scope_to_their_note() { - let db = crate::database::init_mem().await.unwrap(); - // Real note rows: the cap counter lives on the note, so an insert whose - // note does not exist has no slot to take (a 409, like a full note). - let owner = crate::domain::user::UserId::generate(); - let note_of = async |title: &str| { - crate::db::note::create( - &db, - &owner, - crate::domain::note::NoteTitle::try_new(title).unwrap(), - crate::domain::note::NoteContent::try_new("body").unwrap(), - ) - .await - .unwrap() - }; - let note_a = note_of("a").await.get_id().clone(); - let note_b = note_of("b").await.get_id().clone(); - let file = NoteFile::new( - ¬e_a, - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ) - .insert(&db) - .await - .unwrap(); - - // Readable under its own note, invisible under another. - let found = NoteFile::read_for(file.get_id(), ¬e_a, &db) - .await - .unwrap(); - assert_eq!(found.unwrap().get_name().as_str(), "plan.pdf"); - assert!( - NoteFile::read_for(file.get_id(), ¬e_b, &db) - .await - .unwrap() - .is_none() - ); - - let listed = async |note: &NoteId| NoteFile::list_for(note, None, 0, &db).await.unwrap().0; - assert_eq!(listed(¬e_a).await.len(), 1); - assert!(listed(¬e_b).await.is_empty()); - - file.delete(&db).await.unwrap(); - assert!(listed(¬e_a).await.is_empty()); - } - - /// The counter and the rows are written in one transaction, so the stored - /// count must equal the stored rows — after a success *and* after the - /// refusal that fills the cap, which must move neither. - #[tokio::test] - async fn counter_tracks_stored_rows() { - let db = crate::database::init_mem().await.unwrap(); - let note = crate::db::note::create( - &db, - &crate::domain::user::UserId::generate(), - crate::domain::note::NoteTitle::try_new("a").unwrap(), - crate::domain::note::NoteContent::try_new("body").unwrap(), - ) - .await - .unwrap() - .get_id() - .clone(); - let stored_count = async |note: &NoteId| -> i64 { - db.query("SELECT VALUE file_count FROM $note") - .bind(("note", note.record())) - .await - .unwrap() - .take::>(0) - .unwrap() - .into_iter() - .next() - .unwrap_or(0) - }; - let add = async |note: &NoteId| { - NoteFile::new( - note, - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ) - .insert(&db) - .await - }; - - for filled in 1..=MAX_NOTE_FILES { - add(¬e).await.unwrap(); - assert_eq!(stored_count(¬e).await, filled as i64); - assert_eq!( - NoteFile::list_for(¬e, None, 0, &db).await.unwrap().1, - filled as i64 - ); - } - - // At the cap: the refusal writes nothing, counter included. - assert!(matches!(add(¬e).await, Err(AppError::Conflict(_)))); - assert_eq!(stored_count(¬e).await, MAX_NOTE_FILES as i64); - assert_eq!( - NoteFile::list_for(¬e, None, 0, &db).await.unwrap().1, - MAX_NOTE_FILES as i64 - ); - } } diff --git a/src/domain/rag_output.rs b/src/domain/rag_output.rs index b0356d3..31ee0d7 100644 --- a/src/domain/rag_output.rs +++ b/src/domain/rag_output.rs @@ -16,11 +16,11 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::RAG_OUTPUT_TABLE; use crate::database::Database; +use crate::db::page::PagedList; use crate::domain::course::CourseId; use crate::domain::course_note::CourseNoteId; use crate::domain::course_note_file::CourseNoteFileId; use crate::domain::monotonic_id::next_ulid; -use crate::db::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::error::AppError; @@ -203,25 +203,27 @@ mod tests { ) .await .unwrap(); - CourseNote::create( + crate::db::course_note::create( + db, course.get_id(), &creator, CourseNoteTitle::try_new(title).unwrap(), CourseNoteContent::try_new("body").unwrap(), - db, ) .await .unwrap() } async fn file_on(db: &Database, note: &CourseNoteId) -> CourseNoteFileId { - CourseNoteFile::new( - note, - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, + crate::db::course_note_file::insert( + db, + CourseNoteFile::new( + note, + FileName::try_new("plan.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ), ) - .insert(db) .await .unwrap() .get_id() diff --git a/src/service/board.rs b/src/service/board.rs new file mode 100644 index 0000000..28a18ca --- /dev/null +++ b/src/service/board.rs @@ -0,0 +1,291 @@ +//! Board workflows: the roster gates the REST surface drives and the lock +//! that serializes every read-modify-write of a board's `participants` array. +//! The queries live in [`crate::db::board`]; the room's WebSocket keeps its +//! own binding policy in [`crate::web::board_ws`], reading through here. + +use tokio::sync::Mutex; + +use crate::constant::MAX_BOARD_PARTICIPANTS; +use crate::database::Database; +use crate::db::board; +use crate::domain::board::{Board, BoardId, BoardTitle}; +use crate::domain::role::Role; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ValidationError}; + +/// Serializes every **read-modify-write** of a board's `participants` array: +/// `POST /boards/{id}/invite` (union the resolved group into the roster it just +/// read) and the roster branch of `PATCH /boards/{id}` (which reads the current +/// list to decide which no-longer-eligible ids survive). +/// +/// [`crate::db::board::set_participants`] stores the whole array, so two +/// invites that both read roster `R` write `R ∪ X` and `R ∪ Y` and the second +/// one silently drops the first one's group — a caller told `200` with a list +/// of people who are not on the board, against the route's own "strictly +/// additive" contract. The database cannot refuse that: both are single +/// well-formed writes to one field, and neither is wrong on its own. +/// +/// A lock rather than a compare-and-set because the deployment is one process +/// with stop-the-world deploys, so it genuinely serializes — and because the +/// alternative answer is a `409` on a race between two calls that do not +/// conflict in intent, which a client could only resolve by re-sending the same +/// invite. Contended invites simply queue; the section they hold is one board +/// read, one user-list read and one field write. +/// +/// **A leaf**: nothing under it takes another lock. Note it does not reach the +/// demotion sweep in [`crate::service::user::set_role`], which strips ids +/// from every roster inside the role write's own transaction — an invite that +/// read a roster before that sweep can put a swept id back, which the boot +/// repair and the room's own live gate both still catch. +pub static BOARD_ROSTER_LOCK: Mutex<()> = Mutex::const_new(()); + +/// The board, or a 404 — including the deliberate 404 for a caller who is not +/// on it. Every route starts here, so existence never leaks. +/// +/// A `parent` is treated as an outsider rather than refused with a 403: the +/// role is barred from the whiteboard entirely, and a 403 would confirm the +/// board exists. [`resolve_participants`] keeps parents off every roster, so +/// this arm only ever fires for a row written before that rule. +pub async fn board_for(id: &str, user: &User, db: &Database) -> Result { + let board = board::read(db, &BoardId::from_key(id)) + .await? + .ok_or(AppError::NotFound)?; + if !user.get_role().at_least(Role::Student) || !board.is_participant(user.get_id()) { + return Err(AppError::NotFound); + } + Ok(board) +} + +/// The creator-only gate. A 403, never a 404: the caller reached it through +/// [`board_for`], so they are a participant and the board's existence is +/// already theirs to see. +pub fn ensure_creator(board: &Board, user: &User) -> Result<(), AppError> { + if !board.is_creator(user.get_id()) { + return Err(AppError::Forbidden( + "only the board's creator can clear, lock, close or delete it", + )); + } + Ok(()) +} + +/// The invite list off the wire: deduped, capped, and every id resolved against +/// a real user. The cap is applied *before* the lookup (the domain caps too, but +/// only after the read would already have run), and an unknown id is a 400 +/// rather than a silently dropped invitation. +/// +/// The eligible set is fetched in **one** read, not one per id. That was a +/// per-id loop while a roster could only be typed by hand and so was a handful +/// of ids; bulk invite made a full board an ordinary thing to own, and a +/// read-modify-write PATCH of one — read the board, drop a name, send the rest +/// back — is the common client shape, so the loop had become +/// `max_participants` sequential round trips on a routine edit. +/// +/// A `parent` is refused here, and that is the cut that keeps the role off the +/// whiteboard: never on a roster means [`board_for`] and the room's door already +/// answer 404 on every id-scoped route, and no socket can ever open. +/// +/// The creator is a participant by construction, so they are neither injected +/// into the list nor rejected from it. +/// +/// `current` is the board's roster as it stands (empty when a board is being +/// created), and it is what makes a read-modify-write PATCH survive: an id +/// *already* on the board that no longer qualifies — demoted, or deleted +/// outright — is dropped silently instead of failing the whole call, so a +/// creator echoing back the roster they were just served gets a 200 and a +/// cleaned list. An id that is **new** to the board still 400s; without that +/// split the drop would be a hole letting a caller seed a roster with anyone. +pub async fn resolve_participants( + ids: Option>, + current: &[UserId], + db: &Database, +) -> Result, AppError> { + let Some(mut ids) = ids else { + return Ok(Vec::new()); + }; + ids.sort(); + ids.dedup(); + if ids.len() > MAX_BOARD_PARTICIPANTS { + return Err(AppError::Validation(ValidationError::TooLong { + field: "participants", + max: MAX_BOARD_PARTICIPANTS, + got: ids.len(), + })); + } + let wanted: Vec = ids.iter().map(|id| UserId::from_key(id)).collect(); + // Absent from this list means "no such user, or below `student`" — the two + // are one case here, and telling them apart is what the caller must not be + // able to do anyway. + let eligible: Vec = crate::service::user::list_by_ids(db, &wanted) + .await? + .iter() + .filter(|found| found.get_role().at_least(Role::Student)) + .map(|found| found.get_id().clone()) + .collect(); + let mut users = Vec::with_capacity(wanted.len()); + for user in wanted { + if !eligible.contains(&user) { + if current.contains(&user) { + continue; + } + return Err(AppError::Validation(ValidationError::Invalid { + field: "participants", + reason: "every participant must be an existing user of at least the student role", + })); + } + users.push(user); + } + Ok(users) +} + +/// Union a bulk-invite source's resolved ids into a board's roster: everyone +/// the source names who still resolves to an eligible user is **added**, +/// nobody is ever removed by it. The filters are silent on purpose — a source +/// is a whole group, and one member who has left or was never eligible must +/// not fail the invite for the other twenty-nine. The cap is +/// **all-or-nothing**: an over-full union is refused with a `409` naming the +/// two numbers and the roster is left exactly as it was. +/// +/// The caller holds [`BOARD_ROSTER_LOCK`] across the board read this `board` +/// came from and this write — together they are the read-modify-write the +/// lock exists for. +pub async fn invite(db: &Database, board: &Board, invited: Vec) -> Result { + // One read for the whole group. The filters below are silent on purpose — + // a source is a whole group, and one member who has left or was never + // eligible must not fail the invite for the other twenty-nine. + let mut roster = board.get_participants().to_vec(); + for candidate in crate::service::user::list_by_ids(db, &invited).await? { + if !candidate.get_role().at_least(Role::Student) { + continue; + } + // The creator is a participant by construction and never sits in the + // array; adding them there would spend a seat on someone who already + // has access. + if candidate.get_id() == board.get_creator() || roster.contains(candidate.get_id()) { + continue; + } + roster.push(candidate.get_id().clone()); + } + + if roster.len() > MAX_BOARD_PARTICIPANTS { + return Err(AppError::ConflictOwned(format!( + "this invite would put the board at {} participants, over the limit of {MAX_BOARD_PARTICIPANTS}; nobody was added", + roster.len() + ))); + } + // Unchanged rosters still write and still fan out: the alternative is a + // branch that has to prove the two lists are equal, and a re-invite that + // added nobody is the idempotent case, not the hot path. + board::set_participants(db, board, roster).await +} + +pub async fn create( + db: &Database, + creator: &UserId, + title: BoardTitle, + participants: Vec, +) -> Result { + board::create(db, creator, title, participants).await +} + +pub async fn read(db: &Database, id: &BoardId) -> Result, AppError> { + board::read(db, id).await +} + +pub async fn list_for_user( + db: &Database, + user: &UserId, + open: Option, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + board::list_for_user(db, user, open, limit, offset).await +} + +pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result { + board::set_title(db, board, title).await +} + +pub async fn set_participants( + db: &Database, + board: &Board, + participants: Vec, +) -> Result { + board::set_participants(db, board, participants).await +} + +pub async fn set_locked( + db: &Database, + board: &Board, + locked: bool, + by: &UserId, +) -> Result { + board::set_locked(db, board, locked, by).await +} + +pub async fn close(db: &Database, board: &Board) -> Result { + board::close(db, board).await +} + +/// Delete the board and its whole stroke history; also frees the creator's +/// board seat. +pub async fn delete(db: &Database, board: Board) -> Result { + board::delete(db, board).await +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The security boundary of the gates this module owns, in one test: an + /// outsider is told the board does not exist, an insider without rights is + /// told it is not theirs to command. Swapping those two leaks the school's + /// board list on one side and hides a rendered board from its own + /// participant on the other. + #[tokio::test] + async fn an_outsider_gets_404_and_a_participant_gets_403() { + let db = crate::database::init_mem().await.unwrap(); + db.query( + "CREATE user:c SET username = 'c', password_hash = 'x'; + CREATE user:p SET username = 'p', password_hash = 'x'; + CREATE user:s SET username = 's', password_hash = 'x';", + ) + .await + .unwrap() + .check() + .unwrap(); + let who = async |key: &str| { + crate::service::user::read(&db, &UserId::from_key(key)) + .await + .unwrap() + .unwrap() + }; + let (creator, participant, stranger) = (who("c").await, who("p").await, who("s").await); + let board = create( + &db, + creator.get_id(), + BoardTitle::try_new("Geometri").unwrap(), + vec![participant.get_id().clone()], + ) + .await + .unwrap(); + let id = board.get_id().key().to_string(); + + assert!(matches!( + board_for(&id, &stranger, &db).await, + Err(AppError::NotFound) + )); + // A board that does not exist at all answers the same way, so the two + // are indistinguishable from outside. + assert!(matches!( + board_for("nope", &creator, &db).await, + Err(AppError::NotFound) + )); + + let seen = board_for(&id, &participant, &db).await.unwrap(); + assert!(matches!( + ensure_creator(&seen, &participant), + Err(AppError::Forbidden(_)) + )); + assert!(ensure_creator(&board_for(&id, &creator, &db).await.unwrap(), &creator).is_ok()); + } +} diff --git a/src/service/board_stroke.rs b/src/service/board_stroke.rs new file mode 100644 index 0000000..b3d0d91 --- /dev/null +++ b/src/service/board_stroke.rs @@ -0,0 +1,58 @@ +//! Board-stroke workflows: the drawing, clearing and replay paths the REST +//! surface and the board room drive. The queries live in +//! [`crate::db::board_stroke`]; the room's publish ordering stays in +//! [`crate::web::board_ws`]. + +use crate::database::Database; +use crate::db::board_stroke; +use crate::domain::board::BoardId; +use crate::domain::board_stroke::BoardStroke; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Append one mark to the board's current `epoch`; the conditional claim in +/// the db layer refuses a full canvas, a locked or closed board, and a stale +/// epoch. +pub async fn append( + db: &Database, + board: &BoardId, + author: &UserId, + payload: &str, + epoch: i64, +) -> Result { + board_stroke::append(db, board, author, payload, epoch).await +} + +/// End the current epoch — creator-only upstream: the canvas empties, the +/// history does not. +pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result { + board_stroke::clear(db, board, by).await +} + +/// The current epoch's marks, in mint order, one chunk at a time (`after` is +/// the last stroke already drawn). +pub async fn replay_current( + db: &Database, + board: &BoardId, + epoch: i64, + after: Option<&str>, +) -> Result, AppError> { + board_stroke::replay_current(db, board, epoch, after).await +} + +/// The whole log, oldest first; `marks_only` drops the `clear` markers. +pub async fn history( + db: &Database, + board: &BoardId, + epoch: Option, + marks_only: bool, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + board_stroke::history(db, board, epoch, marks_only, limit, offset).await +} + +/// The epoch index: every `clear` marker this board has, oldest first. +pub async fn epochs(db: &Database, board: &BoardId) -> Result, AppError> { + board_stroke::epochs(db, board).await +} diff --git a/src/service/course.rs b/src/service/course.rs index df515be..1969288 100644 --- a/src/service/course.rs +++ b/src/service/course.rs @@ -8,7 +8,6 @@ use crate::database::Database; use crate::db::course; use crate::domain::answer_image::AnswerImage; use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; -use crate::domain::course_note_file::CourseNoteFile; use crate::domain::homework_file::HomeworkFile; use crate::domain::question_image::QuestionImage; use crate::domain::role::Role; @@ -168,7 +167,8 @@ pub async fn delete(db: &Database, course: &Course) -> Result Result { + course_note::create(db, course, author, title, content).await +} + +pub async fn read(db: &Database, id: &CourseNoteId) -> Result, AppError> { + course_note::read(db, id).await +} + +pub async fn list_for_course( + db: &Database, + course: &CourseId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + course_note::list_for_course(db, course, limit, offset).await +} + +/// Only what the request carried is written: an omitted field (`None`) is +/// not stored at all, so a concurrent edit of the other field survives. +pub async fn update( + db: &Database, + note: CourseNote, + title: Option, + content: Option, +) -> Result { + course_note::update(db, note, title, content).await +} + +/// Delete the note and cascade its attachment rows; the returned files are +/// exactly whose blobs the caller may unlink. +pub async fn delete( + db: &Database, + note: CourseNote, +) -> Result<(CourseNote, Vec), AppError> { + course_note::delete(db, note).await +} diff --git a/src/service/course_note_file.rs b/src/service/course_note_file.rs new file mode 100644 index 0000000..8a943b6 --- /dev/null +++ b/src/service/course_note_file.rs @@ -0,0 +1,48 @@ +//! Course-note-file workflows: the attachment paths the course-notes surface +//! drives. The queries live in [`crate::db::course_note_file`]; blob +//! unlinking and the AI re-index stay in the web layer. + +use crate::database::Database; +use crate::db::course_note_file; +use crate::domain::course_note::CourseNoteId; +use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; +use crate::error::AppError; + +/// Persist a row assembled by [`CourseNoteFile::new`]; refuses with a +/// conflict once the note holds its cap. +pub async fn insert(db: &Database, file: CourseNoteFile) -> Result { + course_note_file::insert(db, file).await +} + +/// Read a file's row by id alone — the AI bridge reaches the note *through* +/// the file, so no note scoping happens here. +pub async fn read( + db: &Database, + id: &CourseNoteFileId, +) -> Result, AppError> { + course_note_file::read(db, id).await +} + +/// Read a file's row only if it belongs to `note`. +pub async fn read_for( + db: &Database, + id: &CourseNoteFileId, + note: &CourseNoteId, +) -> Result, AppError> { + course_note_file::read_for(db, id, note).await +} + +pub async fn list_for( + db: &Database, + note: &CourseNoteId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + course_note_file::list_for(db, note, limit, offset).await +} + +/// Delete the row and hand its slot back in the same transaction; the +/// returned row is exactly whose blob the caller may unlink. +pub async fn delete(db: &Database, file: CourseNoteFile) -> Result { + course_note_file::delete(db, file).await +} diff --git a/src/service/mod.rs b/src/service/mod.rs index 691aa94..a830358 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -3,8 +3,12 @@ pub mod appointment; pub mod appointment_slot; +pub mod board; +pub mod board_stroke; pub mod class_blueprint; pub mod course; +pub mod course_note; +pub mod course_note_file; pub mod course_session; pub mod enrollment; pub mod exam; @@ -12,6 +16,7 @@ pub mod exam_attempt; pub mod exam_question; pub mod meal_booking; pub mod note; +pub mod note_file; pub mod payment_ledger; pub mod session; pub mod settings; diff --git a/src/service/note_file.rs b/src/service/note_file.rs new file mode 100644 index 0000000..a2bb312 --- /dev/null +++ b/src/service/note_file.rs @@ -0,0 +1,39 @@ +//! Note-file workflows: the attachment paths the notes surface drives. The +//! queries live in [`crate::db::note_file`]; blob unlinking stays in the web +//! layer. + +use crate::database::Database; +use crate::db::note_file; +use crate::domain::note::NoteId; +use crate::domain::note_file::{NoteFile, NoteFileId}; +use crate::error::AppError; + +/// Persist a row assembled by [`NoteFile::new`]; refuses with a conflict once +/// the note holds its cap. +pub async fn insert(db: &Database, file: NoteFile) -> Result { + note_file::insert(db, file).await +} + +/// Read a file's row only if it belongs to `note`. +pub async fn read_for( + db: &Database, + id: &NoteFileId, + note: &NoteId, +) -> Result, AppError> { + note_file::read_for(db, id, note).await +} + +pub async fn list_for( + db: &Database, + note: &NoteId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + note_file::list_for(db, note, limit, offset).await +} + +/// Delete the row and hand its slot back in the same transaction; the returned +/// row is exactly whose blob the caller may unlink. +pub async fn delete(db: &Database, file: NoteFile) -> Result { + note_file::delete(db, file).await +} diff --git a/src/service/user.rs b/src/service/user.rs index a6c7b4f..2bd73cb 100644 --- a/src/service/user.rs +++ b/src/service/user.rs @@ -64,8 +64,7 @@ pub async fn ensure_admin( // is no marker that could tell such a row apart from a stranger // who registered the name first, so the hole cannot be healed // later; it has to be impossible to open. - user::create_with_role(db, username, password.hash_async().await?, Role::Admin) - .await?; + user::create_with_role(db, username, password.hash_async().await?, Role::Admin).await?; // No `username` field: with OTLP on every event is exported as a // log record, so an account name here leaves the process. tracing::info!("seeded the admin account named by ADMIN_USERNAME"); @@ -183,7 +182,18 @@ pub async fn set_profile( display_name: Option>, bio: Option>, ) -> Result { - user::set_profile(db, id, name, surname, email, phone, birth_date, display_name, bio).await + user::set_profile( + db, + id, + name, + surname, + email, + phone, + birth_date, + display_name, + bio, + ) + .await } /// Persist an avatar upload, handing back the replaced blob's name. @@ -249,32 +259,28 @@ mod tests { /// just changed is simply never told. Assert the rows come back. #[tokio::test] async fn the_cascade_returns_the_boards_it_stripped() { - use crate::domain::board::{Board, BoardTitle}; + use crate::domain::board::BoardTitle; let db = init_mem().await.unwrap(); let creator = a_user("ogretmen", &db).await; let guest = a_user("ogrenci", &db).await; - let board = Board::create( + let board = crate::db::board::create( + &db, creator.get_id(), BoardTitle::try_new("Geometri").unwrap(), vec![guest.get_id().clone()], - &db, ) .await .unwrap(); // A promotion touches no roster and must report none. - let (guest, boards) = set_role(&db, guest.get_id(), Role::Teacher) - .await - .unwrap(); + let (guest, boards) = set_role(&db, guest.get_id(), Role::Teacher).await.unwrap(); assert!( boards.is_empty(), "only a demotion to parent strips rosters" ); - let (_, boards) = set_role(&db, guest.get_id(), Role::Parent) - .await - .unwrap(); + let (_, boards) = set_role(&db, guest.get_id(), Role::Parent).await.unwrap(); assert_eq!(boards.len(), 1, "the stripped room must be reported back"); assert_eq!(boards[0].get_id(), board.get_id()); assert!( @@ -292,36 +298,37 @@ mod tests { /// readable. #[tokio::test] async fn a_demoted_creator_s_board_is_closed_and_still_readable() { - use crate::domain::board::{Board, BoardTitle}; - use crate::domain::board_stroke::{BOARD_CLOSED, BoardStroke}; + use crate::domain::board::BoardTitle; + use crate::domain::board_stroke::BOARD_CLOSED; let db = init_mem().await.unwrap(); let creator = a_user("ogretmen", &db).await; let guest = a_user("ogrenci", &db).await; - let board = Board::create( + let board = crate::db::board::create( + &db, creator.get_id(), BoardTitle::try_new("Geometri").unwrap(), vec![guest.get_id().clone()], - &db, ) .await .unwrap(); let mark = |epoch| { let (id, author, db) = (board.get_id().clone(), guest.get_id().clone(), db.clone()); - async move { BoardStroke::append(&id, &author, "{\"p\":[1]}", epoch, &db).await } + async move { crate::db::board_stroke::append(&db, &id, &author, "{\"p\":[1]}", epoch).await } }; mark(0).await.unwrap(); - let (creator, boards) = set_role(&db, creator.get_id(), Role::Parent) - .await - .unwrap(); + let (creator, boards) = set_role(&db, creator.get_id(), Role::Parent).await.unwrap(); assert_eq!(boards.len(), 1, "the room must be reported back"); let stamp = boards[0] .get_closed_at() .expect("and carry the closing stamp the room is told about"); // Stored, not merely reported — and nothing else moved. - let stored = Board::read(board.get_id(), &db).await.unwrap().unwrap(); + let stored = crate::db::board::read(&db, board.get_id()) + .await + .unwrap() + .unwrap(); assert_eq!(stored.get_closed_at(), Some(stamp)); assert_eq!( stored.get_participants(), @@ -329,7 +336,7 @@ mod tests { "closing must not empty the roster it did not touch" ); assert_eq!( - BoardStroke::history(board.get_id(), None, false, None, 0, &db) + crate::db::board_stroke::history(&db, board.get_id(), None, false, None, 0) .await .unwrap() .1, @@ -345,11 +352,9 @@ mod tests { // The stamp is the record: a re-run of the sweep must not move it. tokio::time::sleep(std::time::Duration::from_millis(2)).await; - set_role(&db, creator.get_id(), Role::Parent) - .await - .unwrap(); + set_role(&db, creator.get_id(), Role::Parent).await.unwrap(); assert_eq!( - Board::read(board.get_id(), &db) + crate::db::board::read(&db, board.get_id()) .await .unwrap() .unwrap() @@ -369,8 +374,8 @@ mod tests { #[tokio::test] async fn a_demotion_withdraws_the_calendar_and_settles_its_bookings() { use crate::domain::appointment::{AppointmentReason, AppointmentStatus}; - use crate::service::appointment; use crate::domain::timestamp::Timestamp; + use crate::service::appointment; let db = init_mem().await.unwrap(); let staff = |name: &'static str, db: Database| async move { @@ -388,9 +393,15 @@ mod tests { let slot = |owner: &User, offset: i64, db: Database| { let owner = owner.get_id().clone(); async move { - crate::service::appointment_slot::create(&db, &owner, soon(offset), soon(offset + 60_000), None) - .await - .unwrap() + crate::service::appointment_slot::create( + &db, + &owner, + soon(offset), + soon(offset + 60_000), + None, + ) + .await + .unwrap() } }; @@ -454,7 +465,12 @@ mod tests { .unwrap() .check() .unwrap(); - assert!(result.take::>(0).unwrap().is_empty()); + assert!( + result + .take::>(0) + .unwrap() + .is_empty() + ); // Another teacher's calendar is nobody else's business. assert_eq!( diff --git a/src/web/board_ws.rs b/src/web/board_ws.rs index 79ff4fc..e392031 100644 --- a/src/web/board_ws.rs +++ b/src/web/board_ws.rs @@ -9,7 +9,7 @@ //! Two rules shape everything below. //! //! **Persist, then publish.** A stroke is fanned out only once -//! [`BoardStroke::append`] has returned `Ok`, so the channel can never carry a +//! [`board_stroke::append`] has returned `Ok`, so the channel can never carry a //! mark the database refused (a locked board, a full canvas, a closed board). //! The database is the canvas; the channel is a notification about it. A //! client still dedupes by stroke `id` — a resync deliberately re-serves marks @@ -69,11 +69,14 @@ use tokio::sync::broadcast::error::RecvError; use crate::constant::{BOARD_REPLAY_CHUNK, BOARD_WS_TICK_SECS, MAX_BOARD_ID_LEN}; use crate::database::Database; use crate::domain::board::{Board, BoardId}; -use crate::domain::board_stroke::{self, BoardStroke}; +use crate::domain::board_stroke::{ + BOARD_CLOSED, BOARD_LOCKED, BoardStroke, CANVAS_BLANK, EPOCH_FULL, +}; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; +use crate::service::{board, board_stroke}; use crate::state::AppState; use crate::tenant::Slug; use crate::web::CurrentUser; @@ -130,7 +133,7 @@ pub async fn board_ws( if id.len() > MAX_BOARD_ID_LEN || !user.get_role().at_least(Role::Student) { return Err(AppError::NotFound); } - let board = Board::read(&BoardId::from_key(&id), &st.db) + let board = board::read(&st.db, &BoardId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !board.is_participant(user.get_id()) { @@ -213,7 +216,7 @@ async fn live_board(board: &BoardId, user: &UserId, db: &Database) -> Result Step { let mut cursor = after; loop { - let chunk = match BoardStroke::replay_current(board, epoch, cursor.as_deref(), db).await { + let chunk = match board_stroke::replay_current(db, board, epoch, cursor.as_deref()).await { Ok(chunk) => chunk, Err(err) => return send(socket, error_frame(&err, None)).await, }; @@ -460,7 +463,7 @@ async fn handle_message( // cleared since this socket last heard anything. let saved = match live_board(board, user, &st.db).await { Ok(live) => { - BoardStroke::append(board, user, &payload, live.get_epoch(), &st.db).await + board_stroke::append(&st.db, board, user, &payload, live.get_epoch()).await } Err(err) => Err(err), }; @@ -490,7 +493,7 @@ async fn handle_message( } ClientMessage::Clear => match creator_board(socket, board, user, &st.db).await? { None => Ok(()), - Some(live) => match BoardStroke::clear(live.get_id(), user, &st.db).await { + Some(live) => match board_stroke::clear(&st.db, live.get_id(), user).await { // The marker carries the epoch it *closed*; the room's new // canvas is the next one. Same shape as `POST /boards/{id}/clear`. Ok(marker) => { @@ -511,7 +514,7 @@ async fn handle_message( }, ClientMessage::Lock { locked } => match creator_board(socket, board, user, &st.db).await? { None => Ok(()), - Some(live) => match live.set_locked(locked, user, &st.db).await { + Some(live) => match board::set_locked(&st.db, &live, locked, user).await { Ok(_) => { st.board_hub.publish( slug, @@ -570,10 +573,10 @@ async fn creator_board( fn error_frame(err: &AppError, client_seq: Option) -> Value { let code = match err { AppError::Forbidden(_) => "forbidden", - AppError::Conflict(message) if *message == board_stroke::EPOCH_FULL => "epoch_full", - AppError::Conflict(message) if *message == board_stroke::BOARD_LOCKED => "locked", - AppError::Conflict(message) if *message == board_stroke::BOARD_CLOSED => "board_closed", - AppError::Conflict(message) if *message == board_stroke::CANVAS_BLANK => "canvas_blank", + AppError::Conflict(message) if *message == EPOCH_FULL => "epoch_full", + AppError::Conflict(message) if *message == BOARD_LOCKED => "locked", + AppError::Conflict(message) if *message == BOARD_CLOSED => "board_closed", + AppError::Conflict(message) if *message == CANVAS_BLANK => "canvas_blank", // A refusal that already carries its own code keeps it — no board path // raises one today, but re-labelling one "conflict" would throw the // only machine answer it has away. @@ -601,6 +604,7 @@ fn error_frame(err: &AppError, client_seq: Option) -> Value { #[cfg(test)] mod tests { use super::*; + use crate::domain::board_stroke::{BOARD_MOVED, REFUSALS}; fn code(err: AppError) -> String { error_frame(&err, None)["code"] @@ -618,26 +622,26 @@ mod tests { /// test that pins the wording rots into a test of a string the code can no /// longer emit, which is exactly how the blank canvas shipped as /// `board_closed` through a green suite. The length assertion is the other - /// half — a refusal added to `board_stroke::REFUSALS` fails here until it + /// half — a refusal added to `REFUSALS` fails here until it /// is given the code its client must act on. #[test] fn every_refusal_gets_the_code_its_client_must_act_on() { let pairs = [ - (board_stroke::EPOCH_FULL, "epoch_full"), - (board_stroke::BOARD_LOCKED, "locked"), - (board_stroke::BOARD_CLOSED, "board_closed"), - (board_stroke::CANVAS_BLANK, "canvas_blank"), + (EPOCH_FULL, "epoch_full"), + (BOARD_LOCKED, "locked"), + (BOARD_CLOSED, "board_closed"), + (CANVAS_BLANK, "canvas_blank"), // A stroke that lost its epoch to a clear is a plain retryable // conflict, and must never be mistaken for terminal. - (board_stroke::BOARD_MOVED, "conflict"), + (BOARD_MOVED, "conflict"), ]; assert_eq!( pairs.len(), - board_stroke::REFUSALS.len(), + REFUSALS.len(), "a refusal the room cannot code" ); for (message, expected) in pairs { - assert!(board_stroke::REFUSALS.contains(&message)); + assert!(REFUSALS.contains(&message)); assert_eq!(code(AppError::Conflict(message)), expected, "{message}"); } assert_eq!(code(AppError::Forbidden("nope")), "forbidden"); @@ -653,18 +657,9 @@ mod tests { /// the three collapse into one code. #[test] fn a_blank_canvas_is_never_terminal() { - assert_eq!( - code(AppError::Conflict(board_stroke::CANVAS_BLANK)), - "canvas_blank" - ); - assert_eq!( - code(AppError::Conflict(board_stroke::BOARD_CLOSED)), - "board_closed" - ); - assert_eq!( - code(AppError::Conflict(board_stroke::BOARD_LOCKED)), - "locked" - ); + assert_eq!(code(AppError::Conflict(CANVAS_BLANK)), "canvas_blank"); + assert_eq!(code(AppError::Conflict(BOARD_CLOSED)), "board_closed"); + assert_eq!(code(AppError::Conflict(BOARD_LOCKED)), "locked"); } /// The upgrade door's role bar has to hold for the *life* of the socket. @@ -696,11 +691,11 @@ mod tests { .await .unwrap(); let mate_id = mate.get_id().clone(); - let board = Board::create( + let board = board::create( + &db, creator.get_id(), BoardTitle::try_new("Tahta").unwrap(), vec![mate_id.clone()], - &db, ) .await .unwrap(); diff --git a/src/web/boards.rs b/src/web/boards.rs index d816d0c..d2d5055 100644 --- a/src/web/boards.rs +++ b/src/web/boards.rs @@ -28,9 +28,8 @@ use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; -use crate::constant::MAX_BOARD_PARTICIPANTS; use crate::database::Database; -use crate::domain::board::{BOARD_ROSTER_LOCK, Board, BoardId, BoardTitle}; +use crate::domain::board::{Board, BoardId, BoardTitle}; use crate::domain::board_stroke::BoardStroke; use crate::domain::class_group::{ClassGroup, ClassGroupId}; use crate::domain::class_member::ClassMember; @@ -39,6 +38,8 @@ use crate::domain::event::{Event, EventId}; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service::board::BOARD_ROSTER_LOCK; +use crate::service::{board, board_stroke}; use crate::state::AppState; use crate::tenant::Slug; @@ -61,104 +62,6 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(invite_board)) } -/// The board, or a 404 — including the deliberate 404 for a caller who is not -/// on it. Every route starts here, so existence never leaks. -/// -/// A `parent` is treated as an outsider rather than refused with a 403: the -/// role is barred from the whiteboard entirely, and a 403 would confirm the -/// board exists. [`resolve_participants`] keeps parents off every roster, so -/// this arm only ever fires for a row written before that rule. -async fn board_for(id: &str, user: &User, db: &Database) -> Result { - let board = Board::read(&BoardId::from_key(id), db) - .await? - .ok_or(AppError::NotFound)?; - if !user.get_role().at_least(Role::Student) || !board.is_participant(user.get_id()) { - return Err(AppError::NotFound); - } - Ok(board) -} - -/// The creator-only gate. A 403, never a 404: the caller reached it through -/// [`board_for`], so they are a participant and the board's existence is -/// already theirs to see. -fn ensure_creator(board: &Board, user: &User) -> Result<(), AppError> { - if !board.is_creator(user.get_id()) { - return Err(AppError::Forbidden( - "only the board's creator can clear, lock, close or delete it", - )); - } - Ok(()) -} - -/// The invite list off the wire: deduped, capped, and every id resolved against -/// a real user. The cap is applied *before* the lookup (the domain caps too, but -/// only after the read would already have run), and an unknown id is a 400 -/// rather than a silently dropped invitation. -/// -/// The eligible set is fetched in **one** read, not one per id. That was a -/// per-id loop while a roster could only be typed by hand and so was a handful -/// of ids; bulk invite made a full board an ordinary thing to own, and a -/// read-modify-write PATCH of one — read the board, drop a name, send the rest -/// back — is the common client shape, so the loop had become -/// `max_participants` sequential round trips on a routine edit. -/// -/// A `parent` is refused here, and that is the cut that keeps the role off the -/// whiteboard: never on a roster means [`board_for`] and the room's door already -/// answer 404 on every id-scoped route, and no socket can ever open. -/// -/// The creator is a participant by construction, so they are neither injected -/// into the list nor rejected from it. -/// -/// `current` is the board's roster as it stands (empty when a board is being -/// created), and it is what makes a read-modify-write PATCH survive: an id -/// *already* on the board that no longer qualifies — demoted, or deleted -/// outright — is dropped silently instead of failing the whole call, so a -/// creator echoing back the roster they were just served gets a 200 and a -/// cleaned list. An id that is **new** to the board still 400s; without that -/// split the drop would be a hole letting a caller seed a roster with anyone. -async fn resolve_participants( - ids: Option>, - current: &[UserId], - db: &Database, -) -> Result, AppError> { - let Some(mut ids) = ids else { - return Ok(Vec::new()); - }; - ids.sort(); - ids.dedup(); - if ids.len() > MAX_BOARD_PARTICIPANTS { - return Err(AppError::Validation(ValidationError::TooLong { - field: "participants", - max: MAX_BOARD_PARTICIPANTS, - got: ids.len(), - })); - } - let wanted: Vec = ids.iter().map(|id| UserId::from_key(id)).collect(); - // Absent from this list means "no such user, or below `student`" — the two - // are one case here, and telling them apart is what the caller must not be - // able to do anyway. - let eligible: Vec = crate::service::user::list_by_ids(db, &wanted) - .await? - .iter() - .filter(|found| found.get_role().at_least(Role::Student)) - .map(|found| found.get_id().clone()) - .collect(); - let mut users = Vec::with_capacity(wanted.len()); - for user in wanted { - if !eligible.contains(&user) { - if current.contains(&user) { - continue; - } - return Err(AppError::Validation(ValidationError::Invalid { - field: "participants", - reason: "every participant must be an existing user of at least the student role", - })); - } - users.push(user); - } - Ok(users) -} - /// Push one frame to whoever is in the room right now. An empty room is the /// normal case, not a failure. fn fan_out(st: &AppState, slug: &Slug, board: &BoardId, frame: serde_json::Value) { @@ -300,8 +203,8 @@ async fn create_board( ) -> Result<(StatusCode, Json), AppError> { let title = BoardTitle::try_new(&req.title)?; // No roster yet, so nothing is grandfathered: every id must qualify. - let participants = resolve_participants(req.participants, &[], &st.db).await?; - let board = Board::create(user.get_id(), title, participants, &st.db).await?; + let participants = board::resolve_participants(req.participants, &[], &st.db).await?; + let board = board::create(&st.db, user.get_id(), title, participants).await?; Ok((StatusCode::CREATED, Json(BoardResponse::new(&board)))) } @@ -343,7 +246,7 @@ async fn list_boards( ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; let (boards, total) = - Board::list_for_user(user.get_id(), filter.open, limit, offset, &st.db).await?; + board::list_for_user(&st.db, user.get_id(), filter.open, limit, offset).await?; let items = boards.iter().map(BoardResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -368,7 +271,7 @@ async fn get_board( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { - let board = board_for(&id, &user, &st.db).await?; + let board = board::board_for(&id, &user, &st.db).await?; Ok(Json(BoardResponse::new(&board))) } @@ -397,20 +300,20 @@ async fn list_strokes( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let board = board_for(&id, &user, &st.db).await?; + let board = board::board_for(&id, &user, &st.db).await?; // The current epoch holds no `clear` marker — a marker is written with the // epoch it *closed* — so scoping history to it is the live canvas. Markers // are dropped anyway: a clear committing between the board read above and // this read files one under the epoch just named, and the room's socket // never shows it, so without the filter the two views disagree in exactly // that race. - let (strokes, total) = BoardStroke::history( + let (strokes, total) = board_stroke::history( + &st.db, board.get_id(), Some(board.get_epoch()), true, limit, offset, - &st.db, ) .await?; let items = strokes.iter().map(StrokeResponse::new).collect(); @@ -448,9 +351,9 @@ async fn list_history( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let board = board_for(&id, &user, &st.db).await?; + let board = board::board_for(&id, &user, &st.db).await?; let (strokes, total) = - BoardStroke::history(board.get_id(), scope.epoch, false, limit, offset, &st.db).await?; + board_stroke::history(&st.db, board.get_id(), scope.epoch, false, limit, offset).await?; let items = strokes.iter().map(StrokeResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -481,8 +384,8 @@ async fn list_epochs( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let board = board_for(&id, &user, &st.db).await?; - let markers = BoardStroke::epochs(board.get_id(), &st.db).await?; + let board = board::board_for(&id, &user, &st.db).await?; + let markers = board_stroke::epochs(&st.db, board.get_id()).await?; // Paged in the web layer: the marker list is one bounded read, and a board // has at most one marker per clear. let items = paginate(&markers, limit, offset) @@ -550,22 +453,22 @@ async fn update_board( true => Some(BOARD_ROSTER_LOCK.lock().await), false => None, }; - let mut board = board_for(&id, &user, &st.db).await?; + let mut board = board::board_for(&id, &user, &st.db).await?; if req.participants.is_some() || req.locked.is_some() { - ensure_creator(&board, &user)?; + board::ensure_creator(&board, &user)?; } if let Some(title) = req.title.as_deref() { - board = board.set_title(BoardTitle::try_new(title)?, &st.db).await?; + board = board::set_title(&st.db, &board, BoardTitle::try_new(title)?).await?; } if let Some(participants) = req.participants { let participants = - resolve_participants(participants, board.get_participants(), &st.db).await?; - board = board.set_participants(participants, &st.db).await?; + board::resolve_participants(participants, board.get_participants(), &st.db).await?; + board = board::set_participants(&st.db, &board, participants).await?; fan_out(&st, &slug, board.get_id(), participants_frame(&board)); } if let Some(locked) = req.locked { - board = board.set_locked(locked, user.get_id(), &st.db).await?; + board = board::set_locked(&st.db, &board, locked, user.get_id()).await?; fan_out( &st, &slug, @@ -608,9 +511,9 @@ async fn clear_board( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result<(StatusCode, Json), AppError> { - let board = board_for(&id, &user, &st.db).await?; - ensure_creator(&board, &user)?; - let marker = BoardStroke::clear(board.get_id(), user.get_id(), &st.db).await?; + let board = board::board_for(&id, &user, &st.db).await?; + board::ensure_creator(&board, &user)?; + let marker = board_stroke::clear(&st.db, board.get_id(), user.get_id()).await?; // The marker carries the epoch it *closed*; the room's new canvas is the // next one. fan_out( @@ -650,9 +553,9 @@ async fn close_board( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { - let board = board_for(&id, &user, &st.db).await?; - ensure_creator(&board, &user)?; - let board = board.close(&st.db).await?; + let board = board::board_for(&id, &user, &st.db).await?; + board::ensure_creator(&board, &user)?; + let board = board::close(&st.db, &board).await?; fan_out( &st, &slug, @@ -830,37 +733,10 @@ async fn invite_board( // the same roster and the second write would drop the first one's people — // silently, with both callers told 200. See [`BOARD_ROSTER_LOCK`]. let _guard = BOARD_ROSTER_LOCK.lock().await; - let board = board_for(&id, &user, &st.db).await?; - ensure_creator(&board, &user)?; + let board = board::board_for(&id, &user, &st.db).await?; + board::ensure_creator(&board, &user)?; let invited = req.resolve(&user, &st.db).await?; - - // One read for the whole group. The filters below are silent on purpose — - // a source is a whole group, and one member who has left or was never - // eligible must not fail the invite for the other twenty-nine. - let mut roster = board.get_participants().to_vec(); - for candidate in crate::service::user::list_by_ids(&st.db, &invited).await? { - if !candidate.get_role().at_least(Role::Student) { - continue; - } - // The creator is a participant by construction and never sits in the - // array; adding them there would spend a seat on someone who already - // has access. - if candidate.get_id() == board.get_creator() || roster.contains(candidate.get_id()) { - continue; - } - roster.push(candidate.get_id().clone()); - } - - if roster.len() > MAX_BOARD_PARTICIPANTS { - return Err(AppError::ConflictOwned(format!( - "this invite would put the board at {} participants, over the limit of {MAX_BOARD_PARTICIPANTS}; nobody was added", - roster.len() - ))); - } - // Unchanged rosters still write and still fan out: the alternative is a - // branch that has to prove the two lists are equal, and a re-invite that - // added nobody is the idempotent case, not the hot path. - let board = board.set_participants(roster, &st.db).await?; + let board = board::invite(&st.db, &board, invited).await?; fan_out(&st, &slug, board.get_id(), participants_frame(&board)); Ok(Json(BoardResponse::new(&board))) } @@ -888,70 +764,12 @@ async fn delete_board( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result { - let board = board_for(&id, &user, &st.db).await?; - ensure_creator(&board, &user)?; + let board = board::board_for(&id, &user, &st.db).await?; + board::ensure_creator(&board, &user)?; let id = board.get_id().clone(); - board.delete(&st.db).await?; + board::delete(&st.db, board).await?; // Told after the row is gone: a room that acts on this and then re-reads // must find nothing, not a board about to disappear. fan_out(&st, &slug, &id, json!({"type": "deleted"})); Ok(StatusCode::NO_CONTENT) } - -#[cfg(test)] -mod tests { - use super::*; - - /// The security boundary of this module, in one test: an outsider is told - /// the board does not exist, an insider without rights is told it is not - /// theirs to command. Swapping those two leaks the school's board list on - /// one side and hides a rendered board from its own participant on the - /// other. - #[tokio::test] - async fn an_outsider_gets_404_and_a_participant_gets_403() { - let db = crate::database::init_mem().await.unwrap(); - db.query( - "CREATE user:c SET username = 'c', password_hash = 'x'; - CREATE user:p SET username = 'p', password_hash = 'x'; - CREATE user:s SET username = 's', password_hash = 'x';", - ) - .await - .unwrap() - .check() - .unwrap(); - let who = async |key: &str| { - crate::service::user::read(&db, &UserId::from_key(key)) - .await - .unwrap() - .unwrap() - }; - let (creator, participant, stranger) = (who("c").await, who("p").await, who("s").await); - let board = Board::create( - creator.get_id(), - BoardTitle::try_new("Geometri").unwrap(), - vec![participant.get_id().clone()], - &db, - ) - .await - .unwrap(); - let id = board.get_id().key().to_string(); - - assert!(matches!( - board_for(&id, &stranger, &db).await, - Err(AppError::NotFound) - )); - // A board that does not exist at all answers the same way, so the two - // are indistinguishable from outside. - assert!(matches!( - board_for("nope", &creator, &db).await, - Err(AppError::NotFound) - )); - - let seen = board_for(&id, &participant, &db).await.unwrap(); - assert!(matches!( - ensure_creator(&seen, &participant), - Err(AppError::Forbidden(_)) - )); - assert!(ensure_creator(&board_for(&id, &creator, &db).await.unwrap(), &creator).is_ok()); - } -} diff --git a/src/web/course_notes.rs b/src/web/course_notes.rs index 163a6c9..50ae71f 100644 --- a/src/web/course_notes.rs +++ b/src/web/course_notes.rs @@ -57,7 +57,7 @@ pub fn routes() -> OpenApiRouter { /// The note plus its course, or a 404 — every entity handler here gates on /// the parent course, so they always travel together. async fn note_with_course(id: &str, db: &Database) -> Result<(CourseNote, Course), AppError> { - let note = CourseNote::read(&CourseNoteId::from_key(id), db) + let note = service::course_note::read(db, &CourseNoteId::from_key(id)) .await? .ok_or(AppError::NotFound)?; let course = crate::service::course::read(db, note.get_course()) @@ -141,7 +141,8 @@ async fn create( crate::service::course::require_open(&st.db, &course).await?; let title = CourseNoteTitle::try_new(&req.title)?; let content = CourseNoteContent::try_new(&req.content.unwrap_or_default())?; - let note = CourseNote::create(course.get_id(), user.get_id(), title, content, &st.db).await?; + let note = service::course_note::create(&st.db, course.get_id(), user.get_id(), title, content) + .await?; // Indexing is a background bonus, never a condition of storing the note: // the dispatch runs in its own task, so a slow or absent AI service cannot // delay or fail this 201. @@ -189,7 +190,7 @@ async fn list( } let (limit, offset) = page.resolve()?; let (notes, total) = - CourseNote::list_for_course(course.get_id(), limit, offset, &st.db).await?; + service::course_note::list_for_course(&st.db, course.get_id(), limit, offset).await?; let items = notes.iter().map(CourseNoteResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -267,7 +268,7 @@ async fn update( .map(CourseNoteContent::try_new) .transpose()?; - let updated = note.update(title, content, &st.db).await?; + let updated = service::course_note::update(&st.db, note, title, content).await?; // The stored index describes the old text — refresh it. spawn_index(&st, &tenant, updated.clone()); Ok(Json(CourseNoteResponse::new(&updated))) @@ -310,7 +311,7 @@ async fn delete_one( // between strands at worst an unreachable blob, never a row whose blob is // already gone. The files to unlink come from the delete itself, not a // pre-read list — an upload that landed in between is in the cascade too. - let (_, files) = note.delete(&st.db).await?; + let (_, files) = service::course_note::delete(&st.db, note).await?; for file in &files { remove_blob(&st.files_path, file.get_id().key()).await; } @@ -379,8 +380,9 @@ async fn upload_file( )); } crate::service::course::require_open(&st.db, &course).await?; - // The 10-file cap is enforced inside `CourseNoteFile::insert` (count and - // create under one lock) — checking it here too would just race. + // The 10-file cap is enforced inside `service::course_note_file::insert` + // (count and create in one conditional write) — checking it here too would + // just race. let limit = service::settings::load(&st.db).await?.get_max_file_bytes(); let upload = read_upload(&mut multipart, limit).await?; @@ -395,7 +397,7 @@ async fn upload_file( tokio::fs::write(&path, &upload.data) .await .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; - match file.insert(&st.db).await { + match service::course_note_file::insert(&st.db, file).await { Ok(created) => { // The note now holds one more source than the stored index knows. spawn_index(&st, &tenant, note); @@ -440,7 +442,8 @@ async fn list_files( "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note's files", )); } - let (files, total) = CourseNoteFile::list_for(note.get_id(), limit, offset, &st.db).await?; + let (files, total) = + service::course_note_file::list_for(&st.db, note.get_id(), limit, offset).await?; let items = files.iter().map(CourseNoteFileResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -474,10 +477,13 @@ async fn download_file( "only enrolled users, the course creator, an assigned teacher, or a manager/admin can download this course note's files", )); } - let file = - CourseNoteFile::read_for(&CourseNoteFileId::from_key(&file_id), note.get_id(), &st.db) - .await? - .ok_or(AppError::NotFound)?; + let file = service::course_note_file::read_for( + &st.db, + &CourseNoteFileId::from_key(&file_id), + note.get_id(), + ) + .await? + .ok_or(AppError::NotFound)?; let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id().key())) .await .map_err(|err| { @@ -534,16 +540,19 @@ async fn delete_file( )); } crate::service::course::require_open(&st.db, &course).await?; - let file = - CourseNoteFile::read_for(&CourseNoteFileId::from_key(&file_id), note.get_id(), &st.db) - .await? - .ok_or(AppError::NotFound)?; + let file = service::course_note_file::read_for( + &st.db, + &CourseNoteFileId::from_key(&file_id), + note.get_id(), + ) + .await? + .ok_or(AppError::NotFound)?; // Drop every output built from this file before the file itself, so a // stale index cannot outlive its source in a deployment with no AI service // at all, and a failure here leaves the file whole instead of stranding its // blob; the re-index rebuilds from what is left, if a service is connected. RagOutput::delete_with_source(file.get_id(), &st.db).await?; - let file = file.delete(&st.db).await?; + let file = service::course_note_file::delete(&st.db, file).await?; remove_blob(&st.files_path, file.get_id().key()).await; spawn_index(&st, &tenant, note); Ok(StatusCode::NO_CONTENT) @@ -649,7 +658,7 @@ async fn delete_rag( )); } crate::service::course::require_open(&st.db, &course).await?; - // Scoped to the note in the path, like `CourseNoteFile::read_for`: an + // Scoped to the note in the path, like `service::course_note_file::read_for`: an // output of another note is a 404 here, never a cross-note delete. let output = RagOutput::read(&RagOutputId::from_key(&output_id), &st.db) .await? diff --git a/src/web/notes.rs b/src/web/notes.rs index 9c41d24..d562fab 100644 --- a/src/web/notes.rs +++ b/src/web/notes.rs @@ -272,8 +272,9 @@ async fn upload_file( let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) .await? .ok_or(AppError::NotFound)?; - // The 10-file cap is enforced inside `NoteFile::insert` (count and create - // under one lock) — checking it here too would just race. + // The 10-file cap is enforced inside `service::note_file::insert` (count + // and create in one conditional write) — checking it here too would just + // race. let limit = service::settings::load(&st.db).await?.get_max_file_bytes(); let upload = read_upload(&mut multipart, limit).await?; @@ -288,7 +289,7 @@ async fn upload_file( tokio::fs::write(&path, &upload.data) .await .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; - match file.insert(&st.db).await { + match service::note_file::insert(&st.db, file).await { Ok(created) => Ok((StatusCode::CREATED, Json(NoteFileResponse::new(&created)))), Err(err) => { let _ = tokio::fs::remove_file(&path).await; @@ -322,7 +323,7 @@ async fn list_files( let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) .await? .ok_or(AppError::NotFound)?; - let (files, total) = NoteFile::list_for(note.get_id(), limit, offset, &st.db).await?; + let (files, total) = service::note_file::list_for(&st.db, note.get_id(), limit, offset).await?; let items = files.iter().map(NoteFileResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -352,7 +353,7 @@ async fn download_file( let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) .await? .ok_or(AppError::NotFound)?; - let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db) + let file = service::note_file::read_for(&st.db, &NoteFileId::from_key(&file_id), note.get_id()) .await? .ok_or(AppError::NotFound)?; let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id().key())) @@ -405,10 +406,10 @@ async fn delete_file( let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id()) .await? .ok_or(AppError::NotFound)?; - let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db) + let file = service::note_file::read_for(&st.db, &NoteFileId::from_key(&file_id), note.get_id()) .await? .ok_or(AppError::NotFound)?; - let file = file.delete(&st.db).await?; + let file = service::note_file::delete(&st.db, file).await?; remove_blob(&st.files_path, file.get_id().key()).await; Ok(StatusCode::NO_CONTENT) } diff --git a/tests/integration.rs b/tests/integration.rs index 65a4ac1..0a680f3 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -24972,12 +24972,12 @@ async fn draw( epoch: i64, payload: &str, ) -> Result { - BoardStroke::append( + hezarfen_backend::db::board_stroke::append( + db, &BoardId::from_key(board), &UserId::from_key(author), payload, epoch, - db, ) .await } @@ -24985,7 +24985,9 @@ async fn draw( /// The board row as the store holds it — never the response body, which cannot /// prove a counter moved (src/domain/cap.rs:44-49). async fn stored_board(db: &Database, board: &str) -> Option { - Board::read(&BoardId::from_key(board), db).await.unwrap() + hezarfen_backend::db::board::read(db, &BoardId::from_key(board)) + .await + .unwrap() } /// Every stroke row of a board, oldest first, straight out of the table. diff --git a/tests/pagination.rs b/tests/pagination.rs index f19e7ba..96aa2e0 100644 --- a/tests/pagination.rs +++ b/tests/pagination.rs @@ -421,12 +421,12 @@ async fn board_lists_are_paged() { // canvas. for epoch in 0..2 { for n in 0..2 { - hezarfen_backend::domain::board_stroke::BoardStroke::append( + hezarfen_backend::db::board_stroke::append( + &db, &hezarfen_backend::domain::board::BoardId::from_key(&board), &hezarfen_backend::domain::user::UserId::from_key(&ali_id), &format!("{{\"p\":[{epoch},{n}]}}"), epoch, - &db, ) .await .expect("append"); @@ -442,12 +442,12 @@ async fn board_lists_are_paged() { assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); } for n in 0..5 { - hezarfen_backend::domain::board_stroke::BoardStroke::append( + hezarfen_backend::db::board_stroke::append( + &db, &hezarfen_backend::domain::board::BoardId::from_key(&board), &hezarfen_backend::domain::user::UserId::from_key(&ali_id), &format!("{{\"p\":[2,{n}]}}"), 2, - &db, ) .await .expect("append"); diff --git a/tests/persistence.rs b/tests/persistence.rs index e3b5174..4c27276 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -2134,12 +2134,12 @@ async fn boards_and_their_strokes_survive_remigration() { // Two epochs: two marks cleared away, then one live mark. let draw = async |epoch: i64, payload: &str| { - hezarfen_backend::domain::board_stroke::BoardStroke::append( + hezarfen_backend::db::board_stroke::append( + &db, &hezarfen_backend::domain::board::BoardId::from_key(&board), &hezarfen_backend::domain::user::UserId::from_key(&ali_id), payload, epoch, - &db, ) .await .expect("append") diff --git a/tests/regress_boards.rs b/tests/regress_boards.rs index 237824b..a08ee78 100644 --- a/tests/regress_boards.rs +++ b/tests/regress_boards.rs @@ -7,7 +7,6 @@ mod common; use axum::http::StatusCode; use common::{app_and_db, items, login, me_id, send}; use hezarfen_backend::domain::board::BoardId; -use hezarfen_backend::domain::board_stroke::BoardStroke; use hezarfen_backend::domain::user::UserId; use serde_json::json; @@ -38,12 +37,12 @@ async fn a_strokes_page_never_carries_a_clear_marker() { let board = a_board(&app, &ali).await; for n in 0..2 { - BoardStroke::append( + hezarfen_backend::db::board_stroke::append( + &db, &BoardId::from_key(&board), &UserId::from_key(&ali_id), &format!("{{\"p\":[0,{n}]}}"), 0, - &db, ) .await .expect("append"); @@ -120,12 +119,12 @@ async fn a_locked_board_refuses_the_creator_s_clear_with_409() { let ali = login(&app, "ali").await; let ali_id = me_id(&app, &ali).await; let board = a_board(&app, &ali).await; - BoardStroke::append( + hezarfen_backend::db::board_stroke::append( + &db, &BoardId::from_key(&board), &UserId::from_key(&ali_id), "{\"p\":[1,2]}", 0, - &db, ) .await .expect("append"); diff --git a/tests/regress_caps.rs b/tests/regress_caps.rs index 8dff9fe..d06ce99 100644 --- a/tests/regress_caps.rs +++ b/tests/regress_caps.rs @@ -13,7 +13,6 @@ mod common; use axum::http::StatusCode; use common::{app_and_db, create_course, create_exam, enroll, id_of, login, login_as, me_id, send}; use hezarfen_backend::domain::board::BoardId; -use hezarfen_backend::domain::board_stroke::BoardStroke; use hezarfen_backend::domain::user::UserId; use serde_json::json; @@ -281,12 +280,12 @@ async fn a_blank_canvas_cannot_be_cleared_for_a_free_row() { assert_eq!(rows(&db, &board).await, 0, "the refusal minted no marker"); // One mark pays for one marker... - BoardStroke::append( + hezarfen_backend::db::board_stroke::append( + &db, &BoardId::from_key(&board), &UserId::from_key(&ali_id), "{\"p\":[1,2]}", 0, - &db, ) .await .expect("append"); @@ -364,12 +363,12 @@ async fn a_clear_marker_is_charged_to_the_lifetime_counter() { .await; let board = id_of(&res.body); for _ in 0..2 { - BoardStroke::append( + hezarfen_backend::db::board_stroke::append( + &db, &BoardId::from_key(&board), &UserId::from_key(&ali_id), "{\"p\":[1,2]}", 0, - &db, ) .await .expect("append"); @@ -384,12 +383,12 @@ async fn a_clear_marker_is_charged_to_the_lifetime_counter() { // The next epoch keeps counting from there — a marker is never re-counted // and never uncounted. - BoardStroke::append( + hezarfen_backend::db::board_stroke::append( + &db, &BoardId::from_key(&board), &UserId::from_key(&ali_id), "{\"p\":[3,4]}", 1, - &db, ) .await .expect("append"); @@ -492,12 +491,12 @@ async fn a_boards_lifetime_counter_is_repaired_from_its_rows_on_boot() { ) .await; let board = id_of(&res.body); - BoardStroke::append( + hezarfen_backend::db::board_stroke::append( + &db, &BoardId::from_key(&board), &UserId::from_key(&ali_id), "{\"p\":[1,2]}", 0, - &db, ) .await .expect("append"); diff --git a/tests/regress_course_child_orphans.rs b/tests/regress_course_child_orphans.rs index b5d2c2f..59af0b9 100644 --- a/tests/regress_course_child_orphans.rs +++ b/tests/regress_course_child_orphans.rs @@ -51,7 +51,7 @@ use hezarfen_backend::database::{self, Database}; use hezarfen_backend::db::course; use hezarfen_backend::db::course_session as db_course_session; use hezarfen_backend::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; -use hezarfen_backend::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; +use hezarfen_backend::domain::course_note::{CourseNoteContent, CourseNoteTitle}; use hezarfen_backend::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; use hezarfen_backend::domain::course_session::SessionTopic; use hezarfen_backend::domain::exam::{ @@ -151,12 +151,12 @@ fn make_subject(course: CourseId, db: Database) -> JoinHandle JoinHandle> { tokio::spawn(async move { - CourseNote::create( + hezarfen_backend::db::course_note::create( + &db, &course, &teacher(), CourseNoteTitle::try_new("plan").unwrap(), CourseNoteContent::try_new("").unwrap(), - &db, ) .await .map(|_| ()) @@ -264,22 +264,24 @@ async fn the_creates_give_the_courses_roster_counter_back_untouched() { async fn a_course_note_and_its_files_never_outlive_a_course_delete() { let db = database::init_mem().await.unwrap(); let course = a_course(&db).await; - let note = CourseNote::create( + let note = hezarfen_backend::db::course_note::create( + &db, &course, &teacher(), CourseNoteTitle::try_new("plan").unwrap(), CourseNoteContent::try_new("body").unwrap(), - &db, ) .await .unwrap(); - CourseNoteFile::new( - note.get_id(), - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, + hezarfen_backend::db::course_note_file::insert( + &db, + CourseNoteFile::new( + note.get_id(), + FileName::try_new("plan.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ), ) - .insert(&db) .await .unwrap(); @@ -316,12 +318,12 @@ async fn a_course_note_and_its_files_never_outlive_a_course_delete() { async fn a_course_note_file_under_a_deleted_note_is_refused() { let db = database::init_mem().await.unwrap(); let course = a_course(&db).await; - let note = CourseNote::create( + let note = hezarfen_backend::db::course_note::create( + &db, &course, &teacher(), CourseNoteTitle::try_new("plan").unwrap(), CourseNoteContent::try_new("").unwrap(), - &db, ) .await .unwrap(); @@ -332,13 +334,15 @@ async fn a_course_note_file_under_a_deleted_note_is_refused() { "the course, and its note with it, goes" ); - let file = CourseNoteFile::new( - note.get_id(), - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, + let file = hezarfen_backend::db::course_note_file::insert( + &db, + CourseNoteFile::new( + note.get_id(), + FileName::try_new("plan.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ), ) - .insert(&db) .await; assert!( matches!(file, Err(AppError::Conflict(_))),