Skip to content

Commit f06c87a

Browse files
committed
feat(admin): the overview counts the open alerts in one banner, and the sidebar marks the Alerts tab
1 parent 51b2d38 commit f06c87a

10 files changed

Lines changed: 173 additions & 39 deletions

File tree

‎apps/auth-service/src/admin/overview/mod.rs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@ impl Rate {
5959
/// What needs an administrator's attention.
6060
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6161
pub enum Problem {
62+
/// Alerts are open: nobody posted an update on them yet.
63+
OpenAlerts(u64),
6264
/// Far more sign-ins failed in the last hour than usually do.
6365
FailedSignIns(Rate),
6466
/// Messages wait to be delivered, the oldest for longer than they should.
@@ -91,6 +93,8 @@ pub struct Overview {
9193
pub newest: Vec<User>,
9294
/// The emails waiting to be sent.
9395
pub email_backlog: DeliveryBacklog,
96+
/// How many alerts are open.
97+
pub open_alerts: u64,
9498
/// When it was read.
9599
pub now: DateTime<Utc>,
96100
}
@@ -100,6 +104,9 @@ impl Overview {
100104
#[must_use]
101105
pub fn problems(&self) -> Vec<Problem> {
102106
let mut problems = Vec::new();
107+
if self.open_alerts > 0 {
108+
problems.push(Problem::OpenAlerts(self.open_alerts));
109+
}
103110
if self.failed_sign_ins.spikes() {
104111
problems.push(Problem::FailedSignIns(self.failed_sign_ins));
105112
}
@@ -117,7 +124,8 @@ impl Overview {
117124

118125
impl AdminService {
119126
/// Reads the overview: the last hour's rates against the week's, what is
120-
/// signed in now, the newest events and accounts, and the email backlog.
127+
/// signed in now, the newest events and accounts, the email backlog and the
128+
/// open alerts.
121129
///
122130
/// # Errors
123131
/// Fails when the operator may not read, or a query fails.
@@ -148,6 +156,7 @@ impl AdminService {
148156
events: newest_events,
149157
newest: self.database.users().newest(NEWEST_SHOWN).await?,
150158
email_backlog: self.database.deliveries().backlog::<Email>().await?,
159+
open_alerts: self.database.alerts().open_count().await?,
151160
now,
152161
})
153162
}

‎apps/auth-service/src/web/admin/alerts.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,9 @@ pub(super) async fn update(cx: &Cx, form: Option<Form<UpdateForm>>) -> Result<Re
9494
};
9595
service
9696
.update_alert(&admin.operator, id, input.status, note)
97-
.await
97+
.await?;
98+
App::forget_attention(cx);
99+
Ok::<_, AdminError>(())
98100
})
99101
.await?;
100102
let (status, note) = refused.as_ref().map_or((None, ""), |refused| {

‎apps/auth-service/src/web/admin/mod.rs‎

Lines changed: 86 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ mod users;
5959
use crate::{
6060
AdminError, AdminService, AuthConfig, KeyStore, MAX_DASHBOARD_BODY_BYTES,
6161
account::{AccountError, AccountService},
62-
admin::{AdminOperation, DashboardSignIn, SignedInAdmin},
62+
admin::{AdminOperation, DashboardSignIn, Overview, Problem, SignedInAdmin},
6363
assets::EmbeddedAssets,
6464
config::{DashboardConfig, PolicyLinks},
6565
federation::ReturnTo,
@@ -103,9 +103,59 @@ use topcoat::{
103103
/// shown: showing it asks for a confirmation this much newer than the service
104104
/// needs.
105105
const FORM_TIME: Duration = Duration::minutes(2);
106-
/// How long every page shows the health the overview last found, before a page
106+
/// How long every page shows what the overview last found, before a page
107107
/// reads it again: the status bar must not cost each page the overview's queries.
108-
const HEALTH_FOR: StdDuration = StdDuration::from_secs(60);
108+
const ATTENTION_FOR: StdDuration = StdDuration::from_secs(60);
109+
110+
/// What the overview last found, as every page shows it: the status bar's
111+
/// count, and the tabs the sidebar marks.
112+
#[derive(Clone, Copy, Default)]
113+
pub(super) struct Attention {
114+
/// How many things need attention: each open alert, and each other problem.
115+
count: u32,
116+
/// Whether alerts are open, which marks the Alerts tab.
117+
alerts: bool,
118+
/// Whether the overview found another problem, which marks its own tab.
119+
overview: bool,
120+
}
121+
122+
impl Attention {
123+
/// What `overview` found.
124+
fn of(overview: &Overview) -> Self {
125+
let others = overview
126+
.problems()
127+
.iter()
128+
.filter(|problem| !matches!(problem, Problem::OpenAlerts(_)))
129+
.count();
130+
let count = u32::try_from(overview.open_alerts)
131+
.unwrap_or(u32::MAX)
132+
.saturating_add(u32::try_from(others).unwrap_or(u32::MAX));
133+
Self {
134+
count,
135+
alerts: overview.open_alerts > 0,
136+
overview: others > 0,
137+
}
138+
}
139+
140+
/// The status bar's health.
141+
const fn health(self) -> Health {
142+
match self.count {
143+
0 => Health::Normal,
144+
count => Health::Warnings(count),
145+
}
146+
}
147+
148+
/// The tabs the sidebar marks.
149+
fn tabs(self) -> Vec<DashboardTab> {
150+
[
151+
(self.overview, DashboardTab::Overview),
152+
(self.alerts, DashboardTab::Alerts),
153+
]
154+
.into_iter()
155+
.filter_map(|(marked, tab)| marked.then_some(tab))
156+
.collect()
157+
}
158+
}
109159

110160
/// The dashboard's pages, and what every one of them needs.
111161
#[derive(Clone)]
@@ -136,8 +186,8 @@ pub(crate) struct AdminApplication {
136186
policy: HeaderValue,
137187
/// Piquel's policies on piquel.fr, which every page's footer links.
138188
policies: PolicyLinks,
139-
/// The health the overview last found, and when, shared by every page.
140-
health: Arc<Mutex<Option<(Instant, Health)>>>,
189+
/// What the overview last found, and when, shared by every page.
190+
attention: Arc<Mutex<Option<(Instant, Attention)>>>,
141191
}
142192

143193
/// What a page answers in its place, such as the redirect through auth's handoff
@@ -247,7 +297,7 @@ impl AdminApplication {
247297
kek: config.key_encryption_key.clone(),
248298
policy: HeaderValue::try_from(policy)?,
249299
policies: config.oidc.policies.clone(),
250-
health: Arc::default(),
300+
attention: Arc::default(),
251301
})
252302
}
253303

@@ -572,44 +622,50 @@ struct SearchQuery {
572622

573623
impl AdminApplication {
574624
/// Whether the service needs attention, as the overview last found, read
575-
/// again once that is [`HEALTH_FOR`] old. A browser that is not signed in
625+
/// again once that is [`ATTENTION_FOR`] old. A browser that is not signed in
576626
/// learns nothing, and neither does a page whose read fails: the status bar
577627
/// never costs the page, so a failed read is logged and shows as normal.
578-
async fn health(cx: &Cx) -> Health {
628+
async fn attention(cx: &Cx) -> Attention {
579629
let app = Self::of(cx);
580630
let Ok(admin) = Self::admin(cx).await else {
581-
return Health::Normal;
631+
return Attention::default();
582632
};
583633
let cached = app
584-
.health
634+
.attention
585635
.lock()
586636
.unwrap_or_else(PoisonError::into_inner)
587-
.filter(|(read, _)| read.elapsed() < HEALTH_FOR)
588-
.map(|(_, health)| health);
589-
if let Some(health) = cached {
590-
return health;
637+
.filter(|(read, _)| read.elapsed() < ATTENTION_FOR)
638+
.map(|(_, attention)| attention);
639+
if let Some(attention) = cached {
640+
return attention;
591641
}
592642
match app.service.overview(&admin.operator).await {
593-
Ok(overview) => Self::remember_health(cx, &overview),
643+
Ok(overview) => Self::remember_attention(cx, &overview),
594644
Err(error) => {
595645
tracing::warn!(error = %ErrorChain(&error), "the health check failed");
596-
Health::Normal
646+
Attention::default()
597647
}
598648
}
599649
}
600650

601-
/// Keeps what `overview` found as the health every page shows for the next
602-
/// [`HEALTH_FOR`], and says what that is.
603-
pub(super) fn remember_health(cx: &Cx, overview: &crate::admin::Overview) -> Health {
604-
let health = match u32::try_from(overview.problems().len()).unwrap_or(u32::MAX) {
605-
0 => Health::Normal,
606-
count => Health::Warnings(count),
607-
};
651+
/// Keeps what `overview` found as what every page shows for the next
652+
/// [`ATTENTION_FOR`], and says what that is.
653+
pub(super) fn remember_attention(cx: &Cx, overview: &Overview) -> Attention {
654+
let attention = Attention::of(overview);
655+
*Self::of(cx)
656+
.attention
657+
.lock()
658+
.unwrap_or_else(PoisonError::into_inner) = Some((Instant::now(), attention));
659+
attention
660+
}
661+
662+
/// Forgets what every page shows, so the next page reads it again: an
663+
/// administrator's own change, such as an update on an alert, shows at once.
664+
pub(super) fn forget_attention(cx: &Cx) {
608665
*Self::of(cx)
609-
.health
666+
.attention
610667
.lock()
611-
.unwrap_or_else(PoisonError::into_inner) = Some((Instant::now(), health));
612-
health
668+
.unwrap_or_else(PoisonError::into_inner) = None;
613669
}
614670

615671
/// Each tab's page, in the sidebar's order.
@@ -750,7 +806,8 @@ impl AdminApplication {
750806
});
751807
// The avatar leads to the administrator's own settings, on auth.
752808
let me = app.auth.join(routes::page::settings::HOME);
753-
let health = Self::health(cx).await;
809+
let attention = Self::attention(cx).await;
810+
let marked = attention.tabs();
754811
let environment = app.auth.host();
755812
let dashboard = Dashboard {
756813
title,
@@ -766,7 +823,8 @@ impl AdminApplication {
766823
preferences: BrowserCookie::read_preferences(headers(cx)),
767824
preferences_action: prefer,
768825
here,
769-
health: Some(health),
826+
health: Some(attention.health()),
827+
attention: &marked,
770828
environment,
771829
policies: app.policies.links(),
772830
search: Search {

‎apps/auth-service/src/web/admin/overview.rs‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! The dashboard's overview, at `/`: what needs attention, the last hour's
22
//! numbers against the week's, the newest events and the newest accounts.
33
4-
use super::{AdminApplication as App, deliveries, lists, users};
4+
use super::{AdminApplication as App, alerts, deliveries, lists, users};
55
use crate::admin::{Kinds, Problem};
66
use piquel_common::admin::EventSearch;
77
use piquel_ui::{AdminOverview, Measure, Query};
@@ -18,7 +18,7 @@ pub(super) async fn overview(cx: &Cx) -> Result<Response> {
1818
let admin = App::admin(cx).await?;
1919
let service = &App::of(cx).service;
2020
let overview = service.overview(&admin.operator).await?;
21-
App::remember_health(cx, &overview);
21+
App::remember_attention(cx, &overview);
2222
let administrators: Vec<_> = service
2323
.list_administrators(&admin.operator)
2424
.await?
@@ -32,10 +32,15 @@ pub(super) async fn overview(cx: &Cx) -> Result<Response> {
3232
}
3333
.on(&events_page)?;
3434
let queue = href!(deliveries::list).resolve(cx);
35+
let alerts = href!(alerts::list).resolve(cx);
3536
let problems: Vec<_> = overview
3637
.problems()
3738
.into_iter()
3839
.map(|problem| match problem {
40+
Problem::OpenAlerts(count) => piquel_ui::Problem::OpenAlerts {
41+
count,
42+
alerts: &alerts,
43+
},
3944
Problem::FailedSignIns(rate) => piquel_ui::Problem::FailedSignIns {
4045
count: rate.last_hour,
4146
usual: rate.usual,

‎apps/auth-service/src/web/admin/tests.rs‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1864,9 +1864,9 @@ async fn announcements_are_drafted_then_sent_from_the_dashboard() {
18641864
}
18651865

18661866
/// The Alerts page shows an open alert as needing attention, with posting an
1867-
/// update on it. An update is recorded as the administrator's, and the alert
1868-
/// then shows its status and note. The alerts that cleared are on a page of
1869-
/// their own.
1867+
/// update on it, and the overview's banner leads there. An update is recorded
1868+
/// as the administrator's, and the alert then shows its status and note. The
1869+
/// alerts that cleared are on a page of their own.
18701870
#[tokio::test]
18711871
#[ignore = "requires TEST_DATABASE_URL"]
18721872
async fn alerts_take_updates_from_the_dashboard() {
@@ -1909,6 +1909,10 @@ async fn alerts_take_updates_from_the_dashboard() {
19091909
assert!(page.contains(&format!(r#"action="{update}""#)), "{page}");
19101910
assert!(page.contains(&position.to_string()), "{page}");
19111911
assert!(page.contains("Needs attention"), "{page}");
1912+
// Other tests' alerts may be open too, so only the banner's presence is
1913+
// checked, not its count.
1914+
let overview = html(harness.visit(&dashboard, "/").await).await;
1915+
assert!(overview.contains("See the alerts"), "{overview}");
19121916

19131917
let url = format!("{DASHBOARD}{update}");
19141918
let fields = [("status", "fixing"), ("note", "Restoring from backup")];

‎crates/database/.sqlx/query-c05223f483ef3519e27dbd3f6b37147198e5bf052fee72de31cdf2a31f5fa0ce.json‎

Lines changed: 20 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/database/src/repositories/alerts.rs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,4 +320,21 @@ impl AlertRepository<'_> {
320320
)?;
321321
rows.into_iter().map(UpdateRow::decode).collect()
322322
}
323+
324+
/// How many alerts are open: current, and with no update posted on them.
325+
///
326+
/// # Errors
327+
///
328+
/// Returns [`DatabaseError`] if the query fails.
329+
pub async fn open_count(&mut self) -> Result<u64, DatabaseError> {
330+
let count = run!(
331+
self,
332+
fetch_one,
333+
sqlx::query_scalar!(
334+
r#"SELECT count(*) AS "count!" FROM alerts
335+
WHERE cleared_at IS NULL AND acknowledged_at IS NULL"#,
336+
)
337+
)?;
338+
Ok(count.try_into().unwrap_or_default())
339+
}
323340
}

‎crates/ui/src/admin/mod.rs‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,8 @@ pub struct Dashboard<'a> {
210210
pub here: &'a str,
211211
/// Whether the service needs attention, as the overview finds, if known.
212212
pub health: Option<Health>,
213+
/// The tabs whose pages need attention, which the sidebar marks.
214+
pub attention: &'a [Tab],
213215
/// The deployment the status bar names.
214216
pub environment: &'a str,
215217
/// Piquel's policies, which the status bar links.
@@ -254,9 +256,6 @@ pub async fn dashboard_frame<'a>(
254256
dashboard: &'a Dashboard<'a>,
255257
child: Child<'_>,
256258
) -> Result<impl View> {
257-
let warning = dashboard
258-
.health
259-
.is_some_and(|health| health != Health::Normal);
260259
let items: Vec<_> = dashboard
261260
.tabs
262261
.iter()
@@ -265,7 +264,7 @@ pub async fn dashboard_frame<'a>(
265264
label: tab.label(),
266265
href,
267266
current: dashboard.current == Some(*tab),
268-
warning: warning && *tab == Tab::Overview,
267+
warning: dashboard.attention.contains(tab),
269268
count: None,
270269
})
271270
.collect();

‎crates/ui/src/admin/overview.rs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,13 @@ use topcoat::{
1515
/// Something that needs an administrator's attention.
1616
#[derive(Clone, Debug, PartialEq, Eq)]
1717
pub enum Problem<'a> {
18+
/// Alerts are open: nobody posted an update on them yet.
19+
OpenAlerts {
20+
/// How many.
21+
count: u64,
22+
/// The alerts.
23+
alerts: &'a str,
24+
},
1825
/// Far more sign-ins failed in the last hour than usually do.
1926
FailedSignIns {
2027
/// How many failed in the last hour.
@@ -202,6 +209,16 @@ pub async fn admin_overview<'a>(overview: AdminOverview<'a>) -> Result<impl View
202209
async fn problem_notice<'a>(problem: &'a Problem<'a>) -> Result<impl View> {
203210
Ok(view! {
204211
match problem {
212+
Problem::OpenAlerts { count, alerts } => {
213+
<section class="notice warning" role="alert">
214+
icon(kind: Icon::Warning)
215+
<div class="text">
216+
<strong>(if *count == 1 { "1 alert needs attention".to_owned() } else { format!("{count} alerts need attention") })</strong>
217+
<small>(if *count == 1 { "Nobody has posted an update on it yet." } else { "Nobody has posted an update on them yet." })</small>
218+
</div>
219+
<a class="button secondary small" href=(*alerts)>"See the alerts"</a>
220+
</section>
221+
},
205222
Problem::FailedSignIns { count, usual, events } => {
206223
<section class="notice warning" role="alert">
207224
icon(kind: Icon::Warning)

0 commit comments

Comments
 (0)