diff --git a/Cargo.lock b/Cargo.lock index 808755b..47b6125 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -109,6 +109,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ "axum-core", + "base64 0.22.1", "bytes", "form_urlencoded", "futures-util", @@ -127,8 +128,10 @@ dependencies = [ "serde_json", "serde_path_to_error", "serde_urlencoded", + "sha1", "sync_wrapper", "tokio", + "tokio-tungstenite", "tower", "tower-layer", "tower-service", @@ -442,6 +445,12 @@ dependencies = [ "typenum", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "data-url" version = "0.3.2" @@ -702,6 +711,7 @@ dependencies = [ "axum-extra", "db", "deunicode", + "futures-util", "http-body-util", "serde", "serde_json", @@ -710,6 +720,7 @@ dependencies = [ "thiserror", "time", "tokio", + "tokio-tungstenite", "tower", "tower-http", "tracing", @@ -2924,6 +2935,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + [[package]] name = "tower" version = "0.5.3" @@ -3074,6 +3097,22 @@ dependencies = [ "core_maths", ] +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror", +] + [[package]] name = "typenum" version = "1.20.1" diff --git a/deploy/Caddyfile b/deploy/Caddyfile index 7f164da..920e132 100644 --- a/deploy/Caddyfile +++ b/deploy/Caddyfile @@ -15,10 +15,20 @@ # No basic auth any more: the site is open, and new accounts need an # invitation (SIGNUP_MODE=invite in the backend). encode zstd gzip - reverse_proxy frontend:3000 { - # The address the backend trusts (rate limits, share visits); it - # overwrites whatever the browser sent in this header. - header_up X-Real-IP {client_ip} + # The forum's live connection (WebSocket) goes straight to the forum + # service: the frontend's /api/v1 proxy cannot carry it. + handle /api/v1/forum/ws { + rewrite * /v1/forum/ws + reverse_proxy forum:8083 { + header_up X-Real-IP {client_ip} + } + } + handle { + reverse_proxy frontend:3000 { + # The address the backend trusts (rate limits, share visits); it + # overwrites whatever the browser sent in this header. + header_up X-Real-IP {client_ip} + } } } diff --git a/docker-compose.yml b/docker-compose.yml index ab302ff..05509c3 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -138,6 +138,10 @@ services: HOROSCOPE_API_URL: http://horoscope-api:8080 # Empty: the forum is switched off (no menu item, its pages 404). FORUM_URL: ${FORUM_URL:-http://forum:8083} + # The forum's live connection, as the browser reaches it (production: + # Caddy's /api/v1/forum/ws). Over an SSH tunnel, tunnel 8083 too, or the + # forum falls back to polling every 30 seconds. + FORUM_WS_URL: ${FORUM_WS_URL:-ws://localhost:8083/v1/forum/ws} depends_on: backend: condition: service_healthy diff --git a/docs/kozosseg.md b/docs/kozosseg.md index ddd7073..d8e0e55 100644 --- a/docs/kozosseg.md +++ b/docs/kozosseg.md @@ -122,6 +122,20 @@ Jelölés: ami mellett **(javaslat)** áll, azt még nem hagytuk jóvá, a több - a lezárt jelentések és a lejárt eltiltások oka 1 év után törlődik, a moderálási napló 2 év után; - az el nem fogadott kérések 90 nap után törlődnek, és a régi álnevek foglalása is 90 nap után jár le. +### Ami elkészült (4. kör) + +- **Élő jelzés WebSocketen** (`services/forum/src/live.rs`, `GET /v1/forum/ws`): + - Csak csengő, adatot nem visz: `{"t":"nav"}`, ha a menü számlálói változtak; `{"t":"thread","id":…}`, ha egy szálban történt valami; `{"t":"conversation","id":…}`, ha egy beszélgetésben. Az oldal ilyenkor HTTP-n kéri le az újat. + - Az eseményeket a Postgres `NOTIFY forum_events` viszi, így több fórumpéldánynál is mindenki megkapja. + - A szerver 30 másodpercenként pingel (a Cloudflare 100 másodperc tétlenség után bont), és ez frissíti az online pöttyöt is. + - Csak a saját oldalról lehet kapcsolódni: az `Origin` fejléc ellenőrzése véd az idegen oldalról nyitott kapcsolat ellen. + - Ha nincs kapcsolat, a menü 30 másodpercenként lekérdez. +- **A menü** kliensoldalon frissíti a jelvényeket: élő jelzésre, minden lapváltáskor, és amikor az oldal újra előtérbe kerül. Eddig csak teljes újratöltéskor frissült. +- **Azonnal frissül:** a nyitott szál, a beszélgetés és az üzenetlista. +- **Útvonal:** + - Élesben a Caddy küldi a `/api/v1/forum/ws`-t közvetlenül a fórumszolgáltatásnak (`deploy/Caddyfile`). + - Fejlesztéskor a frontend `FORUM_WS_URL` változója mutat rá (`ws://localhost:8083/v1/forum/ws`). SSH-alagúton át a 8083-as portot is át kell vinni, különben marad a 30 másodperces lekérdezés. + ### Élesítéskor - `FORUM_URL=http://forum:8083` az éles `.env`-be. @@ -133,7 +147,6 @@ Jelölés: ami mellett **(javaslat)** áll, azt még nem hagytuk jóvá, a több - **Hírlevél:** az oldalnak még nincs hírlevele. Ha lesz, külön, kifejezett hozzájárulással, nem a fórum beállításai között. -- **WebSocket-csengő** a lekérdezés helyett. - **Napi „Mai égbolt” szál:** a worker nyitná meg automatikusan. - **AI-funkciók:** előszűrés, lelki krízis jelzése, az AI-összefoglaló kártya a főoldalon. - **Saját avatar feltöltése** (Spaces), és a „Támogató” jelvény. diff --git a/services/forum/Cargo.toml b/services/forum/Cargo.toml index 7acaedd..5276d7c 100644 --- a/services/forum/Cargo.toml +++ b/services/forum/Cargo.toml @@ -10,7 +10,7 @@ publish.workspace = true db.workspace = true service-kit.workspace = true anyhow.workspace = true -axum.workspace = true +axum = { workspace = true, features = ["ws"] } axum-extra.workspace = true deunicode.workspace = true serde.workspace = true @@ -18,11 +18,13 @@ serde_json.workspace = true sqlx.workspace = true thiserror.workspace = true time.workspace = true -tokio.workspace = true +tokio = { workspace = true, features = ["time"] } tower-http.workspace = true tracing.workspace = true uuid.workspace = true [dev-dependencies] tower = { version = "0.5", features = ["util"] } +tokio-tungstenite = "0.29" +futures-util = { version = "0.3", default-features = false } http-body-util = "0.1" diff --git a/services/forum/src/live.rs b/services/forum/src/live.rs new file mode 100644 index 0000000..11d36b8 --- /dev/null +++ b/services/forum/src/live.rs @@ -0,0 +1,244 @@ +//! 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, + /// 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, +} + +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 { + 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 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>, + 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 { + 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); + } +} diff --git a/services/forum/src/main.rs b/services/forum/src/main.rs index cc7f083..358c2af 100644 --- a/services/forum/src/main.rs +++ b/services/forum/src/main.rs @@ -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?; diff --git a/services/forum/src/routes/messages.rs b/services/forum/src/routes/messages.rs index 045ba38..991c5f7 100644 --- a/services/forum/src/routes/messages.rs +++ b/services/forum/src/routes/messages.rs @@ -225,6 +225,11 @@ pub async fn request( }; tx.commit().await?; crate::mail::after_message(&state, id, me.user_id, true, Some(&intro)).await; + crate::live::emit( + &state.db, + crate::live::Event { conversation: Some(id), ..Default::default() }.for_users(vec![other]), + ) + .await; Ok((StatusCode::CREATED, Json(json!({ "id": id })))) } @@ -398,6 +403,8 @@ pub async fn respond(state: St, viewer: Viewer, path: IdPath, answer: &'static s .await?; } } + let event = crate::live::Event { conversation: Some(id), ..Default::default() }.for_users(vec![c.other(me), me]); + crate::live::emit(&state.db, event).await; Ok(StatusCode::NO_CONTENT) } @@ -463,6 +470,8 @@ pub async fn send( mark(&mut *tx, id, me, message_id).await?; tx.commit().await?; crate::mail::after_message(&state, id, me, false, None).await; + let event = crate::live::Event { conversation: Some(id), ..Default::default() }.for_users(vec![c.other(me)]); + crate::live::emit(&state.db, event).await; Ok(( StatusCode::CREATED, Json(json!({ "id": message_id, "mine": true, "body": body, "created_at": rfc3339(created_at) })), diff --git a/services/forum/src/routes/mod.rs b/services/forum/src/routes/mod.rs index 5a6a979..f5341b6 100644 --- a/services/forum/src/routes/mod.rs +++ b/services/forum/src/routes/mod.rs @@ -66,6 +66,7 @@ pub fn router(state: Arc) -> Router { .route("/v1/forum/nickname-check", get(members::nickname_check)) .route("/v1/forum/presence", post(members::presence)) .route("/v1/forum/unsubscribe", post(members::unsubscribe)) + .route("/v1/forum/ws", get(crate::live::connect)) .route("/v1/forum/members/{nickname}", get(members::profile)) .route("/v1/forum/members/{nickname}/ban", post(moderation::ban).delete(moderation::unban)) .route("/v1/forum/mod/log", get(moderation::log)) diff --git a/services/forum/src/routes/posts.rs b/services/forum/src/routes/posts.rs index f4371c2..18918a0 100644 --- a/services/forum/src/routes/posts.rs +++ b/services/forum/src/routes/posts.rs @@ -18,6 +18,11 @@ use crate::error::{ApiError, ApiResult}; use crate::rank::HELPED_POINTS; use crate::text; +/// Anyone viewing the thread refetches it (reactions, edits, removals). +async fn announce(state: &crate::AppState, thread: i64) { + crate::live::emit(&state.db, crate::live::Event { thread: Some(thread), ..Default::default() }).await; +} + /// A post and its thread, both readable by the viewer. async fn load(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<(PostRow, ThreadRow)> { let post: PostRow = sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE id = $1")) @@ -55,6 +60,7 @@ pub async fn edit( .bind(&body) .fetch_one(&state.db) .await?; + announce(&state, post.thread_id).await; Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0))) } @@ -120,6 +126,7 @@ pub async fn remove( } crate::mail::notify_reporters(&state, &reporters, "removed").await; } + announce(&state, post.thread_id).await; Ok(StatusCode::NO_CONTENT) } @@ -224,6 +231,7 @@ pub async fn react( .await?; add_points(&mut tx, post.author_id, delta).await?; tx.commit().await?; + announce(&state, post.thread_id).await; Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0))) } @@ -241,6 +249,7 @@ pub async fn unreact(State(state): St, viewer: Viewer, WithRejection(Path(id), _ add_points(&mut tx, post.author_id, -points_of(&kind)).await?; } tx.commit().await?; + announce(&state, post.thread_id).await; Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0))) } @@ -293,6 +302,7 @@ async fn set_helped( add_points(&mut tx, post.author_id, if on { HELPED_POINTS } else { -HELPED_POINTS }).await?; } tx.commit().await?; + announce(&state, thread.id).await; let post: PostRow = sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE id = $1")) .bind(id) .fetch_one(&state.db) diff --git a/services/forum/src/routes/reports.rs b/services/forum/src/routes/reports.rs index 4419f41..954964a 100644 --- a/services/forum/src/routes/reports.rs +++ b/services/forum/src/routes/reports.rs @@ -97,6 +97,7 @@ pub async fn report_post( .execute(&state.db) .await?; tracing::info!(post = id, kind = %req.kind, "post reported"); + crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await; Ok((StatusCode::CREATED, received(&req.kind))) } @@ -132,6 +133,7 @@ pub async fn report_message( .execute(&state.db) .await?; tracing::info!(message = id, kind = %req.kind, "message reported"); + crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await; Ok((StatusCode::CREATED, received(&req.kind))) } @@ -322,6 +324,7 @@ pub async fn handle( tx.commit().await?; let outcome = if status == "resolved" { "handled" } else { "no_violation" }; crate::mail::notify_reporters(&state, &reporters, outcome).await; + crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await; Ok(StatusCode::NO_CONTENT) } diff --git a/services/forum/src/routes/threads.rs b/services/forum/src/routes/threads.rs index c24bbe2..78a652f 100644 --- a/services/forum/src/routes/threads.rs +++ b/services/forum/src/routes/threads.rs @@ -421,6 +421,9 @@ pub async fn reply( after_post(&mut tx, member.user_id, id, post.id).await?; tx.commit().await?; crate::mail::after_reply(&state, id, post.id, member.user_id, post.parent_id, &body).await; + let followers = crate::live::followers(&state.db, id, member.user_id).await; + crate::live::emit(&state.db, crate::live::Event { thread: Some(id), ..Default::default() }.for_users(followers)) + .await; let post = posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0); Ok((StatusCode::CREATED, Json(post))) } diff --git a/services/forum/src/tests.rs b/services/forum/src/tests.rs index 3b4c6c8..dd03f9c 100644 --- a/services/forum/src/tests.rs +++ b/services/forum/src/tests.rs @@ -30,7 +30,12 @@ struct User { impl TestApp { fn new(pool: PgPool) -> Self { - let state = AppState { db: pool.clone(), flood_secs: 0, base_url: "https://sorsfonalak.test".into() }; + let state = AppState { + db: pool.clone(), + flood_secs: 0, + base_url: "https://sorsfonalak.test".into(), + hub: crate::live::Hub::default(), + }; Self { router: routes::router(Arc::new(state)), pool } } @@ -842,3 +847,68 @@ async fn instant_mails_and_unsubscribe(pool: PgPool) { let me = app.get("/v1/forum/me", Some(&anna)).await; assert_eq!(me["member"]["email"], json!({"replies": "off", "followed": "off", "messages": "off"})); } + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn live_doorbell_over_websocket(pool: PgPool) { + use tokio_tungstenite::tungstenite::client::IntoClientRequest; + + let state = Arc::new(AppState { + db: pool.clone(), + flood_secs: 0, + base_url: "https://sorsfonalak.test".into(), + hub: crate::live::Hub::default(), + }); + tokio::spawn(crate::live::listen(pool.clone(), state.hub.clone())); + let router = routes::router(state.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let served = router.clone(); + tokio::spawn(async move { axum::serve(listener, served).await.unwrap() }); + let app = TestApp { router, pool }; + let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await; + let bea = app.member("bea@example.com", "Holdfény", &["user"]).await; + let thread = app.thread(&anna, "belso-utak", "Reggeli csend").await; + // Give the database listener a moment to start. + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + + let request = |token: &str, origin: Option<&str>| { + let mut req = format!("ws://{addr}/v1/forum/ws").into_client_request().unwrap(); + req.headers_mut().insert("authorization", format!("Bearer {token}").parse().unwrap()); + if let Some(o) = origin { + req.headers_mut().insert("origin", o.parse().unwrap()); + } + req + }; + // Another site may not open it with the visitor's credentials. + let refused = tokio_tungstenite::connect_async(request(&anna.token, Some("https://evil.example"))).await; + assert!(refused.is_err()); + let (mut ws, _) = + tokio_tungstenite::connect_async(request(&anna.token, Some("https://sorsfonalak.test"))).await.unwrap(); + + // Bea replies in Anna's thread: Anna hears of the thread and of her menu. + app.reply(&bea, thread, "Én hajnalban ülök le.", None).await; + let mut heard = Vec::new(); + while heard.len() < 2 { + let next = tokio::time::timeout(std::time::Duration::from_secs(5), futures_next(&mut ws)).await; + match next { + Ok(Some(text)) => heard.push(text), + _ => break, + } + } + assert_eq!(heard, vec![format!(r#"{{"id":{thread},"t":"thread"}}"#), r#"{"t":"nav"}"#.to_string()]); +} + +/// The next text message of a test WebSocket. +async fn futures_next( + ws: &mut tokio_tungstenite::WebSocketStream>, +) -> Option { + use futures_util::StreamExt; + use tokio_tungstenite::tungstenite::Message; + loop { + match ws.next().await? { + Ok(Message::Text(t)) => return Some(t.to_string()), + Ok(_) => continue, + Err(_) => return None, + } + } +} diff --git a/services/frontend/src/app/forum/layout.tsx b/services/frontend/src/app/forum/layout.tsx index 776e0ab..6e0aead 100644 --- a/services/frontend/src/app/forum/layout.tsx +++ b/services/frontend/src/app/forum/layout.tsx @@ -17,6 +17,9 @@ export const metadata: Metadata = { }; /** + * The live connection's address: in production Caddy sends `/api/v1/forum/ws` + * straight to the forum service; in development FORUM_WS_URL points at it. + * * The forum's frame: the visitor header (the logged-in one comes from the * root layout), the forum's bar with its menu and the light/dark switch. * Light by default; the choice lives in a cookie. @@ -38,14 +41,13 @@ export default async function ForumLayout({ children }: { children: React.ReactN - {nav.ok && nav.data.reports ? ( - - Jelentés: {nav.data.reports} - - ) : null}
{children}
diff --git a/services/frontend/src/app/forum/uzenetek/Conversations.tsx b/services/frontend/src/app/forum/uzenetek/Conversations.tsx index 084b426..0db6b78 100644 --- a/services/frontend/src/app/forum/uzenetek/Conversations.tsx +++ b/services/frontend/src/app/forum/uzenetek/Conversations.tsx @@ -2,7 +2,7 @@ import Link from "next/link"; import { useRouter } from "next/navigation"; -import { useState } from "react"; +import { useEffect, useState } from "react"; import { AuthorLine } from "@/components/forum/AuthorLine"; import { Avatar } from "@/components/forum/Avatar"; @@ -12,6 +12,13 @@ import { type ConversationItem, ago } from "@/lib/forum"; export function Conversations({ initial }: { initial: ConversationItem[] }) { const router = useRouter(); const [items, setItems] = useState(initial); + // New messages and requests show up while the list is open. + useEffect(() => setItems(initial), [initial]); + useEffect(() => { + const live = () => router.refresh(); + window.addEventListener("forum:live", live); + return () => window.removeEventListener("forum:live", live); + }, [router]); const [busy, setBusy] = useState(null); const [error, setError] = useState(null); diff --git a/services/frontend/src/app/forum/uzenetek/[id]/Chat.tsx b/services/frontend/src/app/forum/uzenetek/[id]/Chat.tsx index eab6026..c7862dc 100644 --- a/services/frontend/src/app/forum/uzenetek/[id]/Chat.tsx +++ b/services/frontend/src/app/forum/uzenetek/[id]/Chat.tsx @@ -7,12 +7,13 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { Avatar } from "@/components/forum/Avatar"; import { Composer } from "@/components/forum/Composer"; import { PostBody } from "@/components/forum/PostBody"; +import type { LiveNotice } from "@/components/forum/ForumNav"; import { ReportButton } from "@/components/forum/ReportButton"; import { api, errorText } from "@/lib/api"; import { type ChatMessage, type ConversationPage, memberHref } from "@/lib/forum"; -/** How often an open conversation looks for new messages (while in front). */ -const POLL_MS = 15_000; +/** A safety net: how often an open conversation looks for new messages anyway. */ +const POLL_MS = 30_000; function when(iso: string) { return new Date(iso).toLocaleString("hu-HU", { @@ -50,12 +51,23 @@ export function Chat({ initial }: { initial: ConversationPage }) { }, [base]); useEffect(() => { - if (c.state !== "accepted") return; - const timer = window.setInterval(() => { - if (document.visibilityState === "visible") void refresh(); - }, POLL_MS); - return () => window.clearInterval(timer); - }, [c.state, refresh]); + // The live connection rings for this conversation (a message, or the request answered). + const live = (e: Event) => { + const notice = (e as CustomEvent).detail; + if (notice.t === "conversation" && notice.id === c.id) void refresh(); + }; + window.addEventListener("forum:live", live); + const timer = + c.state === "accepted" + ? window.setInterval(() => { + if (document.visibilityState === "visible") void refresh(); + }, POLL_MS) + : undefined; + return () => { + window.removeEventListener("forum:live", live); + window.clearInterval(timer); + }; + }, [c.id, c.state, refresh]); async function run(work: () => Promise) { setBusy(true); diff --git a/services/frontend/src/components/forum/ForumNav.tsx b/services/frontend/src/components/forum/ForumNav.tsx index def7a27..9393057 100644 --- a/services/frontend/src/components/forum/ForumNav.tsx +++ b/services/frontend/src/components/forum/ForumNav.tsx @@ -2,24 +2,88 @@ import Link from "next/link"; import { usePathname } from "next/navigation"; -import { useEffect } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { api } from "@/lib/api"; +import type { ForumNavData } from "@/lib/forum"; -/** Every minute while the page is in front: keeps the member's online dot. */ -function usePresence(member: boolean) { +/** The menu's counts. */ +export interface NavCounts { + unread: number; + messages: number; + reports: number; +} + +/** The live notice a page listens to (`window` event `forum:live`). */ +export interface LiveNotice { + t: "thread" | "conversation" | "nav"; + id?: number; +} + +/** How often the counts are asked for while there is no live connection (also the online dot). */ +const POLL_MS = 30_000; + +function counts(data: ForumNavData): NavCounts { + return { unread: data.followed?.new_replies ?? 0, messages: data.messages ?? 0, reports: data.reports ?? 0 }; +} + +/** + * The live connection (a member's): the server rings when something changed, + * the menu fetches its counts, and an open thread or conversation is told + * (`forum:live` events). Without a connection, the counts are polled. + */ +function useLive(member: boolean, wsUrl: string, refresh: () => void) { + const open = useRef(false); useEffect(() => { if (!member) return; - const ping = () => { - if (document.visibilityState === "visible") api("/forum/presence", { method: "POST" }).catch(() => {}); + let socket: WebSocket | null = null; + let retry = 1000; + let timer: number | undefined; + let stopped = false; + const url = new URL(wsUrl, window.location.href); + url.protocol = url.protocol === "https:" ? "wss:" : url.protocol === "http:" ? "ws:" : url.protocol; + const connect = () => { + if (stopped) return; + socket = new WebSocket(url); + socket.onopen = () => { + open.current = true; + retry = 1000; + refresh(); + }; + socket.onmessage = (e) => { + let notice: LiveNotice; + try { + notice = JSON.parse(String(e.data)) as LiveNotice; + } catch { + return; + } + if (notice.t === "nav") refresh(); + window.dispatchEvent(new CustomEvent("forum:live", { detail: notice })); + }; + socket.onclose = () => { + open.current = false; + if (stopped) return; + timer = window.setTimeout(connect, retry); + retry = Math.min(retry * 2, 60_000); + }; }; - const timer = window.setInterval(ping, 60_000); - document.addEventListener("visibilitychange", ping); + connect(); + // Polling while there is no connection; and when the page comes back to the front. + const poll = window.setInterval(() => { + if (!open.current && document.visibilityState === "visible") refresh(); + }, POLL_MS); + const visible = () => { + if (document.visibilityState === "visible") refresh(); + }; + document.addEventListener("visibilitychange", visible); return () => { - window.clearInterval(timer); - document.removeEventListener("visibilitychange", ping); + stopped = true; + window.clearTimeout(timer); + window.clearInterval(poll); + document.removeEventListener("visibilitychange", visible); + socket?.close(); }; - }, [member]); + }, [member, wsUrl, refresh]); } function Icon({ name }: { name: "forum" | "followed" | "new" | "messages" | "profile" }) { @@ -66,16 +130,31 @@ function Icon({ name }: { name: "forum" | "followed" | "new" | "messages" | "pro export function ForumNav({ member, loggedIn, - unread, - messages, + initial, + wsUrl, }: { member: string | null; loggedIn: boolean; - unread: number; - messages: number; + initial: NavCounts; + wsUrl: string; }) { const path = usePathname(); - usePresence(member !== null); + const [{ unread, messages, reports }, setCounts] = useState(initial); + const refresh = useCallback(() => { + api("/forum/nav") + .then((data) => setCounts(counts(data))) + .catch(() => {}); + }, []); + useLive(member !== null, wsUrl, refresh); + // The menu stays on screen between pages: fresh counts on every page. + const first = useRef(true); + useEffect(() => { + if (first.current) { + first.current = false; + return; + } + if (loggedIn) refresh(); + }, [path, loggedIn, refresh]); const items = [ { href: "/forum", @@ -119,20 +198,27 @@ export function ForumNav({ }, ]; return ( - + )} + + ); } diff --git a/services/frontend/src/components/forum/ThreadView.tsx b/services/frontend/src/components/forum/ThreadView.tsx index e1f8a99..0810ab5 100644 --- a/services/frontend/src/components/forum/ThreadView.tsx +++ b/services/frontend/src/components/forum/ThreadView.tsx @@ -10,6 +10,7 @@ import { AuthorLine, signsText } from "./AuthorLine"; import { Avatar } from "./Avatar"; import { Composer } from "./Composer"; import { PostBody } from "./PostBody"; +import type { LiveNotice } from "./ForumNav"; import { ReportButton } from "./ReportButton"; /** How often the open thread looks for new replies (while the page is in front). */ @@ -354,8 +355,17 @@ export function ThreadView({ initial }: { initial: ThreadPage }) { }, [base, lastId, thread.deleted]); useEffect(() => { const timer = window.setInterval(poll, POLL_MS); - return () => window.clearInterval(timer); - }, [poll]); + // The live connection rings for this thread: look at once. + const live = (e: Event) => { + const notice = (e as CustomEvent).detail; + if (notice.t === "thread" && notice.id === thread.id) void poll(); + }; + window.addEventListener("forum:live", live); + return () => { + window.clearInterval(timer); + window.removeEventListener("forum:live", live); + }; + }, [poll, thread.id]); const newCount = incoming ? incoming.posts.filter((p) => p.id > lastId && !p.own).length : 0;