forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB08aa13eAhmet Kaan Gümüş2 months ago378 commits

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