Skip to main content

runnerd_core/api/insights/
shown.rs

1//! What insights and the digest mean as every client shows them: each insight's labels and tone, how many warn,
2//! the window they come from, what the page says without any, and the digest's lines. Plain derivations of
3//! [`Insights`] and [`Digest`]; the dashboard, `runnerctl`, the TUI and notifications only lay them out.
4
5use super::{
6    Digest, HostHazard, HostSpan, Insight, InsightKind, Insights, LongWait, Severity, WaitSpread,
7};
8use crate::api::units::short_date;
9use crate::api::{HostMemory, Tone, duration};
10use crate::config::ByteSize;
11use std::fmt::Write as _;
12
13impl InsightKind {
14    /// Its name as a label: `Slower`, `Flaky`, `Near its cap`, `Cold cache`, `Memory pressure`, `CPU cap`,
15    /// `Host memory`, `Host low`, `Waits`, or `Insight` for a kind from a later release.
16    pub fn label(&self) -> &'static str {
17        match self {
18            InsightKind::Slower { .. } => "Slower",
19            InsightKind::Flaky { .. } => "Flaky",
20            InsightKind::NearCap { .. } => "Near its cap",
21            InsightKind::ColdCache { .. } => "Cold cache",
22            InsightKind::Throttled { .. } => "Memory pressure",
23            InsightKind::CpuHeld { .. } => "CPU cap",
24            InsightKind::HostHeld { .. } => "Host memory",
25            InsightKind::HostLow { .. } => "Host low",
26            InsightKind::Waits { .. } => "Waits",
27            InsightKind::Unknown => "Insight",
28        }
29    }
30
31    /// Its name as one word, the API's `kind`: `slower`, `flaky`, `near-cap`, `cold-cache`, `throttled`,
32    /// `cpu-held`, `host-held`, `host-low` or `waits`; `unknown` for a kind from a later release.
33    pub fn word(&self) -> &'static str {
34        match self {
35            InsightKind::Slower { .. } => "slower",
36            InsightKind::Flaky { .. } => "flaky",
37            InsightKind::NearCap { .. } => "near-cap",
38            InsightKind::ColdCache { .. } => "cold-cache",
39            InsightKind::Throttled { .. } => "throttled",
40            InsightKind::CpuHeld { .. } => "cpu-held",
41            InsightKind::HostHeld { .. } => "host-held",
42            InsightKind::HostLow { .. } => "host-low",
43            InsightKind::Waits { .. } => "waits",
44            InsightKind::Unknown => "unknown",
45        }
46    }
47}
48
49impl Insight {
50    /// What a [`HostHeld`](InsightKind::HostHeld) insight says: `3 jobs wait for the host's memory, the longest for
51    /// 42m 10s (halyard/api: CI / build); programs outside CI hold 30G, most java 9.3G and claude 5.1G. Closing programs
52    /// frees only part of that.` `longest` names the job that waited longest; `memory` is the
53    /// reading that names who holds the memory. The part the programs named leave is the kernel, compressed swap and
54    /// the many small programs, so the sentence never says closing them frees the whole figure.
55    pub fn host_held_sentence(
56        jobs: u32,
57        waited: u64,
58        longest: &str,
59        memory: &HostMemory,
60    ) -> String {
61        let who = if jobs == 1 {
62            "1 job waits".to_owned()
63        } else {
64            format!("{jobs} jobs wait")
65        };
66        format!(
67            "{who} for the host's memory, the longest for {} ({longest}); {}. Closing programs frees only part of \
68             that.",
69            duration(waited),
70            memory.outside_line()
71        )
72    }
73}
74
75impl Severity {
76    /// `warning` or `notice`.
77    pub fn label(self) -> &'static str {
78        match self {
79            Severity::Warning => "warning",
80            Severity::Notice => "notice",
81        }
82    }
83}
84
85impl Insight {
86    /// What it means for the reader, by its severity alone, whatever its kind: a warning is worth a look, a notice
87    /// a plain fact.
88    pub fn tone(&self) -> Tone {
89        match self.severity {
90            Severity::Warning => Tone::Warn,
91            Severity::Notice => Tone::Neutral,
92        }
93    }
94}
95
96impl Insights {
97    /// How many insights warn.
98    pub fn warning_count(&self) -> usize {
99        self.insights
100            .iter()
101            .filter(|insight| insight.severity == Severity::Warning)
102            .count()
103    }
104
105    /// How many insights warn, worded for the overview: `3 insights`; `None` when none does.
106    pub fn warning_line(&self) -> Option<String> {
107        match self.warning_count() {
108            0 => None,
109            1 => Some("1 insight".to_owned()),
110            count => Some(format!("{count} insights")),
111        }
112    }
113
114    /// The whole days its window covers.
115    pub fn days(&self) -> u64 {
116        self.until.saturating_sub(self.since) / 86_400
117    }
118
119    /// Where its insights come from: `from the last 30 days`.
120    pub fn window_line(&self) -> String {
121        format!("from the last {} days", self.days())
122    }
123
124    /// What it says without any insight: `nothing stands out from the last 30 days`.
125    pub fn empty_line(&self) -> String {
126        format!("nothing stands out {}", self.window_line())
127    }
128}
129
130impl WaitSpread {
131    /// `value`, one of its percentiles, when it has jobs to take it over; `None` to show none.
132    pub fn reading(&self, value: Option<u64>) -> Option<u64> {
133        value.filter(|_| self.jobs > 0)
134    }
135}
136
137impl Insight {
138    /// What a [`HostLow`](InsightKind::HostLow) insight says: `On Nov 6 the host had under 6.2G available for 34s while
139    /// a host credit stood, down to 4.1G. The credit lets runners start on memory the running ones may still grow
140    /// into; [host] pooled_count = false makes the budgets count every reservation again.`
141    pub fn host_low_sentence(day: u64, seconds: u64, lowest: u64, line: u64) -> String {
142        format!(
143            "On {} the host had under {} available for {} while a host credit stood, down to {}. The credit lets \
144             runners start on memory the running ones may still grow into; [host] pooled_count = false makes the \
145             budgets count every reservation again.",
146            short_date(day),
147            ByteSize(line),
148            duration(seconds),
149            ByteSize(lowest)
150        )
151    }
152}
153
154impl HostHazard {
155    /// The window in a line: `CI ran 9h 12m, 6h 10m of it on a host credit; under 19.4G available for 1h 04m (41m on
156    /// a credit); under 6.2G available for 34s (34s on a credit); lowest 4.1G (4.5G on a credit); swap free at least
157    /// 8.2G`.
158    /// Without a host credit in it, nothing is said of one.
159    pub fn line(&self) -> String {
160        let credited = self.credited > 0;
161        let share = |seconds: u64| {
162            if credited {
163                format!(" ({} on a credit)", duration(seconds))
164            } else {
165                String::new()
166            }
167        };
168        let under = |line: u64, span: HostSpan| match span.seconds {
169            0 => format!("never under {} available", ByteSize(line)),
170            seconds => format!(
171                "under {} available for {}{}",
172                ByteSize(line),
173                duration(seconds),
174                share(span.credited)
175            ),
176        };
177        let mut line = format!("CI ran {}", duration(self.running));
178        if credited {
179            let _ = write!(line, ", {} of it on a host credit", duration(self.credited));
180        }
181        let _ = write!(
182            line,
183            "; {}; {}; lowest {}",
184            under(self.low_line, self.low),
185            under(self.critical_line, self.critical),
186            ByteSize(self.lowest)
187        );
188        if let Some(lowest) = self.lowest_credited {
189            let _ = write!(line, " ({} on a credit)", ByteSize(lowest));
190        }
191        if let Some(swap) = self.lowest_swap_free {
192            let _ = write!(line, "; swap free at least {}", ByteSize(swap));
193        }
194        line
195    }
196
197    /// The window's UTC day and its line, as `runnerctl insights` and the dashboard list the days: `Nov 6: CI ran …`.
198    pub fn dated_line(&self) -> String {
199        format!("{}: {}", short_date(self.since), self.line())
200    }
201}
202
203impl Digest {
204    /// Its day in a line: `12 jobs finished, 2 failed`, then `, 1 new insight` when some are new.
205    pub fn summary_line(&self) -> String {
206        let jobs = if self.finished == 1 { "job" } else { "jobs" };
207        let line = format!("{} {jobs} finished, {} failed", self.finished, self.failed);
208        match self.new.len() {
209            0 => line,
210            1 => format!("{line}, 1 new insight"),
211            new => format!("{line}, {new} new insights"),
212        }
213    }
214
215    /// The host's memory over its day in a line, `Host memory while CI ran: CI ran …`, or nothing when CI did not
216    /// run.
217    pub fn host_line(&self) -> Option<String> {
218        self.host
219            .as_ref()
220            .map(|host| format!("Host memory while CI ran: {}.", host.line()))
221    }
222}
223
224impl LongWait {
225    /// It in a line: `halyard/api CI / test waited 1m 30s`, or `halyard/api job 7 waited 1m 30s` until the daemon
226    /// knows the job's name.
227    pub fn line(&self) -> String {
228        format!(
229            "{} {} waited {}",
230            self.repository,
231            crate::api::job_title(self.workflow.as_deref(), &self.name, Some(self.job)),
232            duration(self.waited)
233        )
234    }
235}
236
237#[cfg(test)]
238mod tests;