From 5dfce557b1038dfa9c11360fabe0d336f7594d68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 31 Jul 2026 13:54:24 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=F0=9F=96=8D=EF=B8=8F=20collaborative?= =?UTF-8?q?=20whiteboard=20domain,=20REST=20and=20limits?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Boards are an ad-hoc invite list: the creator names participants, and every participant draws. Clearing, locking, closing and deleting are the creator's alone. Strokes are an append-only log and a clear NEVER deletes — it bumps the board's epoch, so the live canvas empties while the whole history stays replayable. The clear marker row doubles as the epoch index, carrying the epoch it closed and that epoch's final stroke count, which is why there is no epochs table. Growth is bounded by two counters claimed together in one conditional write: epoch_stroke_count resets on a clear and caps the live canvas (recoverable — clear and keep drawing), while total_stroke_count never resets and stamps closed_at when the lifetime cap is hit, leaving the board permanently read-only but fully readable. board_count on user bounds the open-a-new-board escape hatch. Outsiders get 404 everywhere so a board's existence never leaks; a participant lacking creator rights gets 403, since existence has already been disclosed to them. The WebSocket room lands separately. --- src/constant.rs | 84 +++++ src/domain/board.rs | 491 +++++++++++++++++++++++++++ src/domain/board_stroke.rs | 613 +++++++++++++++++++++++++++++++++ src/domain/cap.rs | 274 +++++++++++++++ src/domain/mod.rs | 2 + src/lib.rs | 2 + src/main.rs | 1 + src/migration_sql.rs | 45 +++ src/state.rs | 81 +++++ src/web/boards.rs | 640 +++++++++++++++++++++++++++++++++++ src/web/limits.rs | 42 +++ src/web/mod.rs | 1 + tests/ai_bridge.rs | 2 + tests/common/mod.rs | 1 + tests/e2e.rs | 1 + tests/integration.rs | 17 + tests/limits_completeness.rs | 16 + tests/persistence.rs | 1 + tests/rate_limit.rs | 2 + tests/spec_bounds.rs | 26 ++ 20 files changed, 2342 insertions(+) create mode 100644 src/domain/board.rs create mode 100644 src/domain/board_stroke.rs create mode 100644 src/web/boards.rs diff --git a/src/constant.rs b/src/constant.rs index 60ef900..8f9cb7c 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -273,6 +273,52 @@ pub const MAX_FEE_PLAN_ASSIGN_STUDENTS: usize = 200; /// UUID or a receipt number comfortably. pub const MAX_PAYMENT_REQUEST_KEY_LEN: usize = 64; +/// Bounds on a whiteboard: its title, and how many people the creator may name +/// onto it. Fifty is a class and its teachers, not the school; every +/// participant may draw, so this is also what bounds one board's writer count. +pub const MAX_BOARD_TITLE_LEN: usize = 200; +pub const MAX_BOARD_PARTICIPANTS: usize = 50; + +/// Ceiling on one stroke's serialized payload. A stroke is a short path — a +/// handful of points, a colour, a width — and it is stored verbatim and fanned +/// out to every socket in the room, so it is bounded at the wire rather than at +/// the canvas: 4 KiB takes a long freehand curve and still keeps the worst-case +/// board (`MAX_BOARD_STROKES` of them) inside a couple hundred megabytes. +pub const MAX_STROKE_PAYLOAD_LEN: usize = 4_096; + +/// The two growth caps, both counted on the board row (see the counter fields +/// below). They are different kinds of full on purpose: +/// +/// `MAX_EPOCH_STROKES` caps the *live* canvas — the strokes since the last +/// clear. Hitting it is recoverable: the creator clears, the epoch counter +/// resets to zero and drawing resumes. Nothing is deleted by that clear. +/// +/// `MAX_BOARD_STROKES` caps the board's total *storage*, and never resets, +/// because a clear keeps its history for playback. Hitting it stamps +/// `closed_at`: the board turns permanently read-only, but stays fully +/// readable and replayable — a closed board loses no stroke it ever carried. +pub const MAX_EPOCH_STROKES: i64 = 5_000; +pub const MAX_BOARD_STROKES: i64 = 50_000; + +/// How many boards one creator may hold. Without it the two caps above cost an +/// attacker nothing — a full board is answered by opening the next one — so +/// this is the counter that actually bounds a single account's storage. Kept on +/// the user row, the same shape as `CHATBOT_THREAD_COUNT_FIELD`. +pub const MAX_BOARDS_PER_CREATOR: i64 = 200; + +/// The only accepted stroke kinds. `stroke`: a drawn path, carrying its +/// payload. `clear`: the marker row that ends an epoch — it deletes nothing, +/// it is the epoch index, so replaying across it reconstructs the whole +/// session. +pub const BOARD_STROKE_KINDS: [&str; 2] = ["stroke", "clear"]; + +/// Ceiling on a `board_id` arriving on the board WebSocket, for the same reason +/// as [`MAX_QUESTION_ID_LEN`]: the field is a record key — a 26-char ULID in +/// every real payload — and the error frame *echoes* it back, so an unbounded +/// id lets a client make its own room reflect a 64 MiB frame at it. Checked +/// before any database work. +pub const MAX_BOARD_ID_LEN: usize = 64; + /// Inclusive bounds for an exam's per-attempt duration, milliseconds /// (1 minute to 24 hours). Required for `async`, optional for `open`. pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000; @@ -315,6 +361,22 @@ pub const DB_CONNECT_BACKOFF_MAX_SECS: u64 = 5; /// (`GET /exams/{id}/attempt/ws`). pub const EXAM_WS_TICK_SECS: u64 = 2; +/// Cadence of the keepalive ticks on the whiteboard-room WebSocket. Slower than +/// the exam room's, because a board room carries no countdown a client renders +/// against — the tick only keeps an idle socket from being reaped. +pub const BOARD_WS_TICK_SECS: u64 = 15; + +/// How many strokes one replay message carries when a socket joins. The join +/// replays the current epoch, which is `MAX_EPOCH_STROKES` at worst, so it is +/// sent in batches rather than as one frame that could reach the WebSocket +/// frame limit on a busy board. +pub const BOARD_REPLAY_CHUNK: usize = 200; + +/// Depth of one board room's fan-out channel: how far a slow socket may lag the +/// strokes being drawn before it is dropped and has to rejoin (which replays +/// the epoch from storage anyway, so nothing is lost by the drop). +pub const BOARD_HUB_CAPACITY: usize = 256; + /// Ceiling on a `question_id` arriving on the exam-room WebSocket. The field is /// a record key — a 26-char ULID in every real payload — not free text, so this /// is generous by a factor of two and change. The cap exists because the @@ -663,6 +725,8 @@ pub const MEAL_LEDGER_TABLE: &str = "meal_ledger"; pub const FEE_PLAN_TABLE: &str = "fee_plan"; pub const FEE_PLAN_ASSIGNMENT_TABLE: &str = "fee_plan_assignment"; pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger"; +pub const BOARD_TABLE: &str = "board"; +pub const BOARD_STROKE_TABLE: &str = "board_stroke"; /// One row per *name* the school's settings offer, keyed by the name itself: /// how many rows still reference it, and whether it has been retired out of the /// list (see the reference counters in [`crate::domain::cap`]). @@ -702,6 +766,20 @@ pub const FEE_PLAN_UNASSIGNED_GUARD: &str = "(assignment_count ?? 0) = 0"; pub const NOTE_FILE_COUNT_FIELD: &str = "file_count"; pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count"; pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count"; +/// How many boards this user created, on the user row — the same per-user shape +/// as `CHATBOT_THREAD_COUNT_FIELD`, capped at `MAX_BOARDS_PER_CREATOR`. It is +/// what closes the "open another board" way around the two board counters +/// below; released when a board is deleted. +pub const USER_BOARD_COUNT_FIELD: &str = "board_count"; +/// The two stroke counters on a board row. `epoch_stroke_count` is reset to +/// zero by a clear and capped at `MAX_EPOCH_STROKES` — a full epoch is +/// recoverable. `total_stroke_count` is never reset and capped at +/// `MAX_BOARD_STROKES`; reaching it stamps `closed_at`, and a closed board is +/// read-only for good. Both are claimed in the same conditional write as the +/// stroke row, so two people drawing at once contend on the board record rather +/// than on a `SELECT count()` either of them can outrun. +pub const BOARD_EPOCH_STROKE_COUNT_FIELD: &str = "epoch_stroke_count"; +pub const BOARD_TOTAL_STROKE_COUNT_FIELD: &str = "total_stroke_count"; /// Cap 1, not N: an appointment slot holds at most one live booking, so this /// counter is really an "is it taken" flag kept in the shape every other cap /// uses (`claim`/`release`), which is what makes rejecting or cancelling a @@ -743,6 +821,12 @@ pub const SUBMISSION_GRADED_FIELD: &str = "graded_by_result"; /// The condition itself, spelled once: a submission is writable exactly while /// its grade stamp is absent. pub const SUBMISSION_OPEN_GUARD: &str = "graded_by_result = NONE"; +/// The same idea for a whiteboard, spelled once: a board accepts strokes +/// exactly while the creator has not locked it and it has not closed itself on +/// `MAX_BOARD_STROKES`. Every stroke write carries it, so "is this board still +/// open" and the write it licenses are one conditional single-record write — +/// a lock landing mid-draw beats the stroke instead of racing it. +pub const BOARD_OPEN_GUARD: &str = "locked = false AND closed_at = NONE"; /// How hard a counter write tries before giving up, and the first backoff step /// it sleeps between attempts (doubling, plus jitter). Contention on one record diff --git a/src/domain/board.rs b/src/domain/board.rs new file mode 100644 index 0000000..e996ab8 --- /dev/null +++ b/src/domain/board.rs @@ -0,0 +1,491 @@ +//! A collaborative whiteboard room. Membership is an ad-hoc invite list the +//! creator names — no course, session or appointment is involved — and the +//! whole permission model is the two predicates [`Board::is_participant`] +//! (draw) and [`Board::is_creator`] (clear / lock / close / delete). Every +//! route and every socket frame gates on exactly those two. +//! +//! The marks themselves live in `board_stroke`, appended and never deleted: a +//! clear bumps `epoch` so the canvas empties while the history stays +//! replayable. The two stroke counters (`epoch_stroke_count`, +//! `total_stroke_count`) are `option` columns this struct deliberately +//! does NOT carry — they are written only by the stroke path's conditional +//! claim, so every mutation here is field-scoped `UPDATE … SET`. A whole-row +//! `CONTENT` save would silently wipe both (src/constant.rs:717-722). + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; + +use crate::constant::{ + BOARD_TABLE, MAX_BOARD_PARTICIPANTS, MAX_BOARD_TITLE_LEN, MAX_BOARDS_PER_CREATOR, + USER_BOARD_COUNT_FIELD, +}; +use crate::database::Database; +use crate::domain::cap; +use crate::domain::monotonic_id::next_ulid; +use crate::domain::page::PagedList; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::validate_required; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct BoardId(RecordId); + +impl BoardId { + /// Monotonic, not `Ulid::new()`: boards list newest-first by id, and a + /// random low half scrambles rows minted in the same millisecond. + pub fn generate() -> Self { + Self(RecordId::new(BOARD_TABLE, next_ulid().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(BOARD_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct BoardTitle(String); + +impl BoardTitle { + pub fn try_new(value: &str) -> Result { + validate_required("title", value, MAX_BOARD_TITLE_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// 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> { + let mut unique: Vec = Vec::with_capacity(participants.len()); + for user in participants { + if !unique.contains(&user) { + unique.push(user); + } + } + if unique.len() > MAX_BOARD_PARTICIPANTS { + return Err(ValidationError::TooLong { + field: "participants", + max: MAX_BOARD_PARTICIPANTS, + got: unique.len(), + }); + } + Ok(unique) +} + +#[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, +} + +impl Board { + pub fn get_id(&self) -> &BoardId { + &self.id + } + + pub fn get_creator(&self) -> &UserId { + &self.creator + } + + pub fn get_title(&self) -> &BoardTitle { + &self.title + } + + pub fn get_participants(&self) -> &[UserId] { + &self.participants + } + + pub fn is_locked(&self) -> bool { + self.locked + } + + pub fn get_locked_by(&self) -> Option<&UserId> { + self.locked_by.as_ref() + } + + pub fn get_locked_at(&self) -> Option { + self.locked_at + } + + pub fn get_epoch(&self) -> i64 { + self.epoch + } + + pub fn get_closed_at(&self) -> Option { + self.closed_at + } + + pub fn get_created_at(&self) -> Timestamp { + self.created_at + } + + /// May draw. The creator is always in, without being named on the list. + pub fn is_participant(&self, user: &UserId) -> bool { + &self.creator == user || self.participants.contains(user) + } + + /// May clear, lock, close and delete. Nothing else is creator-only. + 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. + pub async fn list_for_user( + user: &UserId, + limit: Option, + offset: i64, + db: &Database, + ) -> Result<(Vec, i64), AppError> { + PagedList::new( + "board WHERE creator = $usr OR participants CONTAINS $usr", + "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)?) + } + + /// 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 { + let mut result = db + .query( + "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;", + ) + .bind(("id", self.id.record())) + .bind(("usr", self.creator.record())) + .await? + .check()?; + // 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 + } + + 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() + } + + #[tokio::test] + async fn the_two_predicates_are_the_permission_model() { + let db = a_db().await; + let board = a_board(&db).await; + // Creator: draws AND commands. + assert!(board.is_participant(&user("c"))); + assert!(board.is_creator(&user("c"))); + // Invited: draws only. + assert!(board.is_participant(&user("p"))); + assert!(!board.is_creator(&user("p"))); + // Stranger: neither. + assert!(!board.is_participant(&user("s"))); + assert!(!board.is_creator(&user("s"))); + } + + #[test] + fn title_is_required_and_bounded() { + assert!(BoardTitle::try_new(" ").is_err()); + assert!(BoardTitle::try_new(&"x".repeat(MAX_BOARD_TITLE_LEN)).is_ok()); + assert!(BoardTitle::try_new(&"x".repeat(MAX_BOARD_TITLE_LEN + 1)).is_err()); + } + + #[tokio::test] + async fn participants_are_deduplicated_and_bounded() { + assert_eq!( + checked_participants(vec![user("p"), user("p")]) + .unwrap() + .len(), + 1 + ); + let many = (0..MAX_BOARD_PARTICIPANTS + 1) + .map(|n| UserId::from_key(&format!("u{n}"))) + .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]); + } +} diff --git a/src/domain/board_stroke.rs b/src/domain/board_stroke.rs new file mode 100644 index 0000000..d55a7e1 --- /dev/null +++ b/src/domain/board_stroke.rs @@ -0,0 +1,613 @@ +//! One board's marks, appended and never deleted. +//! +//! 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. +//! +//! 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 +//! 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 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::domain::cap; +use crate::domain::monotonic_id::next_ulid; +use crate::domain::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]; + +/// The `THROW` the clear transaction refuses with: not the creator, or the +/// board is already closed. A decision, so it outranks a lost round. +const CLEAR_REFUSED: &str = "board_clear_refused"; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct BoardStrokeId(RecordId); + +impl BoardStrokeId { + /// Monotonic, not `Ulid::new()`: this id *is* the board's total order, and + /// a random low half scrambles every stroke drawn in the same millisecond — + /// which is what a burst of drawing looks like. + pub fn generate() -> Self { + Self(RecordId::new(BOARD_STROKE_TABLE, next_ulid().to_string())) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct BoardStroke { + id: BoardStrokeId, + board: BoardId, + author: UserId, + kind: String, + payload: Option, + count: Option, + epoch: i64, + created_at: Timestamp, +} + +impl BoardStroke { + pub fn get_id(&self) -> &BoardStrokeId { + &self.id + } + + pub fn get_board(&self) -> &BoardId { + &self.board + } + + pub fn get_author(&self) -> &UserId { + &self.author + } + + pub fn get_kind(&self) -> &str { + &self.kind + } + + pub fn get_payload(&self) -> Option<&str> { + self.payload.as_deref() + } + + /// The epoch's final stroke count — present only on a `clear` marker. + pub fn get_count(&self) -> Option { + self.count + } + + pub fn get_epoch(&self) -> i64 { + self.epoch + } + + pub fn get_created_at(&self) -> Timestamp { + self.created_at + } + + 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. + // + // ponytail: `epoch` is the caller's read of the board, so a clear landing + // between that read and this write files the stroke under the epoch that + // just ended — it is kept and replayable, but it never appears on the live + // canvas, and the marker's `count` under-reports it by one. Harmless (a + // stroke drawn during a clear is exactly the stroke the clear was erasing); + // closing it means passing the epoch through the conditional write, which + // the shared `cap` helper's static CONTENT cannot express. + 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(), + }; + 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, + BOARD_OPEN_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( + "this board is full — clear it to keep drawing", + )), + // Three refusals share this answer (lifetime full / guard failed / + // board gone), so the board is re-read to pick the message. The + // re-read decides *wording* only: every branch is a refusal the + // caller cannot retry into a success, so a board that changes state + // between the claim and the re-read still gets told "no". + cap::ClaimedTwo::FullHard => Err(Self::why_refused(board, db).await?), + } + } + + async fn why_refused(board: &BoardId, db: &Database) -> Result { + let board = Board::read(board, db).await?.ok_or(AppError::NotFound)?; + if board.is_locked() { + return Ok(AppError::Conflict( + "this board is locked — the creator has paused drawing", + )); + } + if board.get_closed_at().is_none() { + // Neither locked nor closed, so the lifetime cap was just reached. + // `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( + "this board is closed — it is permanently read-only", + )) + } + + /// 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. + 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 \ + WHERE creator = $by AND closed_at = NONE 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()), + ]; + 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(AppError::Conflict( + "this board cannot be cleared — it is closed, or you did not create it", + )); + } + 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())) + } + + /// 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. + pub async fn history( + board: &BoardId, + epoch: Option, + limit: Option, + offset: i64, + db: &Database, + ) -> Result<(Vec, i64), AppError> { + let scope = match epoch { + Some(_) => " AND epoch = $e", + None => "", + }; + PagedList::new( + format!("{BOARD_STROKE_TABLE} WHERE board = $b{scope}"), + "ORDER BY id", + ) + .bind("b", board.record()) + .bind("e", epoch.unwrap_or_default()) + .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()); + } + + /// 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, None, 0, &db) + .await + .unwrap(); + assert_eq!((all.len(), total), (3, 3)); + let (first, total) = BoardStroke::history(board.get_id(), Some(0), None, 0, &db) + .await + .unwrap(); + // Epoch 0: its stroke and the marker that closed it. + assert_eq!((first.len(), total), (2, 2)); + } +} diff --git a/src/domain/cap.rs b/src/domain/cap.rs index 1c0b504..aef7284 100644 --- a/src/domain/cap.rs +++ b/src/domain/cap.rs @@ -112,6 +112,15 @@ async fn claim_at( const FULL_MARK: &str = "cap_full"; const HELD_MARK: &str = "cap_held"; +/// The two markers [`claim_two_when_and_create`] aborts with, one per counter, +/// deliberately *not* shared: its two caps mean opposite things to the person +/// who hit one. The soft cap is a resettable working set (a whiteboard's live +/// canvas, emptied by a clear and drawn on again); the hard cap is the parent's +/// lifetime budget, and hitting it is terminal. One marker for both would tell +/// a caller a recoverable state is a permanent one. +const SOFT_FULL_MARK: &str = "cap_full_soft"; +const HARD_FULL_MARK: &str = "cap_full_hard"; + /// What [`claim_and_create`] settled. pub(crate) enum Claimed { /// The seat and the row committed together. @@ -220,6 +229,130 @@ pub(crate) async fn claim_and_create( .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) } +/// What [`claim_two_when_and_create`] settled. +pub(crate) enum ClaimedTwo { + /// Both seats and the row committed together. + Made(T), + /// The *resettable* counter (`fields[0]`) is full — nothing was written, + /// and whatever empties it lets the caller through again. + FullSoft, + /// The *lifetime* counter (`fields[1]`) is full, the guard failed, or the + /// parent row is gone — nothing was written. The caller re-reads the parent + /// to tell those apart, and only to pick the message: both are refusals the + /// caller cannot retry into a success. + FullHard, +} + +/// Take a slot on *two* of `parent`'s counters, while `guard` holds, and write +/// the child that fills them — one transaction, one verdict. +/// +/// Two [`claim_when`] calls cannot promise this. A parent whose children are +/// counted twice — once against a resettable working set, once against a +/// lifetime budget — has the two counters describing the same rows, so a writer +/// that lands one increment and loses the other leaves them disagreeing +/// forever, and the lifetime cap stops bounding anything. Here either both +/// increments and the row commit, or the transaction aborts having written +/// nothing. +/// +/// The hard cap is claimed *first*, carrying the guard, so a terminal refusal +/// outranks a recoverable one: a parent that has spent its lifetime budget is +/// not helped by being told its resettable counter is also full. +/// +/// There is no `$held` gate — [`claim_and_create`]'s exists because its child +/// carries a deterministic id two writers can both aim at. This one's caller +/// mints a fresh monotonic ULID on a table with no `UNIQUE` index, so no rival +/// can target that id, and its absence is also what keeps the batch retryable: +/// no statement in it can legitimately answer "already exists" (see +/// [`crate::database::transaction_with_retry`]). +/// +/// The two counters are named one by one rather than passed as a pair of +/// arrays: which slot is the resettable one and which is terminal decides +/// whether a refusal is phrased "clear it and carry on" or "this is over", and +/// two `[i64; 2]` positions swapped by mistake compile, pass every test — both +/// slots are the same type — and misreport that forever. The names are the +/// guard against it. +/// +/// The fields and `guard` are always in-crate constants, never user input. +pub(crate) async fn claim_two_when_and_create( + parent: &RecordId, + soft_field: &str, + soft_cap: i64, + hard_field: &str, + hard_cap: i64, + guard: &str, + id: &RecordId, + content: &T, + db: &Database, +) -> Result, AppError> { + // Parenthesized `??` throughout: `n ?? 0 < $cap` parses as `n ?? (0 < $cap)`, + // which is truthy for every row and would claim past the cap. + let sql = format!( + "BEGIN TRANSACTION; + LET $lifetime = (UPDATE $parent SET {hard_field} = ({hard_field} ?? 0) + 1 \ + WHERE ({hard_field} ?? 0) < $hard AND ({guard}) RETURN VALUE id); + IF array::len($lifetime) = 0 {{ THROW '{HARD_FULL_MARK}' }}; + LET $seat = (UPDATE $parent SET {soft_field} = ({soft_field} ?? 0) + 1 \ + WHERE ({soft_field} ?? 0) < $soft RETURN VALUE id); + IF array::len($seat) = 0 {{ THROW '{SOFT_FULL_MARK}' }}; + CREATE $id CONTENT $row; + COMMIT TRANSACTION;" + ); + let _guard = CLAIM_LOCK.lock().await; + let mut last = None; + for attempt in 0..CAP_WRITE_TRIES { + backoff(attempt).await; + let attempted = db + .query(sql.as_str()) + .bind(("parent", parent.clone())) + .bind(("soft", soft_cap)) + .bind(("hard", hard_cap)) + .bind(("id", id.clone())) + .bind(("row", content.clone())) + .await; + let mut result = match attempted { + Ok(result) => result, + Err(err) if lost_the_race(&err) => { + last = Some(err); + continue; + } + Err(err) => return Err(err.into()), + }; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the failing slot says why. The two markers are read + // before the conflict check, because a `THROW` is a decision. + let mut errors = result.take_errors(); + if errors + .values() + .any(|error| error.to_string().contains(HARD_FULL_MARK)) + { + return Ok(ClaimedTwo::FullHard); + } + if errors + .values() + .any(|error| error.to_string().contains(SOFT_FULL_MARK)) + { + return Ok(ClaimedTwo::FullSoft); + } + if errors.values().any(lost_the_race) { + last = errors.drain().map(|(_, error)| error).find(lost_the_race); + continue; + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5. + return result + .take::>(5)? + .into_iter() + .next() + .map(ClaimedTwo::Made) + .ok_or_else(|| AppError::Internal("cap claim wrote no row".into())); + } + Err(last + .map(AppError::from) + .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) +} + /// Move `parent` to its next revision. A revision column is not a cap: it is /// what a reader pins a value it took off the parent to, so that a write which /// invalidates that value (a menu's price) can refuse the claim carrying the old @@ -341,3 +474,144 @@ async fn write( .map(AppError::from) .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::constant::{ + BOARD_EPOCH_STROKE_COUNT_FIELD, BOARD_OPEN_GUARD, BOARD_TOTAL_STROKE_COUNT_FIELD, + }; + + #[derive(Debug, Clone, SurrealValue)] + struct Stroke { + board: RecordId, + author: RecordId, + kind: String, + epoch: i64, + created_at: i64, + } + + /// The pair of counters, re-read out of the store — never off a return + /// value, which the in-memory engine forges wins on (see `CLAIM_LOCK`). + async fn stored(db: &Database) -> (i64, i64) { + let mut result = db + .query("SELECT VALUE [epoch_stroke_count ?? 0, total_stroke_count ?? 0] FROM board:b") + .await + .unwrap() + .check() + .unwrap(); + let rows: Vec> = result.take(0).unwrap(); + (rows[0][0], rows[0][1]) + } + + async fn strokes(db: &Database) -> usize { + let mut result = db + .query("SELECT VALUE id FROM board_stroke") + .await + .unwrap() + .check() + .unwrap(); + result.take::>(0).unwrap().len() + } + + async fn a_board(epoch: i64, total: i64, locked: bool) -> Database { + let db = crate::database::init_mem().await.unwrap(); + db.query( + "CREATE user:u SET username = 'u', password_hash = 'x'; + CREATE board:b SET creator = user:u, title = 't', participants = [user:u], + locked = $locked, epoch = 0, epoch_stroke_count = $epoch, + total_stroke_count = $total, created_at = 1;", + ) + .bind(("locked", locked)) + .bind(("epoch", epoch)) + .bind(("total", total)) + .await + .unwrap() + .check() + .unwrap(); + db + } + + fn a_stroke() -> Stroke { + Stroke { + board: RecordId::new("board", "b"), + author: RecordId::new("user", "u"), + kind: "stroke".into(), + epoch: 0, + created_at: 2, + } + } + + async fn claim(db: &Database, caps: [i64; 2], key: &str) -> ClaimedTwo { + claim_two_when_and_create( + &RecordId::new("board", "b"), + BOARD_EPOCH_STROKE_COUNT_FIELD, + caps[0], + BOARD_TOTAL_STROKE_COUNT_FIELD, + caps[1], + BOARD_OPEN_GUARD, + &RecordId::new("board_stroke", key), + &a_stroke(), + db, + ) + .await + .unwrap() + } + + #[tokio::test] + async fn both_counters_move_together_or_not_at_all() { + let db = a_board(0, 0, false).await; + assert!(matches!( + claim(&db, [2, 2], "s1").await, + ClaimedTwo::Made(_) + )); + assert_eq!(stored(&db).await, (1, 1)); + assert_eq!(strokes(&db).await, 1); + } + + /// One cap refuses; the *other* counter must not have advanced, asserted by + /// re-reading the row. A drift here would let the lifetime cap be passed. + #[tokio::test] + async fn a_refused_claim_advances_neither_counter() { + // Soft (epoch) full, hard (lifetime) with room to spare. + let db = a_board(5, 5, false).await; + assert!(matches!( + claim(&db, [5, 99], "s1").await, + ClaimedTwo::FullSoft + )); + assert_eq!(stored(&db).await, (5, 5)); + assert_eq!(strokes(&db).await, 0); + + // Hard full, soft with room to spare. + let db = a_board(5, 5, false).await; + assert!(matches!( + claim(&db, [99, 5], "s1").await, + ClaimedTwo::FullHard + )); + assert_eq!(stored(&db).await, (5, 5)); + assert_eq!(strokes(&db).await, 0); + } + + /// The two `THROW` markers must reach the caller as *different* answers: + /// one board is recoverable by a clear, the other is read-only for good. + #[tokio::test] + async fn the_two_caps_refuse_distinguishably() { + let db = a_board(5, 5, false).await; + let soft = claim(&db, [5, 99], "s1").await; + let hard = claim(&db, [99, 5], "s2").await; + assert!(matches!(soft, ClaimedTwo::FullSoft)); + assert!(matches!(hard, ClaimedTwo::FullHard)); + assert_eq!(stored(&db).await, (5, 5)); + } + + #[tokio::test] + async fn the_guard_refuses_a_locked_board() { + let db = a_board(0, 0, true).await; + assert!(matches!( + claim(&db, [9, 9], "s1").await, + ClaimedTwo::FullHard + )); + assert_eq!(stored(&db).await, (0, 0)); + assert_eq!(strokes(&db).await, 0); + } +} diff --git a/src/domain/mod.rs b/src/domain/mod.rs index a9f5254..d351f7d 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -8,6 +8,8 @@ pub mod appointment_slot; pub mod attendance; pub mod bank_question; pub mod bank_question_image; +pub mod board; +pub mod board_stroke; pub mod cap; pub mod chatbot_message; pub mod chatbot_thread; diff --git a/src/lib.rs b/src/lib.rs index 15fb48e..b3e5280 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -63,6 +63,7 @@ use crate::state::AppState; (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Also the food program: the meal slots menus are published for — each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) — the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` — one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. Read: any authenticated user; edit: manager+"), (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"), (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course — whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files — any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored — the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks); a linked parent reads a student's homework report — statuses, late flags, marks — but never the submitted files"), + (name = "boards", description = "Collaborative whiteboards. Anyone opens a board (`POST /boards`) with a title and an ad-hoc invite list of user ids — no course, session or appointment is involved — and every participant draws on it; the creator alone clears, locks, closes or deletes it. A caller who is not on a board gets a `404` for it on every route, existence included, while a participant who is not the creator gets a `403` on those four commands (they are already rendering the board, so hiding it from them would be a lie their client cannot act on). Strokes are **append-only and a clear deletes nothing**: it bumps the board's `epoch`, so the live canvas empties while every mark ever drawn stays stored — `GET /boards/{id}/strokes` is the current epoch (what a client draws to catch up), `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers, each carrying the epoch it closed, that epoch's final stroke count, who cleared and when (the markers *are* the index, so the open epoch is deliberately absent from it). Two growth caps, both published at `GET /limits`: `max_epoch_strokes` bounds the *live* canvas and is recoverable (clear it and drawing resumes, losing nothing), while `max_board_strokes` bounds the board's *lifetime* storage and stamps `closed_at` on the way past — a closed board is permanently read-only and fully readable, never deleted, and there is no reopen. `POST /boards/{id}/close` is the manual form of that, and idempotent. `DELETE /boards/{id}` is the one operation here that really destroys marks — it takes the whole stroke log with it and frees one of the creator's `max_boards_per_creator` seats. `PATCH /boards/{id}` re-titles (any participant) or changes the roster and the lock (creator only). Not in this spec (WebSocket): the live board room, where the drawing itself happens"), (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. A term still linked by any course cannot be deleted (409) — unlink those courses first. Read: any authenticated user; edit: manager+"), ), )] @@ -116,6 +117,7 @@ pub fn build_router(state: AppState) -> Router { .nest("/subjects", web::subjects::routes()) .nest("/homework", web::homework::routes()) .nest("/terms", web::terms::routes()) + .nest("/boards", web::boards::routes()) .split_for_parts(); // Catch-all per-IP limit over every route (Swagger included). Kept inside diff --git a/src/main.rs b/src/main.rs index 48d3a43..88e1145 100644 --- a/src/main.rs +++ b/src/main.rs @@ -35,6 +35,7 @@ async fn main() -> anyhow::Result<()> { rate_limit: cfg.rate_limit.clone(), chatbot_limit: UserRateLimiter::per_user_minute(cfg.chatbot_per_minute), exam_presence: Default::default(), + board_hub: Default::default(), db_up, ai, }); diff --git a/src/migration_sql.rs b/src/migration_sql.rs index 1a7a54a..2cce3a1 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -59,6 +59,7 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS language ON user TYPE option; DEFINE FIELD IF NOT EXISTS palette_color ON user TYPE option; DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option; + DEFINE FIELD IF NOT EXISTS board_count ON user TYPE option; DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; DEFINE TABLE IF NOT EXISTS session SCHEMAFULL; @@ -94,6 +95,50 @@ pub const MIGRATION: &str = " DEFINE INDEX IF NOT EXISTS message_sender ON message FIELDS sender; DEFINE INDEX IF NOT EXISTS message_recipient ON message FIELDS recipient; + -- Collaborative whiteboard (2026-07-31): one `board` is a room, one + -- `board_stroke` is one append-only mark. A clear NEVER deletes — it bumps + -- `epoch`, so the canvas empties while the whole history stays replayable. + -- `locked` is a plain bool, not an option: the open-board guard asks for + -- `locked = false`, which a NONE would never match. `locked_by`/`locked_at`/ + -- `closed_at` are three top-level option columns rather than one nested + -- object, because SurrealDB 3 drops an object key valued NONE. + DEFINE TABLE IF NOT EXISTS board SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS creator ON board TYPE record; + DEFINE FIELD IF NOT EXISTS title ON board TYPE string; + DEFINE FIELD IF NOT EXISTS participants ON board TYPE array>; + DEFINE FIELD IF NOT EXISTS locked ON board TYPE bool DEFAULT false; + DEFINE FIELD IF NOT EXISTS locked_by ON board TYPE option>; + DEFINE FIELD IF NOT EXISTS locked_at ON board TYPE option; + DEFINE FIELD IF NOT EXISTS epoch ON board TYPE int DEFAULT 0; + -- Resets to 0 on every clear (recoverable); never resets (stamps closed_at). + DEFINE FIELD IF NOT EXISTS epoch_stroke_count ON board TYPE option; + DEFINE FIELD IF NOT EXISTS total_stroke_count ON board TYPE option; + -- Stamped once, when the lifetime cap is hit: permanently read-only. + DEFINE FIELD IF NOT EXISTS closed_at ON board TYPE option; + DEFINE FIELD IF NOT EXISTS created_at ON board TYPE int; + DEFINE INDEX IF NOT EXISTS board_creator ON board FIELDS creator; + -- Listing a user's boards asks `creator = $u OR participants CONTAINS $u`; + -- without this the CONTAINS half is a full scan. SurrealDB indexes an + -- array field per element, so it covers the membership test directly. + DEFINE INDEX IF NOT EXISTS board_participants ON board FIELDS participants; + + DEFINE TABLE IF NOT EXISTS board_stroke SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS board ON board_stroke TYPE record; + DEFINE FIELD IF NOT EXISTS author ON board_stroke TYPE record; + -- 'stroke' or 'clear'; `payload` is the opaque blob, absent on a clear + -- marker, and `count` is populated only on a clear marker — the final + -- stroke count of the epoch that marker closed. + DEFINE FIELD IF NOT EXISTS kind ON board_stroke TYPE string; + DEFINE FIELD IF NOT EXISTS payload ON board_stroke TYPE option; + DEFINE FIELD IF NOT EXISTS count ON board_stroke TYPE option; + DEFINE FIELD IF NOT EXISTS epoch ON board_stroke TYPE int; + DEFINE FIELD IF NOT EXISTS created_at ON board_stroke TYPE int; + -- Keeps a socket's join-replay scoped to the current epoch instead of + -- scanning the board's whole history. + DEFINE INDEX IF NOT EXISTS board_stroke_board_epoch ON board_stroke FIELDS board, epoch; + -- The clear markers ARE the epoch index, so listing them is a hot read. + DEFINE INDEX IF NOT EXISTS board_stroke_board_kind ON board_stroke FIELDS board, kind; + DEFINE TABLE IF NOT EXISTS note_file SCHEMAFULL; DEFINE FIELD IF NOT EXISTS note ON note_file TYPE record; DEFINE FIELD IF NOT EXISTS name ON note_file TYPE string; diff --git a/src/state.rs b/src/state.rs index 5850ca8..d23611e 100644 --- a/src/state.rs +++ b/src/state.rs @@ -3,6 +3,8 @@ use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; +use tokio::sync::broadcast; + use crate::ai::AiBridge; use crate::database::Database; use crate::rate_limit::{RateLimitConfig, UserRateLimiter}; @@ -28,6 +30,8 @@ pub struct AppState { pub chatbot_limit: UserRateLimiter, /// Who is inside which exam room right now (see [`ExamPresence`]). pub exam_presence: ExamPresence, + /// Live stroke fan-out for the shared whiteboards (see [`BoardHub`]). + pub board_hub: BoardHub, /// Whether the database socket answered its last ping (see [`DbHealth`]). pub db_up: DbHealth, /// The QUIC bridge to the AI services, when one is configured @@ -116,10 +120,87 @@ impl ExamPresence { } } +/// One broadcast channel per live whiteboard, keyed by the board's record key, +/// so a stroke saved by one socket reaches every *other* socket in that board. +/// Nothing else in this codebase fans out — an exam room only ever replies to +/// the socket that spoke — so this is the only multi-subscriber push we have. +/// +/// The socket count exists to drop the entry when the last socket leaves; +/// without it the map would keep one channel per board ever opened, forever. +/// +/// The inner mutex only guards the map (never held across an await — keep it +/// that way): every method locks, mutates or clones out, and drops the guard +/// before the caller can await anything. +#[derive(Clone, Default)] +pub struct BoardHub(Arc, usize)>>>); + +impl BoardHub { + /// Count one socket into `board` and hand back its stream of other + /// people's frames, creating the channel on the first join. + pub fn subscribe(&self, board: &str) -> broadcast::Receiver { + let mut boards = self.0.lock().expect("board hub lock"); + let room = boards + .entry(board.to_string()) + .or_insert_with(|| (broadcast::channel(crate::constant::BOARD_HUB_CAPACITY).0, 0)); + room.1 += 1; + room.0.subscribe() + } + + /// Push `frame` to every socket currently subscribed to `board`. A send + /// with no receivers left is the normal empty-room case, not a failure. + pub fn publish(&self, board: &str, frame: String) { + let sender = { + let boards = self.0.lock().expect("board hub lock"); + boards.get(board).map(|room| room.0.clone()) + }; + if let Some(sender) = sender { + let _ = sender.send(frame); + } + } + + /// Count one socket out of `board`; the last one out drops the channel. + pub fn leave(&self, board: &str) { + let mut boards = self.0.lock().expect("board hub lock"); + match boards.get_mut(board) { + Some(room) if room.1 > 1 => room.1 -= 1, + // Last one out, or an unbalanced leave — either way the room is + // empty, and a stale entry would leak for the process's lifetime. + _ => { + boards.remove(board); + } + } + } +} + #[cfg(test)] mod tests { use super::*; + #[tokio::test] + async fn every_subscriber_gets_the_stroke_and_the_room_is_reclaimed() { + let hub = BoardHub::default(); + let mut alice = hub.subscribe("board-a"); + let mut bob = hub.subscribe("board-a"); + hub.publish("board-a", "stroke".to_string()); + assert_eq!(alice.recv().await.expect("alice"), "stroke"); + assert_eq!(bob.recv().await.expect("bob"), "stroke"); + + // Boards are independent, and publishing into an empty one is a no-op. + hub.publish("board-b", "nobody home".to_string()); + assert!(!hub.0.lock().unwrap().contains_key("board-b")); + + hub.leave("board-a"); + assert!( + hub.0.lock().unwrap().contains_key("board-a"), + "one socket of two out keeps the room" + ); + hub.leave("board-a"); + assert!( + hub.0.lock().unwrap().is_empty(), + "the last socket out must drop the entry, or the map leaks" + ); + } + #[tokio::test] async fn only_the_last_socket_out_is_a_real_exit() { let presence = ExamPresence::default(); diff --git a/src/web/boards.rs b/src/web/boards.rs new file mode 100644 index 0000000..8de0e18 --- /dev/null +++ b/src/web/boards.rs @@ -0,0 +1,640 @@ +//! The whiteboard's HTTP surface: open a board, read its roster, its live +//! canvas and its whole history, and run the creator's four commands (clear, +//! lock, close, delete). Live drawing itself rides the board-room WebSocket +//! next door; everything here is the REST half it sits beside. +//! +//! The permission model is two predicates and nothing else +//! ([`Board::is_participant`], [`Board::is_creator`]), applied in one order on +//! every route: a non-participant gets a **404** even for a board that plainly +//! exists (a 403 would confirm it — see the rationale at `src/lib.rs`), while a +//! participant who is not the creator gets a **403** on the four commands. They +//! are already rendering the board and its strokes, so hiding it from them +//! there would be a lie their client cannot act on (same two-tier line as +//! [`super::homework`]). +//! +//! Every mutation a live room must notice ends in a `board_hub` publish, and +//! one of them is a permission fix rather than a nicety: a participant dropped +//! mid-session keeps drawing over an already-open socket until the room hears +//! about it, so a roster change *must* fan out. + +use axum::Json; +use axum::extract::{Path, Query, State}; +use axum::http::StatusCode; +use serde::{Deserialize, Serialize}; +use serde_json::json; +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, BoardId, BoardTitle}; +use crate::domain::board_stroke::BoardStroke; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::state::AppState; + +use super::{CurrentUser, Page, PageParams, paginate, set_or_clear}; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(create_board, list_boards)) + .routes(routes!(get_board, update_board, delete_board)) + .routes(routes!(list_strokes)) + .routes(routes!(list_history)) + .routes(routes!(list_epochs)) + .routes(routes!(clear_board)) + .routes(routes!(close_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. +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 !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 lookups (the domain caps too, +/// but only after this loop would have run one read per id), and an unknown id +/// is a 400 rather than a silently dropped invitation. +/// +/// The creator is a participant by construction, so they are neither injected +/// into the list nor rejected from it. +async fn resolve_participants( + ids: Option>, + 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 mut users = Vec::with_capacity(ids.len()); + for id in ids { + let user = UserId::from_key(&id); + if User::read(&user, db).await?.is_none() { + return Err(AppError::Validation(ValidationError::Invalid { + field: "participants", + reason: "every participant must be an existing user", + })); + } + 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, board: &BoardId, frame: serde_json::Value) { + st.board_hub.publish(board.key(), frame.to_string()); +} + +#[derive(Serialize, ToSchema)] +struct BoardResponse { + id: String, + title: String, + /// The creator: draws, and is the only one who may clear, lock, close or + /// delete. Always a participant without appearing in `participants`. + creator: String, + /// The invited user ids. Everyone here draws. + participants: Vec, + /// Drawing is paused while `true`; the creator toggles it. + locked: bool, + locked_by: Option, + /// UTC unix-milliseconds, `null` while unlocked. + locked_at: Option, + /// The live canvas' generation. A clear bumps it; strokes from earlier + /// epochs stay stored and replayable through `/history`. + epoch: i64, + /// Stamped when the board was closed — by its creator or by the lifetime + /// stroke cap. A closed board is permanently read-only, never deleted. + closed_at: Option, + created_at: i64, +} + +impl BoardResponse { + fn new(board: &Board) -> Self { + Self { + id: board.get_id().key().to_string(), + title: board.get_title().as_str().to_string(), + creator: board.get_creator().key().to_string(), + participants: board + .get_participants() + .iter() + .map(|user| user.key().to_string()) + .collect(), + locked: board.is_locked(), + locked_by: board.get_locked_by().map(|user| user.key().to_string()), + locked_at: board.get_locked_at().map(|at| at.as_millis()), + epoch: board.get_epoch(), + closed_at: board.get_closed_at().map(|at| at.as_millis()), + created_at: board.get_created_at().as_millis(), + } + } +} + +/// One row of the append-only stroke log. Both kinds ride this shape: a +/// `stroke` carries `payload`, a `clear` marker carries `count` — the final +/// stroke count of the epoch it closed — and never the other way round. +#[derive(Serialize, ToSchema)] +struct StrokeResponse { + id: String, + author: String, + /// `stroke` or `clear`. + kind: String, + /// The client's serialized mark. `null` on a `clear` marker. + payload: Option, + /// The closed epoch's final stroke count. Present only on a `clear`. + count: Option, + epoch: i64, + created_at: i64, +} + +impl StrokeResponse { + fn new(stroke: &BoardStroke) -> Self { + Self { + id: stroke.get_id().key().to_string(), + author: stroke.get_author().key().to_string(), + kind: stroke.get_kind().to_string(), + payload: stroke.get_payload().map(str::to_string), + count: stroke.get_count(), + epoch: stroke.get_epoch(), + created_at: stroke.get_created_at().as_millis(), + } + } +} + +#[derive(Deserialize, ToSchema)] +struct CreateBoard { + #[schema(max_length = 200)] + title: String, + /// Who may draw, besides the creator. Omit or send an empty list to open a + /// board alone and invite later. + #[schema(max_items = 50)] + participant_ids: Option>, +} + +/// Open a whiteboard. The caller becomes its creator — the only one who may +/// clear, lock, close or delete it — and everyone named in `participant_ids` +/// may draw on it. `409` once the caller holds `max_boards_per_creator` boards +/// (`GET /limits`); delete one to free a seat. +#[utoipa::path( + post, + path = "/", + tag = "boards", + security(("session_cookie" = [])), + request_body = CreateBoard, + responses( + (status = 201, description = "The new board", body = BoardResponse), + (status = 400, description = "Invalid title, or a participant list that is too long or names an unknown user", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 409, description = "The caller already holds the maximum number of boards", body = ErrorResponse), + ), +)] +async fn create_board( + State(st): State, + CurrentUser(user): CurrentUser, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let title = BoardTitle::try_new(&req.title)?; + let participants = resolve_participants(req.participant_ids, &st.db).await?; + let board = Board::create(user.get_id(), title, participants, &st.db).await?; + Ok((StatusCode::CREATED, Json(BoardResponse::new(&board)))) +} + +/// Every board the caller may open — the ones they created and the ones they +/// were invited to — newest first. Paged via `?limit=&offset=` (omit `limit` +/// for all of them). +#[utoipa::path( + get, + path = "/", + tag = "boards", + security(("session_cookie" = [])), + params(PageParams), + responses( + (status = 200, description = "A page of the caller's boards", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn list_boards( + State(st): State, + CurrentUser(user): CurrentUser, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let (boards, total) = Board::list_for_user(user.get_id(), limit, offset, &st.db).await?; + let items = boards.iter().map(BoardResponse::new).collect(); + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// Fetch one board. A caller who is neither its creator nor one of its +/// participants gets a `404`, not a `403` — an outsider must not learn that a +/// board exists. +#[utoipa::path( + get, + path = "/{id}", + tag = "boards", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Board id")), + responses( + (status = 200, description = "The board", body = BoardResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse), + ), +)] +async fn get_board( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let board = board_for(&id, &user, &st.db).await?; + Ok(Json(BoardResponse::new(&board))) +} + +/// The live canvas: the current epoch's strokes, oldest first, paged via +/// `?limit=&offset=`. This is what a client draws to catch up — earlier epochs +/// are still stored, and read through `/history`. +#[utoipa::path( + get, + path = "/{id}/strokes", + tag = "boards", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Board id"), PageParams), + responses( + (status = 200, description = "A page of the current epoch's strokes", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse), + ), +)] +async fn list_strokes( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let board = board_for(&id, &user, &st.db).await?; + // The current epoch has no `clear` marker yet — a marker is written with + // the epoch it *closed* — so scoping history to it is exactly the live + // canvas, and needs no second query shape. + let (strokes, total) = BoardStroke::history( + board.get_id(), + Some(board.get_epoch()), + limit, + offset, + &st.db, + ) + .await?; + let items = strokes.iter().map(StrokeResponse::new).collect(); + Ok(Json(Page::new(items, total, limit, offset))) +} + +#[derive(Deserialize, utoipa::IntoParams)] +struct HistoryParams { + /// One epoch's rows only. Omit for the board's whole life, oldest first. + epoch: Option, +} + +/// The whole stroke log, oldest first — every epoch the board ever had, or the +/// single `?epoch=` named. A clear deletes nothing, so this replays the entire +/// session; the `clear` markers in the stream are where one epoch ended. +/// Paged via `?limit=&offset=`. +#[utoipa::path( + get, + path = "/{id}/history", + tag = "boards", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Board id"), HistoryParams, PageParams), + responses( + (status = 200, description = "A page of the stroke log", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse), + ), +)] +async fn list_history( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, + Query(scope): Query, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let board = board_for(&id, &user, &st.db).await?; + let (strokes, total) = + BoardStroke::history(board.get_id(), scope.epoch, limit, offset, &st.db).await?; + let items = strokes.iter().map(StrokeResponse::new).collect(); + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// The epoch index: every `clear` marker this board has, oldest first. Each one +/// carries the epoch it closed (`epoch`), that epoch's final stroke count +/// (`count`), who cleared and when — which is all a client needs to offer +/// "replay session 3" without scanning the log. The markers *are* the index, so +/// the current (unclosed) epoch is deliberately absent. Paged via +/// `?limit=&offset=`. +#[utoipa::path( + get, + path = "/{id}/epochs", + tag = "boards", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Board id"), PageParams), + responses( + (status = 200, description = "A page of the board's clear markers", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse), + ), +)] +async fn list_epochs( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, + 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?; + // 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) + .iter() + .map(StrokeResponse::new) + .collect(); + Ok(Json(Page::new(items, markers.len() as i64, limit, offset))) +} + +#[derive(Deserialize, ToSchema)] +struct UpdateBoard { + /// Re-title. Any participant may. Omit to keep. + #[schema(max_length = 200)] + title: Option, + /// Replace the invite list — **creator only**. Omit to keep; send `null` + /// (or an empty list) to leave the creator alone on the board. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option>, max_items = 50)] + participants: Option>>, + /// Pause (`true`) or resume (`false`) drawing — **creator only**. Omit to + /// keep. + locked: Option, +} + +/// Edit a board. Re-titling is open to every participant; changing the invite +/// list or the lock is the creator's alone (`403` for anyone else on the +/// board). Omitted fields keep their value. +/// +/// A roster change and a lock change are both fanned out to the live room at +/// once — a participant removed here would otherwise keep drawing over the +/// socket they already hold. +#[utoipa::path( + patch, + path = "/{id}", + tag = "boards", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Board id")), + request_body = UpdateBoard, + responses( + (status = 200, description = "The updated board", body = BoardResponse), + (status = 400, description = "Invalid title, or a participant list that is too long or names an unknown user", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Only the creator may change the participants or the lock", body = ErrorResponse), + (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse), + ), +)] +async fn update_board( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let mut board = board_for(&id, &user, &st.db).await?; + if req.participants.is_some() || req.locked.is_some() { + ensure_creator(&board, &user)?; + } + + if let Some(title) = req.title.as_deref() { + board = board.set_title(BoardTitle::try_new(title)?, &st.db).await?; + } + if let Some(participants) = req.participants { + let participants = resolve_participants(participants, &st.db).await?; + board = board.set_participants(participants, &st.db).await?; + fan_out( + &st, + board.get_id(), + json!({ + "type": "participants", + "creator": board.get_creator().key(), + "participants": board + .get_participants() + .iter() + .map(|user| user.key()) + .collect::>(), + }), + ); + } + if let Some(locked) = req.locked { + board = board.set_locked(locked, user.get_id(), &st.db).await?; + fan_out( + &st, + board.get_id(), + json!({"type": "locked", "locked": locked, "by": user.get_id().key()}), + ); + } + Ok(Json(BoardResponse::new(&board))) +} + +/// Empty the canvas — creator only. **Nothing is deleted**: the board's epoch +/// is bumped and a `clear` marker is appended carrying the closed epoch's final +/// stroke count, so the live canvas is blank while every mark ever drawn stays +/// readable through `/history`. Also resets the live-canvas cap, which is how a +/// board that answered "clear it to keep drawing" is recovered. `409` on a +/// closed board. +#[utoipa::path( + post, + path = "/{id}/clear", + tag = "boards", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Board id")), + responses( + (status = 201, description = "The clear marker that closed the epoch", body = StrokeResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Only the creator may clear the board", body = ErrorResponse), + (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse), + (status = 409, description = "The board is closed", body = ErrorResponse), + ), +)] +async fn clear_board( + State(st): State, + 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?; + // The marker carries the epoch it *closed*; the room's new canvas is the + // next one. + fan_out( + &st, + board.get_id(), + json!({ + "type": "cleared", + "epoch": marker.get_epoch() + 1, + "by": user.get_id().key(), + }), + ); + Ok((StatusCode::CREATED, Json(StrokeResponse::new(&marker)))) +} + +/// Retire the board — creator only. It becomes permanently read-only: no more +/// strokes and no more clears, while every stroke and every epoch stays +/// readable. Idempotent: closing an already-closed board returns it with its +/// original `closed_at` rather than re-stamping. There is no reopen — a closed +/// board is finished, and a new one is cheap. +#[utoipa::path( + post, + path = "/{id}/close", + tag = "boards", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Board id")), + responses( + (status = 200, description = "The closed board", body = BoardResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Only the creator may close the board", body = ErrorResponse), + (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse), + ), +)] +async fn close_board( + State(st): State, + 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?; + fan_out( + &st, + board.get_id(), + json!({ + "type": "closed", + "closed_at": board.get_closed_at().map(|at| at.as_millis()), + }), + ); + Ok(Json(BoardResponse::new(&board))) +} + +/// Delete the board and its whole stroke history — creator only, and the one +/// operation in this system that really destroys marks (a clear never does). +/// It also frees the creator's board seat. Use `/close` to retire a board while +/// keeping it readable. +#[utoipa::path( + delete, + path = "/{id}", + tag = "boards", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Board id")), + responses( + (status = 204, description = "Deleted, with every stroke it held"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Only the creator may delete the board", body = ErrorResponse), + (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse), + ), +)] +async fn delete_board( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result { + let board = board_for(&id, &user, &st.db).await?; + ensure_creator(&board, &user)?; + let id = board.get_id().clone(); + board.delete(&st.db).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, &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| { + User::read(&UserId::from_key(key), &db) + .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/limits.rs b/src/web/limits.rs index a9d9324..80ee3dd 100644 --- a/src/web/limits.rs +++ b/src/web/limits.rs @@ -267,6 +267,36 @@ struct ChatbotLimits { default_max_threads: i64, } +/// A collaborative whiteboard: its title, its roster, and the two growth caps +/// that decide when a canvas must be cleared and when a board is finished. +#[derive(Serialize, ToSchema)] +struct BoardLimits { + max_title_len: usize, + /// People the creator may name onto one board. Every participant draws, so + /// this also bounds a room's writer count. + max_participants: usize, + /// Ceiling on one stroke's serialized payload, bytes. + max_stroke_payload_len: usize, + /// The *live* canvas cap: strokes since the last clear. Hitting it is + /// recoverable — the creator clears, the canvas empties, the history is + /// kept, and drawing resumes. + max_epoch_strokes: i64, + /// The *lifetime* storage cap, which never resets because a clear keeps its + /// history. Hitting it makes the board permanently read-only: it stays + /// fully readable and replayable, and a new board must be opened. + max_board_strokes: i64, + /// Boards one creating user may hold. Deleting a board frees a seat. + max_boards_per_creator: i64, + /// The accepted stroke kinds. `clear` is a marker that ends an epoch, not a + /// deletion. + #[schema(example = json!(["stroke", "clear"]))] + stroke_kinds: Vec<&'static str>, + /// Cadence of the board-room WebSocket's keepalive ticks, seconds. + ws_tick_secs: u64, + /// Ceiling on a `board_id` sent over the board-room WebSocket. + ws_max_board_id_len: usize, +} + /// Bounds on the school-editable lists in `PATCH /settings`. #[derive(Serialize, ToSchema)] struct SettingsLimits { @@ -333,6 +363,7 @@ struct LimitsResponse { meal: MealLimits, payment: PaymentLimits, chatbot: ChatbotLimits, + board: BoardLimits, settings: SettingsLimits, request: RequestLimits, rate: RateLimits, @@ -467,6 +498,17 @@ impl LimitsResponse { max_max_threads: MAX_MAX_CHATBOT_THREADS, default_max_threads: DEFAULT_MAX_CHATBOT_THREADS, }, + board: BoardLimits { + max_title_len: MAX_BOARD_TITLE_LEN, + max_participants: MAX_BOARD_PARTICIPANTS, + max_stroke_payload_len: MAX_STROKE_PAYLOAD_LEN, + max_epoch_strokes: MAX_EPOCH_STROKES, + max_board_strokes: MAX_BOARD_STROKES, + max_boards_per_creator: MAX_BOARDS_PER_CREATOR, + stroke_kinds: BOARD_STROKE_KINDS.to_vec(), + ws_tick_secs: BOARD_WS_TICK_SECS, + ws_max_board_id_len: MAX_BOARD_ID_LEN, + }, settings: SettingsLimits { max_list_len: MAX_SETTINGS_LIST_LEN, max_item_len: MAX_SETTINGS_ITEM_LEN, diff --git a/src/web/mod.rs b/src/web/mod.rs index e625cca..3a96bed 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -8,6 +8,7 @@ pub mod appointments; pub mod attendance; pub mod auth; pub mod bank_questions; +pub mod boards; pub mod chatbot; pub mod courses; pub mod etag; diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index 4512c03..fab67e7 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -807,6 +807,7 @@ async fn fetch_certificate(ai: Option) -> (axum::http::StatusCode, Val rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), chatbot_limit: Default::default(), exam_presence: Default::default(), + board_hub: Default::default(), db_up: Default::default(), ai, }); @@ -940,6 +941,7 @@ async fn chat_app(bridge: &AiBridge) -> (Router, Database) { rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), chatbot_limit: Default::default(), exam_presence: Default::default(), + board_hub: Default::default(), db_up: Default::default(), ai: Some(bridge.clone()), }); diff --git a/tests/common/mod.rs b/tests/common/mod.rs index fc13245..d0c45be 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -49,6 +49,7 @@ pub async fn app_and_db() -> (Router, Database) { rate_limit: RateLimitConfig::unlimited(), chatbot_limit: Default::default(), exam_presence: Default::default(), + board_hub: Default::default(), db_up: Default::default(), ai: None, }); diff --git a/tests/e2e.rs b/tests/e2e.rs index 717c8f9..551c00a 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -29,6 +29,7 @@ async fn spawn_server_with_ai(ai: Option) -> (St rate_limit: RateLimitConfig::unlimited(), chatbot_limit: Default::default(), exam_presence: Default::default(), + board_hub: Default::default(), db_up: Default::default(), ai, }); diff --git a/tests/integration.rs b/tests/integration.rs index c65c0e0..10e5af5 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -159,6 +159,7 @@ async fn limits_still_answers_while_the_database_is_down() { rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), chatbot_limit: Default::default(), exam_presence: Default::default(), + board_hub: Default::default(), db_up: db_up.clone(), ai: None, }); @@ -382,6 +383,19 @@ async fn protected_routes_require_session() { ("GET", "/pomodoro/u"), ("GET", "/attendance/me"), ("GET", "/attendance/u"), + ("GET", "/boards"), + ("POST", "/boards"), + ("GET", "/boards/x"), + ("PATCH", "/boards/x"), + ("DELETE", "/boards/x"), + ("GET", "/boards/x/strokes"), + ("GET", "/boards/x/history"), + ("GET", "/boards/x/epochs"), + ("POST", "/boards/x/clear"), + ("POST", "/boards/x/close"), + // The board room authenticates before it upgrades, so a rejection is + // an HTTP status here and not an instant close. + ("GET", "/boards/x/ws"), ] { let res = send(&app, method, uri, None, None).await; assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{method} {uri}"); @@ -6023,6 +6037,7 @@ async fn session_cookie_secure_attribute_follows_config() { rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), chatbot_limit: Default::default(), exam_presence: Default::default(), + board_hub: Default::default(), db_up: Default::default(), ai: None, }); @@ -6062,6 +6077,7 @@ async fn db_down_refuses_before_touching_the_database() { rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), chatbot_limit: Default::default(), exam_presence: Default::default(), + board_hub: Default::default(), db_up: db_up.clone(), ai: None, }); @@ -15856,6 +15872,7 @@ async fn chat_app_limited( rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), chatbot_limit, exam_presence: Default::default(), + board_hub: Default::default(), db_up: Default::default(), ai, }); diff --git a/tests/limits_completeness.rs b/tests/limits_completeness.rs index 77f4b23..ce1ed26 100644 --- a/tests/limits_completeness.rs +++ b/tests/limits_completeness.rs @@ -57,6 +57,22 @@ const EXCLUDED: &[(&str, &str)] = &[ assigned plan freezes in the database; the client sees the freeze as a \ 409, never as a number", ), + ( + "BOARD_OPEN_GUARD", + "SQL fragment: the condition every whiteboard-stroke write carries so a \ + locked or closed board freezes in the database; the client sees the \ + freeze as a 409, never as a number", + ), + ( + "BOARD_REPLAY_CHUNK", + "how the board-room socket batches its join replay; the client reads the \ + strokes, not the batch size", + ), + ( + "BOARD_HUB_CAPACITY", + "depth of one board room's fan-out channel; a lagging socket is dropped \ + and rejoins, which the client handles as a reconnect, not as a number", + ), ( "UPLOAD_BODY_OVERHEAD_BYTES", "multipart headroom over max_file_bytes; the client sizes against \ diff --git a/tests/persistence.rs b/tests/persistence.rs index d674977..e6add9d 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -27,6 +27,7 @@ async fn reboot(db: &Database) -> Router { rate_limit: RateLimitConfig::unlimited(), chatbot_limit: Default::default(), exam_presence: Default::default(), + board_hub: Default::default(), db_up: Default::default(), ai: None, }) diff --git a/tests/rate_limit.rs b/tests/rate_limit.rs index bf6a13d..9884b81 100644 --- a/tests/rate_limit.rs +++ b/tests/rate_limit.rs @@ -26,6 +26,7 @@ async fn app_with(rate_limit: RateLimitConfig) -> Router { rate_limit, chatbot_limit: Default::default(), exam_presence: Default::default(), + board_hub: Default::default(), db_up: Default::default(), ai: None, }) @@ -463,6 +464,7 @@ async fn spawn_server(rate_limit: RateLimitConfig) -> String { rate_limit, chatbot_limit: Default::default(), exam_presence: Default::default(), + board_hub: Default::default(), db_up: Default::default(), ai: None, }); diff --git a/tests/spec_bounds.rs b/tests/spec_bounds.rs index 3c25acd..e24bf59 100644 --- a/tests/spec_bounds.rs +++ b/tests/spec_bounds.rs @@ -32,6 +32,7 @@ async fn spec() -> Value { rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), chatbot_limit: Default::default(), exam_presence: Default::default(), + board_hub: Default::default(), db_up: Default::default(), ai: None, }); @@ -785,6 +786,31 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { "maxLength", MAX_CHATBOT_THREAD_TITLE_LEN as i64, ), + // --- whiteboards --- + ( + "CreateBoard", + "title", + "maxLength", + MAX_BOARD_TITLE_LEN as i64, + ), + ( + "CreateBoard", + "participant_ids", + "maxItems", + MAX_BOARD_PARTICIPANTS as i64, + ), + ( + "UpdateBoard", + "title", + "maxLength", + MAX_BOARD_TITLE_LEN as i64, + ), + ( + "UpdateBoard", + "participants", + "maxItems", + MAX_BOARD_PARTICIPANTS as i64, + ), ] }