1use 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
15pub const STORE_VERSION: u32 = 1;
17
18pub 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#[derive(Debug, thiserror::Error)]
29pub enum StoreError {
30 #[error("device store {path}: {source}")]
32 Io {
33 path: PathBuf,
35 source: std::io::Error,
37 },
38 #[error("device store {path}: {message}")]
40 Parse {
41 path: PathBuf,
43 message: String,
45 },
46}
47
48pub 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
73pub 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 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
107pub 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#[derive(Clone, Debug, Default)]
118pub struct Dirty {
119 notify: Arc<Notify>,
120}
121
122impl Dirty {
123 pub fn mark(&self) {
125 self.notify.notify_one();
126 }
127
128 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}