use std::path::Path;
use modem_device::config::{ConfigValue, ParamKind, Schema};
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub(crate) struct Entry {
pub group: String,
pub name: String,
pub value: toml::Value,
pub overrode: toml::Value,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub(crate) struct Overlay {
pub schema: String,
#[serde(default, rename = "entry")]
pub entries: Vec<Entry>,
}
impl Overlay {
pub(crate) fn new(schema: String) -> Self {
Self {
schema,
entries: Vec::new(),
}
}
pub(crate) fn load(path: &Path) -> anyhow::Result<Option<Self>> {
match std::fs::read_to_string(path) {
Ok(text) => Ok(Some(toml::from_str(&text)?)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
pub(crate) fn save(&self, path: &Path) -> anyhow::Result<()> {
use std::io::Write as _;
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let tmp = path.with_extension("toml.tmp");
let text = toml::to_string(self)?;
{
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt as _;
opts.mode(0o600);
}
let mut f = opts.open(&tmp)?;
f.write_all(text.as_bytes())?;
f.sync_all()?;
}
std::fs::rename(&tmp, path)?;
Ok(())
}
pub(crate) fn upsert(
&mut self,
group: &str,
name: &str,
value: toml::Value,
overrode: toml::Value,
) {
match self
.entries
.iter_mut()
.find(|e| e.group == group && e.name == name)
{
Some(e) => {
e.value = value;
e.overrode = overrode;
}
None => self.entries.push(Entry {
group: group.to_string(),
name: name.to_string(),
value,
overrode,
}),
}
}
}
pub(crate) fn to_toml(v: &ConfigValue) -> toml::Value {
match v {
ConfigValue::Bool(b) => toml::Value::Boolean(*b),
ConfigValue::Integer(i) => toml::Value::Integer(*i),
ConfigValue::Text(t) => toml::Value::String(t.clone()),
_ => toml::Value::String(v.to_string()),
}
}
pub(crate) fn from_toml(v: &toml::Value) -> Option<ConfigValue> {
match v {
toml::Value::Boolean(b) => Some(ConfigValue::Bool(*b)),
toml::Value::Integer(i) => Some(ConfigValue::Integer(*i)),
toml::Value::String(t) => Some(ConfigValue::Text(t.clone())),
_ => None,
}
}
pub(crate) fn schema_hash(schema: &Schema) -> String {
let mut text = String::new();
for g in &schema.groups {
text.push_str(&format!("{}:{:?}\n", g.name, g.class));
for p in &g.parameters {
let kind = match &p.kind {
ParamKind::Bool => "bool".to_string(),
ParamKind::Integer { min, max, unit } => {
format!("integer:{min:?}:{max:?}:{unit:?}")
}
ParamKind::Text => "text".to_string(),
_ => "other".to_string(),
};
text.push_str(&format!(" {}:{kind}:{}\n", p.name, p.sensitive));
}
}
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in text.bytes() {
h ^= u64::from(b);
h = h.wrapping_mul(0x0100_0000_01b3);
}
format!("{h:016x}")
}
#[cfg(test)]
mod tests {
use super::*;
use modem_device::config::{ConfigGroup, ParamClass, ParamSpec};
fn schema() -> Schema {
Schema::new().with(
ConfigGroup::new("poll", ParamClass::Hot, "").with(ParamSpec::new(
"signal_poll_s",
ParamKind::integer(Some(0), None, Some("s")),
"",
)),
)
}
#[test]
fn the_file_round_trips_and_is_private() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("sat0.overlay.toml");
let mut o = Overlay::new(schema_hash(&schema()));
o.upsert(
"poll",
"signal_poll_s",
toml::Value::Integer(30),
toml::Value::Integer(60),
);
o.upsert(
"poll",
"signal_poll_s",
toml::Value::Integer(20),
toml::Value::Integer(60),
);
o.save(&path).expect("saved");
assert_eq!(o.entries.len(), 1, "replaced, not appended");
let back = Overlay::load(&path).expect("read").expect("present");
assert_eq!(back, o);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(
mode, 0o600,
"a remote write that survives a reboot is guarded"
);
}
assert!(
Overlay::load(&dir.path().join("none.toml"))
.unwrap()
.is_none()
);
}
#[test]
fn the_hash_moves_when_the_schema_does_and_not_otherwise() {
let a = schema_hash(&schema());
assert_eq!(a, schema_hash(&schema()));
let wider = Schema::new().with(ConfigGroup::new("poll", ParamClass::Hot, "").with(
ParamSpec::new(
"signal_poll_s",
ParamKind::integer(Some(1), None, Some("s")),
"",
),
));
assert_ne!(a, schema_hash(&wider), "a bound is part of the contract");
}
}