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.23`.
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.23`.
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    /// Refuses a `[host] memory_ceiling` under one runner of the largest profile beside the mirror: no host of that
1177    /// size starts one, so it is a typo, such as `24M` for `24G`. Whether the host's `MemTotal` is already past it,
1178    /// and what the margin leaves, `runnerd doctor` says, as the config check does not read the host.
1179    fn check_memory_ceiling(&self) -> Result<(), ConfigError> {
1180        let Some(ceiling) = self.host.memory_ceiling else {
1181            return Ok(());
1182        };
1183        let mirror = self.mirror_memory();
1184        let largest = self
1185            .profiles
1186            .iter()
1187            .map(|(name, profile)| (name, profile.memory.0.saturating_add(mirror)))
1188            .max_by_key(|(_, needs)| *needs);
1189        match largest {
1190            Some((profile, needs)) if needs > ceiling.0 => Err(ConfigError::CeilingUnderProfile {
1191                profile: profile.clone(),
1192                needs: ByteSize(needs),
1193                ceiling,
1194            }),
1195            _ => Ok(()),
1196        }
1197    }
1198
1199    /// Refuses a profile outside the bounds auto sizing keeps it in, or whose bounds cross.
1200    fn check_sizing_bounds(&self) -> Result<(), ConfigError> {
1201        for (name, p) in &self.profiles {
1202            let memory = p.memory.0;
1203            let field = if p
1204                .min_memory
1205                .zip(p.max_memory)
1206                .is_some_and(|(min, max)| min.0 > max.0)
1207            {
1208                "min_memory is above its max_memory"
1209            } else if p.min_memory.is_some_and(|min| memory < min.0) {
1210                "memory is below its min_memory"
1211            } else if p.max_memory.is_some_and(|max| memory > max.0) {
1212                "memory is above its max_memory"
1213            } else if p.max_slots.is_some_and(|max| p.slots > max) {
1214                "slots are above its max_slots"
1215            } else {
1216                continue;
1217            };
1218            return Err(ConfigError::SizingBounds {
1219                profile: name.clone(),
1220                why: field,
1221            });
1222        }
1223        Ok(())
1224    }
1225
1226    /// Checks that each repository's pools tell its jobs apart: each in its own profile, with labels no other of its
1227    /// pools has, so at most one pool matches a job; and that they agree on whose runs write to the build cache.
1228    fn check_pools(&self) -> Result<(), ConfigError> {
1229        for (at, first) in self.repositories.iter().enumerate() {
1230            for second in self.repositories[at + 1..]
1231                .iter()
1232                .filter(|second| second.name == first.name)
1233            {
1234                if second.profile == first.profile {
1235                    return Err(ConfigError::PoolProfileTwice {
1236                        repository: first.name.clone(),
1237                        profile: first.profile.clone(),
1238                    });
1239                }
1240                if let Some(label) = first.labels.iter().find(|label| {
1241                    second
1242                        .labels
1243                        .iter()
1244                        .any(|other| other.eq_ignore_ascii_case(label))
1245                }) {
1246                    return Err(ConfigError::PoolLabelsOverlap {
1247                        repository: first.name.clone(),
1248                        first: first.profile.clone(),
1249                        second: second.profile.clone(),
1250                        label: label.clone(),
1251                    });
1252                }
1253                if second.build_cache_writers != first.build_cache_writers {
1254                    return Err(ConfigError::PoolWritersDiffer {
1255                        repository: first.name.clone(),
1256                    });
1257                }
1258            }
1259        }
1260        Ok(())
1261    }
1262
1263    /// The pool of `repository` whose labels match a job asking for `labels`: every label it asks for is one of
1264    /// the pool's. `None` when no pool of it does.
1265    pub fn pool(&self, repository: &str, labels: &[String]) -> Option<&Repository> {
1266        self.repositories
1267            .iter()
1268            .find(|pool| pool.name == repository && labels_match(labels, &pool.labels))
1269    }
1270
1271    /// The pool of `repository` in `profile`, whose runners start in that profile's slots.
1272    pub fn pool_in(&self, repository: &str, profile: &str) -> Option<&Repository> {
1273        self.repositories
1274            .iter()
1275            .find(|pool| pool.name == repository && pool.profile == profile)
1276    }
1277
1278    /// The GitHub-hosted runner each profile's jobs are priced at (ADR 0072).
1279    pub fn pricing(&self) -> api::Pricing {
1280        api::Pricing {
1281            profiles: self
1282                .profiles
1283                .iter()
1284                .filter_map(|(name, profile)| Some((name.clone(), profile.priced_as?)))
1285                .collect(),
1286            default_sku: api::Sku::standard_for(std::env::consts::ARCH),
1287        }
1288    }
1289
1290    /// The repositories served, each once, in the order the config first names them.
1291    pub fn repository_names(&self) -> Vec<String> {
1292        let mut names: Vec<String> = Vec::new();
1293        for repository in &self.repositories {
1294            if !names.contains(&repository.name) {
1295                names.push(repository.name.clone());
1296            }
1297        }
1298        names
1299    }
1300
1301    /// Checks the config against the slice's `MemoryMax` (`None` when the slice is unlimited).
1302    pub fn validate(&self, memory_max: Option<ByteSize>) -> Result<Vec<Warning>, ConfigError> {
1303        if self.host.isolation == Isolation::UnsafeDind && !self.host.allow_unsafe {
1304            return Err(ConfigError::UnsafeNotAllowed);
1305        }
1306        let zero_limits = self.profiles.iter().flat_map(|(name, p)| {
1307            [
1308                (p.memory.0 == 0, format!("profiles.{name}.memory")),
1309                (p.cpus == 0, format!("profiles.{name}.cpus")),
1310                (p.slots == 0, format!("profiles.{name}.slots")),
1311                (p.max_slots == Some(0), format!("profiles.{name}.max_slots")),
1312            ]
1313        });
1314        let mirror = &self.caches.mirror;
1315        let mirror_zero_limits = [
1316            (
1317                mirror.enabled && mirror.memory.0 == 0,
1318                "caches.mirror.memory".to_owned(),
1319            ),
1320            (
1321                mirror.enabled && mirror.cpus == 0,
1322                "caches.mirror.cpus".to_owned(),
1323            ),
1324            (
1325                self.host.poll_interval.is_zero(),
1326                "host.poll_interval".to_owned(),
1327            ),
1328            (
1329                self.host.memory_ceiling == Some(ByteSize(0)),
1330                "host.memory_ceiling".to_owned(),
1331            ),
1332            (self.records.max_count == 0, "records.max_count".to_owned()),
1333            (self.sizing.min_jobs == 0, "sizing.min_jobs".to_owned()),
1334            (self.sizing.interval.is_zero(), "sizing.interval".to_owned()),
1335            (
1336                self.sizing.raise_interval.is_zero(),
1337                "sizing.raise_interval".to_owned(),
1338            ),
1339            (self.sizing.max_step == 0, "sizing.max_step".to_owned()),
1340            (
1341                self.records.max_total.0 == 0,
1342                "records.max_total".to_owned(),
1343            ),
1344        ];
1345        if let Some((_, field)) = zero_limits
1346            .chain(mirror_zero_limits)
1347            .find(|(zero, _)| *zero)
1348        {
1349            return Err(ConfigError::ZeroLimit { field });
1350        }
1351        self.check_sizing_bounds()?;
1352        self.caches.build.validate()?;
1353        self.host.check_cpu_overcommit()?;
1354        self.check_memory_ceiling()?;
1355        self.web.validate()?;
1356        self.notify.validate()?;
1357        for repository in &self.repositories {
1358            if !self.profiles.contains_key(&repository.profile) {
1359                return Err(ConfigError::UnknownProfile {
1360                    repository: repository.name.clone(),
1361                    profile: repository.profile.clone(),
1362                    defined: self.profiles.keys().cloned().collect(),
1363                });
1364            }
1365            if repository.labels.is_empty() || repository.labels.iter().any(|l| l.trim().is_empty())
1366            {
1367                return Err(ConfigError::MissingLabels {
1368                    repository: repository.name.clone(),
1369                });
1370            }
1371        }
1372        self.check_pools()?;
1373        self.check_budget(memory_max)
1374    }
1375
1376    /// Holds what `[host] admission` needs to the slice's `MemoryMax`; warns when the slice has none to hold caps to.
1377    fn check_budget(&self, memory_max: Option<ByteSize>) -> Result<Vec<Warning>, ConfigError> {
1378        let total = self.memory_caps()?;
1379        if self.host.admission == Admission::Measured {
1380            let Some(memory_max) = memory_max else {
1381                return Err(ConfigError::MeasuredWithoutMemoryMax {
1382                    slice: self.host.slice.clone(),
1383                });
1384            };
1385            let mirror = self.mirror_memory();
1386            if let Some((profile, needs)) = self
1387                .profiles
1388                .iter()
1389                .map(|(name, profile)| (name, profile.memory.0.saturating_add(mirror)))
1390                .find(|(_, needs)| *needs > memory_max.0)
1391            {
1392                return Err(ConfigError::ProfileOverBudget {
1393                    profile: profile.clone(),
1394                    needs: ByteSize(needs),
1395                    slice: self.host.slice.clone(),
1396                    memory_max,
1397                });
1398            }
1399            // Without a profile, the mirror alone must fit: the caps sum, which is all `memory_needed` holds.
1400            let needed = self.memory_needed()?;
1401            if needed > memory_max {
1402                return Err(ConfigError::OverBudget {
1403                    total: needed,
1404                    slice: self.host.slice.clone(),
1405                    memory_max,
1406                });
1407            }
1408            return Ok(Vec::new());
1409        }
1410        match memory_max {
1411            Some(memory_max) if total > memory_max => Err(ConfigError::OverBudget {
1412                total,
1413                slice: self.host.slice.clone(),
1414                memory_max,
1415            }),
1416            Some(_) => Ok(Vec::new()),
1417            None => Ok(vec![Warning::UnlimitedSlice {
1418                slice: self.host.slice.clone(),
1419                total,
1420            }]),
1421        }
1422    }
1423}
1424
1425/// Why `resize_profile` cannot change a config.
1426#[derive(Debug, thiserror::Error)]
1427pub enum ResizeError {
1428    /// The text is not valid TOML.
1429    #[error(transparent)]
1430    Parse(#[from] toml_edit::TomlError),
1431    /// `[profiles]` does not define the profile.
1432    #[error("the config has no profile {0:?} under [profiles]")]
1433    NoProfile(String),
1434}
1435
1436/// `text` with the profile's `memory` and `slots` replaced, and its `cpus` when `resize` has them, everything else as
1437/// written, comments included: what applying a sizing suggestion sends to `PUT /v1/config`, which validates it.
1438pub fn resize_profile(
1439    text: &str,
1440    profile: &str,
1441    resize: api::Resize,
1442) -> Result<String, ResizeError> {
1443    let mut document: toml_edit::DocumentMut = text.parse()?;
1444    let table = document
1445        .get_mut("profiles")
1446        .and_then(|profiles| profiles.get_mut(profile))
1447        .and_then(toml_edit::Item::as_table_like_mut)
1448        .ok_or_else(|| ResizeError::NoProfile(profile.to_owned()))?;
1449    let values = [
1450        (
1451            "memory",
1452            toml_edit::Value::from(ByteSize(resize.memory).to_string()),
1453        ),
1454        ("slots", toml_edit::Value::from(i64::from(resize.slots))),
1455    ];
1456    let cpus = resize
1457        .cpus
1458        .map(|cpus| ("cpus", toml_edit::Value::from(i64::from(cpus))));
1459    for (key, mut value) in values.into_iter().chain(cpus) {
1460        // The comment after the old value stays after the new one.
1461        if let Some(old) = table.get(key).and_then(toml_edit::Item::as_value) {
1462            *value.decor_mut() = old.decor().clone();
1463        }
1464        table.insert(key, toml_edit::Item::Value(value));
1465    }
1466    Ok(document.to_string())
1467}
1468
1469/// What `GET /v1/config` shows in place of a notification target's URL and header values (ADR 0051).
1470pub const SECRET_SHOWN: &str = "<secret>";
1471
1472/// `text` with each `[[notify.targets]]` entry's `url` and header values shown as [`SECRET_SHOWN`], everything else
1473/// as written: what `GET /v1/config` answers, so no client, the dashboard's browsers included, holds them. `None`
1474/// when `text` is not TOML.
1475pub fn mask_secrets(text: &str) -> Option<String> {
1476    let mut document: toml_edit::DocumentMut = text.parse().ok()?;
1477    let mut masked = false;
1478    for target in notify_targets(&mut document) {
1479        for (_, value) in secrets_of(target) {
1480            replace_value(value, toml_edit::Value::from(SECRET_SHOWN));
1481            masked = true;
1482        }
1483    }
1484    Some(if masked {
1485        document.to_string()
1486    } else {
1487        text.to_owned()
1488    })
1489}
1490
1491/// `text` with each [`SECRET_SHOWN`] in a target's `url` or headers replaced by the value `stored` has for the target
1492/// of the same name, everything else as written: what `PUT /v1/config` and `POST /v1/config/check` read, so a config
1493/// shown masked saves with its secrets. A value with nothing to keep stays [`SECRET_SHOWN`], which `Config::validate`
1494/// refuses. A text that does not parse as a config is answered as sent: a TOML error quotes the line it is on, and
1495/// that line must hold the mask, not the value put back. One that parses still does with the values put back, as they
1496/// are strings where strings were, and `Config::validate` names a target's field, never its value.
1497pub fn keep_secrets(text: &str, stored: &str) -> String {
1498    if !text.contains(SECRET_SHOWN) || Config::parse(text).is_err() {
1499        return text.to_owned();
1500    }
1501    let (Ok(mut document), Ok(mut old)) = (
1502        text.parse::<toml_edit::DocumentMut>(),
1503        stored.parse::<toml_edit::DocumentMut>(),
1504    ) else {
1505        return text.to_owned();
1506    };
1507    let mut kept: BTreeMap<String, Vec<(SecretField, toml_edit::Value)>> = BTreeMap::new();
1508    for target in notify_targets(&mut old) {
1509        let Some(name) = target_name(target) else {
1510            continue;
1511        };
1512        let secrets = secrets_of(target)
1513            .into_iter()
1514            .map(|(field, value)| (field, value.clone()))
1515            .collect();
1516        kept.insert(name, secrets);
1517    }
1518    for target in notify_targets(&mut document) {
1519        let Some(secrets) = target_name(target).and_then(|name| kept.get(&name)) else {
1520            continue;
1521        };
1522        for (field, value) in secrets_of(target) {
1523            if value.as_str() != Some(SECRET_SHOWN) {
1524                continue;
1525            }
1526            if let Some((_, old)) = secrets.iter().find(|(kept, _)| *kept == field) {
1527                replace_value(value, old.clone());
1528            }
1529        }
1530    }
1531    document.to_string()
1532}
1533
1534/// Where a target keeps a secret.
1535#[derive(Debug, PartialEq, Eq)]
1536enum SecretField {
1537    Url,
1538    Header(String),
1539}
1540
1541/// The tables of `[[notify.targets]]`, or of an inline `targets = [...]`.
1542fn notify_targets(document: &mut toml_edit::DocumentMut) -> Vec<&mut dyn toml_edit::TableLike> {
1543    match document
1544        .get_mut("notify")
1545        .and_then(|notify| notify.get_mut("targets"))
1546    {
1547        Some(toml_edit::Item::ArrayOfTables(tables)) => tables
1548            .iter_mut()
1549            .map(|table| table as &mut dyn toml_edit::TableLike)
1550            .collect(),
1551        Some(toml_edit::Item::Value(toml_edit::Value::Array(array))) => array
1552            .iter_mut()
1553            .filter_map(toml_edit::Value::as_inline_table_mut)
1554            .map(|table| table as &mut dyn toml_edit::TableLike)
1555            .collect(),
1556        _ => Vec::new(),
1557    }
1558}
1559
1560fn target_name(target: &dyn toml_edit::TableLike) -> Option<String> {
1561    target
1562        .get("name")
1563        .and_then(toml_edit::Item::as_str)
1564        .map(str::to_owned)
1565}
1566
1567/// A target's `url` and header values.
1568fn secrets_of(target: &mut dyn toml_edit::TableLike) -> Vec<(SecretField, &mut toml_edit::Value)> {
1569    let mut found = Vec::new();
1570    for (key, item) in target.iter_mut() {
1571        match key.get() {
1572            "url" => found.extend(item.as_value_mut().map(|value| (SecretField::Url, value))),
1573            "headers" => {
1574                let Some(headers) = item.as_table_like_mut() else {
1575                    continue;
1576                };
1577                for (name, item) in headers.iter_mut() {
1578                    let field = SecretField::Header(name.get().to_owned());
1579                    found.extend(item.as_value_mut().map(|value| (field, value)));
1580                }
1581            }
1582            _ => {}
1583        }
1584    }
1585    found
1586}
1587
1588/// Puts `new` in place of `value`, with the spaces and comment around it as they were.
1589fn replace_value(value: &mut toml_edit::Value, mut new: toml_edit::Value) {
1590    *new.decor_mut() = value.decor().clone();
1591    *value = new;
1592}
1593
1594/// A config text's revision: a hash of its bytes (64-bit FNV-1a, in hex), the same in every runnerd. `PUT
1595/// /v1/config?revision=` refuses a text sent against another revision than the daemon's.
1596pub fn revision(text: &str) -> String {
1597    let hash = text.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
1598        (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
1599    });
1600    format!("{hash:016x}")
1601}
1602
1603/// Reads a slice's `MemoryMax` from systemd; `None` when it is unlimited.
1604pub fn slice_memory_max(slice: &str) -> std::io::Result<Option<ByteSize>> {
1605    let output = Command::new("systemctl")
1606        .args(["show", slice, "--property=MemoryMax", "--value"])
1607        .output()?;
1608    if !output.status.success() {
1609        return Err(std::io::Error::other(format!(
1610            "systemctl show {slice} failed: {}",
1611            String::from_utf8_lossy(&output.stderr).trim()
1612        )));
1613    }
1614    let value = String::from_utf8_lossy(&output.stdout);
1615    parse_memory_max(value.trim()).ok_or_else(|| {
1616        std::io::Error::other(format!(
1617            "systemctl show {slice}: unexpected MemoryMax {value:?}"
1618        ))
1619    })
1620}
1621
1622/// The CPU budget, in millicores, of `millicores` of CPUs overcommitted `overcommit` times.
1623pub fn cpu_budget(millicores: u64, overcommit: f64) -> u64 {
1624    #[expect(
1625        clippy::cast_precision_loss,
1626        clippy::cast_possible_truncation,
1627        clippy::cast_sign_loss,
1628        reason = "a host's millicores are far below 2^52, and the config check holds the factor above 0 and at \
1629                  most 16"
1630    )]
1631    let budget = (millicores as f64 * overcommit.max(0.0)).round() as u64;
1632    budget
1633}
1634
1635/// Reads the CPUs a slice's processes may use from systemd, in millicores: its `EffectiveCPUs` (or `AllowedCPUs`,
1636/// else the host's CPUs), less when its `CPUQuota` is lower.
1637pub fn slice_cpus(slice: &str) -> std::io::Result<u64> {
1638    let output = Command::new("systemctl")
1639        .args([
1640            "show",
1641            slice,
1642            "--property=EffectiveCPUs",
1643            "--property=AllowedCPUs",
1644            "--property=CPUQuotaPerSecUSec",
1645        ])
1646        .output()?;
1647    if !output.status.success() {
1648        return Err(std::io::Error::other(format!(
1649            "systemctl show {slice} failed: {}",
1650            String::from_utf8_lossy(&output.stderr).trim()
1651        )));
1652    }
1653    let host = std::thread::available_parallelism().map_or(1, std::num::NonZero::get) as u64;
1654    parse_slice_cpus(&String::from_utf8_lossy(&output.stdout), host).ok_or_else(|| {
1655        std::io::Error::other(format!(
1656            "systemctl show {slice}: unexpected CPU properties {:?}",
1657            String::from_utf8_lossy(&output.stdout).trim()
1658        ))
1659    })
1660}
1661
1662/// The CPUs, in millicores, that `systemctl show`'s `EffectiveCPUs`, `AllowedCPUs` and `CPUQuotaPerSecUSec` lines
1663/// leave a slice on a host with `host` CPUs; `None` when a value does not parse.
1664pub fn parse_slice_cpus(properties: &str, host: u64) -> Option<u64> {
1665    let value = |name: &str| {
1666        properties.lines().find_map(|line| {
1667            line.strip_prefix(name)
1668                .and_then(|rest| rest.strip_prefix('='))
1669                .map(str::trim)
1670        })
1671    };
1672    let set = [value("EffectiveCPUs"), value("AllowedCPUs")]
1673        .into_iter()
1674        .flatten()
1675        .find(|cpus| !cpus.is_empty());
1676    let cpus = match set {
1677        Some(set) => cpu_count(set)?,
1678        None => host,
1679    };
1680    let quota = match value("CPUQuotaPerSecUSec") {
1681        None | Some("" | "infinity") => u64::MAX,
1682        Some(quota) => quota_millicores(quota)?,
1683    };
1684    Some(cpus.saturating_mul(1000).min(quota))
1685}
1686
1687/// How many CPUs a set names, as systemd prints it (`0-3 8-11`) or as it is written (`0-3,8,10-11`).
1688fn cpu_count(set: &str) -> Option<u64> {
1689    set.split([',', ' '])
1690        .filter(|range| !range.is_empty())
1691        .try_fold(0u64, |count, range| {
1692            let (first, last) = range.split_once('-').unwrap_or((range, range));
1693            let (first, last): (u64, u64) = (first.parse().ok()?, last.parse().ok()?);
1694            Some(count + last.checked_sub(first)? + 1)
1695        })
1696}
1697
1698/// A `CPUQuotaPerSecUSec` as systemd prints a timespan, such as `800ms`, `2.500000s` or `1min 4s`, as the
1699/// millicores it allows: a second of CPU time each second is 1000.
1700fn quota_millicores(quota: &str) -> Option<u64> {
1701    // Each unit's length in milliseconds, as systemd's `format_timespan` names them.
1702    const UNITS: [(&str, f64); 10] = [
1703        ("y", 31_557_600_000.0),
1704        ("M", 2_629_800_000.0),
1705        ("w", 604_800_000.0),
1706        ("d", 86_400_000.0),
1707        ("h", 3_600_000.0),
1708        ("min", 60_000.0),
1709        ("s", 1000.0),
1710        ("ms", 1.0),
1711        ("us", 0.001),
1712        ("µs", 0.001),
1713    ];
1714    let millicores = quota.split_whitespace().try_fold(0.0, |total, part| {
1715        let at = part.find(|c: char| !(c.is_ascii_digit() || c == '.'))?;
1716        let (number, unit) = part.split_at(at);
1717        let per_unit = UNITS
1718            .iter()
1719            .find_map(|(name, per_unit)| (*name == unit).then_some(*per_unit))?;
1720        Some(total + number.parse::<f64>().ok()? * per_unit)
1721    })?;
1722    #[allow(
1723        clippy::cast_possible_truncation,
1724        clippy::cast_sign_loss,
1725        reason = "a quota is a few thousand millicores per CPU, checked finite and not negative first"
1726    )]
1727    (!quota.trim().is_empty() && millicores.is_finite() && millicores >= 0.0)
1728        .then(|| millicores.round() as u64)
1729}
1730
1731/// Parses a `MemoryMax` value as `systemctl show` prints it: bytes, or `infinity`.
1732pub fn parse_memory_max(value: &str) -> Option<Option<ByteSize>> {
1733    if value == "infinity" {
1734        Some(None)
1735    } else {
1736        value.parse().ok().map(|bytes| Some(ByteSize(bytes)))
1737    }
1738}
1739
1740/// A size in bytes, written with a binary unit as Docker and systemd do: `512M`, `9G`, `32.5G`.
1741#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1742pub struct ByteSize(pub u64);
1743
1744const UNITS: [(char, u64); 4] = [
1745    ('T', 1 << 40),
1746    ('G', 1 << 30),
1747    ('M', 1 << 20),
1748    ('K', 1 << 10),
1749];
1750
1751impl FromStr for ByteSize {
1752    type Err = String;
1753
1754    #[allow(
1755        clippy::cast_precision_loss,
1756        clippy::cast_possible_truncation,
1757        clippy::cast_sign_loss,
1758        reason = "sizes in a config are far below 2^52 bytes, and the result is checked against u64's range first"
1759    )]
1760    fn from_str(s: &str) -> Result<Self, Self::Err> {
1761        let invalid = || {
1762            format!(
1763                "invalid size {s:?}, expected a number and a unit (K, M, G or T), such as \"9G\""
1764            )
1765        };
1766        let unit = s.chars().last().ok_or_else(invalid)?.to_ascii_uppercase();
1767        let (_, factor) = UNITS.iter().find(|(u, _)| *u == unit).ok_or_else(invalid)?;
1768        let number = &s[..s.len() - 1];
1769        if number.is_empty() || !number.chars().all(|c| c.is_ascii_digit() || c == '.') {
1770            return Err(invalid());
1771        }
1772        let number: f64 = number.parse().map_err(|_| invalid())?;
1773        let bytes = (number * *factor as f64).round();
1774        // `u64::MAX as f64` is 2^64, the first value out of range.
1775        if bytes >= u64::MAX as f64 {
1776            return Err(format!("size {s:?} is too large"));
1777        }
1778        Ok(ByteSize(bytes as u64))
1779    }
1780}
1781
1782impl fmt::Display for ByteSize {
1783    #[allow(
1784        clippy::cast_precision_loss,
1785        reason = "shown with two decimals, far coarser than f64's precision"
1786    )]
1787    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1788        let Some((unit, factor)) = UNITS.iter().find(|(_, factor)| self.0 >= *factor) else {
1789            return write!(f, "{}B", self.0);
1790        };
1791        let number = format!("{:.2}", self.0 as f64 / *factor as f64);
1792        let number = number.trim_end_matches('0').trim_end_matches('.');
1793        write!(f, "{number}{unit}")
1794    }
1795}
1796
1797impl ByteSize {
1798    /// The size rounded to the nearest, for a label too narrow for its `Display`: two significant digits below 10
1799    /// of its unit, whole units above, and the next unit up once it rounds to 1024: `3.3G` for 3.25G, `12G`,
1800    /// `512M`, and `1G` for 1023.5M. Every client's budget bar labels a block with it.
1801    #[allow(
1802        clippy::cast_precision_loss,
1803        reason = "shown with one decimal at most, far coarser than f64's precision"
1804    )]
1805    pub fn short(self) -> String {
1806        let Some(index) = UNITS.iter().position(|(_, factor)| self.0 >= *factor) else {
1807            return format!("{}B", self.0);
1808        };
1809        let (mut unit, factor) = UNITS[index];
1810        let mut value = self.0 as f64 / factor as f64;
1811        if value.round() >= 1024.0
1812            && let Some(larger) = index.checked_sub(1)
1813        {
1814            unit = UNITS[larger].0;
1815            value /= 1024.0;
1816        }
1817        // Halves round up, as `f64::round` does and formatting, which rounds them to even, does not.
1818        let tenths = (value * 10.0).round() / 10.0;
1819        if tenths < 10.0 {
1820            let number = format!("{tenths:.1}");
1821            format!("{}{unit}", number.trim_end_matches(".0"))
1822        } else {
1823            format!("{:.0}{unit}", value.round())
1824        }
1825    }
1826}
1827
1828impl<'de> Deserialize<'de> for ByteSize {
1829    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1830        String::deserialize(deserializer)?
1831            .parse()
1832            .map_err(de::Error::custom)
1833    }
1834}
1835
1836/// Parses a duration as Go and the registry write it, `30s`, `90m`, `168h`, or in days: `7d`.
1837pub fn parse_duration(s: &str) -> Result<Duration, String> {
1838    let invalid = || {
1839        format!(
1840            "invalid duration {s:?}, expected a number and s, m, h or d, such as \"168h\" or \"7d\""
1841        )
1842    };
1843    let (number, factor) = match s.chars().last() {
1844        Some('s') => (&s[..s.len() - 1], 1),
1845        Some('m') => (&s[..s.len() - 1], 60),
1846        Some('h') => (&s[..s.len() - 1], 3600),
1847        Some('d') => (&s[..s.len() - 1], 86400),
1848        _ => return Err(invalid()),
1849    };
1850    let number: u64 = number.parse().map_err(|_| invalid())?;
1851    number
1852        .checked_mul(factor)
1853        .map(Duration::from_secs)
1854        .ok_or_else(invalid)
1855}
1856
1857/// Parses an age as the clients' `--since` and `--older-than` take it: `30m`, `12h`, `7d`, `2w`.
1858pub fn parse_age(text: &str) -> Result<Duration, String> {
1859    let error = || "expected a number and s, m, h, d or w, such as 12h".to_owned();
1860    let split = text.find(|c: char| !c.is_ascii_digit()).ok_or_else(error)?;
1861    let (number, unit) = text.split_at(split);
1862    let number: u64 = number.parse().map_err(|_| error())?;
1863    let unit = match unit {
1864        "s" => 1,
1865        "m" => 60,
1866        "h" => 3600,
1867        "d" => 86_400,
1868        "w" => 7 * 86_400,
1869        _ => return Err(error()),
1870    };
1871    Ok(Duration::from_secs(number.saturating_mul(unit)))
1872}
1873
1874fn duration<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Duration, D::Error> {
1875    parse_duration(&String::deserialize(deserializer)?).map_err(de::Error::custom)
1876}
1877
1878#[cfg(test)]
1879mod tests;