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