forge
Explore
Log in

Don't you dare go Hollow

The code view updates live when commits are pushed

Browse files at this commit

ac2aa27bd5364d76b1711b4c43c7e5cb6d054aa5Ahmet Kaan GümüşParent: ad88fce
  • feat
    • the code view updates live when commits are pushed
Show full message
✨ feat: the code view updates live when commits are pushed
crates/forge-web/assets/nav.jsmodified+27 -7
@@ -10,7 +10,8 @@
10 var root = document.documentElement;10 var root = document.documentElement;
11 var latest = 0; // id of the newest request; older responses are dropped11 var latest = 0; // id of the newest request; older responses are dropped
12 var userBusy = 0; // navigations and form posts on the wire (not live refreshes)12 var userBusy = 0; // navigations and form posts on the wire (not live refreshes)
13- var liveDirty = false; // a live change came while a navigation was on the wire13+ var liveDirty = false; // a live change came while a navigation or a live fetch was on the wire
14+ var liveBusy = false; // a live fetch is on the wire: later changes wait for it, then share one fetch
14 var inFlight = 0; // requests on the wire, drives aria-busy15 var inFlight = 0; // requests on the wire, drives aria-busy
15 var pending = new WeakSet(); // forms with a request on the wire: a second submit is ignored16 var pending = new WeakSet(); // forms with a request on the wire: a second submit is ignored
16 var queued = new WeakSet(); // forms that changed while pending: submitted again once it completes17 var queued = new WeakSet(); // forms that changed while pending: submitted again once it completes
@@ -323,10 +324,15 @@
323 if (final.origin !== location.origin || !html) {324 if (final.origin !== location.origin || !html) {
324 return { leave: true, url: final, redirected: r.redirected };325 return { leave: true, url: final, redirected: r.redirected };
325 }326 }
326- return r.text().then(function (text) { return { html: text, url: final }; });327+ return r.text().then(function (text) { return { html: text, url: final, status: r.status }; });
327 }).then(function (res) {328 }).then(function (res) {
328 if (mark !== latest) { return; }329 if (mark !== latest) { return; }
329 if (res.leave) { leave(res, o); return; }330 if (res.leave) { leave(res, o); return; }
331+ // A code view keeps its page when a live refresh fails. A 404 means its path is gone at the new ref.
332+ if (o.how === 'live' && res.status >= 400 && document.querySelector('[data-live-code]')) {
333+ if (res.status === 404) { showGone(); }
334+ return;
335+ }
330 var dest = new URL(res.url.href);336 var dest = new URL(res.url.href);
331 dest.hash = o.dest.hash;337 dest.hash = o.dest.hash;
332 swap(res.html, dest, o.how, !!o.keep && res.url.pathname === o.target.pathname);338 swap(res.html, dest, o.how, !!o.keep && res.url.pathname === o.target.pathname);
@@ -336,10 +342,9 @@
336 }).then(function () {342 }).then(function () {
337 busyEnd();343 busyEnd();
338 if (o.form) { pending.delete(o.form); }344 if (o.form) { pending.delete(o.form); }
339- if (user) {345+ if (o.how === 'live') { liveBusy = false; }
340- userBusy -= 1;346+ if (user) { userBusy -= 1; }
341- if (liveDirty) { refreshLive(); }347+ if (liveDirty) { refreshLive(); }
342- }
343 if (o.form && queued.has(o.form)) { queued.delete(o.form); resend(o.form); }348 if (o.form && queued.has(o.form)) { queued.delete(o.form); resend(o.form); }
344 });349 });
345 }350 }
@@ -985,6 +990,8 @@
985 // A job page's stream opens with the status the page already shows: nothing to re-render then.990 // A job page's stream opens with the status the page already shows: nothing to re-render then.
986 var wrap = document.querySelector('[data-live]');991 var wrap = document.querySelector('[data-live]');
987 if (document.querySelector('[data-live-log]') && wrap && wrap.getAttribute('data-live-state') === e.data) { return; }992 if (document.querySelector('[data-live-log]') && wrap && wrap.getAttribute('data-live-state') === e.data) { return; }
993+ // A code view re-renders at once. Events that come while a fetch is on the wire share the next one.
994+ if (document.querySelector('[data-live-code]')) { refreshLive(); return; }
988 // The run list changes on every log chunk of every job: refresh at most once a second.995 // The run list changes on every log chunk of every job: refresh at most once a second.
989 if (document.querySelector('[data-live-log]')) { refreshLive(); return; }996 if (document.querySelector('[data-live-log]')) { refreshLive(); return; }
990 if (liveTimer) { return; }997 if (liveTimer) { return; }
@@ -1008,12 +1015,25 @@
1008 // response could be superseded: the change is kept and sent after that request completes.1015 // response could be superseded: the change is kept and sent after that request completes.
1009 function refreshLive() {1016 function refreshLive() {
1010 if (!liveStream) { return; }1017 if (!liveStream) { return; }
1011- if (userBusy > 0) { liveDirty = true; return; }1018+ if (userBusy > 0 || liveBusy) { liveDirty = true; return; }
1012 liveDirty = false;1019 liveDirty = false;
1020+ liveBusy = true;
1013 var here = new URL(location.href);1021 var here = new URL(location.href);
1014 load({ target: withoutHash(here), dest: here, init: GET_INIT, how: 'live', keep: true, post: false, form: null });1022 load({ target: withoutHash(here), dest: here, init: GET_INIT, how: 'live', keep: true, post: false, form: null });
1015 }1023 }
1016 1024
1025+ // A code view whose path is gone at the new ref keeps its page and shows one inline notice.
1026+ function showGone() {
1027+ var bar = document.querySelector('[data-live-code]');
1028+ if (!bar || document.querySelector('[data-live-notice]')) { return; }
1029+ var note = document.createElement('p');
1030+ note.className = 'notice';
1031+ note.setAttribute('role', 'status');
1032+ note.setAttribute('data-live-notice', '');
1033+ note.textContent = bar.getAttribute('data-live-gone') || '';
1034+ bar.insertAdjacentElement('afterend', note);
1035+ }
1036+
1017 // Local clock for what runs. Server-rendered [data-since] (unix seconds) is the start of a duration1037 // Local clock for what runs. Server-rendered [data-since] (unix seconds) is the start of a duration
1018 // still counting: its text is rewritten each second. [data-tick] boxes of the run list's bars and1038 // still counting: its text is rewritten each second. [data-tick] boxes of the run list's bars and
1019 // the run timeline grow with the clock. This is a display clock only: no request is made. The1039 // the run timeline grow with the clock. This is a display clock only: no request is made. The
crates/forge-web/src/boot.rsmodified+1 -0
@@ -134,6 +134,7 @@ pub async fn serve(
134 mail_waker: Arc::new(Notify::new()),134 mail_waker: Arc::new(Notify::new()),
135 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),135 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),
136 ci_live: Arc::new(crate::ci::CiLive::default()),136 ci_live: Arc::new(crate::ci::CiLive::default()),
137+ live: Arc::new(crate::live::LiveHub::default()),
137 };138 };
138 if let Err(e) = crate::signatures::rebuild_allowed_signers(&state).await {139 if let Err(e) = crate::signatures::rebuild_allowed_signers(&state).await {
139 tracing::error!(error = %e, "building the SSH allowed-signers file failed");140 tracing::error!(error = %e, "building the SSH allowed-signers file failed");
crates/forge-web/src/i18n/code.rsmodified+4 -0
@@ -53,6 +53,7 @@ pub enum K {
53 SubmoduleSuffix,53 SubmoduleSuffix,
54 TruncatedPrefix,54 TruncatedPrefix,
55 ViewFullRaw,55 ViewFullRaw,
56+ LivePathGone,
56 StatusAdded,57 StatusAdded,
57 StatusDeleted,58 StatusDeleted,
58 StatusModified,59 StatusModified,
@@ -216,6 +217,8 @@ pub fn t(lang: Lang, key: K) -> &'static str {
216 (TruncatedPrefix, Tr) => "Bu dosyanın ilk 1 MiB'ı gösteriliyor. ",217 (TruncatedPrefix, Tr) => "Bu dosyanın ilk 1 MiB'ı gösteriliyor. ",
217 (ViewFullRaw, En) => "View the full file raw",218 (ViewFullRaw, En) => "View the full file raw",
218 (ViewFullRaw, Tr) => "Dosyanın tamamını ham olarak görüntüle",219 (ViewFullRaw, Tr) => "Dosyanın tamamını ham olarak görüntüle",
220+ (LivePathGone, En) => "This path no longer exists in this ref.",
221+ (LivePathGone, Tr) => "Bu yol bu referansta artık yok.",
219 (StatusAdded, En) => "added",222 (StatusAdded, En) => "added",
220 (StatusAdded, Tr) => "eklendi",223 (StatusAdded, Tr) => "eklendi",
221 (StatusDeleted, En) => "deleted",224 (StatusDeleted, En) => "deleted",
@@ -549,6 +552,7 @@ mod tests {
549 K::SubmoduleSuffix,552 K::SubmoduleSuffix,
550 K::TruncatedPrefix,553 K::TruncatedPrefix,
551 K::ViewFullRaw,554 K::ViewFullRaw,
555+ K::LivePathGone,
552 K::StatusAdded,556 K::StatusAdded,
553 K::StatusDeleted,557 K::StatusDeleted,
554 K::StatusModified,558 K::StatusModified,
crates/forge-web/src/live.rsadded+157 -0
@@ -0,0 +1,157 @@
1+//! Live pages: change signals keyed by [`Topic`], and the event stream that carries them.
2+//!
3+//! A write that changes what a topic shows calls [`LiveHub::bump`]. Every open stream subscribed
4+//! to that topic wakes and sends one `changed` event. The signal carries no data: the page reads
5+//! its state again on the client (a soft re-fetch of the URL, see `nav.js`), so a bump that
6+//! lands during another one is never lost. Nothing polls. A topic with no subscriber is not kept.
7+//!
8+//! # Adding a topic
9+//! 1. Add a variant to [`Topic`], keyed by what the page is about (a repo id, a user id, ...).
10+//! 2. Call `state.live.bump(&Topic::Variant(..))` after the write that changes the page.
11+//! 3. In the page's own route (its auth check first), return
12+//! `live::stream_changes(cx, &state.live, &topic, read)`. `read` returns a short fingerprint
13+//! of the state the page shows; a `changed` event is sent only when it differs from the last
14+//! one, so a bump that changes nothing visible sends nothing.
15+//! 4. Render `data-live="<the route URL>"` on the page's element that the client follows.
16+//!
17+//! The hub is in-process only, like [`crate::notify_hub::NotifyHub`]. [`crate::ci::CiLive`] keeps
18+//! its own counters for CI and is not on this hub.
19+
20+use std::collections::HashMap;
21+use std::future::Future;
22+use std::sync::{Mutex, MutexGuard, PoisonError};
23+
24+use futures_util::stream;
25+use tokio::sync::watch;
26+use topcoat::Result;
27+use topcoat::context::Cx;
28+use topcoat::router::content::sse::Event;
29+use topcoat::router::response::Response;
30+
31+use crate::pages::ci_runs::events_response;
32+
33+/// What a live page follows. Add a variant when a page needs a new signal.
34+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
35+pub enum Topic {
36+ /// The refs of a repo: a branch or tag was created, deleted or moved. Keyed by repo id.
37+ RepoRefs(String),
38+}
39+
40+/// The open topics, each with the counter its subscribers wait on.
41+#[derive(Default)]
42+pub struct LiveHub {
43+ topics: Mutex<HashMap<Topic, watch::Sender<u64>>>,
44+}
45+
46+impl LiveHub {
47+ fn topics(&self) -> MutexGuard<'_, HashMap<Topic, watch::Sender<u64>>> {
48+ self.topics.lock().unwrap_or_else(PoisonError::into_inner)
49+ }
50+
51+ /// Subscribes to `topic`. The receiver starts as seen, so a bump after this call wakes it.
52+ /// Subscribe before reading the state, so a change in between is not lost. Topics nobody
53+ /// holds any more are dropped here, so the map stays small.
54+ pub fn subscribe(&self, topic: &Topic) -> watch::Receiver<u64> {
55+ let mut topics = self.topics();
56+ topics.retain(|_, tx| tx.receiver_count() > 0);
57+ topics
58+ .entry(topic.clone())
59+ .or_insert_with(|| watch::channel(0).0)
60+ .subscribe()
61+ }
62+
63+ /// Wakes the subscribers of `topic`. Does nothing when nobody is subscribed.
64+ pub fn bump(&self, topic: &Topic) {
65+ let mut topics = self.topics();
66+ let Some(tx) = topics.get(topic) else {
67+ return;
68+ };
69+ tx.send_modify(|generation| *generation = generation.wrapping_add(1));
70+ if tx.receiver_count() == 0 {
71+ topics.remove(topic);
72+ }
73+ }
74+}
75+
76+/// The state a stream follows between wakes: the fingerprint last sent or seen.
77+struct Follow<F> {
78+ wake: watch::Receiver<u64>,
79+ read: F,
80+ last: String,
81+}
82+
83+/// The `changed` event of a live page. The data is not read by the client.
84+fn changed_event() -> Result<Event> {
85+ Ok(Event::new().event("changed").data("1"))
86+}
87+
88+/// The response of a live stream for `topic`. It sends `changed` after each wake whose
89+/// fingerprint differs from the last one. Nothing is sent on connect: the page already shows the
90+/// state the first read saw. The stream ends if the read fails.
91+pub async fn stream_changes<F, Fut>(
92+ cx: &Cx,
93+ hub: &LiveHub,
94+ topic: &Topic,
95+ read: F,
96+) -> Result<Response>
97+where
98+ F: Fn() -> Fut + Send + 'static,
99+ Fut: Future<Output = Result<String>> + Send,
100+{
101+ // Subscribed before the first read, so a change in between wakes the stream.
102+ let wake = hub.subscribe(topic);
103+ let last = read().await?;
104+ let events = stream::unfold(Follow { wake, read, last }, |mut follow| async move {
105+ loop {
106+ follow.wake.changed().await.ok()?;
107+ let now = match (follow.read)().await {
108+ Ok(now) => now,
109+ Err(e) => {
110+ tracing::error!(error = %e, "live: could not read the page state");
111+ return None;
112+ }
113+ };
114+ if now == follow.last {
115+ continue;
116+ }
117+ follow.last = now;
118+ return Some((changed_event(), follow));
119+ }
120+ });
121+ events_response(cx, events)
122+}
123+
124+#[cfg(test)]
125+mod tests {
126+ use std::time::Duration;
127+
128+ use super::*;
129+
130+ #[tokio::test]
131+ async fn a_bump_wakes_only_the_subscribers_of_that_topic() {
132+ let hub = LiveHub::default();
133+ let a = Topic::RepoRefs("repo-a".to_owned());
134+ let b = Topic::RepoRefs("repo-b".to_owned());
135+ let mut wake_a = hub.subscribe(&a);
136+ let wake_b = hub.subscribe(&b);
137+
138+ hub.bump(&a);
139+
140+ tokio::time::timeout(Duration::from_secs(1), wake_a.changed())
141+ .await
142+ .expect("woken")
143+ .expect("open");
144+ assert!(!wake_b.has_changed().expect("open"));
145+ }
146+
147+ #[tokio::test]
148+ async fn a_topic_nobody_holds_is_dropped_on_the_next_change() {
149+ let hub = LiveHub::default();
150+ let topic = Topic::RepoRefs("repo-a".to_owned());
151+ let wake = hub.subscribe(&topic);
152+ drop(wake);
153+
154+ hub.bump(&topic);
155+ assert!(hub.topics().is_empty());
156+ }
157+}
crates/forge-web/src/main.rsmodified+1 -0
@@ -33,6 +33,7 @@ mod importer;
33 mod internal;33 mod internal;
34 mod lfs;34 mod lfs;
35 mod lfs_pointer;35 mod lfs_pointer;
36+mod live;
36 mod mail;37 mod mail;
37 mod mirrors;38 mod mirrors;
38 mod notify;39 mod notify;
crates/forge-web/src/pages/blob.rsmodified+5 -1
@@ -14,8 +14,10 @@ use crate::i18n::code::{self as g, K};
14 use crate::i18n::{self};14 use crate::i18n::{self};
15 use crate::lfs::has_object;15 use crate::lfs::has_object;
16 use crate::lfs_pointer;16 use crate::lfs_pointer;
17+use crate::pages::code_live::live_url;
17 use crate::pages::finder::file_finder;18 use crate::pages::finder::file_finder;
18 use crate::pages::media::media_url;19 use crate::pages::media::media_url;
20+use crate::pages::refs::load_refs;
19 use crate::pages::repo::repo_head;21 use crate::pages::repo::repo_head;
20 use crate::pages::repo_ctx::load_repo;22 use crate::pages::repo_ctx::load_repo;
21 use crate::pages::tree::{link_context, path_crumbs, read_file, resolve};23 use crate::pages::tree::{link_context, path_crumbs, read_file, resolve};
@@ -267,11 +269,13 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
267 let download_name = file_name.clone();269 let download_name = file_name.clone();
268 let download_href = lfs_href.clone().unwrap_or_else(|| raw.clone());270 let download_href = lfs_href.clone().unwrap_or_else(|| raw.clone());
269 271
272+ let refs = load_refs(ctx.path.clone()).await?;
273+ let live = live_url(&repo.owner_name, &repo.name, &refs, &ref_name);
270 let header = ctx.head(state, "code").await?;274 let header = ctx.head(state, "code").await?;
271 Ok(view! {275 Ok(view! {
272 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),276 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
273 repo_head(head: header)277 repo_head(head: header)
274- <div class="browse-bar">278+ <div class="browse-bar" data-live=(live.as_deref()) data-live-code=(live.is_some().then_some("true")) data-live-gone=(g::t(lang, K::LivePathGone))>
275 breadcrumb(lang: lang, crumbs: crumbs)279 breadcrumb(lang: lang, crumbs: crumbs)
276 file_finder(lang: lang, owner: finder_owner, repo: finder_repo, ref_name: finder_ref)280 file_finder(lang: lang, owner: finder_owner, repo: finder_repo, ref_name: finder_ref)
277 </div>281 </div>
crates/forge-web/src/pages/code_live.rsadded+75 -0
@@ -0,0 +1,75 @@
1+//! Live stream of the code view. A tree or blob page of a branch, and the repo home, render
2+//! `data-live` with the URL of this stream. It sends `changed` when the branch moves, or when a
3+//! branch or tag is created or deleted (the ref selector and the branch list depend on that).
4+//! Moves of other refs send nothing. Commits and tags are not followed: they do not move.
5+
6+use std::path::PathBuf;
7+
8+use forge_git::browse::{RefInfo, RefKind};
9+use topcoat::Result;
10+use topcoat::context::{Cx, app_context};
11+use topcoat::router::response::Response;
12+use topcoat::router::{path_param, query_params, route};
13+
14+use crate::auth::percent_encode;
15+use crate::live::{Topic, stream_changes};
16+use crate::pages::refs::load_refs;
17+use crate::pages::repo_ctx::load_repo;
18+use crate::state::AppState;
19+
20+path_param!(owner);
21+path_param!(repo);
22+
23+#[query_params(error = bad_request)]
24+struct LiveQuery {
25+ ref_name: Option<String>,
26+}
27+
28+/// The stream URL of a code view of `ref_name`, or None when the ref is not a branch.
29+pub fn live_url(owner: &str, repo: &str, refs: &[RefInfo], ref_name: &str) -> Option<String> {
30+ let branch = refs
31+ .iter()
32+ .any(|r| r.kind == RefKind::Branch && r.name == ref_name);
33+ branch.then(|| {
34+ format!(
35+ "/{owner}/{repo}/code/events?ref_name={}",
36+ percent_encode(ref_name)
37+ )
38+ })
39+}
40+
41+/// The state the code view shows: every branch and tag name, and the commit `branch` points at.
42+/// A move of another branch leaves it unchanged.
43+async fn refs_fingerprint(path: PathBuf, branch: String) -> Result<String> {
44+ let refs = load_refs(path).await?;
45+ let mut names: Vec<String> = refs
46+ .iter()
47+ .map(|r| format!("{} {}", r.kind == RefKind::Branch, r.name))
48+ .collect();
49+ names.sort();
50+ let at = refs
51+ .iter()
52+ .find(|r| r.kind == RefKind::Branch && r.name == branch)
53+ .map_or("", |r| r.target.as_str());
54+ Ok(format!("{}\n{at}", names.join("\n")))
55+}
56+
57+/// The code view's change stream. Auth is the repo read check of the page: a viewer who cannot
58+/// read the repo gets the same 404 as the page.
59+#[route(GET "/{owner}/{repo}/code/events")]
60+async fn code_events(cx: &Cx) -> Result<Response> {
61+ let owner = path_param::<Owner>(cx);
62+ let name = path_param::<Repo>(cx);
63+ let branch = query_params::<LiveQuery>(cx)?
64+ .ref_name
65+ .clone()
66+ .unwrap_or_default();
67+ let ctx = load_repo(cx, owner, name).await?;
68+ let state = app_context::<AppState>(cx);
69+ let topic = Topic::RepoRefs(ctx.repo.id.clone());
70+ let path = ctx.path.clone();
71+ stream_changes(cx, &state.live, &topic, move || {
72+ refs_fingerprint(path.clone(), branch.clone())
73+ })
74+ .await
75+}
crates/forge-web/src/pages/mod.rsmodified+1 -0
@@ -28,6 +28,7 @@ pub mod ci_job;
28 pub mod ci_runs;28 pub mod ci_runs;
29 #[cfg(test)]29 #[cfg(test)]
30 mod ci_tests;30 mod ci_tests;
31+pub mod code_live;
31 pub mod code_search;32 pub mod code_search;
32 pub mod commit;33 pub mod commit;
33 pub mod commits;34 pub mod commits;
crates/forge-web/src/pages/repo.rsmodified+3 -1
@@ -20,6 +20,7 @@ use topcoat::view::{View, component, view};
20 20
21 use crate::i18n::code::{self as g, K};21 use crate::i18n::code::{self as g, K};
22 use crate::i18n::{self, Lang};22 use crate::i18n::{self, Lang};
23+use crate::pages::code_live::live_url;
23 use crate::pages::dashboard::badge_class;24 use crate::pages::dashboard::badge_class;
24 use crate::pages::finder::file_finder;25 use crate::pages::finder::file_finder;
25 use crate::pages::issue_parts::stamp_unix;26 use crate::pages::issue_parts::stamp_unix;
@@ -448,6 +449,7 @@ async fn repo_page(cx: &Cx) -> Result<impl View> {
448 ctx.viewer_tz(),449 ctx.viewer_tz(),
449 ));450 ));
450 }451 }
452+ let live = live_url(&repo.owner_name, &repo.name, &refs, &branch);
451 let branch_names: Vec<String> = refs453 let branch_names: Vec<String> = refs
452 .into_iter()454 .into_iter()
453 .filter(|r| r.kind == browse::RefKind::Branch)455 .filter(|r| r.kind == browse::RefKind::Branch)
@@ -470,7 +472,7 @@ async fn repo_page(cx: &Cx) -> Result<impl View> {
470 recent_pushes(banners: banners, now: now, lang: lang)472 recent_pushes(banners: banners, now: now, lang: lang)
471 }473 }
472 if let Some(rows) = tree {474 if let Some(rows) = tree {
473- <div class="browse-bar">475+ <div class="browse-bar" data-live=(live.as_deref()) data-live-code=(live.is_some().then_some("true")) data-live-gone=(g::t(lang, K::LivePathGone))>
474 <span class="muted small">(g::t(lang, K::BranchLabel))</span>476 <span class="muted small">(g::t(lang, K::BranchLabel))</span>
475 <code>(branch.clone())</code>477 <code>(branch.clone())</code>
476 file_finder(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(),478 file_finder(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(),
crates/forge-web/src/pages/settings_security.rsmodified+1 -0
@@ -1100,6 +1100,7 @@ mod tests {
1100 mail_waker: Arc::new(tokio::sync::Notify::new()),1100 mail_waker: Arc::new(tokio::sync::Notify::new()),
1101 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),1101 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),
1102 ci_live: Arc::new(crate::ci::CiLive::default()),1102 ci_live: Arc::new(crate::ci::CiLive::default()),
1103+ live: Arc::new(crate::live::LiveHub::default()),
1103 };1104 };
1104 let hash = hash_password_async(PASSWORD.into()).await.unwrap();1105 let hash = hash_password_async(PASSWORD.into()).await.unwrap();
1105 let user = store1106 let user = store
crates/forge-web/src/pages/tree.rsmodified+3 -1
@@ -17,6 +17,7 @@ use topcoat::view::{Unescaped, View, component, view};
17 17
18 use crate::i18n::code::{self as g, K};18 use crate::i18n::code::{self as g, K};
19 use crate::i18n::{self, Lang};19 use crate::i18n::{self, Lang};
20+use crate::pages::code_live::live_url;
20 use crate::pages::finder::file_finder;21 use crate::pages::finder::file_finder;
21 use crate::pages::refs::{load_refs, ref_links};22 use crate::pages::refs::{load_refs, ref_links};
22 use crate::pages::repo::repo_head;23 use crate::pages::repo::repo_head;
@@ -547,6 +548,7 @@ async fn tree_page(cx: &Cx) -> Result<impl View> {
547 ctx.viewer_tz(),548 ctx.viewer_tz(),
548 );549 );
549 let (branches, tags) = ref_links(&refs, &ref_name, &repo.default_branch, repo);550 let (branches, tags) = ref_links(&refs, &ref_name, &repo.default_branch, repo);
551+ let live = live_url(&repo.owner_name, &repo.name, &refs, &ref_name);
550 552
551 let title = format!("{}/{}", repo.owner_name, repo.name);553 let title = format!("{}/{}", repo.owner_name, repo.name);
552 let crumbs = path_crumbs(repo, &ref_name, "tree", &dir);554 let crumbs = path_crumbs(repo, &ref_name, "tree", &dir);
@@ -557,7 +559,7 @@ async fn tree_page(cx: &Cx) -> Result<impl View> {
557 Ok(view! {559 Ok(view! {
558 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),560 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
559 repo_head(head: header)561 repo_head(head: header)
560- <div class="browse-bar">562+ <div class="browse-bar" data-live=(live.as_deref()) data-live-code=(live.is_some().then_some("true")) data-live-gone=(g::t(lang, K::LivePathGone))>
561 ref_selector(lang: lang, current: ref_name.clone(), branches: branches, tags: tags)563 ref_selector(lang: lang, current: ref_name.clone(), branches: branches, tags: tags)
562 breadcrumb(lang: lang, crumbs: crumbs)564 breadcrumb(lang: lang, crumbs: crumbs)
563 file_finder(lang: lang, owner: finder_owner, repo: finder_repo, ref_name: finder_ref)565 file_finder(lang: lang, owner: finder_owner, repo: finder_repo, ref_name: finder_ref)
crates/forge-web/src/post_update.rsmodified+4 -0
@@ -41,6 +41,10 @@ pub async fn after_ref_update(
41 ) -> forge_core::Result<()> {41 ) -> forge_core::Result<()> {
42 let sender = lookup_sender(state, actor_id).await;42 let sender = lookup_sender(state, actor_id).await;
43 emit_ref_update(state, repo, &sender, refname, old, new).await;43 emit_ref_update(state, repo, &sender, refname, old, new).await;
44+ // Code views that follow a branch or the ref list re-read it.
45+ state
46+ .live
47+ .bump(&crate::live::Topic::RepoRefs(repo.id.clone()));
44 crate::ci::on_ref_update(state, repo, actor_id, refname, new).await;48 crate::ci::on_ref_update(state, repo, actor_id, refname, new).await;
45 if (refname.starts_with("refs/heads/") || refname.starts_with("refs/tags/"))49 if (refname.starts_with("refs/heads/") || refname.starts_with("refs/tags/"))
46 && let Err(e) = crate::mirrors::enqueue_push_mirrors(state, &repo.id).await50 && let Err(e) = crate::mirrors::enqueue_push_mirrors(state, &repo.id).await
crates/forge-web/src/state.rsmodified+2 -0
@@ -49,6 +49,8 @@ pub struct AppState {
49 pub notify_hub: Arc<crate::notify_hub::NotifyHub>,49 pub notify_hub: Arc<crate::notify_hub::NotifyHub>,
50 /// Change counters of CI jobs and runs. Log followers and run pages wait on them.50 /// Change counters of CI jobs and runs. Log followers and run pages wait on them.
51 pub ci_live: Arc<crate::ci::CiLive>,51 pub ci_live: Arc<crate::ci::CiLive>,
52+ /// Change signals of live pages, keyed by topic. See `live`.
53+ pub live: Arc<crate::live::LiveHub>,
52 }54 }
53 55
54 /// A settings handle over `config` with no stored overrides and no file keys. For tests.56 /// A settings handle over `config` with no stored overrides and no file keys. For tests.
crates/forge-web/src/test_support.rsmodified+1 -0
@@ -86,6 +86,7 @@ pub async fn test_state(dir: &Path) -> AppState {
86 mail_waker: Arc::new(Notify::new()),86 mail_waker: Arc::new(Notify::new()),
87 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),87 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),
88 ci_live: Arc::new(crate::ci::CiLive::default()),88 ci_live: Arc::new(crate::ci::CiLive::default()),
89+ live: Arc::new(crate::live::LiveHub::default()),
89 }90 }
90 }91 }
91 92
crates/forge-web/tests/browse_e2e.rsmodified+137 -0
@@ -629,3 +629,140 @@ async fn browse_end_to_end() {
629 );629 );
630 assert_no_cookie(&login_page, "raw /login");630 assert_no_cookie(&login_page, "raw /login");
631 }631 }
632+
633+/// Opens a code view stream and returns the response with its body still unread.
634+async fn open_stream(http: &Http, path: &str, cookie: Option<&str>) -> reqwest::Response {
635+ let mut req = http.client.get(format!("{}{path}", http.base));
636+ if let Some(cookie) = cookie {
637+ req = req.header(COOKIE, cookie);
638+ }
639+ req.send().await.expect("stream request")
640+}
641+
642+/// The next chunk of a stream. None when nothing arrives within two seconds.
643+async fn next_chunk(res: &mut reqwest::Response) -> Option<String> {
644+ let chunk = tokio::time::timeout(Duration::from_secs(2), res.chunk())
645+ .await
646+ .ok()?
647+ .expect("stream chunk")?;
648+ Some(String::from_utf8_lossy(&chunk).into_owned())
649+}
650+
651+#[tokio::test]
652+async fn code_view_stream_follows_pushes() {
653+ if !tool_on_path("git") {
654+ eprintln!("SKIP browse_e2e: `git` was not found on PATH, so the stream test is skipped");
655+ return;
656+ }
657+
658+ let root = tempfile::Builder::new()
659+ .prefix("fliv")
660+ .tempdir_in("/tmp")
661+ .expect("temp dir");
662+ let dir = root.path().to_path_buf();
663+ let ports = pick_ports();
664+ let config = write_config(&dir, ports);
665+ run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW);
666+ let (_server, ports) = launch(&dir, ports).await;
667+ let http = Http::new(ports.http);
668+
669+ let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
670+ let token = create_token(&http, &tahinli, "live-token").await;
671+ create_repo(&http, &tahinli, "pub", "public").await;
672+ create_repo(&http, &tahinli, "priv", "private").await;
673+ let pub_url = format!(
674+ "http://tahinli:{token}@127.0.0.1:{}/tahinli/pub.git",
675+ ports.http
676+ );
677+ let priv_url = format!(
678+ "http://tahinli:{token}@127.0.0.1:{}/tahinli/priv.git",
679+ ports.http
680+ );
681+ let pub_main = push_fixtures(&dir, &pub_url, &dir.join("pub-live"));
682+ push_fixtures(&dir, &priv_url, &dir.join("priv-live"));
683+ let work = dir.join("pub-live");
684+
685+ // The branch page follows its branch. A commit page does not, since a commit never moves.
686+ let branch_page = http.get("/tahinli/pub/tree/main/", None).await;
687+ assert_eq!(branch_page.status, 200);
688+ assert!(
689+ branch_page
690+ .body()
691+ .contains(r#"data-live="/tahinli/pub/code/events?ref_name=main""#),
692+ "branch page follows main"
693+ );
694+ let commit_page = http
695+ .get(&format!("/tahinli/pub/tree/{pub_main}/"), None)
696+ .await;
697+ assert_eq!(commit_page.status, 200);
698+ assert!(
699+ !commit_page.body().contains("data-live="),
700+ "a commit page does not follow"
701+ );
702+
703+ // Anyone can follow a public branch.
704+ let mut stream = open_stream(&http, "/tahinli/pub/code/events?ref_name=main", None).await;
705+ assert_eq!(stream.status().as_u16(), 200);
706+ assert_eq!(
707+ stream.headers().get(CONTENT_TYPE).unwrap(),
708+ "text/event-stream"
709+ );
710+
711+ // A push to another branch sends nothing: main did not move and no ref was created.
712+ ok(
713+ &git(&work, &["checkout", "-q", "feature/x"]),
714+ "checkout feature/x",
715+ );
716+ fs::write(work.join("other.txt"), "other\n").expect("write other.txt");
717+ commit_all(&work, "other branch commit");
718+ ok(
719+ &git(&work, &["push", "-q", "origin", "feature/x"]),
720+ "push feature/x",
721+ );
722+ assert!(next_chunk(&mut stream).await.is_none(), "other branch sent");
723+
724+ // A push to main sends one `changed` event.
725+ ok(&git(&work, &["checkout", "-q", "main"]), "checkout main");
726+ fs::write(work.join("README.md"), "# Live\n\nChanged by a push.\n").expect("write README");
727+ commit_all(&work, "change the README");
728+ ok(&git(&work, &["push", "-q", "origin", "main"]), "push main");
729+ let event = next_chunk(&mut stream).await.expect("event for main");
730+ assert!(event.contains("event: changed"), "{event}");
731+
732+ // Creating and deleting a branch changes the branch list, so the page follows it too.
733+ ok(
734+ &git(&work, &["checkout", "-q", "-b", "topic"]),
735+ "create topic",
736+ );
737+ ok(
738+ &git(&work, &["push", "-q", "origin", "topic"]),
739+ "push topic",
740+ );
741+ let created = next_chunk(&mut stream)
742+ .await
743+ .expect("event for a new branch");
744+ assert!(created.contains("event: changed"), "{created}");
745+ ok(
746+ &git(&work, &["push", "-q", "origin", "--delete", "topic"]),
747+ "delete topic",
748+ );
749+ let deleted = next_chunk(&mut stream)
750+ .await
751+ .expect("event for a deleted branch");
752+ assert!(deleted.contains("event: changed"), "{deleted}");
753+
754+ // A private repo streams only to a viewer who can read it.
755+ let private = "/tahinli/priv/code/events?ref_name=main";
756+ let anonymous = open_stream(&http, private, None).await;
757+ assert_eq!(
758+ anonymous.status().as_u16(),
759+ 404,
760+ "private stream without a session"
761+ );
762+ let member = open_stream(&http, private, Some(tahinli.as_str())).await;
763+ assert_eq!(
764+ member.status().as_u16(),
765+ 200,
766+ "private stream for its owner"
767+ );
768+}