use super::{
BuildCacheCounts, BuildCacheStats, CacheKind, CacheVolume, LogSummary, RecordLimits,
RecordNote, RecordRemoval, Records, Tone, period,
};
use crate::config::ByteSize;
pub const RECORDS_NEAR_FULL: u64 = 80;
pub fn records_near_full(bytes: u64, max_total: u64) -> bool {
u128::from(bytes) * 100 >= u128::from(max_total) * u128::from(RECORDS_NEAR_FULL)
}
impl CacheKind {
pub fn description(&self) -> String {
match self {
CacheKind::Snapshot { profile } => format!("{profile} snapshot"),
CacheKind::Slot { profile, slot } => format!("{profile} slot {slot} layer"),
CacheKind::Pnpm => "pnpm store, shared".to_owned(),
CacheKind::Maven => "Maven repository, shared".to_owned(),
CacheKind::Mirror => "Docker Hub mirror".to_owned(),
CacheKind::Build => "build cache, shared".to_owned(),
}
}
pub fn profile(&self) -> Option<&str> {
match self {
CacheKind::Snapshot { profile } | CacheKind::Slot { profile, .. } => Some(profile),
CacheKind::Pnpm | CacheKind::Maven | CacheKind::Mirror | CacheKind::Build => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CacheLimit {
pub limit: u64,
pub over: bool,
pub label: String,
}
impl CacheLimit {
pub fn tone(&self) -> Tone {
if self.over { Tone::Warn } else { Tone::Neutral }
}
}
impl CacheVolume {
pub fn limit_status(&self) -> Option<CacheLimit> {
let limit = self.limit?;
let size = ByteSize(limit);
let label = match self.kind {
CacheKind::Build => format!("trimmed to {size}"),
CacheKind::Snapshot { .. } => format!("started over at its next reseed above {size}"),
CacheKind::Slot { .. } | CacheKind::Pnpm | CacheKind::Maven | CacheKind::Mirror => {
format!("emptied above {size}")
}
};
Some(CacheLimit {
limit,
over: self.bytes > limit,
label,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BuildCacheActivity {
pub counts: BuildCacheCounts,
}
impl BuildCacheCounts {
pub fn activity(&self) -> Option<BuildCacheActivity> {
(self.lookups() > 0 || self.written_bytes > 0 || self.refused > 0)
.then_some(BuildCacheActivity { counts: *self })
}
}
impl BuildCacheActivity {
pub fn lookups_line(&self) -> String {
let counts = &self.counts;
match counts.hit_percent() {
Some(percent) => format!(
"{} of {} lookups hit ({percent}%)",
counts.hits,
counts.lookups()
),
None => "no lookups".to_owned(),
}
}
pub fn served_line(&self) -> String {
format!("{} served", ByteSize(self.counts.read_bytes))
}
pub fn stored_line(&self) -> String {
if self.counts.writer {
format!("{} stored", ByteSize(self.counts.written_bytes))
} else {
"read only".to_owned()
}
}
pub fn refused_line(&self) -> Option<String> {
(self.counts.refused > 0).then(|| format!("{} uploads refused", self.counts.refused))
}
pub fn line(&self) -> String {
let mut parts = vec![self.lookups_line(), self.served_line(), self.stored_line()];
parts.extend(self.refused_line());
parts.join(", ")
}
}
pub const BUILD_CACHE_TOOLS: &str =
"Gradle, sccache, Bazel and Turborepo, and Nx where a workflow opts in";
pub const ACTIONS_CACHE: &str = "GitHub Actions' cache";
pub fn actions_cache_place(served: bool) -> &'static str {
if served {
"served from the build cache on this host, in place of GitHub's"
} else {
"GitHub's, as [caches.build] actions_cache = false sets"
}
}
impl BuildCacheStats {
pub fn actions_cache_line(&self) -> String {
let place = actions_cache_place(self.actions_cache);
if self.actions_cache {
format!(
"{ACTIONS_CACHE}: {place}, and counted with it; [caches.build] actions_cache = false turns it \
off"
)
} else {
format!("{ACTIONS_CACHE}: {place}")
}
}
pub fn week_line(&self) -> String {
let week = &self.week;
let mut parts = match week.hit_percent() {
Some(percent) => vec![
format!("{percent}% of {} lookups hit in 7 days", week.lookups()),
format!("{} served", ByteSize(week.read_bytes)),
],
None => vec!["no lookups in 7 days".to_owned()],
};
if week.activity().is_some() {
parts.push(format!("{} stored", ByteSize(week.written_bytes)));
}
if week.refused > 0 {
parts.push(format!("{} uploads refused", week.refused));
}
format!("{} entries; {}", self.entries, parts.join(", "))
}
}
impl RecordLimits {
pub fn near_full(&self, bytes: u64) -> bool {
records_near_full(bytes, self.max_total)
}
}
impl Records {
pub fn summary(&self) -> String {
match self.pressure() {
Some(pressure) => format!("{}; {pressure}", self.usage()),
None => self.usage(),
}
}
pub fn usage(&self) -> String {
let limits = &self.limits;
let age = match limits.max_age / 86_400 {
1 if limits.max_age == 86_400 => "1 day".to_owned(),
days if days > 1 && limits.max_age.is_multiple_of(86_400) => format!("{days} days"),
_ => period(limits.max_age),
};
format!(
"{} of {} records, {} of {}, each kept {age}",
self.records.len(),
limits.max_count,
ByteSize(self.bytes()),
ByteSize(limits.max_total),
)
}
pub fn pressure(&self) -> Option<&'static str> {
self.limits
.near_full(self.bytes())
.then_some("near max_total, so new ones remove the oldest")
}
pub fn summary_tone(&self) -> Tone {
if self.limits.near_full(self.bytes()) {
Tone::Warn
} else {
Tone::Neutral
}
}
pub fn empty_reason() -> &'static str {
"none kept: a profile with record_failures = true keeps each failed job's runner as a record, to open a \
shell where it failed"
}
pub fn shell_open(&self, job: u64) -> bool {
self.shells.contains(&job)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecordState<'note> {
Skipped {
why: &'note str,
},
Removed {
at: u64,
by: Option<RecordRemoval>,
},
Kept {
bytes: Option<u64>,
},
}
impl RecordNote {
pub fn state(&self) -> RecordState<'_> {
match (&self.skipped, self.removed_at) {
(Some(why), _) => RecordState::Skipped { why },
(None, Some(at)) => RecordState::Removed {
at,
by: self.removed_by,
},
(None, None) => RecordState::Kept { bytes: self.bytes },
}
}
pub fn shell_command(job: u64) -> String {
format!("runnerctl shell {job}")
}
}
impl RecordState<'_> {
pub fn line(&self) -> String {
match self {
RecordState::Skipped { why } => format!("not kept: {why}"),
RecordState::Removed { by, .. } => {
by.map_or_else(|| "removed".to_owned(), |by| by.to_string())
}
RecordState::Kept { bytes: Some(bytes) } => {
format!("record kept, {}", ByteSize(*bytes))
}
RecordState::Kept { bytes: None } => "record kept".to_owned(),
}
}
}
impl LogSummary {
pub fn description(&self) -> String {
let line = format!("{} lines, {}", self.lines, ByteSize(self.bytes));
if self.truncated {
format!("{line}, cut at history.log_max")
} else {
line
}
}
}
#[cfg(test)]
mod tests;