From 8122bc8891b1872ca85eb119ebdaf5cb820edbef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 22 Oct 2026 06:16:37 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20feat:=20the=20discussion=20list=20a?= =?UTF-8?q?nd=20each=20discussion=20page=20update=20live?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-web/src/boot.rs | 1 + crates/forge-web/src/live.rs | 7 + crates/forge-web/src/pages/discussion_live.rs | 155 +++++++++++ .../src/pages/discussion_live_tests.rs | 249 ++++++++++++++++++ crates/forge-web/src/pages/discussion_view.rs | 4 +- crates/forge-web/src/pages/discussions.rs | 4 +- crates/forge-web/src/pages/mod.rs | 3 + crates/forge-web/src/test_support.rs | 1 + docs/architecture.md | 1 + 9 files changed, 423 insertions(+), 2 deletions(-) create mode 100644 crates/forge-web/src/pages/discussion_live.rs create mode 100644 crates/forge-web/src/pages/discussion_live_tests.rs diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 4e56572..31232b4 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -169,6 +169,7 @@ pub async fn serve( .layer(crate::pages::settings_profile::avatar_body_limit()) .layer(crate::pages::repo_ctx::RepoMovedLayer) .layer(crate::pages::pull_live::PullWriteLayer) + .layer(crate::pages::discussion_live::DiscussionWriteLayer) .layer(crate::pages::not_found_page::NotFoundLayer) .layer(TowerLayer::new(crate::compression::ResponseCompression)) .compression(Compression::off()) diff --git a/crates/forge-web/src/live.rs b/crates/forge-web/src/live.rs index 0e0161b..85fbfc4 100644 --- a/crates/forge-web/src/live.rs +++ b/crates/forge-web/src/live.rs @@ -63,6 +63,13 @@ pub enum Topic { Inbox(String), /// The public repo listing: a public repo was added, changed, or starred. Global. Explore, + /// The discussions of a repo as a list: a discussion was opened, or any discussion of the repo + /// changed (a comment, a reaction, an answer, a lock, a category). Keyed by repo id. Bumped by + /// [`crate::pages::discussion_live`]. + Discussions(String), + /// One discussion: its body, comments, reactions, answer and lock state. Keyed by discussion + /// id. Bumped by [`crate::pages::discussion_live`]. + Discussion(String), } /// The open topics, each with the counter its subscribers wait on. diff --git a/crates/forge-web/src/pages/discussion_live.rs b/crates/forge-web/src/pages/discussion_live.rs new file mode 100644 index 0000000..4c2254d --- /dev/null +++ b/crates/forge-web/src/pages/discussion_live.rs @@ -0,0 +1,155 @@ +//! Live discussions. The discussion list (`/{o}/{r}/discussions`) follows [`Topic::Discussions`]; +//! a discussion page follows [`Topic::Discussion`]. Both pages render `data-live` with the URL of +//! their stream, and a `changed` event re-renders them in place (see `nav.js`). The reply box and +//! the other fields keep what was typed, since `nav.js` captures the fields before the swap. +//! +//! Every discussion write is a POST under `/{o}/{r}/discussions/...`, or the discussions toggle in +//! the repo settings. [`DiscussionWriteLayer`] bumps after the handler ran, so no route calls a +//! bump itself. The topics are resolved before the handler, so a write that deletes the discussion +//! still wakes its page, which then shows the 404 the page now gives. +//! +//! Both streams take the page's own read check: the repo read check, and the discussions toggle +//! (a repo with discussions off is 404 on every page). The item stream also 404s on a discussion +//! that is not there. + +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::request::{method, uri}; +use topcoat::router::response::Response; +use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, path_param, route}; + +use crate::live::{Topic, stream_wakes}; +use crate::pages::discussions::{discussion_by_number, ensure_enabled}; +use crate::pages::repo_ctx::load_repo; +use crate::state::AppState; + +path_param!(owner); +path_param!(repo); +path_param!(number); + +/// The stream URL of the discussion list of `owner/repo`. +pub fn list_live_url(owner: &str, repo: &str) -> String { + format!("/{owner}/{repo}/discussions/live") +} + +/// The stream URL of one discussion, for its page. +pub fn item_live_url(owner: &str, repo: &str, number: i64) -> String { + format!("/{owner}/{repo}/discussions/{number}/live") +} + +/// The change stream of the discussion list. +#[route(GET "/{owner}/{repo}/discussions/live")] +async fn discussions_live(cx: &Cx) -> Result { + let ctx = load_repo(cx, path_param::(cx), path_param::(cx)).await?; + let state = app_context::(cx); + ensure_enabled(state, &ctx).await?; + stream_wakes(cx, &state.live, &[Topic::Discussions(ctx.repo.id.clone())]) +} + +/// The change stream of one discussion page. +#[route(GET "/{owner}/{repo}/discussions/{number}/live")] +async fn discussion_live(cx: &Cx) -> Result { + let ctx = load_repo(cx, path_param::(cx), path_param::(cx)).await?; + let state = app_context::(cx); + ensure_enabled(state, &ctx).await?; + let discussion = discussion_by_number(state, &ctx, path_param::(cx)).await?; + stream_wakes(cx, &state.live, &[Topic::Discussion(discussion.id.clone())]) +} + +// The write layer + +/// Which topics a discussion write reaches. +enum Written { + /// A new discussion, or the discussions toggle of the repo settings: the list. + List { owner: String, repo: String }, + /// A write to one discussion (`/{o}/{r}/discussions/{n}/...`): the list and the discussion. + Discussion { + owner: String, + repo: String, + number: String, + }, +} + +/// The write a request makes to the discussion side, when it is a POST that can change one. +fn written(cx: &Cx) -> Option { + if *method(cx) != Method::POST { + return None; + } + let path = uri(cx).path().to_owned(); + let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); + let [owner, repo, kind, rest @ ..] = parts.as_slice() else { + return None; + }; + let (owner, repo) = ((*owner).to_owned(), (*repo).to_owned()); + match (*kind, rest) { + ("discussions", ["new"]) => Some(Written::List { owner, repo }), + ("discussions", [number, ..]) => Some(Written::Discussion { + owner, + repo, + number: (*number).to_owned(), + }), + ("settings", ["discussions"]) => Some(Written::List { owner, repo }), + _ => None, + } +} + +/// The topics a write reaches, looked up before the handler runs. A repo or discussion that does +/// not exist yields nothing, and a failed lookup is logged. +async fn topics_of(state: &AppState, target: Written) -> Vec { + let (owner, name) = match &target { + Written::List { owner, repo } | Written::Discussion { owner, repo, .. } => { + (owner.as_str(), repo.as_str()) + } + }; + let repo = match state.store.repo_by_owner_and_name(owner, name).await { + Ok(Some(repo)) => repo, + Ok(None) => return Vec::new(), + Err(e) => { + tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed"); + return Vec::new(); + } + }; + let mut topics = vec![Topic::Discussions(repo.id.clone())]; + if let Written::Discussion { number, .. } = target + && let Ok(number) = number.parse::() + { + match state.store.discussion_by_number(&repo.id, number).await { + Ok(Some(discussion)) => topics.push(Topic::Discussion(discussion.id)), + Ok(None) => {} + Err(e) => { + tracing::error!(error = %e, number, "live: loading the discussion to bump failed") + } + } + } + topics +} + +/// Bumps the topics a write reaches, once the handler has run. The handler's result passes +/// through unchanged, so a refused write (an error or a redirect) bumps too: the page re-reads and +/// agrees. +async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result { + let state = app_context::(cx); + let topics = match written(cx) { + Some(target) => topics_of(state, target).await, + None => Vec::new(), + }; + let result = next.run(cx, body).await; + for topic in &topics { + state.live.bump(topic); + } + result +} + +/// Wraps every request. Only a POST under the discussions paths, or the discussions settings +/// toggle, does anything. Registered on the public router in `boot.rs`, next to the other layers. +pub struct DiscussionWriteLayer; + +impl Layer for DiscussionWriteLayer { + fn path(&self) -> Option<&Path> { + None + } + + fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { + Box::pin(bump_after_write(cx, body, next)) + } +} diff --git a/crates/forge-web/src/pages/discussion_live_tests.rs b/crates/forge-web/src/pages/discussion_live_tests.rs new file mode 100644 index 0000000..907b8ce --- /dev/null +++ b/crates/forge-web/src/pages/discussion_live_tests.rs @@ -0,0 +1,249 @@ +//! Router-level tests for the discussion live streams: a write bumps the topics it reaches, and a +//! viewer without read access (or a repo with discussions off) gets 404 from a stream. + +use std::sync::Arc; + +use forge_core::discussions::DiscussionCategory; +use forge_core::{Store, Visibility}; +use topcoat::router::request::Request; +use topcoat::router::{Body, Router, to_bytes}; + +use crate::auth::SESSION_COOKIE; +use crate::live::{LiveHub, Topic}; + +const CSRF: &str = "discussion-live-csrf"; + +struct Site { + router: Router, + store: Store, + live: Arc, + _dir: tempfile::TempDir, +} + +async fn site() -> Site { + let dir = tempfile::tempdir().expect("tempdir"); + let state = crate::test_support::test_state(dir.path()).await; + let store = state.store.clone(); + let live = state.live.clone(); + let router = crate::test_support::app_router(state); + Site { + router, + store, + live, + _dir: dir, + } +} + +async fn sign_in(store: &Store, user_id: &str, token: &str) -> String { + crate::test_support::create_session(store, user_id, token, CSRF).await; + format!("__Host-{SESSION_COOKIE}={token}") +} + +/// Sends a form POST and returns its status. The body is read, so the write has finished. +async fn post(site: &Site, uri: &str, cookie: &str, fields: &[(&str, &str)]) -> u16 { + let body = Body::from( + form_urlencoded::Serializer::new(String::new()) + .extend_pairs(fields) + .finish(), + ); + let request = Request::builder() + .method("POST") + .uri(uri) + .header("cookie", cookie) + .header("content-type", "application/x-www-form-urlencoded") + .body(body) + .expect("request"); + let res = site.router.handle(request).await; + let status = res.status().as_u16(); + to_bytes(res.into_body(), usize::MAX).await.expect("body"); + status +} + +/// The status of a stream request. The stream body is not read: it never ends on its own. +async fn stream_status(site: &Site, uri: &str, cookie: Option<&str>) -> u16 { + let mut builder = Request::builder().method("GET").uri(uri); + if let Some(cookie) = cookie { + builder = builder.header("cookie", cookie); + } + let res = site + .router + .handle(builder.body(Body::empty()).expect("request")) + .await; + res.status().as_u16() +} + +struct Seed { + site: Site, + owner_cookie: String, + bob_cookie: String, + repo_id: String, + discussion_id: String, +} + +/// Tahinli owns `tahinli/forge` with discussions on and one discussion, number 1. Bob signs in +/// with no role on the repo. +async fn seeded(visibility: Visibility) -> Seed { + let site = site().await; + let store = site.store.clone(); + let tahinli = store + .create_user("tahinli", None, "unused", false) + .await + .expect("tahinli"); + let bob = store + .create_user("bob", None, "unused", false) + .await + .expect("bob"); + let repo = store + .create_repo(&tahinli.id, "forge", "", visibility, "main") + .await + .expect("repo"); + store + .set_discussions_enabled(&repo.id, true) + .await + .expect("enable"); + let discussion = store + .create_discussion( + &repo.id, + &tahinli.id, + DiscussionCategory::General, + "Hello", + "Body", + ) + .await + .expect("discussion"); + let owner_cookie = sign_in(&store, &tahinli.id, "owner-token").await; + let bob_cookie = sign_in(&store, &bob.id, "bob-token").await; + Seed { + site, + owner_cookie, + bob_cookie, + repo_id: repo.id, + discussion_id: discussion.id, + } +} + +#[tokio::test] +async fn a_comment_bumps_the_list_and_the_discussion_only() { + let seed = seeded(Visibility::Public).await; + let site = &seed.site; + let list = site + .live + .subscribe(&Topic::Discussions(seed.repo_id.clone())); + let item = site + .live + .subscribe(&Topic::Discussion(seed.discussion_id.clone())); + let other = site.live.subscribe(&Topic::Discussion("other".to_owned())); + + let status = post( + site, + "/tahinli/forge/discussions/1/comments", + &seed.owner_cookie, + &[("csrf", CSRF), ("body", "A reply")], + ) + .await; + + assert_ne!(status, 404, "the comment was refused"); + let comments = site + .store + .list_discussion_comments(&seed.discussion_id) + .await + .expect("comments"); + assert_eq!(comments.len(), 1, "the comment was stored"); + assert!(list.has_changed().expect("open"), "the list was bumped"); + assert!( + item.has_changed().expect("open"), + "the discussion was bumped" + ); + assert!(!other.has_changed().expect("open")); +} + +#[tokio::test] +async fn a_new_discussion_bumps_the_list() { + let seed = seeded(Visibility::Public).await; + let site = &seed.site; + let list = site + .live + .subscribe(&Topic::Discussions(seed.repo_id.clone())); + let category = DiscussionCategory::General.as_str(); + + let status = post( + site, + "/tahinli/forge/discussions/new", + &seed.owner_cookie, + &[ + ("csrf", CSRF), + ("category", category), + ("title", "Another"), + ("body", "Text"), + ], + ) + .await; + + assert_ne!(status, 404, "the discussion was refused"); + assert!(list.has_changed().expect("open"), "the list was bumped"); +} + +#[tokio::test] +async fn a_refused_write_still_bumps_so_the_page_reads_the_truth() { + let seed = seeded(Visibility::Public).await; + let site = &seed.site; + let item = site + .live + .subscribe(&Topic::Discussion(seed.discussion_id.clone())); + + // A blank comment is refused by the handler. The write layer bumps after the handler either way. + let status = post( + site, + "/tahinli/forge/discussions/1/comments", + &seed.bob_cookie, + &[("csrf", CSRF), ("body", "")], + ) + .await; + + assert_ne!(status, 404, "the discussion page answered"); + assert!( + item.has_changed().expect("open"), + "the discussion was bumped" + ); +} + +#[tokio::test] +async fn streams_follow_the_page_read_check() { + let seed = seeded(Visibility::Private).await; + let site = &seed.site; + let list = "/tahinli/forge/discussions/live"; + let item = "/tahinli/forge/discussions/1/live"; + + assert_eq!(stream_status(site, list, None).await, 404, "anonymous list"); + assert_eq!(stream_status(site, item, None).await, 404, "anonymous item"); + assert_eq!( + stream_status(site, list, Some(&seed.bob_cookie)).await, + 404, + "bob, no access, list" + ); + assert_eq!( + stream_status(site, item, Some(&seed.bob_cookie)).await, + 404, + "bob, no access, item" + ); + assert_eq!( + stream_status(site, list, Some(&seed.owner_cookie)).await, + 200, + "owner, list" + ); + assert_eq!( + stream_status(site, item, Some(&seed.owner_cookie)).await, + 200, + "owner, item" + ); + assert_eq!( + stream_status( + site, + "/tahinli/forge/discussions/9/live", + Some(&seed.owner_cookie) + ) + .await, + 404, + "a discussion that is not there" + ); +} diff --git a/crates/forge-web/src/pages/discussion_view.rs b/crates/forge-web/src/pages/discussion_view.rs index fe1cc85..ac2cac7 100644 --- a/crates/forge-web/src/pages/discussion_view.rs +++ b/crates/forge-web/src/pages/discussion_view.rs @@ -14,6 +14,7 @@ use topcoat::view::{Unescaped, View, component, view}; use crate::i18n::community::{self as g, K}; use crate::i18n::{self, Lang}; +use crate::pages::discussion_live::item_live_url; use crate::pages::discussions::{ discussion_by_number, discussions_href, ensure_enabled, is_author, may_converse, }; @@ -395,13 +396,14 @@ async fn discussion_page( let page_title = format!("{} {number_label} \u{b7} {owner}/{name}", discussion.title); let login_href = "/login".to_owned(); let lock_notice = g::t(lang, K::LockedNotice); + let live_href = item_live_url(&owner, &name, number); let header = ctx.head(state, "discussions").await?; let comments_label = g::comments_total(lang, discussion.comment_count); Ok(view! { cx => shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), repo_head(head: header) -
+

(discussion.title.as_str()) " " (number_label.as_str())

+