use super::{
Digest, HostHazard, HostSpan, Insight, InsightKind, Insights, LongWait, RepositoryWaits,
Severity, WaitSpread,
};
use crate::api::units::short_date;
use crate::api::{HostMemory, Tone, duration};
use crate::config::ByteSize;
use std::fmt::Write as _;
impl InsightKind {
pub fn label(&self) -> &'static str {
match self {
InsightKind::Slower { .. } => "Slower",
InsightKind::Flaky { .. } => "Flaky",
InsightKind::NearCap { .. } => "Near its cap",
InsightKind::ColdCache { .. } => "Cold cache",
InsightKind::Throttled { .. } => "Memory pressure",
InsightKind::CpuHeld { .. } => "CPU cap",
InsightKind::HostHeld { .. } => "Host memory",
InsightKind::HostLow { .. } => "Host low",
InsightKind::Waits { .. } => "Waits",
InsightKind::Unknown => "Insight",
}
}
pub fn word(&self) -> &'static str {
match self {
InsightKind::Slower { .. } => "slower",
InsightKind::Flaky { .. } => "flaky",
InsightKind::NearCap { .. } => "near-cap",
InsightKind::ColdCache { .. } => "cold-cache",
InsightKind::Throttled { .. } => "throttled",
InsightKind::CpuHeld { .. } => "cpu-held",
InsightKind::HostHeld { .. } => "host-held",
InsightKind::HostLow { .. } => "host-low",
InsightKind::Waits { .. } => "waits",
InsightKind::Unknown => "unknown",
}
}
}
impl Insight {
pub fn host_held_sentence(
jobs: u32,
waited: u64,
longest: &str,
memory: &HostMemory,
) -> String {
let who = if jobs == 1 {
"1 job waits".to_owned()
} else {
format!("{jobs} jobs wait")
};
format!(
"{who} for the host's memory, the longest for {} ({longest}); {}. Closing programs frees only part of \
that.",
duration(waited),
memory.outside_line()
)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InsightFigure {
pub value: String,
pub label: String,
}
impl Insight {
pub fn figure(&self) -> Option<InsightFigure> {
let figure = |value: String, label: String| Some(InsightFigure { value, label });
let of = |part: u32, whole: u32| format!("{part} of {whole}");
match &self.kind {
InsightKind::Slower { before, now, .. } => {
figure(duration(*now), format!("from {}", duration(*before)))
}
InsightKind::Flaky { flaky, total } => {
figure(of(*flaky, *total), "runs passed on a re-run".to_owned())
}
InsightKind::NearCap {
profile, peak, cap, ..
} => figure(
ByteSize(*peak).to_string(),
format!("p95 peak, of {profile}'s {}", ByteSize(*cap)),
),
InsightKind::ColdCache { hits, lookups, .. } => {
let percent = (u128::from(*hits) * 100 + u128::from(*lookups) / 2)
/ u128::from((*lookups).max(1));
figure(
format!("{}%", percent.min(100)),
format!("of {lookups} lookups hit"),
)
}
InsightKind::Throttled { throttled, total } => {
figure(of(*throttled, *total), "runs throttled".to_owned())
}
InsightKind::Waits { before, now } => figure(
duration(*now),
format!("p95 wait, from {}", duration(*before)),
),
InsightKind::CpuHeld {
profile,
cpus,
held,
total,
..
} => figure(
of(*held, *total),
format!("runs held back by {profile}'s {cpus} CPUs"),
),
InsightKind::HostHeld { jobs, waited } => figure(
duration(*waited),
if *jobs == 1 {
"1 job waits for the host's memory".to_owned()
} else {
format!("longest of {jobs} waits for the host's memory")
},
),
InsightKind::HostLow { lowest, .. } => figure(
ByteSize(*lowest).to_string(),
"least memory available".to_owned(),
),
InsightKind::Unknown => None,
}
}
}
impl Severity {
pub fn label(self) -> &'static str {
match self {
Severity::Warning => "warning",
Severity::Notice => "notice",
}
}
}
impl Insight {
pub fn tone(&self) -> Tone {
match self.severity {
Severity::Warning => Tone::Warn,
Severity::Notice => Tone::Neutral,
}
}
}
impl Insights {
pub fn warning_count(&self) -> usize {
self.insights
.iter()
.filter(|insight| insight.severity == Severity::Warning)
.count()
}
pub fn heading(&self) -> InsightsHeading {
let count = self.insights.len();
let figure = match count {
0 => "no insights".to_owned(),
1 => "1 insight".to_owned(),
count => format!("{count} insights"),
};
let note = match self.warning_count() {
0 => format!(" {}", self.window_line()),
1 => format!(", 1 warning, {}", self.window_line()),
warnings => format!(", {warnings} warnings, {}", self.window_line()),
};
InsightsHeading { figure, note }
}
pub fn days(&self) -> u64 {
self.until.saturating_sub(self.since) / 86_400
}
pub fn window_line(&self) -> String {
format!("from the last {} days", self.days())
}
pub fn empty_line(&self) -> String {
format!("nothing stands out {}", self.window_line())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InsightsHeading {
pub figure: String,
pub note: String,
}
impl std::fmt::Display for InsightsHeading {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "{}{}", self.figure, self.note)
}
}
impl WaitSpread {
pub fn reading(&self, value: Option<u64>) -> Option<u64> {
value.filter(|_| self.jobs > 0)
}
}
impl Insight {
pub fn host_low_sentence(day: u64, seconds: u64, lowest: u64, line: u64) -> String {
format!(
"On {} the host had under {} available for {} while a host credit stood, down to {}. The credit lets \
runners start on memory the running ones may still grow into; [host] pooled_count = false makes the \
budgets count every reservation again.",
short_date(day),
ByteSize(line),
duration(seconds),
ByteSize(lowest)
)
}
}
impl HostHazard {
pub const TITLE: &'static str = "Host memory while CI ran";
pub fn line(&self) -> String {
let credited = self.credited > 0;
let share = |seconds: u64| {
if credited {
format!(" ({} on a credit)", duration(seconds))
} else {
String::new()
}
};
let under = |line: u64, span: HostSpan| match span.seconds {
0 => format!("never under {} available", ByteSize(line)),
seconds => format!(
"under {} available for {}{}",
ByteSize(line),
duration(seconds),
share(span.credited)
),
};
let mut line = format!("CI ran {}", duration(self.running));
if credited {
let _ = write!(line, ", {} of it on a host credit", duration(self.credited));
}
let _ = write!(
line,
"; {}; {}; lowest {}",
under(self.low_line, self.low),
under(self.critical_line, self.critical),
ByteSize(self.lowest)
);
if let Some(lowest) = self.lowest_credited {
let _ = write!(line, " ({} on a credit)", ByteSize(lowest));
}
if let Some(swap) = self.lowest_swap_free {
let _ = write!(line, "; swap free at least {}", ByteSize(swap));
}
line
}
pub fn dated_line(&self) -> String {
format!("{}: {}", short_date(self.since), self.line())
}
}
impl Digest {
pub fn summary_line(&self) -> String {
let jobs = if self.finished == 1 { "job" } else { "jobs" };
let line = format!("{} {jobs} finished, {} failed", self.finished, self.failed);
match self.new.len() {
0 => line,
1 => format!("{line}, 1 new insight"),
new => format!("{line}, {new} new insights"),
}
}
pub fn host_line(&self) -> Option<String> {
self.host
.as_ref()
.map(|host| format!("{}: {}.", HostHazard::TITLE, host.line()))
}
}
impl LongWait {
pub fn line(&self) -> String {
format!(
"{} {} waited {}",
self.repository,
crate::api::job_title(self.workflow.as_deref(), &self.name, Some(self.job)),
duration(self.waited)
)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WaitFigure {
pub label: &'static str,
pub value: String,
}
impl RepositoryWaits {
pub const TITLE: &'static str = "Waits this week";
pub fn figures(&self) -> Vec<WaitFigure> {
let wait = |spread: &WaitSpread, value: Option<u64>| {
spread
.reading(value)
.map_or_else(|| "–".to_owned(), duration)
};
let now = &self.now;
let before = &self.before.all;
[
(crate::api::JOBS_HEADING, now.all.jobs.to_string()),
("Median", wait(&now.all, now.all.p50)),
("p95", wait(&now.all, now.all.p95)),
("Warm median", wait(&now.warm, now.warm.p50)),
("Cold median", wait(&now.cold, now.cold.p50)),
("p95 the week before", wait(before, before.p95)),
]
.into_iter()
.map(|(label, value)| WaitFigure { label, value })
.collect()
}
}
#[cfg(test)]
mod tests;