1use super::{
6 BuildCacheCounts, BuildCacheStats, CacheKind, CacheVolume, LogSummary, RecordLimits,
7 RecordNote, RecordRemoval, Records, Tone, period,
8};
9use crate::config::ByteSize;
10
11pub const RECORDS_NEAR_FULL: u64 = 80;
14
15pub fn records_near_full(bytes: u64, max_total: u64) -> bool {
17 u128::from(bytes) * 100 >= u128::from(max_total) * u128::from(RECORDS_NEAR_FULL)
18}
19
20impl CacheKind {
21 pub fn description(&self) -> String {
24 match self {
25 CacheKind::Snapshot { profile } => format!("{profile} snapshot"),
26 CacheKind::Slot { profile, slot } => format!("{profile} slot {slot} layer"),
27 CacheKind::Pnpm => "pnpm store, shared".to_owned(),
28 CacheKind::Maven => "Maven repository, shared".to_owned(),
29 CacheKind::Mirror => "Docker Hub mirror".to_owned(),
30 CacheKind::Build => "build cache, shared".to_owned(),
31 }
32 }
33
34 pub fn profile(&self) -> Option<&str> {
36 match self {
37 CacheKind::Snapshot { profile } | CacheKind::Slot { profile, .. } => Some(profile),
38 CacheKind::Pnpm | CacheKind::Maven | CacheKind::Mirror | CacheKind::Build => None,
39 }
40 }
41}
42
43#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct CacheLimit {
46 pub limit: u64,
48 pub over: bool,
50 pub label: String,
53}
54
55impl CacheLimit {
56 pub fn tone(&self) -> Tone {
58 if self.over { Tone::Warn } else { Tone::Neutral }
59 }
60}
61
62impl CacheVolume {
63 pub fn limit_status(&self) -> Option<CacheLimit> {
65 let limit = self.limit?;
66 let size = ByteSize(limit);
67 let label = match self.kind {
68 CacheKind::Build => format!("trimmed to {size}"),
69 CacheKind::Snapshot { .. } => format!("started over at its next reseed above {size}"),
70 CacheKind::Slot { .. } | CacheKind::Pnpm | CacheKind::Maven | CacheKind::Mirror => {
71 format!("emptied above {size}")
72 }
73 };
74 Some(CacheLimit {
75 limit,
76 over: self.bytes > limit,
77 label,
78 })
79 }
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub struct BuildCacheActivity {
85 pub counts: BuildCacheCounts,
87}
88
89impl BuildCacheCounts {
90 pub fn activity(&self) -> Option<BuildCacheActivity> {
93 (self.lookups() > 0 || self.written_bytes > 0 || self.refused > 0)
94 .then_some(BuildCacheActivity { counts: *self })
95 }
96}
97
98impl BuildCacheActivity {
99 pub fn lookups_line(&self) -> String {
101 let counts = &self.counts;
102 match counts.hit_percent() {
103 Some(percent) => format!(
104 "{} of {} lookups hit ({percent}%)",
105 counts.hits,
106 counts.lookups()
107 ),
108 None => "no lookups".to_owned(),
109 }
110 }
111
112 pub fn served_line(&self) -> String {
114 format!("{} served", ByteSize(self.counts.read_bytes))
115 }
116
117 pub fn stored_line(&self) -> String {
119 if self.counts.writer {
120 format!("{} stored", ByteSize(self.counts.written_bytes))
121 } else {
122 "read only".to_owned()
123 }
124 }
125
126 pub fn refused_line(&self) -> Option<String> {
128 (self.counts.refused > 0).then(|| format!("{} uploads refused", self.counts.refused))
129 }
130
131 pub fn line(&self) -> String {
133 let mut parts = vec![self.lookups_line(), self.served_line(), self.stored_line()];
134 parts.extend(self.refused_line());
135 parts.join(", ")
136 }
137}
138
139pub const BUILD_CACHE_TOOLS: &str =
142 "Gradle, sccache, Bazel and Turborepo, and Nx where a workflow opts in";
143
144pub const ACTIONS_CACHE: &str = "GitHub Actions' cache";
146
147pub fn actions_cache_place(served: bool) -> &'static str {
149 if served {
150 "served from the build cache on this host, in place of GitHub's"
151 } else {
152 "GitHub's, as [caches.build] actions_cache = false sets"
153 }
154}
155
156impl BuildCacheStats {
157 pub fn actions_cache_line(&self) -> String {
161 let place = actions_cache_place(self.actions_cache);
162 if self.actions_cache {
163 format!(
164 "{ACTIONS_CACHE}: {place}, and counted with it; [caches.build] actions_cache = false turns it \
165 off"
166 )
167 } else {
168 format!("{ACTIONS_CACHE}: {place}")
169 }
170 }
171
172 pub fn week_line(&self) -> String {
176 let week = &self.week;
177 let mut parts = match week.hit_percent() {
178 Some(percent) => vec![
179 format!("{percent}% of {} lookups hit in 7 days", week.lookups()),
180 format!("{} served", ByteSize(week.read_bytes)),
181 ],
182 None => vec!["no lookups in 7 days".to_owned()],
183 };
184 if week.activity().is_some() {
185 parts.push(format!("{} stored", ByteSize(week.written_bytes)));
186 }
187 if week.refused > 0 {
188 parts.push(format!("{} uploads refused", week.refused));
189 }
190 format!("{} entries; {}", self.entries, parts.join(", "))
191 }
192}
193
194impl RecordLimits {
195 pub fn near_full(&self, bytes: u64) -> bool {
197 records_near_full(bytes, self.max_total)
198 }
199}
200
201impl Records {
202 pub fn summary(&self) -> String {
205 match self.pressure() {
206 Some(pressure) => format!("{}; {pressure}", self.usage()),
207 None => self.usage(),
208 }
209 }
210
211 pub fn usage(&self) -> String {
213 let limits = &self.limits;
214 let age = match limits.max_age / 86_400 {
216 1 if limits.max_age == 86_400 => "1 day".to_owned(),
217 days if days > 1 && limits.max_age.is_multiple_of(86_400) => format!("{days} days"),
218 _ => period(limits.max_age),
219 };
220 format!(
221 "{} of {} records, {} of {}, each kept {age}",
222 self.records.len(),
223 limits.max_count,
224 ByteSize(self.bytes()),
225 ByteSize(limits.max_total),
226 )
227 }
228
229 pub fn pressure(&self) -> Option<&'static str> {
231 self.limits
232 .near_full(self.bytes())
233 .then_some("near max_total, so new ones remove the oldest")
234 }
235
236 pub fn summary_tone(&self) -> Tone {
238 if self.limits.near_full(self.bytes()) {
239 Tone::Warn
240 } else {
241 Tone::Neutral
242 }
243 }
244
245 pub fn empty_reason() -> &'static str {
248 "none kept: a profile with record_failures = true keeps each failed job's runner as a record, to open a \
249 shell where it failed"
250 }
251
252 pub fn shell_open(&self, job: u64) -> bool {
254 self.shells.contains(&job)
255 }
256}
257
258#[derive(Debug, Clone, Copy, PartialEq, Eq)]
260pub enum RecordState<'note> {
261 Skipped {
263 why: &'note str,
265 },
266 Removed {
268 at: u64,
270 by: Option<RecordRemoval>,
272 },
273 Kept {
275 bytes: Option<u64>,
277 },
278}
279
280impl RecordNote {
281 pub fn state(&self) -> RecordState<'_> {
283 match (&self.skipped, self.removed_at) {
284 (Some(why), _) => RecordState::Skipped { why },
285 (None, Some(at)) => RecordState::Removed {
286 at,
287 by: self.removed_by,
288 },
289 (None, None) => RecordState::Kept { bytes: self.bytes },
290 }
291 }
292
293 pub fn shell_command(job: u64) -> String {
295 format!("runnerctl shell {job}")
296 }
297}
298
299impl RecordState<'_> {
300 pub fn line(&self) -> String {
303 match self {
304 RecordState::Skipped { why } => format!("not kept: {why}"),
305 RecordState::Removed { by, .. } => {
306 by.map_or_else(|| "removed".to_owned(), |by| by.to_string())
307 }
308 RecordState::Kept { bytes: Some(bytes) } => {
309 format!("record kept, {}", ByteSize(*bytes))
310 }
311 RecordState::Kept { bytes: None } => "record kept".to_owned(),
312 }
313 }
314}
315
316impl LogSummary {
317 pub fn description(&self) -> String {
320 let line = format!("{} lines, {}", self.lines, ByteSize(self.bytes));
321 if self.truncated {
322 format!("{line}, cut at history.log_max")
323 } else {
324 line
325 }
326 }
327}
328
329#[cfg(test)]
330mod tests;