Skip to main content

fedimint_server_ui/dashboard/
availability.rs

1//! Local observations, deliberately separate from live connectivity and from
2//! the client-side, Byzantine-bounded merged estimate.
3use std::collections::BTreeMap;
4use std::time::Duration;
5
6use axum::extract::State;
7use axum::response::Html;
8use fedimint_core::PeerId;
9use fedimint_core::peer_availability::{PEER_AVAILABILITY_WINDOWS_SECS, WindowAvailability};
10use fedimint_server_core::dashboard_ui::{DashboardPeerAvailability, DynDashboardApi};
11use fedimint_ui_common::UiState;
12use fedimint_ui_common::auth::UserAuth;
13use maud::{Markup, html};
14
15pub(crate) const ROUTE: &str = "/ui/peer-availability";
16// Persistence is every ten minutes. Allow one missed interval before marking
17// the snapshot stale; this is not a peer-offline threshold.
18const STALE_AFTER_SECS: u64 = 20 * 60;
19
20pub(crate) fn loading() -> Markup {
21    html! {
22        section class="card" id="peer-availability"
23            hx-get=(ROUTE) hx-trigger="load" hx-swap="outerHTML" {
24            div class="card-header dashboard-header" { "Observed availability" }
25            div class="card-body" {
26                p class="mb-0" role="status" {
27                    "Loading observations… Reload to retry."
28                }
29            }
30        }
31    }
32}
33
34pub(crate) async fn view(
35    State(state): State<UiState<DynDashboardApi>>,
36    _auth: UserAuth,
37) -> Html<String> {
38    let result = tokio::time::timeout(Duration::from_secs(5), async {
39        (
40            state.api.guardian_id().await,
41            state.api.guardian_names().await,
42            state.api.peer_availability().await,
43        )
44    })
45    .await;
46    let now = fedimint_core::time::duration_since_epoch().as_secs();
47    Html(
48        match result {
49            Ok((identity, names, snapshot)) => render(identity, &names, snapshot.as_ref(), now),
50            Err(_) => unavailable(),
51        }
52        .into_string(),
53    )
54}
55
56fn header() -> Markup {
57    let explanation = "Local consensus activity · exponential averages, not uptime. This guardian’s observations, not the federation’s merged estimate. Idle or locally isolated periods are excluded; these values do not prove a peer is online.";
58    html! {
59        div class="card-header dashboard-header d-flex flex-wrap gap-2 justify-content-between align-items-center" {
60            div {
61                "Observed availability "
62                details class="availability-details d-inline-block align-top text-muted" {
63                    summary title=(explanation) aria-label="About observed availability" {
64                        span class="border border-secondary rounded-circle d-inline-block text-center small"
65                            style="width: 1.2em; line-height: 1.2em;" aria-hidden="true" { "i" }
66                    }
67                    span class="d-block small fw-normal" style="max-width: 28rem;" {
68                        (explanation)
69                    }
70                }
71            }
72        }
73    }
74}
75
76fn unavailable() -> Markup {
77    html! {
78        section class="card" id="peer-availability" {
79            (header())
80            div class="card-body" {
81                div class="alert alert-warning mb-0" role="status" {
82                    "Observations unavailable. Reload to retry."
83                }
84            }
85        }
86    }
87}
88
89fn timestamp(secs: u64) -> String {
90    i64::try_from(secs)
91        .ok()
92        .and_then(|secs| chrono::DateTime::from_timestamp(secs, 0))
93        .map_or_else(
94            || "Unknown timestamp".to_owned(),
95            |time| time.format("%Y-%m-%d %H:%M:%S UTC").to_string(),
96        )
97}
98
99fn percentage(bps: u16) -> String {
100    format!("{}.{:02}%", bps / 100, bps % 100)
101}
102
103fn relative_time(age_secs: u64) -> String {
104    let (value, unit) = match age_secs {
105        0..60 => (age_secs, "s"),
106        60..3600 => (age_secs / 60, "m"),
107        3600..86400 => (age_secs / 3600, "h"),
108        _ => (age_secs / 86400, "d"),
109    };
110    format!("{value}{unit} ago")
111}
112
113fn window(snapshot: &DashboardPeerAvailability, index: usize) -> Option<&WindowAvailability> {
114    snapshot
115        .report
116        .windows
117        .get(index)
118        .filter(|window| window.window_secs == PEER_AVAILABILITY_WINDOWS_SECS[index])
119}
120
121fn peer_score(window: &WindowAvailability, peer: PeerId) -> Option<u16> {
122    let coverage = window
123        .peer_coverage_bps
124        .get(&peer)
125        .copied()
126        .unwrap_or(window.coverage_bps);
127    window
128        .peers
129        .get(&peer)
130        .copied()
131        .filter(|value| *value <= 10_000 && (1..=10_000).contains(&coverage))
132}
133
134fn render(
135    identity: PeerId,
136    names: &BTreeMap<PeerId, String>,
137    snapshot: Option<&DashboardPeerAvailability>,
138    now: u64,
139) -> Markup {
140    let stale = snapshot.is_some_and(|snapshot| {
141        snapshot.updated_at_secs == 0
142            || snapshot.updated_at_secs > now
143            || now - snapshot.updated_at_secs > STALE_AFTER_SECS
144    });
145    html! {
146        section class="card" id="peer-availability" {
147            (header())
148            div class="card-body" {
149                @if snapshot.is_some() {
150                    @if stale {
151                        div class="alert alert-warning py-2 mb-2" role="status" {
152                            "Stale snapshot · historical values only."
153                        }
154                    }
155                } @else {
156                    div class="alert alert-secondary py-2 mb-2" role="status" {
157                        "Awaiting observations · first save after ≥10 min."
158                    }
159                }
160                div class="table-responsive" {
161                    table class="table table-sm table-striped text-nowrap align-middle mb-0" {
162                        thead {
163                            tr {
164                                th scope="col" { "Guardian" }
165                                @for (index, label) in ["7-day EMA", "30-day EMA"].iter().enumerate() {
166                                    th scope="col" {
167                                        (label)
168                                        div class="small text-muted fw-normal"
169                                            title="Coverage: decayed observation weight, not elapsed time. Low coverage means limited evidence, even at 100% activity." {
170                                            "Coverage "
171                                            br class="d-sm-none";
172                                            @if let Some(window) = snapshot.and_then(|snapshot| window(snapshot, index))
173                                                .filter(|window| (1..=10_000).contains(&window.coverage_bps)) {
174                                                (percentage(window.coverage_bps))
175                                            } @else {
176                                                "—"
177                                            }
178                                        }
179                                    }
180                                }
181                                th scope="col" { "Last message" }
182                            }
183                        }
184                        tbody {
185                            @for (peer, name) in names {
186                                tr {
187                                    th scope="row" {
188                                        (name) " "
189                                        span class="text-muted fw-normal" { "#" (peer.to_string()) }
190                                        @if *peer == identity {
191                                            span class="badge bg-secondary ms-1" { "Self" }
192                                        }
193                                    }
194                                    @for index in 0..2 {
195                                        td {
196                                            @if *peer == identity {
197                                                span class="text-muted" title="This guardian is not measured" { "—" }
198                                            } @else if let Some((window, value)) = snapshot
199                                                .and_then(|snapshot| window(snapshot, index))
200                                                .and_then(|window| peer_score(window, *peer).map(|value| (window, value))) {
201                                                div class="small mb-1" {
202                                                    (percentage(value))
203                                                }
204                                                div class="progress" style="height: 6px; min-width: 5rem;"
205                                                    role="progressbar" aria-label="Observed consensus activity"
206                                                    aria-valuenow=(percentage(value).trim_end_matches('%'))
207                                                    aria-valuemin="0" aria-valuemax="100" {
208                                                    div class=(if stale { "progress-bar bg-secondary" } else { "progress-bar" })
209                                                        style=(format!("width: {}", percentage(value))) {}
210                                                }
211                                                @if let Some(coverage) = window.peer_coverage_bps.get(peer) {
212                                                    div class="small text-muted"
213                                                        title="Observation coverage since this peer’s reset; overrides the shared header coverage." {
214                                                        "Coverage " (percentage(*coverage)) " since reset"
215                                                    }
216                                                }
217                                            } @else {
218                                                span class="text-muted" { "No data" }
219                                            }
220                                        }
221                                    }
222                                    td class="small" {
223                                        @if *peer == identity {
224                                            span class="text-muted" title="This guardian is not measured" { "—" }
225                                        } @else if let Some(seen) = snapshot
226                                            .and_then(|snapshot| snapshot.report.last_seen_secs.get(peer))
227                                            .filter(|seen| **seen > 0 && **seen <= now) {
228                                            details class="availability-details" {
229                                                summary title=(timestamp(*seen)) { (relative_time(now - *seen)) }
230                                                span class="d-block" {
231                                                    (timestamp(*seen))
232                                                }
233                                            }
234                                        } @else {
235                                            span class="text-muted" { "Unknown" }
236                                        }
237                                    }
238                                }
239                            }
240                        }
241                    }
242                }
243            }
244        }
245    }
246}
247
248#[cfg(test)]
249mod tests;