diff --git a/src/lib.rs b/src/lib.rs index b3e5280..700a53d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -63,7 +63,7 @@ use crate::state::AppState; (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Also the food program: the meal slots menus are published for — each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) — the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` — one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. Read: any authenticated user; edit: manager+"), (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"), (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course — whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files — any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored — the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks); a linked parent reads a student's homework report — statuses, late flags, marks — but never the submitted files"), - (name = "boards", description = "Collaborative whiteboards. Anyone opens a board (`POST /boards`) with a title and an ad-hoc invite list of user ids — no course, session or appointment is involved — and every participant draws on it; the creator alone clears, locks, closes or deletes it. A caller who is not on a board gets a `404` for it on every route, existence included, while a participant who is not the creator gets a `403` on those four commands (they are already rendering the board, so hiding it from them would be a lie their client cannot act on). Strokes are **append-only and a clear deletes nothing**: it bumps the board's `epoch`, so the live canvas empties while every mark ever drawn stays stored — `GET /boards/{id}/strokes` is the current epoch (what a client draws to catch up), `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers, each carrying the epoch it closed, that epoch's final stroke count, who cleared and when (the markers *are* the index, so the open epoch is deliberately absent from it). Two growth caps, both published at `GET /limits`: `max_epoch_strokes` bounds the *live* canvas and is recoverable (clear it and drawing resumes, losing nothing), while `max_board_strokes` bounds the board's *lifetime* storage and stamps `closed_at` on the way past — a closed board is permanently read-only and fully readable, never deleted, and there is no reopen. `POST /boards/{id}/close` is the manual form of that, and idempotent. `DELETE /boards/{id}` is the one operation here that really destroys marks — it takes the whole stroke log with it and frees one of the creator's `max_boards_per_creator` seats. `PATCH /boards/{id}` re-titles (any participant) or changes the roster and the lock (creator only). Not in this spec (WebSocket): the live board room, where the drawing itself happens"), + (name = "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 at `GET /boards/{id}/ws`, where the drawing itself happens — JSON frames, cookie-authed, and a **404** at the door for anyone not on the board. A `join` replays the current epoch only (chunked `strokes`, then `synced` with the cursor to resume from); a `stroke` is persisted before it is fanned out, so every canvas in the room is showing rows that committed; `clear` and `lock` are the creator's alone and refuse anyone else with `error{code:\"forbidden\"}` *without* closing their socket. The REST mutations above fan out into the same room, and a roster change drops the socket of anyone it removed. See `src/web/board_ws.rs` for the frame-by-frame protocol"), (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+"), ), )] diff --git a/src/web/board_ws.rs b/src/web/board_ws.rs index 8a043b0..2a4f656 100644 --- a/src/web/board_ws.rs +++ b/src/web/board_ws.rs @@ -74,6 +74,10 @@ use crate::domain::user::UserId; use crate::error::AppError; use crate::state::AppState; use crate::web::CurrentUser; +use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq}; + +/// How this room names itself in the logs [`room::public_message`] writes. +const ROOM: &str = "board room"; /// What the client asked for, tagged by `type`. #[derive(Deserialize)] @@ -165,38 +169,24 @@ async fn room(mut socket: WebSocket, st: AppState, board: BoardId, user: UserId) } Err(RecvError::Closed) => Err(RoomClosed), }, - incoming = socket.recv() => match incoming { - Some(Ok(Message::Text(text))) => { + incoming = socket.recv() => match room::classify(incoming) { + Incoming::Text(text) => { handle_message(&mut socket, text.as_str(), &board, &user, &mut mine, &st).await } - // Ping/pong frames are answered by axum itself; other non-text - // frames carry nothing for this protocol. - Some(Ok(Message::Close(_))) | Some(Err(_)) | None => Err(RoomClosed), - Some(Ok(_)) => Ok(()), + Incoming::Gone => Err(RoomClosed), + Incoming::Ignore => Ok(()), }, }; if step.is_err() { break; } } - // Best-effort closing handshake — a bare TCP teardown reads as an error on - // the client; a Close frame reads as "the room is over". - let _ = socket.send(Message::Close(None)).await; + room::close(&mut socket).await; st.board_hub.leave(board.key()); } -/// The room is over: the peer went away, or the board ended. -struct RoomClosed; - type Step = Result<(), RoomClosed>; -async fn send(socket: &mut WebSocket, frame: Value) -> Step { - socket - .send(Message::Text(frame.to_string().into())) - .await - .map_err(|_| RoomClosed) -} - /// The board as it stands right now, for a caller who must still be on it. /// Every action re-reads through here: the roster, the lock and the epoch are /// all live facts, and a frame this socket may never have seen is not an @@ -530,63 +520,36 @@ async fn creator_board( } } -/// Attach the request's correlation id, if it sent one. Omitted stays omitted — -/// never `null` — so a client that sends no `client_seq` sees byte-identical -/// frames (mirrors [`super::exam_ws`]). -fn with_client_seq(frame: &mut Value, client_seq: Option) { - if let Some(client_seq) = client_seq { - frame["client_seq"] = json!(client_seq); - } -} - /// A machine-readable `code` beside the public words. The three refusals the /// stroke path can raise are distinguished by their message, because that is /// what [`BoardStroke::append`] hands back and each one means a different thing /// to a client: `epoch_full` is recoverable by clearing, `locked` is a pause /// that will lift, `board_closed` is terminal. fn error_frame(err: &AppError, client_seq: Option) -> Value { - let (code, message) = match err { - AppError::Forbidden(message) => ("forbidden", (*message).to_string()), - AppError::Conflict(message) if message.contains("clear it to keep drawing") => { - ("epoch_full", (*message).to_string()) - } - AppError::Conflict(message) if message.contains("locked") => { - ("locked", (*message).to_string()) - } + let code = match err { + AppError::Forbidden(_) => "forbidden", + AppError::Conflict(message) if message.contains("clear it to keep drawing") => "epoch_full", + AppError::Conflict(message) if message.contains("locked") => "locked", // "read-only" (the lifetime cap), and the clear's own "it is closed, or // you did not create it" — the socket already checked the creator, so // what is left is closed, and that is what the client must act on. AppError::Conflict(message) if message.contains("read-only") || message.contains("closed") => { - ("board_closed", (*message).to_string()) - } - AppError::Conflict(message) => ("conflict", (*message).to_string()), - AppError::ConflictOwned(message) => ("conflict", message.clone()), - AppError::Validation(err) => ("invalid", err.to_string()), - AppError::PayloadTooLarge(message) => ("invalid", message.clone()), - AppError::NotFound => ("not_found", "not found".to_string()), - AppError::Unauthorized => ("unauthorized", "unauthorized".to_string()), - AppError::TooManyRequests { .. } => ("too_many_requests", "too many requests".to_string()), - AppError::DbUnavailable => { - tracing::warn!("board room: database reconnecting"); - ( - "internal", - "database reconnecting — retry shortly".to_string(), - ) - } - AppError::DbTimeout => { - tracing::error!("board room: database timed out"); - ( - "internal", - "the database timed out — reload the room".to_string(), - ) + "board_closed" } - AppError::Db(_) | AppError::Internal(_) => { - tracing::error!("board room error: {err}"); - ("internal", "internal server error".to_string()) + AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict", + AppError::Validation(_) | AppError::PayloadTooLarge(_) => "invalid", + AppError::NotFound => "not_found", + AppError::Unauthorized => "unauthorized", + AppError::TooManyRequests { .. } => "too_many_requests", + AppError::DbUnavailable | AppError::DbTimeout | AppError::Db(_) | AppError::Internal(_) => { + "internal" } }; + // The words (and the logging of anything internal) are the rooms' shared + // half; only the `code` above is this room's own. + let message = room::public_message(err, ROOM); let mut frame = json!({ "type": "error", "code": code, "message": message }); with_client_seq(&mut frame, client_seq); frame diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 472abc7..2a8e6ee 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -56,7 +56,7 @@ use std::time::Duration; -use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; +use axum::extract::ws::{WebSocket, WebSocketUpgrade}; use axum::extract::{Path, State}; use axum::response::Response; use serde::Deserialize; @@ -78,6 +78,10 @@ use crate::web::exams::{ EXAM_LOCK, check_rejoin, ensure_enrolled, ensure_sittable, ensure_student, save_answer_in, writable_attempt, }; +use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq}; + +/// How this room names itself in the logs [`room::public_message`] writes. +const ROOM: &str = "exam room"; /// Serializes every presence transition with its matching `left_at` write: /// `enter` + clear at room start and `leave` + maybe-stamp at room teardown @@ -179,12 +183,10 @@ async fn room(mut socket: WebSocket, st: AppState, exam: Exam, attempt: ExamAtte } } incoming = socket.recv() => { - let text = match incoming { - Some(Ok(Message::Text(text))) => text, - // Ping/pong frames are answered by axum itself; other - // non-text frames carry nothing for this protocol. - Some(Ok(Message::Close(_))) | Some(Err(_)) | None => break, - Some(Ok(_)) => continue, + let text = match room::classify(incoming) { + Incoming::Text(text) => text, + Incoming::Gone => break, + Incoming::Ignore => continue, }; if handle_message(&mut socket, text.as_str(), &exam_id, &attempt_id, &user, &st.db) .await @@ -195,9 +197,7 @@ async fn room(mut socket: WebSocket, st: AppState, exam: Exam, attempt: ExamAtte } } } - // Best-effort closing handshake — a bare TCP teardown reads as an error - // on the client; a Close frame reads as "the room is over". - let _ = socket.send(Message::Close(None)).await; + room::close(&mut socket).await; // Leave critical section: only the last socket out means the student // actually left the room, and the count-down and its stamp are one atomic // step under PRESENCE_LOCK (a join racing this either lands wholly before @@ -244,10 +244,6 @@ async fn stamp_left(exam_id: &ExamId, attempt_id: &ExamAttemptId, db: &Database) } } -/// Errors that end the room: the peer went away, or the attempt reached a -/// terminal state and the close frame was sent. -struct RoomClosed; - /// The room's own sitting, provided it is still the student's current one and /// writable. Messages act on the sitting the room was opened for — never on a /// retake started elsewhere while this socket lingered, which a stale tab @@ -269,13 +265,6 @@ async fn writable_room_attempt( Ok(attempt) } -async fn send(socket: &mut WebSocket, frame: Value) -> Result<(), RoomClosed> { - socket - .send(Message::Text(frame.to_string().into())) - .await - .map_err(|_| RoomClosed) -} - /// Re-read everything, push a `state` frame, and close the room (after a /// `finished`/`expired` notice) once the room's sitting is no longer in /// progress. @@ -500,15 +489,6 @@ fn error_frame(err: &AppError) -> Value { error_frame_for(err, None, None) } -/// Attach the request's correlation id, if it sent one. Omitted stays omitted -/// — never `null` — so a client that sends no `client_seq` sees byte-identical -/// frames. -fn with_client_seq(frame: &mut Value, client_seq: Option) { - if let Some(client_seq) = client_seq { - frame["client_seq"] = json!(client_seq); - } -} - /// [`error_frame`] plus the optional blame: `question_id` when the failure /// belongs to one `answer` message, and `client_seq` whenever the `answer` carried /// one — the two are independent, so an unattributable failure is still @@ -516,29 +496,7 @@ fn with_client_seq(frame: &mut Value, client_seq: Option) { /// an unattributed failure — so a client that ignores the fields behaves /// exactly as before. fn error_frame_for(err: &AppError, question: Option<&str>, client_seq: Option) -> Value { - let message = match err { - AppError::Validation(err) => err.to_string(), - AppError::NotFound => "not found".to_string(), - AppError::Unauthorized => "unauthorized".to_string(), - AppError::Forbidden(message) => (*message).to_string(), - AppError::Conflict(message) => (*message).to_string(), - AppError::ConflictOwned(message) => message.clone(), - AppError::PayloadTooLarge(message) => message.clone(), - AppError::TooManyRequests { .. } => "too many requests".to_string(), - AppError::DbUnavailable => { - tracing::warn!("exam room: database reconnecting"); - "database reconnecting — retry shortly".to_string() - } - AppError::DbTimeout => { - tracing::error!("exam room: database timed out"); - "the database timed out — reload the room".to_string() - } - AppError::Db(_) | AppError::Internal(_) => { - tracing::error!("exam room error: {err}"); - "internal server error".to_string() - } - }; - let mut frame = json!({ "type": "error", "message": message }); + let mut frame = json!({ "type": "error", "message": room::public_message(err, ROOM) }); if let Some(question) = question { frame["question_id"] = json!(question); } diff --git a/src/web/mod.rs b/src/web/mod.rs index 7d8919d..badf464 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -25,6 +25,7 @@ pub mod notes; pub mod payments; pub mod pomodoro; pub mod questions; +pub mod room; pub mod sessions; pub mod settings; pub mod subjects; diff --git a/src/web/room.rs b/src/web/room.rs new file mode 100644 index 0000000..0262c83 --- /dev/null +++ b/src/web/room.rs @@ -0,0 +1,106 @@ +//! Machinery shared by every WebSocket room. +//! +//! Two rooms speak WebSocket in this crate — the student exam room +//! ([`super::exam_ws`]) and the collaborative whiteboard ([`super::board_ws`]) +//! — and they share less than they look like they do. The exam room only ever +//! replies to the socket that spoke; the board room fans out to everyone else +//! on the board. What they genuinely share is the plumbing *around* that +//! difference: how a frame goes out, how an incoming message is classified, how +//! an [`AppError`] becomes words a client may read, and how a client's +//! correlation id is echoed back untouched. +//! +//! Deliberately **not** here, and the reason each time: +//! +//! - the `select!` loop — the board's third arm is a fan-out receiver the exam +//! room has no analogue of, and the two loops' terminal conditions are +//! different domain facts. A trait to unify them would be longer than both +//! loops together and would still need a null receiver for the exam room. +//! - the pre-upgrade gates — the *pattern* (every gate before `on_upgrade`, so +//! a refusal is an HTTP status and not an instant close) is shared, but the +//! shared code is the single `ws.on_upgrade(…)` line at the end of it. The +//! gates themselves are each room's own domain rules. +//! - presence — the exam room counts sockets per attempt to pair the last one +//! out with a `left_at` stamp ([`crate::state::ExamPresence`]); the board +//! room's join/leave is the fan-out subscription itself +//! ([`crate::state::BoardHub`]), which counts its own sockets and has no +//! paired database write to serialize against. + +use axum::extract::ws::{Message, Utf8Bytes, WebSocket}; +use serde_json::{Value, json}; + +use crate::error::AppError; + +/// Errors that end a room: the peer went away, or the room reached a terminal +/// state and its closing frame was sent. +pub(crate) struct RoomClosed; + +/// Send one JSON frame. A failed send means the peer is gone, which ends the +/// room — every caller propagates it with `?`. +pub(crate) async fn send(socket: &mut WebSocket, frame: Value) -> Result<(), RoomClosed> { + socket + .send(Message::Text(frame.to_string().into())) + .await + .map_err(|_| RoomClosed) +} + +/// The best-effort closing handshake a room ends with — a bare TCP teardown +/// reads as an error on the client; a Close frame reads as "the room is over". +pub(crate) async fn close(socket: &mut WebSocket) { + let _ = socket.send(Message::Close(None)).await; +} + +/// What `socket.recv()` handed us, in the three shapes a room cares about. +pub(crate) enum Incoming { + /// A text frame — the only kind either protocol speaks. + Text(Utf8Bytes), + /// A frame carrying nothing for this protocol: ping/pong are answered by + /// axum itself, and neither room speaks binary. Read the next one. + Ignore, + /// Close, transport error, or end of stream: the room is over. + Gone, +} + +pub(crate) fn classify(incoming: Option>) -> Incoming { + match incoming { + Some(Ok(Message::Text(text))) => Incoming::Text(text), + Some(Ok(Message::Close(_))) | Some(Err(_)) | None => Incoming::Gone, + Some(Ok(_)) => Incoming::Ignore, + } +} + +/// Attach the request's correlation id, if it sent one. Omitted stays omitted +/// — never `null` — so a client that sends no `client_seq` sees byte-identical +/// frames. +pub(crate) fn with_client_seq(frame: &mut Value, client_seq: Option) { + if let Some(client_seq) = client_seq { + frame["client_seq"] = json!(client_seq); + } +} + +/// The public words for an error — the same strings the HTTP layer would use, +/// with internals logged under `room` (`"exam room"`, `"board room"`) and never +/// sent. +pub(crate) fn public_message(err: &AppError, room: &str) -> String { + match err { + AppError::Validation(err) => err.to_string(), + AppError::NotFound => "not found".to_string(), + AppError::Unauthorized => "unauthorized".to_string(), + AppError::Forbidden(message) => (*message).to_string(), + AppError::Conflict(message) => (*message).to_string(), + AppError::ConflictOwned(message) => message.clone(), + AppError::PayloadTooLarge(message) => message.clone(), + AppError::TooManyRequests { .. } => "too many requests".to_string(), + AppError::DbUnavailable => { + tracing::warn!("{room}: database reconnecting"); + "database reconnecting — retry shortly".to_string() + } + AppError::DbTimeout => { + tracing::error!("{room}: database timed out"); + "the database timed out — reload the room".to_string() + } + AppError::Db(_) | AppError::Internal(_) => { + tracing::error!("{room} error: {err}"); + "internal server error".to_string() + } + } +}