Files
sorsfonalak/services/forum/src/live.rs
T

245 lines
9.4 KiB
Rust
Raw Normal View History

2026-11-26 11:41:45 +00:00
//! 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. 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<i64>,
/// A conversation changed (only its two members hear it, through `users`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub conversation: Option<i64>,
/// Whose menu counts changed.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub users: Vec<Uuid>,
/// 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,
}
impl Event {
pub fn for_users(mut self, users: Vec<Uuid>) -> 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<String> {
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<Arc<Event>>,
}
impl Default for Hub {
fn default() -> Self {
Self { tx: broadcast::channel(1024).0 }
}
}
impl Hub {
pub fn subscribe(&self) -> broadcast::Receiver<Arc<Event>> {
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::<Event>(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<Arc<AppState>>,
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 moderator = viewer.is_moderator();
let rx = state.hub.subscribe();
let db = state.db.clone();
ws.on_upgrade(move |socket| serve(socket, rx, db, member.user_id, moderator))
}
async fn serve(
mut socket: WebSocket,
mut rx: broadcast::Receiver<Arc<Event>>,
db: PgPool,
user: Uuid,
moderator: bool,
) {
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 {
// The page has nothing to say; 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<Uuid> {
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);
}
}