1use std::collections::BTreeMap;
16use std::fmt;
17
18#[derive(Clone, Debug, PartialEq, Eq)]
26#[non_exhaustive]
27pub enum ParamKind {
28 Bool,
30 Integer {
32 min: Option<i64>,
34 max: Option<i64>,
36 unit: Option<&'static str>,
38 },
39 Text,
41}
42
43impl ParamKind {
44 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
57#[non_exhaustive]
58pub enum ParamClass {
59 Hot,
61 Reach,
65 Contract,
68}
69
70#[derive(Clone, Debug, PartialEq, Eq)]
72#[non_exhaustive]
73pub struct ParamSpec {
74 pub name: &'static str,
77 pub kind: ParamKind,
79 pub sensitive: bool,
82 pub description: &'static str,
84 pub file_key: Option<&'static str>,
89}
90
91impl ParamSpec {
92 #[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 #[must_use]
106 pub const fn sensitive(mut self) -> Self {
107 self.sensitive = true;
108 self
109 }
110
111 #[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 #[must_use]
120 pub fn key_in_file(&self) -> &str {
121 self.file_key.unwrap_or(self.name)
122 }
123
124 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#[derive(Clone, Debug, PartialEq, Eq)]
162#[non_exhaustive]
163pub struct ConfigGroup {
164 pub name: &'static str,
166 pub class: ParamClass,
168 pub description: &'static str,
170 pub parameters: Vec<ParamSpec>,
172}
173
174impl ConfigGroup {
175 #[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 #[must_use]
188 pub fn with(mut self, spec: ParamSpec) -> Self {
189 self.parameters.push(spec);
190 self
191 }
192
193 #[must_use]
195 pub fn parameter(&self, name: &str) -> Option<&ParamSpec> {
196 self.parameters.iter().find(|p| p.name == name)
197 }
198}
199
200#[derive(Clone, Debug, Default, PartialEq, Eq)]
202#[non_exhaustive]
203pub struct Schema {
204 pub groups: Vec<ConfigGroup>,
206}
207
208impl Schema {
209 #[must_use]
211 pub const fn new() -> Self {
212 Self { groups: Vec::new() }
213 }
214
215 #[must_use]
217 pub fn with(mut self, group: ConfigGroup) -> Self {
218 self.groups.push(group);
219 self
220 }
221
222 #[must_use]
224 pub fn group(&self, name: &str) -> Option<&ConfigGroup> {
225 self.groups.iter().find(|g| g.name == name)
226 }
227
228 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 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#[derive(Clone, Debug, PartialEq, Eq)]
261#[non_exhaustive]
262pub enum ConfigValue {
263 Bool(bool),
265 Integer(i64),
267 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#[derive(Clone, PartialEq, Eq)]
310pub struct Sensitive<T>(T);
311
312impl<T> Sensitive<T> {
313 pub const fn new(value: T) -> Self {
315 Self(value)
316 }
317
318 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
336pub type Effective = BTreeMap<String, BTreeMap<String, ConfigValue>>;
339
340pub type Undo = BTreeMap<String, ConfigValue>;
342
343#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
345#[non_exhaustive]
346pub enum ConfigError {
347 #[error("unknown group {0:?}; the schema names every group it accepts")]
349 UnknownGroup(String),
350 #[error("group {group:?} declares no parameter {name:?}")]
352 UnknownParameter { group: String, name: String },
353 #[error("{group}/{name}: {reason}")]
355 Invalid {
356 group: String,
357 name: String,
358 reason: String,
359 },
360 #[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 #[error("the device refused the change: {0}")]
368 Device(String),
369 #[error("changing {0:?} at runtime is not supported by this device")]
371 Unsupported(String),
372}
373
374#[async_trait::async_trait]
383pub trait Configure: Send + Sync {
384 fn schema(&self) -> Schema;
386
387 fn effective(&self) -> Effective;
391
392 fn confirm_floor(&self) -> std::time::Duration {
399 std::time::Duration::from_secs(60)
400 }
401
402 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}