Skip to main content

stratum_node_config/
schema.rs

1//! The schema table: the single source of every field's type, default,
2//! description and apply class.
3
4use std::fmt;
5use std::iter::FusedIterator;
6
7use serde::ser::{Serialize, SerializeStruct, Serializer};
8
9use crate::error::{ValidationError, ValidationErrorKind};
10use crate::rules;
11use crate::value::Value;
12
13/// The version of the `stratum.toml` schema this library implements.
14///
15/// A document must carry `schema_version = 1`; any other value is rejected.
16pub const SCHEMA_VERSION: u32 = 1;
17
18/// The largest number of entries `backup.age_recipients` may hold.
19///
20/// A Stratum node encrypts its keystore to every listed recipient in each
21/// backup and refuses to write a backup to more than 32 of them, so a longer
22/// list is rejected here, when the configuration is validated, rather than
23/// at backup time. The field's [`FieldDescriptor::description`] states the
24/// same limit.
25///
26/// # Examples
27///
28/// ```
29/// use stratum_node_config::{schema, Value, MAX_BACKUP_RECIPIENTS};
30///
31/// let field = schema().field("backup.age_recipients").expect("field exists");
32/// let too_many = vec!["age1pq1…".to_owned(); MAX_BACKUP_RECIPIENTS + 1];
33/// let err = field.validate(&Value::from(too_many)).unwrap_err();
34/// assert_eq!(err.message(), "must hold at most 32 recipients, found 33");
35/// ```
36pub const MAX_BACKUP_RECIPIENTS: usize = 32;
37
38/// When a changed field takes effect.
39///
40/// The variants are ordered from least to most disruptive, so the strictest
41/// class of a set of changes is their maximum.
42///
43/// # Examples
44///
45/// ```
46/// use stratum_node_config::ApplyClass;
47///
48/// let classes = [ApplyClass::Live, ApplyClass::Redeploy, ApplyClass::Restart];
49/// assert_eq!(classes.into_iter().max(), Some(ApplyClass::Redeploy));
50/// assert_eq!(ApplyClass::Restart.to_string(), "restart");
51/// ```
52#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize)]
53#[serde(rename_all = "lowercase")]
54#[non_exhaustive]
55pub enum ApplyClass {
56    /// Takes effect in the running node without a restart.
57    Live,
58    /// Takes effect when the controller process restarts.
59    Restart,
60    /// Takes effect only after the deployment around the node is rebuilt,
61    /// for example the tunnel or the public origin.
62    Redeploy,
63}
64
65impl ApplyClass {
66    /// Returns the lowercase name: `live`, `restart` or `redeploy`.
67    pub fn as_str(self) -> &'static str {
68        match self {
69            Self::Live => "live",
70            Self::Restart => "restart",
71            Self::Redeploy => "redeploy",
72        }
73    }
74}
75
76impl fmt::Display for ApplyClass {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        f.write_str(self.as_str())
79    }
80}
81
82/// The type of a schema field, including any range or variant set.
83///
84/// Serialises with a `kind` tag, for example
85/// `{"kind": "integer", "min": 1, "max": 64}`.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
87#[serde(tag = "kind", rename_all = "snake_case")]
88#[non_exhaustive]
89pub enum ValueType {
90    /// A UTF-8 string.
91    String,
92    /// An integer in `min..=max`.
93    Integer {
94        /// The smallest accepted value.
95        min: i64,
96        /// The largest accepted value.
97        max: i64,
98    },
99    /// A boolean.
100    Boolean,
101    /// A string that must be one of a fixed set.
102    Enum {
103        /// The accepted strings.
104        variants: &'static [&'static str],
105    },
106    /// A list of strings.
107    StringList,
108    /// An opaque reference to a secret held by a custody service.
109    ///
110    /// This library never resolves it. Secret-reference fields are excluded
111    /// from the [`PublicConfig`](crate::PublicConfig) and its hash, and their
112    /// values are redacted in change lists.
113    SecretRef,
114}
115
116impl ValueType {
117    fn name(self) -> &'static str {
118        match self {
119            Self::String | Self::Enum { .. } | Self::SecretRef => "a string",
120            Self::Integer { .. } => "an integer",
121            Self::Boolean => "a boolean",
122            Self::StringList => "a list of strings",
123        }
124    }
125
126    /// Checks that `value` has this type and lies within its range or set.
127    fn check(self, value: &Value) -> Result<(), (ValidationErrorKind, String)> {
128        let found = value.kind_name();
129        let wrong = || {
130            (
131                ValidationErrorKind::WrongType,
132                format!("expected {}, found {found}", self.name()),
133            )
134        };
135        match (self, value) {
136            (Self::String | Self::SecretRef, Value::String(_))
137            | (Self::Boolean, Value::Boolean(_))
138            | (Self::StringList, Value::StringList(_)) => Ok(()),
139            (Self::Integer { min, max }, Value::Integer(i)) => {
140                if (min..=max).contains(i) {
141                    Ok(())
142                } else {
143                    Err((
144                        ValidationErrorKind::OutOfRange,
145                        format!("must be between {min} and {max}"),
146                    ))
147                }
148            }
149            (Self::Enum { variants }, Value::String(s)) => {
150                if variants.contains(&s.as_str()) {
151                    Ok(())
152                } else {
153                    let list: Vec<String> = variants.iter().map(|v| format!("\"{v}\"")).collect();
154                    Err((
155                        ValidationErrorKind::InvalidValue,
156                        format!("must be one of {}", list.join(", ")),
157                    ))
158                }
159            }
160            _ => Err(wrong()),
161        }
162    }
163}
164
165/// A default as it can be written in a `static` table.
166#[derive(Debug, Clone, Copy)]
167enum StaticDefault {
168    Str(&'static str),
169    Int(i64),
170    Bool(bool),
171    List(&'static [&'static str]),
172}
173
174impl StaticDefault {
175    fn to_value(self) -> Value {
176        match self {
177            Self::Str(s) => Value::from(s),
178            Self::Int(i) => Value::Integer(i),
179            Self::Bool(b) => Value::Boolean(b),
180            Self::List(l) => Value::from(l),
181        }
182    }
183}
184
185/// A field-specific rule applied after the type check.
186type Rule = fn(&Value) -> Result<(), String>;
187
188/// One field of the schema: its path, type, default, description and apply
189/// class.
190///
191/// Descriptors are obtained from [`Schema::fields`] or [`Schema::field`]; they
192/// cannot be constructed outside this crate.
193///
194/// # Examples
195///
196/// ```
197/// use stratum_node_config::{schema, ApplyClass, Value};
198///
199/// let field = schema().field("limits.max_body_bytes").ok_or("missing field")?;
200/// assert_eq!(field.apply_class(), ApplyClass::Restart);
201/// assert_eq!(field.default_value(), Value::Integer(262_144));
202/// assert!(field.validate(&Value::Integer(10)).is_err());
203/// # Ok::<(), Box<dyn std::error::Error>>(())
204/// ```
205pub struct FieldDescriptor {
206    path: &'static str,
207    value_type: ValueType,
208    default: StaticDefault,
209    description: &'static str,
210    apply_class: ApplyClass,
211    rule: Option<Rule>,
212}
213
214impl FieldDescriptor {
215    /// Returns the dotted path, such as `listen.address`.
216    pub fn path(&self) -> &'static str {
217        self.path
218    }
219
220    /// Returns the table the field lives in: the part of the path before the
221    /// first dot.
222    pub fn section(&self) -> &'static str {
223        self.split().0
224    }
225
226    /// Returns the key within its table: the part of the path after the
227    /// first dot.
228    pub fn key(&self) -> &'static str {
229        self.split().1
230    }
231
232    fn split(&self) -> (&'static str, &'static str) {
233        self.path.split_once('.').unwrap_or((self.path, ""))
234    }
235
236    /// Returns the field's type.
237    pub fn value_type(&self) -> ValueType {
238        self.value_type
239    }
240
241    /// Returns the value the field takes when a document omits it.
242    pub fn default_value(&self) -> Value {
243        self.default.to_value()
244    }
245
246    /// Returns the one-paragraph, plain-text description.
247    pub fn description(&self) -> &'static str {
248        self.description
249    }
250
251    /// Returns when a change to this field takes effect.
252    pub fn apply_class(&self) -> ApplyClass {
253        self.apply_class
254    }
255
256    /// Returns `true` if the field holds a secret reference.
257    pub fn is_secret_ref(&self) -> bool {
258        matches!(self.value_type, ValueType::SecretRef)
259    }
260
261    /// Checks `value` against this field's type, range and rule.
262    ///
263    /// Cross-field rules, such as the state and backup directories having to
264    /// differ, are only checked by [`ConfigDocument::parse`](crate::ConfigDocument::parse).
265    ///
266    /// # Errors
267    ///
268    /// Returns a [`ValidationError`] at this field's path when the value has
269    /// the wrong type, is out of range, or breaks the field's rule.
270    pub fn validate(&self, value: &Value) -> Result<(), ValidationError> {
271        self.value_type
272            .check(value)
273            .map_err(|(kind, msg)| ValidationError::at(kind, self.path, msg))?;
274        match self.rule {
275            Some(rule) => rule(value).map_err(|msg| {
276                ValidationError::at(ValidationErrorKind::InvalidValue, self.path, msg)
277            }),
278            None => Ok(()),
279        }
280    }
281}
282
283/// Shows the path, type, default and apply class; the description and rule
284/// are elided.
285impl fmt::Debug for FieldDescriptor {
286    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287        f.debug_struct("FieldDescriptor")
288            .field("path", &self.path)
289            .field("value_type", &self.value_type)
290            .field("default", &self.default_value())
291            .field("apply_class", &self.apply_class)
292            .finish_non_exhaustive()
293    }
294}
295
296impl Serialize for FieldDescriptor {
297    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
298        let mut s = serializer.serialize_struct("FieldDescriptor", 5)?;
299        s.serialize_field("path", self.path)?;
300        s.serialize_field("type", &self.value_type)?;
301        s.serialize_field("default", &self.default_value())?;
302        s.serialize_field("description", self.description)?;
303        s.serialize_field("apply_class", &self.apply_class)?;
304        s.end()
305    }
306}
307
308/// The complete `stratum.toml` schema.
309///
310/// There is one schema per library version; obtain it with [`schema`]. It
311/// serialises as `{"schema_version": 1, "fields": [...]}` for the HTTP schema
312/// endpoint, and every other part of this crate (validation, the seed
313/// document, the public view) is derived from the same table.
314///
315/// # Examples
316///
317/// ```
318/// use stratum_node_config::schema;
319///
320/// for field in schema().fields() {
321///     println!("{} ({}): {}", field.path(), field.apply_class(), field.description());
322/// }
323/// assert!(schema().field("listen.address").is_some());
324/// ```
325pub struct Schema {
326    fields: &'static [FieldDescriptor],
327}
328
329impl Schema {
330    /// Returns [`SCHEMA_VERSION`].
331    pub fn version(&self) -> u32 {
332        SCHEMA_VERSION
333    }
334
335    /// Iterates over every field in schema order.
336    pub fn fields(&self) -> Fields {
337        Fields {
338            inner: self.fields.iter(),
339        }
340    }
341
342    /// Looks a field up by its dotted path.
343    pub fn field(&self, path: &str) -> Option<&'static FieldDescriptor> {
344        self.fields.iter().find(|f| f.path == path)
345    }
346
347    /// Returns the schema-order index of a field.
348    pub(crate) fn index_of(&self, path: &str) -> Option<usize> {
349        self.fields.iter().position(|f| f.path == path)
350    }
351
352    /// Returns the schema's field table.
353    pub(crate) fn table(&self) -> &'static [FieldDescriptor] {
354        self.fields
355    }
356
357    /// Iterates over the section names in order of first appearance.
358    pub(crate) fn sections(&self) -> impl Iterator<Item = &'static str> {
359        let fields = self.fields;
360        fields
361            .iter()
362            .enumerate()
363            .filter(move |(i, f)| !fields[..*i].iter().any(|g| g.section() == f.section()))
364            .map(|(_, f)| f.section())
365    }
366}
367
368/// Shows the version and the field paths.
369impl fmt::Debug for Schema {
370    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371        let paths: Vec<&str> = self.fields.iter().map(|d| d.path).collect();
372        f.debug_struct("Schema")
373            .field("version", &SCHEMA_VERSION)
374            .field("fields", &paths)
375            .finish()
376    }
377}
378
379impl Serialize for Schema {
380    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
381        let mut s = serializer.serialize_struct("Schema", 2)?;
382        s.serialize_field("schema_version", &SCHEMA_VERSION)?;
383        s.serialize_field("fields", self.fields)?;
384        s.end()
385    }
386}
387
388/// Iterator over the schema's [`FieldDescriptor`]s, returned by
389/// [`Schema::fields`].
390#[derive(Debug, Clone)]
391pub struct Fields {
392    inner: std::slice::Iter<'static, FieldDescriptor>,
393}
394
395impl Iterator for Fields {
396    type Item = &'static FieldDescriptor;
397
398    fn next(&mut self) -> Option<Self::Item> {
399        self.inner.next()
400    }
401
402    fn size_hint(&self) -> (usize, Option<usize>) {
403        self.inner.size_hint()
404    }
405}
406
407impl DoubleEndedIterator for Fields {
408    fn next_back(&mut self) -> Option<Self::Item> {
409        self.inner.next_back()
410    }
411}
412
413impl ExactSizeIterator for Fields {}
414
415impl FusedIterator for Fields {}
416
417/// Returns the `stratum.toml` schema.
418pub fn schema() -> &'static Schema {
419    &SCHEMA
420}
421
422static SCHEMA: Schema = Schema { fields: FIELDS };
423
424static FIELDS: &[FieldDescriptor] = &[
425    FieldDescriptor {
426        path: "node.name",
427        value_type: ValueType::String,
428        default: StaticDefault::Str("stratum"),
429        description: "Human-readable name of this node, shown on the setup page, in \
430            status output and to members. It is a label only and carries no authority. \
431            It must be 1 to 64 characters with no control characters.",
432        apply_class: ApplyClass::Live,
433        rule: Some(rules::node_name),
434    },
435    FieldDescriptor {
436        path: "node.canonical_origin",
437        value_type: ValueType::String,
438        default: StaticDefault::Str(""),
439        description: "Public HTTPS origin the node is reached at, such as \
440            https://pod.example.org. Leave it empty until the public origin is set up. \
441            When set it must be an https:// origin with a lowercase host, an optional \
442            non-default port, and no path, query, fragment or trailing slash. An IPv6 host \
443            is written in brackets in its canonical RFC 5952 form, such as [2001:db8::1].",
444        apply_class: ApplyClass::Redeploy,
445        rule: Some(rules::canonical_origin),
446    },
447    FieldDescriptor {
448        path: "listen.address",
449        value_type: ValueType::String,
450        default: StaticDefault::Str("127.0.0.1:7460"),
451        description: "Socket address the controller's administrative API and setup page \
452            listen on, written as ip:port. The IP must be a loopback address \
453            (127.0.0.0/8 or [::1]); the API is never exposed on another interface.",
454        apply_class: ApplyClass::Restart,
455        rule: Some(rules::loopback_socket_address),
456    },
457    FieldDescriptor {
458        path: "storage.state_dir",
459        value_type: ValueType::String,
460        default: StaticDefault::Str("/var/lib/stratum/state"),
461        description: "Directory holding the node's store, keystore and bootstrap token. \
462            It must be an absolute, normalised POSIX path (starting with /, no trailing \
463            slash, no empty, . or .. components) and must neither equal, contain nor lie \
464            inside storage.backup_dir. The running state directory is given on the \
465            daemon's command line, not read from this field.",
466        apply_class: ApplyClass::Restart,
467        rule: Some(rules::absolute_path),
468    },
469    FieldDescriptor {
470        path: "storage.backup_dir",
471        value_type: ValueType::String,
472        default: StaticDefault::Str("/var/lib/stratum/backups"),
473        description: "Directory backups are written into, one subdirectory per backup. \
474            It must be an absolute, normalised POSIX path and must neither equal, contain \
475            nor lie inside storage.state_dir.",
476        apply_class: ApplyClass::Restart,
477        rule: Some(rules::absolute_path),
478    },
479    FieldDescriptor {
480        path: "backup.age_recipients",
481        value_type: ValueType::StringList,
482        default: StaticDefault::List(&[]),
483        description: "age public keys the keystore is encrypted to in each backup. Every \
484            entry must be a post-quantum hybrid age recipient (ML-KEM-768 with X25519, as \
485            written by age 0.13 and later), a lowercase Bech32 string beginning with age1pq1; \
486            classical age1 recipients are refused. The list holds at most 32 entries. While \
487            the list is empty, backups are refused.",
488        apply_class: ApplyClass::Live,
489        rule: Some(rules::age_recipients),
490    },
491    FieldDescriptor {
492        path: "secrets.pod_admin_key_ref",
493        value_type: ValueType::SecretRef,
494        default: StaticDefault::Str(""),
495        description: "Reserved and not read: the node generates the pod administration \
496            key itself. The field is kept so that existing documents stay valid. Like every \
497            secret reference it is left out of the public configuration and its hash and is \
498            redacted in change lists. It must not contain whitespace or control characters.",
499        apply_class: ApplyClass::Restart,
500        rule: Some(rules::secret_ref),
501    },
502    FieldDescriptor {
503        path: "federation.egress_enabled",
504        value_type: ValueType::Boolean,
505        default: StaticDefault::Bool(false),
506        description: "Whether the node may open outbound federation connections to other \
507            nodes. Off by default.",
508        apply_class: ApplyClass::Live,
509        rule: None,
510    },
511    FieldDescriptor {
512        path: "membership.max_tenants",
513        value_type: ValueType::Integer {
514            min: 1,
515            max: 10_000,
516        },
517        default: StaticDefault::Int(8),
518        description: "Largest number of tenants the node admits. Members that are \
519            reserved, provisioned, active or suspended count against it; a cancelled or \
520            removed member does not. \
521            A redemption that would exceed it is refused and its invitation stays issued. \
522            Lowering it below the current count admits nobody new and removes nobody.",
523        apply_class: ApplyClass::Live,
524        rule: None,
525    },
526    FieldDescriptor {
527        path: "membership.invitations_enabled",
528        value_type: ValueType::Boolean,
529        default: StaticDefault::Bool(true),
530        description: "Whether the administrator may issue invitations and invitees may \
531            redeem them. Turning it off refuses both; existing members keep working.",
532        apply_class: ApplyClass::Live,
533        rule: None,
534    },
535    FieldDescriptor {
536        path: "membership.invitation_ttl_secs",
537        value_type: ValueType::Integer {
538            min: 60,
539            max: 2_592_000,
540        },
541        default: StaticDefault::Int(604_800),
542        description: "Lifetime, in seconds, of an invitation issued without an explicit \
543            expiry: 604800 is seven days. At least 60 and at most 2592000 (30 days).",
544        apply_class: ApplyClass::Live,
545        rule: None,
546    },
547    FieldDescriptor {
548        path: "membership.removal_grace_days",
549        value_type: ValueType::Integer { min: 0, max: 3650 },
550        default: StaticDefault::Int(30),
551        description: "Days after a member is removed or cancelled before `stratumd purge` may \
552            delete their pod data. The grace is fixed when the member is removed or \
553            cancelled, from the value configured then, so changing it later does not \
554            shorten a grace already given. Zero is allowed; the node never allows less \
555            than 120 seconds. Purge is always an explicit offline command: nothing deletes \
556            pod data when the grace ends. At most 3650.",
557        apply_class: ApplyClass::Live,
558        rule: None,
559    },
560    FieldDescriptor {
561        path: "limits.max_body_bytes",
562        value_type: ValueType::Integer {
563            min: 1024,
564            max: 1_048_576,
565        },
566        default: StaticDefault::Int(262_144),
567        description: "Largest request body, in bytes, the administrative API accepts. \
568            Larger requests are refused before they are read in full.",
569        apply_class: ApplyClass::Restart,
570        rule: None,
571    },
572    FieldDescriptor {
573        path: "limits.max_outstanding_challenges",
574        value_type: ValueType::Integer { min: 1, max: 64 },
575        default: StaticDefault::Int(16),
576        description: "Largest number of unexpired bootstrap challenges held at once. A \
577            request for a new challenge beyond this limit is refused.",
578        apply_class: ApplyClass::Live,
579        rule: None,
580    },
581    FieldDescriptor {
582        path: "limits.max_pod_body_bytes",
583        value_type: ValueType::Integer {
584            min: 1024,
585            max: 52_428_800,
586        },
587        default: StaticDefault::Int(16_777_216),
588        description: "Largest request body, in bytes, the gate accepts on a pod route: \
589            16777216 is 16 MiB. A larger body is refused with 413 before it is forwarded. \
590            At least 1024 and at most 52428800 (50 MiB), the largest body the pod server \
591            itself accepts.",
592        apply_class: ApplyClass::Live,
593        rule: None,
594    },
595    FieldDescriptor {
596        path: "limits.admission_requests_per_minute",
597        value_type: ValueType::Integer { min: 1, max: 6000 },
598        default: StaticDefault::Int(30),
599        description: "Largest number of redemption requests the gate passes to the node \
600            per minute. Requests over the limit are refused with 429 and a Retry-After \
601            header.",
602        apply_class: ApplyClass::Live,
603        rule: None,
604    },
605    FieldDescriptor {
606        path: "limits.min_pod_free_bytes",
607        value_type: ValueType::Integer {
608            min: 0,
609            max: i64::MAX,
610        },
611        default: StaticDefault::Int(1_073_741_824),
612        description: "Free space, in bytes, below which the pod volume counts as low: \
613            1073741824 is 1 GiB. While it is low the gate refuses every pod write with 507 \
614            and reads continue. Zero turns the check off.",
615        apply_class: ApplyClass::Live,
616        rule: None,
617    },
618    FieldDescriptor {
619        path: "limits.pod_bytes_per_tenant",
620        value_type: ValueType::Integer {
621            min: 0,
622            max: i64::MAX,
623        },
624        default: StaticDefault::Int(10_737_418_240),
625        description: "Size limit, in bytes, of each tenant's pod: 10737418240 is 10 GiB. \
626            The node measures every pod periodically; a pod whose files total strictly \
627            more than this is over quota, and the gate then refuses PUT to it with 507 \
628            while GET, HEAD and DELETE continue. The limit is soft: writes that land \
629            between two measurements can overshoot it. Zero means no limit.",
630        apply_class: ApplyClass::Live,
631        rule: None,
632    },
633    FieldDescriptor {
634        path: "limits.job_max_cpus",
635        value_type: ValueType::Integer { min: 1, max: 64 },
636        default: StaticDefault::Int(4),
637        description: "Ceiling on the CPUs an application's job may ask for, in whole CPUs. \
638            Approving a manifest whose cpus is above it is refused, and so is launching a job \
639            if the ceiling was lowered since. At least 1 and at most 64.",
640        apply_class: ApplyClass::Live,
641        rule: None,
642    },
643    FieldDescriptor {
644        path: "limits.job_max_memory_bytes",
645        value_type: ValueType::Integer {
646            min: 1_048_576,
647            max: 1_099_511_627_776,
648        },
649        default: StaticDefault::Int(4_294_967_296),
650        description: "Ceiling on a job's memory, in bytes: 4294967296 is 4 GiB. Swap is \
651            set equal to it, so a job never swaps. Approval and launch refuse a manifest \
652            above it. At least 1048576 (1 MiB) and at most 1099511627776 (1 TiB).",
653        apply_class: ApplyClass::Live,
654        rule: None,
655    },
656    FieldDescriptor {
657        path: "limits.job_max_pids",
658        value_type: ValueType::Integer {
659            min: 1,
660            max: 65_536,
661        },
662        default: StaticDefault::Int(512),
663        description: "Ceiling on the number of processes a job may run at once. Approval \
664            and launch refuse a manifest above it. At least 1 and at most 65536.",
665        apply_class: ApplyClass::Live,
666        rule: None,
667    },
668    FieldDescriptor {
669        path: "limits.job_max_tmp_bytes",
670        value_type: ValueType::Integer {
671            min: 1_048_576,
672            max: 1_099_511_627_776,
673        },
674        default: StaticDefault::Int(1_073_741_824),
675        description: "Ceiling on the size of a job's /tmp scratch space, in bytes: \
676            1073741824 is 1 GiB. Scratch pages are charged to the job's memory, so a \
677            manifest's tmp_bytes must also be below its memory_bytes. At least 1048576 \
678            (1 MiB) and at most 1099511627776 (1 TiB).",
679        apply_class: ApplyClass::Live,
680        rule: None,
681    },
682    FieldDescriptor {
683        path: "limits.job_max_timeout_secs",
684        value_type: ValueType::Integer {
685            min: 240,
686            max: 43_200,
687        },
688        default: StaticDefault::Int(3_600),
689        description: "Ceiling on a job attempt's timeout, in seconds. The attempt's \
690            deadline is its claim time plus the timeout, and the signer opens a signing \
691            window until that deadline. At least 240, the shortest timeout a manifest may \
692            ask for, and at most 43200 (12 hours), well inside the one day the signer \
693            allows a window.",
694        apply_class: ApplyClass::Live,
695        rule: None,
696    },
697    FieldDescriptor {
698        path: "runner.max_concurrent_jobs",
699        value_type: ValueType::Integer { min: 1, max: 256 },
700        default: StaticDefault::Int(4),
701        description: "Largest number of job containers the node runs at once, across \
702            every member. A job beyond it stays pending until a running one ends. Lowering \
703            it stops no running job. At least 1 and at most 256.",
704        apply_class: ApplyClass::Live,
705        rule: None,
706    },
707];
708
709#[cfg(test)]
710mod tests {
711    use super::*;
712
713    static COLOURS: FieldDescriptor = FieldDescriptor {
714        path: "test.colour",
715        value_type: ValueType::Enum {
716            variants: &["red", "green"],
717        },
718        default: StaticDefault::Str("red"),
719        description: "Test-only enum field.",
720        apply_class: ApplyClass::Live,
721        rule: None,
722    };
723
724    #[test]
725    fn enum_type_accepts_listed_variants_only() {
726        assert!(
727            COLOURS.validate(&Value::from("green")).is_ok(),
728            "listed variant"
729        );
730        let err = COLOURS
731            .validate(&Value::from("blue"))
732            .expect_err("unlisted variant must fail");
733        assert_eq!(err.kind(), ValidationErrorKind::InvalidValue, "kind");
734        assert_eq!(err.message(), r#"must be one of "red", "green""#, "message");
735        let err = COLOURS
736            .validate(&Value::Integer(1))
737            .expect_err("integer must fail");
738        assert_eq!(err.kind(), ValidationErrorKind::WrongType, "kind");
739        assert_eq!(err.path(), Some("test.colour"), "path");
740    }
741
742    #[test]
743    fn sections_are_unique_and_in_order() {
744        let sections: Vec<&str> = schema().sections().collect();
745        assert_eq!(
746            sections,
747            [
748                "node",
749                "listen",
750                "storage",
751                "backup",
752                "secrets",
753                "federation",
754                "membership",
755                "limits",
756                "runner"
757            ],
758            "section order"
759        );
760    }
761}