Forum: live notices over WebSocket

A doorbell, not the data: the forum service tells a member's page that
their menu counts, a thread or a conversation changed, and the page
fetches the news over HTTP. Events go through Postgres NOTIFY so every
instance hears them; pings keep the connection (and the online dot)
alive; only the site's own origin may connect. The menu now refreshes
its badges live, on every page change and when the page comes back to
the front, and polls while there is no connection. Caddy sends
/api/v1/forum/ws straight to the forum service; in development
FORUM_WS_URL points at it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-26 11:41:45 +00:00
co-authored by Claude Opus 5.5
parent 88d9a5df3e
commit 2cf7266fc1
18 changed files with 589 additions and 58 deletions
+9 -3
View File
@@ -13,6 +13,7 @@
mod auth;
mod error;
mod live;
mod mail;
mod rank;
mod routes;
@@ -31,13 +32,16 @@ pub struct AppState {
pub db: PgPool,
/// Seconds a member waits between two posts (0 in the tests).
pub flood_secs: i32,
/// The site's address, for the links in e-mails (`PUBLIC_BASE_URL`).
/// The site's address, for the links in e-mails (`PUBLIC_BASE_URL`); also
/// the only origin allowed to open a live connection.
pub base_url: String,
/// The live events of this instance (`live::listen` fills it).
pub hub: live::Hub,
}
impl AppState {
pub fn new(db: PgPool, base_url: String) -> Self {
Self { db, flood_secs: 5, base_url: base_url.trim_end_matches('/').to_string() }
Self { db, flood_secs: 5, base_url: base_url.trim_end_matches('/').to_string(), hub: live::Hub::default() }
}
}
@@ -52,7 +56,9 @@ async fn main() -> anyhow::Result<()> {
let pool = db::connect(&url).await.context("connecting to the database")?;
db::migrate(&pool).await.context("running database migrations")?;
let base_url = std::env::var("PUBLIC_BASE_URL").unwrap_or_else(|_| "http://localhost:3001".into());
let app = routes::router(Arc::new(AppState::new(pool, base_url)));
let state = Arc::new(AppState::new(pool, base_url));
tokio::spawn(live::listen(state.db.clone(), state.hub.clone()));
let app = routes::router(state);
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
tracing::info!(%addr, "listening");
axum::serve(listener, app).with_graceful_shutdown(service_kit::shutdown_signal()).await?;