forge
Explore
Log in

Don't you dare go Hollow

The admin pages update live (users, account, audit, backups, replication, health, server, mail)

Browse files at this commit

07bdd5d6a66a7f1869300047bef68150e1927727Ahmet Kaan GümüşParent: b20e524
  • feat
    • the admin pages update live (users, account, audit, backups, replication, health, server, mail)
Show full message
⚡ feat: the admin pages update live (users, account, audit, backups, replication, health, server, mail)
crates/forge-web/src/alerts.rsmodified+3 -0
@@ -70,6 +70,7 @@ pub async fn raise(state: &AppState, topic: &str, key: &str, subject: &str, deta
70 pub async fn resolve(state: &AppState, key: &str) {70 pub async fn resolve(state: &AppState, key: &str) {
71 match state.store.resolve_alert(key).await {71 match state.store.resolve_alert(key).await {
72 Ok(Some(alert)) => {72 Ok(Some(alert)) => {
73+ crate::live::admin().bump(&crate::live::Topic::AdminHealth);
73 let kind = kind_of(&alert.kind);74 let kind = kind_of(&alert.kind);
74 if state.live().alerts.kind_enabled(kind) {75 if state.live().alerts.kind_enabled(kind) {
75 deliver(state, key, &alert.kind, &alert.subject, &alert.detail, true).await;76 deliver(state, key, &alert.kind, &alert.subject, &alert.detail, true).await;
@@ -105,6 +106,8 @@ async fn deliver(
105 detail: &str,106 detail: &str,
106 resolved: bool,107 resolved: bool,
107 ) {108 ) {
109+ // The alert was written (raised, resolved or recorded): the health page follows it.
110+ crate::live::admin().bump(&crate::live::Topic::AdminHealth);
108 let users = match state.store.list_users().await {111 let users = match state.store.list_users().await {
109 Ok(users) => users,112 Ok(users) => users,
110 Err(e) => {113 Err(e) => {
crates/forge-web/src/audit.rsmodified+13 -0
@@ -6,6 +6,7 @@ use serde_json::Value;
6 use topcoat::context::Cx;6 use topcoat::context::Cx;
7 7
8 use crate::client_ip::client_ip;8 use crate::client_ip::client_ip;
9+use crate::live::Topic;
9 10
10 /// Who did it. `Anonymous` is an unauthenticated attempt, `Cli` is the admin command line.11 /// Who did it. `Anonymous` is an unauthenticated attempt, `Cli` is the admin command line.
11 pub enum Actor<'a> {12 pub enum Actor<'a> {
@@ -50,5 +51,17 @@ pub async fn record(
50 }51 }
51 if let Err(err) = store.record_audit(&entry).await {52 if let Err(err) = store.record_audit(&entry).await {
52 tracing::error!(action = action.as_str(), error = %err, "failed to record audit entry");53 tracing::error!(action = action.as_str(), error = %err, "failed to record audit entry");
54+ return;
55+ }
56+ // The entry is committed: the audit log and the account list follow it, and so do the
57+ // accounts it names (the actor's last login, the target's facts and status).
58+ let hub = crate::live::admin();
59+ hub.bump(&Topic::AdminAudit);
60+ hub.bump(&Topic::AdminUsers);
61+ if let Some(actor) = &entry.actor_id {
62+ hub.bump(&Topic::AdminUser(actor.clone()));
63+ }
64+ if target.kind == "user" && !target.id.is_empty() {
65+ hub.bump(&Topic::AdminUser(target.id.to_string()));
53 }66 }
54 }67 }
crates/forge-web/src/backup/scheduler.rsmodified+15 -0
@@ -6,6 +6,7 @@ use std::path::PathBuf;
6 use std::sync::{Arc, Mutex, PoisonError};6 use std::sync::{Arc, Mutex, PoisonError};
7 use std::time::{Duration, SystemTime};7 use std::time::{Duration, SystemTime};
8 8
9+use crate::live::Topic;
9 use forge_core::store::backup_runs::{BackupRun, RunKind, RunTrigger};10 use forge_core::store::backup_runs::{BackupRun, RunKind, RunTrigger};
10 use forge_core::{Error, Result};11 use forge_core::{Error, Result};
11 use time::OffsetDateTime;12 use time::OffsetDateTime;
@@ -46,6 +47,7 @@ impl Jobs {
46 )));47 )));
47 }48 }
48 *slot = Some(kind);49 *slot = Some(kind);
50+ runs_changed();
49 Ok(JobGuard {51 Ok(JobGuard {
50 jobs: Arc::clone(self),52 jobs: Arc::clone(self),
51 kind,53 kind,
@@ -68,9 +70,19 @@ impl Drop for JobGuard {
68 if *slot == Some(self.kind) {70 if *slot == Some(self.kind) {
69 *slot = None;71 *slot = None;
70 }72 }
73+ drop(slot);
74+ runs_changed();
71 }75 }
72 }76 }
73 77
78+/// A run started or finished, or its slot was taken or freed: the backup and health pages of the
79+/// admin area follow it.
80+fn runs_changed() {
81+ let hub = crate::live::admin();
82+ hub.bump(&Topic::AdminBackups);
83+ hub.bump(&Topic::AdminHealth);
84+}
85+
74 fn started_unix(run: &BackupRun) -> Option<i64> {86 fn started_unix(run: &BackupRun) -> Option<i64> {
75 OffsetDateTime::parse(&run.started_at, &Rfc3339)87 OffsetDateTime::parse(&run.started_at, &Rfc3339)
76 .ok()88 .ok()
@@ -222,6 +234,7 @@ pub async fn backup_job(
222 prune: bool,234 prune: bool,
223 ) -> Result<BackupSummary> {235 ) -> Result<BackupSummary> {
224 let run_id = state.store.start_run(RunKind::Backup, trigger).await?;236 let run_id = state.store.start_run(RunKind::Backup, trigger).await?;
237+ runs_changed();
225 let healthcheck_url = Some(state.config.backup.healthcheck_url.as_str())238 let healthcheck_url = Some(state.config.backup.healthcheck_url.as_str())
226 .filter(|url| trigger == RunTrigger::Schedule && !url.is_empty());239 .filter(|url| trigger == RunTrigger::Schedule && !url.is_empty());
227 if let Some(url) = healthcheck_url {240 if let Some(url) = healthcheck_url {
@@ -281,6 +294,7 @@ async fn backup_set(state: &AppState, opts: &BackupOptions) -> Result<BackupSumm
281 /// Runs fsck over every repo and the database, and records it. The caller holds the run slot.294 /// Runs fsck over every repo and the database, and records it. The caller holds the run slot.
282 pub async fn fsck_job(state: &AppState, trigger: RunTrigger, full: bool) -> Result<FsckSummary> {295 pub async fn fsck_job(state: &AppState, trigger: RunTrigger, full: bool) -> Result<FsckSummary> {
283 let run_id = state.store.start_run(RunKind::Fsck, trigger).await?;296 let run_id = state.store.start_run(RunKind::Fsck, trigger).await?;
297+ runs_changed();
284 let outcome = run_fsck(&state.store, &state.git, full).await;298 let outcome = run_fsck(&state.store, &state.git, full).await;
285 match &outcome {299 match &outcome {
286 Ok(summary) if summary.is_ok() => crate::alerts::fsck_finished(state, Ok(())).await,300 Ok(summary) if summary.is_ok() => crate::alerts::fsck_finished(state, Ok(())).await,
@@ -315,6 +329,7 @@ async fn record_finish(
315 if let Err(e) = state.store.finish_run(run_id, ok, path, bytes, error).await {329 if let Err(e) = state.store.finish_run(run_id, ok, path, bytes, error).await {
316 tracing::error!(error = %e, run_id, "could not record the outcome of a backup run");330 tracing::error!(error = %e, run_id, "could not record the outcome of a backup run");
317 }331 }
332+ runs_changed();
318 }333 }
319 334
320 /// Starts a manual run in the background and returns at once. The caller claimed the run slot335 /// Starts a manual run in the background and returns at once. The caller claimed the run slot
crates/forge-web/src/ci/api.rsmodified+1 -0
@@ -160,6 +160,7 @@ async fn register(cx: &Cx, body: Body) -> topcoat::Result<Response> {
160 .await160 .await
161 {161 {
162 Ok((runner, secret)) => {162 Ok((runner, secret)) => {
163+ state.ci_live.bump_runners();
163 let body = RegisterResponse {164 let body = RegisterResponse {
164 runner_id: runner.id,165 runner_id: runner.id,
165 runner_secret: secret,166 runner_secret: secret,
crates/forge-web/src/live.rsmodified+28 -1
@@ -25,7 +25,7 @@
25 25
26 use std::collections::HashMap;26 use std::collections::HashMap;
27 use std::future::Future;27 use std::future::Future;
28-use std::sync::{Mutex, MutexGuard, PoisonError};28+use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
29 29
30 use futures_util::future::select_all;30 use futures_util::future::select_all;
31 use futures_util::stream;31 use futures_util::stream;
@@ -81,6 +81,31 @@ pub enum Topic {
81 /// An organization's pages: its members, teams, team members and linked repos, and settings.81 /// An organization's pages: its members, teams, team members and linked repos, and settings.
82 /// Keyed by the org's user id. Bumped by [`crate::pages::org_live`] after a POST under the org.82 /// Keyed by the org's user id. Bumped by [`crate::pages::org_live`] after a POST under the org.
83 Org(String),83 Org(String),
84+ /// The account list of the admin area: an account was registered, edited, suspended, lifted,
85+ /// given or lost admin rights, or deleted. Global. Admin pages only, on [`admin`].
86+ AdminUsers,
87+ /// One account's admin page: its facts, suspension and passkeys. Keyed by user id. Admin
88+ /// pages only, on [`admin`].
89+ AdminUser(String),
90+ /// The audit log: an entry was written. Global. Admin pages only, on [`admin`].
91+ AdminAudit,
92+ /// Backup and fsck runs: one started or finished. Global. Admin pages only, on [`admin`].
93+ AdminBackups,
94+ /// Replication: a copy was written, failed, or removed. Global. Admin pages only, on [`admin`].
95+ AdminReplication,
96+ /// The health page: an alert was raised or cleared, or a backup or copy finished. Global.
97+ /// Admin pages only, on [`admin`].
98+ AdminHealth,
99+ /// The server settings: a value was saved or reset, or a restart was requested. Global.
100+ /// Admin pages only, on [`admin`].
101+ AdminServer,
102+}
103+
104+/// The hub of the admin pages. It is process-wide, not part of [`crate::state::AppState`]: the
105+/// audit writer has no app state, and every audit entry wakes the admin pages from there.
106+pub fn admin() -> &'static LiveHub {
107+ static ADMIN: OnceLock<LiveHub> = OnceLock::new();
108+ ADMIN.get_or_init(LiveHub::default)
84 }109 }
85 110
86 /// The open topics, each with the counter its subscribers wait on.111 /// The open topics, each with the counter its subscribers wait on.
@@ -138,6 +163,8 @@ impl LiveHub {
138 self.bump(&Topic::User(owner_id.to_owned()));163 self.bump(&Topic::User(owner_id.to_owned()));
139 self.bump(&Topic::Explore);164 self.bump(&Topic::Explore);
140 self.bump(&Topic::Repo(repo_id.to_owned()));165 self.bump(&Topic::Repo(repo_id.to_owned()));
166+ // The owner's repo count is on the admin page of the account.
167+ admin().bump(&Topic::AdminUser(owner_id.to_owned()));
141 }168 }
142 }169 }
143 170
crates/forge-web/src/mail/live.rsmodified+2 -0
@@ -21,6 +21,8 @@ pub fn subscribe() -> watch::Receiver<u64> {
21 /// Counts one change of the queue. Nobody has to be listening.21 /// Counts one change of the queue. Nobody has to be listening.
22 pub fn bump() {22 pub fn bump() {
23 sender().send_modify(|generation| *generation = generation.wrapping_add(1));23 sender().send_modify(|generation| *generation = generation.wrapping_add(1));
24+ // The health page counts the queue too.
25+ crate::live::admin().bump(&crate::live::Topic::AdminHealth);
24 }26 }
25 27
26 #[cfg(test)]28 #[cfg(test)]
crates/forge-web/src/pages/admin_backups.rsmodified+30 -1
@@ -6,7 +6,7 @@
6 6
7 use forge_core::store::backup_runs::{BackupRun, RunKind};7 use forge_core::store::backup_runs::{BackupRun, RunKind};
8 use forge_core::tz::format_in_tz;8 use forge_core::tz::format_in_tz;
9-use forge_core::{AuditAction, Error, User};9+use forge_core::{AuditAction, Error, Store, User};
10 use serde::Deserialize;10 use serde::Deserialize;
11 use topcoat::Result;11 use topcoat::Result;
12 use topcoat::context::{Cx, app_context};12 use topcoat::context::{Cx, app_context};
@@ -21,6 +21,7 @@ use crate::auth::check_csrf;
21 use crate::backup::scheduler::{configured_dir, start_manual};21 use crate::backup::scheduler::{configured_dir, start_manual};
22 use crate::i18n::admin::{self as g, K};22 use crate::i18n::admin::{self as g, K};
23 use crate::i18n::{self, Lang};23 use crate::i18n::{self, Lang};
24+use crate::live::{Topic, stream_changes};
24 use crate::pages::admin_users::admin_only;25 use crate::pages::admin_users::admin_only;
25 use crate::pages::issues_list::stamp_unix;26 use crate::pages::issues_list::stamp_unix;
26 use crate::state::AppState;27 use crate::state::AppState;
@@ -138,6 +139,7 @@ async fn backups_view(
138 notice: Option<String>,139 notice: Option<String>,
139 ) -> Result<impl View> {140 ) -> Result<impl View> {
140 Ok(view! {141 Ok(view! {
142+ <div data-live="/admin/backups/events">
141 <section class="page-head">143 <section class="page-head">
142 <h1>(g::t(lang, K::Backups))</h1>144 <h1>(g::t(lang, K::Backups))</h1>
143 <p class="muted">(g::t(lang, K::BackupsIntro))</p>145 <p class="muted">(g::t(lang, K::BackupsIntro))</p>
@@ -212,9 +214,36 @@ async fn backups_view(
212 </div>214 </div>
213 }215 }
214 </section>216 </section>
217+ </div>
215 })218 })
216 }219 }
217 220
221+/// The backups page's state, as one string: the run in progress and the recent runs.
222+async fn runs_fingerprint(store: &Store, running: Option<RunKind>) -> Result<String> {
223+ let runs = store.recent_runs(RUN_LIMIT).await?;
224+ Ok(format!("{running:?}|{runs:?}"))
225+}
226+
227+/// The backups page's change stream. Admins only.
228+#[route(GET "/admin/backups/events")]
229+async fn backups_events(cx: &Cx) -> Result<Response> {
230+ admin_only(cx).await?;
231+ let state = app_context::<AppState>(cx);
232+ let store = state.store.clone();
233+ let jobs = state.jobs.clone();
234+ stream_changes(
235+ cx,
236+ crate::live::admin(),
237+ &[Topic::AdminBackups],
238+ move || {
239+ let store = store.clone();
240+ let running = jobs.running();
241+ async move { runs_fingerprint(&store, running).await }
242+ },
243+ )
244+ .await
245+}
246+
218 #[page("/admin/backups")]247 #[page("/admin/backups")]
219 async fn backups_page(cx: &Cx) -> Result<impl View> {248 async fn backups_page(cx: &Cx) -> Result<impl View> {
220 let viewer = admin_only(cx).await?;249 let viewer = admin_only(cx).await?;
crates/forge-web/src/pages/admin_health.rsmodified+34 -1
@@ -13,12 +13,14 @@ use forge_core::tz::format_in_tz;
13 use tokio::process::Command;13 use tokio::process::Command;
14 use topcoat::Result;14 use topcoat::Result;
15 use topcoat::context::{Cx, app_context};15 use topcoat::context::{Cx, app_context};
16-use topcoat::router::page;16+use topcoat::router::response::Response;
17+use topcoat::router::{page, route};
17 use topcoat::view::{View, component, view};18 use topcoat::view::{View, component, view};
18 19
19 use crate::i18n::accounts::{A, duration_short, t as at};20 use crate::i18n::accounts::{A, duration_short, t as at};
20 use crate::i18n::alerts as alert_text;21 use crate::i18n::alerts as alert_text;
21 use crate::i18n::{self, Lang};22 use crate::i18n::{self, Lang};
23+use crate::live::{Topic, stream_changes};
22 use crate::pages::admin_users::admin_only;24 use crate::pages::admin_users::admin_only;
23 use crate::state::AppState;25 use crate::state::AppState;
24 use crate::views::{human_size, now_unix, relative_time, shell};26 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<Vec<AlertR
320 async fn health_view(lang: Lang, tiles: Vec<Tile>, alerts: Vec<AlertRow>) -> Result<impl View> {322 async fn health_view(lang: Lang, tiles: Vec<Tile>, alerts: Vec<AlertRow>) -> Result<impl View> {
321 let count = alerts.len();323 let count = alerts.len();
322 Ok(view! {324 Ok(view! {
325+ <div data-live="/admin/health/events">
323 <section class="page-head">326 <section class="page-head">
324 <h1>(at(lang, A::Health))</h1>327 <h1>(at(lang, A::Health))</h1>
325 <p class="muted">(at(lang, A::HealthIntro))</p>328 <p class="muted">(at(lang, A::HealthIntro))</p>
@@ -355,6 +358,7 @@ async fn health_view(lang: Lang, tiles: Vec<Tile>, alerts: Vec<AlertRow>) -> Res
355 </section>358 </section>
356 }359 }
357 </div>360 </div>
361+ </div>
358 })362 })
359 }363 }
360 364
@@ -371,6 +375,35 @@ async fn health_page(cx: &Cx) -> Result<impl View> {
371 })375 })
372 }376 }
373 377
378+/// What the event-driven parts of the health page show, as one string: the alerts, the counts and
379+/// the mail queue. The disk and tree probes (`df`, `du`) are not read here: they cost a process
380+/// each, so they run only when the page renders.
381+async fn health_fingerprint(state: &AppState) -> Result<String> {
382+ let counts = state.store.health_counts().await?;
383+ let mail = state
384+ .store
385+ .mail_state_counts(&forge_core::time::now_stamp())
386+ .await?;
387+ let alerts: Vec<(String, String)> = alert_rows(state, Lang::En, "UTC")
388+ .await?
389+ .into_iter()
390+ .map(|alert| (alert.title, alert.body))
391+ .collect();
392+ Ok(format!("{counts:?}|{mail:?}|{alerts:?}"))
393+}
394+
395+/// The health page's change stream. Admins only.
396+#[route(GET "/admin/health/events")]
397+async fn health_events(cx: &Cx) -> Result<Response> {
398+ admin_only(cx).await?;
399+ let state = app_context::<AppState>(cx).clone();
400+ stream_changes(cx, crate::live::admin(), &[Topic::AdminHealth], move || {
401+ let state = state.clone();
402+ async move { health_fingerprint(&state).await }
403+ })
404+ .await
405+}
406+
374 #[cfg(test)]407 #[cfg(test)]
375 mod tests {408 mod tests {
376 use super::*;409 use super::*;
crates/forge-web/src/pages/admin_live_tests.rsadded+304 -0
@@ -0,0 +1,304 @@
1+//! The live streams of the admin pages. Each one is admin only (anyone else gets 404), and each
2+//! sends one `changed` event when the data of its page changes, through the real write path.
3+
4+use std::fmt::Debug;
5+use std::time::Duration;
6+
7+use bytes::Bytes;
8+use forge_core::AuditAction;
9+use forge_core::store::backup_runs::RunKind;
10+use forge_core::store::replication::DB_SUBJECT;
11+use futures_util::{Stream, StreamExt};
12+use serde_json::Value;
13+use topcoat::router::request::Request;
14+use topcoat::router::{Body, Router};
15+
16+use crate::audit::{self, Actor, Target};
17+use crate::auth::SESSION_COOKIE;
18+use crate::live::{Topic, admin};
19+use crate::state::AppState;
20+use crate::test_support::{app_router, create_session, test_state};
21+
22+const ADMIN_TOKEN: &str = "admin-live-admin-session";
23+const USER_TOKEN: &str = "admin-live-user-session";
24+const CSRF: &str = "admin-live-csrf";
25+
26+/// Every stream of the admin area that this module covers, for the given account.
27+fn streams(user_id: &str) -> Vec<String> {
28+ vec![
29+ "/admin/users/events".to_owned(),
30+ format!("/admin/users/{user_id}/events"),
31+ "/admin/audit/events".to_owned(),
32+ "/admin/backups/events".to_owned(),
33+ "/admin/replication/events".to_owned(),
34+ "/admin/health/events".to_owned(),
35+ "/admin/server/events".to_owned(),
36+ ]
37+}
38+
39+struct Fixture {
40+ _dir: tempfile::TempDir,
41+ app: Router,
42+ state: AppState,
43+ admin_id: String,
44+ user_id: String,
45+}
46+
47+async fn fixture() -> Fixture {
48+ let dir = tempfile::tempdir().expect("tempdir");
49+ let data_dir = dir.path().join("data");
50+ std::fs::create_dir_all(&data_dir).expect("data dir");
51+ let state = test_state(&data_dir).await;
52+ let admin = state
53+ .store
54+ .create_user("root", None, "h", true)
55+ .await
56+ .expect("admin");
57+ let user = state
58+ .store
59+ .create_user("plain", None, "h", false)
60+ .await
61+ .expect("user");
62+ create_session(&state.store, &admin.id, ADMIN_TOKEN, CSRF).await;
63+ create_session(&state.store, &user.id, USER_TOKEN, CSRF).await;
64+ let app = app_router(state.clone());
65+ Fixture {
66+ _dir: dir,
67+ app,
68+ state,
69+ admin_id: admin.id,
70+ user_id: user.id,
71+ }
72+}
73+
74+/// Opens a GET, with the session cookie when there is a token. The body is not read.
75+async fn open(app: &Router, uri: &str, token: Option<&str>) -> topcoat::router::response::Response {
76+ let mut builder = Request::builder().method("GET").uri(uri);
77+ if let Some(token) = token {
78+ builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}"));
79+ }
80+ app.handle(builder.body(Body::from(String::new())).expect("request"))
81+ .await
82+}
83+
84+/// The next frame of an event stream, or None once it has ended. Fails after five seconds.
85+async fn next_frame<S, E>(frames: &mut S) -> Option<Vec<u8>>
86+where
87+ S: Stream<Item = Result<Bytes, E>> + Unpin,
88+ E: Debug,
89+{
90+ let frame = tokio::time::timeout(Duration::from_secs(5), frames.next())
91+ .await
92+ .expect("a frame within five seconds")?;
93+ Some(frame.expect("data").to_vec())
94+}
95+
96+/// The next `changed` event of a stream. Every stream opens with its `retry` field: skipped here.
97+async fn next_event<S, E>(frames: &mut S) -> Vec<u8>
98+where
99+ S: Stream<Item = Result<Bytes, E>> + Unpin,
100+ E: Debug,
101+{
102+ loop {
103+ let bytes = next_frame(frames).await.expect("an event before the end");
104+ if !bytes.starts_with(b"retry: ") {
105+ return bytes;
106+ }
107+ }
108+}
109+
110+/// The `changed` event of a stream whose data is `data`.
111+fn changed(data: &str) -> Vec<u8> {
112+ format!("event: changed\ndata: {data}\n\n").into_bytes()
113+}
114+
115+#[tokio::test]
116+async fn admin_streams_answer_only_admins() {
117+ let fx = fixture().await;
118+ for uri in streams(&fx.user_id) {
119+ let anonymous = open(&fx.app, &uri, None).await;
120+ assert_eq!(anonymous.status().as_u16(), 404, "anonymous: {uri}");
121+ let plain = open(&fx.app, &uri, Some(USER_TOKEN)).await;
122+ assert_eq!(plain.status().as_u16(), 404, "a plain user: {uri}");
123+ let admin_reply = open(&fx.app, &uri, Some(ADMIN_TOKEN)).await;
124+ assert_eq!(admin_reply.status().as_u16(), 200, "an admin: {uri}");
125+ }
126+}
127+
128+#[tokio::test]
129+async fn the_account_list_sends_when_an_account_is_created() {
130+ let fx = fixture().await;
131+ let mut frames = open(&fx.app, "/admin/users/events", Some(ADMIN_TOKEN))
132+ .await
133+ .into_body()
134+ .into_data_stream();
135+ let retry = next_frame(&mut frames).await.expect("the retry field");
136+ assert!(retry.starts_with(b"retry: "), "{retry:?}");
137+
138+ let newcomer = fx
139+ .state
140+ .store
141+ .create_user("newcomer", None, "h", false)
142+ .await
143+ .expect("user");
144+ audit::record(
145+ &fx.state.store,
146+ None,
147+ Actor::Cli,
148+ AuditAction::UserCreated,
149+ Target {
150+ kind: "user",
151+ id: &newcomer.id,
152+ name: "newcomer",
153+ },
154+ Value::Null,
155+ )
156+ .await;
157+ assert_eq!(next_event(&mut frames).await, changed("1"));
158+}
159+
160+#[tokio::test]
161+async fn an_account_page_sends_when_its_account_is_suspended() {
162+ let fx = fixture().await;
163+ let uri = format!("/admin/users/{}/events", fx.user_id);
164+ let mut frames = open(&fx.app, &uri, Some(ADMIN_TOKEN))
165+ .await
166+ .into_body()
167+ .into_data_stream();
168+
169+ fx.state
170+ .store
171+ .suspend_user(&fx.user_id, "spam", Some(&fx.admin_id))
172+ .await
173+ .expect("suspend");
174+ audit::record(
175+ &fx.state.store,
176+ None,
177+ Actor::Cli,
178+ AuditAction::UserSuspended,
179+ Target {
180+ kind: "user",
181+ id: &fx.user_id,
182+ name: "plain",
183+ },
184+ Value::Null,
185+ )
186+ .await;
187+ assert_eq!(next_event(&mut frames).await, changed("1"));
188+}
189+
190+#[tokio::test]
191+async fn an_account_page_of_a_missing_account_is_404() {
192+ let fx = fixture().await;
193+ let reply = open(
194+ &fx.app,
195+ "/admin/users/no-such-account/events",
196+ Some(ADMIN_TOKEN),
197+ )
198+ .await;
199+ assert_eq!(reply.status().as_u16(), 404);
200+}
201+
202+#[tokio::test]
203+async fn the_audit_log_sends_a_new_entry_of_its_filter() {
204+ let fx = fixture().await;
205+ let mut frames = open(
206+ &fx.app,
207+ "/admin/audit/events?action=login_failed",
208+ Some(ADMIN_TOKEN),
209+ )
210+ .await
211+ .into_body()
212+ .into_data_stream();
213+
214+ audit::record(
215+ &fx.state.store,
216+ None,
217+ Actor::Anonymous,
218+ AuditAction::LoginFailed,
219+ Target::default(),
220+ Value::Null,
221+ )
222+ .await;
223+ assert_eq!(next_event(&mut frames).await, changed("1"));
224+}
225+
226+#[tokio::test]
227+async fn the_backups_page_sends_when_a_run_starts_and_ends() {
228+ let fx = fixture().await;
229+ let mut frames = open(&fx.app, "/admin/backups/events", Some(ADMIN_TOKEN))
230+ .await
231+ .into_body()
232+ .into_data_stream();
233+
234+ // Taking the run slot is the start of a run; dropping its guard is the end of it.
235+ let guard = fx
236+ .state
237+ .jobs
238+ .claim(RunKind::Backup)
239+ .expect("the slot is free");
240+ assert_eq!(next_event(&mut frames).await, changed("1"));
241+ drop(guard);
242+ assert_eq!(next_event(&mut frames).await, changed("1"));
243+}
244+
245+#[tokio::test]
246+async fn the_replication_page_sends_when_a_copy_fails() {
247+ let fx = fixture().await;
248+ let mut frames = open(&fx.app, "/admin/replication/events", Some(ADMIN_TOKEN))
249+ .await
250+ .into_body()
251+ .into_data_stream();
252+
253+ // The worker's own recording path: a failed step is written and the page is woken.
254+ let outcome = crate::replication::worker::record(
255+ &fx.state.store,
256+ DB_SUBJECT,
257+ Err("standby unreachable".to_owned()),
258+ )
259+ .await;
260+ assert!(outcome.is_err());
261+ assert_eq!(next_event(&mut frames).await, changed("1"));
262+}
263+
264+#[tokio::test]
265+async fn the_health_page_sends_when_an_alert_is_raised() {
266+ let fx = fixture().await;
267+ let mut frames = open(&fx.app, "/admin/health/events", Some(ADMIN_TOKEN))
268+ .await
269+ .into_body()
270+ .into_data_stream();
271+
272+ crate::alerts::raise(
273+ &fx.state,
274+ "runner_offline",
275+ "runner-offline:tahinli-ci",
276+ "tahinli-ci",
277+ "silent for an hour",
278+ )
279+ .await;
280+ assert_eq!(next_event(&mut frames).await, changed("1"));
281+}
282+
283+#[tokio::test]
284+async fn the_server_page_sends_when_a_setting_changes_and_on_a_restart() {
285+ let fx = fixture().await;
286+ // A page that waits for a restart: a process other than the one it waits for sends at once.
287+ let mut frames = open(
288+ &fx.app,
289+ "/admin/server/events?restarting=an-older-boot",
290+ Some(ADMIN_TOKEN),
291+ )
292+ .await
293+ .into_body()
294+ .into_data_stream();
295+ assert_eq!(next_event(&mut frames).await, changed("restarted"));
296+
297+ // Any saved or reset setting wakes the stream.
298+ let mut settings = open(&fx.app, "/admin/server/events", Some(ADMIN_TOKEN))
299+ .await
300+ .into_body()
301+ .into_data_stream();
302+ admin().bump(&Topic::AdminServer);
303+ assert_eq!(next_event(&mut settings).await, changed("settings"));
304+}
crates/forge-web/src/pages/admin_mail.rsmodified+10 -3
@@ -3,8 +3,8 @@
3 //! Two tabs. Settings: the SMTP server, sender and password (the password is write-only: a blank3 //! Two tabs. Settings: the SMTP server, sender and password (the password is write-only: a blank
4 //! field keeps the stored one) and "Send test mail" to the admin's own address. Queue: every4 //! field keeps the stored one) and "Send test mail" to the admin's own address. Queue: every
5 //! message in the outbox with its state, kind, tries and last error, filtered by state. A failed5 //! message in the outbox with its state, kind, tries and last error, filtered by state. A failed
6-//! message can be retried or discarded there. The queue's wrapper carries `data-live`, so each6+//! message can be retried or discarded there. Both tabs carry `data-live`, so each queue change or
7-//! queue change re-renders it through `/admin/mail/events` with no reload and no polling.7+//! saved setting re-renders the tab through `/admin/mail/events` with no reload and no polling.
8 //! Saving the settings and queuing a test are audited.8 //! Saving the settings and queuing a test are audited.
9 9
10 use forge_core::config::MailTransport;10 use forge_core::config::MailTransport;
@@ -250,6 +250,9 @@ async fn mail_view(
250 </section>250 </section>
251 }251 }
252 if settings_on {252 if settings_on {
253+ // Saved by any admin session: the stream re-renders the settings with the same signal
254+ // as the queue (the save bumps it too), and the form keeps what was typed.
255+ <div data-live="/admin/mail/events">
253 <section class="card">256 <section class="card">
254 <h2>(g::t(lang, K::SmtpServer))</h2>257 <h2>(g::t(lang, K::SmtpServer))</h2>
255 <p class="muted small">(g::t(lang, K::MailTransportNote))</p>258 <p class="muted small">(g::t(lang, K::MailTransportNote))</p>
@@ -282,6 +285,7 @@ async fn mail_view(
282 </div>285 </div>
283 </form>286 </form>
284 </section>287 </section>
288+ </div>
285 } else if let Some(queue) = data.queue {289 } else if let Some(queue) = data.queue {
286 <section class="card">290 <section class="card">
287 <p class="muted small">(g::t(lang, K::MailQueueIntro))</p>291 <p class="muted small">(g::t(lang, K::MailQueueIntro))</p>
@@ -940,7 +944,10 @@ mod tests {
940 );944 );
941 945
942 let (_, settings) = send(&fx.router, "GET", "/admin/mail", Some(ADMIN_TOKEN), None).await;946 let (_, settings) = send(&fx.router, "GET", "/admin/mail", Some(ADMIN_TOKEN), None).await;
943- assert!(!settings.contains("data-live="), "only the queue is live");947+ assert!(
948+ settings.contains(r#"data-live="/admin/mail/events""#),
949+ "the settings tab is live too"
950+ );
944 assert!(951 assert!(
945 !settings.contains("Reset your password"),952 !settings.contains("Reset your password"),
946 "the queue is on its own tab"953 "the queue is on its own tab"
crates/forge-web/src/pages/admin_replication.rsmodified+41 -0
@@ -25,6 +25,7 @@ use crate::audit::{self, Actor, Target};
25 use crate::auth::check_csrf;25 use crate::auth::check_csrf;
26 use crate::i18n::admin::{self as g, K};26 use crate::i18n::admin::{self as g, K};
27 use crate::i18n::{self, Key, Lang};27 use crate::i18n::{self, Key, Lang};
28+use crate::live::{Topic, stream_changes};
28 use crate::pages::admin_users::admin_only;29 use crate::pages::admin_users::admin_only;
29 use crate::pages::issues_list::stamp_unix;30 use crate::pages::issues_list::stamp_unix;
30 use crate::state::AppState;31 use crate::state::AppState;
@@ -166,6 +167,7 @@ async fn replication_view(
166 notice: Option<String>,167 notice: Option<String>,
167 ) -> Result<impl View> {168 ) -> Result<impl View> {
168 Ok(view! {169 Ok(view! {
170+ <div data-live="/admin/replication/events">
169 <section class="page-head">171 <section class="page-head">
170 <h1>(g::t(lang, K::Replication))</h1>172 <h1>(g::t(lang, K::Replication))</h1>
171 <p class="muted">(g::t(lang, K::ReplicationIntro))</p>173 <p class="muted">(g::t(lang, K::ReplicationIntro))</p>
@@ -228,9 +230,48 @@ async fn replication_view(
228 </div>230 </div>
229 }231 }
230 </section>232 </section>
233+ </div>
231 })234 })
232 }235 }
233 236
237+/// What the replication page shows, as one string. The health labels are read at each wake, so a
238+/// wake also refreshes a copy that has gone stale since the last change.
239+async fn page_fingerprint(state: &AppState) -> Result<String> {
240+ let data = page_data(state, "UTC", Lang::En).await?;
241+ let rows: Vec<_> = data
242+ .repos
243+ .iter()
244+ .map(|row| (&row.name, row.health, &row.last_ok, &row.error))
245+ .collect();
246+ Ok(format!(
247+ "{}|{}|{}|{}|{}|{}|{:?}",
248+ data.enabled,
249+ data.db_health,
250+ data.db_last_ok,
251+ data.db_last_attempt,
252+ data.db_error,
253+ data.target,
254+ rows
255+ ))
256+}
257+
258+/// The replication page's change stream. Admins only.
259+#[route(GET "/admin/replication/events")]
260+async fn replication_events(cx: &Cx) -> Result<Response> {
261+ admin_only(cx).await?;
262+ let state = app_context::<AppState>(cx).clone();
263+ stream_changes(
264+ cx,
265+ crate::live::admin(),
266+ &[Topic::AdminReplication],
267+ move || {
268+ let state = state.clone();
269+ async move { page_fingerprint(&state).await }
270+ },
271+ )
272+ .await
273+}
274+
234 #[page("/admin/replication")]275 #[page("/admin/replication")]
235 async fn replication_page(cx: &Cx) -> Result<impl View> {276 async fn replication_page(cx: &Cx) -> Result<impl View> {
236 let viewer = admin_only(cx).await?;277 let viewer = admin_only(cx).await?;
crates/forge-web/src/pages/admin_runners.rsmodified+2 -0
@@ -619,6 +619,7 @@ async fn runner_set_disabled(cx: &Cx, Form(form): Form<DisableForm>) -> Result<S
619 }619 }
620 let disabled = form.disabled == "1";620 let disabled = form.disabled == "1";
621 state.store.set_runner_disabled(id, disabled).await?;621 state.store.set_runner_disabled(id, disabled).await?;
622+ state.ci_live.bump_runners();
622 tracing::info!(actor_id = %viewer.0.id, runner_id = %id, disabled, "ci runner state changed");623 tracing::info!(actor_id = %viewer.0.id, runner_id = %id, disabled, "ci runner state changed");
623 Ok(back_to_list(if disabled { "disabled" } else { "enabled" }))624 Ok(back_to_list(if disabled { "disabled" } else { "enabled" }))
624 }625 }
@@ -636,6 +637,7 @@ async fn runner_delete(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther>
636 return Ok(back_to_list("missing"));637 return Ok(back_to_list("missing"));
637 };638 };
638 state.store.delete_runner(id).await?;639 state.store.delete_runner(id).await?;
640+ state.ci_live.bump_runners();
639 audit::record(641 audit::record(
640 &state.store,642 &state.store,
641 Some(cx),643 Some(cx),
crates/forge-web/src/pages/admin_server.rsmodified+32 -12
@@ -32,6 +32,7 @@ use crate::audit::{self, Actor, Target};
32 use crate::auth::check_csrf;32 use crate::auth::check_csrf;
33 use crate::i18n::admin::{self as g, K};33 use crate::i18n::admin::{self as g, K};
34 use crate::i18n::{self, Key, Lang};34 use crate::i18n::{self, Key, Lang};
35+use crate::live::Topic;
35 use crate::pages::admin_users::admin_only;36 use crate::pages::admin_users::admin_only;
36 use crate::pages::ci_runs::{changed_event, events_response};37 use crate::pages::ci_runs::{changed_event, events_response};
37 use crate::self_update;38 use crate::self_update;
@@ -217,9 +218,17 @@ async fn server_view(
217 ) -> Result<impl View> {218 ) -> Result<impl View> {
218 let tab = group.slug();219 let tab = group.slug();
219 let any_editable = rows.iter().any(|r| !r.fixed);220 let any_editable = rows.iter().any(|r| !r.fixed);
220- let live = (restart == Restart::Pending).then_some("/admin/server/events");221+ // A pending restart names the boot id it waits for: the stream then sends at once when a new
222+ // process answers, and the page re-renders.
223+ let live = match restart {
224+ Restart::Pending => format!(
225+ "/admin/server/events?restarting={}",
226+ enc(self_update::boot_id())
227+ ),
228+ _ => "/admin/server/events".to_owned(),
229+ };
221 Ok(view! {230 Ok(view! {
222- <div data-live=(live)>231+ <div data-live=(live.as_str())>
223 <section class="page-head">232 <section class="page-head">
224 <h1>(g::t(lang, K::ServerSettings))</h1>233 <h1>(g::t(lang, K::ServerSettings))</h1>
225 <p class="muted">(g::t(lang, K::ServerSettingsIntro))</p>234 <p class="muted">(g::t(lang, K::ServerSettingsIntro))</p>
@@ -401,6 +410,7 @@ async fn save(
401 state.store.clear_server_override(key).await?;410 state.store.clear_server_override(key).await?;
402 }411 }
403 state.settings.publish(&plan.overrides)?;412 state.settings.publish(&plan.overrides)?;
413+ crate::live::admin().bump(&Topic::AdminServer);
404 let keys: Vec<&str> = plan.sets.iter().map(|(k, _)| k.as_str()).collect();414 let keys: Vec<&str> = plan.sets.iter().map(|(k, _)| k.as_str()).collect();
405 audit::record(415 audit::record(
406 &state.store,416 &state.store,
@@ -462,17 +472,26 @@ async fn server_restart(cx: &Cx, Form(form): Form<RestartForm>) -> Result<Respon
462 .into())472 .into())
463 }473 }
464 474
465-/// The stream of the "Restarting" page. It sends one `changed` event with the boot id when it475+/// The server settings' change stream. Admins only. It sends `changed` when a setting is saved or
466-/// connects and then stays quiet. The server going down closes it, the browser reconnects by476+/// reset, by any session. When the page waits for a restart (`restarting` names the boot id it
467-/// itself, and the first event of the new process re-renders the page.477+/// waits past) and this process is not that one, it sends one `changed` on connect: the browser
478+/// reconnects to the new process after the old one goes down, and that re-renders the page.
468 #[route(GET "/admin/server/events")]479 #[route(GET "/admin/server/events")]
469 async fn server_events(cx: &Cx) -> Result<Response> {480 async fn server_events(cx: &Cx) -> Result<Response> {
470 admin_only(cx).await?;481 admin_only(cx).await?;
471- let events = futures_util::stream::once(std::future::ready(changed_event(482+ let query = query_params::<ServerQuery>(cx)?;
472- self_update::boot_id().to_owned(),483+ let restarted = query
473- )))484+ .restarting
474- .chain(futures_util::stream::pending());485+ .as_deref()
475- events_response(cx, events)486+ .is_some_and(|id| !id.is_empty() && id != self_update::boot_id());
487+ let on_connect =
488+ futures_util::stream::iter(restarted.then(|| changed_event("restarted".to_owned())));
489+ let wake = crate::live::admin().subscribe(&Topic::AdminServer);
490+ let changes = futures_util::stream::unfold(wake, |mut wake| async move {
491+ wake.changed().await.ok()?;
492+ Some((changed_event("settings".to_owned()), wake))
493+ });
494+ events_response(cx, on_connect.chain(changes))
476 }495 }
477 496
478 #[derive(Deserialize, Default)]497 #[derive(Deserialize, Default)]
@@ -518,6 +537,7 @@ async fn reset(
518 let next = state.settings.plan_reset(&existing, key)?;537 let next = state.settings.plan_reset(&existing, key)?;
519 state.store.clear_server_override(key).await?;538 state.store.clear_server_override(key).await?;
520 state.settings.publish(&next)?;539 state.settings.publish(&next)?;
540+ crate::live::admin().bump(&Topic::AdminServer);
521 audit::record(541 audit::record(
522 &state.store,542 &state.store,
523 Some(cx),543 Some(cx),
@@ -862,10 +882,10 @@ mod tests {
862 // Same process: "Restarting" with the event stream. A new process: back to normal.882 // Same process: "Restarting" with the event stream. A new process: back to normal.
863 let page = admin_get(&fx, &location).await;883 let page = admin_get(&fx, &location).await;
864 assert!(page.contains("Restarting..."));884 assert!(page.contains("Restarting..."));
865- assert!(page.contains(r#"data-live="/admin/server/events""#));885+ assert!(page.contains(r#"data-live="/admin/server/events?restarting="#));
866 let page = admin_get(&fx, "/admin/server?restarting=an-older-boot").await;886 let page = admin_get(&fx, "/admin/server?restarting=an-older-boot").await;
867 assert!(!page.contains("Restarting..."));887 assert!(!page.contains("Restarting..."));
868- assert!(!page.contains("data-live="));888+ assert!(page.contains(r#"data-live="/admin/server/events""#));
869 assert!(page.contains("The server restarted"));889 assert!(page.contains("The server restarted"));
870 }890 }
871 891
crates/forge-web/src/pages/admin_user_detail.rsmodified+46 -2
@@ -6,13 +6,14 @@ use forge_core::names::normalize_name;
6 use forge_core::store::suspension::{AccountFacts, Suspension};6 use forge_core::store::suspension::{AccountFacts, Suspension};
7 use forge_core::store::user_delete::GHOST_USERNAME;7 use forge_core::store::user_delete::GHOST_USERNAME;
8 use forge_core::tz::format_in_tz;8 use forge_core::tz::format_in_tz;
9-use forge_core::{AuditAction, User};9+use forge_core::{AuditAction, Store, User};
10 use serde::Deserialize;10 use serde::Deserialize;
11 use topcoat::Result;11 use topcoat::Result;
12 use topcoat::context::{Cx, app_context};12 use topcoat::context::{Cx, app_context};
13 use topcoat::router::content::Form;13 use topcoat::router::content::Form;
14 use topcoat::router::error::{forbidden, not_found, see_other};14 use topcoat::router::error::{forbidden, not_found, see_other};
15-use topcoat::router::{page, path_param_segment, query_params};15+use topcoat::router::response::Response;
16+use topcoat::router::{page, path_param_segment, query_params, route};
16 use topcoat::view::{View, component, view};17 use topcoat::view::{View, component, view};
17 18
18 use crate::audit::{self, Actor, Target};19 use crate::audit::{self, Actor, Target};
@@ -20,6 +21,7 @@ use crate::auth::{check_csrf, two_factor_enabled};
20 use crate::i18n::accounts::{A, t as at};21 use crate::i18n::accounts::{A, t as at};
21 use crate::i18n::admin::{self as g, K};22 use crate::i18n::admin::{self as g, K};
22 use crate::i18n::{self, Key, Lang};23 use crate::i18n::{self, Key, Lang};
24+use crate::live::{Topic, stream_changes};
23 use crate::pages::admin_users::admin_only;25 use crate::pages::admin_users::admin_only;
24 use crate::pages::issues_list::stamp_unix;26 use crate::pages::issues_list::stamp_unix;
25 use crate::pages::passkeys::s;27 use crate::pages::passkeys::s;
@@ -162,8 +164,10 @@ async fn detail_body(
162 let passkeys_action = format!("{base}/remove-passkeys");164 let passkeys_action = format!("{base}/remove-passkeys");
163 let passkey_count = passkeys.to_string();165 let passkey_count = passkeys.to_string();
164 let delete_href = format!("{base}/delete");166 let delete_href = format!("{base}/delete");
167+ let live = format!("{base}/events");
165 let Notice { done, error, link } = notice;168 let Notice { done, error, link } = notice;
166 Ok(view! {169 Ok(view! {
170+ <div data-live=(live.as_str())>
167 <section class="page-head">171 <section class="page-head">
168 <h1>(target.username.as_str())</h1>172 <h1>(target.username.as_str())</h1>
169 </section>173 </section>
@@ -270,9 +274,49 @@ async fn detail_body(
270 }274 }
271 </p>275 </p>
272 </section>276 </section>
277+ </div>
273 })278 })
274 }279 }
275 280
281+/// What the page shows of one account, as one string. A missing or hidden account is a 404.
282+async fn account_fingerprint(store: &Store, user_id: &str) -> Result<String> {
283+ let Some(target) = store.user_by_id(user_id).await? else {
284+ return Err(not_found().into());
285+ };
286+ if target.is_org() || is_ghost(&target) {
287+ return Err(not_found().into());
288+ }
289+ let facts = store.account_facts(user_id).await?;
290+ let suspension = store.suspension(user_id).await?;
291+ let passkeys = store.passkey_count(user_id).await?;
292+ Ok(format!(
293+ "{}|{}|{}|{}|{:?}|{:?}|{}",
294+ target.username,
295+ target.email.as_deref().unwrap_or(""),
296+ target.is_admin,
297+ target.created_at,
298+ facts,
299+ suspension,
300+ passkeys
301+ ))
302+}
303+
304+/// The account's change stream. Admins only; anyone else gets 404. The page follows the account's
305+/// facts: its last login, two-factor state, repo count and passkeys, and its suspension.
306+#[route(GET "/admin/users/{user_id}/events")]
307+async fn detail_events(cx: &Cx) -> Result<Response> {
308+ admin_only(cx).await?;
309+ let id = path_param_segment(cx, "user_id").to_owned();
310+ let store = app_context::<AppState>(cx).store.clone();
311+ let topic = Topic::AdminUser(id.clone());
312+ stream_changes(cx, crate::live::admin(), &[topic], move || {
313+ let store = store.clone();
314+ let id = id.clone();
315+ async move { account_fingerprint(&store, &id).await }
316+ })
317+ .await
318+}
319+
276 #[page("/admin/users/{user_id}")]320 #[page("/admin/users/{user_id}")]
277 async fn detail_page(cx: &Cx) -> Result<impl View> {321 async fn detail_page(cx: &Cx) -> Result<impl View> {
278 let viewer = admin_only(cx).await?;322 let viewer = admin_only(cx).await?;
crates/forge-web/src/pages/admin_users.rsmodified+37 -1
@@ -9,13 +9,15 @@ use topcoat::Result;
9 use topcoat::context::{Cx, app_context};9 use topcoat::context::{Cx, app_context};
10 use topcoat::router::content::Form;10 use topcoat::router::content::Form;
11 use topcoat::router::error::{forbidden, not_found, see_other};11 use topcoat::router::error::{forbidden, not_found, see_other};
12-use topcoat::router::{page, path_param_segment};12+use topcoat::router::response::Response;
13+use topcoat::router::{page, path_param_segment, route};
13 use topcoat::view::{View, component, view};14 use topcoat::view::{View, component, view};
14 15
15 use crate::audit::{self, Actor, Target};16 use crate::audit::{self, Actor, Target};
16 use crate::auth::{check_csrf, current_user, hash_password_async};17 use crate::auth::{check_csrf, current_user, hash_password_async};
17 use crate::i18n::admin::{self as g, K};18 use crate::i18n::admin::{self as g, K};
18 use crate::i18n::{self, Key, Lang};19 use crate::i18n::{self, Key, Lang};
20+use crate::live::{Topic, stream_changes};
19 use crate::pages::issues_list::stamp_unix;21 use crate::pages::issues_list::stamp_unix;
20 use crate::state::AppState;22 use crate::state::AppState;
21 use crate::views::{alert, enc, shell, user_facing_message};23 use crate::views::{alert, enc, shell, user_facing_message};
@@ -61,6 +63,7 @@ async fn users_view(
61 error: Option<String>,63 error: Option<String>,
62 ) -> Result<impl View> {64 ) -> Result<impl View> {
63 Ok(view! {65 Ok(view! {
66+ <div data-live="/admin/users/events">
64 <section class="page-head">67 <section class="page-head">
65 <h1>(g::t(lang, K::Users))</h1>68 <h1>(g::t(lang, K::Users))</h1>
66 </section>69 </section>
@@ -121,9 +124,42 @@ async fn users_view(
121 <button type="submit" class="primary">(g::t(lang, K::CreateUser))</button>124 <button type="submit" class="primary">(g::t(lang, K::CreateUser))</button>
122 </form>125 </form>
123 </section>126 </section>
127+ </div>
124 })128 })
125 }129 }
126 130
131+/// What the account list shows, as one string: a change to any of it is sent to the page.
132+async fn list_fingerprint(store: &Store) -> topcoat::Result<String> {
133+ let users = store.list_users().await?;
134+ Ok(users
135+ .iter()
136+ .map(|u| {
137+ format!(
138+ "{}|{}|{}|{}|{}|{}",
139+ u.id,
140+ u.username,
141+ u.email.as_deref().unwrap_or(""),
142+ u.is_admin,
143+ u.is_org(),
144+ u.created_at
145+ )
146+ })
147+ .collect::<Vec<_>>()
148+ .join("\n"))
149+}
150+
151+/// The account list's change stream. Admins only; anyone else gets 404.
152+#[route(GET "/admin/users/events")]
153+async fn users_events(cx: &Cx) -> Result<Response> {
154+ admin_only(cx).await?;
155+ let store = app_context::<AppState>(cx).store.clone();
156+ stream_changes(cx, crate::live::admin(), &[Topic::AdminUsers], move || {
157+ let store = store.clone();
158+ async move { list_fingerprint(&store).await }
159+ })
160+ .await
161+}
162+
127 #[page("/admin/users")]163 #[page("/admin/users")]
128 async fn users_page(cx: &Cx) -> Result<impl View> {164 async fn users_page(cx: &Cx) -> Result<impl View> {
129 let viewer = admin_only(cx).await?;165 let viewer = admin_only(cx).await?;
crates/forge-web/src/pages/audit_log.rsmodified+52 -2
@@ -6,12 +6,14 @@ use forge_core::tz::format_in_tz;
6 use forge_core::{AuditAction, AuditCursor, AuditEntry, AuditFilter, Store};6 use forge_core::{AuditAction, AuditCursor, AuditEntry, AuditFilter, Store};
7 use topcoat::Result;7 use topcoat::Result;
8 use topcoat::context::{Cx, app_context};8 use topcoat::context::{Cx, app_context};
9-use topcoat::router::{page, query_params};9+use topcoat::router::response::Response;
10+use topcoat::router::{page, query_params, route};
10 use topcoat::view::{View, component, view};11 use topcoat::view::{View, component, view};
11 12
12 use crate::auth::require_user;13 use crate::auth::require_user;
13 use crate::i18n::admin::{self as g, K};14 use crate::i18n::admin::{self as g, K};
14 use crate::i18n::{self, Lang};15 use crate::i18n::{self, Lang};
16+use crate::live::{Topic, stream_changes};
15 use crate::pages::admin_users::admin_only;17 use crate::pages::admin_users::admin_only;
16 use crate::pages::issues_list::{list_href, stamp_unix};18 use crate::pages::issues_list::{list_href, stamp_unix};
17 use crate::state::AppState;19 use crate::state::AppState;
@@ -131,6 +133,7 @@ async fn audit_table(lang: Lang, rows: Vec<RowView>, show_actor: bool) -> Result
131 #[component]133 #[component]
132 async fn admin_audit_view(134 async fn admin_audit_view(
133 lang: Lang,135 lang: Lang,
136+ live: String,
134 action: String,137 action: String,
135 actor: String,138 actor: String,
136 notice: Option<String>,139 notice: Option<String>,
@@ -138,6 +141,7 @@ async fn admin_audit_view(
138 older_href: Option<String>,141 older_href: Option<String>,
139 ) -> Result<impl View> {142 ) -> Result<impl View> {
140 Ok(view! {143 Ok(view! {
144+ <div data-live=(live.as_str())>
141 <section class="page-head">145 <section class="page-head">
142 <h1>(g::t(lang, K::AuditLog))</h1>146 <h1>(g::t(lang, K::AuditLog))</h1>
143 <p class="muted">(g::t(lang, K::AuditIntro))</p>147 <p class="muted">(g::t(lang, K::AuditIntro))</p>
@@ -173,6 +177,7 @@ async fn admin_audit_view(
173 }177 }
174 </nav>178 </nav>
175 </section>179 </section>
180+ </div>
176 })181 })
177 }182 }
178 183
@@ -243,12 +248,57 @@ async fn admin_audit_page(cx: &Cx) -> Result<impl View> {
243 ],248 ],
244 )249 )
245 });250 });
251+ let live = list_href(
252+ "/admin/audit/events",
253+ &[("action", action.as_str()), ("actor", actor.as_str())],
254+ );
246 let title = g::t(lang, K::AuditLog);255 let title = g::t(lang, K::AuditLog);
247 Ok(view! {256 Ok(view! {
248- shell(title: title, viewer: Some(&viewer), admin_audit_view(lang: lang, action: action, actor: actor, notice: notice, rows: rows, older_href: older_href))257+ 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))
249 })258 })
250 }259 }
251 260
261+/// The first page of entries the filter selects, as one string: the stream sends when it changes.
262+/// An unknown action or actor selects nothing, as on the page.
263+async fn first_page_fingerprint(store: &Store, action: &str, actor: &str) -> Result<String> {
264+ let mut filter = AuditFilter::default();
265+ if !action.is_empty() {
266+ match AuditAction::parse(action) {
267+ Some(known) => filter.action = Some(known),
268+ None => return Ok(String::new()),
269+ }
270+ }
271+ if !actor.is_empty() {
272+ match store.user_by_username(actor).await? {
273+ Some(user) => filter.actor_id = Some(user.id),
274+ None => return Ok(String::new()),
275+ }
276+ }
277+ let (entries, _) = fetch_page(store, &filter, None).await?;
278+ Ok(entries
279+ .iter()
280+ .map(|entry| entry.id.as_str())
281+ .collect::<Vec<_>>()
282+ .join(","))
283+}
284+
285+/// The audit log's change stream, for the filter in its query. Admins only.
286+#[route(GET "/admin/audit/events")]
287+async fn admin_audit_events(cx: &Cx) -> Result<Response> {
288+ admin_only(cx).await?;
289+ let query = query_params::<AuditQuery>(cx)?;
290+ let action = query.action.clone().unwrap_or_default().trim().to_owned();
291+ let actor = query.actor.clone().unwrap_or_default().trim().to_owned();
292+ let store = app_context::<AppState>(cx).store.clone();
293+ stream_changes(cx, crate::live::admin(), &[Topic::AdminAudit], move || {
294+ let store = store.clone();
295+ let action = action.clone();
296+ let actor = actor.clone();
297+ async move { first_page_fingerprint(&store, &action, &actor).await }
298+ })
299+ .await
300+}
301+
252 #[page("/settings/security/log")]302 #[page("/settings/security/log")]
253 async fn own_log_page(cx: &Cx) -> Result<impl View> {303 async fn own_log_page(cx: &Cx) -> Result<impl View> {
254 let viewer = require_user(cx).await?;304 let viewer = require_user(cx).await?;
crates/forge-web/src/pages/mod.rsmodified+2 -0
@@ -4,6 +4,8 @@
4 mod account_tools_tests;4 mod account_tools_tests;
5 pub mod admin_backups;5 pub mod admin_backups;
6 pub mod admin_health;6 pub mod admin_health;
7+#[cfg(test)]
8+mod admin_live_tests;
7 pub mod admin_mail;9 pub mod admin_mail;
8 pub mod admin_replication;10 pub mod admin_replication;
9 pub mod admin_runners;11 pub mod admin_runners;
crates/forge-web/src/replication/worker.rsmodified+12 -1
@@ -20,6 +20,7 @@ use super::{
20 remote_refs_checksum, sh_quote, snapshot_stamp, wiki_subject, wiki_subject_repo,20 remote_refs_checksum, sh_quote, snapshot_stamp, wiki_subject, wiki_subject_repo,
21 };21 };
22 use crate::backup::healthcheck;22 use crate::backup::healthcheck;
23+use crate::live::Topic;
23 use crate::state::AppState;24 use crate::state::AppState;
24 25
25 /// Longest the worker sleeps with nothing due. Guards against a missed wake, not polling.26 /// 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) {
145 146
146 /// Records an outcome for `subject` and passes the error on. `refs` is the checksum to store on147 /// Records an outcome for `subject` and passes the error on. `refs` is the checksum to store on
147 /// success (repos only).148 /// success (repos only).
148-async fn record(149+pub(crate) async fn record(
149 store: &Store,150 store: &Store,
150 subject: &str,151 subject: &str,
151 result: Result<Option<String>, String>,152 result: Result<Option<String>, String>,
@@ -155,6 +156,7 @@ async fn record(
155 if let Err(e) = store.record_replication_ok(subject, refs.as_deref()).await {156 if let Err(e) = store.record_replication_ok(subject, refs.as_deref()).await {
156 tracing::error!(error = %e, subject, "replication: could not record success");157 tracing::error!(error = %e, subject, "replication: could not record success");
157 }158 }
159+ status_changed();
158 Ok(())160 Ok(())
159 }161 }
160 Err(e) => {162 Err(e) => {
@@ -162,11 +164,19 @@ async fn record(
162 if let Err(db) = store.record_replication_error(subject, &e).await {164 if let Err(db) = store.record_replication_error(subject, &e).await {
163 tracing::error!(error = %db, subject, "replication: could not record failure");165 tracing::error!(error = %db, subject, "replication: could not record failure");
164 }166 }
167+ status_changed();
165 Err(e)168 Err(e)
166 }169 }
167 }170 }
168 }171 }
169 172
173+/// A copy's status changed: the replication page and the health page of the admin area follow it.
174+fn status_changed() {
175+ let hub = crate::live::admin();
176+ hub.bump(&Topic::AdminReplication);
177+ hub.bump(&Topic::AdminHealth);
178+}
179+
170 /// Pushes one repo to the standby and checks that its refs match. A mismatch triggers one180 /// Pushes one repo to the standby and checks that its refs match. A mismatch triggers one
171 /// re-push; a second mismatch is an error. Records the outcome for the repo.181 /// re-push; a second mismatch is an error. Records the outcome for the repo.
172 ///182 ///
@@ -378,6 +388,7 @@ pub async fn reconcile_once<T: StandbyTransport>(ctx: &Ctx<T>) -> ReconcileRepor
378 if let Err(e) = ctx.store.delete_replication_status(&status.subject).await {388 if let Err(e) = ctx.store.delete_replication_status(&status.subject).await {
379 report.failures.push(format!("{}: {e}", status.subject));389 report.failures.push(format!("{}: {e}", status.subject));
380 }390 }
391+ status_changed();
381 }392 }
382 Err(e) => report393 Err(e) => report
383 .failures394 .failures
docs/architecture.mdmodified+7 -1
@@ -266,10 +266,16 @@ Pages update without a reload. A write that changes what a page shows calls `Liv
266 | Org teams `/org/{org}/teams` | `/org/{org}/teams/events` | the org (teams and their coverage) |266 | Org teams `/org/{org}/teams` | `/org/{org}/teams/events` | the org (teams and their coverage) |
267 | Org team `/org/{org}/teams/{team}` | `/org/{org}/teams/{team}/events` | the org (members, linked repos) and each linked repo (name, visibility) |267 | Org team `/org/{org}/teams/{team}` | `/org/{org}/teams/{team}/events` | the org (members, linked repos) and each linked repo (name, visibility) |
268 | Org settings `/org/{org}/settings` | `/org/{org}/settings/events` | the org (description, default repo role, member repo creation) |268 | Org settings `/org/{org}/settings` | `/org/{org}/settings/events` | the org (description, default repo role, member repo creation) |
269+| 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 |
270+| Admin audit `/admin/audit` | `/admin/audit/events`, with the filter in the query | the first page of the filter |
271+| Admin backups `/admin/backups` | `/admin/backups/events` | the run in progress and the last 20 runs |
272+| Admin replication `/admin/replication` | `/admin/replication/events` | each copy's status and the database snapshot |
273+| 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 |
274+| 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 |
269 275
270 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.276 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.
271 277
272-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.278+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.
273 279
274 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.280 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.
275 281