From 374e72194e656b81a7ece3889a901937daef7a0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 03:30:05 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20everything=20live-updates:?= =?UTF-8?q?=20server=20settings=20and=20the=20banner,=20repo=20header=20co?= =?UTF-8?q?unts=20and=20switches,=20labels,=20milestones,=20review=20reque?= =?UTF-8?q?sts,=20pull=20timeline,=20runner=20online=20state,=20health,=20?= =?UTF-8?q?CI=20artifacts=20and=20purges,=20and=20admin=20CLI=20writes;=20?= =?UTF-8?q?small-range=20settings=20and=20required=20approvals=20use=20the?= =?UTF-8?q?=20stepper?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-core/src/store/ci.rs | 61 +++- crates/forge-core/src/store/health.rs | 13 +- crates/forge-web/assets/nav.js | 57 +++- crates/forge-web/src/admin_cli.rs | 40 ++- crates/forge-web/src/admin_client.rs | 27 ++ crates/forge-web/src/alerts.rs | 15 + crates/forge-web/src/boot.rs | 1 + crates/forge-web/src/ci/api.rs | 15 + crates/forge-web/src/ci/live.rs | 51 ++++ crates/forge-web/src/ci/reaper.rs | 22 +- crates/forge-web/src/importer/mod.rs | 22 ++ crates/forge-web/src/internal.rs | 97 ++++++ crates/forge-web/src/live.rs | 28 +- crates/forge-web/src/mail/worker.rs | 7 +- crates/forge-web/src/merge_queue.rs | 22 +- crates/forge-web/src/mirrors/mod.rs | 3 + crates/forge-web/src/oci/manifests.rs | 4 + crates/forge-web/src/package_ops.rs | 12 + crates/forge-web/src/pages/admin_health.rs | 91 ++++-- crates/forge-web/src/pages/admin_runners.rs | 10 +- crates/forge-web/src/pages/admin_server.rs | 9 + crates/forge-web/src/pages/assets.rs | 4 +- crates/forge-web/src/pages/banner.rs | 3 + crates/forge-web/src/pages/ci_job.rs | 114 ++++--- crates/forge-web/src/pages/ci_runs.rs | 7 - crates/forge-web/src/pages/ci_tests.rs | 13 +- crates/forge-web/src/pages/code_live.rs | 161 ++++++++-- crates/forge-web/src/pages/code_search.rs | 3 + crates/forge-web/src/pages/compare.rs | 4 + .../src/pages/discussion_settings.rs | 3 + crates/forge-web/src/pages/edit_history.rs | 10 +- crates/forge-web/src/pages/import.rs | 33 +- crates/forge-web/src/pages/issue_parts.rs | 2 + crates/forge-web/src/pages/issues_list.rs | 4 + crates/forge-web/src/pages/labels_page.rs | 13 +- crates/forge-web/src/pages/milestones_page.rs | 7 +- crates/forge-web/src/pages/notifications.rs | 8 + crates/forge-web/src/pages/org_live.rs | 6 +- crates/forge-web/src/pages/org_new.rs | 3 + crates/forge-web/src/pages/org_settings.rs | 6 +- crates/forge-web/src/pages/profile.rs | 18 ++ crates/forge-web/src/pages/profile_pins.rs | 56 +++- crates/forge-web/src/pages/pull_live.rs | 49 ++- crates/forge-web/src/pages/pull_reviews.rs | 2 + crates/forge-web/src/pages/repo.rs | 4 +- crates/forge-web/src/pages/repo_settings.rs | 14 +- .../forge-web/src/pages/repo_settings_live.rs | 9 +- crates/forge-web/src/pages/review_requests.rs | 48 ++- crates/forge-web/src/pages/settings_live.rs | 289 +++++++++++++++--- .../forge-web/src/pages/settings_profile.rs | 20 +- crates/forge-web/src/pages/wiki.rs | 3 + crates/forge-web/src/post_update.rs | 9 + crates/forge-web/src/views/mod.rs | 2 +- 53 files changed, 1314 insertions(+), 220 deletions(-) diff --git a/crates/forge-core/src/store/ci.rs b/crates/forge-core/src/store/ci.rs index 1e8ae52..16eef91 100644 --- a/crates/forge-core/src/store/ci.rs +++ b/crates/forge-core/src/store/ci.rs @@ -738,6 +738,19 @@ impl Store { Ok(true) } + /// Whether the runner is disabled. `false` when the runner is gone. A primary-key read. + pub async fn runner_disabled(&self, id: &str) -> Result { + let conn = self.read_conn().await; + let found = fetch_opt( + &conn, + "SELECT disabled FROM ci_runners WHERE id = ?1", + (id.to_string(),), + |row| col_bool(row, 0), + ) + .await?; + Ok(found.unwrap_or(false)) + } + /// The runner's concurrency override, read fresh. `None` when unset or the runner is gone. pub async fn runner_concurrency_override(&self, id: &str) -> Result> { let conn = self.read_conn().await; @@ -1641,26 +1654,38 @@ impl Store { /// but the newest `keep_runs` runs that have artifacts are deleted (0 keeps all). Then, if /// `max_total_bytes` is non-zero and the artifacts left still exceed it, the artifacts of the /// oldest runs are deleted a whole run at a time until the total fits. Artifact ids are - /// returned (deduplicated) so the caller deletes the files. + /// returned (deduplicated) so the caller deletes the files. Run ids are returned too (the runs + /// whose logs or artifacts went), so the pages showing them can be woken. pub async fn purge_old( &self, logs_before: &str, artifacts_before: &str, keep_runs: u32, max_total_bytes: u64, - ) -> Result<(Vec, Vec)> { + ) -> Result<(Vec, Vec, Vec)> { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; - let outcome: Result<(Vec, Vec)> = async { - let job_ids = fetch_all( + let outcome: Result<(Vec, Vec, Vec)> = async { + // Which run owns each artifact, read before the rows go. + let owners: BTreeMap = fetch_all( &tx, - "SELECT j.id FROM ci_jobs j JOIN ci_runs r ON r.id = j.run_id \ + "SELECT a.id, j.run_id FROM ci_artifacts a JOIN ci_jobs j ON j.id = a.job_id", + (), + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), + ) + .await? + .into_iter() + .collect(); + let log_jobs = fetch_all( + &tx, + "SELECT j.id, j.run_id FROM ci_jobs j JOIN ci_runs r ON r.id = j.run_id \ WHERE r.finished_at IS NOT NULL AND r.finished_at < ?1 AND j.log_bytes > 0 \ ORDER BY j.id", (logs_before.to_string(),), - |row| col_text(row, 0), + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), ) .await?; + let job_ids: Vec = log_jobs.iter().map(|(id, _)| id.clone()).collect(); for id in &job_ids { tx.execute( "UPDATE ci_jobs SET log_bytes = 0 WHERE id = ?1", @@ -1738,7 +1763,14 @@ impl Store { artifact_ids.sort(); artifact_ids.dedup(); - Ok((job_ids, artifact_ids)) + let mut run_ids: Vec = log_jobs + .into_iter() + .map(|(_, run)| run) + .chain(artifact_ids.iter().filter_map(|id| owners.get(id).cloned())) + .collect(); + run_ids.sort(); + run_ids.dedup(); + Ok((job_ids, artifact_ids, run_ids)) } .await; finish(tx, outcome).await @@ -3278,11 +3310,12 @@ mod tests { assert_eq!( fx.store.purge_old(DAWN, DAWN, 0, 0).await.unwrap(), - (vec![], vec![]) + (vec![], vec![], vec![]) ); - let (logs, artifacts) = fx.store.purge_old(&later, &later, 0, 0).await.unwrap(); + let (logs, artifacts, runs) = fx.store.purge_old(&later, &later, 0, 0).await.unwrap(); assert_eq!(logs, vec![a.id.clone()]); assert_eq!(artifacts.len(), 1); + assert_eq!(runs, vec![run.id.clone()]); assert_eq!(job_named(&fx.store, &run.id, "a").await.log_bytes, 0); assert!( fx.store @@ -3291,8 +3324,8 @@ mod tests { .unwrap() .is_none() ); - let (logs2, artifacts2) = fx.store.purge_old(&later, &later, 0, 0).await.unwrap(); - assert!(logs2.is_empty() && artifacts2.is_empty()); + let (logs2, artifacts2, runs2) = fx.store.purge_old(&later, &later, 0, 0).await.unwrap(); + assert!(logs2.is_empty() && artifacts2.is_empty() && runs2.is_empty()); } #[tokio::test] @@ -3319,12 +3352,12 @@ mod tests { tokio::time::sleep(Duration::from_millis(2)).await; } // Keep the newest two runs: the oldest run's artifact goes. - let (_, deleted) = fx.store.purge_old(DAWN, DAWN, 2, 0).await.unwrap(); + let (_, deleted, _) = fx.store.purge_old(DAWN, DAWN, 2, 0).await.unwrap(); assert_eq!(deleted, vec![artifacts[0].clone()]); // 20 + 30 bytes left against a 35 byte limit: the older run (20 bytes) goes. - let (_, deleted) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap(); + let (_, deleted, _) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap(); assert_eq!(deleted, vec![artifacts[1].clone()]); - let (_, again) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap(); + let (_, again, _) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap(); assert!(again.is_empty()); } diff --git a/crates/forge-core/src/store/health.rs b/crates/forge-core/src/store/health.rs index df5c53f..d291844 100644 --- a/crates/forge-core/src/store/health.rs +++ b/crates/forge-core/src/store/health.rs @@ -2,11 +2,22 @@ use super::{Store, col_int, fetch_opt}; use crate::error::{Error, Result}; -use crate::time::stamp_ago; +use crate::time::{stamp_ago, stamp_to_unix}; /// Window in which a runner's last report counts as online. pub const RUNNER_ONLINE_SECS: u64 = 90; +/// Whether a runner counts as online at `now_unix`: enabled, and its last report within +/// [`RUNNER_ONLINE_SECS`]. The runners page dot and the live signal of the runners page both use +/// this one rule. +pub fn runner_is_online(disabled: bool, last_seen_at: Option<&str>, now_unix: i64) -> bool { + let limit = i64::try_from(RUNNER_ONLINE_SECS).unwrap_or(i64::MAX); + !disabled + && last_seen_at + .and_then(stamp_to_unix) + .is_some_and(|seen| now_unix.saturating_sub(seen) <= limit) +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct HealthCounts { pub repos: i64, diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 760d284..82ee8b1 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -174,6 +174,7 @@ syncPush(); syncTick(); syncRel(); + syncBannerExpiry(); } // The log tail is a terminal: it opens at its end. A reader who scrolls up keeps their place. @@ -550,7 +551,11 @@ if (window.EventSource) { alive = keepOpen('/-/alive', aliveOpen, aliveDown, { theme: applyAppearance, - language: function () { refreshLive(true); } + language: function () { refreshLive(true); }, + // The header's identity (username, avatar, admin rights) or the session changed: the page re-renders. + account: function () { refreshLive(true); }, + // A live server setting changed (the banner, registration, limits...): the page re-renders. + settings: function () { refreshLive(true); } }); document.addEventListener('visibilitychange', function () { wake(false); }); document.addEventListener('resume', function () { wake(true); }); @@ -768,7 +773,9 @@ document.addEventListener('click', function (e) { var btn = e.target && e.target.closest ? e.target.closest('[data-step]') : null; if (!btn || !btn.form) { return; } - var field = btn.form.querySelector('input[type="number"]'); + // The pill's own field first: a form can hold several number fields (the server settings). + var pill = btn.closest('.runner-pill'); + var field = (pill && pill.querySelector('input[type="number"]')) || btn.form.querySelector('input[type="number"]'); if (!field) { return; } var next = (parseFloat(field.value) || 0) + (parseFloat(btn.getAttribute('data-step')) || 0); var min = parseFloat(field.min); @@ -1099,19 +1106,18 @@ // Live unread count. The bell is re-rendered by every swap, so it is looked up on each update. One // EventSource serves the page and stays open across swaps. It is opened only while a bell is shown // (signed-in pages) and closed when the bell is gone. The server pushes each change; nothing polls. + // The count shows twice: on the bell, and next to Notifications in the sidebar and the phone menu. var unreadStream = null; function bell() { return document.querySelector('a.bell'); } - // Shows the count the way the server renders it: a `.bell-count` span with the number, or no span at zero. - function setUnread(n) { - var el = bell(); - if (!el) { return; } - var badge = el.querySelector('.bell-count'); + // Shows the count in one link the way the server renders it: a span with the number, or no span at zero. + function setCount(el, cls, n) { + var badge = el.querySelector('.' + cls); if (n > 0) { if (!badge) { badge = document.createElement('span'); - badge.className = 'bell-count'; + badge.className = cls; el.appendChild(badge); } badge.textContent = String(n); @@ -1120,6 +1126,14 @@ } } + function setUnread(n) { + var el = bell(); + if (el) { setCount(el, 'bell-count', n); } + // The sidebar's Notifications link (the sidebar and the phone menu hold one each), `.count` as the server renders it. + var links = document.querySelectorAll('nav.side-links a[href="/notifications"]'); + for (var i = 0; i < links.length; i++) { setCount(links[i], 'count', n); } + } + function syncUnread() { if (!bell()) { if (unreadStream) { unreadStream.close(); unreadStream = null; } @@ -1625,14 +1639,14 @@ // with no history entry and the scroll kept. A job page also has a log tail (data-live-log) whose // `log` events append the new bytes as they come. The stream opens at the tail's data-offset, and // each swap brings a fresh offset, so the stream is opened again after every swap. The server ends - // the stream once the status is terminal, and the swap that shows that page (no data-live) closes it. + // 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. // Every element with data-live names an event stream the page follows: the repo header, the // page's own list, issue or run. One EventSource is open per distinct URL, so a page with several // streams updates for each of them. A `changed` event re-fetches the page and swaps it in with no // history entry and the scroll kept. A job page also has a log tail (data-live-log) whose `log` // events append the new bytes as they come. The tail's stream opens at its data-offset, and each // swap brings a fresh offset, so that stream is opened again after every swap. The server ends - // the stream once the status is terminal, and the swap that shows that page (no data-live) closes it. + // 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. var liveStreams = {}; // URL (with the tail's offset) -> EventSource var liveTimer = null; // a run list's pending refresh: bursts of events (log lines) share one @@ -1656,7 +1670,8 @@ function openLive(url) { var es = new EventSource(url); es.addEventListener('changed', function (e) { - // A job page's stream opens with the status the page already shows: nothing to re-render then. + // A job event carries the job's fingerprint (status|artifact ids|log), which the page renders as + // data-live-state. The same fingerprint means nothing changed: nothing to re-render then. var job = document.querySelector('[data-live-log]'); var wrap = job ? job.closest('[data-live]') : null; if (wrap && wrap.getAttribute('data-live-state') === e.data) { return; } @@ -1704,7 +1719,8 @@ // A change re-renders the current page. It waits while a navigation is on the wire, since that // response could be superseded: the change is kept and sent after that request completes. - // `force` re-renders a page that holds no stream of its own (a language change, sent by /-/alive). + // `force` re-renders a page that holds no stream of its own (a language change, or a live server + // setting such as the banner, sent by /-/alive). function refreshLive(force) { if (!force && !Object.keys(liveStreams).length) { return; } // A one-time secret (a token, recovery codes) is on screen only in the response that made it: a @@ -1813,6 +1829,22 @@ } } + // The site banner with an expiry carries `data-expires` (unix seconds). When it passes, the banner + // is removed here, so an open page does not keep one that is gone. One timer is armed for the + // banner on the page; a swap re-arms it. setTimeout takes a 32-bit delay, so a longer wait is armed + // again when this one fires. + var bannerTimer = null; + + function syncBannerExpiry() { + if (bannerTimer) { clearTimeout(bannerTimer); } + bannerTimer = null; + var banner = document.querySelector('.site-banner[data-expires]'); + if (!banner) { return; } + var wait = (parseInt(banner.getAttribute('data-expires'), 10) || 0) * 1000 - Date.now(); + if (wait <= 0) { banner.remove(); return; } + bannerTimer = setTimeout(syncBannerExpiry, Math.min(wait, 2147483647)); + } + function syncRel() { var now = document.documentElement.getAttribute('data-rel-now'); relSkew = now === null ? 0 : (parseInt(now, 10) || 0) * 1000 - Date.now(); @@ -1888,6 +1920,7 @@ syncPush(); syncTick(); syncRel(); + syncBannerExpiry(); window.__forgeQuery = function (href) { var url = pageUrl(href); diff --git a/crates/forge-web/src/admin_cli.rs b/crates/forge-web/src/admin_cli.rs index e99edc0..f1436df 100644 --- a/crates/forge-web/src/admin_cli.rs +++ b/crates/forge-web/src/admin_cli.rs @@ -25,7 +25,7 @@ use forge_core::store::user_delete::{DeletionReport, GHOST_USERNAME}; use forge_core::{AuditAction, Config, Error, Store, names, token}; use forge_git::GitEnv; -use crate::admin_client::running_server; +use crate::admin_client::{notify_live, running_server}; use crate::audit::{self, Actor, Target}; use crate::auth::hash_password_async; use crate::backup::{ @@ -98,6 +98,11 @@ pub async fn create_user( serde_json::json!({ "admin": user.is_admin }), ) .await; + notify_live( + &config, + serde_json::json!({ "admin": ["users", "audit"], "user_ids": [user.id] }), + ) + .await; println!( "created user {} (id {}{})", user.username, @@ -112,7 +117,16 @@ pub async fn create_user( pub async fn delete_user(config_path: &Path, username: &str, yes: bool) -> forge_core::Result<()> { let config = Config::load(config_path)?; let store = Store::open(&config.database).await?; + // The id is gone once the account is deleted, so it is read first. + let user_id = store.user_by_username(username).await?.map(|u| u.id); let report = delete_user_in(&store, username, yes).await?; + if let Some(id) = user_id { + notify_live( + &config, + serde_json::json!({ "admin": ["users", "audit"], "user_ids": [id] }), + ) + .await; + } print_deletion_report(&format!("deleted {username}"), &report); Ok(()) } @@ -207,6 +221,15 @@ pub async fn set_username( serde_json::json!({ "from": user.username }), ) .await; + notify_live( + &config, + serde_json::json!({ + "admin": ["users", "audit"], + "user_ids": [user.id], + "account_ids": [user.id], + }), + ) + .await; println!("renamed {} to {}", user.username, display); Ok(()) } @@ -216,7 +239,19 @@ pub async fn set_username( pub async fn reset_password(config_path: &Path, username: &str) -> forge_core::Result<()> { let config = Config::load(config_path)?; let store = Store::open(&config.database).await?; + let user_id = store.user_by_username(username).await?.map(|u| u.id); let (password, display) = reset_password_in(&store, username).await?; + if let Some(id) = user_id { + notify_live( + &config, + serde_json::json!({ + "admin": ["users", "audit"], + "user_ids": [id], + "account_ids": [id], + }), + ) + .await; + } println!("temporary password for {display}: {password}"); println!("all sessions of {display} were signed out; change this password after logging in"); Ok(()) @@ -301,6 +336,9 @@ pub async fn audit_purge(config_path: &Path, days: u64) -> forge_core::Result<() let cutoff = forge_core::time::stamp_ago(Duration::from_secs(days.saturating_mul(86_400))); let removed = store.purge_audit_before(&cutoff).await?; tracing::info!(removed, cutoff = %cutoff, "purged audit log entries"); + if removed > 0 { + notify_live(&config, serde_json::json!({ "admin": ["audit"] })).await; + } println!("purged {removed} audit log entries older than {days} days"); Ok(()) } diff --git a/crates/forge-web/src/admin_client.rs b/crates/forge-web/src/admin_client.rs index a27f7f1..f14fcce 100644 --- a/crates/forge-web/src/admin_client.rs +++ b/crates/forge-web/src/admin_client.rs @@ -91,6 +91,33 @@ pub async fn running_server(config: &Config) -> Result> { })) } +/// How long a CLI write waits for the running server to answer a live notice. +const NOTIFY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2); + +/// Tells the running server which open pages a CLI write changed (`/internal/admin/live`). Best +/// effort: no server, a stale socket, a refusal or a timeout is logged at debug and ignored, so +/// the command never fails because of it. +pub async fn notify_live(config: &Config, body: Value) { + let server = match running_server(config).await { + Ok(Some(server)) => server, + Ok(None) => return, + Err(e) => { + tracing::debug!(error = %e, "live: no server to notify"); + return; + } + }; + match tokio::time::timeout( + NOTIFY_TIMEOUT, + server.post::("/internal/admin/live", &body), + ) + .await + { + Ok(Ok(_)) => {} + Ok(Err(e)) => tracing::debug!(error = %e, "live: the server refused the notice"), + Err(_) => tracing::debug!("live: the server did not answer the notice in time"), + } +} + #[derive(serde::Deserialize)] struct ErrorBody { error: String, diff --git a/crates/forge-web/src/alerts.rs b/crates/forge-web/src/alerts.rs index cee34fe..848aa81 100644 --- a/crates/forge-web/src/alerts.rs +++ b/crates/forge-web/src/alerts.rs @@ -327,6 +327,18 @@ pub async fn check_runners_at(state: &AppState, now: i64) { } }; let mut offline = std::collections::BTreeSet::new(); + // The runners page dot flips on its own window, so a runner that goes quiet changes the page + // here, not on its next report. Only a change wakes the page. + for runner in &runners { + let online = forge_core::store::health::runner_is_online( + runner.disabled, + runner.last_seen_at.as_deref(), + now, + ); + state.ci_live.note_runner_online(&runner.id, online); + } + let ids: Vec<&str> = runners.iter().map(|r| r.id.as_str()).collect(); + state.ci_live.forget_runners_except(&ids); for runner in &runners { let seen = runner.last_seen_at.as_deref().and_then(stamp_to_unix); if runner.disabled || !alerts::runner_is_offline(now, seen, cfg.runner_offline_minutes) { @@ -354,6 +366,9 @@ pub async fn check_slow(state: &AppState) { check_disk(state).await; check_backup_overdue(state, now_unix()).await; check_replication(state, now_unix()).await; + // A copy goes lagging by the clock alone, so the replication page is woken on this tick. Its + // fingerprint drops the wake when no row changed. + crate::live::admin().bump(&crate::live::Topic::AdminReplication); let old = forge_core::time::stamp_ago(std::time::Duration::from_secs(90 * 86_400)); if let Err(e) = state.store.prune_admin_alerts(&old).await { tracing::error!(error = %e, "alerts: pruning failed"); diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index eacbeba..62dbaf9 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -159,6 +159,7 @@ pub async fn serve( } crate::alerts::on_boot(&state).await; crate::ci::reaper::spawn(state.clone()); + crate::pages::admin_health::spawn_repo_size(state.clone()); crate::ci::scheduled::spawn(state.clone()); // Topcoat's builder-wide compression is off because it cannot filter by content type or path. diff --git a/crates/forge-web/src/ci/api.rs b/crates/forge-web/src/ci/api.rs index 313bd6e..f5e1a4b 100644 --- a/crates/forge-web/src/ci/api.rs +++ b/crates/forge-web/src/ci/api.rs @@ -82,6 +82,8 @@ async fn runner_from(state: &AppState, headers: &HeaderMap) -> Result { crate::alerts::runner_seen(state, &runner.id).await; + // The stamp above is written, so a page that reads it after the wake sees it. + state.ci_live.note_runner_online(&runner.id, true); Ok(runner) } Ok(None) => Err(unauthorized()), @@ -615,6 +617,12 @@ async fn heartbeat(cx: &Cx) -> topcoat::Result { if let Err(e) = state.store.touch_runner(runner_id).await { tracing::warn!(error = %e, "ci: runner last-seen not stored"); } + // A busy runner only heartbeats here. Its state is read only when it is not + // recorded online, so a steady heartbeat costs a map lookup. + if !state.ci_live.runner_recorded_online(runner_id) { + let disabled = state.store.runner_disabled(runner_id).await.unwrap_or(false); + state.ci_live.note_runner_online(runner_id, !disabled); + } let said = headers(cx) .get(CONCURRENCY_HEADER) .and_then(|v| v.to_str().ok()) @@ -836,6 +844,13 @@ async fn upload_artifact(cx: &Cx, body: Body) -> topcoat::Result { } match upload(state, &job, name, body).await { Ok(artifact_id) => { + // The job's artifact list and its run's artifact list show the new one. The run page + // follows its repo's stream, so the repo wakes too. + state.ci_live.bump_job(&job.id); + state.ci_live.bump_run(&job.run_id); + if let Ok(Some(run)) = state.store.run_by_id(&job.run_id).await { + state.ci_live.bump_repo(&run.repo_id); + } // A new artifact may push the store past its disk limit. Enforce it now, not at the // next daily purge. The request does not wait for it. let state = state.clone(); diff --git a/crates/forge-web/src/ci/live.rs b/crates/forge-web/src/ci/live.rs index 3b913d7..83a0ab6 100644 --- a/crates/forge-web/src/ci/live.rs +++ b/crates/forge-web/src/ci/live.rs @@ -23,9 +23,43 @@ pub struct CiLive { repos: Signals, runners: Signals, queues: Signals, + /// The last online state each runner was seen in. Only a change wakes the runners pages. + runner_online: Mutex>, } impl CiLive { + /// Records whether runner `runner_id` is online now. Wakes the runners pages only when that + /// differs from the state last recorded, so a heartbeat of a runner that stays online costs one + /// map lookup. + pub fn note_runner_online(&self, runner_id: &str, online: bool) { + let changed = self + .runner_online + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert(runner_id.to_owned(), online) + != Some(online); + if changed { + self.bump_runners(); + } + } + + /// Whether runner `runner_id` was last recorded online. + pub fn runner_recorded_online(&self, runner_id: &str) -> bool { + self.runner_online + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(runner_id) + == Some(&true) + } + + /// Forgets the recorded state of every runner not in `keep`, so a deleted runner leaves no entry. + pub fn forget_runners_except(&self, keep: &[&str]) { + self.runner_online + .lock() + .unwrap_or_else(PoisonError::into_inner) + .retain(|id, _| keep.contains(&id.as_str())); + } + /// Subscribes to changes of the merge queue of repo `repo_id`: an entry was added, moved or /// finished. Same rules as [`CiLive::subscribe_job`]. pub fn subscribe_queue(&self, repo_id: &str) -> watch::Receiver { @@ -208,6 +242,23 @@ mod tests { assert!(live.jobs.counters().is_empty()); } + #[tokio::test] + async fn a_runner_wakes_the_pages_only_when_its_online_state_changes() { + let live = CiLive::default(); + let mut runners = live.subscribe_runners(); + + live.note_runner_online("runner-1", true); + assert!(runners.has_changed().expect("open")); + runners.borrow_and_update(); + + live.note_runner_online("runner-1", true); + assert!(!runners.has_changed().expect("open")); + + live.note_runner_online("runner-1", false); + assert!(runners.has_changed().expect("open")); + assert!(!live.runner_recorded_online("runner-1")); + } + #[tokio::test] async fn close_wakes_the_subscriber_once_and_then_ends_the_signal() { let live = CiLive::default(); diff --git a/crates/forge-web/src/ci/reaper.rs b/crates/forge-web/src/ci/reaper.rs index 724bd0d..a60bb2f 100644 --- a/crates/forge-web/src/ci/reaper.rs +++ b/crates/forge-web/src/ci/reaper.rs @@ -21,6 +21,9 @@ const LOST_AFTER: Duration = Duration::from_secs(120); const ALERTS_SLOW_EVERY: Duration = Duration::from_secs(5 * 60); /// How often retention runs. const PURGE_EVERY: Duration = Duration::from_secs(24 * 60 * 60); +/// How often the health page is woken. Its disk, uptime and mail figures change with the clock and +/// the disk, not with a write; its fingerprint drops a wake that changed nothing. +const HEALTH_EVERY: Duration = Duration::from_secs(60); /// Starts the reaper task. It runs until the process exits. pub fn spawn(state: AppState) { @@ -33,10 +36,15 @@ async fn run(state: AppState) { // Retention runs on the first pass after boot, then once a day. let mut next_purge = Instant::now(); let mut next_slow_alerts = Instant::now() + ALERTS_SLOW_EVERY; + let mut next_health = Instant::now() + HEALTH_EVERY; loop { tick.tick().await; reap_once(&state).await; crate::alerts::check_runners(&state).await; + if Instant::now() >= next_health { + crate::live::admin().bump(&crate::live::Topic::AdminHealth); + next_health = Instant::now() + HEALTH_EVERY; + } if Instant::now() >= next_slow_alerts { crate::alerts::check_slow(&state).await; next_slow_alerts = Instant::now() + ALERTS_SLOW_EVERY; @@ -105,7 +113,7 @@ pub async fn purge_once(state: &AppState) -> (usize, usize) { let logs_before = stamp_ago(day(ci.log_retention_days)); let artifacts_before = stamp_ago(day(ci.artifact_retention_days)); let max_total_bytes = ci.artifact_max_total_mb.saturating_mul(1024 * 1024); - let (job_ids, artifact_ids) = match state + let (job_ids, artifact_ids, run_ids) = match state .store .purge_old( &logs_before, @@ -145,5 +153,17 @@ pub async fn purge_once(state: &AppState) -> (usize, usize) { tracing::error!(error = %e, artifact_id = %id, "ci: deleting an artifact failed"); } } + // The rows are gone and the files too: the pages that list or show the logs and artifacts + // re-read them now. + for id in &job_ids { + state.ci_live.bump_job(id); + } + for id in &run_ids { + state.ci_live.bump_run(id); + // The run page follows its repo's stream. + if let Ok(Some(run)) = state.store.run_by_id(id).await { + state.ci_live.bump_repo(&run.repo_id); + } + } (log_count, artifact_count) } diff --git a/crates/forge-web/src/importer/mod.rs b/crates/forge-web/src/importer/mod.rs index 4187e78..a3eaeec 100644 --- a/crates/forge-web/src/importer/mod.rs +++ b/crates/forge-web/src/importer/mod.rs @@ -29,6 +29,7 @@ use self::api::{ApiError, ExtAsset, ExtIssue, ExtRelease, GitHub, Notice, Remote pub use self::remote::{ default_name, make_forgejo, make_github, make_gitlab, parse_remote, source_ref, }; +use crate::live::Topic; use crate::mirrors::{check_remote, policy, pull_refs, ref_snapshot}; use crate::state::AppState; @@ -39,6 +40,8 @@ static SLOTS: Semaphore = Semaphore::const_new(2); const IMPORTED_PR_LABEL: &str = "imported PR"; const IMPORTED_PR_COLOR: &str = "#8b7bd8"; const FALLBACK_LABEL_COLOR: &str = "#8b949e"; +/// Imported issues between two wakes of the repo's issue list. +const IMPORT_BUMP_BATCH: usize = 25; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Source { @@ -310,11 +313,14 @@ pub fn asset_name(name: &str) -> String { /// Starts the job in the background. It waits for a free slot, then runs. pub fn spawn_job(state: AppState, job: ImportJob, spec: JobSpec) { + // The owner's import list shows the job as queued, then finished or failed (see `run_job`). + state.live.bump(&Topic::Imports(job.user_id.clone())); tokio::spawn(async move { let Ok(_slot) = SLOTS.acquire().await else { return; }; run_production(&state, &job, &spec).await; + state.live.bump(&Topic::Imports(job.user_id.clone())); }); } @@ -385,6 +391,7 @@ pub async fn run_job( return; } bump(&job.id); + state.live.bump(&Topic::Imports(job.user_id.clone())); match run_steps(state, job, spec, api, transport, &rep).await { Ok(summary) => { rep.log("info", summary).await; @@ -576,6 +583,12 @@ impl Run<'_, A> { &self.state.store } + /// Wakes the repo's issue list, labels, milestones and tabs. Called per batch and at the end of + /// a phase, not per write. + fn bump_issues(&self) { + self.state.live.bump_repo_issues(&self.repo.id); + } + async fn mapped(&self, kind: &str, ext: &str) -> Result, String> { self.store() .import_origin(&self.repo.id, kind, ext) @@ -626,6 +639,7 @@ impl Run<'_, A> { } } } + self.bump_issues(); self.rep.log("info", format!("{total} labels read")).await; Ok(()) } @@ -677,6 +691,7 @@ impl Run<'_, A> { self.record("milestone", &m.id, &created.id, "", "").await; totals.milestones += 1; } + self.bump_issues(); Ok(()) } @@ -749,6 +764,7 @@ impl Run<'_, A> { format!("Importing {total} issues and pull requests"), ) .await; + let mut created_since_bump = 0usize; for (i, item) in items.iter().enumerate() { self.rep.stage("issues", i, total).await; let kind = if item.is_pr { "pull" } else { "issue" }; @@ -758,6 +774,11 @@ impl Run<'_, A> { None => match self.create_item(item, &mut labels, &milestones).await { Ok(id) => { self.record(kind, &ext, &id, &item.author, &item.url).await; + created_since_bump += 1; + if created_since_bump == IMPORT_BUMP_BATCH { + created_since_bump = 0; + self.bump_issues(); + } if item.is_pr { totals.pulls += 1; } else { @@ -814,6 +835,7 @@ impl Run<'_, A> { } } self.rep.stage("issues", total, total).await; + self.bump_issues(); Ok(()) } diff --git a/crates/forge-web/src/internal.rs b/crates/forge-web/src/internal.rs index f360c52..8523a2b 100644 --- a/crates/forge-web/src/internal.rs +++ b/crates/forge-web/src/internal.rs @@ -28,6 +28,7 @@ use crate::admin_client::ADMIN_TOKEN_HEADER; use crate::audit::{self, Actor, Target}; use crate::backup::scheduler::{run_backup_now, run_fsck_now}; use crate::backup::{BackupOptions, Scope}; +use crate::live::{self, Topic}; use crate::post_update::after_ref_update; use crate::state::AppState; use forge_core::AuditAction; @@ -115,6 +116,11 @@ pub fn router(state: AppState) -> Router { "/internal/admin/lfs-gc", admin_lfs_gc, )) + .route(RouteFn::new( + Method::POST, + "/internal/admin/live", + admin_live, + )) .app_context(state) .build() } @@ -190,6 +196,66 @@ fn admin_lfs_gc(cx: &Cx, body: Body) -> RouteFuture<'_> { Box::pin(async move { admin_lfs_gc_endpoint(cx, body).await }) } +fn admin_live(cx: &Cx, body: Body) -> RouteFuture<'_> { + Box::pin(async move { admin_live_endpoint(cx, body).await }) +} + +/// Body of `POST /internal/admin/live`. The CLI names what its write changed, and the server +/// wakes the same topics its own writers would. Every list may be empty. +#[derive(Deserialize, Default)] +struct AdminLiveRequest { + /// Global admin topics by short name: `users`, `audit`, `backups`, `health`, `replication`, + /// `server`. + #[serde(default)] + admin: Vec, + /// Users whose admin page and public profile changed. + #[serde(default)] + user_ids: Vec, + /// Accounts whose own settings (sessions, username) changed. + #[serde(default)] + account_ids: Vec, +} + +/// `POST /internal/admin/live`. Wakes the open pages of the running server for a write made by +/// another process (the admin CLI). The body is small and the answer carries no data. +async fn admin_live_endpoint(cx: &Cx, body: Body) -> topcoat::Result { + let state = app_context::(cx); + if !admin_authorized(cx, state) { + return Err(forbidden().into()); + } + let bytes = to_bytes(body, MAX_BODY_BYTES).await?; + let req: AdminLiveRequest = serde_json::from_slice(&bytes) + .map_err(|e| bad_request(format!("invalid live request: {e}")))?; + let mut admin_topics = Vec::with_capacity(req.admin.len()); + for name in &req.admin { + admin_topics.push(match name.as_str() { + "users" => Topic::AdminUsers, + "audit" => Topic::AdminAudit, + "backups" => Topic::AdminBackups, + "health" => Topic::AdminHealth, + "replication" => Topic::AdminReplication, + "server" => Topic::AdminServer, + other => { + return Ok(admin_error(&forge_core::Error::Invalid(format!( + "unknown admin topic: {other}" + )))); + } + }); + } + let hub = live::admin(); + for topic in &admin_topics { + hub.bump(topic); + } + for id in &req.user_ids { + hub.bump(&Topic::AdminUser(id.clone())); + state.live.bump(&Topic::User(id.clone())); + } + for id in &req.account_ids { + state.live.bump(&Topic::Account(id.clone())); + } + Ok(admin_response(StatusCode::OK, serde_json::json!({ "ok": true }))) +} + /// `POST /internal/admin/lfs-gc`. The body is ignored. async fn admin_lfs_gc_endpoint(cx: &Cx, _body: Body) -> topcoat::Result { let state = app_context::(cx); @@ -795,6 +861,37 @@ mod tests { assert_eq!(res.status(), 200); } + /// The live route needs the admin token and wakes the topics it names on the right hub. + #[tokio::test] + async fn live_bump_wakes_the_named_topics() { + let dir = tempfile::tempdir().expect("tempdir"); + let state = crate::test_support::test_state(dir.path()).await; + let users = live::admin().subscribe(&Topic::AdminUsers); + let profile = state.live.subscribe(&Topic::User("u1".to_owned())); + let router = router(state); + let body = r#"{"admin":["users"],"user_ids":["u1"]}"#; + + let refused = topcoat::router::request::Request::builder() + .method("POST") + .uri("/internal/admin/live") + .header("content-type", "application/json") + .header(ADMIN_TOKEN_HEADER, "wrong") + .body(Body::from(body)) + .expect("request"); + assert_eq!(router.handle(refused).await.status(), 403); + + let req = topcoat::router::request::Request::builder() + .method("POST") + .uri("/internal/admin/live") + .header("content-type", "application/json") + .header(ADMIN_TOKEN_HEADER, crate::test_support::ADMIN_TOKEN) + .body(Body::from(body)) + .expect("request"); + assert_eq!(router.handle(req).await.status(), 200); + assert!(users.has_changed().expect("open")); + assert!(profile.has_changed().expect("open")); + } + #[tokio::test] async fn hook_routes_are_not_collected_by_discover() { // The public router uses `.discover()`. Hook routes are plain RouteFns and must not be in it. diff --git a/crates/forge-web/src/live.rs b/crates/forge-web/src/live.rs index ea4a474..95e64f5 100644 --- a/crates/forge-web/src/live.rs +++ b/crates/forge-web/src/live.rs @@ -53,14 +53,25 @@ pub enum Topic { /// One pull request, its conversation, commits and files. Keyed by the pull's issue id. /// Bumped by [`crate::pages::pull_live`]. Pull(String), - /// A repo's own state that its header shows: stars, watchers, forks, and its name and - /// description. Keyed by repo id. + /// A repo's own state that its header shows: stars, watchers, forks, its name, description, + /// archived flag and default branch, the tab switches, and the mirror's last sync. Keyed by repo + /// id. Bumped after the write, and also when a package linked to the repo publishes or yanks (the + /// home page shows its newest version). The header's counts follow [`Topic::RepoIssues`] and + /// [`Topic::PullList`] as well. Repo(String), /// A user's repo listing, pins, contribution calendar and the signed-in sidebar's repo list. /// Keyed by user id (an organization is a user too). User(String), /// A user's inbox: a notification was added, read or marked read. Keyed by user id. Inbox(String), + /// A user's review requests: a pull request asked the user to review, a request was withdrawn, + /// the user submitted a review, or a pull request with the user's request closed or merged. + /// Keyed by the reviewer's user id. Streamed only to that user. Bumped by + /// [`crate::pages::review_requests`] and [`crate::pages::pull_live`]. + ReviewRequests(String), + /// A user's import jobs: a job was queued, started, progressed or finished. Keyed by user id. + /// Bumped by the importer when a job's state changes. Streamed only to that user. + Imports(String), /// The public repo listing: a public repo was added, changed, or starred. Global. Explore, /// 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 { AdminServer, /// The releases of a repo: a release was created, edited or deleted, an asset was added, /// replaced or removed, or an asset was downloaded (its count). Keyed by repo id. The release - /// list and the release pages follow it. Bumped by [`crate::release_ops`]. + /// list, the release pages and the repo home page's latest release card follow it. Bumped by + /// [`crate::release_ops`]. RepoReleases(String), /// A user's own settings: a profile, key, token, passkey, session, notification or appearance /// 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 { /// The commit statuses of a repo: a status was reported or replaced. Keyed by repo id. Bumped /// by the CI runner and the statuses API, after the write. CommitStatuses(String), + /// The server settings that pages render (every `Kind::Live` setting, such as the banner, the + /// registration mode or the limits): one was saved or reset. Global. Every page holds + /// `/-/alive`, anonymous viewers included, and follows it there (see + /// [`crate::pages::settings_live::alive_response`]). Bumped by the server settings after a save + /// or reset. + ServerSettings, } /// The hub of the admin pages. It is process-wide, not part of [`crate::state::AppState`]: the @@ -173,9 +191,11 @@ impl LiveHub { /// A repo changed in a way its owner's pages, the explore list and its own header show: it /// was created, renamed, moved, re-described, starred, watched or forked. Call it once per - /// owner whose listing changed (a transfer has two). + /// owner whose listing changed (a transfer has two). An organization owner's team pages list + /// its repos too, so they are woken as well. pub fn bump_repo(&self, owner_id: &str, repo_id: &str) { self.bump(&Topic::User(owner_id.to_owned())); + self.bump(&Topic::Org(owner_id.to_owned())); self.bump(&Topic::Explore); self.bump(&Topic::Repo(repo_id.to_owned())); // The owner's repo count is on the admin page of the account. diff --git a/crates/forge-web/src/mail/worker.rs b/crates/forge-web/src/mail/worker.rs index 09306b0..67d3953 100644 --- a/crates/forge-web/src/mail/worker.rs +++ b/crates/forge-web/src/mail/worker.rs @@ -68,7 +68,12 @@ async fn tick(state: &AppState) -> forge_core::Result { } let now = now_stamp(); let lease_until = stamp_after(LEASE); - for entry in state.store.lease_mail(&now, &lease_until, BATCH).await? { + let leased = state.store.lease_mail(&now, &lease_until, BATCH).await?; + if !leased.is_empty() { + // The queue page shows these as Sending while the batch goes out. + live::bump(); + } + for entry in leased { deliver(state, &entry).await; } let next = state.store.next_mail_due().await?; diff --git a/crates/forge-web/src/merge_queue.rs b/crates/forge-web/src/merge_queue.rs index 3cb875d..0d502d5 100644 --- a/crates/forge-web/src/merge_queue.rs +++ b/crates/forge-web/src/merge_queue.rs @@ -74,7 +74,7 @@ pub async fn enqueue( .await { Ok(entry) => { - notify_changed(state, &repo.id); + notify_entry(state, repo, &entry); advance(state, repo, &pr.base_branch).await; Ok(Ok(entry)) } @@ -91,7 +91,7 @@ pub async fn remove(state: &AppState, repo: &Repo, entry: &QueueEntry, reason: & .queue_finish(&entry.id, QueueState::Removed, reason) .await { - Ok(true) => notify_changed(state, &repo.id), + Ok(true) => notify_entry(state, repo, entry), Ok(false) => {} Err(e) => { tracing::error!(error = %e, repo_id = %repo.id, "merge queue: removing an entry failed"); @@ -235,7 +235,7 @@ async fn start( { return Ok(false); } - notify_changed(state, &repo.id); + notify_entry(state, repo, entry); // A run is created here only when the workflow runs for this candidate. Its statuses may // arrive before this returns; `evaluate` finds the run through its ref and commit. merge_queue_run( @@ -354,12 +354,12 @@ async fn land( Err(forge_git::error::Error::RefMoved(_)) => { // The target moved since the candidate was built: build it again on the new tip. state.store.queue_set_queued(&entry.id).await?; - notify_changed(state, &repo.id); + notify_entry(state, repo, entry); return Ok(true); } Err(e) => { state.store.queue_set_queued(&entry.id).await?; - notify_changed(state, &repo.id); + notify_entry(state, repo, entry); return Err(e.into()); } } @@ -379,7 +379,7 @@ async fn finish_removed( .store .queue_finish(&entry.id, QueueState::Removed, reason) .await?; - notify_changed(state, &repo.id); + notify_entry(state, repo, entry); Ok(()) } @@ -399,7 +399,7 @@ async fn fail( { return Ok(()); } - notify_changed(state, &repo.id); + notify_entry(state, repo, entry); let who = match state.store.user_by_id(&entry.enqueued_by).await? { Some(user) => format!("@{}", user.username), None => String::new(), @@ -414,6 +414,7 @@ async fn fail( .await { Ok(_) => { + crate::pages::pull_live::bump_pull(state, &repo.id, &pr.issue.id); notify::dispatch( state, repo, @@ -431,7 +432,8 @@ async fn fail( Ok(()) } -/// Wakes the queue pages of `repo_id`. -pub fn notify_changed(state: &AppState, repo_id: &str) { - state.ci_live.bump_queue(repo_id); +/// Wakes the queue pages of `repo_id`, and the pull page and list of the entry's pull request. +fn notify_entry(state: &AppState, repo: &Repo, entry: &QueueEntry) { + state.ci_live.bump_queue(&repo.id); + crate::pages::pull_live::bump_pull(state, &repo.id, &entry.issue_id); } diff --git a/crates/forge-web/src/mirrors/mod.rs b/crates/forge-web/src/mirrors/mod.rs index 2200df5..e636844 100644 --- a/crates/forge-web/src/mirrors/mod.rs +++ b/crates/forge-web/src/mirrors/mod.rs @@ -22,6 +22,7 @@ use reqwest::Url; use serde_json::json; use crate::audit::{self, Actor, Target}; +use crate::live::Topic; use crate::pages::repo_settings_live::bump_settings; use crate::post_update::after_ref_update; use crate::state::AppState; @@ -281,6 +282,8 @@ pub async fn run_one(state: &AppState, mirror: &Mirror, policy: &WebhookPolicy) } // The mirror list and detail of the repo's settings show the sync state, so they wake now. bump_settings(&state.live, &mirror.repo_id); + // The repo header shows the mirror's last sync and its result. + state.live.bump(&Topic::Repo(mirror.repo_id.clone())); if let Some(error) = &error { tracing::warn!(mirror_id = %mirror.id, error = %error, "mirrors: sync failed"); if mirror.last_ok != Some(false) { diff --git a/crates/forge-web/src/oci/manifests.rs b/crates/forge-web/src/oci/manifests.rs index 4cbdd09..a16ed2d 100644 --- a/crates/forge-web/src/oci/manifests.rs +++ b/crates/forge-web/src/oci/manifests.rs @@ -13,6 +13,7 @@ use topcoat::router::{Body, StatusCode, to_bytes}; use super::auth::{self, Caller, internal}; use super::blobs::{insert, write_package}; use super::{gc, oci_error}; +use crate::package_ops::bump_linked_repo; use crate::state::AppState; /// Largest manifest accepted, in bytes. @@ -184,6 +185,7 @@ pub async fn put_manifest( return internal(e); } state.packages_live.bump(&target.owner.id); + bump_linked_repo(state, &package.id).await; let mut res = Response::new(Body::empty()); *res.status_mut() = StatusCode::CREATED; insert( @@ -281,6 +283,7 @@ pub async fn delete_manifest( }, } state.packages_live.bump(&target.owner.id); + bump_linked_repo(state, &package.id).await; let mut res = Response::new(Body::empty()); *res.status_mut() = StatusCode::ACCEPTED; res @@ -311,6 +314,7 @@ pub async fn remove_tag( } gc::sweep(state, &package.id).await?; state.packages_live.bump(&owner.id); + bump_linked_repo(state, &package.id).await; Ok(true) } diff --git a/crates/forge-web/src/package_ops.rs b/crates/forge-web/src/package_ops.rs index 5928555..6932b41 100644 --- a/crates/forge-web/src/package_ops.rs +++ b/crates/forge-web/src/package_ops.rs @@ -225,9 +225,20 @@ pub async fn publish( return Err(PackageError::Internal(e.to_string())); } state.packages_live.bump(&owner.id); + bump_linked_repo(state, &package.id).await; Ok(()) } +/// Wakes the repo that `package_id` is linked to, if any: its home page shows the package's newest +/// version. A failed lookup skips the wake only, since the write has already happened. +pub async fn bump_linked_repo(state: &AppState, package_id: &str) { + if let Ok(Some(package)) = state.store.package(package_id).await + && let Some(repo_id) = package.repo_id + { + state.live.bump(&crate::live::Topic::Repo(repo_id)); + } +} + /// Sets the yank state of a version. Yanked versions stay in the index and stay downloadable, /// marked as yanked, so existing lockfiles keep working. pub async fn set_yanked( @@ -255,6 +266,7 @@ pub async fn set_yanked( return Err(PackageError::NotFound); } state.packages_live.bump(&owner.id); + bump_linked_repo(state, &package.id).await; Ok(()) } diff --git a/crates/forge-web/src/pages/admin_health.rs b/crates/forge-web/src/pages/admin_health.rs index 27aa61c..9e5e182 100644 --- a/crates/forge-web/src/pages/admin_health.rs +++ b/crates/forge-web/src/pages/admin_health.rs @@ -1,9 +1,11 @@ //! Page: instance health for admins (`/admin/health`). A summary line, a storage card with the data //! disk's usage bar, and a services card. Every number is a cheap query or a short external probe -//! (`df`, `du`), so there is no polling; reloading the page, or opening it again, reads fresh values. -//! Non-admins get 404. +//! (`df`), so there is no polling; reloading the page, or opening it again, reads fresh values. The +//! tree size of the repos (`du`) walks every repo, so a background task caches it (see +//! [`spawn_repo_size`]) and the page only reads the cache. Non-admins get 404. use std::path::Path; +use std::sync::Mutex; use std::time::Duration; use forge_core::mail::MailState; @@ -143,8 +145,48 @@ async fn disk(path: &Path) -> Option<(u64, u64)> { parse_df(&probe("df", &["-Pk"], path, Duration::from_secs(3)).await?) } -async fn tree_size(path: &Path) -> Option { - parse_du(&probe("du", &["-sk"], path, Duration::from_secs(4)).await?) +async fn tree_size(path: &Path, limit: Duration) -> Option { + parse_du(&probe("du", &["-sk"], path, limit).await?) +} + +/// Total bytes of the repos, from the last background walk. `None` until the first walk finishes, +/// or when every walk so far failed. +static REPO_BYTES: Mutex> = Mutex::new(None); +/// How often the repos are walked again. +const REPO_SIZE_EVERY: Duration = Duration::from_secs(10 * 60); +/// The first walk, shortly after boot. +const REPO_SIZE_FIRST: Duration = Duration::from_secs(30); + +fn cached_repo_bytes() -> Option { + *REPO_BYTES.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Starts the background walk of the repos' size: once shortly after boot, then every +/// [`REPO_SIZE_EVERY`]. Runs until the process exits. `du` is a child process, so the walk does not +/// block the executor. A changed size wakes the health page. +pub fn spawn_repo_size(state: AppState) { + tokio::spawn(async move { + tokio::time::sleep(REPO_SIZE_FIRST).await; + loop { + refresh_repo_bytes(&state).await; + tokio::time::sleep(REPO_SIZE_EVERY).await; + } + }); +} + +async fn refresh_repo_bytes(state: &AppState) { + let repos_dir = state.live().data_dir.join("repos"); + // A failed or timed-out walk keeps the last good value. + let Some(bytes) = tree_size(&repos_dir, Duration::from_secs(5 * 60)).await else { + return; + }; + let previous = REPO_BYTES + .lock() + .unwrap_or_else(|e| e.into_inner()) + .replace(bytes); + if previous != Some(bytes) { + crate::live::admin().bump(&Topic::AdminHealth); + } } /// Seconds since the process started, from `/proc` (Linux). `None` elsewhere. @@ -167,18 +209,17 @@ async fn gather(state: &AppState, lang: Lang, tz: &str) -> Result { let live = state.live(); let now = now_unix(); let data_dir = live.data_dir.clone(); - let repos_dir = data_dir.join("repos"); let backup_dir = live.backup.dir.clone(); let database = live.database.clone(); let backup_on = !backup_dir.as_os_str().is_empty(); - let (data_space, repo_bytes, backup_space) = - tokio::join!(disk(&data_dir), tree_size(&repos_dir), async { - if backup_on { - disk(&backup_dir).await - } else { - None - } - }); + let (data_space, backup_space) = tokio::join!(disk(&data_dir), async { + if backup_on { + disk(&backup_dir).await + } else { + None + } + }); + let repo_bytes = cached_repo_bytes(); let counts = state.store.health_counts().await?; let mail = state .store @@ -532,9 +573,10 @@ async fn health_page(cx: &Cx) -> Result { }) } -/// What the event-driven parts of the health page show, as one string: the alerts, the counts and -/// the mail queue. The disk and tree probes (`df`, `du`) are not read here: they cost a process -/// each, so they run only when the page renders. +/// What the health page shows that can change between renders, as one string: the alerts, the +/// counts, the mail queue, the disk figures and the uptime, each as the page would display it. The +/// disk figures come from `statvfs` (the same numbers `df` prints), not a process. The tree size +/// of the repos is the cached value of the background walk, as the page displays it. async fn health_fingerprint(state: &AppState) -> Result { let counts = state.store.health_counts().await?; let mail = state @@ -546,7 +588,22 @@ async fn health_fingerprint(state: &AppState) -> Result { .into_iter() .map(|alert| (alert.title, alert.body)) .collect(); - Ok(format!("{counts:?}|{mail:?}|{alerts:?}")) + let live = state.live(); + let disk_text = |path: &Path| { + crate::alerts::disk_space(path).map(|(total, avail)| { + let (pct, text) = space(Lang::En, total, avail); + (pct, text, human_size(Lang::En, total.saturating_sub(avail))) + }) + }; + let data = disk_text(&live.data_dir); + let backup = (!live.backup.dir.as_os_str().is_empty()) + .then(|| disk_text(&live.backup.dir)) + .flatten(); + let uptime = uptime_secs().map(duration_short); + let repos = cached_repo_bytes().map(|b| human_size(Lang::En, b)); + Ok(format!( + "{counts:?}|{mail:?}|{alerts:?}|{data:?}|{backup:?}|{uptime:?}|{repos:?}" + )) } /// The health page's change stream. Admins only. diff --git a/crates/forge-web/src/pages/admin_runners.rs b/crates/forge-web/src/pages/admin_runners.rs index 9af5a4b..334f9a4 100644 --- a/crates/forge-web/src/pages/admin_runners.rs +++ b/crates/forge-web/src/pages/admin_runners.rs @@ -9,7 +9,7 @@ use forge_ci::build::{self, Freshness}; use forge_core::AuditAction; use forge_core::ci::{CiRunner, FieldKind, RUNNER_FIELDS, RestartMode, runner_field}; -use forge_core::store::health::RUNNER_ONLINE_SECS; +use forge_core::store::health::runner_is_online; use serde::Deserialize; use time::OffsetDateTime; use time::format_description::well_known::Rfc3339; @@ -197,13 +197,7 @@ fn dot_of(lang: Lang, runner: &CiRunner, now: i64) -> (&'static str, &'static st if runner.disabled { return ("runner-dot is-disabled", g::t(lang, K::Disabled)); } - let limit = i64::try_from(RUNNER_ONLINE_SECS).unwrap_or(i64::MAX); - let online = runner - .last_seen_at - .as_deref() - .and_then(|stamp| OffsetDateTime::parse(stamp, &Rfc3339).ok()) - .is_some_and(|at| at.unix_timestamp() >= now.saturating_sub(limit)); - if online { + if runner_is_online(false, runner.last_seen_at.as_deref(), now) { ("runner-dot is-online", s(lang, "online", "çevrim içi")) } else { ("runner-dot is-offline", s(lang, "offline", "çevrim dışı")) diff --git a/crates/forge-web/src/pages/admin_server.rs b/crates/forge-web/src/pages/admin_server.rs index fec32ee..1d1f4e5 100644 --- a/crates/forge-web/src/pages/admin_server.rs +++ b/crates/forge-web/src/pages/admin_server.rs @@ -280,6 +280,13 @@ async fn server_view( } + } else if r.is_number && r.max.parse::().is_ok_and(|max| max <= 100) { + // A small range steps with − and +, like the runner's Max. +
+ + + +
} else if r.is_number { } else if r.is_secret { @@ -414,6 +421,7 @@ async fn save( state.store.clear_server_override(key).await?; } state.settings.publish(&plan.overrides)?; + state.live.bump(&Topic::ServerSettings); crate::live::admin().bump(&Topic::AdminServer); let keys: Vec<&str> = plan.sets.iter().map(|(k, _)| k.as_str()).collect(); audit::record( @@ -541,6 +549,7 @@ async fn reset( let next = state.settings.plan_reset(&existing, key)?; state.store.clear_server_override(key).await?; state.settings.publish(&next)?; + state.live.bump(&Topic::ServerSettings); crate::live::admin().bump(&Topic::AdminServer); audit::record( &state.store, diff --git a/crates/forge-web/src/pages/assets.rs b/crates/forge-web/src/pages/assets.rs index 266ebab..49d3851 100644 --- a/crates/forge-web/src/pages/assets.rs +++ b/crates/forge-web/src/pages/assets.rs @@ -167,7 +167,9 @@ async fn offline_js() -> Result<(StatusCode, HeaderMap, &'static str)> { /// The stream every page and the offline page watch to learn that the server is back. It carries /// no data and needs no login: it sends `retry`, then holds the connection open with keep-alive -/// 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. +/// comments. Every viewer gets `settings` events when a live server setting changes, and 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. #[route(GET "/-/alive")] async fn alive(cx: &Cx) -> Result { crate::pages::settings_live::alive_response(cx).await diff --git a/crates/forge-web/src/pages/banner.rs b/crates/forge-web/src/pages/banner.rs index d1e6909..1a5103a 100644 --- a/crates/forge-web/src/pages/banner.rs +++ b/crates/forge-web/src/pages/banner.rs @@ -29,6 +29,8 @@ pub struct BannerView { pub message: String, pub warning: bool, pub hash: String, + /// Unix seconds when the banner expires, or `None` for never. The page drops it at that time. + pub expires: Option, } /// Short stable id of a message and level. @@ -51,6 +53,7 @@ pub fn view_for(config: &BannerConfig, now: i64, dismissed: Option<&str>) -> Opt message, warning: config.level == "warning", hash, + expires: config.expires_unix(), }) } diff --git a/crates/forge-web/src/pages/ci_job.rs b/crates/forge-web/src/pages/ci_job.rs index 9e5e518..c801faa 100644 --- a/crates/forge-web/src/pages/ci_job.rs +++ b/crates/forge-web/src/pages/ci_job.rs @@ -1,10 +1,10 @@ //! Pages: one CI job (`/{owner}/{repo}/ci/jobs/{job_id}`), its live log (`.../log.txt`) and its //! artifacts (`.../artifacts/{name}`). Reading follows repo Read, like the run pages. The job page -//! shows the last 512 KiB of the log. While the job is not terminal the page is live: it carries a -//! `data-live` marker for its `.../events` stream, and nav.js re-renders it when the job's status -//! changes. `log.txt` streams the whole log and keeps following it until the job is -//! terminal and the file is read to its end. Artifacts are blobs under `ci/` and are -//! always served as attachments. +//! shows the last 512 KiB of the log. The page carries a `data-live` marker for its `.../events` +//! stream, and `data-live-state` holds the job's fingerprint (status, artifact ids, log kept): nav.js +//! re-renders the page when the stream sends a different one. `log.txt` streams the whole log and +//! keeps following it until the job is terminal and the file is read to its end. Artifacts are blobs +//! under `ci/` and are always served as attachments. use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -34,8 +34,8 @@ use crate::i18n::{ releases_ci::{self as g, K}, }; use crate::pages::ci_runs::{ - age_text, can_write, changed_event, duration_text, events_response, job_href, job_status, - run_href, state_text, + age_text, can_write, changed_event, duration_text, events_response, job_href, run_href, + state_text, }; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; @@ -254,8 +254,8 @@ fn full_date(stamp: &str) -> String { /// The job page's values, already shown as text. struct JobView { name: String, - /// The status word as the events carry it, for the live check. - status: String, + /// The fingerprint the events carry and the page renders as `data-live-state` (see `job_fingerprint`). + fingerprint: String, state: String, state_class: String, runner: String, @@ -282,8 +282,35 @@ struct ArtifactRow { size: String, } -/// The job page body. A job that is not terminal carries `live`, the URL of its event stream, and -/// the status the page shows. The log tail carries the offset its text ends at. +/// The job's fingerprint: its status, the ids of its artifacts (by name) and whether its log is +/// still kept. The events send it as `changed` data and the page renders it as `data-live-state`, +/// so a status change, an artifact added or deleted, or a log deleted re-renders the page. The +/// log's size is left out: a running job's log grows with every chunk, and the log stream carries +/// that. Format: `{status}|{artifact ids joined by ','}|{log or nolog}`. +fn job_fingerprint(status: &str, artifact_ids: &[&str], log_kept: bool) -> String { + format!( + "{status}|{}|{}", + artifact_ids.join(","), + if log_kept { "log" } else { "nolog" } + ) +} + +/// The job's fingerprint now. `None` when the job row is gone. +async fn job_fingerprint_now(store: &Store, job_id: &str) -> Result> { + let Some(job) = store.job_by_id(job_id).await? else { + return Ok(None); + }; + let artifacts = store.list_artifacts(job_id).await?; + let ids: Vec<&str> = artifacts.iter().map(|artifact| artifact.id.as_str()).collect(); + Ok(Some(job_fingerprint( + job.state.as_str(), + &ids, + job.log_bytes > 0, + ))) +} + +/// The job page body. Every job carries `live`, the URL of its event stream, so a finished job +/// follows its artifacts and log too. The log tail carries the offset its text ends at. #[component] async fn job_body( head: RepoHead, @@ -294,11 +321,11 @@ async fn job_body( first_line: String, truncated: bool, artifacts: Vec, - live: Option, + live: String, ) -> Result { Ok(view! { repo_head(head: RepoHead { live: String::new(), ..head }) -
+

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

(job.name.as_str())

@@ -384,10 +411,10 @@ async fn job_page(cx: &Cx) -> Result { offset: log_offset, first_line, } = log_tail(&log_path(&state.config.data_dir, &job.id)).await?; - let artifacts = state - .store - .list_artifacts(&job.id) - .await? + let listed = state.store.list_artifacts(&job.id).await?; + let ids: Vec<&str> = listed.iter().map(|artifact| artifact.id.as_str()).collect(); + let fingerprint = job_fingerprint(job.state.as_str(), &ids, job.log_bytes > 0); + let artifacts = listed .into_iter() .map(|artifact| ArtifactRow { href: format!( @@ -411,10 +438,10 @@ async fn job_page(cx: &Cx) -> Result { None => String::new(), }; let title = title_of(&ctx); - let live = (!job.state.is_terminal()).then(|| format!("{}/events", job_href(&title, &job.id))); + let live = format!("{}/events", job_href(&title, &job.id)); let view = JobView { name: job.name.clone(), - status: job.state.as_str().to_owned(), + fingerprint, state: state_text(lang, job.state.as_str()), state_class: format!("ci-state ci-{}", job.state.as_str()), runner, @@ -470,7 +497,8 @@ const LOG_EVENT_BYTES: u64 = 64 * 1024; /// The job's live stream. It opens with the status, sends a `changed` event when the status changes /// and a `log` event with each new run of log bytes. A `log` event's id is the offset past its text, /// so a reconnect (`Last-Event-ID`) resumes there. A new stream starts at `?from=`, the offset the -/// page already shows. The stream ends once the job is terminal and its log is read to the end. +/// page already shows. The stream stays open after the job is terminal and wakes only on a bump of +/// this job (see `CiLive`), so a finished page still hears about deleted artifacts or logs. #[route(GET "/{owner}/{repo}/ci/jobs/{job_id}/events")] async fn job_events(cx: &Cx) -> Result { let owner = path_param::(cx); @@ -491,11 +519,10 @@ async fn job_events(cx: &Cx) -> Result { path: log_path(&state.config.data_dir, &job.id), wake, offset, - status: None, - terminal: false, + fingerprint: None, more: false, primed: false, - pending_status: None, + pending_fingerprint: None, pending_log: None, }; events_response(cx, job_stream(follow)) @@ -519,15 +546,13 @@ struct JobFollow { wake: watch::Receiver, /// The log offset read so far. The next read starts here. offset: u64, - /// The status last read. - status: Option, - /// The job was terminal at the last read. - terminal: bool, + /// The fingerprint last read (see `job_fingerprint`). + fingerprint: Option, /// The last read sent log bytes, so more may be waiting. more: bool, /// False until the first read. Later reads wait for a wake first, unless `more` is set. primed: bool, - pending_status: Option, + pending_fingerprint: Option, /// The text and the offset past it. pending_log: Option<(String, u64)>, } @@ -535,33 +560,31 @@ struct JobFollow { fn job_stream(follow: JobFollow) -> impl Stream> + Send + 'static { futures_util::stream::unfold(follow, |mut f| async move { loop { - if let Some(status) = f.pending_status.take() { - return Some((changed_event(status), f)); + if let Some(fingerprint) = f.pending_fingerprint.take() { + return Some((changed_event(fingerprint), f)); } if let Some((text, end)) = f.pending_log.take() { let event = Event::new().event("log").data(text).id(end.to_string()); return Some((Ok(event), f)); } - if f.terminal && !f.more { - return None; - } + // A terminal job keeps the stream open too: its artifacts and log can still be deleted + // by the retention purge, and the wake of that purge is the only thing that wakes it. if f.primed && !f.more && f.wake.changed().await.is_err() { return None; } f.primed = true; f.more = false; - let (status, terminal) = match job_status(&f.store, &f.job_id).await { - Ok(Some(found)) => found, + let fingerprint = match job_fingerprint_now(&f.store, &f.job_id).await { + Ok(Some(fingerprint)) => fingerprint, Ok(None) => return None, Err(e) => { tracing::error!(error = %e, "ci: job stream could not read the job"); return None; } }; - f.terminal = terminal; - if f.status.as_deref() != Some(status.as_str()) { - f.status = Some(status.clone()); - f.pending_status = Some(status); + if f.fingerprint.as_deref() != Some(fingerprint.as_str()) { + f.fingerprint = Some(fingerprint.clone()); + f.pending_fingerprint = Some(fingerprint); } match read_log(&f.path, f.offset).await { Ok(Some((text, end))) => { @@ -691,3 +714,16 @@ fn artifact_response( ); Ok(res) } + +#[cfg(test)] +mod tests { + use super::job_fingerprint; + + #[test] + fn an_artifact_or_the_log_changing_changes_the_fingerprint() { + let base = job_fingerprint("success", &["a1"], true); + assert_eq!(base, "success|a1|log"); + assert_ne!(base, job_fingerprint("success", &[], true)); + assert_ne!(base, job_fingerprint("success", &["a1"], false)); + } +} diff --git a/crates/forge-web/src/pages/ci_runs.rs b/crates/forge-web/src/pages/ci_runs.rs index 11804f8..6f788a3 100644 --- a/crates/forge-web/src/pages/ci_runs.rs +++ b/crates/forge-web/src/pages/ci_runs.rs @@ -1958,13 +1958,6 @@ pub(crate) async fn run_status(store: &Store, run_id: &str) -> Result { .map(|run| (run.state.as_str().to_owned(), run_finished(&run.state)))) } -pub(crate) async fn job_status(store: &Store, job_id: &str) -> Result { - Ok(store - .job_by_id(job_id) - .await? - .map(|job| (job.state.as_str().to_owned(), job.state.is_terminal()))) -} - /// One `changed` event carrying the status word. pub(crate) fn changed_event(status: String) -> Result { Ok(Event::new().event("changed").data(status)) diff --git a/crates/forge-web/src/pages/ci_tests.rs b/crates/forge-web/src/pages/ci_tests.rs index 4e393b1..839ae23 100644 --- a/crates/forge-web/src/pages/ci_tests.rs +++ b/crates/forge-web/src/pages/ci_tests.rs @@ -432,9 +432,10 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() { finish_job(&fx).await; let done = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await; + // A finished job stays live: a retention purge can still take its artifacts and log. assert!( - !done.text().contains(&job_marker), - "job not live when finished" + done.text().contains(&job_marker), + "job still live when finished" ); assert!( !done.text().contains("http-equiv=\"refresh\""), @@ -472,7 +473,7 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() { let first = next_event(&mut job_frames).await.expect("the job status"); assert_eq!( first, - format!("event: changed\ndata: {}\n\n", job.state.as_str()).into_bytes() + format!("event: changed\ndata: {}||nolog\n\n", job.state.as_str()).into_bytes() ); // 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() { let last = next_event(&mut job_frames).await.expect("the final status"); assert_eq!( last, - format!("event: changed\ndata: {}\n\n", JobState::Success.as_str()).into_bytes() + format!("event: changed\ndata: {}||nolog\n\n", JobState::Success.as_str()).into_bytes() ); assert!(next_event(&mut job_frames).await.is_none(), "stream ends"); } @@ -618,7 +619,7 @@ async fn job_log_events() { let first = next_event(&mut frames).await.expect("the status"); assert_eq!( first, - format!("event: changed\ndata: {}\n\n", job.state.as_str()).into_bytes() + format!("event: changed\ndata: {}||nolog\n\n", job.state.as_str()).into_bytes() ); let mut file = std::fs::OpenOptions::new() @@ -724,7 +725,7 @@ async fn job_page_log_tail() { "tail offset" ); assert!( - text.contains(&format!("data-live-state=\"{}\"", job.state.as_str())), + text.contains(&format!("data-live-state=\"{}|", job.state.as_str())), "rendered status" ); } diff --git a/crates/forge-web/src/pages/code_live.rs b/crates/forge-web/src/pages/code_live.rs index bb88119..62f1222 100644 --- a/crates/forge-web/src/pages/code_live.rs +++ b/crates/forge-web/src/pages/code_live.rs @@ -1,14 +1,19 @@ //! Live stream of a repo's pages, at `/{owner}/{repo}/events`. The repo header renders `data-live` //! with this URL on every repo page (see `repo::repo_head`). A code view adds its branch to the -//! URL. The stream sends `changed` when the header changes: stars, watchers, forks, or the repo's -//! name, description or visibility. On a code view of a branch it also sends `changed` when the -//! branch moves, or when a branch or tag is created or deleted (the ref selector and the branch -//! list depend on that). Moves of other refs send nothing. Commits and tags are not followed: they -//! do not move. +//! URL. The stream sends `changed` when the header changes: stars, watchers, forks, the repo's +//! name, description, visibility, archived flag or default branch, the open issue and pull counts, +//! the discussions and wiki switches, the viewer's own watch level, or the mirror's last sync. The +//! header follows the repo's issues and pulls, so an issue or pull opened or closed shows at once. +//! On a code view of a branch it also sends `changed` when the branch moves, or when a branch or +//! tag is created or deleted (the ref selector and the branch list depend on that). Moves of other +//! refs send nothing. Commits and tags are not followed: they do not move. +//! +//! The repo home page (`home_live_url`) also follows the releases, and sends `changed` when the +//! latest release or the linked packages' versions change. Other repo pages do not read those. use std::path::PathBuf; -use forge_core::Visibility; +use forge_core::{Repo as RepoRecord, User, Visibility}; use forge_git::browse::{RefInfo, RefKind}; use topcoat::Result; use topcoat::context::{Cx, app_context}; @@ -17,6 +22,7 @@ use topcoat::router::{path_param, query_params, route}; use crate::auth::percent_encode; use crate::live::{Topic, stream_changes}; +use crate::pages::packages::repo_package_links; use crate::pages::refs::load_refs; use crate::pages::repo_ctx::{fork_count, load_repo}; use crate::state::AppState; @@ -27,6 +33,7 @@ path_param!(repo); #[query_params(error = bad_request)] struct LiveQuery { ref_name: Option, + home: Option, } /// 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 { format!("/{owner}/{repo}/events?ref_name={}", percent_encode(branch)) } +/// The stream URL of the repo home page: the branch's stream, which also follows the releases and +/// the linked packages. +pub fn home_live_url(owner: &str, repo: &str, branch: &str) -> String { + format!("{}&home=1", branch_live_url(owner, repo, branch)) +} + /// The stream URL of a repo page. A code view of a branch adds the branch to it. pub fn live_url(owner: &str, repo: &str, refs: &[RefInfo], ref_name: &str) -> String { if follows_branch(refs, ref_name) { @@ -66,19 +79,75 @@ async fn refs_fingerprint(path: PathBuf, branch: String) -> Result { } /// The state the repo header shows. A repo that is gone reads as empty, which ends nothing: the -/// stream then sends `changed` once and the page's own re-read shows the 404. -async fn header_fingerprint(state: &AppState, repo_id: &str) -> Result { +/// stream then sends `changed` once and the page's own re-read shows the 404. `viewer_id` is the +/// signed-in viewer, whose watch level the header shows. +async fn header_fingerprint( + state: &AppState, + repo_id: &str, + viewer_id: Option<&str>, +) -> Result { let Some(repo) = state.store.repo_by_id(repo_id).await? else { return Ok(String::new()); }; let stars = state.store.star_count(repo_id).await?; let watchers = state.store.watchers(repo_id).await?.len(); let forks = fork_count(state, repo_id).await?; + let (open_issues, _) = state.store.issue_counts(repo_id).await?; + let (open_pulls, _) = state.store.pull_counts(repo_id).await?; + let discussions = state.store.discussions_enabled(repo_id).await?; + let wiki = state.store.wiki_enabled(repo_id).await?; + let watch = match viewer_id { + Some(viewer) => format!("{:?}", state.store.watch_level(viewer, repo_id).await?), + None => String::new(), + }; + let mirror = match state.store.pull_mirror(repo_id).await? { + Some(m) => format!( + "{} {} {:?}", + m.url, + m.last_sync_at.as_deref().unwrap_or(""), + m.last_ok + ), + None => String::new(), + }; + Ok(header_text(&repo, [stars, watchers as u64, forks, open_issues, open_pulls], &format!( + "{discussions} {wiki} {watch}\n{mirror}" + ))) +} + +/// Joins the header's fields into the fingerprint text. +fn header_text(repo: &RepoRecord, counts: [u64; 5], rest: &str) -> String { let public = repo.visibility == Visibility::Public; - Ok(format!( - "{}\n{}\n{public}\n{}\n{stars} {watchers} {forks}", - repo.owner_name, repo.name, repo.description - )) + let [stars, watchers, forks, issues, pulls] = counts; + format!( + "{}\n{}\n{public}\n{}\n{stars} {watchers} {forks} {issues} {pulls} {} {}\n{rest}", + repo.owner_name, repo.name, repo.description, repo.archived, repo.default_branch + ) +} + +/// The state the home page's latest-release card and linked-package card show. +async fn home_fingerprint(state: &AppState, repo_id: &str, viewer: Option<&User>) -> Result { + let mut release_text = String::new(); + if let Some(release) = state.store.latest_release(repo_id).await? { + let assets = state.store.list_release_assets(&release.id).await?; + let names: Vec = assets + .iter() + .map(|asset| format!("{} {}", asset.id, asset.name)) + .collect(); + release_text = format!( + "{} {} {} {} {}", + release.id, + release.tag, + release.title, + release.published_at.as_deref().unwrap_or(""), + names.join(" ") + ); + } + let packages = repo_package_links(state, viewer, repo_id).await?; + let package_text: Vec = packages + .iter() + .map(|link| format!("{} {}", link.name, link.latest)) + .collect(); + Ok(format!("{release_text}\n{}", package_text.join("\n"))) } /// 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 { async fn repo_events(cx: &Cx) -> Result { let owner = path_param::(cx); let name = path_param::(cx); - let branch = query_params::(cx)? - .ref_name - .clone() - .unwrap_or_default(); + let query = query_params::(cx)?; + let branch = query.ref_name.clone().unwrap_or_default(); + let home = query.home.as_deref() == Some("1"); let ctx = load_repo(cx, owner, name).await?; let state = app_context::(cx).clone(); - let mut topics = vec![Topic::Repo(ctx.repo.id.clone())]; + let repo_id = ctx.repo.id.clone(); + let mut topics = vec![ + Topic::Repo(repo_id.clone()), + Topic::RepoIssues(repo_id.clone()), + Topic::PullList(repo_id.clone()), + ]; if !branch.is_empty() { - topics.push(Topic::RepoRefs(ctx.repo.id.clone())); + topics.push(Topic::RepoRefs(repo_id.clone())); + } + if home { + topics.push(Topic::RepoReleases(repo_id.clone())); } + let viewer = ctx.viewer.as_ref().map(|(user, _)| user.clone()); let path = ctx.path.clone(); - let repo_id = ctx.repo.id.clone(); stream_changes(cx, &state.live.clone(), &topics, move || { let state = state.clone(); let repo_id = repo_id.clone(); let path = path.clone(); let branch = branch.clone(); + let viewer = viewer.clone(); async move { - let header = header_fingerprint(&state, &repo_id).await?; - if branch.is_empty() { - return Ok(header); + let viewer_id = viewer.as_ref().map(|user| user.id.as_str()); + let mut out = header_fingerprint(&state, &repo_id, viewer_id).await?; + if !branch.is_empty() { + let refs = refs_fingerprint(path, branch).await?; + out = format!("{out}\n{refs}"); } - let refs = refs_fingerprint(path, branch).await?; - Ok(format!("{header}\n{refs}")) + if home { + let extra = home_fingerprint(&state, &repo_id, viewer.as_ref()).await?; + out = format!("{out}\n{extra}"); + } + Ok(out) } }) .await } + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn opening_an_issue_changes_the_header_state() { + let dir = tempfile::tempdir().unwrap(); + let state = crate::test_support::test_state(dir.path()).await; + let user = state + .store + .create_user("tahinli", None, "x", false) + .await + .unwrap(); + let repo = state + .store + .create_repo(&user.id, "demo", "", Visibility::Public, "main") + .await + .unwrap(); + let before = header_fingerprint(&state, &repo.id, None).await.unwrap(); + + state + .store + .create_issue(&repo.id, &user.id, "Broken build", "") + .await + .unwrap(); + + let after = header_fingerprint(&state, &repo.id, None).await.unwrap(); + assert_ne!(before, after); + } +} diff --git a/crates/forge-web/src/pages/code_search.rs b/crates/forge-web/src/pages/code_search.rs index 3401273..1687787 100644 --- a/crates/forge-web/src/pages/code_search.rs +++ b/crates/forge-web/src/pages/code_search.rs @@ -15,6 +15,7 @@ use crate::i18n::{ self, code::{self as g, K}, }; +use crate::pages::code_live::branch_live_url; use crate::pages::commits::blocking; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::load_repo; @@ -203,6 +204,8 @@ async fn search_page(cx: &Cx) -> Result { let mut header = ctx.head(state, "code").await?; header.hide_search = true; + // Results of a branch go stale when it moves: the header's stream follows that branch's head. + header.live = branch_live_url(&owner_name, &repo_name, &ref_name); Ok(view! { shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), repo_head(head: header) diff --git a/crates/forge-web/src/pages/compare.rs b/crates/forge-web/src/pages/compare.rs index feec1d0..be22814 100644 --- a/crates/forge-web/src/pages/compare.rs +++ b/crates/forge-web/src/pages/compare.rs @@ -615,6 +615,10 @@ async fn pull_create(cx: &Cx, Form(form): Form) -> Result { pr }; emit_pull(state, &ctx.repo, &Sender::of(&user), "opened", &pr).await; + // The author's contribution calendar counts the pull request. + state + .live + .bump(&crate::live::Topic::User(user.id.clone())); if !as_draft { // A draft tells nobody until it is marked ready for review. notify::dispatch( diff --git a/crates/forge-web/src/pages/discussion_settings.rs b/crates/forge-web/src/pages/discussion_settings.rs index b33b961..81062c4 100644 --- a/crates/forge-web/src/pages/discussion_settings.rs +++ b/crates/forge-web/src/pages/discussion_settings.rs @@ -15,6 +15,7 @@ use crate::audit::{self, Actor, Target}; use crate::auth::require_csrf; use crate::i18n::Lang; use crate::i18n::community::{self as g, K}; +use crate::live::Topic; use crate::pages::repo_ctx::load_repo; use crate::state::AppState; use crate::views::repo_href; @@ -69,6 +70,8 @@ async fn settings_discussions_save(cx: &Cx, Form(form): Form) -> Res .store .set_discussions_enabled(&ctx.repo.id, enabled) .await?; + // The repo header shows the Discussions tab. + state.live.bump(&Topic::Repo(ctx.repo.id.clone())); let name = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name); let action = if enabled { AuditAction::DiscussionsEnabled diff --git a/crates/forge-web/src/pages/edit_history.rs b/crates/forge-web/src/pages/edit_history.rs index 1bbed07..6295466 100644 --- a/crates/forge-web/src/pages/edit_history.rs +++ b/crates/forge-web/src/pages/edit_history.rs @@ -19,6 +19,7 @@ use crate::i18n::issues::{self as g, K}; use crate::i18n::{self, Lang}; use crate::pages::issue_parts::{ItemKind, When, item_for, parse_number}; use crate::pages::issues_live::item_live_url; +use crate::pages::pull_live::pull_live_url; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, load_repo}; use crate::state::AppState; @@ -227,13 +228,16 @@ async fn history_page( let heading = g::history_heading(lang, what); let back_label = g::back_to_item(lang, number); let count_label = g::earlier_versions(lang, entries.len()); - // An issue's history follows the issue: a new edit adds a version to the list. - let live = (kind_item == ItemKind::Issue).then(|| item_live_url(&owner, &name, number)); + // A history follows its item: a new edit adds a version to the list. + let live = match kind_item { + ItemKind::Issue => item_live_url(&owner, &name, number), + ItemKind::Pull => pull_live_url(&owner, &name, number), + }; Ok(view! { cx => shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), repo_head(head: header) -
+

(heading.as_str())

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

if empty { @@ -1050,6 +1051,36 @@ async fn jobs_list(lang: Lang, jobs: Vec<(ImportJob, Option)>) -> Result Result { + let rows = load_job_rows(state, user_id, 50).await?; + Ok(rows + .iter() + .map(|(job, repo)| { + let repo = repo + .as_ref() + .map_or(String::new(), |repo| format!("{}/{}", repo.owner_name, repo.name)); + format!("{} {} {} {repo}", job.id, job.state.as_str(), job.source_ref) + }) + .collect::>() + .join("\n")) +} + +/// The import list's change stream: the viewer's own jobs, from the session only. It sends when the +/// list would show something different (see [`Topic::Imports`]). +#[route(GET "/import/events")] +async fn jobs_events(cx: &Cx) -> Result { + let viewer = require_user(cx).await?; + let state = app_context::(cx).clone(); + let user_id = viewer.0.id.clone(); + stream_changes(cx, &state.live.clone(), &[Topic::Imports(user_id.clone())], move || { + let state = state.clone(); + let user_id = user_id.clone(); + async move { jobs_fingerprint(&state, &user_id).await } + }) + .await +} + #[page("/import")] async fn jobs_page(cx: &Cx) -> Result { let viewer = require_user(cx).await?; diff --git a/crates/forge-web/src/pages/issue_parts.rs b/crates/forge-web/src/pages/issue_parts.rs index 6ffd026..11403b5 100644 --- a/crates/forge-web/src/pages/issue_parts.rs +++ b/crates/forge-web/src/pages/issue_parts.rs @@ -1351,6 +1351,8 @@ pub(crate) async fn post_comment( if !pull { state.live.bump_issue(&ctx.repo.id, &item.id); } + // The author's contribution calendar counts the comment. + state.live.bump(&crate::live::Topic::User(user.id.clone())); emit_comment(state, &ctx.repo, &sender, "created", pull, item, &comment).await; notify::dispatch( state, diff --git a/crates/forge-web/src/pages/issues_list.rs b/crates/forge-web/src/pages/issues_list.rs index 08a522a..9188473 100644 --- a/crates/forge-web/src/pages/issues_list.rs +++ b/crates/forge-web/src/pages/issues_list.rs @@ -835,6 +835,10 @@ async fn new_issue_submit(cx: &Cx, RawForm(raw): RawForm) -> Result { .await?; } state.live.bump_issue(&ctx.repo.id, &issue.id); + // The author's contribution calendar counts the issue. + state + .live + .bump(&crate::live::Topic::User(viewer.0.id.clone())); emit_issue(state, &ctx.repo, &Sender::of(&viewer.0), "opened", &issue).await; notify::dispatch( state, diff --git a/crates/forge-web/src/pages/labels_page.rs b/crates/forge-web/src/pages/labels_page.rs index 8715fb8..ca6912d 100644 --- a/crates/forge-web/src/pages/labels_page.rs +++ b/crates/forge-web/src/pages/labels_page.rs @@ -17,6 +17,7 @@ use crate::i18n::{self, Lang}; use crate::pages::issue_meta::{ RepoFrame, action_error_at, issue_subnav, refusal_message, triage_guard, }; +use crate::pages::issues_live::list_live_url; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::load_repo; use crate::state::AppState; @@ -65,7 +66,12 @@ fn labels_href(title: &str) -> String { /// The header, the label list and, for triage holders, the forms. #[component] -async fn labels_body(lang: Lang, frame: RepoFrame, rows: Vec) -> Result { +async fn labels_body( + lang: Lang, + frame: RepoFrame, + rows: Vec, + live: String, +) -> Result { let labels_action = labels_href(&frame.title); let defaults_action = format!("{labels_action}/defaults"); let empty = rows.is_empty(); @@ -79,7 +85,7 @@ async fn labels_body(lang: Lang, frame: RepoFrame, rows: Vec) -> Resul if archived {
(g::t(lang, K::LabelsArchived))
} -
+

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

if empty {

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

@@ -193,12 +199,13 @@ async fn labels_page(cx: &Cx) -> Result { } }) .collect(); + let live = list_live_url(&ctx.repo.owner_name, &ctx.repo.name); let css_href = format!("/{}/labels.css", frame.title); let page_title = g::labels_title(lang, &frame.title); Ok(view! { shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), extra_stylesheet: Some(css_href.as_str()), - labels_body(lang: lang, frame: frame, rows: rows)) + labels_body(lang: lang, frame: frame, rows: rows, live: live)) }) } diff --git a/crates/forge-web/src/pages/milestones_page.rs b/crates/forge-web/src/pages/milestones_page.rs index 97f4b75..d1a07e0 100644 --- a/crates/forge-web/src/pages/milestones_page.rs +++ b/crates/forge-web/src/pages/milestones_page.rs @@ -20,6 +20,7 @@ use crate::i18n::{self, Lang}; use crate::pages::issue_meta::{ RepoFrame, action_error_at, can_triage, issue_subnav, refusal_message, triage_guard, }; +use crate::pages::issues_live::list_live_url; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::load_repo; use crate::render::markdown::render_markdown; @@ -232,10 +233,11 @@ async fn milestones_page(cx: &Cx) -> Result { let csrf = frame.csrf.clone(); let can_create = frame.can_triage; let create_action = milestones_href(&frame.title); + let live = list_live_url(&ctx.repo.owner_name, &ctx.repo.name); Ok(view! { shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), milestones_body(lang: lang, frame: frame, rows: rows, empty: empty, closed: closed, - csrf: csrf, can_create: can_create, create_action: create_action)) + csrf: csrf, can_create: can_create, create_action: create_action, live: live)) }) } @@ -250,6 +252,7 @@ async fn milestones_body( csrf: String, can_create: bool, create_action: String, + live: String, ) -> Result { let title = frame.title.clone(); let can_triage = frame.can_triage; @@ -262,7 +265,7 @@ async fn milestones_body(
(g::t(lang, K::MilestonesArchived))
} state_tabs(lang: lang, title: title.clone(), closed: closed) -
+
if empty {

(if closed { g::t(lang, K::NoClosedMilestones) } else { g::t(lang, K::NoOpenMilestones) })

} diff --git a/crates/forge-web/src/pages/notifications.rs b/crates/forge-web/src/pages/notifications.rs index b88c74e..fc70228 100644 --- a/crates/forge-web/src/pages/notifications.rs +++ b/crates/forge-web/src/pages/notifications.rs @@ -797,6 +797,14 @@ async fn set_subscription(cx: &Cx, pull: bool, form: &SubscriptionForm) -> Resul } _ => return Err(bad_request("unknown subscription action").into()), } + // The page's button shows the viewer's subscription, so the page and its stream are woken. + if pull { + crate::pages::pull_live::bump_pull(state, &ctx.repo.id, &issue.id); + } else { + state + .live + .bump(&crate::live::Topic::Issue(issue.id.clone())); + } let section = if pull { "pulls" } else { "issues" }; let href = repo_href( &ctx.repo.owner_name, diff --git a/crates/forge-web/src/pages/org_live.rs b/crates/forge-web/src/pages/org_live.rs index b617cd7..6a309d1 100644 --- a/crates/forge-web/src/pages/org_live.rs +++ b/crates/forge-web/src/pages/org_live.rs @@ -3,7 +3,8 @@ //! a repo that is renamed or made private reaches the team page that names it. //! //! Every POST under `/org/{org}/{members|teams|settings}` bumps the org's topic through -//! [`OrgWriteLayer`], after the handler ran. A refused write bumps too, as in the pull layer. The +//! [`OrgWriteLayer`], after the handler ran, and the org's user topic too: its public profile shows +//! the about text and the member and team counts. A refused write bumps too, as in the pull layer. The //! streams send `changed` only when their fingerprint moves, so over-bumping is cheap. //! //! 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 }; let result = next.run(cx, body).await; if let Some(org_id) = org_id { - state.live.bump(&Topic::Org(org_id)); + state.live.bump(&Topic::Org(org_id.clone())); + state.live.bump(&Topic::User(org_id)); } result } diff --git a/crates/forge-web/src/pages/org_new.rs b/crates/forge-web/src/pages/org_new.rs index e0ffed4..7c349f2 100644 --- a/crates/forge-web/src/pages/org_new.rs +++ b/crates/forge-web/src/pages/org_new.rs @@ -16,6 +16,7 @@ use crate::audit::{self, Actor, Target}; use crate::auth::{require_csrf, require_user}; use crate::i18n::orgs::{self as g, K}; use crate::i18n::{self, Lang}; +use crate::live::Topic; use crate::state::AppState; use crate::views::{alert, csrf_field, shell, user_facing_message}; @@ -147,5 +148,7 @@ async fn create_org( serde_json::Value::Null, ) .await; + // The explore list names the orgs too. + state.live.bump(&Topic::Explore); Ok(Ok(org)) } diff --git a/crates/forge-web/src/pages/org_settings.rs b/crates/forge-web/src/pages/org_settings.rs index bd98f92..daebe41 100644 --- a/crates/forge-web/src/pages/org_settings.rs +++ b/crates/forge-web/src/pages/org_settings.rs @@ -15,6 +15,7 @@ use topcoat::view::{View, component, view}; use crate::audit::{self, Actor, Target}; use crate::i18n::orgs::{self as g, K}; use crate::i18n::{self, Lang}; +use crate::live::Topic; use crate::pages::org_ctx::{ DEFAULT_ROLES, load_org, notice_href, org_head, org_notice, require_form_csrf, require_owner, take_notice, @@ -200,7 +201,10 @@ async fn org_delete(cx: &Cx, Form(form): Form) -> Result { return Ok(see_other(notice_href(&back, "confirm_name"))); } match state.store.delete_org(&ctx.org.id).await { - Ok(()) => {} + Ok(()) => { + // The explore list names the orgs too. + state.live.bump(&Topic::Explore); + } Err(forge_core::Error::Conflict(_)) => { return Ok(see_other(notice_href(&back, "has_repos"))); } diff --git a/crates/forge-web/src/pages/profile.rs b/crates/forge-web/src/pages/profile.rs index 42b3609..b45d96d 100644 --- a/crates/forge-web/src/pages/profile.rs +++ b/crates/forge-web/src/pages/profile.rs @@ -276,6 +276,24 @@ async fn profile_fingerprint( .await? .to_string(), ]; + // The header's about text and avatar, read fresh: the stream's `user` is a snapshot from connect. + let about = state + .store + .user_by_id(&user.id) + .await? + .map(|fresh| fresh.about) + .unwrap_or_default(); + lines.push(format!("about {about}")); + lines.push(format!( + "avatar {}", + state.store.avatar_hash(&user.id).await?.unwrap_or_default() + )); + // An organization's page shows its member and team counts. + if user.is_org() { + let members = state.store.org_members(&user.id).await?.len(); + let teams = state.store.teams_for_org(&user.id).await?.len(); + lines.push(format!("org {members} {teams}")); + } let pins = readable( state, actor, diff --git a/crates/forge-web/src/pages/profile_pins.rs b/crates/forge-web/src/pages/profile_pins.rs index 2dcafcd..2c68cd8 100644 --- a/crates/forge-web/src/pages/profile_pins.rs +++ b/crates/forge-web/src/pages/profile_pins.rs @@ -4,17 +4,19 @@ //! after a save. use forge_core::store::profile_pins::MAX_PROFILE_PINS; -use forge_core::{Repo, Session, User}; +use forge_core::{Repo, Session, Store, User}; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::RawForm; use topcoat::router::error::see_other; -use topcoat::router::{page, path_param}; +use topcoat::router::response::Response; +use topcoat::router::{page, path_param, route}; use topcoat::view::{View, component, view}; use crate::auth::{require_csrf, require_user}; use crate::i18n::orgs::{self as g, K}; use crate::i18n::{self, Lang}; +use crate::live::{Topic, stream_changes}; use crate::pages::issue_meta::{form_all, form_field, form_pairs}; use crate::pages::org_ctx::{load_org, require_form_csrf, require_owner}; use crate::state::AppState; @@ -69,9 +71,11 @@ async fn pins_form( let csrf = viewer.1.csrf_token.clone(); let title = g::t(lang, K::CustomizePins); let error = error.map(str::to_owned); + // The form follows the owner's topic: a pin or a repo of the owner changed elsewhere re-renders it. + let live = format!("{action}/events"); Ok(view! { cx => shell(title: title, viewer: Some(&viewer), - pins_body(lang: lang, action: action, csrf: csrf, options: options, error: error)) + pins_body(lang: lang, action: action, live: live, csrf: csrf, options: options, error: error)) }) } @@ -79,6 +83,7 @@ async fn pins_form( async fn pins_body( lang: Lang, action: String, + live: String, csrf: String, options: Vec, error: Option, @@ -88,7 +93,7 @@ async fn pins_body( let empty = g::t(lang, K::NoPinnableRepos); let save = g::t(lang, K::SavePins); Ok(view! { -
+

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

(intro)

if let Some(message) = error { @@ -139,6 +144,33 @@ async fn save_pins( Err(see_other(back).into()) } +/// What the pin form shows: the owner's pinned repos in order, then each repo the owner may pin. +async fn pins_fingerprint(store: &Store, owner_id: &str) -> Result { + let mut lines = Vec::new(); + for repo in store.profile_pins(owner_id).await? { + lines.push(format!("pin {}", repo.id)); + } + for repo in store.list_repos_by_owner(owner_id).await? { + lines.push(format!("repo {} {}/{}", repo.id, repo.owner_name, repo.name)); + } + Ok(lines.join("\n")) +} + +/// The pin form's change stream for the signed-in user. Its own page only, as the form. +#[route(GET "/settings/pins/events")] +async fn pins_events(cx: &Cx) -> Result { + let viewer = require_user(cx).await?; + let state = app_context::(cx); + let owner_id = viewer.0.id.clone(); + let store = state.store.clone(); + stream_changes(cx, &state.live, &[Topic::User(owner_id.clone())], move || { + let store = store.clone(); + let owner_id = owner_id.clone(); + async move { pins_fingerprint(&store, &owner_id).await } + }) + .await +} + /// Gets the pin form for the signed-in user's own profile. #[page("/settings/pins")] async fn pins_page(cx: &Cx) -> Result { @@ -160,6 +192,22 @@ async fn pins_save(cx: &Cx, RawForm(raw): RawForm) -> Result { save_pins(cx, viewer, owner, "/settings/pins".to_owned(), chosen, back).await } +/// The pin form's change stream for an organization. Owners only, as the form. +#[route(GET "/org/{org}/settings/pins/events")] +async fn org_pins_events(cx: &Cx) -> Result { + let ctx = load_org(cx, path_param::(cx)).await?; + require_owner(&ctx)?; + let state = app_context::(cx); + let owner_id = ctx.org.id.clone(); + let store = state.store.clone(); + stream_changes(cx, &state.live, &[Topic::User(owner_id.clone())], move || { + let store = store.clone(); + let owner_id = owner_id.clone(); + async move { pins_fingerprint(&store, &owner_id).await } + }) + .await +} + /// Gets the pin form for an organization. Owners only. #[page("/org/{org}/settings/pins")] async fn org_pins_page(cx: &Cx) -> Result { diff --git a/crates/forge-web/src/pages/pull_live.rs b/crates/forge-web/src/pages/pull_live.rs index c8e7921..d00c1e6 100644 --- a/crates/forge-web/src/pages/pull_live.rs +++ b/crates/forge-web/src/pages/pull_live.rs @@ -15,6 +15,7 @@ //! [`list_fingerprint`]). A bump that changes none of it sends nothing, so over-bumping is cheap. use forge_core::PullRequest; +use forge_core::reactions::ReactionTarget; use forge_core::store::Store; use topcoat::Result; use topcoat::context::{Cx, app_context}; @@ -92,6 +93,28 @@ pub(crate) async fn pull_fingerprint( let reviews = store.list_reviews(id).await?; let threads = store.review_threads(id, viewer).await?; let statuses = store.statuses_for(repo_id, &pr.head_oid).await?; + // The reactions of the body, then of each comment in the comments' order. A map's own order is + // not stable, so each target is looked up by its id. + let comment_ids: Vec = comments.iter().map(|c| c.id.clone()).collect(); + let body_reactions = store + .reactions_for(ReactionTarget::Issue, &[id.to_owned()], viewer) + .await?; + let comment_reactions = store + .reactions_for(ReactionTarget::Comment, &comment_ids, viewer) + .await?; + let mut reaction_digest = vec![format!("{:?}", body_reactions.get(id))]; + reaction_digest.extend( + comment_ids + .iter() + .map(|cid| format!("{:?}", comment_reactions.get(cid))), + ); + let events = store.list_events(id).await?; + // The merge gate reads the repo's protection rules, so a rule change changes the page. + let rules = store.list_branch_rules(repo_id).await?; + let subscription = match viewer { + Some(viewer) => store.subscription(viewer, id).await?, + None => None, + }; let mut lines = vec![ format!( @@ -103,6 +126,18 @@ pub(crate) async fn pull_fingerprint( pr.issue.comment_count ), format!("body {}", pr.issue.body), + format!( + "milestone {:?} locked {} {:?}", + pr.issue.milestone_id, pr.issue.locked, pr.issue.lock_reason + ), + format!("reactions {}", reaction_digest.join(" ")), + format!( + "events {} last {:?}", + events.len(), + events.last().map(|e| e.id.as_str()) + ), + format!("subscription {subscription:?}"), + format!("rules {rules:?}"), format!( "draft {} head {} base {} {:?} {:?} {:?} {:?}", pr.draft, @@ -159,6 +194,11 @@ async fn pull_read( // Streams +/// The stream URL of one pull request, for its page and its edit history. +pub fn pull_live_url(owner: &str, repo: &str, number: i64) -> String { + format!("/{owner}/{repo}/pulls/{number}/events") +} + /// The pull list's change stream. Auth is the repo read check of the list page. #[route(GET "/{owner}/{repo}/pulls/events")] async fn pulls_events(cx: &Cx) -> Result { @@ -265,7 +305,14 @@ async fn bump_written(state: &AppState, target: Written) { }; match target { Written::Pull { number, .. } => match state.store.pull_by_number(&repo.id, number).await { - Ok(Some(pr)) => bump_pull(state, &repo.id, &pr.issue.id), + Ok(Some(pr)) => { + bump_pull(state, &repo.id, &pr.issue.id); + // A closed or merged pull leaves its reviewers' request lists. + if pr.issue.state != forge_core::IssueState::Open || pr.merged_at.is_some() { + crate::pages::review_requests::bump_pending_reviewers(state, &pr.issue.id) + .await; + } + } Ok(None) => {} Err(e) => tracing::error!(error = %e, number, "live: loading the pull to bump failed"), }, diff --git a/crates/forge-web/src/pages/pull_reviews.rs b/crates/forge-web/src/pages/pull_reviews.rs index 6690fd0..69d8521 100644 --- a/crates/forge-web/src/pages/pull_reviews.rs +++ b/crates/forge-web/src/pages/pull_reviews.rs @@ -735,6 +735,8 @@ async fn review_submit(cx: &Cx, Form(form): Form) -> Result Ok(refusal(&tab, ERR_OWN_PR, "")), diff --git a/crates/forge-web/src/pages/repo.rs b/crates/forge-web/src/pages/repo.rs index 1f16224..f8938e4 100644 --- a/crates/forge-web/src/pages/repo.rs +++ b/crates/forge-web/src/pages/repo.rs @@ -20,7 +20,7 @@ use topcoat::view::{View, component, view}; use crate::i18n::code::{self as g, K}; use crate::i18n::{self, Lang}; -use crate::pages::code_live::{branch_live_url, follows_branch}; +use crate::pages::code_live::{follows_branch, home_live_url}; use crate::pages::dashboard::badge_class; use crate::pages::finder::file_finder; use crate::pages::issue_parts::stamp_unix; @@ -468,7 +468,7 @@ async fn repo_page(cx: &Cx) -> Result { } let follows = follows_branch(&refs, &branch); // The home page follows the default branch even before its first push, so that push goes live. - let live = branch_live_url(&repo.owner_name, &repo.name, &branch); + let live = home_live_url(&repo.owner_name, &repo.name, &branch); let owner_name = repo.owner_name.clone(); let repo_name = repo.name.clone(); let branches_href = repo_href(&owner_name, &repo_name, "branches", ""); diff --git a/crates/forge-web/src/pages/repo_settings.rs b/crates/forge-web/src/pages/repo_settings.rs index 87666dc..faec7aa 100644 --- a/crates/forge-web/src/pages/repo_settings.rs +++ b/crates/forge-web/src/pages/repo_settings.rs @@ -34,6 +34,7 @@ use crate::i18n::merge_queue as mq; use crate::i18n::repo_admin::{self as g, K}; use crate::i18n::{self, Lang}; use crate::pages::discussion_settings::discussions_card; +use crate::pages::passkeys; use crate::pages::refs::load_refs; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; @@ -645,13 +646,17 @@ async fn branch_rule_form(
(g::t(lang, K::SectionMerging))
-