Skip to main content

runnerd_core/
config.rs

1//! `runnerd.toml`: the repositories to serve, the runner profiles they use, the shared caches and the host
2//! budget they must fit in. Builds without the `host` feature, so clients can read a config; its only I/O is
3//! reading the file and asking `systemctl` for a slice's `MemoryMax`. It never talks to Docker or GitHub.
4
5use std::collections::BTreeMap;
6use std::fmt;
7use std::net::{Ipv4Addr, Ipv6Addr};
8use std::path::{Path, PathBuf};
9use std::process::Command;
10use std::str::FromStr;
11use std::time::Duration;
12
13use serde::{Deserialize, Deserializer, de};
14
15use crate::api;
16
17mod budget;
18
19pub use budget::{BudgetBlock, CheckBudget, Remainder, Verdict};
20
21/// A parsed `runnerd.toml`. `validate` checks it against the host's budget.
22#[derive(Debug, Deserialize)]
23#[serde(deny_unknown_fields)]
24pub struct Config {
25    /// The host's budget and isolation.
26    pub host: Host,
27    /// The caches runners share.
28    pub caches: Caches,
29    /// Runner profiles by name.
30    pub profiles: BTreeMap<String, Profile>,
31    /// The repositories to serve, one pool per entry: a repository named by several entries is served by each of
32    /// their profiles, a job by the one whose labels match it (ADR 0058).
33    pub repositories: Vec<Repository>,
34    /// What is kept of past jobs.
35    #[serde(default)]
36    pub history: History,
37    /// How much the records of failed jobs may keep.
38    #[serde(default)]
39    pub records: Records,
40    /// How sizing advice reads the job history.
41    #[serde(default)]
42    pub sizing: Sizing,
43    /// Who may use the dashboard through another address.
44    #[serde(default)]
45    pub web: Web,
46    /// Where the daemon sends notifications; none by default.
47    #[serde(default)]
48    pub notify: Notify,
49}
50
51/// `[host]`: where runner containers run and how they are isolated.
52#[derive(Debug, Deserialize)]
53#[serde(deny_unknown_fields)]
54pub struct Host {
55    /// The systemd slice every runner container is placed in; its `MemoryMax` is the budget.
56    pub slice: String,
57    /// How runner containers are kept from the host.
58    pub isolation: Isolation,
59    /// Must be set for `isolation = "unsafe-dind"`, so a copied config cannot turn it on silently.
60    #[serde(default)]
61    pub allow_unsafe: bool,
62    /// How often GitHub is asked for queued jobs.
63    #[serde(default = "default_poll_interval", deserialize_with = "duration")]
64    pub poll_interval: Duration,
65    /// What a runner must fit in before it starts. Default `caps`.
66    #[serde(default)]
67    pub admission: Admission,
68    /// Set, a runner also starts only when its predicted CPU fits the slice's CPUs times this; absent, CPU is not
69    /// admitted.
70    #[serde(default)]
71    pub cpu_overcommit: Option<f64>,
72    /// Set, the most memory the host can grow to, for a VM whose hypervisor adds memory as the guest asks for it:
73    /// admission counts what it can still grow by past `MemTotal` as available, and keeps the margin of this
74    /// (ADR 0084). Absent, or not above `MemTotal`, the host is the memory it has now.
75    #[serde(default)]
76    pub memory_ceiling: Option<ByteSize>,
77    /// Under measured admission, whether `MemoryMax` and the host's limit count what runs uses and keep room for its
78    /// growth (ADR 0099, 0108, 0130) rather than every runner's worst case. Default on; off, both add every runner's
79    /// take, the way back if a host meets what the count did not foresee.
80    #[serde(default = "default_on")]
81    pub pooled_count: bool,
82}
83
84impl Host {
85    /// Refuses a `cpu_overcommit` that is not above 0 and at most `MAX_CPU_OVERCOMMIT`.
86    fn check_cpu_overcommit(&self) -> Result<(), ConfigError> {
87        match self.cpu_overcommit {
88            Some(value) if !(value > 0.0 && value <= MAX_CPU_OVERCOMMIT) => {
89                Err(ConfigError::CpuOvercommit { value })
90            }
91            _ => Ok(()),
92        }
93    }
94}
95
96/// The largest `cpu_overcommit` the config check takes.
97pub const MAX_CPU_OVERCOMMIT: f64 = 16.0;
98
99/// `admission` under `[host]`: what a new runner must fit in the slice's `MemoryMax` beside the running ones.
100#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
101#[serde(rename_all = "kebab-case")]
102pub enum Admission {
103    /// Every runner's memory cap: `slots × memory` over all profiles, with the mirror, must fit `MemoryMax`.
104    #[default]
105    Caps,
106    /// Every runner's predicted peak, from the job history; `slots` only bounds how many run at once, and one
107    /// runner of each profile with the mirror must fit `MemoryMax`. Nothing starts while the slice is at 90% of it.
108    Measured,
109}
110
111impl Admission {
112    /// The policy as the API names it.
113    pub fn policy(self) -> api::AdmissionPolicy {
114        match self {
115            Admission::Caps => api::AdmissionPolicy::Caps,
116            Admission::Measured => api::AdmissionPolicy::Measured,
117        }
118    }
119}
120
121fn default_on() -> bool {
122    true
123}
124
125fn default_poll_interval() -> Duration {
126    Duration::from_secs(15)
127}
128
129/// How runner containers are kept from the host: `isolation` under `[host]`.
130#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
131#[serde(rename_all = "kebab-case")]
132pub enum Isolation {
133    /// Sysbox: Docker inside an unprivileged container.
134    Sysbox,
135    /// Privileged Docker-in-Docker: a job can take over the host.
136    UnsafeDind,
137}
138
139/// `[caches]`: what runners share and keep between jobs.
140#[derive(Debug, Clone, Deserialize)]
141#[serde(deny_unknown_fields)]
142pub struct Caches {
143    /// The Docker Hub mirror.
144    pub mirror: Mirror,
145    /// The shared pnpm store.
146    pub pnpm: CacheLimit,
147    /// The shared Maven repository.
148    pub maven: CacheLimit,
149    /// When a profile has no job running and its slot 1 changed its layers by at least this much, slot 1's
150    /// layers become the profile's new snapshot.
151    #[serde(default = "default_reseed_at")]
152    pub reseed_at: ByteSize,
153    /// A reseed that would make a profile's snapshot larger than this starts it over from slot 1's changes alone,
154    /// or from the image when those are larger too.
155    #[serde(default = "default_snapshot_max")]
156    pub snapshot_max: ByteSize,
157    /// The build cache every runner shares.
158    #[serde(default)]
159    pub build: BuildCache,
160}
161
162/// `[caches.build]`: the build cache every runner shares (ADR 0052): Gradle's, and the other tools' the runner image
163/// points at it. Every field has a default.
164#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
165#[serde(deny_unknown_fields, default)]
166pub struct BuildCache {
167    /// Whether runners get it. Default true.
168    pub enabled: bool,
169    /// Above this size, the entries used least recently go when no job runs. Default 10G.
170    pub max_size: ByteSize,
171    /// The branches whose pushes, scheduled and manually started runs may write to it besides each repository's
172    /// default branch, which always may. Every other job only reads. Default empty.
173    pub branches: Vec<String>,
174    /// Where its entries are kept; default `$XDG_CACHE_HOME/runnerd/build-cache`.
175    pub directory: Option<PathBuf>,
176    /// Whether it also serves GitHub Actions' cache, for `actions/cache`, the `setup-*` actions' caches and
177    /// BuildKit's `type=gha`, in place of GitHub's (ADR 0082). Default true.
178    pub actions_cache: bool,
179}
180
181impl BuildCache {
182    /// Doctor's word on where jobs' GitHub Actions cache is: for information, it fails nothing.
183    pub fn actions_cache_check(&self) -> api::Check {
184        api::Check {
185            name: api::ACTIONS_CACHE.to_owned(),
186            status: api::CheckStatus::Info,
187            detail: if self.enabled {
188                api::actions_cache_place(self.actions_cache)
189            } else {
190                "GitHub's, as the build cache is off"
191            }
192            .to_owned(),
193            fix: None,
194        }
195    }
196
197    fn validate(&self) -> Result<(), ConfigError> {
198        if self.enabled && self.max_size.0 == 0 {
199            return Err(ConfigError::ZeroLimit {
200                field: "caches.build.max_size".to_owned(),
201            });
202        }
203        Ok(())
204    }
205}
206
207impl Default for BuildCache {
208    fn default() -> BuildCache {
209        BuildCache {
210            enabled: true,
211            max_size: ByteSize(10 << 30),
212            branches: Vec::new(),
213            directory: None,
214            actions_cache: true,
215        }
216    }
217}
218
219fn default_reseed_at() -> ByteSize {
220    ByteSize(2 << 30)
221}
222
223/// Above the 8.7G a profile running Flutter and Android builds needs: its Flutter SDK, NDK and Gradle caches.
224fn default_snapshot_max() -> ByteSize {
225    ByteSize(10 << 30)
226}
227
228fn default_mirror_max_size() -> ByteSize {
229    ByteSize(10 << 30)
230}
231
232/// The Docker Hub pull-through mirror shared by all runners.
233#[derive(Debug, Clone, Deserialize)]
234#[serde(deny_unknown_fields)]
235pub struct Mirror {
236    /// Whether runners pull through the mirror.
237    pub enabled: bool,
238    /// The mirror container's memory limit.
239    pub memory: ByteSize,
240    /// The mirror container's CPUs.
241    pub cpus: u32,
242    /// How long content not pulled again is kept.
243    #[serde(deserialize_with = "duration")]
244    pub ttl: Duration,
245    /// Its storage is emptied above this size when no job runs.
246    #[serde(default = "default_mirror_max_size")]
247    pub max_size: ByteSize,
248}
249
250/// A size limit on a shared cache.
251#[derive(Debug, Clone, Deserialize)]
252#[serde(deny_unknown_fields)]
253pub struct CacheLimit {
254    /// The cache is emptied above this size when no job runs.
255    pub max_size: ByteSize,
256}
257
258/// Where runnerd's release workflow publishes the runner images, one tag per stage and version, such as
259/// `ghcr.io/ayagmar/runnerd-runner:jvm-0.1.0`.
260pub const PUBLISHED_RUNNER: &str = "ghcr.io/ayagmar/runnerd-runner";
261
262/// A runner image with its limits; every job of the profile gets one container with these limits.
263#[derive(Debug, Clone, Deserialize)]
264#[serde(try_from = "ProfileToml")]
265pub struct Profile {
266    /// The image its runners run: `image_stage` or `image`, exactly one of them.
267    pub image: Image,
268    /// CPUs per slot.
269    pub cpus: u32,
270    /// Memory per slot; the container's hard limit.
271    pub memory: ByteSize,
272    /// The most jobs of this profile running at once.
273    pub slots: u32,
274    /// Whether a failed job's runner is kept as a record, to open a shell in (`runnerctl shell`).
275    pub record_failures: bool,
276    /// The least `memory` auto sizing lowers it to; `None` for no bound.
277    pub min_memory: Option<ByteSize>,
278    /// The most `memory` auto sizing raises it to; `None` for what the slice's `MemoryMax` holds.
279    pub max_memory: Option<ByteSize>,
280    /// The most `slots` auto sizing raises them to; `None` for as many as the slice's `MemoryMax` holds.
281    pub max_slots: Option<u32>,
282    /// The GitHub-hosted runner its jobs are priced at (ADR 0072); `None` for the daemon's architecture's 2-core
283    /// standard runner.
284    pub priced_as: Option<api::Sku>,
285}
286
287/// The image a profile's runners run.
288#[derive(Debug, Clone, PartialEq, Eq)]
289pub enum Image {
290    /// `image_stage`: a stage of `image/Dockerfile` built on this host as `runnerd-runner:<stage>`.
291    Stage(String),
292    /// `image`: a reference runnerd pulls when Docker lacks it, such as
293    /// `ghcr.io/ayagmar/runnerd-runner:jvm-0.1.0`.
294    Pulled(String),
295}
296
297impl Image {
298    /// The reference Docker runs.
299    pub fn reference(&self) -> String {
300        match self {
301            Image::Stage(stage) => format!("runnerd-runner:{stage}"),
302            Image::Pulled(reference) => reference.clone(),
303        }
304    }
305}
306
307/// `[profiles.<name>]` as written, before `Profile` checks it names one image.
308#[derive(Deserialize)]
309#[serde(deny_unknown_fields)]
310struct ProfileToml {
311    image_stage: Option<String>,
312    image: Option<String>,
313    cpus: u32,
314    memory: ByteSize,
315    slots: u32,
316    #[serde(default)]
317    record_failures: bool,
318    min_memory: Option<ByteSize>,
319    max_memory: Option<ByteSize>,
320    max_slots: Option<u32>,
321    priced_as: Option<api::Sku>,
322}
323
324impl TryFrom<ProfileToml> for Profile {
325    type Error = String;
326
327    fn try_from(profile: ProfileToml) -> Result<Profile, String> {
328        let image = match (profile.image_stage, profile.image) {
329            (Some(stage), None) if !stage.is_empty() => Image::Stage(stage),
330            (None, Some(reference)) if !reference.is_empty() => Image::Pulled(reference),
331            (Some(_), Some(_)) => {
332                return Err(
333                    "set image_stage (a stage built from image/Dockerfile) or image (a reference to pull), \
334                     not both"
335                        .to_owned(),
336                );
337            }
338            _ => {
339                return Err(
340                    "set image_stage (a stage built from image/Dockerfile) or image (a reference to pull)"
341                        .to_owned(),
342                );
343            }
344        };
345        Ok(Profile {
346            image,
347            cpus: profile.cpus,
348            memory: profile.memory,
349            slots: profile.slots,
350            record_failures: profile.record_failures,
351            min_memory: profile.min_memory,
352            max_memory: profile.max_memory,
353            max_slots: profile.max_slots,
354            priced_as: profile.priced_as,
355        })
356    }
357}
358
359/// Whether a job asking for `wanted` may run on runners registered with `labels`: every label it asks for is one of
360/// theirs. GitHub compares labels without regard to case. A job asking for no label, as one that names only a runner
361/// group, matches no runners: nothing says which pool it is for (ADR 0058).
362pub fn labels_match(wanted: &[String], labels: &[String]) -> bool {
363    !wanted.is_empty()
364        && wanted.iter().all(|wanted| {
365            labels
366                .iter()
367                .any(|label| label.eq_ignore_ascii_case(wanted))
368        })
369}
370
371/// A repository to serve: `[[repositories]]`. Each entry is one of the repository's pools; entries with the same
372/// `name` serve it in several profiles, each with its own labels, which no two of them share (ADR 0058).
373#[derive(Debug, Deserialize)]
374#[serde(deny_unknown_fields)]
375pub struct Repository {
376    /// `owner/name` on GitHub.
377    pub name: String,
378    /// The profile the jobs this pool's labels match run in.
379    pub profile: String,
380    /// The labels its runners register with; a job runs on them when every label it asks for is one of these.
381    pub labels: Vec<String>,
382    /// How many idle runners it keeps registered for jobs not queued yet while it is active (ADR 0050, 0107); 0 turns
383    /// warm runners and bursts off. Default 1.
384    #[serde(default = "default_warm")]
385    pub warm: u32,
386    /// Whether its runners get the shared build cache, when `[caches.build]` is enabled. Default true.
387    #[serde(default = "default_true")]
388    pub build_cache: bool,
389    /// Whose runs may write to the shared build cache besides the branches' (ADR 0053), the same in every pool of
390    /// the repository. Default `"default-branch"`.
391    #[serde(default)]
392    pub build_cache_writers: BuildCacheWriters,
393}
394
395/// `build_cache_writers` of a `[[repositories]]`: whose jobs' uploads the shared build cache keeps (ADR 0053).
396#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
397#[serde(rename_all = "kebab-case")]
398pub enum BuildCacheWriters {
399    /// Pushes, scheduled and manually started runs of the default branch and of `[caches.build] branches`.
400    #[default]
401    DefaultBranch,
402    /// Those, and `pull_request` runs of the repository's own branches that people, not bots, opened and pushed.
403    PullRequests,
404}
405
406fn default_true() -> bool {
407    true
408}
409
410fn default_warm() -> u32 {
411    1
412}
413
414/// `[history]`: the job history database and how long it keeps what. Every field has a default.
415#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
416#[serde(deny_unknown_fields, default)]
417pub struct History {
418    /// The SQLite database; default `$XDG_STATE_HOME/runnerd/runnerd.db`.
419    pub database: Option<PathBuf>,
420    /// How long CPU and memory samples are kept; a job's totals and peaks stay. Default 7 days.
421    #[serde(deserialize_with = "duration")]
422    pub samples: Duration,
423    /// How long a finished job's log is kept. Default 30 days.
424    #[serde(deserialize_with = "duration")]
425    pub logs: Duration,
426    /// How long events are kept for clients resuming with `Last-Event-ID`. Default 30 days.
427    #[serde(deserialize_with = "duration")]
428    pub events: Duration,
429    /// How long a finished job's record is kept, with its steps, totals and runner. Default 90 days.
430    #[serde(deserialize_with = "duration")]
431    pub jobs: Duration,
432    /// The most log stored per job; later lines are dropped. Default 50M.
433    pub log_max: ByteSize,
434}
435
436impl Default for History {
437    fn default() -> History {
438        History {
439            database: None,
440            samples: Duration::from_hours(7 * 24),
441            logs: Duration::from_hours(30 * 24),
442            events: Duration::from_hours(30 * 24),
443            jobs: Duration::from_hours(90 * 24),
444            log_max: ByteSize(50 << 20),
445        }
446    }
447}
448
449/// `[records]`: how much the records of failed jobs may keep (`record_failures` under a profile turns them on).
450/// When a new record would pass a limit, the oldest records go first. Every field has a default.
451#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
452#[serde(deny_unknown_fields, default)]
453pub struct Records {
454    /// The most disk all records may take together. Default 20G.
455    pub max_total: ByteSize,
456    /// The most records kept. Default 10.
457    pub max_count: u32,
458    /// How long a record is kept. Default 7 days.
459    #[serde(deserialize_with = "duration")]
460    pub max_age: Duration,
461    /// The disk Docker must keep free: no record is made that would leave less. Default 10G.
462    pub min_free: ByteSize,
463}
464
465impl Default for Records {
466    fn default() -> Records {
467        Records {
468            max_total: ByteSize(20 << 30),
469            max_count: 10,
470            max_age: Duration::from_hours(7 * 24),
471            min_free: ByteSize(10 << 30),
472        }
473    }
474}
475
476/// `[sizing]`: how `runnerctl sizing` turns the job history's peaks into advice, and whether the daemon applies it
477/// itself. Every field has a default.
478#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
479#[serde(deny_unknown_fields, default)]
480pub struct Sizing {
481    /// The percent added to the largest sampled memory peak: a container is sampled every 2 s, so a spike between
482    /// two samples goes unseen. Default 15. Advice adds at least `api::PAGE_CACHE_ROOM`.
483    pub margin: u32,
484    /// The fewest jobs a profile, or a job of a repository's workflow, needs before its peaks become advice.
485    /// Default 10.
486    pub min_jobs: u32,
487    /// Whether the daemon writes each profile's advice into the config itself, within each profile's
488    /// `min_memory`, `max_memory` and `max_slots`. Default off.
489    pub auto: bool,
490    /// The least time between a change auto sizing makes to one profile and one that lowers anything in it. Default
491    /// 1 hour: a lowering that went too far is taken back at its first kill (docs/adr/0071).
492    #[serde(deserialize_with = "duration")]
493    pub interval: Duration,
494    /// The least time between a change auto sizing makes to one profile and one that only raises its `memory`,
495    /// `slots` or `cpus`; at most `interval`, which a longer one counts as. Default 1 hour.
496    #[serde(deserialize_with = "duration")]
497    pub raise_interval: Duration,
498    /// The most a change lowers a profile's `memory` or moves its `cpus`, in percent of them; a raise of `memory`,
499    /// which only a run that met the cap gives, goes straight to the advice. Default 50.
500    pub max_step: u32,
501}
502
503impl Sizing {
504    /// The least time between a change to one profile and one that only raises it: `raise_interval`, at most
505    /// `interval`.
506    pub fn raise_after(&self) -> Duration {
507        self.raise_interval.min(self.interval)
508    }
509}
510
511impl Default for Sizing {
512    fn default() -> Sizing {
513        Sizing {
514            margin: 15,
515            min_jobs: 10,
516            auto: false,
517            interval: Duration::from_hours(1),
518            raise_interval: Duration::from_hours(1),
519            max_step: 50,
520        }
521    }
522}
523
524/// `[web]`: the dashboard behind a reverse proxy, such as `tailscale serve`. Read when the daemon starts.
525#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
526#[serde(deny_unknown_fields, default)]
527pub struct Web {
528    /// The origins, besides the dashboard's own loopback address, whose pages may write: pause, reseed, save the
529    /// config. Default none.
530    pub origins: Vec<Origin>,
531    /// The one of `origins` that `runnerctl web` opens the dashboard on, such as a tailnet's address. Default none:
532    /// it opens the loopback address.
533    pub open: Option<Origin>,
534}
535
536impl Web {
537    /// Refuses an `open` that is not one of `origins`.
538    fn validate(&self) -> Result<(), ConfigError> {
539        match &self.open {
540            Some(open) if !self.origins.contains(open) => {
541                Err(ConfigError::OpenNotListed { open: open.clone() })
542            }
543            _ => Ok(()),
544        }
545    }
546}
547
548/// `[notify]`: where the daemon sends notifications (ADR 0051). Without targets nothing leaves the machine.
549#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
550#[serde(deny_unknown_fields, default)]
551pub struct Notify {
552    /// When the digest goes to the targets that want it, in the host's local time. Default `09:00`.
553    pub digest_at: DayTime,
554    /// The targets, each `[[notify.targets]]`.
555    pub targets: Vec<NotifyTarget>,
556}
557
558impl Default for Notify {
559    fn default() -> Notify {
560        Notify {
561            digest_at: DayTime { minutes: 9 * 60 },
562            targets: Vec::new(),
563        }
564    }
565}
566
567impl Notify {
568    /// Refuses a target without a name, with a name another has, with a URL that is not `http` or `https`, or with
569    /// a header that cannot be sent. Says which target and which field, never the URL or a header's value.
570    fn validate(&self) -> Result<(), ConfigError> {
571        let refuse = |target: &str, why: &'static str| {
572            Err(ConfigError::Notify {
573                target: target.to_owned(),
574                why,
575            })
576        };
577        for (index, target) in self.targets.iter().enumerate() {
578            let name = target.name.as_str();
579            if name.trim().is_empty() || name.chars().any(char::is_control) {
580                return refuse(name, "name is empty");
581            }
582            if self.targets[..index].iter().any(|other| other.name == name) {
583                return refuse(name, "another target has this name");
584            }
585            let url = target.url.expose();
586            if url == SECRET_SHOWN {
587                return refuse(
588                    name,
589                    "url is <secret>, which runnerd fills in only for a target of the same name that had one; write the url",
590                );
591            }
592            let Some(rest) = url
593                .strip_prefix("https://")
594                .or_else(|| url.strip_prefix("http://"))
595            else {
596                return refuse(name, "url does not start with https:// or http://");
597            };
598            let (host, path) = rest.split_once('/').unwrap_or((rest, ""));
599            if host.is_empty() || url.chars().any(|c| c.is_whitespace() || c.is_control()) {
600                return refuse(name, "url is not a URL");
601            }
602            if target.kind == NotifyKind::Ntfy
603                && (path.is_empty() || path.contains(['/', '?', '#']))
604            {
605                return refuse(
606                    name,
607                    "url is not an ntfy topic's, such as https://ntfy.sh/<topic>",
608                );
609            }
610            for (header, value) in &target.headers {
611                if value.expose() == SECRET_SHOWN {
612                    return refuse(
613                        name,
614                        "a header is <secret>, which runnerd fills in only for a target of the same name that had it; write its value",
615                    );
616                }
617                let token = |c: char| c.is_ascii_alphanumeric() || "!#$%&'*+-.^_`|~".contains(c);
618                if header.is_empty() || !header.chars().all(token) {
619                    return refuse(name, "a header's name is not a header name");
620                }
621                if value.expose().chars().any(char::is_control) {
622                    return refuse(name, "a header's value has a control character");
623                }
624            }
625            if target.events.contains(&api::NotifyEvent::Test) {
626                return refuse(
627                    name,
628                    "events lists test, which only runnerctl notify test sends",
629                );
630            }
631        }
632        Ok(())
633    }
634}
635
636/// `[[notify.targets]]`: one place notifications go.
637#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
638#[serde(deny_unknown_fields)]
639pub struct NotifyTarget {
640    /// What logs and `runnerctl notify test` call it, such as `phone`; the history keeps where it got to by it.
641    pub name: String,
642    /// What it takes.
643    pub kind: NotifyKind,
644    /// Where it is posted: the webhook's URL, Discord's included, or the ntfy topic's, such as `https://ntfy.sh/<topic>`.
645    /// A secret.
646    pub url: Secret,
647    /// Headers sent with each post, such as an ntfy access token's `Authorization`. Their values are secrets.
648    #[serde(default)]
649    pub headers: BTreeMap<String, Secret>,
650    /// What it is sent. Default `failed`, `lost`, `runner` and `insights`.
651    #[serde(default = "default_notify_events")]
652    pub events: Vec<api::NotifyEvent>,
653}
654
655fn default_notify_events() -> Vec<api::NotifyEvent> {
656    vec![
657        api::NotifyEvent::Failed,
658        api::NotifyEvent::Lost,
659        api::NotifyEvent::Runner,
660        api::NotifyEvent::Insights,
661    ]
662}
663
664/// What a notification target takes.
665#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
666#[serde(rename_all = "kebab-case")]
667pub enum NotifyKind {
668    /// `api::Notification` as JSON.
669    Webhook,
670    /// An ntfy topic: the title, message, priority and link, published as ntfy's JSON.
671    Ntfy,
672    /// A Discord channel's webhook: the title, message and link as one embed, coloured by event, that pings no one.
673    Discord,
674}
675
676/// A value no `Debug` output, log line or error shows: a notification target's URL or header.
677#[derive(Clone, PartialEq, Eq, Deserialize)]
678#[serde(transparent)]
679pub struct Secret(String);
680
681impl Secret {
682    /// The value, for the request that sends it.
683    pub fn expose(&self) -> &str {
684        &self.0
685    }
686}
687
688impl From<&str> for Secret {
689    fn from(value: &str) -> Secret {
690        Secret(value.to_owned())
691    }
692}
693
694impl fmt::Debug for Secret {
695    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
696        f.write_str("<secret>")
697    }
698}
699
700/// A time of day, `HH:MM`, 24-hour.
701#[derive(Debug, Clone, Copy, PartialEq, Eq)]
702pub struct DayTime {
703    /// Minutes after midnight.
704    pub minutes: u32,
705}
706
707impl FromStr for DayTime {
708    type Err = String;
709
710    fn from_str(text: &str) -> Result<DayTime, String> {
711        let invalid = || format!("invalid time of day {text:?}, expected HH:MM such as \"09:00\"");
712        let (hour, minute) = text.split_once(':').ok_or_else(invalid)?;
713        let digits = |part: &str| part.len() == 2 && part.chars().all(|c| c.is_ascii_digit());
714        if !digits(hour) || !digits(minute) {
715            return Err(invalid());
716        }
717        let (hour, minute): (u32, u32) = (
718            hour.parse().map_err(|_| invalid())?,
719            minute.parse().map_err(|_| invalid())?,
720        );
721        if hour > 23 || minute > 59 {
722            return Err(invalid());
723        }
724        Ok(DayTime {
725            minutes: hour * 60 + minute,
726        })
727    }
728}
729
730impl fmt::Display for DayTime {
731    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
732        write!(f, "{:02}:{:02}", self.minutes / 60, self.minutes % 60)
733    }
734}
735
736impl<'de> Deserialize<'de> for DayTime {
737    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
738        String::deserialize(deserializer)?
739            .parse()
740            .map_err(de::Error::custom)
741    }
742}
743
744/// An origin as a browser sends it in `Origin`: `https://host[:port]`, or `http://` for a loopback host, in lower
745/// case, without the scheme's default port, and an address written as the URL standard serializes it. Nothing after
746/// the port: no path, query or user.
747#[derive(Debug, Clone, PartialEq, Eq)]
748pub struct Origin(String);
749
750impl Origin {
751    /// The origin as a browser sends it, such as `https://host.example.ts.net:8443`.
752    pub fn as_str(&self) -> &str {
753        &self.0
754    }
755}
756
757impl FromStr for Origin {
758    type Err = String;
759
760    fn from_str(s: &str) -> Result<Origin, String> {
761        let invalid = |why: &str| {
762            format!(
763                "invalid origin {s:?}: {why}; write the scheme, host and port only, such as \
764                 \"https://host.example.ts.net:8443\""
765            )
766        };
767        let (scheme, rest) = s
768            .split_once("://")
769            .ok_or_else(|| invalid("it has no scheme"))?;
770        let scheme = scheme.to_ascii_lowercase();
771        if rest.contains(['/', '?', '#']) {
772            return Err(invalid("it has a path"));
773        }
774        if rest.contains('@') {
775            return Err(invalid("it names a user"));
776        }
777        let (host, port) = match rest.strip_prefix('[') {
778            Some(v6) => {
779                let (address, after) = v6
780                    .split_once(']')
781                    .ok_or_else(|| invalid("its IPv6 address has no closing ]"))?;
782                let port = match after {
783                    "" => None,
784                    _ => Some(after.strip_prefix(':').ok_or_else(|| invalid("its port"))?),
785                };
786                (format!("[{address}]"), port)
787            }
788            None => match rest.split_once(':') {
789                Some((host, port)) => (host.to_owned(), Some(port)),
790                None => (rest.to_owned(), None),
791            },
792        };
793        let host = host.to_ascii_lowercase();
794        let not_a_host = || invalid("its host is not a name or an address");
795        // An address is kept as a browser serializes it, or it would never match the `Origin` the browser sends.
796        let (host, loopback) =
797            if let Some(v6) = host.strip_prefix('[').and_then(|v6| v6.strip_suffix(']')) {
798                let address: Ipv6Addr = v6.parse().map_err(|_| not_a_host())?;
799                (format!("[{}]", ipv6_origin(address)), address.is_loopback())
800            } else {
801                if host.is_empty()
802                    || !host
803                        .chars()
804                        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.')
805                {
806                    return Err(not_a_host());
807                }
808                // As the URL standard reads a host: one whose last label is a number is an IPv4 address.
809                let name = host.strip_suffix('.').unwrap_or(&host);
810                let last = name.rsplit('.').next().unwrap_or_default();
811                let numeric = !last.is_empty()
812                    && (last.bytes().all(|byte| byte.is_ascii_digit())
813                        || last
814                            .strip_prefix("0x")
815                            .is_some_and(|hex| hex.bytes().all(|byte| byte.is_ascii_hexdigit())));
816                if numeric {
817                    let address: Ipv4Addr = name.parse().map_err(|_| {
818                        invalid("its IPv4 address is not four decimal numbers, such as 192.0.2.1")
819                    })?;
820                    (address.to_string(), address.is_loopback())
821                } else {
822                    let loopback = host == "localhost";
823                    (host, loopback)
824                }
825            };
826        let port = port
827            .map(|port| {
828                Some(port)
829                    .filter(|port| port.bytes().all(|byte| byte.is_ascii_digit()))
830                    .and_then(|port| port.parse::<u16>().ok())
831                    .filter(|port| *port != 0)
832                    .ok_or_else(|| invalid("its port is not a number from 1 to 65535"))
833            })
834            .transpose()?;
835        let default_port = match scheme.as_str() {
836            "https" => 443,
837            "http" if loopback => 80,
838            "http" => {
839                return Err(invalid(
840                    "http is for a loopback host only, since the session cookie would cross the network in \
841                     the clear; use https",
842                ));
843            }
844            _ => return Err(invalid("its scheme is not https")),
845        };
846        Ok(Origin(match port {
847            Some(port) if port != default_port => format!("{scheme}://{host}:{port}"),
848            _ => format!("{scheme}://{host}"),
849        }))
850    }
851}
852
853/// An IPv6 address as the URL standard serializes it: lower-case hex pieces, the first longest run of two or more
854/// zero pieces as `::`, and no dotted IPv4 tail.
855fn ipv6_origin(address: Ipv6Addr) -> String {
856    let pieces = address.segments();
857    let (mut zeros_at, mut zeros) = (0, 0);
858    let mut at = 0;
859    while at < pieces.len() {
860        let run = pieces[at..].iter().take_while(|piece| **piece == 0).count();
861        if run > zeros {
862            (zeros_at, zeros) = (at, run);
863        }
864        at += run.max(1);
865    }
866    let hex = |pieces: &[u16]| {
867        pieces
868            .iter()
869            .map(|piece| format!("{piece:x}"))
870            .collect::<Vec<_>>()
871            .join(":")
872    };
873    if zeros < 2 {
874        return hex(&pieces);
875    }
876    format!(
877        "{}::{}",
878        hex(&pieces[..zeros_at]),
879        hex(&pieces[zeros_at + zeros..])
880    )
881}
882
883impl fmt::Display for Origin {
884    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
885        f.write_str(&self.0)
886    }
887}
888
889impl<'de> Deserialize<'de> for Origin {
890    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
891        String::deserialize(deserializer)?
892            .parse()
893            .map_err(de::Error::custom)
894    }
895}
896
897/// Why a config cannot be used.
898#[derive(Debug, thiserror::Error)]
899pub enum ConfigError {
900    /// The file cannot be read.
901    #[error("cannot read {}: {source}", path.display())]
902    Read {
903        /// The config file.
904        path: PathBuf,
905        /// Why reading it failed.
906        source: std::io::Error,
907    },
908    /// The file is not valid TOML or does not match the config's shape.
909    #[error(transparent)]
910    Parse(#[from] toml::de::Error),
911    /// A repository names a profile `[profiles]` does not define.
912    #[error(
913        "repository {repository} uses profile {profile:?}, which is not defined under [profiles]; {}",
914        defined_profiles(.defined)
915    )]
916    UnknownProfile {
917        /// The repository's `owner/name`.
918        repository: String,
919        /// The profile it names.
920        profile: String,
921        /// The profiles `[profiles]` defines.
922        defined: Vec<String>,
923    },
924    /// A repository has no labels, or an empty one.
925    #[error("repository {repository} needs at least one non-empty label")]
926    MissingLabels {
927        /// The repository's `owner/name`.
928        repository: String,
929    },
930    /// Two `[[repositories]]` entries of one repository use the same profile.
931    #[error(
932        "repository {repository} has two entries with profile {profile:?}; give each of its pools its own profile"
933    )]
934    PoolProfileTwice {
935        /// The repository's `owner/name`.
936        repository: String,
937        /// The profile both entries name.
938        profile: String,
939    },
940    /// Two `[[repositories]]` entries of one repository share a label, so a job asking only for labels they share
941    /// could run in either.
942    #[error(
943        "repository {repository}'s pools in {first} and {second} both have the label {label:?}, so a job asking for \
944         it could land in either; give each pool labels of its own, such as only {second:?}'s own label for the \
945         lighter one"
946    )]
947    PoolLabelsOverlap {
948        /// The repository's `owner/name`.
949        repository: String,
950        /// The profile of the first entry.
951        first: String,
952        /// The profile of the later entry.
953        second: String,
954        /// A label both have.
955        label: String,
956    },
957    /// Two `[[repositories]]` entries of one repository say differently whose runs write to the build cache.
958    #[error(
959        "repository {repository}'s entries set build_cache_writers differently; whose runs may write to the build \
960         cache is the repository's, so set the same in each"
961    )]
962    PoolWritersDiffer {
963        /// The repository's `owner/name`.
964        repository: String,
965    },
966    /// `unsafe-dind` without `allow_unsafe = true`.
967    #[error(
968        "isolation \"unsafe-dind\" runs runner containers privileged, so a job can take over the host; \
969         set allow_unsafe = true under [host] to use it anyway"
970    )]
971    UnsafeNotAllowed,
972    /// A limit is 0.
973    #[error("{field} is 0; set it above 0")]
974    ZeroLimit {
975        /// The setting, such as `profiles.app.cpus`.
976        field: String,
977    },
978    /// `cpu_overcommit` is not a number above 0 and at most `MAX_CPU_OVERCOMMIT`.
979    #[error(
980        "host.cpu_overcommit is {value}; set it above 0 and at most {MAX_CPU_OVERCOMMIT}, such as 1.0"
981    )]
982    CpuOvercommit {
983        /// The value set.
984        value: f64,
985    },
986    /// `[web] open` is not one of `[web] origins`.
987    #[error(
988        "web.open is {open}, which is not one of [web] origins; add it to origins, or remove open"
989    )]
990    OpenNotListed {
991        /// The origin `open` names.
992        open: Origin,
993    },
994    /// A profile's `memory` or `slots` are outside its `min_memory`, `max_memory` or `max_slots`, or its
995    /// `min_memory` is above its `max_memory`.
996    #[error("profiles.{profile}: {why}")]
997    SizingBounds {
998        /// The profile.
999        profile: String,
1000        /// Which bound, such as `memory is above its max_memory`.
1001        why: &'static str,
1002    },
1003    /// A `[[notify.targets]]` entry cannot be used. Never says its URL or a header's value.
1004    #[error("notify target {target:?}: {why}")]
1005    Notify {
1006        /// The target's name.
1007        target: String,
1008        /// What is wrong, such as `url does not start with https:// or http://`.
1009        why: &'static str,
1010    },
1011    /// `[host] memory_ceiling` is under one runner of a profile and the mirror, so that profile could never start.
1012    #[error(
1013        "host.memory_ceiling is {ceiling}, under the {needs} one runner of {profile} and the mirror take; set it \
1014         to the most memory the host can grow to, such as the VM's maximum"
1015    )]
1016    CeilingUnderProfile {
1017        /// The profile.
1018        profile: String,
1019        /// Its `memory` and the mirror's.
1020        needs: ByteSize,
1021        /// The ceiling set.
1022        ceiling: ByteSize,
1023    },
1024    /// The caps add up past `u64::MAX` bytes.
1025    #[error("slots × memory over all profiles plus the mirror is too large to add up")]
1026    BudgetOverflow,
1027    /// `admission = "measured"` with a slice that has no `MemoryMax` to admit against.
1028    #[error(
1029        "admission = \"measured\" admits runners against the slice {slice}'s MemoryMax, and it has none; install \
1030         a unit file for it (`runnerd doctor` prints one)"
1031    )]
1032    MeasuredWithoutMemoryMax {
1033        /// The slice runners run in.
1034        slice: String,
1035    },
1036    /// Under `admission = "measured"`, one runner of a profile and the mirror do not fit `MemoryMax`.
1037    #[error(
1038        "one runner of {profile} and the mirror take {needs}, the slice {slice}'s MemoryMax is {memory_max}; lower \
1039         its `memory` or raise the slice's MemoryMax"
1040    )]
1041    ProfileOverBudget {
1042        /// The profile.
1043        profile: String,
1044        /// Its `memory` and the mirror's.
1045        needs: ByteSize,
1046        /// The slice runners run in.
1047        slice: String,
1048        /// The slice's `MemoryMax`.
1049        memory_max: ByteSize,
1050    },
1051    /// The caps add up to more than the slice's `MemoryMax`.
1052    #[error(
1053        "slots × memory over all profiles plus the mirror is {total}, \
1054         the slice {slice}'s MemoryMax is {memory_max}; lower `slots` or `memory`, or raise the slice's \
1055         MemoryMax (`runnerd doctor` prints its unit)"
1056    )]
1057    OverBudget {
1058        /// What every runner and the mirror may use at once.
1059        total: ByteSize,
1060        /// The slice runners run in.
1061        slice: String,
1062        /// The slice's `MemoryMax`.
1063        memory_max: ByteSize,
1064    },
1065}
1066
1067fn defined_profiles(defined: &[String]) -> String {
1068    if defined.is_empty() {
1069        "it defines none".to_owned()
1070    } else {
1071        format!("defined: {}", defined.join(", "))
1072    }
1073}
1074
1075/// What a valid config should still fix.
1076#[derive(Debug, Clone, PartialEq, Eq)]
1077pub enum Warning {
1078    /// The slice has no unit file, so systemd creates it without limits.
1079    UnlimitedSlice {
1080        /// The slice runners run in.
1081        slice: String,
1082        /// What every runner and the mirror may use at once.
1083        total: ByteSize,
1084    },
1085}
1086
1087impl fmt::Display for Warning {
1088    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1089        match self {
1090            Warning::UnlimitedSlice { slice, total } => write!(
1091                f,
1092                "the slice {slice} has no MemoryMax, so nothing holds runners to their {total} of caps; \
1093                 install a unit file for it"
1094            ),
1095        }
1096    }
1097}
1098
1099impl Config {
1100    /// Reads and parses a config file.
1101    pub fn load(path: &Path) -> Result<Config, ConfigError> {
1102        let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Read {
1103            path: path.to_owned(),
1104            source,
1105        })?;
1106        Config::parse(&text)
1107    }
1108
1109    /// Parses a config from TOML text.
1110    pub fn parse(text: &str) -> Result<Config, ConfigError> {
1111        Ok(toml::from_str(text)?)
1112    }
1113
1114    /// Parses `text` and validates it against the `MemoryMax` that `memory_max` reads for the slice it names:
1115    /// what `runnerd check-config` prints and `POST /v1/config/check` answers. Returns the config if it is valid.
1116    pub fn check(
1117        text: &str,
1118        memory_max: impl FnOnce(&str) -> std::io::Result<Option<ByteSize>>,
1119    ) -> (Option<Config>, api::ConfigCheck) {
1120        let config = match Config::parse(text) {
1121            Ok(config) => config,
1122            Err(error) => return (None, budget::invalid(error.to_string(), None, None)),
1123        };
1124        let max = match memory_max(&config.host.slice) {
1125            Ok(max) => max,
1126            Err(error) => {
1127                return (
1128                    None,
1129                    budget::invalid(error.to_string(), Some(&config), None),
1130                );
1131            }
1132        };
1133        let check = config.check_against(max);
1134        if check.valid {
1135            (Some(config), check)
1136        } else {
1137            (None, check)
1138        }
1139    }
1140
1141    /// The mirror's memory cap, 0 when it is disabled.
1142    pub fn mirror_memory(&self) -> u64 {
1143        if self.caches.mirror.enabled {
1144            self.caches.mirror.memory.0
1145        } else {
1146            0
1147        }
1148    }
1149
1150    /// The memory every runner and the mirror may use at once.
1151    pub fn memory_caps(&self) -> Result<ByteSize, ConfigError> {
1152        let mirror = self.mirror_memory();
1153        self.profiles
1154            .values()
1155            .try_fold(mirror, |total, p| {
1156                p.memory
1157                    .0
1158                    .checked_mul(u64::from(p.slots))?
1159                    .checked_add(total)
1160            })
1161            .map(ByteSize)
1162            .ok_or(ConfigError::BudgetOverflow)
1163    }
1164
1165    /// The memory `[host] admission` must fit in `MemoryMax`: every cap at once under caps; under measured, the
1166    /// largest single runner with the mirror, since `slots` there only bounds how many run at once.
1167    pub fn memory_needed(&self) -> Result<ByteSize, ConfigError> {
1168        match self.host.admission {
1169            Admission::Caps => self.memory_caps(),
1170            Admission::Measured => {
1171                let largest = self
1172                    .profiles
1173                    .values()
1174                    .map(|p| p.memory.0)
1175                    .max()
1176                    .unwrap_or(0);
1177                largest
1178                    .checked_add(self.mirror_memory())
1179                    .map(ByteSize)
1180                    .ok_or(ConfigError::BudgetOverflow)
1181            }
1182        }
1183    }
1184
1185    /// The most `memory` one runner of any profile may have under `[host] memory_ceiling`: the ceiling less the
1186    /// mirror while it is enabled, as no host of that size starts more beside it. `None` without a ceiling. The
1187    /// config check refuses a profile above it, and auto sizing raises none past it (ADR 0086).
1188    pub fn runner_ceiling(&self) -> Option<u64> {
1189        self.host
1190            .memory_ceiling
1191            .map(|ceiling| ceiling.0.saturating_sub(self.mirror_memory()))
1192    }
1193
1194    /// Refuses a `[host] memory_ceiling` under one runner of the largest profile beside the mirror
1195    /// (`runner_ceiling`): no host of that size starts one, so it is a typo, such as `24M` for `24G`. Whether the
1196    /// host's `MemTotal` is already past it, and what the margin leaves, `runnerd doctor` says, as the config check
1197    /// does not read the host.
1198    fn check_memory_ceiling(&self) -> Result<(), ConfigError> {
1199        let (Some(ceiling), Some(most)) = (self.host.memory_ceiling, self.runner_ceiling()) else {
1200            return Ok(());
1201        };
1202        let largest = self
1203            .profiles
1204            .iter()
1205            .max_by_key(|(_, profile)| profile.memory.0);
1206        match largest {
1207            Some((profile, largest)) if largest.memory.0 > most => {
1208                Err(ConfigError::CeilingUnderProfile {
1209                    profile: profile.clone(),
1210                    needs: ByteSize(largest.memory.0.saturating_add(self.mirror_memory())),
1211                    ceiling,
1212                })
1213            }
1214            _ => Ok(()),
1215        }
1216    }
1217
1218    /// Refuses a profile outside the bounds auto sizing keeps it in, or whose bounds cross.
1219    fn check_sizing_bounds(&self) -> Result<(), ConfigError> {
1220        for (name, p) in &self.profiles {
1221            let memory = p.memory.0;
1222            let field = if p
1223                .min_memory
1224                .zip(p.max_memory)
1225                .is_some_and(|(min, max)| min.0 > max.0)
1226            {
1227                "min_memory is above its max_memory"
1228            } else if p.min_memory.is_some_and(|min| memory < min.0) {
1229                "memory is below its min_memory"
1230            } else if p.max_memory.is_some_and(|max| memory > max.0) {
1231                "memory is above its max_memory"
1232            } else if p.max_slots.is_some_and(|max| p.slots > max) {
1233                "slots are above its max_slots"
1234            } else {
1235                continue;
1236            };
1237            return Err(ConfigError::SizingBounds {
1238                profile: name.clone(),
1239                why: field,
1240            });
1241        }
1242        Ok(())
1243    }
1244
1245    /// Checks that each repository's pools tell its jobs apart: each in its own profile, with labels no other of its
1246    /// pools has, so at most one pool matches a job; and that they agree on whose runs write to the build cache.
1247    fn check_pools(&self) -> Result<(), ConfigError> {
1248        for (at, first) in self.repositories.iter().enumerate() {
1249            for second in self.repositories[at + 1..]
1250                .iter()
1251                .filter(|second| second.name == first.name)
1252            {
1253                if second.profile == first.profile {
1254                    return Err(ConfigError::PoolProfileTwice {
1255                        repository: first.name.clone(),
1256                        profile: first.profile.clone(),
1257                    });
1258                }
1259                if let Some(label) = first.labels.iter().find(|label| {
1260                    second
1261                        .labels
1262                        .iter()
1263                        .any(|other| other.eq_ignore_ascii_case(label))
1264                }) {
1265                    return Err(ConfigError::PoolLabelsOverlap {
1266                        repository: first.name.clone(),
1267                        first: first.profile.clone(),
1268                        second: second.profile.clone(),
1269                        label: label.clone(),
1270                    });
1271                }
1272                if second.build_cache_writers != first.build_cache_writers {
1273                    return Err(ConfigError::PoolWritersDiffer {
1274                        repository: first.name.clone(),
1275                    });
1276                }
1277            }
1278        }
1279        Ok(())
1280    }
1281
1282    /// The pool of `repository` whose labels match a job asking for `labels`: every label it asks for is one of
1283    /// the pool's. `None` when no pool of it does.
1284    pub fn pool(&self, repository: &str, labels: &[String]) -> Option<&Repository> {
1285        self.repositories
1286            .iter()
1287            .find(|pool| pool.name == repository && labels_match(labels, &pool.labels))
1288    }
1289
1290    /// The pool of `repository` in `profile`, whose runners start in that profile's slots.
1291    pub fn pool_in(&self, repository: &str, profile: &str) -> Option<&Repository> {
1292        self.repositories
1293            .iter()
1294            .find(|pool| pool.name == repository && pool.profile == profile)
1295    }
1296
1297    /// The GitHub-hosted runner each profile's jobs are priced at (ADR 0072).
1298    pub fn pricing(&self) -> api::Pricing {
1299        api::Pricing {
1300            profiles: self
1301                .profiles
1302                .iter()
1303                .filter_map(|(name, profile)| Some((name.clone(), profile.priced_as?)))
1304                .collect(),
1305            default_sku: api::Sku::standard_for(std::env::consts::ARCH),
1306        }
1307    }
1308
1309    /// The repositories served, each once, in the order the config first names them.
1310    pub fn repository_names(&self) -> Vec<String> {
1311        let mut names: Vec<String> = Vec::new();
1312        for repository in &self.repositories {
1313            if !names.contains(&repository.name) {
1314                names.push(repository.name.clone());
1315            }
1316        }
1317        names
1318    }
1319
1320    /// Checks the config against the slice's `MemoryMax` (`None` when the slice is unlimited).
1321    pub fn validate(&self, memory_max: Option<ByteSize>) -> Result<Vec<Warning>, ConfigError> {
1322        if self.host.isolation == Isolation::UnsafeDind && !self.host.allow_unsafe {
1323            return Err(ConfigError::UnsafeNotAllowed);
1324        }
1325        let zero_limits = self.profiles.iter().flat_map(|(name, p)| {
1326            [
1327                (p.memory.0 == 0, format!("profiles.{name}.memory")),
1328                (p.cpus == 0, format!("profiles.{name}.cpus")),
1329                (p.slots == 0, format!("profiles.{name}.slots")),
1330                (p.max_slots == Some(0), format!("profiles.{name}.max_slots")),
1331            ]
1332        });
1333        let mirror = &self.caches.mirror;
1334        let mirror_zero_limits = [
1335            (
1336                mirror.enabled && mirror.memory.0 == 0,
1337                "caches.mirror.memory".to_owned(),
1338            ),
1339            (
1340                mirror.enabled && mirror.cpus == 0,
1341                "caches.mirror.cpus".to_owned(),
1342            ),
1343            (
1344                self.host.poll_interval.is_zero(),
1345                "host.poll_interval".to_owned(),
1346            ),
1347            (
1348                self.host.memory_ceiling == Some(ByteSize(0)),
1349                "host.memory_ceiling".to_owned(),
1350            ),
1351            (self.records.max_count == 0, "records.max_count".to_owned()),
1352            (self.sizing.min_jobs == 0, "sizing.min_jobs".to_owned()),
1353            (self.sizing.interval.is_zero(), "sizing.interval".to_owned()),
1354            (
1355                self.sizing.raise_interval.is_zero(),
1356                "sizing.raise_interval".to_owned(),
1357            ),
1358            (self.sizing.max_step == 0, "sizing.max_step".to_owned()),
1359            (
1360                self.records.max_total.0 == 0,
1361                "records.max_total".to_owned(),
1362            ),
1363        ];
1364        if let Some((_, field)) = zero_limits
1365            .chain(mirror_zero_limits)
1366            .find(|(zero, _)| *zero)
1367        {
1368            return Err(ConfigError::ZeroLimit { field });
1369        }
1370        self.check_sizing_bounds()?;
1371        self.caches.build.validate()?;
1372        self.host.check_cpu_overcommit()?;
1373        self.check_memory_ceiling()?;
1374        self.web.validate()?;
1375        self.notify.validate()?;
1376        for repository in &self.repositories {
1377            if !self.profiles.contains_key(&repository.profile) {
1378                return Err(ConfigError::UnknownProfile {
1379                    repository: repository.name.clone(),
1380                    profile: repository.profile.clone(),
1381                    defined: self.profiles.keys().cloned().collect(),
1382                });
1383            }
1384            if repository.labels.is_empty() || repository.labels.iter().any(|l| l.trim().is_empty())
1385            {
1386                return Err(ConfigError::MissingLabels {
1387                    repository: repository.name.clone(),
1388                });
1389            }
1390        }
1391        self.check_pools()?;
1392        self.check_budget(memory_max)
1393    }
1394
1395    /// Holds what `[host] admission` needs to the slice's `MemoryMax`; warns when the slice has none to hold caps to.
1396    fn check_budget(&self, memory_max: Option<ByteSize>) -> Result<Vec<Warning>, ConfigError> {
1397        let total = self.memory_caps()?;
1398        if self.host.admission == Admission::Measured {
1399            let Some(memory_max) = memory_max else {
1400                return Err(ConfigError::MeasuredWithoutMemoryMax {
1401                    slice: self.host.slice.clone(),
1402                });
1403            };
1404            let mirror = self.mirror_memory();
1405            if let Some((profile, needs)) = self
1406                .profiles
1407                .iter()
1408                .map(|(name, profile)| (name, profile.memory.0.saturating_add(mirror)))
1409                .find(|(_, needs)| *needs > memory_max.0)
1410            {
1411                return Err(ConfigError::ProfileOverBudget {
1412                    profile: profile.clone(),
1413                    needs: ByteSize(needs),
1414                    slice: self.host.slice.clone(),
1415                    memory_max,
1416                });
1417            }
1418            // Without a profile, the mirror alone must fit: the caps sum, which is all `memory_needed` holds.
1419            let needed = self.memory_needed()?;
1420            if needed > memory_max {
1421                return Err(ConfigError::OverBudget {
1422                    total: needed,
1423                    slice: self.host.slice.clone(),
1424                    memory_max,
1425                });
1426            }
1427            return Ok(Vec::new());
1428        }
1429        match memory_max {
1430            Some(memory_max) if total > memory_max => Err(ConfigError::OverBudget {
1431                total,
1432                slice: self.host.slice.clone(),
1433                memory_max,
1434            }),
1435            Some(_) => Ok(Vec::new()),
1436            None => Ok(vec![Warning::UnlimitedSlice {
1437                slice: self.host.slice.clone(),
1438                total,
1439            }]),
1440        }
1441    }
1442}
1443
1444/// Why `resize_profile` cannot change a config.
1445#[derive(Debug, thiserror::Error)]
1446pub enum ResizeError {
1447    /// The text is not valid TOML.
1448    #[error(transparent)]
1449    Parse(#[from] toml_edit::TomlError),
1450    /// `[profiles]` does not define the profile.
1451    #[error("the config has no profile {0:?} under [profiles]")]
1452    NoProfile(String),
1453}
1454
1455/// `text` with the profile's `memory` and `slots` replaced, and its `cpus` when `resize` has them, everything else as
1456/// written, comments included: what applying a sizing suggestion sends to `PUT /v1/config`, which validates it.
1457pub fn resize_profile(
1458    text: &str,
1459    profile: &str,
1460    resize: api::Resize,
1461) -> Result<String, ResizeError> {
1462    let mut document: toml_edit::DocumentMut = text.parse()?;
1463    let table = document
1464        .get_mut("profiles")
1465        .and_then(|profiles| profiles.get_mut(profile))
1466        .and_then(toml_edit::Item::as_table_like_mut)
1467        .ok_or_else(|| ResizeError::NoProfile(profile.to_owned()))?;
1468    let values = [
1469        (
1470            "memory",
1471            toml_edit::Value::from(ByteSize(resize.memory).exact()),
1472        ),
1473        ("slots", toml_edit::Value::from(i64::from(resize.slots))),
1474    ];
1475    let cpus = resize
1476        .cpus
1477        .map(|cpus| ("cpus", toml_edit::Value::from(i64::from(cpus))));
1478    for (key, mut value) in values.into_iter().chain(cpus) {
1479        // The comment after the old value stays after the new one.
1480        if let Some(old) = table.get(key).and_then(toml_edit::Item::as_value) {
1481            *value.decor_mut() = old.decor().clone();
1482        }
1483        table.insert(key, toml_edit::Item::Value(value));
1484    }
1485    Ok(document.to_string())
1486}
1487
1488/// `profile`'s `memory`, `slots` and `cpus` in the config `text`, as a sizing start changes them from; `None` when
1489/// `text` is not a config or has no such profile.
1490pub fn profile_sizes(text: &str, profile: &str) -> Option<api::Resize> {
1491    let config = Config::parse(text).ok()?;
1492    let sizes = config.profiles.get(profile)?;
1493    Some(api::Resize {
1494        memory: sizes.memory.0,
1495        slots: sizes.slots,
1496        cpus: Some(sizes.cpus),
1497    })
1498}
1499
1500/// Where `resize_profile` wrote `resize` in `text`: the bytes from the first of the profile's `memory`, `slots` and,
1501/// when `resize` has them, `cpus` settings to the end of the last, so a client can select them. `None` when `text` is
1502/// not TOML or the profile sets none of them.
1503pub fn resized_at(
1504    text: &str,
1505    profile: &str,
1506    resize: api::Resize,
1507) -> Option<std::ops::Range<usize>> {
1508    let document = toml_edit::Document::parse(text).ok()?;
1509    let table = document
1510        .as_table()
1511        .get("profiles")?
1512        .get(profile)?
1513        .as_table_like()?;
1514    let cpus = resize.cpus.map(|_| "cpus");
1515    ["memory", "slots"]
1516        .into_iter()
1517        .chain(cpus)
1518        .filter_map(|key| {
1519            let (key, item) = table.get_key_value(key)?;
1520            Some(key.span()?.start..item.span()?.end)
1521        })
1522        .reduce(|first, next| first.start.min(next.start)..first.end.max(next.end))
1523}
1524
1525/// What `GET /v1/config` shows in place of a notification target's URL and header values (ADR 0051).
1526pub const SECRET_SHOWN: &str = "<secret>";
1527
1528/// `text` with each `[[notify.targets]]` entry's `url` and header values shown as [`SECRET_SHOWN`], everything else
1529/// as written: what `GET /v1/config` answers, so no client, the dashboard's browsers included, holds them. `None`
1530/// when `text` is not TOML.
1531pub fn mask_secrets(text: &str) -> Option<String> {
1532    let mut document: toml_edit::DocumentMut = text.parse().ok()?;
1533    let mut masked = false;
1534    for target in notify_targets(&mut document) {
1535        for (_, value) in secrets_of(target) {
1536            replace_value(value, toml_edit::Value::from(SECRET_SHOWN));
1537            masked = true;
1538        }
1539    }
1540    Some(if masked {
1541        document.to_string()
1542    } else {
1543        text.to_owned()
1544    })
1545}
1546
1547/// `text` with each [`SECRET_SHOWN`] in a target's `url` or headers replaced by the value `stored` has for the target
1548/// of the same name, everything else as written: what `PUT /v1/config` and `POST /v1/config/check` read, so a config
1549/// shown masked saves with its secrets. A value with nothing to keep stays [`SECRET_SHOWN`], which `Config::validate`
1550/// refuses. A text that does not parse as a config is answered as sent: a TOML error quotes the line it is on, and
1551/// that line must hold the mask, not the value put back. One that parses still does with the values put back, as they
1552/// are strings where strings were, and `Config::validate` names a target's field, never its value.
1553pub fn keep_secrets(text: &str, stored: &str) -> String {
1554    if !text.contains(SECRET_SHOWN) || Config::parse(text).is_err() {
1555        return text.to_owned();
1556    }
1557    let (Ok(mut document), Ok(mut old)) = (
1558        text.parse::<toml_edit::DocumentMut>(),
1559        stored.parse::<toml_edit::DocumentMut>(),
1560    ) else {
1561        return text.to_owned();
1562    };
1563    let mut kept: BTreeMap<String, Vec<(SecretField, toml_edit::Value)>> = BTreeMap::new();
1564    for target in notify_targets(&mut old) {
1565        let Some(name) = target_name(target) else {
1566            continue;
1567        };
1568        let secrets = secrets_of(target)
1569            .into_iter()
1570            .map(|(field, value)| (field, value.clone()))
1571            .collect();
1572        kept.insert(name, secrets);
1573    }
1574    for target in notify_targets(&mut document) {
1575        let Some(secrets) = target_name(target).and_then(|name| kept.get(&name)) else {
1576            continue;
1577        };
1578        for (field, value) in secrets_of(target) {
1579            if value.as_str() != Some(SECRET_SHOWN) {
1580                continue;
1581            }
1582            if let Some((_, old)) = secrets.iter().find(|(kept, _)| *kept == field) {
1583                replace_value(value, old.clone());
1584            }
1585        }
1586    }
1587    document.to_string()
1588}
1589
1590/// Where a target keeps a secret.
1591#[derive(Debug, PartialEq, Eq)]
1592enum SecretField {
1593    Url,
1594    Header(String),
1595}
1596
1597/// The tables of `[[notify.targets]]`, or of an inline `targets = [...]`.
1598fn notify_targets(document: &mut toml_edit::DocumentMut) -> Vec<&mut dyn toml_edit::TableLike> {
1599    match document
1600        .get_mut("notify")
1601        .and_then(|notify| notify.get_mut("targets"))
1602    {
1603        Some(toml_edit::Item::ArrayOfTables(tables)) => tables
1604            .iter_mut()
1605            .map(|table| table as &mut dyn toml_edit::TableLike)
1606            .collect(),
1607        Some(toml_edit::Item::Value(toml_edit::Value::Array(array))) => array
1608            .iter_mut()
1609            .filter_map(toml_edit::Value::as_inline_table_mut)
1610            .map(|table| table as &mut dyn toml_edit::TableLike)
1611            .collect(),
1612        _ => Vec::new(),
1613    }
1614}
1615
1616fn target_name(target: &dyn toml_edit::TableLike) -> Option<String> {
1617    target
1618        .get("name")
1619        .and_then(toml_edit::Item::as_str)
1620        .map(str::to_owned)
1621}
1622
1623/// A target's `url` and header values.
1624fn secrets_of(target: &mut dyn toml_edit::TableLike) -> Vec<(SecretField, &mut toml_edit::Value)> {
1625    let mut found = Vec::new();
1626    for (key, item) in target.iter_mut() {
1627        match key.get() {
1628            "url" => found.extend(item.as_value_mut().map(|value| (SecretField::Url, value))),
1629            "headers" => {
1630                let Some(headers) = item.as_table_like_mut() else {
1631                    continue;
1632                };
1633                for (name, item) in headers.iter_mut() {
1634                    let field = SecretField::Header(name.get().to_owned());
1635                    found.extend(item.as_value_mut().map(|value| (field, value)));
1636                }
1637            }
1638            _ => {}
1639        }
1640    }
1641    found
1642}
1643
1644/// Puts `new` in place of `value`, with the spaces and comment around it as they were.
1645fn replace_value(value: &mut toml_edit::Value, mut new: toml_edit::Value) {
1646    *new.decor_mut() = value.decor().clone();
1647    *value = new;
1648}
1649
1650/// A config text's revision: a hash of its bytes (64-bit FNV-1a, in hex), the same in every runnerd. `PUT
1651/// /v1/config?revision=` refuses a text sent against another revision than the daemon's.
1652pub fn revision(text: &str) -> String {
1653    let hash = text.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
1654        (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
1655    });
1656    format!("{hash:016x}")
1657}
1658
1659/// Reads a slice's `MemoryMax` from systemd; `None` when it is unlimited.
1660pub fn slice_memory_max(slice: &str) -> std::io::Result<Option<ByteSize>> {
1661    let output = Command::new("systemctl")
1662        .args(["show", slice, "--property=MemoryMax", "--value"])
1663        .output()?;
1664    if !output.status.success() {
1665        return Err(std::io::Error::other(format!(
1666            "systemctl show {slice} failed: {}",
1667            String::from_utf8_lossy(&output.stderr).trim()
1668        )));
1669    }
1670    let value = String::from_utf8_lossy(&output.stdout);
1671    parse_memory_max(value.trim()).ok_or_else(|| {
1672        std::io::Error::other(format!(
1673            "systemctl show {slice}: unexpected MemoryMax {value:?}"
1674        ))
1675    })
1676}
1677
1678/// The CPU budget, in millicores, of `millicores` of CPUs overcommitted `overcommit` times.
1679pub fn cpu_budget(millicores: u64, overcommit: f64) -> u64 {
1680    #[expect(
1681        clippy::cast_precision_loss,
1682        clippy::cast_possible_truncation,
1683        clippy::cast_sign_loss,
1684        reason = "a host's millicores are far below 2^52, and the config check holds the factor above 0 and at \
1685                  most 16"
1686    )]
1687    let budget = (millicores as f64 * overcommit.max(0.0)).round() as u64;
1688    budget
1689}
1690
1691/// Reads the CPUs a slice's processes may use from systemd, in millicores: its `EffectiveCPUs` (or `AllowedCPUs`,
1692/// else the host's CPUs), less when its `CPUQuota` is lower.
1693pub fn slice_cpus(slice: &str) -> std::io::Result<u64> {
1694    let output = Command::new("systemctl")
1695        .args([
1696            "show",
1697            slice,
1698            "--property=EffectiveCPUs",
1699            "--property=AllowedCPUs",
1700            "--property=CPUQuotaPerSecUSec",
1701        ])
1702        .output()?;
1703    if !output.status.success() {
1704        return Err(std::io::Error::other(format!(
1705            "systemctl show {slice} failed: {}",
1706            String::from_utf8_lossy(&output.stderr).trim()
1707        )));
1708    }
1709    let host = std::thread::available_parallelism().map_or(1, std::num::NonZero::get) as u64;
1710    parse_slice_cpus(&String::from_utf8_lossy(&output.stdout), host).ok_or_else(|| {
1711        std::io::Error::other(format!(
1712            "systemctl show {slice}: unexpected CPU properties {:?}",
1713            String::from_utf8_lossy(&output.stdout).trim()
1714        ))
1715    })
1716}
1717
1718/// The CPUs, in millicores, that `systemctl show`'s `EffectiveCPUs`, `AllowedCPUs` and `CPUQuotaPerSecUSec` lines
1719/// leave a slice on a host with `host` CPUs; `None` when a value does not parse.
1720pub fn parse_slice_cpus(properties: &str, host: u64) -> Option<u64> {
1721    let value = |name: &str| {
1722        properties.lines().find_map(|line| {
1723            line.strip_prefix(name)
1724                .and_then(|rest| rest.strip_prefix('='))
1725                .map(str::trim)
1726        })
1727    };
1728    let set = [value("EffectiveCPUs"), value("AllowedCPUs")]
1729        .into_iter()
1730        .flatten()
1731        .find(|cpus| !cpus.is_empty());
1732    let cpus = match set {
1733        Some(set) => cpu_count(set)?,
1734        None => host,
1735    };
1736    let quota = match value("CPUQuotaPerSecUSec") {
1737        None | Some("" | "infinity") => u64::MAX,
1738        Some(quota) => quota_millicores(quota)?,
1739    };
1740    Some(cpus.saturating_mul(1000).min(quota))
1741}
1742
1743/// How many CPUs a set names, as systemd prints it (`0-3 8-11`) or as it is written (`0-3,8,10-11`).
1744fn cpu_count(set: &str) -> Option<u64> {
1745    set.split([',', ' '])
1746        .filter(|range| !range.is_empty())
1747        .try_fold(0u64, |count, range| {
1748            let (first, last) = range.split_once('-').unwrap_or((range, range));
1749            let (first, last): (u64, u64) = (first.parse().ok()?, last.parse().ok()?);
1750            Some(count + last.checked_sub(first)? + 1)
1751        })
1752}
1753
1754/// A `CPUQuotaPerSecUSec` as systemd prints a timespan, such as `800ms`, `2.500000s` or `1min 4s`, as the
1755/// millicores it allows: a second of CPU time each second is 1000.
1756fn quota_millicores(quota: &str) -> Option<u64> {
1757    // Each unit's length in milliseconds, as systemd's `format_timespan` names them.
1758    const UNITS: [(&str, f64); 10] = [
1759        ("y", 31_557_600_000.0),
1760        ("M", 2_629_800_000.0),
1761        ("w", 604_800_000.0),
1762        ("d", 86_400_000.0),
1763        ("h", 3_600_000.0),
1764        ("min", 60_000.0),
1765        ("s", 1000.0),
1766        ("ms", 1.0),
1767        ("us", 0.001),
1768        ("µs", 0.001),
1769    ];
1770    let millicores = quota.split_whitespace().try_fold(0.0, |total, part| {
1771        let at = part.find(|c: char| !(c.is_ascii_digit() || c == '.'))?;
1772        let (number, unit) = part.split_at(at);
1773        let per_unit = UNITS
1774            .iter()
1775            .find_map(|(name, per_unit)| (*name == unit).then_some(*per_unit))?;
1776        Some(total + number.parse::<f64>().ok()? * per_unit)
1777    })?;
1778    #[allow(
1779        clippy::cast_possible_truncation,
1780        clippy::cast_sign_loss,
1781        reason = "a quota is a few thousand millicores per CPU, checked finite and not negative first"
1782    )]
1783    (!quota.trim().is_empty() && millicores.is_finite() && millicores >= 0.0)
1784        .then(|| millicores.round() as u64)
1785}
1786
1787/// Parses a `MemoryMax` value as `systemctl show` prints it: bytes, or `infinity`.
1788pub fn parse_memory_max(value: &str) -> Option<Option<ByteSize>> {
1789    if value == "infinity" {
1790        Some(None)
1791    } else {
1792        value.parse().ok().map(|bytes| Some(ByteSize(bytes)))
1793    }
1794}
1795
1796/// A size in bytes, written with a binary unit as Docker and systemd do: `512M`, `9G`, `32.5G`.
1797#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1798pub struct ByteSize(pub u64);
1799
1800const UNITS: [(char, u64); 4] = [
1801    ('T', 1 << 40),
1802    ('G', 1 << 30),
1803    ('M', 1 << 20),
1804    ('K', 1 << 10),
1805];
1806
1807impl FromStr for ByteSize {
1808    type Err = String;
1809
1810    #[allow(
1811        clippy::cast_precision_loss,
1812        clippy::cast_possible_truncation,
1813        clippy::cast_sign_loss,
1814        reason = "sizes in a config are far below 2^52 bytes, and the result is checked against u64's range first"
1815    )]
1816    fn from_str(s: &str) -> Result<Self, Self::Err> {
1817        let invalid = || {
1818            format!(
1819                "invalid size {s:?}, expected a number and a unit (K, M, G or T), such as \"9G\""
1820            )
1821        };
1822        let unit = s.chars().last().ok_or_else(invalid)?.to_ascii_uppercase();
1823        let (_, factor) = UNITS.iter().find(|(u, _)| *u == unit).ok_or_else(invalid)?;
1824        let number = &s[..s.len() - 1];
1825        if number.is_empty() || !number.chars().all(|c| c.is_ascii_digit() || c == '.') {
1826            return Err(invalid());
1827        }
1828        let number: f64 = number.parse().map_err(|_| invalid())?;
1829        let bytes = (number * *factor as f64).round();
1830        // `u64::MAX as f64` is 2^64, the first value out of range.
1831        if bytes >= u64::MAX as f64 {
1832            return Err(format!("size {s:?} is too large"));
1833        }
1834        Ok(ByteSize(bytes as u64))
1835    }
1836}
1837
1838impl fmt::Display for ByteSize {
1839    #[allow(
1840        clippy::cast_precision_loss,
1841        reason = "shown with two decimals, far coarser than f64's precision"
1842    )]
1843    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1844        let Some((unit, factor)) = UNITS.iter().find(|(_, factor)| self.0 >= *factor) else {
1845            return write!(f, "{}B", self.0);
1846        };
1847        let number = format!("{:.2}", self.0 as f64 / *factor as f64);
1848        let number = number.trim_end_matches('0').trim_end_matches('.');
1849        write!(f, "{number}{unit}")
1850    }
1851}
1852
1853impl ByteSize {
1854    /// The size as a config file writes it, reading back to the byte: `Display`'s form when that reads back as it,
1855    /// else the shortest exact decimal in one of the units, such as `1029.5G` where `Display` says `1.01T`. A size
1856    /// written from it, as auto sizing writes `memory`, is the size the config check then reads.
1857    #[allow(
1858        clippy::cast_precision_loss,
1859        reason = "a unit is a power of two, so the quotient is exact below 2^53 bytes; the parse checks it"
1860    )]
1861    pub fn exact(self) -> String {
1862        let reads_back = |text: &String| text.parse::<ByteSize>() == Ok(self);
1863        let shown = self.to_string();
1864        if reads_back(&shown) {
1865            return shown;
1866        }
1867        let mut shortest: Option<String> = None;
1868        for (unit, factor) in UNITS {
1869            let text = format!("{}{unit}", self.0 as f64 / factor as f64);
1870            if reads_back(&text) && shortest.as_ref().is_none_or(|best| text.len() < best.len()) {
1871                shortest = Some(text);
1872            }
1873        }
1874        shortest.unwrap_or(shown)
1875    }
1876
1877    /// The size rounded to the nearest, for a label too narrow for its `Display`: two significant digits below 10
1878    /// of its unit, whole units above, and the next unit up once it rounds to 1024: `3.3G` for 3.25G, `12G`,
1879    /// `512M`, and `1G` for 1023.5M. Every client's budget bar labels a block with it.
1880    #[allow(
1881        clippy::cast_precision_loss,
1882        reason = "shown with one decimal at most, far coarser than f64's precision"
1883    )]
1884    pub fn short(self) -> String {
1885        let Some(index) = UNITS.iter().position(|(_, factor)| self.0 >= *factor) else {
1886            return format!("{}B", self.0);
1887        };
1888        let (mut unit, factor) = UNITS[index];
1889        let mut value = self.0 as f64 / factor as f64;
1890        if value.round() >= 1024.0
1891            && let Some(larger) = index.checked_sub(1)
1892        {
1893            unit = UNITS[larger].0;
1894            value /= 1024.0;
1895        }
1896        // Halves round up, as `f64::round` does and formatting, which rounds them to even, does not.
1897        let tenths = (value * 10.0).round() / 10.0;
1898        if tenths < 10.0 {
1899            let number = format!("{tenths:.1}");
1900            format!("{}{unit}", number.trim_end_matches(".0"))
1901        } else {
1902            format!("{:.0}{unit}", value.round())
1903        }
1904    }
1905}
1906
1907impl<'de> Deserialize<'de> for ByteSize {
1908    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1909        String::deserialize(deserializer)?
1910            .parse()
1911            .map_err(de::Error::custom)
1912    }
1913}
1914
1915/// Parses a duration as Go and the registry write it, `30s`, `90m`, `168h`, or in days: `7d`.
1916pub fn parse_duration(s: &str) -> Result<Duration, String> {
1917    let invalid = || {
1918        format!(
1919            "invalid duration {s:?}, expected a number and s, m, h or d, such as \"168h\" or \"7d\""
1920        )
1921    };
1922    let (number, factor) = match s.chars().last() {
1923        Some('s') => (&s[..s.len() - 1], 1),
1924        Some('m') => (&s[..s.len() - 1], 60),
1925        Some('h') => (&s[..s.len() - 1], 3600),
1926        Some('d') => (&s[..s.len() - 1], 86400),
1927        _ => return Err(invalid()),
1928    };
1929    let number: u64 = number.parse().map_err(|_| invalid())?;
1930    number
1931        .checked_mul(factor)
1932        .map(Duration::from_secs)
1933        .ok_or_else(invalid)
1934}
1935
1936/// Parses an age as the clients' `--since` and `--older-than` take it: `30m`, `12h`, `7d`, `2w`.
1937pub fn parse_age(text: &str) -> Result<Duration, String> {
1938    let error = || "expected a number and s, m, h, d or w, such as 12h".to_owned();
1939    let split = text.find(|c: char| !c.is_ascii_digit()).ok_or_else(error)?;
1940    let (number, unit) = text.split_at(split);
1941    let number: u64 = number.parse().map_err(|_| error())?;
1942    let unit = match unit {
1943        "s" => 1,
1944        "m" => 60,
1945        "h" => 3600,
1946        "d" => 86_400,
1947        "w" => 7 * 86_400,
1948        _ => return Err(error()),
1949    };
1950    Ok(Duration::from_secs(number.saturating_mul(unit)))
1951}
1952
1953fn duration<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Duration, D::Error> {
1954    parse_duration(&String::deserialize(deserializer)?).map_err(de::Error::custom)
1955}
1956
1957#[cfg(test)]
1958mod tests;