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