forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

board_ws.rs735 lines, 31.0 KiBHistoryRawDownload
1//! The collaborative board room: a WebSocket at `GET /boards/{id}/ws`.
2//!
3//! This is where the drawing actually happens. REST next door
4//! ([`super::boards`]) opens boards, reads the canvas and the history, and runs
5//! the creator's commands; the room is the live half — one socket per
6//! participant, every accepted stroke fanned out to the rest through
7//! [`crate::state::BoardHub`].
8//!
9//! Two rules shape everything below.
10//!
11//! **Persist, then publish.** A stroke is fanned out only once
12//! [`board_stroke::append`] has returned `Ok`, so the channel can never carry a
13//! mark the database refused (a locked board, a full canvas, a closed board).
14//! The database is the canvas; the channel is a notification about it. A
15//! client still dedupes by stroke `id` — a resync deliberately re-serves marks
16//! it already drew — but it never sees the echo of its own strokes: those are
17//! acknowledged with `saved` and filtered back out of its fan-out.
18//!
19//! **A clear deletes nothing.** `clear` bumps the board's epoch, so the live
20//! canvas empties while every stroke stays stored. A join therefore replays the
21//! *current epoch only* — history never rides this socket, it is an explicit
22//! REST read (`GET /boards/{id}/history`). A client that reconnects with a
23//! cursor from an older epoch is told `cleared` and given the whole current
24//! epoch, never a diff from a cursor that no longer means anything.
25//!
26//! Wire protocol (JSON text frames):
27//!
28//! client → server
29//! - `{"type":"join", after?, epoch?}` — replay the current epoch. `after` is
30//! the last stroke id already drawn and `epoch` the canvas it belongs to;
31//! send both to resume, neither for a full replay. A stale `epoch` gets a
32//! `cleared` frame and a full replay.
33//! - `{"type":"stroke", payload, client_seq?}` — any participant
34//! - `{"type":"clear"}` / `{"type":"lock", locked}` — **creator only**; anyone
35//! else gets `error{code:"forbidden"}` and *keeps the socket*
36//! - `{"type":"ping"}`
37//!
38//! server → client
39//! - `{"type":"state", board, epoch, locked, closed_at, creator, participants, now}`
40//! on connect and every [`BOARD_WS_TICK_SECS`]
41//! - `{"type":"strokes", epoch, strokes:[{id, author, payload}]}` — one replay
42//! chunk ([`BOARD_REPLAY_CHUNK`] at a time), then
43//! `{"type":"synced", epoch, cursor}`
44//! - `{"type":"stroke", id, author, payload, epoch}` — someone *else* drew
45//! - `{"type":"saved", id, client_seq?}` — your stroke landed
46//! - `{"type":"pong"}`
47//! - `{"type":"error", code, message, client_seq?}`
48//! - the five frames the REST routes publish, forwarded verbatim: `cleared`,
49//! `locked`, `closed`, `participants`, `deleted`
50//!
51//! `closed` and `deleted` end the room. A frame is never the authority here:
52//! every frame is authorized against the database *before* it is delivered,
53//! and every stroke, clear and lock re-reads the board and re-checks the role
54//! and the roster before it is written. So a caller who lost the right to be
55//! here — taken off the roster, or demoted out of whiteboard access — is
56//! refused and dropped whether or not any notification reached them.
57
58use std::collections::VecDeque;
59use std::time::Duration;
60
61use crate::web::tenant_state::{SchoolIdCookie, State};
62use axum::extract::Path;
63use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
64use axum::response::Response;
65use serde::Deserialize;
66use serde_json::{Value, json};
67use tokio::sync::broadcast::error::RecvError;
68
69use crate::constant::{BOARD_REPLAY_CHUNK, BOARD_WS_TICK_SECS, MAX_BOARD_ID_LEN};
70use crate::database::Database;
71use crate::domain::board::{Board, BoardId};
72use crate::domain::board_stroke::{
73 BOARD_CLOSED, BOARD_LOCKED, BoardStroke, CANVAS_BLANK, EPOCH_FULL,
74};
75use crate::domain::role::Role;
76use crate::domain::timestamp::Timestamp;
77use crate::domain::user::UserId;
78use crate::error::AppError;
79use crate::service::{board, board_stroke};
80use crate::state::AppState;
81use crate::tenant::SchoolId;
82use crate::web::CurrentUser;
83use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq};
84
85/// How this room names itself in the logs [`room::public_message`] writes.
86const ROOM: &str = "board room";
87
88/// What the client asked for, tagged by `type`.
89#[derive(Deserialize)]
90#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
91enum ClientMessage {
92 Join {
93 /// The last stroke id this client already drew.
94 #[serde(default)]
95 after: Option<String>,
96 /// The epoch that cursor belongs to. A mismatch means the canvas was
97 /// cleared while the client was away, and the cursor is dead.
98 #[serde(default)]
99 epoch: Option<i64>,
100 },
101 Stroke {
102 payload: String,
103 /// The client's own correlation id, echoed verbatim on this message's
104 /// `saved` or `error` and never read by the server.
105 #[serde(default)]
106 client_seq: Option<u64>,
107 },
108 Clear,
109 Lock {
110 locked: bool,
111 },
112 Ping,
113}
114
115/// Enter the caller's board room. Every gate runs *before* the upgrade so a
116/// rejection is an HTTP status rather than an instant close: no session (401),
117/// and a board that does not exist — or that the caller is not on, or that the
118/// caller is a `parent` and so barred from the whiteboard outright — is the
119/// same **404**, because a non-participant must not learn a board exists (the
120/// rationale at `src/lib.rs`). Refusing the door keeps a parent out; keeping
121/// one out who was demoted *after* the upgrade is [`live_board`]'s job, which
122/// every action already re-reads through.
123pub async fn board_ws(
124 State(st): State<AppState>,
125 SchoolIdCookie(school): SchoolIdCookie,
126 CurrentUser(user): CurrentUser,
127 Path(id): Path<String>,
128 ws: WebSocketUpgrade,
129) -> Result<Response, AppError> {
130 // Length-capped before the key is read back or echoed in a `state` frame.
131 // A key this long names no board, so it answers like any other stranger's
132 // board: 404.
133 if id.len() > MAX_BOARD_ID_LEN || !user.get_role().at_least(Role::Student) {
134 return Err(AppError::NotFound);
135 }
136 let board = board::read(&st.db, &BoardId::from_key(&id))
137 .await?
138 .ok_or(AppError::NotFound)?;
139 if !board.is_participant(user.get_id()) {
140 return Err(AppError::NotFound);
141 }
142 let board_id = board.get_id().clone();
143 let user_id = *user.get_id();
144 Ok(ws.on_upgrade(move |socket| room(socket, st, school, board_id, user_id)))
145}
146
147/// The room loop: the board's frames out, draw/clear/lock/ping in, until the
148/// socket closes or the board ends (closed, deleted, or the caller taken off
149/// it).
150async fn room(mut socket: WebSocket, st: AppState, school: SchoolId, board: BoardId, user: UserId) {
151 // Subscribe *before* anything is read out of the database: a stroke that
152 // lands between a replay's read and this subscribe would otherwise be lost
153 // outright, whereas one delivered twice is deduplicated by its id at the
154 // client (which a resync forces anyway).
155 let _connected = room::Connected::open(&st.metrics, "board", school.as_str(), &board.key());
156 let mut feed = st.board_hub.subscribe(&school, &board.key());
157 // The ids this socket drew, in the order they were published. The hub has
158 // no idea who is listening, so the room filters its own strokes back out
159 // here — a client that had to ignore the echo of every mark it just drew
160 // would be reimplementing this in every frontend.
161 let mut mine = VecDeque::new();
162 let mut tick = tokio::time::interval(Duration::from_secs(BOARD_WS_TICK_SECS));
163 loop {
164 let step = tokio::select! {
165 // First tick fires immediately — the connect-time state frame.
166 _ = tick.tick() => push_state(&mut socket, &board, &user, &st.db).await,
167 frame = feed.recv() => match frame {
168 Ok(frame) => forward(&mut socket, &frame, &board, &user, &mut mine, &st.db).await,
169 // The room fell further behind than the hub's capacity, so
170 // frames were dropped. Silently continuing here is the one bug
171 // that corrupts a canvas permanently and reports nothing: say
172 // so, then re-serve the whole current epoch from the database.
173 Err(RecvError::Lagged(dropped)) => {
174 tracing::warn!("board room dropped {dropped} frames, resyncing");
175 // The dropped frames may have included this socket's own
176 // echoes, so the queue no longer lines up with the stream.
177 // The replay that follows carries those strokes anyway.
178 mine.clear();
179 resync(&mut socket, &board, &user, &st.db).await
180 }
181 Err(RecvError::Closed) => Err(RoomClosed),
182 },
183 incoming = socket.recv() => match room::classify(incoming) {
184 Incoming::Text(text) => {
185 handle_message(&mut socket, text.as_str(), &school, &board, &user, &mut mine, &st).await
186 }
187 Incoming::Gone => Err(RoomClosed),
188 Incoming::Ignore => Ok(()),
189 },
190 };
191 if step.is_err() {
192 break;
193 }
194 }
195 room::close(&mut socket).await;
196 st.board_hub.leave(&school, &board.key());
197}
198
199type Step = Result<(), RoomClosed>;
200
201/// The board as it stands right now, for a caller who must still be on it and
202/// who must still hold a role the whiteboard is open to. Every action re-reads
203/// through here: the role, the roster, the lock and the epoch are all live
204/// facts, and a frame this socket may never have seen is not an authority over
205/// any of them.
206///
207/// The role is re-read for the same reason the roster is: the upgrade door's
208/// bar (`board_ws`, mirroring [`super::boards`]'s `board_for`) is checked once,
209/// nothing publishes a frame on a role change, and a demotion to `parent` — the
210/// role barred from the whiteboard outright — must not leave an open socket
211/// still committing strokes.
212async fn live_board(board: &BoardId, user: &UserId, db: &Database) -> Result<Board, AppError> {
213 let barred = crate::service::user::read(db, user)
214 .await?
215 .is_none_or(|caller| !caller.get_role().at_least(Role::Student));
216 if barred {
217 return Err(AppError::Forbidden("your role can no longer use boards"));
218 }
219 let board = board::read(db, board).await?.ok_or(AppError::NotFound)?;
220 if !board.is_participant(user) {
221 return Err(AppError::Forbidden("you are no longer on this board"));
222 }
223 Ok(board)
224}
225
226/// Push a `state` frame, and end the room if the board is gone or the caller
227/// has been taken off it.
228async fn push_state(socket: &mut WebSocket, board: &BoardId, user: &UserId, db: &Database) -> Step {
229 match live_board(board, user, db).await {
230 Ok(board) => {
231 send(
232 socket,
233 json!({
234 "type": "state",
235 "board": board.get_id().key(),
236 "epoch": board.get_epoch(),
237 "locked": board.is_locked(),
238 "closed_at": board.get_closed_at().map(|at| at.as_millis()),
239 "creator": board.get_creator().key(),
240 "participants": board
241 .get_participants()
242 .iter()
243 .map(|user| user.key())
244 .collect::<Vec<_>>(),
245 "now": Timestamp::now().as_millis(),
246 }),
247 )
248 .await
249 }
250 Err(err) => {
251 let frame = match err {
252 AppError::NotFound => json!({ "type": "deleted" }),
253 err => error_frame(&err, None),
254 };
255 let _ = send(socket, frame).await;
256 Err(RoomClosed)
257 }
258 }
259}
260
261/// One frame off the hub, on its way to this socket. Forwarded verbatim — the
262/// five REST shapes are the contract — with three of them acted on as well,
263/// and this socket's own strokes dropped: it already got a `saved` for each.
264async fn forward(
265 socket: &mut WebSocket,
266 frame: &str,
267 board: &BoardId,
268 user: &UserId,
269 mine: &mut VecDeque<String>,
270 db: &Database,
271) -> Step {
272 let parsed = serde_json::from_str::<Value>(frame).ok();
273 // The channel is FIFO, so this socket's own strokes come back in the order
274 // it published them: only the head can match, which keeps the check O(1)
275 // and cannot swallow someone else's mark that happens to be next.
276 //
277 // corner-cut: that ordering is an unenforced coupling — the head only ever
278 // matches because `mine.push_back` immediately precedes `publish` in
279 // `handle_message`, on a loop that is single-threaded per socket. Separate
280 // those two lines (or publish from anywhere else) and this socket starts
281 // receiving the echo of its own strokes; NO test catches it, because both
282 // orders pass every existing assertion. Upgrade path: publish through one
283 // helper that takes the queue and does both, so the pair cannot be split.
284 if let Some(parsed) = &parsed
285 && parsed["type"] == "stroke"
286 && mine.front().is_some_and(|id| parsed["id"] == id.as_str())
287 {
288 mine.pop_front();
289 return Ok(());
290 }
291 // Authorize *before* the frame is handed over, never after. This used to
292 // run only for the `participants` frame, so a caller who lost the right to
293 // read — a roster removal that published nothing, or a demotion to
294 // `parent`, the role with no whiteboard access at all — was served every
295 // mark, clear and lock for up to [`BOARD_WS_TICK_SECS`] before the state
296 // tick noticed. Re-derived against the database, never read off the frame:
297 // the frame is the prompt, the row is the authority.
298 //
299 // corner-cut: that is one `live_board` (two reads) per forwarded frame, paid
300 // by every listening socket, where the fan-out used to be read-free — a
301 // busy board now multiplies its database traffic by the size of the room.
302 // The drawer's own echo is dropped above without paying it, which is the
303 // only relief. Upgrade path: give [`crate::state::BoardHub`] a generation
304 // counter bumped by every role/roster write, and re-read only when this
305 // socket's copy is stale.
306 if let Err(err) = live_board(board, user, db).await {
307 let refusal = match err {
308 AppError::NotFound => json!({ "type": "deleted" }),
309 err => error_frame(&err, None),
310 };
311 let _ = send(socket, refusal).await;
312 return Err(RoomClosed);
313 }
314 socket
315 .send(Message::Text(frame.to_string().into()))
316 .await
317 .map_err(|_| RoomClosed)?;
318 let kind = parsed.and_then(|frame| frame["type"].as_str().map(str::to_string));
319 match kind.as_deref() {
320 // The board ended. Nothing left to serve either way.
321 Some("closed" | "deleted") => Err(RoomClosed),
322 _ => Ok(()),
323 }
324}
325
326/// Frames were dropped: tell the client, then re-serve the current epoch in
327/// full. A diff is impossible — the gap's contents are exactly what is unknown.
328async fn resync(socket: &mut WebSocket, board: &BoardId, user: &UserId, db: &Database) -> Step {
329 let live = match live_board(board, user, db).await {
330 Ok(live) => live,
331 Err(err) => {
332 let frame = match err {
333 AppError::NotFound => json!({ "type": "deleted" }),
334 err => error_frame(&err, None),
335 };
336 let _ = send(socket, frame).await;
337 return Err(RoomClosed);
338 }
339 };
340 send(
341 socket,
342 json!({
343 "type": "error",
344 "code": "resync",
345 "message": "the room fell behind — the canvas below replaces what you have",
346 }),
347 )
348 .await?;
349 replay(socket, board, live.get_epoch(), None, db).await
350}
351
352/// Serve one epoch, oldest first, [`BOARD_REPLAY_CHUNK`] rows at a time, and
353/// close with the cursor the client can resume from. The loop runs until a
354/// short chunk comes back — stopping at the first full one is how a replay
355/// silently truncates at the chunk boundary.
356async fn replay(
357 socket: &mut WebSocket,
358 board: &BoardId,
359 epoch: i64,
360 after: Option<String>,
361 db: &Database,
362) -> Step {
363 let mut cursor = after;
364 loop {
365 let chunk = match board_stroke::replay_current(db, board, epoch, cursor.as_deref()).await {
366 Ok(chunk) => chunk,
367 Err(err) => return send(socket, error_frame(&err, None)).await,
368 };
369 let short = chunk.len() < BOARD_REPLAY_CHUNK;
370 if let Some(last) = chunk.last() {
371 cursor = Some(last.get_id().key().to_string());
372 send(
373 socket,
374 json!({
375 "type": "strokes",
376 "epoch": epoch,
377 "strokes": chunk.iter().map(stroke_body).collect::<Vec<_>>(),
378 }),
379 )
380 .await?;
381 }
382 if short {
383 break;
384 }
385 }
386 send(
387 socket,
388 json!({ "type": "synced", "epoch": epoch, "cursor": cursor }),
389 )
390 .await
391}
392
393fn stroke_body(stroke: &BoardStroke) -> Value {
394 json!({
395 "id": stroke.get_id().key(),
396 "author": stroke.get_author().key(),
397 "payload": stroke.get_payload(),
398 })
399}
400
401async fn handle_message(
402 socket: &mut WebSocket,
403 text: &str,
404 school: &SchoolId,
405 board: &BoardId,
406 user: &UserId,
407 mine: &mut VecDeque<String>,
408 st: &AppState,
409) -> Step {
410 let message = match serde_json::from_str::<ClientMessage>(text) {
411 Ok(message) => message,
412 Err(err) => {
413 return send(
414 socket,
415 json!({
416 "type": "error",
417 "code": "invalid",
418 "message": format!("unrecognized message: {err}"),
419 }),
420 )
421 .await;
422 }
423 };
424 match message {
425 ClientMessage::Ping => send(socket, json!({ "type": "pong" })).await,
426 ClientMessage::Join { after, epoch } => {
427 let live = match live_board(board, user, &st.db).await {
428 Ok(live) => live,
429 Err(err) => {
430 let _ = send(socket, error_frame(&err, None)).await;
431 return Err(RoomClosed);
432 }
433 };
434 // A cursor is only meaningful inside the epoch it was taken from.
435 // Against any other one the canvas was wiped in between: say so,
436 // and replay the whole live canvas rather than a diff from a dead
437 // cursor — which would leave the client staring at a blank board.
438 let resume = match epoch {
439 Some(epoch) if epoch != live.get_epoch() => {
440 send(
441 socket,
442 json!({
443 "type": "cleared",
444 "epoch": live.get_epoch(),
445 "by": Value::Null,
446 }),
447 )
448 .await?;
449 None
450 }
451 // Bounded like the board key it sits beside — both are record
452 // keys of the same shape, and this one is echoed back as the
453 // `synced` cursor.
454 _ => after.filter(|after| after.len() <= MAX_BOARD_ID_LEN),
455 };
456 replay(socket, board, live.get_epoch(), resume, &st.db).await
457 }
458 ClientMessage::Stroke {
459 payload,
460 client_seq,
461 } => {
462 // Re-read for the roster *and* the epoch: the canvas may have been
463 // cleared since this socket last heard anything.
464 let saved = match live_board(board, user, &st.db).await {
465 Ok(live) => {
466 board_stroke::append(&st.db, board, user, &payload, live.get_epoch()).await
467 }
468 Err(err) => Err(err),
469 };
470 match saved {
471 Ok(stroke) => {
472 // Persist, then publish: the fan-out only ever carries
473 // marks the database already accepted.
474 let mut fanned = stroke_body(&stroke);
475 fanned["type"] = json!("stroke");
476 fanned["epoch"] = json!(stroke.get_epoch());
477 mine.push_back(stroke.get_id().key().to_string());
478 st.board_hub.publish(school, &board.key(), fanned.to_string());
479 let mut frame = json!({ "type": "saved", "id": stroke.get_id().key() });
480 with_client_seq(&mut frame, client_seq);
481 send(socket, frame).await
482 }
483 // A removal is terminal — this socket is no longer on the
484 // board, so it is told once and dropped. Everything else
485 // (locked, full, closed, a bad payload) leaves the room open:
486 // a refusal is not a reason to boot a class off the board.
487 Err(err @ AppError::Forbidden(_)) => {
488 let _ = send(socket, error_frame(&err, client_seq)).await;
489 Err(RoomClosed)
490 }
491 Err(err) => send(socket, error_frame(&err, client_seq)).await,
492 }
493 }
494 ClientMessage::Clear => match creator_board(socket, board, user, &st.db).await? {
495 None => Ok(()),
496 Some(live) => match board_stroke::clear(&st.db, live.get_id(), user).await {
497 // The marker carries the epoch it *closed*; the room's new
498 // canvas is the next one. Same shape as `POST /boards/{id}/clear`.
499 Ok(marker) => {
500 st.board_hub.publish(
501 school,
502 &board.key(),
503 json!({
504 "type": "cleared",
505 "epoch": marker.get_epoch() + 1,
506 "by": user.key(),
507 })
508 .to_string(),
509 );
510 Ok(())
511 }
512 Err(err) => send(socket, error_frame(&err, None)).await,
513 },
514 },
515 ClientMessage::Lock { locked } => match creator_board(socket, board, user, &st.db).await? {
516 None => Ok(()),
517 Some(live) => match board::set_locked(&st.db, &live, locked, user).await {
518 Ok(_) => {
519 st.board_hub.publish(
520 school,
521 &board.key(),
522 json!({ "type": "locked", "locked": locked, "by": user.key() }).to_string(),
523 );
524 Ok(())
525 }
526 Err(err) => send(socket, error_frame(&err, None)).await,
527 },
528 },
529 }
530}
531
532/// The board for a creator-only command. `None` means it was refused and the
533/// client told — **the socket stays open**: a participant who clicks "clear"
534/// has made a mistake, not left the room.
535async fn creator_board(
536 socket: &mut WebSocket,
537 board: &BoardId,
538 user: &UserId,
539 db: &Database,
540) -> Result<Option<Board>, RoomClosed> {
541 match live_board(board, user, db).await {
542 Ok(live) if live.is_creator(user) => Ok(Some(live)),
543 Ok(_) => {
544 send(
545 socket,
546 error_frame(
547 &AppError::Forbidden(
548 "only the board's creator can clear, lock, close or delete it",
549 ),
550 None,
551 ),
552 )
553 .await?;
554 Ok(None)
555 }
556 // Off the board, or the board is gone: both end the room.
557 Err(err) => {
558 let _ = send(socket, error_frame(&err, None)).await;
559 Err(RoomClosed)
560 }
561 }
562}
563
564/// A machine-readable `code` beside the public words. Each refusal the board
565/// path can raise means a different thing to a client: `epoch_full` is
566/// recoverable by clearing, `locked` is a pause that will lift, `canvas_blank`
567/// is nothing to do, `board_closed` is terminal.
568///
569/// The match is on the refusal *constants* [`board_stroke`] raises, by value —
570/// never on a substring of them. Guessing from a substring made every reworded
571/// refusal a silent re-labelling: "the canvas is already blank" contains the
572/// word "closed", so a blank canvas told a live room its board was finished.
573fn error_frame(err: &AppError, client_seq: Option<u64>) -> Value {
574 let code = match err {
575 AppError::Forbidden(_) => "forbidden",
576 AppError::Conflict(message) if *message == EPOCH_FULL => "epoch_full",
577 AppError::Conflict(message) if *message == BOARD_LOCKED => "locked",
578 AppError::Conflict(message) if *message == BOARD_CLOSED => "board_closed",
579 AppError::Conflict(message) if *message == CANVAS_BLANK => "canvas_blank",
580 // A refusal that already carries its own code keeps it — no board path
581 // raises one today, but re-labelling one "conflict" would throw the
582 // only machine answer it has away.
583 AppError::ConflictCoded { code, .. } => code,
584 // Everything else, `BOARD_MOVED` included: retryable, never terminal.
585 AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict",
586 AppError::Validation(_) | AppError::PayloadTooLarge(_) => "invalid",
587 AppError::NotFound => "not_found",
588 AppError::Expired(_) => "expired",
589 // See `room::public_message`: the gate refuses the upgrade first.
590 AppError::ModuleDisabled(_) => "module_disabled",
591 AppError::Unauthorized => "unauthorized",
592 AppError::TooManyRequests { .. } => "too_many_requests",
593 AppError::DbUnavailable | AppError::DbTimeout | AppError::Db(_) | AppError::Internal(_) => {
594 "internal"
595 }
596 };
597 // The words (and the logging of anything internal) are the rooms' shared
598 // half; only the `code` above is this room's own.
599 let message = room::public_message(err, ROOM);
600 let mut frame = json!({ "type": "error", "code": code, "message": message });
601 with_client_seq(&mut frame, client_seq);
602 frame
603}
604
605#[cfg(test)]
606mod tests {
607 use super::*;
608 use crate::domain::board_stroke::{BOARD_MOVED, REFUSALS};
609
610 fn code(err: AppError) -> String {
611 error_frame(&err, None)["code"]
612 .as_str()
613 .unwrap()
614 .to_string()
615 }
616
617 /// The pairing is the whole contract behind `epoch_full` (clear and carry
618 /// on), `locked` (wait), `canvas_blank` (nothing to do) and `board_closed`
619 /// (never again). Getting it wrong sends a paused room off clearing a
620 /// canvas it never needed to lose.
621 ///
622 /// Written against the constants, never against copies of their words: a
623 /// test that pins the wording rots into a test of a string the code can no
624 /// longer emit, which is exactly how the blank canvas shipped as
625 /// `board_closed` through a green suite. The length assertion is the other
626 /// half — a refusal added to `REFUSALS` fails here until it
627 /// is given the code its client must act on.
628 #[test]
629 fn every_refusal_gets_the_code_its_client_must_act_on() {
630 let pairs = [
631 (EPOCH_FULL, "epoch_full"),
632 (BOARD_LOCKED, "locked"),
633 (BOARD_CLOSED, "board_closed"),
634 (CANVAS_BLANK, "canvas_blank"),
635 // A stroke that lost its epoch to a clear is a plain retryable
636 // conflict, and must never be mistaken for terminal.
637 (BOARD_MOVED, "conflict"),
638 ];
639 assert_eq!(
640 pairs.len(),
641 REFUSALS.len(),
642 "a refusal the room cannot code"
643 );
644 for (message, expected) in pairs {
645 assert!(REFUSALS.contains(&message));
646 assert_eq!(code(AppError::Conflict(message)), expected, "{message}");
647 }
648 assert_eq!(code(AppError::Forbidden("nope")), "forbidden");
649 // Internals are logged, never wired.
650 let frame = error_frame(&AppError::Internal("secret".into()), None);
651 assert_eq!(frame["code"], "internal");
652 assert_eq!(frame["message"], "internal server error");
653 }
654
655 /// A blank canvas is the refusal that hides: it is a *live* board saying
656 /// "nothing to clear", so it must never carry the terminal code. The two it
657 /// sits between are checked with it, since what matters is that no two of
658 /// the three collapse into one code.
659 #[test]
660 fn a_blank_canvas_is_never_terminal() {
661 assert_eq!(code(AppError::Conflict(CANVAS_BLANK)), "canvas_blank");
662 assert_eq!(code(AppError::Conflict(BOARD_CLOSED)), "board_closed");
663 assert_eq!(code(AppError::Conflict(BOARD_LOCKED)), "locked");
664 }
665
666 /// The upgrade door's role bar has to hold for the *life* of the socket.
667 /// Nothing publishes a frame on a role change and the state tick used not
668 /// to look, so a student demoted to `parent` — the one role the whiteboard
669 /// is closed to outright — kept committing strokes on the socket they
670 /// already held. Driven at [`live_board`] because that is where every
671 /// stroke, clear, lock, join and tick funnels through; a real upgrade
672 /// cannot be driven from the `oneshot` harness the suites use.
673 #[tokio::test]
674 async fn a_demotion_bars_the_open_socket_from_every_write() {
675 use crate::domain::board::BoardTitle;
676 use crate::domain::user::Username;
677
678 let (db, _leases) = crate::database::init_test_db().await;
679 let creator =
680 crate::service::user::create(&db, Username::try_new("ogretmen").unwrap(), None)
681 .await
682 .unwrap();
683 let mate = crate::service::user::create(&db, Username::try_new("ogrenci").unwrap(), None)
684 .await
685 .unwrap();
686 let mate_id = *mate.get_id();
687 let board = board::create(
688 &db,
689 creator.get_id(),
690 BoardTitle::try_new("Tahta").unwrap(),
691 vec![mate_id],
692 )
693 .await
694 .unwrap();
695
696 // A student participant draws.
697 assert!(
698 live_board(board.get_id(), &mate_id, &db).await.is_ok(),
699 "a student on the board must pass"
700 );
701
702 // Demoted while the socket is open: refused from here on, and with the
703 // frame a denied write already uses — no new frame type.
704 crate::service::user::set_role(&db, mate.get_id(), Role::Parent)
705 .await
706 .unwrap();
707 let err = live_board(board.get_id(), &mate_id, &db).await.unwrap_err();
708 assert!(
709 matches!(err, AppError::Forbidden(_)),
710 "a parent must be refused"
711 );
712 assert_eq!(error_frame(&err, None)["code"], "forbidden");
713
714 // Nobody else is affected.
715 assert!(
716 live_board(board.get_id(), creator.get_id(), &db)
717 .await
718 .is_ok()
719 );
720 }
721
722 /// Omitted stays omitted, never `null`.
723 #[test]
724 fn client_seq_rides_along_only_when_it_was_sent() {
725 assert_eq!(
726 error_frame(&AppError::Forbidden("nope"), Some(9))["client_seq"],
727 json!(9)
728 );
729 assert!(
730 error_frame(&AppError::Forbidden("nope"), None)
731 .get("client_seq")
732 .is_none()
733 );
734 }
735}