diff --git a/crates/forge-web/src/alerts.rs b/crates/forge-web/src/alerts.rs index 0284bf1..cee34fe 100644 --- a/crates/forge-web/src/alerts.rs +++ b/crates/forge-web/src/alerts.rs @@ -70,6 +70,7 @@ pub async fn raise(state: &AppState, topic: &str, key: &str, subject: &str, deta pub async fn resolve(state: &AppState, key: &str) { match state.store.resolve_alert(key).await { Ok(Some(alert)) => { + crate::live::admin().bump(&crate::live::Topic::AdminHealth); let kind = kind_of(&alert.kind); if state.live().alerts.kind_enabled(kind) { deliver(state, key, &alert.kind, &alert.subject, &alert.detail, true).await; @@ -105,6 +106,8 @@ async fn deliver( detail: &str, resolved: bool, ) { + // The alert was written (raised, resolved or recorded): the health page follows it. + crate::live::admin().bump(&crate::live::Topic::AdminHealth); let users = match state.store.list_users().await { Ok(users) => users, Err(e) => { diff --git a/crates/forge-web/src/audit.rs b/crates/forge-web/src/audit.rs index 798795c..be74e04 100644 --- a/crates/forge-web/src/audit.rs +++ b/crates/forge-web/src/audit.rs @@ -6,6 +6,7 @@ use serde_json::Value; use topcoat::context::Cx; use crate::client_ip::client_ip; +use crate::live::Topic; /// Who did it. `Anonymous` is an unauthenticated attempt, `Cli` is the admin command line. pub enum Actor<'a> { @@ -50,5 +51,17 @@ pub async fn record( } if let Err(err) = store.record_audit(&entry).await { tracing::error!(action = action.as_str(), error = %err, "failed to record audit entry"); + return; + } + // The entry is committed: the audit log and the account list follow it, and so do the + // accounts it names (the actor's last login, the target's facts and status). + let hub = crate::live::admin(); + hub.bump(&Topic::AdminAudit); + hub.bump(&Topic::AdminUsers); + if let Some(actor) = &entry.actor_id { + hub.bump(&Topic::AdminUser(actor.clone())); + } + if target.kind == "user" && !target.id.is_empty() { + hub.bump(&Topic::AdminUser(target.id.to_string())); } } diff --git a/crates/forge-web/src/backup/scheduler.rs b/crates/forge-web/src/backup/scheduler.rs index fc98a84..f19f288 100644 --- a/crates/forge-web/src/backup/scheduler.rs +++ b/crates/forge-web/src/backup/scheduler.rs @@ -6,6 +6,7 @@ use std::path::PathBuf; use std::sync::{Arc, Mutex, PoisonError}; use std::time::{Duration, SystemTime}; +use crate::live::Topic; use forge_core::store::backup_runs::{BackupRun, RunKind, RunTrigger}; use forge_core::{Error, Result}; use time::OffsetDateTime; @@ -46,6 +47,7 @@ impl Jobs { ))); } *slot = Some(kind); + runs_changed(); Ok(JobGuard { jobs: Arc::clone(self), kind, @@ -68,9 +70,19 @@ impl Drop for JobGuard { if *slot == Some(self.kind) { *slot = None; } + drop(slot); + runs_changed(); } } +/// A run started or finished, or its slot was taken or freed: the backup and health pages of the +/// admin area follow it. +fn runs_changed() { + let hub = crate::live::admin(); + hub.bump(&Topic::AdminBackups); + hub.bump(&Topic::AdminHealth); +} + fn started_unix(run: &BackupRun) -> Option { OffsetDateTime::parse(&run.started_at, &Rfc3339) .ok() @@ -222,6 +234,7 @@ pub async fn backup_job( prune: bool, ) -> Result { let run_id = state.store.start_run(RunKind::Backup, trigger).await?; + runs_changed(); let healthcheck_url = Some(state.config.backup.healthcheck_url.as_str()) .filter(|url| trigger == RunTrigger::Schedule && !url.is_empty()); if let Some(url) = healthcheck_url { @@ -281,6 +294,7 @@ async fn backup_set(state: &AppState, opts: &BackupOptions) -> Result Result { let run_id = state.store.start_run(RunKind::Fsck, trigger).await?; + runs_changed(); let outcome = run_fsck(&state.store, &state.git, full).await; match &outcome { Ok(summary) if summary.is_ok() => crate::alerts::fsck_finished(state, Ok(())).await, @@ -315,6 +329,7 @@ async fn record_finish( if let Err(e) = state.store.finish_run(run_id, ok, path, bytes, error).await { tracing::error!(error = %e, run_id, "could not record the outcome of a backup run"); } + runs_changed(); } /// Starts a manual run in the background and returns at once. The caller claimed the run slot diff --git a/crates/forge-web/src/ci/api.rs b/crates/forge-web/src/ci/api.rs index e8adc1d..638eb58 100644 --- a/crates/forge-web/src/ci/api.rs +++ b/crates/forge-web/src/ci/api.rs @@ -160,6 +160,7 @@ async fn register(cx: &Cx, body: Body) -> topcoat::Result { .await { Ok((runner, secret)) => { + state.ci_live.bump_runners(); let body = RegisterResponse { runner_id: runner.id, runner_secret: secret, diff --git a/crates/forge-web/src/live.rs b/crates/forge-web/src/live.rs index ef26ac5..0a693d6 100644 --- a/crates/forge-web/src/live.rs +++ b/crates/forge-web/src/live.rs @@ -25,7 +25,7 @@ use std::collections::HashMap; use std::future::Future; -use std::sync::{Mutex, MutexGuard, PoisonError}; +use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError}; use futures_util::future::select_all; use futures_util::stream; @@ -81,6 +81,31 @@ pub enum Topic { /// An organization's pages: its members, teams, team members and linked repos, and settings. /// Keyed by the org's user id. Bumped by [`crate::pages::org_live`] after a POST under the org. Org(String), + /// The account list of the admin area: an account was registered, edited, suspended, lifted, + /// given or lost admin rights, or deleted. Global. Admin pages only, on [`admin`]. + AdminUsers, + /// One account's admin page: its facts, suspension and passkeys. Keyed by user id. Admin + /// pages only, on [`admin`]. + AdminUser(String), + /// The audit log: an entry was written. Global. Admin pages only, on [`admin`]. + AdminAudit, + /// Backup and fsck runs: one started or finished. Global. Admin pages only, on [`admin`]. + AdminBackups, + /// Replication: a copy was written, failed, or removed. Global. Admin pages only, on [`admin`]. + AdminReplication, + /// The health page: an alert was raised or cleared, or a backup or copy finished. Global. + /// Admin pages only, on [`admin`]. + AdminHealth, + /// The server settings: a value was saved or reset, or a restart was requested. Global. + /// Admin pages only, on [`admin`]. + AdminServer, +} + +/// The hub of the admin pages. It is process-wide, not part of [`crate::state::AppState`]: the +/// audit writer has no app state, and every audit entry wakes the admin pages from there. +pub fn admin() -> &'static LiveHub { + static ADMIN: OnceLock = OnceLock::new(); + ADMIN.get_or_init(LiveHub::default) } /// The open topics, each with the counter its subscribers wait on. @@ -138,6 +163,8 @@ impl LiveHub { self.bump(&Topic::User(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. + admin().bump(&Topic::AdminUser(owner_id.to_owned())); } } diff --git a/crates/forge-web/src/mail/live.rs b/crates/forge-web/src/mail/live.rs index 8f7438d..905f22d 100644 --- a/crates/forge-web/src/mail/live.rs +++ b/crates/forge-web/src/mail/live.rs @@ -21,6 +21,8 @@ pub fn subscribe() -> watch::Receiver { /// Counts one change of the queue. Nobody has to be listening. pub fn bump() { sender().send_modify(|generation| *generation = generation.wrapping_add(1)); + // The health page counts the queue too. + crate::live::admin().bump(&crate::live::Topic::AdminHealth); } #[cfg(test)] diff --git a/crates/forge-web/src/pages/admin_backups.rs b/crates/forge-web/src/pages/admin_backups.rs index bf6ba04..719b484 100644 --- a/crates/forge-web/src/pages/admin_backups.rs +++ b/crates/forge-web/src/pages/admin_backups.rs @@ -6,7 +6,7 @@ use forge_core::store::backup_runs::{BackupRun, RunKind}; use forge_core::tz::format_in_tz; -use forge_core::{AuditAction, Error, User}; +use forge_core::{AuditAction, Error, Store, User}; use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, app_context}; @@ -21,6 +21,7 @@ use crate::auth::check_csrf; use crate::backup::scheduler::{configured_dir, start_manual}; use crate::i18n::admin::{self as g, K}; use crate::i18n::{self, Lang}; +use crate::live::{Topic, stream_changes}; use crate::pages::admin_users::admin_only; use crate::pages::issues_list::stamp_unix; use crate::state::AppState; @@ -138,6 +139,7 @@ async fn backups_view( notice: Option, ) -> Result { Ok(view! { +

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

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

@@ -212,9 +214,36 @@ async fn backups_view(
} + }) } +/// The backups page's state, as one string: the run in progress and the recent runs. +async fn runs_fingerprint(store: &Store, running: Option) -> Result { + let runs = store.recent_runs(RUN_LIMIT).await?; + Ok(format!("{running:?}|{runs:?}")) +} + +/// The backups page's change stream. Admins only. +#[route(GET "/admin/backups/events")] +async fn backups_events(cx: &Cx) -> Result { + admin_only(cx).await?; + let state = app_context::(cx); + let store = state.store.clone(); + let jobs = state.jobs.clone(); + stream_changes( + cx, + crate::live::admin(), + &[Topic::AdminBackups], + move || { + let store = store.clone(); + let running = jobs.running(); + async move { runs_fingerprint(&store, running).await } + }, + ) + .await +} + #[page("/admin/backups")] async fn backups_page(cx: &Cx) -> Result { let viewer = admin_only(cx).await?; diff --git a/crates/forge-web/src/pages/admin_health.rs b/crates/forge-web/src/pages/admin_health.rs index 9bc7f51..8f32579 100644 --- a/crates/forge-web/src/pages/admin_health.rs +++ b/crates/forge-web/src/pages/admin_health.rs @@ -13,12 +13,14 @@ use forge_core::tz::format_in_tz; use tokio::process::Command; use topcoat::Result; use topcoat::context::{Cx, app_context}; -use topcoat::router::page; +use topcoat::router::response::Response; +use topcoat::router::{page, route}; use topcoat::view::{View, component, view}; use crate::i18n::accounts::{A, duration_short, t as at}; use crate::i18n::alerts as alert_text; use crate::i18n::{self, Lang}; +use crate::live::{Topic, stream_changes}; use crate::pages::admin_users::admin_only; use crate::state::AppState; use crate::views::{human_size, now_unix, relative_time, shell}; @@ -320,6 +322,7 @@ async fn alert_rows(state: &AppState, lang: Lang, tz: &str) -> Result, alerts: Vec) -> Result { let count = alerts.len(); Ok(view! { +

(at(lang, A::Health))

(at(lang, A::HealthIntro))

@@ -355,6 +358,7 @@ async fn health_view(lang: Lang, tiles: Vec, alerts: Vec) -> Res
}
+ }) } @@ -371,6 +375,35 @@ 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. +async fn health_fingerprint(state: &AppState) -> Result { + let counts = state.store.health_counts().await?; + let mail = state + .store + .mail_state_counts(&forge_core::time::now_stamp()) + .await?; + let alerts: Vec<(String, String)> = alert_rows(state, Lang::En, "UTC") + .await? + .into_iter() + .map(|alert| (alert.title, alert.body)) + .collect(); + Ok(format!("{counts:?}|{mail:?}|{alerts:?}")) +} + +/// The health page's change stream. Admins only. +#[route(GET "/admin/health/events")] +async fn health_events(cx: &Cx) -> Result { + admin_only(cx).await?; + let state = app_context::(cx).clone(); + stream_changes(cx, crate::live::admin(), &[Topic::AdminHealth], move || { + let state = state.clone(); + async move { health_fingerprint(&state).await } + }) + .await +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/forge-web/src/pages/admin_live_tests.rs b/crates/forge-web/src/pages/admin_live_tests.rs new file mode 100644 index 0000000..3cf20d1 --- /dev/null +++ b/crates/forge-web/src/pages/admin_live_tests.rs @@ -0,0 +1,304 @@ +//! The live streams of the admin pages. Each one is admin only (anyone else gets 404), and each +//! sends one `changed` event when the data of its page changes, through the real write path. + +use std::fmt::Debug; +use std::time::Duration; + +use bytes::Bytes; +use forge_core::AuditAction; +use forge_core::store::backup_runs::RunKind; +use forge_core::store::replication::DB_SUBJECT; +use futures_util::{Stream, StreamExt}; +use serde_json::Value; +use topcoat::router::request::Request; +use topcoat::router::{Body, Router}; + +use crate::audit::{self, Actor, Target}; +use crate::auth::SESSION_COOKIE; +use crate::live::{Topic, admin}; +use crate::state::AppState; +use crate::test_support::{app_router, create_session, test_state}; + +const ADMIN_TOKEN: &str = "admin-live-admin-session"; +const USER_TOKEN: &str = "admin-live-user-session"; +const CSRF: &str = "admin-live-csrf"; + +/// Every stream of the admin area that this module covers, for the given account. +fn streams(user_id: &str) -> Vec { + vec![ + "/admin/users/events".to_owned(), + format!("/admin/users/{user_id}/events"), + "/admin/audit/events".to_owned(), + "/admin/backups/events".to_owned(), + "/admin/replication/events".to_owned(), + "/admin/health/events".to_owned(), + "/admin/server/events".to_owned(), + ] +} + +struct Fixture { + _dir: tempfile::TempDir, + app: Router, + state: AppState, + admin_id: String, + user_id: String, +} + +async fn fixture() -> Fixture { + let dir = tempfile::tempdir().expect("tempdir"); + let data_dir = dir.path().join("data"); + std::fs::create_dir_all(&data_dir).expect("data dir"); + let state = test_state(&data_dir).await; + let admin = state + .store + .create_user("root", None, "h", true) + .await + .expect("admin"); + let user = state + .store + .create_user("plain", None, "h", false) + .await + .expect("user"); + create_session(&state.store, &admin.id, ADMIN_TOKEN, CSRF).await; + create_session(&state.store, &user.id, USER_TOKEN, CSRF).await; + let app = app_router(state.clone()); + Fixture { + _dir: dir, + app, + state, + admin_id: admin.id, + user_id: user.id, + } +} + +/// Opens a GET, with the session cookie when there is a token. The body is not read. +async fn open(app: &Router, uri: &str, token: Option<&str>) -> topcoat::router::response::Response { + let mut builder = Request::builder().method("GET").uri(uri); + if let Some(token) = token { + builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}")); + } + app.handle(builder.body(Body::from(String::new())).expect("request")) + .await +} + +/// The next frame of an event stream, or None once it has ended. Fails after five seconds. +async fn next_frame(frames: &mut S) -> Option> +where + S: Stream> + Unpin, + E: Debug, +{ + let frame = tokio::time::timeout(Duration::from_secs(5), frames.next()) + .await + .expect("a frame within five seconds")?; + Some(frame.expect("data").to_vec()) +} + +/// The next `changed` event of a stream. Every stream opens with its `retry` field: skipped here. +async fn next_event(frames: &mut S) -> Vec +where + S: Stream> + Unpin, + E: Debug, +{ + loop { + let bytes = next_frame(frames).await.expect("an event before the end"); + if !bytes.starts_with(b"retry: ") { + return bytes; + } + } +} + +/// The `changed` event of a stream whose data is `data`. +fn changed(data: &str) -> Vec { + format!("event: changed\ndata: {data}\n\n").into_bytes() +} + +#[tokio::test] +async fn admin_streams_answer_only_admins() { + let fx = fixture().await; + for uri in streams(&fx.user_id) { + let anonymous = open(&fx.app, &uri, None).await; + assert_eq!(anonymous.status().as_u16(), 404, "anonymous: {uri}"); + let plain = open(&fx.app, &uri, Some(USER_TOKEN)).await; + assert_eq!(plain.status().as_u16(), 404, "a plain user: {uri}"); + let admin_reply = open(&fx.app, &uri, Some(ADMIN_TOKEN)).await; + assert_eq!(admin_reply.status().as_u16(), 200, "an admin: {uri}"); + } +} + +#[tokio::test] +async fn the_account_list_sends_when_an_account_is_created() { + let fx = fixture().await; + let mut frames = open(&fx.app, "/admin/users/events", Some(ADMIN_TOKEN)) + .await + .into_body() + .into_data_stream(); + let retry = next_frame(&mut frames).await.expect("the retry field"); + assert!(retry.starts_with(b"retry: "), "{retry:?}"); + + let newcomer = fx + .state + .store + .create_user("newcomer", None, "h", false) + .await + .expect("user"); + audit::record( + &fx.state.store, + None, + Actor::Cli, + AuditAction::UserCreated, + Target { + kind: "user", + id: &newcomer.id, + name: "newcomer", + }, + Value::Null, + ) + .await; + assert_eq!(next_event(&mut frames).await, changed("1")); +} + +#[tokio::test] +async fn an_account_page_sends_when_its_account_is_suspended() { + let fx = fixture().await; + let uri = format!("/admin/users/{}/events", fx.user_id); + let mut frames = open(&fx.app, &uri, Some(ADMIN_TOKEN)) + .await + .into_body() + .into_data_stream(); + + fx.state + .store + .suspend_user(&fx.user_id, "spam", Some(&fx.admin_id)) + .await + .expect("suspend"); + audit::record( + &fx.state.store, + None, + Actor::Cli, + AuditAction::UserSuspended, + Target { + kind: "user", + id: &fx.user_id, + name: "plain", + }, + Value::Null, + ) + .await; + assert_eq!(next_event(&mut frames).await, changed("1")); +} + +#[tokio::test] +async fn an_account_page_of_a_missing_account_is_404() { + let fx = fixture().await; + let reply = open( + &fx.app, + "/admin/users/no-such-account/events", + Some(ADMIN_TOKEN), + ) + .await; + assert_eq!(reply.status().as_u16(), 404); +} + +#[tokio::test] +async fn the_audit_log_sends_a_new_entry_of_its_filter() { + let fx = fixture().await; + let mut frames = open( + &fx.app, + "/admin/audit/events?action=login_failed", + Some(ADMIN_TOKEN), + ) + .await + .into_body() + .into_data_stream(); + + audit::record( + &fx.state.store, + None, + Actor::Anonymous, + AuditAction::LoginFailed, + Target::default(), + Value::Null, + ) + .await; + assert_eq!(next_event(&mut frames).await, changed("1")); +} + +#[tokio::test] +async fn the_backups_page_sends_when_a_run_starts_and_ends() { + let fx = fixture().await; + let mut frames = open(&fx.app, "/admin/backups/events", Some(ADMIN_TOKEN)) + .await + .into_body() + .into_data_stream(); + + // Taking the run slot is the start of a run; dropping its guard is the end of it. + let guard = fx + .state + .jobs + .claim(RunKind::Backup) + .expect("the slot is free"); + assert_eq!(next_event(&mut frames).await, changed("1")); + drop(guard); + assert_eq!(next_event(&mut frames).await, changed("1")); +} + +#[tokio::test] +async fn the_replication_page_sends_when_a_copy_fails() { + let fx = fixture().await; + let mut frames = open(&fx.app, "/admin/replication/events", Some(ADMIN_TOKEN)) + .await + .into_body() + .into_data_stream(); + + // The worker's own recording path: a failed step is written and the page is woken. + let outcome = crate::replication::worker::record( + &fx.state.store, + DB_SUBJECT, + Err("standby unreachable".to_owned()), + ) + .await; + assert!(outcome.is_err()); + assert_eq!(next_event(&mut frames).await, changed("1")); +} + +#[tokio::test] +async fn the_health_page_sends_when_an_alert_is_raised() { + let fx = fixture().await; + let mut frames = open(&fx.app, "/admin/health/events", Some(ADMIN_TOKEN)) + .await + .into_body() + .into_data_stream(); + + crate::alerts::raise( + &fx.state, + "runner_offline", + "runner-offline:tahinli-ci", + "tahinli-ci", + "silent for an hour", + ) + .await; + assert_eq!(next_event(&mut frames).await, changed("1")); +} + +#[tokio::test] +async fn the_server_page_sends_when_a_setting_changes_and_on_a_restart() { + let fx = fixture().await; + // A page that waits for a restart: a process other than the one it waits for sends at once. + let mut frames = open( + &fx.app, + "/admin/server/events?restarting=an-older-boot", + Some(ADMIN_TOKEN), + ) + .await + .into_body() + .into_data_stream(); + assert_eq!(next_event(&mut frames).await, changed("restarted")); + + // Any saved or reset setting wakes the stream. + let mut settings = open(&fx.app, "/admin/server/events", Some(ADMIN_TOKEN)) + .await + .into_body() + .into_data_stream(); + admin().bump(&Topic::AdminServer); + assert_eq!(next_event(&mut settings).await, changed("settings")); +} diff --git a/crates/forge-web/src/pages/admin_mail.rs b/crates/forge-web/src/pages/admin_mail.rs index 15c04dc..86fdc02 100644 --- a/crates/forge-web/src/pages/admin_mail.rs +++ b/crates/forge-web/src/pages/admin_mail.rs @@ -3,8 +3,8 @@ //! Two tabs. Settings: the SMTP server, sender and password (the password is write-only: a blank //! field keeps the stored one) and "Send test mail" to the admin's own address. Queue: every //! message in the outbox with its state, kind, tries and last error, filtered by state. A failed -//! message can be retried or discarded there. The queue's wrapper carries `data-live`, so each -//! queue change re-renders it through `/admin/mail/events` with no reload and no polling. +//! message can be retried or discarded there. Both tabs carry `data-live`, so each queue change or +//! saved setting re-renders the tab through `/admin/mail/events` with no reload and no polling. //! Saving the settings and queuing a test are audited. use forge_core::config::MailTransport; @@ -250,6 +250,9 @@ async fn mail_view( } if settings_on { + // Saved by any admin session: the stream re-renders the settings with the same signal + // as the queue (the save bumps it too), and the form keeps what was typed. +

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

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

@@ -282,6 +285,7 @@ async fn mail_view(
+ } else if let Some(queue) = data.queue {

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

@@ -940,7 +944,10 @@ mod tests { ); let (_, settings) = send(&fx.router, "GET", "/admin/mail", Some(ADMIN_TOKEN), None).await; - assert!(!settings.contains("data-live="), "only the queue is live"); + assert!( + settings.contains(r#"data-live="/admin/mail/events""#), + "the settings tab is live too" + ); assert!( !settings.contains("Reset your password"), "the queue is on its own tab" diff --git a/crates/forge-web/src/pages/admin_replication.rs b/crates/forge-web/src/pages/admin_replication.rs index 3f9feeb..2b2b43c 100644 --- a/crates/forge-web/src/pages/admin_replication.rs +++ b/crates/forge-web/src/pages/admin_replication.rs @@ -25,6 +25,7 @@ use crate::audit::{self, Actor, Target}; use crate::auth::check_csrf; use crate::i18n::admin::{self as g, K}; use crate::i18n::{self, Key, Lang}; +use crate::live::{Topic, stream_changes}; use crate::pages::admin_users::admin_only; use crate::pages::issues_list::stamp_unix; use crate::state::AppState; @@ -166,6 +167,7 @@ async fn replication_view( notice: Option, ) -> Result { Ok(view! { +

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

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

@@ -228,9 +230,48 @@ async fn replication_view(
}
+ }) } +/// What the replication page shows, as one string. The health labels are read at each wake, so a +/// wake also refreshes a copy that has gone stale since the last change. +async fn page_fingerprint(state: &AppState) -> Result { + let data = page_data(state, "UTC", Lang::En).await?; + let rows: Vec<_> = data + .repos + .iter() + .map(|row| (&row.name, row.health, &row.last_ok, &row.error)) + .collect(); + Ok(format!( + "{}|{}|{}|{}|{}|{}|{:?}", + data.enabled, + data.db_health, + data.db_last_ok, + data.db_last_attempt, + data.db_error, + data.target, + rows + )) +} + +/// The replication page's change stream. Admins only. +#[route(GET "/admin/replication/events")] +async fn replication_events(cx: &Cx) -> Result { + admin_only(cx).await?; + let state = app_context::(cx).clone(); + stream_changes( + cx, + crate::live::admin(), + &[Topic::AdminReplication], + move || { + let state = state.clone(); + async move { page_fingerprint(&state).await } + }, + ) + .await +} + #[page("/admin/replication")] async fn replication_page(cx: &Cx) -> Result { let viewer = admin_only(cx).await?; diff --git a/crates/forge-web/src/pages/admin_runners.rs b/crates/forge-web/src/pages/admin_runners.rs index 686a565..290708a 100644 --- a/crates/forge-web/src/pages/admin_runners.rs +++ b/crates/forge-web/src/pages/admin_runners.rs @@ -619,6 +619,7 @@ async fn runner_set_disabled(cx: &Cx, Form(form): Form) -> Result) -> Result return Ok(back_to_list("missing")); }; state.store.delete_runner(id).await?; + state.ci_live.bump_runners(); audit::record( &state.store, Some(cx), diff --git a/crates/forge-web/src/pages/admin_server.rs b/crates/forge-web/src/pages/admin_server.rs index 9fc43b7..83d6be8 100644 --- a/crates/forge-web/src/pages/admin_server.rs +++ b/crates/forge-web/src/pages/admin_server.rs @@ -32,6 +32,7 @@ use crate::audit::{self, Actor, Target}; use crate::auth::check_csrf; use crate::i18n::admin::{self as g, K}; use crate::i18n::{self, Key, Lang}; +use crate::live::Topic; use crate::pages::admin_users::admin_only; use crate::pages::ci_runs::{changed_event, events_response}; use crate::self_update; @@ -217,9 +218,17 @@ async fn server_view( ) -> Result { let tab = group.slug(); let any_editable = rows.iter().any(|r| !r.fixed); - let live = (restart == Restart::Pending).then_some("/admin/server/events"); + // A pending restart names the boot id it waits for: the stream then sends at once when a new + // process answers, and the page re-renders. + let live = match restart { + Restart::Pending => format!( + "/admin/server/events?restarting={}", + enc(self_update::boot_id()) + ), + _ => "/admin/server/events".to_owned(), + }; Ok(view! { -
+

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

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

@@ -401,6 +410,7 @@ async fn save( state.store.clear_server_override(key).await?; } state.settings.publish(&plan.overrides)?; + crate::live::admin().bump(&Topic::AdminServer); let keys: Vec<&str> = plan.sets.iter().map(|(k, _)| k.as_str()).collect(); audit::record( &state.store, @@ -462,17 +472,26 @@ async fn server_restart(cx: &Cx, Form(form): Form) -> Result Result { admin_only(cx).await?; - let events = futures_util::stream::once(std::future::ready(changed_event( - self_update::boot_id().to_owned(), - ))) - .chain(futures_util::stream::pending()); - events_response(cx, events) + let query = query_params::(cx)?; + let restarted = query + .restarting + .as_deref() + .is_some_and(|id| !id.is_empty() && id != self_update::boot_id()); + let on_connect = + futures_util::stream::iter(restarted.then(|| changed_event("restarted".to_owned()))); + let wake = crate::live::admin().subscribe(&Topic::AdminServer); + let changes = futures_util::stream::unfold(wake, |mut wake| async move { + wake.changed().await.ok()?; + Some((changed_event("settings".to_owned()), wake)) + }); + events_response(cx, on_connect.chain(changes)) } #[derive(Deserialize, Default)] @@ -518,6 +537,7 @@ async fn reset( let next = state.settings.plan_reset(&existing, key)?; state.store.clear_server_override(key).await?; state.settings.publish(&next)?; + crate::live::admin().bump(&Topic::AdminServer); audit::record( &state.store, Some(cx), @@ -862,10 +882,10 @@ mod tests { // Same process: "Restarting" with the event stream. A new process: back to normal. let page = admin_get(&fx, &location).await; assert!(page.contains("Restarting...")); - assert!(page.contains(r#"data-live="/admin/server/events""#)); + assert!(page.contains(r#"data-live="/admin/server/events?restarting="#)); let page = admin_get(&fx, "/admin/server?restarting=an-older-boot").await; assert!(!page.contains("Restarting...")); - assert!(!page.contains("data-live=")); + assert!(page.contains(r#"data-live="/admin/server/events""#)); assert!(page.contains("The server restarted")); } diff --git a/crates/forge-web/src/pages/admin_user_detail.rs b/crates/forge-web/src/pages/admin_user_detail.rs index c0faf46..3b627a3 100644 --- a/crates/forge-web/src/pages/admin_user_detail.rs +++ b/crates/forge-web/src/pages/admin_user_detail.rs @@ -6,13 +6,14 @@ use forge_core::names::normalize_name; use forge_core::store::suspension::{AccountFacts, Suspension}; use forge_core::store::user_delete::GHOST_USERNAME; use forge_core::tz::format_in_tz; -use forge_core::{AuditAction, User}; +use forge_core::{AuditAction, Store, User}; use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; use topcoat::router::error::{forbidden, not_found, see_other}; -use topcoat::router::{page, path_param_segment, query_params}; +use topcoat::router::response::Response; +use topcoat::router::{page, path_param_segment, query_params, route}; use topcoat::view::{View, component, view}; use crate::audit::{self, Actor, Target}; @@ -20,6 +21,7 @@ use crate::auth::{check_csrf, two_factor_enabled}; use crate::i18n::accounts::{A, t as at}; use crate::i18n::admin::{self as g, K}; use crate::i18n::{self, Key, Lang}; +use crate::live::{Topic, stream_changes}; use crate::pages::admin_users::admin_only; use crate::pages::issues_list::stamp_unix; use crate::pages::passkeys::s; @@ -162,8 +164,10 @@ async fn detail_body( let passkeys_action = format!("{base}/remove-passkeys"); let passkey_count = passkeys.to_string(); let delete_href = format!("{base}/delete"); + let live = format!("{base}/events"); let Notice { done, error, link } = notice; Ok(view! { +

(target.username.as_str())

@@ -270,9 +274,49 @@ async fn detail_body( }

+
}) } +/// What the page shows of one account, as one string. A missing or hidden account is a 404. +async fn account_fingerprint(store: &Store, user_id: &str) -> Result { + let Some(target) = store.user_by_id(user_id).await? else { + return Err(not_found().into()); + }; + if target.is_org() || is_ghost(&target) { + return Err(not_found().into()); + } + let facts = store.account_facts(user_id).await?; + let suspension = store.suspension(user_id).await?; + let passkeys = store.passkey_count(user_id).await?; + Ok(format!( + "{}|{}|{}|{}|{:?}|{:?}|{}", + target.username, + target.email.as_deref().unwrap_or(""), + target.is_admin, + target.created_at, + facts, + suspension, + passkeys + )) +} + +/// The account's change stream. Admins only; anyone else gets 404. The page follows the account's +/// facts: its last login, two-factor state, repo count and passkeys, and its suspension. +#[route(GET "/admin/users/{user_id}/events")] +async fn detail_events(cx: &Cx) -> Result { + admin_only(cx).await?; + let id = path_param_segment(cx, "user_id").to_owned(); + let store = app_context::(cx).store.clone(); + let topic = Topic::AdminUser(id.clone()); + stream_changes(cx, crate::live::admin(), &[topic], move || { + let store = store.clone(); + let id = id.clone(); + async move { account_fingerprint(&store, &id).await } + }) + .await +} + #[page("/admin/users/{user_id}")] async fn detail_page(cx: &Cx) -> Result { let viewer = admin_only(cx).await?; diff --git a/crates/forge-web/src/pages/admin_users.rs b/crates/forge-web/src/pages/admin_users.rs index 3c6078d..a4294f3 100644 --- a/crates/forge-web/src/pages/admin_users.rs +++ b/crates/forge-web/src/pages/admin_users.rs @@ -9,13 +9,15 @@ use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; use topcoat::router::error::{forbidden, not_found, see_other}; -use topcoat::router::{page, path_param_segment}; +use topcoat::router::response::Response; +use topcoat::router::{page, path_param_segment, route}; use topcoat::view::{View, component, view}; use crate::audit::{self, Actor, Target}; use crate::auth::{check_csrf, current_user, hash_password_async}; use crate::i18n::admin::{self as g, K}; use crate::i18n::{self, Key, Lang}; +use crate::live::{Topic, stream_changes}; use crate::pages::issues_list::stamp_unix; use crate::state::AppState; use crate::views::{alert, enc, shell, user_facing_message}; @@ -61,6 +63,7 @@ async fn users_view( error: Option, ) -> Result { Ok(view! { +

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

@@ -121,9 +124,42 @@ async fn users_view( +
}) } +/// What the account list shows, as one string: a change to any of it is sent to the page. +async fn list_fingerprint(store: &Store) -> topcoat::Result { + let users = store.list_users().await?; + Ok(users + .iter() + .map(|u| { + format!( + "{}|{}|{}|{}|{}|{}", + u.id, + u.username, + u.email.as_deref().unwrap_or(""), + u.is_admin, + u.is_org(), + u.created_at + ) + }) + .collect::>() + .join("\n")) +} + +/// The account list's change stream. Admins only; anyone else gets 404. +#[route(GET "/admin/users/events")] +async fn users_events(cx: &Cx) -> Result { + admin_only(cx).await?; + let store = app_context::(cx).store.clone(); + stream_changes(cx, crate::live::admin(), &[Topic::AdminUsers], move || { + let store = store.clone(); + async move { list_fingerprint(&store).await } + }) + .await +} + #[page("/admin/users")] async fn users_page(cx: &Cx) -> Result { let viewer = admin_only(cx).await?; diff --git a/crates/forge-web/src/pages/audit_log.rs b/crates/forge-web/src/pages/audit_log.rs index 67b6028..d6b894a 100644 --- a/crates/forge-web/src/pages/audit_log.rs +++ b/crates/forge-web/src/pages/audit_log.rs @@ -6,12 +6,14 @@ use forge_core::tz::format_in_tz; use forge_core::{AuditAction, AuditCursor, AuditEntry, AuditFilter, Store}; use topcoat::Result; use topcoat::context::{Cx, app_context}; -use topcoat::router::{page, query_params}; +use topcoat::router::response::Response; +use topcoat::router::{page, query_params, route}; use topcoat::view::{View, component, view}; use crate::auth::require_user; use crate::i18n::admin::{self as g, K}; use crate::i18n::{self, Lang}; +use crate::live::{Topic, stream_changes}; use crate::pages::admin_users::admin_only; use crate::pages::issues_list::{list_href, stamp_unix}; use crate::state::AppState; @@ -131,6 +133,7 @@ async fn audit_table(lang: Lang, rows: Vec, show_actor: bool) -> Result #[component] async fn admin_audit_view( lang: Lang, + live: String, action: String, actor: String, notice: Option, @@ -138,6 +141,7 @@ async fn admin_audit_view( older_href: Option, ) -> Result { Ok(view! { +

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

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

@@ -173,6 +177,7 @@ async fn admin_audit_view( }
+
}) } @@ -243,12 +248,57 @@ async fn admin_audit_page(cx: &Cx) -> Result { ], ) }); + let live = list_href( + "/admin/audit/events", + &[("action", action.as_str()), ("actor", actor.as_str())], + ); let title = g::t(lang, K::AuditLog); Ok(view! { - shell(title: title, viewer: Some(&viewer), admin_audit_view(lang: lang, action: action, actor: actor, notice: notice, rows: rows, older_href: older_href)) + shell(title: title, viewer: Some(&viewer), admin_audit_view(lang: lang, live: live, action: action, actor: actor, notice: notice, rows: rows, older_href: older_href)) }) } +/// The first page of entries the filter selects, as one string: the stream sends when it changes. +/// An unknown action or actor selects nothing, as on the page. +async fn first_page_fingerprint(store: &Store, action: &str, actor: &str) -> Result { + let mut filter = AuditFilter::default(); + if !action.is_empty() { + match AuditAction::parse(action) { + Some(known) => filter.action = Some(known), + None => return Ok(String::new()), + } + } + if !actor.is_empty() { + match store.user_by_username(actor).await? { + Some(user) => filter.actor_id = Some(user.id), + None => return Ok(String::new()), + } + } + let (entries, _) = fetch_page(store, &filter, None).await?; + Ok(entries + .iter() + .map(|entry| entry.id.as_str()) + .collect::>() + .join(",")) +} + +/// The audit log's change stream, for the filter in its query. Admins only. +#[route(GET "/admin/audit/events")] +async fn admin_audit_events(cx: &Cx) -> Result { + admin_only(cx).await?; + let query = query_params::(cx)?; + let action = query.action.clone().unwrap_or_default().trim().to_owned(); + let actor = query.actor.clone().unwrap_or_default().trim().to_owned(); + let store = app_context::(cx).store.clone(); + stream_changes(cx, crate::live::admin(), &[Topic::AdminAudit], move || { + let store = store.clone(); + let action = action.clone(); + let actor = actor.clone(); + async move { first_page_fingerprint(&store, &action, &actor).await } + }) + .await +} + #[page("/settings/security/log")] async fn own_log_page(cx: &Cx) -> Result { let viewer = require_user(cx).await?; diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index c3908af..5f2048e 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -4,6 +4,8 @@ mod account_tools_tests; pub mod admin_backups; pub mod admin_health; +#[cfg(test)] +mod admin_live_tests; pub mod admin_mail; pub mod admin_replication; pub mod admin_runners; diff --git a/crates/forge-web/src/replication/worker.rs b/crates/forge-web/src/replication/worker.rs index 454bca3..78c365e 100644 --- a/crates/forge-web/src/replication/worker.rs +++ b/crates/forge-web/src/replication/worker.rs @@ -20,6 +20,7 @@ use super::{ remote_refs_checksum, sh_quote, snapshot_stamp, wiki_subject, wiki_subject_repo, }; use crate::backup::healthcheck; +use crate::live::Topic; use crate::state::AppState; /// Longest the worker sleeps with nothing due. Guards against a missed wake, not polling. @@ -145,7 +146,7 @@ async fn ping(url: &str, report: &ReconcileReport) { /// Records an outcome for `subject` and passes the error on. `refs` is the checksum to store on /// success (repos only). -async fn record( +pub(crate) async fn record( store: &Store, subject: &str, result: Result, String>, @@ -155,6 +156,7 @@ async fn record( if let Err(e) = store.record_replication_ok(subject, refs.as_deref()).await { tracing::error!(error = %e, subject, "replication: could not record success"); } + status_changed(); Ok(()) } Err(e) => { @@ -162,11 +164,19 @@ async fn record( if let Err(db) = store.record_replication_error(subject, &e).await { tracing::error!(error = %db, subject, "replication: could not record failure"); } + status_changed(); Err(e) } } } +/// A copy's status changed: the replication page and the health page of the admin area follow it. +fn status_changed() { + let hub = crate::live::admin(); + hub.bump(&Topic::AdminReplication); + hub.bump(&Topic::AdminHealth); +} + /// Pushes one repo to the standby and checks that its refs match. A mismatch triggers one /// re-push; a second mismatch is an error. Records the outcome for the repo. /// @@ -378,6 +388,7 @@ pub async fn reconcile_once(ctx: &Ctx) -> ReconcileRepor if let Err(e) = ctx.store.delete_replication_status(&status.subject).await { report.failures.push(format!("{}: {e}", status.subject)); } + status_changed(); } Err(e) => report .failures diff --git a/docs/architecture.md b/docs/architecture.md index 6600be1..e288afc 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -266,10 +266,16 @@ Pages update without a reload. A write that changes what a page shows calls `Liv | Org teams `/org/{org}/teams` | `/org/{org}/teams/events` | the org (teams and their coverage) | | Org team `/org/{org}/teams/{team}` | `/org/{org}/teams/{team}/events` | the org (members, linked repos) and each linked repo (name, visibility) | | Org settings `/org/{org}/settings` | `/org/{org}/settings/events` | the org (description, default repo role, member repo creation) | +| Admin users `/admin/users` and an account `/admin/users/{id}` | `/admin/users/events`, `/admin/users/{id}/events` | the account list, and one account's facts, suspension and passkeys | +| Admin audit `/admin/audit` | `/admin/audit/events`, with the filter in the query | the first page of the filter | +| Admin backups `/admin/backups` | `/admin/backups/events` | the run in progress and the last 20 runs | +| Admin replication `/admin/replication` | `/admin/replication/events` | each copy's status and the database snapshot | +| Admin health `/admin/health` | `/admin/health/events` | the alerts, the counts and the mail queue. The disk and tree probes are read when the page renders, not on each change | +| Admin server `/admin/server` | `/admin/server/events` | saved or reset settings. A page waiting for a restart gets one event when a new process answers | The org streams follow the same access as their pages: a non-member gets 404, and a member who is not an owner gets 403 on the settings stream. A team page names only the linked repos the viewer may read. Each org write (a POST under `/org/{org}/members`, `teams` or `settings`) wakes the org's streams. The org notices (for example "Member added.") are carried in the redirect's `?notice=` query, not a cookie, so a live refresh of the page shows the same notice again. -The user topics are keyed by user id, and their streams take the viewer from the session, so no URL names another user's inbox. Repo streams follow the same visibility as the repo page (a private repo answers 404 to a viewer who cannot read it). Explore lists public repos only. +The user topics are keyed by user id, and their streams take the viewer from the session, so no URL names another user's inbox. Repo streams follow the same visibility as the repo page (a private repo answers 404 to a viewer who cannot read it). Explore lists public repos only. The admin streams answer 404 to anyone who is not an instance admin, like the admin pages they serve. Every audited write also wakes the account pages of the users it names, so a login or a passkey change updates the account's facts. The admin pages' hub is process-wide (`live::admin()`), because the audit writer has no app state. A page can hold several streams at once: the repo header (`/{owner}/{repo}/events`) sits above the page's own list, issue, pull or run. `nav.js` opens one EventSource for each distinct `data-live` URL in the page, so each of them updates the page.