forge
Explore
Log in

Don't you dare go Hollow

πŸ–οΈ collaborative whiteboard domain, REST and limits

Browse files at this commit

5dfce557b1038dfa9c11360fabe0d336f7594d68Ahmet Kaan GümüşParent: bb774eb
  • feat
    • πŸ–οΈ collaborative whiteboard domain, REST and limits
Show full message
feat: πŸ–οΈ collaborative whiteboard domain, REST and limits

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.rsmodified+84 -0
@@ -273,6 +273,52 @@ pub const MAX_FEE_PLAN_ASSIGN_STUDENTS: usize = 200;
273 /// UUID or a receipt number comfortably.273 /// UUID or a receipt number comfortably.
274 pub const MAX_PAYMENT_REQUEST_KEY_LEN: usize = 64;274 pub const MAX_PAYMENT_REQUEST_KEY_LEN: usize = 64;
275 275
276+/// Bounds on a whiteboard: its title, and how many people the creator may name
277+/// onto it. Fifty is a class and its teachers, not the school; every
278+/// participant may draw, so this is also what bounds one board's writer count.
279+pub const MAX_BOARD_TITLE_LEN: usize = 200;
280+pub const MAX_BOARD_PARTICIPANTS: usize = 50;
281+
282+/// Ceiling on one stroke's serialized payload. A stroke is a short path β€” a
283+/// handful of points, a colour, a width β€” and it is stored verbatim and fanned
284+/// out to every socket in the room, so it is bounded at the wire rather than at
285+/// the canvas: 4 KiB takes a long freehand curve and still keeps the worst-case
286+/// board (`MAX_BOARD_STROKES` of them) inside a couple hundred megabytes.
287+pub const MAX_STROKE_PAYLOAD_LEN: usize = 4_096;
288+
289+/// The two growth caps, both counted on the board row (see the counter fields
290+/// below). They are different kinds of full on purpose:
291+///
292+/// `MAX_EPOCH_STROKES` caps the *live* canvas β€” the strokes since the last
293+/// clear. Hitting it is recoverable: the creator clears, the epoch counter
294+/// resets to zero and drawing resumes. Nothing is deleted by that clear.
295+///
296+/// `MAX_BOARD_STROKES` caps the board's total *storage*, and never resets,
297+/// because a clear keeps its history for playback. Hitting it stamps
298+/// `closed_at`: the board turns permanently read-only, but stays fully
299+/// readable and replayable β€” a closed board loses no stroke it ever carried.
300+pub const MAX_EPOCH_STROKES: i64 = 5_000;
301+pub const MAX_BOARD_STROKES: i64 = 50_000;
302+
303+/// How many boards one creator may hold. Without it the two caps above cost an
304+/// attacker nothing β€” a full board is answered by opening the next one β€” so
305+/// this is the counter that actually bounds a single account's storage. Kept on
306+/// the user row, the same shape as `CHATBOT_THREAD_COUNT_FIELD`.
307+pub const MAX_BOARDS_PER_CREATOR: i64 = 200;
308+
309+/// The only accepted stroke kinds. `stroke`: a drawn path, carrying its
310+/// payload. `clear`: the marker row that ends an epoch β€” it deletes nothing,
311+/// it is the epoch index, so replaying across it reconstructs the whole
312+/// session.
313+pub const BOARD_STROKE_KINDS: [&str; 2] = ["stroke", "clear"];
314+
315+/// Ceiling on a `board_id` arriving on the board WebSocket, for the same reason
316+/// as [`MAX_QUESTION_ID_LEN`]: the field is a record key β€” a 26-char ULID in
317+/// every real payload β€” and the error frame *echoes* it back, so an unbounded
318+/// id lets a client make its own room reflect a 64 MiB frame at it. Checked
319+/// before any database work.
320+pub const MAX_BOARD_ID_LEN: usize = 64;
321+
276 /// Inclusive bounds for an exam's per-attempt duration, milliseconds322 /// Inclusive bounds for an exam's per-attempt duration, milliseconds
277 /// (1 minute to 24 hours). Required for `async`, optional for `open`.323 /// (1 minute to 24 hours). Required for `async`, optional for `open`.
278 pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000;324 pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000;
@@ -315,6 +361,22 @@ pub const DB_CONNECT_BACKOFF_MAX_SECS: u64 = 5;
315 /// (`GET /exams/{id}/attempt/ws`).361 /// (`GET /exams/{id}/attempt/ws`).
316 pub const EXAM_WS_TICK_SECS: u64 = 2;362 pub const EXAM_WS_TICK_SECS: u64 = 2;
317 363
364+/// Cadence of the keepalive ticks on the whiteboard-room WebSocket. Slower than
365+/// the exam room's, because a board room carries no countdown a client renders
366+/// against β€” the tick only keeps an idle socket from being reaped.
367+pub const BOARD_WS_TICK_SECS: u64 = 15;
368+
369+/// How many strokes one replay message carries when a socket joins. The join
370+/// replays the current epoch, which is `MAX_EPOCH_STROKES` at worst, so it is
371+/// sent in batches rather than as one frame that could reach the WebSocket
372+/// frame limit on a busy board.
373+pub const BOARD_REPLAY_CHUNK: usize = 200;
374+
375+/// Depth of one board room's fan-out channel: how far a slow socket may lag the
376+/// strokes being drawn before it is dropped and has to rejoin (which replays
377+/// the epoch from storage anyway, so nothing is lost by the drop).
378+pub const BOARD_HUB_CAPACITY: usize = 256;
379+
318 /// Ceiling on a `question_id` arriving on the exam-room WebSocket. The field is380 /// Ceiling on a `question_id` arriving on the exam-room WebSocket. The field is
319 /// a record key β€” a 26-char ULID in every real payload β€” not free text, so this381 /// a record key β€” a 26-char ULID in every real payload β€” not free text, so this
320 /// is generous by a factor of two and change. The cap exists because the382 /// 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";
663 pub const FEE_PLAN_TABLE: &str = "fee_plan";725 pub const FEE_PLAN_TABLE: &str = "fee_plan";
664 pub const FEE_PLAN_ASSIGNMENT_TABLE: &str = "fee_plan_assignment";726 pub const FEE_PLAN_ASSIGNMENT_TABLE: &str = "fee_plan_assignment";
665 pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger";727 pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger";
728+pub const BOARD_TABLE: &str = "board";
729+pub const BOARD_STROKE_TABLE: &str = "board_stroke";
666 /// One row per *name* the school's settings offer, keyed by the name itself:730 /// One row per *name* the school's settings offer, keyed by the name itself:
667 /// how many rows still reference it, and whether it has been retired out of the731 /// how many rows still reference it, and whether it has been retired out of the
668 /// list (see the reference counters in [`crate::domain::cap`]).732 /// list (see the reference counters in [`crate::domain::cap`]).
@@ -702,6 +766,20 @@ pub const FEE_PLAN_UNASSIGNED_GUARD: &str = "(assignment_count ?? 0) = 0";
702 pub const NOTE_FILE_COUNT_FIELD: &str = "file_count";766 pub const NOTE_FILE_COUNT_FIELD: &str = "file_count";
703 pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count";767 pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count";
704 pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count";768 pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count";
769+/// How many boards this user created, on the user row β€” the same per-user shape
770+/// as `CHATBOT_THREAD_COUNT_FIELD`, capped at `MAX_BOARDS_PER_CREATOR`. It is
771+/// what closes the "open another board" way around the two board counters
772+/// below; released when a board is deleted.
773+pub const USER_BOARD_COUNT_FIELD: &str = "board_count";
774+/// The two stroke counters on a board row. `epoch_stroke_count` is reset to
775+/// zero by a clear and capped at `MAX_EPOCH_STROKES` β€” a full epoch is
776+/// recoverable. `total_stroke_count` is never reset and capped at
777+/// `MAX_BOARD_STROKES`; reaching it stamps `closed_at`, and a closed board is
778+/// read-only for good. Both are claimed in the same conditional write as the
779+/// stroke row, so two people drawing at once contend on the board record rather
780+/// than on a `SELECT count()` either of them can outrun.
781+pub const BOARD_EPOCH_STROKE_COUNT_FIELD: &str = "epoch_stroke_count";
782+pub const BOARD_TOTAL_STROKE_COUNT_FIELD: &str = "total_stroke_count";
705 /// Cap 1, not N: an appointment slot holds at most one live booking, so this783 /// Cap 1, not N: an appointment slot holds at most one live booking, so this
706 /// counter is really an "is it taken" flag kept in the shape every other cap784 /// counter is really an "is it taken" flag kept in the shape every other cap
707 /// uses (`claim`/`release`), which is what makes rejecting or cancelling a785 /// uses (`claim`/`release`), which is what makes rejecting or cancelling a
@@ -743,6 +821,12 @@ pub const SUBMISSION_GRADED_FIELD: &str = "graded_by_result";
743 /// The condition itself, spelled once: a submission is writable exactly while821 /// The condition itself, spelled once: a submission is writable exactly while
744 /// its grade stamp is absent.822 /// its grade stamp is absent.
745 pub const SUBMISSION_OPEN_GUARD: &str = "graded_by_result = NONE";823 pub const SUBMISSION_OPEN_GUARD: &str = "graded_by_result = NONE";
824+/// The same idea for a whiteboard, spelled once: a board accepts strokes
825+/// exactly while the creator has not locked it and it has not closed itself on
826+/// `MAX_BOARD_STROKES`. Every stroke write carries it, so "is this board still
827+/// open" and the write it licenses are one conditional single-record write β€”
828+/// a lock landing mid-draw beats the stroke instead of racing it.
829+pub const BOARD_OPEN_GUARD: &str = "locked = false AND closed_at = NONE";
746 830
747 /// How hard a counter write tries before giving up, and the first backoff step831 /// How hard a counter write tries before giving up, and the first backoff step
748 /// it sleeps between attempts (doubling, plus jitter). Contention on one record832 /// it sleeps between attempts (doubling, plus jitter). Contention on one record
src/domain/board.rsadded+491 -0
@@ -0,0 +1,491 @@
1+//! A collaborative whiteboard room. Membership is an ad-hoc invite list the
2+//! creator names β€” no course, session or appointment is involved β€” and the
3+//! whole permission model is the two predicates [`Board::is_participant`]
4+//! (draw) and [`Board::is_creator`] (clear / lock / close / delete). Every
5+//! route and every socket frame gates on exactly those two.
6+//!
7+//! The marks themselves live in `board_stroke`, appended and never deleted: a
8+//! clear bumps `epoch` so the canvas empties while the history stays
9+//! replayable. The two stroke counters (`epoch_stroke_count`,
10+//! `total_stroke_count`) are `option<int>` columns this struct deliberately
11+//! does NOT carry β€” they are written only by the stroke path's conditional
12+//! claim, so every mutation here is field-scoped `UPDATE … SET`. A whole-row
13+//! `CONTENT` save would silently wipe both (src/constant.rs:717-722).
14+
15+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
16+
17+use crate::constant::{
18+ BOARD_TABLE, MAX_BOARD_PARTICIPANTS, MAX_BOARD_TITLE_LEN, MAX_BOARDS_PER_CREATOR,
19+ USER_BOARD_COUNT_FIELD,
20+};
21+use crate::database::Database;
22+use crate::domain::cap;
23+use crate::domain::monotonic_id::next_ulid;
24+use crate::domain::page::PagedList;
25+use crate::domain::timestamp::Timestamp;
26+use crate::domain::user::UserId;
27+use crate::error::{AppError, ValidationError};
28+use crate::validate::validate_required;
29+
30+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
31+pub struct BoardId(RecordId);
32+
33+impl BoardId {
34+ /// Monotonic, not `Ulid::new()`: boards list newest-first by id, and a
35+ /// random low half scrambles rows minted in the same millisecond.
36+ pub fn generate() -> Self {
37+ Self(RecordId::new(BOARD_TABLE, next_ulid().to_string()))
38+ }
39+
40+ pub fn from_key(key: &str) -> Self {
41+ Self(RecordId::new(BOARD_TABLE, key))
42+ }
43+
44+ pub fn record(&self) -> RecordId {
45+ self.0.clone()
46+ }
47+
48+ pub fn key(&self) -> &str {
49+ match &self.0.key {
50+ RecordIdKey::String(key) => key,
51+ _ => "",
52+ }
53+ }
54+}
55+
56+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
57+pub struct BoardTitle(String);
58+
59+impl BoardTitle {
60+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
61+ validate_required("title", value, MAX_BOARD_TITLE_LEN)?;
62+ Ok(Self(value.to_string()))
63+ }
64+
65+ pub fn as_str(&self) -> &str {
66+ &self.0
67+ }
68+}
69+
70+/// The invite list, deduplicated and bounded. The creator is a participant by
71+/// construction ([`Board::is_participant`]), so their presence in the list is
72+/// neither required nor rejected.
73+fn checked_participants(participants: Vec<UserId>) -> Result<Vec<UserId>, ValidationError> {
74+ let mut unique: Vec<UserId> = Vec::with_capacity(participants.len());
75+ for user in participants {
76+ if !unique.contains(&user) {
77+ unique.push(user);
78+ }
79+ }
80+ if unique.len() > MAX_BOARD_PARTICIPANTS {
81+ return Err(ValidationError::TooLong {
82+ field: "participants",
83+ max: MAX_BOARD_PARTICIPANTS,
84+ got: unique.len(),
85+ });
86+ }
87+ Ok(unique)
88+}
89+
90+#[derive(Debug, Clone, SurrealValue)]
91+pub struct Board {
92+ id: BoardId,
93+ creator: UserId,
94+ title: BoardTitle,
95+ participants: Vec<UserId>,
96+ locked: bool,
97+ locked_by: Option<UserId>,
98+ locked_at: Option<Timestamp>,
99+ epoch: i64,
100+ closed_at: Option<Timestamp>,
101+ created_at: Timestamp,
102+}
103+
104+impl Board {
105+ pub fn get_id(&self) -> &BoardId {
106+ &self.id
107+ }
108+
109+ pub fn get_creator(&self) -> &UserId {
110+ &self.creator
111+ }
112+
113+ pub fn get_title(&self) -> &BoardTitle {
114+ &self.title
115+ }
116+
117+ pub fn get_participants(&self) -> &[UserId] {
118+ &self.participants
119+ }
120+
121+ pub fn is_locked(&self) -> bool {
122+ self.locked
123+ }
124+
125+ pub fn get_locked_by(&self) -> Option<&UserId> {
126+ self.locked_by.as_ref()
127+ }
128+
129+ pub fn get_locked_at(&self) -> Option<Timestamp> {
130+ self.locked_at
131+ }
132+
133+ pub fn get_epoch(&self) -> i64 {
134+ self.epoch
135+ }
136+
137+ pub fn get_closed_at(&self) -> Option<Timestamp> {
138+ self.closed_at
139+ }
140+
141+ pub fn get_created_at(&self) -> Timestamp {
142+ self.created_at
143+ }
144+
145+ /// May draw. The creator is always in, without being named on the list.
146+ pub fn is_participant(&self, user: &UserId) -> bool {
147+ &self.creator == user || self.participants.contains(user)
148+ }
149+
150+ /// May clear, lock, close and delete. Nothing else is creator-only.
151+ pub fn is_creator(&self, user: &UserId) -> bool {
152+ &self.creator == user
153+ }
154+
155+ /// Open a board, taking a slot on the creator's `board_count` in the same
156+ /// transaction as the row β€” the counter is the authority on how many
157+ /// boards exist, so it can never count a row that did not commit.
158+ pub async fn create(
159+ creator: &UserId,
160+ title: BoardTitle,
161+ participants: Vec<UserId>,
162+ db: &Database,
163+ ) -> Result<Board, AppError> {
164+ let board = Board {
165+ id: BoardId::generate(),
166+ creator: creator.clone(),
167+ title,
168+ participants: checked_participants(participants)?,
169+ locked: false,
170+ locked_by: None,
171+ locked_at: None,
172+ epoch: 0,
173+ closed_at: None,
174+ created_at: Timestamp::now(),
175+ };
176+ match cap::claim_and_create(
177+ &creator.record(),
178+ USER_BOARD_COUNT_FIELD,
179+ MAX_BOARDS_PER_CREATOR,
180+ &board.id.record(),
181+ &board,
182+ db,
183+ )
184+ .await?
185+ {
186+ cap::Claimed::Made(saved) => Ok(saved),
187+ // Full, or the creator's row is gone β€” the conditional write
188+ // matches nothing either way.
189+ cap::Claimed::Full => Err(AppError::Conflict(
190+ "you have reached the limit on boards β€” delete one first",
191+ )),
192+ // The id is a freshly minted ULID on a table with no UNIQUE index,
193+ // so no rival can have aimed at it.
194+ cap::Claimed::Duplicate => Err(AppError::Internal("board id collided".into())),
195+ }
196+ }
197+
198+ pub async fn read(id: &BoardId, db: &Database) -> Result<Option<Board>, AppError> {
199+ Ok(db.select(id.record()).await?)
200+ }
201+
202+ /// Every board `user` may open: the ones they created and the ones they
203+ /// were invited to. Newest first β€” the ids are monotonic, so `id` is the
204+ /// creation order.
205+ pub async fn list_for_user(
206+ user: &UserId,
207+ limit: Option<i64>,
208+ offset: i64,
209+ db: &Database,
210+ ) -> Result<(Vec<Board>, i64), AppError> {
211+ PagedList::new(
212+ "board WHERE creator = $usr OR participants CONTAINS $usr",
213+ "ORDER BY id DESC",
214+ )
215+ .bind("usr", user.record())
216+ .run(limit, offset, db)
217+ .await
218+ }
219+
220+ /// Re-invite. Field-scoped, like every write here: a stroke landing
221+ /// concurrently is moving the counters this struct does not carry.
222+ pub async fn set_participants(
223+ &self,
224+ participants: Vec<UserId>,
225+ db: &Database,
226+ ) -> Result<Board, AppError> {
227+ let participants = checked_participants(participants)?;
228+ let mut result = db
229+ .query("UPDATE $id SET participants = $who RETURN AFTER")
230+ .bind(("id", self.id.record()))
231+ .bind((
232+ "who",
233+ participants
234+ .iter()
235+ .map(|user| user.record())
236+ .collect::<Vec<_>>(),
237+ ))
238+ .await?
239+ .check()?;
240+ one(result.take::<Vec<Board>>(0)?)
241+ }
242+
243+ pub async fn set_title(&self, title: BoardTitle, db: &Database) -> Result<Board, AppError> {
244+ let mut result = db
245+ .query("UPDATE $id SET title = $title RETURN AFTER")
246+ .bind(("id", self.id.record()))
247+ .bind(("title", title.0))
248+ .await?
249+ .check()?;
250+ one(result.take::<Vec<Board>>(0)?)
251+ }
252+
253+ /// Freeze or thaw drawing. `locked_by`/`locked_at` are cleared on unlock so
254+ /// the row never claims a lock that is not held.
255+ pub async fn set_locked(
256+ &self,
257+ locked: bool,
258+ by: &UserId,
259+ db: &Database,
260+ ) -> Result<Board, AppError> {
261+ let now = Timestamp::now();
262+ let mut result = db
263+ .query("UPDATE $id SET locked = $locked, locked_by = $by, locked_at = $at RETURN AFTER")
264+ .bind(("id", self.id.record()))
265+ .bind(("locked", locked))
266+ .bind(("by", locked.then(|| by.record())))
267+ .bind(("at", locked.then(|| now.as_millis())))
268+ .await?
269+ .check()?;
270+ one(result.take::<Vec<Board>>(0)?)
271+ }
272+
273+ /// Retire the board: permanently read-only, history still readable.
274+ /// Idempotent by the `WHERE` β€” a second call matches nothing and the first
275+ /// stamp stands, which is what the stroke path's open-guard reads.
276+ pub async fn close(&self, db: &Database) -> Result<Board, AppError> {
277+ let mut result = db
278+ .query("UPDATE $id SET closed_at = $now WHERE closed_at = NONE RETURN AFTER")
279+ .bind(("id", self.id.record()))
280+ .bind(("now", Timestamp::now().as_millis()))
281+ .await?
282+ .check()?;
283+ match result.take::<Vec<Board>>(0)?.into_iter().next() {
284+ Some(board) => Ok(board),
285+ // Already closed: the row is unchanged, so read it back rather
286+ // than report a 404 for a board that plainly exists.
287+ None => Self::read(&self.id, db).await?.ok_or(AppError::NotFound),
288+ }
289+ }
290+
291+ /// Delete the board and give the creator's slot back in the *same*
292+ /// transaction β€” a release issued afterwards can be lost, and the counter
293+ /// would then ratchet the creator's limit shut forever.
294+ ///
295+ /// The stroke cascade rides in that same transaction: it is the one and
296+ /// only legitimate delete of `board_stroke` rows (a clear deletes nothing),
297+ /// and issued separately it could leave a board's whole history orphaned
298+ /// under a record that no longer exists.
299+ pub async fn delete(self, db: &Database) -> Result<Board, AppError> {
300+ let mut result = db
301+ .query(
302+ "BEGIN TRANSACTION;
303+ DELETE board_stroke WHERE board = $id;
304+ LET $gone = (DELETE $id RETURN BEFORE);
305+ UPDATE $usr SET board_count = math::max([(board_count ?? 0) - array::len($gone), 0]);
306+ RETURN $gone;
307+ COMMIT TRANSACTION;",
308+ )
309+ .bind(("id", self.id.record()))
310+ .bind(("usr", self.creator.record()))
311+ .await?
312+ .check()?;
313+ // Slots count BEGIN, the cascade, the LET and the UPDATE: the RETURN
314+ // is slot 4.
315+ one(result.take::<Vec<Board>>(4)?)
316+ }
317+}
318+
319+fn one(rows: Vec<Board>) -> Result<Board, AppError> {
320+ rows.into_iter().next().ok_or(AppError::NotFound)
321+}
322+
323+#[cfg(test)]
324+mod tests {
325+ use super::*;
326+
327+ async fn a_db() -> Database {
328+ let db = crate::database::init_mem().await.unwrap();
329+ db.query(
330+ "CREATE user:c SET username = 'c', password_hash = 'x';
331+ CREATE user:p SET username = 'p', password_hash = 'x';
332+ CREATE user:s SET username = 's', password_hash = 'x';",
333+ )
334+ .await
335+ .unwrap()
336+ .check()
337+ .unwrap();
338+ db
339+ }
340+
341+ fn user(key: &str) -> UserId {
342+ UserId::from_key(key)
343+ }
344+
345+ /// The stored counter, re-read out of the database. Never asserted off a
346+ /// return value: the in-memory engine forges concurrent-write wins
347+ /// (src/domain/cap.rs:44-49).
348+ async fn stored_count(db: &Database) -> i64 {
349+ let mut result = db
350+ .query("SELECT VALUE board_count ?? 0 FROM user:c")
351+ .await
352+ .unwrap()
353+ .check()
354+ .unwrap();
355+ result.take::<Vec<i64>>(0).unwrap()[0]
356+ }
357+
358+ async fn a_board(db: &Database) -> Board {
359+ Board::create(
360+ &user("c"),
361+ BoardTitle::try_new("Geometri").unwrap(),
362+ vec![user("p")],
363+ db,
364+ )
365+ .await
366+ .unwrap()
367+ }
368+
369+ #[tokio::test]
370+ async fn the_two_predicates_are_the_permission_model() {
371+ let db = a_db().await;
372+ let board = a_board(&db).await;
373+ // Creator: draws AND commands.
374+ assert!(board.is_participant(&user("c")));
375+ assert!(board.is_creator(&user("c")));
376+ // Invited: draws only.
377+ assert!(board.is_participant(&user("p")));
378+ assert!(!board.is_creator(&user("p")));
379+ // Stranger: neither.
380+ assert!(!board.is_participant(&user("s")));
381+ assert!(!board.is_creator(&user("s")));
382+ }
383+
384+ #[test]
385+ fn title_is_required_and_bounded() {
386+ assert!(BoardTitle::try_new(" ").is_err());
387+ assert!(BoardTitle::try_new(&"x".repeat(MAX_BOARD_TITLE_LEN)).is_ok());
388+ assert!(BoardTitle::try_new(&"x".repeat(MAX_BOARD_TITLE_LEN + 1)).is_err());
389+ }
390+
391+ #[tokio::test]
392+ async fn participants_are_deduplicated_and_bounded() {
393+ assert_eq!(
394+ checked_participants(vec![user("p"), user("p")])
395+ .unwrap()
396+ .len(),
397+ 1
398+ );
399+ let many = (0..MAX_BOARD_PARTICIPANTS + 1)
400+ .map(|n| UserId::from_key(&format!("u{n}")))
401+ .collect();
402+ assert!(checked_participants(many).is_err());
403+ }
404+
405+ /// The cap refuses at `MAX_BOARDS_PER_CREATOR`, and the refusal writes
406+ /// nothing β€” asserted by re-reading the counter, not off the return value.
407+ #[tokio::test]
408+ async fn the_per_creator_cap_refuses_a_full_creator() {
409+ let db = a_db().await;
410+ db.query("UPDATE user:c SET board_count = $full")
411+ .bind(("full", MAX_BOARDS_PER_CREATOR))
412+ .await
413+ .unwrap()
414+ .check()
415+ .unwrap();
416+ let refused = Board::create(
417+ &user("c"),
418+ BoardTitle::try_new("Geometri").unwrap(),
419+ vec![],
420+ &db,
421+ )
422+ .await;
423+ assert!(matches!(refused, Err(AppError::Conflict(_))));
424+ assert_eq!(stored_count(&db).await, MAX_BOARDS_PER_CREATOR);
425+ let mut result = db
426+ .query("SELECT VALUE id FROM board")
427+ .await
428+ .unwrap()
429+ .check()
430+ .unwrap();
431+ assert!(result.take::<Vec<RecordId>>(0).unwrap().is_empty());
432+ }
433+
434+ /// A seat is taken on create and handed back on delete, both read back out
435+ /// of the store.
436+ #[tokio::test]
437+ async fn a_seat_is_claimed_and_released() {
438+ let db = a_db().await;
439+ let board = a_board(&db).await;
440+ assert_eq!(stored_count(&db).await, 1);
441+ board.delete(&db).await.unwrap();
442+ assert_eq!(stored_count(&db).await, 0);
443+ }
444+
445+ /// Closing twice must not re-stamp: the first `closed_at` is the record.
446+ #[tokio::test]
447+ async fn close_is_idempotent() {
448+ let db = a_db().await;
449+ let board = a_board(&db).await;
450+ let closed = board.close(&db).await.unwrap();
451+ let first = closed.get_closed_at().unwrap();
452+ // A whole millisecond apart, so a re-stamp could not go unnoticed.
453+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;
454+ assert_eq!(board.close(&db).await.unwrap().get_closed_at(), Some(first));
455+ assert_eq!(
456+ Board::read(board.get_id(), &db)
457+ .await
458+ .unwrap()
459+ .unwrap()
460+ .get_closed_at(),
461+ Some(first)
462+ );
463+ }
464+
465+ #[tokio::test]
466+ async fn field_scoped_writes_leave_the_stroke_counters_alone() {
467+ let db = a_db().await;
468+ let board = a_board(&db).await;
469+ db.query("UPDATE $id SET epoch_stroke_count = 7, total_stroke_count = 9")
470+ .bind(("id", board.get_id().record()))
471+ .await
472+ .unwrap()
473+ .check()
474+ .unwrap();
475+ board
476+ .set_title(BoardTitle::try_new("Cebir").unwrap(), &db)
477+ .await
478+ .unwrap();
479+ board.set_participants(vec![user("s")], &db).await.unwrap();
480+ board.set_locked(true, &user("c"), &db).await.unwrap();
481+ board.close(&db).await.unwrap();
482+ let mut result = db
483+ .query("SELECT VALUE [epoch_stroke_count, total_stroke_count] FROM $id")
484+ .bind(("id", board.get_id().record()))
485+ .await
486+ .unwrap()
487+ .check()
488+ .unwrap();
489+ assert_eq!(result.take::<Vec<Vec<i64>>>(0).unwrap()[0], vec![7, 9]);
490+ }
491+}
src/domain/board_stroke.rsadded+613 -0
@@ -0,0 +1,613 @@
1+//! One board's marks, appended and never deleted.
2+//!
3+//! A clear does NOT remove strokes β€” it bumps the board's `epoch`, so the live
4+//! canvas empties while every mark the board ever carried stays on the table
5+//! and stays replayable. That is the whole storage model: the only legitimate
6+//! delete of a stroke row in the feature is [`crate::domain::board::Board::delete`]'s
7+//! cascade, which runs inside the same transaction as the board's own delete.
8+//!
9+//! The `clear` marker row IS the epoch index: it carries the epoch it closed,
10+//! that epoch's final stroke count, who cleared and when β€” so replaying a whole
11+//! session needs no second table and no `GROUP BY` over the history.
12+//!
13+//! This module is the sole write funnel for `board_stroke`, and for the board's
14+//! two stroke counters. Nothing else may write either, because two invariants
15+//! the schema cannot state depend on it: `count` is populated *only* on a
16+//! `clear` row (SCHEMAFULL types both kinds the same), and the two counters
17+//! must move together with the row they count (`cap::claim_two_when_and_create`
18+//! is what makes that one transaction).
19+
20+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value};
21+
22+use crate::constant::{
23+ BOARD_EPOCH_STROKE_COUNT_FIELD, BOARD_OPEN_GUARD, BOARD_REPLAY_CHUNK, BOARD_STROKE_KINDS,
24+ BOARD_STROKE_TABLE, BOARD_TOTAL_STROKE_COUNT_FIELD, MAX_BOARD_STROKES, MAX_EPOCH_STROKES,
25+ MAX_STROKE_PAYLOAD_LEN,
26+};
27+use crate::database::{Database, transaction_with_retry};
28+use crate::domain::board::{Board, BoardId};
29+use crate::domain::cap;
30+use crate::domain::monotonic_id::next_ulid;
31+use crate::domain::page::PagedList;
32+use crate::domain::timestamp::Timestamp;
33+use crate::domain::user::UserId;
34+use crate::error::AppError;
35+use crate::validate::validate_required;
36+
37+/// A drawn mark, and the marker that ends an epoch.
38+const KIND_STROKE: &str = BOARD_STROKE_KINDS[0];
39+const KIND_CLEAR: &str = BOARD_STROKE_KINDS[1];
40+
41+/// The `THROW` the clear transaction refuses with: not the creator, or the
42+/// board is already closed. A decision, so it outranks a lost round.
43+const CLEAR_REFUSED: &str = "board_clear_refused";
44+
45+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
46+pub struct BoardStrokeId(RecordId);
47+
48+impl BoardStrokeId {
49+ /// Monotonic, not `Ulid::new()`: this id *is* the board's total order, and
50+ /// a random low half scrambles every stroke drawn in the same millisecond β€”
51+ /// which is what a burst of drawing looks like.
52+ pub fn generate() -> Self {
53+ Self(RecordId::new(BOARD_STROKE_TABLE, next_ulid().to_string()))
54+ }
55+
56+ pub fn record(&self) -> RecordId {
57+ self.0.clone()
58+ }
59+
60+ pub fn key(&self) -> &str {
61+ match &self.0.key {
62+ RecordIdKey::String(key) => key,
63+ _ => "",
64+ }
65+ }
66+}
67+
68+#[derive(Debug, Clone, SurrealValue)]
69+pub struct BoardStroke {
70+ id: BoardStrokeId,
71+ board: BoardId,
72+ author: UserId,
73+ kind: String,
74+ payload: Option<String>,
75+ count: Option<i64>,
76+ epoch: i64,
77+ created_at: Timestamp,
78+}
79+
80+impl BoardStroke {
81+ pub fn get_id(&self) -> &BoardStrokeId {
82+ &self.id
83+ }
84+
85+ pub fn get_board(&self) -> &BoardId {
86+ &self.board
87+ }
88+
89+ pub fn get_author(&self) -> &UserId {
90+ &self.author
91+ }
92+
93+ pub fn get_kind(&self) -> &str {
94+ &self.kind
95+ }
96+
97+ pub fn get_payload(&self) -> Option<&str> {
98+ self.payload.as_deref()
99+ }
100+
101+ /// The epoch's final stroke count β€” present only on a `clear` marker.
102+ pub fn get_count(&self) -> Option<i64> {
103+ self.count
104+ }
105+
106+ pub fn get_epoch(&self) -> i64 {
107+ self.epoch
108+ }
109+
110+ pub fn get_created_at(&self) -> Timestamp {
111+ self.created_at
112+ }
113+
114+ pub fn is_clear(&self) -> bool {
115+ self.kind == KIND_CLEAR
116+ }
117+
118+ /// Append one mark to `board`'s current `epoch`.
119+ ///
120+ /// Both stroke counters and the row commit together or not at all: the
121+ /// resettable epoch counter, the lifetime counter, and the open-board guard
122+ /// are one conditional write, so a locked or closed board can never be
123+ /// drawn on by a writer that read it a moment earlier.
124+ //
125+ // ponytail: `epoch` is the caller's read of the board, so a clear landing
126+ // between that read and this write files the stroke under the epoch that
127+ // just ended β€” it is kept and replayable, but it never appears on the live
128+ // canvas, and the marker's `count` under-reports it by one. Harmless (a
129+ // stroke drawn during a clear is exactly the stroke the clear was erasing);
130+ // closing it means passing the epoch through the conditional write, which
131+ // the shared `cap` helper's static CONTENT cannot express.
132+ pub async fn append(
133+ board: &BoardId,
134+ author: &UserId,
135+ payload: &str,
136+ epoch: i64,
137+ db: &Database,
138+ ) -> Result<BoardStroke, AppError> {
139+ validate_required("payload", payload, MAX_STROKE_PAYLOAD_LEN)?;
140+ let stroke = BoardStroke {
141+ id: BoardStrokeId::generate(),
142+ board: board.clone(),
143+ author: author.clone(),
144+ kind: KIND_STROKE.to_string(),
145+ payload: Some(payload.to_string()),
146+ count: None,
147+ epoch,
148+ created_at: Timestamp::now(),
149+ };
150+ match cap::claim_two_when_and_create(
151+ &board.record(),
152+ BOARD_EPOCH_STROKE_COUNT_FIELD,
153+ MAX_EPOCH_STROKES,
154+ BOARD_TOTAL_STROKE_COUNT_FIELD,
155+ MAX_BOARD_STROKES,
156+ BOARD_OPEN_GUARD,
157+ &stroke.id.record(),
158+ &stroke,
159+ db,
160+ )
161+ .await?
162+ {
163+ cap::ClaimedTwo::Made(saved) => Ok(saved),
164+ // The live canvas is full and nothing else: recoverable by a clear,
165+ // which resets this counter without losing a single mark.
166+ cap::ClaimedTwo::FullSoft => Err(AppError::Conflict(
167+ "this board is full β€” clear it to keep drawing",
168+ )),
169+ // Three refusals share this answer (lifetime full / guard failed /
170+ // board gone), so the board is re-read to pick the message. The
171+ // re-read decides *wording* only: every branch is a refusal the
172+ // caller cannot retry into a success, so a board that changes state
173+ // between the claim and the re-read still gets told "no".
174+ cap::ClaimedTwo::FullHard => Err(Self::why_refused(board, db).await?),
175+ }
176+ }
177+
178+ async fn why_refused(board: &BoardId, db: &Database) -> Result<AppError, AppError> {
179+ let board = Board::read(board, db).await?.ok_or(AppError::NotFound)?;
180+ if board.is_locked() {
181+ return Ok(AppError::Conflict(
182+ "this board is locked β€” the creator has paused drawing",
183+ ));
184+ }
185+ if board.get_closed_at().is_none() {
186+ // Neither locked nor closed, so the lifetime cap was just reached.
187+ // `Board::close` is the one-way idempotent stamp: a second append
188+ // takes this branch too and leaves the first `closed_at` standing.
189+ board.close(db).await?;
190+ }
191+ Ok(AppError::Conflict(
192+ "this board is closed β€” it is permanently read-only",
193+ ))
194+ }
195+
196+ /// End the current epoch: the canvas empties, the history does not.
197+ ///
198+ /// The bump and the marker are one transaction, because the marker carries
199+ /// the epoch's final count β€” written apart, a crash between them would
200+ /// leave an epoch no marker indexes, and the playback would silently join
201+ /// two sessions into one.
202+ pub async fn clear(
203+ board: &BoardId,
204+ by: &UserId,
205+ db: &Database,
206+ ) -> Result<BoardStroke, AppError> {
207+ let marker = BoardStrokeId::generate();
208+ // `($before[0].epoch_stroke_count ?? 0)` is parenthesized: the bare form
209+ // parses as `?? (0 = …)` and stores a boolean count (src/constant.rs:699).
210+ let sql = format!(
211+ "BEGIN TRANSACTION;
212+ LET $before = (UPDATE $b SET epoch += 1, {BOARD_EPOCH_STROKE_COUNT_FIELD} = 0 \
213+ WHERE creator = $by AND closed_at = NONE RETURN BEFORE);
214+ IF array::len($before) = 0 {{ THROW '{CLEAR_REFUSED}' }};
215+ CREATE $mid CONTENT {{ board: $b, author: $by, kind: $kind, \
216+ epoch: $before[0].epoch, \
217+ count: ($before[0].{BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0), \
218+ created_at: $now }};
219+ COMMIT TRANSACTION;"
220+ );
221+ let bound: Vec<(String, Value)> = vec![
222+ ("b".into(), board.record().into_value()),
223+ ("by".into(), by.record().into_value()),
224+ ("mid".into(), marker.record().into_value()),
225+ ("kind".into(), KIND_CLEAR.into_value()),
226+ ("now".into(), Timestamp::now().as_millis().into_value()),
227+ ];
228+ let (mut result, mut errors) =
229+ transaction_with_retry(db, &sql, &bound, &[CLEAR_REFUSED]).await?;
230+ if errors
231+ .values()
232+ .any(|error| error.to_string().contains(CLEAR_REFUSED))
233+ {
234+ return Err(AppError::Conflict(
235+ "this board cannot be cleared β€” it is closed, or you did not create it",
236+ ));
237+ }
238+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
239+ return Err(error.into());
240+ }
241+ // Slots count BEGIN, the LET and the IF: the CREATE is slot 3. Only
242+ // read once the error map is empty β€” `take_errors` swap-removes.
243+ result
244+ .take::<Vec<BoardStroke>>(3)?
245+ .into_iter()
246+ .next()
247+ .ok_or_else(|| AppError::Internal("board clear wrote no marker".into()))
248+ }
249+
250+ /// What a joining socket draws: the current epoch's marks only, in mint
251+ /// order, one [`BOARD_REPLAY_CHUNK`] at a time.
252+ ///
253+ /// Paged by `id`, never `created_at` β€” a millisecond stamp has ties by
254+ /// construction, and the ULID's monotonic low half is exactly what breaks
255+ /// them. `after` is the key of the last stroke already drawn.
256+ pub async fn replay_current(
257+ board: &BoardId,
258+ epoch: i64,
259+ after: Option<&str>,
260+ db: &Database,
261+ ) -> Result<Vec<BoardStroke>, AppError> {
262+ let cursor = match after {
263+ Some(_) => " AND id > $after",
264+ None => "",
265+ };
266+ let mut result = db
267+ .query(format!(
268+ "SELECT * FROM {BOARD_STROKE_TABLE} \
269+ WHERE board = $b AND epoch = $e AND kind = $kind{cursor} \
270+ ORDER BY id LIMIT $chunk"
271+ ))
272+ .bind(("b", board.record()))
273+ .bind(("e", epoch))
274+ .bind(("kind", KIND_STROKE))
275+ .bind((
276+ "after",
277+ RecordId::new(BOARD_STROKE_TABLE, after.unwrap_or_default()),
278+ ))
279+ .bind(("chunk", BOARD_REPLAY_CHUNK as i64))
280+ .await?
281+ .check()?;
282+ Ok(result.take::<Vec<BoardStroke>>(0)?)
283+ }
284+
285+ /// The whole log, oldest first β€” every epoch, or one named epoch. Both
286+ /// kinds of row come back: the `clear` markers are what tell a reader where
287+ /// one epoch ended and the next began.
288+ pub async fn history(
289+ board: &BoardId,
290+ epoch: Option<i64>,
291+ limit: Option<i64>,
292+ offset: i64,
293+ db: &Database,
294+ ) -> Result<(Vec<BoardStroke>, i64), AppError> {
295+ let scope = match epoch {
296+ Some(_) => " AND epoch = $e",
297+ None => "",
298+ };
299+ PagedList::new(
300+ format!("{BOARD_STROKE_TABLE} WHERE board = $b{scope}"),
301+ "ORDER BY id",
302+ )
303+ .bind("b", board.record())
304+ .bind("e", epoch.unwrap_or_default())
305+ .run(limit, offset, db)
306+ .await
307+ }
308+
309+ /// The epoch index: every `clear` marker this board has, oldest first.
310+ pub async fn epochs(board: &BoardId, db: &Database) -> Result<Vec<BoardStroke>, AppError> {
311+ let mut result = db
312+ .query(format!(
313+ "SELECT * FROM {BOARD_STROKE_TABLE} \
314+ WHERE board = $b AND kind = $kind ORDER BY id"
315+ ))
316+ .bind(("b", board.record()))
317+ .bind(("kind", KIND_CLEAR))
318+ .await?
319+ .check()?;
320+ Ok(result.take::<Vec<BoardStroke>>(0)?)
321+ }
322+}
323+
324+#[cfg(test)]
325+mod tests {
326+ use super::*;
327+ use crate::domain::board::BoardTitle;
328+
329+ async fn a_db() -> Database {
330+ let db = crate::database::init_mem().await.unwrap();
331+ db.query(
332+ "CREATE user:c SET username = 'c', password_hash = 'x';
333+ CREATE user:p SET username = 'p', password_hash = 'x';",
334+ )
335+ .await
336+ .unwrap()
337+ .check()
338+ .unwrap();
339+ db
340+ }
341+
342+ fn user(key: &str) -> UserId {
343+ UserId::from_key(key)
344+ }
345+
346+ async fn a_board(db: &Database) -> Board {
347+ Board::create(
348+ &user("c"),
349+ BoardTitle::try_new("Geometri").unwrap(),
350+ vec![user("p")],
351+ db,
352+ )
353+ .await
354+ .unwrap()
355+ }
356+
357+ /// Every stroke row of a board, read straight out of the store β€” never off
358+ /// a return value, which the in-memory engine forges wins on
359+ /// (src/domain/cap.rs:44-49).
360+ async fn rows(board: &BoardId, db: &Database) -> Vec<BoardStroke> {
361+ let mut result = db
362+ .query("SELECT * FROM board_stroke WHERE board = $b ORDER BY id")
363+ .bind(("b", board.record()))
364+ .await
365+ .unwrap()
366+ .check()
367+ .unwrap();
368+ result.take(0).unwrap()
369+ }
370+
371+ async fn reread(board: &Board, db: &Database) -> Board {
372+ Board::read(board.get_id(), db).await.unwrap().unwrap()
373+ }
374+
375+ async fn set_counters(board: &Board, epoch: i64, total: i64, db: &Database) {
376+ db.query("UPDATE $id SET epoch_stroke_count = $e, total_stroke_count = $t")
377+ .bind(("id", board.get_id().record()))
378+ .bind(("e", epoch))
379+ .bind(("t", total))
380+ .await
381+ .unwrap()
382+ .check()
383+ .unwrap();
384+ }
385+
386+ async fn draw(board: &Board, db: &Database) -> Result<BoardStroke, AppError> {
387+ BoardStroke::append(
388+ board.get_id(),
389+ &user("p"),
390+ "{\"p\":[1,2]}",
391+ board.get_epoch(),
392+ db,
393+ )
394+ .await
395+ }
396+
397+ #[tokio::test]
398+ async fn a_full_canvas_is_refused_but_the_board_stays_open() {
399+ let db = a_db().await;
400+ let board = a_board(&db).await;
401+ set_counters(&board, MAX_EPOCH_STROKES, 10, &db).await;
402+ let refused = draw(&board, &db).await;
403+ assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("clear it")));
404+ // Nothing written, and above all: NOT closed β€” a full canvas is
405+ // recoverable, and closing it here would make it permanent.
406+ assert!(rows(board.get_id(), &db).await.is_empty());
407+ assert!(reread(&board, &db).await.get_closed_at().is_none());
408+ }
409+
410+ /// The user's decision in one test: a clear empties the canvas and loses
411+ /// nothing. If this ever passes with the pre-clear rows gone, the feature
412+ /// is wrong.
413+ #[tokio::test]
414+ async fn a_clear_keeps_every_pre_clear_stroke() {
415+ let db = a_db().await;
416+ let board = a_board(&db).await;
417+ for _ in 0..3 {
418+ draw(&board, &db).await.unwrap();
419+ }
420+ let before: Vec<String> = rows(board.get_id(), &db)
421+ .await
422+ .iter()
423+ .map(|row| row.get_id().key().to_string())
424+ .collect();
425+
426+ BoardStroke::clear(board.get_id(), &user("c"), &db)
427+ .await
428+ .unwrap();
429+ let board = reread(&board, &db).await;
430+ assert_eq!(board.get_epoch(), 1);
431+ draw(&board, &db).await.unwrap();
432+
433+ // The three original rows are still in the table, by direct read.
434+ let after: Vec<String> = rows(board.get_id(), &db)
435+ .await
436+ .iter()
437+ .map(|row| row.get_id().key().to_string())
438+ .collect();
439+ for key in &before {
440+ assert!(after.contains(key), "a clear deleted stroke {key}");
441+ }
442+ // 3 old + 1 marker + 1 new, and the live canvas is the new one alone.
443+ assert_eq!(after.len(), 5);
444+ let live = BoardStroke::replay_current(board.get_id(), 1, None, &db)
445+ .await
446+ .unwrap();
447+ assert_eq!(live.len(), 1);
448+ // The old epoch is still replayable in full.
449+ assert_eq!(
450+ BoardStroke::replay_current(board.get_id(), 0, None, &db)
451+ .await
452+ .unwrap()
453+ .len(),
454+ 3
455+ );
456+ }
457+
458+ /// The marker IS the epoch index, so its `count` has to be that epoch's
459+ /// final stroke count β€” and `count` must appear on no other row.
460+ #[tokio::test]
461+ async fn the_marker_counts_the_epoch_it_closed() {
462+ let db = a_db().await;
463+ let board = a_board(&db).await;
464+ for _ in 0..4 {
465+ draw(&board, &db).await.unwrap();
466+ }
467+ let marker = BoardStroke::clear(board.get_id(), &user("c"), &db)
468+ .await
469+ .unwrap();
470+ assert_eq!(marker.get_count(), Some(4));
471+ assert_eq!(marker.get_epoch(), 0);
472+ assert!(marker.is_clear());
473+
474+ // And the epoch counter reset, so drawing resumes against a fresh cap.
475+ let board = reread(&board, &db).await;
476+ draw(&board, &db).await.unwrap();
477+ let epochs = BoardStroke::epochs(board.get_id(), &db).await.unwrap();
478+ assert_eq!(epochs.len(), 1);
479+ assert_eq!(epochs[0].get_count(), Some(4));
480+ // `count` lives on clear markers only β€” this module is that guard.
481+ for row in rows(board.get_id(), &db).await {
482+ assert_eq!(row.get_count().is_some(), row.is_clear());
483+ assert_eq!(row.get_payload().is_some(), !row.is_clear());
484+ }
485+ }
486+
487+ #[tokio::test]
488+ async fn the_lifetime_cap_closes_the_board_exactly_once() {
489+ let db = a_db().await;
490+ let board = a_board(&db).await;
491+ set_counters(&board, 0, MAX_BOARD_STROKES, &db).await;
492+ let refused = draw(&board, &db).await;
493+ assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("read-only")));
494+ let stamp = reread(&board, &db).await.get_closed_at();
495+ assert!(stamp.is_some());
496+
497+ // A whole millisecond apart, so a re-stamp could not go unnoticed.
498+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;
499+ assert!(draw(&board, &db).await.is_err());
500+ assert_eq!(reread(&board, &db).await.get_closed_at(), stamp);
501+ assert!(rows(board.get_id(), &db).await.is_empty());
502+ }
503+
504+ /// A locked board must be told it is locked. Both refusals arrive as the
505+ /// same `FullHard`, so a re-read that got this wrong would tell a paused
506+ /// room its canvas is full β€” and send it clearing a board it need not clear.
507+ #[tokio::test]
508+ async fn a_locked_board_is_refused_as_locked() {
509+ let db = a_db().await;
510+ let board = a_board(&db).await;
511+ let board = board.set_locked(true, &user("c"), &db).await.unwrap();
512+ let refused = draw(&board, &db).await;
513+ assert!(matches!(refused, Err(AppError::Conflict(msg)) if msg.contains("locked")));
514+ assert!(rows(board.get_id(), &db).await.is_empty());
515+ // A lock is not a close: unlocking restores drawing.
516+ assert!(reread(&board, &db).await.get_closed_at().is_none());
517+ let board = board.set_locked(false, &user("c"), &db).await.unwrap();
518+ assert!(draw(&board, &db).await.is_ok());
519+ }
520+
521+ /// The `next_ulid` hazard: rows minted inside one millisecond must replay
522+ /// in mint order, not at random (src/domain/monotonic_id.rs:41-46).
523+ #[tokio::test]
524+ async fn replay_is_in_mint_order_within_a_millisecond() {
525+ let db = a_db().await;
526+ let board = a_board(&db).await;
527+ let mut minted = Vec::new();
528+ for _ in 0..25 {
529+ minted.push(draw(&board, &db).await.unwrap().get_id().key().to_string());
530+ }
531+ let replayed: Vec<String> = BoardStroke::replay_current(board.get_id(), 0, None, &db)
532+ .await
533+ .unwrap()
534+ .iter()
535+ .map(|row| row.get_id().key().to_string())
536+ .collect();
537+ assert_eq!(replayed, minted);
538+
539+ // The cursor resumes exactly where the last chunk stopped.
540+ let rest: Vec<String> =
541+ BoardStroke::replay_current(board.get_id(), 0, Some(&minted[9]), &db)
542+ .await
543+ .unwrap()
544+ .iter()
545+ .map(|row| row.get_id().key().to_string())
546+ .collect();
547+ assert_eq!(rest, minted[10..]);
548+ }
549+
550+ /// The one legitimate delete of stroke rows: without it, deleting a board
551+ /// orphans its whole history under a record that no longer exists.
552+ #[tokio::test]
553+ async fn deleting_a_board_takes_its_strokes_with_it() {
554+ let db = a_db().await;
555+ let board = a_board(&db).await;
556+ let other = a_board(&db).await;
557+ draw(&board, &db).await.unwrap();
558+ draw(&board, &db).await.unwrap();
559+ BoardStroke::clear(board.get_id(), &user("c"), &db)
560+ .await
561+ .unwrap();
562+ draw(&other, &db).await.unwrap();
563+
564+ let id = board.get_id().clone();
565+ board.delete(&db).await.unwrap();
566+ assert!(rows(&id, &db).await.is_empty());
567+ // The cascade is scoped to its own board.
568+ assert_eq!(rows(other.get_id(), &db).await.len(), 1);
569+ }
570+
571+ #[tokio::test]
572+ async fn an_oversized_payload_is_refused_before_the_write() {
573+ let db = a_db().await;
574+ let board = a_board(&db).await;
575+ let big = "x".repeat(MAX_STROKE_PAYLOAD_LEN + 1);
576+ assert!(
577+ BoardStroke::append(board.get_id(), &user("p"), &big, 0, &db)
578+ .await
579+ .is_err()
580+ );
581+ assert!(
582+ BoardStroke::append(board.get_id(), &user("p"), " ", 0, &db)
583+ .await
584+ .is_err()
585+ );
586+ assert!(rows(board.get_id(), &db).await.is_empty());
587+ // Nothing was claimed either β€” the counters must not have moved.
588+ assert_eq!(reread(&board, &db).await.get_epoch(), 0);
589+ }
590+
591+ /// History spans epochs; a named epoch is that epoch alone.
592+ #[tokio::test]
593+ async fn history_spans_every_epoch_unless_one_is_named() {
594+ let db = a_db().await;
595+ let board = a_board(&db).await;
596+ draw(&board, &db).await.unwrap();
597+ BoardStroke::clear(board.get_id(), &user("c"), &db)
598+ .await
599+ .unwrap();
600+ let board = reread(&board, &db).await;
601+ draw(&board, &db).await.unwrap();
602+
603+ let (all, total) = BoardStroke::history(board.get_id(), None, None, 0, &db)
604+ .await
605+ .unwrap();
606+ assert_eq!((all.len(), total), (3, 3));
607+ let (first, total) = BoardStroke::history(board.get_id(), Some(0), None, 0, &db)
608+ .await
609+ .unwrap();
610+ // Epoch 0: its stroke and the marker that closed it.
611+ assert_eq!((first.len(), total), (2, 2));
612+ }
613+}
src/domain/cap.rsmodified+274 -0
@@ -112,6 +112,15 @@ async fn claim_at(
112 const FULL_MARK: &str = "cap_full";112 const FULL_MARK: &str = "cap_full";
113 const HELD_MARK: &str = "cap_held";113 const HELD_MARK: &str = "cap_held";
114 114
115+/// The two markers [`claim_two_when_and_create`] aborts with, one per counter,
116+/// deliberately *not* shared: its two caps mean opposite things to the person
117+/// who hit one. The soft cap is a resettable working set (a whiteboard's live
118+/// canvas, emptied by a clear and drawn on again); the hard cap is the parent's
119+/// lifetime budget, and hitting it is terminal. One marker for both would tell
120+/// a caller a recoverable state is a permanent one.
121+const SOFT_FULL_MARK: &str = "cap_full_soft";
122+const HARD_FULL_MARK: &str = "cap_full_hard";
123+
115 /// What [`claim_and_create`] settled.124 /// What [`claim_and_create`] settled.
116 pub(crate) enum Claimed<T> {125 pub(crate) enum Claimed<T> {
117 /// The seat and the row committed together.126 /// The seat and the row committed together.
@@ -220,6 +229,130 @@ pub(crate) async fn claim_and_create<T: SurrealValue + Clone>(
220 .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into())))229 .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into())))
221 }230 }
222 231
232+/// What [`claim_two_when_and_create`] settled.
233+pub(crate) enum ClaimedTwo<T> {
234+ /// Both seats and the row committed together.
235+ Made(T),
236+ /// The *resettable* counter (`fields[0]`) is full β€” nothing was written,
237+ /// and whatever empties it lets the caller through again.
238+ FullSoft,
239+ /// The *lifetime* counter (`fields[1]`) is full, the guard failed, or the
240+ /// parent row is gone β€” nothing was written. The caller re-reads the parent
241+ /// to tell those apart, and only to pick the message: both are refusals the
242+ /// caller cannot retry into a success.
243+ FullHard,
244+}
245+
246+/// Take a slot on *two* of `parent`'s counters, while `guard` holds, and write
247+/// the child that fills them β€” one transaction, one verdict.
248+///
249+/// Two [`claim_when`] calls cannot promise this. A parent whose children are
250+/// counted twice β€” once against a resettable working set, once against a
251+/// lifetime budget β€” has the two counters describing the same rows, so a writer
252+/// that lands one increment and loses the other leaves them disagreeing
253+/// forever, and the lifetime cap stops bounding anything. Here either both
254+/// increments and the row commit, or the transaction aborts having written
255+/// nothing.
256+///
257+/// The hard cap is claimed *first*, carrying the guard, so a terminal refusal
258+/// outranks a recoverable one: a parent that has spent its lifetime budget is
259+/// not helped by being told its resettable counter is also full.
260+///
261+/// There is no `$held` gate β€” [`claim_and_create`]'s exists because its child
262+/// carries a deterministic id two writers can both aim at. This one's caller
263+/// mints a fresh monotonic ULID on a table with no `UNIQUE` index, so no rival
264+/// can target that id, and its absence is also what keeps the batch retryable:
265+/// no statement in it can legitimately answer "already exists" (see
266+/// [`crate::database::transaction_with_retry`]).
267+///
268+/// The two counters are named one by one rather than passed as a pair of
269+/// arrays: which slot is the resettable one and which is terminal decides
270+/// whether a refusal is phrased "clear it and carry on" or "this is over", and
271+/// two `[i64; 2]` positions swapped by mistake compile, pass every test β€” both
272+/// slots are the same type β€” and misreport that forever. The names are the
273+/// guard against it.
274+///
275+/// The fields and `guard` are always in-crate constants, never user input.
276+pub(crate) async fn claim_two_when_and_create<T: SurrealValue + Clone>(
277+ parent: &RecordId,
278+ soft_field: &str,
279+ soft_cap: i64,
280+ hard_field: &str,
281+ hard_cap: i64,
282+ guard: &str,
283+ id: &RecordId,
284+ content: &T,
285+ db: &Database,
286+) -> Result<ClaimedTwo<T>, AppError> {
287+ // Parenthesized `??` throughout: `n ?? 0 < $cap` parses as `n ?? (0 < $cap)`,
288+ // which is truthy for every row and would claim past the cap.
289+ let sql = format!(
290+ "BEGIN TRANSACTION;
291+ LET $lifetime = (UPDATE $parent SET {hard_field} = ({hard_field} ?? 0) + 1 \
292+ WHERE ({hard_field} ?? 0) < $hard AND ({guard}) RETURN VALUE id);
293+ IF array::len($lifetime) = 0 {{ THROW '{HARD_FULL_MARK}' }};
294+ LET $seat = (UPDATE $parent SET {soft_field} = ({soft_field} ?? 0) + 1 \
295+ WHERE ({soft_field} ?? 0) < $soft RETURN VALUE id);
296+ IF array::len($seat) = 0 {{ THROW '{SOFT_FULL_MARK}' }};
297+ CREATE $id CONTENT $row;
298+ COMMIT TRANSACTION;"
299+ );
300+ let _guard = CLAIM_LOCK.lock().await;
301+ let mut last = None;
302+ for attempt in 0..CAP_WRITE_TRIES {
303+ backoff(attempt).await;
304+ let attempted = db
305+ .query(sql.as_str())
306+ .bind(("parent", parent.clone()))
307+ .bind(("soft", soft_cap))
308+ .bind(("hard", hard_cap))
309+ .bind(("id", id.clone()))
310+ .bind(("row", content.clone()))
311+ .await;
312+ let mut result = match attempted {
313+ Ok(result) => result,
314+ Err(err) if lost_the_race(&err) => {
315+ last = Some(err);
316+ continue;
317+ }
318+ Err(err) => return Err(err.into()),
319+ };
320+ // An aborted transaction errors *every* slot, most with a generic "not
321+ // executed" β€” only the failing slot says why. The two markers are read
322+ // before the conflict check, because a `THROW` is a decision.
323+ let mut errors = result.take_errors();
324+ if errors
325+ .values()
326+ .any(|error| error.to_string().contains(HARD_FULL_MARK))
327+ {
328+ return Ok(ClaimedTwo::FullHard);
329+ }
330+ if errors
331+ .values()
332+ .any(|error| error.to_string().contains(SOFT_FULL_MARK))
333+ {
334+ return Ok(ClaimedTwo::FullSoft);
335+ }
336+ if errors.values().any(lost_the_race) {
337+ last = errors.drain().map(|(_, error)| error).find(lost_the_race);
338+ continue;
339+ }
340+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
341+ return Err(error.into());
342+ }
343+ // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5.
344+ return result
345+ .take::<Vec<T>>(5)?
346+ .into_iter()
347+ .next()
348+ .map(ClaimedTwo::Made)
349+ .ok_or_else(|| AppError::Internal("cap claim wrote no row".into()));
350+ }
351+ Err(last
352+ .map(AppError::from)
353+ .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into())))
354+}
355+
223 /// Move `parent` to its next revision. A revision column is not a cap: it is356 /// Move `parent` to its next revision. A revision column is not a cap: it is
224 /// what a reader pins a value it took off the parent to, so that a write which357 /// what a reader pins a value it took off the parent to, so that a write which
225 /// invalidates that value (a menu's price) can refuse the claim carrying the old358 /// invalidates that value (a menu's price) can refuse the claim carrying the old
@@ -341,3 +474,144 @@ async fn write(
341 .map(AppError::from)474 .map(AppError::from)
342 .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into())))475 .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into())))
343 }476 }
477+
478+#[cfg(test)]
479+mod tests {
480+ use super::*;
481+ use crate::constant::{
482+ BOARD_EPOCH_STROKE_COUNT_FIELD, BOARD_OPEN_GUARD, BOARD_TOTAL_STROKE_COUNT_FIELD,
483+ };
484+
485+ #[derive(Debug, Clone, SurrealValue)]
486+ struct Stroke {
487+ board: RecordId,
488+ author: RecordId,
489+ kind: String,
490+ epoch: i64,
491+ created_at: i64,
492+ }
493+
494+ /// The pair of counters, re-read out of the store β€” never off a return
495+ /// value, which the in-memory engine forges wins on (see `CLAIM_LOCK`).
496+ async fn stored(db: &Database) -> (i64, i64) {
497+ let mut result = db
498+ .query("SELECT VALUE [epoch_stroke_count ?? 0, total_stroke_count ?? 0] FROM board:b")
499+ .await
500+ .unwrap()
501+ .check()
502+ .unwrap();
503+ let rows: Vec<Vec<i64>> = result.take(0).unwrap();
504+ (rows[0][0], rows[0][1])
505+ }
506+
507+ async fn strokes(db: &Database) -> usize {
508+ let mut result = db
509+ .query("SELECT VALUE id FROM board_stroke")
510+ .await
511+ .unwrap()
512+ .check()
513+ .unwrap();
514+ result.take::<Vec<RecordId>>(0).unwrap().len()
515+ }
516+
517+ async fn a_board(epoch: i64, total: i64, locked: bool) -> Database {
518+ let db = crate::database::init_mem().await.unwrap();
519+ db.query(
520+ "CREATE user:u SET username = 'u', password_hash = 'x';
521+ CREATE board:b SET creator = user:u, title = 't', participants = [user:u],
522+ locked = $locked, epoch = 0, epoch_stroke_count = $epoch,
523+ total_stroke_count = $total, created_at = 1;",
524+ )
525+ .bind(("locked", locked))
526+ .bind(("epoch", epoch))
527+ .bind(("total", total))
528+ .await
529+ .unwrap()
530+ .check()
531+ .unwrap();
532+ db
533+ }
534+
535+ fn a_stroke() -> Stroke {
536+ Stroke {
537+ board: RecordId::new("board", "b"),
538+ author: RecordId::new("user", "u"),
539+ kind: "stroke".into(),
540+ epoch: 0,
541+ created_at: 2,
542+ }
543+ }
544+
545+ async fn claim(db: &Database, caps: [i64; 2], key: &str) -> ClaimedTwo<Stroke> {
546+ claim_two_when_and_create(
547+ &RecordId::new("board", "b"),
548+ BOARD_EPOCH_STROKE_COUNT_FIELD,
549+ caps[0],
550+ BOARD_TOTAL_STROKE_COUNT_FIELD,
551+ caps[1],
552+ BOARD_OPEN_GUARD,
553+ &RecordId::new("board_stroke", key),
554+ &a_stroke(),
555+ db,
556+ )
557+ .await
558+ .unwrap()
559+ }
560+
561+ #[tokio::test]
562+ async fn both_counters_move_together_or_not_at_all() {
563+ let db = a_board(0, 0, false).await;
564+ assert!(matches!(
565+ claim(&db, [2, 2], "s1").await,
566+ ClaimedTwo::Made(_)
567+ ));
568+ assert_eq!(stored(&db).await, (1, 1));
569+ assert_eq!(strokes(&db).await, 1);
570+ }
571+
572+ /// One cap refuses; the *other* counter must not have advanced, asserted by
573+ /// re-reading the row. A drift here would let the lifetime cap be passed.
574+ #[tokio::test]
575+ async fn a_refused_claim_advances_neither_counter() {
576+ // Soft (epoch) full, hard (lifetime) with room to spare.
577+ let db = a_board(5, 5, false).await;
578+ assert!(matches!(
579+ claim(&db, [5, 99], "s1").await,
580+ ClaimedTwo::FullSoft
581+ ));
582+ assert_eq!(stored(&db).await, (5, 5));
583+ assert_eq!(strokes(&db).await, 0);
584+
585+ // Hard full, soft with room to spare.
586+ let db = a_board(5, 5, false).await;
587+ assert!(matches!(
588+ claim(&db, [99, 5], "s1").await,
589+ ClaimedTwo::FullHard
590+ ));
591+ assert_eq!(stored(&db).await, (5, 5));
592+ assert_eq!(strokes(&db).await, 0);
593+ }
594+
595+ /// The two `THROW` markers must reach the caller as *different* answers:
596+ /// one board is recoverable by a clear, the other is read-only for good.
597+ #[tokio::test]
598+ async fn the_two_caps_refuse_distinguishably() {
599+ let db = a_board(5, 5, false).await;
600+ let soft = claim(&db, [5, 99], "s1").await;
601+ let hard = claim(&db, [99, 5], "s2").await;
602+ assert!(matches!(soft, ClaimedTwo::FullSoft));
603+ assert!(matches!(hard, ClaimedTwo::FullHard));
604+ assert_eq!(stored(&db).await, (5, 5));
605+ }
606+
607+ #[tokio::test]
608+ async fn the_guard_refuses_a_locked_board() {
609+ let db = a_board(0, 0, true).await;
610+ assert!(matches!(
611+ claim(&db, [9, 9], "s1").await,
612+ ClaimedTwo::FullHard
613+ ));
614+ assert_eq!(stored(&db).await, (0, 0));
615+ assert_eq!(strokes(&db).await, 0);
616+ }
617+}
src/domain/mod.rsmodified+2 -0
@@ -8,6 +8,8 @@ pub mod appointment_slot;
8 pub mod attendance;8 pub mod attendance;
9 pub mod bank_question;9 pub mod bank_question;
10 pub mod bank_question_image;10 pub mod bank_question_image;
11+pub mod board;
12+pub mod board_stroke;
11 pub mod cap;13 pub mod cap;
12 pub mod chatbot_message;14 pub mod chatbot_message;
13 pub mod chatbot_thread;15 pub mod chatbot_thread;
src/lib.rsmodified+2 -0
@@ -63,6 +63,7 @@ use crate::state::AppState;
63 (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+"),63 (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+"),
64 (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"),64 (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"),
65 (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"),65 (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"),
66+ (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"),
66 (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+"),67 (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+"),
67 ),68 ),
68 )]69 )]
@@ -116,6 +117,7 @@ pub fn build_router(state: AppState) -> Router {
116 .nest("/subjects", web::subjects::routes())117 .nest("/subjects", web::subjects::routes())
117 .nest("/homework", web::homework::routes())118 .nest("/homework", web::homework::routes())
118 .nest("/terms", web::terms::routes())119 .nest("/terms", web::terms::routes())
120+ .nest("/boards", web::boards::routes())
119 .split_for_parts();121 .split_for_parts();
120 122
121 // Catch-all per-IP limit over every route (Swagger included). Kept inside123 // Catch-all per-IP limit over every route (Swagger included). Kept inside
src/main.rsmodified+1 -0
@@ -35,6 +35,7 @@ async fn main() -> anyhow::Result<()> {
35 rate_limit: cfg.rate_limit.clone(),35 rate_limit: cfg.rate_limit.clone(),
36 chatbot_limit: UserRateLimiter::per_user_minute(cfg.chatbot_per_minute),36 chatbot_limit: UserRateLimiter::per_user_minute(cfg.chatbot_per_minute),
37 exam_presence: Default::default(),37 exam_presence: Default::default(),
38+ board_hub: Default::default(),
38 db_up,39 db_up,
39 ai,40 ai,
40 });41 });
src/migration_sql.rsmodified+45 -0
@@ -59,6 +59,7 @@ pub const MIGRATION: &str = "
59 DEFINE FIELD IF NOT EXISTS language ON user TYPE option<string>;59 DEFINE FIELD IF NOT EXISTS language ON user TYPE option<string>;
60 DEFINE FIELD IF NOT EXISTS palette_color ON user TYPE option<string>;60 DEFINE FIELD IF NOT EXISTS palette_color ON user TYPE option<string>;
61 DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option<int>;61 DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option<int>;
62+ DEFINE FIELD IF NOT EXISTS board_count ON user TYPE option<int>;
62 DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE;63 DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE;
63 64
64 DEFINE TABLE IF NOT EXISTS session SCHEMAFULL;65 DEFINE TABLE IF NOT EXISTS session SCHEMAFULL;
@@ -94,6 +95,50 @@ pub const MIGRATION: &str = "
94 DEFINE INDEX IF NOT EXISTS message_sender ON message FIELDS sender;95 DEFINE INDEX IF NOT EXISTS message_sender ON message FIELDS sender;
95 DEFINE INDEX IF NOT EXISTS message_recipient ON message FIELDS recipient;96 DEFINE INDEX IF NOT EXISTS message_recipient ON message FIELDS recipient;
96 97
98+ -- Collaborative whiteboard (2026-07-31): one `board` is a room, one
99+ -- `board_stroke` is one append-only mark. A clear NEVER deletes β€” it bumps
100+ -- `epoch`, so the canvas empties while the whole history stays replayable.
101+ -- `locked` is a plain bool, not an option: the open-board guard asks for
102+ -- `locked = false`, which a NONE would never match. `locked_by`/`locked_at`/
103+ -- `closed_at` are three top-level option columns rather than one nested
104+ -- object, because SurrealDB 3 drops an object key valued NONE.
105+ DEFINE TABLE IF NOT EXISTS board SCHEMAFULL;
106+ DEFINE FIELD IF NOT EXISTS creator ON board TYPE record<user>;
107+ DEFINE FIELD IF NOT EXISTS title ON board TYPE string;
108+ DEFINE FIELD IF NOT EXISTS participants ON board TYPE array<record<user>>;
109+ DEFINE FIELD IF NOT EXISTS locked ON board TYPE bool DEFAULT false;
110+ DEFINE FIELD IF NOT EXISTS locked_by ON board TYPE option<record<user>>;
111+ DEFINE FIELD IF NOT EXISTS locked_at ON board TYPE option<int>;
112+ DEFINE FIELD IF NOT EXISTS epoch ON board TYPE int DEFAULT 0;
113+ -- Resets to 0 on every clear (recoverable); never resets (stamps closed_at).
114+ DEFINE FIELD IF NOT EXISTS epoch_stroke_count ON board TYPE option<int>;
115+ DEFINE FIELD IF NOT EXISTS total_stroke_count ON board TYPE option<int>;
116+ -- Stamped once, when the lifetime cap is hit: permanently read-only.
117+ DEFINE FIELD IF NOT EXISTS closed_at ON board TYPE option<int>;
118+ DEFINE FIELD IF NOT EXISTS created_at ON board TYPE int;
119+ DEFINE INDEX IF NOT EXISTS board_creator ON board FIELDS creator;
120+ -- Listing a user's boards asks `creator = $u OR participants CONTAINS $u`;
121+ -- without this the CONTAINS half is a full scan. SurrealDB indexes an
122+ -- array field per element, so it covers the membership test directly.
123+ DEFINE INDEX IF NOT EXISTS board_participants ON board FIELDS participants;
124+
125+ DEFINE TABLE IF NOT EXISTS board_stroke SCHEMAFULL;
126+ DEFINE FIELD IF NOT EXISTS board ON board_stroke TYPE record<board>;
127+ DEFINE FIELD IF NOT EXISTS author ON board_stroke TYPE record<user>;
128+ -- 'stroke' or 'clear'; `payload` is the opaque blob, absent on a clear
129+ -- marker, and `count` is populated only on a clear marker β€” the final
130+ -- stroke count of the epoch that marker closed.
131+ DEFINE FIELD IF NOT EXISTS kind ON board_stroke TYPE string;
132+ DEFINE FIELD IF NOT EXISTS payload ON board_stroke TYPE option<string>;
133+ DEFINE FIELD IF NOT EXISTS count ON board_stroke TYPE option<int>;
134+ DEFINE FIELD IF NOT EXISTS epoch ON board_stroke TYPE int;
135+ DEFINE FIELD IF NOT EXISTS created_at ON board_stroke TYPE int;
136+ -- Keeps a socket's join-replay scoped to the current epoch instead of
137+ -- scanning the board's whole history.
138+ DEFINE INDEX IF NOT EXISTS board_stroke_board_epoch ON board_stroke FIELDS board, epoch;
139+ -- The clear markers ARE the epoch index, so listing them is a hot read.
140+ DEFINE INDEX IF NOT EXISTS board_stroke_board_kind ON board_stroke FIELDS board, kind;
141+
97 DEFINE TABLE IF NOT EXISTS note_file SCHEMAFULL;142 DEFINE TABLE IF NOT EXISTS note_file SCHEMAFULL;
98 DEFINE FIELD IF NOT EXISTS note ON note_file TYPE record<note>;143 DEFINE FIELD IF NOT EXISTS note ON note_file TYPE record<note>;
99 DEFINE FIELD IF NOT EXISTS name ON note_file TYPE string;144 DEFINE FIELD IF NOT EXISTS name ON note_file TYPE string;
src/state.rsmodified+81 -0
@@ -3,6 +3,8 @@ use std::path::PathBuf;
3 use std::sync::atomic::{AtomicBool, Ordering};3 use std::sync::atomic::{AtomicBool, Ordering};
4 use std::sync::{Arc, Mutex};4 use std::sync::{Arc, Mutex};
5 5
6+use tokio::sync::broadcast;
7+
6 use crate::ai::AiBridge;8 use crate::ai::AiBridge;
7 use crate::database::Database;9 use crate::database::Database;
8 use crate::rate_limit::{RateLimitConfig, UserRateLimiter};10 use crate::rate_limit::{RateLimitConfig, UserRateLimiter};
@@ -28,6 +30,8 @@ pub struct AppState {
28 pub chatbot_limit: UserRateLimiter,30 pub chatbot_limit: UserRateLimiter,
29 /// Who is inside which exam room right now (see [`ExamPresence`]).31 /// Who is inside which exam room right now (see [`ExamPresence`]).
30 pub exam_presence: ExamPresence,32 pub exam_presence: ExamPresence,
33+ /// Live stroke fan-out for the shared whiteboards (see [`BoardHub`]).
34+ pub board_hub: BoardHub,
31 /// Whether the database socket answered its last ping (see [`DbHealth`]).35 /// Whether the database socket answered its last ping (see [`DbHealth`]).
32 pub db_up: DbHealth,36 pub db_up: DbHealth,
33 /// The QUIC bridge to the AI services, when one is configured37 /// The QUIC bridge to the AI services, when one is configured
@@ -116,10 +120,87 @@ impl ExamPresence {
116 }120 }
117 }121 }
118 122
123+/// One broadcast channel per live whiteboard, keyed by the board's record key,
124+/// so a stroke saved by one socket reaches every *other* socket in that board.
125+/// Nothing else in this codebase fans out β€” an exam room only ever replies to
126+/// the socket that spoke β€” so this is the only multi-subscriber push we have.
127+///
128+/// The socket count exists to drop the entry when the last socket leaves;
129+/// without it the map would keep one channel per board ever opened, forever.
130+///
131+/// The inner mutex only guards the map (never held across an await β€” keep it
132+/// that way): every method locks, mutates or clones out, and drops the guard
133+/// before the caller can await anything.
134+#[derive(Clone, Default)]
135+pub struct BoardHub(Arc<Mutex<HashMap<String, (broadcast::Sender<String>, usize)>>>);
136+
137+impl BoardHub {
138+ /// Count one socket into `board` and hand back its stream of other
139+ /// people's frames, creating the channel on the first join.
140+ pub fn subscribe(&self, board: &str) -> broadcast::Receiver<String> {
141+ let mut boards = self.0.lock().expect("board hub lock");
142+ let room = boards
143+ .entry(board.to_string())
144+ .or_insert_with(|| (broadcast::channel(crate::constant::BOARD_HUB_CAPACITY).0, 0));
145+ room.1 += 1;
146+ room.0.subscribe()
147+ }
148+
149+ /// Push `frame` to every socket currently subscribed to `board`. A send
150+ /// with no receivers left is the normal empty-room case, not a failure.
151+ pub fn publish(&self, board: &str, frame: String) {
152+ let sender = {
153+ let boards = self.0.lock().expect("board hub lock");
154+ boards.get(board).map(|room| room.0.clone())
155+ };
156+ if let Some(sender) = sender {
157+ let _ = sender.send(frame);
158+ }
159+ }
160+
161+ /// Count one socket out of `board`; the last one out drops the channel.
162+ pub fn leave(&self, board: &str) {
163+ let mut boards = self.0.lock().expect("board hub lock");
164+ match boards.get_mut(board) {
165+ Some(room) if room.1 > 1 => room.1 -= 1,
166+ // Last one out, or an unbalanced leave β€” either way the room is
167+ // empty, and a stale entry would leak for the process's lifetime.
168+ _ => {
169+ boards.remove(board);
170+ }
171+ }
172+ }
173+}
174+
119 #[cfg(test)]175 #[cfg(test)]
120 mod tests {176 mod tests {
121 use super::*;177 use super::*;
122 178
179+ #[tokio::test]
180+ async fn every_subscriber_gets_the_stroke_and_the_room_is_reclaimed() {
181+ let hub = BoardHub::default();
182+ let mut alice = hub.subscribe("board-a");
183+ let mut bob = hub.subscribe("board-a");
184+ hub.publish("board-a", "stroke".to_string());
185+ assert_eq!(alice.recv().await.expect("alice"), "stroke");
186+ assert_eq!(bob.recv().await.expect("bob"), "stroke");
187+
188+ // Boards are independent, and publishing into an empty one is a no-op.
189+ hub.publish("board-b", "nobody home".to_string());
190+ assert!(!hub.0.lock().unwrap().contains_key("board-b"));
191+
192+ hub.leave("board-a");
193+ assert!(
194+ hub.0.lock().unwrap().contains_key("board-a"),
195+ "one socket of two out keeps the room"
196+ );
197+ hub.leave("board-a");
198+ assert!(
199+ hub.0.lock().unwrap().is_empty(),
200+ "the last socket out must drop the entry, or the map leaks"
201+ );
202+ }
203+
123 #[tokio::test]204 #[tokio::test]
124 async fn only_the_last_socket_out_is_a_real_exit() {205 async fn only_the_last_socket_out_is_a_real_exit() {
125 let presence = ExamPresence::default();206 let presence = ExamPresence::default();
src/web/boards.rsadded+640 -0
@@ -0,0 +1,640 @@
1+//! The whiteboard's HTTP surface: open a board, read its roster, its live
2+//! canvas and its whole history, and run the creator's four commands (clear,
3+//! lock, close, delete). Live drawing itself rides the board-room WebSocket
4+//! next door; everything here is the REST half it sits beside.
5+//!
6+//! The permission model is two predicates and nothing else
7+//! ([`Board::is_participant`], [`Board::is_creator`]), applied in one order on
8+//! every route: a non-participant gets a **404** even for a board that plainly
9+//! exists (a 403 would confirm it β€” see the rationale at `src/lib.rs`), while a
10+//! participant who is not the creator gets a **403** on the four commands. They
11+//! are already rendering the board and its strokes, so hiding it from them
12+//! there would be a lie their client cannot act on (same two-tier line as
13+//! [`super::homework`]).
14+//!
15+//! Every mutation a live room must notice ends in a `board_hub` publish, and
16+//! one of them is a permission fix rather than a nicety: a participant dropped
17+//! mid-session keeps drawing over an already-open socket until the room hears
18+//! about it, so a roster change *must* fan out.
19+
20+use axum::Json;
21+use axum::extract::{Path, Query, State};
22+use axum::http::StatusCode;
23+use serde::{Deserialize, Serialize};
24+use serde_json::json;
25+use utoipa::ToSchema;
26+use utoipa_axum::router::OpenApiRouter;
27+use utoipa_axum::routes;
28+
29+use crate::constant::MAX_BOARD_PARTICIPANTS;
30+use crate::database::Database;
31+use crate::domain::board::{Board, BoardId, BoardTitle};
32+use crate::domain::board_stroke::BoardStroke;
33+use crate::domain::user::{User, UserId};
34+use crate::error::{AppError, ErrorResponse, ValidationError};
35+use crate::state::AppState;
36+
37+use super::{CurrentUser, Page, PageParams, paginate, set_or_clear};
38+
39+pub fn routes() -> OpenApiRouter<AppState> {
40+ OpenApiRouter::new()
41+ .routes(routes!(create_board, list_boards))
42+ .routes(routes!(get_board, update_board, delete_board))
43+ .routes(routes!(list_strokes))
44+ .routes(routes!(list_history))
45+ .routes(routes!(list_epochs))
46+ .routes(routes!(clear_board))
47+ .routes(routes!(close_board))
48+}
49+
50+/// The board, or a 404 β€” including the deliberate 404 for a caller who is not
51+/// on it. Every route starts here, so existence never leaks.
52+async fn board_for(id: &str, user: &User, db: &Database) -> Result<Board, AppError> {
53+ let board = Board::read(&BoardId::from_key(id), db)
54+ .await?
55+ .ok_or(AppError::NotFound)?;
56+ if !board.is_participant(user.get_id()) {
57+ return Err(AppError::NotFound);
58+ }
59+ Ok(board)
60+}
61+
62+/// The creator-only gate. A 403, never a 404: the caller reached it through
63+/// [`board_for`], so they are a participant and the board's existence is
64+/// already theirs to see.
65+fn ensure_creator(board: &Board, user: &User) -> Result<(), AppError> {
66+ if !board.is_creator(user.get_id()) {
67+ return Err(AppError::Forbidden(
68+ "only the board's creator can clear, lock, close or delete it",
69+ ));
70+ }
71+ Ok(())
72+}
73+
74+/// The invite list off the wire: deduped, capped, and every id resolved against
75+/// a real user. The cap is applied *before* the lookups (the domain caps too,
76+/// but only after this loop would have run one read per id), and an unknown id
77+/// is a 400 rather than a silently dropped invitation.
78+///
79+/// The creator is a participant by construction, so they are neither injected
80+/// into the list nor rejected from it.
81+async fn resolve_participants(
82+ ids: Option<Vec<String>>,
83+ db: &Database,
84+) -> Result<Vec<UserId>, AppError> {
85+ let Some(mut ids) = ids else {
86+ return Ok(Vec::new());
87+ };
88+ ids.sort();
89+ ids.dedup();
90+ if ids.len() > MAX_BOARD_PARTICIPANTS {
91+ return Err(AppError::Validation(ValidationError::TooLong {
92+ field: "participants",
93+ max: MAX_BOARD_PARTICIPANTS,
94+ got: ids.len(),
95+ }));
96+ }
97+ let mut users = Vec::with_capacity(ids.len());
98+ for id in ids {
99+ let user = UserId::from_key(&id);
100+ if User::read(&user, db).await?.is_none() {
101+ return Err(AppError::Validation(ValidationError::Invalid {
102+ field: "participants",
103+ reason: "every participant must be an existing user",
104+ }));
105+ }
106+ users.push(user);
107+ }
108+ Ok(users)
109+}
110+
111+/// Push one frame to whoever is in the room right now. An empty room is the
112+/// normal case, not a failure.
113+fn fan_out(st: &AppState, board: &BoardId, frame: serde_json::Value) {
114+ st.board_hub.publish(board.key(), frame.to_string());
115+}
116+
117+#[derive(Serialize, ToSchema)]
118+struct BoardResponse {
119+ id: String,
120+ title: String,
121+ /// The creator: draws, and is the only one who may clear, lock, close or
122+ /// delete. Always a participant without appearing in `participants`.
123+ creator: String,
124+ /// The invited user ids. Everyone here draws.
125+ participants: Vec<String>,
126+ /// Drawing is paused while `true`; the creator toggles it.
127+ locked: bool,
128+ locked_by: Option<String>,
129+ /// UTC unix-milliseconds, `null` while unlocked.
130+ locked_at: Option<i64>,
131+ /// The live canvas' generation. A clear bumps it; strokes from earlier
132+ /// epochs stay stored and replayable through `/history`.
133+ epoch: i64,
134+ /// Stamped when the board was closed β€” by its creator or by the lifetime
135+ /// stroke cap. A closed board is permanently read-only, never deleted.
136+ closed_at: Option<i64>,
137+ created_at: i64,
138+}
139+
140+impl BoardResponse {
141+ fn new(board: &Board) -> Self {
142+ Self {
143+ id: board.get_id().key().to_string(),
144+ title: board.get_title().as_str().to_string(),
145+ creator: board.get_creator().key().to_string(),
146+ participants: board
147+ .get_participants()
148+ .iter()
149+ .map(|user| user.key().to_string())
150+ .collect(),
151+ locked: board.is_locked(),
152+ locked_by: board.get_locked_by().map(|user| user.key().to_string()),
153+ locked_at: board.get_locked_at().map(|at| at.as_millis()),
154+ epoch: board.get_epoch(),
155+ closed_at: board.get_closed_at().map(|at| at.as_millis()),
156+ created_at: board.get_created_at().as_millis(),
157+ }
158+ }
159+}
160+
161+/// One row of the append-only stroke log. Both kinds ride this shape: a
162+/// `stroke` carries `payload`, a `clear` marker carries `count` β€” the final
163+/// stroke count of the epoch it closed β€” and never the other way round.
164+#[derive(Serialize, ToSchema)]
165+struct StrokeResponse {
166+ id: String,
167+ author: String,
168+ /// `stroke` or `clear`.
169+ kind: String,
170+ /// The client's serialized mark. `null` on a `clear` marker.
171+ payload: Option<String>,
172+ /// The closed epoch's final stroke count. Present only on a `clear`.
173+ count: Option<i64>,
174+ epoch: i64,
175+ created_at: i64,
176+}
177+
178+impl StrokeResponse {
179+ fn new(stroke: &BoardStroke) -> Self {
180+ Self {
181+ id: stroke.get_id().key().to_string(),
182+ author: stroke.get_author().key().to_string(),
183+ kind: stroke.get_kind().to_string(),
184+ payload: stroke.get_payload().map(str::to_string),
185+ count: stroke.get_count(),
186+ epoch: stroke.get_epoch(),
187+ created_at: stroke.get_created_at().as_millis(),
188+ }
189+ }
190+}
191+
192+#[derive(Deserialize, ToSchema)]
193+struct CreateBoard {
194+ #[schema(max_length = 200)]
195+ title: String,
196+ /// Who may draw, besides the creator. Omit or send an empty list to open a
197+ /// board alone and invite later.
198+ #[schema(max_items = 50)]
199+ participant_ids: Option<Vec<String>>,
200+}
201+
202+/// Open a whiteboard. The caller becomes its creator β€” the only one who may
203+/// clear, lock, close or delete it β€” and everyone named in `participant_ids`
204+/// may draw on it. `409` once the caller holds `max_boards_per_creator` boards
205+/// (`GET /limits`); delete one to free a seat.
206+#[utoipa::path(
207+ post,
208+ path = "/",
209+ tag = "boards",
210+ security(("session_cookie" = [])),
211+ request_body = CreateBoard,
212+ responses(
213+ (status = 201, description = "The new board", body = BoardResponse),
214+ (status = 400, description = "Invalid title, or a participant list that is too long or names an unknown user", body = ErrorResponse),
215+ (status = 401, description = "Not authenticated", body = ErrorResponse),
216+ (status = 409, description = "The caller already holds the maximum number of boards", body = ErrorResponse),
217+ ),
218+)]
219+async fn create_board(
220+ State(st): State<AppState>,
221+ CurrentUser(user): CurrentUser,
222+ Json(req): Json<CreateBoard>,
223+) -> Result<(StatusCode, Json<BoardResponse>), AppError> {
224+ let title = BoardTitle::try_new(&req.title)?;
225+ let participants = resolve_participants(req.participant_ids, &st.db).await?;
226+ let board = Board::create(user.get_id(), title, participants, &st.db).await?;
227+ Ok((StatusCode::CREATED, Json(BoardResponse::new(&board))))
228+}
229+
230+/// Every board the caller may open β€” the ones they created and the ones they
231+/// were invited to β€” newest first. Paged via `?limit=&offset=` (omit `limit`
232+/// for all of them).
233+#[utoipa::path(
234+ get,
235+ path = "/",
236+ tag = "boards",
237+ security(("session_cookie" = [])),
238+ params(PageParams),
239+ responses(
240+ (status = 200, description = "A page of the caller's boards", body = Page<BoardResponse>),
241+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
242+ (status = 401, description = "Not authenticated", body = ErrorResponse),
243+ ),
244+)]
245+async fn list_boards(
246+ State(st): State<AppState>,
247+ CurrentUser(user): CurrentUser,
248+ Query(page): Query<PageParams>,
249+) -> Result<Json<Page<BoardResponse>>, AppError> {
250+ let (limit, offset) = page.resolve()?;
251+ let (boards, total) = Board::list_for_user(user.get_id(), limit, offset, &st.db).await?;
252+ let items = boards.iter().map(BoardResponse::new).collect();
253+ Ok(Json(Page::new(items, total, limit, offset)))
254+}
255+
256+/// Fetch one board. A caller who is neither its creator nor one of its
257+/// participants gets a `404`, not a `403` β€” an outsider must not learn that a
258+/// board exists.
259+#[utoipa::path(
260+ get,
261+ path = "/{id}",
262+ tag = "boards",
263+ security(("session_cookie" = [])),
264+ params(("id" = String, Path, description = "Board id")),
265+ responses(
266+ (status = 200, description = "The board", body = BoardResponse),
267+ (status = 401, description = "Not authenticated", body = ErrorResponse),
268+ (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
269+ ),
270+)]
271+async fn get_board(
272+ State(st): State<AppState>,
273+ CurrentUser(user): CurrentUser,
274+ Path(id): Path<String>,
275+) -> Result<Json<BoardResponse>, AppError> {
276+ let board = board_for(&id, &user, &st.db).await?;
277+ Ok(Json(BoardResponse::new(&board)))
278+}
279+
280+/// The live canvas: the current epoch's strokes, oldest first, paged via
281+/// `?limit=&offset=`. This is what a client draws to catch up β€” earlier epochs
282+/// are still stored, and read through `/history`.
283+#[utoipa::path(
284+ get,
285+ path = "/{id}/strokes",
286+ tag = "boards",
287+ security(("session_cookie" = [])),
288+ params(("id" = String, Path, description = "Board id"), PageParams),
289+ responses(
290+ (status = 200, description = "A page of the current epoch's strokes", body = Page<StrokeResponse>),
291+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
292+ (status = 401, description = "Not authenticated", body = ErrorResponse),
293+ (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
294+ ),
295+)]
296+async fn list_strokes(
297+ State(st): State<AppState>,
298+ CurrentUser(user): CurrentUser,
299+ Path(id): Path<String>,
300+ Query(page): Query<PageParams>,
301+) -> Result<Json<Page<StrokeResponse>>, AppError> {
302+ let (limit, offset) = page.resolve()?;
303+ let board = board_for(&id, &user, &st.db).await?;
304+ // The current epoch has no `clear` marker yet β€” a marker is written with
305+ // the epoch it *closed* β€” so scoping history to it is exactly the live
306+ // canvas, and needs no second query shape.
307+ let (strokes, total) = BoardStroke::history(
308+ board.get_id(),
309+ Some(board.get_epoch()),
310+ limit,
311+ offset,
312+ &st.db,
313+ )
314+ .await?;
315+ let items = strokes.iter().map(StrokeResponse::new).collect();
316+ Ok(Json(Page::new(items, total, limit, offset)))
317+}
318+
319+#[derive(Deserialize, utoipa::IntoParams)]
320+struct HistoryParams {
321+ /// One epoch's rows only. Omit for the board's whole life, oldest first.
322+ epoch: Option<i64>,
323+}
324+
325+/// The whole stroke log, oldest first β€” every epoch the board ever had, or the
326+/// single `?epoch=` named. A clear deletes nothing, so this replays the entire
327+/// session; the `clear` markers in the stream are where one epoch ended.
328+/// Paged via `?limit=&offset=`.
329+#[utoipa::path(
330+ get,
331+ path = "/{id}/history",
332+ tag = "boards",
333+ security(("session_cookie" = [])),
334+ params(("id" = String, Path, description = "Board id"), HistoryParams, PageParams),
335+ responses(
336+ (status = 200, description = "A page of the stroke log", body = Page<StrokeResponse>),
337+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
338+ (status = 401, description = "Not authenticated", body = ErrorResponse),
339+ (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
340+ ),
341+)]
342+async fn list_history(
343+ State(st): State<AppState>,
344+ CurrentUser(user): CurrentUser,
345+ Path(id): Path<String>,
346+ Query(scope): Query<HistoryParams>,
347+ Query(page): Query<PageParams>,
348+) -> Result<Json<Page<StrokeResponse>>, AppError> {
349+ let (limit, offset) = page.resolve()?;
350+ let board = board_for(&id, &user, &st.db).await?;
351+ let (strokes, total) =
352+ BoardStroke::history(board.get_id(), scope.epoch, limit, offset, &st.db).await?;
353+ let items = strokes.iter().map(StrokeResponse::new).collect();
354+ Ok(Json(Page::new(items, total, limit, offset)))
355+}
356+
357+/// The epoch index: every `clear` marker this board has, oldest first. Each one
358+/// carries the epoch it closed (`epoch`), that epoch's final stroke count
359+/// (`count`), who cleared and when β€” which is all a client needs to offer
360+/// "replay session 3" without scanning the log. The markers *are* the index, so
361+/// the current (unclosed) epoch is deliberately absent. Paged via
362+/// `?limit=&offset=`.
363+#[utoipa::path(
364+ get,
365+ path = "/{id}/epochs",
366+ tag = "boards",
367+ security(("session_cookie" = [])),
368+ params(("id" = String, Path, description = "Board id"), PageParams),
369+ responses(
370+ (status = 200, description = "A page of the board's clear markers", body = Page<StrokeResponse>),
371+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
372+ (status = 401, description = "Not authenticated", body = ErrorResponse),
373+ (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
374+ ),
375+)]
376+async fn list_epochs(
377+ State(st): State<AppState>,
378+ CurrentUser(user): CurrentUser,
379+ Path(id): Path<String>,
380+ Query(page): Query<PageParams>,
381+) -> Result<Json<Page<StrokeResponse>>, AppError> {
382+ let (limit, offset) = page.resolve()?;
383+ let board = board_for(&id, &user, &st.db).await?;
384+ let markers = BoardStroke::epochs(board.get_id(), &st.db).await?;
385+ // Paged in the web layer: the marker list is one bounded read, and a board
386+ // has at most one marker per clear.
387+ let items = paginate(&markers, limit, offset)
388+ .iter()
389+ .map(StrokeResponse::new)
390+ .collect();
391+ Ok(Json(Page::new(items, markers.len() as i64, limit, offset)))
392+}
393+
394+#[derive(Deserialize, ToSchema)]
395+struct UpdateBoard {
396+ /// Re-title. Any participant may. Omit to keep.
397+ #[schema(max_length = 200)]
398+ title: Option<String>,
399+ /// Replace the invite list β€” **creator only**. Omit to keep; send `null`
400+ /// (or an empty list) to leave the creator alone on the board.
401+ #[serde(default, deserialize_with = "set_or_clear")]
402+ #[schema(value_type = Option<Vec<String>>, max_items = 50)]
403+ participants: Option<Option<Vec<String>>>,
404+ /// Pause (`true`) or resume (`false`) drawing β€” **creator only**. Omit to
405+ /// keep.
406+ locked: Option<bool>,
407+}
408+
409+/// Edit a board. Re-titling is open to every participant; changing the invite
410+/// list or the lock is the creator's alone (`403` for anyone else on the
411+/// board). Omitted fields keep their value.
412+///
413+/// A roster change and a lock change are both fanned out to the live room at
414+/// once β€” a participant removed here would otherwise keep drawing over the
415+/// socket they already hold.
416+#[utoipa::path(
417+ patch,
418+ path = "/{id}",
419+ tag = "boards",
420+ security(("session_cookie" = [])),
421+ params(("id" = String, Path, description = "Board id")),
422+ request_body = UpdateBoard,
423+ responses(
424+ (status = 200, description = "The updated board", body = BoardResponse),
425+ (status = 400, description = "Invalid title, or a participant list that is too long or names an unknown user", body = ErrorResponse),
426+ (status = 401, description = "Not authenticated", body = ErrorResponse),
427+ (status = 403, description = "Only the creator may change the participants or the lock", body = ErrorResponse),
428+ (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
429+ ),
430+)]
431+async fn update_board(
432+ State(st): State<AppState>,
433+ CurrentUser(user): CurrentUser,
434+ Path(id): Path<String>,
435+ Json(req): Json<UpdateBoard>,
436+) -> Result<Json<BoardResponse>, AppError> {
437+ let mut board = board_for(&id, &user, &st.db).await?;
438+ if req.participants.is_some() || req.locked.is_some() {
439+ ensure_creator(&board, &user)?;
440+ }
441+
442+ if let Some(title) = req.title.as_deref() {
443+ board = board.set_title(BoardTitle::try_new(title)?, &st.db).await?;
444+ }
445+ if let Some(participants) = req.participants {
446+ let participants = resolve_participants(participants, &st.db).await?;
447+ board = board.set_participants(participants, &st.db).await?;
448+ fan_out(
449+ &st,
450+ board.get_id(),
451+ json!({
452+ "type": "participants",
453+ "creator": board.get_creator().key(),
454+ "participants": board
455+ .get_participants()
456+ .iter()
457+ .map(|user| user.key())
458+ .collect::<Vec<_>>(),
459+ }),
460+ );
461+ }
462+ if let Some(locked) = req.locked {
463+ board = board.set_locked(locked, user.get_id(), &st.db).await?;
464+ fan_out(
465+ &st,
466+ board.get_id(),
467+ json!({"type": "locked", "locked": locked, "by": user.get_id().key()}),
468+ );
469+ }
470+ Ok(Json(BoardResponse::new(&board)))
471+}
472+
473+/// Empty the canvas β€” creator only. **Nothing is deleted**: the board's epoch
474+/// is bumped and a `clear` marker is appended carrying the closed epoch's final
475+/// stroke count, so the live canvas is blank while every mark ever drawn stays
476+/// readable through `/history`. Also resets the live-canvas cap, which is how a
477+/// board that answered "clear it to keep drawing" is recovered. `409` on a
478+/// closed board.
479+#[utoipa::path(
480+ post,
481+ path = "/{id}/clear",
482+ tag = "boards",
483+ security(("session_cookie" = [])),
484+ params(("id" = String, Path, description = "Board id")),
485+ responses(
486+ (status = 201, description = "The clear marker that closed the epoch", body = StrokeResponse),
487+ (status = 401, description = "Not authenticated", body = ErrorResponse),
488+ (status = 403, description = "Only the creator may clear the board", body = ErrorResponse),
489+ (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
490+ (status = 409, description = "The board is closed", body = ErrorResponse),
491+ ),
492+)]
493+async fn clear_board(
494+ State(st): State<AppState>,
495+ CurrentUser(user): CurrentUser,
496+ Path(id): Path<String>,
497+) -> Result<(StatusCode, Json<StrokeResponse>), AppError> {
498+ let board = board_for(&id, &user, &st.db).await?;
499+ ensure_creator(&board, &user)?;
500+ let marker = BoardStroke::clear(board.get_id(), user.get_id(), &st.db).await?;
501+ // The marker carries the epoch it *closed*; the room's new canvas is the
502+ // next one.
503+ fan_out(
504+ &st,
505+ board.get_id(),
506+ json!({
507+ "type": "cleared",
508+ "epoch": marker.get_epoch() + 1,
509+ "by": user.get_id().key(),
510+ }),
511+ );
512+ Ok((StatusCode::CREATED, Json(StrokeResponse::new(&marker))))
513+}
514+
515+/// Retire the board β€” creator only. It becomes permanently read-only: no more
516+/// strokes and no more clears, while every stroke and every epoch stays
517+/// readable. Idempotent: closing an already-closed board returns it with its
518+/// original `closed_at` rather than re-stamping. There is no reopen β€” a closed
519+/// board is finished, and a new one is cheap.
520+#[utoipa::path(
521+ post,
522+ path = "/{id}/close",
523+ tag = "boards",
524+ security(("session_cookie" = [])),
525+ params(("id" = String, Path, description = "Board id")),
526+ responses(
527+ (status = 200, description = "The closed board", body = BoardResponse),
528+ (status = 401, description = "Not authenticated", body = ErrorResponse),
529+ (status = 403, description = "Only the creator may close the board", body = ErrorResponse),
530+ (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
531+ ),
532+)]
533+async fn close_board(
534+ State(st): State<AppState>,
535+ CurrentUser(user): CurrentUser,
536+ Path(id): Path<String>,
537+) -> Result<Json<BoardResponse>, AppError> {
538+ let board = board_for(&id, &user, &st.db).await?;
539+ ensure_creator(&board, &user)?;
540+ let board = board.close(&st.db).await?;
541+ fan_out(
542+ &st,
543+ board.get_id(),
544+ json!({
545+ "type": "closed",
546+ "closed_at": board.get_closed_at().map(|at| at.as_millis()),
547+ }),
548+ );
549+ Ok(Json(BoardResponse::new(&board)))
550+}
551+
552+/// Delete the board and its whole stroke history β€” creator only, and the one
553+/// operation in this system that really destroys marks (a clear never does).
554+/// It also frees the creator's board seat. Use `/close` to retire a board while
555+/// keeping it readable.
556+#[utoipa::path(
557+ delete,
558+ path = "/{id}",
559+ tag = "boards",
560+ security(("session_cookie" = [])),
561+ params(("id" = String, Path, description = "Board id")),
562+ responses(
563+ (status = 204, description = "Deleted, with every stroke it held"),
564+ (status = 401, description = "Not authenticated", body = ErrorResponse),
565+ (status = 403, description = "Only the creator may delete the board", body = ErrorResponse),
566+ (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
567+ ),
568+)]
569+async fn delete_board(
570+ State(st): State<AppState>,
571+ CurrentUser(user): CurrentUser,
572+ Path(id): Path<String>,
573+) -> Result<StatusCode, AppError> {
574+ let board = board_for(&id, &user, &st.db).await?;
575+ ensure_creator(&board, &user)?;
576+ let id = board.get_id().clone();
577+ board.delete(&st.db).await?;
578+ // Told after the row is gone: a room that acts on this and then re-reads
579+ // must find nothing, not a board about to disappear.
580+ fan_out(&st, &id, json!({"type": "deleted"}));
581+ Ok(StatusCode::NO_CONTENT)
582+}
583+
584+#[cfg(test)]
585+mod tests {
586+ use super::*;
587+
588+ /// The security boundary of this module, in one test: an outsider is told
589+ /// the board does not exist, an insider without rights is told it is not
590+ /// theirs to command. Swapping those two leaks the school's board list on
591+ /// one side and hides a rendered board from its own participant on the
592+ /// other.
593+ #[tokio::test]
594+ async fn an_outsider_gets_404_and_a_participant_gets_403() {
595+ let db = crate::database::init_mem().await.unwrap();
596+ db.query(
597+ "CREATE user:c SET username = 'c', password_hash = 'x';
598+ CREATE user:p SET username = 'p', password_hash = 'x';
599+ CREATE user:s SET username = 's', password_hash = 'x';",
600+ )
601+ .await
602+ .unwrap()
603+ .check()
604+ .unwrap();
605+ let who = async |key: &str| {
606+ User::read(&UserId::from_key(key), &db)
607+ .await
608+ .unwrap()
609+ .unwrap()
610+ };
611+ let (creator, participant, stranger) = (who("c").await, who("p").await, who("s").await);
612+ let board = Board::create(
613+ creator.get_id(),
614+ BoardTitle::try_new("Geometri").unwrap(),
615+ vec![participant.get_id().clone()],
616+ &db,
617+ )
618+ .await
619+ .unwrap();
620+ let id = board.get_id().key().to_string();
621+
622+ assert!(matches!(
623+ board_for(&id, &stranger, &db).await,
624+ Err(AppError::NotFound)
625+ ));
626+ // A board that does not exist at all answers the same way, so the two
627+ // are indistinguishable from outside.
628+ assert!(matches!(
629+ board_for("nope", &creator, &db).await,
630+ Err(AppError::NotFound)
631+ ));
632+
633+ let seen = board_for(&id, &participant, &db).await.unwrap();
634+ assert!(matches!(
635+ ensure_creator(&seen, &participant),
636+ Err(AppError::Forbidden(_))
637+ ));
638+ assert!(ensure_creator(&board_for(&id, &creator, &db).await.unwrap(), &creator).is_ok());
639+ }
640+}
src/web/limits.rsmodified+42 -0
@@ -267,6 +267,36 @@ struct ChatbotLimits {
267 default_max_threads: i64,267 default_max_threads: i64,
268 }268 }
269 269
270+/// A collaborative whiteboard: its title, its roster, and the two growth caps
271+/// that decide when a canvas must be cleared and when a board is finished.
272+#[derive(Serialize, ToSchema)]
273+struct BoardLimits {
274+ max_title_len: usize,
275+ /// People the creator may name onto one board. Every participant draws, so
276+ /// this also bounds a room's writer count.
277+ max_participants: usize,
278+ /// Ceiling on one stroke's serialized payload, bytes.
279+ max_stroke_payload_len: usize,
280+ /// The *live* canvas cap: strokes since the last clear. Hitting it is
281+ /// recoverable β€” the creator clears, the canvas empties, the history is
282+ /// kept, and drawing resumes.
283+ max_epoch_strokes: i64,
284+ /// The *lifetime* storage cap, which never resets because a clear keeps its
285+ /// history. Hitting it makes the board permanently read-only: it stays
286+ /// fully readable and replayable, and a new board must be opened.
287+ max_board_strokes: i64,
288+ /// Boards one creating user may hold. Deleting a board frees a seat.
289+ max_boards_per_creator: i64,
290+ /// The accepted stroke kinds. `clear` is a marker that ends an epoch, not a
291+ /// deletion.
292+ #[schema(example = json!(["stroke", "clear"]))]
293+ stroke_kinds: Vec<&'static str>,
294+ /// Cadence of the board-room WebSocket's keepalive ticks, seconds.
295+ ws_tick_secs: u64,
296+ /// Ceiling on a `board_id` sent over the board-room WebSocket.
297+ ws_max_board_id_len: usize,
298+}
299+
270 /// Bounds on the school-editable lists in `PATCH /settings`.300 /// Bounds on the school-editable lists in `PATCH /settings`.
271 #[derive(Serialize, ToSchema)]301 #[derive(Serialize, ToSchema)]
272 struct SettingsLimits {302 struct SettingsLimits {
@@ -333,6 +363,7 @@ struct LimitsResponse {
333 meal: MealLimits,363 meal: MealLimits,
334 payment: PaymentLimits,364 payment: PaymentLimits,
335 chatbot: ChatbotLimits,365 chatbot: ChatbotLimits,
366+ board: BoardLimits,
336 settings: SettingsLimits,367 settings: SettingsLimits,
337 request: RequestLimits,368 request: RequestLimits,
338 rate: RateLimits,369 rate: RateLimits,
@@ -467,6 +498,17 @@ impl LimitsResponse {
467 max_max_threads: MAX_MAX_CHATBOT_THREADS,498 max_max_threads: MAX_MAX_CHATBOT_THREADS,
468 default_max_threads: DEFAULT_MAX_CHATBOT_THREADS,499 default_max_threads: DEFAULT_MAX_CHATBOT_THREADS,
469 },500 },
501+ board: BoardLimits {
502+ max_title_len: MAX_BOARD_TITLE_LEN,
503+ max_participants: MAX_BOARD_PARTICIPANTS,
504+ max_stroke_payload_len: MAX_STROKE_PAYLOAD_LEN,
505+ max_epoch_strokes: MAX_EPOCH_STROKES,
506+ max_board_strokes: MAX_BOARD_STROKES,
507+ max_boards_per_creator: MAX_BOARDS_PER_CREATOR,
508+ stroke_kinds: BOARD_STROKE_KINDS.to_vec(),
509+ ws_tick_secs: BOARD_WS_TICK_SECS,
510+ ws_max_board_id_len: MAX_BOARD_ID_LEN,
511+ },
470 settings: SettingsLimits {512 settings: SettingsLimits {
471 max_list_len: MAX_SETTINGS_LIST_LEN,513 max_list_len: MAX_SETTINGS_LIST_LEN,
472 max_item_len: MAX_SETTINGS_ITEM_LEN,514 max_item_len: MAX_SETTINGS_ITEM_LEN,
src/web/mod.rsmodified+1 -0
@@ -8,6 +8,7 @@ pub mod appointments;
8 pub mod attendance;8 pub mod attendance;
9 pub mod auth;9 pub mod auth;
10 pub mod bank_questions;10 pub mod bank_questions;
11+pub mod boards;
11 pub mod chatbot;12 pub mod chatbot;
12 pub mod courses;13 pub mod courses;
13 pub mod etag;14 pub mod etag;
tests/ai_bridge.rsmodified+2 -0
@@ -807,6 +807,7 @@ async fn fetch_certificate(ai: Option<AiBridge>) -> (axum::http::StatusCode, Val
807 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),807 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
808 chatbot_limit: Default::default(),808 chatbot_limit: Default::default(),
809 exam_presence: Default::default(),809 exam_presence: Default::default(),
810+ board_hub: Default::default(),
810 db_up: Default::default(),811 db_up: Default::default(),
811 ai,812 ai,
812 });813 });
@@ -940,6 +941,7 @@ async fn chat_app(bridge: &AiBridge) -> (Router, Database) {
940 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),941 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
941 chatbot_limit: Default::default(),942 chatbot_limit: Default::default(),
942 exam_presence: Default::default(),943 exam_presence: Default::default(),
944+ board_hub: Default::default(),
943 db_up: Default::default(),945 db_up: Default::default(),
944 ai: Some(bridge.clone()),946 ai: Some(bridge.clone()),
945 });947 });
tests/common/mod.rsmodified+1 -0
@@ -49,6 +49,7 @@ pub async fn app_and_db() -> (Router, Database) {
49 rate_limit: RateLimitConfig::unlimited(),49 rate_limit: RateLimitConfig::unlimited(),
50 chatbot_limit: Default::default(),50 chatbot_limit: Default::default(),
51 exam_presence: Default::default(),51 exam_presence: Default::default(),
52+ board_hub: Default::default(),
52 db_up: Default::default(),53 db_up: Default::default(),
53 ai: None,54 ai: None,
54 });55 });
tests/e2e.rsmodified+1 -0
@@ -29,6 +29,7 @@ async fn spawn_server_with_ai(ai: Option<hezarfen_backend::ai::AiBridge>) -> (St
29 rate_limit: RateLimitConfig::unlimited(),29 rate_limit: RateLimitConfig::unlimited(),
30 chatbot_limit: Default::default(),30 chatbot_limit: Default::default(),
31 exam_presence: Default::default(),31 exam_presence: Default::default(),
32+ board_hub: Default::default(),
32 db_up: Default::default(),33 db_up: Default::default(),
33 ai,34 ai,
34 });35 });
tests/integration.rsmodified+17 -0
@@ -159,6 +159,7 @@ async fn limits_still_answers_while_the_database_is_down() {
159 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),159 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
160 chatbot_limit: Default::default(),160 chatbot_limit: Default::default(),
161 exam_presence: Default::default(),161 exam_presence: Default::default(),
162+ board_hub: Default::default(),
162 db_up: db_up.clone(),163 db_up: db_up.clone(),
163 ai: None,164 ai: None,
164 });165 });
@@ -382,6 +383,19 @@ async fn protected_routes_require_session() {
382 ("GET", "/pomodoro/u"),383 ("GET", "/pomodoro/u"),
383 ("GET", "/attendance/me"),384 ("GET", "/attendance/me"),
384 ("GET", "/attendance/u"),385 ("GET", "/attendance/u"),
386+ ("GET", "/boards"),
387+ ("POST", "/boards"),
388+ ("GET", "/boards/x"),
389+ ("PATCH", "/boards/x"),
390+ ("DELETE", "/boards/x"),
391+ ("GET", "/boards/x/strokes"),
392+ ("GET", "/boards/x/history"),
393+ ("GET", "/boards/x/epochs"),
394+ ("POST", "/boards/x/clear"),
395+ ("POST", "/boards/x/close"),
396+ // The board room authenticates before it upgrades, so a rejection is
397+ // an HTTP status here and not an instant close.
398+ ("GET", "/boards/x/ws"),
385 ] {399 ] {
386 let res = send(&app, method, uri, None, None).await;400 let res = send(&app, method, uri, None, None).await;
387 assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{method} {uri}");401 assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{method} {uri}");
@@ -6023,6 +6037,7 @@ async fn session_cookie_secure_attribute_follows_config() {
6023 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),6037 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
6024 chatbot_limit: Default::default(),6038 chatbot_limit: Default::default(),
6025 exam_presence: Default::default(),6039 exam_presence: Default::default(),
6040+ board_hub: Default::default(),
6026 db_up: Default::default(),6041 db_up: Default::default(),
6027 ai: None,6042 ai: None,
6028 });6043 });
@@ -6062,6 +6077,7 @@ async fn db_down_refuses_before_touching_the_database() {
6062 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),6077 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
6063 chatbot_limit: Default::default(),6078 chatbot_limit: Default::default(),
6064 exam_presence: Default::default(),6079 exam_presence: Default::default(),
6080+ board_hub: Default::default(),
6065 db_up: db_up.clone(),6081 db_up: db_up.clone(),
6066 ai: None,6082 ai: None,
6067 });6083 });
@@ -15856,6 +15872,7 @@ async fn chat_app_limited(
15856 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),15872 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
15857 chatbot_limit,15873 chatbot_limit,
15858 exam_presence: Default::default(),15874 exam_presence: Default::default(),
15875+ board_hub: Default::default(),
15859 db_up: Default::default(),15876 db_up: Default::default(),
15860 ai,15877 ai,
15861 });15878 });
tests/limits_completeness.rsmodified+16 -0
@@ -57,6 +57,22 @@ const EXCLUDED: &[(&str, &str)] = &[
57 assigned plan freezes in the database; the client sees the freeze as a \57 assigned plan freezes in the database; the client sees the freeze as a \
58 409, never as a number",58 409, never as a number",
59 ),59 ),
60+ (
61+ "BOARD_OPEN_GUARD",
62+ "SQL fragment: the condition every whiteboard-stroke write carries so a \
63+ locked or closed board freezes in the database; the client sees the \
64+ freeze as a 409, never as a number",
65+ ),
66+ (
67+ "BOARD_REPLAY_CHUNK",
68+ "how the board-room socket batches its join replay; the client reads the \
69+ strokes, not the batch size",
70+ ),
71+ (
72+ "BOARD_HUB_CAPACITY",
73+ "depth of one board room's fan-out channel; a lagging socket is dropped \
74+ and rejoins, which the client handles as a reconnect, not as a number",
75+ ),
60 (76 (
61 "UPLOAD_BODY_OVERHEAD_BYTES",77 "UPLOAD_BODY_OVERHEAD_BYTES",
62 "multipart headroom over max_file_bytes; the client sizes against \78 "multipart headroom over max_file_bytes; the client sizes against \
tests/persistence.rsmodified+1 -0
@@ -27,6 +27,7 @@ async fn reboot(db: &Database) -> Router {
27 rate_limit: RateLimitConfig::unlimited(),27 rate_limit: RateLimitConfig::unlimited(),
28 chatbot_limit: Default::default(),28 chatbot_limit: Default::default(),
29 exam_presence: Default::default(),29 exam_presence: Default::default(),
30+ board_hub: Default::default(),
30 db_up: Default::default(),31 db_up: Default::default(),
31 ai: None,32 ai: None,
32 })33 })
tests/rate_limit.rsmodified+2 -0
@@ -26,6 +26,7 @@ async fn app_with(rate_limit: RateLimitConfig) -> Router {
26 rate_limit,26 rate_limit,
27 chatbot_limit: Default::default(),27 chatbot_limit: Default::default(),
28 exam_presence: Default::default(),28 exam_presence: Default::default(),
29+ board_hub: Default::default(),
29 db_up: Default::default(),30 db_up: Default::default(),
30 ai: None,31 ai: None,
31 })32 })
@@ -463,6 +464,7 @@ async fn spawn_server(rate_limit: RateLimitConfig) -> String {
463 rate_limit,464 rate_limit,
464 chatbot_limit: Default::default(),465 chatbot_limit: Default::default(),
465 exam_presence: Default::default(),466 exam_presence: Default::default(),
467+ board_hub: Default::default(),
466 db_up: Default::default(),468 db_up: Default::default(),
467 ai: None,469 ai: None,
468 });470 });
tests/spec_bounds.rsmodified+26 -0
@@ -32,6 +32,7 @@ async fn spec() -> Value {
32 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),32 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
33 chatbot_limit: Default::default(),33 chatbot_limit: Default::default(),
34 exam_presence: Default::default(),34 exam_presence: Default::default(),
35+ board_hub: Default::default(),
35 db_up: Default::default(),36 db_up: Default::default(),
36 ai: None,37 ai: None,
37 });38 });
@@ -785,6 +786,31 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> {
785 "maxLength",786 "maxLength",
786 MAX_CHATBOT_THREAD_TITLE_LEN as i64,787 MAX_CHATBOT_THREAD_TITLE_LEN as i64,
787 ),788 ),
789+ // --- whiteboards ---
790+ (
791+ "CreateBoard",
792+ "title",
793+ "maxLength",
794+ MAX_BOARD_TITLE_LEN as i64,
795+ ),
796+ (
797+ "CreateBoard",
798+ "participant_ids",
799+ "maxItems",
800+ MAX_BOARD_PARTICIPANTS as i64,
801+ ),
802+ (
803+ "UpdateBoard",
804+ "title",
805+ "maxLength",
806+ MAX_BOARD_TITLE_LEN as i64,
807+ ),
808+ (
809+ "UpdateBoard",
810+ "participants",
811+ "maxItems",
812+ MAX_BOARD_PARTICIPANTS as i64,
813+ ),
788 ]814 ]
789 }815 }
790 816