forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

state.rs268 lines, 11.4 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::{SchoolId, 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 /// Per-user RAG limit (see [`UserRateLimiter`], built from
39 /// [`crate::config::Config::rag_per_minute`]). Not middleware: the
40 /// caller is only known after `CurrentUser` has run, so handlers call it
41 /// themselves.
42 pub rag_limit: UserRateLimiter,
43 /// Who is inside which exam room right now (see [`ExamPresence`]).
44 pub exam_presence: ExamPresence,
45 /// Live stroke fan-out for the shared whiteboards (see [`BoardHub`]).
46 pub board_hub: BoardHub,
47 /// The QUIC bridge to the AI services, when one is configured
48 /// (`AI_QUIC_ADDR`). `None` means AI features are off for this deployment
49 /// — handlers must degrade rather than fail, since the core API has never
50 /// needed the bridge to work.
51 pub ai: Option<AiBridge>,
52 /// The process's metric instruments (see [`crate::telemetry::Metrics`]).
53 /// Noop unless `OTEL_EXPORTER_OTLP_ENDPOINT` configured an exporter, so
54 /// recording into one is always safe and always cheap.
55 pub metrics: crate::telemetry::Metrics,
56}
57
58/// The map key for `key` inside `id`'s school. One process serves every
59/// school, but record keys are only unique *within* a database, so an
60/// unscoped key would put two schools' identical attempts (or boards) in the
61/// same room. The maps below are the only users of this, and their methods
62/// take a [`SchoolId`] rather than a ready-made key — there is no way to reach
63/// one with an unscoped string. The per-user chatbot limiter keys through here
64/// too, for the same reason. A hyphenated uuid cannot contain `:`, so the join
65/// is unambiguous.
66pub fn scoped_key(id: &SchoolId, key: &str) -> String {
67 format!("{id}:{key}")
68}
69
70/// How many exam-room sockets each attempt has open right now, keyed by the
71/// attempt's record key within its school. The room counts itself in on entry and out on exit,
72/// and only the last socket out stamps the walk-out (`left_at`) — a student
73/// closing one of two tabs never counts as having left the exam.
74///
75/// The inner mutex only guards the map (never held across an await — keep it
76/// that way). The matching `left_at` writes are idempotent single statements
77/// against the sitting's own row (see `web::exam_ws`): join clears the marker;
78/// last socket out stamps it only while `left_at IS NULL`. Concurrent last-outs
79/// are harmless — only the first stamp lands.
80#[derive(Clone, Default)]
81pub struct ExamPresence(Arc<Mutex<HashMap<String, usize>>>);
82
83impl ExamPresence {
84 /// Count one socket into `attempt`'s room.
85 pub fn enter(&self, id: &SchoolId, attempt: &str) {
86 let mut rooms = self.0.lock().expect("exam presence lock");
87 *rooms.entry(scoped_key(id, attempt)).or_insert(0) += 1;
88 }
89
90 /// Count one socket out of `attempt`'s room; `true` when it was the last
91 /// one — the student has actually left.
92 pub fn leave(&self, id: &SchoolId, attempt: &str) -> bool {
93 let attempt = &scoped_key(id, attempt);
94 let mut rooms = self.0.lock().expect("exam presence lock");
95 match rooms.get_mut(attempt) {
96 Some(count) if *count > 1 => {
97 *count -= 1;
98 false
99 }
100 Some(_) => {
101 rooms.remove(attempt);
102 true
103 }
104 // Unbalanced (an enter was lost) — treat the close as a real exit
105 // rather than leaving the walk-out unrecorded forever.
106 None => true,
107 }
108 }
109}
110
111/// One broadcast channel per live whiteboard, keyed by the board's record key
112/// within its school,
113/// so a stroke saved by one socket reaches every *other* socket in that board.
114/// Nothing else in this codebase fans out — an exam room only ever replies to
115/// the socket that spoke — so this is the only multi-subscriber push we have.
116///
117/// The socket count exists to drop the entry when the last socket leaves;
118/// without it the map would keep one channel per board ever opened, forever.
119///
120/// The inner mutex only guards the map (never held across an await — keep it
121/// that way): every method locks, mutates or clones out, and drops the guard
122/// before the caller can await anything.
123/// What [`BoardHub`] holds: one channel per scoped board key, with the number
124/// of sockets currently on it.
125type BoardRooms = HashMap<String, (broadcast::Sender<String>, usize)>;
126
127#[derive(Clone, Default)]
128pub struct BoardHub(Arc<Mutex<BoardRooms>>);
129
130impl BoardHub {
131 /// Count one socket into `board` and hand back its stream of other
132 /// people's frames, creating the channel on the first join.
133 pub fn subscribe(&self, id: &SchoolId, board: &str) -> broadcast::Receiver<String> {
134 let mut boards = self.0.lock().expect("board hub lock");
135 let room = boards
136 .entry(scoped_key(id, board))
137 .or_insert_with(|| (broadcast::channel(crate::constant::BOARD_HUB_CAPACITY).0, 0));
138 room.1 += 1;
139 room.0.subscribe()
140 }
141
142 /// Push `frame` to every socket currently subscribed to `board`. A send
143 /// with no receivers left is the normal empty-room case, not a failure.
144 pub fn publish(&self, id: &SchoolId, board: &str, frame: String) {
145 let sender = {
146 let boards = self.0.lock().expect("board hub lock");
147 boards
148 .get(&scoped_key(id, board))
149 .map(|room| room.0.clone())
150 };
151 if let Some(sender) = sender {
152 let _ = sender.send(frame);
153 }
154 }
155
156 /// Count one socket out of `board`; the last one out drops the channel.
157 pub fn leave(&self, id: &SchoolId, board: &str) {
158 let board = &scoped_key(id, board);
159 let mut boards = self.0.lock().expect("board hub lock");
160 match boards.get_mut(board) {
161 Some(room) if room.1 > 1 => room.1 -= 1,
162 // Last one out, or an unbalanced leave — either way the room is
163 // empty, and a stale entry would leak for the process's lifetime.
164 _ => {
165 boards.remove(board);
166 }
167 }
168 }
169}
170
171#[cfg(test)]
172mod tests {
173 use super::*;
174
175 fn school(value: &str) -> SchoolId {
176 SchoolId::try_parse(value).expect(value)
177 }
178
179 #[tokio::test]
180 async fn every_subscriber_gets_the_stroke_and_the_room_is_reclaimed() {
181 let a = school("019732e3-7b00-7000-8000-00000000a11a");
182 let hub = BoardHub::default();
183 let mut alice = hub.subscribe(&a, "board-a");
184 let mut bob = hub.subscribe(&a, "board-a");
185 hub.publish(&a, "board-a", "stroke".to_string());
186 assert_eq!(alice.recv().await.expect("alice"), "stroke");
187 assert_eq!(bob.recv().await.expect("bob"), "stroke");
188
189 // Boards are independent, and publishing into an empty one is a no-op.
190 hub.publish(&a, "board-b", "nobody home".to_string());
191 assert!(!hub.0.lock().unwrap().contains_key(&scoped_key(&a, "board-b")));
192
193 hub.leave(&a, "board-a");
194 assert!(
195 hub.0.lock().unwrap().contains_key(&scoped_key(&a, "board-a")),
196 "one socket of two out keeps the room"
197 );
198 hub.leave(&a, "board-a");
199 assert!(
200 hub.0.lock().unwrap().is_empty(),
201 "the last socket out must drop the entry, or the map leaks"
202 );
203 }
204
205 /// Record keys are unique per database, so two schools routinely hold the
206 /// same board key. One process serves both — nothing may cross.
207 #[tokio::test]
208 async fn a_stroke_never_crosses_into_another_school() {
209 let (a, b) = (school("019732e3-7b00-7000-8000-00000000a11a"), school("019732e3-7b00-7000-8000-00000000be7a"));
210 let hub = BoardHub::default();
211 let mut in_a = hub.subscribe(&a, "board-1");
212 let mut in_b = hub.subscribe(&b, "board-1");
213
214 hub.publish(&a, "board-1", "alpha stroke".to_string());
215 assert_eq!(
216 in_a.recv().await.expect("alpha's own stroke"),
217 "alpha stroke"
218 );
219 assert!(
220 in_b.try_recv().is_err(),
221 "beta's board must not hear alpha's stroke"
222 );
223
224 // And the rooms are counted apart: alpha's last socket out leaves
225 // beta's room standing.
226 hub.leave(&a, "board-1");
227 let boards = hub.0.lock().unwrap();
228 assert!(!boards.contains_key(&scoped_key(&a, "board-1")));
229 assert!(boards.contains_key(&scoped_key(&b, "board-1")));
230 }
231
232 #[tokio::test]
233 async fn only_the_last_socket_out_is_a_real_exit() {
234 let a = school("019732e3-7b00-7000-8000-00000000a11a");
235 let presence = ExamPresence::default();
236 presence.enter(&a, "attempt-a");
237 presence.enter(&a, "attempt-a");
238 assert!(
239 !presence.leave(&a, "attempt-a"),
240 "one tab of two is not an exit"
241 );
242 assert!(presence.leave(&a, "attempt-a"), "the last tab out is");
243 // Rooms are independent, and a fresh key starts over.
244 presence.enter(&a, "attempt-b");
245 presence.enter(&a, "attempt-a");
246 assert!(presence.leave(&a, "attempt-b"));
247 assert!(presence.leave(&a, "attempt-a"));
248 // Unbalanced leaves degrade to "really left", never to a stuck room.
249 assert!(presence.leave(&a, "attempt-a"));
250 }
251
252 /// Two schools sitting the same attempt key count separately — otherwise
253 /// one school's second tab would hold the other school's room open, and
254 /// its walk-out would go unstamped.
255 #[tokio::test]
256 async fn presence_counts_are_per_school() {
257 let (a, b) = (school("019732e3-7b00-7000-8000-00000000a11a"), school("019732e3-7b00-7000-8000-00000000be7a"));
258 let presence = ExamPresence::default();
259 presence.enter(&a, "attempt-1");
260 presence.enter(&b, "attempt-1");
261 assert!(
262 presence.leave(&a, "attempt-1"),
263 "alpha's only socket out is alpha's exit, whatever beta is doing"
264 );
265 assert!(presence.leave(&b, "attempt-1"));
266 assert!(presence.0.lock().unwrap().is_empty());
267 }
268}