Skip to main content

modem_device/
config.rs

1//! The configuration plane's vocabulary (#125).
2//!
3//! What a device declares about its own configuration, in this crate's own
4//! words: it links no zenkey, and the management plane converts these to the
5//! convention's types (zenkey RFC 05 §5.1) in `modem-contract`. The shape is
6//! the convention's, so the conversion is a rename — and the one thing the
7//! convention leaves to the producer, where a value came from, is a fact the
8//! driver knows from the startup file and the device does not, which is what
9//! [`ParamSpec::file_key`] is for.
10//!
11//! The read side first (#125): nothing is written until it can be read back.
12//! `apply` (#126) has a default that refuses, so a device declares its schema
13//! before it can act on it and says so honestly.
14
15use std::collections::BTreeMap;
16use std::fmt;
17
18/// What values a parameter accepts (#125).
19///
20/// Three kinds, and no more until something acts on a fourth: every radio or
21/// interface parameter met so far is a switch, a bounded integer in a stated
22/// unit, or text. **No float**: a value that needs one is an integer in a
23/// finer unit — `fake-medium`'s duty budget is a fraction and is exposed in
24/// ppm — which also keeps equality exact.
25#[derive(Clone, Debug, PartialEq, Eq)]
26#[non_exhaustive]
27pub enum ParamKind {
28    /// `true` or `false`.
29    Bool,
30    /// A whole number, optionally bounded, in a stated unit.
31    Integer {
32        /// Smallest accepted value, inclusive.
33        min: Option<i64>,
34        /// Largest accepted value, inclusive.
35        max: Option<i64>,
36        /// What one unit is — `"s"`, `"bit/s"`, `"ppm"`. `None` for a count.
37        unit: Option<&'static str>,
38    },
39    /// Free text.
40    Text,
41}
42
43impl ParamKind {
44    /// A bounded integer in a unit.
45    #[must_use]
46    pub const fn integer(min: Option<i64>, max: Option<i64>, unit: Option<&'static str>) -> Self {
47        Self::Integer { min, max, unit }
48    }
49}
50
51/// Whether a group may change under a running driver (#125, report §4.9).
52///
53/// **The class belongs to the device, not the name**: an MTU is `Contract`
54/// on an SDU medium whose transport was sized against it and `Hot` on a
55/// netdev whose TCP link adapts.
56#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
57#[non_exhaustive]
58pub enum ParamClass {
59    /// Takes effect at once; the reply to a change is the read-back.
60    Hot,
61    /// Decides whether the device can reach the bus at all — a frequency, an
62    /// APN. Changed only as a confirmed change (#127), because the read-back
63    /// would cross the link being changed.
64    Reach,
65    /// Part of what the transport was started against. Refused at runtime
66    /// with the restart named; changed in the startup configuration.
67    Contract,
68}
69
70/// One parameter a device declares (#125).
71#[derive(Clone, Debug, PartialEq, Eq)]
72#[non_exhaustive]
73pub struct ParamSpec {
74    /// The name a change addresses, unique within its group — and the key
75    /// the startup TOML spells it under, so a bound is written once.
76    pub name: &'static str,
77    /// What values it accepts.
78    pub kind: ParamKind,
79    /// Write-only: never read back, published, logged or evented. A PIN, a
80    /// key. It appears in the schema and never with a value.
81    pub sensitive: bool,
82    /// One line for the operator reading the schema cold.
83    pub description: &'static str,
84    /// The key the startup file spells it under, when that is not `name`:
85    /// a dotted path into the device's section (`duty_budget.fraction`).
86    /// The driver reads the file and the device never sees it; this is
87    /// how the read-back says a value came from the file (#125).
88    pub file_key: Option<&'static str>,
89}
90
91impl ParamSpec {
92    /// A parameter of the given kind.
93    #[must_use]
94    pub const fn new(name: &'static str, kind: ParamKind, description: &'static str) -> Self {
95        Self {
96            name,
97            kind,
98            sensitive: false,
99            description,
100            file_key: None,
101        }
102    }
103
104    /// Mark the parameter write-only.
105    #[must_use]
106    pub const fn sensitive(mut self) -> Self {
107        self.sensitive = true;
108        self
109    }
110
111    /// The startup file's key for it, when that is not the name.
112    #[must_use]
113    pub const fn file_key(mut self, key: &'static str) -> Self {
114        self.file_key = Some(key);
115        self
116    }
117
118    /// The startup file's key for it.
119    #[must_use]
120    pub fn key_in_file(&self) -> &str {
121        self.file_key.unwrap_or(self.name)
122    }
123
124    /// Whether `value` is one this parameter accepts: the kind, and the
125    /// bounds — with the bound named.
126    pub fn check(&self, value: &ConfigValue) -> Result<(), String> {
127        match (&self.kind, value) {
128            (ParamKind::Bool, ConfigValue::Bool(_)) | (ParamKind::Text, ConfigValue::Text(_)) => {
129                Ok(())
130            }
131            (ParamKind::Integer { min, max, unit }, ConfigValue::Integer(v)) => {
132                let unit = unit.map_or(String::new(), |u| format!(" {u}"));
133                if let Some(min) = min
134                    && v < min
135                {
136                    return Err(format!("{v}{unit} is below the minimum of {min}{unit}"));
137                }
138                if let Some(max) = max
139                    && v > max
140                {
141                    return Err(format!("{v}{unit} is above the maximum of {max}{unit}"));
142                }
143                Ok(())
144            }
145            (kind, value) => Err(format!(
146                "expected {}, got {value}",
147                match kind {
148                    ParamKind::Bool => "a boolean",
149                    ParamKind::Integer { .. } => "an integer",
150                    ParamKind::Text => "text",
151                }
152            )),
153        }
154    }
155}
156
157/// Parameters that change together (#125): the unit a change addresses and
158/// the unit that has a class. Coupled parameters share a group because a
159/// single-parameter intermediate state can be unsafe — a frequency without
160/// its bandwidth, a spreading factor without its coding rate.
161#[derive(Clone, Debug, PartialEq, Eq)]
162#[non_exhaustive]
163pub struct ConfigGroup {
164    /// The group's name, a plain chunk: it is spelled in the write key.
165    pub name: &'static str,
166    /// Whether it may change under a running driver.
167    pub class: ParamClass,
168    /// One line for the operator.
169    pub description: &'static str,
170    /// The parameters, in the order the device lists them.
171    pub parameters: Vec<ParamSpec>,
172}
173
174impl ConfigGroup {
175    /// A group with its class; parameters are added with [`with`](Self::with).
176    #[must_use]
177    pub const fn new(name: &'static str, class: ParamClass, description: &'static str) -> Self {
178        Self {
179            name,
180            class,
181            description,
182            parameters: Vec::new(),
183        }
184    }
185
186    /// Builder form of pushing a parameter.
187    #[must_use]
188    pub fn with(mut self, spec: ParamSpec) -> Self {
189        self.parameters.push(spec);
190        self
191    }
192
193    /// One parameter by name.
194    #[must_use]
195    pub fn parameter(&self, name: &str) -> Option<&ParamSpec> {
196        self.parameters.iter().find(|p| p.name == name)
197    }
198}
199
200/// A device's configuration schema: its groups (#125).
201#[derive(Clone, Debug, Default, PartialEq, Eq)]
202#[non_exhaustive]
203pub struct Schema {
204    /// The groups, in the order the device lists them.
205    pub groups: Vec<ConfigGroup>,
206}
207
208impl Schema {
209    /// An empty schema.
210    #[must_use]
211    pub const fn new() -> Self {
212        Self { groups: Vec::new() }
213    }
214
215    /// Builder form of pushing a group.
216    #[must_use]
217    pub fn with(mut self, group: ConfigGroup) -> Self {
218        self.groups.push(group);
219        self
220    }
221
222    /// One group by name.
223    #[must_use]
224    pub fn group(&self, name: &str) -> Option<&ConfigGroup> {
225        self.groups.iter().find(|g| g.name == name)
226    }
227
228    /// Whether `value` is one `group/name` accepts: the kind, and the bounds
229    /// — with the bound named, which is what a startup value that fails at
230    /// start reports (#125, completing #114).
231    pub fn check(&self, group: &str, name: &str, value: &ConfigValue) -> Result<(), ConfigError> {
232        let g = self
233            .group(group)
234            .ok_or_else(|| ConfigError::UnknownGroup(group.to_string()))?;
235        let spec = g
236            .parameter(name)
237            .ok_or_else(|| ConfigError::UnknownParameter {
238                group: group.to_string(),
239                name: name.to_string(),
240            })?;
241        spec.check(value).map_err(|reason| ConfigError::Invalid {
242            group: group.to_string(),
243            name: name.to_string(),
244            reason,
245        })
246    }
247
248    /// Every value in `values` against the schema, first failure named.
249    pub fn check_all(&self, values: &Effective) -> Result<(), ConfigError> {
250        for (group, params) in values {
251            for (name, value) in params {
252                self.check(group, name, value)?;
253            }
254        }
255        Ok(())
256    }
257}
258
259/// A parameter's value (#125).
260#[derive(Clone, Debug, PartialEq, Eq)]
261#[non_exhaustive]
262pub enum ConfigValue {
263    /// A switch.
264    Bool(bool),
265    /// A whole number in the parameter's unit.
266    Integer(i64),
267    /// Free text.
268    Text(String),
269}
270
271impl fmt::Display for ConfigValue {
272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273        match self {
274            Self::Bool(b) => write!(f, "{b}"),
275            Self::Integer(i) => write!(f, "{i}"),
276            Self::Text(t) => write!(f, "{t:?}"),
277        }
278    }
279}
280
281impl From<bool> for ConfigValue {
282    fn from(b: bool) -> Self {
283        Self::Bool(b)
284    }
285}
286
287impl From<i64> for ConfigValue {
288    fn from(i: i64) -> Self {
289        Self::Integer(i)
290    }
291}
292
293impl From<&str> for ConfigValue {
294    fn from(t: &str) -> Self {
295        Self::Text(t.to_string())
296    }
297}
298
299impl From<String> for ConfigValue {
300    fn from(t: String) -> Self {
301        Self::Text(t)
302    }
303}
304
305/// A value that must never appear in a log line, an event, a reply or an
306/// overlay (#125): a PIN, a key. `Debug` and `Display` redact; there is no
307/// `Serialize`. The only way out is [`into_inner`](Self::into_inner), which
308/// a device calls at the point it hands the value to the hardware.
309#[derive(Clone, PartialEq, Eq)]
310pub struct Sensitive<T>(T);
311
312impl<T> Sensitive<T> {
313    /// Wrap a value.
314    pub const fn new(value: T) -> Self {
315        Self(value)
316    }
317
318    /// The value, for the one place that needs it.
319    pub fn into_inner(self) -> T {
320        self.0
321    }
322}
323
324impl<T> fmt::Debug for Sensitive<T> {
325    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326        f.write_str("<redacted>")
327    }
328}
329
330impl<T> fmt::Display for Sensitive<T> {
331    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332        f.write_str("<redacted>")
333    }
334}
335
336/// What a device runs with, by group and parameter (#125): the read-back.
337/// A sensitive parameter is never in it.
338pub type Effective = BTreeMap<String, BTreeMap<String, ConfigValue>>;
339
340/// What to restore to undo a change (#126): the values a group had.
341pub type Undo = BTreeMap<String, ConfigValue>;
342
343/// Why a configuration operation did not happen (#125).
344#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
345#[non_exhaustive]
346pub enum ConfigError {
347    /// No such group.
348    #[error("unknown group {0:?}; the schema names every group it accepts")]
349    UnknownGroup(String),
350    /// No such parameter in the group.
351    #[error("group {group:?} declares no parameter {name:?}")]
352    UnknownParameter { group: String, name: String },
353    /// A value the schema does not accept, with the bound or kind named.
354    #[error("{group}/{name}: {reason}")]
355    Invalid {
356        group: String,
357        name: String,
358        reason: String,
359    },
360    /// The group is part of what the transport was started against.
361    #[error(
362        "group {0:?} is part of what this device's transport was started against; set it in the \
363         startup configuration and restart"
364    )]
365    Contract(String),
366    /// The device refused, in its own words.
367    #[error("the device refused the change: {0}")]
368    Device(String),
369    /// The device declares the group and cannot change it yet.
370    #[error("changing {0:?} at runtime is not supported by this device")]
371    Unsupported(String),
372}
373
374/// What a device's configuration plane looks like to the driver (#125).
375///
376/// The read side first: nothing is written until it can be read back
377/// (architecture §4.6 — "setting a power level without being able to read
378/// one back is not an operation, it is a wish"). `schema` says what may be
379/// configured and how; `effective` says what the device runs with, now,
380/// cached like [`Device::report`](crate::Device::report); `apply` (#126) changes one group and
381/// answers what to restore.
382#[async_trait::async_trait]
383pub trait Configure: Send + Sync {
384    /// The groups of parameters this device declares, with their class.
385    fn schema(&self) -> Schema;
386
387    /// What the device runs with: every non-sensitive parameter of every
388    /// group, by name. Sync and cached; a device that cannot read a value
389    /// back leaves it out, and the plane says so.
390    fn effective(&self) -> Effective;
391
392    /// The smallest confirm window that makes sense on this link (#127): a
393    /// change armed with a shorter one is armed with this instead, and the
394    /// reply says so. Derived from the device's round trip — an SBD session
395    /// takes minutes, and a coverage gap can outlast any fixed window — so a
396    /// rollback never undoes a change the caller could not yet have
397    /// confirmed. Sixty seconds unless the device knows better.
398    fn confirm_floor(&self) -> std::time::Duration {
399        std::time::Duration::from_secs(60)
400    }
401
402    /// Change one group's values (#126). Answers the values to restore, or
403    /// why not; the default refuses, which is what a device that declares
404    /// its schema before it can act on it says.
405    async fn apply(
406        &self,
407        group: &str,
408        values: &BTreeMap<String, ConfigValue>,
409    ) -> Result<Undo, ConfigError> {
410        let _ = values;
411        Err(ConfigError::Unsupported(group.to_string()))
412    }
413}
414
415#[cfg(test)]
416mod tests {
417    use super::*;
418
419    fn schema() -> Schema {
420        Schema::new().with(
421            ConfigGroup::new("poll", ParamClass::Hot, "polling")
422                .with(ParamSpec::new(
423                    "signal_poll_s",
424                    ParamKind::integer(Some(1), Some(3600), Some("s")),
425                    "how often",
426                ))
427                .with(ParamSpec::new("ring_alerts", ParamKind::Bool, "alerts"))
428                .with(ParamSpec::new("pin", ParamKind::Text, "the SIM PIN").sensitive()),
429        )
430    }
431
432    #[test]
433    fn a_bound_is_named_when_a_value_falls_outside_it() {
434        let s = schema();
435        let err = s
436            .check("poll", "signal_poll_s", &ConfigValue::Integer(0))
437            .expect_err("below the minimum");
438        assert_eq!(
439            err.to_string(),
440            "poll/signal_poll_s: 0 s is below the minimum of 1 s"
441        );
442        let err = s
443            .check("poll", "signal_poll_s", &ConfigValue::Integer(9_000))
444            .expect_err("above the maximum");
445        assert!(
446            err.to_string().contains("above the maximum of 3600 s"),
447            "{err}"
448        );
449        assert!(
450            s.check("poll", "signal_poll_s", &ConfigValue::Integer(60))
451                .is_ok()
452        );
453    }
454
455    #[test]
456    fn a_kind_mismatch_and_an_unknown_name_are_named_too() {
457        let s = schema();
458        let err = s
459            .check("poll", "ring_alerts", &ConfigValue::Integer(1))
460            .expect_err("a switch is not an integer");
461        assert!(
462            err.to_string().contains("expected a boolean, got 1"),
463            "{err}"
464        );
465        assert!(matches!(
466            s.check("poll", "nope", &ConfigValue::Bool(true)),
467            Err(ConfigError::UnknownParameter { .. })
468        ));
469        assert!(matches!(
470            s.check("nope", "ring_alerts", &ConfigValue::Bool(true)),
471            Err(ConfigError::UnknownGroup(_))
472        ));
473    }
474
475    #[test]
476    fn a_sensitive_value_never_prints() {
477        let pin = Sensitive::new("1234".to_string());
478        assert_eq!(format!("{pin:?}"), "<redacted>");
479        assert_eq!(pin.to_string(), "<redacted>");
480        assert_eq!(pin.into_inner(), "1234");
481    }
482
483    #[test]
484    fn the_file_key_defaults_to_the_name() {
485        let p = ParamSpec::new("period_s", ParamKind::Text, "");
486        assert_eq!(p.key_in_file(), "period_s");
487        assert_eq!(
488            p.file_key("duty_budget.period_s").key_in_file(),
489            "duty_budget.period_s"
490        );
491    }
492}