Skip to main content

runnerd_core/
config.rs

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