//! Live notices over WebSocket: a doorbell, never the data. The server only //! says "something changed" (`{"t":"nav"}`: the menu's counts; `{"t":"thread", //! "id":…}`: a thread; `{"t":"conversation","id":…}`), and the page fetches the //! news over HTTP as before. The one thing a page says is that its member is //! typing (`{"typing":"thread"|"conversation","id":…}`, every few seconds while //! they type); the others there get `{"t":"typing","kind":…,"id":…,"who":…}`. A dropped connection loses nothing: the page asks //! again when it reconnects, and polls while it cannot. //! //! Events go through Postgres (`NOTIFY forum_events`), so every instance of the //! service hears every change, whichever instance it happened on; each one //! passes them to its own connections. use std::sync::Arc; use std::time::Duration; use axum::extract::State; use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; use axum::http::{HeaderMap, StatusCode, header}; use axum::response::{IntoResponse, Response}; use serde::{Deserialize, Serialize}; use serde_json::json; use sqlx::PgPool; use sqlx::postgres::PgListener; use tokio::sync::broadcast; use uuid::Uuid; use crate::AppState; use crate::auth::Viewer; pub const CHANNEL: &str = "forum_events"; /// A ping this often keeps the connection open through proxies (Cloudflare /// closes one idle for 100 seconds), and refreshes the online dot. const PING: Duration = Duration::from_secs(30); /// Above this many recipients an event goes to everyone (NOTIFY payloads are small). const MAX_USERS: usize = 300; /// What changed, and for whom. #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] pub struct Event { /// A thread got a post, an edit, a reaction or a removal (anyone viewing it refetches). #[serde(default, skip_serializing_if = "Option::is_none")] pub thread: Option, /// A conversation changed (only its two members hear it, through `users`). #[serde(default, skip_serializing_if = "Option::is_none")] pub conversation: Option, /// Whose menu counts changed. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub users: Vec, /// Everyone's menu (too many recipients to list). #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub everyone: bool, /// The moderators' menu (the open reports). #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub moderators: bool, /// Someone is typing in a thread (everyone there sees it) or a /// conversation (the other member, in `users`). #[serde(default, skip_serializing_if = "Option::is_none")] pub typing: Option, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Typing { /// `thread` or `conversation`. pub kind: String, pub id: i64, /// The nickname shown ("Holdfény gépel…"). pub who: String, /// Who types (they do not hear of themselves). pub from: Uuid, } impl Event { pub fn for_users(mut self, users: Vec) -> Self { if users.len() > MAX_USERS { self.everyone = true; } else { self.users = users; } self } /// The messages one connection gets from this event. pub fn messages_for(&self, user: Uuid, moderator: bool) -> Vec { if let Some(t) = &self.typing { let hears = t.from != user && (t.kind == "thread" || self.users.contains(&user)); return if hears { vec![json!({ "t": "typing", "kind": t.kind, "id": t.id, "who": t.who }).to_string()] } else { Vec::new() }; } let mine = self.everyone || self.users.contains(&user); let mut out = Vec::new(); if let Some(id) = self.thread { out.push(json!({ "t": "thread", "id": id }).to_string()); } if let (Some(id), true) = (self.conversation, self.users.contains(&user)) { out.push(json!({ "t": "conversation", "id": id }).to_string()); } if mine || (self.moderators && moderator) { out.push(json!({ "t": "nav" }).to_string()); } out } } /// The events of this instance, for its connections. #[derive(Clone)] pub struct Hub { tx: broadcast::Sender>, } impl Default for Hub { fn default() -> Self { Self { tx: broadcast::channel(1024).0 } } } impl Hub { pub fn subscribe(&self) -> broadcast::Receiver> { self.tx.subscribe() } } /// Announces a change to every instance. A failure is logged: the pages poll anyway. pub async fn emit(db: &PgPool, event: Event) { let payload = serde_json::to_string(&event).unwrap_or_default(); if let Err(e) = sqlx::query("SELECT pg_notify($1, $2)").bind(CHANNEL).bind(&payload).execute(db).await { tracing::warn!(error = %e, "announcing a forum event"); } } /// Passes the database's events to this instance's connections, for good /// (it reconnects after a lost database connection). pub async fn listen(db: PgPool, hub: Hub) { loop { match PgListener::connect_with(&db).await { Ok(mut listener) => { if let Err(e) = listener.listen(CHANNEL).await { tracing::warn!(error = %e, "LISTEN forum_events failed"); } else { loop { match listener.recv().await { Ok(note) => match serde_json::from_str::(note.payload()) { Ok(event) => { // No connection listening is fine. let _ = hub.tx.send(Arc::new(event)); } Err(e) => tracing::warn!(error = %e, "unreadable forum event"), }, Err(e) => { tracing::warn!(error = %e, "forum events: listener lost"); break; } } } } } Err(e) => tracing::warn!(error = %e, "forum events: cannot listen"), } tokio::time::sleep(Duration::from_secs(3)).await; } } /// Only the site itself may open a connection with the visitor's cookie /// (no cross-site WebSocket hijacking). fn origin_allowed(headers: &HeaderMap, base_url: &str) -> bool { match headers.get(header::ORIGIN).and_then(|o| o.to_str().ok()) { Some(origin) => origin.trim_end_matches('/') == base_url, // Not a browser (no Origin header): it brings its own token. None => headers.contains_key(header::AUTHORIZATION), } } /// `GET /v1/forum/ws`: a member's live connection. pub async fn connect( State(state): State>, viewer: Viewer, headers: HeaderMap, ws: WebSocketUpgrade, ) -> Response { if !origin_allowed(&headers, &state.base_url) { return StatusCode::FORBIDDEN.into_response(); } let Some(member) = viewer.member.clone() else { return StatusCode::UNAUTHORIZED.into_response() }; let me = Me { user: member.user_id, nickname: member.nickname, moderator: viewer.is_moderator() }; let rx = state.hub.subscribe(); let db = state.db.clone(); ws.on_upgrade(move |socket| serve(socket, rx, db, me)) } /// Who is on the other end of a connection. struct Me { user: Uuid, nickname: String, moderator: bool, } #[derive(Deserialize)] struct Incoming { typing: String, id: i64, } /// At most one typing notice per target in this time. const TYPING_EVERY: Duration = Duration::from_secs(2); /// "I am typing", from the page: passed on to those who may see that place. async fn typing(db: &PgPool, me: &Me, text: &str) -> Option { let incoming: Incoming = serde_json::from_str(text).ok()?; let users = match incoming.typing.as_str() { "conversation" => { let other: Option = sqlx::query_scalar( "SELECT CASE WHEN user_a = $2 THEN user_b ELSE user_a END FROM forum.conversations \ WHERE id = $1 AND status = 'accepted' AND $2 IN (user_a, user_b)", ) .bind(incoming.id) .bind(me.user) .fetch_optional(db) .await .ok()?; vec![other?] } "thread" => { let visibility: Option = sqlx::query_scalar( "SELECT tp.visibility FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \ WHERE th.id = $1 AND th.deleted_at IS NULL AND (NOT th.locked OR $2)", ) .bind(incoming.id) .bind(me.moderator) .fetch_optional(db) .await .ok()?; if visibility? == "restricted" && !me.moderator { return None; } Vec::new() } _ => return None, }; Some(Event { users, typing: Some(Typing { kind: incoming.typing, id: incoming.id, who: me.nickname.clone(), from: me.user }), ..Default::default() }) } async fn serve(mut socket: WebSocket, mut rx: broadcast::Receiver>, db: PgPool, me: Me) { let (user, moderator) = (me.user, me.moderator); let mut last_typing: Option<(String, std::time::Instant)> = None; let mut ping = tokio::time::interval(PING); ping.tick().await; loop { tokio::select! { event = rx.recv() => { let messages = match event { Ok(event) => event.messages_for(user, moderator), // Too slow to follow: just refresh everything. Err(broadcast::error::RecvError::Lagged(_)) => vec![json!({ "t": "nav" }).to_string()], Err(broadcast::error::RecvError::Closed) => break, }; for message in messages { if socket.send(Message::Text(message.into())).await.is_err() { return; } } } _ = ping.tick() => { if socket.send(Message::Ping(Vec::new().into())).await.is_err() { return; } // Connected means present: the online dot. let _ = sqlx::query( "UPDATE forum.members SET last_seen_at = now() \ WHERE user_id = $1 AND (last_seen_at IS NULL OR last_seen_at < now() - interval '60 seconds')", ) .bind(user) .execute(&db) .await; } incoming = socket.recv() => match incoming { Some(Ok(Message::Text(text))) => { // Typing notices, a few seconds apart per place. let fresh = last_typing .as_ref() .is_none_or(|(place, at)| *place != text.as_str() || at.elapsed() >= TYPING_EVERY); if fresh { last_typing = Some((text.to_string(), std::time::Instant::now())); if let Some(event) = typing(&db, &me, &text).await { emit(&db, event).await; } } } // Pongs and the like are fine. Some(Ok(Message::Close(_))) | None | Some(Err(_)) => break, Some(Ok(_)) => {} }, } } } /// The followers of a thread other than `except` (whose menu counts change). pub async fn followers(db: &PgPool, thread: i64, except: Uuid) -> Vec { sqlx::query_scalar("SELECT user_id FROM forum.follows WHERE thread_id = $1 AND user_id <> $2") .bind(thread) .bind(except) .fetch_all(db) .await .unwrap_or_default() } #[cfg(test)] mod tests { use super::*; #[test] fn who_hears_what() { let (anna, bea) = (Uuid::now_v7(), Uuid::now_v7()); let post = Event { thread: Some(7), ..Default::default() }.for_users(vec![anna]); assert_eq!(post.messages_for(anna, false), vec![r#"{"id":7,"t":"thread"}"#, r#"{"t":"nav"}"#]); assert_eq!(post.messages_for(bea, false), vec![r#"{"id":7,"t":"thread"}"#]); let message = Event { conversation: Some(3), ..Default::default() }.for_users(vec![bea]); assert!(message.messages_for(anna, true).is_empty(), "nobody else hears of a conversation"); assert_eq!(message.messages_for(bea, false).len(), 2); let report = Event { moderators: true, ..Default::default() }; assert!(report.messages_for(anna, false).is_empty()); assert_eq!(report.messages_for(anna, true), vec![r#"{"t":"nav"}"#]); let many = Event::default().for_users((0..400).map(|_| Uuid::now_v7()).collect()); assert!(many.everyone && many.users.is_empty()); let round: Event = serde_json::from_str(&serde_json::to_string(&post).unwrap()).unwrap(); assert_eq!(round, post); // Typing: never to oneself; a conversation only to the other member. let typing = |kind: &str, users: Vec| Event { users, typing: Some(Typing { kind: kind.into(), id: 9, who: "Holdfény".into(), from: bea }), ..Default::default() }; let in_thread = typing("thread", vec![]); assert_eq!( in_thread.messages_for(anna, false), vec![r#"{"id":9,"kind":"thread","t":"typing","who":"Holdfény"}"#] ); assert!(in_thread.messages_for(bea, false).is_empty()); let in_chat = typing("conversation", vec![anna]); assert_eq!(in_chat.messages_for(anna, false).len(), 1); assert!(in_chat.messages_for(Uuid::now_v7(), true).is_empty()); } }