forge
Explore
Log in

Don't you dare go Hollow

Everything live-updates: server settings and the banner, repo header counts and switches, labels, milestones, review requests, pull timeline, runner online state, health, CI artifacts and purges, and admin CLI writes

Browse files at this commit

374e72194e656b81a7ece3889a901937daef7a0fAhmet Kaan GümüşParent: 24b6025
All checks have passed
Show checks
  • feat
    • everything live-updates: server settings and the banner, repo header counts and switches, labels, milestones, review requests, pull timeline, runner online state, health, CI artifacts and purges, and admin CLI writes
    • small-range settings and required approvals use the stepper
Show full message
✨ feat: everything live-updates: server settings and the banner, repo header counts and switches, labels, milestones, review requests, pull timeline, runner online state, health, CI artifacts and purges, and admin CLI writes; small-range settings and required approvals use the stepper

53 changed files +1314 -220

crates/forge-core/src/store/ci.rsmodified+47 -14
@@ -738,6 +738,19 @@ impl Store {
738738 Ok(true)
739739 }
740740
741+ /// Whether the runner is disabled. `false` when the runner is gone. A primary-key read.
742+ pub async fn runner_disabled(&self, id: &str) -> Result<bool> {
743+ let conn = self.read_conn().await;
744+ let found = fetch_opt(
745+ &conn,
746+ "SELECT disabled FROM ci_runners WHERE id = ?1",
747+ (id.to_string(),),
748+ |row| col_bool(row, 0),
749+ )
750+ .await?;
751+ Ok(found.unwrap_or(false))
752+ }
753+
741754 /// The runner's concurrency override, read fresh. `None` when unset or the runner is gone.
742755 pub async fn runner_concurrency_override(&self, id: &str) -> Result<Option<u32>> {
743756 let conn = self.read_conn().await;
@@ -1641,26 +1654,38 @@ impl Store {
16411654 /// but the newest `keep_runs` runs that have artifacts are deleted (0 keeps all). Then, if
16421655 /// `max_total_bytes` is non-zero and the artifacts left still exceed it, the artifacts of the
16431656 /// oldest runs are deleted a whole run at a time until the total fits. Artifact ids are
1644- /// returned (deduplicated) so the caller deletes the files.
1657+ /// returned (deduplicated) so the caller deletes the files. Run ids are returned too (the runs
1658+ /// whose logs or artifacts went), so the pages showing them can be woken.
16451659 pub async fn purge_old(
16461660 &self,
16471661 logs_before: &str,
16481662 artifacts_before: &str,
16491663 keep_runs: u32,
16501664 max_total_bytes: u64,
1651- ) -> Result<(Vec<String>, Vec<String>)> {
1665+ ) -> Result<(Vec<String>, Vec<String>, Vec<String>)> {
16521666 let conn = self.inner.conn.lock().await;
16531667 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
1654- let outcome: Result<(Vec<String>, Vec<String>)> = async {
1655- let job_ids = fetch_all(
1668+ let outcome: Result<(Vec<String>, Vec<String>, Vec<String>)> = async {
1669+ // Which run owns each artifact, read before the rows go.
1670+ let owners: BTreeMap<String, String> = fetch_all(
16561671 &tx,
1657- "SELECT j.id FROM ci_jobs j JOIN ci_runs r ON r.id = j.run_id \
1672+ "SELECT a.id, j.run_id FROM ci_artifacts a JOIN ci_jobs j ON j.id = a.job_id",
1673+ (),
1674+ |row| Ok((col_text(row, 0)?, col_text(row, 1)?)),
1675+ )
1676+ .await?
1677+ .into_iter()
1678+ .collect();
1679+ let log_jobs = fetch_all(
1680+ &tx,
1681+ "SELECT j.id, j.run_id FROM ci_jobs j JOIN ci_runs r ON r.id = j.run_id \
16581682 WHERE r.finished_at IS NOT NULL AND r.finished_at < ?1 AND j.log_bytes > 0 \
16591683 ORDER BY j.id",
16601684 (logs_before.to_string(),),
1661- |row| col_text(row, 0),
1685+ |row| Ok((col_text(row, 0)?, col_text(row, 1)?)),
16621686 )
16631687 .await?;
1688+ let job_ids: Vec<String> = log_jobs.iter().map(|(id, _)| id.clone()).collect();
16641689 for id in &job_ids {
16651690 tx.execute(
16661691 "UPDATE ci_jobs SET log_bytes = 0 WHERE id = ?1",
@@ -1738,7 +1763,14 @@ impl Store {
17381763
17391764 artifact_ids.sort();
17401765 artifact_ids.dedup();
1741- Ok((job_ids, artifact_ids))
1766+ let mut run_ids: Vec<String> = log_jobs
1767+ .into_iter()
1768+ .map(|(_, run)| run)
1769+ .chain(artifact_ids.iter().filter_map(|id| owners.get(id).cloned()))
1770+ .collect();
1771+ run_ids.sort();
1772+ run_ids.dedup();
1773+ Ok((job_ids, artifact_ids, run_ids))
17421774 }
17431775 .await;
17441776 finish(tx, outcome).await
@@ -3278,11 +3310,12 @@ mod tests {
32783310
32793311 assert_eq!(
32803312 fx.store.purge_old(DAWN, DAWN, 0, 0).await.unwrap(),
3281- (vec![], vec![])
3313+ (vec![], vec![], vec![])
32823314 );
3283- let (logs, artifacts) = fx.store.purge_old(&later, &later, 0, 0).await.unwrap();
3315+ let (logs, artifacts, runs) = fx.store.purge_old(&later, &later, 0, 0).await.unwrap();
32843316 assert_eq!(logs, vec![a.id.clone()]);
32853317 assert_eq!(artifacts.len(), 1);
3318+ assert_eq!(runs, vec![run.id.clone()]);
32863319 assert_eq!(job_named(&fx.store, &run.id, "a").await.log_bytes, 0);
32873320 assert!(
32883321 fx.store
@@ -3291,8 +3324,8 @@ mod tests {
32913324 .unwrap()
32923325 .is_none()
32933326 );
3294- let (logs2, artifacts2) = fx.store.purge_old(&later, &later, 0, 0).await.unwrap();
3295- assert!(logs2.is_empty() && artifacts2.is_empty());
3327+ let (logs2, artifacts2, runs2) = fx.store.purge_old(&later, &later, 0, 0).await.unwrap();
3328+ assert!(logs2.is_empty() && artifacts2.is_empty() && runs2.is_empty());
32963329 }
32973330
32983331 #[tokio::test]
@@ -3319,12 +3352,12 @@ mod tests {
33193352 tokio::time::sleep(Duration::from_millis(2)).await;
33203353 }
33213354 // Keep the newest two runs: the oldest run's artifact goes.
3322- let (_, deleted) = fx.store.purge_old(DAWN, DAWN, 2, 0).await.unwrap();
3355+ let (_, deleted, _) = fx.store.purge_old(DAWN, DAWN, 2, 0).await.unwrap();
33233356 assert_eq!(deleted, vec![artifacts[0].clone()]);
33243357 // 20 + 30 bytes left against a 35 byte limit: the older run (20 bytes) goes.
3325- let (_, deleted) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap();
3358+ let (_, deleted, _) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap();
33263359 assert_eq!(deleted, vec![artifacts[1].clone()]);
3327- let (_, again) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap();
3360+ let (_, again, _) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap();
33283361 assert!(again.is_empty());
33293362 }
33303363
crates/forge-core/src/store/health.rsmodified+12 -1
@@ -2,11 +2,22 @@
22
33 use super::{Store, col_int, fetch_opt};
44 use crate::error::{Error, Result};
5-use crate::time::stamp_ago;
5+use crate::time::{stamp_ago, stamp_to_unix};
66
77 /// Window in which a runner's last report counts as online.
88 pub const RUNNER_ONLINE_SECS: u64 = 90;
99
10+/// Whether a runner counts as online at `now_unix`: enabled, and its last report within
11+/// [`RUNNER_ONLINE_SECS`]. The runners page dot and the live signal of the runners page both use
12+/// this one rule.
13+pub fn runner_is_online(disabled: bool, last_seen_at: Option<&str>, now_unix: i64) -> bool {
14+ let limit = i64::try_from(RUNNER_ONLINE_SECS).unwrap_or(i64::MAX);
15+ !disabled
16+ && last_seen_at
17+ .and_then(stamp_to_unix)
18+ .is_some_and(|seen| now_unix.saturating_sub(seen) <= limit)
19+}
20+
1021 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1122 pub struct HealthCounts {
1223 pub repos: i64,
crates/forge-web/assets/nav.jsmodified+45 -12
@@ -174,6 +174,7 @@
174174 syncPush();
175175 syncTick();
176176 syncRel();
177+ syncBannerExpiry();
177178 }
178179
179180 // The log tail is a terminal: it opens at its end. A reader who scrolls up keeps their place.
@@ -550,7 +551,11 @@
550551 if (window.EventSource) {
551552 alive = keepOpen('/-/alive', aliveOpen, aliveDown, {
552553 theme: applyAppearance,
553- language: function () { refreshLive(true); }
554+ language: function () { refreshLive(true); },
555+ // The header's identity (username, avatar, admin rights) or the session changed: the page re-renders.
556+ account: function () { refreshLive(true); },
557+ // A live server setting changed (the banner, registration, limits...): the page re-renders.
558+ settings: function () { refreshLive(true); }
554559 });
555560 document.addEventListener('visibilitychange', function () { wake(false); });
556561 document.addEventListener('resume', function () { wake(true); });
@@ -768,7 +773,9 @@
768773 document.addEventListener('click', function (e) {
769774 var btn = e.target && e.target.closest ? e.target.closest('[data-step]') : null;
770775 if (!btn || !btn.form) { return; }
771- var field = btn.form.querySelector('input[type="number"]');
776+ // The pill's own field first: a form can hold several number fields (the server settings).
777+ var pill = btn.closest('.runner-pill');
778+ var field = (pill && pill.querySelector('input[type="number"]')) || btn.form.querySelector('input[type="number"]');
772779 if (!field) { return; }
773780 var next = (parseFloat(field.value) || 0) + (parseFloat(btn.getAttribute('data-step')) || 0);
774781 var min = parseFloat(field.min);
@@ -1099,19 +1106,18 @@
10991106 // Live unread count. The bell is re-rendered by every swap, so it is looked up on each update. One
11001107 // EventSource serves the page and stays open across swaps. It is opened only while a bell is shown
11011108 // (signed-in pages) and closed when the bell is gone. The server pushes each change; nothing polls.
1109+ // The count shows twice: on the bell, and next to Notifications in the sidebar and the phone menu.
11021110 var unreadStream = null;
11031111
11041112 function bell() { return document.querySelector('a.bell'); }
11051113
1106- // Shows the count the way the server renders it: a `.bell-count` span with the number, or no span at zero.
1107- function setUnread(n) {
1108- var el = bell();
1109- if (!el) { return; }
1110- var badge = el.querySelector('.bell-count');
1114+ // Shows the count in one link the way the server renders it: a span with the number, or no span at zero.
1115+ function setCount(el, cls, n) {
1116+ var badge = el.querySelector('.' + cls);
11111117 if (n > 0) {
11121118 if (!badge) {
11131119 badge = document.createElement('span');
1114- badge.className = 'bell-count';
1120+ badge.className = cls;
11151121 el.appendChild(badge);
11161122 }
11171123 badge.textContent = String(n);
@@ -1120,6 +1126,14 @@
11201126 }
11211127 }
11221128
1129+ function setUnread(n) {
1130+ var el = bell();
1131+ if (el) { setCount(el, 'bell-count', n); }
1132+ // The sidebar's Notifications link (the sidebar and the phone menu hold one each), `.count` as the server renders it.
1133+ var links = document.querySelectorAll('nav.side-links a[href="/notifications"]');
1134+ for (var i = 0; i < links.length; i++) { setCount(links[i], 'count', n); }
1135+ }
1136+
11231137 function syncUnread() {
11241138 if (!bell()) {
11251139 if (unreadStream) { unreadStream.close(); unreadStream = null; }
@@ -1625,14 +1639,14 @@
16251639 // with no history entry and the scroll kept. A job page also has a log tail (data-live-log) whose
16261640 // `log` events append the new bytes as they come. The stream opens at the tail's data-offset, and
16271641 // each swap brings a fresh offset, so the stream is opened again after every swap. The server ends
1628- // the stream once the status is terminal, and the swap that shows that page (no data-live) closes it.
1642+ // the stream once a run is terminal; a job's stream stays open and wakes on its own changes, and the swap that shows that page (no data-live) closes it.
16291643 // Every element with data-live names an event stream the page follows: the repo header, the
16301644 // page's own list, issue or run. One EventSource is open per distinct URL, so a page with several
16311645 // streams updates for each of them. A `changed` event re-fetches the page and swaps it in with no
16321646 // history entry and the scroll kept. A job page also has a log tail (data-live-log) whose `log`
16331647 // events append the new bytes as they come. The tail's stream opens at its data-offset, and each
16341648 // swap brings a fresh offset, so that stream is opened again after every swap. The server ends
1635- // the stream once the status is terminal, and the swap that shows that page (no data-live) closes it.
1649+ // the stream once a run is terminal; a job's stream stays open and wakes on its own changes, and the swap that shows that page (no data-live) closes it.
16361650 var liveStreams = {}; // URL (with the tail's offset) -> EventSource
16371651 var liveTimer = null; // a run list's pending refresh: bursts of events (log lines) share one
16381652
@@ -1656,7 +1670,8 @@
16561670 function openLive(url) {
16571671 var es = new EventSource(url);
16581672 es.addEventListener('changed', function (e) {
1659- // A job page's stream opens with the status the page already shows: nothing to re-render then.
1673+ // A job event carries the job's fingerprint (status|artifact ids|log), which the page renders as
1674+ // data-live-state. The same fingerprint means nothing changed: nothing to re-render then.
16601675 var job = document.querySelector('[data-live-log]');
16611676 var wrap = job ? job.closest('[data-live]') : null;
16621677 if (wrap && wrap.getAttribute('data-live-state') === e.data) { return; }
@@ -1704,7 +1719,8 @@
17041719
17051720 // A change re-renders the current page. It waits while a navigation is on the wire, since that
17061721 // response could be superseded: the change is kept and sent after that request completes.
1707- // `force` re-renders a page that holds no stream of its own (a language change, sent by /-/alive).
1722+ // `force` re-renders a page that holds no stream of its own (a language change, or a live server
1723+ // setting such as the banner, sent by /-/alive).
17081724 function refreshLive(force) {
17091725 if (!force && !Object.keys(liveStreams).length) { return; }
17101726 // A one-time secret (a token, recovery codes) is on screen only in the response that made it: a
@@ -1813,6 +1829,22 @@
18131829 }
18141830 }
18151831
1832+ // The site banner with an expiry carries `data-expires` (unix seconds). When it passes, the banner
1833+ // is removed here, so an open page does not keep one that is gone. One timer is armed for the
1834+ // banner on the page; a swap re-arms it. setTimeout takes a 32-bit delay, so a longer wait is armed
1835+ // again when this one fires.
1836+ var bannerTimer = null;
1837+
1838+ function syncBannerExpiry() {
1839+ if (bannerTimer) { clearTimeout(bannerTimer); }
1840+ bannerTimer = null;
1841+ var banner = document.querySelector('.site-banner[data-expires]');
1842+ if (!banner) { return; }
1843+ var wait = (parseInt(banner.getAttribute('data-expires'), 10) || 0) * 1000 - Date.now();
1844+ if (wait <= 0) { banner.remove(); return; }
1845+ bannerTimer = setTimeout(syncBannerExpiry, Math.min(wait, 2147483647));
1846+ }
1847+
18161848 function syncRel() {
18171849 var now = document.documentElement.getAttribute('data-rel-now');
18181850 relSkew = now === null ? 0 : (parseInt(now, 10) || 0) * 1000 - Date.now();
@@ -1888,6 +1920,7 @@
18881920 syncPush();
18891921 syncTick();
18901922 syncRel();
1923+ syncBannerExpiry();
18911924
18921925 window.__forgeQuery = function (href) {
18931926 var url = pageUrl(href);
crates/forge-web/src/admin_cli.rsmodified+39 -1
@@ -25,7 +25,7 @@ use forge_core::store::user_delete::{DeletionReport, GHOST_USERNAME};
2525 use forge_core::{AuditAction, Config, Error, Store, names, token};
2626 use forge_git::GitEnv;
2727
28-use crate::admin_client::running_server;
28+use crate::admin_client::{notify_live, running_server};
2929 use crate::audit::{self, Actor, Target};
3030 use crate::auth::hash_password_async;
3131 use crate::backup::{
@@ -98,6 +98,11 @@ pub async fn create_user(
9898 serde_json::json!({ "admin": user.is_admin }),
9999 )
100100 .await;
101+ notify_live(
102+ &config,
103+ serde_json::json!({ "admin": ["users", "audit"], "user_ids": [user.id] }),
104+ )
105+ .await;
101106 println!(
102107 "created user {} (id {}{})",
103108 user.username,
@@ -112,7 +117,16 @@ pub async fn create_user(
112117 pub async fn delete_user(config_path: &Path, username: &str, yes: bool) -> forge_core::Result<()> {
113118 let config = Config::load(config_path)?;
114119 let store = Store::open(&config.database).await?;
120+ // The id is gone once the account is deleted, so it is read first.
121+ let user_id = store.user_by_username(username).await?.map(|u| u.id);
115122 let report = delete_user_in(&store, username, yes).await?;
123+ if let Some(id) = user_id {
124+ notify_live(
125+ &config,
126+ serde_json::json!({ "admin": ["users", "audit"], "user_ids": [id] }),
127+ )
128+ .await;
129+ }
116130 print_deletion_report(&format!("deleted {username}"), &report);
117131 Ok(())
118132 }
@@ -207,6 +221,15 @@ pub async fn set_username(
207221 serde_json::json!({ "from": user.username }),
208222 )
209223 .await;
224+ notify_live(
225+ &config,
226+ serde_json::json!({
227+ "admin": ["users", "audit"],
228+ "user_ids": [user.id],
229+ "account_ids": [user.id],
230+ }),
231+ )
232+ .await;
210233 println!("renamed {} to {}", user.username, display);
211234 Ok(())
212235 }
@@ -216,7 +239,19 @@ pub async fn set_username(
216239 pub async fn reset_password(config_path: &Path, username: &str) -> forge_core::Result<()> {
217240 let config = Config::load(config_path)?;
218241 let store = Store::open(&config.database).await?;
242+ let user_id = store.user_by_username(username).await?.map(|u| u.id);
219243 let (password, display) = reset_password_in(&store, username).await?;
244+ if let Some(id) = user_id {
245+ notify_live(
246+ &config,
247+ serde_json::json!({
248+ "admin": ["users", "audit"],
249+ "user_ids": [id],
250+ "account_ids": [id],
251+ }),
252+ )
253+ .await;
254+ }
220255 println!("temporary password for {display}: {password}");
221256 println!("all sessions of {display} were signed out; change this password after logging in");
222257 Ok(())
@@ -301,6 +336,9 @@ pub async fn audit_purge(config_path: &Path, days: u64) -> forge_core::Result<()
301336 let cutoff = forge_core::time::stamp_ago(Duration::from_secs(days.saturating_mul(86_400)));
302337 let removed = store.purge_audit_before(&cutoff).await?;
303338 tracing::info!(removed, cutoff = %cutoff, "purged audit log entries");
339+ if removed > 0 {
340+ notify_live(&config, serde_json::json!({ "admin": ["audit"] })).await;
341+ }
304342 println!("purged {removed} audit log entries older than {days} days");
305343 Ok(())
306344 }
crates/forge-web/src/admin_client.rsmodified+27 -0
@@ -91,6 +91,33 @@ pub async fn running_server(config: &Config) -> Result<Option<AdminClient>> {
9191 }))
9292 }
9393
94+/// How long a CLI write waits for the running server to answer a live notice.
95+const NOTIFY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
96+
97+/// Tells the running server which open pages a CLI write changed (`/internal/admin/live`). Best
98+/// effort: no server, a stale socket, a refusal or a timeout is logged at debug and ignored, so
99+/// the command never fails because of it.
100+pub async fn notify_live(config: &Config, body: Value) {
101+ let server = match running_server(config).await {
102+ Ok(Some(server)) => server,
103+ Ok(None) => return,
104+ Err(e) => {
105+ tracing::debug!(error = %e, "live: no server to notify");
106+ return;
107+ }
108+ };
109+ match tokio::time::timeout(
110+ NOTIFY_TIMEOUT,
111+ server.post::<Value>("/internal/admin/live", &body),
112+ )
113+ .await
114+ {
115+ Ok(Ok(_)) => {}
116+ Ok(Err(e)) => tracing::debug!(error = %e, "live: the server refused the notice"),
117+ Err(_) => tracing::debug!("live: the server did not answer the notice in time"),
118+ }
119+}
120+
94121 #[derive(serde::Deserialize)]
95122 struct ErrorBody {
96123 error: String,
crates/forge-web/src/alerts.rsmodified+15 -0
@@ -327,6 +327,18 @@ pub async fn check_runners_at(state: &AppState, now: i64) {
327327 }
328328 };
329329 let mut offline = std::collections::BTreeSet::new();
330+ // The runners page dot flips on its own window, so a runner that goes quiet changes the page
331+ // here, not on its next report. Only a change wakes the page.
332+ for runner in &runners {
333+ let online = forge_core::store::health::runner_is_online(
334+ runner.disabled,
335+ runner.last_seen_at.as_deref(),
336+ now,
337+ );
338+ state.ci_live.note_runner_online(&runner.id, online);
339+ }
340+ let ids: Vec<&str> = runners.iter().map(|r| r.id.as_str()).collect();
341+ state.ci_live.forget_runners_except(&ids);
330342 for runner in &runners {
331343 let seen = runner.last_seen_at.as_deref().and_then(stamp_to_unix);
332344 if runner.disabled || !alerts::runner_is_offline(now, seen, cfg.runner_offline_minutes) {
@@ -354,6 +366,9 @@ pub async fn check_slow(state: &AppState) {
354366 check_disk(state).await;
355367 check_backup_overdue(state, now_unix()).await;
356368 check_replication(state, now_unix()).await;
369+ // A copy goes lagging by the clock alone, so the replication page is woken on this tick. Its
370+ // fingerprint drops the wake when no row changed.
371+ crate::live::admin().bump(&crate::live::Topic::AdminReplication);
357372 let old = forge_core::time::stamp_ago(std::time::Duration::from_secs(90 * 86_400));
358373 if let Err(e) = state.store.prune_admin_alerts(&old).await {
359374 tracing::error!(error = %e, "alerts: pruning failed");
crates/forge-web/src/boot.rsmodified+1 -0
@@ -159,6 +159,7 @@ pub async fn serve(
159159 }
160160 crate::alerts::on_boot(&state).await;
161161 crate::ci::reaper::spawn(state.clone());
162+ crate::pages::admin_health::spawn_repo_size(state.clone());
162163 crate::ci::scheduled::spawn(state.clone());
163164
164165 // Topcoat's builder-wide compression is off because it cannot filter by content type or path.
crates/forge-web/src/ci/api.rsmodified+15 -0
@@ -82,6 +82,8 @@ async fn runner_from(state: &AppState, headers: &HeaderMap) -> Result<CiRunner,
8282 ))),
8383 Ok(Some(runner)) => {
8484 crate::alerts::runner_seen(state, &runner.id).await;
85+ // The stamp above is written, so a page that reads it after the wake sees it.
86+ state.ci_live.note_runner_online(&runner.id, true);
8587 Ok(runner)
8688 }
8789 Ok(None) => Err(unauthorized()),
@@ -615,6 +617,12 @@ async fn heartbeat(cx: &Cx) -> topcoat::Result<Response> {
615617 if let Err(e) = state.store.touch_runner(runner_id).await {
616618 tracing::warn!(error = %e, "ci: runner last-seen not stored");
617619 }
620+ // A busy runner only heartbeats here. Its state is read only when it is not
621+ // recorded online, so a steady heartbeat costs a map lookup.
622+ if !state.ci_live.runner_recorded_online(runner_id) {
623+ let disabled = state.store.runner_disabled(runner_id).await.unwrap_or(false);
624+ state.ci_live.note_runner_online(runner_id, !disabled);
625+ }
618626 let said = headers(cx)
619627 .get(CONCURRENCY_HEADER)
620628 .and_then(|v| v.to_str().ok())
@@ -836,6 +844,13 @@ async fn upload_artifact(cx: &Cx, body: Body) -> topcoat::Result<Response> {
836844 }
837845 match upload(state, &job, name, body).await {
838846 Ok(artifact_id) => {
847+ // The job's artifact list and its run's artifact list show the new one. The run page
848+ // follows its repo's stream, so the repo wakes too.
849+ state.ci_live.bump_job(&job.id);
850+ state.ci_live.bump_run(&job.run_id);
851+ if let Ok(Some(run)) = state.store.run_by_id(&job.run_id).await {
852+ state.ci_live.bump_repo(&run.repo_id);
853+ }
839854 // A new artifact may push the store past its disk limit. Enforce it now, not at the
840855 // next daily purge. The request does not wait for it.
841856 let state = state.clone();
crates/forge-web/src/ci/live.rsmodified+51 -0
@@ -23,9 +23,43 @@ pub struct CiLive {
2323 repos: Signals,
2424 runners: Signals,
2525 queues: Signals,
26+ /// The last online state each runner was seen in. Only a change wakes the runners pages.
27+ runner_online: Mutex<HashMap<String, bool>>,
2628 }
2729
2830 impl CiLive {
31+ /// Records whether runner `runner_id` is online now. Wakes the runners pages only when that
32+ /// differs from the state last recorded, so a heartbeat of a runner that stays online costs one
33+ /// map lookup.
34+ pub fn note_runner_online(&self, runner_id: &str, online: bool) {
35+ let changed = self
36+ .runner_online
37+ .lock()
38+ .unwrap_or_else(PoisonError::into_inner)
39+ .insert(runner_id.to_owned(), online)
40+ != Some(online);
41+ if changed {
42+ self.bump_runners();
43+ }
44+ }
45+
46+ /// Whether runner `runner_id` was last recorded online.
47+ pub fn runner_recorded_online(&self, runner_id: &str) -> bool {
48+ self.runner_online
49+ .lock()
50+ .unwrap_or_else(PoisonError::into_inner)
51+ .get(runner_id)
52+ == Some(&true)
53+ }
54+
55+ /// Forgets the recorded state of every runner not in `keep`, so a deleted runner leaves no entry.
56+ pub fn forget_runners_except(&self, keep: &[&str]) {
57+ self.runner_online
58+ .lock()
59+ .unwrap_or_else(PoisonError::into_inner)
60+ .retain(|id, _| keep.contains(&id.as_str()));
61+ }
62+
2963 /// Subscribes to changes of the merge queue of repo `repo_id`: an entry was added, moved or
3064 /// finished. Same rules as [`CiLive::subscribe_job`].
3165 pub fn subscribe_queue(&self, repo_id: &str) -> watch::Receiver<u64> {
@@ -208,6 +242,23 @@ mod tests {
208242 assert!(live.jobs.counters().is_empty());
209243 }
210244
245+ #[tokio::test]
246+ async fn a_runner_wakes_the_pages_only_when_its_online_state_changes() {
247+ let live = CiLive::default();
248+ let mut runners = live.subscribe_runners();
249+
250+ live.note_runner_online("runner-1", true);
251+ assert!(runners.has_changed().expect("open"));
252+ runners.borrow_and_update();
253+
254+ live.note_runner_online("runner-1", true);
255+ assert!(!runners.has_changed().expect("open"));
256+
257+ live.note_runner_online("runner-1", false);
258+ assert!(runners.has_changed().expect("open"));
259+ assert!(!live.runner_recorded_online("runner-1"));
260+ }
261+
211262 #[tokio::test]
212263 async fn close_wakes_the_subscriber_once_and_then_ends_the_signal() {
213264 let live = CiLive::default();
crates/forge-web/src/ci/reaper.rsmodified+21 -1
@@ -21,6 +21,9 @@ const LOST_AFTER: Duration = Duration::from_secs(120);
2121 const ALERTS_SLOW_EVERY: Duration = Duration::from_secs(5 * 60);
2222 /// How often retention runs.
2323 const PURGE_EVERY: Duration = Duration::from_secs(24 * 60 * 60);
24+/// How often the health page is woken. Its disk, uptime and mail figures change with the clock and
25+/// the disk, not with a write; its fingerprint drops a wake that changed nothing.
26+const HEALTH_EVERY: Duration = Duration::from_secs(60);
2427
2528 /// Starts the reaper task. It runs until the process exits.
2629 pub fn spawn(state: AppState) {
@@ -33,10 +36,15 @@ async fn run(state: AppState) {
3336 // Retention runs on the first pass after boot, then once a day.
3437 let mut next_purge = Instant::now();
3538 let mut next_slow_alerts = Instant::now() + ALERTS_SLOW_EVERY;
39+ let mut next_health = Instant::now() + HEALTH_EVERY;
3640 loop {
3741 tick.tick().await;
3842 reap_once(&state).await;
3943 crate::alerts::check_runners(&state).await;
44+ if Instant::now() >= next_health {
45+ crate::live::admin().bump(&crate::live::Topic::AdminHealth);
46+ next_health = Instant::now() + HEALTH_EVERY;
47+ }
4048 if Instant::now() >= next_slow_alerts {
4149 crate::alerts::check_slow(&state).await;
4250 next_slow_alerts = Instant::now() + ALERTS_SLOW_EVERY;
@@ -105,7 +113,7 @@ pub async fn purge_once(state: &AppState) -> (usize, usize) {
105113 let logs_before = stamp_ago(day(ci.log_retention_days));
106114 let artifacts_before = stamp_ago(day(ci.artifact_retention_days));
107115 let max_total_bytes = ci.artifact_max_total_mb.saturating_mul(1024 * 1024);
108- let (job_ids, artifact_ids) = match state
116+ let (job_ids, artifact_ids, run_ids) = match state
109117 .store
110118 .purge_old(
111119 &logs_before,
@@ -145,5 +153,17 @@ pub async fn purge_once(state: &AppState) -> (usize, usize) {
145153 tracing::error!(error = %e, artifact_id = %id, "ci: deleting an artifact failed");
146154 }
147155 }
156+ // The rows are gone and the files too: the pages that list or show the logs and artifacts
157+ // re-read them now.
158+ for id in &job_ids {
159+ state.ci_live.bump_job(id);
160+ }
161+ for id in &run_ids {
162+ state.ci_live.bump_run(id);
163+ // The run page follows its repo's stream.
164+ if let Ok(Some(run)) = state.store.run_by_id(id).await {
165+ state.ci_live.bump_repo(&run.repo_id);
166+ }
167+ }
148168 (log_count, artifact_count)
149169 }
crates/forge-web/src/importer/mod.rsmodified+22 -0
@@ -29,6 +29,7 @@ use self::api::{ApiError, ExtAsset, ExtIssue, ExtRelease, GitHub, Notice, Remote
2929 pub use self::remote::{
3030 default_name, make_forgejo, make_github, make_gitlab, parse_remote, source_ref,
3131 };
32+use crate::live::Topic;
3233 use crate::mirrors::{check_remote, policy, pull_refs, ref_snapshot};
3334 use crate::state::AppState;
3435
@@ -39,6 +40,8 @@ static SLOTS: Semaphore = Semaphore::const_new(2);
3940 const IMPORTED_PR_LABEL: &str = "imported PR";
4041 const IMPORTED_PR_COLOR: &str = "#8b7bd8";
4142 const FALLBACK_LABEL_COLOR: &str = "#8b949e";
43+/// Imported issues between two wakes of the repo's issue list.
44+const IMPORT_BUMP_BATCH: usize = 25;
4245
4346 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
4447 pub enum Source {
@@ -310,11 +313,14 @@ pub fn asset_name(name: &str) -> String {
310313
311314 /// Starts the job in the background. It waits for a free slot, then runs.
312315 pub fn spawn_job(state: AppState, job: ImportJob, spec: JobSpec) {
316+ // The owner's import list shows the job as queued, then finished or failed (see `run_job`).
317+ state.live.bump(&Topic::Imports(job.user_id.clone()));
313318 tokio::spawn(async move {
314319 let Ok(_slot) = SLOTS.acquire().await else {
315320 return;
316321 };
317322 run_production(&state, &job, &spec).await;
323+ state.live.bump(&Topic::Imports(job.user_id.clone()));
318324 });
319325 }
320326
@@ -385,6 +391,7 @@ pub async fn run_job<A: RemoteApi>(
385391 return;
386392 }
387393 bump(&job.id);
394+ state.live.bump(&Topic::Imports(job.user_id.clone()));
388395 match run_steps(state, job, spec, api, transport, &rep).await {
389396 Ok(summary) => {
390397 rep.log("info", summary).await;
@@ -576,6 +583,12 @@ impl<A: RemoteApi> Run<'_, A> {
576583 &self.state.store
577584 }
578585
586+ /// Wakes the repo's issue list, labels, milestones and tabs. Called per batch and at the end of
587+ /// a phase, not per write.
588+ fn bump_issues(&self) {
589+ self.state.live.bump_repo_issues(&self.repo.id);
590+ }
591+
579592 async fn mapped(&self, kind: &str, ext: &str) -> Result<Option<ImportOrigin>, String> {
580593 self.store()
581594 .import_origin(&self.repo.id, kind, ext)
@@ -626,6 +639,7 @@ impl<A: RemoteApi> Run<'_, A> {
626639 }
627640 }
628641 }
642+ self.bump_issues();
629643 self.rep.log("info", format!("{total} labels read")).await;
630644 Ok(())
631645 }
@@ -677,6 +691,7 @@ impl<A: RemoteApi> Run<'_, A> {
677691 self.record("milestone", &m.id, &created.id, "", "").await;
678692 totals.milestones += 1;
679693 }
694+ self.bump_issues();
680695 Ok(())
681696 }
682697
@@ -749,6 +764,7 @@ impl<A: RemoteApi> Run<'_, A> {
749764 format!("Importing {total} issues and pull requests"),
750765 )
751766 .await;
767+ let mut created_since_bump = 0usize;
752768 for (i, item) in items.iter().enumerate() {
753769 self.rep.stage("issues", i, total).await;
754770 let kind = if item.is_pr { "pull" } else { "issue" };
@@ -758,6 +774,11 @@ impl<A: RemoteApi> Run<'_, A> {
758774 None => match self.create_item(item, &mut labels, &milestones).await {
759775 Ok(id) => {
760776 self.record(kind, &ext, &id, &item.author, &item.url).await;
777+ created_since_bump += 1;
778+ if created_since_bump == IMPORT_BUMP_BATCH {
779+ created_since_bump = 0;
780+ self.bump_issues();
781+ }
761782 if item.is_pr {
762783 totals.pulls += 1;
763784 } else {
@@ -814,6 +835,7 @@ impl<A: RemoteApi> Run<'_, A> {
814835 }
815836 }
816837 self.rep.stage("issues", total, total).await;
838+ self.bump_issues();
817839 Ok(())
818840 }
819841
crates/forge-web/src/internal.rsmodified+97 -0
@@ -28,6 +28,7 @@ use crate::admin_client::ADMIN_TOKEN_HEADER;
2828 use crate::audit::{self, Actor, Target};
2929 use crate::backup::scheduler::{run_backup_now, run_fsck_now};
3030 use crate::backup::{BackupOptions, Scope};
31+use crate::live::{self, Topic};
3132 use crate::post_update::after_ref_update;
3233 use crate::state::AppState;
3334 use forge_core::AuditAction;
@@ -115,6 +116,11 @@ pub fn router(state: AppState) -> Router {
115116 "/internal/admin/lfs-gc",
116117 admin_lfs_gc,
117118 ))
119+ .route(RouteFn::new(
120+ Method::POST,
121+ "/internal/admin/live",
122+ admin_live,
123+ ))
118124 .app_context(state)
119125 .build()
120126 }
@@ -190,6 +196,66 @@ fn admin_lfs_gc(cx: &Cx, body: Body) -> RouteFuture<'_> {
190196 Box::pin(async move { admin_lfs_gc_endpoint(cx, body).await })
191197 }
192198
199+fn admin_live(cx: &Cx, body: Body) -> RouteFuture<'_> {
200+ Box::pin(async move { admin_live_endpoint(cx, body).await })
201+}
202+
203+/// Body of `POST /internal/admin/live`. The CLI names what its write changed, and the server
204+/// wakes the same topics its own writers would. Every list may be empty.
205+#[derive(Deserialize, Default)]
206+struct AdminLiveRequest {
207+ /// Global admin topics by short name: `users`, `audit`, `backups`, `health`, `replication`,
208+ /// `server`.
209+ #[serde(default)]
210+ admin: Vec<String>,
211+ /// Users whose admin page and public profile changed.
212+ #[serde(default)]
213+ user_ids: Vec<String>,
214+ /// Accounts whose own settings (sessions, username) changed.
215+ #[serde(default)]
216+ account_ids: Vec<String>,
217+}
218+
219+/// `POST /internal/admin/live`. Wakes the open pages of the running server for a write made by
220+/// another process (the admin CLI). The body is small and the answer carries no data.
221+async fn admin_live_endpoint(cx: &Cx, body: Body) -> topcoat::Result<Response> {
222+ let state = app_context::<AppState>(cx);
223+ if !admin_authorized(cx, state) {
224+ return Err(forbidden().into());
225+ }
226+ let bytes = to_bytes(body, MAX_BODY_BYTES).await?;
227+ let req: AdminLiveRequest = serde_json::from_slice(&bytes)
228+ .map_err(|e| bad_request(format!("invalid live request: {e}")))?;
229+ let mut admin_topics = Vec::with_capacity(req.admin.len());
230+ for name in &req.admin {
231+ admin_topics.push(match name.as_str() {
232+ "users" => Topic::AdminUsers,
233+ "audit" => Topic::AdminAudit,
234+ "backups" => Topic::AdminBackups,
235+ "health" => Topic::AdminHealth,
236+ "replication" => Topic::AdminReplication,
237+ "server" => Topic::AdminServer,
238+ other => {
239+ return Ok(admin_error(&forge_core::Error::Invalid(format!(
240+ "unknown admin topic: {other}"
241+ ))));
242+ }
243+ });
244+ }
245+ let hub = live::admin();
246+ for topic in &admin_topics {
247+ hub.bump(topic);
248+ }
249+ for id in &req.user_ids {
250+ hub.bump(&Topic::AdminUser(id.clone()));
251+ state.live.bump(&Topic::User(id.clone()));
252+ }
253+ for id in &req.account_ids {
254+ state.live.bump(&Topic::Account(id.clone()));
255+ }
256+ Ok(admin_response(StatusCode::OK, serde_json::json!({ "ok": true })))
257+}
258+
193259 /// `POST /internal/admin/lfs-gc`. The body is ignored.
194260 async fn admin_lfs_gc_endpoint(cx: &Cx, _body: Body) -> topcoat::Result<Response> {
195261 let state = app_context::<AppState>(cx);
@@ -795,6 +861,37 @@ mod tests {
795861 assert_eq!(res.status(), 200);
796862 }
797863
864+ /// The live route needs the admin token and wakes the topics it names on the right hub.
865+ #[tokio::test]
866+ async fn live_bump_wakes_the_named_topics() {
867+ let dir = tempfile::tempdir().expect("tempdir");
868+ let state = crate::test_support::test_state(dir.path()).await;
869+ let users = live::admin().subscribe(&Topic::AdminUsers);
870+ let profile = state.live.subscribe(&Topic::User("u1".to_owned()));
871+ let router = router(state);
872+ let body = r#"{"admin":["users"],"user_ids":["u1"]}"#;
873+
874+ let refused = topcoat::router::request::Request::builder()
875+ .method("POST")
876+ .uri("/internal/admin/live")
877+ .header("content-type", "application/json")
878+ .header(ADMIN_TOKEN_HEADER, "wrong")
879+ .body(Body::from(body))
880+ .expect("request");
881+ assert_eq!(router.handle(refused).await.status(), 403);
882+
883+ let req = topcoat::router::request::Request::builder()
884+ .method("POST")
885+ .uri("/internal/admin/live")
886+ .header("content-type", "application/json")
887+ .header(ADMIN_TOKEN_HEADER, crate::test_support::ADMIN_TOKEN)
888+ .body(Body::from(body))
889+ .expect("request");
890+ assert_eq!(router.handle(req).await.status(), 200);
891+ assert!(users.has_changed().expect("open"));
892+ assert!(profile.has_changed().expect("open"));
893+ }
894+
798895 #[tokio::test]
799896 async fn hook_routes_are_not_collected_by_discover() {
800897 // The public router uses `.discover()`. Hook routes are plain RouteFns and must not be in it.
crates/forge-web/src/live.rsmodified+24 -4
@@ -53,14 +53,25 @@ pub enum Topic {
5353 /// One pull request, its conversation, commits and files. Keyed by the pull's issue id.
5454 /// Bumped by [`crate::pages::pull_live`].
5555 Pull(String),
56- /// A repo's own state that its header shows: stars, watchers, forks, and its name and
57- /// description. Keyed by repo id.
56+ /// A repo's own state that its header shows: stars, watchers, forks, its name, description,
57+ /// archived flag and default branch, the tab switches, and the mirror's last sync. Keyed by repo
58+ /// id. Bumped after the write, and also when a package linked to the repo publishes or yanks (the
59+ /// home page shows its newest version). The header's counts follow [`Topic::RepoIssues`] and
60+ /// [`Topic::PullList`] as well.
5861 Repo(String),
5962 /// A user's repo listing, pins, contribution calendar and the signed-in sidebar's repo list.
6063 /// Keyed by user id (an organization is a user too).
6164 User(String),
6265 /// A user's inbox: a notification was added, read or marked read. Keyed by user id.
6366 Inbox(String),
67+ /// A user's review requests: a pull request asked the user to review, a request was withdrawn,
68+ /// the user submitted a review, or a pull request with the user's request closed or merged.
69+ /// Keyed by the reviewer's user id. Streamed only to that user. Bumped by
70+ /// [`crate::pages::review_requests`] and [`crate::pages::pull_live`].
71+ ReviewRequests(String),
72+ /// A user's import jobs: a job was queued, started, progressed or finished. Keyed by user id.
73+ /// Bumped by the importer when a job's state changes. Streamed only to that user.
74+ Imports(String),
6475 /// The public repo listing: a public repo was added, changed, or starred. Global.
6576 Explore,
6677 /// The discussions of a repo as a list: a discussion was opened, or any discussion of the repo
@@ -101,7 +112,8 @@ pub enum Topic {
101112 AdminServer,
102113 /// The releases of a repo: a release was created, edited or deleted, an asset was added,
103114 /// replaced or removed, or an asset was downloaded (its count). Keyed by repo id. The release
104- /// list and the release pages follow it. Bumped by [`crate::release_ops`].
115+ /// list, the release pages and the repo home page's latest release card follow it. Bumped by
116+ /// [`crate::release_ops`].
105117 RepoReleases(String),
106118 /// A user's own settings: a profile, key, token, passkey, session, notification or appearance
107119 /// setting changed, or a sign-in or a key or token use happened. Keyed by user id. Streamed only
@@ -114,6 +126,12 @@ pub enum Topic {
114126 /// The commit statuses of a repo: a status was reported or replaced. Keyed by repo id. Bumped
115127 /// by the CI runner and the statuses API, after the write.
116128 CommitStatuses(String),
129+ /// The server settings that pages render (every `Kind::Live` setting, such as the banner, the
130+ /// registration mode or the limits): one was saved or reset. Global. Every page holds
131+ /// `/-/alive`, anonymous viewers included, and follows it there (see
132+ /// [`crate::pages::settings_live::alive_response`]). Bumped by the server settings after a save
133+ /// or reset.
134+ ServerSettings,
117135 }
118136
119137 /// The hub of the admin pages. It is process-wide, not part of [`crate::state::AppState`]: the
@@ -173,9 +191,11 @@ impl LiveHub {
173191
174192 /// A repo changed in a way its owner's pages, the explore list and its own header show: it
175193 /// was created, renamed, moved, re-described, starred, watched or forked. Call it once per
176- /// owner whose listing changed (a transfer has two).
194+ /// owner whose listing changed (a transfer has two). An organization owner's team pages list
195+ /// its repos too, so they are woken as well.
177196 pub fn bump_repo(&self, owner_id: &str, repo_id: &str) {
178197 self.bump(&Topic::User(owner_id.to_owned()));
198+ self.bump(&Topic::Org(owner_id.to_owned()));
179199 self.bump(&Topic::Explore);
180200 self.bump(&Topic::Repo(repo_id.to_owned()));
181201 // The owner's repo count is on the admin page of the account.
crates/forge-web/src/mail/worker.rsmodified+6 -1
@@ -68,7 +68,12 @@ async fn tick(state: &AppState) -> forge_core::Result<Duration> {
6868 }
6969 let now = now_stamp();
7070 let lease_until = stamp_after(LEASE);
71- for entry in state.store.lease_mail(&now, &lease_until, BATCH).await? {
71+ let leased = state.store.lease_mail(&now, &lease_until, BATCH).await?;
72+ if !leased.is_empty() {
73+ // The queue page shows these as Sending while the batch goes out.
74+ live::bump();
75+ }
76+ for entry in leased {
7277 deliver(state, &entry).await;
7378 }
7479 let next = state.store.next_mail_due().await?;
crates/forge-web/src/merge_queue.rsmodified+12 -10
@@ -74,7 +74,7 @@ pub async fn enqueue(
7474 .await
7575 {
7676 Ok(entry) => {
77- notify_changed(state, &repo.id);
77+ notify_entry(state, repo, &entry);
7878 advance(state, repo, &pr.base_branch).await;
7979 Ok(Ok(entry))
8080 }
@@ -91,7 +91,7 @@ pub async fn remove(state: &AppState, repo: &Repo, entry: &QueueEntry, reason: &
9191 .queue_finish(&entry.id, QueueState::Removed, reason)
9292 .await
9393 {
94- Ok(true) => notify_changed(state, &repo.id),
94+ Ok(true) => notify_entry(state, repo, entry),
9595 Ok(false) => {}
9696 Err(e) => {
9797 tracing::error!(error = %e, repo_id = %repo.id, "merge queue: removing an entry failed");
@@ -235,7 +235,7 @@ async fn start(
235235 {
236236 return Ok(false);
237237 }
238- notify_changed(state, &repo.id);
238+ notify_entry(state, repo, entry);
239239 // A run is created here only when the workflow runs for this candidate. Its statuses may
240240 // arrive before this returns; `evaluate` finds the run through its ref and commit.
241241 merge_queue_run(
@@ -354,12 +354,12 @@ async fn land(
354354 Err(forge_git::error::Error::RefMoved(_)) => {
355355 // The target moved since the candidate was built: build it again on the new tip.
356356 state.store.queue_set_queued(&entry.id).await?;
357- notify_changed(state, &repo.id);
357+ notify_entry(state, repo, entry);
358358 return Ok(true);
359359 }
360360 Err(e) => {
361361 state.store.queue_set_queued(&entry.id).await?;
362- notify_changed(state, &repo.id);
362+ notify_entry(state, repo, entry);
363363 return Err(e.into());
364364 }
365365 }
@@ -379,7 +379,7 @@ async fn finish_removed(
379379 .store
380380 .queue_finish(&entry.id, QueueState::Removed, reason)
381381 .await?;
382- notify_changed(state, &repo.id);
382+ notify_entry(state, repo, entry);
383383 Ok(())
384384 }
385385
@@ -399,7 +399,7 @@ async fn fail(
399399 {
400400 return Ok(());
401401 }
402- notify_changed(state, &repo.id);
402+ notify_entry(state, repo, entry);
403403 let who = match state.store.user_by_id(&entry.enqueued_by).await? {
404404 Some(user) => format!("@{}", user.username),
405405 None => String::new(),
@@ -414,6 +414,7 @@ async fn fail(
414414 .await
415415 {
416416 Ok(_) => {
417+ crate::pages::pull_live::bump_pull(state, &repo.id, &pr.issue.id);
417418 notify::dispatch(
418419 state,
419420 repo,
@@ -431,7 +432,8 @@ async fn fail(
431432 Ok(())
432433 }
433434
434-/// Wakes the queue pages of `repo_id`.
435-pub fn notify_changed(state: &AppState, repo_id: &str) {
436- state.ci_live.bump_queue(repo_id);
435+/// Wakes the queue pages of `repo_id`, and the pull page and list of the entry's pull request.
436+fn notify_entry(state: &AppState, repo: &Repo, entry: &QueueEntry) {
437+ state.ci_live.bump_queue(&repo.id);
438+ crate::pages::pull_live::bump_pull(state, &repo.id, &entry.issue_id);
437439 }
crates/forge-web/src/mirrors/mod.rsmodified+3 -0
@@ -22,6 +22,7 @@ use reqwest::Url;
2222 use serde_json::json;
2323
2424 use crate::audit::{self, Actor, Target};
25+use crate::live::Topic;
2526 use crate::pages::repo_settings_live::bump_settings;
2627 use crate::post_update::after_ref_update;
2728 use crate::state::AppState;
@@ -281,6 +282,8 @@ pub async fn run_one(state: &AppState, mirror: &Mirror, policy: &WebhookPolicy)
281282 }
282283 // The mirror list and detail of the repo's settings show the sync state, so they wake now.
283284 bump_settings(&state.live, &mirror.repo_id);
285+ // The repo header shows the mirror's last sync and its result.
286+ state.live.bump(&Topic::Repo(mirror.repo_id.clone()));
284287 if let Some(error) = &error {
285288 tracing::warn!(mirror_id = %mirror.id, error = %error, "mirrors: sync failed");
286289 if mirror.last_ok != Some(false) {
crates/forge-web/src/oci/manifests.rsmodified+4 -0
@@ -13,6 +13,7 @@ use topcoat::router::{Body, StatusCode, to_bytes};
1313 use super::auth::{self, Caller, internal};
1414 use super::blobs::{insert, write_package};
1515 use super::{gc, oci_error};
16+use crate::package_ops::bump_linked_repo;
1617 use crate::state::AppState;
1718
1819 /// Largest manifest accepted, in bytes.
@@ -184,6 +185,7 @@ pub async fn put_manifest(
184185 return internal(e);
185186 }
186187 state.packages_live.bump(&target.owner.id);
188+ bump_linked_repo(state, &package.id).await;
187189 let mut res = Response::new(Body::empty());
188190 *res.status_mut() = StatusCode::CREATED;
189191 insert(
@@ -281,6 +283,7 @@ pub async fn delete_manifest(
281283 },
282284 }
283285 state.packages_live.bump(&target.owner.id);
286+ bump_linked_repo(state, &package.id).await;
284287 let mut res = Response::new(Body::empty());
285288 *res.status_mut() = StatusCode::ACCEPTED;
286289 res
@@ -311,6 +314,7 @@ pub async fn remove_tag(
311314 }
312315 gc::sweep(state, &package.id).await?;
313316 state.packages_live.bump(&owner.id);
317+ bump_linked_repo(state, &package.id).await;
314318 Ok(true)
315319 }
316320
crates/forge-web/src/package_ops.rsmodified+12 -0
@@ -225,9 +225,20 @@ pub async fn publish(
225225 return Err(PackageError::Internal(e.to_string()));
226226 }
227227 state.packages_live.bump(&owner.id);
228+ bump_linked_repo(state, &package.id).await;
228229 Ok(())
229230 }
230231
232+/// Wakes the repo that `package_id` is linked to, if any: its home page shows the package's newest
233+/// version. A failed lookup skips the wake only, since the write has already happened.
234+pub async fn bump_linked_repo(state: &AppState, package_id: &str) {
235+ if let Ok(Some(package)) = state.store.package(package_id).await
236+ && let Some(repo_id) = package.repo_id
237+ {
238+ state.live.bump(&crate::live::Topic::Repo(repo_id));
239+ }
240+}
241+
231242 /// Sets the yank state of a version. Yanked versions stay in the index and stay downloadable,
232243 /// marked as yanked, so existing lockfiles keep working.
233244 pub async fn set_yanked(
@@ -255,6 +266,7 @@ pub async fn set_yanked(
255266 return Err(PackageError::NotFound);
256267 }
257268 state.packages_live.bump(&owner.id);
269+ bump_linked_repo(state, &package.id).await;
258270 Ok(())
259271 }
260272
crates/forge-web/src/pages/admin_health.rsmodified+74 -17
@@ -1,9 +1,11 @@
11 //! Page: instance health for admins (`/admin/health`). A summary line, a storage card with the data
22 //! disk's usage bar, and a services card. Every number is a cheap query or a short external probe
3-//! (`df`, `du`), so there is no polling; reloading the page, or opening it again, reads fresh values.
4-//! Non-admins get 404.
3+//! (`df`), so there is no polling; reloading the page, or opening it again, reads fresh values. The
4+//! tree size of the repos (`du`) walks every repo, so a background task caches it (see
5+//! [`spawn_repo_size`]) and the page only reads the cache. Non-admins get 404.
56
67 use std::path::Path;
8+use std::sync::Mutex;
79 use std::time::Duration;
810
911 use forge_core::mail::MailState;
@@ -143,8 +145,48 @@ async fn disk(path: &Path) -> Option<(u64, u64)> {
143145 parse_df(&probe("df", &["-Pk"], path, Duration::from_secs(3)).await?)
144146 }
145147
146-async fn tree_size(path: &Path) -> Option<u64> {
147- parse_du(&probe("du", &["-sk"], path, Duration::from_secs(4)).await?)
148+async fn tree_size(path: &Path, limit: Duration) -> Option<u64> {
149+ parse_du(&probe("du", &["-sk"], path, limit).await?)
150+}
151+
152+/// Total bytes of the repos, from the last background walk. `None` until the first walk finishes,
153+/// or when every walk so far failed.
154+static REPO_BYTES: Mutex<Option<u64>> = Mutex::new(None);
155+/// How often the repos are walked again.
156+const REPO_SIZE_EVERY: Duration = Duration::from_secs(10 * 60);
157+/// The first walk, shortly after boot.
158+const REPO_SIZE_FIRST: Duration = Duration::from_secs(30);
159+
160+fn cached_repo_bytes() -> Option<u64> {
161+ *REPO_BYTES.lock().unwrap_or_else(|e| e.into_inner())
162+}
163+
164+/// Starts the background walk of the repos' size: once shortly after boot, then every
165+/// [`REPO_SIZE_EVERY`]. Runs until the process exits. `du` is a child process, so the walk does not
166+/// block the executor. A changed size wakes the health page.
167+pub fn spawn_repo_size(state: AppState) {
168+ tokio::spawn(async move {
169+ tokio::time::sleep(REPO_SIZE_FIRST).await;
170+ loop {
171+ refresh_repo_bytes(&state).await;
172+ tokio::time::sleep(REPO_SIZE_EVERY).await;
173+ }
174+ });
175+}
176+
177+async fn refresh_repo_bytes(state: &AppState) {
178+ let repos_dir = state.live().data_dir.join("repos");
179+ // A failed or timed-out walk keeps the last good value.
180+ let Some(bytes) = tree_size(&repos_dir, Duration::from_secs(5 * 60)).await else {
181+ return;
182+ };
183+ let previous = REPO_BYTES
184+ .lock()
185+ .unwrap_or_else(|e| e.into_inner())
186+ .replace(bytes);
187+ if previous != Some(bytes) {
188+ crate::live::admin().bump(&Topic::AdminHealth);
189+ }
148190 }
149191
150192 /// Seconds since the process started, from `/proc` (Linux). `None` elsewhere.
@@ -167,18 +209,17 @@ async fn gather(state: &AppState, lang: Lang, tz: &str) -> Result<Health> {
167209 let live = state.live();
168210 let now = now_unix();
169211 let data_dir = live.data_dir.clone();
170- let repos_dir = data_dir.join("repos");
171212 let backup_dir = live.backup.dir.clone();
172213 let database = live.database.clone();
173214 let backup_on = !backup_dir.as_os_str().is_empty();
174- let (data_space, repo_bytes, backup_space) =
175- tokio::join!(disk(&data_dir), tree_size(&repos_dir), async {
176- if backup_on {
177- disk(&backup_dir).await
178- } else {
179- None
180- }
181- });
215+ let (data_space, backup_space) = tokio::join!(disk(&data_dir), async {
216+ if backup_on {
217+ disk(&backup_dir).await
218+ } else {
219+ None
220+ }
221+ });
222+ let repo_bytes = cached_repo_bytes();
182223 let counts = state.store.health_counts().await?;
183224 let mail = state
184225 .store
@@ -532,9 +573,10 @@ async fn health_page(cx: &Cx) -> Result<impl View> {
532573 })
533574 }
534575
535-/// What the event-driven parts of the health page show, as one string: the alerts, the counts and
536-/// the mail queue. The disk and tree probes (`df`, `du`) are not read here: they cost a process
537-/// each, so they run only when the page renders.
576+/// What the health page shows that can change between renders, as one string: the alerts, the
577+/// counts, the mail queue, the disk figures and the uptime, each as the page would display it. The
578+/// disk figures come from `statvfs` (the same numbers `df` prints), not a process. The tree size
579+/// of the repos is the cached value of the background walk, as the page displays it.
538580 async fn health_fingerprint(state: &AppState) -> Result<String> {
539581 let counts = state.store.health_counts().await?;
540582 let mail = state
@@ -546,7 +588,22 @@ async fn health_fingerprint(state: &AppState) -> Result<String> {
546588 .into_iter()
547589 .map(|alert| (alert.title, alert.body))
548590 .collect();
549- Ok(format!("{counts:?}|{mail:?}|{alerts:?}"))
591+ let live = state.live();
592+ let disk_text = |path: &Path| {
593+ crate::alerts::disk_space(path).map(|(total, avail)| {
594+ let (pct, text) = space(Lang::En, total, avail);
595+ (pct, text, human_size(Lang::En, total.saturating_sub(avail)))
596+ })
597+ };
598+ let data = disk_text(&live.data_dir);
599+ let backup = (!live.backup.dir.as_os_str().is_empty())
600+ .then(|| disk_text(&live.backup.dir))
601+ .flatten();
602+ let uptime = uptime_secs().map(duration_short);
603+ let repos = cached_repo_bytes().map(|b| human_size(Lang::En, b));
604+ Ok(format!(
605+ "{counts:?}|{mail:?}|{alerts:?}|{data:?}|{backup:?}|{uptime:?}|{repos:?}"
606+ ))
550607 }
551608
552609 /// The health page's change stream. Admins only.
crates/forge-web/src/pages/admin_runners.rsmodified+2 -8
@@ -9,7 +9,7 @@
99 use forge_ci::build::{self, Freshness};
1010 use forge_core::AuditAction;
1111 use forge_core::ci::{CiRunner, FieldKind, RUNNER_FIELDS, RestartMode, runner_field};
12-use forge_core::store::health::RUNNER_ONLINE_SECS;
12+use forge_core::store::health::runner_is_online;
1313 use serde::Deserialize;
1414 use time::OffsetDateTime;
1515 use time::format_description::well_known::Rfc3339;
@@ -197,13 +197,7 @@ fn dot_of(lang: Lang, runner: &CiRunner, now: i64) -> (&'static str, &'static st
197197 if runner.disabled {
198198 return ("runner-dot is-disabled", g::t(lang, K::Disabled));
199199 }
200- let limit = i64::try_from(RUNNER_ONLINE_SECS).unwrap_or(i64::MAX);
201- let online = runner
202- .last_seen_at
203- .as_deref()
204- .and_then(|stamp| OffsetDateTime::parse(stamp, &Rfc3339).ok())
205- .is_some_and(|at| at.unix_timestamp() >= now.saturating_sub(limit));
206- if online {
200+ if runner_is_online(false, runner.last_seen_at.as_deref(), now) {
207201 ("runner-dot is-online", s(lang, "online", "çevrim içi"))
208202 } else {
209203 ("runner-dot is-offline", s(lang, "offline", "çevrim dışı"))
crates/forge-web/src/pages/admin_server.rsmodified+9 -0
@@ -280,6 +280,13 @@ async fn server_view(
280280 <option value=(option.value.as_str()) selected=(option.selected)>(option.label.as_str())</option>
281281 }
282282 </select>
283+ } else if r.is_number && r.max.parse::<u64>().is_ok_and(|max| max <= 100) {
284+ // A small range steps with − and +, like the runner's Max.
285+ <div class="runner-pill">
286+ <button type="button" class="runner-step" data-step="-1" aria-label=(s(lang, "Fewer", "Azalt"))>"−"</button>
287+ <input type="number" name=(r.key) value=(r.value.as_str()) min=(r.min.as_str()) max=(r.max.as_str()) step="1" inputmode="numeric" aria-label=(r.label)>
288+ <button type="button" class="runner-step" data-step="1" aria-label=(s(lang, "More", "Artır"))>"+"</button>
289+ </div>
283290 } else if r.is_number {
284291 <input type="number" name=(r.key) value=(r.value.as_str()) min=(r.min.as_str()) max=(r.max.as_str()) aria-label=(r.label)>
285292 } else if r.is_secret {
@@ -414,6 +421,7 @@ async fn save(
414421 state.store.clear_server_override(key).await?;
415422 }
416423 state.settings.publish(&plan.overrides)?;
424+ state.live.bump(&Topic::ServerSettings);
417425 crate::live::admin().bump(&Topic::AdminServer);
418426 let keys: Vec<&str> = plan.sets.iter().map(|(k, _)| k.as_str()).collect();
419427 audit::record(
@@ -541,6 +549,7 @@ async fn reset(
541549 let next = state.settings.plan_reset(&existing, key)?;
542550 state.store.clear_server_override(key).await?;
543551 state.settings.publish(&next)?;
552+ state.live.bump(&Topic::ServerSettings);
544553 crate::live::admin().bump(&Topic::AdminServer);
545554 audit::record(
546555 &state.store,
crates/forge-web/src/pages/assets.rsmodified+3 -1
@@ -167,7 +167,9 @@ async fn offline_js() -> Result<(StatusCode, HeaderMap, &'static str)> {
167167
168168 /// The stream every page and the offline page watch to learn that the server is back. It carries
169169 /// no data and needs no login: it sends `retry`, then holds the connection open with keep-alive
170-/// comments. A signed-in viewer also gets `theme` events (see `settings_live::alive_response`). A dropped connection (or a proxy's 502 while forge restarts) is what the pages watch for.
170+/// comments. Every viewer gets `settings` events when a live server setting changes, and a signed-in
171+/// viewer also gets `theme` events (see `settings_live::alive_response`). A dropped connection (or a
172+/// proxy's 502 while forge restarts) is what the pages watch for.
171173 #[route(GET "/-/alive")]
172174 async fn alive(cx: &Cx) -> Result<Response> {
173175 crate::pages::settings_live::alive_response(cx).await
crates/forge-web/src/pages/banner.rsmodified+3 -0
@@ -29,6 +29,8 @@ pub struct BannerView {
2929 pub message: String,
3030 pub warning: bool,
3131 pub hash: String,
32+ /// Unix seconds when the banner expires, or `None` for never. The page drops it at that time.
33+ pub expires: Option<i64>,
3234 }
3335
3436 /// Short stable id of a message and level.
@@ -51,6 +53,7 @@ pub fn view_for(config: &BannerConfig, now: i64, dismissed: Option<&str>) -> Opt
5153 message,
5254 warning: config.level == "warning",
5355 hash,
56+ expires: config.expires_unix(),
5457 })
5558 }
5659
crates/forge-web/src/pages/ci_job.rsmodified+75 -39
@@ -1,10 +1,10 @@
11 //! Pages: one CI job (`/{owner}/{repo}/ci/jobs/{job_id}`), its live log (`.../log.txt`) and its
22 //! artifacts (`.../artifacts/{name}`). Reading follows repo Read, like the run pages. The job page
3-//! shows the last 512 KiB of the log. While the job is not terminal the page is live: it carries a
4-//! `data-live` marker for its `.../events` stream, and nav.js re-renders it when the job's status
5-//! changes. `log.txt` streams the whole log and keeps following it until the job is
6-//! terminal and the file is read to its end. Artifacts are blobs under `ci/<artifact id>` and are
7-//! always served as attachments.
3+//! shows the last 512 KiB of the log. The page carries a `data-live` marker for its `.../events`
4+//! stream, and `data-live-state` holds the job's fingerprint (status, artifact ids, log kept): nav.js
5+//! re-renders the page when the stream sends a different one. `log.txt` streams the whole log and
6+//! keeps following it until the job is terminal and the file is read to its end. Artifacts are blobs
7+//! under `ci/<artifact id>` and are always served as attachments.
88
99 use std::path::{Path, PathBuf};
1010 use std::sync::Arc;
@@ -34,8 +34,8 @@ use crate::i18n::{
3434 releases_ci::{self as g, K},
3535 };
3636 use crate::pages::ci_runs::{
37- age_text, can_write, changed_event, duration_text, events_response, job_href, job_status,
38- run_href, state_text,
37+ age_text, can_write, changed_event, duration_text, events_response, job_href, run_href,
38+ state_text,
3939 };
4040 use crate::pages::repo::repo_head;
4141 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
@@ -254,8 +254,8 @@ fn full_date(stamp: &str) -> String {
254254 /// The job page's values, already shown as text.
255255 struct JobView {
256256 name: String,
257- /// The status word as the events carry it, for the live check.
258- status: String,
257+ /// The fingerprint the events carry and the page renders as `data-live-state` (see `job_fingerprint`).
258+ fingerprint: String,
259259 state: String,
260260 state_class: String,
261261 runner: String,
@@ -282,8 +282,35 @@ struct ArtifactRow {
282282 size: String,
283283 }
284284
285-/// The job page body. A job that is not terminal carries `live`, the URL of its event stream, and
286-/// the status the page shows. The log tail carries the offset its text ends at.
285+/// The job's fingerprint: its status, the ids of its artifacts (by name) and whether its log is
286+/// still kept. The events send it as `changed` data and the page renders it as `data-live-state`,
287+/// so a status change, an artifact added or deleted, or a log deleted re-renders the page. The
288+/// log's size is left out: a running job's log grows with every chunk, and the log stream carries
289+/// that. Format: `{status}|{artifact ids joined by ','}|{log or nolog}`.
290+fn job_fingerprint(status: &str, artifact_ids: &[&str], log_kept: bool) -> String {
291+ format!(
292+ "{status}|{}|{}",
293+ artifact_ids.join(","),
294+ if log_kept { "log" } else { "nolog" }
295+ )
296+}
297+
298+/// The job's fingerprint now. `None` when the job row is gone.
299+async fn job_fingerprint_now(store: &Store, job_id: &str) -> Result<Option<String>> {
300+ let Some(job) = store.job_by_id(job_id).await? else {
301+ return Ok(None);
302+ };
303+ let artifacts = store.list_artifacts(job_id).await?;
304+ let ids: Vec<&str> = artifacts.iter().map(|artifact| artifact.id.as_str()).collect();
305+ Ok(Some(job_fingerprint(
306+ job.state.as_str(),
307+ &ids,
308+ job.log_bytes > 0,
309+ )))
310+}
311+
312+/// The job page body. Every job carries `live`, the URL of its event stream, so a finished job
313+/// follows its artifacts and log too. The log tail carries the offset its text ends at.
287314 #[component]
288315 async fn job_body(
289316 head: RepoHead,
@@ -294,11 +321,11 @@ async fn job_body(
294321 first_line: String,
295322 truncated: bool,
296323 artifacts: Vec<ArtifactRow>,
297- live: Option<String>,
324+ live: String,
298325 ) -> Result<impl View> {
299326 Ok(view! {
300327 repo_head(head: RepoHead { live: String::new(), ..head })
301- <div data-live=(live.as_deref()) data-live-state=(job.status.as_str())>
328+ <div data-live=(live.as_str()) data-live-state=(job.fingerprint.as_str())>
302329 <p class="muted small"><a href=(job.run_href.as_str())>(g::t(lang, K::RunNumber)) (job.run_number)</a></p>
303330 <section class="card">
304331 <h2>(job.name.as_str())</h2>
@@ -384,10 +411,10 @@ async fn job_page(cx: &Cx) -> Result<impl View> {
384411 offset: log_offset,
385412 first_line,
386413 } = log_tail(&log_path(&state.config.data_dir, &job.id)).await?;
387- let artifacts = state
388- .store
389- .list_artifacts(&job.id)
390- .await?
414+ let listed = state.store.list_artifacts(&job.id).await?;
415+ let ids: Vec<&str> = listed.iter().map(|artifact| artifact.id.as_str()).collect();
416+ let fingerprint = job_fingerprint(job.state.as_str(), &ids, job.log_bytes > 0);
417+ let artifacts = listed
391418 .into_iter()
392419 .map(|artifact| ArtifactRow {
393420 href: format!(
@@ -411,10 +438,10 @@ async fn job_page(cx: &Cx) -> Result<impl View> {
411438 None => String::new(),
412439 };
413440 let title = title_of(&ctx);
414- let live = (!job.state.is_terminal()).then(|| format!("{}/events", job_href(&title, &job.id)));
441+ let live = format!("{}/events", job_href(&title, &job.id));
415442 let view = JobView {
416443 name: job.name.clone(),
417- status: job.state.as_str().to_owned(),
444+ fingerprint,
418445 state: state_text(lang, job.state.as_str()),
419446 state_class: format!("ci-state ci-{}", job.state.as_str()),
420447 runner,
@@ -470,7 +497,8 @@ const LOG_EVENT_BYTES: u64 = 64 * 1024;
470497 /// The job's live stream. It opens with the status, sends a `changed` event when the status changes
471498 /// and a `log` event with each new run of log bytes. A `log` event's id is the offset past its text,
472499 /// so a reconnect (`Last-Event-ID`) resumes there. A new stream starts at `?from=`, the offset the
473-/// page already shows. The stream ends once the job is terminal and its log is read to the end.
500+/// page already shows. The stream stays open after the job is terminal and wakes only on a bump of
501+/// this job (see `CiLive`), so a finished page still hears about deleted artifacts or logs.
474502 #[route(GET "/{owner}/{repo}/ci/jobs/{job_id}/events")]
475503 async fn job_events(cx: &Cx) -> Result<Response> {
476504 let owner = path_param::<Owner>(cx);
@@ -491,11 +519,10 @@ async fn job_events(cx: &Cx) -> Result<Response> {
491519 path: log_path(&state.config.data_dir, &job.id),
492520 wake,
493521 offset,
494- status: None,
495- terminal: false,
522+ fingerprint: None,
496523 more: false,
497524 primed: false,
498- pending_status: None,
525+ pending_fingerprint: None,
499526 pending_log: None,
500527 };
501528 events_response(cx, job_stream(follow))
@@ -519,15 +546,13 @@ struct JobFollow {
519546 wake: watch::Receiver<u64>,
520547 /// The log offset read so far. The next read starts here.
521548 offset: u64,
522- /// The status last read.
523- status: Option<String>,
524- /// The job was terminal at the last read.
525- terminal: bool,
549+ /// The fingerprint last read (see `job_fingerprint`).
550+ fingerprint: Option<String>,
526551 /// The last read sent log bytes, so more may be waiting.
527552 more: bool,
528553 /// False until the first read. Later reads wait for a wake first, unless `more` is set.
529554 primed: bool,
530- pending_status: Option<String>,
555+ pending_fingerprint: Option<String>,
531556 /// The text and the offset past it.
532557 pending_log: Option<(String, u64)>,
533558 }
@@ -535,33 +560,31 @@ struct JobFollow {
535560 fn job_stream(follow: JobFollow) -> impl Stream<Item = Result<Event>> + Send + 'static {
536561 futures_util::stream::unfold(follow, |mut f| async move {
537562 loop {
538- if let Some(status) = f.pending_status.take() {
539- return Some((changed_event(status), f));
563+ if let Some(fingerprint) = f.pending_fingerprint.take() {
564+ return Some((changed_event(fingerprint), f));
540565 }
541566 if let Some((text, end)) = f.pending_log.take() {
542567 let event = Event::new().event("log").data(text).id(end.to_string());
543568 return Some((Ok(event), f));
544569 }
545- if f.terminal && !f.more {
546- return None;
547- }
570+ // A terminal job keeps the stream open too: its artifacts and log can still be deleted
571+ // by the retention purge, and the wake of that purge is the only thing that wakes it.
548572 if f.primed && !f.more && f.wake.changed().await.is_err() {
549573 return None;
550574 }
551575 f.primed = true;
552576 f.more = false;
553- let (status, terminal) = match job_status(&f.store, &f.job_id).await {
554- Ok(Some(found)) => found,
577+ let fingerprint = match job_fingerprint_now(&f.store, &f.job_id).await {
578+ Ok(Some(fingerprint)) => fingerprint,
555579 Ok(None) => return None,
556580 Err(e) => {
557581 tracing::error!(error = %e, "ci: job stream could not read the job");
558582 return None;
559583 }
560584 };
561- f.terminal = terminal;
562- if f.status.as_deref() != Some(status.as_str()) {
563- f.status = Some(status.clone());
564- f.pending_status = Some(status);
585+ if f.fingerprint.as_deref() != Some(fingerprint.as_str()) {
586+ f.fingerprint = Some(fingerprint.clone());
587+ f.pending_fingerprint = Some(fingerprint);
565588 }
566589 match read_log(&f.path, f.offset).await {
567590 Ok(Some((text, end))) => {
@@ -691,3 +714,16 @@ fn artifact_response(
691714 );
692715 Ok(res)
693716 }
717+
718+#[cfg(test)]
719+mod tests {
720+ use super::job_fingerprint;
721+
722+ #[test]
723+ fn an_artifact_or_the_log_changing_changes_the_fingerprint() {
724+ let base = job_fingerprint("success", &["a1"], true);
725+ assert_eq!(base, "success|a1|log");
726+ assert_ne!(base, job_fingerprint("success", &[], true));
727+ assert_ne!(base, job_fingerprint("success", &["a1"], false));
728+ }
729+}
crates/forge-web/src/pages/ci_runs.rsmodified+0 -7
@@ -1958,13 +1958,6 @@ pub(crate) async fn run_status(store: &Store, run_id: &str) -> Result<Status> {
19581958 .map(|run| (run.state.as_str().to_owned(), run_finished(&run.state))))
19591959 }
19601960
1961-pub(crate) async fn job_status(store: &Store, job_id: &str) -> Result<Status> {
1962- Ok(store
1963- .job_by_id(job_id)
1964- .await?
1965- .map(|job| (job.state.as_str().to_owned(), job.state.is_terminal())))
1966-}
1967-
19681961 /// One `changed` event carrying the status word.
19691962 pub(crate) fn changed_event(status: String) -> Result<Event> {
19701963 Ok(Event::new().event("changed").data(status))
crates/forge-web/src/pages/ci_tests.rsmodified+7 -6
@@ -432,9 +432,10 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() {
432432
433433 finish_job(&fx).await;
434434 let done = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await;
435+ // A finished job stays live: a retention purge can still take its artifacts and log.
435436 assert!(
436- !done.text().contains(&job_marker),
437- "job not live when finished"
437+ done.text().contains(&job_marker),
438+ "job still live when finished"
438439 );
439440 assert!(
440441 !done.text().contains("http-equiv=\"refresh\""),
@@ -472,7 +473,7 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() {
472473 let first = next_event(&mut job_frames).await.expect("the job status");
473474 assert_eq!(
474475 first,
475- format!("event: changed\ndata: {}\n\n", job.state.as_str()).into_bytes()
476+ format!("event: changed\ndata: {}||nolog\n\n", job.state.as_str()).into_bytes()
476477 );
477478
478479 // A bump with no new log bytes and no status change sends nothing.
@@ -500,7 +501,7 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() {
500501 let last = next_event(&mut job_frames).await.expect("the final status");
501502 assert_eq!(
502503 last,
503- format!("event: changed\ndata: {}\n\n", JobState::Success.as_str()).into_bytes()
504+ format!("event: changed\ndata: {}||nolog\n\n", JobState::Success.as_str()).into_bytes()
504505 );
505506 assert!(next_event(&mut job_frames).await.is_none(), "stream ends");
506507 }
@@ -618,7 +619,7 @@ async fn job_log_events() {
618619 let first = next_event(&mut frames).await.expect("the status");
619620 assert_eq!(
620621 first,
621- format!("event: changed\ndata: {}\n\n", job.state.as_str()).into_bytes()
622+ format!("event: changed\ndata: {}||nolog\n\n", job.state.as_str()).into_bytes()
622623 );
623624
624625 let mut file = std::fs::OpenOptions::new()
@@ -724,7 +725,7 @@ async fn job_page_log_tail() {
724725 "tail offset"
725726 );
726727 assert!(
727- text.contains(&format!("data-live-state=\"{}\"", job.state.as_str())),
728+ text.contains(&format!("data-live-state=\"{}|", job.state.as_str())),
728729 "rendered status"
729730 );
730731 }
crates/forge-web/src/pages/code_live.rsmodified+137 -24
@@ -1,14 +1,19 @@
11 //! Live stream of a repo's pages, at `/{owner}/{repo}/events`. The repo header renders `data-live`
22 //! with this URL on every repo page (see `repo::repo_head`). A code view adds its branch to the
3-//! URL. The stream sends `changed` when the header changes: stars, watchers, forks, or the repo's
4-//! name, description or visibility. On a code view of a branch it also sends `changed` when the
5-//! branch moves, or when a branch or tag is created or deleted (the ref selector and the branch
6-//! list depend on that). Moves of other refs send nothing. Commits and tags are not followed: they
7-//! do not move.
3+//! URL. The stream sends `changed` when the header changes: stars, watchers, forks, the repo's
4+//! name, description, visibility, archived flag or default branch, the open issue and pull counts,
5+//! the discussions and wiki switches, the viewer's own watch level, or the mirror's last sync. The
6+//! header follows the repo's issues and pulls, so an issue or pull opened or closed shows at once.
7+//! On a code view of a branch it also sends `changed` when the branch moves, or when a branch or
8+//! tag is created or deleted (the ref selector and the branch list depend on that). Moves of other
9+//! refs send nothing. Commits and tags are not followed: they do not move.
10+//!
11+//! The repo home page (`home_live_url`) also follows the releases, and sends `changed` when the
12+//! latest release or the linked packages' versions change. Other repo pages do not read those.
813
914 use std::path::PathBuf;
1015
11-use forge_core::Visibility;
16+use forge_core::{Repo as RepoRecord, User, Visibility};
1217 use forge_git::browse::{RefInfo, RefKind};
1318 use topcoat::Result;
1419 use topcoat::context::{Cx, app_context};
@@ -17,6 +22,7 @@ use topcoat::router::{path_param, query_params, route};
1722
1823 use crate::auth::percent_encode;
1924 use crate::live::{Topic, stream_changes};
25+use crate::pages::packages::repo_package_links;
2026 use crate::pages::refs::load_refs;
2127 use crate::pages::repo_ctx::{fork_count, load_repo};
2228 use crate::state::AppState;
@@ -27,6 +33,7 @@ path_param!(repo);
2733 #[query_params(error = bad_request)]
2834 struct LiveQuery {
2935 ref_name: Option<String>,
36+ home: Option<String>,
3037 }
3138
3239 /// Whether a code view of `ref_name` follows the branch: the ref is a branch of the repo.
@@ -40,6 +47,12 @@ pub fn branch_live_url(owner: &str, repo: &str, branch: &str) -> String {
4047 format!("/{owner}/{repo}/events?ref_name={}", percent_encode(branch))
4148 }
4249
50+/// The stream URL of the repo home page: the branch's stream, which also follows the releases and
51+/// the linked packages.
52+pub fn home_live_url(owner: &str, repo: &str, branch: &str) -> String {
53+ format!("{}&home=1", branch_live_url(owner, repo, branch))
54+}
55+
4356 /// The stream URL of a repo page. A code view of a branch adds the branch to it.
4457 pub fn live_url(owner: &str, repo: &str, refs: &[RefInfo], ref_name: &str) -> String {
4558 if follows_branch(refs, ref_name) {
@@ -66,19 +79,75 @@ async fn refs_fingerprint(path: PathBuf, branch: String) -> Result<String> {
6679 }
6780
6881 /// The state the repo header shows. A repo that is gone reads as empty, which ends nothing: the
69-/// stream then sends `changed` once and the page's own re-read shows the 404.
70-async fn header_fingerprint(state: &AppState, repo_id: &str) -> Result<String> {
82+/// stream then sends `changed` once and the page's own re-read shows the 404. `viewer_id` is the
83+/// signed-in viewer, whose watch level the header shows.
84+async fn header_fingerprint(
85+ state: &AppState,
86+ repo_id: &str,
87+ viewer_id: Option<&str>,
88+) -> Result<String> {
7189 let Some(repo) = state.store.repo_by_id(repo_id).await? else {
7290 return Ok(String::new());
7391 };
7492 let stars = state.store.star_count(repo_id).await?;
7593 let watchers = state.store.watchers(repo_id).await?.len();
7694 let forks = fork_count(state, repo_id).await?;
95+ let (open_issues, _) = state.store.issue_counts(repo_id).await?;
96+ let (open_pulls, _) = state.store.pull_counts(repo_id).await?;
97+ let discussions = state.store.discussions_enabled(repo_id).await?;
98+ let wiki = state.store.wiki_enabled(repo_id).await?;
99+ let watch = match viewer_id {
100+ Some(viewer) => format!("{:?}", state.store.watch_level(viewer, repo_id).await?),
101+ None => String::new(),
102+ };
103+ let mirror = match state.store.pull_mirror(repo_id).await? {
104+ Some(m) => format!(
105+ "{} {} {:?}",
106+ m.url,
107+ m.last_sync_at.as_deref().unwrap_or(""),
108+ m.last_ok
109+ ),
110+ None => String::new(),
111+ };
112+ Ok(header_text(&repo, [stars, watchers as u64, forks, open_issues, open_pulls], &format!(
113+ "{discussions} {wiki} {watch}\n{mirror}"
114+ )))
115+}
116+
117+/// Joins the header's fields into the fingerprint text.
118+fn header_text(repo: &RepoRecord, counts: [u64; 5], rest: &str) -> String {
77119 let public = repo.visibility == Visibility::Public;
78- Ok(format!(
79- "{}\n{}\n{public}\n{}\n{stars} {watchers} {forks}",
80- repo.owner_name, repo.name, repo.description
81- ))
120+ let [stars, watchers, forks, issues, pulls] = counts;
121+ format!(
122+ "{}\n{}\n{public}\n{}\n{stars} {watchers} {forks} {issues} {pulls} {} {}\n{rest}",
123+ repo.owner_name, repo.name, repo.description, repo.archived, repo.default_branch
124+ )
125+}
126+
127+/// The state the home page's latest-release card and linked-package card show.
128+async fn home_fingerprint(state: &AppState, repo_id: &str, viewer: Option<&User>) -> Result<String> {
129+ let mut release_text = String::new();
130+ if let Some(release) = state.store.latest_release(repo_id).await? {
131+ let assets = state.store.list_release_assets(&release.id).await?;
132+ let names: Vec<String> = assets
133+ .iter()
134+ .map(|asset| format!("{} {}", asset.id, asset.name))
135+ .collect();
136+ release_text = format!(
137+ "{} {} {} {} {}",
138+ release.id,
139+ release.tag,
140+ release.title,
141+ release.published_at.as_deref().unwrap_or(""),
142+ names.join(" ")
143+ );
144+ }
145+ let packages = repo_package_links(state, viewer, repo_id).await?;
146+ let package_text: Vec<String> = packages
147+ .iter()
148+ .map(|link| format!("{} {}", link.name, link.latest))
149+ .collect();
150+ Ok(format!("{release_text}\n{}", package_text.join("\n")))
82151 }
83152
84153 /// The repo's live stream. Auth is the repo read check of the page: a viewer who cannot read the
@@ -87,31 +156,75 @@ async fn header_fingerprint(state: &AppState, repo_id: &str) -> Result<String> {
87156 async fn repo_events(cx: &Cx) -> Result<Response> {
88157 let owner = path_param::<Owner>(cx);
89158 let name = path_param::<Repo>(cx);
90- let branch = query_params::<LiveQuery>(cx)?
91- .ref_name
92- .clone()
93- .unwrap_or_default();
159+ let query = query_params::<LiveQuery>(cx)?;
160+ let branch = query.ref_name.clone().unwrap_or_default();
161+ let home = query.home.as_deref() == Some("1");
94162 let ctx = load_repo(cx, owner, name).await?;
95163 let state = app_context::<AppState>(cx).clone();
96- let mut topics = vec![Topic::Repo(ctx.repo.id.clone())];
164+ let repo_id = ctx.repo.id.clone();
165+ let mut topics = vec![
166+ Topic::Repo(repo_id.clone()),
167+ Topic::RepoIssues(repo_id.clone()),
168+ Topic::PullList(repo_id.clone()),
169+ ];
97170 if !branch.is_empty() {
98- topics.push(Topic::RepoRefs(ctx.repo.id.clone()));
171+ topics.push(Topic::RepoRefs(repo_id.clone()));
172+ }
173+ if home {
174+ topics.push(Topic::RepoReleases(repo_id.clone()));
99175 }
176+ let viewer = ctx.viewer.as_ref().map(|(user, _)| user.clone());
100177 let path = ctx.path.clone();
101- let repo_id = ctx.repo.id.clone();
102178 stream_changes(cx, &state.live.clone(), &topics, move || {
103179 let state = state.clone();
104180 let repo_id = repo_id.clone();
105181 let path = path.clone();
106182 let branch = branch.clone();
183+ let viewer = viewer.clone();
107184 async move {
108- let header = header_fingerprint(&state, &repo_id).await?;
109- if branch.is_empty() {
110- return Ok(header);
185+ let viewer_id = viewer.as_ref().map(|user| user.id.as_str());
186+ let mut out = header_fingerprint(&state, &repo_id, viewer_id).await?;
187+ if !branch.is_empty() {
188+ let refs = refs_fingerprint(path, branch).await?;
189+ out = format!("{out}\n{refs}");
111190 }
112- let refs = refs_fingerprint(path, branch).await?;
113- Ok(format!("{header}\n{refs}"))
191+ if home {
192+ let extra = home_fingerprint(&state, &repo_id, viewer.as_ref()).await?;
193+ out = format!("{out}\n{extra}");
194+ }
195+ Ok(out)
114196 }
115197 })
116198 .await
117199 }
200+
201+#[cfg(test)]
202+mod tests {
203+ use super::*;
204+
205+ #[tokio::test]
206+ async fn opening_an_issue_changes_the_header_state() {
207+ let dir = tempfile::tempdir().unwrap();
208+ let state = crate::test_support::test_state(dir.path()).await;
209+ let user = state
210+ .store
211+ .create_user("tahinli", None, "x", false)
212+ .await
213+ .unwrap();
214+ let repo = state
215+ .store
216+ .create_repo(&user.id, "demo", "", Visibility::Public, "main")
217+ .await
218+ .unwrap();
219+ let before = header_fingerprint(&state, &repo.id, None).await.unwrap();
220+
221+ state
222+ .store
223+ .create_issue(&repo.id, &user.id, "Broken build", "")
224+ .await
225+ .unwrap();
226+
227+ let after = header_fingerprint(&state, &repo.id, None).await.unwrap();
228+ assert_ne!(before, after);
229+ }
230+}
crates/forge-web/src/pages/code_search.rsmodified+3 -0
@@ -15,6 +15,7 @@ use crate::i18n::{
1515 self,
1616 code::{self as g, K},
1717 };
18+use crate::pages::code_live::branch_live_url;
1819 use crate::pages::commits::blocking;
1920 use crate::pages::repo::repo_head;
2021 use crate::pages::repo_ctx::load_repo;
@@ -203,6 +204,8 @@ async fn search_page(cx: &Cx) -> Result<impl View> {
203204
204205 let mut header = ctx.head(state, "code").await?;
205206 header.hide_search = true;
207+ // Results of a branch go stale when it moves: the header's stream follows that branch's head.
208+ header.live = branch_live_url(&owner_name, &repo_name, &ref_name);
206209 Ok(view! {
207210 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
208211 repo_head(head: header)
crates/forge-web/src/pages/compare.rsmodified+4 -0
@@ -615,6 +615,10 @@ async fn pull_create(cx: &Cx, Form(form): Form<PullForm>) -> Result<impl View> {
615615 pr
616616 };
617617 emit_pull(state, &ctx.repo, &Sender::of(&user), "opened", &pr).await;
618+ // The author's contribution calendar counts the pull request.
619+ state
620+ .live
621+ .bump(&crate::live::Topic::User(user.id.clone()));
618622 if !as_draft {
619623 // A draft tells nobody until it is marked ready for review.
620624 notify::dispatch(
crates/forge-web/src/pages/discussion_settings.rsmodified+3 -0
@@ -15,6 +15,7 @@ use crate::audit::{self, Actor, Target};
1515 use crate::auth::require_csrf;
1616 use crate::i18n::Lang;
1717 use crate::i18n::community::{self as g, K};
18+use crate::live::Topic;
1819 use crate::pages::repo_ctx::load_repo;
1920 use crate::state::AppState;
2021 use crate::views::repo_href;
@@ -69,6 +70,8 @@ async fn settings_discussions_save(cx: &Cx, Form(form): Form<ToggleForm>) -> Res
6970 .store
7071 .set_discussions_enabled(&ctx.repo.id, enabled)
7172 .await?;
73+ // The repo header shows the Discussions tab.
74+ state.live.bump(&Topic::Repo(ctx.repo.id.clone()));
7275 let name = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name);
7376 let action = if enabled {
7477 AuditAction::DiscussionsEnabled
crates/forge-web/src/pages/edit_history.rsmodified+7 -3
@@ -19,6 +19,7 @@ use crate::i18n::issues::{self as g, K};
1919 use crate::i18n::{self, Lang};
2020 use crate::pages::issue_parts::{ItemKind, When, item_for, parse_number};
2121 use crate::pages::issues_live::item_live_url;
22+use crate::pages::pull_live::pull_live_url;
2223 use crate::pages::repo::repo_head;
2324 use crate::pages::repo_ctx::{RepoCtx, load_repo};
2425 use crate::state::AppState;
@@ -227,13 +228,16 @@ async fn history_page(
227228 let heading = g::history_heading(lang, what);
228229 let back_label = g::back_to_item(lang, number);
229230 let count_label = g::earlier_versions(lang, entries.len());
230- // An issue's history follows the issue: a new edit adds a version to the list.
231- let live = (kind_item == ItemKind::Issue).then(|| item_live_url(&owner, &name, number));
231+ // A history follows its item: a new edit adds a version to the list.
232+ let live = match kind_item {
233+ ItemKind::Issue => item_live_url(&owner, &name, number),
234+ ItemKind::Pull => pull_live_url(&owner, &name, number),
235+ };
232236
233237 Ok(view! { cx =>
234238 shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(),
235239 repo_head(head: header)
236- <section class="issue-head" data-live=(live.as_deref()) data-live-now="">
240+ <section class="issue-head" data-live=(live.as_str()) data-live-now="">
237241 <h1 class="issue-heading">(heading.as_str())</h1>
238242 <p class="issue-byline">
239243 <a href=(back.as_str())>(back_label.as_str())</a>
crates/forge-web/src/pages/import.rsmodified+32 -1
@@ -23,6 +23,7 @@ use crate::auth::{require_csrf, require_user};
2323 use crate::i18n::migrate::{self as g, K};
2424 use crate::i18n::{self, Key, Lang};
2525 use crate::importer::api::{ApiError, RemoteApi};
26+use crate::live::{Topic, stream_changes};
2627 use crate::importer::{
2728 self, ImportOptions, JobSpec, Source, default_name, make_forgejo, make_github, make_gitlab,
2829 parse_remote, source_ref,
@@ -1037,7 +1038,7 @@ async fn jobs_list(lang: Lang, jobs: Vec<(ImportJob, Option<Repo>)>) -> Result<i
10371038 let empty = jobs.is_empty();
10381039 Ok(view! {
10391040 newrepo_tabs(lang: lang, active: "import")
1040- <section class="page-head">
1041+ <section class="page-head" data-live="/import/events">
10411042 <h1>(g::t(lang, K::JobsTitle))</h1>
10421043 </section>
10431044 if empty {
@@ -1050,6 +1051,36 @@ async fn jobs_list(lang: Lang, jobs: Vec<(ImportJob, Option<Repo>)>) -> Result<i
10501051 })
10511052 }
10521053
1054+/// What the import list shows for `user_id`: each job's id, state, source and repo, in list order.
1055+async fn jobs_fingerprint(state: &AppState, user_id: &str) -> Result<String> {
1056+ let rows = load_job_rows(state, user_id, 50).await?;
1057+ Ok(rows
1058+ .iter()
1059+ .map(|(job, repo)| {
1060+ let repo = repo
1061+ .as_ref()
1062+ .map_or(String::new(), |repo| format!("{}/{}", repo.owner_name, repo.name));
1063+ format!("{} {} {} {repo}", job.id, job.state.as_str(), job.source_ref)
1064+ })
1065+ .collect::<Vec<_>>()
1066+ .join("\n"))
1067+}
1068+
1069+/// The import list's change stream: the viewer's own jobs, from the session only. It sends when the
1070+/// list would show something different (see [`Topic::Imports`]).
1071+#[route(GET "/import/events")]
1072+async fn jobs_events(cx: &Cx) -> Result<Response> {
1073+ let viewer = require_user(cx).await?;
1074+ let state = app_context::<AppState>(cx).clone();
1075+ let user_id = viewer.0.id.clone();
1076+ stream_changes(cx, &state.live.clone(), &[Topic::Imports(user_id.clone())], move || {
1077+ let state = state.clone();
1078+ let user_id = user_id.clone();
1079+ async move { jobs_fingerprint(&state, &user_id).await }
1080+ })
1081+ .await
1082+}
1083+
10531084 #[page("/import")]
10541085 async fn jobs_page(cx: &Cx) -> Result<impl View> {
10551086 let viewer = require_user(cx).await?;
crates/forge-web/src/pages/issue_parts.rsmodified+2 -0
@@ -1351,6 +1351,8 @@ pub(crate) async fn post_comment(
13511351 if !pull {
13521352 state.live.bump_issue(&ctx.repo.id, &item.id);
13531353 }
1354+ // The author's contribution calendar counts the comment.
1355+ state.live.bump(&crate::live::Topic::User(user.id.clone()));
13541356 emit_comment(state, &ctx.repo, &sender, "created", pull, item, &comment).await;
13551357 notify::dispatch(
13561358 state,
crates/forge-web/src/pages/issues_list.rsmodified+4 -0
@@ -835,6 +835,10 @@ async fn new_issue_submit(cx: &Cx, RawForm(raw): RawForm) -> Result<impl View> {
835835 .await?;
836836 }
837837 state.live.bump_issue(&ctx.repo.id, &issue.id);
838+ // The author's contribution calendar counts the issue.
839+ state
840+ .live
841+ .bump(&crate::live::Topic::User(viewer.0.id.clone()));
838842 emit_issue(state, &ctx.repo, &Sender::of(&viewer.0), "opened", &issue).await;
839843 notify::dispatch(
840844 state,
crates/forge-web/src/pages/labels_page.rsmodified+10 -3
@@ -17,6 +17,7 @@ use crate::i18n::{self, Lang};
1717 use crate::pages::issue_meta::{
1818 RepoFrame, action_error_at, issue_subnav, refusal_message, triage_guard,
1919 };
20+use crate::pages::issues_live::list_live_url;
2021 use crate::pages::repo::repo_head;
2122 use crate::pages::repo_ctx::load_repo;
2223 use crate::state::AppState;
@@ -65,7 +66,12 @@ fn labels_href(title: &str) -> String {
6566
6667 /// The header, the label list and, for triage holders, the forms.
6768 #[component]
68-async fn labels_body(lang: Lang, frame: RepoFrame, rows: Vec<LabelRow>) -> Result<impl View> {
69+async fn labels_body(
70+ lang: Lang,
71+ frame: RepoFrame,
72+ rows: Vec<LabelRow>,
73+ live: String,
74+) -> Result<impl View> {
6975 let labels_action = labels_href(&frame.title);
7076 let defaults_action = format!("{labels_action}/defaults");
7177 let empty = rows.is_empty();
@@ -79,7 +85,7 @@ async fn labels_body(lang: Lang, frame: RepoFrame, rows: Vec<LabelRow>) -> Resul
7985 if archived {
8086 <section class="card notice" role="status">(g::t(lang, K::LabelsArchived))</section>
8187 }
82- <section class="card">
88+ <section class="card" data-live=(live.as_str()) data-live-now="">
8389 <h2>(g::t(lang, K::Labels))</h2>
8490 if empty {
8591 <p class="muted">(g::t(lang, K::NoLabelsYet))</p>
@@ -193,12 +199,13 @@ async fn labels_page(cx: &Cx) -> Result<impl View> {
193199 }
194200 })
195201 .collect();
202+ let live = list_live_url(&ctx.repo.owner_name, &ctx.repo.name);
196203 let css_href = format!("/{}/labels.css", frame.title);
197204 let page_title = g::labels_title(lang, &frame.title);
198205 Ok(view! {
199206 shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(),
200207 extra_stylesheet: Some(css_href.as_str()),
201- labels_body(lang: lang, frame: frame, rows: rows))
208+ labels_body(lang: lang, frame: frame, rows: rows, live: live))
202209 })
203210 }
204211
crates/forge-web/src/pages/milestones_page.rsmodified+5 -2
@@ -20,6 +20,7 @@ use crate::i18n::{self, Lang};
2020 use crate::pages::issue_meta::{
2121 RepoFrame, action_error_at, can_triage, issue_subnav, refusal_message, triage_guard,
2222 };
23+use crate::pages::issues_live::list_live_url;
2324 use crate::pages::repo::repo_head;
2425 use crate::pages::repo_ctx::load_repo;
2526 use crate::render::markdown::render_markdown;
@@ -232,10 +233,11 @@ async fn milestones_page(cx: &Cx) -> Result<impl View> {
232233 let csrf = frame.csrf.clone();
233234 let can_create = frame.can_triage;
234235 let create_action = milestones_href(&frame.title);
236+ let live = list_live_url(&ctx.repo.owner_name, &ctx.repo.name);
235237 Ok(view! {
236238 shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(),
237239 milestones_body(lang: lang, frame: frame, rows: rows, empty: empty, closed: closed,
238- csrf: csrf, can_create: can_create, create_action: create_action))
240+ csrf: csrf, can_create: can_create, create_action: create_action, live: live))
239241 })
240242 }
241243
@@ -250,6 +252,7 @@ async fn milestones_body(
250252 csrf: String,
251253 can_create: bool,
252254 create_action: String,
255+ live: String,
253256 ) -> Result<impl View> {
254257 let title = frame.title.clone();
255258 let can_triage = frame.can_triage;
@@ -262,7 +265,7 @@ async fn milestones_body(
262265 <section class="card notice" role="status">(g::t(lang, K::MilestonesArchived))</section>
263266 }
264267 state_tabs(lang: lang, title: title.clone(), closed: closed)
265- <section class="card">
268+ <section class="card" data-live=(live.as_str()) data-live-now="">
266269 if empty {
267270 <p class="muted">(if closed { g::t(lang, K::NoClosedMilestones) } else { g::t(lang, K::NoOpenMilestones) })</p>
268271 }
crates/forge-web/src/pages/notifications.rsmodified+8 -0
@@ -797,6 +797,14 @@ async fn set_subscription(cx: &Cx, pull: bool, form: &SubscriptionForm) -> Resul
797797 }
798798 _ => return Err(bad_request("unknown subscription action").into()),
799799 }
800+ // The page's button shows the viewer's subscription, so the page and its stream are woken.
801+ if pull {
802+ crate::pages::pull_live::bump_pull(state, &ctx.repo.id, &issue.id);
803+ } else {
804+ state
805+ .live
806+ .bump(&crate::live::Topic::Issue(issue.id.clone()));
807+ }
800808 let section = if pull { "pulls" } else { "issues" };
801809 let href = repo_href(
802810 &ctx.repo.owner_name,
crates/forge-web/src/pages/org_live.rsmodified+4 -2
@@ -3,7 +3,8 @@
33 //! a repo that is renamed or made private reaches the team page that names it.
44 //!
55 //! Every POST under `/org/{org}/{members|teams|settings}` bumps the org's topic through
6-//! [`OrgWriteLayer`], after the handler ran. A refused write bumps too, as in the pull layer. The
6+//! [`OrgWriteLayer`], after the handler ran, and the org's user topic too: its public profile shows
7+//! the about text and the member and team counts. A refused write bumps too, as in the pull layer. The
78 //! streams send `changed` only when their fingerprint moves, so over-bumping is cheap.
89 //!
910 //! Auth is the page's own: each stream runs the same `load_org` and role check as its page, so a
@@ -232,7 +233,8 @@ async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Resul
232233 };
233234 let result = next.run(cx, body).await;
234235 if let Some(org_id) = org_id {
235- state.live.bump(&Topic::Org(org_id));
236+ state.live.bump(&Topic::Org(org_id.clone()));
237+ state.live.bump(&Topic::User(org_id));
236238 }
237239 result
238240 }
crates/forge-web/src/pages/org_new.rsmodified+3 -0
@@ -16,6 +16,7 @@ use crate::audit::{self, Actor, Target};
1616 use crate::auth::{require_csrf, require_user};
1717 use crate::i18n::orgs::{self as g, K};
1818 use crate::i18n::{self, Lang};
19+use crate::live::Topic;
1920 use crate::state::AppState;
2021 use crate::views::{alert, csrf_field, shell, user_facing_message};
2122
@@ -147,5 +148,7 @@ async fn create_org(
147148 serde_json::Value::Null,
148149 )
149150 .await;
151+ // The explore list names the orgs too.
152+ state.live.bump(&Topic::Explore);
150153 Ok(Ok(org))
151154 }
crates/forge-web/src/pages/org_settings.rsmodified+5 -1
@@ -15,6 +15,7 @@ use topcoat::view::{View, component, view};
1515 use crate::audit::{self, Actor, Target};
1616 use crate::i18n::orgs::{self as g, K};
1717 use crate::i18n::{self, Lang};
18+use crate::live::Topic;
1819 use crate::pages::org_ctx::{
1920 DEFAULT_ROLES, load_org, notice_href, org_head, org_notice, require_form_csrf, require_owner,
2021 take_notice,
@@ -200,7 +201,10 @@ async fn org_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<SeeOther> {
200201 return Ok(see_other(notice_href(&back, "confirm_name")));
201202 }
202203 match state.store.delete_org(&ctx.org.id).await {
203- Ok(()) => {}
204+ Ok(()) => {
205+ // The explore list names the orgs too.
206+ state.live.bump(&Topic::Explore);
207+ }
204208 Err(forge_core::Error::Conflict(_)) => {
205209 return Ok(see_other(notice_href(&back, "has_repos")));
206210 }
crates/forge-web/src/pages/profile.rsmodified+18 -0
@@ -276,6 +276,24 @@ async fn profile_fingerprint(
276276 .await?
277277 .to_string(),
278278 ];
279+ // The header's about text and avatar, read fresh: the stream's `user` is a snapshot from connect.
280+ let about = state
281+ .store
282+ .user_by_id(&user.id)
283+ .await?
284+ .map(|fresh| fresh.about)
285+ .unwrap_or_default();
286+ lines.push(format!("about {about}"));
287+ lines.push(format!(
288+ "avatar {}",
289+ state.store.avatar_hash(&user.id).await?.unwrap_or_default()
290+ ));
291+ // An organization's page shows its member and team counts.
292+ if user.is_org() {
293+ let members = state.store.org_members(&user.id).await?.len();
294+ let teams = state.store.teams_for_org(&user.id).await?.len();
295+ lines.push(format!("org {members} {teams}"));
296+ }
279297 let pins = readable(
280298 state,
281299 actor,
crates/forge-web/src/pages/profile_pins.rsmodified+52 -4
@@ -4,17 +4,19 @@
44 //! after a save.
55
66 use forge_core::store::profile_pins::MAX_PROFILE_PINS;
7-use forge_core::{Repo, Session, User};
7+use forge_core::{Repo, Session, Store, User};
88 use topcoat::Result;
99 use topcoat::context::{Cx, app_context};
1010 use topcoat::router::content::RawForm;
1111 use topcoat::router::error::see_other;
12-use topcoat::router::{page, path_param};
12+use topcoat::router::response::Response;
13+use topcoat::router::{page, path_param, route};
1314 use topcoat::view::{View, component, view};
1415
1516 use crate::auth::{require_csrf, require_user};
1617 use crate::i18n::orgs::{self as g, K};
1718 use crate::i18n::{self, Lang};
19+use crate::live::{Topic, stream_changes};
1820 use crate::pages::issue_meta::{form_all, form_field, form_pairs};
1921 use crate::pages::org_ctx::{load_org, require_form_csrf, require_owner};
2022 use crate::state::AppState;
@@ -69,9 +71,11 @@ async fn pins_form(
6971 let csrf = viewer.1.csrf_token.clone();
7072 let title = g::t(lang, K::CustomizePins);
7173 let error = error.map(str::to_owned);
74+ // The form follows the owner's topic: a pin or a repo of the owner changed elsewhere re-renders it.
75+ let live = format!("{action}/events");
7276 Ok(view! { cx =>
7377 shell(title: title, viewer: Some(&viewer),
74- pins_body(lang: lang, action: action, csrf: csrf, options: options, error: error))
78+ pins_body(lang: lang, action: action, live: live, csrf: csrf, options: options, error: error))
7579 })
7680 }
7781
@@ -79,6 +83,7 @@ async fn pins_form(
7983 async fn pins_body(
8084 lang: Lang,
8185 action: String,
86+ live: String,
8287 csrf: String,
8388 options: Vec<PinOption>,
8489 error: Option<String>,
@@ -88,7 +93,7 @@ async fn pins_body(
8893 let empty = g::t(lang, K::NoPinnableRepos);
8994 let save = g::t(lang, K::SavePins);
9095 Ok(view! {
91- <section class="profile-pins-edit">
96+ <section class="profile-pins-edit" data-live=(live.as_str())>
9297 <h1>(g::t(lang, K::CustomizePins))</h1>
9398 <p class="muted">(intro)</p>
9499 if let Some(message) = error {
@@ -139,6 +144,33 @@ async fn save_pins(
139144 Err(see_other(back).into())
140145 }
141146
147+/// What the pin form shows: the owner's pinned repos in order, then each repo the owner may pin.
148+async fn pins_fingerprint(store: &Store, owner_id: &str) -> Result<String> {
149+ let mut lines = Vec::new();
150+ for repo in store.profile_pins(owner_id).await? {
151+ lines.push(format!("pin {}", repo.id));
152+ }
153+ for repo in store.list_repos_by_owner(owner_id).await? {
154+ lines.push(format!("repo {} {}/{}", repo.id, repo.owner_name, repo.name));
155+ }
156+ Ok(lines.join("\n"))
157+}
158+
159+/// The pin form's change stream for the signed-in user. Its own page only, as the form.
160+#[route(GET "/settings/pins/events")]
161+async fn pins_events(cx: &Cx) -> Result<Response> {
162+ let viewer = require_user(cx).await?;
163+ let state = app_context::<AppState>(cx);
164+ let owner_id = viewer.0.id.clone();
165+ let store = state.store.clone();
166+ stream_changes(cx, &state.live, &[Topic::User(owner_id.clone())], move || {
167+ let store = store.clone();
168+ let owner_id = owner_id.clone();
169+ async move { pins_fingerprint(&store, &owner_id).await }
170+ })
171+ .await
172+}
173+
142174 /// Gets the pin form for the signed-in user's own profile.
143175 #[page("/settings/pins")]
144176 async fn pins_page(cx: &Cx) -> Result<impl View> {
@@ -160,6 +192,22 @@ async fn pins_save(cx: &Cx, RawForm(raw): RawForm) -> Result<impl View> {
160192 save_pins(cx, viewer, owner, "/settings/pins".to_owned(), chosen, back).await
161193 }
162194
195+/// The pin form's change stream for an organization. Owners only, as the form.
196+#[route(GET "/org/{org}/settings/pins/events")]
197+async fn org_pins_events(cx: &Cx) -> Result<Response> {
198+ let ctx = load_org(cx, path_param::<Org>(cx)).await?;
199+ require_owner(&ctx)?;
200+ let state = app_context::<AppState>(cx);
201+ let owner_id = ctx.org.id.clone();
202+ let store = state.store.clone();
203+ stream_changes(cx, &state.live, &[Topic::User(owner_id.clone())], move || {
204+ let store = store.clone();
205+ let owner_id = owner_id.clone();
206+ async move { pins_fingerprint(&store, &owner_id).await }
207+ })
208+ .await
209+}
210+
163211 /// Gets the pin form for an organization. Owners only.
164212 #[page("/org/{org}/settings/pins")]
165213 async fn org_pins_page(cx: &Cx) -> Result<impl View> {
crates/forge-web/src/pages/pull_live.rsmodified+48 -1
@@ -15,6 +15,7 @@
1515 //! [`list_fingerprint`]). A bump that changes none of it sends nothing, so over-bumping is cheap.
1616
1717 use forge_core::PullRequest;
18+use forge_core::reactions::ReactionTarget;
1819 use forge_core::store::Store;
1920 use topcoat::Result;
2021 use topcoat::context::{Cx, app_context};
@@ -92,6 +93,28 @@ pub(crate) async fn pull_fingerprint(
9293 let reviews = store.list_reviews(id).await?;
9394 let threads = store.review_threads(id, viewer).await?;
9495 let statuses = store.statuses_for(repo_id, &pr.head_oid).await?;
96+ // The reactions of the body, then of each comment in the comments' order. A map's own order is
97+ // not stable, so each target is looked up by its id.
98+ let comment_ids: Vec<String> = comments.iter().map(|c| c.id.clone()).collect();
99+ let body_reactions = store
100+ .reactions_for(ReactionTarget::Issue, &[id.to_owned()], viewer)
101+ .await?;
102+ let comment_reactions = store
103+ .reactions_for(ReactionTarget::Comment, &comment_ids, viewer)
104+ .await?;
105+ let mut reaction_digest = vec![format!("{:?}", body_reactions.get(id))];
106+ reaction_digest.extend(
107+ comment_ids
108+ .iter()
109+ .map(|cid| format!("{:?}", comment_reactions.get(cid))),
110+ );
111+ let events = store.list_events(id).await?;
112+ // The merge gate reads the repo's protection rules, so a rule change changes the page.
113+ let rules = store.list_branch_rules(repo_id).await?;
114+ let subscription = match viewer {
115+ Some(viewer) => store.subscription(viewer, id).await?,
116+ None => None,
117+ };
95118
96119 let mut lines = vec![
97120 format!(
@@ -103,6 +126,18 @@ pub(crate) async fn pull_fingerprint(
103126 pr.issue.comment_count
104127 ),
105128 format!("body {}", pr.issue.body),
129+ format!(
130+ "milestone {:?} locked {} {:?}",
131+ pr.issue.milestone_id, pr.issue.locked, pr.issue.lock_reason
132+ ),
133+ format!("reactions {}", reaction_digest.join(" ")),
134+ format!(
135+ "events {} last {:?}",
136+ events.len(),
137+ events.last().map(|e| e.id.as_str())
138+ ),
139+ format!("subscription {subscription:?}"),
140+ format!("rules {rules:?}"),
106141 format!(
107142 "draft {} head {} base {} {:?} {:?} {:?} {:?}",
108143 pr.draft,
@@ -159,6 +194,11 @@ async fn pull_read(
159194
160195 // Streams
161196
197+/// The stream URL of one pull request, for its page and its edit history.
198+pub fn pull_live_url(owner: &str, repo: &str, number: i64) -> String {
199+ format!("/{owner}/{repo}/pulls/{number}/events")
200+}
201+
162202 /// The pull list's change stream. Auth is the repo read check of the list page.
163203 #[route(GET "/{owner}/{repo}/pulls/events")]
164204 async fn pulls_events(cx: &Cx) -> Result<Response> {
@@ -265,7 +305,14 @@ async fn bump_written(state: &AppState, target: Written) {
265305 };
266306 match target {
267307 Written::Pull { number, .. } => match state.store.pull_by_number(&repo.id, number).await {
268- Ok(Some(pr)) => bump_pull(state, &repo.id, &pr.issue.id),
308+ Ok(Some(pr)) => {
309+ bump_pull(state, &repo.id, &pr.issue.id);
310+ // A closed or merged pull leaves its reviewers' request lists.
311+ if pr.issue.state != forge_core::IssueState::Open || pr.merged_at.is_some() {
312+ crate::pages::review_requests::bump_pending_reviewers(state, &pr.issue.id)
313+ .await;
314+ }
315+ }
269316 Ok(None) => {}
270317 Err(e) => tracing::error!(error = %e, number, "live: loading the pull to bump failed"),
271318 },
crates/forge-web/src/pages/pull_reviews.rsmodified+2 -0
@@ -735,6 +735,8 @@ async fn review_submit(cx: &Cx, Form(form): Form<ReviewForm>) -> Result<SeeOther
735735 )
736736 .await;
737737 crate::automerge::on_pull(state, &ctx.repo, number).await;
738+ // The submitted review clears the viewer's own request, so their list changes.
739+ crate::pages::review_requests::bump_review_requests(state, &user.id);
738740 Ok(see_other(format!("{tab}#review-{}", review.id)))
739741 }
740742 Err(forge_core::Error::Forbidden(_)) => Ok(refusal(&tab, ERR_OWN_PR, "")),
crates/forge-web/src/pages/repo.rsmodified+2 -2
@@ -20,7 +20,7 @@ use topcoat::view::{View, component, view};
2020
2121 use crate::i18n::code::{self as g, K};
2222 use crate::i18n::{self, Lang};
23-use crate::pages::code_live::{branch_live_url, follows_branch};
23+use crate::pages::code_live::{follows_branch, home_live_url};
2424 use crate::pages::dashboard::badge_class;
2525 use crate::pages::finder::file_finder;
2626 use crate::pages::issue_parts::stamp_unix;
@@ -468,7 +468,7 @@ async fn repo_page(cx: &Cx) -> Result<impl View> {
468468 }
469469 let follows = follows_branch(&refs, &branch);
470470 // The home page follows the default branch even before its first push, so that push goes live.
471- let live = branch_live_url(&repo.owner_name, &repo.name, &branch);
471+ let live = home_live_url(&repo.owner_name, &repo.name, &branch);
472472 let owner_name = repo.owner_name.clone();
473473 let repo_name = repo.name.clone();
474474 let branches_href = repo_href(&owner_name, &repo_name, "branches", "");
crates/forge-web/src/pages/repo_settings.rsmodified+10 -4
@@ -34,6 +34,7 @@ use crate::i18n::merge_queue as mq;
3434 use crate::i18n::repo_admin::{self as g, K};
3535 use crate::i18n::{self, Lang};
3636 use crate::pages::discussion_settings::discussions_card;
37+use crate::pages::passkeys;
3738 use crate::pages::refs::load_refs;
3839 use crate::pages::repo::repo_head;
3940 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
@@ -645,13 +646,17 @@ async fn branch_rule_form(
645646 <fieldset class="rule-section">
646647 <legend>(g::t(lang, K::SectionMerging))</legend>
647648 <div class="switch-list">
648- <label class="switch-row">
649+ <div class="switch-row stepper-row">
649650 <span class="switch-text">
650- <span class="switch-title">(g::t(lang, K::RequiredApprovals))</span>
651+ <span class="switch-title" id="required-approvals-label">(g::t(lang, K::RequiredApprovals))</span>
651652 <span class="switch-desc">(g::t(lang, K::ApprovalsHelp))</span>
652653 </span>
653- <input type="number" name="required_approvals" min="0" max="20" step="1" inputmode="numeric" value=(required_approvals.as_str())>
654- </label>
654+ <div class="runner-pill">
655+ <button type="button" class="runner-step" data-step="-1" aria-label=(passkeys::s(lang, "Fewer", "Azalt"))>"−"</button>
656+ <input type="number" name="required_approvals" min="0" max="20" step="1" inputmode="numeric" value=(required_approvals.as_str()) aria-labelledby="required-approvals-label">
657+ <button type="button" class="runner-step" data-step="1" aria-label=(passkeys::s(lang, "More", "Artır"))>"+"</button>
658+ </div>
659+ </div>
655660 switch_row(name: "block_on_changes_requested".to_owned(), checked: block_on_changes_requested,
656661 title: g::t(lang, K::BlockWhileChanges).to_owned(), description: None)
657662 switch_row(name: "require_up_to_date".to_owned(), checked: require_up_to_date,
@@ -1035,6 +1040,7 @@ async fn settings_archive_save(cx: &Cx, Form(form): Form<ArchiveForm>) -> Result
10351040 .store
10361041 .set_repo_archived(&ctx.repo.id, archived)
10371042 .await?;
1043+ state.live.bump_repo(&ctx.repo.owner_id, &ctx.repo.id);
10381044 let action = if archived {
10391045 AuditAction::RepoArchived
10401046 } else {
crates/forge-web/src/pages/repo_settings_live.rsmodified+8 -1
@@ -143,7 +143,14 @@ async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> Result<Respons
143143 };
144144 let result = next.run(cx, body).await;
145145 if let Some(repo_id) = repo_id {
146- bump_settings(&app_context::<AppState>(cx).live, &repo_id);
146+ let state = app_context::<AppState>(cx);
147+ bump_settings(&state.live, &repo_id);
148+ // The repo header shows settings too (the mirror line, the archived notice, the tabs); its
149+ // stream sends nothing when its fingerprint holds.
150+ state.live.bump(&crate::live::Topic::Repo(repo_id.clone()));
151+ // The merge gate of a pull page reads the branch protection rules, so every pull of the
152+ // repo may show a different gate. A pull's stream sends nothing when its fingerprint holds.
153+ crate::pages::pull_live::bump_repo_pulls(state, &repo_id).await;
147154 }
148155 result
149156 }
crates/forge-web/src/pages/review_requests.rsmodified+45 -3
@@ -11,12 +11,14 @@ use topcoat::context::{Cx, app_context};
1111 use topcoat::router::content::Form;
1212 use topcoat::router::error::{SeeOther, forbidden, not_found, see_other};
1313 use topcoat::router::request::uri;
14-use topcoat::router::{page, path_param, route};
14+use topcoat::router::response::Response;
15+use topcoat::router::{Body, StatusCode, page, path_param, route};
1516 use topcoat::view::{View, component, view};
1617
17-use crate::auth::require_user;
18+use crate::auth::{current_user, require_user};
1819 use crate::i18n::authoring::{self as ga, K as AK};
1920 use crate::i18n::{self, Lang};
21+use crate::live::{Topic, stream_wakes};
2022 use crate::notify;
2123 use crate::pages::issue_parts::{ItemKind, check_write, may_change, parse_number};
2224 use crate::pages::repo_ctx::{RepoCtx, load_repo};
@@ -38,6 +40,44 @@ struct ReviewerForm {
3840 username: String,
3941 }
4042
43+/// Wakes the review-request list of `user_id`: a request was added or withdrawn, or the user
44+/// submitted a review (which clears their own request).
45+pub fn bump_review_requests(state: &AppState, user_id: &str) {
46+ state.live.bump(&Topic::ReviewRequests(user_id.to_owned()));
47+}
48+
49+/// Wakes the review-request lists of everyone with a pending request on the pull request. Call it
50+/// after the pull closed or merged, which drops it from those lists.
51+pub async fn bump_pending_reviewers(state: &AppState, issue_id: &str) {
52+ let names = match state.store.requested_reviewers(issue_id).await {
53+ Ok(names) => names,
54+ Err(e) => {
55+ tracing::error!(error = %e, issue_id, "live: listing reviewers to bump failed");
56+ return;
57+ }
58+ };
59+ for name in names {
60+ match state.store.user_by_username(&name).await {
61+ Ok(Some(user)) => bump_review_requests(state, &user.id),
62+ Ok(None) => {}
63+ Err(e) => tracing::error!(error = %e, name, "live: loading a reviewer to bump failed"),
64+ }
65+ }
66+}
67+
68+/// The review-request list's stream. The viewer comes from the session only, so a user follows only
69+/// their own list. Without a session: 401.
70+#[route(GET "/review-requests/events")]
71+async fn review_requests_events(cx: &Cx) -> Result<Response> {
72+ let Some((user, _)) = current_user(cx).await? else {
73+ let mut res = Response::new(Body::empty());
74+ *res.status_mut() = StatusCode::UNAUTHORIZED;
75+ return Ok(res);
76+ };
77+ let state = app_context::<AppState>(cx);
78+ stream_wakes(cx, &state.live, &[Topic::ReviewRequests(user.id)])
79+}
80+
4181 /// Why a request was refused, as the `reviewer_error` query word the pull page shows.
4282 fn refusal(code: &str, href: &str) -> SeeOther {
4383 see_other(format!("{href}?reviewer_error={code}#reviewers"))
@@ -72,6 +112,7 @@ async fn reviewers_save(cx: &Cx, Form(form): Form<ReviewerForm>) -> Result<SeeOt
72112 .store
73113 .withdraw_review_request(&pull.id, &target.id)
74114 .await?;
115+ bump_review_requests(state, &target.id);
75116 return Ok(see_other(format!("{href}#reviewers")));
76117 }
77118 if pull.state != forge_core::IssueState::Open {
@@ -97,6 +138,7 @@ async fn reviewers_save(cx: &Cx, Form(form): Form<ReviewerForm>) -> Result<SeeOt
97138 .request_review(&pull.id, &target.id, &user.id)
98139 .await?
99140 {
141+ bump_review_requests(state, &target.id);
100142 notify::dispatch_review_requested(state, &ctx.repo, &pull, &user.id, &target.id).await;
101143 } else {
102144 return Ok(refusal("already", &href));
@@ -243,7 +285,7 @@ async fn review_requests(cx: &Cx) -> Result<impl View> {
243285 let empty = rows.is_empty();
244286 Ok(view! {
245287 shell(title: heading, viewer: Some(&viewer),
246- <section class="page-head">
288+ <section class="page-head" data-live="/review-requests/events">
247289 <h1>(heading)</h1>
248290 </section>
249291 if empty {
crates/forge-web/src/pages/settings_live.rsmodified+248 -41
@@ -15,15 +15,19 @@
1515 //! A session revoked elsewhere is caught the same way. The re-read finds no session, so the page
1616 //! leaves for the login page.
1717 //!
18-//! Every page also holds `/-/alive` (see [`alive_response`]). For a signed-in viewer that stream
19-//! sends a `theme` event with the appearance attributes when they change, so a tab applies a theme,
20-//! accent or sidebar change made elsewhere without a reload.
18+//! Every page also holds `/-/alive` (see [`alive_response`]). That stream follows
19+//! [`Topic::ServerSettings`] for every viewer, anonymous included: a `settings` event when a live
20+//! server setting changes, so the open page re-renders. For a signed-in viewer it also sends a
21+//! `theme` event with the appearance attributes when they change, so a tab applies a theme, accent
22+//! or sidebar change made elsewhere without a reload.
2123
2224 use std::collections::VecDeque;
2325
26+use forge_core::server_settings::{self, FIELDS, Kind};
2427 use futures_util::stream;
28+use tokio::sync::watch;
2529 use topcoat::Result;
26-use topcoat::context::{Cx, app_context};
30+use topcoat::context::{Cx, app_context, try_app_context};
2731 use topcoat::router::content::sse::Event;
2832 use topcoat::router::request::{method, uri};
2933 use topcoat::router::response::Response;
@@ -57,11 +61,17 @@ async fn settings_events(cx: &Cx) -> Result<Response> {
5761 /// a tab that applies it shows what a fresh load of the page would show. The last pair, `custom_css`,
5862 /// is the stylesheet of the hue choices (empty for presets only); `nav.js` applies only `data-*`
5963 /// pairs, so it reads this one itself.
60-/// The account state the alive stream compares: the appearance (see below) and the language
61-/// preference, which changes the page text rather than its attributes.
62-pub async fn account_state(state: &AppState, user_id: &str) -> Result<(String, String)> {
64+/// The account state the alive stream compares: the appearance (see below), the language
65+/// preference, which changes the page text rather than its attributes, and the identity the
66+/// header shows (the username, the avatar's hash, admin rights) with whether the viewer's session
67+/// still exists. A session revoked elsewhere makes that last part change.
68+pub async fn account_state(
69+ state: &AppState,
70+ user_id: &str,
71+ session_id: &str,
72+) -> Result<AccountState> {
6373 let Some(user) = state.store.user_by_id(user_id).await? else {
64- return Ok((String::new(), String::new()));
74+ return Ok((String::new(), String::new(), String::new()));
6575 };
6676 let theme = match crate::theme::resolve_preference(&user.theme) {
6777 "auto" => "",
@@ -83,55 +93,177 @@ pub async fn account_state(state: &AppState, user_id: &str) -> Result<(String, S
8393 let appearance = format!(
8494 "data-theme={theme};data-accent-light={accent_light};data-accent-dark={accent_dark};data-base-light={base_light};data-base-dark={base_dark};data-sidebar={sidebar};custom_css={custom_css}",
8595 );
86- Ok((appearance, user.language.clone()))
96+ let avatar = state.store.avatar_hash(user_id).await?.unwrap_or_default();
97+ let session_open = state
98+ .store
99+ .list_sessions(user_id)
100+ .await?
101+ .iter()
102+ .any(|session| session.id == session_id);
103+ let identity = format!(
104+ "{}\n{avatar}\n{}\n{session_open}",
105+ user.username, user.is_admin
106+ );
107+ Ok((appearance, user.language.clone(), identity))
108+}
109+
110+/// The account state the alive stream compares: appearance, language, identity (see
111+/// [`account_state`]).
112+pub type AccountState = (String, String, String);
113+
114+/// The viewer's account as the alive stream follows it: the user and session ids, the wake of its
115+/// topic, and the account state last sent.
116+struct AccountFollow {
117+ user_id: String,
118+ session_id: String,
119+ wake: watch::Receiver<u64>,
120+ last: AccountState,
121+}
122+
123+/// What the alive stream holds between events.
124+struct Alive {
125+ state: AppState,
126+ /// Present for a signed-in viewer only.
127+ account: Option<AccountFollow>,
128+ server_wake: watch::Receiver<u64>,
129+ /// The server settings fingerprint last sent or seen (see [`settings_fingerprint`]).
130+ settings_last: String,
131+ queue: VecDeque<Event>,
132+}
133+
134+/// What woke the alive stream.
135+enum Wake {
136+ Account,
137+ Settings,
138+}
139+
140+/// The server settings the pages render, as one fingerprint: the values of every `Kind::Live`
141+/// setting, in field order. A `settings` event goes out when it differs from the last one sent.
142+pub fn settings_fingerprint(state: &AppState) -> String {
143+ let live = state.live();
144+ FIELDS
145+ .iter()
146+ .filter(|f| f.kind == Kind::Live)
147+ .map(|f| server_settings::get(&live, f.key))
148+ .collect::<Vec<_>>()
149+ .join("\n")
150+}
151+
152+/// Waits for the viewer's account topic. A stream with no signed-in viewer waits on nothing.
153+async fn wait_account(account: &mut Option<AccountFollow>) -> bool {
154+ match account {
155+ Some(follow) => follow.wake.changed().await.is_ok(),
156+ None => std::future::pending().await,
157+ }
87158 }
88159
89-/// The response of `GET /-/alive`, the stream every page holds. Anonymous: it only stays open, as
90-/// before. A signed-in viewer also follows their account topic, and each time the appearance differs
91-/// from the last one sent it gets a `theme` event carrying the new attributes (see `nav.js`). The
92-/// stream still opens with `retry`, and its open still means the server is back.
160+/// The response of `GET /-/alive`, the stream every page holds. Every viewer follows the server
161+/// settings topic: a change to a live setting sends a `settings` event, and the page re-renders
162+/// (see `nav.js`). A signed-in viewer also follows their account topic: each time the appearance
163+/// differs from the last one sent it gets a `theme` event carrying the new attributes, a language
164+/// change a `language` event, and a change of the header's identity (username, avatar, admin) or a
165+/// revoked session an `account` event. The stream still opens with `retry`, and its open still
166+/// means the server is back.
93167 pub async fn alive_response(cx: &Cx) -> Result<Response> {
94- let Some((user, _)) = current_user(cx).await? else {
168+ // A router with no app state (the asset tests) has nothing to follow: the stream only stays open.
169+ let Some(state) = try_app_context::<AppState>(cx).cloned() else {
95170 return events_response(cx, stream::pending::<Result<Event>>());
96171 };
97- let state = app_context::<AppState>(cx).clone();
98- let user_id = user.id;
99- // Subscribed before the baseline is read, so a change in between is not lost.
100- let wake = state.live.subscribe(&Topic::Account(user_id.clone()));
101- let last = account_state(&state, &user_id).await?;
102- // One change can move both the appearance and the language: each gets its event, in that order.
103- let events = stream::unfold(
104- (wake, last, VecDeque::<Event>::new(), state, user_id),
105- |(mut wake, mut last, mut queue, state, user_id)| async move {
106- loop {
107- if let Some(event) = queue.pop_front() {
108- return Some((Ok(event), (wake, last, queue, state, user_id)));
172+ let viewer = current_user(cx)
173+ .await?
174+ .map(|(user, session)| (user.id, session.id));
175+ // Subscribed before each baseline is read, so a change in between is not lost.
176+ let server_wake = state.live.subscribe(&Topic::ServerSettings);
177+ let settings_last = settings_fingerprint(&state);
178+ let account = match viewer {
179+ Some((user_id, session_id)) => {
180+ let wake = state.live.subscribe(&Topic::Account(user_id.clone()));
181+ let last = account_state(&state, &user_id, &session_id).await?;
182+ Some(AccountFollow {
183+ user_id,
184+ session_id,
185+ wake,
186+ last,
187+ })
188+ }
189+ None => None,
190+ };
191+ let alive = Alive {
192+ state,
193+ account,
194+ server_wake,
195+ settings_last,
196+ queue: VecDeque::new(),
197+ };
198+ events_response(cx, stream::unfold(alive, next_alive_event))
199+}
200+
201+/// Waits for the next event of the alive stream. A wake that changes nothing the viewer sees sends
202+/// nothing. None when a topic is gone, which ends the stream.
203+async fn next_alive_event(mut alive: Alive) -> Option<(Result<Event>, Alive)> {
204+ loop {
205+ if let Some(event) = alive.queue.pop_front() {
206+ return Some((Ok(event), alive));
207+ }
208+ let Alive {
209+ state,
210+ account,
211+ server_wake,
212+ settings_last,
213+ queue,
214+ } = &mut alive;
215+ let wake = tokio::select! {
216+ woke = wait_account(account) => {
217+ if !woke {
218+ return None;
109219 }
110- if wake.changed().await.is_err() {
220+ Wake::Account
221+ }
222+ woke = server_wake.changed() => {
223+ if woke.is_err() {
111224 return None;
112225 }
113- let now = match account_state(&state, &user_id).await {
226+ Wake::Settings
227+ }
228+ };
229+ match wake {
230+ Wake::Settings => {
231+ let now = settings_fingerprint(state);
232+ if now != *settings_last {
233+ queue.push_back(Event::new().event("settings").data("1"));
234+ *settings_last = now;
235+ }
236+ }
237+ Wake::Account => {
238+ let Some(follow) = account.as_mut() else {
239+ continue;
240+ };
241+ let now = match account_state(state, &follow.user_id, &follow.session_id).await {
114242 Ok(now) => now,
115243 Err(e) => {
116244 tracing::error!(error = %e, "live: could not read the account state");
117245 return None;
118246 }
119247 };
120- if now == last {
121- continue;
122- }
123- if now.0 != last.0 {
124- queue.push_back(Event::new().event("theme").data(now.0.clone()));
125- }
126- if now.1 != last.1 {
127- // The page text is re-rendered by the client (a soft refresh, see `nav.js`).
128- queue.push_back(Event::new().event("language").data("1"));
248+ let last = &mut follow.last;
249+ if now != *last {
250+ // One change can move several parts: each gets its own event.
251+ if now.0 != last.0 {
252+ queue.push_back(Event::new().event("theme").data(now.0.clone()));
253+ }
254+ if now.1 != last.1 {
255+ // The page text is re-rendered by the client (a soft refresh, see `nav.js`).
256+ queue.push_back(Event::new().event("language").data("1"));
257+ }
258+ if now.2 != last.2 {
259+ // The header or the session changed: the page re-renders (see `nav.js`).
260+ queue.push_back(Event::new().event("account").data("1"));
261+ }
262+ *last = now;
129263 }
130- last = now;
131264 }
132- },
133- );
134- events_response(cx, events)
265+ }
266+ }
135267 }
136268
137269 /// Wraps the requests under `/settings`. Only a POST does anything. Registered on the public router
@@ -169,6 +301,8 @@ async fn bump_after_settings_write(cx: &Cx, body: Body, next: Next<'_>) -> Resul
169301
170302 #[cfg(test)]
171303 mod tests {
304+ use std::collections::BTreeMap;
305+
172306 use futures_util::StreamExt;
173307 use topcoat::router::request::Request;
174308 use topcoat::router::{Body, to_bytes};
@@ -345,4 +479,77 @@ mod tests {
345479 "alive stream: language event"
346480 );
347481 }
482+
483+ /// An anonymous page holds `/-/alive` too. A live server setting that changes, then a bump of the
484+ /// server settings topic, sends one `settings` event.
485+ #[tokio::test]
486+ async fn the_alive_stream_sends_settings_to_anonymous_viewers() {
487+ let dir = tempfile::tempdir().expect("tempdir");
488+ let state = test_state(dir.path()).await;
489+ let live = state.live.clone();
490+ let settings = state.settings.clone();
491+ let router = app_router(state);
492+
493+ let request = Request::builder()
494+ .method("GET")
495+ .uri("/-/alive")
496+ .body(Body::empty())
497+ .expect("request");
498+ let res = router.handle(request).await;
499+ let mut frames = res.into_body().into_data_stream();
500+ let retry = frames.next().await.expect("a frame").expect("data");
501+ assert!(retry.starts_with(b"retry: 1000"), "alive stream: {retry:?}");
502+
503+ let overrides = BTreeMap::from([(
504+ "banner.message".to_owned(),
505+ "maintenance tonight".to_owned(),
506+ )]);
507+ settings.publish(&overrides).expect("publish");
508+ live.bump(&Topic::ServerSettings);
509+ let event = frames.next().await.expect("a frame").expect("data");
510+ assert_eq!(
511+ &event[..],
512+ b"event: settings\ndata: 1\n\n",
513+ "alive stream: settings event"
514+ );
515+ }
516+
517+ /// A new avatar on the signed-in viewer's account reaches the alive stream as one `account` event,
518+ /// so the header re-renders.
519+ #[tokio::test]
520+ async fn the_alive_stream_sends_account_when_the_header_changes() {
521+ let dir = tempfile::tempdir().expect("tempdir");
522+ let state = test_state(dir.path()).await;
523+ let store = state.store.clone();
524+ let live = state.live.clone();
525+ let owner = store
526+ .create_user("tahinli", None, "h", false)
527+ .await
528+ .expect("user");
529+ create_session(&store, &owner.id, "owner-token", CSRF).await;
530+ let router = app_router(state);
531+
532+ let request = Request::builder()
533+ .method("GET")
534+ .uri("/-/alive")
535+ .header("cookie", format!("__Host-{SESSION_COOKIE}=owner-token"))
536+ .body(Body::empty())
537+ .expect("request");
538+ let res = router.handle(request).await;
539+ let mut alive = res.into_body().into_data_stream();
540+ let retry = alive.next().await.expect("a frame").expect("data");
541+ assert!(retry.starts_with(b"retry: 1000"), "alive stream: {retry:?}");
542+
543+ store
544+ .set_avatar(&owner.id, b"png", "avatar-two")
545+ .await
546+ .expect("avatar");
547+ live.bump(&Topic::Account(owner.id.clone()));
548+ let event = alive.next().await.expect("a frame").expect("data");
549+ assert_eq!(
550+ &event[..],
551+ b"event: account\ndata: 1\n\n",
552+ "alive stream: account event"
553+ );
554+ }
348555 }
crates/forge-web/src/pages/settings_profile.rsmodified+15 -5
@@ -19,6 +19,7 @@ use topcoat::view::{View, component, view};
1919 use crate::audit::{self, Actor, Target};
2020 use crate::auth::{require_csrf, require_user};
2121 use crate::i18n::{self, Key, Lang, about_too_long, display_name_too_long, t};
22+use crate::live::Topic;
2223 use crate::state::AppState;
2324 use crate::views::{alert, avatar_url, shell, user_facing_message};
2425
@@ -390,6 +391,11 @@ async fn profile_save(cx: &Cx, Form(form): Form<ProfileForm>) -> Result<impl Vie
390391 )
391392 .await;
392393 }
394+ // The public profile shows the name, the username and the about text: its viewers follow the
395+ // user's topic too.
396+ app_context::<AppState>(cx)
397+ .live
398+ .bump(&Topic::User(viewer.0.id.clone()));
393399 Err(see_other("/settings/profile?saved=1").into())
394400 }
395401
@@ -411,7 +417,12 @@ async fn avatar_upload(cx: &Cx, mut multipart: Multipart) -> Result<impl View> {
411417 let store = &app_context::<AppState>(cx).store;
412418
413419 let message = match store_avatar(store, &viewer.0.id, image, lang).await {
414- Ok(()) => return Err(see_other("/settings/profile?saved=avatar").into()),
420+ Ok(()) => {
421+ app_context::<AppState>(cx)
422+ .live
423+ .bump(&Topic::User(viewer.0.id.clone()));
424+ return Err(see_other("/settings/profile?saved=avatar").into());
425+ }
415426 Err(e) => match user_facing_message(&e) {
416427 Some(message) => message,
417428 None => return Err(e.into()),
@@ -430,10 +441,9 @@ async fn avatar_upload(cx: &Cx, mut multipart: Multipart) -> Result<impl View> {
430441 #[route(POST "/settings/profile/avatar/delete")]
431442 async fn avatar_remove(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
432443 let viewer = require_csrf(cx, &form.csrf).await?;
433- app_context::<AppState>(cx)
434- .store
435- .delete_avatar(&viewer.0.id)
436- .await?;
444+ let state = app_context::<AppState>(cx);
445+ state.store.delete_avatar(&viewer.0.id).await?;
446+ state.live.bump(&Topic::User(viewer.0.id.clone()));
437447 Ok(see_other("/settings/profile?saved=avatar-removed"))
438448 }
439449
crates/forge-web/src/pages/wiki.rsmodified+3 -0
@@ -23,6 +23,7 @@ use crate::audit::{self, Actor, Target};
2323 use crate::auth::{require_csrf, require_user};
2424 use crate::i18n::community::{self as g, K};
2525 use crate::i18n::{self, Lang};
26+use crate::live::Topic;
2627 use crate::pages::repo::repo_head;
2728 use crate::pages::repo_ctx::{RepoCtx, load_repo};
2829 use crate::pages::wiki_live::{bump_wiki, page_live_url, wiki_live_url};
@@ -748,6 +749,8 @@ async fn wiki_settings_post(cx: &Cx, Form(form): Form<WikiSettingsForm>) -> Resu
748749 let enable = form.enabled.is_some();
749750 let before = state.store.wiki_enabled(&ctx.repo.id).await?;
750751 state.store.set_wiki_enabled(&ctx.repo.id, enable).await?;
752+ // The repo header shows the Wiki tab.
753+ state.live.bump(&Topic::Repo(ctx.repo.id.clone()));
751754 if before != enable {
752755 let action = if enable {
753756 AuditAction::WikiEnabled
crates/forge-web/src/post_update.rsmodified+9 -0
@@ -62,6 +62,10 @@ pub async fn after_ref_update(
6262 .live
6363 .bump(&crate::live::Topic::User(repo.owner_id.clone()));
6464 }
65+ // The explore list shows each public repo's last activity, so a push moves it there.
66+ if repo.visibility == forge_core::Visibility::Public {
67+ state.live.bump(&crate::live::Topic::Explore);
68+ }
6569 crate::ci::on_ref_update(state, repo, actor_id, refname, new).await;
6670 if (refname.starts_with("refs/heads/") || refname.starts_with("refs/tags/"))
6771 && let Err(e) = crate::mirrors::enqueue_push_mirrors(state, &repo.id).await
@@ -228,6 +232,9 @@ async fn apply_commit_refs(
228232 )
229233 .await?;
230234 if closed {
235+ state.live.bump_issue(&repo.id, &issue.id);
236+ // A pull is an issue row too, so a keyword can close one.
237+ crate::pages::pull_live::bump_pull(state, &repo.id, &issue.id);
231238 emit_item_action(state, repo, sender, false, number, "closed").await;
232239 notify::dispatch(
233240 state,
@@ -249,6 +256,8 @@ async fn apply_commit_refs(
249256 store
250257 .add_event(&issue.id, actor, "referenced", json!({"commit": oid}))
251258 .await?;
259+ state.live.bump_issue(&repo.id, &issue.id);
260+ crate::pages::pull_live::bump_pull(state, &repo.id, &issue.id);
252261 }
253262 }
254263 Ok(())
crates/forge-web/src/views/mod.rsmodified+1 -1
@@ -391,7 +391,7 @@ pub async fn shell(
391391 }
392392 </header>
393393 if let Some(banner) = banner {
394- <div class=(if banner.warning { "site-banner warning" } else { "site-banner" }) role="status">
394+ <div class=(if banner.warning { "site-banner warning" } else { "site-banner" }) role="status" data-expires=(banner.expires.map(|t| t.to_string()))>
395395 <p>(banner.message.as_str())</p>
396396 <form method="post" action="/-/banner/dismiss">
397397 <input type="hidden" name="hash" value=(banner.hash.as_str())>