forge
Explore
Log in

Don't you dare go Hollow

Admin alerts for runners, backups, disk, killed jobs, self-update and replication

Browse files at this commit

baf3aeaa2716a72640925eca183f215904102397Ahmet Kaan GümüşParent: 8093285
  • feat
    • admin alerts for runners, backups, disk, killed jobs, self-update and replication
Show full message
✨ feat: admin alerts for runners, backups, disk, killed jobs, self-update and replication
Cargo.lockmodified+1 -0
@@ -2101,6 +2101,7 @@ dependencies = [
2101 "jiff",2101 "jiff",
2102 "lettre",2102 "lettre",
2103 "multer",2103 "multer",
2104+ "nix 0.31.3",
2104 "object_store",2105 "object_store",
2105 "rand 0.10.3",2106 "rand 0.10.3",
2106 "reqwest",2107 "reqwest",
config/forge.example.tomlmodified+21 -0
@@ -164,3 +164,24 @@ trusted_proxies = []
164 # job = "build"164 # job = "build"
165 # The artifact name produced by job. A single file. CI flattens paths, so dist/forge is stored as dist_forge.165 # The artifact name produced by job. A single file. CI flattens paths, so dist/forge is stored as dist_forge.
166 # artifact = "dist_forge"166 # artifact = "dist_forge"
167+
168+# Admin alerts. The site admins hear about trouble before it breaks: a silent CI runner, a failed
169+# or overdue backup, low disk space, a CI job killed for memory, a self-update, a lagging standby.
170+# Each is told once until it resolves. Delivered as an inbox row, an email, and a banner on /admin/health.
171+# All of these can also be changed live on /admin/server.
172+# [alerts]
173+# enabled = true
174+# Also email admins with a verified address.
175+# email = true
176+# Minutes without a heartbeat before a runner counts as offline.
177+# runner_offline_minutes = 10
178+# Alert under this percent of free space in data_dir, or under disk_free_gib GiB (0 turns that off).
179+# disk_free_percent = 10
180+# disk_free_gib = 0
181+# Per-kind switches.
182+# on_runner_offline = true
183+# on_backup = true
184+# on_disk = true
185+# on_ci_killed = true
186+# on_self_update = true
187+# on_replication = true
crates/forge-core/migrations/0059_admin_alerts.sqladded+25 -0
@@ -0,0 +1,25 @@
1+-- Admin alerts: one row per condition (`key`) that is active, resolved or a one-shot event, and
2+-- one inbox row per site admin and message. An alert is raised once until it resolves.
3+CREATE TABLE admin_alerts (
4+ key TEXT PRIMARY KEY,
5+ kind TEXT NOT NULL,
6+ subject TEXT NOT NULL DEFAULT '',
7+ detail TEXT NOT NULL DEFAULT '',
8+ state TEXT NOT NULL,
9+ raised_at TEXT NOT NULL,
10+ resolved_at TEXT NULL,
11+ updated_at TEXT NOT NULL
12+);
13+CREATE INDEX admin_alerts_state ON admin_alerts (state, raised_at);
14+CREATE TABLE admin_notifications (
15+ id TEXT PRIMARY KEY,
16+ user_id TEXT NOT NULL REFERENCES users(id),
17+ alert_key TEXT NOT NULL,
18+ kind TEXT NOT NULL,
19+ subject TEXT NOT NULL DEFAULT '',
20+ detail TEXT NOT NULL DEFAULT '',
21+ resolved INTEGER NOT NULL DEFAULT 0,
22+ unread INTEGER NOT NULL DEFAULT 1,
23+ updated_at TEXT NOT NULL
24+);
25+CREATE INDEX admin_notifications_inbox ON admin_notifications (user_id, unread, updated_at);
crates/forge-core/src/alerts.rsadded+180 -0
@@ -0,0 +1,180 @@
1+//! Admin alerts: the kinds of trouble the forge tells its admins about, and the pure rules that
2+//! decide when to. Delivery and state live in `store::admin_alerts` and forge-web's `alerts`.
3+
4+/// What an alert is about. Each kind has its own on/off setting.
5+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6+pub enum AlertKind {
7+ /// A CI runner stopped checking in.
8+ RunnerOffline,
9+ /// A backup, its verification or an fsck failed, or no backup succeeded in time.
10+ Backup,
11+ /// The data directory is nearly full.
12+ Disk,
13+ /// A CI job was killed by SIGKILL or the OOM killer.
14+ CiKilled,
15+ /// A self-update deployed or failed, and the server restarted.
16+ SelfUpdate,
17+ /// The standby is failing or lagging.
18+ Replication,
19+}
20+
21+impl AlertKind {
22+ pub const ALL: [AlertKind; 6] = [
23+ AlertKind::RunnerOffline,
24+ AlertKind::Backup,
25+ AlertKind::Disk,
26+ AlertKind::CiKilled,
27+ AlertKind::SelfUpdate,
28+ AlertKind::Replication,
29+ ];
30+
31+ pub fn as_str(self) -> &'static str {
32+ match self {
33+ AlertKind::RunnerOffline => "runner_offline",
34+ AlertKind::Backup => "backup",
35+ AlertKind::Disk => "disk",
36+ AlertKind::CiKilled => "ci_killed",
37+ AlertKind::SelfUpdate => "self_update",
38+ AlertKind::Replication => "replication",
39+ }
40+ }
41+
42+ pub fn parse(s: &str) -> Option<AlertKind> {
43+ AlertKind::ALL.into_iter().find(|k| k.as_str() == s)
44+ }
45+}
46+
47+/// Whether a job's result looks like the process was killed: SIGKILL (`signal: 9`, `SIGKILL`,
48+/// `Killed`), the shell's `128 + 9` exit code, or an out-of-memory message.
49+pub fn is_kill_signature(exit_code: Option<i64>, message: Option<&str>) -> bool {
50+ if matches!(exit_code, Some(137) | Some(-9)) {
51+ return true;
52+ }
53+ let Some(message) = message else {
54+ return false;
55+ };
56+ let text = message.to_ascii_lowercase();
57+ if text.contains("sigkill")
58+ || text.contains("out of memory")
59+ || text.contains("oom-kill")
60+ || text.contains("oom kill")
61+ || text.contains("oom_kill")
62+ || text.contains("oomkill")
63+ || text.contains("exit code 137")
64+ || text.contains("exit status 137")
65+ {
66+ return true;
67+ }
68+ // "signal: 9", "signal 9", "signal=9", "killed by signal 9". A longer number such as 90 is
69+ // not a match.
70+ let mut rest = text.as_str();
71+ while let Some(at) = rest.find("signal") {
72+ rest = &rest[at + "signal".len()..];
73+ let digits: String = rest
74+ .trim_start_matches([':', '=', ' '])
75+ .chars()
76+ .take_while(char::is_ascii_digit)
77+ .collect();
78+ if digits == "9" {
79+ return true;
80+ }
81+ }
82+ text.trim() == "killed"
83+}
84+
85+/// Free space as a percentage of the total, rounded down. `None` for an empty filesystem.
86+pub fn free_percent(total: u64, available: u64) -> Option<u64> {
87+ (u128::from(available) * 100)
88+ .checked_div(u128::from(total))
89+ .map(|p| u64::try_from(p).unwrap_or(100))
90+}
91+
92+/// Whether free space is below the configured floor: under `min_percent` of the total, or under
93+/// `min_gib` GiB when that is non-zero.
94+pub fn disk_is_low(total: u64, available: u64, min_percent: u64, min_gib: u64) -> bool {
95+ let low_percent = free_percent(total, available).is_some_and(|p| p < min_percent);
96+ let low_gib = min_gib > 0 && available < min_gib.saturating_mul(1 << 30);
97+ low_percent || low_gib
98+}
99+
100+/// Whether the newest successful backup is older than twice the schedule interval. A forge that
101+/// never made one counts from `since_unix`, when the alerting began.
102+pub fn backup_overdue(
103+ now_unix: i64,
104+ last_ok_unix: Option<i64>,
105+ since_unix: i64,
106+ interval_hours: u64,
107+) -> bool {
108+ let limit =
109+ i64::try_from(interval_hours.saturating_mul(3600).saturating_mul(2)).unwrap_or(i64::MAX);
110+ let basis = last_ok_unix.unwrap_or(since_unix);
111+ now_unix.saturating_sub(basis) > limit
112+}
113+
114+/// Whether a runner has been silent too long. `last_seen_unix` is `None` for one that never
115+/// checked in, which is not offline: it was never online.
116+pub fn runner_is_offline(now_unix: i64, last_seen_unix: Option<i64>, minutes: u64) -> bool {
117+ let limit = i64::try_from(minutes.saturating_mul(60)).unwrap_or(i64::MAX);
118+ last_seen_unix.is_some_and(|seen| now_unix.saturating_sub(seen) > limit)
119+}
120+
121+#[cfg(test)]
122+mod tests {
123+ use super::*;
124+
125+ #[test]
126+ fn kill_signatures_are_recognised() {
127+ assert!(is_kill_signature(Some(137), None));
128+ assert!(is_kill_signature(Some(-9), None));
129+ assert!(is_kill_signature(
130+ None,
131+ Some("process exited: signal: 9 (killed)")
132+ ));
133+ assert!(is_kill_signature(None, Some("terminated by SIGKILL")));
134+ assert!(is_kill_signature(None, Some("fatal: out of memory")));
135+ assert!(is_kill_signature(None, Some("Killed")));
136+ assert!(is_kill_signature(None, Some("job died with signal 9")));
137+ assert!(is_kill_signature(None, Some("exit status 137")));
138+ }
139+
140+ #[test]
141+ fn other_failures_are_not_kills() {
142+ assert!(!is_kill_signature(Some(1), None));
143+ assert!(!is_kill_signature(Some(0), Some("ok")));
144+ assert!(!is_kill_signature(
145+ None,
146+ Some("job was terminated by a signal")
147+ ));
148+ assert!(!is_kill_signature(None, Some("signal: 90")));
149+ assert!(!is_kill_signature(None, Some("signal 15 (terminated)")));
150+ assert!(!is_kill_signature(None, Some("a broom closet")));
151+ assert!(!is_kill_signature(None, None));
152+ }
153+
154+ #[test]
155+ fn disk_thresholds() {
156+ let gib = 1u64 << 30;
157+ assert_eq!(free_percent(100 * gib, 5 * gib), Some(5));
158+ assert_eq!(free_percent(0, 0), None);
159+ assert!(disk_is_low(100 * gib, 5 * gib, 10, 0));
160+ assert!(!disk_is_low(100 * gib, 10 * gib, 10, 0));
161+ assert!(disk_is_low(1000 * gib, 50 * gib, 1, 60));
162+ assert!(!disk_is_low(1000 * gib, 70 * gib, 1, 60));
163+ }
164+
165+ #[test]
166+ fn backup_overdue_after_twice_the_interval() {
167+ let h = 3600;
168+ assert!(!backup_overdue(47 * h, Some(0), 0, 24));
169+ assert!(backup_overdue(49 * h, Some(0), 0, 24));
170+ assert!(backup_overdue(49 * h, None, 0, 24));
171+ assert!(!backup_overdue(49 * h, None, 10 * h, 24));
172+ }
173+
174+ #[test]
175+ fn runner_offline_uses_the_threshold() {
176+ assert!(!runner_is_offline(1000, Some(500), 10));
177+ assert!(runner_is_offline(1000, Some(300), 10));
178+ assert!(!runner_is_offline(1000, None, 10));
179+ }
180+}
crates/forge-core/src/config.rsmodified+60 -0
@@ -108,6 +108,66 @@ pub struct Config {
108 /// Site announcement shown under every page header, from the `[banner]` section.108 /// Site announcement shown under every page header, from the `[banner]` section.
109 #[serde(default)]109 #[serde(default)]
110 pub banner: BannerConfig,110 pub banner: BannerConfig,
111+ /// Alerts to site admins, from the `[alerts]` section.
112+ #[serde(default)]
113+ pub alerts: AlertsConfig,
114+}
115+
116+/// Admin alerts: what the forge tells the site admins about before something breaks.
117+#[derive(Debug, Clone, Deserialize)]
118+#[serde(deny_unknown_fields, default)]
119+pub struct AlertsConfig {
120+ /// Master switch. Off sends nothing and raises nothing.
121+ pub enabled: bool,
122+ /// Also email the admins, when they have a verified address and mail is set up.
123+ pub email: bool,
124+ /// Minutes without a heartbeat before a runner counts as offline.
125+ pub runner_offline_minutes: u64,
126+ /// Alert when the data directory has less than this percent free.
127+ pub disk_free_percent: u64,
128+ /// Alert when the data directory has less than this many GiB free. 0 turns this check off.
129+ pub disk_free_gib: u64,
130+ /// Per-kind switches.
131+ pub on_runner_offline: bool,
132+ pub on_backup: bool,
133+ pub on_disk: bool,
134+ pub on_ci_killed: bool,
135+ pub on_self_update: bool,
136+ pub on_replication: bool,
137+}
138+
139+impl Default for AlertsConfig {
140+ fn default() -> Self {
141+ AlertsConfig {
142+ enabled: true,
143+ email: true,
144+ runner_offline_minutes: 10,
145+ disk_free_percent: 10,
146+ disk_free_gib: 0,
147+ on_runner_offline: true,
148+ on_backup: true,
149+ on_disk: true,
150+ on_ci_killed: true,
151+ on_self_update: true,
152+ on_replication: true,
153+ }
154+ }
155+}
156+
157+impl AlertsConfig {
158+ /// Whether alerts of `kind` are raised: the master switch and the kind's own switch.
159+ pub fn kind_enabled(&self, kind: crate::alerts::AlertKind) -> bool {
160+ use crate::alerts::AlertKind as K;
161+ self.enabled
162+ && match kind {
163+ K::RunnerOffline => self.on_runner_offline,
164+ K::Backup => self.on_backup,
165+ K::Disk => self.on_disk,
166+ K::CiKilled => self.on_ci_killed,
167+ K::SelfUpdate => self.on_self_update,
168+ K::Replication => self.on_replication,
169+ }
170+ }
111 }171 }
112 172
113 /// Site announcement banner. An empty `message` shows nothing.173 /// Site announcement banner. An empty `message` shows nothing.
crates/forge-core/src/lib.rsmodified+1 -0
@@ -1,6 +1,7 @@
1 //! Domain types, storage, configuration and security primitives for forge.1 //! Domain types, storage, configuration and security primitives for forge.
2 2
3 pub mod advisories;3 pub mod advisories;
4+pub mod alerts;
4 pub mod audit;5 pub mod audit;
5 pub mod authz;6 pub mod authz;
6 pub mod avatar;7 pub mod avatar;
crates/forge-core/src/server_settings.rsmodified+115 -2
@@ -39,15 +39,17 @@ pub enum Group {
39 Storage,39 Storage,
40 Backups,40 Backups,
41 Integrations,41 Integrations,
42+ Alerts,
42 }43 }
43 44
44 impl Group {45 impl Group {
45- pub const ALL: [Group; 5] = [46+ pub const ALL: [Group; 6] = [
46 Group::General,47 Group::General,
47 Group::Limits,48 Group::Limits,
48 Group::Storage,49 Group::Storage,
49 Group::Backups,50 Group::Backups,
50 Group::Integrations,51 Group::Integrations,
52+ Group::Alerts,
51 ];53 ];
52 54
53 pub fn slug(self) -> &'static str {55 pub fn slug(self) -> &'static str {
@@ -57,6 +59,7 @@ impl Group {
57 Group::Storage => "storage",59 Group::Storage => "storage",
58 Group::Backups => "backups",60 Group::Backups => "backups",
59 Group::Integrations => "integrations",61 Group::Integrations => "integrations",
62+ Group::Alerts => "alerts",
60 }63 }
61 }64 }
62 65
@@ -117,7 +120,7 @@ const fn f(
117 }120 }
118 }121 }
119 122
120-use Group::{Backups, General, Integrations, Limits, Storage};123+use Group::{Alerts, Backups, General, Integrations, Limits, Storage};
121 use Kind::{Live as L, ReadOnly as R, Restart as X};124 use Kind::{Live as L, ReadOnly as R, Restart as X};
122 125
123 const REGISTRATION: &[&str] = &["closed", "invite", "open"];126 const REGISTRATION: &[&str] = &["closed", "invite", "open"];
@@ -606,6 +609,94 @@ pub static FIELDS: &[Field] = &[
606 "Self-update artifact",609 "Self-update artifact",
607 "",610 "",
608 ),611 ),
612+ f(
613+ "alerts.enabled",
614+ Alerts,
615+ L,
616+ Ty::Bool,
617+ "Admin alerts",
618+ "Master switch. Off raises and sends nothing.",
619+ ),
620+ f(
621+ "alerts.email",
622+ Alerts,
623+ L,
624+ Ty::Bool,
625+ "Email alerts",
626+ "Also email the admins who have a verified address.",
627+ ),
628+ f(
629+ "alerts.runner_offline_minutes",
630+ Alerts,
631+ L,
632+ Ty::Uint(1, 1_440),
633+ "Runner offline after (minutes)",
634+ "A runner with no heartbeat for this long raises an alert.",
635+ ),
636+ f(
637+ "alerts.disk_free_percent",
638+ Alerts,
639+ L,
640+ Ty::Uint(1, 90),
641+ "Low disk space (percent free)",
642+ "Alert when the data directory has less than this free.",
643+ ),
644+ f(
645+ "alerts.disk_free_gib",
646+ Alerts,
647+ L,
648+ Ty::Uint(0, 100_000),
649+ "Low disk space (GiB free)",
650+ "Also alert under this many GiB. 0 turns this check off.",
651+ ),
652+ f(
653+ "alerts.on_runner_offline",
654+ Alerts,
655+ L,
656+ Ty::Bool,
657+ "Runner offline alerts",
658+ "",
659+ ),
660+ f(
661+ "alerts.on_backup",
662+ Alerts,
663+ L,
664+ Ty::Bool,
665+ "Backup alerts",
666+ "Failed, unverified or overdue backups, and failed fsck runs.",
667+ ),
668+ f(
669+ "alerts.on_disk",
670+ Alerts,
671+ L,
672+ Ty::Bool,
673+ "Disk space alerts",
674+ "",
675+ ),
676+ f(
677+ "alerts.on_ci_killed",
678+ Alerts,
679+ L,
680+ Ty::Bool,
681+ "Killed CI job alerts",
682+ "Jobs killed by SIGKILL or the OOM killer, once per run.",
683+ ),
684+ f(
685+ "alerts.on_self_update",
686+ Alerts,
687+ L,
688+ Ty::Bool,
689+ "Self-update alerts",
690+ "Deployed, failed, and server restarted.",
691+ ),
692+ f(
693+ "alerts.on_replication",
694+ Alerts,
695+ L,
696+ Ty::Bool,
697+ "Replication alerts",
698+ "Standby failing or lagging.",
699+ ),
609 ];700 ];
610 701
611 /// The field for a dotted key.702 /// The field for a dotted key.
@@ -751,6 +842,17 @@ pub fn get(cfg: &Config, key: &str) -> String {
751 "banner.message" => cfg.banner.message.clone(),842 "banner.message" => cfg.banner.message.clone(),
752 "banner.level" => cfg.banner.level.clone(),843 "banner.level" => cfg.banner.level.clone(),
753 "banner.expires" => cfg.banner.expires.clone(),844 "banner.expires" => cfg.banner.expires.clone(),
845+ "alerts.enabled" => cfg.alerts.enabled.to_string(),
846+ "alerts.email" => cfg.alerts.email.to_string(),
847+ "alerts.runner_offline_minutes" => cfg.alerts.runner_offline_minutes.to_string(),
848+ "alerts.disk_free_percent" => cfg.alerts.disk_free_percent.to_string(),
849+ "alerts.disk_free_gib" => cfg.alerts.disk_free_gib.to_string(),
850+ "alerts.on_runner_offline" => cfg.alerts.on_runner_offline.to_string(),
851+ "alerts.on_backup" => cfg.alerts.on_backup.to_string(),
852+ "alerts.on_disk" => cfg.alerts.on_disk.to_string(),
853+ "alerts.on_ci_killed" => cfg.alerts.on_ci_killed.to_string(),
854+ "alerts.on_self_update" => cfg.alerts.on_self_update.to_string(),
855+ "alerts.on_replication" => cfg.alerts.on_replication.to_string(),
754 "base_url" => cfg.base_url.clone(),856 "base_url" => cfg.base_url.clone(),
755 "user_content_base_url" => cfg.user_content_base_url.clone(),857 "user_content_base_url" => cfg.user_content_base_url.clone(),
756 "ssh_public_host" => cfg.ssh_public_host.clone(),858 "ssh_public_host" => cfg.ssh_public_host.clone(),
@@ -857,6 +959,17 @@ pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> {
857 "banner.message" => cfg.banner.message = s(),959 "banner.message" => cfg.banner.message = s(),
858 "banner.level" => cfg.banner.level = s(),960 "banner.level" => cfg.banner.level = s(),
859 "banner.expires" => cfg.banner.expires = s(),961 "banner.expires" => cfg.banner.expires = s(),
962+ "alerts.enabled" => cfg.alerts.enabled = b(v),
963+ "alerts.email" => cfg.alerts.email = b(v),
964+ "alerts.runner_offline_minutes" => cfg.alerts.runner_offline_minutes = n(v),
965+ "alerts.disk_free_percent" => cfg.alerts.disk_free_percent = n(v),
966+ "alerts.disk_free_gib" => cfg.alerts.disk_free_gib = n(v),
967+ "alerts.on_runner_offline" => cfg.alerts.on_runner_offline = b(v),
968+ "alerts.on_backup" => cfg.alerts.on_backup = b(v),
969+ "alerts.on_disk" => cfg.alerts.on_disk = b(v),
970+ "alerts.on_ci_killed" => cfg.alerts.on_ci_killed = b(v),
971+ "alerts.on_self_update" => cfg.alerts.on_self_update = b(v),
972+ "alerts.on_replication" => cfg.alerts.on_replication = b(v),
860 "base_url" => cfg.base_url = s(),973 "base_url" => cfg.base_url = s(),
861 "user_content_base_url" => cfg.user_content_base_url = s(),974 "user_content_base_url" => cfg.user_content_base_url = s(),
862 "ssh_public_host" => cfg.ssh_public_host = s(),975 "ssh_public_host" => cfg.ssh_public_host = s(),
crates/forge-core/src/store/admin_alerts.rsadded+372 -0
@@ -0,0 +1,372 @@
1+//! Admin alerts (migration 0058): the state of each alert condition, and the admins' inbox rows.
2+//!
3+//! A condition has a stable `key`. [`Store::raise_alert`] returns true only on the change from
4+//! "not active" to "active", and [`Store::resolve_alert`] only on "active" to "resolved", so a
5+//! condition that stays true is told once, and its end is told once.
6+
7+use turso::{Row, Value};
8+
9+use super::issues::finish;
10+use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, new_id};
11+use crate::error::Result;
12+use crate::time::now_stamp;
13+
14+/// A condition that is active now. Resolved alerts and one-shot events are not listed.
15+#[derive(Debug, Clone, PartialEq, Eq)]
16+pub struct AdminAlert {
17+ pub key: String,
18+ pub kind: String,
19+ pub subject: String,
20+ pub detail: String,
21+ pub raised_at: String,
22+}
23+
24+/// One admin's inbox row: a raised alert, or the message that it resolved.
25+#[derive(Debug, Clone, PartialEq, Eq)]
26+pub struct AdminNotice {
27+ pub id: String,
28+ pub alert_key: String,
29+ pub kind: String,
30+ pub subject: String,
31+ pub detail: String,
32+ pub resolved: bool,
33+ pub unread: bool,
34+ pub updated_at: String,
35+}
36+
37+const NOTICE_COLS: &str = "id, alert_key, kind, subject, detail, resolved, unread, updated_at";
38+
39+fn map_alert(row: &Row) -> Result<AdminAlert> {
40+ Ok(AdminAlert {
41+ key: col_text(row, 0)?,
42+ kind: col_text(row, 1)?,
43+ subject: col_text(row, 2)?,
44+ detail: col_text(row, 3)?,
45+ raised_at: col_text(row, 4)?,
46+ })
47+}
48+
49+fn map_notice(row: &Row) -> Result<AdminNotice> {
50+ Ok(AdminNotice {
51+ id: col_text(row, 0)?,
52+ alert_key: col_text(row, 1)?,
53+ kind: col_text(row, 2)?,
54+ subject: col_text(row, 3)?,
55+ detail: col_text(row, 4)?,
56+ resolved: col_int(row, 5)? != 0,
57+ unread: col_int(row, 6)? != 0,
58+ updated_at: col_text(row, 7)?,
59+ })
60+}
61+
62+fn text(s: &str) -> Value {
63+ Value::Text(s.to_owned())
64+}
65+
66+impl Store {
67+ /// Marks the condition `key` active. Returns true when it was not active before, which is
68+ /// when the admins are told. An alert already active keeps its first `raised_at`; only its
69+ /// detail is refreshed.
70+ pub async fn raise_alert(
71+ &self,
72+ key: &str,
73+ kind: &str,
74+ subject: &str,
75+ detail: &str,
76+ ) -> Result<bool> {
77+ let now = now_stamp();
78+ let conn = self.inner.conn.lock().await;
79+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
80+ let outcome: Result<bool> = async {
81+ let state = fetch_opt(
82+ &tx,
83+ "SELECT state FROM admin_alerts WHERE key = ?1",
84+ (key.to_owned(),),
85+ |row| col_text(row, 0),
86+ )
87+ .await?;
88+ match state.as_deref() {
89+ Some("active") => {
90+ tx.execute(
91+ "UPDATE admin_alerts SET detail = ?2, updated_at = ?3 WHERE key = ?1",
92+ vec![text(key), text(detail), text(&now)],
93+ )
94+ .await
95+ .map_err(db_err)?;
96+ Ok(false)
97+ }
98+ _ => {
99+ tx.execute(
100+ "INSERT INTO admin_alerts (key, kind, subject, detail, state, raised_at, \
101+ resolved_at, updated_at) VALUES (?1, ?2, ?3, ?4, 'active', ?5, NULL, ?5) \
102+ ON CONFLICT(key) DO UPDATE SET kind = excluded.kind, \
103+ subject = excluded.subject, detail = excluded.detail, state = 'active', \
104+ raised_at = excluded.raised_at, resolved_at = NULL, \
105+ updated_at = excluded.updated_at",
106+ vec![
107+ text(key),
108+ text(kind),
109+ text(subject),
110+ text(detail),
111+ text(&now),
112+ ],
113+ )
114+ .await
115+ .map_err(db_err)?;
116+ Ok(true)
117+ }
118+ }
119+ }
120+ .await;
121+ finish(tx, outcome).await
122+ }
123+
124+ /// Marks the condition `key` resolved. Returns the alert when it was active, so the caller
125+ /// can say it is over, and `None` when there was nothing to resolve.
126+ pub async fn resolve_alert(&self, key: &str) -> Result<Option<AdminAlert>> {
127+ let now = now_stamp();
128+ let conn = self.inner.conn.lock().await;
129+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
130+ let outcome: Result<Option<AdminAlert>> = async {
131+ let alert = fetch_opt(
132+ &tx,
133+ "SELECT key, kind, subject, detail, raised_at FROM admin_alerts \
134+ WHERE key = ?1 AND state = 'active'",
135+ (key.to_owned(),),
136+ map_alert,
137+ )
138+ .await?;
139+ if alert.is_some() {
140+ tx.execute(
141+ "UPDATE admin_alerts SET state = 'resolved', resolved_at = ?2, \
142+ updated_at = ?2 WHERE key = ?1",
143+ vec![text(key), text(&now)],
144+ )
145+ .await
146+ .map_err(db_err)?;
147+ }
148+ Ok(alert)
149+ }
150+ .await;
151+ finish(tx, outcome).await
152+ }
153+
154+ /// Records a one-shot event under `key`. Returns true the first time only. An event is never
155+ /// active, so it is not in [`Store::active_alerts`].
156+ pub async fn record_alert_event(
157+ &self,
158+ key: &str,
159+ kind: &str,
160+ subject: &str,
161+ detail: &str,
162+ ) -> Result<bool> {
163+ let now = now_stamp();
164+ let conn = self.inner.conn.lock().await;
165+ let changed = conn
166+ .execute(
167+ "INSERT OR IGNORE INTO admin_alerts (key, kind, subject, detail, state, \
168+ raised_at, resolved_at, updated_at) VALUES (?1, ?2, ?3, ?4, 'event', ?5, NULL, ?5)",
169+ vec![
170+ text(key),
171+ text(kind),
172+ text(subject),
173+ text(detail),
174+ text(&now),
175+ ],
176+ )
177+ .await
178+ .map_err(db_err)?;
179+ Ok(changed > 0)
180+ }
181+
182+ /// Every alert that is active now, oldest first.
183+ pub async fn active_alerts(&self) -> Result<Vec<AdminAlert>> {
184+ let conn = self.read_conn().await;
185+ fetch_all(
186+ &conn,
187+ "SELECT key, kind, subject, detail, raised_at FROM admin_alerts \
188+ WHERE state = 'active' ORDER BY raised_at, key",
189+ (),
190+ map_alert,
191+ )
192+ .await
193+ }
194+
195+ /// The keys of the active alerts of one kind.
196+ pub async fn active_alert_keys(&self, kind: &str) -> Result<Vec<String>> {
197+ let conn = self.read_conn().await;
198+ fetch_all(
199+ &conn,
200+ "SELECT key FROM admin_alerts WHERE state = 'active' AND kind = ?1",
201+ (kind.to_owned(),),
202+ |row| col_text(row, 0),
203+ )
204+ .await
205+ }
206+
207+ /// Adds an inbox row for `user_id`.
208+ pub async fn add_admin_notice(
209+ &self,
210+ user_id: &str,
211+ alert_key: &str,
212+ kind: &str,
213+ subject: &str,
214+ detail: &str,
215+ resolved: bool,
216+ ) -> Result<()> {
217+ let conn = self.inner.conn.lock().await;
218+ conn.execute(
219+ "INSERT INTO admin_notifications (id, user_id, alert_key, kind, subject, detail, \
220+ resolved, unread, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, 1, ?8)",
221+ vec![
222+ text(&new_id()),
223+ text(user_id),
224+ text(alert_key),
225+ text(kind),
226+ text(subject),
227+ text(detail),
228+ Value::Integer(i64::from(resolved)),
229+ text(&now_stamp()),
230+ ],
231+ )
232+ .await
233+ .map_err(db_err)?;
234+ Ok(())
235+ }
236+
237+ /// The user's alert inbox rows, newest first.
238+ pub async fn list_admin_notices(
239+ &self,
240+ user_id: &str,
241+ unread_only: bool,
242+ before: Option<&str>,
243+ limit: u32,
244+ ) -> Result<Vec<AdminNotice>> {
245+ let mut sql = format!("SELECT {NOTICE_COLS} FROM admin_notifications WHERE user_id = ?");
246+ let mut params = vec![text(user_id)];
247+ if unread_only {
248+ sql.push_str(" AND unread = 1");
249+ }
250+ if let Some(stamp) = before {
251+ sql.push_str(" AND updated_at < ?");
252+ params.push(text(stamp));
253+ }
254+ sql.push_str(" ORDER BY updated_at DESC, id DESC LIMIT ?");
255+ params.push(Value::Integer(i64::from(limit.clamp(1, 200))));
256+ let conn = self.read_conn().await;
257+ fetch_all(&conn, &sql, params, map_notice).await
258+ }
259+
260+ /// Marks one of the user's alert rows read. Another user's row changes nothing.
261+ pub async fn mark_admin_notice_read(&self, user_id: &str, id: &str) -> Result<()> {
262+ let conn = self.inner.conn.lock().await;
263+ conn.execute(
264+ "UPDATE admin_notifications SET unread = 0 WHERE id = ?1 AND user_id = ?2",
265+ (id.to_owned(), user_id.to_owned()),
266+ )
267+ .await
268+ .map_err(db_err)?;
269+ Ok(())
270+ }
271+
272+ /// Marks all of the user's alert rows read.
273+ pub async fn mark_all_admin_notices_read(&self, user_id: &str) -> Result<()> {
274+ let conn = self.inner.conn.lock().await;
275+ conn.execute(
276+ "UPDATE admin_notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1",
277+ (user_id.to_owned(),),
278+ )
279+ .await
280+ .map_err(db_err)?;
281+ Ok(())
282+ }
283+
284+ /// Deletes resolved and event rows and read inbox rows older than `before`, so the tables do
285+ /// not grow without bound. Active alerts stay.
286+ pub async fn prune_admin_alerts(&self, before: &str) -> Result<()> {
287+ let conn = self.inner.conn.lock().await;
288+ conn.execute(
289+ "DELETE FROM admin_alerts WHERE state <> 'active' AND updated_at < ?1",
290+ (before.to_owned(),),
291+ )
292+ .await
293+ .map_err(db_err)?;
294+ conn.execute(
295+ "DELETE FROM admin_notifications WHERE unread = 0 AND updated_at < ?1",
296+ (before.to_owned(),),
297+ )
298+ .await
299+ .map_err(db_err)?;
300+ Ok(())
301+ }
302+}
303+
304+#[cfg(test)]
305+mod tests {
306+ use crate::store::Store;
307+
308+ async fn store() -> (Store, tempfile::TempDir) {
309+ let dir = tempfile::tempdir().unwrap();
310+ let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
311+ (store, dir)
312+ }
313+
314+ #[tokio::test]
315+ async fn an_alert_is_raised_once_until_it_resolves() {
316+ let (store, _dir) = store().await;
317+ assert!(
318+ store
319+ .raise_alert("runner_offline:r1", "runner_offline", "ci-1", "")
320+ .await
321+ .unwrap()
322+ );
323+ assert!(
324+ !store
325+ .raise_alert("runner_offline:r1", "runner_offline", "ci-1", "later")
326+ .await
327+ .unwrap(),
328+ "still active: not raised again"
329+ );
330+ let active = store.active_alerts().await.unwrap();
331+ assert_eq!(active.len(), 1);
332+ assert_eq!(active[0].detail, "later");
333+
334+ let resolved = store.resolve_alert("runner_offline:r1").await.unwrap();
335+ assert_eq!(resolved.map(|a| a.subject), Some("ci-1".to_owned()));
336+ assert!(
337+ store
338+ .resolve_alert("runner_offline:r1")
339+ .await
340+ .unwrap()
341+ .is_none(),
342+ "resolving twice says nothing the second time"
343+ );
344+ assert!(store.active_alerts().await.unwrap().is_empty());
345+
346+ assert!(
347+ store
348+ .raise_alert("runner_offline:r1", "runner_offline", "ci-1", "")
349+ .await
350+ .unwrap(),
351+ "a new failure after the resolution is raised again"
352+ );
353+ }
354+
355+ #[tokio::test]
356+ async fn events_fire_once_and_are_never_active() {
357+ let (store, _dir) = store().await;
358+ assert!(
359+ store
360+ .record_alert_event("ci_killed:run1", "ci_killed", "ci-1", "")
361+ .await
362+ .unwrap()
363+ );
364+ assert!(
365+ !store
366+ .record_alert_event("ci_killed:run1", "ci_killed", "ci-1", "")
367+ .await
368+ .unwrap()
369+ );
370+ assert!(store.active_alerts().await.unwrap().is_empty());
371+ }
372+}
crates/forge-core/src/store/migrate.rsmodified+1 -0
@@ -98,6 +98,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
98 (56, include_str!("../../migrations/0056_runner_build.sql")),98 (56, include_str!("../../migrations/0056_runner_build.sql")),
99 (57, include_str!("../../migrations/0057_runner_restart.sql")),99 (57, include_str!("../../migrations/0057_runner_restart.sql")),
100 (58, include_str!("../../migrations/0058_passkeys.sql")),100 (58, include_str!("../../migrations/0058_passkeys.sql")),
101+ (59, include_str!("../../migrations/0059_admin_alerts.sql")),
101 ];102 ];
102 103
103 /// The highest migration version this binary knows about.104 /// The highest migration version this binary knows about.
crates/forge-core/src/store/mod.rsmodified+1 -0
@@ -1,6 +1,7 @@
1 //! Turso-backed storage. All metadata lives here.1 //! Turso-backed storage. All metadata lives here.
2 2
3 pub mod account_tokens;3 pub mod account_tokens;
4+pub mod admin_alerts;
4 pub mod advisories;5 pub mod advisories;
5 pub mod attachments;6 pub mod attachments;
6 pub mod audit;7 pub mod audit;
crates/forge-core/src/store/notifications.rsmodified+2 -1
@@ -325,7 +325,8 @@ impl Store {
325 &conn,325 &conn,
326 "SELECT (SELECT COUNT(*) FROM notifications WHERE user_id = ?1 AND unread = 1) + \326 "SELECT (SELECT COUNT(*) FROM notifications WHERE user_id = ?1 AND unread = 1) + \
327 (SELECT COUNT(*) FROM discussion_notifications WHERE user_id = ?1 AND unread = 1) + \327 (SELECT COUNT(*) FROM discussion_notifications WHERE user_id = ?1 AND unread = 1) + \
328- (SELECT COUNT(*) FROM advisory_notifications WHERE user_id = ?1 AND unread = 1)",328+ (SELECT COUNT(*) FROM advisory_notifications WHERE user_id = ?1 AND unread = 1) + \
329+ (SELECT COUNT(*) FROM admin_notifications WHERE user_id = ?1 AND unread = 1)",
329 (user_id.to_string(),),330 (user_id.to_string(),),
330 |row| col_int(row, 0),331 |row| col_int(row, 0),
331 )332 )
crates/forge-core/src/store/user_delete.rsmodified+1 -0
@@ -135,6 +135,7 @@ const REMOVED: &[(&str, &str, &str)] = &[
135 "advisory_notifications",135 "advisory_notifications",
136 "user_id",136 "user_id",
137 ),137 ),
138+ ("admin notifications", "admin_notifications", "user_id"),
138 ("reactions", "reactions", "user_id"),139 ("reactions", "reactions", "user_id"),
139 ("review requests", "review_requests", "reviewer_id"),140 ("review requests", "review_requests", "reviewer_id"),
140 ];141 ];
crates/forge-web/Cargo.tomlmodified+1 -0
@@ -36,6 +36,7 @@ http-body.workspace = true
36 rpassword.workspace = true36 rpassword.workspace = true
37 rand.workspace = true37 rand.workspace = true
38 hex.workspace = true38 hex.workspace = true
39+nix = { workspace = true }
39 sha2.workspace = true40 sha2.workspace = true
40 time.workspace = true41 time.workspace = true
41 comrak = { workspace = true }42 comrak = { workspace = true }
crates/forge-web/src/alerts.rsadded+630 -0
@@ -0,0 +1,630 @@
1+//! Admin alerts: tells the site admins about trouble before something breaks.
2+//!
3+//! An alert is a condition with a stable key. [`raise`] tells the admins once, however often the
4+//! condition is reported, and [`resolve`] tells them once that it is over (see
5+//! `Store::raise_alert`). [`event`] is for a thing that happened once, such as a killed CI job.
6+//! Delivery is an inbox row for every site admin, pushed to their open bell stream, plus an email
7+//! when `alerts.email` is on and the admin has a verified address.
8+//!
9+//! Most alerts are raised where the trouble is seen: a failed backup, a failed self-update, a
10+//! killed job, a runner that checks in again. The conditions nothing reports (a runner that went
11+//! silent, a full disk, an overdue backup, a lagging standby) are looked at on ticks that already
12+//! exist: [`check_runners`] on every CI reaper pass, [`check_slow`] on every tenth.
13+
14+use std::sync::OnceLock;
15+use std::sync::atomic::{AtomicBool, Ordering};
16+
17+use forge_core::alerts::{self, AlertKind};
18+use forge_core::mail::{MailKind, OutgoingMail};
19+use forge_core::store::backup_runs::RunKind;
20+use forge_core::time::stamp_to_unix;
21+
22+use crate::i18n::{self, alerts as text};
23+use crate::mail;
24+use crate::notify_hub::publish_unread;
25+use crate::state::AppState;
26+use crate::views::now_unix;
27+
28+/// True while some runner-offline alert is active, so a runner that checks in costs a database
29+/// write only when there is something to resolve.
30+static OFFLINE_ACTIVE: AtomicBool = AtomicBool::new(false);
31+/// When this process started, as unix seconds. An install that never made a backup is overdue
32+/// from here, not from 1970.
33+static STARTED: OnceLock<i64> = OnceLock::new();
34+
35+fn started() -> i64 {
36+ *STARTED.get_or_init(now_unix)
37+}
38+
39+fn kind_of(topic: &str) -> AlertKind {
40+ match topic {
41+ "runner_offline" => AlertKind::RunnerOffline,
42+ "backup_failed" | "backup_verify_failed" | "backup_overdue" | "fsck_failed" => {
43+ AlertKind::Backup
44+ }
45+ "disk_low" => AlertKind::Disk,
46+ "ci_killed" => AlertKind::CiKilled,
47+ "self_update_restart" | "self_update_failed" => AlertKind::SelfUpdate,
48+ _ => AlertKind::Replication,
49+ }
50+}
51+
52+/// Raises the alert `key` of `topic`. The admins hear about it once, until it resolves.
53+pub async fn raise(state: &AppState, topic: &str, key: &str, subject: &str, detail: &str) {
54+ if !state.live().alerts.kind_enabled(kind_of(topic)) {
55+ return;
56+ }
57+ match state.store.raise_alert(key, topic, subject, detail).await {
58+ Ok(true) => {
59+ if topic == "runner_offline" {
60+ OFFLINE_ACTIVE.store(true, Ordering::Relaxed);
61+ }
62+ deliver(state, key, topic, subject, detail, false).await;
63+ }
64+ Ok(false) => {}
65+ Err(e) => tracing::error!(error = %e, key, "alerts: raising failed"),
66+ }
67+}
68+
69+/// Resolves the alert `key`. The admins are told only when it was active.
70+pub async fn resolve(state: &AppState, key: &str) {
71+ match state.store.resolve_alert(key).await {
72+ Ok(Some(alert)) => {
73+ let kind = kind_of(&alert.kind);
74+ if state.live().alerts.kind_enabled(kind) {
75+ deliver(state, key, &alert.kind, &alert.subject, &alert.detail, true).await;
76+ }
77+ }
78+ Ok(None) => {}
79+ Err(e) => tracing::error!(error = %e, key, "alerts: resolving failed"),
80+ }
81+}
82+
83+/// Tells the admins that something happened, once per `key`.
84+pub async fn event(state: &AppState, topic: &str, key: &str, subject: &str, detail: &str) {
85+ if !state.live().alerts.kind_enabled(kind_of(topic)) {
86+ return;
87+ }
88+ match state
89+ .store
90+ .record_alert_event(key, topic, subject, detail)
91+ .await
92+ {
93+ Ok(true) => deliver(state, key, topic, subject, detail, false).await,
94+ Ok(false) => {}
95+ Err(e) => tracing::error!(error = %e, key, "alerts: recording an event failed"),
96+ }
97+}
98+
99+/// Writes the inbox rows and queues the emails for one message to every site admin.
100+async fn deliver(
101+ state: &AppState,
102+ key: &str,
103+ topic: &str,
104+ subject: &str,
105+ detail: &str,
106+ resolved: bool,
107+) {
108+ let users = match state.store.list_users().await {
109+ Ok(users) => users,
110+ Err(e) => {
111+ tracing::error!(error = %e, "alerts: listing the admins failed");
112+ return;
113+ }
114+ };
115+ let live = state.live();
116+ let base = live.base_url.trim_end_matches('/').to_owned();
117+ let state_word = if resolved { "resolved" } else { "raised" };
118+ for admin in users.into_iter().filter(|u| u.is_admin && !u.is_org()) {
119+ if let Err(e) = state
120+ .store
121+ .add_admin_notice(&admin.id, key, topic, subject, detail, resolved)
122+ .await
123+ {
124+ tracing::error!(error = %e, key, "alerts: writing an inbox row failed");
125+ continue;
126+ }
127+ publish_unread(state, &admin.id).await;
128+ if !live.alerts.email {
129+ continue;
130+ }
131+ let Some(address) = admin.email.as_deref().filter(|a| !a.is_empty()) else {
132+ continue;
133+ };
134+ match state.store.email_is_verified(&admin.id).await {
135+ Ok(true) => {}
136+ Ok(false) => continue,
137+ Err(e) => {
138+ tracing::error!(error = %e, "alerts: checking the admin's address failed");
139+ continue;
140+ }
141+ }
142+ let lang = i18n::resolve(Some(admin.language.as_str()), &http::HeaderMap::new());
143+ let title = text::title(lang, topic, subject, resolved);
144+ let body = text::mail_body(
145+ lang,
146+ &text::body(lang, topic, subject, detail, resolved),
147+ &format!("{base}/admin/health"),
148+ &format!("{base}/admin/server?tab=alerts"),
149+ );
150+ let outgoing = OutgoingMail {
151+ to: address.to_owned(),
152+ subject: text::mail_subject(lang, &title),
153+ body,
154+ message_id: None,
155+ in_reply_to: None,
156+ kind: MailKind::Notification,
157+ user_id: Some(admin.id.clone()),
158+ };
159+ let idem = format!(
160+ "alert:{key}:{state_word}:{}:{}",
161+ forge_core::time::now_stamp(),
162+ admin.id
163+ );
164+ if let Err(e) = mail::enqueue_message(state, &idem, &outgoing).await {
165+ tracing::error!(error = %e, key, "alerts: queueing the email failed");
166+ }
167+ }
168+}
169+
170+// ---- events seen where they happen ----
171+
172+/// A runner authenticated, so it is online. Resolves its offline alert if it had one.
173+pub async fn runner_seen(state: &AppState, runner_id: &str) {
174+ if !OFFLINE_ACTIVE.load(Ordering::Relaxed) {
175+ return;
176+ }
177+ resolve(state, &format!("runner_offline:{runner_id}")).await;
178+ match state.store.active_alert_keys("runner_offline").await {
179+ Ok(keys) if keys.is_empty() => OFFLINE_ACTIVE.store(false, Ordering::Relaxed),
180+ Ok(_) => {}
181+ Err(e) => tracing::error!(error = %e, "alerts: reading the active alerts failed"),
182+ }
183+}
184+
185+/// A job ended `Failure` or `Error`. Tells the admins once per run when it looks like the job was
186+/// killed, naming the runner.
187+pub async fn job_ended(
188+ state: &AppState,
189+ job: &forge_core::ci::CiJob,
190+ exit_code: Option<i64>,
191+ message: Option<&str>,
192+) {
193+ if !alerts::is_kill_signature(exit_code, message) {
194+ return;
195+ }
196+ let runner = match &job.runner_id {
197+ Some(id) => state
198+ .store
199+ .list_runners()
200+ .await
201+ .ok()
202+ .and_then(|runners| runners.into_iter().find(|r| &r.id == id))
203+ .map_or_else(|| id.clone(), |r| r.name),
204+ None => "unknown".to_owned(),
205+ };
206+ let detail = format!("job {} of run {}", job.name, job.run_id);
207+ event(
208+ state,
209+ "ci_killed",
210+ &format!("ci_killed:{}", job.run_id),
211+ &runner,
212+ &detail,
213+ )
214+ .await;
215+}
216+
217+/// The outcome of a scheduled or manual backup. A good one resolves the backup alerts.
218+pub async fn backup_finished(state: &AppState, outcome: Result<(), &str>) {
219+ match outcome {
220+ Ok(()) => {
221+ resolve(state, "backup_failed").await;
222+ resolve(state, "backup_verify_failed").await;
223+ resolve(state, "backup_overdue").await;
224+ }
225+ Err(error) => {
226+ let topic = if error.contains("failed verification") {
227+ "backup_verify_failed"
228+ } else {
229+ "backup_failed"
230+ };
231+ raise(state, topic, topic, "", error).await;
232+ }
233+ }
234+}
235+
236+/// The outcome of an integrity check.
237+pub async fn fsck_finished(state: &AppState, outcome: Result<(), &str>) {
238+ match outcome {
239+ Ok(()) => resolve(state, "fsck_failed").await,
240+ Err(error) => raise(state, "fsck_failed", "fsck_failed", "", error).await,
241+ }
242+}
243+
244+/// A self-update installed a new binary and asked for a restart.
245+pub async fn self_update_deployed(state: &AppState, version: &str) {
246+ raise(
247+ state,
248+ "self_update_restart",
249+ "self_update_restart",
250+ version,
251+ "",
252+ )
253+ .await;
254+}
255+
256+/// A self-update failed. One message per run.
257+pub async fn self_update_failed(state: &AppState, run_id: &str, error: &str) {
258+ event(
259+ state,
260+ "self_update_failed",
261+ &format!("self_update_failed:{run_id}"),
262+ "",
263+ error,
264+ )
265+ .await;
266+}
267+
268+/// Called once at boot. A self-update that asked for a restart is over when the server is up.
269+pub async fn on_boot(state: &AppState) {
270+ started();
271+ match state.store.active_alert_keys("runner_offline").await {
272+ Ok(keys) => OFFLINE_ACTIVE.store(!keys.is_empty(), Ordering::Relaxed),
273+ Err(e) => tracing::error!(error = %e, "alerts: reading the active alerts failed"),
274+ }
275+ if let Ok(Some(alert)) = state.store.resolve_alert("self_update_restart").await
276+ && state.live().alerts.kind_enabled(AlertKind::SelfUpdate)
277+ {
278+ {
279+ let version = crate::self_update::running()
280+ .map(|r| r.sha256.chars().take(12).collect::<String>())
281+ .unwrap_or(alert.subject.clone());
282+ deliver(
283+ state,
284+ "self_update_restart",
285+ "self_update_restart",
286+ &version,
287+ "",
288+ true,
289+ )
290+ .await;
291+ }
292+ }
293+}
294+
295+// ---- conditions nothing reports: looked at on existing ticks ----
296+
297+/// Raises an alert for each runner silent for longer than the configured minutes and resolves the
298+/// ones that are not any more. Runs on every CI reaper pass: one query.
299+pub async fn check_runners(state: &AppState) {
300+ check_runners_at(state, now_unix()).await;
301+}
302+
303+/// [`check_runners`] with an explicit clock.
304+pub async fn check_runners_at(state: &AppState, now: i64) {
305+ let live = state.live();
306+ let cfg = &live.alerts;
307+ let runners = match state.store.list_runners().await {
308+ Ok(runners) => runners,
309+ Err(e) => {
310+ tracing::error!(error = %e, "alerts: listing the runners failed");
311+ return;
312+ }
313+ };
314+ let mut offline = std::collections::BTreeSet::new();
315+ for runner in &runners {
316+ let seen = runner.last_seen_at.as_deref().and_then(stamp_to_unix);
317+ if runner.disabled || !alerts::runner_is_offline(now, seen, cfg.runner_offline_minutes) {
318+ continue;
319+ }
320+ let key = format!("runner_offline:{}", runner.id);
321+ offline.insert(key.clone());
322+ let since = seen.map_or_else(String::new, |t| forge_core::tz::format_in_tz(t, "UTC"));
323+ raise(state, "runner_offline", &key, &runner.name, &since).await;
324+ }
325+ // Whatever is active but no longer offline (back, disabled or deleted) is resolved.
326+ match state.store.active_alert_keys("runner_offline").await {
327+ Ok(active) => {
328+ for key in active.into_iter().filter(|k| !offline.contains(k)) {
329+ resolve(state, &key).await;
330+ }
331+ }
332+ Err(e) => tracing::error!(error = %e, "alerts: reading the active alerts failed"),
333+ }
334+}
335+
336+/// The checks that need a look at the disk or the history: free space, an overdue backup and the
337+/// standby. Meant to run every few minutes.
338+pub async fn check_slow(state: &AppState) {
339+ check_disk(state).await;
340+ check_backup_overdue(state, now_unix()).await;
341+ check_replication(state, now_unix()).await;
342+ let old = forge_core::time::stamp_ago(std::time::Duration::from_secs(90 * 86_400));
343+ if let Err(e) = state.store.prune_admin_alerts(&old).await {
344+ tracing::error!(error = %e, "alerts: pruning failed");
345+ }
346+}
347+
348+/// Free and total bytes of the filesystem holding `path`.
349+pub fn disk_space(path: &std::path::Path) -> Option<(u64, u64)> {
350+ let stat = nix::sys::statvfs::statvfs(path).ok()?;
351+ let block = stat.fragment_size();
352+ let total = stat.blocks().saturating_mul(block);
353+ let avail = stat.blocks_available().saturating_mul(block);
354+ Some((total, avail))
355+}
356+
357+async fn check_disk(state: &AppState) {
358+ let live = state.live();
359+ let cfg = &live.alerts;
360+ if !cfg.kind_enabled(AlertKind::Disk) {
361+ return;
362+ }
363+ let dir = live.data_dir.clone();
364+ let space = tokio::task::spawn_blocking({
365+ let dir = dir.clone();
366+ move || disk_space(&dir)
367+ })
368+ .await
369+ .ok()
370+ .flatten();
371+ let Some((total, avail)) = space else {
372+ return;
373+ };
374+ if alerts::disk_is_low(total, avail, cfg.disk_free_percent, cfg.disk_free_gib) {
375+ let percent = alerts::free_percent(total, avail).unwrap_or(0);
376+ let detail = format!(
377+ "{percent}% free ({} of {})",
378+ crate::views::human_size(i18n::Lang::En, avail),
379+ crate::views::human_size(i18n::Lang::En, total)
380+ );
381+ raise(
382+ state,
383+ "disk_low",
384+ "disk_low",
385+ &dir.to_string_lossy(),
386+ &detail,
387+ )
388+ .await;
389+ } else {
390+ resolve(state, "disk_low").await;
391+ }
392+}
393+
394+async fn check_backup_overdue(state: &AppState, now: i64) {
395+ let live = state.live();
396+ if !live.backup.enabled() || !live.alerts.kind_enabled(AlertKind::Backup) {
397+ return;
398+ }
399+ let last_ok = match state.store.last_ok(RunKind::Backup).await {
400+ Ok(run) => run.and_then(|r| r.finished_at.or(Some(r.started_at))),
401+ Err(e) => {
402+ tracing::error!(error = %e, "alerts: reading the backup history failed");
403+ return;
404+ }
405+ };
406+ let last_ok_unix = last_ok.as_deref().and_then(stamp_to_unix);
407+ if alerts::backup_overdue(now, last_ok_unix, started(), live.backup.interval_hours) {
408+ let detail = last_ok_unix.map_or_else(
409+ || "never".to_owned(),
410+ |t| forge_core::tz::format_in_tz(t, "UTC"),
411+ );
412+ raise(state, "backup_overdue", "backup_overdue", "", &detail).await;
413+ } else {
414+ resolve(state, "backup_overdue").await;
415+ }
416+}
417+
418+async fn check_replication(state: &AppState, now: i64) {
419+ let live = state.live();
420+ if !live.replication.enabled() || !live.alerts.kind_enabled(AlertKind::Replication) {
421+ return;
422+ }
423+ let rows = match state.store.list_replication_status().await {
424+ Ok(rows) => rows,
425+ Err(e) => {
426+ tracing::error!(error = %e, "alerts: reading the replication status failed");
427+ return;
428+ }
429+ };
430+ let window =
431+ i64::try_from(live.replication.db_snapshot_minutes.saturating_mul(120)).unwrap_or(i64::MAX);
432+ let mut problem: Option<String> = None;
433+ for row in &rows {
434+ if let Some(error) = &row.last_error {
435+ problem = Some(format!("{}: {error}.", row.subject));
436+ break;
437+ }
438+ if row.subject == forge_core::store::replication::DB_SUBJECT {
439+ let ok = row.last_ok_at.as_deref().and_then(stamp_to_unix);
440+ if ok.is_none_or(|t| now.saturating_sub(t) > window) {
441+ problem = Some("The database snapshot has not reached the standby in time.".into());
442+ break;
443+ }
444+ }
445+ }
446+ match problem {
447+ Some(detail) => raise(state, "replication", "replication", "", &detail).await,
448+ None => resolve(state, "replication").await,
449+ }
450+}
451+
452+#[cfg(test)]
453+mod tests {
454+ use super::*;
455+ use crate::test_support::test_state;
456+ use forge_core::mail::MailState;
457+
458+ async fn admin(state: &AppState, name: &str, verified: bool) -> String {
459+ let address = format!("{name}@test.example");
460+ let user = state
461+ .store
462+ .create_user(name, Some(&address), "hash", true)
463+ .await
464+ .unwrap();
465+ if verified {
466+ let token = state
467+ .store
468+ .create_verify_token(&user.id, &address)
469+ .await
470+ .unwrap();
471+ state.store.redeem_verify_token(&token).await.unwrap();
472+ }
473+ user.id
474+ }
475+
476+ async fn inbox(
477+ state: &AppState,
478+ user_id: &str,
479+ ) -> Vec<forge_core::store::admin_alerts::AdminNotice> {
480+ state
481+ .store
482+ .list_admin_notices(user_id, false, None, 50)
483+ .await
484+ .unwrap()
485+ }
486+
487+ async fn queued_mail(state: &AppState) -> usize {
488+ state
489+ .store
490+ .mail_state_counts(&forge_core::time::now_stamp())
491+ .await
492+ .unwrap()
493+ .into_iter()
494+ .filter(|(s, _)| matches!(s, MailState::Queued | MailState::Retrying))
495+ .map(|(_, n)| n as usize)
496+ .sum()
497+ }
498+
499+ #[tokio::test]
500+ async fn an_alert_reaches_every_admin_once_and_resolves_once() {
501+ let dir = tempfile::tempdir().unwrap();
502+ let state = test_state(dir.path()).await;
503+ let tahinli = admin(&state, "tahinli", true).await;
504+ let second = admin(&state, "tahinli2", false).await;
505+
506+ raise(&state, "disk_low", "disk_low", "/data", "4% free").await;
507+ raise(&state, "disk_low", "disk_low", "/data", "3% free").await;
508+ assert_eq!(inbox(&state, &tahinli).await.len(), 1, "deduplicated");
509+ assert_eq!(inbox(&state, &second).await.len(), 1);
510+ assert_eq!(state.store.active_alerts().await.unwrap().len(), 1);
511+ assert_eq!(
512+ queued_mail(&state).await,
513+ 1,
514+ "only the verified admin is mailed"
515+ );
516+
517+ resolve(&state, "disk_low").await;
518+ resolve(&state, "disk_low").await;
519+ let rows = inbox(&state, &tahinli).await;
520+ assert_eq!(rows.len(), 2, "raised and resolved, once each");
521+ assert!(rows.iter().any(|r| r.resolved));
522+ assert!(state.store.active_alerts().await.unwrap().is_empty());
523+ assert_eq!(queued_mail(&state).await, 2);
524+ assert_eq!(state.store.unread_count(&tahinli).await.unwrap(), 2);
525+
526+ raise(&state, "disk_low", "disk_low", "/data", "2% free").await;
527+ assert_eq!(
528+ inbox(&state, &tahinli).await.len(),
529+ 3,
530+ "a new episode is told again"
531+ );
532+ }
533+
534+ #[tokio::test]
535+ async fn switches_stop_raising_and_email_off_sends_no_mail() {
536+ let dir = tempfile::tempdir().unwrap();
537+ let mut state = test_state(dir.path()).await;
538+ let tahinli = admin(&state, "tahinli", true).await;
539+ let mut config = (*state.config).clone();
540+ config.alerts.on_disk = false;
541+ state.set_config(config.clone());
542+ raise(&state, "disk_low", "disk_low", "/data", "4% free").await;
543+ assert!(inbox(&state, &tahinli).await.is_empty());
544+
545+ config.alerts.on_disk = true;
546+ config.alerts.email = false;
547+ state.set_config(config.clone());
548+ raise(&state, "disk_low", "disk_low", "/data", "4% free").await;
549+ assert_eq!(inbox(&state, &tahinli).await.len(), 1);
550+ assert_eq!(queued_mail(&state).await, 0);
551+
552+ config.alerts.enabled = false;
553+ state.set_config(config);
554+ raise(&state, "backup_failed", "backup_failed", "", "boom").await;
555+ assert_eq!(
556+ inbox(&state, &tahinli).await.len(),
557+ 1,
558+ "the master switch wins"
559+ );
560+ }
561+
562+ #[tokio::test]
563+ async fn a_silent_runner_is_flagged_and_clears_when_it_checks_in() {
564+ let dir = tempfile::tempdir().unwrap();
565+ let state = test_state(dir.path()).await;
566+ let tahinli = admin(&state, "tahinli", false).await;
567+ let token = state
568+ .store
569+ .create_registration_token(&tahinli, 1)
570+ .await
571+ .unwrap();
572+ let (runner, secret) = state
573+ .store
574+ .register_runner(&token, "tahinli-ci", &["linux".to_owned()])
575+ .await
576+ .unwrap();
577+ // The runner has just been seen: the clock is real for the first check.
578+ state.store.runner_by_secret(&secret).await.unwrap();
579+
580+ let now = now_unix();
581+ check_runners_at(&state, now).await;
582+ assert!(inbox(&state, &tahinli).await.is_empty(), "fresh heartbeat");
583+
584+ // Eleven minutes of silence on a fake clock (the default is ten).
585+ check_runners_at(&state, now + 11 * 60).await;
586+ check_runners_at(&state, now + 12 * 60).await;
587+ let rows = inbox(&state, &tahinli).await;
588+ assert_eq!(rows.len(), 1, "told once");
589+ assert_eq!(rows[0].subject, "tahinli-ci");
590+ assert_eq!(state.store.active_alerts().await.unwrap().len(), 1);
591+
592+ // It checks in again: the heartbeat hook resolves it.
593+ runner_seen(&state, &runner.id).await;
594+ let rows = inbox(&state, &tahinli).await;
595+ assert_eq!(rows.len(), 2);
596+ assert!(rows[0].resolved);
597+ assert!(state.store.active_alerts().await.unwrap().is_empty());
598+ }
599+
600+ #[tokio::test]
601+ async fn a_killed_job_is_told_once_per_run() {
602+ let dir = tempfile::tempdir().unwrap();
603+ let state = test_state(dir.path()).await;
604+ let tahinli = admin(&state, "tahinli", false).await;
605+ let mut job = forge_core::ci::CiJob {
606+ id: "job-1".into(),
607+ run_id: "run-1".into(),
608+ name: "build".into(),
609+ spec_json: "{}".into(),
610+ state: forge_core::ci::JobState::Running,
611+ runner_id: None,
612+ exit_code: None,
613+ message: None,
614+ queued_at: None,
615+ started_at: None,
616+ finished_at: None,
617+ heartbeat_at: None,
618+ cancel_requested: false,
619+ log_bytes: 0,
620+ };
621+ job_ended(&state, &job, Some(137), None).await;
622+ job.name = "second".into();
623+ job_ended(&state, &job, None, Some("signal: 9")).await;
624+ job_ended(&state, &job, Some(1), None).await;
625+ assert_eq!(inbox(&state, &tahinli).await.len(), 1);
626+ job.run_id = "run-2".into();
627+ job_ended(&state, &job, Some(137), None).await;
628+ assert_eq!(inbox(&state, &tahinli).await.len(), 2);
629+ }
630+}
crates/forge-web/src/backup/scheduler.rsmodified+9 -0
@@ -229,6 +229,10 @@ pub async fn backup_job(
229 }229 }
230 230
231 let outcome = backup_set(state, &opts).await;231 let outcome = backup_set(state, &opts).await;
232+ match &outcome {
233+ Ok(_) => crate::alerts::backup_finished(state, Ok(())).await,
234+ Err(e) => crate::alerts::backup_finished(state, Err(&e.to_string())).await,
235+ }
232 match &outcome {236 match &outcome {
233 Ok(summary) => {237 Ok(summary) => {
234 let path = summary.path.to_string_lossy().into_owned();238 let path = summary.path.to_string_lossy().into_owned();
@@ -278,6 +282,11 @@ async fn backup_set(state: &AppState, opts: &BackupOptions) -> Result<BackupSumm
278 pub async fn fsck_job(state: &AppState, trigger: RunTrigger, full: bool) -> Result<FsckSummary> {282 pub async fn fsck_job(state: &AppState, trigger: RunTrigger, full: bool) -> Result<FsckSummary> {
279 let run_id = state.store.start_run(RunKind::Fsck, trigger).await?;283 let run_id = state.store.start_run(RunKind::Fsck, trigger).await?;
280 let outcome = run_fsck(&state.store, &state.git, full).await;284 let outcome = run_fsck(&state.store, &state.git, full).await;
285+ match &outcome {
286+ Ok(summary) if summary.is_ok() => crate::alerts::fsck_finished(state, Ok(())).await,
287+ Ok(summary) => crate::alerts::fsck_finished(state, Err(&summary.problems.join("\n"))).await,
288+ Err(e) => crate::alerts::fsck_finished(state, Err(&e.to_string())).await,
289+ }
281 match &outcome {290 match &outcome {
282 Ok(summary) if summary.is_ok() => {291 Ok(summary) if summary.is_ok() => {
283 record_finish(state, &run_id, true, None, None, None).await;292 record_finish(state, &run_id, true, None, None, None).await;
crates/forge-web/src/boot.rsmodified+1 -0
@@ -153,6 +153,7 @@ pub async fn serve(
153 if state.config.replication.enabled() {153 if state.config.replication.enabled() {
154 crate::replication::worker::spawn(state.clone());154 crate::replication::worker::spawn(state.clone());
155 }155 }
156+ crate::alerts::on_boot(&state).await;
156 crate::ci::reaper::spawn(state.clone());157 crate::ci::reaper::spawn(state.clone());
157 crate::ci::scheduled::spawn(state.clone());158 crate::ci::scheduled::spawn(state.clone());
158 159
crates/forge-web/src/ci/api.rsmodified+7 -1
@@ -82,7 +82,10 @@ async fn runner_from(state: &AppState, headers: &HeaderMap) -> Result<CiRunner,
82 StatusCode::FORBIDDEN,82 StatusCode::FORBIDDEN,
83 "the runner is disabled",83 "the runner is disabled",
84 ))),84 ))),
85- Ok(Some(runner)) => Ok(runner),85+ Ok(Some(runner)) => {
86+ crate::alerts::runner_seen(state, &runner.id).await;
87+ Ok(runner)
88+ }
86 Ok(None) => Err(unauthorized()),89 Ok(None) => Err(unauthorized()),
87 Err(e) => Err(api::internal(e)),90 Err(e) => Err(api::internal(e)),
88 }91 }
@@ -932,6 +935,9 @@ async fn finish_job(
932 }935 }
933 }936 }
934 state.ci_live.bump_runners();937 state.ci_live.bump_runners();
938+ if matches!(outcome, JobState::Failure | JobState::Error) {
939+ crate::alerts::job_ended(state, job, exit_code, request.message.as_deref()).await;
940+ }
935 if any_changed {941 if any_changed {
936 state.ci_live.bump_run(&run.id);942 state.ci_live.bump_run(&run.id);
937 state.ci_live.bump_repo(&run.repo_id);943 state.ci_live.bump_repo(&run.repo_id);
crates/forge-web/src/ci/reaper.rsmodified+9 -0
@@ -16,6 +16,9 @@ use crate::state::AppState;
16 const REAP_EVERY: Duration = Duration::from_secs(30);16 const REAP_EVERY: Duration = Duration::from_secs(30);
17 /// A running job with no heartbeat for this long is lost.17 /// A running job with no heartbeat for this long is lost.
18 const LOST_AFTER: Duration = Duration::from_secs(120);18 const LOST_AFTER: Duration = Duration::from_secs(120);
19+/// How often the alert checks that look at the disk and the backup history run. They share this
20+/// loop rather than adding their own.
21+const ALERTS_SLOW_EVERY: Duration = Duration::from_secs(5 * 60);
19 /// How often retention runs.22 /// How often retention runs.
20 const PURGE_EVERY: Duration = Duration::from_secs(24 * 60 * 60);23 const PURGE_EVERY: Duration = Duration::from_secs(24 * 60 * 60);
21 24
@@ -29,9 +32,15 @@ async fn run(state: AppState) {
29 tick.set_missed_tick_behavior(MissedTickBehavior::Delay);32 tick.set_missed_tick_behavior(MissedTickBehavior::Delay);
30 // Retention runs on the first pass after boot, then once a day.33 // Retention runs on the first pass after boot, then once a day.
31 let mut next_purge = Instant::now();34 let mut next_purge = Instant::now();
35+ let mut next_slow_alerts = Instant::now() + ALERTS_SLOW_EVERY;
32 loop {36 loop {
33 tick.tick().await;37 tick.tick().await;
34 reap_once(&state).await;38 reap_once(&state).await;
39+ crate::alerts::check_runners(&state).await;
40+ if Instant::now() >= next_slow_alerts {
41+ crate::alerts::check_slow(&state).await;
42+ next_slow_alerts = Instant::now() + ALERTS_SLOW_EVERY;
43+ }
35 if Instant::now() >= next_purge {44 if Instant::now() >= next_purge {
36 purge_once(&state).await;45 purge_once(&state).await;
37 next_purge = Instant::now() + PURGE_EVERY;46 next_purge = Instant::now() + PURGE_EVERY;
crates/forge-web/src/i18n/admin.rsmodified+4 -0
@@ -73,6 +73,7 @@ pub enum K {
73 SrvTabStorage,73 SrvTabStorage,
74 SrvTabBackups,74 SrvTabBackups,
75 SrvTabIntegrations,75 SrvTabIntegrations,
76+ SrvTabAlerts,
76 SrvSaved,77 SrvSaved,
77 SrvNothingChanged,78 SrvNothingChanged,
78 SrvResetDone,79 SrvResetDone,
@@ -345,6 +346,8 @@ pub fn t(lang: Lang, key: K) -> &'static str {
345 (SrvTabBackups, Tr) => "Yedekler",346 (SrvTabBackups, Tr) => "Yedekler",
346 (SrvTabIntegrations, En) => "Integrations",347 (SrvTabIntegrations, En) => "Integrations",
347 (SrvTabIntegrations, Tr) => "Entegrasyonlar",348 (SrvTabIntegrations, Tr) => "Entegrasyonlar",
349+ (SrvTabAlerts, En) => "Alerts",
350+ (SrvTabAlerts, Tr) => "Uyarılar",
348 (SrvSaved, En) => "Server settings saved.",351 (SrvSaved, En) => "Server settings saved.",
349 (SrvSaved, Tr) => "Sunucu ayarları kaydedildi.",352 (SrvSaved, Tr) => "Sunucu ayarları kaydedildi.",
350 (SrvNothingChanged, En) => "Nothing changed.",353 (SrvNothingChanged, En) => "Nothing changed.",
@@ -859,6 +862,7 @@ mod tests {
859 K::SrvTabStorage,862 K::SrvTabStorage,
860 K::SrvTabBackups,863 K::SrvTabBackups,
861 K::SrvTabIntegrations,864 K::SrvTabIntegrations,
865+ K::SrvTabAlerts,
862 K::SrvSaved,866 K::SrvSaved,
863 K::SrvNothingChanged,867 K::SrvNothingChanged,
864 K::SrvResetDone,868 K::SrvResetDone,
crates/forge-web/src/i18n/alerts.rsadded+238 -0
@@ -0,0 +1,238 @@
1+//! Strings for admin alerts: the inbox rows, the `/admin/health` banner and the emails. An alert
2+//! is stored as a topic, a subject and a detail, and worded here in the reader's language.
3+//!
4+//! Topics: `runner_offline`, `backup_failed`, `backup_verify_failed`, `backup_overdue`,
5+//! `fsck_failed`, `disk_low`, `ci_killed`, `self_update_restart`, `self_update_failed`,
6+//! `replication`.
7+
8+use super::Lang;
9+
10+/// The one-line headline of an alert. `resolved` words the message that says it is over.
11+pub fn title(lang: Lang, topic: &str, subject: &str, resolved: bool) -> String {
12+ match (lang, topic, resolved) {
13+ (Lang::En, "runner_offline", false) => format!("Runner {subject} is offline"),
14+ (Lang::En, "runner_offline", true) => format!("Runner {subject} is back online"),
15+ (Lang::Tr, "runner_offline", false) => format!("{subject} runner'ı çevrimdışı"),
16+ (Lang::Tr, "runner_offline", true) => format!("{subject} runner'ı yeniden çevrimiçi"),
17+
18+ (Lang::En, "backup_failed", false) => "A backup failed".to_owned(),
19+ (Lang::En, "backup_failed", true) => "Backups work again".to_owned(),
20+ (Lang::Tr, "backup_failed", false) => "Bir yedekleme başarısız oldu".to_owned(),
21+ (Lang::Tr, "backup_failed", true) => "Yedeklemeler yeniden çalışıyor".to_owned(),
22+
23+ (Lang::En, "backup_verify_failed", false) => "Backup verification failed".to_owned(),
24+ (Lang::En, "backup_verify_failed", true) => "Backup verification passes again".to_owned(),
25+ (Lang::Tr, "backup_verify_failed", false) => "Yedek doğrulaması başarısız oldu".to_owned(),
26+ (Lang::Tr, "backup_verify_failed", true) => "Yedek doğrulaması yeniden başarılı".to_owned(),
27+
28+ (Lang::En, "backup_overdue", false) => "No recent backup".to_owned(),
29+ (Lang::En, "backup_overdue", true) => "A backup finished, none overdue".to_owned(),
30+ (Lang::Tr, "backup_overdue", false) => "Yakın zamanda yedek alınmadı".to_owned(),
31+ (Lang::Tr, "backup_overdue", true) => "Bir yedek tamamlandı, gecikme yok".to_owned(),
32+
33+ (Lang::En, "fsck_failed", false) => "The integrity check found problems".to_owned(),
34+ (Lang::En, "fsck_failed", true) => "The integrity check passes again".to_owned(),
35+ (Lang::Tr, "fsck_failed", false) => "Bütünlük denetimi sorun buldu".to_owned(),
36+ (Lang::Tr, "fsck_failed", true) => "Bütünlük denetimi yeniden başarılı".to_owned(),
37+
38+ (Lang::En, "disk_low", false) => "Disk space is low".to_owned(),
39+ (Lang::En, "disk_low", true) => "Disk space is back to normal".to_owned(),
40+ (Lang::Tr, "disk_low", false) => "Disk alanı azaldı".to_owned(),
41+ (Lang::Tr, "disk_low", true) => "Disk alanı normale döndü".to_owned(),
42+
43+ (Lang::En, "ci_killed", _) => format!("A CI job was killed on runner {subject}"),
44+ (Lang::Tr, "ci_killed", _) => format!("{subject} runner'ında bir CI işi öldürüldü"),
45+
46+ (Lang::En, "self_update_restart", false) => "Self-update deployed, restarting".to_owned(),
47+ (Lang::En, "self_update_restart", true) => "Server restarted after self-update".to_owned(),
48+ (Lang::Tr, "self_update_restart", false) => {
49+ "Kendini güncelleme dağıtıldı, yeniden başlıyor".to_owned()
50+ }
51+ (Lang::Tr, "self_update_restart", true) => {
52+ "Sunucu kendini güncelledikten sonra yeniden başladı".to_owned()
53+ }
54+
55+ (Lang::En, "self_update_failed", _) => "Self-update failed".to_owned(),
56+ (Lang::Tr, "self_update_failed", _) => "Kendini güncelleme başarısız oldu".to_owned(),
57+
58+ (Lang::En, "replication", false) => "Standby replication has a problem".to_owned(),
59+ (Lang::En, "replication", true) => "Standby replication is healthy again".to_owned(),
60+ (Lang::Tr, "replication", false) => "Yedek sunucuya kopyalamada sorun var".to_owned(),
61+ (Lang::Tr, "replication", true) => "Yedek sunucuya kopyalama yeniden sağlıklı".to_owned(),
62+
63+ (_, other, _) => other.to_owned(),
64+ }
65+}
66+
67+/// The explanation under the headline.
68+pub fn body(lang: Lang, topic: &str, subject: &str, detail: &str, resolved: bool) -> String {
69+ match (lang, topic, resolved) {
70+ (Lang::En, "runner_offline", false) => format!(
71+ "No heartbeat since {detail}. Queued jobs wait for another runner until it returns."
72+ ),
73+ (Lang::Tr, "runner_offline", false) => format!(
74+ "{detail} tarihinden beri sinyal yok. Sıradaki işler, geri dönene kadar başka bir runner bekler."
75+ ),
76+ (Lang::En, "runner_offline", true) => format!("Runner {subject} checked in again."),
77+ (Lang::Tr, "runner_offline", true) => format!("{subject} runner'ı yeniden bağlandı."),
78+
79+ (Lang::En, "backup_failed" | "backup_verify_failed" | "fsck_failed", false) => {
80+ detail.to_owned()
81+ }
82+ (Lang::Tr, "backup_failed" | "backup_verify_failed" | "fsck_failed", false) => {
83+ detail.to_owned()
84+ }
85+ (Lang::En, "backup_failed", true) => "The latest backup succeeded.".to_owned(),
86+ (Lang::Tr, "backup_failed", true) => "Son yedekleme başarılı oldu.".to_owned(),
87+ (Lang::En, "backup_verify_failed", true) => {
88+ "The latest backup set was verified.".to_owned()
89+ }
90+ (Lang::Tr, "backup_verify_failed", true) => "Son yedek seti doğrulandı.".to_owned(),
91+ (Lang::En, "fsck_failed", true) => "The latest integrity check was clean.".to_owned(),
92+ (Lang::Tr, "fsck_failed", true) => "Son bütünlük denetimi temiz çıktı.".to_owned(),
93+
94+ (Lang::En, "backup_overdue", false) => format!(
95+ "No backup has succeeded within twice the schedule interval. Last good backup: {detail}."
96+ ),
97+ (Lang::Tr, "backup_overdue", false) => format!(
98+ "Zamanlama aralığının iki katı içinde başarılı yedek yok. Son iyi yedek: {detail}."
99+ ),
100+ (Lang::En, "backup_overdue", true) => "The backup schedule is back on track.".to_owned(),
101+ (Lang::Tr, "backup_overdue", true) => "Yedekleme takvimi yeniden yolunda.".to_owned(),
102+
103+ (Lang::En, "disk_low", false) => format!("{subject}: {detail}."),
104+ (Lang::Tr, "disk_low", false) => format!("{subject}: {detail}."),
105+ (Lang::En, "disk_low", true) => format!("{subject} has enough free space again."),
106+ (Lang::Tr, "disk_low", true) => format!("{subject} yeniden yeterli boş alana sahip."),
107+
108+ (Lang::En, "ci_killed", _) => format!(
109+ "{detail} ended with a kill signal, probably the out-of-memory killer. \
110+ Consider lowering the concurrency of runner {subject}."
111+ ),
112+ (Lang::Tr, "ci_killed", _) => format!(
113+ "{detail} bir öldürme sinyaliyle sona erdi, büyük olasılıkla bellek yetersizliği. \
114+ {subject} runner'ının eşzamanlılığını düşürmeyi düşünün."
115+ ),
116+
117+ (Lang::En, "self_update_restart", false) => {
118+ format!("Version {subject} is installed. The server is restarting to run it.")
119+ }
120+ (Lang::Tr, "self_update_restart", false) => {
121+ format!("{subject} sürümü kuruldu. Sunucu onu çalıştırmak için yeniden başlıyor.")
122+ }
123+ (Lang::En, "self_update_restart", true) => {
124+ format!("The server is running version {subject}.")
125+ }
126+ (Lang::Tr, "self_update_restart", true) => {
127+ format!("Sunucu {subject} sürümünü çalıştırıyor.")
128+ }
129+
130+ (_, "self_update_failed", _) => detail.to_owned(),
131+
132+ (Lang::En, "replication", false) => {
133+ format!("{detail} The standby may be behind until this is fixed.")
134+ }
135+ (Lang::Tr, "replication", false) => {
136+ format!("{detail} Bu düzelene kadar yedek sunucu geride kalabilir.")
137+ }
138+ (Lang::En, "replication", true) => "The standby is up to date.".to_owned(),
139+ (Lang::Tr, "replication", true) => "Yedek sunucu güncel.".to_owned(),
140+
141+ _ => detail.to_owned(),
142+ }
143+}
144+
145+/// Label of the group heading in the inbox, and of the banner on the health page.
146+pub fn inbox_heading(lang: Lang) -> &'static str {
147+ match lang {
148+ Lang::En => "Admin alerts",
149+ Lang::Tr => "Yönetici uyarıları",
150+ }
151+}
152+
153+/// Banner heading on `/admin/health`.
154+pub fn banner_heading(lang: Lang, count: usize) -> String {
155+ match lang {
156+ Lang::En if count == 1 => "1 active alert".to_owned(),
157+ Lang::En => format!("{count} active alerts"),
158+ Lang::Tr => format!("{count} etkin uyarı"),
159+ }
160+}
161+
162+/// Link from the banner to the alert settings.
163+pub fn settings_link(lang: Lang) -> &'static str {
164+ match lang {
165+ Lang::En => "Alert settings",
166+ Lang::Tr => "Uyarı ayarları",
167+ }
168+}
169+
170+/// "since <time>" on the banner.
171+pub fn since(lang: Lang, when: &str) -> String {
172+ match lang {
173+ Lang::En => format!("since {when}"),
174+ Lang::Tr => format!("{when} tarihinden beri"),
175+ }
176+}
177+
178+/// Email subject: the title, tagged with the instance.
179+pub fn mail_subject(lang: Lang, title: &str) -> String {
180+ match lang {
181+ Lang::En => format!("[forge] {title}"),
182+ Lang::Tr => format!("[forge] {title}"),
183+ }
184+}
185+
186+/// Email body: the explanation, then where to look.
187+pub fn mail_body(lang: Lang, body: &str, health_url: &str, settings_url: &str) -> String {
188+ match lang {
189+ Lang::En => format!(
190+ "{body}\n\nHealth page: {health_url}\n\nYou get this because you are a site admin. \
191+ Turn alerts off or change thresholds at {settings_url}\n"
192+ ),
193+ Lang::Tr => format!(
194+ "{body}\n\nSağlık sayfası: {health_url}\n\nBunu site yöneticisi olduğunuz için \
195+ alıyorsunuz. Uyarıları kapatmak veya eşikleri değiştirmek için: {settings_url}\n"
196+ ),
197+ }
198+}
199+
200+#[cfg(test)]
201+mod tests {
202+ use super::*;
203+
204+ const TOPICS: &[&str] = &[
205+ "runner_offline",
206+ "backup_failed",
207+ "backup_verify_failed",
208+ "backup_overdue",
209+ "fsck_failed",
210+ "disk_low",
211+ "ci_killed",
212+ "self_update_restart",
213+ "self_update_failed",
214+ "replication",
215+ ];
216+
217+ #[test]
218+ fn every_topic_is_worded_in_both_languages_without_em_dashes() {
219+ for lang in [Lang::En, Lang::Tr] {
220+ for topic in TOPICS {
221+ for resolved in [false, true] {
222+ let t = title(lang, topic, "tahinli-ci", resolved);
223+ let b = body(lang, topic, "tahinli-ci", "detail", resolved);
224+ assert_ne!(t, *topic, "{topic} has a title");
225+ assert!(!b.is_empty(), "{topic} has a body");
226+ assert!(!t.contains('\u{2014}') && !b.contains('\u{2014}'));
227+ }
228+ }
229+ let mail = mail_body(
230+ lang,
231+ "x",
232+ "https://forge.test/admin/health",
233+ "https://forge.test/admin/server",
234+ );
235+ assert!(!mail.contains('\u{2014}'));
236+ }
237+ }
238+}
crates/forge-web/src/i18n/misc.rsmodified+8 -0
@@ -43,6 +43,7 @@ pub enum K {
43 KindClosedPull,43 KindClosedPull,
44 KindDiscussion,44 KindDiscussion,
45 KindSecurityAlerts,45 KindSecurityAlerts,
46+ KindAdminAlert,
46 // Notifications: reason badges.47 // Notifications: reason badges.
47 ReasonMentioned,48 ReasonMentioned,
48 ReasonAssigned,49 ReasonAssigned,
@@ -54,6 +55,7 @@ pub enum K {
54 ReasonWatching,55 ReasonWatching,
55 ReasonReplied,56 ReasonReplied,
56 ReasonSecurity,57 ReasonSecurity,
58+ ReasonAdmin,
57 // Notifications: activity verbs (`activity_line` adds the actor).59 // Notifications: activity verbs (`activity_line` adds the actor).
58 VerbOpened,60 VerbOpened,
59 VerbCommented,61 VerbCommented,
@@ -189,6 +191,7 @@ const ALL: &[K] = &[
189 K::KindClosedPull,191 K::KindClosedPull,
190 K::KindDiscussion,192 K::KindDiscussion,
191 K::KindSecurityAlerts,193 K::KindSecurityAlerts,
194+ K::KindAdminAlert,
192 K::ReasonMentioned,195 K::ReasonMentioned,
193 K::ReasonAssigned,196 K::ReasonAssigned,
194 K::ReasonReviewRequested,197 K::ReasonReviewRequested,
@@ -199,6 +202,7 @@ const ALL: &[K] = &[
199 K::ReasonWatching,202 K::ReasonWatching,
200 K::ReasonReplied,203 K::ReasonReplied,
201 K::ReasonSecurity,204 K::ReasonSecurity,
205+ K::ReasonAdmin,
202 K::VerbOpened,206 K::VerbOpened,
203 K::VerbCommented,207 K::VerbCommented,
204 K::VerbClosed,208 K::VerbClosed,
@@ -358,6 +362,8 @@ pub fn t(lang: Lang, key: K) -> &'static str {
358 (KindDiscussion, Tr) => "Tartışma",362 (KindDiscussion, Tr) => "Tartışma",
359 (KindSecurityAlerts, En) => "Security alerts",363 (KindSecurityAlerts, En) => "Security alerts",
360 (KindSecurityAlerts, Tr) => "Güvenlik uyarıları",364 (KindSecurityAlerts, Tr) => "Güvenlik uyarıları",
365+ (KindAdminAlert, En) => "Admin alert",
366+ (KindAdminAlert, Tr) => "Yönetici uyarısı",
361 (ReasonMentioned, En) => "mentioned",367 (ReasonMentioned, En) => "mentioned",
362 (ReasonMentioned, Tr) => "bahsedildi",368 (ReasonMentioned, Tr) => "bahsedildi",
363 (ReasonAssigned, En) => "assigned",369 (ReasonAssigned, En) => "assigned",
@@ -378,6 +384,8 @@ pub fn t(lang: Lang, key: K) -> &'static str {
378 (ReasonReplied, Tr) => "yanıtladı",384 (ReasonReplied, Tr) => "yanıtladı",
379 (ReasonSecurity, En) => "security",385 (ReasonSecurity, En) => "security",
380 (ReasonSecurity, Tr) => "güvenlik",386 (ReasonSecurity, Tr) => "güvenlik",
387+ (ReasonAdmin, En) => "admin",
388+ (ReasonAdmin, Tr) => "yönetici",
381 (VerbOpened, En) => "opened",389 (VerbOpened, En) => "opened",
382 (VerbOpened, Tr) => "açıldı",390 (VerbOpened, Tr) => "açıldı",
383 (VerbCommented, En) => "commented",391 (VerbCommented, En) => "commented",
crates/forge-web/src/i18n/mod.rsmodified+1 -0
@@ -20,6 +20,7 @@ use forge_core::User;
20 pub mod accents;20 pub mod accents;
21 pub mod accounts;21 pub mod accounts;
22 pub mod admin;22 pub mod admin;
23+pub mod alerts;
23 pub mod authoring;24 pub mod authoring;
24 pub mod browse;25 pub mod browse;
25 pub mod code;26 pub mod code;
crates/forge-web/src/main.rsmodified+1 -0
@@ -13,6 +13,7 @@ mod access;
13 mod admin_cli;13 mod admin_cli;
14 mod admin_client;14 mod admin_client;
15 mod advisories;15 mod advisories;
16+mod alerts;
16 mod api;17 mod api;
17 mod audit;18 mod audit;
18 mod auth;19 mod auth;
crates/forge-web/src/pages/admin_health.rsmodified+55 -2
@@ -17,6 +17,7 @@ use topcoat::router::page;
17 use topcoat::view::{View, component, view};17 use topcoat::view::{View, component, view};
18 18
19 use crate::i18n::accounts::{A, duration_short, t as at};19 use crate::i18n::accounts::{A, duration_short, t as at};
20+use crate::i18n::alerts as alert_text;
20 use crate::i18n::{self, Lang};21 use crate::i18n::{self, Lang};
21 use crate::pages::admin_users::admin_only;22 use crate::pages::admin_users::admin_only;
22 use crate::state::AppState;23 use crate::state::AppState;
@@ -282,13 +283,64 @@ async fn tiles(state: &AppState, lang: Lang, tz: &str) -> Result<Vec<Tile>> {
282 Ok(out)283 Ok(out)
283 }284 }
284 285
286+/// One active alert in the banner.
287+struct AlertRow {
288+ title: String,
289+ body: String,
290+ since: String,
291+}
292+
293+/// The alerts active now, worded for the viewer.
294+async fn alert_rows(state: &AppState, lang: Lang, tz: &str) -> Result<Vec<AlertRow>> {
295+ let now = now_unix();
296+ Ok(state
297+ .store
298+ .active_alerts()
299+ .await?
300+ .into_iter()
301+ .map(|alert| {
302+ let raised = stamp_to_unix(&alert.raised_at).unwrap_or(now);
303+ AlertRow {
304+ title: alert_text::title(lang, &alert.kind, &alert.subject, false),
305+ body: alert_text::body(lang, &alert.kind, &alert.subject, &alert.detail, false),
306+ since: alert_text::since(
307+ lang,
308+ &format!(
309+ "{} ({})",
310+ format_in_tz(raised, tz),
311+ relative_time(lang, raised, now)
312+ ),
313+ ),
314+ }
315+ })
316+ .collect())
317+}
318+
285 #[component]319 #[component]
286-async fn health_view(lang: Lang, tiles: Vec<Tile>) -> Result<impl View> {320+async fn health_view(lang: Lang, tiles: Vec<Tile>, alerts: Vec<AlertRow>) -> Result<impl View> {
321+ let count = alerts.len();
287 Ok(view! {322 Ok(view! {
288 <section class="page-head">323 <section class="page-head">
289 <h1>(at(lang, A::Health))</h1>324 <h1>(at(lang, A::Health))</h1>
290 <p class="muted">(at(lang, A::HealthIntro))</p>325 <p class="muted">(at(lang, A::HealthIntro))</p>
291 </section>326 </section>
327+ if count > 0 {
328+ <section class="admin-alerts" role="alert">
329+ <h2>(alert_text::banner_heading(lang, count))</h2>
330+ <ul>
331+ for a in alerts.into_iter() {
332+ <li>
333+ <strong>(a.title.as_str())</strong>
334+ <span class="muted small">(a.since.as_str())</span>
335+ if !a.body.is_empty() {
336+ <div class="small">(a.body.as_str())</div>
337+ }
338+ </li>
339+ }
340+ </ul>
341+ <a class="small" href="/admin/server?tab=alerts">(alert_text::settings_link(lang))</a>
342+ </section>
343+ }
292 <div class="health-grid">344 <div class="health-grid">
293 for t in tiles.into_iter() {345 for t in tiles.into_iter() {
294 <section class=(format!("tile {}", t.tone))>346 <section class=(format!("tile {}", t.tone))>
@@ -312,9 +364,10 @@ async fn health_page(cx: &Cx) -> Result<impl View> {
312 let lang = i18n::lang(cx, Some(&viewer.0));364 let lang = i18n::lang(cx, Some(&viewer.0));
313 let state = app_context::<AppState>(cx);365 let state = app_context::<AppState>(cx);
314 let tiles = tiles(state, lang, &viewer.0.timezone).await?;366 let tiles = tiles(state, lang, &viewer.0.timezone).await?;
367+ let alerts = alert_rows(state, lang, &viewer.0.timezone).await?;
315 let title = at(lang, A::Health);368 let title = at(lang, A::Health);
316 Ok(view! {369 Ok(view! {
317- shell(title: title, viewer: Some(&viewer), health_view(lang: lang, tiles: tiles))370+ shell(title: title, viewer: Some(&viewer), health_view(lang: lang, tiles: tiles, alerts: alerts))
318 })371 })
319 }372 }
320 373
crates/forge-web/src/pages/admin_server.rsmodified+1 -0
@@ -117,6 +117,7 @@ fn tab_label(lang: Lang, group: Group) -> &'static str {
117 Group::Storage => K::SrvTabStorage,117 Group::Storage => K::SrvTabStorage,
118 Group::Backups => K::SrvTabBackups,118 Group::Backups => K::SrvTabBackups,
119 Group::Integrations => K::SrvTabIntegrations,119 Group::Integrations => K::SrvTabIntegrations,
120+ Group::Alerts => K::SrvTabAlerts,
120 },121 },
121 )122 )
122 }123 }
crates/forge-web/src/pages/notifications.rsmodified+118 -1
@@ -9,6 +9,7 @@ use std::time::Duration;
9 9
10 use forge_core::authz::{Action, authorize};10 use forge_core::authz::{Action, authorize};
11 use forge_core::discussions::{DiscussionNotification, DiscussionReason};11 use forge_core::discussions::{DiscussionNotification, DiscussionReason};
12+use forge_core::store::admin_alerts::AdminNotice;
12 use forge_core::store::advisories::AdvisoryNotice;13 use forge_core::store::advisories::AdvisoryNotice;
13 use forge_core::store::transfers::PendingTransfer;14 use forge_core::store::transfers::PendingTransfer;
14 use forge_core::{Notification, Reason, Role, SubState, User, WatchLevel};15 use forge_core::{Notification, Reason, Role, SubState, User, WatchLevel};
@@ -24,6 +25,7 @@ use topcoat::router::{Body, HeaderValue, StatusCode, page, path_param, query_par
24 use topcoat::view::{View, component, view};25 use topcoat::view::{View, component, view};
25 26
26 use crate::auth::{current_user, percent_encode, require_csrf, require_user};27 use crate::auth::{current_user, percent_encode, require_csrf, require_user};
28+use crate::i18n::alerts as alert_text;
27 use crate::i18n::misc::{self as g, K};29 use crate::i18n::misc::{self as g, K};
28 use crate::i18n::{self, Key, Lang};30 use crate::i18n::{self, Key, Lang};
29 use crate::notify_hub::publish_unread;31 use crate::notify_hub::publish_unread;
@@ -43,6 +45,10 @@ path_param!(number);
43 path_param!(note);45 path_param!(note);
44 path_param!(discussion_id);46 path_param!(discussion_id);
45 path_param!(advisory_repo_id);47 path_param!(advisory_repo_id);
48+path_param!(admin_note);
49+
50+/// The pseudo repo id of the admin alerts group in the inbox.
51+const ADMIN_GROUP: &str = "admin";
46 52
47 #[query_params(error = bad_request)]53 #[query_params(error = bad_request)]
48 struct InboxQuery {54 struct InboxQuery {
@@ -107,6 +113,8 @@ enum Entry {
107 Issue(Notification),113 Issue(Notification),
108 Discussion(DiscussionNotification),114 Discussion(DiscussionNotification),
109 Advisory(AdvisoryNotice),115 Advisory(AdvisoryNotice),
116+ /// An admin alert. It belongs to no repo.
117+ Admin(AdminNotice),
110 }118 }
111 119
112 impl Entry {120 impl Entry {
@@ -115,6 +123,7 @@ impl Entry {
115 Entry::Issue(note) => &note.repo_id,123 Entry::Issue(note) => &note.repo_id,
116 Entry::Discussion(note) => &note.repo_id,124 Entry::Discussion(note) => &note.repo_id,
117 Entry::Advisory(note) => &note.repo_id,125 Entry::Advisory(note) => &note.repo_id,
126+ Entry::Admin(_) => ADMIN_GROUP,
118 }127 }
119 }128 }
120 129
@@ -123,6 +132,7 @@ impl Entry {
123 Entry::Issue(note) => &note.repo_owner,132 Entry::Issue(note) => &note.repo_owner,
124 Entry::Discussion(note) => &note.repo_owner,133 Entry::Discussion(note) => &note.repo_owner,
125 Entry::Advisory(note) => &note.repo_owner,134 Entry::Advisory(note) => &note.repo_owner,
135+ Entry::Admin(_) => "",
126 }136 }
127 }137 }
128 138
@@ -131,6 +141,7 @@ impl Entry {
131 Entry::Issue(note) => &note.repo_name,141 Entry::Issue(note) => &note.repo_name,
132 Entry::Discussion(note) => &note.repo_name,142 Entry::Discussion(note) => &note.repo_name,
133 Entry::Advisory(note) => &note.repo_name,143 Entry::Advisory(note) => &note.repo_name,
144+ Entry::Admin(_) => "",
134 }145 }
135 }146 }
136 147
@@ -139,6 +150,7 @@ impl Entry {
139 Entry::Issue(note) => &note.updated_at,150 Entry::Issue(note) => &note.updated_at,
140 Entry::Discussion(note) => &note.updated_at,151 Entry::Discussion(note) => &note.updated_at,
141 Entry::Advisory(note) => &note.updated_at,152 Entry::Advisory(note) => &note.updated_at,
153+ Entry::Admin(note) => &note.updated_at,
142 }154 }
143 }155 }
144 }156 }
@@ -250,6 +262,34 @@ fn advisory_row(lang: Lang, note: &AdvisoryNotice, tz: &str, now: i64) -> RowVie
250 }262 }
251 }263 }
252 264
265+/// The row for an admin alert: the headline as the title and the explanation as the activity. It
266+/// opens the health page.
267+fn admin_row(lang: Lang, note: &AdminNotice, tz: &str, now: i64) -> RowView {
268+ let unix = stamp_unix(&note.updated_at);
269+ RowView {
270+ item_class: if note.unread {
271+ "notif-row unread"
272+ } else {
273+ "notif-row"
274+ },
275+ icon_class: if note.resolved {
276+ "notif-icon admin-resolved"
277+ } else {
278+ "notif-icon admin-alert"
279+ },
280+ kind_label: g::t(lang, K::KindAdminAlert),
281+ open_href: format!("/notifications/admin/{}/open", percent_encode(&note.id)),
282+ read_action: format!("/notifications/admin/{}/read", percent_encode(&note.id)),
283+ title_line: alert_text::title(lang, &note.kind, &note.subject, note.resolved),
284+ reason: g::t(lang, K::ReasonAdmin),
285+ activity: alert_text::body(lang, &note.kind, &note.subject, &note.detail, note.resolved),
286+ iso: iso_time(unix),
287+ absolute: forge_core::tz::format_in_tz(unix, tz),
288+ relative: relative_time(lang, unix, now),
289+ unread: note.unread,
290+ }
291+}
292+
253 #[page("/notifications")]293 #[page("/notifications")]
254 async fn inbox(cx: &Cx) -> Result<impl View> {294 async fn inbox(cx: &Cx) -> Result<impl View> {
255 let viewer = require_user(cx).await?;295 let viewer = require_user(cx).await?;
@@ -274,16 +314,26 @@ async fn inbox(cx: &Cx) -> Result<impl View> {
274 .store314 .store
275 .list_advisory_notifications(&user.id, !all, before.as_deref(), PAGE_SIZE)315 .list_advisory_notifications(&user.id, !all, before.as_deref(), PAGE_SIZE)
276 .await?;316 .await?;
317+ let admin_rows = if user.is_admin {
318+ state
319+ .store
320+ .list_admin_notices(&user.id, !all, before.as_deref(), PAGE_SIZE)
321+ .await?
322+ } else {
323+ Vec::new()
324+ };
277 // Every list is newest first and holds at most one page, so the top page of the merge is325 // Every list is newest first and holds at most one page, so the top page of the merge is
278 // complete. A `more` link is due when any list was full or the merge has rows past the page.326 // complete. A `more` link is due when any list was full or the merge has rows past the page.
279 let lists_full = rows.len() == PAGE_SIZE as usize327 let lists_full = rows.len() == PAGE_SIZE as usize
280 || discussion_rows.len() == PAGE_SIZE as usize328 || discussion_rows.len() == PAGE_SIZE as usize
281- || advisory_rows.len() == PAGE_SIZE as usize;329+ || advisory_rows.len() == PAGE_SIZE as usize
330+ || admin_rows.len() == PAGE_SIZE as usize;
282 let mut merged: Vec<Entry> = rows331 let mut merged: Vec<Entry> = rows
283 .into_iter()332 .into_iter()
284 .map(Entry::Issue)333 .map(Entry::Issue)
285 .chain(discussion_rows.into_iter().map(Entry::Discussion))334 .chain(discussion_rows.into_iter().map(Entry::Discussion))
286 .chain(advisory_rows.into_iter().map(Entry::Advisory))335 .chain(advisory_rows.into_iter().map(Entry::Advisory))
336+ .chain(admin_rows.into_iter().map(Entry::Admin))
287 .collect();337 .collect();
288 merged.sort_by(|a, b| b.updated_at().cmp(a.updated_at()));338 merged.sort_by(|a, b| b.updated_at().cmp(a.updated_at()));
289 let more_rows = lists_full || merged.len() > PAGE_SIZE as usize;339 let more_rows = lists_full || merged.len() > PAGE_SIZE as usize;
@@ -309,6 +359,26 @@ async fn inbox(cx: &Cx) -> Result<impl View> {
309 let mut index: HashMap<String, usize> = HashMap::new();359 let mut index: HashMap<String, usize> = HashMap::new();
310 for entry in merged {360 for entry in merged {
311 let repo_id = entry.repo_id().to_owned();361 let repo_id = entry.repo_id().to_owned();
362+ if let Entry::Admin(_) = &entry {
363+ // Admin alerts need no repo access.
364+ let slot = match index.get(&repo_id) {
365+ Some(slot) => *slot,
366+ None => {
367+ groups.push(RepoGroup {
368+ heading: alert_text::inbox_heading(lang).to_owned(),
369+ href: "/admin/health".to_owned(),
370+ mark_action: format!("/notifications/mark_all_read?repo={ADMIN_GROUP}"),
371+ rows: Vec::new(),
372+ });
373+ index.insert(repo_id.clone(), groups.len() - 1);
374+ groups.len() - 1
375+ }
376+ };
377+ if let Entry::Admin(note) = &entry {
378+ groups[slot].rows.push(admin_row(lang, note, &tz, now));
379+ }
380+ continue;
381+ }
312 let visible = match readable.get(&repo_id) {382 let visible = match readable.get(&repo_id) {
313 Some(visible) => *visible,383 Some(visible) => *visible,
314 None => {384 None => {
@@ -346,6 +416,7 @@ async fn inbox(cx: &Cx) -> Result<impl View> {
346 Entry::Issue(note) => issue_row(lang, &note, &tz, now),416 Entry::Issue(note) => issue_row(lang, &note, &tz, now),
347 Entry::Discussion(note) => discussion_row(lang, &note, &tz, now),417 Entry::Discussion(note) => discussion_row(lang, &note, &tz, now),
348 Entry::Advisory(note) => advisory_row(lang, &note, &tz, now),418 Entry::Advisory(note) => advisory_row(lang, &note, &tz, now),
419+ Entry::Admin(note) => admin_row(lang, &note, &tz, now),
349 };420 };
350 groups[slot].rows.push(row);421 groups[slot].rows.push(row);
351 }422 }
@@ -365,6 +436,12 @@ async fn inbox(cx: &Cx) -> Result<impl View> {
365 .mark_advisory_notification_read(&user.id, &note.repo_id)436 .mark_advisory_notification_read(&user.id, &note.repo_id)
366 .await?;437 .await?;
367 }438 }
439+ Entry::Admin(note) => {
440+ state
441+ .store
442+ .mark_admin_notice_read(&user.id, &note.id)
443+ .await?
444+ }
368 }445 }
369 }446 }
370 447
@@ -487,6 +564,38 @@ async fn read_advisory_notification(cx: &Cx, Form(form): Form<CsrfForm>) -> Resu
487 Ok(see_other(back(cx)))564 Ok(see_other(back(cx)))
488 }565 }
489 566
567+/// Opens an admin alert row: marks it read and sends the viewer to the health page. Only the
568+/// owner of the row can open it; anyone else gets 404.
569+#[route(GET "/notifications/admin/{admin_note}/open")]
570+async fn open_admin_notification(cx: &Cx) -> Result<SeeOther> {
571+ let (user, _) = require_user(cx).await?;
572+ let state = app_context::<AppState>(cx);
573+ let id = path_param::<AdminNote>(cx);
574+ let owned = state
575+ .store
576+ .list_admin_notices(&user.id, false, None, 200)
577+ .await?
578+ .into_iter()
579+ .any(|note| note.id == id);
580+ if !owned || !user.is_admin {
581+ return Err(not_found().into());
582+ }
583+ state.store.mark_admin_notice_read(&user.id, id).await?;
584+ publish_unread(state, &user.id).await;
585+ Ok(see_other("/admin/health"))
586+}
587+
588+/// Marks one admin alert row read, then returns to the page the viewer came from.
589+#[route(POST "/notifications/admin/{admin_note}/read")]
590+async fn read_admin_notification(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
591+ let (user, _) = require_csrf(cx, &form.csrf).await?;
592+ let state = app_context::<AppState>(cx);
593+ let id = path_param::<AdminNote>(cx);
594+ state.store.mark_admin_notice_read(&user.id, id).await?;
595+ publish_unread(state, &user.id).await;
596+ Ok(see_other(back(cx)))
597+}
598+
490 /// Marks one inbox row read, then returns to the page the viewer came from.599 /// Marks one inbox row read, then returns to the page the viewer came from.
491 #[route(POST "/notifications/{note}/read")]600 #[route(POST "/notifications/{note}/read")]
492 async fn read_notification(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {601 async fn read_notification(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
@@ -505,6 +614,14 @@ async fn mark_all_read(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther>
505 let state = app_context::<AppState>(cx);614 let state = app_context::<AppState>(cx);
506 let query = query_params::<RepoQuery>(cx)?;615 let query = query_params::<RepoQuery>(cx)?;
507 let repo_id = query.repo.as_deref().filter(|s| !s.is_empty());616 let repo_id = query.repo.as_deref().filter(|s| !s.is_empty());
617+ if repo_id == Some(ADMIN_GROUP) {
618+ state.store.mark_all_admin_notices_read(&user.id).await?;
619+ publish_unread(state, &user.id).await;
620+ return Ok(see_other(back(cx)));
621+ }
622+ if repo_id.is_none() {
623+ state.store.mark_all_admin_notices_read(&user.id).await?;
624+ }
508 state.store.mark_all_read(&user.id, repo_id).await?;625 state.store.mark_all_read(&user.id, repo_id).await?;
509 state626 state
510 .store627 .store
crates/forge-web/src/pages/settings_security.rsmodified+1 -0
@@ -1074,6 +1074,7 @@ mod tests {
1074 orgs: Default::default(),1074 orgs: Default::default(),
1075 self_update: Default::default(),1075 self_update: Default::default(),
1076 banner: Default::default(),1076 banner: Default::default(),
1077+ alerts: Default::default(),
1077 };1078 };
1078 let config = Arc::new(config);1079 let config = Arc::new(config);
1079 let state = AppState {1080 let state = AppState {
crates/forge-web/src/self_update.rsmodified+2 -0
@@ -208,6 +208,7 @@ pub async fn deploy(state: AppState, run: CiRun) {
208 };208 };
209 if let Err(e) = deploy_inner(&state, &run).await {209 if let Err(e) = deploy_inner(&state, &run).await {
210 tracing::error!(run_id = %run.id, error = %e, "self-update: deploy failed");210 tracing::error!(run_id = %run.id, error = %e, "self-update: deploy failed");
211+ crate::alerts::self_update_failed(&state, &run.id, &e).await;
211 }212 }
212 }213 }
213 214
@@ -276,6 +277,7 @@ async fn deploy_inner(state: &AppState, run: &CiRun) -> Result<(), String> {
276 exe = %running.path.display(),277 exe = %running.path.display(),
277 "self-update: binary replaced, restarting"278 "self-update: binary replaced, restarting"
278 );279 );
280+ crate::alerts::self_update_deployed(state, &sha.chars().take(12).collect::<String>()).await;
279 RESTART_REQUESTED.store(true, Ordering::SeqCst);281 RESTART_REQUESTED.store(true, Ordering::SeqCst);
280 RESTART.notify_one();282 RESTART.notify_one();
281 Ok(())283 Ok(())
crates/forge-web/src/test_support.rsmodified+1 -0
@@ -54,6 +54,7 @@ pub fn test_config(dir: &Path) -> Config {
54 orgs: Default::default(),54 orgs: Default::default(),
55 self_update: Default::default(),55 self_update: Default::default(),
56 banner: Default::default(),56 banner: Default::default(),
57+ alerts: Default::default(),
57 }58 }
58 }59 }
59 60
style/_account_admin.scssmodified+34 -0
@@ -170,3 +170,37 @@
170 gap: 8px 20px;170 gap: 8px 20px;
171 margin: 16px 0 0;171 margin: 16px 0 0;
172 }172 }
173+
174+// Active admin alerts, above the health tiles.
175+.admin-alerts {
176+ background: var(--danger-bg);
177+ border: 1px solid var(--danger);
178+ border-radius: var(--radius-lg);
179+ padding: 12px 16px;
180+ margin-bottom: 16px;
181+
182+ h2 {
183+ margin: 0 0 8px;
184+ font-size: 0.9375rem;
185+ color: var(--danger);
186+ }
187+
188+ ul {
189+ list-style: none;
190+ margin: 0 0 8px;
191+ padding: 0;
192+ }
193+
194+ li {
195+ padding: 6px 0;
196+ overflow-wrap: anywhere;
197+
198+ & + li {
199+ border-top: 1px solid var(--border);
200+ }
201+
202+ .muted {
203+ margin-left: 8px;
204+ }
205+ }
206+}
style/main.scssmodified+7 -1
@@ -3613,10 +3613,16 @@ span.reaction {
3613 }3613 }
3614 3614
3615 &.issue-closed,3615 &.issue-closed,
3616- &.pull-closed {3616+ &.pull-closed,
3617+ &.admin-alert {
3617 border-color: var(--danger);3618 border-color: var(--danger);
3618 background: var(--danger-bg);3619 background: var(--danger-bg);
3619 }3620 }
3621+
3622+ &.admin-resolved {
3623+ border-color: var(--public-text);
3624+ background: var(--public-bg);
3625+ }
3620 }3626 }
3621 3627
3622 // Visually hidden text for screen readers, used next to icons.3628 // Visually hidden text for screen readers, used next to icons.