1use super::{
6 BuildCacheCounts, BuildCacheStats, CacheKind, CacheVolume, Check, CheckStatus, LogSummary,
7 RecordLimits, 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
20pub fn records_check(bytes: u64, max_total: u64) -> Check {
23 let taken = format!(
24 "the records of failed jobs take {} of [records] max_total = {}",
25 ByteSize(bytes),
26 ByteSize(max_total)
27 );
28 if records_near_full(bytes, max_total) {
29 Check {
30 name: "records".to_owned(),
31 status: CheckStatus::Warn,
32 detail: format!("{taken}; new ones remove the oldest to fit"),
33 fix: Some(
34 "runnerctl records rm --older-than 2d, or raise max_total under [records]"
35 .to_owned(),
36 ),
37 }
38 } else {
39 Check {
40 name: "records".to_owned(),
41 status: CheckStatus::Info,
42 detail: taken,
43 fix: None,
44 }
45 }
46}
47
48impl CacheKind {
49 pub fn description(&self) -> String {
52 match self {
53 CacheKind::Snapshot { profile } => format!("{profile} snapshot"),
54 CacheKind::Slot { profile, slot } => format!("{profile} slot {slot} layer"),
55 CacheKind::Pnpm => "pnpm store, shared".to_owned(),
56 CacheKind::Maven => "Maven repository, shared".to_owned(),
57 CacheKind::Mirror => "Docker Hub mirror".to_owned(),
58 CacheKind::Build => "build cache, shared".to_owned(),
59 }
60 }
61
62 pub fn profile(&self) -> Option<&str> {
64 match self {
65 CacheKind::Snapshot { profile } | CacheKind::Slot { profile, .. } => Some(profile),
66 CacheKind::Pnpm | CacheKind::Maven | CacheKind::Mirror | CacheKind::Build => None,
67 }
68 }
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct CacheLimit {
74 pub limit: u64,
76 pub over: bool,
78 pub label: String,
81}
82
83impl CacheLimit {
84 pub fn tone(&self) -> Tone {
86 if self.over { Tone::Warn } else { Tone::Neutral }
87 }
88}
89
90impl CacheVolume {
91 pub fn limit_status(&self) -> Option<CacheLimit> {
93 let limit = self.limit?;
94 let size = ByteSize(limit);
95 let label = match self.kind {
96 CacheKind::Build => format!("trimmed to {size}"),
97 CacheKind::Snapshot { .. } => format!("started over at its next reseed above {size}"),
98 CacheKind::Slot { .. } | CacheKind::Pnpm | CacheKind::Maven | CacheKind::Mirror => {
99 format!("emptied above {size}")
100 }
101 };
102 Some(CacheLimit {
103 limit,
104 over: self.bytes > limit,
105 label,
106 })
107 }
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub struct BuildCacheActivity {
113 pub counts: BuildCacheCounts,
115}
116
117impl BuildCacheCounts {
118 pub fn activity(&self) -> Option<BuildCacheActivity> {
121 (self.lookups() > 0 || self.written_bytes > 0 || self.refused > 0)
122 .then_some(BuildCacheActivity { counts: *self })
123 }
124}
125
126impl BuildCacheActivity {
127 pub fn lookups_line(&self) -> String {
129 let counts = &self.counts;
130 match counts.hit_percent() {
131 Some(percent) => format!(
132 "{} of {} lookups hit ({percent}%)",
133 counts.hits,
134 counts.lookups()
135 ),
136 None => "no lookups".to_owned(),
137 }
138 }
139
140 pub fn served_line(&self) -> String {
142 format!("{} served", ByteSize(self.counts.read_bytes))
143 }
144
145 pub fn stored_line(&self) -> String {
147 if self.counts.writer {
148 format!("{} stored", ByteSize(self.counts.written_bytes))
149 } else {
150 "read only".to_owned()
151 }
152 }
153
154 pub fn refused_line(&self) -> Option<String> {
156 (self.counts.refused > 0).then(|| format!("{} uploads refused", self.counts.refused))
157 }
158
159 pub fn short_line(&self) -> String {
162 let mut parts = match self.counts.hit_percent() {
163 Some(percent) => vec![format!("{percent}% hit"), self.served_line()],
164 None => vec![self.stored_line()],
165 };
166 parts.extend(self.refused_line());
167 parts.join(", ")
168 }
169
170 pub fn line(&self) -> String {
172 let mut parts = vec![self.lookups_line(), self.served_line(), self.stored_line()];
173 parts.extend(self.refused_line());
174 parts.join(", ")
175 }
176}
177
178pub const BUILD_CACHE_TOOLS: &str =
181 "Gradle, sccache, Bazel and Turborepo, and Nx where a workflow opts in";
182
183pub const ACTIONS_CACHE: &str = "GitHub Actions' cache";
185
186pub fn actions_cache_place(served: bool) -> &'static str {
188 if served {
189 "served from the build cache on this host, in place of GitHub's"
190 } else {
191 "GitHub's, as [caches.build] actions_cache = false sets"
192 }
193}
194
195impl BuildCacheStats {
196 pub fn actions_cache_line(&self) -> String {
200 let place = actions_cache_place(self.actions_cache);
201 if self.actions_cache {
202 format!(
203 "{ACTIONS_CACHE}: {place}, and counted with it; [caches.build] actions_cache = false turns it \
204 off"
205 )
206 } else {
207 format!("{ACTIONS_CACHE}: {place}")
208 }
209 }
210
211 pub fn week_line(&self) -> String {
215 let week = &self.week;
216 let mut parts = match week.hit_percent() {
217 Some(percent) => vec![
218 format!("{percent}% of {} lookups hit in 7 days", week.lookups()),
219 format!("{} served", ByteSize(week.read_bytes)),
220 ],
221 None => vec!["no lookups in 7 days".to_owned()],
222 };
223 if week.activity().is_some() {
224 parts.push(format!("{} stored", ByteSize(week.written_bytes)));
225 }
226 if week.refused > 0 {
227 parts.push(format!("{} uploads refused", week.refused));
228 }
229 format!("{} entries; {}", self.entries, parts.join(", "))
230 }
231}
232
233impl RecordLimits {
234 pub fn near_full(&self, bytes: u64) -> bool {
236 records_near_full(bytes, self.max_total)
237 }
238}
239
240impl Records {
241 pub fn summary(&self) -> String {
244 match self.pressure() {
245 Some(pressure) => format!("{}; {pressure}", self.usage()),
246 None => self.usage(),
247 }
248 }
249
250 pub fn usage(&self) -> String {
252 let limits = &self.limits;
253 let age = match limits.max_age / 86_400 {
255 1 if limits.max_age == 86_400 => "1 day".to_owned(),
256 days if days > 1 && limits.max_age.is_multiple_of(86_400) => format!("{days} days"),
257 _ => period(limits.max_age),
258 };
259 format!(
260 "{} of {} records, {} of {}, each kept {age}",
261 self.records.len(),
262 limits.max_count,
263 ByteSize(self.bytes()),
264 ByteSize(limits.max_total),
265 )
266 }
267
268 pub fn pressure(&self) -> Option<&'static str> {
270 self.limits
271 .near_full(self.bytes())
272 .then_some("near max_total, so new ones remove the oldest")
273 }
274
275 pub fn summary_tone(&self) -> Tone {
277 if self.limits.near_full(self.bytes()) {
278 Tone::Warn
279 } else {
280 Tone::Neutral
281 }
282 }
283
284 pub fn empty_reason() -> &'static str {
287 "none kept: a profile with record_failures = true keeps each failed job's runner as a record, to open a \
288 shell where it failed"
289 }
290
291 pub fn history_gone() -> &'static str {
294 "its job is past the history; its shell still opens"
295 }
296
297 pub fn shell_open(&self, job: u64) -> bool {
299 self.shells.contains(&job)
300 }
301}
302
303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305pub enum RecordState<'note> {
306 Skipped {
308 why: &'note str,
310 },
311 Removed {
313 at: u64,
315 by: Option<RecordRemoval>,
317 },
318 Gone {
320 noticed_at: u64,
322 },
323 Kept {
325 bytes: Option<u64>,
327 },
328}
329
330impl RecordNote {
331 pub fn state(&self) -> RecordState<'_> {
334 match (&self.skipped, self.removed_at, self.gone_at) {
335 (Some(why), _, _) => RecordState::Skipped { why },
336 (None, Some(at), _) => RecordState::Removed {
337 at,
338 by: self.removed_by,
339 },
340 (None, None, Some(noticed_at)) => RecordState::Gone { noticed_at },
341 (None, None, None) => RecordState::Kept { bytes: self.bytes },
342 }
343 }
344
345 pub fn shell_command(job: u64) -> String {
347 format!("runnerctl shell {job}")
348 }
349}
350
351impl RecordState<'_> {
352 pub fn gone_words() -> &'static str {
354 "removed outside runnerd, when and why unknown"
355 }
356
357 pub fn line(&self) -> String {
360 match self {
361 RecordState::Skipped { why } => format!("not kept: {why}"),
362 RecordState::Removed { by, .. } => {
363 by.map_or_else(|| "removed".to_owned(), |by| by.to_string())
364 }
365 RecordState::Gone { .. } => RecordState::gone_words().to_owned(),
366 RecordState::Kept { bytes: Some(bytes) } => {
367 format!("record kept, {}", ByteSize(*bytes))
368 }
369 RecordState::Kept { bytes: None } => "record kept".to_owned(),
370 }
371 }
372}
373
374impl LogSummary {
375 pub fn description(&self) -> String {
378 let line = format!("{} lines, {}", self.lines, ByteSize(self.bytes));
379 if self.truncated {
380 format!("{line}, cut at history.log_max")
381 } else {
382 line
383 }
384 }
385}
386
387#[cfg(test)]
388mod tests;