1use std::fmt;
4use std::net::SocketAddr;
5use std::path::{Path, PathBuf};
6use std::time::Duration;
7
8use crate::error::{ValidationError, ValidationErrorKind};
9use crate::rules;
10use crate::schema::schema;
11use crate::value::Value;
12
13const SECS_PER_DAY: u64 = 86_400;
15
16#[derive(Clone, PartialEq, Eq, Hash)]
22pub struct SecretRef(String);
23
24impl SecretRef {
25 pub fn as_str(&self) -> &str {
27 &self.0
28 }
29}
30
31impl fmt::Debug for SecretRef {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 f.write_str("SecretRef(<redacted>)")
34 }
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Config {
58 node_name: String,
59 canonical_origin: Option<String>,
60 listen_address: SocketAddr,
61 state_dir: PathBuf,
62 backup_dir: PathBuf,
63 age_recipients: Vec<String>,
64 pod_admin_key_ref: Option<SecretRef>,
65 federation_egress_enabled: bool,
66 max_tenants: u32,
67 invitations_enabled: bool,
68 invitation_ttl_secs: u32,
69 removal_grace_days: u32,
70 max_body_bytes: u32,
71 max_outstanding_challenges: u32,
72 max_pod_body_bytes: u32,
73 admission_requests_per_minute: u32,
74 min_pod_free_bytes: u64,
75 pod_bytes_per_tenant: u64,
76 job_max_cpus: u32,
77 job_max_memory_bytes: u64,
78 job_max_pids: u64,
79 job_max_tmp_bytes: u64,
80 job_max_timeout_secs: u64,
81 max_concurrent_jobs: u32,
82}
83
84impl Config {
85 pub(crate) fn from_values(values: &[Value]) -> Result<Self, ValidationError> {
94 let v = Lookup::new(values).expect("expected one value per schema field");
95 let non_empty = |s: &str| (!s.is_empty()).then(|| s.to_owned());
96 let listen = v.str("listen.address")?;
97 Ok(Self {
98 node_name: v.str("node.name")?.to_owned(),
99 canonical_origin: non_empty(v.str("node.canonical_origin")?),
100 listen_address: rules::parse_loopback(listen).map_err(|msg| {
101 ValidationError::at(ValidationErrorKind::InvalidValue, "listen.address", msg)
102 })?,
103 state_dir: PathBuf::from(v.str("storage.state_dir")?),
104 backup_dir: PathBuf::from(v.str("storage.backup_dir")?),
105 age_recipients: v.list("backup.age_recipients")?.to_vec(),
106 pod_admin_key_ref: non_empty(v.str("secrets.pod_admin_key_ref")?).map(SecretRef),
107 federation_egress_enabled: v.bool("federation.egress_enabled")?,
108 max_body_bytes: v.u32("limits.max_body_bytes")?,
109 max_tenants: v.u32("membership.max_tenants")?,
110 invitations_enabled: v.bool("membership.invitations_enabled")?,
111 invitation_ttl_secs: v.u32("membership.invitation_ttl_secs")?,
112 removal_grace_days: v.u32("membership.removal_grace_days")?,
113 max_outstanding_challenges: v.u32("limits.max_outstanding_challenges")?,
114 max_pod_body_bytes: v.u32("limits.max_pod_body_bytes")?,
115 admission_requests_per_minute: v.u32("limits.admission_requests_per_minute")?,
116 min_pod_free_bytes: v.u64("limits.min_pod_free_bytes")?,
117 pod_bytes_per_tenant: v.u64("limits.pod_bytes_per_tenant")?,
118 job_max_cpus: v.u32("limits.job_max_cpus")?,
119 job_max_memory_bytes: v.u64("limits.job_max_memory_bytes")?,
120 job_max_pids: v.u64("limits.job_max_pids")?,
121 job_max_tmp_bytes: v.u64("limits.job_max_tmp_bytes")?,
122 job_max_timeout_secs: v.u64("limits.job_max_timeout_secs")?,
123 max_concurrent_jobs: v.u32("runner.max_concurrent_jobs")?,
124 })
125 }
126
127 pub fn node_name(&self) -> &str {
129 &self.node_name
130 }
131
132 pub fn canonical_origin(&self) -> Option<&str> {
134 self.canonical_origin.as_deref()
135 }
136
137 pub fn listen_address(&self) -> SocketAddr {
139 self.listen_address
140 }
141
142 pub fn state_dir(&self) -> &Path {
144 &self.state_dir
145 }
146
147 pub fn backup_dir(&self) -> &Path {
150 &self.backup_dir
151 }
152
153 pub fn age_recipients(&self) -> &[String] {
156 &self.age_recipients
157 }
158
159 pub fn pod_admin_key_ref(&self) -> Option<&SecretRef> {
164 self.pod_admin_key_ref.as_ref()
165 }
166
167 pub fn federation_egress_enabled(&self) -> bool {
169 self.federation_egress_enabled
170 }
171
172 pub fn max_body_bytes(&self) -> u32 {
174 self.max_body_bytes
175 }
176
177 pub fn max_outstanding_challenges(&self) -> u32 {
179 self.max_outstanding_challenges
180 }
181
182 pub fn max_tenants(&self) -> u32 {
184 self.max_tenants
185 }
186
187 pub fn invitations_enabled(&self) -> bool {
189 self.invitations_enabled
190 }
191
192 pub fn invitation_ttl_secs(&self) -> u32 {
194 self.invitation_ttl_secs
195 }
196
197 pub fn max_pod_body_bytes(&self) -> u32 {
199 self.max_pod_body_bytes
200 }
201
202 pub fn admission_requests_per_minute(&self) -> u32 {
204 self.admission_requests_per_minute
205 }
206
207 pub fn min_pod_free_bytes(&self) -> u64 {
209 self.min_pod_free_bytes
210 }
211
212 pub fn removal_grace_days(&self) -> u32 {
232 self.removal_grace_days
233 }
234
235 pub fn removal_grace(&self) -> Duration {
253 Duration::from_secs(u64::from(self.removal_grace_days) * SECS_PER_DAY)
254 }
255
256 pub fn pod_bytes_per_tenant(&self) -> u64 {
270 self.pod_bytes_per_tenant
271 }
272
273 pub fn job_max_cpus(&self) -> u32 {
294 self.job_max_cpus
295 }
296
297 pub fn job_max_memory_bytes(&self) -> u64 {
299 self.job_max_memory_bytes
300 }
301
302 pub fn job_max_pids(&self) -> u64 {
304 self.job_max_pids
305 }
306
307 pub fn job_max_tmp_bytes(&self) -> u64 {
309 self.job_max_tmp_bytes
310 }
311
312 pub fn job_max_timeout_secs(&self) -> u64 {
314 self.job_max_timeout_secs
315 }
316
317 pub fn max_concurrent_jobs(&self) -> u32 {
321 self.max_concurrent_jobs
322 }
323
324 pub fn is_over_quota(&self, pod_bytes: u64) -> bool {
350 self.pod_bytes_per_tenant > 0 && pod_bytes > self.pod_bytes_per_tenant
351 }
352}
353
354struct Lookup<'v>(&'v [Value]);
356
357impl<'v> Lookup<'v> {
358 fn new(values: &'v [Value]) -> Option<Self> {
361 (values.len() == schema().table().len()).then_some(Self(values))
362 }
363
364 fn get(&self, path: &'static str) -> Result<&'v Value, ValidationError> {
367 let index = schema().index_of(path).ok_or_else(|| {
368 ValidationError::at(
369 ValidationErrorKind::UnknownKey,
370 path,
371 "field is not in the schema",
372 )
373 })?;
374 Ok(&self.0[index])
375 }
376
377 fn mismatch(path: &'static str, expected: &str) -> ValidationError {
378 ValidationError::at(
379 ValidationErrorKind::WrongType,
380 path,
381 format!("expected {expected}"),
382 )
383 }
384
385 fn str(&self, path: &'static str) -> Result<&'v str, ValidationError> {
386 self.get(path)?
387 .as_str()
388 .ok_or_else(|| Self::mismatch(path, "a string"))
389 }
390
391 fn list(&self, path: &'static str) -> Result<&'v [String], ValidationError> {
392 self.get(path)?
393 .as_string_list()
394 .ok_or_else(|| Self::mismatch(path, "a list of strings"))
395 }
396
397 fn bool(&self, path: &'static str) -> Result<bool, ValidationError> {
398 self.get(path)?
399 .as_bool()
400 .ok_or_else(|| Self::mismatch(path, "a boolean"))
401 }
402
403 fn u64(&self, path: &'static str) -> Result<u64, ValidationError> {
406 let i = self
407 .get(path)?
408 .as_integer()
409 .ok_or_else(|| Self::mismatch(path, "an integer"))?;
410 u64::try_from(i).map_err(|_| {
411 ValidationError::at(
412 ValidationErrorKind::OutOfRange,
413 path,
414 format!("must be between 0 and {}", i64::MAX),
415 )
416 })
417 }
418
419 fn u32(&self, path: &'static str) -> Result<u32, ValidationError> {
422 let i = self
423 .get(path)?
424 .as_integer()
425 .ok_or_else(|| Self::mismatch(path, "an integer"))?;
426 u32::try_from(i).map_err(|_| {
427 ValidationError::at(
428 ValidationErrorKind::OutOfRange,
429 path,
430 format!("must be between 0 and {}", u32::MAX),
431 )
432 })
433 }
434}
435
436#[cfg(test)]
437mod tests {
438 use super::*;
439 use crate::schema::FieldDescriptor;
440
441 fn defaults() -> Vec<Value> {
443 schema()
444 .fields()
445 .map(FieldDescriptor::default_value)
446 .collect()
447 }
448
449 fn with(path: &str, value: Value) -> Vec<Value> {
450 let mut values = defaults();
451 let i = schema().index_of(path).expect("path in schema");
452 values[i] = value;
453 values
454 }
455
456 #[test]
457 fn integer_outside_u32_is_out_of_range() {
458 for n in [-1, i64::from(u32::MAX) + 1] {
459 let values = with("limits.max_body_bytes", Value::Integer(n));
460 let e = Lookup::new(&values)
461 .expect("full value list")
462 .u32("limits.max_body_bytes")
463 .expect_err("out of range");
464 assert_eq!(e.kind(), ValidationErrorKind::OutOfRange, "{n}");
465 assert_eq!(e.message(), "must be between 0 and 4294967295", "{n}");
466 }
467 let values = with("limits.max_body_bytes", Value::Integer(4_294_967_295));
468 assert_eq!(
469 Lookup::new(&values)
470 .expect("full value list")
471 .u32("limits.max_body_bytes"),
472 Ok(u32::MAX),
473 "upper bound"
474 );
475 }
476
477 #[test]
478 fn non_integer_is_wrong_type() {
479 let values = with("limits.max_body_bytes", Value::from("many"));
480 let e = Lookup::new(&values)
481 .expect("full value list")
482 .u32("limits.max_body_bytes")
483 .expect_err("wrong type");
484 assert_eq!(e.kind(), ValidationErrorKind::WrongType, "kind");
485 assert_eq!(e.message(), "expected an integer", "message");
486 }
487
488 #[test]
489 fn unknown_path_is_unknown_key() {
490 let values = defaults();
491 let e = Lookup::new(&values)
492 .expect("full value list")
493 .get("limits.nope")
494 .expect_err("unknown");
495 assert_eq!(e.kind(), ValidationErrorKind::UnknownKey, "kind");
496 }
497
498 #[test]
499 #[should_panic(expected = "expected one value per schema field")]
500 fn short_value_list_is_a_bug_not_an_unknown_key() {
501 let mut values = defaults();
502 values.pop();
503 let _ = Config::from_values(&values);
504 }
505
506 #[test]
507 fn defaults_build_a_config() {
508 let config = Config::from_values(&defaults()).expect("defaults are valid");
509 assert_eq!(config.max_body_bytes(), 262_144, "default");
510 }
511}