diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 75498b0..e73d163 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -9,6 +9,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 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 shown = location.pathname + location.search; @@ -142,6 +144,8 @@ old.replaceWith(s); }); if (kept) { restoreFields(kept); } + syncUnread(); + syncLive(); } function focusMain() { @@ -161,19 +165,28 @@ } // how: 'nav' (link or GET form: push, top), 'pop' (history: push nothing, restore scroll), - // 'post' (form post: replace, keep scroll), 'query' (in place: replace, keep scroll). + // 'post' (form post: replace, keep scroll), 'query' (in place: replace, keep scroll), 'live' (a + // live page's change: no history entry, keep scroll, no fragment jump). function swap(html, dest, how, keepFields) { var doc = new DOMParser().parseFromString(html, 'text/html'); if (!doc.body) { location.assign(dest.href); return; } var x = window.scrollX, y = window.scrollY; var saved = history.state; + // A live swap keeps the log tail where the reader had it: at the end it stays at the end. + var tail = how === 'live' ? document.querySelector('[data-live-log]') : null; + var tailAt = tail ? { top: tail.scrollTop, end: tail.scrollTop + tail.clientHeight >= tail.scrollHeight - 8 } : null; + closeDropdowns(null); adopt(doc, keepFields); + if (tailAt) { + var nextTail = document.querySelector('[data-live-log]'); + if (nextTail) { nextTail.scrollTop = tailAt.end ? nextTail.scrollHeight : tailAt.top; } + } if (how === 'nav') { history.pushState(null, '', dest.href); } else if (how === 'post' || how === 'query') { history.replaceState(null, '', dest.href); } shown = dest.pathname + dest.search; if (how === 'nav' || how === 'pop') { focusMain(); } - if (placeHash(dest.hash)) { return; } - if (how === 'post' || how === 'query') { window.scrollTo(x, y); } + if (how !== 'live' && placeHash(dest.hash)) { return; } + if (how === 'post' || how === 'query' || how === 'live') { window.scrollTo(x, y); } else if (how === 'pop') { window.scrollTo(0, saved && typeof saved.y === 'number' ? saved.y : 0); } else { window.scrollTo(0, 0); } } @@ -194,6 +207,8 @@ // how, keep (keep fields on a re-render of the same path), post, and the form for a POST or GET form. function load(o) { var mark = ++latest; + var user = o.how !== 'live'; + if (user) { userBusy += 1; } busyStart(); fetch(o.target.href, o.init).then(function (r) { var final = new URL(r.url || o.target.href); @@ -209,11 +224,15 @@ dest.hash = o.dest.hash; swap(res.html, dest, o.how, !!o.keep && res.url.pathname === o.target.pathname); }).catch(function () { - if (mark !== latest) { return; } + if (mark !== latest || o.how === 'live') { return; } if (o.post) { o.form.submit(); } else { location.assign(o.dest.href); } }).then(function () { busyEnd(); if (o.form) { pending.delete(o.form); } + if (user) { + userBusy -= 1; + if (liveDirty) { refreshLive(); } + } }); } @@ -221,6 +240,39 @@ try { history.replaceState({ y: window.scrollY }, '', location.href); } catch (err) { } } + // Dropdown menus: the
that float over the page (avatar menu, branch selector, clone + // popover, phone menu). Inline disclosures are not listed here and keep their state. + var DROPDOWN = 'details.menu, details.ref-select, details.clone, details.nav-toggle'; + + // Closes every open dropdown except `keep` (pass null to close them all). + function closeDropdowns(keep) { + document.querySelectorAll(DROPDOWN).forEach(function (d) { + if (d.open && d !== keep) { d.open = false; } + }); + } + + // A click outside an open dropdown closes it. A click inside one (a select, a form field) keeps + // it open. Opening a dropdown by its summary closes the others: the browser toggles it after this. + document.addEventListener('click', function (e) { + var inside = e.target && e.target.closest ? e.target.closest(DROPDOWN) : null; + closeDropdowns(inside); + }, false); + + // Escape closes the open dropdowns and returns focus to the summary of the one that held it. + document.addEventListener('keydown', function (e) { + if (e.key !== 'Escape') { return; } + var back = null; + document.querySelectorAll(DROPDOWN).forEach(function (d) { + if (!d.open) { return; } + if (d.contains(document.activeElement)) { back = d; } + d.open = false; + }); + if (back) { + var summary = back.querySelector('summary'); + if (summary) { summary.focus(); } + } + }, false); + document.addEventListener('click', function (e) { if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { return; } var a = e.target && e.target.closest ? e.target.closest('a[href]') : null; @@ -297,6 +349,103 @@ // A filtered view asked for in place: the URL is replaced (no history entry per change), fields // and caret come through the swap, and the scroll stays put. + // Live unread count. The bell is re-rendered by every swap, so it is looked up on each update. One + // EventSource serves the page and stays open across swaps. It is opened only while a bell is shown + // (signed-in pages) and closed when the bell is gone. The server pushes each change; nothing polls. + var unreadStream = null; + + function bell() { return document.querySelector('a.bell'); } + + // Shows the count the way the server renders it: a `.bell-count` span with the number, or no span at zero. + function setUnread(n) { + var el = bell(); + if (!el) { return; } + var badge = el.querySelector('.bell-count'); + if (n > 0) { + if (!badge) { + badge = document.createElement('span'); + badge.className = 'bell-count'; + el.appendChild(badge); + } + badge.textContent = String(n); + } else if (badge) { + badge.remove(); + } + } + + function syncUnread() { + if (!bell()) { + if (unreadStream) { unreadStream.close(); unreadStream = null; } + return; + } + if (unreadStream || !window.EventSource) { return; } + unreadStream = new EventSource('/notifications/stream'); + unreadStream.addEventListener('unread', function (e) { + setUnread(parseInt(e.data, 10) || 0); + }); + } + + syncUnread(); + + // Live pages. A run or job page that is not finished marks its wrapper with data-live, the URL of + // its event stream. One EventSource follows it. A `changed` event re-fetches the page and swaps it in + // with no history entry and the scroll kept. A job page also has a log tail (data-live-log) whose + // `log` events append the new bytes as they come. The stream opens at the tail's data-offset, and + // each swap brings a fresh offset, so the stream is opened again after every swap. The server ends + // the stream once the status is terminal, and the swap that shows that page (no data-live) closes it. + var liveStream = null; + var liveUrl = null; + + function closeLive() { + if (liveStream) { liveStream.close(); } + liveStream = null; + liveUrl = null; + liveDirty = false; + } + + function syncLive() { + var el = document.querySelector('[data-live]'); + var url = el ? el.getAttribute('data-live') : null; + var tail = document.querySelector('[data-live-log]'); + if (url && tail) { + url += (url.indexOf('?') < 0 ? '?' : '&') + 'from=' + encodeURIComponent(tail.getAttribute('data-offset') || '0'); + } + if (!url || !window.EventSource) { closeLive(); return; } + if (liveStream && liveUrl === url) { return; } + closeLive(); + liveUrl = url; + liveStream = new EventSource(url); + liveStream.addEventListener('changed', function (e) { + // 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; } + refreshLive(); + }); + liveStream.addEventListener('log', function (e) { appendLog(e.data); }); + } + + // Appends streamed log text to the tail as a text node, never as HTML. The tail follows the end + // only while the reader is already at the end. + function appendLog(text) { + var pre = document.querySelector('[data-live-log]'); + if (!pre || !text) { return; } + var atEnd = pre.scrollTop + pre.clientHeight >= pre.scrollHeight - 8; + pre.appendChild(document.createTextNode(text)); + if (atEnd) { pre.scrollTop = pre.scrollHeight; } + } + + // A change re-renders the current page. It waits while a navigation is on the wire, since that + // 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; } + liveDirty = false; + var here = new URL(location.href); + load({ target: withoutHash(here), dest: here, init: GET_INIT, how: 'live', keep: true, post: false, form: null }); + } + + syncLive(); + window.__forgeQuery = function (href) { var url = pageUrl(href); if (!url) { location.assign(href); return; } diff --git a/crates/forge-web/src/ci/live.rs b/crates/forge-web/src/ci/live.rs new file mode 100644 index 0000000..be0289a --- /dev/null +++ b/crates/forge-web/src/ci/live.rs @@ -0,0 +1,163 @@ +//! Change signals for CI jobs and runs. [`CiLive`] keeps one generation counter per job and one per +//! run. A write that changes a job or a run bumps its counter, and every subscriber wakes on the +//! change. The counter carries no data: a subscriber reads the database or the log file again when +//! it wakes. Nothing polls. A signal with no receivers left is removed, so the maps hold only the +//! jobs and runs somebody is watching. The hub is in-process only, like [`NotifyHub`]. +//! +//! [`NotifyHub`]: crate::notify_hub::NotifyHub + +use std::collections::HashMap; +use std::sync::{Mutex, MutexGuard, PoisonError}; + +use tokio::sync::watch; + +/// The change counters of CI jobs and runs, each keyed by its id. +#[derive(Default)] +pub struct CiLive { + jobs: Signals, + runs: Signals, +} + +impl CiLive { + /// Subscribes to changes of job `job_id`. The receiver starts as seen, so a bump after this + /// call wakes it. Subscribe before the state you read, so a change in between is not lost. + pub fn subscribe_job(&self, job_id: &str) -> watch::Receiver { + self.jobs.subscribe(job_id) + } + + /// Subscribes to changes of run `run_id`. Same rules as [`CiLive::subscribe_job`]. + // No caller yet: the run status stream that waits on this is the next change. + #[allow(dead_code)] + pub fn subscribe_run(&self, run_id: &str) -> watch::Receiver { + self.runs.subscribe(run_id) + } + + /// Wakes the subscribers of job `job_id`: its log grew or its state changed. Does nothing when + /// nobody is subscribed. + pub fn bump_job(&self, job_id: &str) { + self.jobs.bump(job_id); + } + + /// Wakes the subscribers of run `run_id`: one of its jobs or its own status changed. + pub fn bump_run(&self, run_id: &str) { + self.runs.bump(run_id); + } + + /// Wakes the subscribers of job `job_id` once more and drops its signal. Call it when the job + /// has reached a terminal state: no change follows, so the signal is not kept. A subscriber + /// that waits on a closed signal wakes once and then sees it closed. + pub fn close_job(&self, job_id: &str) { + self.jobs.close(job_id); + } +} + +/// One keyed set of counters. A key has an entry only while it has a receiver or a bump is due. +#[derive(Default)] +struct Signals { + counters: Mutex>>, +} + +impl Signals { + fn counters(&self) -> MutexGuard<'_, HashMap>> { + self.counters.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn subscribe(&self, key: &str) -> watch::Receiver { + self.counters() + .entry(key.to_owned()) + .or_insert_with(|| watch::channel(0).0) + .subscribe() + } + + /// Counts one change. Without a subscriber there is no entry, so the bump is a no-op. An entry + /// whose last receiver is gone is removed here. + fn bump(&self, key: &str) { + let mut counters = self.counters(); + let Some(tx) = counters.get(key) else { + return; + }; + tx.send_modify(|generation| *generation = generation.wrapping_add(1)); + if tx.receiver_count() == 0 { + counters.remove(key); + } + } + + /// Counts one last change and removes the entry. The sender is dropped afterwards, so each + /// subscriber wakes once more and then finds the signal closed. + fn close(&self, key: &str) { + let removed = self.counters().remove(key); + if let Some(tx) = removed { + tx.send_modify(|generation| *generation = generation.wrapping_add(1)); + } + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + + #[tokio::test] + async fn a_bump_wakes_only_the_subscribers_of_that_job() { + let live = CiLive::default(); + let mut job = live.subscribe_job("job-1"); + let other = live.subscribe_job("job-2"); + let run = live.subscribe_run("run-1"); + + live.bump_job("job-1"); + + tokio::time::timeout(Duration::from_secs(1), job.changed()) + .await + .expect("woken") + .expect("open"); + assert_eq!(*job.borrow_and_update(), 1); + assert!(!other.has_changed().expect("open")); + assert!(!run.has_changed().expect("open")); + } + + #[tokio::test] + async fn a_bump_before_subscribing_is_not_seen_and_a_bump_after_is() { + let live = CiLive::default(); + let early = live.subscribe_run("run-1"); + live.bump_run("run-1"); + let mut late = live.subscribe_run("run-1"); + assert!(early.has_changed().expect("open")); + assert!(!late.has_changed().expect("open")); + live.bump_run("run-1"); + assert!(late.has_changed().expect("open")); + late.changed().await.expect("open"); + assert_eq!(*late.borrow_and_update(), 2); + } + + #[test] + fn a_bump_without_subscribers_keeps_no_entry() { + let live = CiLive::default(); + live.bump_job("job-1"); + live.bump_run("run-1"); + assert!(live.jobs.counters().is_empty()); + assert!(live.runs.counters().is_empty()); + } + + #[test] + fn a_bump_drops_the_entry_once_its_last_receiver_is_gone() { + let live = CiLive::default(); + let rx = live.subscribe_job("job-1"); + assert_eq!(live.jobs.counters().len(), 1); + drop(rx); + live.bump_job("job-1"); + assert!(live.jobs.counters().is_empty()); + } + + #[tokio::test] + async fn close_wakes_the_subscriber_once_and_then_ends_the_signal() { + let live = CiLive::default(); + let mut rx = live.subscribe_job("job-1"); + live.close_job("job-1"); + assert!(live.jobs.counters().is_empty()); + + rx.changed().await.expect("the last change is delivered"); + assert_eq!(*rx.borrow_and_update(), 1); + assert!(rx.changed().await.is_err()); + } +} diff --git a/crates/forge-web/src/i18n/misc.rs b/crates/forge-web/src/i18n/misc.rs index c7133a6..771d7f0 100644 --- a/crates/forge-web/src/i18n/misc.rs +++ b/crates/forge-web/src/i18n/misc.rs @@ -80,10 +80,12 @@ pub enum K { // Notifications: subscription box and watch control. Subscribe, Unsubscribe, - NotificationLevel, OptParticipating, OptWatching, OptIgnoring, + WatchDescParticipating, + WatchDescWatching, + WatchDescIgnoring, // Repo security page. SecurityOff, LockfilesRead, @@ -140,6 +142,9 @@ pub enum K { BreadcrumbNav, ApplyTheme, RefLabel, + // Top-bar user menu: the viewer's public profile and the settings editor. + YourProfile, + EditProfile, } /// Every variant, for the coverage test below. @@ -207,10 +212,12 @@ const ALL: &[K] = &[ K::Older, K::Subscribe, K::Unsubscribe, - K::NotificationLevel, K::OptParticipating, K::OptWatching, K::OptIgnoring, + K::WatchDescParticipating, + K::WatchDescWatching, + K::WatchDescIgnoring, K::SecurityOff, K::LockfilesRead, K::NoAlerts, @@ -262,6 +269,8 @@ const ALL: &[K] = &[ K::BreadcrumbNav, K::ApplyTheme, K::RefLabel, + K::YourProfile, + K::EditProfile, ]; pub fn t(lang: Lang, key: K) -> &'static str { @@ -400,14 +409,20 @@ pub fn t(lang: Lang, key: K) -> &'static str { (Subscribe, Tr) => "Abone ol", (Unsubscribe, En) => "Unsubscribe", (Unsubscribe, Tr) => "Abonelikten çık", - (NotificationLevel, En) => "Notification level", - (NotificationLevel, Tr) => "Bildirim düzeyi", (OptParticipating, En) => "Participating", (OptParticipating, Tr) => "Katılımcı", (OptWatching, En) => "Watching", (OptWatching, Tr) => "İzleniyor", (OptIgnoring, En) => "Ignoring", (OptIgnoring, Tr) => "Yok sayılıyor", + (WatchDescParticipating, En) => "Only threads you start, join or are mentioned in.", + (WatchDescParticipating, Tr) => { + "Yalnızca başlattığın, katıldığın veya adının geçtiği konular." + } + (WatchDescWatching, En) => "All activity in this repository.", + (WatchDescWatching, Tr) => "Bu depodaki tüm etkinlik.", + (WatchDescIgnoring, En) => "Nothing from this repository, except mentions.", + (WatchDescIgnoring, Tr) => "Bu depodan hiçbir şey, yalnızca adınızın geçtikleri hariç.", (SecurityOff, En) => { "Security advisories are off on this instance, so no lockfile is scanned. An administrator can turn them on with the [advisories] section of the config." } @@ -526,6 +541,10 @@ pub fn t(lang: Lang, key: K) -> &'static str { (ApplyTheme, Tr) => "Uygula", (RefLabel, En) => "Ref", (RefLabel, Tr) => "Referans", + (YourProfile, En) => "Your profile", + (YourProfile, Tr) => "Profilin", + (EditProfile, En) => "Edit profile", + (EditProfile, Tr) => "Profili düzenle", } } diff --git a/crates/forge-web/src/notify.rs b/crates/forge-web/src/notify.rs index e8c21e8..6557eb5 100644 --- a/crates/forge-web/src/notify.rs +++ b/crates/forge-web/src/notify.rs @@ -17,6 +17,7 @@ use crate::mail::{ self, templates::{self, Verb, Why}, }; +use crate::notify_hub::publish_unread; use crate::render::markdown::mentioned_usernames; use crate::state::AppState; @@ -181,6 +182,7 @@ async fn notify_advisory_admins(state: &AppState, repo: &Repo, opened: usize) -> .store .notify_new_alerts(&admin, &repo.id, count) .await?; + publish_unread(state, &admin).await; } Ok(()) } @@ -365,7 +367,7 @@ async fn run( } for (user_id, reason) in recipients { - if let Err(e) = store + match store .upsert_notification( &user_id, &repo.id, @@ -376,7 +378,8 @@ async fn run( ) .await { - tracing::error!(error = %e, user_id, issue_id, "notify: inbox write failed"); + Ok(()) => publish_unread(state, &user_id).await, + Err(e) => tracing::error!(error = %e, user_id, issue_id, "notify: inbox write failed"), } if let Some(plan) = &plan && let Err(e) = queue_email(state, plan, &user_id, reason).await diff --git a/crates/forge-web/src/notify_hub.rs b/crates/forge-web/src/notify_hub.rs new file mode 100644 index 0000000..029b106 --- /dev/null +++ b/crates/forge-web/src/notify_hub.rs @@ -0,0 +1,202 @@ +//! Live unread counts for the bell. [`NotifyHub`] keeps one `watch` channel per signed-in user who +//! has an open `GET /notifications/stream`. A write that changes a user's inbox publishes the new +//! count, and each open stream of that user sends it. Nothing polls: a stream waits on its channel. +//! The hub is in-process only, so a second server process would not see the change. +//! +//! A channel with no receivers left is removed, so the map holds only users who are connected. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; + +use tokio::sync::watch; + +use crate::state::AppState; + +/// The users with an open stream, each with the channel that carries its unread count. +pub struct NotifyHub { + users: Mutex>>, + /// Set once on server shutdown. Every open stream ends when it sees this. + closing: watch::Sender, +} + +impl NotifyHub { + pub fn new() -> Self { + Self { + users: Mutex::new(HashMap::new()), + closing: watch::channel(false).0, + } + } + + fn users(&self) -> MutexGuard<'_, HashMap>> { + self.users.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Opens a subscription to the counts published for `user_id`. The first count is not sent + /// here: the caller reads it from the store after subscribing, so a change in between is + /// seen by the subscription and sent again rather than lost. + pub fn subscribe(self: &Arc, user_id: &str) -> Subscription { + let rx = self + .users() + .entry(user_id.to_owned()) + .or_insert_with(|| watch::channel(0).0) + .subscribe(); + Subscription { + rx: Some(rx), + closing: self.closing.subscribe(), + hub: Arc::clone(self), + user_id: user_id.to_owned(), + } + } + + /// True when `user_id` has an open stream. A write skips the count query for anyone else. + pub fn is_watched(&self, user_id: &str) -> bool { + self.users() + .get(user_id) + .is_some_and(|tx| tx.receiver_count() > 0) + } + + /// Sends `count` to every open stream of `user_id`. Drops the channel when none is left. + pub fn publish(&self, user_id: &str, count: u64) { + let mut users = self.users(); + let Some(tx) = users.get(user_id) else { + return; + }; + if tx.receiver_count() == 0 { + users.remove(user_id); + return; + } + tx.send_replace(count); + } + + /// Ends every open stream. Called once when the server shuts down. + pub fn close(&self) { + self.closing.send_replace(true); + } + + /// Removes the user's channel once its last subscription is gone. + fn release(&self, user_id: &str) { + let mut users = self.users(); + if users + .get(user_id) + .is_some_and(|tx| tx.receiver_count() == 0) + { + users.remove(user_id); + } + } +} + +/// One open stream's view of its user's count. Dropping it releases the user's channel when no +/// other stream of that user is open. +pub struct Subscription { + /// Taken in `drop` before the hub is told, so the hub counts this receiver as gone. + rx: Option>, + closing: watch::Receiver, + hub: Arc, + user_id: String, +} + +impl Subscription { + /// Waits for the next published count. `None` once the hub is closing (server shutdown). + pub async fn next_count(&mut self) -> Option { + loop { + if *self.closing.borrow() { + return None; + } + let rx = self.rx.as_mut()?; + tokio::select! { + changed = rx.changed() => { + changed.ok()?; + return Some(*rx.borrow_and_update()); + } + changed = self.closing.changed() => { + changed.ok()?; + } + } + } + } +} + +impl Drop for Subscription { + fn drop(&mut self) { + self.rx = None; + self.hub.release(&self.user_id); + } +} + +/// 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. +pub async fn publish_unread(state: &AppState, user_id: &str) { + if !state.notify_hub.is_watched(user_id) { + return; + } + match state.store.unread_count(user_id).await { + Ok(count) => state.notify_hub.publish(user_id, count), + Err(e) => tracing::error!(error = %e, user_id, "notify: unread count failed"), + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + + #[tokio::test] + async fn publish_reaches_the_subscriber_of_that_user_only() { + let hub = Arc::new(NotifyHub::new()); + let mut tahinli = hub.subscribe("tahinli"); + let mut bob = hub.subscribe("bob"); + + hub.publish("tahinli", 3); + assert_eq!(tahinli.next_count().await, Some(3)); + + // Bob heard nothing: his wait times out. + let quiet = tokio::time::timeout(Duration::from_millis(50), bob.next_count()).await; + assert!(quiet.is_err()); + } + + #[tokio::test] + async fn publish_without_subscribers_is_a_no_op_and_nothing_is_kept() { + let hub = Arc::new(NotifyHub::new()); + assert!(!hub.is_watched("tahinli")); + hub.publish("tahinli", 1); + assert!(!hub.is_watched("tahinli")); + assert!(hub.users().is_empty()); + } + + #[tokio::test] + async fn the_channel_is_released_when_the_last_subscription_drops() { + let hub = Arc::new(NotifyHub::new()); + let first = hub.subscribe("tahinli"); + let second = hub.subscribe("tahinli"); + assert!(hub.is_watched("tahinli")); + + drop(first); + assert!(hub.is_watched("tahinli")); + + drop(second); + assert!(!hub.is_watched("tahinli")); + assert!(hub.users().is_empty()); + } + + #[tokio::test] + async fn every_open_stream_of_a_user_gets_the_count() { + let hub = Arc::new(NotifyHub::new()); + let mut tab_one = hub.subscribe("tahinli"); + let mut tab_two = hub.subscribe("tahinli"); + + hub.publish("tahinli", 5); + assert_eq!(tab_one.next_count().await, Some(5)); + assert_eq!(tab_two.next_count().await, Some(5)); + } + + #[tokio::test] + async fn close_ends_every_subscription() { + let hub = Arc::new(NotifyHub::new()); + let mut sub = hub.subscribe("tahinli"); + + hub.close(); + assert_eq!(sub.next_count().await, None); + } +} diff --git a/crates/forge-web/src/pages/ci_job.rs b/crates/forge-web/src/pages/ci_job.rs index a8236e3..5ca6558 100644 --- a/crates/forge-web/src/pages/ci_job.rs +++ b/crates/forge-web/src/pages/ci_job.rs @@ -1,11 +1,13 @@ //! Pages: one CI job (`/{owner}/{repo}/ci/jobs/{job_id}`), its live log (`.../log.txt`) and its //! artifacts (`.../artifacts/{name}`). Reading follows repo Read, like the run pages. The job page -//! shows the last 512 KiB of the log with no JavaScript: while the job is not terminal it refreshes -//! itself with a meta tag. `log.txt` streams the whole log and keeps following it until the job is +//! shows the last 512 KiB of the log. While the job is not terminal the page is live: it carries a +//! `data-live` marker for its `.../events` stream, and nav.js re-renders it when the job's status +//! changes. `log.txt` streams the whole log and keeps following it until the job is //! terminal and the file is read to its end. Artifacts are blobs under `ci/` and are //! always served as attachments. use std::path::{Path, PathBuf}; +use std::sync::Arc; use std::time::Duration; use bytes::Bytes; @@ -16,19 +18,24 @@ use http::header::{CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_TYPE}; use http_body::Frame; use http_body_util::StreamBody; use tokio::io::{AsyncReadExt, AsyncSeekExt, SeekFrom}; +use tokio::sync::watch; use topcoat::Result; use topcoat::context::{Cx, app_context}; +use topcoat::router::content::sse::{Event, last_event_id}; use topcoat::router::error::not_found; +use topcoat::router::request::uri; use topcoat::router::response::Response; use topcoat::router::{Body, HeaderName, HeaderValue, StatusCode, page, path_param, route}; use topcoat::view::{View, component, view}; -use crate::ci::{artifact_key, log_path}; +use crate::ci::{CiLive, artifact_key, log_path}; use crate::i18n::{ self, Lang, releases_ci::{self as g, K}, }; -use crate::pages::ci_runs::{job_href, run_href, state_text}; +use crate::pages::ci_runs::{ + changed_event, events_response, job_href, job_status, run_href, state_text, +}; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; use crate::state::AppState; @@ -43,8 +50,9 @@ path_param!(artifact_name); pub const TAIL_BYTES: u64 = 512 * 1024; /// Bytes read per chunk while following a log. const CHUNK_BYTES: usize = 64 * 1024; -/// How long `log.txt` waits before it looks at the file again. -const FOLLOW_POLL: Duration = Duration::from_secs(1); +/// The longest a follower waits for a change to its job before it reads again anyway. A change +/// wakes it at once; this only guards against a missed wake. +const WAKE_BACKSTOP: Duration = Duration::from_secs(60); /// The job and its run, both checked to belong to this repo. Anything else is 404. async fn job_of(state: &AppState, ctx: &RepoCtx, id: &str) -> Result<(CiJob, CiRun)> { @@ -60,18 +68,30 @@ async fn job_of(state: &AppState, ctx: &RepoCtx, id: &str) -> Result<(CiJob, CiR Ok((job, run)) } -/// The last `TAIL_BYTES` of a log, from a line boundary, and whether anything was cut. A log that -/// does not exist yet is empty. -async fn log_tail(path: &Path) -> Result<(String, bool)> { +/// The length of the longest whole-UTF-8 prefix of `buf`. A character that a read cut short at the +/// end is left out, so the next read sends it whole. Other invalid bytes are kept. +fn whole_utf8_len(buf: &[u8]) -> usize { + match std::str::from_utf8(buf) { + Ok(_) => buf.len(), + Err(e) if e.error_len().is_none() => e.valid_up_to(), + Err(_) => buf.len(), + } +} + +/// The last `TAIL_BYTES` of a log, from a line boundary, whether anything was cut, and the byte +/// offset just past the text shown. A log that does not exist yet is empty. +async fn log_tail(path: &Path) -> Result<(String, bool, u64)> { let mut file = match tokio::fs::File::open(path).await { Ok(file) => file, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((String::new(), false)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((String::new(), false, 0)), Err(e) => return Err(forge_core::Error::Io(e).into()), }; let len = file.metadata().await.map_err(forge_core::Error::Io)?.len(); let truncated = len > TAIL_BYTES; + let mut start = 0; if truncated { - file.seek(SeekFrom::Start(len - TAIL_BYTES)) + start = len - TAIL_BYTES; + file.seek(SeekFrom::Start(start)) .await .map_err(forge_core::Error::Io)?; } @@ -83,30 +103,45 @@ async fn log_tail(path: &Path) -> Result<(String, bool)> { .map_err(forge_core::Error::Io)?; if truncated && let Some(end) = buf.iter().position(|byte| *byte == b'\n') { buf.drain(..=end); + start += end as u64 + 1; } - Ok((String::from_utf8_lossy(&buf).into_owned(), truncated)) + buf.truncate(whole_utf8_len(&buf)); + let offset = start + buf.len() as u64; + Ok(( + String::from_utf8_lossy(&buf).into_owned(), + truncated, + offset, + )) } -/// Follows a log: yields what the file holds, then polls for new bytes once a second. The stream -/// ends when the job is terminal and a read after seeing that returns nothing, so every byte the -/// runner wrote is sent. A job that is gone, or a read error, ends the stream. -fn follow_log( +/// Follows a log: yields what the file holds, then sends new bytes each time the job changes (its +/// log grew or its state did). The stream ends when the job is terminal and a read after seeing +/// that returns nothing, so every byte the runner wrote is sent. A job that is gone, or a read +/// error, ends the stream. +pub(crate) fn follow_log( store: Store, + live: Arc, job_id: String, path: PathBuf, ) -> impl Stream> + Send + 'static { struct Follow { store: Store, + live: Arc, job_id: String, path: PathBuf, file: Option, + /// Subscribed before the first read, so a change between the read and the wait is seen. + wake: watch::Receiver, } + let wake = live.subscribe_job(&job_id); futures_util::stream::unfold( Follow { store, + live, job_id, path, file: None, + wake, }, |mut follow| async move { loop { @@ -139,7 +174,12 @@ fn follow_log( if terminal { return None; } - tokio::time::sleep(FOLLOW_POLL).await; + // A closed signal means the job finished, which the next check sees as terminal. + // It is subscribed again so this wait does not return at once. + if let Ok(Err(_)) = tokio::time::timeout(WAKE_BACKSTOP, follow.wake.changed()).await + { + follow.wake = follow.live.subscribe_job(&follow.job_id); + } } }, ) @@ -161,6 +201,8 @@ fn attachment_name(name: &str) -> String { /// The job page's values, already shown as text. struct JobView { name: String, + /// The status word as the events carry it, for the live check. + status: String, state: String, state_class: String, runner: String, @@ -180,22 +222,22 @@ struct ArtifactRow { size: String, } -/// The job page body. The meta refresh is in the body, since the shell has no head hook. +/// The job page body. A job that is not terminal carries `live`, the URL of its event stream, and +/// the status the page shows. The log tail carries the offset its text ends at. #[component] async fn job_body( head: RepoHead, lang: Lang, job: JobView, log: String, + log_offset: String, truncated: bool, artifacts: Vec, - refresh: bool, + live: Option, ) -> Result { Ok(view! { repo_head(head: head) - if refresh { - - } +

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

(job.name.as_str())

@@ -224,7 +266,7 @@ async fn job_body( if truncated {

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

} -
(log.as_str())
+
(log.as_str())
if !artifacts.is_empty() {
@@ -236,6 +278,7 @@ async fn job_body(
} +
}) } @@ -249,7 +292,7 @@ async fn job_page(cx: &Cx) -> Result { let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(user, _)| user)); let state = app_context::(cx); let (job, run) = job_of(state, &ctx, &id).await?; - let (log, truncated) = log_tail(&log_path(&state.config.data_dir, &job.id)).await?; + let (log, truncated, log_offset) = log_tail(&log_path(&state.config.data_dir, &job.id)).await?; let artifacts = state .store .list_artifacts(&job.id) @@ -277,9 +320,10 @@ async fn job_page(cx: &Cx) -> Result { None => String::new(), }; let title = title_of(&ctx); - let refresh = !job.state.is_terminal(); + let live = (!job.state.is_terminal()).then(|| format!("{}/events", job_href(&title, &job.id))); let view = JobView { name: job.name.clone(), + status: job.state.as_str().to_owned(), state: state_text(lang, job.state.as_str()), state_class: format!("ci-state ci-{}", job.state.as_str()), runner, @@ -298,8 +342,8 @@ async fn job_page(cx: &Cx) -> Result { let page_title = format!("{title} \u{b7} CI \u{b7} {}", view.name); Ok(view! { shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), - job_body(head: head, lang: lang, job: view, log: log, truncated: truncated, - artifacts: artifacts, refresh: refresh)) + job_body(head: head, lang: lang, job: view, log: log, log_offset: log_offset.to_string(), + truncated: truncated, artifacts: artifacts, live: live)) }) } @@ -307,6 +351,146 @@ fn title_of(ctx: &RepoCtx) -> String { format!("{}/{}", ctx.repo.owner_name, ctx.repo.name) } +/// Bytes of log per `log` event. A bigger append is sent as several events. +const LOG_EVENT_BYTES: u64 = 64 * 1024; + +/// The job's live stream. It opens with the status, sends a `changed` event when the status changes +/// and a `log` event with each new run of log bytes. A `log` event's id is the offset past its text, +/// so a reconnect (`Last-Event-ID`) resumes there. A new stream starts at `?from=`, the offset the +/// page already shows. The stream ends once the job is terminal and its log is read to the end. +#[route(GET "/{owner}/{repo}/ci/jobs/{job_id}/events")] +async fn job_events(cx: &Cx) -> Result { + let owner = path_param::(cx); + let name = path_param::(cx); + let id = path_param::(cx).to_owned(); + let ctx = load_repo(cx, owner, name).await?; + let state = app_context::(cx); + let (job, _) = job_of(state, &ctx, &id).await?; + let offset = last_event_id(cx) + .and_then(|id| id.parse::().ok()) + .or_else(|| from_query(cx)) + .unwrap_or(0); + // Subscribed before the first read, so a change in between is sent. + let wake = state.ci_live.subscribe_job(&job.id); + let follow = JobFollow { + store: state.store.clone(), + job_id: job.id.clone(), + path: log_path(&state.config.data_dir, &job.id), + wake, + offset, + status: None, + terminal: false, + more: false, + primed: false, + pending_status: None, + pending_log: None, + }; + events_response(cx, job_stream(follow)) +} + +/// The `from` offset of the events URL, if it is a number. +fn from_query(cx: &Cx) -> Option { + uri(cx).query().and_then(|query| { + form_urlencoded::parse(query.as_bytes()) + .find(|(key, _)| key == "from") + .and_then(|(_, value)| value.parse::().ok()) + }) +} + +/// One job's stream state. Each read of the status and the log happens after a wake, and a read that +/// sent log bytes is followed by another read at once, so a long append drains in order. +struct JobFollow { + store: Store, + job_id: String, + path: PathBuf, + wake: watch::Receiver, + /// The log offset read so far. The next read starts here. + offset: u64, + /// The status last read. + status: Option, + /// The job was terminal at the last read. + terminal: bool, + /// The last read sent log bytes, so more may be waiting. + more: bool, + /// False until the first read. Later reads wait for a wake first, unless `more` is set. + primed: bool, + pending_status: Option, + /// The text and the offset past it. + pending_log: Option<(String, u64)>, +} + +fn job_stream(follow: JobFollow) -> impl Stream> + Send + 'static { + futures_util::stream::unfold(follow, |mut f| async move { + loop { + if let Some(status) = f.pending_status.take() { + return Some((changed_event(status), f)); + } + if let Some((text, end)) = f.pending_log.take() { + let event = Event::new().event("log").data(text).id(end.to_string()); + return Some((Ok(event), f)); + } + if f.terminal && !f.more { + return None; + } + if f.primed && !f.more && f.wake.changed().await.is_err() { + return None; + } + f.primed = true; + f.more = false; + let (status, terminal) = match job_status(&f.store, &f.job_id).await { + Ok(Some(found)) => found, + Ok(None) => return None, + Err(e) => { + tracing::error!(error = %e, "ci: job stream could not read the job"); + return None; + } + }; + f.terminal = terminal; + if f.status.as_deref() != Some(status.as_str()) { + f.status = Some(status.clone()); + f.pending_status = Some(status); + } + match read_log(&f.path, f.offset).await { + Ok(Some((text, end))) => { + f.offset = end; + f.more = true; + f.pending_log = Some((text, end)); + } + Ok(None) => {} + Err(e) => { + tracing::error!(error = %e, "ci: job stream could not read the log"); + return None; + } + } + } + }) +} + +/// The whole text of the log from `offset`, at most `LOG_EVENT_BYTES`, and the offset past it. None +/// when there is nothing new (no file, no bytes past `offset`, or only part of a character). +async fn read_log(path: &Path, offset: u64) -> std::io::Result> { + let mut file = match tokio::fs::File::open(path).await { + Ok(file) => file, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e), + }; + file.seek(SeekFrom::Start(offset)).await?; + let mut buf = Vec::new(); + (&mut file) + .take(LOG_EVENT_BYTES) + .read_to_end(&mut buf) + .await?; + let whole = whole_utf8_len(&buf); + if whole == 0 { + return Ok(None); + } + buf.truncate(whole); + Ok(Some(( + String::from_utf8_lossy(&buf).into_owned(), + offset + whole as u64, + ))) +} + /// Streams the job's log as plain text. It sends the file so far and then follows it until the job /// is terminal. #[route(GET "/{owner}/{repo}/ci/jobs/{job_id}/log.txt")] @@ -318,7 +502,13 @@ async fn job_log(cx: &Cx) -> Result { let state = app_context::(cx); let (job, _) = job_of(state, &ctx, &id).await?; let path = log_path(&state.config.data_dir, &job.id); - let chunks = follow_log(state.store.clone(), job.id.clone(), path).map_ok(Frame::data); + let chunks = follow_log( + state.store.clone(), + Arc::clone(&state.ci_live), + job.id.clone(), + path, + ) + .map_ok(Frame::data); let mut res = Response::new(Body::new(StreamBody::new(chunks))); *res.status_mut() = StatusCode::OK; let headers = res.headers_mut(); diff --git a/crates/forge-web/src/pages/ci_runs.rs b/crates/forge-web/src/pages/ci_runs.rs index 92f2bdf..7d53645 100644 --- a/crates/forge-web/src/pages/ci_runs.rs +++ b/crates/forge-web/src/pages/ci_runs.rs @@ -2,22 +2,30 @@ //! the repo sees its runs, their jobs and the config error of a run. Starting a manual run, cancelling, //! re-running and approving need Write, and the buttons are shown only to writers. Anyone else gets a //! 404 for a private repo and a refusal for a change. Every change notifies the job waker and syncs -//! the commit status of each job it changed. +//! the commit status of each job it changed. A run or job page that is not finished stays live: it +//! opens a `changed` event stream (`.../events`) and re-renders itself on each event, with no reload +//! and no timer. use std::collections::HashMap; +use std::future::Future; +use std::time::Duration; use forge_core::ci::{CiJob, CiRun, RunState}; -use forge_core::{Action, Denied, User, authorize}; +use forge_core::{Action, Denied, Store, User, authorize}; use forge_git::browse::{RefInfo, RefKind}; +use futures_util::{Stream, stream}; use serde::Deserialize; use time::OffsetDateTime; use time::format_description::well_known::Rfc3339; +use tokio::sync::watch; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; +use topcoat::router::content::sse::{Event, KeepAlive, Sse}; use topcoat::router::error::{SeeOther, forbidden, not_found, see_other}; use topcoat::router::request::uri; -use topcoat::router::{page, path_param, route}; +use topcoat::router::response::{IntoResponse, Response}; +use topcoat::router::{HeaderValue, page, path_param, route}; use topcoat::view::{View, component, view}; use crate::auth::{current_user, require_csrf}; @@ -116,6 +124,15 @@ pub fn job_href(title: &str, job_id: &str) -> String { format!("/{title}/ci/jobs/{}", enc(job_id)) } +/// The badge image (same origin, default branch) and the README snippet that links it to the CI +/// runs page. The snippet uses the configured base URL so it works when pasted elsewhere. +fn badge_info(state: &AppState, title: &str, default_branch: &str) -> BadgeInfo { + let base = state.config.base_url.trim_end_matches('/'); + let image = format!("/{}/badge.svg?branch={}", enc(title), enc(default_branch)); + let snippet = format!("[![CI]({base}{image})]({base}{})", ci_href(&enc(title))); + BadgeInfo { image, snippet } +} + /// The notice from `?notice=`. Anything else is ignored. fn notice_from_query(cx: &Cx, lang: Lang) -> Option<(&'static str, bool)> { let query = uri(cx).query()?; @@ -230,16 +247,22 @@ async fn run_of(state: &AppState, ctx: &RepoCtx, number: &str) -> Result /// Wakes the job queue and syncs the commit status of every job whose state changed since `before`. /// A job missing from `before` (a fresh run) counts as changed. async fn after_change(state: &AppState, run_id: &str, before: &[CiJob]) -> Result<()> { - state.ci_waker.notify_one(); + state.ci_waker.notify_waiters(); let Some(run) = state.store.run_by_id(run_id).await? else { return Ok(()); }; + state.ci_live.bump_run(run_id); for job in state.store.jobs_for_run(run_id).await? { let changed = before .iter() .find(|old| old.id == job.id) .is_none_or(|old| old.state != job.state); if changed { + if job.state.is_terminal() { + state.ci_live.close_job(&job.id); + } else { + state.ci_live.bump_job(&job.id); + } crate::ci::sync_status(state, &run, &job).await; } } @@ -266,6 +289,12 @@ struct ManualRun { branches: Vec, } +/// The status badge section: the image path (same origin) and the Markdown for a README. +struct BadgeInfo { + image: String, + snippet: String, +} + /// A job row on the run page. struct JobRow { href: String, @@ -331,6 +360,7 @@ async fn runs_body( lang: Lang, notice: Option<(&'static str, bool)>, manual: Option, + badge: BadgeInfo, rows: Vec, newer_href: Option, older_href: Option, @@ -363,6 +393,17 @@ async fn runs_body( } +
+
+ (g::t(lang, K::BadgeHeading)) +

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

+

CI

+ +
+

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

if rows.is_empty() { @@ -455,11 +496,12 @@ async fn runs_list_page(cx: &Cx) -> Result { None }; let notice = notice_from_query(cx, lang); + let badge = badge_info(state, &title_of(&ctx), &ctx.repo.default_branch); let head = ctx.head(state, "ci").await?; let title = format!("{} \u{b7} CI", title_of(&ctx)); Ok(view! { shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), - runs_body(head: head, lang: lang, notice: notice, manual: manual, rows: rows, + runs_body(head: head, lang: lang, notice: notice, manual: manual, badge: badge, rows: rows, newer_href: newer_href, older_href: older_href, page_label: page_label)) }) } @@ -544,7 +586,113 @@ fn job_rows( .collect() } -/// The run page body: the header, the buttons for writers, the config error, and the jobs. +/// How often an idle event stream sends a `: keepalive` comment, so a reverse proxy does not drop +/// the connection. This is not a poll: events follow the change signals. +const STREAM_KEEP_ALIVE: Duration = Duration::from_secs(30); + +/// A run's or job's status word and whether it is terminal. `None` when the row is gone. +pub(crate) type Status = Option<(String, bool)>; + +pub(crate) async fn run_status(store: &Store, run_id: &str) -> Result { + Ok(store + .run_by_id(run_id) + .await? + .map(|run| (run.state.as_str().to_owned(), run_finished(&run.state)))) +} + +pub(crate) async fn job_status(store: &Store, job_id: &str) -> Result { + Ok(store + .job_by_id(job_id) + .await? + .map(|job| (job.state.as_str().to_owned(), job.state.is_terminal()))) +} + +/// One `changed` event carrying the status word. +pub(crate) fn changed_event(status: String) -> Result { + Ok(Event::new().event("changed").data(status)) +} + +/// The `changed` events of a CI page. The first event carries the status now. Each later one +/// follows a wake of `wake`: with `only_on_status`, only when the status differs from the last one +/// sent. The stream ends after the terminal status is sent, when the row is gone, or when the signal +/// closes. Subscribe `wake` before the first read, so a change in between is not lost. +pub(crate) fn changed_stream( + wake: watch::Receiver, + only_on_status: bool, + read: F, +) -> impl Stream> + Send + 'static +where + F: Fn() -> Fut + Send + 'static, + Fut: Future> + Send, +{ + struct Follow { + wake: watch::Receiver, + only_on_status: bool, + read: F, + /// The status last read, sent or not. + last: Option, + /// Set once a terminal status is read. Nothing follows it. + done: bool, + /// False until the first read. Every later read waits for a wake first. + primed: bool, + } + stream::unfold( + Follow { + wake, + only_on_status, + read, + last: None, + done: false, + primed: false, + }, + |mut follow| async move { + loop { + if follow.done { + return None; + } + if follow.primed && follow.wake.changed().await.is_err() { + return None; + } + follow.primed = true; + let (status, terminal) = match (follow.read)().await { + Ok(Some(found)) => found, + Ok(None) => return None, + Err(e) => { + tracing::error!(error = %e, "ci: live stream could not read the status"); + return None; + } + }; + follow.done = terminal; + let changed = follow.last.as_deref() != Some(status.as_str()); + let send = changed || !follow.only_on_status; + follow.last = Some(status.clone()); + if send { + return Some((changed_event(status), follow)); + } + } + }, + ) +} + +/// The response of an event stream for a CI page: keep-alive comments while idle, and no buffering +/// by a reverse proxy. +pub(crate) fn events_response( + cx: &Cx, + events: impl Stream> + Send + 'static, +) -> Result { + let events = Sse::new(events).keep_alive( + KeepAlive::new() + .interval(STREAM_KEEP_ALIVE) + .text("keepalive"), + ); + let mut res = events.into_response(cx)?; + res.headers_mut() + .insert("x-accel-buffering", HeaderValue::from_static("no")); + Ok(res) +} + +/// The run page body: the header, the buttons for writers, the config error, and the jobs. A run +/// that is not finished carries `live`, the URL of its event stream. #[component] async fn run_body( head: RepoHead, @@ -553,13 +701,11 @@ async fn run_body( run: RunView, jobs: Vec, writer_csrf: Option, - refresh: bool, + live: Option, ) -> Result { Ok(view! { repo_head(head: head) - if refresh { - - } +
if let Some((text, is_error)) = notice { if is_error { alert(message: text) @@ -625,6 +771,7 @@ async fn run_body(
}
+ }) } @@ -657,7 +804,8 @@ async fn run_page(cx: &Cx) -> Result { .collect(); let title = title_of(&ctx); let rows = job_rows(&title, &jobs, &runners, lang); - let refresh = !run_finished(&run.state) && run.state != RunState::WaitingApproval; + let live = + (!run_finished(&run.state)).then(|| format!("{}/events", run_href(&title, run.number))); let notice = notice_from_query(cx, lang); let header = run_view(state, &ctx, &run, writer, lang).await?; let head = ctx.head(state, "ci").await?; @@ -665,10 +813,32 @@ async fn run_page(cx: &Cx) -> Result { Ok(view! { shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), run_body(head: head, lang: lang, notice: notice, run: header, jobs: rows, - writer_csrf: writer_csrf, refresh: refresh)) + writer_csrf: writer_csrf, live: live)) }) } +/// The live `changed` stream of a run that is not finished. It is sent on every change to the run +/// or to one of its jobs, so the page can render its rows again. +#[route(GET "/{owner}/{repo}/ci/runs/{run_number}/events")] +async fn run_events(cx: &Cx) -> Result { + let owner = path_param::(cx); + let name = path_param::(cx); + let number = path_param::(cx).to_owned(); + let ctx = load_repo(cx, owner, name).await?; + let state = app_context::(cx); + let run = run_of(state, &ctx, &number).await?; + // Subscribed before the status is read, so a change in between is sent. + let wake = state.ci_live.subscribe_run(&run.id); + let store = state.store.clone(); + let run_id = run.id.clone(); + let events = changed_stream(wake, false, move || { + let store = store.clone(); + let run_id = run_id.clone(); + async move { run_status(&store, &run_id).await } + }); + events_response(cx, events) +} + /// Cancels a run that has not finished. Queued and blocked jobs are cancelled at once; running jobs /// get a cancel request that their runner sees on its next heartbeat. #[route(POST "/{owner}/{repo}/ci/runs/{run_number}/cancel")] diff --git a/crates/forge-web/src/pages/ci_tests.rs b/crates/forge-web/src/pages/ci_tests.rs index 83a88f9..d5b04f1 100644 --- a/crates/forge-web/src/pages/ci_tests.rs +++ b/crates/forge-web/src/pages/ci_tests.rs @@ -1,7 +1,10 @@ //! Route tests for the CI run and job pages. The fixture: tahinli owns the private repo `proj`, bob //! has Write, dave has Read, and carol is outside the repo. +use std::io::Write; use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; use forge_core::ci::{CiJob, CiRun, JobState, NewJob, RunState}; use forge_core::{Role, Store, Visibility}; @@ -11,7 +14,7 @@ use topcoat::router::{Body, HeaderMap, Router, to_bytes}; use crate::auth::SESSION_COOKIE; use crate::blobs::BlobStore; -use crate::ci::{artifact_key, log_path}; +use crate::ci::{CiLive, artifact_key, log_path}; use crate::test_support::{app_router, create_session, test_state}; const CSRF: &str = "ci-test-csrf"; @@ -22,6 +25,7 @@ const RUN_BASE: &str = "/tahinli/proj/ci"; struct Fixture { store: Store, app: Router, + live: Arc, repo: forge_core::Repo, tahinli: String, data_dir: PathBuf, @@ -69,9 +73,11 @@ async fn fixture(dir: &Path) -> Fixture { create_session(&store, &carol.id, "carol-token", CSRF).await; let data_dir = state.config.data_dir.clone(); let blobs = state.blobs.clone(); + let live = Arc::clone(&state.ci_live); Fixture { store, app: app_router(state), + live, repo, tahinli: tahinli.id, data_dir, @@ -300,23 +306,300 @@ async fn run_list_pages_25_at_a_time() { ); } +/// The pages no longer reload themselves. A page that is not finished carries its live marker, and +/// a finished one carries none. #[tokio::test] -async fn meta_refresh_only_while_the_job_is_not_terminal() { +async fn pages_are_live_while_not_finished_and_never_meta_refresh() { let dir = tempfile::tempdir().expect("tempdir"); let fx = fixture(dir.path()).await; let run = run_with(&fx, &["build"], false).await; let job = job_of(&fx, &run).await; let url = format!("/tahinli/proj/ci/jobs/{}", job.id); + let run_url = format!("{RUN_BASE}/runs/{}", run.number); + let job_marker = format!("data-live=\"{url}/events\""); + let run_marker = format!("data-live=\"{run_url}/events\""); + let queued = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await; + assert!(queued.text().contains(&job_marker), "job live while queued"); + let run_page = get(&fx.app, &run_url, Some(&cookie_for("tahinli-token"))).await; assert!( - queued.text().contains("http-equiv=\"refresh\""), - "refresh while queued" + run_page.text().contains(&run_marker), + "run live while queued" ); + for page in [&queued, &run_page] { + assert!( + !page.text().contains("http-equiv=\"refresh\""), + "no meta refresh" + ); + } + finish_job(&fx).await; let done = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await; + assert!( + !done.text().contains("data-live="), + "job not live when finished" + ); assert!( !done.text().contains("http-equiv=\"refresh\""), - "no refresh when finished" + "no meta refresh" + ); +} + +/// Opens an event stream without reading it. The response head carries the status. +async fn open( + app: &Router, + uri: &str, + cookie: Option<&str>, +) -> topcoat::router::response::Response { + let mut builder = Request::builder().method("GET").uri(uri); + if let Some(cookie) = cookie { + builder = builder.header("cookie", cookie); + } + app.handle(builder.body(Body::from(String::new())).expect("request")) + .await +} + +/// The next frame of an event stream, or None once the stream has ended. Fails after five seconds. +async fn next_event(frames: &mut S) -> Option> +where + S: futures_util::Stream> + Unpin, + E: std::fmt::Debug, +{ + use futures_util::StreamExt; + + let frame = tokio::time::timeout(Duration::from_secs(5), frames.next()) + .await + .expect("an event within five seconds")?; + Some(frame.expect("data").to_vec()) +} + +#[tokio::test] +async fn live_events_need_the_same_access_as_the_page() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let urls = [ + format!("{RUN_BASE}/runs/{}/events", run.number), + format!("/tahinli/proj/ci/jobs/{}/events", job.id), + ]; + for url in &urls { + let anon = open(&fx.app, url, None).await; + assert_eq!(anon.status().as_u16(), 404, "anonymous {url}"); + let outsider = open(&fx.app, url, Some(&cookie_for("carol-token"))).await; + assert_eq!(outsider.status().as_u16(), 404, "outsider {url}"); + let reader = open(&fx.app, url, Some(&cookie_for("dave-token"))).await; + assert_eq!(reader.status().as_u16(), 200, "reader {url}"); + } +} + +/// Each stream opens with its status. The run stream follows every bump; the job stream sends only +/// status changes, so a log append is silent, and it ends once the job is terminal. +#[tokio::test] +async fn live_events_open_with_the_status_and_follow_changes() { + use futures_util::StreamExt; + + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let tahinli = cookie_for("tahinli-token"); + + let mut run_frames = open( + &fx.app, + &format!("{RUN_BASE}/runs/{}/events", run.number), + Some(&tahinli), + ) + .await + .into_body() + .into_data_stream(); + let first = next_event(&mut run_frames).await.expect("the run status"); + assert_eq!( + first, + format!("event: changed\ndata: {}\n\n", run.state.as_str()).into_bytes() + ); + + let mut job_frames = open( + &fx.app, + &format!("/tahinli/proj/ci/jobs/{}/events", job.id), + Some(&tahinli), + ) + .await + .into_body() + .into_data_stream(); + let first = next_event(&mut job_frames).await.expect("the job status"); + assert_eq!( + first, + format!("event: changed\ndata: {}\n\n", job.state.as_str()).into_bytes() + ); + + // A bump with no new log bytes and no status change sends nothing. + fx.live.bump_job(&job.id); + let quiet = tokio::time::timeout(Duration::from_millis(200), job_frames.next()).await; + assert!(quiet.is_err(), "a log append sends no status event"); + + // The run stream sends its status on every bump of the run. + fx.live.bump_run(&run.id); + let bumped = next_event(&mut run_frames).await.expect("the run status"); + let now = fx + .store + .run_by_id(&run.id) + .await + .expect("run") + .expect("run"); + assert_eq!( + bumped, + format!("event: changed\ndata: {}\n\n", now.state.as_str()).into_bytes() + ); + + // The job finishes: its final status is sent, then the stream ends. + finish_job(&fx).await; + fx.live.close_job(&job.id); + let last = next_event(&mut job_frames).await.expect("the final status"); + assert_eq!( + last, + format!("event: changed\ndata: {}\n\n", JobState::Success.as_str()).into_bytes() + ); + assert!(next_event(&mut job_frames).await.is_none(), "stream ends"); +} + +/// The job's log events: each append is sent as a `log` event with its bytes, the id is the offset +/// past them, and the bytes before `?from=` are not sent again. +#[tokio::test] +async fn job_events_send_each_log_append_as_a_log_event() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let path = log_path(&fx.data_dir, &job.id); + std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); + std::fs::write(&path, b"one\n").expect("log"); + + let mut frames = open( + &fx.app, + &format!("/tahinli/proj/ci/jobs/{}/events?from=4", job.id), + Some(&cookie_for("tahinli-token")), + ) + .await + .into_body() + .into_data_stream(); + let first = next_event(&mut frames).await.expect("the status"); + assert_eq!( + first, + format!("event: changed\ndata: {}\n\n", job.state.as_str()).into_bytes() + ); + + let mut file = std::fs::OpenOptions::new() + .append(true) + .open(&path) + .expect("log"); + file.write_all(b"two\nthree\n").expect("append"); + fx.live.bump_job(&job.id); + let log = next_event(&mut frames).await.expect("the log event"); + assert_eq!( + log, + b"event: log\ndata: two\ndata: three\ndata: \nid: 14\n\n".to_vec() + ); +} + +/// An append longer than 64 KiB is sent in several `log` events, in order. +#[tokio::test] +async fn job_events_split_a_long_append_into_64_kib_events() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let path = log_path(&fx.data_dir, &job.id); + std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); + std::fs::write(&path, b"").expect("log"); + + let mut frames = open( + &fx.app, + &format!("/tahinli/proj/ci/jobs/{}/events", job.id), + Some(&cookie_for("tahinli-token")), + ) + .await + .into_body() + .into_data_stream(); + next_event(&mut frames).await.expect("the status"); + + let long = "a".repeat(150 * 1024); + let mut file = std::fs::OpenOptions::new() + .append(true) + .open(&path) + .expect("log"); + file.write_all(long.as_bytes()).expect("append"); + fx.live.bump_job(&job.id); + + let mut sizes = Vec::new(); + for _ in 0..3 { + let frame = next_event(&mut frames).await.expect("a log event"); + let text = String::from_utf8(frame).expect("text"); + assert!(text.starts_with("event: log\n"), "{text}"); + let data = text + .lines() + .find_map(|line| line.strip_prefix("data: ")) + .expect("data line"); + sizes.push(data.len()); + if sizes.len() == 3 { + assert!( + text.contains("id: 153600\n"), + "the last id is the end offset" + ); + } + } + assert_eq!(sizes, vec![64 * 1024, 64 * 1024, 150 * 1024 - 128 * 1024]); +} + +/// A reconnect sends `Last-Event-ID`, and the stream resumes after that offset, not at `?from=`. +#[tokio::test] +async fn job_events_resume_after_the_last_event_id() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let path = log_path(&fx.data_dir, &job.id); + std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); + std::fs::write(&path, b"one\ntwo\n").expect("log"); + + let request = Request::builder() + .method("GET") + .uri(format!("/tahinli/proj/ci/jobs/{}/events?from=0", job.id)) + .header("cookie", cookie_for("tahinli-token")) + .header("last-event-id", "4") + .body(Body::from(String::new())) + .expect("request"); + let mut frames = fx.app.handle(request).await.into_body().into_data_stream(); + next_event(&mut frames).await.expect("the status"); + let log = next_event(&mut frames).await.expect("the log event"); + assert_eq!(log, b"event: log\ndata: two\ndata: \nid: 8\n\n".to_vec()); +} + +/// The job page's log tail says where its text ends, so the events stream starts from there. +#[tokio::test] +async fn job_page_tail_carries_its_offset() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let path = log_path(&fx.data_dir, &job.id); + std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); + std::fs::write(&path, b"one\ntwo\n").expect("log"); + + let page = get( + &fx.app, + &format!("/tahinli/proj/ci/jobs/{}", job.id), + Some(&cookie_for("tahinli-token")), + ) + .await; + let text = page.text(); + assert!( + text.contains("data-live-log=\"true\" data-offset=\"8\""), + "tail offset" + ); + assert!( + text.contains(&format!("data-live-state=\"{}\"", job.state.as_str())), + "rendered status" ); } @@ -384,6 +667,67 @@ async fn log_txt_is_the_full_file_for_a_finished_job() { ); } +/// The next chunk a follower sends. Fails the test when none comes within five seconds. +async fn next_chunk( + chunks: &mut tokio::sync::mpsc::UnboundedReceiver, +) -> Option { + tokio::time::timeout(Duration::from_secs(5), chunks.recv()) + .await + .expect("a chunk within five seconds") +} + +/// A follower sends each append as soon as the job's signal is bumped. The wait is far longer +/// than the timeouts here, so a chunk that arrives in time was woken by the bump, not by a timer. +#[tokio::test] +async fn log_follower_is_woken_by_bumps_and_ends_on_close() { + use futures_util::StreamExt; + + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let path = log_path(&fx.data_dir, &job.id); + std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); + std::fs::write(&path, b"one\n").expect("log"); + let live = Arc::new(CiLive::default()); + let mut stream = Box::pin(super::ci_job::follow_log( + fx.store.clone(), + Arc::clone(&live), + job.id.clone(), + path.clone(), + )); + let (tx, mut chunks) = tokio::sync::mpsc::unbounded_channel(); + tokio::spawn(async move { + while let Some(Ok(chunk)) = stream.next().await { + if tx.send(chunk).is_err() { + break; + } + } + }); + assert_eq!( + next_chunk(&mut chunks).await.as_deref(), + Some(&b"one\n"[..]) + ); + + let mut file = std::fs::OpenOptions::new() + .append(true) + .open(&path) + .expect("log"); + file.write_all(b"two\n").expect("append"); + live.bump_job(&job.id); + assert_eq!( + next_chunk(&mut chunks).await.as_deref(), + Some(&b"two\n"[..]) + ); + + finish_job(&fx).await; + live.close_job(&job.id); + let end = tokio::time::timeout(Duration::from_secs(5), chunks.recv()) + .await + .expect("the stream ends once the job is terminal"); + assert!(end.is_none()); +} + #[tokio::test] async fn artifact_download_sends_attachment_headers() { let dir = tempfile::tempdir().expect("tempdir"); @@ -579,3 +923,75 @@ async fn manual_run_refuses_an_unknown_branch() { .await; assert_eq!(reader.status, 403, "reader cannot start a manual run"); } + +#[tokio::test] +async fn badge_follows_read_access_and_reports_the_latest_run() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let open = fx + .store + .create_repo(&fx.tahinli, "open", "", Visibility::Public, "main") + .await + .expect("public repo"); + let svg_path = "/tahinli/proj/badge.svg"; + + // The private repo: a run exists, but only readers see its badge. + run_with(&fx, &["build"], false).await; + finish_job(&fx).await; + assert_eq!(get(&fx.app, svg_path, None).await.status, 404, "anonymous"); + let outsider = get(&fx.app, svg_path, Some(&cookie_for("carol-token"))).await; + assert_eq!(outsider.status, 404, "outsider"); + let reader = get(&fx.app, svg_path, Some(&cookie_for("dave-token"))).await; + assert_eq!(reader.status, 200, "reader"); + assert!(reader.text().contains("passing")); + assert_eq!( + reader + .headers + .get("content-type") + .and_then(|v| v.to_str().ok()), + Some("image/svg+xml") + ); + assert_eq!( + reader + .headers + .get("cache-control") + .and_then(|v| v.to_str().ok()), + Some("no-cache, max-age=0") + ); + + // The public repo: anyone sees the badge. Unknown branches and jobs have no status. + let needs: &[String] = &[]; + let specs = [NewJob { + name: "build", + spec_json: SPEC, + needs, + }]; + fx.store + .create_run( + &open.id, + "push", + "refs/heads/main", + SHA, + None, + &fx.tahinli, + false, + &specs, + None, + ) + .await + .expect("run"); + finish_job(&fx).await; + let anon = get(&fx.app, "/tahinli/open/badge.svg", None).await; + assert_eq!(anon.status, 200); + assert!(anon.text().contains(">passing")); + let unknown = get(&fx.app, "/tahinli/open/badge.svg?branch=nope", None).await; + assert_eq!(unknown.status, 200); + assert!(unknown.text().contains(">no status")); + let job = get(&fx.app, "/tahinli/open/badge.svg?job=build", None).await; + assert!(job.text().contains(">build")); + assert!(job.text().contains(">passing")); + let missing_job = get(&fx.app, "/tahinli/open/badge.svg?job=lint", None).await; + assert!(missing_job.text().contains(">no status")); + let unknown_repo = get(&fx.app, "/tahinli/nothere/badge.svg", None).await; + assert_eq!(unknown_repo.status, 404); +} diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index 742c95f..5aa4d4b 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -10,6 +10,7 @@ pub mod assets; pub mod audit_log; pub mod avatars; pub mod blob; +pub mod ci_badge; pub mod ci_job; pub mod ci_runs; #[cfg(test)] diff --git a/crates/forge-web/src/pages/notifications.rs b/crates/forge-web/src/pages/notifications.rs index a7534bd..f10cd29 100644 --- a/crates/forge-web/src/pages/notifications.rs +++ b/crates/forge-web/src/pages/notifications.rs @@ -5,23 +5,28 @@ //! The sidebar box and the watch form are shared with the issue, pull and repo header views. use std::collections::HashMap; +use std::time::Duration; use forge_core::authz::{Action, authorize}; use forge_core::discussions::{DiscussionNotification, DiscussionReason}; use forge_core::store::advisories::AdvisoryNotice; use forge_core::store::transfers::PendingTransfer; use forge_core::{Notification, Reason, Role, SubState, User, WatchLevel}; +use futures_util::{StreamExt, future, stream}; use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; +use topcoat::router::content::sse::{Event, KeepAlive, Sse}; use topcoat::router::error::{SeeOther, bad_request, not_found, see_other}; -use topcoat::router::{page, path_param, query_params, route}; +use topcoat::router::response::{IntoResponse, Response}; +use topcoat::router::{Body, HeaderValue, StatusCode, page, path_param, query_params, route}; use topcoat::view::{View, component, view}; -use crate::auth::{percent_encode, require_csrf, require_user}; +use crate::auth::{current_user, percent_encode, require_csrf, require_user}; use crate::i18n::misc::{self as g, K}; use crate::i18n::{self, Key, Lang}; +use crate::notify_hub::publish_unread; use crate::pages::issue_parts::{parse_number, stamp_unix}; use crate::pages::repo_ctx::{RepoCtx, load_repo}; use crate::pages::repo_transfer::transfer_list_for; @@ -363,6 +368,9 @@ async fn inbox(cx: &Cx) -> Result { } } + if !hidden.is_empty() { + publish_unread(state, &user.id).await; + } 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(); @@ -384,6 +392,7 @@ async fn open_notification(cx: &Cx) -> Result { return Err(not_found().into()); }; state.store.mark_read(&user.id, id).await?; + publish_unread(state, &user.id).await; if !can_read(state, &user, &target.repo_id).await? { return Err(not_found().into()); } @@ -411,6 +420,7 @@ async fn open_discussion_notification(cx: &Cx) -> Result { .store .mark_discussion_notification_read(&user.id, id) .await?; + publish_unread(state, &user.id).await; if !can_read(state, &user, ¬e.repo_id).await? { return Err(not_found().into()); } @@ -433,6 +443,7 @@ async fn read_discussion_notification(cx: &Cx, Form(form): Form) -> Re .store .mark_discussion_notification_read(&user.id, id) .await?; + publish_unread(state, &user.id).await; Ok(see_other(back(cx))) } @@ -450,6 +461,7 @@ async fn open_advisory_notification(cx: &Cx) -> Result { .store .mark_advisory_notification_read(&user.id, repo_id) .await?; + publish_unread(state, &user.id).await; if !can_manage_alerts(state, &user, repo_id).await? { return Err(not_found().into()); } @@ -471,6 +483,7 @@ async fn read_advisory_notification(cx: &Cx, Form(form): Form) -> Resu .store .mark_advisory_notification_read(&user.id, repo_id) .await?; + publish_unread(state, &user.id).await; Ok(see_other(back(cx))) } @@ -481,6 +494,7 @@ async fn read_notification(cx: &Cx, Form(form): Form) -> Result(cx); let id = path_param::(cx); state.store.mark_read(&user.id, id).await?; + publish_unread(state, &user.id).await; Ok(see_other(back(cx))) } @@ -500,9 +514,50 @@ async fn mark_all_read(cx: &Cx, Form(form): Form) -> Result .store .mark_all_advisory_notifications_read(&user.id, repo_id) .await?; + publish_unread(state, &user.id).await; Ok(see_other(back(cx))) } +/// How often an idle stream sends a `: keepalive` comment, so a reverse proxy does not drop the +/// connection. This is the only timer in the feature: counts are pushed as they change. +const STREAM_KEEP_ALIVE: Duration = Duration::from_secs(30); + +/// One `unread` event carrying the count. +fn unread_event(count: u64) -> topcoat::Result { + Ok(Event::new().event("unread").data(count.to_string())) +} + +/// The bell's live count. Sends an `unread` event with the viewer's unread count now, then one +/// after each change to the inbox, until the viewer disconnects or the server shuts down. An +/// anonymous viewer gets a bare 401: an event stream has no login page to redirect to. +#[route(GET "/notifications/stream")] +async fn notification_stream(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); + let subscription = state.notify_hub.subscribe(&user.id); + // Read after subscribing: a change that lands in between is pushed again, never missed. + let count = state.store.unread_count(&user.id).await?; + let first = stream::once(future::ready(unread_event(count))); + let changes = stream::unfold(subscription, |mut sub| async move { + let count = sub.next_count().await?; + Some((unread_event(count), sub)) + }); + let events = Sse::new(first.chain(changes)).keep_alive( + KeepAlive::new() + .interval(STREAM_KEEP_ALIVE) + .text("keepalive"), + ); + let mut res = events.into_response(cx)?; + // Nginx buffers a proxied response unless told not to, which would hold the events back. + res.headers_mut() + .insert("x-accel-buffering", HeaderValue::from_static("no")); + Ok(res) +} + /// Subscribes or unsubscribes the viewer from an issue. #[route(POST "/{owner}/{repo}/issues/{number}/subscription")] async fn issue_subscription(cx: &Cx, Form(form): Form) -> Result { @@ -624,6 +679,7 @@ pub(crate) async fn notify_box_for( return Ok(None); }; state.store.mark_issue_read(&user.id, issue_id).await?; + publish_unread(state, &user.id).await; let level = state.store.watch_level(&user.id, &ctx.repo.id).await?; let subscription = state.store.subscription(&user.id, issue_id).await?; let (subscribed, reason) = if level == WatchLevel::Ignoring { @@ -805,7 +861,9 @@ pub(crate) async fn notify_box( }) } -/// The Watch control in the repo header: a level select and a submit button, plus the count. +/// The Watch control in the repo header: a dropdown whose summary shows the current level, one +/// POST form per level inside it (the current one marked), and the watcher count. The forms post +/// without JavaScript; nav.js submits them in place and closes the menu. #[component] pub(crate) async fn watch_form( lang: Lang, @@ -815,38 +873,69 @@ pub(crate) async fn watch_form( watchers: u64, ) -> Result { let count = g::watchers_count(lang, watchers); + let current = match level { + "watching" => g::t(lang, K::OptWatching), + "ignoring" => g::t(lang, K::OptIgnoring), + _ => g::t(lang, K::OptParticipating), + }; + let class = |value: &str| -> &'static str { + if level == value { + "watch-option is-current" + } else { + "watch-option" + } + }; + let (cls_participating, cls_watching, cls_ignoring) = + (class("participating"), class("watching"), class("ignoring")); Ok(view! { -
- csrf_field(token: csrf.as_str()) - - +
+ (count.as_str()) - +
}) } #[cfg(test)] mod tests { use forge_core::{Issue, Reason, Role, Store, SubState, Visibility, WatchLevel}; + use futures_util::StreamExt; use topcoat::router::request::Request; use topcoat::router::{Body, Router, to_bytes}; @@ -1083,6 +1172,45 @@ mod tests { assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 0); } + #[tokio::test] + async fn the_stream_needs_a_session() { + let site = site().await; + let res = get(&site, "/notifications/stream", None).await; + assert_eq!(res.status, 401); + } + + #[tokio::test] + async fn the_stream_sends_the_count_then_each_change() { + let site = site().await; + let w = world(&site, Visibility::Public).await; + let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await; + notify(&site, &w, Reason::Mention).await; + + let request = Request::builder() + .method("GET") + .uri("/notifications/stream") + .header("cookie", cookie.as_str()) + .body(Body::empty()) + .expect("request"); + let res = site.router.handle(request).await; + assert_eq!(res.status().as_u16(), 200); + assert_eq!( + res.headers().get("content-type").unwrap(), + "text/event-stream" + ); + assert_eq!(res.headers().get("x-accel-buffering").unwrap(), "no"); + + let mut frames = res.into_body().into_data_stream(); + let first = frames.next().await.expect("a frame").expect("data"); + assert_eq!(&first[..], b"event: unread\ndata: 1\n\n"); + + // Marking the row read pushes the new count to the open stream. + let read = post(&site, "/notifications/mark_all_read", &cookie, "").await; + assert_eq!(read.status, 303); + let next = frames.next().await.expect("a frame").expect("data"); + assert_eq!(&next[..], b"event: unread\ndata: 0\n\n"); + } + #[tokio::test] async fn header_bell_shows_the_unread_count() { let site = site().await; @@ -1172,11 +1300,18 @@ mod tests { let header = get(&site, "/tahinli/demo/issues/1", Some(&cookie)).await; assert!(header.body.contains("action=\"/tahinli/demo/watch\"")); - assert!( + assert!(header.body.contains("
")); + assert!(!header.body.contains("") + .matches("class=\"watch-option is-current\"") + .count(), + 1 ); + assert_eq!(header.body.matches("class=\"watch-option\"").count(), 2); assert!(header.body.contains("1 watching")); let bad = post(&site, "/tahinli/demo/watch", &cookie, "&level=loud").await; diff --git a/crates/forge-web/src/views/mod.rs b/crates/forge-web/src/views/mod.rs index 801d2de..a695322 100644 --- a/crates/forge-web/src/views/mod.rs +++ b/crates/forge-web/src/views/mod.rs @@ -262,7 +262,8 @@ pub async fn shell(