use std::collections::BTreeMap;
use std::fmt;
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParamKind {
Bool,
Integer {
min: Option<i64>,
max: Option<i64>,
unit: Option<&'static str>,
},
Text,
}
impl ParamKind {
#[must_use]
pub const fn integer(min: Option<i64>, max: Option<i64>, unit: Option<&'static str>) -> Self {
Self::Integer { min, max, unit }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ParamClass {
Hot,
Reach,
Contract,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ParamSpec {
pub name: &'static str,
pub kind: ParamKind,
pub sensitive: bool,
pub description: &'static str,
pub file_key: Option<&'static str>,
}
impl ParamSpec {
#[must_use]
pub const fn new(name: &'static str, kind: ParamKind, description: &'static str) -> Self {
Self {
name,
kind,
sensitive: false,
description,
file_key: None,
}
}
#[must_use]
pub const fn sensitive(mut self) -> Self {
self.sensitive = true;
self
}
#[must_use]
pub const fn file_key(mut self, key: &'static str) -> Self {
self.file_key = Some(key);
self
}
#[must_use]
pub fn key_in_file(&self) -> &str {
self.file_key.unwrap_or(self.name)
}
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",
}
)),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ConfigGroup {
pub name: &'static str,
pub class: ParamClass,
pub description: &'static str,
pub parameters: Vec<ParamSpec>,
}
impl ConfigGroup {
#[must_use]
pub const fn new(name: &'static str, class: ParamClass, description: &'static str) -> Self {
Self {
name,
class,
description,
parameters: Vec::new(),
}
}
#[must_use]
pub fn with(mut self, spec: ParamSpec) -> Self {
self.parameters.push(spec);
self
}
#[must_use]
pub fn parameter(&self, name: &str) -> Option<&ParamSpec> {
self.parameters.iter().find(|p| p.name == name)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Schema {
pub groups: Vec<ConfigGroup>,
}
impl Schema {
#[must_use]
pub const fn new() -> Self {
Self { groups: Vec::new() }
}
#[must_use]
pub fn with(mut self, group: ConfigGroup) -> Self {
self.groups.push(group);
self
}
#[must_use]
pub fn group(&self, name: &str) -> Option<&ConfigGroup> {
self.groups.iter().find(|g| g.name == name)
}
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,
})
}
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(())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConfigValue {
Bool(bool),
Integer(i64),
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)
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct Sensitive<T>(T);
impl<T> Sensitive<T> {
pub const fn new(value: T) -> Self {
Self(value)
}
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>")
}
}
pub type Effective = BTreeMap<String, BTreeMap<String, ConfigValue>>;
pub type Undo = BTreeMap<String, ConfigValue>;
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ConfigError {
#[error("unknown group {0:?}; the schema names every group it accepts")]
UnknownGroup(String),
#[error("group {group:?} declares no parameter {name:?}")]
UnknownParameter { group: String, name: String },
#[error("{group}/{name}: {reason}")]
Invalid {
group: String,
name: String,
reason: String,
},
#[error(
"group {0:?} is part of what this device's transport was started against; set it in the \
startup configuration and restart"
)]
Contract(String),
#[error("the device refused the change: {0}")]
Device(String),
#[error("changing {0:?} at runtime is not supported by this device")]
Unsupported(String),
}
#[async_trait::async_trait]
pub trait Configure: Send + Sync {
fn schema(&self) -> Schema;
fn effective(&self) -> Effective;
fn confirm_floor(&self) -> std::time::Duration {
std::time::Duration::from_secs(60)
}
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"
);
}
}