Skip to main content

stratum_node_config/
config.rs

1//! Typed accessors over a validated configuration.
2
3use 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
13/// Seconds in one day, for [`Config::removal_grace`].
14const SECS_PER_DAY: u64 = 86_400;
15
16/// An opaque reference to a secret held by a custody service.
17///
18/// The reference names where a secret lives; it is not the secret, and this
19/// library never resolves it. `Debug` is redacted so the reference does not
20/// leak into logs by accident; read it explicitly with [`SecretRef::as_str`].
21#[derive(Clone, PartialEq, Eq, Hash)]
22pub struct SecretRef(String);
23
24impl SecretRef {
25    /// Returns the reference text, for handing to the custody service.
26    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/// The effective configuration of a valid document, with one strongly typed
38/// getter per schema field.
39///
40/// Obtained from [`ConfigDocument::config`](crate::ConfigDocument::config).
41/// Every value has already passed validation, so the getters cannot fail.
42///
43/// # Examples
44///
45/// ```
46/// use stratum_node_config::{schema, ConfigDocument};
47///
48/// let doc = ConfigDocument::parse(&schema().seed_text())?;
49/// let config = doc.config();
50/// assert_eq!(config.listen_address().port(), 7460);
51/// assert!(config.listen_address().ip().is_loopback());
52/// assert_eq!(config.canonical_origin(), None);
53/// assert_eq!(config.max_body_bytes(), 262_144);
54/// # Ok::<(), Box<dyn std::error::Error>>(())
55/// ```
56#[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    /// Builds the typed view from effective values in schema order, one per
86    /// schema field. Fails only if a value does not match its field, which
87    /// validation rules out.
88    ///
89    /// # Panics
90    ///
91    /// Panics if `values` does not hold exactly one value per schema field,
92    /// which is a bug in the caller.
93    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    /// Returns `node.name`.
128    pub fn node_name(&self) -> &str {
129        &self.node_name
130    }
131
132    /// Returns `node.canonical_origin`, or `None` while it is empty.
133    pub fn canonical_origin(&self) -> Option<&str> {
134        self.canonical_origin.as_deref()
135    }
136
137    /// Returns `listen.address`, which is always a loopback address.
138    pub fn listen_address(&self) -> SocketAddr {
139        self.listen_address
140    }
141
142    /// Returns `storage.state_dir`, an absolute normalised path.
143    pub fn state_dir(&self) -> &Path {
144        &self.state_dir
145    }
146
147    /// Returns `storage.backup_dir`, an absolute normalised path distinct from
148    /// and not nested with [`Config::state_dir`].
149    pub fn backup_dir(&self) -> &Path {
150        &self.backup_dir
151    }
152
153    /// Returns `backup.age_recipients`; each is a structurally valid age
154    /// post-quantum hybrid recipient beginning with `age1pq1`.
155    pub fn age_recipients(&self) -> &[String] {
156        &self.age_recipients
157    }
158
159    /// Returns `secrets.pod_admin_key_ref`, or `None` while it is empty.
160    ///
161    /// The field is reserved: a Stratum node generates its pod
162    /// administration key itself and does not read this reference.
163    pub fn pod_admin_key_ref(&self) -> Option<&SecretRef> {
164        self.pod_admin_key_ref.as_ref()
165    }
166
167    /// Returns `federation.egress_enabled`.
168    pub fn federation_egress_enabled(&self) -> bool {
169        self.federation_egress_enabled
170    }
171
172    /// Returns `limits.max_body_bytes`, in `1024..=1048576`.
173    pub fn max_body_bytes(&self) -> u32 {
174        self.max_body_bytes
175    }
176
177    /// Returns `limits.max_outstanding_challenges`, in `1..=64`.
178    pub fn max_outstanding_challenges(&self) -> u32 {
179        self.max_outstanding_challenges
180    }
181
182    /// Returns `membership.max_tenants`, in `1..=10000`.
183    pub fn max_tenants(&self) -> u32 {
184        self.max_tenants
185    }
186
187    /// Returns `membership.invitations_enabled`.
188    pub fn invitations_enabled(&self) -> bool {
189        self.invitations_enabled
190    }
191
192    /// Returns `membership.invitation_ttl_secs`, in `60..=2592000`.
193    pub fn invitation_ttl_secs(&self) -> u32 {
194        self.invitation_ttl_secs
195    }
196
197    /// Returns `limits.max_pod_body_bytes`, in `1024..=52428800`.
198    pub fn max_pod_body_bytes(&self) -> u32 {
199        self.max_pod_body_bytes
200    }
201
202    /// Returns `limits.admission_requests_per_minute`, in `1..=6000`.
203    pub fn admission_requests_per_minute(&self) -> u32 {
204        self.admission_requests_per_minute
205    }
206
207    /// Returns `limits.min_pod_free_bytes`; zero means the check is off.
208    pub fn min_pod_free_bytes(&self) -> u64 {
209        self.min_pod_free_bytes
210    }
211
212    /// Returns `membership.removal_grace_days`, in `0..=3650`.
213    ///
214    /// The node stores the earliest purge time when a member is removed or
215    /// cancelled, from the value in force then, and never allows less than
216    /// 120 seconds.
217    ///
218    /// # Examples
219    ///
220    /// ```
221    /// use stratum_node_config::{schema, ConfigDocument};
222    ///
223    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
224    /// let doc = ConfigDocument::parse(&schema().seed_text())?;
225    /// let config = doc.config();
226    /// assert_eq!(config.removal_grace_days(), 30);
227    /// assert_eq!(config.removal_grace().as_secs(), 30 * 86_400);
228    /// # Ok(())
229    /// # }
230    /// ```
231    pub fn removal_grace_days(&self) -> u32 {
232        self.removal_grace_days
233    }
234
235    /// Returns `membership.removal_grace_days` as a duration of whole days.
236    /// Zero days is a zero duration; the 120 second floor is the node's to
237    /// apply.
238    ///
239    /// # Examples
240    ///
241    /// ```
242    /// use stratum_node_config::{preview, schema, Change};
243    ///
244    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
245    /// let doc = preview(&schema().seed_text(), &[Change::new("membership.removal_grace_days", 0)])?
246    ///     .into_document()
247    ///     .ok_or("the edit is valid")?;
248    /// assert!(doc.config().removal_grace().is_zero());
249    /// # Ok(())
250    /// # }
251    /// ```
252    pub fn removal_grace(&self) -> Duration {
253        Duration::from_secs(u64::from(self.removal_grace_days) * SECS_PER_DAY)
254    }
255
256    /// Returns `limits.pod_bytes_per_tenant`; zero means no limit.
257    ///
258    /// # Examples
259    ///
260    /// ```
261    /// use stratum_node_config::{schema, ConfigDocument};
262    ///
263    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
264    /// let doc = ConfigDocument::parse(&schema().seed_text())?;
265    /// assert_eq!(doc.config().pod_bytes_per_tenant(), 10 * 1024 * 1024 * 1024);
266    /// # Ok(())
267    /// # }
268    /// ```
269    pub fn pod_bytes_per_tenant(&self) -> u64 {
270        self.pod_bytes_per_tenant
271    }
272
273    /// Returns `limits.job_max_cpus`, in whole CPUs, `1..=64`. A manifest's
274    /// `cpus` is held as millicpus, so the ceiling in millicpus is this
275    /// times 1000.
276    ///
277    /// # Examples
278    ///
279    /// ```
280    /// use stratum_node_config::{schema, ConfigDocument};
281    ///
282    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
283    /// let config = ConfigDocument::parse(&schema().seed_text())?.config().clone();
284    /// assert_eq!(config.job_max_cpus(), 4);
285    /// assert_eq!(config.job_max_memory_bytes(), 4 * 1024 * 1024 * 1024);
286    /// assert_eq!(config.job_max_pids(), 512);
287    /// assert_eq!(config.job_max_tmp_bytes(), 1024 * 1024 * 1024);
288    /// assert_eq!(config.job_max_timeout_secs(), 3600);
289    /// assert_eq!(config.max_concurrent_jobs(), 4);
290    /// # Ok(())
291    /// # }
292    /// ```
293    pub fn job_max_cpus(&self) -> u32 {
294        self.job_max_cpus
295    }
296
297    /// Returns `limits.job_max_memory_bytes`, in bytes.
298    pub fn job_max_memory_bytes(&self) -> u64 {
299        self.job_max_memory_bytes
300    }
301
302    /// Returns `limits.job_max_pids`, `1..=65536`.
303    pub fn job_max_pids(&self) -> u64 {
304        self.job_max_pids
305    }
306
307    /// Returns `limits.job_max_tmp_bytes`, in bytes.
308    pub fn job_max_tmp_bytes(&self) -> u64 {
309        self.job_max_tmp_bytes
310    }
311
312    /// Returns `limits.job_max_timeout_secs`, `240..=43200`.
313    pub fn job_max_timeout_secs(&self) -> u64 {
314        self.job_max_timeout_secs
315    }
316
317    /// Returns `runner.max_concurrent_jobs`, `1..=256`: the most job
318    /// containers the controller lets run at once, counted as current
319    /// leases at claim.
320    pub fn max_concurrent_jobs(&self) -> u32 {
321        self.max_concurrent_jobs
322    }
323
324    /// Returns `true` when a pod of `pod_bytes` bytes is over quota: the
325    /// limit is above zero and `pod_bytes` is strictly above it.
326    ///
327    /// This is the one definition of "over quota"; the controller decides
328    /// the flag it publishes with it.
329    ///
330    /// # Examples
331    ///
332    /// ```
333    /// use stratum_node_config::{preview, schema, Change};
334    ///
335    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
336    /// let limited = preview(&schema().seed_text(), &[Change::new("limits.pod_bytes_per_tenant", 100)])?
337    ///     .into_document()
338    ///     .ok_or("the edit is valid")?;
339    /// assert!(!limited.config().is_over_quota(100));
340    /// assert!(limited.config().is_over_quota(101));
341    ///
342    /// let unlimited = preview(&schema().seed_text(), &[Change::new("limits.pod_bytes_per_tenant", 0)])?
343    ///     .into_document()
344    ///     .ok_or("the edit is valid")?;
345    /// assert!(!unlimited.config().is_over_quota(u64::MAX));
346    /// # Ok(())
347    /// # }
348    /// ```
349    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
354/// Typed lookup of effective values by schema path.
355struct Lookup<'v>(&'v [Value]);
356
357impl<'v> Lookup<'v> {
358    /// Wraps `values`, or returns `None` unless it holds exactly one value
359    /// per schema field.
360    fn new(values: &'v [Value]) -> Option<Self> {
361        (values.len() == schema().table().len()).then_some(Self(values))
362    }
363
364    /// Looks up `path`. Only an unknown path fails: [`Lookup::new`] checked
365    /// that every schema field has a value.
366    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    /// A non-integer is [`ValidationErrorKind::WrongType`]; a negative
404    /// integer is [`ValidationErrorKind::OutOfRange`].
405    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    /// A non-integer is [`ValidationErrorKind::WrongType`]; an integer
420    /// outside `u32` is [`ValidationErrorKind::OutOfRange`].
421    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    /// The effective values of the default configuration, in schema order.
442    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}