forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 commits

state.rs263 lines, 10.9 KiBHistoryRawDownload
1use std::collections::HashMap;
2use std::path::PathBuf;
3use std::sync::{Arc, Mutex};
4
5use tokio::sync::broadcast;
6
7use crate::ai::AiBridge;
8use crate::database::Database;
9use crate::rate_limit::{RateLimitConfig, UserRateLimiter};
10use crate::tenant::{Slug, Tenants};
11
12/// Shared application state handed to every handler.
13#[derive(Clone)]
14pub struct AppState {
15 /// The database this request works in. At the router's root this is the
16 /// **control** database; `crate::web::tenant_state::State` swaps in the
17 /// caller's school before any handler that shadows `State` sees it.
18 pub db: Database,
19 /// The school registry and its connections. Always the deployment-wide
20 /// one — it is never narrowed per request, so a handler can still reach
21 /// another school's handle deliberately.
22 pub tenants: Tenants,
23 /// Directory holding uploaded note-file blobs, one file per
24 /// `note_file` row, named by the row's key
25 /// (from [`crate::config::Config::files_path`]).
26 pub files_path: PathBuf,
27 /// Whether the session cookie carries the `Secure` attribute
28 /// (from [`crate::config::Config::cookie_secure`]).
29 pub cookie_secure: bool,
30 /// Per-IP request limits (from [`crate::config::Config::rate_limit`]).
31 /// Read once by [`crate::build_router`] when the limiters are built.
32 pub rate_limit: RateLimitConfig,
33 /// Per-user chatbot limit (see [`UserRateLimiter`], built from
34 /// [`crate::config::Config::chatbot_per_minute`]). Not middleware: the
35 /// caller is only known after `CurrentUser` has run, so handlers call it
36 /// themselves.
37 pub chatbot_limit: UserRateLimiter,
38 /// Who is inside which exam room right now (see [`ExamPresence`]).
39 pub exam_presence: ExamPresence,
40 /// Live stroke fan-out for the shared whiteboards (see [`BoardHub`]).
41 pub board_hub: BoardHub,
42 /// The QUIC bridge to the AI services, when one is configured
43 /// (`AI_QUIC_ADDR`). `None` means AI features are off for this deployment
44 /// — handlers must degrade rather than fail, since the core API has never
45 /// needed the bridge to work.
46 pub ai: Option<AiBridge>,
47 /// The process's metric instruments (see [`crate::telemetry::Metrics`]).
48 /// Noop unless `OTEL_EXPORTER_OTLP_ENDPOINT` configured an exporter, so
49 /// recording into one is always safe and always cheap.
50 pub metrics: crate::telemetry::Metrics,
51}
52
53/// The map key for `key` inside `slug`'s school. One process serves every
54/// school, but record keys are only unique *within* a database, so an
55/// unscoped key would put two schools' identical attempts (or boards) in the
56/// same room. The maps below are the only users of this, and their methods
57/// take a [`Slug`] rather than a ready-made key — there is no way to reach one
58/// with an unscoped string. The per-user chatbot limiter keys through here
59/// too, for the same reason. A slug cannot contain `:`, so the join is
60/// unambiguous.
61pub fn scoped_key(slug: &Slug, key: &str) -> String {
62 format!("{slug}:{key}")
63}
64
65/// How many exam-room sockets each attempt has open right now, keyed by the
66/// attempt's record key within its school. The room counts itself in on entry and out on exit,
67/// and only the last socket out stamps the walk-out (`left_at`) — a student
68/// closing one of two tabs never counts as having left the exam.
69///
70/// The inner mutex only guards the map (never held across an await — keep it
71/// that way). Each count transition and its matching `left_at` DB write are
72/// serialized as one critical section by the exam room's `PRESENCE_LOCK`
73/// (see `web::exam_ws`), so "clear on join" and "stamp on last-out" stay
74/// atomic with the counts they depend on.
75#[derive(Clone, Default)]
76pub struct ExamPresence(Arc<Mutex<HashMap<String, usize>>>);
77
78impl ExamPresence {
79 /// Count one socket into `attempt`'s room.
80 pub fn enter(&self, slug: &Slug, attempt: &str) {
81 let mut rooms = self.0.lock().expect("exam presence lock");
82 *rooms.entry(scoped_key(slug, attempt)).or_insert(0) += 1;
83 }
84
85 /// Count one socket out of `attempt`'s room; `true` when it was the last
86 /// one — the student has actually left.
87 pub fn leave(&self, slug: &Slug, attempt: &str) -> bool {
88 let attempt = &scoped_key(slug, attempt);
89 let mut rooms = self.0.lock().expect("exam presence lock");
90 match rooms.get_mut(attempt) {
91 Some(count) if *count > 1 => {
92 *count -= 1;
93 false
94 }
95 Some(_) => {
96 rooms.remove(attempt);
97 true
98 }
99 // Unbalanced (an enter was lost) — treat the close as a real exit
100 // rather than leaving the walk-out unrecorded forever.
101 None => true,
102 }
103 }
104}
105
106/// One broadcast channel per live whiteboard, keyed by the board's record key
107/// within its school,
108/// so a stroke saved by one socket reaches every *other* socket in that board.
109/// Nothing else in this codebase fans out — an exam room only ever replies to
110/// the socket that spoke — so this is the only multi-subscriber push we have.
111///
112/// The socket count exists to drop the entry when the last socket leaves;
113/// without it the map would keep one channel per board ever opened, forever.
114///
115/// The inner mutex only guards the map (never held across an await — keep it
116/// that way): every method locks, mutates or clones out, and drops the guard
117/// before the caller can await anything.
118/// What [`BoardHub`] holds: one channel per scoped board key, with the number
119/// of sockets currently on it.
120type BoardRooms = HashMap<String, (broadcast::Sender<String>, usize)>;
121
122#[derive(Clone, Default)]
123pub struct BoardHub(Arc<Mutex<BoardRooms>>);
124
125impl BoardHub {
126 /// Count one socket into `board` and hand back its stream of other
127 /// people's frames, creating the channel on the first join.
128 pub fn subscribe(&self, slug: &Slug, board: &str) -> broadcast::Receiver<String> {
129 let mut boards = self.0.lock().expect("board hub lock");
130 let room = boards
131 .entry(scoped_key(slug, board))
132 .or_insert_with(|| (broadcast::channel(crate::constant::BOARD_HUB_CAPACITY).0, 0));
133 room.1 += 1;
134 room.0.subscribe()
135 }
136
137 /// Push `frame` to every socket currently subscribed to `board`. A send
138 /// with no receivers left is the normal empty-room case, not a failure.
139 pub fn publish(&self, slug: &Slug, board: &str, frame: String) {
140 let sender = {
141 let boards = self.0.lock().expect("board hub lock");
142 boards
143 .get(&scoped_key(slug, board))
144 .map(|room| room.0.clone())
145 };
146 if let Some(sender) = sender {
147 let _ = sender.send(frame);
148 }
149 }
150
151 /// Count one socket out of `board`; the last one out drops the channel.
152 pub fn leave(&self, slug: &Slug, board: &str) {
153 let board = &scoped_key(slug, board);
154 let mut boards = self.0.lock().expect("board hub lock");
155 match boards.get_mut(board) {
156 Some(room) if room.1 > 1 => room.1 -= 1,
157 // Last one out, or an unbalanced leave — either way the room is
158 // empty, and a stale entry would leak for the process's lifetime.
159 _ => {
160 boards.remove(board);
161 }
162 }
163 }
164}
165
166#[cfg(test)]
167mod tests {
168 use super::*;
169
170 fn slug(value: &str) -> Slug {
171 Slug::try_new(value).expect(value)
172 }
173
174 #[tokio::test]
175 async fn every_subscriber_gets_the_stroke_and_the_room_is_reclaimed() {
176 let a = slug("alpha");
177 let hub = BoardHub::default();
178 let mut alice = hub.subscribe(&a, "board-a");
179 let mut bob = hub.subscribe(&a, "board-a");
180 hub.publish(&a, "board-a", "stroke".to_string());
181 assert_eq!(alice.recv().await.expect("alice"), "stroke");
182 assert_eq!(bob.recv().await.expect("bob"), "stroke");
183
184 // Boards are independent, and publishing into an empty one is a no-op.
185 hub.publish(&a, "board-b", "nobody home".to_string());
186 assert!(!hub.0.lock().unwrap().contains_key("alpha:board-b"));
187
188 hub.leave(&a, "board-a");
189 assert!(
190 hub.0.lock().unwrap().contains_key("alpha:board-a"),
191 "one socket of two out keeps the room"
192 );
193 hub.leave(&a, "board-a");
194 assert!(
195 hub.0.lock().unwrap().is_empty(),
196 "the last socket out must drop the entry, or the map leaks"
197 );
198 }
199
200 /// Record keys are unique per database, so two schools routinely hold the
201 /// same board key. One process serves both — nothing may cross.
202 #[tokio::test]
203 async fn a_stroke_never_crosses_into_another_school() {
204 let (a, b) = (slug("alpha"), slug("beta"));
205 let hub = BoardHub::default();
206 let mut in_a = hub.subscribe(&a, "board-1");
207 let mut in_b = hub.subscribe(&b, "board-1");
208
209 hub.publish(&a, "board-1", "alpha stroke".to_string());
210 assert_eq!(
211 in_a.recv().await.expect("alpha's own stroke"),
212 "alpha stroke"
213 );
214 assert!(
215 in_b.try_recv().is_err(),
216 "beta's board must not hear alpha's stroke"
217 );
218
219 // And the rooms are counted apart: alpha's last socket out leaves
220 // beta's room standing.
221 hub.leave(&a, "board-1");
222 let boards = hub.0.lock().unwrap();
223 assert!(!boards.contains_key("alpha:board-1"));
224 assert!(boards.contains_key("beta:board-1"));
225 }
226
227 #[tokio::test]
228 async fn only_the_last_socket_out_is_a_real_exit() {
229 let a = slug("alpha");
230 let presence = ExamPresence::default();
231 presence.enter(&a, "attempt-a");
232 presence.enter(&a, "attempt-a");
233 assert!(
234 !presence.leave(&a, "attempt-a"),
235 "one tab of two is not an exit"
236 );
237 assert!(presence.leave(&a, "attempt-a"), "the last tab out is");
238 // Rooms are independent, and a fresh key starts over.
239 presence.enter(&a, "attempt-b");
240 presence.enter(&a, "attempt-a");
241 assert!(presence.leave(&a, "attempt-b"));
242 assert!(presence.leave(&a, "attempt-a"));
243 // Unbalanced leaves degrade to "really left", never to a stuck room.
244 assert!(presence.leave(&a, "attempt-a"));
245 }
246
247 /// Two schools sitting the same attempt key count separately — otherwise
248 /// one school's second tab would hold the other school's room open, and
249 /// its walk-out would go unstamped.
250 #[tokio::test]
251 async fn presence_counts_are_per_school() {
252 let (a, b) = (slug("alpha"), slug("beta"));
253 let presence = ExamPresence::default();
254 presence.enter(&a, "attempt-1");
255 presence.enter(&b, "attempt-1");
256 assert!(
257 presence.leave(&a, "attempt-1"),
258 "alpha's only socket out is alpha's exit, whatever beta is doing"
259 );
260 assert!(presence.leave(&b, "attempt-1"));
261 assert!(presence.0.lock().unwrap().is_empty());
262 }
263}