1use std::collections::{HashMap, HashSet, VecDeque};
5
6use serde::Serialize;
7
8use super::{Link, Mesh, Node};
9
10#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
13pub struct Branch<'a> {
14 #[serde(flatten)]
15 pub node: &'a Node,
16 #[serde(skip_serializing_if = "Vec::is_empty")]
19 pub uplinks: Vec<Uplink>,
20 #[serde(skip_serializing_if = "Vec::is_empty")]
21 pub children: Vec<Branch<'a>>,
22}
23
24#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
26pub struct Uplink {
27 pub kind: Option<String>,
29 pub interface: Option<String>,
32 pub rate_down: Option<u64>,
34 pub rate_up: Option<u64>,
35}
36
37type Below<'a> = HashMap<&'a str, Vec<(&'a str, Uplink)>>;
39
40type Children<'a> = HashMap<&'a str, Vec<(&'a str, Vec<Uplink>)>>;
42
43impl Mesh {
44 #[must_use]
50 pub fn tree(&self) -> Vec<Branch<'_>> {
51 let nodes: HashMap<&str, &Node> = self.nodes.iter().map(|n| (n.uid.as_str(), n)).collect();
52 let below = self.below();
53 let starts = self
54 .nodes
55 .iter()
56 .filter(|n| n.role.as_deref() == Some("master"))
57 .chain(self.nodes.iter().filter(|n| n.meshed));
58 let mut placed = HashSet::new();
59 let mut children = Children::new();
60 let mut roots = Vec::new();
61 for start in starts {
62 let uid = start.uid.as_str();
63 if placed.insert(uid) {
64 roots.push(uid);
65 place(&below, &nodes, uid, &mut placed, &mut children);
66 }
67 }
68 roots
69 .into_iter()
70 .map(|uid| branch(&nodes, &mut children, uid, Vec::new()))
71 .collect()
72 }
73
74 fn below(&self) -> Below<'_> {
75 let mut below = Below::new();
76 let connected = self
77 .links
78 .iter()
79 .filter(|l| l.state.as_deref().is_none_or(|s| s == "CONNECTED"));
80 for link in connected {
81 let (parent, child, uplink) = orient(link);
82 below.entry(parent).or_default().push((child, uplink));
83 }
84 below
85 }
86}
87
88fn orient(link: &Link) -> (&str, &str, Uplink) {
91 let reversed = link
92 .interface
93 .as_deref()
94 .is_some_and(|i| i.starts_with("UPLINK"));
95 let (parent, child, down, up) = if reversed {
96 (&link.to_uid, &link.from_uid, link.rate_rx, link.rate_tx)
97 } else {
98 (&link.from_uid, &link.to_uid, link.rate_tx, link.rate_rx)
99 };
100 let uplink = Uplink {
101 kind: link.kind.clone(),
102 interface: link.interface.clone(),
103 rate_down: down,
104 rate_up: up,
105 };
106 (parent, child, uplink)
107}
108
109fn place<'a>(
112 below: &Below<'a>,
113 nodes: &HashMap<&str, &Node>,
114 start: &'a str,
115 placed: &mut HashSet<&'a str>,
116 children: &mut Children<'a>,
117) {
118 let mut queue = VecDeque::from([start]);
119 while let Some(parent) = queue.pop_front() {
120 let links = below.get(parent).map_or(&[][..], Vec::as_slice);
121 let found = group(links, |child| {
122 nodes.contains_key(child) && !placed.contains(child)
123 });
124 for (child, _) in &found {
125 placed.insert(child);
126 queue.push_back(child);
127 }
128 children.insert(parent, found);
129 }
130}
131
132fn group<'a>(
134 links: &[(&'a str, Uplink)],
135 new: impl Fn(&str) -> bool,
136) -> Vec<(&'a str, Vec<Uplink>)> {
137 let mut found: Vec<(&str, Vec<Uplink>)> = Vec::new();
138 for (child, uplink) in links {
139 if let Some(entry) = found.iter_mut().find(|(c, _)| c == child) {
140 entry.1.push(uplink.clone());
141 } else if new(child) {
142 found.push((child, vec![uplink.clone()]));
143 }
144 }
145 found
146}
147
148fn branch<'a>(
150 nodes: &HashMap<&str, &'a Node>,
151 children: &mut Children<'_>,
152 uid: &str,
153 uplinks: Vec<Uplink>,
154) -> Branch<'a> {
155 let mut below: Vec<Branch<'a>> = children
156 .remove(uid)
157 .unwrap_or_default()
158 .into_iter()
159 .map(|(child, uplinks)| branch(nodes, children, child, uplinks))
160 .collect();
161 below.sort_by_key(|b| {
162 (
163 !b.node.meshed,
164 b.node.name.clone().map(|n| n.to_lowercase()),
165 )
166 });
167 Branch {
168 node: nodes[uid],
169 uplinks,
170 children: below,
171 }
172}
173
174#[cfg(test)]
175mod tests {
176 use super::*;
177
178 fn node(uid: &str, role: Option<&str>) -> Node {
179 Node {
180 uid: uid.to_owned(),
181 name: Some(uid.to_uppercase()),
182 role: role.map(str::to_owned),
183 meshed: role.is_some(),
184 ..Node::default()
185 }
186 }
187
188 fn link(from: &str, to: &str, interface: &str, state: &str) -> Link {
189 Link {
190 from_uid: from.to_owned(),
191 to_uid: to.to_owned(),
192 interface: Some(interface.to_owned()),
193 state: Some(state.to_owned()),
194 rate_rx: Some(1),
195 rate_tx: Some(2),
196 ..Link::default()
197 }
198 }
199
200 fn shape(branch: &Branch) -> String {
202 let below: Vec<String> = branch.children.iter().map(shape).collect();
203 if below.is_empty() {
204 branch.node.uid.clone()
205 } else {
206 format!("{}({})", branch.node.uid, below.join(" "))
207 }
208 }
209
210 #[test]
211 fn builds_the_tree() {
212 let mesh = Mesh {
213 nodes: vec![
214 node("h2", None),
215 node("r1", Some("slave")),
216 node("box", Some("master")),
217 node("r2", Some("slave")),
218 node("h1", None),
219 node("gone", None),
220 node("lost", Some("slave")),
221 ],
222 links: vec![
223 link("r1", "box", "UPLINK:2G:0", "CONNECTED"),
226 link("box", "r1", "AP:5G:0", "CONNECTED"),
227 link("r1", "box", "UPLINK:5G:0", "CONNECTED"),
228 link("r2", "r1", "UPLINK:5G:0", "CONNECTED"),
229 link("r2", "box", "UPLINK:2G:0", "DISCONNECTED"),
230 link("r2", "h2", "LAN:1", "CONNECTED"),
231 link("box", "h1", "AP:2G:0", "CONNECTED"),
232 link("box", "gone", "AP:2G:0", "DISCONNECTED"),
233 link("box", "nowhere", "AP:2G:0", "CONNECTED"),
234 ],
235 };
236 let tree = mesh.tree();
237 let shapes: Vec<String> = tree.iter().map(shape).collect();
238 assert_eq!(shapes, ["box(r1(r2(h2)) h1)", "lost"]);
239 let r1 = &tree[0].children[0];
240 let interfaces: Vec<_> = r1.uplinks.iter().map(|u| u.interface.as_deref()).collect();
241 assert_eq!(
242 interfaces,
243 [Some("UPLINK:2G:0"), Some("AP:5G:0"), Some("UPLINK:5G:0")]
244 );
245 assert_eq!(
248 (r1.uplinks[0].rate_down, r1.uplinks[0].rate_up),
249 (Some(1), Some(2))
250 );
251 assert_eq!(
252 (r1.uplinks[1].rate_down, r1.uplinks[1].rate_up),
253 (Some(2), Some(1))
254 );
255 let json = serde_json::to_value(&tree[1]).unwrap();
256 assert_eq!(json["name"], "LOST");
257 assert!(json.get("children").is_none() && json.get("uid").is_none());
258 }
259}