1use 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#[derive(Debug, Deserialize)]
23#[serde(deny_unknown_fields)]
24pub struct Config {
25 pub host: Host,
27 pub caches: Caches,
29 pub profiles: BTreeMap<String, Profile>,
31 pub repositories: Vec<Repository>,
34 #[serde(default)]
36 pub history: History,
37 #[serde(default)]
39 pub records: Records,
40 #[serde(default)]
42 pub sizing: Sizing,
43 #[serde(default)]
45 pub web: Web,
46 #[serde(default)]
48 pub notify: Notify,
49}
50
51#[derive(Debug, Deserialize)]
53#[serde(deny_unknown_fields)]
54pub struct Host {
55 pub slice: String,
57 pub isolation: Isolation,
59 #[serde(default)]
61 pub allow_unsafe: bool,
62 #[serde(default = "default_poll_interval", deserialize_with = "duration")]
64 pub poll_interval: Duration,
65 #[serde(default)]
67 pub admission: Admission,
68 #[serde(default)]
71 pub cpu_overcommit: Option<f64>,
72}
73
74impl Host {
75 fn check_cpu_overcommit(&self) -> Result<(), ConfigError> {
77 match self.cpu_overcommit {
78 Some(value) if !(value > 0.0 && value <= MAX_CPU_OVERCOMMIT) => {
79 Err(ConfigError::CpuOvercommit { value })
80 }
81 _ => Ok(()),
82 }
83 }
84}
85
86pub const MAX_CPU_OVERCOMMIT: f64 = 16.0;
88
89#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
91#[serde(rename_all = "kebab-case")]
92pub enum Admission {
93 #[default]
95 Caps,
96 Measured,
99}
100
101impl Admission {
102 pub fn policy(self) -> api::AdmissionPolicy {
104 match self {
105 Admission::Caps => api::AdmissionPolicy::Caps,
106 Admission::Measured => api::AdmissionPolicy::Measured,
107 }
108 }
109}
110
111fn default_poll_interval() -> Duration {
112 Duration::from_secs(15)
113}
114
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
117#[serde(rename_all = "kebab-case")]
118pub enum Isolation {
119 Sysbox,
121 UnsafeDind,
123}
124
125#[derive(Debug, Clone, Deserialize)]
127#[serde(deny_unknown_fields)]
128pub struct Caches {
129 pub mirror: Mirror,
131 pub pnpm: CacheLimit,
133 pub maven: CacheLimit,
135 #[serde(default = "default_reseed_at")]
138 pub reseed_at: ByteSize,
139 #[serde(default = "default_snapshot_max")]
142 pub snapshot_max: ByteSize,
143 #[serde(default)]
145 pub build: BuildCache,
146}
147
148#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
151#[serde(deny_unknown_fields, default)]
152pub struct BuildCache {
153 pub enabled: bool,
155 pub max_size: ByteSize,
157 pub branches: Vec<String>,
160 pub directory: Option<PathBuf>,
162}
163
164impl BuildCache {
165 fn validate(&self) -> Result<(), ConfigError> {
166 if self.enabled && self.max_size.0 == 0 {
167 return Err(ConfigError::ZeroLimit {
168 field: "caches.build.max_size".to_owned(),
169 });
170 }
171 Ok(())
172 }
173}
174
175impl Default for BuildCache {
176 fn default() -> BuildCache {
177 BuildCache {
178 enabled: true,
179 max_size: ByteSize(10 << 30),
180 branches: Vec::new(),
181 directory: None,
182 }
183 }
184}
185
186fn default_reseed_at() -> ByteSize {
187 ByteSize(2 << 30)
188}
189
190fn default_snapshot_max() -> ByteSize {
192 ByteSize(10 << 30)
193}
194
195fn default_mirror_max_size() -> ByteSize {
196 ByteSize(10 << 30)
197}
198
199#[derive(Debug, Clone, Deserialize)]
201#[serde(deny_unknown_fields)]
202pub struct Mirror {
203 pub enabled: bool,
205 pub memory: ByteSize,
207 pub cpus: u32,
209 #[serde(deserialize_with = "duration")]
211 pub ttl: Duration,
212 #[serde(default = "default_mirror_max_size")]
214 pub max_size: ByteSize,
215}
216
217#[derive(Debug, Clone, Deserialize)]
219#[serde(deny_unknown_fields)]
220pub struct CacheLimit {
221 pub max_size: ByteSize,
223}
224
225pub const PUBLISHED_RUNNER: &str = "ghcr.io/ayagmar/runnerd-runner";
228
229#[derive(Debug, Clone, Deserialize)]
231#[serde(try_from = "ProfileToml")]
232pub struct Profile {
233 pub image: Image,
235 pub cpus: u32,
237 pub memory: ByteSize,
239 pub slots: u32,
241 pub record_failures: bool,
243 pub min_memory: Option<ByteSize>,
245 pub max_memory: Option<ByteSize>,
247 pub max_slots: Option<u32>,
249}
250
251#[derive(Debug, Clone, PartialEq, Eq)]
253pub enum Image {
254 Stage(String),
256 Pulled(String),
259}
260
261impl Image {
262 pub fn reference(&self) -> String {
264 match self {
265 Image::Stage(stage) => format!("runnerd-runner:{stage}"),
266 Image::Pulled(reference) => reference.clone(),
267 }
268 }
269}
270
271#[derive(Deserialize)]
273#[serde(deny_unknown_fields)]
274struct ProfileToml {
275 image_stage: Option<String>,
276 image: Option<String>,
277 cpus: u32,
278 memory: ByteSize,
279 slots: u32,
280 #[serde(default)]
281 record_failures: bool,
282 min_memory: Option<ByteSize>,
283 max_memory: Option<ByteSize>,
284 max_slots: Option<u32>,
285}
286
287impl TryFrom<ProfileToml> for Profile {
288 type Error = String;
289
290 fn try_from(profile: ProfileToml) -> Result<Profile, String> {
291 let image = match (profile.image_stage, profile.image) {
292 (Some(stage), None) if !stage.is_empty() => Image::Stage(stage),
293 (None, Some(reference)) if !reference.is_empty() => Image::Pulled(reference),
294 (Some(_), Some(_)) => {
295 return Err(
296 "set image_stage (a stage built from image/Dockerfile) or image (a reference to pull), \
297 not both"
298 .to_owned(),
299 );
300 }
301 _ => {
302 return Err(
303 "set image_stage (a stage built from image/Dockerfile) or image (a reference to pull)"
304 .to_owned(),
305 );
306 }
307 };
308 Ok(Profile {
309 image,
310 cpus: profile.cpus,
311 memory: profile.memory,
312 slots: profile.slots,
313 record_failures: profile.record_failures,
314 min_memory: profile.min_memory,
315 max_memory: profile.max_memory,
316 max_slots: profile.max_slots,
317 })
318 }
319}
320
321pub fn labels_match(wanted: &[String], labels: &[String]) -> bool {
325 !wanted.is_empty()
326 && wanted.iter().all(|wanted| {
327 labels
328 .iter()
329 .any(|label| label.eq_ignore_ascii_case(wanted))
330 })
331}
332
333#[derive(Debug, Deserialize)]
336#[serde(deny_unknown_fields)]
337pub struct Repository {
338 pub name: String,
340 pub profile: String,
342 pub labels: Vec<String>,
344 #[serde(default = "default_warm")]
347 pub warm: u32,
348 #[serde(default = "default_true")]
350 pub build_cache: bool,
351 #[serde(default)]
354 pub build_cache_writers: BuildCacheWriters,
355}
356
357#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
359#[serde(rename_all = "kebab-case")]
360pub enum BuildCacheWriters {
361 #[default]
363 DefaultBranch,
364 PullRequests,
366}
367
368fn default_true() -> bool {
369 true
370}
371
372fn default_warm() -> u32 {
373 1
374}
375
376#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
378#[serde(deny_unknown_fields, default)]
379pub struct History {
380 pub database: Option<PathBuf>,
382 #[serde(deserialize_with = "duration")]
384 pub samples: Duration,
385 #[serde(deserialize_with = "duration")]
387 pub logs: Duration,
388 #[serde(deserialize_with = "duration")]
390 pub events: Duration,
391 #[serde(deserialize_with = "duration")]
393 pub jobs: Duration,
394 pub log_max: ByteSize,
396}
397
398impl Default for History {
399 fn default() -> History {
400 History {
401 database: None,
402 samples: Duration::from_hours(7 * 24),
403 logs: Duration::from_hours(30 * 24),
404 events: Duration::from_hours(30 * 24),
405 jobs: Duration::from_hours(90 * 24),
406 log_max: ByteSize(50 << 20),
407 }
408 }
409}
410
411#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
414#[serde(deny_unknown_fields, default)]
415pub struct Records {
416 pub max_total: ByteSize,
418 pub max_count: u32,
420 #[serde(deserialize_with = "duration")]
422 pub max_age: Duration,
423 pub min_free: ByteSize,
425}
426
427impl Default for Records {
428 fn default() -> Records {
429 Records {
430 max_total: ByteSize(20 << 30),
431 max_count: 10,
432 max_age: Duration::from_hours(7 * 24),
433 min_free: ByteSize(10 << 30),
434 }
435 }
436}
437
438#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
441#[serde(deny_unknown_fields, default)]
442pub struct Sizing {
443 pub margin: u32,
446 pub min_jobs: u32,
449 pub auto: bool,
452 #[serde(deserialize_with = "duration")]
455 pub interval: Duration,
456 #[serde(deserialize_with = "duration")]
459 pub raise_interval: Duration,
460 pub max_step: u32,
462}
463
464impl Sizing {
465 pub fn raise_after(&self) -> Duration {
468 self.raise_interval.min(self.interval)
469 }
470}
471
472impl Default for Sizing {
473 fn default() -> Sizing {
474 Sizing {
475 margin: 15,
476 min_jobs: 10,
477 auto: false,
478 interval: Duration::from_hours(24),
479 raise_interval: Duration::from_hours(1),
480 max_step: 25,
481 }
482 }
483}
484
485#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
487#[serde(deny_unknown_fields, default)]
488pub struct Web {
489 pub origins: Vec<Origin>,
492 pub open: Option<Origin>,
495}
496
497impl Web {
498 fn validate(&self) -> Result<(), ConfigError> {
500 match &self.open {
501 Some(open) if !self.origins.contains(open) => {
502 Err(ConfigError::OpenNotListed { open: open.clone() })
503 }
504 _ => Ok(()),
505 }
506 }
507}
508
509#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
511#[serde(deny_unknown_fields, default)]
512pub struct Notify {
513 pub digest_at: DayTime,
515 pub targets: Vec<NotifyTarget>,
517}
518
519impl Default for Notify {
520 fn default() -> Notify {
521 Notify {
522 digest_at: DayTime { minutes: 9 * 60 },
523 targets: Vec::new(),
524 }
525 }
526}
527
528impl Notify {
529 fn validate(&self) -> Result<(), ConfigError> {
532 let refuse = |target: &str, why: &'static str| {
533 Err(ConfigError::Notify {
534 target: target.to_owned(),
535 why,
536 })
537 };
538 for (index, target) in self.targets.iter().enumerate() {
539 let name = target.name.as_str();
540 if name.trim().is_empty() || name.chars().any(char::is_control) {
541 return refuse(name, "name is empty");
542 }
543 if self.targets[..index].iter().any(|other| other.name == name) {
544 return refuse(name, "another target has this name");
545 }
546 let url = target.url.expose();
547 if url == SECRET_SHOWN {
548 return refuse(
549 name,
550 "url is <secret>, which runnerd fills in only for a target of the same name that had one; write the url",
551 );
552 }
553 let Some(rest) = url
554 .strip_prefix("https://")
555 .or_else(|| url.strip_prefix("http://"))
556 else {
557 return refuse(name, "url does not start with https:// or http://");
558 };
559 let (host, path) = rest.split_once('/').unwrap_or((rest, ""));
560 if host.is_empty() || url.chars().any(|c| c.is_whitespace() || c.is_control()) {
561 return refuse(name, "url is not a URL");
562 }
563 if target.kind == NotifyKind::Ntfy
564 && (path.is_empty() || path.contains(['/', '?', '#']))
565 {
566 return refuse(
567 name,
568 "url is not an ntfy topic's, such as https://ntfy.sh/<topic>",
569 );
570 }
571 for (header, value) in &target.headers {
572 if value.expose() == SECRET_SHOWN {
573 return refuse(
574 name,
575 "a header is <secret>, which runnerd fills in only for a target of the same name that had it; write its value",
576 );
577 }
578 let token = |c: char| c.is_ascii_alphanumeric() || "!#$%&'*+-.^_`|~".contains(c);
579 if header.is_empty() || !header.chars().all(token) {
580 return refuse(name, "a header's name is not a header name");
581 }
582 if value.expose().chars().any(char::is_control) {
583 return refuse(name, "a header's value has a control character");
584 }
585 }
586 if target.events.contains(&api::NotifyEvent::Test) {
587 return refuse(
588 name,
589 "events lists test, which only runnerctl notify test sends",
590 );
591 }
592 }
593 Ok(())
594 }
595}
596
597#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
599#[serde(deny_unknown_fields)]
600pub struct NotifyTarget {
601 pub name: String,
603 pub kind: NotifyKind,
605 pub url: Secret,
608 #[serde(default)]
610 pub headers: BTreeMap<String, Secret>,
611 #[serde(default = "default_notify_events")]
613 pub events: Vec<api::NotifyEvent>,
614}
615
616fn default_notify_events() -> Vec<api::NotifyEvent> {
617 vec![
618 api::NotifyEvent::Failed,
619 api::NotifyEvent::Lost,
620 api::NotifyEvent::Runner,
621 api::NotifyEvent::Insights,
622 ]
623}
624
625#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
627#[serde(rename_all = "kebab-case")]
628pub enum NotifyKind {
629 Webhook,
631 Ntfy,
633 Discord,
635}
636
637#[derive(Clone, PartialEq, Eq, Deserialize)]
639#[serde(transparent)]
640pub struct Secret(String);
641
642impl Secret {
643 pub fn expose(&self) -> &str {
645 &self.0
646 }
647}
648
649impl From<&str> for Secret {
650 fn from(value: &str) -> Secret {
651 Secret(value.to_owned())
652 }
653}
654
655impl fmt::Debug for Secret {
656 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
657 f.write_str("<secret>")
658 }
659}
660
661#[derive(Debug, Clone, Copy, PartialEq, Eq)]
663pub struct DayTime {
664 pub minutes: u32,
666}
667
668impl FromStr for DayTime {
669 type Err = String;
670
671 fn from_str(text: &str) -> Result<DayTime, String> {
672 let invalid = || format!("invalid time of day {text:?}, expected HH:MM such as \"09:00\"");
673 let (hour, minute) = text.split_once(':').ok_or_else(invalid)?;
674 let digits = |part: &str| part.len() == 2 && part.chars().all(|c| c.is_ascii_digit());
675 if !digits(hour) || !digits(minute) {
676 return Err(invalid());
677 }
678 let (hour, minute): (u32, u32) = (
679 hour.parse().map_err(|_| invalid())?,
680 minute.parse().map_err(|_| invalid())?,
681 );
682 if hour > 23 || minute > 59 {
683 return Err(invalid());
684 }
685 Ok(DayTime {
686 minutes: hour * 60 + minute,
687 })
688 }
689}
690
691impl fmt::Display for DayTime {
692 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
693 write!(f, "{:02}:{:02}", self.minutes / 60, self.minutes % 60)
694 }
695}
696
697impl<'de> Deserialize<'de> for DayTime {
698 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
699 String::deserialize(deserializer)?
700 .parse()
701 .map_err(de::Error::custom)
702 }
703}
704
705#[derive(Debug, Clone, PartialEq, Eq)]
709pub struct Origin(String);
710
711impl Origin {
712 pub fn as_str(&self) -> &str {
714 &self.0
715 }
716}
717
718impl FromStr for Origin {
719 type Err = String;
720
721 fn from_str(s: &str) -> Result<Origin, String> {
722 let invalid = |why: &str| {
723 format!(
724 "invalid origin {s:?}: {why}; write the scheme, host and port only, such as \
725 \"https://host.example.ts.net:8443\""
726 )
727 };
728 let (scheme, rest) = s
729 .split_once("://")
730 .ok_or_else(|| invalid("it has no scheme"))?;
731 let scheme = scheme.to_ascii_lowercase();
732 if rest.contains(['/', '?', '#']) {
733 return Err(invalid("it has a path"));
734 }
735 if rest.contains('@') {
736 return Err(invalid("it names a user"));
737 }
738 let (host, port) = match rest.strip_prefix('[') {
739 Some(v6) => {
740 let (address, after) = v6
741 .split_once(']')
742 .ok_or_else(|| invalid("its IPv6 address has no closing ]"))?;
743 let port = match after {
744 "" => None,
745 _ => Some(after.strip_prefix(':').ok_or_else(|| invalid("its port"))?),
746 };
747 (format!("[{address}]"), port)
748 }
749 None => match rest.split_once(':') {
750 Some((host, port)) => (host.to_owned(), Some(port)),
751 None => (rest.to_owned(), None),
752 },
753 };
754 let host = host.to_ascii_lowercase();
755 let not_a_host = || invalid("its host is not a name or an address");
756 let (host, loopback) =
758 if let Some(v6) = host.strip_prefix('[').and_then(|v6| v6.strip_suffix(']')) {
759 let address: Ipv6Addr = v6.parse().map_err(|_| not_a_host())?;
760 (format!("[{}]", ipv6_origin(address)), address.is_loopback())
761 } else {
762 if host.is_empty()
763 || !host
764 .chars()
765 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.')
766 {
767 return Err(not_a_host());
768 }
769 let name = host.strip_suffix('.').unwrap_or(&host);
771 let last = name.rsplit('.').next().unwrap_or_default();
772 let numeric = !last.is_empty()
773 && (last.bytes().all(|byte| byte.is_ascii_digit())
774 || last
775 .strip_prefix("0x")
776 .is_some_and(|hex| hex.bytes().all(|byte| byte.is_ascii_hexdigit())));
777 if numeric {
778 let address: Ipv4Addr = name.parse().map_err(|_| {
779 invalid("its IPv4 address is not four decimal numbers, such as 192.0.2.1")
780 })?;
781 (address.to_string(), address.is_loopback())
782 } else {
783 let loopback = host == "localhost";
784 (host, loopback)
785 }
786 };
787 let port = port
788 .map(|port| {
789 Some(port)
790 .filter(|port| port.bytes().all(|byte| byte.is_ascii_digit()))
791 .and_then(|port| port.parse::<u16>().ok())
792 .filter(|port| *port != 0)
793 .ok_or_else(|| invalid("its port is not a number from 1 to 65535"))
794 })
795 .transpose()?;
796 let default_port = match scheme.as_str() {
797 "https" => 443,
798 "http" if loopback => 80,
799 "http" => {
800 return Err(invalid(
801 "http is for a loopback host only, since the session cookie would cross the network in \
802 the clear; use https",
803 ));
804 }
805 _ => return Err(invalid("its scheme is not https")),
806 };
807 Ok(Origin(match port {
808 Some(port) if port != default_port => format!("{scheme}://{host}:{port}"),
809 _ => format!("{scheme}://{host}"),
810 }))
811 }
812}
813
814fn ipv6_origin(address: Ipv6Addr) -> String {
817 let pieces = address.segments();
818 let (mut zeros_at, mut zeros) = (0, 0);
819 let mut at = 0;
820 while at < pieces.len() {
821 let run = pieces[at..].iter().take_while(|piece| **piece == 0).count();
822 if run > zeros {
823 (zeros_at, zeros) = (at, run);
824 }
825 at += run.max(1);
826 }
827 let hex = |pieces: &[u16]| {
828 pieces
829 .iter()
830 .map(|piece| format!("{piece:x}"))
831 .collect::<Vec<_>>()
832 .join(":")
833 };
834 if zeros < 2 {
835 return hex(&pieces);
836 }
837 format!(
838 "{}::{}",
839 hex(&pieces[..zeros_at]),
840 hex(&pieces[zeros_at + zeros..])
841 )
842}
843
844impl fmt::Display for Origin {
845 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
846 f.write_str(&self.0)
847 }
848}
849
850impl<'de> Deserialize<'de> for Origin {
851 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
852 String::deserialize(deserializer)?
853 .parse()
854 .map_err(de::Error::custom)
855 }
856}
857
858#[derive(Debug, thiserror::Error)]
860pub enum ConfigError {
861 #[error("cannot read {}: {source}", path.display())]
863 Read {
864 path: PathBuf,
866 source: std::io::Error,
868 },
869 #[error(transparent)]
871 Parse(#[from] toml::de::Error),
872 #[error(
874 "repository {repository} uses profile {profile:?}, which is not defined under [profiles]; {}",
875 defined_profiles(.defined)
876 )]
877 UnknownProfile {
878 repository: String,
880 profile: String,
882 defined: Vec<String>,
884 },
885 #[error("repository {repository} needs at least one non-empty label")]
887 MissingLabels {
888 repository: String,
890 },
891 #[error(
893 "repository {repository} has two entries with profile {profile:?}; give each of its pools its own profile"
894 )]
895 PoolProfileTwice {
896 repository: String,
898 profile: String,
900 },
901 #[error(
904 "repository {repository}'s pools in {first} and {second} both have the label {label:?}, so a job asking for \
905 it could land in either; give each pool labels of its own, such as only {second:?}'s own label for the \
906 lighter one"
907 )]
908 PoolLabelsOverlap {
909 repository: String,
911 first: String,
913 second: String,
915 label: String,
917 },
918 #[error(
920 "repository {repository}'s entries set build_cache_writers differently; whose runs may write to the build \
921 cache is the repository's, so set the same in each"
922 )]
923 PoolWritersDiffer {
924 repository: String,
926 },
927 #[error(
929 "isolation \"unsafe-dind\" runs runner containers privileged, so a job can take over the host; \
930 set allow_unsafe = true under [host] to use it anyway"
931 )]
932 UnsafeNotAllowed,
933 #[error("{field} is 0; set it above 0")]
935 ZeroLimit {
936 field: String,
938 },
939 #[error(
941 "host.cpu_overcommit is {value}; set it above 0 and at most {MAX_CPU_OVERCOMMIT}, such as 1.0"
942 )]
943 CpuOvercommit {
944 value: f64,
946 },
947 #[error(
949 "web.open is {open}, which is not one of [web] origins; add it to origins, or remove open"
950 )]
951 OpenNotListed {
952 open: Origin,
954 },
955 #[error("profiles.{profile}: {why}")]
958 SizingBounds {
959 profile: String,
961 why: &'static str,
963 },
964 #[error("notify target {target:?}: {why}")]
966 Notify {
967 target: String,
969 why: &'static str,
971 },
972 #[error("slots × memory over all profiles plus the mirror is too large to add up")]
974 BudgetOverflow,
975 #[error(
977 "admission = \"measured\" admits runners against the slice {slice}'s MemoryMax, and it has none; install \
978 a unit file for it (`runnerd doctor` prints one)"
979 )]
980 MeasuredWithoutMemoryMax {
981 slice: String,
983 },
984 #[error(
986 "one runner of {profile} and the mirror take {needs}, the slice {slice}'s MemoryMax is {memory_max}; lower \
987 its `memory` or raise the slice's MemoryMax"
988 )]
989 ProfileOverBudget {
990 profile: String,
992 needs: ByteSize,
994 slice: String,
996 memory_max: ByteSize,
998 },
999 #[error(
1001 "slots × memory over all profiles plus the mirror is {total}, \
1002 the slice {slice}'s MemoryMax is {memory_max}; lower `slots` or `memory`, or raise the slice's \
1003 MemoryMax (`runnerd doctor` prints its unit)"
1004 )]
1005 OverBudget {
1006 total: ByteSize,
1008 slice: String,
1010 memory_max: ByteSize,
1012 },
1013}
1014
1015fn defined_profiles(defined: &[String]) -> String {
1016 if defined.is_empty() {
1017 "it defines none".to_owned()
1018 } else {
1019 format!("defined: {}", defined.join(", "))
1020 }
1021}
1022
1023#[derive(Debug, Clone, PartialEq, Eq)]
1025pub enum Warning {
1026 UnlimitedSlice {
1028 slice: String,
1030 total: ByteSize,
1032 },
1033}
1034
1035impl fmt::Display for Warning {
1036 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1037 match self {
1038 Warning::UnlimitedSlice { slice, total } => write!(
1039 f,
1040 "the slice {slice} has no MemoryMax, so nothing holds runners to their {total} of caps; \
1041 install a unit file for it"
1042 ),
1043 }
1044 }
1045}
1046
1047impl Config {
1048 pub fn load(path: &Path) -> Result<Config, ConfigError> {
1050 let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Read {
1051 path: path.to_owned(),
1052 source,
1053 })?;
1054 Config::parse(&text)
1055 }
1056
1057 pub fn parse(text: &str) -> Result<Config, ConfigError> {
1059 Ok(toml::from_str(text)?)
1060 }
1061
1062 pub fn check(
1065 text: &str,
1066 memory_max: impl FnOnce(&str) -> std::io::Result<Option<ByteSize>>,
1067 ) -> (Option<Config>, api::ConfigCheck) {
1068 let config = match Config::parse(text) {
1069 Ok(config) => config,
1070 Err(error) => return (None, budget::invalid(error.to_string(), None, None)),
1071 };
1072 let max = match memory_max(&config.host.slice) {
1073 Ok(max) => max,
1074 Err(error) => {
1075 return (
1076 None,
1077 budget::invalid(error.to_string(), Some(&config), None),
1078 );
1079 }
1080 };
1081 let check = config.check_against(max);
1082 if check.valid {
1083 (Some(config), check)
1084 } else {
1085 (None, check)
1086 }
1087 }
1088
1089 pub fn mirror_memory(&self) -> u64 {
1091 if self.caches.mirror.enabled {
1092 self.caches.mirror.memory.0
1093 } else {
1094 0
1095 }
1096 }
1097
1098 pub fn memory_caps(&self) -> Result<ByteSize, ConfigError> {
1100 let mirror = self.mirror_memory();
1101 self.profiles
1102 .values()
1103 .try_fold(mirror, |total, p| {
1104 p.memory
1105 .0
1106 .checked_mul(u64::from(p.slots))?
1107 .checked_add(total)
1108 })
1109 .map(ByteSize)
1110 .ok_or(ConfigError::BudgetOverflow)
1111 }
1112
1113 pub fn memory_needed(&self) -> Result<ByteSize, ConfigError> {
1116 match self.host.admission {
1117 Admission::Caps => self.memory_caps(),
1118 Admission::Measured => {
1119 let largest = self
1120 .profiles
1121 .values()
1122 .map(|p| p.memory.0)
1123 .max()
1124 .unwrap_or(0);
1125 largest
1126 .checked_add(self.mirror_memory())
1127 .map(ByteSize)
1128 .ok_or(ConfigError::BudgetOverflow)
1129 }
1130 }
1131 }
1132
1133 fn check_sizing_bounds(&self) -> Result<(), ConfigError> {
1135 for (name, p) in &self.profiles {
1136 let memory = p.memory.0;
1137 let field = if p
1138 .min_memory
1139 .zip(p.max_memory)
1140 .is_some_and(|(min, max)| min.0 > max.0)
1141 {
1142 "min_memory is above its max_memory"
1143 } else if p.min_memory.is_some_and(|min| memory < min.0) {
1144 "memory is below its min_memory"
1145 } else if p.max_memory.is_some_and(|max| memory > max.0) {
1146 "memory is above its max_memory"
1147 } else if p.max_slots.is_some_and(|max| p.slots > max) {
1148 "slots are above its max_slots"
1149 } else {
1150 continue;
1151 };
1152 return Err(ConfigError::SizingBounds {
1153 profile: name.clone(),
1154 why: field,
1155 });
1156 }
1157 Ok(())
1158 }
1159
1160 fn check_pools(&self) -> Result<(), ConfigError> {
1163 for (at, first) in self.repositories.iter().enumerate() {
1164 for second in self.repositories[at + 1..]
1165 .iter()
1166 .filter(|second| second.name == first.name)
1167 {
1168 if second.profile == first.profile {
1169 return Err(ConfigError::PoolProfileTwice {
1170 repository: first.name.clone(),
1171 profile: first.profile.clone(),
1172 });
1173 }
1174 if let Some(label) = first.labels.iter().find(|label| {
1175 second
1176 .labels
1177 .iter()
1178 .any(|other| other.eq_ignore_ascii_case(label))
1179 }) {
1180 return Err(ConfigError::PoolLabelsOverlap {
1181 repository: first.name.clone(),
1182 first: first.profile.clone(),
1183 second: second.profile.clone(),
1184 label: label.clone(),
1185 });
1186 }
1187 if second.build_cache_writers != first.build_cache_writers {
1188 return Err(ConfigError::PoolWritersDiffer {
1189 repository: first.name.clone(),
1190 });
1191 }
1192 }
1193 }
1194 Ok(())
1195 }
1196
1197 pub fn pool(&self, repository: &str, labels: &[String]) -> Option<&Repository> {
1200 self.repositories
1201 .iter()
1202 .find(|pool| pool.name == repository && labels_match(labels, &pool.labels))
1203 }
1204
1205 pub fn pool_in(&self, repository: &str, profile: &str) -> Option<&Repository> {
1207 self.repositories
1208 .iter()
1209 .find(|pool| pool.name == repository && pool.profile == profile)
1210 }
1211
1212 pub fn repository_names(&self) -> Vec<String> {
1214 let mut names: Vec<String> = Vec::new();
1215 for repository in &self.repositories {
1216 if !names.contains(&repository.name) {
1217 names.push(repository.name.clone());
1218 }
1219 }
1220 names
1221 }
1222
1223 pub fn validate(&self, memory_max: Option<ByteSize>) -> Result<Vec<Warning>, ConfigError> {
1225 if self.host.isolation == Isolation::UnsafeDind && !self.host.allow_unsafe {
1226 return Err(ConfigError::UnsafeNotAllowed);
1227 }
1228 let zero_limits = self.profiles.iter().flat_map(|(name, p)| {
1229 [
1230 (p.memory.0 == 0, format!("profiles.{name}.memory")),
1231 (p.cpus == 0, format!("profiles.{name}.cpus")),
1232 (p.slots == 0, format!("profiles.{name}.slots")),
1233 (p.max_slots == Some(0), format!("profiles.{name}.max_slots")),
1234 ]
1235 });
1236 let mirror = &self.caches.mirror;
1237 let mirror_zero_limits = [
1238 (
1239 mirror.enabled && mirror.memory.0 == 0,
1240 "caches.mirror.memory".to_owned(),
1241 ),
1242 (
1243 mirror.enabled && mirror.cpus == 0,
1244 "caches.mirror.cpus".to_owned(),
1245 ),
1246 (
1247 self.host.poll_interval.is_zero(),
1248 "host.poll_interval".to_owned(),
1249 ),
1250 (self.records.max_count == 0, "records.max_count".to_owned()),
1251 (self.sizing.min_jobs == 0, "sizing.min_jobs".to_owned()),
1252 (self.sizing.interval.is_zero(), "sizing.interval".to_owned()),
1253 (
1254 self.sizing.raise_interval.is_zero(),
1255 "sizing.raise_interval".to_owned(),
1256 ),
1257 (self.sizing.max_step == 0, "sizing.max_step".to_owned()),
1258 (
1259 self.records.max_total.0 == 0,
1260 "records.max_total".to_owned(),
1261 ),
1262 ];
1263 if let Some((_, field)) = zero_limits
1264 .chain(mirror_zero_limits)
1265 .find(|(zero, _)| *zero)
1266 {
1267 return Err(ConfigError::ZeroLimit { field });
1268 }
1269 self.check_sizing_bounds()?;
1270 self.caches.build.validate()?;
1271 self.host.check_cpu_overcommit()?;
1272 self.web.validate()?;
1273 self.notify.validate()?;
1274 for repository in &self.repositories {
1275 if !self.profiles.contains_key(&repository.profile) {
1276 return Err(ConfigError::UnknownProfile {
1277 repository: repository.name.clone(),
1278 profile: repository.profile.clone(),
1279 defined: self.profiles.keys().cloned().collect(),
1280 });
1281 }
1282 if repository.labels.is_empty() || repository.labels.iter().any(|l| l.trim().is_empty())
1283 {
1284 return Err(ConfigError::MissingLabels {
1285 repository: repository.name.clone(),
1286 });
1287 }
1288 }
1289 self.check_pools()?;
1290 self.check_budget(memory_max)
1291 }
1292
1293 fn check_budget(&self, memory_max: Option<ByteSize>) -> Result<Vec<Warning>, ConfigError> {
1295 let total = self.memory_caps()?;
1296 if self.host.admission == Admission::Measured {
1297 let Some(memory_max) = memory_max else {
1298 return Err(ConfigError::MeasuredWithoutMemoryMax {
1299 slice: self.host.slice.clone(),
1300 });
1301 };
1302 let mirror = self.mirror_memory();
1303 if let Some((profile, needs)) = self
1304 .profiles
1305 .iter()
1306 .map(|(name, profile)| (name, profile.memory.0.saturating_add(mirror)))
1307 .find(|(_, needs)| *needs > memory_max.0)
1308 {
1309 return Err(ConfigError::ProfileOverBudget {
1310 profile: profile.clone(),
1311 needs: ByteSize(needs),
1312 slice: self.host.slice.clone(),
1313 memory_max,
1314 });
1315 }
1316 let needed = self.memory_needed()?;
1318 if needed > memory_max {
1319 return Err(ConfigError::OverBudget {
1320 total: needed,
1321 slice: self.host.slice.clone(),
1322 memory_max,
1323 });
1324 }
1325 return Ok(Vec::new());
1326 }
1327 match memory_max {
1328 Some(memory_max) if total > memory_max => Err(ConfigError::OverBudget {
1329 total,
1330 slice: self.host.slice.clone(),
1331 memory_max,
1332 }),
1333 Some(_) => Ok(Vec::new()),
1334 None => Ok(vec![Warning::UnlimitedSlice {
1335 slice: self.host.slice.clone(),
1336 total,
1337 }]),
1338 }
1339 }
1340}
1341
1342#[derive(Debug, thiserror::Error)]
1344pub enum ResizeError {
1345 #[error(transparent)]
1347 Parse(#[from] toml_edit::TomlError),
1348 #[error("the config has no profile {0:?} under [profiles]")]
1350 NoProfile(String),
1351}
1352
1353pub fn resize_profile(
1356 text: &str,
1357 profile: &str,
1358 resize: api::Resize,
1359) -> Result<String, ResizeError> {
1360 let mut document: toml_edit::DocumentMut = text.parse()?;
1361 let table = document
1362 .get_mut("profiles")
1363 .and_then(|profiles| profiles.get_mut(profile))
1364 .and_then(toml_edit::Item::as_table_like_mut)
1365 .ok_or_else(|| ResizeError::NoProfile(profile.to_owned()))?;
1366 let values = [
1367 (
1368 "memory",
1369 toml_edit::Value::from(ByteSize(resize.memory).to_string()),
1370 ),
1371 ("slots", toml_edit::Value::from(i64::from(resize.slots))),
1372 ];
1373 let cpus = resize
1374 .cpus
1375 .map(|cpus| ("cpus", toml_edit::Value::from(i64::from(cpus))));
1376 for (key, mut value) in values.into_iter().chain(cpus) {
1377 if let Some(old) = table.get(key).and_then(toml_edit::Item::as_value) {
1379 *value.decor_mut() = old.decor().clone();
1380 }
1381 table.insert(key, toml_edit::Item::Value(value));
1382 }
1383 Ok(document.to_string())
1384}
1385
1386pub const SECRET_SHOWN: &str = "<secret>";
1388
1389pub fn mask_secrets(text: &str) -> Option<String> {
1393 let mut document: toml_edit::DocumentMut = text.parse().ok()?;
1394 let mut masked = false;
1395 for target in notify_targets(&mut document) {
1396 for (_, value) in secrets_of(target) {
1397 replace_value(value, toml_edit::Value::from(SECRET_SHOWN));
1398 masked = true;
1399 }
1400 }
1401 Some(if masked {
1402 document.to_string()
1403 } else {
1404 text.to_owned()
1405 })
1406}
1407
1408pub fn keep_secrets(text: &str, stored: &str) -> String {
1415 if !text.contains(SECRET_SHOWN) || Config::parse(text).is_err() {
1416 return text.to_owned();
1417 }
1418 let (Ok(mut document), Ok(mut old)) = (
1419 text.parse::<toml_edit::DocumentMut>(),
1420 stored.parse::<toml_edit::DocumentMut>(),
1421 ) else {
1422 return text.to_owned();
1423 };
1424 let mut kept: BTreeMap<String, Vec<(SecretField, toml_edit::Value)>> = BTreeMap::new();
1425 for target in notify_targets(&mut old) {
1426 let Some(name) = target_name(target) else {
1427 continue;
1428 };
1429 let secrets = secrets_of(target)
1430 .into_iter()
1431 .map(|(field, value)| (field, value.clone()))
1432 .collect();
1433 kept.insert(name, secrets);
1434 }
1435 for target in notify_targets(&mut document) {
1436 let Some(secrets) = target_name(target).and_then(|name| kept.get(&name)) else {
1437 continue;
1438 };
1439 for (field, value) in secrets_of(target) {
1440 if value.as_str() != Some(SECRET_SHOWN) {
1441 continue;
1442 }
1443 if let Some((_, old)) = secrets.iter().find(|(kept, _)| *kept == field) {
1444 replace_value(value, old.clone());
1445 }
1446 }
1447 }
1448 document.to_string()
1449}
1450
1451#[derive(Debug, PartialEq, Eq)]
1453enum SecretField {
1454 Url,
1455 Header(String),
1456}
1457
1458fn notify_targets(document: &mut toml_edit::DocumentMut) -> Vec<&mut dyn toml_edit::TableLike> {
1460 match document
1461 .get_mut("notify")
1462 .and_then(|notify| notify.get_mut("targets"))
1463 {
1464 Some(toml_edit::Item::ArrayOfTables(tables)) => tables
1465 .iter_mut()
1466 .map(|table| table as &mut dyn toml_edit::TableLike)
1467 .collect(),
1468 Some(toml_edit::Item::Value(toml_edit::Value::Array(array))) => array
1469 .iter_mut()
1470 .filter_map(toml_edit::Value::as_inline_table_mut)
1471 .map(|table| table as &mut dyn toml_edit::TableLike)
1472 .collect(),
1473 _ => Vec::new(),
1474 }
1475}
1476
1477fn target_name(target: &dyn toml_edit::TableLike) -> Option<String> {
1478 target
1479 .get("name")
1480 .and_then(toml_edit::Item::as_str)
1481 .map(str::to_owned)
1482}
1483
1484fn secrets_of(target: &mut dyn toml_edit::TableLike) -> Vec<(SecretField, &mut toml_edit::Value)> {
1486 let mut found = Vec::new();
1487 for (key, item) in target.iter_mut() {
1488 match key.get() {
1489 "url" => found.extend(item.as_value_mut().map(|value| (SecretField::Url, value))),
1490 "headers" => {
1491 let Some(headers) = item.as_table_like_mut() else {
1492 continue;
1493 };
1494 for (name, item) in headers.iter_mut() {
1495 let field = SecretField::Header(name.get().to_owned());
1496 found.extend(item.as_value_mut().map(|value| (field, value)));
1497 }
1498 }
1499 _ => {}
1500 }
1501 }
1502 found
1503}
1504
1505fn replace_value(value: &mut toml_edit::Value, mut new: toml_edit::Value) {
1507 *new.decor_mut() = value.decor().clone();
1508 *value = new;
1509}
1510
1511pub fn revision(text: &str) -> String {
1514 let hash = text.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
1515 (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
1516 });
1517 format!("{hash:016x}")
1518}
1519
1520pub fn slice_memory_max(slice: &str) -> std::io::Result<Option<ByteSize>> {
1522 let output = Command::new("systemctl")
1523 .args(["show", slice, "--property=MemoryMax", "--value"])
1524 .output()?;
1525 if !output.status.success() {
1526 return Err(std::io::Error::other(format!(
1527 "systemctl show {slice} failed: {}",
1528 String::from_utf8_lossy(&output.stderr).trim()
1529 )));
1530 }
1531 let value = String::from_utf8_lossy(&output.stdout);
1532 parse_memory_max(value.trim()).ok_or_else(|| {
1533 std::io::Error::other(format!(
1534 "systemctl show {slice}: unexpected MemoryMax {value:?}"
1535 ))
1536 })
1537}
1538
1539pub fn cpu_budget(millicores: u64, overcommit: f64) -> u64 {
1541 #[expect(
1542 clippy::cast_precision_loss,
1543 clippy::cast_possible_truncation,
1544 clippy::cast_sign_loss,
1545 reason = "a host's millicores are far below 2^52, and the config check holds the factor above 0 and at \
1546 most 16"
1547 )]
1548 let budget = (millicores as f64 * overcommit.max(0.0)).round() as u64;
1549 budget
1550}
1551
1552pub fn slice_cpus(slice: &str) -> std::io::Result<u64> {
1555 let output = Command::new("systemctl")
1556 .args([
1557 "show",
1558 slice,
1559 "--property=EffectiveCPUs",
1560 "--property=AllowedCPUs",
1561 "--property=CPUQuotaPerSecUSec",
1562 ])
1563 .output()?;
1564 if !output.status.success() {
1565 return Err(std::io::Error::other(format!(
1566 "systemctl show {slice} failed: {}",
1567 String::from_utf8_lossy(&output.stderr).trim()
1568 )));
1569 }
1570 let host = std::thread::available_parallelism().map_or(1, std::num::NonZero::get) as u64;
1571 parse_slice_cpus(&String::from_utf8_lossy(&output.stdout), host).ok_or_else(|| {
1572 std::io::Error::other(format!(
1573 "systemctl show {slice}: unexpected CPU properties {:?}",
1574 String::from_utf8_lossy(&output.stdout).trim()
1575 ))
1576 })
1577}
1578
1579pub fn parse_slice_cpus(properties: &str, host: u64) -> Option<u64> {
1582 let value = |name: &str| {
1583 properties.lines().find_map(|line| {
1584 line.strip_prefix(name)
1585 .and_then(|rest| rest.strip_prefix('='))
1586 .map(str::trim)
1587 })
1588 };
1589 let set = [value("EffectiveCPUs"), value("AllowedCPUs")]
1590 .into_iter()
1591 .flatten()
1592 .find(|cpus| !cpus.is_empty());
1593 let cpus = match set {
1594 Some(set) => cpu_count(set)?,
1595 None => host,
1596 };
1597 let quota = match value("CPUQuotaPerSecUSec") {
1598 None | Some("" | "infinity") => u64::MAX,
1599 Some(quota) => quota_millicores(quota)?,
1600 };
1601 Some(cpus.saturating_mul(1000).min(quota))
1602}
1603
1604fn cpu_count(set: &str) -> Option<u64> {
1606 set.split([',', ' '])
1607 .filter(|range| !range.is_empty())
1608 .try_fold(0u64, |count, range| {
1609 let (first, last) = range.split_once('-').unwrap_or((range, range));
1610 let (first, last): (u64, u64) = (first.parse().ok()?, last.parse().ok()?);
1611 Some(count + last.checked_sub(first)? + 1)
1612 })
1613}
1614
1615fn quota_millicores(quota: &str) -> Option<u64> {
1618 const UNITS: [(&str, f64); 10] = [
1620 ("y", 31_557_600_000.0),
1621 ("M", 2_629_800_000.0),
1622 ("w", 604_800_000.0),
1623 ("d", 86_400_000.0),
1624 ("h", 3_600_000.0),
1625 ("min", 60_000.0),
1626 ("s", 1000.0),
1627 ("ms", 1.0),
1628 ("us", 0.001),
1629 ("µs", 0.001),
1630 ];
1631 let millicores = quota.split_whitespace().try_fold(0.0, |total, part| {
1632 let at = part.find(|c: char| !(c.is_ascii_digit() || c == '.'))?;
1633 let (number, unit) = part.split_at(at);
1634 let per_unit = UNITS
1635 .iter()
1636 .find_map(|(name, per_unit)| (*name == unit).then_some(*per_unit))?;
1637 Some(total + number.parse::<f64>().ok()? * per_unit)
1638 })?;
1639 #[allow(
1640 clippy::cast_possible_truncation,
1641 clippy::cast_sign_loss,
1642 reason = "a quota is a few thousand millicores per CPU, checked finite and not negative first"
1643 )]
1644 (!quota.trim().is_empty() && millicores.is_finite() && millicores >= 0.0)
1645 .then(|| millicores.round() as u64)
1646}
1647
1648pub fn parse_memory_max(value: &str) -> Option<Option<ByteSize>> {
1650 if value == "infinity" {
1651 Some(None)
1652 } else {
1653 value.parse().ok().map(|bytes| Some(ByteSize(bytes)))
1654 }
1655}
1656
1657#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1659pub struct ByteSize(pub u64);
1660
1661const UNITS: [(char, u64); 4] = [
1662 ('T', 1 << 40),
1663 ('G', 1 << 30),
1664 ('M', 1 << 20),
1665 ('K', 1 << 10),
1666];
1667
1668impl FromStr for ByteSize {
1669 type Err = String;
1670
1671 #[allow(
1672 clippy::cast_precision_loss,
1673 clippy::cast_possible_truncation,
1674 clippy::cast_sign_loss,
1675 reason = "sizes in a config are far below 2^52 bytes, and the result is checked against u64's range first"
1676 )]
1677 fn from_str(s: &str) -> Result<Self, Self::Err> {
1678 let invalid = || {
1679 format!(
1680 "invalid size {s:?}, expected a number and a unit (K, M, G or T), such as \"9G\""
1681 )
1682 };
1683 let unit = s.chars().last().ok_or_else(invalid)?.to_ascii_uppercase();
1684 let (_, factor) = UNITS.iter().find(|(u, _)| *u == unit).ok_or_else(invalid)?;
1685 let number = &s[..s.len() - 1];
1686 if number.is_empty() || !number.chars().all(|c| c.is_ascii_digit() || c == '.') {
1687 return Err(invalid());
1688 }
1689 let number: f64 = number.parse().map_err(|_| invalid())?;
1690 let bytes = (number * *factor as f64).round();
1691 if bytes >= u64::MAX as f64 {
1693 return Err(format!("size {s:?} is too large"));
1694 }
1695 Ok(ByteSize(bytes as u64))
1696 }
1697}
1698
1699impl fmt::Display for ByteSize {
1700 #[allow(
1701 clippy::cast_precision_loss,
1702 reason = "shown with two decimals, far coarser than f64's precision"
1703 )]
1704 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1705 let Some((unit, factor)) = UNITS.iter().find(|(_, factor)| self.0 >= *factor) else {
1706 return write!(f, "{}B", self.0);
1707 };
1708 let number = format!("{:.2}", self.0 as f64 / *factor as f64);
1709 let number = number.trim_end_matches('0').trim_end_matches('.');
1710 write!(f, "{number}{unit}")
1711 }
1712}
1713
1714impl ByteSize {
1715 #[allow(
1719 clippy::cast_precision_loss,
1720 reason = "shown with one decimal at most, far coarser than f64's precision"
1721 )]
1722 pub fn short(self) -> String {
1723 let Some(index) = UNITS.iter().position(|(_, factor)| self.0 >= *factor) else {
1724 return format!("{}B", self.0);
1725 };
1726 let (mut unit, factor) = UNITS[index];
1727 let mut value = self.0 as f64 / factor as f64;
1728 if value.round() >= 1024.0
1729 && let Some(larger) = index.checked_sub(1)
1730 {
1731 unit = UNITS[larger].0;
1732 value /= 1024.0;
1733 }
1734 let tenths = (value * 10.0).round() / 10.0;
1736 if tenths < 10.0 {
1737 let number = format!("{tenths:.1}");
1738 format!("{}{unit}", number.trim_end_matches(".0"))
1739 } else {
1740 format!("{:.0}{unit}", value.round())
1741 }
1742 }
1743}
1744
1745impl<'de> Deserialize<'de> for ByteSize {
1746 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1747 String::deserialize(deserializer)?
1748 .parse()
1749 .map_err(de::Error::custom)
1750 }
1751}
1752
1753pub fn parse_duration(s: &str) -> Result<Duration, String> {
1755 let invalid = || {
1756 format!(
1757 "invalid duration {s:?}, expected a number and s, m, h or d, such as \"168h\" or \"7d\""
1758 )
1759 };
1760 let (number, factor) = match s.chars().last() {
1761 Some('s') => (&s[..s.len() - 1], 1),
1762 Some('m') => (&s[..s.len() - 1], 60),
1763 Some('h') => (&s[..s.len() - 1], 3600),
1764 Some('d') => (&s[..s.len() - 1], 86400),
1765 _ => return Err(invalid()),
1766 };
1767 let number: u64 = number.parse().map_err(|_| invalid())?;
1768 number
1769 .checked_mul(factor)
1770 .map(Duration::from_secs)
1771 .ok_or_else(invalid)
1772}
1773
1774pub fn parse_age(text: &str) -> Result<Duration, String> {
1776 let error = || "expected a number and s, m, h, d or w, such as 12h".to_owned();
1777 let split = text.find(|c: char| !c.is_ascii_digit()).ok_or_else(error)?;
1778 let (number, unit) = text.split_at(split);
1779 let number: u64 = number.parse().map_err(|_| error())?;
1780 let unit = match unit {
1781 "s" => 1,
1782 "m" => 60,
1783 "h" => 3600,
1784 "d" => 86_400,
1785 "w" => 7 * 86_400,
1786 _ => return Err(error()),
1787 };
1788 Ok(Duration::from_secs(number.saturating_mul(unit)))
1789}
1790
1791fn duration<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Duration, D::Error> {
1792 parse_duration(&String::deserialize(deserializer)?).map_err(de::Error::custom)
1793}
1794
1795#[cfg(test)]
1796mod tests;