Exam presence, board hub and chatbot limiter keys are school-scoped
Browse files at this commit4f92feaebc0116acf1f745e5f51bb06f959de677Parent: b7dfc0c- fix
- exam presence, board hub and chatbot limiter keys are school-scoped
6 changed files +140 -50
- src/state.rs +90 -28
- src/web/board_ws.rs +12 -7
- src/web/boards.rs +15 -6
- src/web/chatbot.rs +5 -3
- src/web/exam_ws.rs +14 -5
- src/web/users.rs +4 -1
src/state.rsmodified+90 -28
| @@ -8,7 +8,7 @@ use tokio::sync::broadcast; | |||
| 8 | use crate::ai::AiBridge; | 8 | use crate::ai::AiBridge; |
| 9 | use crate::database::Database; | 9 | use crate::database::Database; |
| 10 | use crate::rate_limit::{RateLimitConfig, UserRateLimiter}; | 10 | use crate::rate_limit::{RateLimitConfig, UserRateLimiter}; |
| 11 | -use crate::tenant::Tenants; | 11 | +use crate::tenant::{Slug, Tenants}; |
| 12 | 12 | ||
| 13 | /// Shared application state handed to every handler. | 13 | /// Shared application state handed to every handler. |
| 14 | #[derive(Clone)] | 14 | #[derive(Clone)] |
| @@ -88,8 +88,20 @@ impl DbHealth { | |||
| 88 | } | 88 | } |
| 89 | } | 89 | } |
| 90 | 90 | ||
| 91 | +/// The map key for `key` inside `slug`'s school. One process serves every | ||
| 92 | +/// school, but record keys are only unique *within* a database, so an | ||
| 93 | +/// unscoped key would put two schools' identical attempts (or boards) in the | ||
| 94 | +/// same room. The maps below are the only users of this, and their methods | ||
| 95 | +/// take a [`Slug`] rather than a ready-made key — there is no way to reach one | ||
| 96 | +/// with an unscoped string. The per-user chatbot limiter keys through here | ||
| 97 | +/// too, for the same reason. A slug cannot contain `:`, so the join is | ||
| 98 | +/// unambiguous. | ||
| 99 | +pub fn scoped_key(slug: &Slug, key: &str) -> String { | ||
| 100 | + format!("{slug}:{key}") | ||
| 101 | +} | ||
| 102 | + | ||
| 91 | /// How many exam-room sockets each attempt has open right now, keyed by the | 103 | /// How many exam-room sockets each attempt has open right now, keyed by the |
| 92 | -/// attempt's record key. The room counts itself in on entry and out on exit, | 104 | +/// attempt's record key within its school. The room counts itself in on entry and out on exit, |
| 93 | /// and only the last socket out stamps the walk-out (`left_at`) — a student | 105 | /// and only the last socket out stamps the walk-out (`left_at`) — a student |
| 94 | /// closing one of two tabs never counts as having left the exam. | 106 | /// closing one of two tabs never counts as having left the exam. |
| 95 | /// | 107 | /// |
| @@ -103,14 +115,15 @@ pub struct ExamPresence(Arc<Mutex<HashMap<String, usize>>>); | |||
| 103 | 115 | ||
| 104 | impl ExamPresence { | 116 | impl ExamPresence { |
| 105 | /// Count one socket into `attempt`'s room. | 117 | /// Count one socket into `attempt`'s room. |
| 106 | - pub fn enter(&self, attempt: &str) { | 118 | + pub fn enter(&self, slug: &Slug, attempt: &str) { |
| 107 | let mut rooms = self.0.lock().expect("exam presence lock"); | 119 | let mut rooms = self.0.lock().expect("exam presence lock"); |
| 108 | - *rooms.entry(attempt.to_string()).or_insert(0) += 1; | 120 | + *rooms.entry(scoped_key(slug, attempt)).or_insert(0) += 1; |
| 109 | } | 121 | } |
| 110 | 122 | ||
| 111 | /// Count one socket out of `attempt`'s room; `true` when it was the last | 123 | /// Count one socket out of `attempt`'s room; `true` when it was the last |
| 112 | /// one — the student has actually left. | 124 | /// one — the student has actually left. |
| 113 | - pub fn leave(&self, attempt: &str) -> bool { | 125 | + pub fn leave(&self, slug: &Slug, attempt: &str) -> bool { |
| 126 | + let attempt = &scoped_key(slug, attempt); | ||
| 114 | let mut rooms = self.0.lock().expect("exam presence lock"); | 127 | let mut rooms = self.0.lock().expect("exam presence lock"); |
| 115 | match rooms.get_mut(attempt) { | 128 | match rooms.get_mut(attempt) { |
| 116 | Some(count) if *count > 1 => { | 129 | Some(count) if *count > 1 => { |
| @@ -128,7 +141,8 @@ impl ExamPresence { | |||
| 128 | } | 141 | } |
| 129 | } | 142 | } |
| 130 | 143 | ||
| 131 | -/// One broadcast channel per live whiteboard, keyed by the board's record key, | 144 | +/// One broadcast channel per live whiteboard, keyed by the board's record key |
| 145 | +/// within its school, | ||
| 132 | /// so a stroke saved by one socket reaches every *other* socket in that board. | 146 | /// so a stroke saved by one socket reaches every *other* socket in that board. |
| 133 | /// Nothing else in this codebase fans out — an exam room only ever replies to | 147 | /// Nothing else in this codebase fans out — an exam room only ever replies to |
| 134 | /// the socket that spoke — so this is the only multi-subscriber push we have. | 148 | /// the socket that spoke — so this is the only multi-subscriber push we have. |
| @@ -145,10 +159,10 @@ pub struct BoardHub(Arc<Mutex<HashMap<String, (broadcast::Sender<String>, usize) | |||
| 145 | impl BoardHub { | 159 | impl BoardHub { |
| 146 | /// Count one socket into `board` and hand back its stream of other | 160 | /// Count one socket into `board` and hand back its stream of other |
| 147 | /// people's frames, creating the channel on the first join. | 161 | /// people's frames, creating the channel on the first join. |
| 148 | - pub fn subscribe(&self, board: &str) -> broadcast::Receiver<String> { | 162 | + pub fn subscribe(&self, slug: &Slug, board: &str) -> broadcast::Receiver<String> { |
| 149 | let mut boards = self.0.lock().expect("board hub lock"); | 163 | let mut boards = self.0.lock().expect("board hub lock"); |
| 150 | let room = boards | 164 | let room = boards |
| 151 | - .entry(board.to_string()) | 165 | + .entry(scoped_key(slug, board)) |
| 152 | .or_insert_with(|| (broadcast::channel(crate::constant::BOARD_HUB_CAPACITY).0, 0)); | 166 | .or_insert_with(|| (broadcast::channel(crate::constant::BOARD_HUB_CAPACITY).0, 0)); |
| 153 | room.1 += 1; | 167 | room.1 += 1; |
| 154 | room.0.subscribe() | 168 | room.0.subscribe() |
| @@ -156,10 +170,10 @@ impl BoardHub { | |||
| 156 | 170 | ||
| 157 | /// Push `frame` to every socket currently subscribed to `board`. A send | 171 | /// Push `frame` to every socket currently subscribed to `board`. A send |
| 158 | /// with no receivers left is the normal empty-room case, not a failure. | 172 | /// with no receivers left is the normal empty-room case, not a failure. |
| 159 | - pub fn publish(&self, board: &str, frame: String) { | 173 | + pub fn publish(&self, slug: &Slug, board: &str, frame: String) { |
| 160 | let sender = { | 174 | let sender = { |
| 161 | let boards = self.0.lock().expect("board hub lock"); | 175 | let boards = self.0.lock().expect("board hub lock"); |
| 162 | - boards.get(board).map(|room| room.0.clone()) | 176 | + boards.get(&scoped_key(slug, board)).map(|room| room.0.clone()) |
| 163 | }; | 177 | }; |
| 164 | if let Some(sender) = sender { | 178 | if let Some(sender) = sender { |
| 165 | let _ = sender.send(frame); | 179 | let _ = sender.send(frame); |
| @@ -167,7 +181,8 @@ impl BoardHub { | |||
| 167 | } | 181 | } |
| 168 | 182 | ||
| 169 | /// Count one socket out of `board`; the last one out drops the channel. | 183 | /// Count one socket out of `board`; the last one out drops the channel. |
| 170 | - pub fn leave(&self, board: &str) { | 184 | + pub fn leave(&self, slug: &Slug, board: &str) { |
| 185 | + let board = &scoped_key(slug, board); | ||
| 171 | let mut boards = self.0.lock().expect("board hub lock"); | 186 | let mut boards = self.0.lock().expect("board hub lock"); |
| 172 | match boards.get_mut(board) { | 187 | match boards.get_mut(board) { |
| 173 | Some(room) if room.1 > 1 => room.1 -= 1, | 188 | Some(room) if room.1 > 1 => room.1 -= 1, |
| @@ -184,47 +199,94 @@ impl BoardHub { | |||
| 184 | mod tests { | 199 | mod tests { |
| 185 | use super::*; | 200 | use super::*; |
| 186 | 201 | ||
| 202 | + fn slug(value: &str) -> Slug { | ||
| 203 | + Slug::try_new(value).expect(value) | ||
| 204 | + } | ||
| 205 | + | ||
| 187 | #[tokio::test] | 206 | #[tokio::test] |
| 188 | async fn every_subscriber_gets_the_stroke_and_the_room_is_reclaimed() { | 207 | async fn every_subscriber_gets_the_stroke_and_the_room_is_reclaimed() { |
| 208 | + let a = slug("alpha"); | ||
| 189 | let hub = BoardHub::default(); | 209 | let hub = BoardHub::default(); |
| 190 | - let mut alice = hub.subscribe("board-a"); | 210 | + let mut alice = hub.subscribe(&a, "board-a"); |
| 191 | - let mut bob = hub.subscribe("board-a"); | 211 | + let mut bob = hub.subscribe(&a, "board-a"); |
| 192 | - hub.publish("board-a", "stroke".to_string()); | 212 | + hub.publish(&a, "board-a", "stroke".to_string()); |
| 193 | assert_eq!(alice.recv().await.expect("alice"), "stroke"); | 213 | assert_eq!(alice.recv().await.expect("alice"), "stroke"); |
| 194 | assert_eq!(bob.recv().await.expect("bob"), "stroke"); | 214 | assert_eq!(bob.recv().await.expect("bob"), "stroke"); |
| 195 | 215 | ||
| 196 | // Boards are independent, and publishing into an empty one is a no-op. | 216 | // Boards are independent, and publishing into an empty one is a no-op. |
| 197 | - hub.publish("board-b", "nobody home".to_string()); | 217 | + hub.publish(&a, "board-b", "nobody home".to_string()); |
| 198 | - assert!(!hub.0.lock().unwrap().contains_key("board-b")); | 218 | + assert!(!hub.0.lock().unwrap().contains_key("alpha:board-b")); |
| 199 | 219 | ||
| 200 | - hub.leave("board-a"); | 220 | + hub.leave(&a, "board-a"); |
| 201 | assert!( | 221 | assert!( |
| 202 | - hub.0.lock().unwrap().contains_key("board-a"), | 222 | + hub.0.lock().unwrap().contains_key("alpha:board-a"), |
| 203 | "one socket of two out keeps the room" | 223 | "one socket of two out keeps the room" |
| 204 | ); | 224 | ); |
| 205 | - hub.leave("board-a"); | 225 | + hub.leave(&a, "board-a"); |
| 206 | assert!( | 226 | assert!( |
| 207 | hub.0.lock().unwrap().is_empty(), | 227 | hub.0.lock().unwrap().is_empty(), |
| 208 | "the last socket out must drop the entry, or the map leaks" | 228 | "the last socket out must drop the entry, or the map leaks" |
| 209 | ); | 229 | ); |
| 210 | } | 230 | } |
| 211 | 231 | ||
| 232 | + /// Record keys are unique per database, so two schools routinely hold the | ||
| 233 | + /// same board key. One process serves both — nothing may cross. | ||
| 234 | + #[tokio::test] | ||
| 235 | + async fn a_stroke_never_crosses_into_another_school() { | ||
| 236 | + let (a, b) = (slug("alpha"), slug("beta")); | ||
| 237 | + let hub = BoardHub::default(); | ||
| 238 | + let mut in_a = hub.subscribe(&a, "board-1"); | ||
| 239 | + let mut in_b = hub.subscribe(&b, "board-1"); | ||
| 240 | + | ||
| 241 | + hub.publish(&a, "board-1", "alpha stroke".to_string()); | ||
| 242 | + assert_eq!(in_a.recv().await.expect("alpha's own stroke"), "alpha stroke"); | ||
| 243 | + assert!( | ||
| 244 | + in_b.try_recv().is_err(), | ||
| 245 | + "beta's board must not hear alpha's stroke" | ||
| 246 | + ); | ||
| 247 | + | ||
| 248 | + // And the rooms are counted apart: alpha's last socket out leaves | ||
| 249 | + // beta's room standing. | ||
| 250 | + hub.leave(&a, "board-1"); | ||
| 251 | + let boards = hub.0.lock().unwrap(); | ||
| 252 | + assert!(!boards.contains_key("alpha:board-1")); | ||
| 253 | + assert!(boards.contains_key("beta:board-1")); | ||
| 254 | + } | ||
| 255 | + | ||
| 212 | #[tokio::test] | 256 | #[tokio::test] |
| 213 | async fn only_the_last_socket_out_is_a_real_exit() { | 257 | async fn only_the_last_socket_out_is_a_real_exit() { |
| 258 | + let a = slug("alpha"); | ||
| 214 | let presence = ExamPresence::default(); | 259 | let presence = ExamPresence::default(); |
| 215 | - presence.enter("attempt-a"); | 260 | + presence.enter(&a, "attempt-a"); |
| 216 | - presence.enter("attempt-a"); | 261 | + presence.enter(&a, "attempt-a"); |
| 217 | assert!( | 262 | assert!( |
| 218 | - !presence.leave("attempt-a"), | 263 | + !presence.leave(&a, "attempt-a"), |
| 219 | "one tab of two is not an exit" | 264 | "one tab of two is not an exit" |
| 220 | ); | 265 | ); |
| 221 | - assert!(presence.leave("attempt-a"), "the last tab out is"); | 266 | + assert!(presence.leave(&a, "attempt-a"), "the last tab out is"); |
| 222 | // Rooms are independent, and a fresh key starts over. | 267 | // Rooms are independent, and a fresh key starts over. |
| 223 | - presence.enter("attempt-b"); | 268 | + presence.enter(&a, "attempt-b"); |
| 224 | - presence.enter("attempt-a"); | 269 | + presence.enter(&a, "attempt-a"); |
| 225 | - assert!(presence.leave("attempt-b")); | 270 | + assert!(presence.leave(&a, "attempt-b")); |
| 226 | - assert!(presence.leave("attempt-a")); | 271 | + assert!(presence.leave(&a, "attempt-a")); |
| 227 | // Unbalanced leaves degrade to "really left", never to a stuck room. | 272 | // Unbalanced leaves degrade to "really left", never to a stuck room. |
| 228 | - assert!(presence.leave("attempt-a")); | 273 | + assert!(presence.leave(&a, "attempt-a")); |
| 274 | + } | ||
| 275 | + | ||
| 276 | + /// Two schools sitting the same attempt key count separately — otherwise | ||
| 277 | + /// one school's second tab would hold the other school's room open, and | ||
| 278 | + /// its walk-out would go unstamped. | ||
| 279 | + #[tokio::test] | ||
| 280 | + async fn presence_counts_are_per_school() { | ||
| 281 | + let (a, b) = (slug("alpha"), slug("beta")); | ||
| 282 | + let presence = ExamPresence::default(); | ||
| 283 | + presence.enter(&a, "attempt-1"); | ||
| 284 | + presence.enter(&b, "attempt-1"); | ||
| 285 | + assert!( | ||
| 286 | + presence.leave(&a, "attempt-1"), | ||
| 287 | + "alpha's only socket out is alpha's exit, whatever beta is doing" | ||
| 288 | + ); | ||
| 289 | + assert!(presence.leave(&b, "attempt-1")); | ||
| 290 | + assert!(presence.0.lock().unwrap().is_empty()); | ||
| 229 | } | 291 | } |
| 230 | } | 292 | } |
src/web/board_ws.rsmodified+12 -7
| @@ -58,7 +58,7 @@ | |||
| 58 | use std::collections::VecDeque; | 58 | use std::collections::VecDeque; |
| 59 | use std::time::Duration; | 59 | use std::time::Duration; |
| 60 | 60 | ||
| 61 | -use crate::web::tenant_state::State; | 61 | +use crate::web::tenant_state::{SchoolSlug, State}; |
| 62 | use axum::extract::Path; | 62 | use axum::extract::Path; |
| 63 | use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; | 63 | use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; |
| 64 | use axum::response::Response; | 64 | use axum::response::Response; |
| @@ -75,6 +75,7 @@ use crate::domain::timestamp::Timestamp; | |||
| 75 | use crate::domain::user::{User, UserId}; | 75 | use crate::domain::user::{User, UserId}; |
| 76 | use crate::error::AppError; | 76 | use crate::error::AppError; |
| 77 | use crate::state::AppState; | 77 | use crate::state::AppState; |
| 78 | +use crate::tenant::Slug; | ||
| 78 | use crate::web::CurrentUser; | 79 | use crate::web::CurrentUser; |
| 79 | use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq}; | 80 | use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq}; |
| 80 | 81 | ||
| @@ -118,6 +119,7 @@ enum ClientMessage { | |||
| 118 | /// every action already re-reads through. | 119 | /// every action already re-reads through. |
| 119 | pub async fn board_ws( | 120 | pub async fn board_ws( |
| 120 | State(st): State<AppState>, | 121 | State(st): State<AppState>, |
| 122 | + SchoolSlug(slug): SchoolSlug, | ||
| 121 | CurrentUser(user): CurrentUser, | 123 | CurrentUser(user): CurrentUser, |
| 122 | Path(id): Path<String>, | 124 | Path(id): Path<String>, |
| 123 | ws: WebSocketUpgrade, | 125 | ws: WebSocketUpgrade, |
| @@ -136,18 +138,18 @@ pub async fn board_ws( | |||
| 136 | } | 138 | } |
| 137 | let board_id = board.get_id().clone(); | 139 | let board_id = board.get_id().clone(); |
| 138 | let user_id = user.get_id().clone(); | 140 | let user_id = user.get_id().clone(); |
| 139 | - Ok(ws.on_upgrade(move |socket| room(socket, st, board_id, user_id))) | 141 | + Ok(ws.on_upgrade(move |socket| room(socket, st, slug, board_id, user_id))) |
| 140 | } | 142 | } |
| 141 | 143 | ||
| 142 | /// The room loop: the board's frames out, draw/clear/lock/ping in, until the | 144 | /// The room loop: the board's frames out, draw/clear/lock/ping in, until the |
| 143 | /// socket closes or the board ends (closed, deleted, or the caller taken off | 145 | /// socket closes or the board ends (closed, deleted, or the caller taken off |
| 144 | /// it). | 146 | /// it). |
| 145 | -async fn room(mut socket: WebSocket, st: AppState, board: BoardId, user: UserId) { | 147 | +async fn room(mut socket: WebSocket, st: AppState, slug: Slug, board: BoardId, user: UserId) { |
| 146 | // Subscribe *before* anything is read out of the database: a stroke that | 148 | // Subscribe *before* anything is read out of the database: a stroke that |
| 147 | // lands between a replay's read and this subscribe would otherwise be lost | 149 | // lands between a replay's read and this subscribe would otherwise be lost |
| 148 | // outright, whereas one delivered twice is deduplicated by its id at the | 150 | // outright, whereas one delivered twice is deduplicated by its id at the |
| 149 | // client (which a resync forces anyway). | 151 | // client (which a resync forces anyway). |
| 150 | - let mut feed = st.board_hub.subscribe(board.key()); | 152 | + let mut feed = st.board_hub.subscribe(&slug, board.key()); |
| 151 | // The ids this socket drew, in the order they were published. The hub has | 153 | // The ids this socket drew, in the order they were published. The hub has |
| 152 | // no idea who is listening, so the room filters its own strokes back out | 154 | // no idea who is listening, so the room filters its own strokes back out |
| 153 | // here — a client that had to ignore the echo of every mark it just drew | 155 | // 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) | |||
| 176 | }, | 178 | }, |
| 177 | incoming = socket.recv() => match room::classify(incoming) { | 179 | incoming = socket.recv() => match room::classify(incoming) { |
| 178 | Incoming::Text(text) => { | 180 | Incoming::Text(text) => { |
| 179 | - handle_message(&mut socket, text.as_str(), &board, &user, &mut mine, &st).await | 181 | + handle_message(&mut socket, text.as_str(), &slug, &board, &user, &mut mine, &st).await |
| 180 | } | 182 | } |
| 181 | Incoming::Gone => Err(RoomClosed), | 183 | Incoming::Gone => Err(RoomClosed), |
| 182 | Incoming::Ignore => Ok(()), | 184 | Incoming::Ignore => Ok(()), |
| @@ -187,7 +189,7 @@ async fn room(mut socket: WebSocket, st: AppState, board: BoardId, user: UserId) | |||
| 187 | } | 189 | } |
| 188 | } | 190 | } |
| 189 | room::close(&mut socket).await; | 191 | room::close(&mut socket).await; |
| 190 | - st.board_hub.leave(board.key()); | 192 | + st.board_hub.leave(&slug, board.key()); |
| 191 | } | 193 | } |
| 192 | 194 | ||
| 193 | type Step = Result<(), RoomClosed>; | 195 | type Step = Result<(), RoomClosed>; |
| @@ -395,6 +397,7 @@ fn stroke_body(stroke: &BoardStroke) -> Value { | |||
| 395 | async fn handle_message( | 397 | async fn handle_message( |
| 396 | socket: &mut WebSocket, | 398 | socket: &mut WebSocket, |
| 397 | text: &str, | 399 | text: &str, |
| 400 | + slug: &Slug, | ||
| 398 | board: &BoardId, | 401 | board: &BoardId, |
| 399 | user: &UserId, | 402 | user: &UserId, |
| 400 | mine: &mut VecDeque<String>, | 403 | mine: &mut VecDeque<String>, |
| @@ -468,7 +471,7 @@ async fn handle_message( | |||
| 468 | fanned["type"] = json!("stroke"); | 471 | fanned["type"] = json!("stroke"); |
| 469 | fanned["epoch"] = json!(stroke.get_epoch()); | 472 | fanned["epoch"] = json!(stroke.get_epoch()); |
| 470 | mine.push_back(stroke.get_id().key().to_string()); | 473 | mine.push_back(stroke.get_id().key().to_string()); |
| 471 | - st.board_hub.publish(board.key(), fanned.to_string()); | 474 | + st.board_hub.publish(slug, board.key(), fanned.to_string()); |
| 472 | let mut frame = json!({ "type": "saved", "id": stroke.get_id().key() }); | 475 | let mut frame = json!({ "type": "saved", "id": stroke.get_id().key() }); |
| 473 | with_client_seq(&mut frame, client_seq); | 476 | with_client_seq(&mut frame, client_seq); |
| 474 | send(socket, frame).await | 477 | send(socket, frame).await |
| @@ -491,6 +494,7 @@ async fn handle_message( | |||
| 491 | // canvas is the next one. Same shape as `POST /boards/{id}/clear`. | 494 | // canvas is the next one. Same shape as `POST /boards/{id}/clear`. |
| 492 | Ok(marker) => { | 495 | Ok(marker) => { |
| 493 | st.board_hub.publish( | 496 | st.board_hub.publish( |
| 497 | + slug, | ||
| 494 | board.key(), | 498 | board.key(), |
| 495 | json!({ | 499 | json!({ |
| 496 | "type": "cleared", | 500 | "type": "cleared", |
| @@ -509,6 +513,7 @@ async fn handle_message( | |||
| 509 | Some(live) => match live.set_locked(locked, user, &st.db).await { | 513 | Some(live) => match live.set_locked(locked, user, &st.db).await { |
| 510 | Ok(_) => { | 514 | Ok(_) => { |
| 511 | st.board_hub.publish( | 515 | st.board_hub.publish( |
| 516 | + slug, | ||
| 512 | board.key(), | 517 | board.key(), |
| 513 | json!({ "type": "locked", "locked": locked, "by": user.key() }).to_string(), | 518 | json!({ "type": "locked", "locked": locked, "by": user.key() }).to_string(), |
| 514 | ); | 519 | ); |
src/web/boards.rsmodified+15 -6
| @@ -18,7 +18,7 @@ | |||
| 18 | //! mid-session keeps drawing over an already-open socket until the room hears | 18 | //! mid-session keeps drawing over an already-open socket until the room hears |
| 19 | //! about it, so a roster change *must* fan out. | 19 | //! about it, so a roster change *must* fan out. |
| 20 | 20 | ||
| 21 | -use crate::web::tenant_state::State; | 21 | +use crate::web::tenant_state::{SchoolSlug, State}; |
| 22 | use axum::Json; | 22 | use axum::Json; |
| 23 | use axum::extract::{Path, Query}; | 23 | use axum::extract::{Path, Query}; |
| 24 | use axum::http::StatusCode; | 24 | use axum::http::StatusCode; |
| @@ -41,6 +41,7 @@ use crate::domain::role::Role; | |||
| 41 | use crate::domain::user::{User, UserId}; | 41 | use crate::domain::user::{User, UserId}; |
| 42 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 42 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 43 | use crate::state::AppState; | 43 | use crate::state::AppState; |
| 44 | +use crate::tenant::Slug; | ||
| 44 | 45 | ||
| 45 | use super::courses::can_manage_course; | 46 | use super::courses::can_manage_course; |
| 46 | use super::{CurrentUser, Page, PageParams, RequireStudent, paginate, set_or_clear}; | 47 | use super::{CurrentUser, Page, PageParams, RequireStudent, paginate, set_or_clear}; |
| @@ -161,8 +162,8 @@ async fn resolve_participants( | |||
| 161 | 162 | ||
| 162 | /// Push one frame to whoever is in the room right now. An empty room is the | 163 | /// Push one frame to whoever is in the room right now. An empty room is the |
| 163 | /// normal case, not a failure. | 164 | /// normal case, not a failure. |
| 164 | -fn fan_out(st: &AppState, board: &BoardId, frame: serde_json::Value) { | 165 | +fn fan_out(st: &AppState, slug: &Slug, board: &BoardId, frame: serde_json::Value) { |
| 165 | - st.board_hub.publish(board.key(), frame.to_string()); | 166 | + st.board_hub.publish(slug, board.key(), frame.to_string()); |
| 166 | } | 167 | } |
| 167 | 168 | ||
| 168 | /// The roster frame every path that changes the invite list must publish. A | 169 | /// The roster frame every path that changes the invite list must publish. A |
| @@ -537,6 +538,7 @@ struct UpdateBoard { | |||
| 537 | )] | 538 | )] |
| 538 | async fn update_board( | 539 | async fn update_board( |
| 539 | State(st): State<AppState>, | 540 | State(st): State<AppState>, |
| 541 | + SchoolSlug(slug): SchoolSlug, | ||
| 540 | CurrentUser(user): CurrentUser, | 542 | CurrentUser(user): CurrentUser, |
| 541 | Path(id): Path<String>, | 543 | Path(id): Path<String>, |
| 542 | Json(req): Json<UpdateBoard>, | 544 | Json(req): Json<UpdateBoard>, |
| @@ -561,12 +563,13 @@ async fn update_board( | |||
| 561 | let participants = | 563 | let participants = |
| 562 | resolve_participants(participants, board.get_participants(), &st.db).await?; | 564 | resolve_participants(participants, board.get_participants(), &st.db).await?; |
| 563 | board = board.set_participants(participants, &st.db).await?; | 565 | board = board.set_participants(participants, &st.db).await?; |
| 564 | - fan_out(&st, board.get_id(), participants_frame(&board)); | 566 | + fan_out(&st, &slug, board.get_id(), participants_frame(&board)); |
| 565 | } | 567 | } |
| 566 | if let Some(locked) = req.locked { | 568 | if let Some(locked) = req.locked { |
| 567 | board = board.set_locked(locked, user.get_id(), &st.db).await?; | 569 | board = board.set_locked(locked, user.get_id(), &st.db).await?; |
| 568 | fan_out( | 570 | fan_out( |
| 569 | &st, | 571 | &st, |
| 572 | + &slug, | ||
| 570 | board.get_id(), | 573 | board.get_id(), |
| 571 | json!({"type": "locked", "locked": locked, "by": user.get_id().key()}), | 574 | json!({"type": "locked", "locked": locked, "by": user.get_id().key()}), |
| 572 | ); | 575 | ); |
| @@ -602,6 +605,7 @@ async fn update_board( | |||
| 602 | )] | 605 | )] |
| 603 | async fn clear_board( | 606 | async fn clear_board( |
| 604 | State(st): State<AppState>, | 607 | State(st): State<AppState>, |
| 608 | + SchoolSlug(slug): SchoolSlug, | ||
| 605 | CurrentUser(user): CurrentUser, | 609 | CurrentUser(user): CurrentUser, |
| 606 | Path(id): Path<String>, | 610 | Path(id): Path<String>, |
| 607 | ) -> Result<(StatusCode, Json<StrokeResponse>), AppError> { | 611 | ) -> Result<(StatusCode, Json<StrokeResponse>), AppError> { |
| @@ -612,6 +616,7 @@ async fn clear_board( | |||
| 612 | // next one. | 616 | // next one. |
| 613 | fan_out( | 617 | fan_out( |
| 614 | &st, | 618 | &st, |
| 619 | + &slug, | ||
| 615 | board.get_id(), | 620 | board.get_id(), |
| 616 | json!({ | 621 | json!({ |
| 617 | "type": "cleared", | 622 | "type": "cleared", |
| @@ -642,6 +647,7 @@ async fn clear_board( | |||
| 642 | )] | 647 | )] |
| 643 | async fn close_board( | 648 | async fn close_board( |
| 644 | State(st): State<AppState>, | 649 | State(st): State<AppState>, |
| 650 | + SchoolSlug(slug): SchoolSlug, | ||
| 645 | CurrentUser(user): CurrentUser, | 651 | CurrentUser(user): CurrentUser, |
| 646 | Path(id): Path<String>, | 652 | Path(id): Path<String>, |
| 647 | ) -> Result<Json<BoardResponse>, AppError> { | 653 | ) -> Result<Json<BoardResponse>, AppError> { |
| @@ -650,6 +656,7 @@ async fn close_board( | |||
| 650 | let board = board.close(&st.db).await?; | 656 | let board = board.close(&st.db).await?; |
| 651 | fan_out( | 657 | fan_out( |
| 652 | &st, | 658 | &st, |
| 659 | + &slug, | ||
| 653 | board.get_id(), | 660 | board.get_id(), |
| 654 | json!({ | 661 | json!({ |
| 655 | "type": "closed", | 662 | "type": "closed", |
| @@ -812,6 +819,7 @@ impl InviteSource { | |||
| 812 | )] | 819 | )] |
| 813 | async fn invite_board( | 820 | async fn invite_board( |
| 814 | State(st): State<AppState>, | 821 | State(st): State<AppState>, |
| 822 | + SchoolSlug(slug): SchoolSlug, | ||
| 815 | CurrentUser(user): CurrentUser, | 823 | CurrentUser(user): CurrentUser, |
| 816 | Path(id): Path<String>, | 824 | Path(id): Path<String>, |
| 817 | Json(req): Json<InviteSource>, | 825 | Json(req): Json<InviteSource>, |
| @@ -852,7 +860,7 @@ async fn invite_board( | |||
| 852 | // branch that has to prove the two lists are equal, and a re-invite that | 860 | // branch that has to prove the two lists are equal, and a re-invite that |
| 853 | // added nobody is the idempotent case, not the hot path. | 861 | // added nobody is the idempotent case, not the hot path. |
| 854 | let board = board.set_participants(roster, &st.db).await?; | 862 | let board = board.set_participants(roster, &st.db).await?; |
| 855 | - fan_out(&st, board.get_id(), participants_frame(&board)); | 863 | + fan_out(&st, &slug, board.get_id(), participants_frame(&board)); |
| 856 | Ok(Json(BoardResponse::new(&board))) | 864 | Ok(Json(BoardResponse::new(&board))) |
| 857 | } | 865 | } |
| 858 | 866 | ||
| @@ -875,6 +883,7 @@ async fn invite_board( | |||
| 875 | )] | 883 | )] |
| 876 | async fn delete_board( | 884 | async fn delete_board( |
| 877 | State(st): State<AppState>, | 885 | State(st): State<AppState>, |
| 886 | + SchoolSlug(slug): SchoolSlug, | ||
| 878 | CurrentUser(user): CurrentUser, | 887 | CurrentUser(user): CurrentUser, |
| 879 | Path(id): Path<String>, | 888 | Path(id): Path<String>, |
| 880 | ) -> Result<StatusCode, AppError> { | 889 | ) -> Result<StatusCode, AppError> { |
| @@ -884,7 +893,7 @@ async fn delete_board( | |||
| 884 | board.delete(&st.db).await?; | 893 | board.delete(&st.db).await?; |
| 885 | // Told after the row is gone: a room that acts on this and then re-reads | 894 | // Told after the row is gone: a room that acts on this and then re-reads |
| 886 | // must find nothing, not a board about to disappear. | 895 | // must find nothing, not a board about to disappear. |
| 887 | - fan_out(&st, &id, json!({"type": "deleted"})); | 896 | + fan_out(&st, &slug, &id, json!({"type": "deleted"})); |
| 888 | Ok(StatusCode::NO_CONTENT) | 897 | Ok(StatusCode::NO_CONTENT) |
| 889 | } | 898 | } |
| 890 | 899 | ||
src/web/chatbot.rsmodified+5 -3
| @@ -20,7 +20,7 @@ | |||
| 20 | 20 | ||
| 21 | use std::time::Duration; | 21 | use std::time::Duration; |
| 22 | 22 | ||
| 23 | -use crate::web::tenant_state::State; | 23 | +use crate::web::tenant_state::{SchoolSlug, State}; |
| 24 | use axum::Json; | 24 | use axum::Json; |
| 25 | use axum::extract::{Path, Query}; | 25 | use axum::extract::{Path, Query}; |
| 26 | use axum::http::StatusCode; | 26 | use axum::http::StatusCode; |
| @@ -49,7 +49,7 @@ use crate::domain::role::Role; | |||
| 49 | use crate::domain::settings::Settings; | 49 | use crate::domain::settings::Settings; |
| 50 | use crate::domain::user::UserId; | 50 | use crate::domain::user::UserId; |
| 51 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 51 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 52 | -use crate::state::AppState; | 52 | +use crate::state::{AppState, scoped_key}; |
| 53 | 53 | ||
| 54 | use super::{CurrentUser, Page, PageParams}; | 54 | use super::{CurrentUser, Page, PageParams}; |
| 55 | 55 | ||
| @@ -377,12 +377,14 @@ async fn list_messages( | |||
| 377 | )] | 377 | )] |
| 378 | async fn send_message( | 378 | async fn send_message( |
| 379 | State(st): State<AppState>, | 379 | State(st): State<AppState>, |
| 380 | + SchoolSlug(slug): SchoolSlug, | ||
| 380 | CurrentUser(user): CurrentUser, | 381 | CurrentUser(user): CurrentUser, |
| 381 | Path(id): Path<String>, | 382 | Path(id): Path<String>, |
| 382 | Json(req): Json<SendChatbotMessage>, | 383 | Json(req): Json<SendChatbotMessage>, |
| 383 | ) -> Result<Response, AppError> { | 384 | ) -> Result<Response, AppError> { |
| 384 | // Charged first: a rejected turn must cost nothing and leave no row. | 385 | // Charged first: a rejected turn must cost nothing and leave no row. |
| 385 | - st.chatbot_limit.enforce_user(user.get_id().key())?; | 386 | + st.chatbot_limit |
| 387 | + .enforce_user(&scoped_key(&slug, user.get_id().key()))?; | ||
| 386 | 388 | ||
| 387 | let thread = own_thread(&id, user.get_id(), &st.db).await?; | 389 | let thread = own_thread(&id, user.get_id(), &st.db).await?; |
| 388 | let settings = Settings::load(&st.db).await?; | 390 | let settings = Settings::load(&st.db).await?; |
src/web/exam_ws.rsmodified+14 -5
| @@ -56,7 +56,7 @@ | |||
| 56 | 56 | ||
| 57 | use std::time::Duration; | 57 | use std::time::Duration; |
| 58 | 58 | ||
| 59 | -use crate::web::tenant_state::State; | 59 | +use crate::web::tenant_state::{SchoolSlug, State}; |
| 60 | use axum::extract::Path; | 60 | use axum::extract::Path; |
| 61 | use axum::extract::ws::{WebSocket, WebSocketUpgrade}; | 61 | use axum::extract::ws::{WebSocket, WebSocketUpgrade}; |
| 62 | use axum::response::Response; | 62 | use axum::response::Response; |
| @@ -73,6 +73,7 @@ use crate::domain::timestamp::Timestamp; | |||
| 73 | use crate::domain::user::UserId; | 73 | use crate::domain::user::UserId; |
| 74 | use crate::error::AppError; | 74 | use crate::error::AppError; |
| 75 | use crate::state::AppState; | 75 | use crate::state::AppState; |
| 76 | +use crate::tenant::Slug; | ||
| 76 | use crate::validate::validate_required; | 77 | use crate::validate::validate_required; |
| 77 | use crate::web::CurrentUser; | 78 | use crate::web::CurrentUser; |
| 78 | use crate::web::exams::{ | 79 | use crate::web::exams::{ |
| @@ -138,6 +139,7 @@ enum ClientMessage { | |||
| 138 | /// dying socket's teardown stamp a student who was already reconnecting. | 139 | /// dying socket's teardown stamp a student who was already reconnecting. |
| 139 | pub async fn attempt_ws( | 140 | pub async fn attempt_ws( |
| 140 | State(st): State<AppState>, | 141 | State(st): State<AppState>, |
| 142 | + SchoolSlug(slug): SchoolSlug, | ||
| 141 | CurrentUser(user): CurrentUser, | 143 | CurrentUser(user): CurrentUser, |
| 142 | Path(id): Path<String>, | 144 | Path(id): Path<String>, |
| 143 | ws: WebSocketUpgrade, | 145 | ws: WebSocketUpgrade, |
| @@ -153,13 +155,20 @@ pub async fn attempt_ws( | |||
| 153 | course_of(&exam, &st.db).await?.require_open(&st.db).await?; | 155 | course_of(&exam, &st.db).await?.require_open(&st.db).await?; |
| 154 | 156 | ||
| 155 | let user_id = user.get_id().clone(); | 157 | let user_id = user.get_id().clone(); |
| 156 | - Ok(ws.on_upgrade(move |socket| room(socket, st, exam, attempt, user_id))) | 158 | + Ok(ws.on_upgrade(move |socket| room(socket, st, slug, exam, attempt, user_id))) |
| 157 | } | 159 | } |
| 158 | 160 | ||
| 159 | /// The room loop: state ticks out, answer/finish/ping in, until the socket | 161 | /// The room loop: state ticks out, answer/finish/ping in, until the socket |
| 160 | /// closes or the room's sitting reaches a terminal state. The room is bound | 162 | /// closes or the room's sitting reaches a terminal state. The room is bound |
| 161 | /// to the attempt it was opened for — `attempt` — and to no later sitting. | 163 | /// to the attempt it was opened for — `attempt` — and to no later sitting. |
| 162 | -async fn room(mut socket: WebSocket, st: AppState, exam: Exam, attempt: ExamAttempt, user: UserId) { | 164 | +async fn room( |
| 165 | + mut socket: WebSocket, | ||
| 166 | + st: AppState, | ||
| 167 | + slug: Slug, | ||
| 168 | + exam: Exam, | ||
| 169 | + attempt: ExamAttempt, | ||
| 170 | + user: UserId, | ||
| 171 | +) { | ||
| 163 | let exam_id = exam.get_id().clone(); | 172 | let exam_id = exam.get_id().clone(); |
| 164 | let attempt_id = attempt.get_id().clone(); | 173 | let attempt_id = attempt.get_id().clone(); |
| 165 | // Join critical section: this socket counts as presence in the sitting's | 174 | // 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 | |||
| 171 | // failed clear leaves the stamp for the next join or the teacher's door. | 180 | // failed clear leaves the stamp for the next join or the teacher's door. |
| 172 | { | 181 | { |
| 173 | let _guard = PRESENCE_LOCK.lock().await; | 182 | let _guard = PRESENCE_LOCK.lock().await; |
| 174 | - st.exam_presence.enter(attempt_id.key()); | 183 | + st.exam_presence.enter(&slug, attempt_id.key()); |
| 175 | if let Err(err) = attempt.set_left(None, &st.db).await { | 184 | if let Err(err) = attempt.set_left(None, &st.db).await { |
| 176 | tracing::warn!("exam room could not clear left_at on join: {err}"); | 185 | tracing::warn!("exam room could not clear left_at on join: {err}"); |
| 177 | } | 186 | } |
| @@ -211,7 +220,7 @@ async fn room(mut socket: WebSocket, st: AppState, exam: Exam, attempt: ExamAtte | |||
| 211 | // superseded by a retake is terminal) need no stamp. Best-effort: a | 220 | // superseded by a retake is terminal) need no stamp. Best-effort: a |
| 212 | // failed stamp only means it goes unrecorded. | 221 | // failed stamp only means it goes unrecorded. |
| 213 | let _guard = PRESENCE_LOCK.lock().await; | 222 | let _guard = PRESENCE_LOCK.lock().await; |
| 214 | - if st.exam_presence.leave(attempt_id.key()) { | 223 | + if st.exam_presence.leave(&slug, attempt_id.key()) { |
| 215 | stamp_left(&exam_id, &attempt_id, &st.db).await; | 224 | stamp_left(&exam_id, &attempt_id, &st.db).await; |
| 216 | } | 225 | } |
| 217 | } | 226 | } |
src/web/users.rsmodified+4 -1
| @@ -1,4 +1,4 @@ | |||
| 1 | -use crate::web::tenant_state::State; | 1 | +use crate::web::tenant_state::{SchoolSlug, State}; |
| 2 | use axum::Json; | 2 | use axum::Json; |
| 3 | use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; | 3 | use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; |
| 4 | use axum::http::StatusCode; | 4 | use axum::http::StatusCode; |
| @@ -463,6 +463,7 @@ async fn update_user_preferences( | |||
| 463 | )] | 463 | )] |
| 464 | async fn set_role( | 464 | async fn set_role( |
| 465 | State(st): State<AppState>, | 465 | State(st): State<AppState>, |
| 466 | + SchoolSlug(slug): SchoolSlug, | ||
| 466 | RequireAdmin(admin): RequireAdmin, | 467 | RequireAdmin(admin): RequireAdmin, |
| 467 | Path(id): Path<String>, | 468 | Path(id): Path<String>, |
| 468 | Json(req): Json<SetRole>, | 469 | Json(req): Json<SetRole>, |
| @@ -490,6 +491,7 @@ async fn set_role( | |||
| 490 | // stroke came back refused. | 491 | // stroke came back refused. |
| 491 | for board in boards { | 492 | for board in boards { |
| 492 | st.board_hub.publish( | 493 | st.board_hub.publish( |
| 494 | + &slug, | ||
| 493 | board.get_id().key(), | 495 | board.get_id().key(), |
| 494 | json!({ | 496 | json!({ |
| 495 | "type": "participants", | 497 | "type": "participants", |
| @@ -504,6 +506,7 @@ async fn set_role( | |||
| 504 | ); | 506 | ); |
| 505 | if let Some(closed_at) = board.get_closed_at() { | 507 | if let Some(closed_at) = board.get_closed_at() { |
| 506 | st.board_hub.publish( | 508 | st.board_hub.publish( |
| 509 | + &slug, | ||
| 507 | board.get_id().key(), | 510 | board.get_id().key(), |
| 508 | json!({"type": "closed", "closed_at": closed_at.as_millis()}).to_string(), | 511 | json!({"type": "closed", "closed_at": closed_at.as_millis()}).to_string(), |
| 509 | ); | 512 | ); |