Skip to main content

zigbee_host/
store.rs

1//! The device store: one JSON file, written atomically and only when a
2//! device record changes, batched so a burst of changes is one write.
3
4use std::collections::BTreeMap;
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7use std::time::Duration;
8
9use serde::{Deserialize, Serialize};
10use tokio::sync::Notify;
11use zigbee_primitives::Ieee;
12
13use crate::device::Device;
14
15/// The store file's format version.
16pub const STORE_VERSION: u32 = 1;
17
18/// How long changes are gathered before one write.
19pub const WRITE_DELAY: Duration = Duration::from_secs(2);
20
21#[derive(Serialize, Deserialize)]
22struct StoreFile {
23    version: u32,
24    devices: Vec<Device>,
25}
26
27/// Store errors.
28#[derive(Debug, thiserror::Error)]
29pub enum StoreError {
30    /// Reading or writing the file failed.
31    #[error("device store {path}: {source}")]
32    Io {
33        /// The file.
34        path: PathBuf,
35        /// The error.
36        source: std::io::Error,
37    },
38    /// The file did not parse.
39    #[error("device store {path}: {message}")]
40    Parse {
41        /// The file.
42        path: PathBuf,
43        /// What was wrong.
44        message: String,
45    },
46}
47
48/// Load devices from `path`; a missing file is an empty store.
49pub fn load(path: &Path) -> Result<BTreeMap<Ieee, Device>, StoreError> {
50    let text = match std::fs::read_to_string(path) {
51        Ok(text) => text,
52        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
53        Err(source) => {
54            return Err(StoreError::Io {
55                path: path.into(),
56                source,
57            })
58        }
59    };
60    let file: StoreFile = serde_json::from_str(&text).map_err(|e| StoreError::Parse {
61        path: path.into(),
62        message: e.to_string(),
63    })?;
64    if file.version != STORE_VERSION {
65        return Err(StoreError::Parse {
66            path: path.into(),
67            message: format!("unsupported store version {}", file.version),
68        });
69    }
70    Ok(file.devices.into_iter().map(|d| (d.ieee, d)).collect())
71}
72
73/// Write `contents` to `path` atomically: a temporary file in the same
74/// directory, synced, then renamed over the old one. On Unix the file is
75/// readable by its owner only, since backups hold the network key.
76pub fn write_atomic(path: &Path, contents: &[u8]) -> std::io::Result<()> {
77    use std::io::Write;
78    static COUNTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
79    // A temporary name of its own, so concurrent writers never share one.
80    let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
81    let name = path
82        .file_name()
83        .map(|n| n.to_string_lossy().into_owned())
84        .unwrap_or_default();
85    let tmp = path.with_file_name(format!(".{name}.{}.{n}.tmp", std::process::id()));
86    {
87        let mut options = std::fs::OpenOptions::new();
88        options.write(true).create(true).truncate(true);
89        #[cfg(unix)]
90        {
91            use std::os::unix::fs::OpenOptionsExt;
92            options.mode(0o600);
93        }
94        let mut file = options.open(&tmp)?;
95        file.write_all(contents)?;
96        file.sync_all()?;
97    }
98    std::fs::rename(&tmp, path)?;
99    if let Some(dir) = path.parent() {
100        if let Ok(dir) = std::fs::File::open(dir) {
101            let _ = dir.sync_all();
102        }
103    }
104    Ok(())
105}
106
107/// Serialize devices for the store file.
108pub fn serialize(devices: &BTreeMap<Ieee, Device>) -> Vec<u8> {
109    let file = StoreFile {
110        version: STORE_VERSION,
111        devices: devices.values().cloned().collect(),
112    };
113    serde_json::to_vec(&file).unwrap_or_default()
114}
115
116/// Wakes the writer when devices change.
117#[derive(Clone, Debug, Default)]
118pub struct Dirty {
119    notify: Arc<Notify>,
120}
121
122impl Dirty {
123    /// Mark the store changed.
124    pub fn mark(&self) {
125        self.notify.notify_one();
126    }
127
128    /// Wait for a change.
129    pub async fn changed(&self) {
130        self.notify.notified().await;
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[test]
139    fn round_trips_without_volatile_fields() {
140        let dir = tempfile::tempdir().unwrap();
141        let path = dir.path().join("devices.json");
142        assert!(load(&path).unwrap().is_empty());
143        let mut d = Device::new(Ieee(7), 0x1234, 100);
144        d.model = Some("SIM-TH1".into());
145        d.last_lqi = Some(200);
146        let mut map = BTreeMap::new();
147        map.insert(d.ieee, d.clone());
148        write_atomic(&path, &serialize(&map)).unwrap();
149        let loaded = load(&path).unwrap();
150        d.last_lqi = None;
151        assert_eq!(loaded.get(&Ieee(7)), Some(&d));
152        std::fs::write(&path, b"{").unwrap();
153        assert!(load(&path).is_err());
154    }
155}