modem-device 0.2.0

The seam between the zenoh-modem driver and a physical or simulated medium
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! The configuration plane's vocabulary (#125).
//!
//! What a device declares about its own configuration, in this crate's own
//! words: it links no zenkey, and the management plane converts these to the
//! convention's types (zenkey RFC 05 §5.1) in `modem-contract`. The shape is
//! the convention's, so the conversion is a rename — and the one thing the
//! convention leaves to the producer, where a value came from, is a fact the
//! driver knows from the startup file and the device does not, which is what
//! [`ParamSpec::file_key`] is for.
//!
//! The read side first (#125): nothing is written until it can be read back.
//! `apply` (#126) has a default that refuses, so a device declares its schema
//! before it can act on it and says so honestly.

use std::collections::BTreeMap;
use std::fmt;

/// What values a parameter accepts (#125).
///
/// Three kinds, and no more until something acts on a fourth: every radio or
/// interface parameter met so far is a switch, a bounded integer in a stated
/// unit, or text. **No float**: a value that needs one is an integer in a
/// finer unit — `fake-medium`'s duty budget is a fraction and is exposed in
/// ppm — which also keeps equality exact.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParamKind {
    /// `true` or `false`.
    Bool,
    /// A whole number, optionally bounded, in a stated unit.
    Integer {
        /// Smallest accepted value, inclusive.
        min: Option<i64>,
        /// Largest accepted value, inclusive.
        max: Option<i64>,
        /// What one unit is — `"s"`, `"bit/s"`, `"ppm"`. `None` for a count.
        unit: Option<&'static str>,
    },
    /// Free text.
    Text,
}

impl ParamKind {
    /// A bounded integer in a unit.
    #[must_use]
    pub const fn integer(min: Option<i64>, max: Option<i64>, unit: Option<&'static str>) -> Self {
        Self::Integer { min, max, unit }
    }
}

/// Whether a group may change under a running driver (#125, report §4.9).
///
/// **The class belongs to the device, not the name**: an MTU is `Contract`
/// on an SDU medium whose transport was sized against it and `Hot` on a
/// netdev whose TCP link adapts.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ParamClass {
    /// Takes effect at once; the reply to a change is the read-back.
    Hot,
    /// Decides whether the device can reach the bus at all — a frequency, an
    /// APN. Changed only as a confirmed change (#127), because the read-back
    /// would cross the link being changed.
    Reach,
    /// Part of what the transport was started against. Refused at runtime
    /// with the restart named; changed in the startup configuration.
    Contract,
}

/// One parameter a device declares (#125).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ParamSpec {
    /// The name a change addresses, unique within its group — and the key
    /// the startup TOML spells it under, so a bound is written once.
    pub name: &'static str,
    /// What values it accepts.
    pub kind: ParamKind,
    /// Write-only: never read back, published, logged or evented. A PIN, a
    /// key. It appears in the schema and never with a value.
    pub sensitive: bool,
    /// One line for the operator reading the schema cold.
    pub description: &'static str,
    /// The key the startup file spells it under, when that is not `name`:
    /// a dotted path into the device's section (`duty_budget.fraction`).
    /// The driver reads the file and the device never sees it; this is
    /// how the read-back says a value came from the file (#125).
    pub file_key: Option<&'static str>,
}

impl ParamSpec {
    /// A parameter of the given kind.
    #[must_use]
    pub const fn new(name: &'static str, kind: ParamKind, description: &'static str) -> Self {
        Self {
            name,
            kind,
            sensitive: false,
            description,
            file_key: None,
        }
    }

    /// Mark the parameter write-only.
    #[must_use]
    pub const fn sensitive(mut self) -> Self {
        self.sensitive = true;
        self
    }

    /// The startup file's key for it, when that is not the name.
    #[must_use]
    pub const fn file_key(mut self, key: &'static str) -> Self {
        self.file_key = Some(key);
        self
    }

    /// The startup file's key for it.
    #[must_use]
    pub fn key_in_file(&self) -> &str {
        self.file_key.unwrap_or(self.name)
    }

    /// Whether `value` is one this parameter accepts: the kind, and the
    /// bounds — with the bound named.
    pub fn check(&self, value: &ConfigValue) -> Result<(), String> {
        match (&self.kind, value) {
            (ParamKind::Bool, ConfigValue::Bool(_)) | (ParamKind::Text, ConfigValue::Text(_)) => {
                Ok(())
            }
            (ParamKind::Integer { min, max, unit }, ConfigValue::Integer(v)) => {
                let unit = unit.map_or(String::new(), |u| format!(" {u}"));
                if let Some(min) = min
                    && v < min
                {
                    return Err(format!("{v}{unit} is below the minimum of {min}{unit}"));
                }
                if let Some(max) = max
                    && v > max
                {
                    return Err(format!("{v}{unit} is above the maximum of {max}{unit}"));
                }
                Ok(())
            }
            (kind, value) => Err(format!(
                "expected {}, got {value}",
                match kind {
                    ParamKind::Bool => "a boolean",
                    ParamKind::Integer { .. } => "an integer",
                    ParamKind::Text => "text",
                }
            )),
        }
    }
}

/// Parameters that change together (#125): the unit a change addresses and
/// the unit that has a class. Coupled parameters share a group because a
/// single-parameter intermediate state can be unsafe — a frequency without
/// its bandwidth, a spreading factor without its coding rate.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ConfigGroup {
    /// The group's name, a plain chunk: it is spelled in the write key.
    pub name: &'static str,
    /// Whether it may change under a running driver.
    pub class: ParamClass,
    /// One line for the operator.
    pub description: &'static str,
    /// The parameters, in the order the device lists them.
    pub parameters: Vec<ParamSpec>,
}

impl ConfigGroup {
    /// A group with its class; parameters are added with [`with`](Self::with).
    #[must_use]
    pub const fn new(name: &'static str, class: ParamClass, description: &'static str) -> Self {
        Self {
            name,
            class,
            description,
            parameters: Vec::new(),
        }
    }

    /// Builder form of pushing a parameter.
    #[must_use]
    pub fn with(mut self, spec: ParamSpec) -> Self {
        self.parameters.push(spec);
        self
    }

    /// One parameter by name.
    #[must_use]
    pub fn parameter(&self, name: &str) -> Option<&ParamSpec> {
        self.parameters.iter().find(|p| p.name == name)
    }
}

/// A device's configuration schema: its groups (#125).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Schema {
    /// The groups, in the order the device lists them.
    pub groups: Vec<ConfigGroup>,
}

impl Schema {
    /// An empty schema.
    #[must_use]
    pub const fn new() -> Self {
        Self { groups: Vec::new() }
    }

    /// Builder form of pushing a group.
    #[must_use]
    pub fn with(mut self, group: ConfigGroup) -> Self {
        self.groups.push(group);
        self
    }

    /// One group by name.
    #[must_use]
    pub fn group(&self, name: &str) -> Option<&ConfigGroup> {
        self.groups.iter().find(|g| g.name == name)
    }

    /// Whether `value` is one `group/name` accepts: the kind, and the bounds
    /// — with the bound named, which is what a startup value that fails at
    /// start reports (#125, completing #114).
    pub fn check(&self, group: &str, name: &str, value: &ConfigValue) -> Result<(), ConfigError> {
        let g = self
            .group(group)
            .ok_or_else(|| ConfigError::UnknownGroup(group.to_string()))?;
        let spec = g
            .parameter(name)
            .ok_or_else(|| ConfigError::UnknownParameter {
                group: group.to_string(),
                name: name.to_string(),
            })?;
        spec.check(value).map_err(|reason| ConfigError::Invalid {
            group: group.to_string(),
            name: name.to_string(),
            reason,
        })
    }

    /// Every value in `values` against the schema, first failure named.
    pub fn check_all(&self, values: &Effective) -> Result<(), ConfigError> {
        for (group, params) in values {
            for (name, value) in params {
                self.check(group, name, value)?;
            }
        }
        Ok(())
    }
}

/// A parameter's value (#125).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConfigValue {
    /// A switch.
    Bool(bool),
    /// A whole number in the parameter's unit.
    Integer(i64),
    /// Free text.
    Text(String),
}

impl fmt::Display for ConfigValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Bool(b) => write!(f, "{b}"),
            Self::Integer(i) => write!(f, "{i}"),
            Self::Text(t) => write!(f, "{t:?}"),
        }
    }
}

impl From<bool> for ConfigValue {
    fn from(b: bool) -> Self {
        Self::Bool(b)
    }
}

impl From<i64> for ConfigValue {
    fn from(i: i64) -> Self {
        Self::Integer(i)
    }
}

impl From<&str> for ConfigValue {
    fn from(t: &str) -> Self {
        Self::Text(t.to_string())
    }
}

impl From<String> for ConfigValue {
    fn from(t: String) -> Self {
        Self::Text(t)
    }
}

/// A value that must never appear in a log line, an event, a reply or an
/// overlay (#125): a PIN, a key. `Debug` and `Display` redact; there is no
/// `Serialize`. The only way out is [`into_inner`](Self::into_inner), which
/// a device calls at the point it hands the value to the hardware.
#[derive(Clone, PartialEq, Eq)]
pub struct Sensitive<T>(T);

impl<T> Sensitive<T> {
    /// Wrap a value.
    pub const fn new(value: T) -> Self {
        Self(value)
    }

    /// The value, for the one place that needs it.
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> fmt::Debug for Sensitive<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("<redacted>")
    }
}

impl<T> fmt::Display for Sensitive<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("<redacted>")
    }
}

/// What a device runs with, by group and parameter (#125): the read-back.
/// A sensitive parameter is never in it.
pub type Effective = BTreeMap<String, BTreeMap<String, ConfigValue>>;

/// What to restore to undo a change (#126): the values a group had.
pub type Undo = BTreeMap<String, ConfigValue>;

/// Why a configuration operation did not happen (#125).
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ConfigError {
    /// No such group.
    #[error("unknown group {0:?}; the schema names every group it accepts")]
    UnknownGroup(String),
    /// No such parameter in the group.
    #[error("group {group:?} declares no parameter {name:?}")]
    UnknownParameter { group: String, name: String },
    /// A value the schema does not accept, with the bound or kind named.
    #[error("{group}/{name}: {reason}")]
    Invalid {
        group: String,
        name: String,
        reason: String,
    },
    /// The group is part of what the transport was started against.
    #[error(
        "group {0:?} is part of what this device's transport was started against; set it in the \
         startup configuration and restart"
    )]
    Contract(String),
    /// The device refused, in its own words.
    #[error("the device refused the change: {0}")]
    Device(String),
    /// The device declares the group and cannot change it yet.
    #[error("changing {0:?} at runtime is not supported by this device")]
    Unsupported(String),
}

/// What a device's configuration plane looks like to the driver (#125).
///
/// The read side first: nothing is written until it can be read back
/// (architecture §4.6 — "setting a power level without being able to read
/// one back is not an operation, it is a wish"). `schema` says what may be
/// configured and how; `effective` says what the device runs with, now,
/// cached like [`Device::report`](crate::Device::report); `apply` (#126) changes one group and
/// answers what to restore.
#[async_trait::async_trait]
pub trait Configure: Send + Sync {
    /// The groups of parameters this device declares, with their class.
    fn schema(&self) -> Schema;

    /// What the device runs with: every non-sensitive parameter of every
    /// group, by name. Sync and cached; a device that cannot read a value
    /// back leaves it out, and the plane says so.
    fn effective(&self) -> Effective;

    /// The smallest confirm window that makes sense on this link (#127): a
    /// change armed with a shorter one is armed with this instead, and the
    /// reply says so. Derived from the device's round trip — an SBD session
    /// takes minutes, and a coverage gap can outlast any fixed window — so a
    /// rollback never undoes a change the caller could not yet have
    /// confirmed. Sixty seconds unless the device knows better.
    fn confirm_floor(&self) -> std::time::Duration {
        std::time::Duration::from_secs(60)
    }

    /// Change one group's values (#126). Answers the values to restore, or
    /// why not; the default refuses, which is what a device that declares
    /// its schema before it can act on it says.
    async fn apply(
        &self,
        group: &str,
        values: &BTreeMap<String, ConfigValue>,
    ) -> Result<Undo, ConfigError> {
        let _ = values;
        Err(ConfigError::Unsupported(group.to_string()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn schema() -> Schema {
        Schema::new().with(
            ConfigGroup::new("poll", ParamClass::Hot, "polling")
                .with(ParamSpec::new(
                    "signal_poll_s",
                    ParamKind::integer(Some(1), Some(3600), Some("s")),
                    "how often",
                ))
                .with(ParamSpec::new("ring_alerts", ParamKind::Bool, "alerts"))
                .with(ParamSpec::new("pin", ParamKind::Text, "the SIM PIN").sensitive()),
        )
    }

    #[test]
    fn a_bound_is_named_when_a_value_falls_outside_it() {
        let s = schema();
        let err = s
            .check("poll", "signal_poll_s", &ConfigValue::Integer(0))
            .expect_err("below the minimum");
        assert_eq!(
            err.to_string(),
            "poll/signal_poll_s: 0 s is below the minimum of 1 s"
        );
        let err = s
            .check("poll", "signal_poll_s", &ConfigValue::Integer(9_000))
            .expect_err("above the maximum");
        assert!(
            err.to_string().contains("above the maximum of 3600 s"),
            "{err}"
        );
        assert!(
            s.check("poll", "signal_poll_s", &ConfigValue::Integer(60))
                .is_ok()
        );
    }

    #[test]
    fn a_kind_mismatch_and_an_unknown_name_are_named_too() {
        let s = schema();
        let err = s
            .check("poll", "ring_alerts", &ConfigValue::Integer(1))
            .expect_err("a switch is not an integer");
        assert!(
            err.to_string().contains("expected a boolean, got 1"),
            "{err}"
        );
        assert!(matches!(
            s.check("poll", "nope", &ConfigValue::Bool(true)),
            Err(ConfigError::UnknownParameter { .. })
        ));
        assert!(matches!(
            s.check("nope", "ring_alerts", &ConfigValue::Bool(true)),
            Err(ConfigError::UnknownGroup(_))
        ));
    }

    #[test]
    fn a_sensitive_value_never_prints() {
        let pin = Sensitive::new("1234".to_string());
        assert_eq!(format!("{pin:?}"), "<redacted>");
        assert_eq!(pin.to_string(), "<redacted>");
        assert_eq!(pin.into_inner(), "1234");
    }

    #[test]
    fn the_file_key_defaults_to_the_name() {
        let p = ParamSpec::new("period_s", ParamKind::Text, "");
        assert_eq!(p.key_in_file(), "period_s");
        assert_eq!(
            p.file_key("duty_budget.period_s").key_in_file(),
            "duty_budget.period_s"
        );
    }
}