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 #[serde(default)]
76 pub memory_ceiling: Option<ByteSize>,
77}
78
79impl Host {
80 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
91pub const MAX_CPU_OVERCOMMIT: f64 = 16.0;
93
94#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
96#[serde(rename_all = "kebab-case")]
97pub enum Admission {
98 #[default]
100 Caps,
101 Measured,
104}
105
106impl Admission {
107 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
122#[serde(rename_all = "kebab-case")]
123pub enum Isolation {
124 Sysbox,
126 UnsafeDind,
128}
129
130#[derive(Debug, Clone, Deserialize)]
132#[serde(deny_unknown_fields)]
133pub struct Caches {
134 pub mirror: Mirror,
136 pub pnpm: CacheLimit,
138 pub maven: CacheLimit,
140 #[serde(default = "default_reseed_at")]
143 pub reseed_at: ByteSize,
144 #[serde(default = "default_snapshot_max")]
147 pub snapshot_max: ByteSize,
148 #[serde(default)]
150 pub build: BuildCache,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
156#[serde(deny_unknown_fields, default)]
157pub struct BuildCache {
158 pub enabled: bool,
160 pub max_size: ByteSize,
162 pub branches: Vec<String>,
165 pub directory: Option<PathBuf>,
167 pub actions_cache: bool,
170}
171
172impl BuildCache {
173 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
214fn default_snapshot_max() -> ByteSize {
216 ByteSize(10 << 30)
217}
218
219fn default_mirror_max_size() -> ByteSize {
220 ByteSize(10 << 30)
221}
222
223#[derive(Debug, Clone, Deserialize)]
225#[serde(deny_unknown_fields)]
226pub struct Mirror {
227 pub enabled: bool,
229 pub memory: ByteSize,
231 pub cpus: u32,
233 #[serde(deserialize_with = "duration")]
235 pub ttl: Duration,
236 #[serde(default = "default_mirror_max_size")]
238 pub max_size: ByteSize,
239}
240
241#[derive(Debug, Clone, Deserialize)]
243#[serde(deny_unknown_fields)]
244pub struct CacheLimit {
245 pub max_size: ByteSize,
247}
248
249pub const PUBLISHED_RUNNER: &str = "ghcr.io/ayagmar/runnerd-runner";
252
253#[derive(Debug, Clone, Deserialize)]
255#[serde(try_from = "ProfileToml")]
256pub struct Profile {
257 pub image: Image,
259 pub cpus: u32,
261 pub memory: ByteSize,
263 pub slots: u32,
265 pub record_failures: bool,
267 pub min_memory: Option<ByteSize>,
269 pub max_memory: Option<ByteSize>,
271 pub max_slots: Option<u32>,
273 pub priced_as: Option<api::Sku>,
276}
277
278#[derive(Debug, Clone, PartialEq, Eq)]
280pub enum Image {
281 Stage(String),
283 Pulled(String),
286}
287
288impl Image {
289 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#[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
350pub 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#[derive(Debug, Deserialize)]
365#[serde(deny_unknown_fields)]
366pub struct Repository {
367 pub name: String,
369 pub profile: String,
371 pub labels: Vec<String>,
373 #[serde(default = "default_warm")]
376 pub warm: u32,
377 #[serde(default = "default_true")]
379 pub build_cache: bool,
380 #[serde(default)]
383 pub build_cache_writers: BuildCacheWriters,
384}
385
386#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
388#[serde(rename_all = "kebab-case")]
389pub enum BuildCacheWriters {
390 #[default]
392 DefaultBranch,
393 PullRequests,
395}
396
397fn default_true() -> bool {
398 true
399}
400
401fn default_warm() -> u32 {
402 1
403}
404
405#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
407#[serde(deny_unknown_fields, default)]
408pub struct History {
409 pub database: Option<PathBuf>,
411 #[serde(deserialize_with = "duration")]
413 pub samples: Duration,
414 #[serde(deserialize_with = "duration")]
416 pub logs: Duration,
417 #[serde(deserialize_with = "duration")]
419 pub events: Duration,
420 #[serde(deserialize_with = "duration")]
422 pub jobs: Duration,
423 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#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
443#[serde(deny_unknown_fields, default)]
444pub struct Records {
445 pub max_total: ByteSize,
447 pub max_count: u32,
449 #[serde(deserialize_with = "duration")]
451 pub max_age: Duration,
452 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#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
470#[serde(deny_unknown_fields, default)]
471pub struct Sizing {
472 pub margin: u32,
475 pub min_jobs: u32,
478 pub auto: bool,
481 #[serde(deserialize_with = "duration")]
484 pub interval: Duration,
485 #[serde(deserialize_with = "duration")]
488 pub raise_interval: Duration,
489 pub max_step: u32,
492}
493
494impl Sizing {
495 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#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
517#[serde(deny_unknown_fields, default)]
518pub struct Web {
519 pub origins: Vec<Origin>,
522 pub open: Option<Origin>,
525}
526
527impl Web {
528 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#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
541#[serde(deny_unknown_fields, default)]
542pub struct Notify {
543 pub digest_at: DayTime,
545 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 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#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
629#[serde(deny_unknown_fields)]
630pub struct NotifyTarget {
631 pub name: String,
633 pub kind: NotifyKind,
635 pub url: Secret,
638 #[serde(default)]
640 pub headers: BTreeMap<String, Secret>,
641 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
657#[serde(rename_all = "kebab-case")]
658pub enum NotifyKind {
659 Webhook,
661 Ntfy,
663 Discord,
665}
666
667#[derive(Clone, PartialEq, Eq, Deserialize)]
669#[serde(transparent)]
670pub struct Secret(String);
671
672impl Secret {
673 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
693pub struct DayTime {
694 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#[derive(Debug, Clone, PartialEq, Eq)]
739pub struct Origin(String);
740
741impl Origin {
742 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 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 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
844fn 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#[derive(Debug, thiserror::Error)]
890pub enum ConfigError {
891 #[error("cannot read {}: {source}", path.display())]
893 Read {
894 path: PathBuf,
896 source: std::io::Error,
898 },
899 #[error(transparent)]
901 Parse(#[from] toml::de::Error),
902 #[error(
904 "repository {repository} uses profile {profile:?}, which is not defined under [profiles]; {}",
905 defined_profiles(.defined)
906 )]
907 UnknownProfile {
908 repository: String,
910 profile: String,
912 defined: Vec<String>,
914 },
915 #[error("repository {repository} needs at least one non-empty label")]
917 MissingLabels {
918 repository: String,
920 },
921 #[error(
923 "repository {repository} has two entries with profile {profile:?}; give each of its pools its own profile"
924 )]
925 PoolProfileTwice {
926 repository: String,
928 profile: String,
930 },
931 #[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 repository: String,
941 first: String,
943 second: String,
945 label: String,
947 },
948 #[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 repository: String,
956 },
957 #[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 #[error("{field} is 0; set it above 0")]
965 ZeroLimit {
966 field: String,
968 },
969 #[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 value: f64,
976 },
977 #[error(
979 "web.open is {open}, which is not one of [web] origins; add it to origins, or remove open"
980 )]
981 OpenNotListed {
982 open: Origin,
984 },
985 #[error("profiles.{profile}: {why}")]
988 SizingBounds {
989 profile: String,
991 why: &'static str,
993 },
994 #[error("notify target {target:?}: {why}")]
996 Notify {
997 target: String,
999 why: &'static str,
1001 },
1002 #[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 profile: String,
1010 needs: ByteSize,
1012 ceiling: ByteSize,
1014 },
1015 #[error("slots × memory over all profiles plus the mirror is too large to add up")]
1017 BudgetOverflow,
1018 #[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 slice: String,
1026 },
1027 #[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 profile: String,
1035 needs: ByteSize,
1037 slice: String,
1039 memory_max: ByteSize,
1041 },
1042 #[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 total: ByteSize,
1051 slice: String,
1053 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#[derive(Debug, Clone, PartialEq, Eq)]
1068pub enum Warning {
1069 UnlimitedSlice {
1071 slice: String,
1073 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 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 pub fn parse(text: &str) -> Result<Config, ConfigError> {
1102 Ok(toml::from_str(text)?)
1103 }
1104
1105 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 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 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 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 pub fn runner_ceiling(&self) -> Option<u64> {
1180 self.host
1181 .memory_ceiling
1182 .map(|ceiling| ceiling.0.saturating_sub(self.mirror_memory()))
1183 }
1184
1185 fn check_memory_ceiling(&self) -> Result<(), ConfigError> {
1190 let (Some(ceiling), Some(most)) = (self.host.memory_ceiling, self.runner_ceiling()) else {
1191 return Ok(());
1192 };
1193 let largest = self
1194 .profiles
1195 .iter()
1196 .max_by_key(|(_, profile)| profile.memory.0);
1197 match largest {
1198 Some((profile, largest)) if largest.memory.0 > most => {
1199 Err(ConfigError::CeilingUnderProfile {
1200 profile: profile.clone(),
1201 needs: ByteSize(largest.memory.0.saturating_add(self.mirror_memory())),
1202 ceiling,
1203 })
1204 }
1205 _ => Ok(()),
1206 }
1207 }
1208
1209 fn check_sizing_bounds(&self) -> Result<(), ConfigError> {
1211 for (name, p) in &self.profiles {
1212 let memory = p.memory.0;
1213 let field = if p
1214 .min_memory
1215 .zip(p.max_memory)
1216 .is_some_and(|(min, max)| min.0 > max.0)
1217 {
1218 "min_memory is above its max_memory"
1219 } else if p.min_memory.is_some_and(|min| memory < min.0) {
1220 "memory is below its min_memory"
1221 } else if p.max_memory.is_some_and(|max| memory > max.0) {
1222 "memory is above its max_memory"
1223 } else if p.max_slots.is_some_and(|max| p.slots > max) {
1224 "slots are above its max_slots"
1225 } else {
1226 continue;
1227 };
1228 return Err(ConfigError::SizingBounds {
1229 profile: name.clone(),
1230 why: field,
1231 });
1232 }
1233 Ok(())
1234 }
1235
1236 fn check_pools(&self) -> Result<(), ConfigError> {
1239 for (at, first) in self.repositories.iter().enumerate() {
1240 for second in self.repositories[at + 1..]
1241 .iter()
1242 .filter(|second| second.name == first.name)
1243 {
1244 if second.profile == first.profile {
1245 return Err(ConfigError::PoolProfileTwice {
1246 repository: first.name.clone(),
1247 profile: first.profile.clone(),
1248 });
1249 }
1250 if let Some(label) = first.labels.iter().find(|label| {
1251 second
1252 .labels
1253 .iter()
1254 .any(|other| other.eq_ignore_ascii_case(label))
1255 }) {
1256 return Err(ConfigError::PoolLabelsOverlap {
1257 repository: first.name.clone(),
1258 first: first.profile.clone(),
1259 second: second.profile.clone(),
1260 label: label.clone(),
1261 });
1262 }
1263 if second.build_cache_writers != first.build_cache_writers {
1264 return Err(ConfigError::PoolWritersDiffer {
1265 repository: first.name.clone(),
1266 });
1267 }
1268 }
1269 }
1270 Ok(())
1271 }
1272
1273 pub fn pool(&self, repository: &str, labels: &[String]) -> Option<&Repository> {
1276 self.repositories
1277 .iter()
1278 .find(|pool| pool.name == repository && labels_match(labels, &pool.labels))
1279 }
1280
1281 pub fn pool_in(&self, repository: &str, profile: &str) -> Option<&Repository> {
1283 self.repositories
1284 .iter()
1285 .find(|pool| pool.name == repository && pool.profile == profile)
1286 }
1287
1288 pub fn pricing(&self) -> api::Pricing {
1290 api::Pricing {
1291 profiles: self
1292 .profiles
1293 .iter()
1294 .filter_map(|(name, profile)| Some((name.clone(), profile.priced_as?)))
1295 .collect(),
1296 default_sku: api::Sku::standard_for(std::env::consts::ARCH),
1297 }
1298 }
1299
1300 pub fn repository_names(&self) -> Vec<String> {
1302 let mut names: Vec<String> = Vec::new();
1303 for repository in &self.repositories {
1304 if !names.contains(&repository.name) {
1305 names.push(repository.name.clone());
1306 }
1307 }
1308 names
1309 }
1310
1311 pub fn validate(&self, memory_max: Option<ByteSize>) -> Result<Vec<Warning>, ConfigError> {
1313 if self.host.isolation == Isolation::UnsafeDind && !self.host.allow_unsafe {
1314 return Err(ConfigError::UnsafeNotAllowed);
1315 }
1316 let zero_limits = self.profiles.iter().flat_map(|(name, p)| {
1317 [
1318 (p.memory.0 == 0, format!("profiles.{name}.memory")),
1319 (p.cpus == 0, format!("profiles.{name}.cpus")),
1320 (p.slots == 0, format!("profiles.{name}.slots")),
1321 (p.max_slots == Some(0), format!("profiles.{name}.max_slots")),
1322 ]
1323 });
1324 let mirror = &self.caches.mirror;
1325 let mirror_zero_limits = [
1326 (
1327 mirror.enabled && mirror.memory.0 == 0,
1328 "caches.mirror.memory".to_owned(),
1329 ),
1330 (
1331 mirror.enabled && mirror.cpus == 0,
1332 "caches.mirror.cpus".to_owned(),
1333 ),
1334 (
1335 self.host.poll_interval.is_zero(),
1336 "host.poll_interval".to_owned(),
1337 ),
1338 (
1339 self.host.memory_ceiling == Some(ByteSize(0)),
1340 "host.memory_ceiling".to_owned(),
1341 ),
1342 (self.records.max_count == 0, "records.max_count".to_owned()),
1343 (self.sizing.min_jobs == 0, "sizing.min_jobs".to_owned()),
1344 (self.sizing.interval.is_zero(), "sizing.interval".to_owned()),
1345 (
1346 self.sizing.raise_interval.is_zero(),
1347 "sizing.raise_interval".to_owned(),
1348 ),
1349 (self.sizing.max_step == 0, "sizing.max_step".to_owned()),
1350 (
1351 self.records.max_total.0 == 0,
1352 "records.max_total".to_owned(),
1353 ),
1354 ];
1355 if let Some((_, field)) = zero_limits
1356 .chain(mirror_zero_limits)
1357 .find(|(zero, _)| *zero)
1358 {
1359 return Err(ConfigError::ZeroLimit { field });
1360 }
1361 self.check_sizing_bounds()?;
1362 self.caches.build.validate()?;
1363 self.host.check_cpu_overcommit()?;
1364 self.check_memory_ceiling()?;
1365 self.web.validate()?;
1366 self.notify.validate()?;
1367 for repository in &self.repositories {
1368 if !self.profiles.contains_key(&repository.profile) {
1369 return Err(ConfigError::UnknownProfile {
1370 repository: repository.name.clone(),
1371 profile: repository.profile.clone(),
1372 defined: self.profiles.keys().cloned().collect(),
1373 });
1374 }
1375 if repository.labels.is_empty() || repository.labels.iter().any(|l| l.trim().is_empty())
1376 {
1377 return Err(ConfigError::MissingLabels {
1378 repository: repository.name.clone(),
1379 });
1380 }
1381 }
1382 self.check_pools()?;
1383 self.check_budget(memory_max)
1384 }
1385
1386 fn check_budget(&self, memory_max: Option<ByteSize>) -> Result<Vec<Warning>, ConfigError> {
1388 let total = self.memory_caps()?;
1389 if self.host.admission == Admission::Measured {
1390 let Some(memory_max) = memory_max else {
1391 return Err(ConfigError::MeasuredWithoutMemoryMax {
1392 slice: self.host.slice.clone(),
1393 });
1394 };
1395 let mirror = self.mirror_memory();
1396 if let Some((profile, needs)) = self
1397 .profiles
1398 .iter()
1399 .map(|(name, profile)| (name, profile.memory.0.saturating_add(mirror)))
1400 .find(|(_, needs)| *needs > memory_max.0)
1401 {
1402 return Err(ConfigError::ProfileOverBudget {
1403 profile: profile.clone(),
1404 needs: ByteSize(needs),
1405 slice: self.host.slice.clone(),
1406 memory_max,
1407 });
1408 }
1409 let needed = self.memory_needed()?;
1411 if needed > memory_max {
1412 return Err(ConfigError::OverBudget {
1413 total: needed,
1414 slice: self.host.slice.clone(),
1415 memory_max,
1416 });
1417 }
1418 return Ok(Vec::new());
1419 }
1420 match memory_max {
1421 Some(memory_max) if total > memory_max => Err(ConfigError::OverBudget {
1422 total,
1423 slice: self.host.slice.clone(),
1424 memory_max,
1425 }),
1426 Some(_) => Ok(Vec::new()),
1427 None => Ok(vec![Warning::UnlimitedSlice {
1428 slice: self.host.slice.clone(),
1429 total,
1430 }]),
1431 }
1432 }
1433}
1434
1435#[derive(Debug, thiserror::Error)]
1437pub enum ResizeError {
1438 #[error(transparent)]
1440 Parse(#[from] toml_edit::TomlError),
1441 #[error("the config has no profile {0:?} under [profiles]")]
1443 NoProfile(String),
1444}
1445
1446pub fn resize_profile(
1449 text: &str,
1450 profile: &str,
1451 resize: api::Resize,
1452) -> Result<String, ResizeError> {
1453 let mut document: toml_edit::DocumentMut = text.parse()?;
1454 let table = document
1455 .get_mut("profiles")
1456 .and_then(|profiles| profiles.get_mut(profile))
1457 .and_then(toml_edit::Item::as_table_like_mut)
1458 .ok_or_else(|| ResizeError::NoProfile(profile.to_owned()))?;
1459 let values = [
1460 (
1461 "memory",
1462 toml_edit::Value::from(ByteSize(resize.memory).exact()),
1463 ),
1464 ("slots", toml_edit::Value::from(i64::from(resize.slots))),
1465 ];
1466 let cpus = resize
1467 .cpus
1468 .map(|cpus| ("cpus", toml_edit::Value::from(i64::from(cpus))));
1469 for (key, mut value) in values.into_iter().chain(cpus) {
1470 if let Some(old) = table.get(key).and_then(toml_edit::Item::as_value) {
1472 *value.decor_mut() = old.decor().clone();
1473 }
1474 table.insert(key, toml_edit::Item::Value(value));
1475 }
1476 Ok(document.to_string())
1477}
1478
1479pub const SECRET_SHOWN: &str = "<secret>";
1481
1482pub fn mask_secrets(text: &str) -> Option<String> {
1486 let mut document: toml_edit::DocumentMut = text.parse().ok()?;
1487 let mut masked = false;
1488 for target in notify_targets(&mut document) {
1489 for (_, value) in secrets_of(target) {
1490 replace_value(value, toml_edit::Value::from(SECRET_SHOWN));
1491 masked = true;
1492 }
1493 }
1494 Some(if masked {
1495 document.to_string()
1496 } else {
1497 text.to_owned()
1498 })
1499}
1500
1501pub fn keep_secrets(text: &str, stored: &str) -> String {
1508 if !text.contains(SECRET_SHOWN) || Config::parse(text).is_err() {
1509 return text.to_owned();
1510 }
1511 let (Ok(mut document), Ok(mut old)) = (
1512 text.parse::<toml_edit::DocumentMut>(),
1513 stored.parse::<toml_edit::DocumentMut>(),
1514 ) else {
1515 return text.to_owned();
1516 };
1517 let mut kept: BTreeMap<String, Vec<(SecretField, toml_edit::Value)>> = BTreeMap::new();
1518 for target in notify_targets(&mut old) {
1519 let Some(name) = target_name(target) else {
1520 continue;
1521 };
1522 let secrets = secrets_of(target)
1523 .into_iter()
1524 .map(|(field, value)| (field, value.clone()))
1525 .collect();
1526 kept.insert(name, secrets);
1527 }
1528 for target in notify_targets(&mut document) {
1529 let Some(secrets) = target_name(target).and_then(|name| kept.get(&name)) else {
1530 continue;
1531 };
1532 for (field, value) in secrets_of(target) {
1533 if value.as_str() != Some(SECRET_SHOWN) {
1534 continue;
1535 }
1536 if let Some((_, old)) = secrets.iter().find(|(kept, _)| *kept == field) {
1537 replace_value(value, old.clone());
1538 }
1539 }
1540 }
1541 document.to_string()
1542}
1543
1544#[derive(Debug, PartialEq, Eq)]
1546enum SecretField {
1547 Url,
1548 Header(String),
1549}
1550
1551fn notify_targets(document: &mut toml_edit::DocumentMut) -> Vec<&mut dyn toml_edit::TableLike> {
1553 match document
1554 .get_mut("notify")
1555 .and_then(|notify| notify.get_mut("targets"))
1556 {
1557 Some(toml_edit::Item::ArrayOfTables(tables)) => tables
1558 .iter_mut()
1559 .map(|table| table as &mut dyn toml_edit::TableLike)
1560 .collect(),
1561 Some(toml_edit::Item::Value(toml_edit::Value::Array(array))) => array
1562 .iter_mut()
1563 .filter_map(toml_edit::Value::as_inline_table_mut)
1564 .map(|table| table as &mut dyn toml_edit::TableLike)
1565 .collect(),
1566 _ => Vec::new(),
1567 }
1568}
1569
1570fn target_name(target: &dyn toml_edit::TableLike) -> Option<String> {
1571 target
1572 .get("name")
1573 .and_then(toml_edit::Item::as_str)
1574 .map(str::to_owned)
1575}
1576
1577fn secrets_of(target: &mut dyn toml_edit::TableLike) -> Vec<(SecretField, &mut toml_edit::Value)> {
1579 let mut found = Vec::new();
1580 for (key, item) in target.iter_mut() {
1581 match key.get() {
1582 "url" => found.extend(item.as_value_mut().map(|value| (SecretField::Url, value))),
1583 "headers" => {
1584 let Some(headers) = item.as_table_like_mut() else {
1585 continue;
1586 };
1587 for (name, item) in headers.iter_mut() {
1588 let field = SecretField::Header(name.get().to_owned());
1589 found.extend(item.as_value_mut().map(|value| (field, value)));
1590 }
1591 }
1592 _ => {}
1593 }
1594 }
1595 found
1596}
1597
1598fn replace_value(value: &mut toml_edit::Value, mut new: toml_edit::Value) {
1600 *new.decor_mut() = value.decor().clone();
1601 *value = new;
1602}
1603
1604pub fn revision(text: &str) -> String {
1607 let hash = text.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
1608 (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
1609 });
1610 format!("{hash:016x}")
1611}
1612
1613pub fn slice_memory_max(slice: &str) -> std::io::Result<Option<ByteSize>> {
1615 let output = Command::new("systemctl")
1616 .args(["show", slice, "--property=MemoryMax", "--value"])
1617 .output()?;
1618 if !output.status.success() {
1619 return Err(std::io::Error::other(format!(
1620 "systemctl show {slice} failed: {}",
1621 String::from_utf8_lossy(&output.stderr).trim()
1622 )));
1623 }
1624 let value = String::from_utf8_lossy(&output.stdout);
1625 parse_memory_max(value.trim()).ok_or_else(|| {
1626 std::io::Error::other(format!(
1627 "systemctl show {slice}: unexpected MemoryMax {value:?}"
1628 ))
1629 })
1630}
1631
1632pub fn cpu_budget(millicores: u64, overcommit: f64) -> u64 {
1634 #[expect(
1635 clippy::cast_precision_loss,
1636 clippy::cast_possible_truncation,
1637 clippy::cast_sign_loss,
1638 reason = "a host's millicores are far below 2^52, and the config check holds the factor above 0 and at \
1639 most 16"
1640 )]
1641 let budget = (millicores as f64 * overcommit.max(0.0)).round() as u64;
1642 budget
1643}
1644
1645pub fn slice_cpus(slice: &str) -> std::io::Result<u64> {
1648 let output = Command::new("systemctl")
1649 .args([
1650 "show",
1651 slice,
1652 "--property=EffectiveCPUs",
1653 "--property=AllowedCPUs",
1654 "--property=CPUQuotaPerSecUSec",
1655 ])
1656 .output()?;
1657 if !output.status.success() {
1658 return Err(std::io::Error::other(format!(
1659 "systemctl show {slice} failed: {}",
1660 String::from_utf8_lossy(&output.stderr).trim()
1661 )));
1662 }
1663 let host = std::thread::available_parallelism().map_or(1, std::num::NonZero::get) as u64;
1664 parse_slice_cpus(&String::from_utf8_lossy(&output.stdout), host).ok_or_else(|| {
1665 std::io::Error::other(format!(
1666 "systemctl show {slice}: unexpected CPU properties {:?}",
1667 String::from_utf8_lossy(&output.stdout).trim()
1668 ))
1669 })
1670}
1671
1672pub fn parse_slice_cpus(properties: &str, host: u64) -> Option<u64> {
1675 let value = |name: &str| {
1676 properties.lines().find_map(|line| {
1677 line.strip_prefix(name)
1678 .and_then(|rest| rest.strip_prefix('='))
1679 .map(str::trim)
1680 })
1681 };
1682 let set = [value("EffectiveCPUs"), value("AllowedCPUs")]
1683 .into_iter()
1684 .flatten()
1685 .find(|cpus| !cpus.is_empty());
1686 let cpus = match set {
1687 Some(set) => cpu_count(set)?,
1688 None => host,
1689 };
1690 let quota = match value("CPUQuotaPerSecUSec") {
1691 None | Some("" | "infinity") => u64::MAX,
1692 Some(quota) => quota_millicores(quota)?,
1693 };
1694 Some(cpus.saturating_mul(1000).min(quota))
1695}
1696
1697fn cpu_count(set: &str) -> Option<u64> {
1699 set.split([',', ' '])
1700 .filter(|range| !range.is_empty())
1701 .try_fold(0u64, |count, range| {
1702 let (first, last) = range.split_once('-').unwrap_or((range, range));
1703 let (first, last): (u64, u64) = (first.parse().ok()?, last.parse().ok()?);
1704 Some(count + last.checked_sub(first)? + 1)
1705 })
1706}
1707
1708fn quota_millicores(quota: &str) -> Option<u64> {
1711 const UNITS: [(&str, f64); 10] = [
1713 ("y", 31_557_600_000.0),
1714 ("M", 2_629_800_000.0),
1715 ("w", 604_800_000.0),
1716 ("d", 86_400_000.0),
1717 ("h", 3_600_000.0),
1718 ("min", 60_000.0),
1719 ("s", 1000.0),
1720 ("ms", 1.0),
1721 ("us", 0.001),
1722 ("µs", 0.001),
1723 ];
1724 let millicores = quota.split_whitespace().try_fold(0.0, |total, part| {
1725 let at = part.find(|c: char| !(c.is_ascii_digit() || c == '.'))?;
1726 let (number, unit) = part.split_at(at);
1727 let per_unit = UNITS
1728 .iter()
1729 .find_map(|(name, per_unit)| (*name == unit).then_some(*per_unit))?;
1730 Some(total + number.parse::<f64>().ok()? * per_unit)
1731 })?;
1732 #[allow(
1733 clippy::cast_possible_truncation,
1734 clippy::cast_sign_loss,
1735 reason = "a quota is a few thousand millicores per CPU, checked finite and not negative first"
1736 )]
1737 (!quota.trim().is_empty() && millicores.is_finite() && millicores >= 0.0)
1738 .then(|| millicores.round() as u64)
1739}
1740
1741pub fn parse_memory_max(value: &str) -> Option<Option<ByteSize>> {
1743 if value == "infinity" {
1744 Some(None)
1745 } else {
1746 value.parse().ok().map(|bytes| Some(ByteSize(bytes)))
1747 }
1748}
1749
1750#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1752pub struct ByteSize(pub u64);
1753
1754const UNITS: [(char, u64); 4] = [
1755 ('T', 1 << 40),
1756 ('G', 1 << 30),
1757 ('M', 1 << 20),
1758 ('K', 1 << 10),
1759];
1760
1761impl FromStr for ByteSize {
1762 type Err = String;
1763
1764 #[allow(
1765 clippy::cast_precision_loss,
1766 clippy::cast_possible_truncation,
1767 clippy::cast_sign_loss,
1768 reason = "sizes in a config are far below 2^52 bytes, and the result is checked against u64's range first"
1769 )]
1770 fn from_str(s: &str) -> Result<Self, Self::Err> {
1771 let invalid = || {
1772 format!(
1773 "invalid size {s:?}, expected a number and a unit (K, M, G or T), such as \"9G\""
1774 )
1775 };
1776 let unit = s.chars().last().ok_or_else(invalid)?.to_ascii_uppercase();
1777 let (_, factor) = UNITS.iter().find(|(u, _)| *u == unit).ok_or_else(invalid)?;
1778 let number = &s[..s.len() - 1];
1779 if number.is_empty() || !number.chars().all(|c| c.is_ascii_digit() || c == '.') {
1780 return Err(invalid());
1781 }
1782 let number: f64 = number.parse().map_err(|_| invalid())?;
1783 let bytes = (number * *factor as f64).round();
1784 if bytes >= u64::MAX as f64 {
1786 return Err(format!("size {s:?} is too large"));
1787 }
1788 Ok(ByteSize(bytes as u64))
1789 }
1790}
1791
1792impl fmt::Display for ByteSize {
1793 #[allow(
1794 clippy::cast_precision_loss,
1795 reason = "shown with two decimals, far coarser than f64's precision"
1796 )]
1797 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1798 let Some((unit, factor)) = UNITS.iter().find(|(_, factor)| self.0 >= *factor) else {
1799 return write!(f, "{}B", self.0);
1800 };
1801 let number = format!("{:.2}", self.0 as f64 / *factor as f64);
1802 let number = number.trim_end_matches('0').trim_end_matches('.');
1803 write!(f, "{number}{unit}")
1804 }
1805}
1806
1807impl ByteSize {
1808 #[allow(
1812 clippy::cast_precision_loss,
1813 reason = "a unit is a power of two, so the quotient is exact below 2^53 bytes; the parse checks it"
1814 )]
1815 pub fn exact(self) -> String {
1816 let reads_back = |text: &String| text.parse::<ByteSize>() == Ok(self);
1817 let shown = self.to_string();
1818 if reads_back(&shown) {
1819 return shown;
1820 }
1821 let mut shortest: Option<String> = None;
1822 for (unit, factor) in UNITS {
1823 let text = format!("{}{unit}", self.0 as f64 / factor as f64);
1824 if reads_back(&text) && shortest.as_ref().is_none_or(|best| text.len() < best.len()) {
1825 shortest = Some(text);
1826 }
1827 }
1828 shortest.unwrap_or(shown)
1829 }
1830
1831 #[allow(
1835 clippy::cast_precision_loss,
1836 reason = "shown with one decimal at most, far coarser than f64's precision"
1837 )]
1838 pub fn short(self) -> String {
1839 let Some(index) = UNITS.iter().position(|(_, factor)| self.0 >= *factor) else {
1840 return format!("{}B", self.0);
1841 };
1842 let (mut unit, factor) = UNITS[index];
1843 let mut value = self.0 as f64 / factor as f64;
1844 if value.round() >= 1024.0
1845 && let Some(larger) = index.checked_sub(1)
1846 {
1847 unit = UNITS[larger].0;
1848 value /= 1024.0;
1849 }
1850 let tenths = (value * 10.0).round() / 10.0;
1852 if tenths < 10.0 {
1853 let number = format!("{tenths:.1}");
1854 format!("{}{unit}", number.trim_end_matches(".0"))
1855 } else {
1856 format!("{:.0}{unit}", value.round())
1857 }
1858 }
1859}
1860
1861impl<'de> Deserialize<'de> for ByteSize {
1862 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1863 String::deserialize(deserializer)?
1864 .parse()
1865 .map_err(de::Error::custom)
1866 }
1867}
1868
1869pub fn parse_duration(s: &str) -> Result<Duration, String> {
1871 let invalid = || {
1872 format!(
1873 "invalid duration {s:?}, expected a number and s, m, h or d, such as \"168h\" or \"7d\""
1874 )
1875 };
1876 let (number, factor) = match s.chars().last() {
1877 Some('s') => (&s[..s.len() - 1], 1),
1878 Some('m') => (&s[..s.len() - 1], 60),
1879 Some('h') => (&s[..s.len() - 1], 3600),
1880 Some('d') => (&s[..s.len() - 1], 86400),
1881 _ => return Err(invalid()),
1882 };
1883 let number: u64 = number.parse().map_err(|_| invalid())?;
1884 number
1885 .checked_mul(factor)
1886 .map(Duration::from_secs)
1887 .ok_or_else(invalid)
1888}
1889
1890pub fn parse_age(text: &str) -> Result<Duration, String> {
1892 let error = || "expected a number and s, m, h, d or w, such as 12h".to_owned();
1893 let split = text.find(|c: char| !c.is_ascii_digit()).ok_or_else(error)?;
1894 let (number, unit) = text.split_at(split);
1895 let number: u64 = number.parse().map_err(|_| error())?;
1896 let unit = match unit {
1897 "s" => 1,
1898 "m" => 60,
1899 "h" => 3600,
1900 "d" => 86_400,
1901 "w" => 7 * 86_400,
1902 _ => return Err(error()),
1903 };
1904 Ok(Duration::from_secs(number.saturating_mul(unit)))
1905}
1906
1907fn duration<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Duration, D::Error> {
1908 parse_duration(&String::deserialize(deserializer)?).map_err(de::Error::custom)
1909}
1910
1911#[cfg(test)]
1912mod tests;