π§΅ fold the two rooms' shared plumbing into src/web/room.rs
Browse files at this commit6208c973131d1a170f1aeb3decc42dfde60e26d8Parent: b9f3988- chore
- π§΅ fold the two rooms' shared plumbing into src/web/room.rs
5 changed files +143 -115
- src/lib.rs +1 -1
- src/web/board_ws.rs +24 -61
- src/web/exam_ws.rs +11 -53
- src/web/mod.rs +1 -0
- src/web/room.rs +106 -0
src/lib.rsmodified+1 -1
| @@ -63,7 +63,7 @@ use crate::state::AppState; | ||
| 63 | 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 | 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 | 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 = "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"), | |
| 67 | 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+"), |
| 68 | 68 | ), |
| 69 | 69 | )] |
src/web/board_ws.rsmodified+24 -61
| @@ -74,6 +74,10 @@ use crate::domain::user::UserId; | ||
| 74 | 74 | use crate::error::AppError; |
| 75 | 75 | use crate::state::AppState; |
| 76 | 76 | use crate::web::CurrentUser; |
| 77 | +use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq}; | |
| 78 | + | |
| 79 | +/// How this room names itself in the logs [`room::public_message`] writes. | |
| 80 | +const ROOM: &str = "board room"; | |
| 77 | 81 | |
| 78 | 82 | /// What the client asked for, tagged by `type`. |
| 79 | 83 | #[derive(Deserialize)] |
| @@ -165,38 +169,24 @@ async fn room(mut socket: WebSocket, st: AppState, board: BoardId, user: UserId) | ||
| 165 | 169 | } |
| 166 | 170 | Err(RecvError::Closed) => Err(RoomClosed), |
| 167 | 171 | }, |
| 168 | - incoming = socket.recv() => match incoming { | |
| 169 | - Some(Ok(Message::Text(text))) => { | |
| 172 | + incoming = socket.recv() => match room::classify(incoming) { | |
| 173 | + Incoming::Text(text) => { | |
| 170 | 174 | handle_message(&mut socket, text.as_str(), &board, &user, &mut mine, &st).await |
| 171 | 175 | } |
| 172 | - // Ping/pong frames are answered by axum itself; other non-text | |
| 173 | - // frames carry nothing for this protocol. | |
| 174 | - Some(Ok(Message::Close(_))) | Some(Err(_)) | None => Err(RoomClosed), | |
| 175 | - Some(Ok(_)) => Ok(()), | |
| 176 | + Incoming::Gone => Err(RoomClosed), | |
| 177 | + Incoming::Ignore => Ok(()), | |
| 176 | 178 | }, |
| 177 | 179 | }; |
| 178 | 180 | if step.is_err() { |
| 179 | 181 | break; |
| 180 | 182 | } |
| 181 | 183 | } |
| 182 | - // Best-effort closing handshake β a bare TCP teardown reads as an error on | |
| 183 | - // the client; a Close frame reads as "the room is over". | |
| 184 | - let _ = socket.send(Message::Close(None)).await; | |
| 184 | + room::close(&mut socket).await; | |
| 185 | 185 | st.board_hub.leave(board.key()); |
| 186 | 186 | } |
| 187 | 187 | |
| 188 | -/// The room is over: the peer went away, or the board ended. | |
| 189 | -struct RoomClosed; | |
| 190 | - | |
| 191 | 188 | type Step = Result<(), RoomClosed>; |
| 192 | 189 | |
| 193 | -async fn send(socket: &mut WebSocket, frame: Value) -> Step { | |
| 194 | - socket | |
| 195 | - .send(Message::Text(frame.to_string().into())) | |
| 196 | - .await | |
| 197 | - .map_err(|_| RoomClosed) | |
| 198 | -} | |
| 199 | - | |
| 200 | 190 | /// The board as it stands right now, for a caller who must still be on it. |
| 201 | 191 | /// Every action re-reads through here: the roster, the lock and the epoch are |
| 202 | 192 | /// all live facts, and a frame this socket may never have seen is not an |
| @@ -530,63 +520,36 @@ async fn creator_board( | ||
| 530 | 520 | } |
| 531 | 521 | } |
| 532 | 522 | |
| 533 | -/// Attach the request's correlation id, if it sent one. Omitted stays omitted β | |
| 534 | -/// never `null` β so a client that sends no `client_seq` sees byte-identical | |
| 535 | -/// frames (mirrors [`super::exam_ws`]). | |
| 536 | -fn with_client_seq(frame: &mut Value, client_seq: Option<u64>) { | |
| 537 | - if let Some(client_seq) = client_seq { | |
| 538 | - frame["client_seq"] = json!(client_seq); | |
| 539 | - } | |
| 540 | -} | |
| 541 | - | |
| 542 | 523 | /// A machine-readable `code` beside the public words. The three refusals the |
| 543 | 524 | /// stroke path can raise are distinguished by their message, because that is |
| 544 | 525 | /// what [`BoardStroke::append`] hands back and each one means a different thing |
| 545 | 526 | /// to a client: `epoch_full` is recoverable by clearing, `locked` is a pause |
| 546 | 527 | /// that will lift, `board_closed` is terminal. |
| 547 | 528 | fn error_frame(err: &AppError, client_seq: Option<u64>) -> Value { |
| 548 | - let (code, message) = match err { | |
| 549 | - AppError::Forbidden(message) => ("forbidden", (*message).to_string()), | |
| 550 | - AppError::Conflict(message) if message.contains("clear it to keep drawing") => { | |
| 551 | - ("epoch_full", (*message).to_string()) | |
| 552 | - } | |
| 553 | - AppError::Conflict(message) if message.contains("locked") => { | |
| 554 | - ("locked", (*message).to_string()) | |
| 555 | - } | |
| 529 | + let code = match err { | |
| 530 | + AppError::Forbidden(_) => "forbidden", | |
| 531 | + AppError::Conflict(message) if message.contains("clear it to keep drawing") => "epoch_full", | |
| 532 | + AppError::Conflict(message) if message.contains("locked") => "locked", | |
| 556 | 533 | // "read-only" (the lifetime cap), and the clear's own "it is closed, or |
| 557 | 534 | // you did not create it" β the socket already checked the creator, so |
| 558 | 535 | // what is left is closed, and that is what the client must act on. |
| 559 | 536 | AppError::Conflict(message) |
| 560 | 537 | if message.contains("read-only") || message.contains("closed") => |
| 561 | 538 | { |
| 562 | - ("board_closed", (*message).to_string()) | |
| 563 | - } | |
| 564 | - AppError::Conflict(message) => ("conflict", (*message).to_string()), | |
| 565 | - AppError::ConflictOwned(message) => ("conflict", message.clone()), | |
| 566 | - AppError::Validation(err) => ("invalid", err.to_string()), | |
| 567 | - AppError::PayloadTooLarge(message) => ("invalid", message.clone()), | |
| 568 | - AppError::NotFound => ("not_found", "not found".to_string()), | |
| 569 | - AppError::Unauthorized => ("unauthorized", "unauthorized".to_string()), | |
| 570 | - AppError::TooManyRequests { .. } => ("too_many_requests", "too many requests".to_string()), | |
| 571 | - AppError::DbUnavailable => { | |
| 572 | - tracing::warn!("board room: database reconnecting"); | |
| 573 | - ( | |
| 574 | - "internal", | |
| 575 | - "database reconnecting β retry shortly".to_string(), | |
| 576 | - ) | |
| 577 | - } | |
| 578 | - AppError::DbTimeout => { | |
| 579 | - tracing::error!("board room: database timed out"); | |
| 580 | - ( | |
| 581 | - "internal", | |
| 582 | - "the database timed out β reload the room".to_string(), | |
| 583 | - ) | |
| 539 | + "board_closed" | |
| 584 | 540 | } |
| 585 | - AppError::Db(_) | AppError::Internal(_) => { | |
| 586 | - tracing::error!("board room error: {err}"); | |
| 587 | - ("internal", "internal server error".to_string()) | |
| 541 | + AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict", | |
| 542 | + AppError::Validation(_) | AppError::PayloadTooLarge(_) => "invalid", | |
| 543 | + AppError::NotFound => "not_found", | |
| 544 | + AppError::Unauthorized => "unauthorized", | |
| 545 | + AppError::TooManyRequests { .. } => "too_many_requests", | |
| 546 | + AppError::DbUnavailable | AppError::DbTimeout | AppError::Db(_) | AppError::Internal(_) => { | |
| 547 | + "internal" | |
| 588 | 548 | } |
| 589 | 549 | }; |
| 550 | + // The words (and the logging of anything internal) are the rooms' shared | |
| 551 | + // half; only the `code` above is this room's own. | |
| 552 | + let message = room::public_message(err, ROOM); | |
| 590 | 553 | let mut frame = json!({ "type": "error", "code": code, "message": message }); |
| 591 | 554 | with_client_seq(&mut frame, client_seq); |
| 592 | 555 | frame |
src/web/exam_ws.rsmodified+11 -53
| @@ -56,7 +56,7 @@ | ||
| 56 | 56 | |
| 57 | 57 | use std::time::Duration; |
| 58 | 58 | |
| 59 | -use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; | |
| 59 | +use axum::extract::ws::{WebSocket, WebSocketUpgrade}; | |
| 60 | 60 | use axum::extract::{Path, State}; |
| 61 | 61 | use axum::response::Response; |
| 62 | 62 | use serde::Deserialize; |
| @@ -78,6 +78,10 @@ use crate::web::exams::{ | ||
| 78 | 78 | EXAM_LOCK, check_rejoin, ensure_enrolled, ensure_sittable, ensure_student, save_answer_in, |
| 79 | 79 | writable_attempt, |
| 80 | 80 | }; |
| 81 | +use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq}; | |
| 82 | + | |
| 83 | +/// How this room names itself in the logs [`room::public_message`] writes. | |
| 84 | +const ROOM: &str = "exam room"; | |
| 81 | 85 | |
| 82 | 86 | /// Serializes every presence transition with its matching `left_at` write: |
| 83 | 87 | /// `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 | ||
| 179 | 183 | } |
| 180 | 184 | } |
| 181 | 185 | incoming = socket.recv() => { |
| 182 | - let text = match incoming { | |
| 183 | - Some(Ok(Message::Text(text))) => text, | |
| 184 | - // Ping/pong frames are answered by axum itself; other | |
| 185 | - // non-text frames carry nothing for this protocol. | |
| 186 | - Some(Ok(Message::Close(_))) | Some(Err(_)) | None => break, | |
| 187 | - Some(Ok(_)) => continue, | |
| 186 | + let text = match room::classify(incoming) { | |
| 187 | + Incoming::Text(text) => text, | |
| 188 | + Incoming::Gone => break, | |
| 189 | + Incoming::Ignore => continue, | |
| 188 | 190 | }; |
| 189 | 191 | if handle_message(&mut socket, text.as_str(), &exam_id, &attempt_id, &user, &st.db) |
| 190 | 192 | .await |
| @@ -195,9 +197,7 @@ async fn room(mut socket: WebSocket, st: AppState, exam: Exam, attempt: ExamAtte | ||
| 195 | 197 | } |
| 196 | 198 | } |
| 197 | 199 | } |
| 198 | - // Best-effort closing handshake β a bare TCP teardown reads as an error | |
| 199 | - // on the client; a Close frame reads as "the room is over". | |
| 200 | - let _ = socket.send(Message::Close(None)).await; | |
| 200 | + room::close(&mut socket).await; | |
| 201 | 201 | // Leave critical section: only the last socket out means the student |
| 202 | 202 | // actually left the room, and the count-down and its stamp are one atomic |
| 203 | 203 | // 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) | ||
| 244 | 244 | } |
| 245 | 245 | } |
| 246 | 246 | |
| 247 | -/// Errors that end the room: the peer went away, or the attempt reached a | |
| 248 | -/// terminal state and the close frame was sent. | |
| 249 | -struct RoomClosed; | |
| 250 | - | |
| 251 | 247 | /// The room's own sitting, provided it is still the student's current one and |
| 252 | 248 | /// writable. Messages act on the sitting the room was opened for β never on a |
| 253 | 249 | /// retake started elsewhere while this socket lingered, which a stale tab |
| @@ -269,13 +265,6 @@ async fn writable_room_attempt( | ||
| 269 | 265 | Ok(attempt) |
| 270 | 266 | } |
| 271 | 267 | |
| 272 | -async fn send(socket: &mut WebSocket, frame: Value) -> Result<(), RoomClosed> { | |
| 273 | - socket | |
| 274 | - .send(Message::Text(frame.to_string().into())) | |
| 275 | - .await | |
| 276 | - .map_err(|_| RoomClosed) | |
| 277 | -} | |
| 278 | - | |
| 279 | 268 | /// Re-read everything, push a `state` frame, and close the room (after a |
| 280 | 269 | /// `finished`/`expired` notice) once the room's sitting is no longer in |
| 281 | 270 | /// progress. |
| @@ -500,15 +489,6 @@ fn error_frame(err: &AppError) -> Value { | ||
| 500 | 489 | error_frame_for(err, None, None) |
| 501 | 490 | } |
| 502 | 491 | |
| 503 | -/// Attach the request's correlation id, if it sent one. Omitted stays omitted | |
| 504 | -/// β never `null` β so a client that sends no `client_seq` sees byte-identical | |
| 505 | -/// frames. | |
| 506 | -fn with_client_seq(frame: &mut Value, client_seq: Option<u64>) { | |
| 507 | - if let Some(client_seq) = client_seq { | |
| 508 | - frame["client_seq"] = json!(client_seq); | |
| 509 | - } | |
| 510 | -} | |
| 511 | - | |
| 512 | 492 | /// [`error_frame`] plus the optional blame: `question_id` when the failure |
| 513 | 493 | /// belongs to one `answer` message, and `client_seq` whenever the `answer` carried |
| 514 | 494 | /// 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<u64>) { | ||
| 516 | 496 | /// an unattributed failure β so a client that ignores the fields behaves |
| 517 | 497 | /// exactly as before. |
| 518 | 498 | fn error_frame_for(err: &AppError, question: Option<&str>, client_seq: Option<u64>) -> Value { |
| 519 | - let message = match err { | |
| 520 | - AppError::Validation(err) => err.to_string(), | |
| 521 | - AppError::NotFound => "not found".to_string(), | |
| 522 | - AppError::Unauthorized => "unauthorized".to_string(), | |
| 523 | - AppError::Forbidden(message) => (*message).to_string(), | |
| 524 | - AppError::Conflict(message) => (*message).to_string(), | |
| 525 | - AppError::ConflictOwned(message) => message.clone(), | |
| 526 | - AppError::PayloadTooLarge(message) => message.clone(), | |
| 527 | - AppError::TooManyRequests { .. } => "too many requests".to_string(), | |
| 528 | - AppError::DbUnavailable => { | |
| 529 | - tracing::warn!("exam room: database reconnecting"); | |
| 530 | - "database reconnecting β retry shortly".to_string() | |
| 531 | - } | |
| 532 | - AppError::DbTimeout => { | |
| 533 | - tracing::error!("exam room: database timed out"); | |
| 534 | - "the database timed out β reload the room".to_string() | |
| 535 | - } | |
| 536 | - AppError::Db(_) | AppError::Internal(_) => { | |
| 537 | - tracing::error!("exam room error: {err}"); | |
| 538 | - "internal server error".to_string() | |
| 539 | - } | |
| 540 | - }; | |
| 541 | - let mut frame = json!({ "type": "error", "message": message }); | |
| 499 | + let mut frame = json!({ "type": "error", "message": room::public_message(err, ROOM) }); | |
| 542 | 500 | if let Some(question) = question { |
| 543 | 501 | frame["question_id"] = json!(question); |
| 544 | 502 | } |
src/web/mod.rsmodified+1 -0
| @@ -25,6 +25,7 @@ pub mod notes; | ||
| 25 | 25 | pub mod payments; |
| 26 | 26 | pub mod pomodoro; |
| 27 | 27 | pub mod questions; |
| 28 | +pub mod room; | |
| 28 | 29 | pub mod sessions; |
| 29 | 30 | pub mod settings; |
| 30 | 31 | pub mod subjects; |
src/web/room.rsadded+106 -0
| @@ -0,0 +1,106 @@ | ||
| 1 | +//! Machinery shared by every WebSocket room. | |
| 2 | +//! | |
| 3 | +//! Two rooms speak WebSocket in this crate β the student exam room | |
| 4 | +//! ([`super::exam_ws`]) and the collaborative whiteboard ([`super::board_ws`]) | |
| 5 | +//! β and they share less than they look like they do. The exam room only ever | |
| 6 | +//! replies to the socket that spoke; the board room fans out to everyone else | |
| 7 | +//! on the board. What they genuinely share is the plumbing *around* that | |
| 8 | +//! difference: how a frame goes out, how an incoming message is classified, how | |
| 9 | +//! an [`AppError`] becomes words a client may read, and how a client's | |
| 10 | +//! correlation id is echoed back untouched. | |
| 11 | +//! | |
| 12 | +//! Deliberately **not** here, and the reason each time: | |
| 13 | +//! | |
| 14 | +//! - the `select!` loop β the board's third arm is a fan-out receiver the exam | |
| 15 | +//! room has no analogue of, and the two loops' terminal conditions are | |
| 16 | +//! different domain facts. A trait to unify them would be longer than both | |
| 17 | +//! loops together and would still need a null receiver for the exam room. | |
| 18 | +//! - the pre-upgrade gates β the *pattern* (every gate before `on_upgrade`, so | |
| 19 | +//! a refusal is an HTTP status and not an instant close) is shared, but the | |
| 20 | +//! shared code is the single `ws.on_upgrade(β¦)` line at the end of it. The | |
| 21 | +//! gates themselves are each room's own domain rules. | |
| 22 | +//! - presence β the exam room counts sockets per attempt to pair the last one | |
| 23 | +//! out with a `left_at` stamp ([`crate::state::ExamPresence`]); the board | |
| 24 | +//! room's join/leave is the fan-out subscription itself | |
| 25 | +//! ([`crate::state::BoardHub`]), which counts its own sockets and has no | |
| 26 | +//! paired database write to serialize against. | |
| 27 | + | |
| 28 | +use axum::extract::ws::{Message, Utf8Bytes, WebSocket}; | |
| 29 | +use serde_json::{Value, json}; | |
| 30 | + | |
| 31 | +use crate::error::AppError; | |
| 32 | + | |
| 33 | +/// Errors that end a room: the peer went away, or the room reached a terminal | |
| 34 | +/// state and its closing frame was sent. | |
| 35 | +pub(crate) struct RoomClosed; | |
| 36 | + | |
| 37 | +/// Send one JSON frame. A failed send means the peer is gone, which ends the | |
| 38 | +/// room β every caller propagates it with `?`. | |
| 39 | +pub(crate) async fn send(socket: &mut WebSocket, frame: Value) -> Result<(), RoomClosed> { | |
| 40 | + socket | |
| 41 | + .send(Message::Text(frame.to_string().into())) | |
| 42 | + .await | |
| 43 | + .map_err(|_| RoomClosed) | |
| 44 | +} | |
| 45 | + | |
| 46 | +/// The best-effort closing handshake a room ends with β a bare TCP teardown | |
| 47 | +/// reads as an error on the client; a Close frame reads as "the room is over". | |
| 48 | +pub(crate) async fn close(socket: &mut WebSocket) { | |
| 49 | + let _ = socket.send(Message::Close(None)).await; | |
| 50 | +} | |
| 51 | + | |
| 52 | +/// What `socket.recv()` handed us, in the three shapes a room cares about. | |
| 53 | +pub(crate) enum Incoming { | |
| 54 | + /// A text frame β the only kind either protocol speaks. | |
| 55 | + Text(Utf8Bytes), | |
| 56 | + /// A frame carrying nothing for this protocol: ping/pong are answered by | |
| 57 | + /// axum itself, and neither room speaks binary. Read the next one. | |
| 58 | + Ignore, | |
| 59 | + /// Close, transport error, or end of stream: the room is over. | |
| 60 | + Gone, | |
| 61 | +} | |
| 62 | + | |
| 63 | +pub(crate) fn classify(incoming: Option<Result<Message, axum::Error>>) -> Incoming { | |
| 64 | + match incoming { | |
| 65 | + Some(Ok(Message::Text(text))) => Incoming::Text(text), | |
| 66 | + Some(Ok(Message::Close(_))) | Some(Err(_)) | None => Incoming::Gone, | |
| 67 | + Some(Ok(_)) => Incoming::Ignore, | |
| 68 | + } | |
| 69 | +} | |
| 70 | + | |
| 71 | +/// Attach the request's correlation id, if it sent one. Omitted stays omitted | |
| 72 | +/// β never `null` β so a client that sends no `client_seq` sees byte-identical | |
| 73 | +/// frames. | |
| 74 | +pub(crate) fn with_client_seq(frame: &mut Value, client_seq: Option<u64>) { | |
| 75 | + if let Some(client_seq) = client_seq { | |
| 76 | + frame["client_seq"] = json!(client_seq); | |
| 77 | + } | |
| 78 | +} | |
| 79 | + | |
| 80 | +/// The public words for an error β the same strings the HTTP layer would use, | |
| 81 | +/// with internals logged under `room` (`"exam room"`, `"board room"`) and never | |
| 82 | +/// sent. | |
| 83 | +pub(crate) fn public_message(err: &AppError, room: &str) -> String { | |
| 84 | + match err { | |
| 85 | + AppError::Validation(err) => err.to_string(), | |
| 86 | + AppError::NotFound => "not found".to_string(), | |
| 87 | + AppError::Unauthorized => "unauthorized".to_string(), | |
| 88 | + AppError::Forbidden(message) => (*message).to_string(), | |
| 89 | + AppError::Conflict(message) => (*message).to_string(), | |
| 90 | + AppError::ConflictOwned(message) => message.clone(), | |
| 91 | + AppError::PayloadTooLarge(message) => message.clone(), | |
| 92 | + AppError::TooManyRequests { .. } => "too many requests".to_string(), | |
| 93 | + AppError::DbUnavailable => { | |
| 94 | + tracing::warn!("{room}: database reconnecting"); | |
| 95 | + "database reconnecting β retry shortly".to_string() | |
| 96 | + } | |
| 97 | + AppError::DbTimeout => { | |
| 98 | + tracing::error!("{room}: database timed out"); | |
| 99 | + "the database timed out β reload the room".to_string() | |
| 100 | + } | |
| 101 | + AppError::Db(_) | AppError::Internal(_) => { | |
| 102 | + tracing::error!("{room} error: {err}"); | |
| 103 | + "internal server error".to_string() | |
| 104 | + } | |
| 105 | + } | |
| 106 | +} |