diff --git a/crates/forge-web/src/i18n/code.rs b/crates/forge-web/src/i18n/code.rs index 612e1bc..a244b07 100644 --- a/crates/forge-web/src/i18n/code.rs +++ b/crates/forge-web/src/i18n/code.rs @@ -486,6 +486,14 @@ pub fn watching_count(lang: Lang, watchers: u64) -> String { } } +/// ` forks` in English, ` çatal` in Turkish. +pub fn forks_count(lang: Lang, forks: u64) -> String { + match lang { + Lang::En => format!("{forks} forks"), + Lang::Tr => format!("{forks} çatal"), + } +} + /// The mirror status after a successful sync. pub fn mirror_synced(lang: Lang, at: &str) -> String { match lang { diff --git a/crates/forge-web/src/live.rs b/crates/forge-web/src/live.rs index 0531004..8c659aa 100644 --- a/crates/forge-web/src/live.rs +++ b/crates/forge-web/src/live.rs @@ -9,7 +9,7 @@ //! 1. Add a variant to [`Topic`], keyed by what the page is about (a repo id, a user id, ...). //! 2. Call `state.live.bump(&Topic::Variant(..))` after the write that changes the page. //! 3. In the page's own route (its auth check first), return -//! `live::stream_changes(cx, &state.live, &topic, read)`. `read` returns a short fingerprint +//! `live::stream_changes(cx, &state.live, &[topics], read)`. `read` returns a short fingerprint //! of the state the page shows; a `changed` event is sent only when it differs from the last //! one, so a bump that changes nothing visible sends nothing. //! 4. Render `data-live=""` on the page's element that the client follows. @@ -17,6 +17,8 @@ //! A page whose state is cheap to compare can use `stream_changes` (the fingerprint). A page //! whose every bump is a visible change (the issue pages) uses [`stream_wakes`] instead: one //! `changed` per wake, several bumps in a row coalesced into one. +//! A user's topics are keyed by the user id and streamed only to that user: the route takes the +//! viewer from the session, never from the URL, so one user cannot follow another user's inbox. //! //! The hub is in-process only, like [`crate::notify_hub::NotifyHub`]. [`crate::ci::CiLive`] keeps //! its own counters for CI and is not on this hub. @@ -25,6 +27,7 @@ use std::collections::HashMap; use std::future::Future; use std::sync::{Mutex, MutexGuard, PoisonError}; +use futures_util::future::select_all; use futures_util::stream; use tokio::sync::watch; use topcoat::Result; @@ -50,6 +53,16 @@ pub enum Topic { /// One pull request, its conversation, commits and files. Keyed by the pull's issue id. /// Bumped by [`crate::pages::pull_live`]. Pull(String), + /// A repo's own state that its header shows: stars, watchers, forks, and its name and + /// description. Keyed by repo id. + Repo(String), + /// A user's repo listing, pins and contribution calendar. Keyed by user id (an organization + /// is a user too). + User(String), + /// A user's inbox: a notification was added, read or marked read. Keyed by user id. + Inbox(String), + /// The public repo listing: a public repo was added, changed, or starred. Global. + Explore, } /// The open topics, each with the counter its subscribers wait on. @@ -99,11 +112,20 @@ impl LiveHub { self.bump(&Topic::RepoIssues(repo_id.to_owned())); self.bump(&Topic::Issue(issue_id.to_owned())); } + + /// A repo changed in a way its owner's pages, the explore list and its own header show: it + /// was created, renamed, moved, re-described, starred, watched or forked. Call it once per + /// owner whose listing changed (a transfer has two). + pub fn bump_repo(&self, owner_id: &str, repo_id: &str) { + self.bump(&Topic::User(owner_id.to_owned())); + self.bump(&Topic::Explore); + self.bump(&Topic::Repo(repo_id.to_owned())); } } -/// The state a stream follows between wakes: the fingerprint last sent or seen. +/// The state a stream follows between wakes: the receivers of its topics, the read, and the +/// fingerprint last sent or seen. struct Follow { - wake: watch::Receiver, + wakes: Vec>, read: F, last: String, } @@ -113,29 +135,34 @@ fn changed_event() -> Result { Ok(Event::new().event("changed").data("1")) } +/// Waits until one of `wakes` is bumped. False when a topic is gone, which ends the stream. +async fn wait_any(wakes: &mut [watch::Receiver]) -> bool { + let waits = wakes.iter_mut().map(|rx| Box::pin(rx.changed())); + let (woken, _, _) = select_all(waits).await; + woken.is_ok() +} + /// The response of a live stream for any of `topics`. It sends `changed` after each wake, with no /// fingerprint: the caller bumps only after a write that changes the page. Nothing is sent on /// connect. The stream ends when a topic is gone, which cannot happen while the stream holds it. pub fn stream_wakes(cx: &Cx, hub: &LiveHub, topics: &[Topic]) -> Result { let wakes: Vec> = topics.iter().map(|t| hub.subscribe(t)).collect(); let events = stream::unfold(wakes, |mut wakes| async move { - // The futures of the topics not woken are dropped with this statement. - let (woken, _, _) = - futures_util::future::select_all(wakes.iter_mut().map(|wake| Box::pin(wake.changed()))) - .await; - woken.ok()?; + if !wait_any(&mut wakes).await { + return None; + } Some((changed_event(), wakes)) }); events_response(cx, events) } -/// The response of a live stream for `topic`. It sends `changed` after each wake whose +/// The response of a live stream for `topics`. It sends `changed` after each wake whose /// fingerprint differs from the last one. Nothing is sent on connect: the page already shows the /// state the first read saw. The stream ends if the read fails. pub async fn stream_changes( cx: &Cx, hub: &LiveHub, - topic: &Topic, + topics: &[Topic], read: F, ) -> Result where @@ -143,11 +170,13 @@ where Fut: Future> + Send, { // Subscribed before the first read, so a change in between wakes the stream. - let wake = hub.subscribe(topic); + let wakes = topics.iter().map(|topic| hub.subscribe(topic)).collect(); let last = read().await?; - let events = stream::unfold(Follow { wake, read, last }, |mut follow| async move { + let events = stream::unfold(Follow { wakes, read, last }, |mut follow| async move { loop { - follow.wake.changed().await.ok()?; + if !wait_any(&mut follow.wakes).await { + return None; + } let now = match (follow.read)().await { Ok(now) => now, Err(e) => { @@ -198,4 +227,20 @@ mod tests { hub.bump(&topic); assert!(hub.topics().is_empty()); } + + #[tokio::test] + async fn bump_repo_wakes_the_owner_the_explore_list_and_the_repo() { + let hub = LiveHub::default(); + let owner = hub.subscribe(&Topic::User("owner".to_owned())); + let explore = hub.subscribe(&Topic::Explore); + let repo = hub.subscribe(&Topic::Repo("repo".to_owned())); + let other = hub.subscribe(&Topic::User("someone".to_owned())); + + hub.bump_repo("owner", "repo"); + + assert!(owner.has_changed().expect("open")); + assert!(explore.has_changed().expect("open")); + assert!(repo.has_changed().expect("open")); + assert!(!other.has_changed().expect("open")); + } } diff --git a/crates/forge-web/src/notify_hub.rs b/crates/forge-web/src/notify_hub.rs index 029b106..e0f3911 100644 --- a/crates/forge-web/src/notify_hub.rs +++ b/crates/forge-web/src/notify_hub.rs @@ -10,6 +10,7 @@ use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use tokio::sync::watch; +use crate::live::Topic; use crate::state::AppState; /// The users with an open stream, each with the channel that carries its unread count. @@ -123,10 +124,11 @@ impl Drop for Subscription { } } -/// Publishes `user_id`'s current unread count to that user's open streams. Call it after a write -/// that changes the inbox. Skips the count query when nobody is listening. Never fails: problems -/// are logged. +/// Publishes `user_id`'s current unread count to that user's open streams, and wakes the inbox +/// page's live stream. Call it after a write that changes the inbox. Skips the count query when +/// nobody is listening. Never fails: problems are logged. pub async fn publish_unread(state: &AppState, user_id: &str) { + state.live.bump(&Topic::Inbox(user_id.to_owned())); if !state.notify_hub.is_watched(user_id) { return; } diff --git a/crates/forge-web/src/pages/blob.rs b/crates/forge-web/src/pages/blob.rs index 960d242..ff69e11 100644 --- a/crates/forge-web/src/pages/blob.rs +++ b/crates/forge-web/src/pages/blob.rs @@ -14,7 +14,7 @@ use crate::i18n::code::{self as g, K}; use crate::i18n::{self}; use crate::lfs::has_object; use crate::lfs_pointer; -use crate::pages::code_live::live_url; +use crate::pages::code_live::{follows_branch, live_url}; use crate::pages::finder::file_finder; use crate::pages::media::media_url; use crate::pages::refs::load_refs; @@ -270,12 +270,13 @@ async fn blob_page(cx: &Cx) -> Result { let download_href = lfs_href.clone().unwrap_or_else(|| raw.clone()); let refs = load_refs(ctx.path.clone()).await?; - let live = live_url(&repo.owner_name, &repo.name, &refs, &ref_name); - let header = ctx.head(state, "code").await?; + let follows = follows_branch(&refs, &ref_name); + let mut header = ctx.head(state, "code").await?; + header.live = live_url(&repo.owner_name, &repo.name, &refs, &ref_name); Ok(view! { shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), repo_head(head: header) -
+
breadcrumb(lang: lang, crumbs: crumbs) file_finder(lang: lang, owner: finder_owner, repo: finder_repo, ref_name: finder_ref)
diff --git a/crates/forge-web/src/pages/ci_job.rs b/crates/forge-web/src/pages/ci_job.rs index 26a43d4..ddcf4f9 100644 --- a/crates/forge-web/src/pages/ci_job.rs +++ b/crates/forge-web/src/pages/ci_job.rs @@ -297,7 +297,7 @@ async fn job_body( live: Option, ) -> Result { Ok(view! { - repo_head(head: head) + repo_head(head: RepoHead { live: String::new(), ..head })

(g::t(lang, K::RunNumber)) (job.run_number)

diff --git a/crates/forge-web/src/pages/ci_runs.rs b/crates/forge-web/src/pages/ci_runs.rs index 4df1243..f79d89b 100644 --- a/crates/forge-web/src/pages/ci_runs.rs +++ b/crates/forge-web/src/pages/ci_runs.rs @@ -1590,7 +1590,7 @@ async fn runs_body( } = list; let (fm, fs) = duration_templates(lang); Ok(view! { - repo_head(head: head) + repo_head(head: RepoHead { live: String::new(), ..head }) if let Some((text, is_error)) = notice { if is_error { alert(message: text) diff --git a/crates/forge-web/src/pages/code_live.rs b/crates/forge-web/src/pages/code_live.rs index a5ce0b5..496a8d7 100644 --- a/crates/forge-web/src/pages/code_live.rs +++ b/crates/forge-web/src/pages/code_live.rs @@ -1,10 +1,14 @@ -//! Live stream of the code view. A tree or blob page of a branch, and the repo home, render -//! `data-live` with the URL of this stream. It sends `changed` when the branch moves, or when a -//! branch or tag is created or deleted (the ref selector and the branch list depend on that). -//! Moves of other refs send nothing. Commits and tags are not followed: they do not move. +//! Live stream of a repo's pages, at `/{owner}/{repo}/events`. The repo header renders `data-live` +//! with this URL on every repo page (see `repo::repo_head`). A code view adds its branch to the +//! URL. The stream sends `changed` when the header changes: stars, watchers, forks, or the repo's +//! name, description or visibility. On a code view of a branch it also sends `changed` when the +//! branch moves, or when a branch or tag is created or deleted (the ref selector and the branch +//! list depend on that). Moves of other refs send nothing. Commits and tags are not followed: they +//! do not move. use std::path::PathBuf; +use forge_core::Visibility; use forge_git::browse::{RefInfo, RefKind}; use topcoat::Result; use topcoat::context::{Cx, app_context}; @@ -14,7 +18,7 @@ use topcoat::router::{path_param, query_params, route}; use crate::auth::percent_encode; use crate::live::{Topic, stream_changes}; use crate::pages::refs::load_refs; -use crate::pages::repo_ctx::load_repo; +use crate::pages::repo_ctx::{fork_count, load_repo}; use crate::state::AppState; path_param!(owner); @@ -25,17 +29,22 @@ struct LiveQuery { ref_name: Option, } -/// The stream URL of a code view of `ref_name`, or None when the ref is not a branch. -pub fn live_url(owner: &str, repo: &str, refs: &[RefInfo], ref_name: &str) -> Option { - let branch = refs - .iter() - .any(|r| r.kind == RefKind::Branch && r.name == ref_name); - branch.then(|| { +/// Whether a code view of `ref_name` follows the branch: the ref is a branch of the repo. +pub fn follows_branch(refs: &[RefInfo], ref_name: &str) -> bool { + refs.iter() + .any(|r| r.kind == RefKind::Branch && r.name == ref_name) +} + +/// The stream URL of a repo page. A code view of a branch adds the branch to it. +pub fn live_url(owner: &str, repo: &str, refs: &[RefInfo], ref_name: &str) -> String { + if follows_branch(refs, ref_name) { format!( - "/{owner}/{repo}/code/events?ref_name={}", + "/{owner}/{repo}/events?ref_name={}", percent_encode(ref_name) ) - }) + } else { + format!("/{owner}/{repo}/events") + } } /// The state the code view shows: every branch and tag name, and the commit `branch` points at. @@ -54,10 +63,26 @@ async fn refs_fingerprint(path: PathBuf, branch: String) -> Result { Ok(format!("{}\n{at}", names.join("\n"))) } -/// The code view's change stream. Auth is the repo read check of the page: a viewer who cannot -/// read the repo gets the same 404 as the page. -#[route(GET "/{owner}/{repo}/code/events")] -async fn code_events(cx: &Cx) -> Result { +/// The state the repo header shows. A repo that is gone reads as empty, which ends nothing: the +/// stream then sends `changed` once and the page's own re-read shows the 404. +async fn header_fingerprint(state: &AppState, repo_id: &str) -> Result { + let Some(repo) = state.store.repo_by_id(repo_id).await? else { + return Ok(String::new()); + }; + let stars = state.store.star_count(repo_id).await?; + let watchers = state.store.watchers(repo_id).await?.len(); + let forks = fork_count(state, repo_id).await?; + let public = repo.visibility == Visibility::Public; + Ok(format!( + "{}\n{}\n{public}\n{}\n{stars} {watchers} {forks}", + repo.owner_name, repo.name, repo.description + )) +} + +/// The repo's live stream. Auth is the repo read check of the page: a viewer who cannot read the +/// repo gets the same 404 as the page. +#[route(GET "/{owner}/{repo}/events")] +async fn repo_events(cx: &Cx) -> Result { let owner = path_param::(cx); let name = path_param::(cx); let branch = query_params::(cx)? @@ -65,11 +90,26 @@ async fn code_events(cx: &Cx) -> Result { .clone() .unwrap_or_default(); let ctx = load_repo(cx, owner, name).await?; - let state = app_context::(cx); - let topic = Topic::RepoRefs(ctx.repo.id.clone()); + let state = app_context::(cx).clone(); + let mut topics = vec![Topic::Repo(ctx.repo.id.clone())]; + if !branch.is_empty() { + topics.push(Topic::RepoRefs(ctx.repo.id.clone())); + } let path = ctx.path.clone(); - stream_changes(cx, &state.live, &topic, move || { - refs_fingerprint(path.clone(), branch.clone()) + let repo_id = ctx.repo.id.clone(); + stream_changes(cx, &state.live.clone(), &topics, move || { + let state = state.clone(); + let repo_id = repo_id.clone(); + let path = path.clone(); + let branch = branch.clone(); + async move { + let header = header_fingerprint(&state, &repo_id).await?; + if branch.is_empty() { + return Ok(header); + } + let refs = refs_fingerprint(path, branch).await?; + Ok(format!("{header}\n{refs}")) + } }) .await } diff --git a/crates/forge-web/src/pages/dashboard.rs b/crates/forge-web/src/pages/dashboard.rs index ce44db1..2061969 100644 --- a/crates/forge-web/src/pages/dashboard.rs +++ b/crates/forge-web/src/pages/dashboard.rs @@ -9,13 +9,15 @@ use forge_core::{Notification, Repo, Visibility}; use time::OffsetDateTime; use topcoat::Result; use topcoat::context::{Cx, app_context}; -use topcoat::router::page; +use topcoat::router::response::Response; +use topcoat::router::{Body, StatusCode, page, route}; use topcoat::view::{View, component, view}; use crate::auth::{current_user, percent_encode}; use crate::i18n::misc::{self as m, K as MK}; use crate::i18n::orgs::{self as g, K}; use crate::i18n::{self, Lang}; +use crate::live::{Topic, stream_changes}; use crate::pages::issue_parts::stamp_unix; use crate::pages::repo_settings::{notice_banner_for, take_notice}; use crate::state::AppState; @@ -73,6 +75,52 @@ async fn home(cx: &Cx) -> Result { }) } +/// The dashboard's change stream for the viewer. It follows the viewer's own user topic (repo +/// listing and contribution calendar, both moved by the viewer's pushes and repo changes) and +/// their inbox. The viewer comes from the session only. +#[route(GET "/dashboard/events")] +async fn dashboard_events(cx: &Cx) -> Result { + let Some((user, _)) = current_user(cx).await? else { + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(res); + }; + let state = app_context::(cx).clone(); + let topics = [Topic::User(user.id.clone()), Topic::Inbox(user.id.clone())]; + stream_changes(cx, &state.live.clone(), &topics, move || { + let state = state.clone(); + let user = user.clone(); + async move { dashboard_fingerprint(&state, &user).await } + }) + .await +} + +/// The state the dashboard shows: the repo list, the calendar counts and the attention rows. +async fn dashboard_fingerprint(state: &AppState, user: &forge_core::User) -> Result { + let mut lines = Vec::new(); + for repo in state.store.list_repos_by_owner(&user.id).await? { + lines.push(format!( + "repo {} {:?} {}", + repo.name, repo.visibility, repo.description + )); + } + let since = forge_core::time::stamp_ago(Duration::from_secs(CALENDAR_DAYS * 86_400)); + for (day, count) in state.store.contribution_counts(&user.id, &since).await? { + lines.push(format!("day {day} {count}")); + } + for note in state + .store + .list_notifications(&user.id, true, None, ATTENTION_ROWS) + .await? + { + lines.push(format!( + "note {} {} {} {}", + note.id, note.updated_at, note.title, note.issue_state + )); + } + Ok(lines.join("\n")) +} + /// Reads the dashboard data for a signed-in user. async fn load_dashboard( state: &AppState, @@ -129,6 +177,7 @@ async fn dashboard(dash: Dashboard, lang: Lang) -> Result { let greeting = m::greeting(lang, dash.hour, &dash.name); let attention_empty = dash.attention.is_empty(); Ok(view! { +

(greeting)

contribution_calendar(calendar: dash.calendar, lang: lang)
@@ -187,6 +236,7 @@ async fn dashboard(dash: Dashboard, lang: Lang) -> Result {

(m::t(lang, MK::ViewAllNotifications))

+
}) } diff --git a/crates/forge-web/src/pages/explore.rs b/crates/forge-web/src/pages/explore.rs index 587eb60..f9f7996 100644 --- a/crates/forge-web/src/pages/explore.rs +++ b/crates/forge-web/src/pages/explore.rs @@ -6,12 +6,14 @@ use forge_core::store::RepoSort; use topcoat::Result; use topcoat::context::{Cx, app_context}; -use topcoat::router::{page, query_params}; +use topcoat::router::response::Response; +use topcoat::router::{page, query_params, route}; use topcoat::view::{View, component, view}; use crate::auth::current_user; use crate::i18n::orgs::{self as g, K}; use crate::i18n::{self, Lang}; +use crate::live::{Topic, stream_changes}; use crate::state::AppState; use crate::views::repo_list::{ PageLink, RepoRow, SortLink, pager, pager_links, repo_rows, sort_chips, @@ -58,9 +60,8 @@ fn sort_key(raw: Option<&str>) -> &'static str { .unwrap_or(SORTS[0].0) } -#[page("/explore")] -async fn explore_page(cx: &Cx) -> Result { - let query = query_params::(cx)?; +/// The search text, sort key and page the query asks for, with the defaults filled in. +fn listing_args(query: &ExploreQuery) -> (String, &'static str, u64) { let q: String = query .q .as_deref() @@ -76,6 +77,14 @@ async fn explore_page(cx: &Cx) -> Result { .and_then(|p| p.parse::().ok()) .unwrap_or(1) .max(1); + (q, sort, page) +} + +#[page("/explore")] +async fn explore_page(cx: &Cx) -> Result { + let query = query_params::(cx)?; + let (q, sort, page) = listing_args(query); + let live = explore_href(&q, sort, page).replacen("/explore?", "/explore/events?", 1); let viewer = current_user(cx).await?; let lang = i18n::lang(cx, viewer.as_ref().map(|(u, _)| u)); let state = app_context::(cx); @@ -120,10 +129,56 @@ async fn explore_page(cx: &Cx) -> Result { Ok(view! { cx => shell(title: title, viewer: viewer.as_ref(), explore_body(q: q, sort: sort, sort_links: sort_links, rows: rows, - total: total, page: page, pages: pages, nav: nav, orgs: orgs, lang: lang)) + total: total, page: page, pages: pages, nav: nav, orgs: orgs, lang: lang, live: live)) }) } +/// The explore listing's change stream, for the same search, sort and page as the page. Only the +/// public listing is in it, so no viewer check is needed. A new public repo, a changed one or a +/// star moves it. +#[route(GET "/explore/events")] +async fn explore_events(cx: &Cx) -> Result { + let query = query_params::(cx)?; + let (q, sort, page) = listing_args(query); + let state = app_context::(cx).clone(); + stream_changes(cx, &state.live.clone(), &[Topic::Explore], move || { + let state = state.clone(); + let q = q.clone(); + async move { explore_fingerprint(&state, &q, sort, page).await } + }) + .await +} + +/// The state the explore listing shows: its total, each row with its stars, and the org names. +async fn explore_fingerprint( + state: &AppState, + q: &str, + sort: &'static str, + page: u64, +) -> Result { + let sort_kind = match sort { + "stars" => RepoSort::MostStars, + "name" => RepoSort::Name, + _ => RepoSort::RecentlyUpdated, + }; + let search = (!q.is_empty()).then_some(q); + let (listed, total) = state + .store + .list_public_repos(search, sort_kind, page, PER_PAGE) + .await?; + let mut lines = vec![total.to_string()]; + for (repo, stars, activity) in listed { + lines.push(format!( + "{} {} {} {:?} {} {stars} {activity}", + repo.owner_name, repo.name, repo.description, repo.visibility, repo.default_branch + )); + } + for org in state.store.list_orgs().await? { + lines.push(format!("org {}", org.username)); + } + Ok(lines.join("\n")) +} + #[component] async fn explore_body( q: String, @@ -136,12 +191,13 @@ async fn explore_body( nav: (Vec, Option, Option), orgs: Vec, lang: Lang, + live: String, ) -> Result { let empty = rows.is_empty(); let has_orgs = !orgs.is_empty(); let (links, prev, next) = nav; Ok(view! { -
+

(g::t(lang, K::Explore))

(g::t(lang, K::PublicReposIntro))

if has_orgs { diff --git a/crates/forge-web/src/pages/fork.rs b/crates/forge-web/src/pages/fork.rs index a167a18..92eb230 100644 --- a/crates/forge-web/src/pages/fork.rs +++ b/crates/forge-web/src/pages/fork.rs @@ -69,6 +69,8 @@ async fn fork_post(cx: &Cx, Form(form): Form) -> Result { let _ = state.store.delete_repo(&fork.id).await; return Err(e.into()); } + state.live.bump_repo(&fork.owner_id, &fork.id); + state.live.bump_repo(&source_repo.owner_id, &source_repo.id); // A fork gets the source's labels rather than the default set. The fork already exists, so a // label failure is logged rather than failing the request. match state.store.list_labels(&source_repo.id).await { diff --git a/crates/forge-web/src/pages/import.rs b/crates/forge-web/src/pages/import.rs index 0f86f65..59f4e09 100644 --- a/crates/forge-web/src/pages/import.rs +++ b/crates/forge-web/src/pages/import.rs @@ -512,7 +512,10 @@ async fn begin( .create_repo(&target.id, &name, description, visibility, DEFAULT_BRANCH) .await { - Ok(repo) => repo, + Ok(repo) => { + state.live.bump_repo(&repo.owner_id, &repo.id); + repo + } Err(e) => match user_facing_message(&e) { Some(message) => return Ok(Err(message)), None => return Err(e.into()), diff --git a/crates/forge-web/src/pages/new_repo.rs b/crates/forge-web/src/pages/new_repo.rs index 9c4b70d..40d25db 100644 --- a/crates/forge-web/src/pages/new_repo.rs +++ b/crates/forge-web/src/pages/new_repo.rs @@ -338,7 +338,10 @@ async fn create_repo( ) .await { - Ok(repo) => repo, + Ok(repo) => { + state.live.bump_repo(&repo.owner_id, &repo.id); + repo + } Err(e) => match user_facing_message(&e) { Some(message) => return Ok(Err(message)), None => return Err(e.into()), diff --git a/crates/forge-web/src/pages/notifications.rs b/crates/forge-web/src/pages/notifications.rs index a107851..07329db 100644 --- a/crates/forge-web/src/pages/notifications.rs +++ b/crates/forge-web/src/pages/notifications.rs @@ -28,6 +28,7 @@ use crate::auth::{current_user, percent_encode, require_csrf, require_user}; use crate::i18n::alerts as alert_text; use crate::i18n::misc::{self as g, K}; use crate::i18n::{self, Key, Lang}; +use crate::live::{Topic, stream_changes}; use crate::notify_hub::publish_unread; use crate::pages::issue_parts::{parse_number, stamp_unix}; use crate::pages::repo_ctx::{RepoCtx, load_repo}; @@ -451,13 +452,95 @@ async fn inbox(cx: &Cx) -> Result { let unread_count = state.store.unread_count(&user.id).await?; let transfers = state.store.pending_transfers_for_user(&user.id).await?; let csrf = viewer.1.csrf_token.clone(); + let live = inbox_live_url(all); Ok(view! { shell(title: i18n::t(lang, Key::Notifications), viewer: Some(&viewer), - inbox_list(lang: lang, all: all, unread_count: unread_count, groups: groups, more: more, csrf: csrf, transfers: transfers) + inbox_list(lang: lang, all: all, unread_count: unread_count, groups: groups, more: more, csrf: csrf, transfers: transfers, live: live) ) }) } +/// The URL of the inbox's live stream for the tab the viewer is on. +fn inbox_live_url(all: bool) -> String { + if all { + "/notifications/events?all=1".to_owned() + } else { + "/notifications/events".to_owned() + } +} + +/// The state the inbox list shows: the unread count, then each row of the first page with the +/// fields a change to it moves (its read flag, its time and its title). Rows of the older pages +/// are not in it. +async fn inbox_fingerprint(state: &AppState, user: &User, all: bool) -> Result { + let unread_only = !all; + let before = None; + let mut lines = vec![state.store.unread_count(&user.id).await?.to_string()]; + for note in state + .store + .list_notifications(&user.id, unread_only, before, PAGE_SIZE) + .await? + { + lines.push(format!( + "issue {} {} {} {} {}", + note.id, note.unread, note.updated_at, note.title, note.issue_state + )); + } + for note in state + .store + .list_discussion_notifications(&user.id, unread_only, before, PAGE_SIZE) + .await? + { + lines.push(format!( + "discussion {} {} {} {}", + note.discussion_id, note.unread, note.updated_at, note.title + )); + } + for note in state + .store + .list_advisory_notifications(&user.id, unread_only, before, PAGE_SIZE) + .await? + { + lines.push(format!( + "advisory {} {} {}", + note.repo_id, note.unread, note.updated_at + )); + } + if user.is_admin { + for note in state + .store + .list_admin_notices(&user.id, unread_only, before, PAGE_SIZE) + .await? + { + lines.push(format!( + "admin {} {} {}", + note.id, note.unread, note.updated_at + )); + } + } + Ok(lines.join("\n")) +} + +/// The inbox's change stream for the viewer's own inbox. The viewer comes from the session only, +/// so no URL can name another user's inbox. An anonymous viewer gets a bare 401. +#[route(GET "/notifications/events")] +async fn inbox_events(cx: &Cx) -> Result { + let Some((user, _)) = current_user(cx).await? else { + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(res); + }; + let all = query_params::(cx)?.all.as_deref() == Some("1"); + let state = app_context::(cx).clone(); + let topic = Topic::Inbox(user.id.clone()); + stream_changes(cx, &state.live.clone(), &[topic], move || { + let state = state.clone(); + let user = user.clone(); + async move { inbox_fingerprint(&state, &user, all).await } + }) + .await +} + /// Opens one inbox row: marks it read and sends the viewer to the issue or pull. Another user's /// row, or a repo the viewer can no longer read, is 404. #[route(GET "/notifications/{note}/open")] @@ -748,6 +831,7 @@ async fn set_watch(cx: &Cx, Form(form): Form) -> Result { }; let state = app_context::(cx); state.store.set_watch(&user.id, &ctx.repo.id, level).await?; + state.live.bump_repo(&ctx.repo.owner_id, &ctx.repo.id); Ok(see_other(repo_href( &ctx.repo.owner_name, &ctx.repo.name, @@ -888,13 +972,14 @@ async fn inbox_list( more: Option, csrf: String, transfers: Vec, + live: String, ) -> Result { let empty = groups.is_empty(); let unread_class = if all { "" } else { "active" }; let all_class = if all { "active" } else { "" }; let unread_text = format!("{} ({unread_count})", g::t(lang, K::Unread)); Ok(view! { -
+

(i18n::t(lang, Key::Notifications))

if !empty {
diff --git a/crates/forge-web/src/pages/profile.rs b/crates/forge-web/src/pages/profile.rs index 8597967..1bcaa36 100644 --- a/crates/forge-web/src/pages/profile.rs +++ b/crates/forge-web/src/pages/profile.rs @@ -15,13 +15,15 @@ use forge_core::{Repo, User, Visibility}; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::error::not_found; -use topcoat::router::{page, path_param, query_params}; +use topcoat::router::response::Response; +use topcoat::router::{page, path_param, query_params, route}; use topcoat::view::{Unescaped, View, component, view}; use crate::auth::current_user; use crate::i18n::misc::{self as mi, K as MK}; use crate::i18n::orgs::{self as g, K}; use crate::i18n::{self, Lang}; +use crate::live::{Topic, stream_changes}; use crate::pages::dashboard::badge_class; use crate::render::markdown::render_markdown; use crate::state::AppState; @@ -225,6 +227,72 @@ async fn profile_page(cx: &Cx) -> Result { }) } +/// The profile's change stream. It follows the user's topic: repos created, changed or starred, +/// pins, and pushes by the user. The stream is keyed by the username in the URL, but the viewer +/// comes from the session, so what it sends is what that viewer may read. An unknown name is 404. +#[route(GET "/users/{username}/events")] +async fn profile_events(cx: &Cx) -> Result { + let name = path_param::(cx); + let state = app_context::(cx).clone(); + let Some(user) = state.store.user_by_username(name).await? else { + return Err(not_found().into()); + }; + let actor = current_user(cx).await?.map(|(u, _)| u); + let topic = Topic::User(user.id.clone()); + stream_changes(cx, &state.live.clone(), &[topic], move || { + let state = state.clone(); + let user = user.clone(); + let actor = actor.clone(); + async move { profile_fingerprint(&state, &user, actor.as_ref()).await } + }) + .await +} + +/// The state the profile shows: the tab counts, the pins with their stars, and the first page of +/// the owner's repos as the default tab lists them. +async fn profile_fingerprint( + state: &AppState, + user: &User, + actor: Option<&User>, +) -> Result { + let owned = RepoScope::OwnedBy(&user.id); + let starred = RepoScope::StarredBy(&user.id); + let mut lines = vec![ + state + .store + .count_visible_repos(owned, actor) + .await? + .to_string(), + state + .store + .count_visible_repos(starred, actor) + .await? + .to_string(), + ]; + let pins = readable( + state, + actor, + state.store.profile_pins(&user.id).await?, + MAX_PROFILE_PINS, + ) + .await?; + for repo in pins { + let stars = state.store.star_count(&repo.id).await?; + lines.push(format!("pin {} {} {stars}", repo.name, repo.description)); + } + let (listed, _) = state + .store + .list_visible_repos(owned, actor, None, RepoSort::RecentlyUpdated, 1, PER_PAGE) + .await?; + for (repo, stars, activity) in listed { + lines.push(format!( + "repo {} {:?} {} {stars} {activity}", + repo.name, repo.visibility, repo.description + )); + } + Ok(lines.join("\n")) +} + /// What an organization's profile adds: its member names and its team count. struct OrgSummary { members: Vec, @@ -381,7 +449,7 @@ async fn profile_card( } = listing; let has_rows = !rows.is_empty(); Ok(view! { -
+
diff --git a/crates/forge-web/src/pages/profile_pins.rs b/crates/forge-web/src/pages/profile_pins.rs index 8c00466..873782e 100644 --- a/crates/forge-web/src/pages/profile_pins.rs +++ b/crates/forge-web/src/pages/profile_pins.rs @@ -133,10 +133,9 @@ async fn save_pins( let error = g::t(lang, K::PinsTooMany); return pins_form(cx, viewer, owner, action, chosen, Some(error)).await; } - app_context::(cx) - .store - .set_profile_pins(&owner.id, &chosen) - .await?; + let state = app_context::(cx); + state.store.set_profile_pins(&owner.id, &chosen).await?; + state.live.bump(&crate::live::Topic::User(owner.id.clone())); Err(see_other(back).into()) } diff --git a/crates/forge-web/src/pages/pull_live.rs b/crates/forge-web/src/pages/pull_live.rs index 2de68f1..c8e7921 100644 --- a/crates/forge-web/src/pages/pull_live.rs +++ b/crates/forge-web/src/pages/pull_live.rs @@ -168,7 +168,7 @@ async fn pulls_events(cx: &Cx) -> Result { let store = state.store.clone(); let repo_id = ctx.repo.id.clone(); let viewer = ctx.viewer.as_ref().map(|(user, _)| user.id.clone()); - stream_changes(cx, &state.live, &topic, move || { + stream_changes(cx, &state.live, &[topic], move || { let store = store.clone(); let repo_id = repo_id.clone(); let viewer = viewer.clone(); @@ -190,7 +190,7 @@ async fn pull_events(cx: &Cx) -> Result { let store = state.store.clone(); let repo_id = ctx.repo.id.clone(); let viewer = ctx.viewer.as_ref().map(|(user, _)| user.id.clone()); - stream_changes(cx, &state.live, &topic, move || { + stream_changes(cx, &state.live, &[topic], move || { let store = store.clone(); let repo_id = repo_id.clone(); let viewer = viewer.clone(); diff --git a/crates/forge-web/src/pages/repo.rs b/crates/forge-web/src/pages/repo.rs index 03a3bfd..02c3786 100644 --- a/crates/forge-web/src/pages/repo.rs +++ b/crates/forge-web/src/pages/repo.rs @@ -20,7 +20,7 @@ use topcoat::view::{View, component, view}; use crate::i18n::code::{self as g, K}; use crate::i18n::{self, Lang}; -use crate::pages::code_live::live_url; +use crate::pages::code_live::{follows_branch, live_url}; use crate::pages::dashboard::badge_class; use crate::pages::finder::file_finder; use crate::pages::issue_parts::stamp_unix; @@ -81,6 +81,8 @@ pub async fn repo_head(head: RepoHead) -> Result { star, watchers, watch, + forks, + live, mirror, discussions, wiki, @@ -127,6 +129,7 @@ pub async fn repo_head(head: RepoHead) -> Result { (repo_href(&owner, &name, "watch", ""), watch.csrf, level) }); let watch_count = g::watching_count(lang, watchers); + let fork_count = g::forks_count(lang, forks); let search_action = repo_href(&owner, &name, "search", ""); let mirror_line = mirror.as_ref().map(|source| source.url.clone()); let mirror_status = match mirror { @@ -137,8 +140,9 @@ pub async fn repo_head(head: RepoHead) -> Result { }, None => String::new(), }; + let live_attr = (!live.is_empty()).then(|| live.clone()); Ok(view! { -
+

user_link(shown: title_owner.as_str(), login: title_owner.as_str()) "/" (title_name.as_str())

@@ -163,6 +167,7 @@ pub async fn repo_head(head: RepoHead) -> Result { } else { (watch_count.as_str()) } + (fork_count.as_str())
if let Some((action, label, csrf)) = star_control { @@ -449,6 +454,7 @@ async fn repo_page(cx: &Cx) -> Result { ctx.viewer_tz(), )); } + let follows = follows_branch(&refs, &branch); let live = live_url(&repo.owner_name, &repo.name, &refs, &branch); let branch_names: Vec = refs .into_iter() @@ -458,7 +464,8 @@ async fn repo_page(cx: &Cx) -> Result { let owner_name = repo.owner_name.clone(); let repo_name = repo.name.clone(); - let header = ctx.head(state, "code").await?; + let mut header = ctx.head(state, "code").await?; + header.live = live; let latest = crate::pages::releases::latest_release_for_home(state, &ctx).await?; let banners = recent_push_banners(state, &ctx, header.forked_from.clone()).await?; let now = now_unix(); @@ -472,7 +479,7 @@ async fn repo_page(cx: &Cx) -> Result { recent_pushes(banners: banners, now: now, lang: lang) } if let Some(rows) = tree { -
+
(g::t(lang, K::BranchLabel)) (branch.clone()) file_finder(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), diff --git a/crates/forge-web/src/pages/repo_ctx.rs b/crates/forge-web/src/pages/repo_ctx.rs index 67b54ff..caa5d2f 100644 --- a/crates/forge-web/src/pages/repo_ctx.rs +++ b/crates/forge-web/src/pages/repo_ctx.rs @@ -78,6 +78,13 @@ pub struct RepoHead { pub watchers: u64, /// `None` for anonymous viewers, who see the count only. pub watch: Option, + /// Public forks of this repo, for the header count. Private forks are not counted, so their + /// existence is not shown to viewers who cannot read them. + pub forks: u64, + /// The URL of the live stream the header follows (see `code_live`). A code view sets it to + /// its branch's stream. Empty when the page has its own stream (a CI run or job), since the + /// client follows the first stream on a page. + pub live: String, /// The pull mirror this repo follows, shown as the "Mirror of" line. `None` for other repos. pub mirror: Option, /// Whether the repo has discussions turned on, for the Discussions tab. @@ -215,6 +222,7 @@ impl RepoCtx { }), None => None, }; + let forks = fork_count(state, &self.repo.id).await?; let discussions = state.store.discussions_enabled(&self.repo.id).await?; let wiki = state.store.wiki_enabled(&self.repo.id).await?; let security = @@ -250,6 +258,8 @@ impl RepoCtx { star, watchers, watch, + forks, + live: format!("/{}/{}/events", self.repo.owner_name, self.repo.name), mirror, discussions, wiki, @@ -266,6 +276,16 @@ impl RepoCtx { } /// Load `owner/name` for the current viewer, or 404. +/// The number of public forks of `repo_id`. Private forks are left out (see `RepoHead::forks`). +pub async fn fork_count(state: &AppState, repo_id: &str) -> Result { + let forks = state.store.list_forks(repo_id).await?; + let public = forks + .iter() + .filter(|fork| fork.visibility == Visibility::Public) + .count(); + Ok(u64::try_from(public).unwrap_or(u64::MAX)) +} + pub async fn load_repo(cx: &Cx, owner: &str, name: &str) -> Result { let state = app_context::(cx); let viewer = current_user(cx).await?; diff --git a/crates/forge-web/src/pages/repo_rename.rs b/crates/forge-web/src/pages/repo_rename.rs index 8bcc1ab..d292366 100644 --- a/crates/forge-web/src/pages/repo_rename.rs +++ b/crates/forge-web/src/pages/repo_rename.rs @@ -228,10 +228,12 @@ async fn rename_post(cx: &Cx, Form(form): Form) -> Result .chars() .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) { - app_context::(cx) + let state = app_context::(cx); + state .store .rename_repo(&ctx.repo.id, &new_name) .await + .inspect(|()| state.live.bump_repo(&ctx.repo.owner_id, &ctx.repo.id)) } else { Err(CoreError::InvalidName(g::invalid_name(lang, &new_name))) }; @@ -356,6 +358,8 @@ async fn transfer_post(cx: &Cx, Form(form): Form) -> Result { + state.live.bump_repo(&ctx.repo.owner_id, &ctx.repo.id); + state.live.bump_repo(&new_owner.id, &ctx.repo.id); tracing::info!( actor_id = %user.id, repo_id = %ctx.repo.id, diff --git a/crates/forge-web/src/pages/repo_settings.rs b/crates/forge-web/src/pages/repo_settings.rs index 143b92e..333ce08 100644 --- a/crates/forge-web/src/pages/repo_settings.rs +++ b/crates/forge-web/src/pages/repo_settings.rs @@ -802,6 +802,7 @@ async fn settings_general_save(cx: &Cx, Form(form): Form) -> Result .store .update_repo_general(&ctx.repo.id, &description, &default_branch) .await + .inspect(|()| state.live.bump_repo(&ctx.repo.owner_id, &ctx.repo.id)) { if default_branch != ctx.repo.default_branch && let Err(revert) = point_head(&state.git, &ctx.path, &ctx.repo.default_branch).await @@ -851,6 +852,7 @@ async fn settings_visibility_save(cx: &Cx, Form(form): Form) -> .store .set_repo_visibility(&ctx.repo.id, target) .await?; + state.live.bump_repo(&ctx.repo.owner_id, &ctx.repo.id); tracing::info!( actor_id = %user.id, repo_id = %ctx.repo.id, @@ -982,7 +984,9 @@ async fn settings_delete(cx: &Cx, Form(form): Form) -> Result Result { } else { state.store.unstar(&user.id, &ctx.repo.id).await?; } + state.live.bump_repo(&ctx.repo.owner_id, &ctx.repo.id); + // The starred tab of the starrer's profile counts the stars. + state.live.bump(&crate::live::Topic::User(user.id.clone())); let home = repo_href(&ctx.repo.owner_name, &ctx.repo.name, "", ""); Ok(see_other(return_path(cx).unwrap_or(home))) } diff --git a/crates/forge-web/src/pages/tree.rs b/crates/forge-web/src/pages/tree.rs index 0466250..8f532da 100644 --- a/crates/forge-web/src/pages/tree.rs +++ b/crates/forge-web/src/pages/tree.rs @@ -17,7 +17,7 @@ use topcoat::view::{Unescaped, View, component, view}; use crate::i18n::code::{self as g, K}; use crate::i18n::{self, Lang}; -use crate::pages::code_live::live_url; +use crate::pages::code_live::{follows_branch, live_url}; use crate::pages::finder::file_finder; use crate::pages::refs::{load_refs, ref_links}; use crate::pages::repo::repo_head; @@ -548,14 +548,20 @@ async fn tree_page(cx: &Cx) -> Result { ctx.viewer_tz(), ); let (branches, tags) = ref_links(&refs, &ref_name, &repo.default_branch, repo); - let live = live_url(&repo.owner_name, &repo.name, &refs, &ref_name); + let live = follows_branch(&refs, &ref_name) + .then(|| live_url(&repo.owner_name, &repo.name, &refs, &ref_name)); let title = format!("{}/{}", repo.owner_name, repo.name); let crumbs = path_crumbs(repo, &ref_name, "tree", &dir); let finder_owner = repo.owner_name.clone(); let finder_repo = repo.name.clone(); let finder_ref = ref_name.clone(); - let header = ctx.head(state, "code").await?; + let mut header = ctx.head(state, "code").await?; + // The header and the browse bar share the branch's stream: the client follows the first + // [data-live] on the page, which is the header. + if let Some(url) = &live { + header.live = url.clone(); + } Ok(view! { shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), repo_head(head: header) diff --git a/crates/forge-web/src/post_update.rs b/crates/forge-web/src/post_update.rs index 8d01d70..5c846da 100644 --- a/crates/forge-web/src/post_update.rs +++ b/crates/forge-web/src/post_update.rs @@ -45,6 +45,12 @@ pub async fn after_ref_update( state .live .bump(&crate::live::Topic::RepoRefs(repo.id.clone())); + // The pusher's contribution calendar (dashboard and profile) counts the push. + if !actor_id.is_empty() { + state + .live + .bump(&crate::live::Topic::User(actor_id.to_owned())); + } crate::ci::on_ref_update(state, repo, actor_id, refname, new).await; if (refname.starts_with("refs/heads/") || refname.starts_with("refs/tags/")) && let Err(e) = crate::mirrors::enqueue_push_mirrors(state, &repo.id).await diff --git a/crates/forge-web/tests/browse_e2e.rs b/crates/forge-web/tests/browse_e2e.rs index 2aa5b59..fe6dcb1 100644 --- a/crates/forge-web/tests/browse_e2e.rs +++ b/crates/forge-web/tests/browse_e2e.rs @@ -688,7 +688,7 @@ async fn code_view_stream_follows_pushes() { assert!( branch_page .body() - .contains(r#"data-live="/tahinli/pub/code/events?ref_name=main""#), + .contains(r#"data-live="/tahinli/pub/events?ref_name=main""#), "branch page follows main" ); let commit_page = http @@ -696,12 +696,18 @@ async fn code_view_stream_follows_pushes() { .await; assert_eq!(commit_page.status, 200); assert!( - !commit_page.body().contains("data-live="), - "a commit page does not follow" + commit_page + .body() + .contains(r#"data-live="/tahinli/pub/events""#), + "a commit page follows the repo header" + ); + assert!( + !commit_page.body().contains("events?ref_name="), + "a commit page does not follow a branch" ); // Anyone can follow a public branch. - let mut stream = open_stream(&http, "/tahinli/pub/code/events?ref_name=main", None).await; + let mut stream = open_stream(&http, "/tahinli/pub/events?ref_name=main", None).await; assert_eq!(stream.status().as_u16(), 200); assert_eq!( stream.headers().get(CONTENT_TYPE).unwrap(), @@ -752,7 +758,7 @@ async fn code_view_stream_follows_pushes() { assert!(deleted.contains("event: changed"), "{deleted}"); // A private repo streams only to a viewer who can read it. - let private = "/tahinli/priv/code/events?ref_name=main"; + let private = "/tahinli/priv/events?ref_name=main"; let anonymous = open_stream(&http, private, None).await; assert_eq!( anonymous.status().as_u16(), @@ -914,3 +920,97 @@ async fn issue_streams_follow_writes() { let member = open_stream(&http, "/tahinli/priv/issues/live", Some(tahinli.as_str())).await; assert_eq!(member.status().as_u16(), 200, "private list for its owner"); } + + +#[tokio::test] +async fn browsing_pages_stream_their_changes() { + if !tool_on_path("git") { + eprintln!("SKIP browse_e2e: `git` was not found on PATH, so the stream test is skipped"); + return; + } + + let root = tempfile::Builder::new() + .prefix("flive") + .tempdir_in("/tmp") + .expect("temp dir"); + let dir = root.path().to_path_buf(); + let ports = pick_ports(); + let config = write_config(&dir, ports); + run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW); + let (_server, ports) = launch(&dir, ports).await; + let http = Http::new(ports.http); + + let tahinli = login(&http, "tahinli", TAHINLI_PW).await; + let token = create_token(&http, &tahinli, "live-pages-token").await; + create_repo(&http, &tahinli, "pub", "public").await; + let pub_url = format!( + "http://tahinli:{token}@127.0.0.1:{}/tahinli/pub.git", + ports.http + ); + let pushed = push_fixtures(&dir, &pub_url, &dir.join("pub-pages")); + + // The inbox, the dashboard and the header need a session. Without one they refuse, and no URL + // names another user's inbox: the viewer always comes from the session. + for path in [ + "/notifications/events", + "/notifications/events?all=1&user=tahinli", + "/dashboard/events", + ] { + let anonymous = open_stream(&http, path, None).await; + assert_eq!(anonymous.status().as_u16(), 401, "anonymous {path}"); + } + let inbox = open_stream(&http, "/notifications/events", Some(tahinli.as_str())).await; + assert_eq!(inbox.status().as_u16(), 200, "inbox stream for its owner"); + + // The header of a public repo streams to anyone. A star moves its count for every viewer. + let mut header = open_stream(&http, "/tahinli/pub/events", None).await; + assert_eq!(header.status().as_u16(), 200); + let page = http.get("/tahinli/pub", Some(&tahinli)).await; + let csrf = input_value(&page.body(), "csrf"); + let star = http + .post_form("/tahinli/pub/star", &[("csrf", &csrf)], Some(&tahinli)) + .await; + assert_eq!(star.status, 303, "star: {}", star.body()); + let event = next_chunk(&mut header).await.expect("event for a star"); + assert!(event.contains("event: changed"), "{event}"); + let shown = http.get("/tahinli/pub", None).await; + assert!( + shown.body().contains("\u{2605} 1"), + "the header shows the star" + ); + + // A push moves the pusher's calendar on the dashboard. The dashboard streams to its owner only. + let mut dashboard = open_stream(&http, "/dashboard/events", Some(tahinli.as_str())).await; + assert_eq!(dashboard.status().as_u16(), 200); + let work = dir.join("pub-pages"); + // push_fixtures leaves the clone on feature/x, so the new commit must go on main. + ok(&git(&work, &["checkout", "-q", "main"]), "checkout main"); + fs::write(work.join("PUSH.txt"), "pushed again\n").expect("write PUSH.txt"); + commit_all(&work, "a second push"); + ok(&git(&work, &["push", "-q", "origin", "main"]), "push main"); + let pushed_event = next_chunk(&mut dashboard) + .await + .expect("event for the push"); + assert!(pushed_event.contains("event: changed"), "{pushed_event}"); + assert_ne!(pushed, head_sha(&work), "the second push moved main"); + + // The explore listing streams to anyone, and a new public repo changes it. + let mut explore = open_stream(&http, "/explore/events", None).await; + assert_eq!(explore.status().as_u16(), 200); + create_repo(&http, &tahinli, "lib", "public").await; + let listed = next_chunk(&mut explore) + .await + .expect("event for a new public repo"); + assert!(listed.contains("event: changed"), "{listed}"); + + // The profile streams to anyone, and an unknown name is not found. + let mut profile = open_stream(&http, "/users/tahinli/events", None).await; + assert_eq!(profile.status().as_u16(), 200); + create_repo(&http, &tahinli, "tools", "public").await; + let changed = next_chunk(&mut profile) + .await + .expect("event for a new repo of the profile"); + assert!(changed.contains("event: changed"), "{changed}"); + let missing = open_stream(&http, "/users/nobody/events", None).await; + assert_eq!(missing.status().as_u16(), 404, "profile of an unknown user"); +} diff --git a/docs/architecture.md b/docs/architecture.md index ff98d5d..3a1b65d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -246,9 +246,22 @@ Topcoat's builder-wide compression is off on the public router, so it cannot com Content types outside the list (`application/x-git-*`, `application/octet-stream`, archives, images) are never compressed. The raw user-content listener has compression off because its ETag and Content-Length must match the stored bytes. -### Live pages - -A page that shows changing state renders `data-live=""`. The browser opens one EventSource for it (`assets/nav.js`). The server bumps a topic in `LiveHub` (`crates/forge-web/src/live.rs`) after each successful write, and the stream sends one `changed` event per wake. The page then re-renders in place, with the scroll, open dropdowns and the text and caret of every edited field kept. Nothing polls. Issue pages follow two topics: the repo's issues (the list, labels, milestones and tabs) and the one issue. A stream checks the same read permission as its page, so a private repo answers 404 to a viewer who cannot read it. The code view follows its branch and the refs of its repo. Pull request pages do not follow yet. +### 5.7 Live pages + +Pages update without a reload. A write that changes what a page shows calls `LiveHub::bump` on a topic (`crates/forge-web/src/live.rs`). The page's stream sends one `changed` event, and `nav.js` re-fetches the page in place. The event carries no data and nothing polls. Each stream re-reads a short fingerprint of its page on a wake and sends only when it differs. + +| Page | Stream | Topics it follows | +| --- | --- | --- | +| Every repo page (header counts) | `/{owner}/{repo}/events`, with `?ref_name=` on a branch code view | the repo (stars, watchers, forks, name, description, visibility); on a branch, the repo's refs | +| Inbox `/notifications` | `/notifications/events`, with `?all=1` on the All tab | the viewer's inbox | +| Dashboard `/` | `/dashboard/events` | the viewer's user topic (repos, pushes, repo changes) and inbox | +| Profile `/{username}` | `/users/{username}/events` | the owner's user topic (repos, stars, pins, pushes by the owner) | +| Code view `/{owner}/{repo}/...` | `/{owner}/{repo}/events`, with `?ref_name=` on a branch code view | the repo (header counts); on a branch, the repo refs | +| Issues `/{owner}/{repo}/issues` and an issue | `/{owner}/{repo}/issues/live`, `/{owner}/{repo}/issues/{number}/live` | the repo issues (list, labels, milestones, tabs) and the one issue | +| Pull requests `/{owner}/{repo}/pulls` and a pull | `/{owner}/{repo}/pulls/events`, `/{owner}/{repo}/pulls/{number}/events` | the repo pull list, and the one pull (conversation, commits, files) | +| Explore `/explore` | `/explore/events`, with the search, sort and page | the public listing | + +The user topics are keyed by user id, and their streams take the viewer from the session, so no URL names another user's inbox. Repo streams follow the same visibility as the repo page (a private repo answers 404 to a viewer who cannot read it). Explore lists public repos only. ## 6. Authorization model