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 short_line(&self) -> String {
134 let mut parts = match self.counts.hit_percent() {
135 Some(percent) => vec![format!("{percent}% hit"), self.served_line()],
136 None => vec![self.stored_line()],
137 };
138 parts.extend(self.refused_line());
139 parts.join(", ")
140 }
141
142 pub fn line(&self) -> String {
144 let mut parts = vec![self.lookups_line(), self.served_line(), self.stored_line()];
145 parts.extend(self.refused_line());
146 parts.join(", ")
147 }
148}
149
150pub const BUILD_CACHE_TOOLS: &str =
153 "Gradle, sccache, Bazel and Turborepo, and Nx where a workflow opts in";
154
155pub const ACTIONS_CACHE: &str = "GitHub Actions' cache";
157
158pub fn actions_cache_place(served: bool) -> &'static str {
160 if served {
161 "served from the build cache on this host, in place of GitHub's"
162 } else {
163 "GitHub's, as [caches.build] actions_cache = false sets"
164 }
165}
166
167impl BuildCacheStats {
168 pub fn actions_cache_line(&self) -> String {
172 let place = actions_cache_place(self.actions_cache);
173 if self.actions_cache {
174 format!(
175 "{ACTIONS_CACHE}: {place}, and counted with it; [caches.build] actions_cache = false turns it \
176 off"
177 )
178 } else {
179 format!("{ACTIONS_CACHE}: {place}")
180 }
181 }
182
183 pub fn week_line(&self) -> String {
187 let week = &self.week;
188 let mut parts = match week.hit_percent() {
189 Some(percent) => vec![
190 format!("{percent}% of {} lookups hit in 7 days", week.lookups()),
191 format!("{} served", ByteSize(week.read_bytes)),
192 ],
193 None => vec!["no lookups in 7 days".to_owned()],
194 };
195 if week.activity().is_some() {
196 parts.push(format!("{} stored", ByteSize(week.written_bytes)));
197 }
198 if week.refused > 0 {
199 parts.push(format!("{} uploads refused", week.refused));
200 }
201 format!("{} entries; {}", self.entries, parts.join(", "))
202 }
203}
204
205impl RecordLimits {
206 pub fn near_full(&self, bytes: u64) -> bool {
208 records_near_full(bytes, self.max_total)
209 }
210}
211
212impl Records {
213 pub fn summary(&self) -> String {
216 match self.pressure() {
217 Some(pressure) => format!("{}; {pressure}", self.usage()),
218 None => self.usage(),
219 }
220 }
221
222 pub fn usage(&self) -> String {
224 let limits = &self.limits;
225 let age = match limits.max_age / 86_400 {
227 1 if limits.max_age == 86_400 => "1 day".to_owned(),
228 days if days > 1 && limits.max_age.is_multiple_of(86_400) => format!("{days} days"),
229 _ => period(limits.max_age),
230 };
231 format!(
232 "{} of {} records, {} of {}, each kept {age}",
233 self.records.len(),
234 limits.max_count,
235 ByteSize(self.bytes()),
236 ByteSize(limits.max_total),
237 )
238 }
239
240 pub fn pressure(&self) -> Option<&'static str> {
242 self.limits
243 .near_full(self.bytes())
244 .then_some("near max_total, so new ones remove the oldest")
245 }
246
247 pub fn summary_tone(&self) -> Tone {
249 if self.limits.near_full(self.bytes()) {
250 Tone::Warn
251 } else {
252 Tone::Neutral
253 }
254 }
255
256 pub fn empty_reason() -> &'static str {
259 "none kept: a profile with record_failures = true keeps each failed job's runner as a record, to open a \
260 shell where it failed"
261 }
262
263 pub fn shell_open(&self, job: u64) -> bool {
265 self.shells.contains(&job)
266 }
267}
268
269#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub enum RecordState<'note> {
272 Skipped {
274 why: &'note str,
276 },
277 Removed {
279 at: u64,
281 by: Option<RecordRemoval>,
283 },
284 Kept {
286 bytes: Option<u64>,
288 },
289}
290
291impl RecordNote {
292 pub fn state(&self) -> RecordState<'_> {
294 match (&self.skipped, self.removed_at) {
295 (Some(why), _) => RecordState::Skipped { why },
296 (None, Some(at)) => RecordState::Removed {
297 at,
298 by: self.removed_by,
299 },
300 (None, None) => RecordState::Kept { bytes: self.bytes },
301 }
302 }
303
304 pub fn shell_command(job: u64) -> String {
306 format!("runnerctl shell {job}")
307 }
308}
309
310impl RecordState<'_> {
311 pub fn line(&self) -> String {
314 match self {
315 RecordState::Skipped { why } => format!("not kept: {why}"),
316 RecordState::Removed { by, .. } => {
317 by.map_or_else(|| "removed".to_owned(), |by| by.to_string())
318 }
319 RecordState::Kept { bytes: Some(bytes) } => {
320 format!("record kept, {}", ByteSize(*bytes))
321 }
322 RecordState::Kept { bytes: None } => "record kept".to_owned(),
323 }
324 }
325}
326
327impl LogSummary {
328 pub fn description(&self) -> String {
331 let line = format!("{} lines, {}", self.lines, ByteSize(self.bytes));
332 if self.truncated {
333 format!("{line}, cut at history.log_max")
334 } else {
335 line
336 }
337 }
338}
339
340#[cfg(test)]
341mod tests;