diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 12af517..e65035b 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -10,7 +10,8 @@ var root = document.documentElement; var latest = 0; // id of the newest request; older responses are dropped var userBusy = 0; // navigations and form posts on the wire (not live refreshes) - var liveDirty = false; // a live change came while a navigation was on the wire + var liveDirty = false; // a live change came while a navigation or a live fetch was on the wire + var liveBusy = false; // a live fetch is on the wire: later changes wait for it, then share one fetch var inFlight = 0; // requests on the wire, drives aria-busy var pending = new WeakSet(); // forms with a request on the wire: a second submit is ignored var queued = new WeakSet(); // forms that changed while pending: submitted again once it completes @@ -323,10 +324,15 @@ if (final.origin !== location.origin || !html) { return { leave: true, url: final, redirected: r.redirected }; } - return r.text().then(function (text) { return { html: text, url: final }; }); + return r.text().then(function (text) { return { html: text, url: final, status: r.status }; }); }).then(function (res) { if (mark !== latest) { return; } if (res.leave) { leave(res, o); return; } + // A code view keeps its page when a live refresh fails. A 404 means its path is gone at the new ref. + if (o.how === 'live' && res.status >= 400 && document.querySelector('[data-live-code]')) { + if (res.status === 404) { showGone(); } + return; + } var dest = new URL(res.url.href); dest.hash = o.dest.hash; swap(res.html, dest, o.how, !!o.keep && res.url.pathname === o.target.pathname); @@ -336,10 +342,9 @@ }).then(function () { busyEnd(); if (o.form) { pending.delete(o.form); } - if (user) { - userBusy -= 1; - if (liveDirty) { refreshLive(); } - } + if (o.how === 'live') { liveBusy = false; } + if (user) { userBusy -= 1; } + if (liveDirty) { refreshLive(); } if (o.form && queued.has(o.form)) { queued.delete(o.form); resend(o.form); } }); } @@ -985,6 +990,8 @@ // A job page's stream opens with the status the page already shows: nothing to re-render then. var wrap = document.querySelector('[data-live]'); if (document.querySelector('[data-live-log]') && wrap && wrap.getAttribute('data-live-state') === e.data) { return; } + // A code view re-renders at once. Events that come while a fetch is on the wire share the next one. + if (document.querySelector('[data-live-code]')) { refreshLive(); return; } // The run list changes on every log chunk of every job: refresh at most once a second. if (document.querySelector('[data-live-log]')) { refreshLive(); return; } if (liveTimer) { return; } @@ -1008,12 +1015,25 @@ // response could be superseded: the change is kept and sent after that request completes. function refreshLive() { if (!liveStream) { return; } - if (userBusy > 0) { liveDirty = true; return; } + if (userBusy > 0 || liveBusy) { liveDirty = true; return; } liveDirty = false; + liveBusy = true; var here = new URL(location.href); load({ target: withoutHash(here), dest: here, init: GET_INIT, how: 'live', keep: true, post: false, form: null }); } + // A code view whose path is gone at the new ref keeps its page and shows one inline notice. + function showGone() { + var bar = document.querySelector('[data-live-code]'); + if (!bar || document.querySelector('[data-live-notice]')) { return; } + var note = document.createElement('p'); + note.className = 'notice'; + note.setAttribute('role', 'status'); + note.setAttribute('data-live-notice', ''); + note.textContent = bar.getAttribute('data-live-gone') || ''; + bar.insertAdjacentElement('afterend', note); + } + // Local clock for what runs. Server-rendered [data-since] (unix seconds) is the start of a duration // still counting: its text is rewritten each second. [data-tick] boxes of the run list's bars and // the run timeline grow with the clock. This is a display clock only: no request is made. The diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 9b3965e..8634c69 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -134,6 +134,7 @@ pub async fn serve( mail_waker: Arc::new(Notify::new()), notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()), ci_live: Arc::new(crate::ci::CiLive::default()), + live: Arc::new(crate::live::LiveHub::default()), }; if let Err(e) = crate::signatures::rebuild_allowed_signers(&state).await { tracing::error!(error = %e, "building the SSH allowed-signers file failed"); diff --git a/crates/forge-web/src/i18n/code.rs b/crates/forge-web/src/i18n/code.rs index 9b744f4..612e1bc 100644 --- a/crates/forge-web/src/i18n/code.rs +++ b/crates/forge-web/src/i18n/code.rs @@ -53,6 +53,7 @@ pub enum K { SubmoduleSuffix, TruncatedPrefix, ViewFullRaw, + LivePathGone, StatusAdded, StatusDeleted, StatusModified, @@ -216,6 +217,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (TruncatedPrefix, Tr) => "Bu dosyanın ilk 1 MiB'ı gösteriliyor. ", (ViewFullRaw, En) => "View the full file raw", (ViewFullRaw, Tr) => "Dosyanın tamamını ham olarak görüntüle", + (LivePathGone, En) => "This path no longer exists in this ref.", + (LivePathGone, Tr) => "Bu yol bu referansta artık yok.", (StatusAdded, En) => "added", (StatusAdded, Tr) => "eklendi", (StatusDeleted, En) => "deleted", @@ -549,6 +552,7 @@ mod tests { K::SubmoduleSuffix, K::TruncatedPrefix, K::ViewFullRaw, + K::LivePathGone, K::StatusAdded, K::StatusDeleted, K::StatusModified, diff --git a/crates/forge-web/src/live.rs b/crates/forge-web/src/live.rs new file mode 100644 index 0000000..8ad5ea1 --- /dev/null +++ b/crates/forge-web/src/live.rs @@ -0,0 +1,157 @@ +//! Live pages: change signals keyed by [`Topic`], and the event stream that carries them. +//! +//! A write that changes what a topic shows calls [`LiveHub::bump`]. Every open stream subscribed +//! to that topic wakes and sends one `changed` event. The signal carries no data: the page reads +//! its state again on the client (a soft re-fetch of the URL, see `nav.js`), so a bump that +//! lands during another one is never lost. Nothing polls. A topic with no subscriber is not kept. +//! +//! # Adding a topic +//! 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 +//! 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. +//! +//! 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. + +use std::collections::HashMap; +use std::future::Future; +use std::sync::{Mutex, MutexGuard, PoisonError}; + +use futures_util::stream; +use tokio::sync::watch; +use topcoat::Result; +use topcoat::context::Cx; +use topcoat::router::content::sse::Event; +use topcoat::router::response::Response; + +use crate::pages::ci_runs::events_response; + +/// What a live page follows. Add a variant when a page needs a new signal. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum Topic { + /// The refs of a repo: a branch or tag was created, deleted or moved. Keyed by repo id. + RepoRefs(String), +} + +/// The open topics, each with the counter its subscribers wait on. +#[derive(Default)] +pub struct LiveHub { + topics: Mutex>>, +} + +impl LiveHub { + fn topics(&self) -> MutexGuard<'_, HashMap>> { + self.topics.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Subscribes to `topic`. The receiver starts as seen, so a bump after this call wakes it. + /// Subscribe before reading the state, so a change in between is not lost. Topics nobody + /// holds any more are dropped here, so the map stays small. + pub fn subscribe(&self, topic: &Topic) -> watch::Receiver { + let mut topics = self.topics(); + topics.retain(|_, tx| tx.receiver_count() > 0); + topics + .entry(topic.clone()) + .or_insert_with(|| watch::channel(0).0) + .subscribe() + } + + /// Wakes the subscribers of `topic`. Does nothing when nobody is subscribed. + pub fn bump(&self, topic: &Topic) { + let mut topics = self.topics(); + let Some(tx) = topics.get(topic) else { + return; + }; + tx.send_modify(|generation| *generation = generation.wrapping_add(1)); + if tx.receiver_count() == 0 { + topics.remove(topic); + } + } +} + +/// The state a stream follows between wakes: the fingerprint last sent or seen. +struct Follow { + wake: watch::Receiver, + read: F, + last: String, +} + +/// The `changed` event of a live page. The data is not read by the client. +fn changed_event() -> Result { + Ok(Event::new().event("changed").data("1")) +} + +/// The response of a live stream for `topic`. 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, + read: F, +) -> Result +where + F: Fn() -> Fut + Send + 'static, + Fut: Future> + Send, +{ + // Subscribed before the first read, so a change in between wakes the stream. + let wake = hub.subscribe(topic); + let last = read().await?; + let events = stream::unfold(Follow { wake, read, last }, |mut follow| async move { + loop { + follow.wake.changed().await.ok()?; + let now = match (follow.read)().await { + Ok(now) => now, + Err(e) => { + tracing::error!(error = %e, "live: could not read the page state"); + return None; + } + }; + if now == follow.last { + continue; + } + follow.last = now; + return Some((changed_event(), follow)); + } + }); + events_response(cx, events) +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + + #[tokio::test] + async fn a_bump_wakes_only_the_subscribers_of_that_topic() { + let hub = LiveHub::default(); + let a = Topic::RepoRefs("repo-a".to_owned()); + let b = Topic::RepoRefs("repo-b".to_owned()); + let mut wake_a = hub.subscribe(&a); + let wake_b = hub.subscribe(&b); + + hub.bump(&a); + + tokio::time::timeout(Duration::from_secs(1), wake_a.changed()) + .await + .expect("woken") + .expect("open"); + assert!(!wake_b.has_changed().expect("open")); + } + + #[tokio::test] + async fn a_topic_nobody_holds_is_dropped_on_the_next_change() { + let hub = LiveHub::default(); + let topic = Topic::RepoRefs("repo-a".to_owned()); + let wake = hub.subscribe(&topic); + drop(wake); + + hub.bump(&topic); + assert!(hub.topics().is_empty()); + } +} diff --git a/crates/forge-web/src/main.rs b/crates/forge-web/src/main.rs index 2a1c933..34021bb 100644 --- a/crates/forge-web/src/main.rs +++ b/crates/forge-web/src/main.rs @@ -33,6 +33,7 @@ mod importer; mod internal; mod lfs; mod lfs_pointer; +mod live; mod mail; mod mirrors; mod notify; diff --git a/crates/forge-web/src/pages/blob.rs b/crates/forge-web/src/pages/blob.rs index 295f3a6..960d242 100644 --- a/crates/forge-web/src/pages/blob.rs +++ b/crates/forge-web/src/pages/blob.rs @@ -14,8 +14,10 @@ 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::finder::file_finder; use crate::pages::media::media_url; +use crate::pages::refs::load_refs; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::load_repo; use crate::pages::tree::{link_context, path_crumbs, read_file, resolve}; @@ -267,11 +269,13 @@ async fn blob_page(cx: &Cx) -> Result { let download_name = file_name.clone(); 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?; 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/code_live.rs b/crates/forge-web/src/pages/code_live.rs new file mode 100644 index 0000000..a5ce0b5 --- /dev/null +++ b/crates/forge-web/src/pages/code_live.rs @@ -0,0 +1,75 @@ +//! 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. + +use std::path::PathBuf; + +use forge_git::browse::{RefInfo, RefKind}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::response::Response; +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::state::AppState; + +path_param!(owner); +path_param!(repo); + +#[query_params(error = bad_request)] +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(|| { + format!( + "/{owner}/{repo}/code/events?ref_name={}", + percent_encode(ref_name) + ) + }) +} + +/// The state the code view shows: every branch and tag name, and the commit `branch` points at. +/// A move of another branch leaves it unchanged. +async fn refs_fingerprint(path: PathBuf, branch: String) -> Result { + let refs = load_refs(path).await?; + let mut names: Vec = refs + .iter() + .map(|r| format!("{} {}", r.kind == RefKind::Branch, r.name)) + .collect(); + names.sort(); + let at = refs + .iter() + .find(|r| r.kind == RefKind::Branch && r.name == branch) + .map_or("", |r| r.target.as_str()); + 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 { + let owner = path_param::(cx); + let name = path_param::(cx); + let branch = query_params::(cx)? + .ref_name + .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 path = ctx.path.clone(); + stream_changes(cx, &state.live, &topic, move || { + refs_fingerprint(path.clone(), branch.clone()) + }) + .await +} diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index e44ecdc..8015e40 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -28,6 +28,7 @@ pub mod ci_job; pub mod ci_runs; #[cfg(test)] mod ci_tests; +pub mod code_live; pub mod code_search; pub mod commit; pub mod commits; diff --git a/crates/forge-web/src/pages/repo.rs b/crates/forge-web/src/pages/repo.rs index 7c02bac..03a3bfd 100644 --- a/crates/forge-web/src/pages/repo.rs +++ b/crates/forge-web/src/pages/repo.rs @@ -20,6 +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::dashboard::badge_class; use crate::pages::finder::file_finder; use crate::pages::issue_parts::stamp_unix; @@ -448,6 +449,7 @@ async fn repo_page(cx: &Cx) -> Result { ctx.viewer_tz(), )); } + let live = live_url(&repo.owner_name, &repo.name, &refs, &branch); let branch_names: Vec = refs .into_iter() .filter(|r| r.kind == browse::RefKind::Branch) @@ -470,7 +472,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/settings_security.rs b/crates/forge-web/src/pages/settings_security.rs index b97f0b6..c1b36a5 100644 --- a/crates/forge-web/src/pages/settings_security.rs +++ b/crates/forge-web/src/pages/settings_security.rs @@ -1100,6 +1100,7 @@ mod tests { mail_waker: Arc::new(tokio::sync::Notify::new()), notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()), ci_live: Arc::new(crate::ci::CiLive::default()), + live: Arc::new(crate::live::LiveHub::default()), }; let hash = hash_password_async(PASSWORD.into()).await.unwrap(); let user = store diff --git a/crates/forge-web/src/pages/tree.rs b/crates/forge-web/src/pages/tree.rs index c75d1b1..0466250 100644 --- a/crates/forge-web/src/pages/tree.rs +++ b/crates/forge-web/src/pages/tree.rs @@ -17,6 +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::finder::file_finder; use crate::pages::refs::{load_refs, ref_links}; use crate::pages::repo::repo_head; @@ -547,6 +548,7 @@ 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 title = format!("{}/{}", repo.owner_name, repo.name); let crumbs = path_crumbs(repo, &ref_name, "tree", &dir); @@ -557,7 +559,7 @@ async fn tree_page(cx: &Cx) -> Result { Ok(view! { shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), repo_head(head: header) -
+
ref_selector(lang: lang, current: ref_name.clone(), branches: branches, tags: tags) 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/post_update.rs b/crates/forge-web/src/post_update.rs index 7a7c364..353e63c 100644 --- a/crates/forge-web/src/post_update.rs +++ b/crates/forge-web/src/post_update.rs @@ -41,6 +41,10 @@ pub async fn after_ref_update( ) -> forge_core::Result<()> { let sender = lookup_sender(state, actor_id).await; emit_ref_update(state, repo, &sender, refname, old, new).await; + // Code views that follow a branch or the ref list re-read it. + state + .live + .bump(&crate::live::Topic::RepoRefs(repo.id.clone())); 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/src/state.rs b/crates/forge-web/src/state.rs index 9ec7156..f26ea0b 100644 --- a/crates/forge-web/src/state.rs +++ b/crates/forge-web/src/state.rs @@ -49,6 +49,8 @@ pub struct AppState { pub notify_hub: Arc, /// Change counters of CI jobs and runs. Log followers and run pages wait on them. pub ci_live: Arc, + /// Change signals of live pages, keyed by topic. See `live`. + pub live: Arc, } /// A settings handle over `config` with no stored overrides and no file keys. For tests. diff --git a/crates/forge-web/src/test_support.rs b/crates/forge-web/src/test_support.rs index 2db9d8b..23bcdc3 100644 --- a/crates/forge-web/src/test_support.rs +++ b/crates/forge-web/src/test_support.rs @@ -86,6 +86,7 @@ pub async fn test_state(dir: &Path) -> AppState { mail_waker: Arc::new(Notify::new()), notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()), ci_live: Arc::new(crate::ci::CiLive::default()), + live: Arc::new(crate::live::LiveHub::default()), } } diff --git a/crates/forge-web/tests/browse_e2e.rs b/crates/forge-web/tests/browse_e2e.rs index 9727948..4afbeab 100644 --- a/crates/forge-web/tests/browse_e2e.rs +++ b/crates/forge-web/tests/browse_e2e.rs @@ -629,3 +629,140 @@ async fn browse_end_to_end() { ); assert_no_cookie(&login_page, "raw /login"); } + +/// Opens a code view stream and returns the response with its body still unread. +async fn open_stream(http: &Http, path: &str, cookie: Option<&str>) -> reqwest::Response { + let mut req = http.client.get(format!("{}{path}", http.base)); + if let Some(cookie) = cookie { + req = req.header(COOKIE, cookie); + } + req.send().await.expect("stream request") +} + +/// The next chunk of a stream. None when nothing arrives within two seconds. +async fn next_chunk(res: &mut reqwest::Response) -> Option { + let chunk = tokio::time::timeout(Duration::from_secs(2), res.chunk()) + .await + .ok()? + .expect("stream chunk")?; + Some(String::from_utf8_lossy(&chunk).into_owned()) +} + +#[tokio::test] +async fn code_view_stream_follows_pushes() { + 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("fliv") + .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-token").await; + create_repo(&http, &tahinli, "pub", "public").await; + create_repo(&http, &tahinli, "priv", "private").await; + let pub_url = format!( + "http://tahinli:{token}@127.0.0.1:{}/tahinli/pub.git", + ports.http + ); + let priv_url = format!( + "http://tahinli:{token}@127.0.0.1:{}/tahinli/priv.git", + ports.http + ); + let pub_main = push_fixtures(&dir, &pub_url, &dir.join("pub-live")); + push_fixtures(&dir, &priv_url, &dir.join("priv-live")); + let work = dir.join("pub-live"); + + // The branch page follows its branch. A commit page does not, since a commit never moves. + let branch_page = http.get("/tahinli/pub/tree/main/", None).await; + assert_eq!(branch_page.status, 200); + assert!( + branch_page + .body() + .contains(r#"data-live="/tahinli/pub/code/events?ref_name=main""#), + "branch page follows main" + ); + let commit_page = http + .get(&format!("/tahinli/pub/tree/{pub_main}/"), None) + .await; + assert_eq!(commit_page.status, 200); + assert!( + !commit_page.body().contains("data-live="), + "a commit page does not follow" + ); + + // Anyone can follow a public branch. + let mut stream = open_stream(&http, "/tahinli/pub/code/events?ref_name=main", None).await; + assert_eq!(stream.status().as_u16(), 200); + assert_eq!( + stream.headers().get(CONTENT_TYPE).unwrap(), + "text/event-stream" + ); + + // A push to another branch sends nothing: main did not move and no ref was created. + ok( + &git(&work, &["checkout", "-q", "feature/x"]), + "checkout feature/x", + ); + fs::write(work.join("other.txt"), "other\n").expect("write other.txt"); + commit_all(&work, "other branch commit"); + ok( + &git(&work, &["push", "-q", "origin", "feature/x"]), + "push feature/x", + ); + assert!(next_chunk(&mut stream).await.is_none(), "other branch sent"); + + // A push to main sends one `changed` event. + ok(&git(&work, &["checkout", "-q", "main"]), "checkout main"); + fs::write(work.join("README.md"), "# Live\n\nChanged by a push.\n").expect("write README"); + commit_all(&work, "change the README"); + ok(&git(&work, &["push", "-q", "origin", "main"]), "push main"); + let event = next_chunk(&mut stream).await.expect("event for main"); + assert!(event.contains("event: changed"), "{event}"); + + // Creating and deleting a branch changes the branch list, so the page follows it too. + ok( + &git(&work, &["checkout", "-q", "-b", "topic"]), + "create topic", + ); + ok( + &git(&work, &["push", "-q", "origin", "topic"]), + "push topic", + ); + let created = next_chunk(&mut stream) + .await + .expect("event for a new branch"); + assert!(created.contains("event: changed"), "{created}"); + ok( + &git(&work, &["push", "-q", "origin", "--delete", "topic"]), + "delete topic", + ); + let deleted = next_chunk(&mut stream) + .await + .expect("event for a deleted branch"); + 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 anonymous = open_stream(&http, private, None).await; + assert_eq!( + anonymous.status().as_u16(), + 404, + "private stream without a session" + ); + let member = open_stream(&http, private, Some(tahinli.as_str())).await; + assert_eq!( + member.status().as_u16(), + 200, + "private stream for its owner" + ); +}