runnerd-core 0.1.5

Config, domain logic and API types shared by runnerd and its clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! What the disk runnerd keeps means as every client shows it: what each cache volume holds and what its limit does,
//! what the build cache did for a job and over a week, where GitHub Actions' cache is served, how full the records are (the doctor's `records` check too) and what became of a job's record,
//! and how much of a job's log is stored. Plain derivations of the API's types; clients only lay them out.

use super::{
    BuildCacheCounts, BuildCacheStats, CacheKind, CacheVolume, Check, CheckStatus, LabelledFigure,
    LogSummary, RecordLimits, RecordNote, RecordRemoval, Records, Tone, period,
};
use crate::config::ByteSize;

/// The share of `[records] max_total` past which the records are near it, in percent: new ones then remove the
/// oldest to fit.
pub const RECORDS_NEAR_FULL: u64 = 80;

/// Whether records taking `bytes` are near `max_total` (`RECORDS_NEAR_FULL`).
pub fn records_near_full(bytes: u64, max_total: u64) -> bool {
    u128::from(bytes) * 100 >= u128::from(max_total) * u128::from(RECORDS_NEAR_FULL)
}

/// The doctor's `records` check for records taking `bytes` of `[records] max_total`: a warning with what to run when
/// they are near it (`records_near_full`), else how much they take.
pub fn records_check(bytes: u64, max_total: u64) -> Check {
    let taken = format!(
        "the records of failed jobs take {} of [records] max_total = {}",
        ByteSize(bytes),
        ByteSize(max_total)
    );
    if records_near_full(bytes, max_total) {
        Check {
            name: "records".to_owned(),
            status: CheckStatus::Warn,
            detail: format!("{taken}; new ones remove the oldest to fit"),
            fix: Some(
                "runnerctl records rm --older-than 2d, or raise max_total under [records]"
                    .to_owned(),
            ),
        }
    } else {
        Check {
            name: "records".to_owned(),
            status: CheckStatus::Info,
            detail: taken,
            fix: None,
        }
    }
}

impl CacheKind {
    /// What it holds, as every client names it: `jvm snapshot`, `jvm slot 2 layer`, `pnpm store, shared`, `Maven
    /// repository, shared`, `Docker Hub mirror` or `build cache, shared`.
    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(),
        }
    }

    /// The profile it belongs to; `None` for a shared one.
    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,
        }
    }
}

/// A cache volume against its limit, from `CacheVolume::limit_status`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CacheLimit {
    /// In bytes.
    pub limit: u64,
    /// Whether the volume is past it, so runnerd acts on it.
    pub over: bool,
    /// What runnerd does at it: `emptied above 5G`, `trimmed to 20G`, or for a snapshot `cut back at its next
    /// reseed above 30G`, by what the image's seed script drops (the reseed's output says what).
    pub label: String,
}

impl CacheLimit {
    /// What its size means: past the limit is worth a look.
    pub fn tone(&self) -> Tone {
        if self.over { Tone::Warn } else { Tone::Neutral }
    }
}

impl CacheVolume {
    /// Its size against its limit, when it has one.
    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!("cut back 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,
        })
    }
}

/// What the build cache did for one job, from `BuildCacheCounts::activity`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BuildCacheActivity {
    /// The counts.
    pub counts: BuildCacheCounts,
}

impl BuildCacheCounts {
    /// What it did, for a job that used it at all: looked an entry up, stored one, or was refused one. `None` for
    /// a job that never used it.
    pub fn activity(&self) -> Option<BuildCacheActivity> {
        (self.lookups() > 0 || self.written_bytes > 0 || self.refused > 0)
            .then_some(BuildCacheActivity { counts: *self })
    }
}

impl BuildCacheActivity {
    /// Its lookups: `3 of 4 lookups hit (75%)`, or `no lookups`.
    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(),
        }
    }

    /// What it served: `1.5G served`.
    pub fn served_line(&self) -> String {
        format!("{} served", ByteSize(self.counts.read_bytes))
    }

    /// What it stored: `2G stored`, or `read only` for a job that may not write.
    pub fn stored_line(&self) -> String {
        if self.counts.writer {
            format!("{} stored", ByteSize(self.counts.written_bytes))
        } else {
            "read only".to_owned()
        }
    }

    /// The uploads it refused, when it refused any: `3 uploads refused`.
    pub fn refused_line(&self) -> Option<String> {
        (self.counts.refused > 0).then(|| format!("{} uploads refused", self.counts.refused))
    }

    /// A line for a client with little room: the hit rate and what it served, or what a job that only wrote stored,
    /// and always the uploads it refused: `75% hit, 1.5G served, 3 uploads refused`, `read only`.
    pub fn short_line(&self) -> String {
        let mut parts = match self.counts.hit_percent() {
            Some(percent) => vec![format!("{percent}% hit"), self.served_line()],
            None => vec![self.stored_line()],
        };
        parts.extend(self.refused_line());
        parts.join(", ")
    }

    /// All of it in a line: `3 of 4 lookups hit (75%), 1.5G served, 2G stored, 3 uploads 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(", ")
    }
}

/// The tools whose caches the build cache serves, as clients name them over its counts (ADR 0052, 0083). The image
/// points each at it but Nx, which fails its run when the cache does not answer.
pub const BUILD_CACHE_TOOLS: &str =
    "Gradle, sccache, Bazel and Turborepo, and Nx where a workflow opts in";

/// What doctor and the Caches page name GitHub Actions' cache.
pub const ACTIONS_CACHE: &str = "GitHub Actions' cache";

/// Where jobs' GitHub Actions cache is (ADR 0082), with `[caches.build] actions_cache` at `served`.
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 {
    /// Where jobs' GitHub Actions cache is, and while it is here, where its hits are counted and how to turn it off:
    /// `GitHub Actions' cache: served from the build cache on this host, in place of GitHub's, and counted with it;
    /// [caches.build] actions_cache = false turns it off`.
    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}")
        }
    }

    /// Its entries and the last 7 days' jobs as figures, in the order they show: its entries; the share of lookups
    /// that hit, out of how many, and what it served, or that nothing looked an entry up; what it stored, when a job
    /// used it; the uploads it refused, when any. The same facts as [`BuildCacheStats::week_line`].
    pub fn figures(&self) -> Vec<LabelledFigure> {
        let week = &self.week;
        let mut figures = vec![LabelledFigure::new("Entries", self.entries.to_string())];
        match week.hit_percent() {
            Some(percent) => {
                figures.push(
                    LabelledFigure::new("Lookups hit, 7 days", format!("{percent}%"))
                        .of(format!("of {}", week.lookups())),
                );
                figures.push(LabelledFigure::new(
                    "Served",
                    ByteSize(week.read_bytes).to_string(),
                ));
            }
            None => figures.push(LabelledFigure::new("Lookups, 7 days", "0")),
        }
        if week.activity().is_some() {
            figures.push(LabelledFigure::new(
                "Stored",
                ByteSize(week.written_bytes).to_string(),
            ));
        }
        if week.refused > 0 {
            figures.push(LabelledFigure::new(
                "Uploads refused",
                week.refused.to_string(),
            ));
        }
        figures
    }

    /// Its entries and the last 7 days' jobs: `120 entries; 75% of 400 lookups hit in 7 days, 3G served, 1G
    /// stored, 2 uploads refused`, `120 entries; no lookups in 7 days, 1G stored`, or `120 entries; no lookups in 7
    /// days`.
    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 {
    /// Whether records taking `bytes` are near `max_total` (`records_near_full`).
    pub fn near_full(&self, bytes: u64) -> bool {
        records_near_full(bytes, self.max_total)
    }
}

impl Records {
    /// How many there are and how much they take of their limits, and when near `max_total`, `Records::pressure`:
    /// `3 of 20 records, 1.2G of 10G, each kept 7 days; near max_total, so new ones remove the oldest`.
    pub fn summary(&self) -> String {
        match self.pressure() {
            Some(pressure) => format!("{}; {pressure}", self.usage()),
            None => self.usage(),
        }
    }

    /// How many there are and how much they take of their limits: `3 of 20 records, 1.2G of 10G, each kept 7 days`.
    pub fn usage(&self) -> String {
        let limits = &self.limits;
        // `[records] max_age` is in days more often than not.
        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),
        )
    }

    /// What being near `max_total` means, when they are: `near max_total, so new ones remove the oldest`.
    pub fn pressure(&self) -> Option<&'static str> {
        self.limits
            .near_full(self.bytes())
            .then_some("near max_total, so new ones remove the oldest")
    }

    /// What the summary means: near `max_total` is worth a look.
    pub fn summary_tone(&self) -> Tone {
        if self.limits.near_full(self.bytes()) {
            Tone::Warn
        } else {
            Tone::Neutral
        }
    }

    /// Why there are none: `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 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"
    }

    /// What a kept record says when the job history no longer has its job, as `GET /v1/jobs/{id}` answers 404 once
    /// `history.jobs` pruned it: its image is kept, so its shell still opens, but it has no job page.
    pub fn history_gone() -> &'static str {
        "its job is past the history; its shell still opens"
    }

    /// Whether a shell is open in `job`'s record.
    pub fn shell_open(&self, job: u64) -> bool {
        self.shells.contains(&job)
    }
}

/// What became of a failed job's record, from `RecordNote::state`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecordState<'note> {
    /// None was made.
    Skipped {
        /// Why, such as too little free disk.
        why: &'note str,
    },
    /// It was made, then removed.
    Removed {
        /// When.
        at: u64,
        /// Why, when known.
        by: Option<RecordRemoval>,
    },
    /// Its image went from Docker without runnerd removing it: when and why are not known.
    Gone {
        /// When runnerd found it gone.
        noticed_at: u64,
    },
    /// It is kept: a shell can open in it.
    Kept {
        /// Its size when made, when known.
        bytes: Option<u64>,
    },
}

impl RecordNote {
    /// What became of the record: not made, made and removed, gone outside runnerd, or kept, in that order of
    /// precedence.
    pub fn state(&self) -> RecordState<'_> {
        match (&self.skipped, self.removed_at, self.gone_at) {
            (Some(why), _, _) => RecordState::Skipped { why },
            (None, Some(at), _) => RecordState::Removed {
                at,
                by: self.removed_by,
            },
            (None, None, Some(noticed_at)) => RecordState::Gone { noticed_at },
            (None, None, None) => RecordState::Kept { bytes: self.bytes },
        }
    }

    /// The command that opens a shell in `job`'s record: `runnerctl shell 42`.
    pub fn shell_command(job: u64) -> String {
        format!("runnerctl shell {job}")
    }
}

impl RecordState<'_> {
    /// What a record found gone from Docker says, on its job's page and for `record.gone`.
    pub fn gone_words() -> &'static str {
        "removed outside runnerd, when and why unknown"
    }

    /// Its words, before when it was removed for a removed one: `not kept: too little free disk`, `removed past
    /// max_age`, or `record kept, 2G`.
    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::Gone { .. } => RecordState::gone_words().to_owned(),
            RecordState::Kept { bytes: Some(bytes) } => {
                format!("record kept, {}", ByteSize(*bytes))
            }
            RecordState::Kept { bytes: None } => "record kept".to_owned(),
        }
    }
}

impl LogSummary {
    /// How much of the log is stored: `120 lines, 4M`, and `, cut at history.log_max` once later lines were
    /// dropped.
    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;