diff --git a/src/state.rs b/src/state.rs index 74e1c2a..f8773b0 100644 --- a/src/state.rs +++ b/src/state.rs @@ -8,7 +8,7 @@ use tokio::sync::broadcast; use crate::ai::AiBridge; use crate::database::Database; use crate::rate_limit::{RateLimitConfig, UserRateLimiter}; -use crate::tenant::Tenants; +use crate::tenant::{Slug, Tenants}; /// Shared application state handed to every handler. #[derive(Clone)] @@ -88,8 +88,20 @@ impl DbHealth { } } +/// The map key for `key` inside `slug`'s school. One process serves every +/// school, but record keys are only unique *within* a database, so an +/// unscoped key would put two schools' identical attempts (or boards) in the +/// same room. The maps below are the only users of this, and their methods +/// take a [`Slug`] rather than a ready-made key — there is no way to reach one +/// with an unscoped string. The per-user chatbot limiter keys through here +/// too, for the same reason. A slug cannot contain `:`, so the join is +/// unambiguous. +pub fn scoped_key(slug: &Slug, key: &str) -> String { + format!("{slug}:{key}") +} + /// How many exam-room sockets each attempt has open right now, keyed by the -/// attempt's record key. The room counts itself in on entry and out on exit, +/// attempt's record key within its school. The room counts itself in on entry and out on exit, /// and only the last socket out stamps the walk-out (`left_at`) — a student /// closing one of two tabs never counts as having left the exam. /// @@ -103,14 +115,15 @@ pub struct ExamPresence(Arc>>); impl ExamPresence { /// Count one socket into `attempt`'s room. - pub fn enter(&self, attempt: &str) { + pub fn enter(&self, slug: &Slug, attempt: &str) { let mut rooms = self.0.lock().expect("exam presence lock"); - *rooms.entry(attempt.to_string()).or_insert(0) += 1; + *rooms.entry(scoped_key(slug, attempt)).or_insert(0) += 1; } /// Count one socket out of `attempt`'s room; `true` when it was the last /// one — the student has actually left. - pub fn leave(&self, attempt: &str) -> bool { + pub fn leave(&self, slug: &Slug, attempt: &str) -> bool { + let attempt = &scoped_key(slug, attempt); let mut rooms = self.0.lock().expect("exam presence lock"); match rooms.get_mut(attempt) { Some(count) if *count > 1 => { @@ -128,7 +141,8 @@ impl ExamPresence { } } -/// One broadcast channel per live whiteboard, keyed by the board's record key, +/// One broadcast channel per live whiteboard, keyed by the board's record key +/// within its school, /// so a stroke saved by one socket reaches every *other* socket in that board. /// Nothing else in this codebase fans out — an exam room only ever replies to /// the socket that spoke — so this is the only multi-subscriber push we have. @@ -145,10 +159,10 @@ pub struct BoardHub(Arc, usize) impl BoardHub { /// Count one socket into `board` and hand back its stream of other /// people's frames, creating the channel on the first join. - pub fn subscribe(&self, board: &str) -> broadcast::Receiver { + pub fn subscribe(&self, slug: &Slug, board: &str) -> broadcast::Receiver { let mut boards = self.0.lock().expect("board hub lock"); let room = boards - .entry(board.to_string()) + .entry(scoped_key(slug, board)) .or_insert_with(|| (broadcast::channel(crate::constant::BOARD_HUB_CAPACITY).0, 0)); room.1 += 1; room.0.subscribe() @@ -156,10 +170,10 @@ impl BoardHub { /// Push `frame` to every socket currently subscribed to `board`. A send /// with no receivers left is the normal empty-room case, not a failure. - pub fn publish(&self, board: &str, frame: String) { + pub fn publish(&self, slug: &Slug, board: &str, frame: String) { let sender = { let boards = self.0.lock().expect("board hub lock"); - boards.get(board).map(|room| room.0.clone()) + boards.get(&scoped_key(slug, board)).map(|room| room.0.clone()) }; if let Some(sender) = sender { let _ = sender.send(frame); @@ -167,7 +181,8 @@ impl BoardHub { } /// Count one socket out of `board`; the last one out drops the channel. - pub fn leave(&self, board: &str) { + pub fn leave(&self, slug: &Slug, board: &str) { + let board = &scoped_key(slug, board); let mut boards = self.0.lock().expect("board hub lock"); match boards.get_mut(board) { Some(room) if room.1 > 1 => room.1 -= 1, @@ -184,47 +199,94 @@ impl BoardHub { mod tests { use super::*; + fn slug(value: &str) -> Slug { + Slug::try_new(value).expect(value) + } + #[tokio::test] async fn every_subscriber_gets_the_stroke_and_the_room_is_reclaimed() { + let a = slug("alpha"); let hub = BoardHub::default(); - let mut alice = hub.subscribe("board-a"); - let mut bob = hub.subscribe("board-a"); - hub.publish("board-a", "stroke".to_string()); + let mut alice = hub.subscribe(&a, "board-a"); + let mut bob = hub.subscribe(&a, "board-a"); + hub.publish(&a, "board-a", "stroke".to_string()); assert_eq!(alice.recv().await.expect("alice"), "stroke"); assert_eq!(bob.recv().await.expect("bob"), "stroke"); // Boards are independent, and publishing into an empty one is a no-op. - hub.publish("board-b", "nobody home".to_string()); - assert!(!hub.0.lock().unwrap().contains_key("board-b")); + hub.publish(&a, "board-b", "nobody home".to_string()); + assert!(!hub.0.lock().unwrap().contains_key("alpha:board-b")); - hub.leave("board-a"); + hub.leave(&a, "board-a"); assert!( - hub.0.lock().unwrap().contains_key("board-a"), + hub.0.lock().unwrap().contains_key("alpha:board-a"), "one socket of two out keeps the room" ); - hub.leave("board-a"); + hub.leave(&a, "board-a"); assert!( hub.0.lock().unwrap().is_empty(), "the last socket out must drop the entry, or the map leaks" ); } + /// Record keys are unique per database, so two schools routinely hold the + /// same board key. One process serves both — nothing may cross. + #[tokio::test] + async fn a_stroke_never_crosses_into_another_school() { + let (a, b) = (slug("alpha"), slug("beta")); + let hub = BoardHub::default(); + let mut in_a = hub.subscribe(&a, "board-1"); + let mut in_b = hub.subscribe(&b, "board-1"); + + hub.publish(&a, "board-1", "alpha stroke".to_string()); + assert_eq!(in_a.recv().await.expect("alpha's own stroke"), "alpha stroke"); + assert!( + in_b.try_recv().is_err(), + "beta's board must not hear alpha's stroke" + ); + + // And the rooms are counted apart: alpha's last socket out leaves + // beta's room standing. + hub.leave(&a, "board-1"); + let boards = hub.0.lock().unwrap(); + assert!(!boards.contains_key("alpha:board-1")); + assert!(boards.contains_key("beta:board-1")); + } + #[tokio::test] async fn only_the_last_socket_out_is_a_real_exit() { + let a = slug("alpha"); let presence = ExamPresence::default(); - presence.enter("attempt-a"); - presence.enter("attempt-a"); + presence.enter(&a, "attempt-a"); + presence.enter(&a, "attempt-a"); assert!( - !presence.leave("attempt-a"), + !presence.leave(&a, "attempt-a"), "one tab of two is not an exit" ); - assert!(presence.leave("attempt-a"), "the last tab out is"); + assert!(presence.leave(&a, "attempt-a"), "the last tab out is"); // Rooms are independent, and a fresh key starts over. - presence.enter("attempt-b"); - presence.enter("attempt-a"); - assert!(presence.leave("attempt-b")); - assert!(presence.leave("attempt-a")); + presence.enter(&a, "attempt-b"); + presence.enter(&a, "attempt-a"); + assert!(presence.leave(&a, "attempt-b")); + assert!(presence.leave(&a, "attempt-a")); // Unbalanced leaves degrade to "really left", never to a stuck room. - assert!(presence.leave("attempt-a")); + assert!(presence.leave(&a, "attempt-a")); + } + + /// Two schools sitting the same attempt key count separately — otherwise + /// one school's second tab would hold the other school's room open, and + /// its walk-out would go unstamped. + #[tokio::test] + async fn presence_counts_are_per_school() { + let (a, b) = (slug("alpha"), slug("beta")); + let presence = ExamPresence::default(); + presence.enter(&a, "attempt-1"); + presence.enter(&b, "attempt-1"); + assert!( + presence.leave(&a, "attempt-1"), + "alpha's only socket out is alpha's exit, whatever beta is doing" + ); + assert!(presence.leave(&b, "attempt-1")); + assert!(presence.0.lock().unwrap().is_empty()); } } diff --git a/src/web/board_ws.rs b/src/web/board_ws.rs index 220d93a..a520a86 100644 --- a/src/web/board_ws.rs +++ b/src/web/board_ws.rs @@ -58,7 +58,7 @@ use std::collections::VecDeque; use std::time::Duration; -use crate::web::tenant_state::State; +use crate::web::tenant_state::{SchoolSlug, State}; use axum::extract::Path; use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; use axum::response::Response; @@ -75,6 +75,7 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::AppError; use crate::state::AppState; +use crate::tenant::Slug; use crate::web::CurrentUser; use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq}; @@ -118,6 +119,7 @@ enum ClientMessage { /// every action already re-reads through. pub async fn board_ws( State(st): State, + SchoolSlug(slug): SchoolSlug, CurrentUser(user): CurrentUser, Path(id): Path, ws: WebSocketUpgrade, @@ -136,18 +138,18 @@ pub async fn board_ws( } let board_id = board.get_id().clone(); let user_id = user.get_id().clone(); - Ok(ws.on_upgrade(move |socket| room(socket, st, board_id, user_id))) + Ok(ws.on_upgrade(move |socket| room(socket, st, slug, board_id, user_id))) } /// The room loop: the board's frames out, draw/clear/lock/ping in, until the /// socket closes or the board ends (closed, deleted, or the caller taken off /// it). -async fn room(mut socket: WebSocket, st: AppState, board: BoardId, user: UserId) { +async fn room(mut socket: WebSocket, st: AppState, slug: Slug, board: BoardId, user: UserId) { // Subscribe *before* anything is read out of the database: a stroke that // lands between a replay's read and this subscribe would otherwise be lost // outright, whereas one delivered twice is deduplicated by its id at the // client (which a resync forces anyway). - let mut feed = st.board_hub.subscribe(board.key()); + let mut feed = st.board_hub.subscribe(&slug, board.key()); // The ids this socket drew, in the order they were published. The hub has // no idea who is listening, so the room filters its own strokes back out // here — a client that had to ignore the echo of every mark it just drew @@ -176,7 +178,7 @@ async fn room(mut socket: WebSocket, st: AppState, board: BoardId, user: UserId) }, incoming = socket.recv() => match room::classify(incoming) { Incoming::Text(text) => { - handle_message(&mut socket, text.as_str(), &board, &user, &mut mine, &st).await + handle_message(&mut socket, text.as_str(), &slug, &board, &user, &mut mine, &st).await } Incoming::Gone => Err(RoomClosed), Incoming::Ignore => Ok(()), @@ -187,7 +189,7 @@ async fn room(mut socket: WebSocket, st: AppState, board: BoardId, user: UserId) } } room::close(&mut socket).await; - st.board_hub.leave(board.key()); + st.board_hub.leave(&slug, board.key()); } type Step = Result<(), RoomClosed>; @@ -395,6 +397,7 @@ fn stroke_body(stroke: &BoardStroke) -> Value { async fn handle_message( socket: &mut WebSocket, text: &str, + slug: &Slug, board: &BoardId, user: &UserId, mine: &mut VecDeque, @@ -468,7 +471,7 @@ async fn handle_message( fanned["type"] = json!("stroke"); fanned["epoch"] = json!(stroke.get_epoch()); mine.push_back(stroke.get_id().key().to_string()); - st.board_hub.publish(board.key(), fanned.to_string()); + st.board_hub.publish(slug, board.key(), fanned.to_string()); let mut frame = json!({ "type": "saved", "id": stroke.get_id().key() }); with_client_seq(&mut frame, client_seq); send(socket, frame).await @@ -491,6 +494,7 @@ async fn handle_message( // canvas is the next one. Same shape as `POST /boards/{id}/clear`. Ok(marker) => { st.board_hub.publish( + slug, board.key(), json!({ "type": "cleared", @@ -509,6 +513,7 @@ async fn handle_message( Some(live) => match live.set_locked(locked, user, &st.db).await { Ok(_) => { st.board_hub.publish( + slug, board.key(), json!({ "type": "locked", "locked": locked, "by": user.key() }).to_string(), ); diff --git a/src/web/boards.rs b/src/web/boards.rs index 565ec42..3db2f17 100644 --- a/src/web/boards.rs +++ b/src/web/boards.rs @@ -18,7 +18,7 @@ //! mid-session keeps drawing over an already-open socket until the room hears //! about it, so a roster change *must* fan out. -use crate::web::tenant_state::State; +use crate::web::tenant_state::{SchoolSlug, State}; use axum::Json; use axum::extract::{Path, Query}; use axum::http::StatusCode; @@ -41,6 +41,7 @@ use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; +use crate::tenant::Slug; use super::courses::can_manage_course; use super::{CurrentUser, Page, PageParams, RequireStudent, paginate, set_or_clear}; @@ -161,8 +162,8 @@ async fn resolve_participants( /// Push one frame to whoever is in the room right now. An empty room is the /// normal case, not a failure. -fn fan_out(st: &AppState, board: &BoardId, frame: serde_json::Value) { - st.board_hub.publish(board.key(), frame.to_string()); +fn fan_out(st: &AppState, slug: &Slug, board: &BoardId, frame: serde_json::Value) { + st.board_hub.publish(slug, board.key(), frame.to_string()); } /// The roster frame every path that changes the invite list must publish. A @@ -537,6 +538,7 @@ struct UpdateBoard { )] async fn update_board( State(st): State, + SchoolSlug(slug): SchoolSlug, CurrentUser(user): CurrentUser, Path(id): Path, Json(req): Json, @@ -561,12 +563,13 @@ async fn update_board( let participants = resolve_participants(participants, board.get_participants(), &st.db).await?; board = board.set_participants(participants, &st.db).await?; - fan_out(&st, board.get_id(), participants_frame(&board)); + fan_out(&st, &slug, board.get_id(), participants_frame(&board)); } if let Some(locked) = req.locked { board = board.set_locked(locked, user.get_id(), &st.db).await?; fan_out( &st, + &slug, board.get_id(), json!({"type": "locked", "locked": locked, "by": user.get_id().key()}), ); @@ -602,6 +605,7 @@ async fn update_board( )] async fn clear_board( State(st): State, + SchoolSlug(slug): SchoolSlug, CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result<(StatusCode, Json), AppError> { @@ -612,6 +616,7 @@ async fn clear_board( // next one. fan_out( &st, + &slug, board.get_id(), json!({ "type": "cleared", @@ -642,6 +647,7 @@ async fn clear_board( )] async fn close_board( State(st): State, + SchoolSlug(slug): SchoolSlug, CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { @@ -650,6 +656,7 @@ async fn close_board( let board = board.close(&st.db).await?; fan_out( &st, + &slug, board.get_id(), json!({ "type": "closed", @@ -812,6 +819,7 @@ impl InviteSource { )] async fn invite_board( State(st): State, + SchoolSlug(slug): SchoolSlug, CurrentUser(user): CurrentUser, Path(id): Path, Json(req): Json, @@ -852,7 +860,7 @@ async fn invite_board( // branch that has to prove the two lists are equal, and a re-invite that // added nobody is the idempotent case, not the hot path. let board = board.set_participants(roster, &st.db).await?; - fan_out(&st, board.get_id(), participants_frame(&board)); + fan_out(&st, &slug, board.get_id(), participants_frame(&board)); Ok(Json(BoardResponse::new(&board))) } @@ -875,6 +883,7 @@ async fn invite_board( )] async fn delete_board( State(st): State, + SchoolSlug(slug): SchoolSlug, CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result { @@ -884,7 +893,7 @@ async fn delete_board( board.delete(&st.db).await?; // Told after the row is gone: a room that acts on this and then re-reads // must find nothing, not a board about to disappear. - fan_out(&st, &id, json!({"type": "deleted"})); + fan_out(&st, &slug, &id, json!({"type": "deleted"})); Ok(StatusCode::NO_CONTENT) } diff --git a/src/web/chatbot.rs b/src/web/chatbot.rs index e1d5d7c..67c3d0e 100644 --- a/src/web/chatbot.rs +++ b/src/web/chatbot.rs @@ -20,7 +20,7 @@ use std::time::Duration; -use crate::web::tenant_state::State; +use crate::web::tenant_state::{SchoolSlug, State}; use axum::Json; use axum::extract::{Path, Query}; use axum::http::StatusCode; @@ -49,7 +49,7 @@ use crate::domain::role::Role; use crate::domain::settings::Settings; use crate::domain::user::UserId; use crate::error::{AppError, ErrorResponse, ValidationError}; -use crate::state::AppState; +use crate::state::{AppState, scoped_key}; use super::{CurrentUser, Page, PageParams}; @@ -377,12 +377,14 @@ async fn list_messages( )] async fn send_message( State(st): State, + SchoolSlug(slug): SchoolSlug, CurrentUser(user): CurrentUser, Path(id): Path, Json(req): Json, ) -> Result { // Charged first: a rejected turn must cost nothing and leave no row. - st.chatbot_limit.enforce_user(user.get_id().key())?; + st.chatbot_limit + .enforce_user(&scoped_key(&slug, user.get_id().key()))?; let thread = own_thread(&id, user.get_id(), &st.db).await?; let settings = Settings::load(&st.db).await?; diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 440dffc..b6f21c3 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -56,7 +56,7 @@ use std::time::Duration; -use crate::web::tenant_state::State; +use crate::web::tenant_state::{SchoolSlug, State}; use axum::extract::Path; use axum::extract::ws::{WebSocket, WebSocketUpgrade}; use axum::response::Response; @@ -73,6 +73,7 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; use crate::state::AppState; +use crate::tenant::Slug; use crate::validate::validate_required; use crate::web::CurrentUser; use crate::web::exams::{ @@ -138,6 +139,7 @@ enum ClientMessage { /// dying socket's teardown stamp a student who was already reconnecting. pub async fn attempt_ws( State(st): State, + SchoolSlug(slug): SchoolSlug, CurrentUser(user): CurrentUser, Path(id): Path, ws: WebSocketUpgrade, @@ -153,13 +155,20 @@ pub async fn attempt_ws( course_of(&exam, &st.db).await?.require_open(&st.db).await?; let user_id = user.get_id().clone(); - Ok(ws.on_upgrade(move |socket| room(socket, st, exam, attempt, user_id))) + Ok(ws.on_upgrade(move |socket| room(socket, st, slug, exam, attempt, user_id))) } /// The room loop: state ticks out, answer/finish/ping in, until the socket /// closes or the room's sitting reaches a terminal state. The room is bound /// to the attempt it was opened for — `attempt` — and to no later sitting. -async fn room(mut socket: WebSocket, st: AppState, exam: Exam, attempt: ExamAttempt, user: UserId) { +async fn room( + mut socket: WebSocket, + st: AppState, + slug: Slug, + exam: Exam, + attempt: ExamAttempt, + user: UserId, +) { let exam_id = exam.get_id().clone(); let attempt_id = attempt.get_id().clone(); // Join critical section: this socket counts as presence in the sitting's @@ -171,7 +180,7 @@ async fn room(mut socket: WebSocket, st: AppState, exam: Exam, attempt: ExamAtte // failed clear leaves the stamp for the next join or the teacher's door. { let _guard = PRESENCE_LOCK.lock().await; - st.exam_presence.enter(attempt_id.key()); + st.exam_presence.enter(&slug, attempt_id.key()); if let Err(err) = attempt.set_left(None, &st.db).await { tracing::warn!("exam room could not clear left_at on join: {err}"); } @@ -211,7 +220,7 @@ async fn room(mut socket: WebSocket, st: AppState, exam: Exam, attempt: ExamAtte // superseded by a retake is terminal) need no stamp. Best-effort: a // failed stamp only means it goes unrecorded. let _guard = PRESENCE_LOCK.lock().await; - if st.exam_presence.leave(attempt_id.key()) { + if st.exam_presence.leave(&slug, attempt_id.key()) { stamp_left(&exam_id, &attempt_id, &st.db).await; } } diff --git a/src/web/users.rs b/src/web/users.rs index 6e15242..3cd9ace 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -1,4 +1,4 @@ -use crate::web::tenant_state::State; +use crate::web::tenant_state::{SchoolSlug, State}; use axum::Json; use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; use axum::http::StatusCode; @@ -463,6 +463,7 @@ async fn update_user_preferences( )] async fn set_role( State(st): State, + SchoolSlug(slug): SchoolSlug, RequireAdmin(admin): RequireAdmin, Path(id): Path, Json(req): Json, @@ -490,6 +491,7 @@ async fn set_role( // stroke came back refused. for board in boards { st.board_hub.publish( + &slug, board.get_id().key(), json!({ "type": "participants", @@ -504,6 +506,7 @@ async fn set_role( ); if let Some(closed_at) = board.get_closed_at() { st.board_hub.publish( + &slug, board.get_id().key(), json!({"type": "closed", "closed_at": closed_at.as_millis()}).to_string(), );