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

room.rs219 lines, 9.1 KiBHistoryRawDownload
1//! Machinery shared by every WebSocket room.
2//!
3//! Two rooms speak WebSocket in this crate — the student exam room
4//! ([`super::exam_ws`]) and the collaborative whiteboard ([`super::board_ws`])
5//! — and they share less than they look like they do. The exam room only ever
6//! replies to the socket that spoke; the board room fans out to everyone else
7//! on the board. What they genuinely share is the plumbing *around* that
8//! difference: how a frame goes out, how an incoming message is classified, how
9//! an [`AppError`] becomes words a client may read, and how a client's
10//! correlation id is echoed back untouched.
11//!
12//! Deliberately **not** here, and the reason each time:
13//!
14//! - the `select!` loop — the board's third arm is a fan-out receiver the exam
15//! room has no analogue of, and the two loops' terminal conditions are
16//! different domain facts. A trait to unify them would be longer than both
17//! loops together and would still need a null receiver for the exam room.
18//! - the pre-upgrade gates — the *pattern* (every gate before `on_upgrade`, so
19//! a refusal is an HTTP status and not an instant close) is shared, but the
20//! shared code is the single `ws.on_upgrade(…)` line at the end of it. The
21//! gates themselves are each room's own domain rules.
22//! - presence — the exam room counts sockets per attempt to pair the last one
23//! out with a `left_at` stamp ([`crate::state::ExamPresence`]); the board
24//! room's join/leave is the fan-out subscription itself
25//! ([`crate::state::BoardHub`]), which counts its own sockets and has no
26//! paired database write to serialize against.
27
28use axum::extract::ws::{Message, Utf8Bytes, WebSocket};
29use serde_json::{Value, json};
30
31use crate::error::AppError;
32use crate::telemetry::Metrics;
33
34/// Counts one open socket for as long as it lives.
35///
36/// A room has several ways out — a break out of the `select!`, an early
37/// return, a panic — and a decrement written at any one of them is a leaked
38/// gauge at the others, drifting upwards for the process's whole life. `Drop`
39/// is the only placement that covers every exit, so the guard is created at
40/// the top of a room loop and nothing else touches the counter.
41pub(crate) struct Connected {
42 metrics: Metrics,
43 kind: &'static str,
44 school: String,
45 id: String,
46}
47
48impl Connected {
49 /// `kind` is the room's telemetry name (`exam_room`, `board`), `id` a
50 /// **resource** id — the exam, the board — and never the person on the
51 /// socket, which telemetry may not carry.
52 pub(crate) fn open(metrics: &Metrics, kind: &'static str, school: impl AsRef<str>, id: &str) -> Self {
53 metrics
54 .ws_connections
55 .add(1, &[opentelemetry::KeyValue::new("kind", kind)]);
56 // `id` is a resource id (exam, board) and `school` the school uuid —
57 // both are allowed on telemetry. A user id never is.
58 let school = school.as_ref();
59 tracing::info!(kind, school, id, "websocket opened");
60 Self {
61 metrics: metrics.clone(),
62 kind,
63 school: school.to_string(),
64 id: id.to_string(),
65 }
66 }
67}
68
69impl Drop for Connected {
70 fn drop(&mut self) {
71 self.metrics
72 .ws_connections
73 .add(-1, &[opentelemetry::KeyValue::new("kind", self.kind)]);
74 tracing::info!(
75 kind = self.kind,
76 school = self.school,
77 id = self.id,
78 "websocket closed"
79 );
80 }
81}
82
83/// The best-effort closing handshake a room ends with — a bare TCP teardown
84/// reads as an error on the client; a Close frame reads as "the room is over".
85pub(crate) async fn close(socket: &mut WebSocket) {
86 let _ = socket.send(Message::Close(None)).await;
87}
88
89/// What `socket.recv()` handed us, in the three shapes a room cares about.
90pub(crate) enum Incoming {
91 /// A text frame — the only kind either protocol speaks.
92 Text(Utf8Bytes),
93 /// A frame carrying nothing for this protocol: ping/pong are answered by
94 /// axum itself, and neither room speaks binary. Read the next one.
95 Ignore,
96 /// Close, transport error, or end of stream: the room is over.
97 Gone,
98}
99
100pub(crate) fn classify(incoming: Option<Result<Message, axum::Error>>) -> Incoming {
101 match incoming {
102 Some(Ok(Message::Text(text))) => Incoming::Text(text),
103 Some(Ok(Message::Close(_))) | Some(Err(_)) | None => Incoming::Gone,
104 Some(Ok(_)) => Incoming::Ignore,
105 }
106}
107
108/// Attach the request's correlation id, if it sent one. Omitted stays omitted
109/// — never `null` — so a client that sends no `client_seq` sees byte-identical
110/// frames.
111pub(crate) fn with_client_seq(frame: &mut Value, client_seq: Option<u64>) {
112 if let Some(client_seq) = client_seq {
113 frame["client_seq"] = json!(client_seq);
114 }
115}
116
117/// The public words for an error — the same strings the HTTP layer would use,
118/// with internals logged under `room` (`"exam room"`, `"board room"`) and never
119/// sent.
120pub(crate) fn public_message(err: &AppError, room: &str) -> String {
121 match err {
122 AppError::Validation(err) => err.to_string(),
123 AppError::NotFound => "not found".to_string(),
124 AppError::Expired(message) => (*message).to_string(),
125 AppError::Unauthorized => "unauthorized".to_string(),
126 AppError::Forbidden(message) => (*message).to_string(),
127 AppError::Conflict(message) => (*message).to_string(),
128 AppError::ConflictOwned(message) | AppError::ConflictCoded { message, .. } => {
129 message.clone()
130 }
131 AppError::PayloadTooLarge(message) => message.clone(),
132 // Unreachable in practice: the module gate refuses the upgrade before
133 // a socket exists. Spelled out anyway so a new refusal never falls
134 // into "internal server error" by default.
135 AppError::ModuleDisabled(module) => format!("module disabled: {module}"),
136 AppError::TooManyRequests { .. } => "too many requests".to_string(),
137 AppError::DbUnavailable => {
138 tracing::warn!("{room}: database reconnecting");
139 "database reconnecting — retry shortly".to_string()
140 }
141 AppError::DbTimeout => {
142 tracing::error!("{room}: database timed out");
143 "the database timed out — reload the room".to_string()
144 }
145 AppError::Db(_) | AppError::Internal(_) => {
146 tracing::error!("{room} error: {err}");
147 "internal server error".to_string()
148 }
149 }
150}
151
152/// Errors that end a room: the peer went away, or the room reached a terminal
153/// state and its closing frame was sent.
154pub(crate) struct RoomClosed;
155
156/// Send one JSON frame. A failed send means the peer is gone, which ends the
157/// room — every caller propagates it with `?`.
158pub(crate) async fn send(socket: &mut WebSocket, frame: Value) -> Result<(), RoomClosed> {
159 socket
160 .send(Message::Text(frame.to_string().into()))
161 .await
162 .map_err(|_| RoomClosed)
163}
164
165#[cfg(test)]
166mod tests {
167 use opentelemetry::metrics::MeterProvider as _;
168 use opentelemetry_sdk::metrics::data::{AggregatedMetrics, MetricData};
169 use opentelemetry_sdk::metrics::{InMemoryMetricExporter, PeriodicReader, SdkMeterProvider};
170
171 use super::Connected;
172 use crate::telemetry::Metrics;
173
174 /// The guard is the whole reason the gauge balances: every exit from a
175 /// room drops it, including the ones that never reach the loop's end. Read
176 /// back through a meter of this test's own, so the assertion is about what
177 /// was really recorded and no other test in this binary can perturb it.
178 #[test]
179 fn every_open_socket_is_counted_out_again() {
180 let exporter = InMemoryMetricExporter::default();
181 let provider = SdkMeterProvider::builder()
182 .with_reader(PeriodicReader::builder(exporter.clone()).build())
183 .build();
184 let metrics = Metrics::from_meter(provider.meter("test"));
185
186 let guard = Connected::open(&metrics, "exam_room", "demo", "exam_abc");
187 drop(guard);
188 provider.force_flush().expect("flush");
189
190 let mut sum_value = None;
191 for rm in exporter.get_finished_metrics().expect("metrics") {
192 for scope in rm.scope_metrics() {
193 for metric in scope.metrics() {
194 if metric.name() != "ws_connections" {
195 continue;
196 }
197 let AggregatedMetrics::I64(MetricData::Sum(sum)) = metric.data() else {
198 panic!("an up-down counter must export as an i64 sum");
199 };
200 for point in sum.data_points() {
201 assert!(
202 point
203 .attributes()
204 .any(|kv| kv.key.as_str() == "kind"
205 && kv.value.as_str() == "exam_room"),
206 "the only series here is the exam room's"
207 );
208 sum_value = Some(point.value());
209 }
210 }
211 }
212 }
213 assert_eq!(
214 sum_value,
215 Some(0),
216 "a socket opened and dropped leaves the gauge where it started"
217 );
218 }
219}