Skip to main content

matter_controller/
store.rs

1//! The node store: every commissioned node, what its interview found, and
2//! the name a person gave it.
3//!
4//! One JSON file, replaced atomically when something changes (a node
5//! commissioned, interviewed, renamed or removed). Attribute values are not
6//! kept: they come back with the first subscription report after a restart,
7//! so a gateway's flash sees a write per change of the network, not per
8//! message.
9
10use std::collections::BTreeMap;
11use std::path::{Path, PathBuf};
12
13use serde::{Deserialize, Serialize};
14
15use crate::fsutil::{read_json, write_atomic};
16use crate::Error;
17
18/// A device type an endpoint says it is (Descriptor cluster).
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
20pub struct DeviceType {
21    /// Device type id, e.g. `0x0100` for an On/Off Light.
22    pub id: u32,
23    /// Its revision.
24    pub revision: u16,
25}
26
27/// An endpoint of a node, from its Descriptor cluster.
28#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
29pub struct Endpoint {
30    /// What the endpoint is.
31    pub device_types: Vec<DeviceType>,
32    /// Clusters it serves.
33    pub server_clusters: Vec<u32>,
34    /// Clusters it is a client of (it sends their commands, e.g. a switch).
35    pub client_clusters: Vec<u32>,
36    /// Endpoints it is composed of.
37    pub parts: Vec<u16>,
38}
39
40/// What the Basic Information cluster says about a node.
41#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
42pub struct BasicInfo {
43    /// Vendor id.
44    pub vendor_id: Option<u16>,
45    /// Vendor name.
46    pub vendor_name: Option<String>,
47    /// Product id.
48    pub product_id: Option<u16>,
49    /// Product name.
50    pub product_name: Option<String>,
51    /// The label a user set on the node itself.
52    pub node_label: Option<String>,
53    /// Hardware version string.
54    pub hardware_version: Option<String>,
55    /// Software version string.
56    pub software_version: Option<String>,
57    /// Serial number.
58    pub serial_number: Option<String>,
59    /// Unique id, stable across factory resets.
60    pub unique_id: Option<String>,
61}
62
63/// A commissioned node.
64#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
65pub struct Node {
66    /// Operational node id on our fabric.
67    pub node_id: u64,
68    /// The name a person gave it (unique in the store).
69    pub name: String,
70    /// Basic Information, from the interview.
71    #[serde(default)]
72    pub basic: BasicInfo,
73    /// Endpoints by id, from the interview.
74    #[serde(default)]
75    pub endpoints: BTreeMap<u16, Endpoint>,
76    /// Whether the interview has completed.
77    #[serde(default)]
78    pub interviewed: bool,
79    /// When it was commissioned, seconds since the Unix epoch.
80    pub commissioned_at: u64,
81}
82
83impl Node {
84    /// The default name of node `node_id`.
85    pub fn default_name(node_id: u64) -> String {
86        format!("node_{node_id}")
87    }
88}
89
90#[derive(Default, Serialize, Deserialize)]
91struct StoreFile {
92    version: u32,
93    nodes: Vec<Node>,
94}
95
96/// The node store.
97pub struct NodeStore {
98    path: PathBuf,
99    nodes: BTreeMap<u64, Node>,
100}
101
102impl NodeStore {
103    const VERSION: u32 = 1;
104
105    /// Open the store at `path`, empty if there is no file yet.
106    pub fn open(path: &Path) -> Result<Self, Error> {
107        let file = read_json::<StoreFile>(path)?.unwrap_or_default();
108        if file.version > Self::VERSION {
109            return Err(Error::Store(format!(
110                "{}: version {} is newer than this build reads ({})",
111                path.display(),
112                file.version,
113                Self::VERSION
114            )));
115        }
116        Ok(Self {
117            path: path.to_path_buf(),
118            nodes: file.nodes.into_iter().map(|n| (n.node_id, n)).collect(),
119        })
120    }
121
122    fn save(&self) -> Result<(), Error> {
123        let file = StoreFile {
124            version: Self::VERSION,
125            nodes: self.nodes.values().cloned().collect(),
126        };
127        write_atomic(&self.path, &serde_json::to_vec_pretty(&file)?, false)
128    }
129
130    /// Every node, by node id.
131    pub fn nodes(&self) -> impl Iterator<Item = &Node> {
132        self.nodes.values()
133    }
134
135    /// The node with `node_id`.
136    pub fn get(&self, node_id: u64) -> Option<&Node> {
137        self.nodes.get(&node_id)
138    }
139
140    /// The node named `name`, or with node id `name` in decimal or `0x` hex.
141    pub fn find(&self, name: &str) -> Option<&Node> {
142        self.nodes.values().find(|n| n.name == name).or_else(|| {
143            let id = match name.strip_prefix("0x") {
144                Some(hex) => u64::from_str_radix(hex, 16).ok(),
145                None => name.parse().ok(),
146            }?;
147            self.nodes.get(&id)
148        })
149    }
150
151    /// Add or replace a node, and save.
152    pub fn put(&mut self, node: Node) -> Result<(), Error> {
153        if let Some(other) = self
154            .nodes
155            .values()
156            .find(|n| n.name == node.name && n.node_id != node.node_id)
157        {
158            return Err(Error::Invalid(format!(
159                "the name `{}` is taken by node {}",
160                node.name, other.node_id
161            )));
162        }
163        if self.nodes.get(&node.node_id) == Some(&node) {
164            return Ok(());
165        }
166        self.nodes.insert(node.node_id, node);
167        self.save()
168    }
169
170    /// Remove a node, and save.
171    pub fn remove(&mut self, node_id: u64) -> Result<Option<Node>, Error> {
172        let node = self.nodes.remove(&node_id);
173        if node.is_some() {
174            self.save()?;
175        }
176        Ok(node)
177    }
178
179    /// A name for a new node that no node has: `base`, or `base_2`, ...
180    pub fn unique_name(&self, base: &str) -> String {
181        if !self.nodes.values().any(|n| n.name == base) {
182            return base.to_string();
183        }
184        (2..)
185            .map(|i| format!("{base}_{i}"))
186            .find(|name| !self.nodes.values().any(|n| &n.name == name))
187            .unwrap()
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    fn node(id: u64, name: &str) -> Node {
196        Node {
197            node_id: id,
198            name: name.into(),
199            basic: BasicInfo::default(),
200            endpoints: BTreeMap::new(),
201            interviewed: false,
202            commissioned_at: 0,
203        }
204    }
205
206    #[test]
207    fn persists_and_finds() {
208        let dir = tempfile::tempdir().unwrap();
209        let path = dir.path().join("nodes.json");
210        let mut store = NodeStore::open(&path).unwrap();
211        store.put(node(5, "lamp")).unwrap();
212        store.put(node(6, "plug")).unwrap();
213        assert!(store.put(node(7, "lamp")).is_err());
214        assert_eq!(store.unique_name("lamp"), "lamp_2");
215
216        let store = NodeStore::open(&path).unwrap();
217        assert_eq!(store.find("lamp").unwrap().node_id, 5);
218        assert_eq!(store.find("6").unwrap().name, "plug");
219        assert_eq!(store.find("0x6").unwrap().name, "plug");
220        assert!(store.find("nope").is_none());
221    }
222
223    #[test]
224    fn unchanged_put_does_not_write() {
225        let dir = tempfile::tempdir().unwrap();
226        let path = dir.path().join("nodes.json");
227        let mut store = NodeStore::open(&path).unwrap();
228        store.put(node(1, "a")).unwrap();
229        let before = std::fs::metadata(&path).unwrap().modified().unwrap();
230        std::fs::remove_file(&path).unwrap();
231        store.put(node(1, "a")).unwrap();
232        assert!(!path.exists(), "an unchanged node was written again");
233        let _ = before;
234    }
235
236    #[test]
237    fn rejects_a_newer_version() {
238        let dir = tempfile::tempdir().unwrap();
239        let path = dir.path().join("nodes.json");
240        std::fs::write(&path, br#"{"version": 99, "nodes": []}"#).unwrap();
241        assert!(NodeStore::open(&path).is_err());
242    }
243}