Add function for parsing topology messages.

This commit is contained in:
Joe Ardent 2025-09-17 12:55:23 -07:00
parent 067a03b918
commit c7f3c21fd0

View file

@ -1,5 +1,5 @@
use std::{
collections::HashMap,
collections::{BTreeMap, HashMap},
io::{BufRead, Write},
sync::{
Arc, Mutex, OnceLock,
@ -20,6 +20,7 @@ pub type NodeyNodeFace = Arc<Mutex<dyn Node>>;
pub type OnInit = Box<dyn Fn(&Runner)>;
pub type RpcFuture = Receiver<Message>;
pub type RpcResult = std::result::Result<Option<Value>, ErrorCode>;
pub type Topology = BTreeMap<String, Vec<String>>;
pub trait Node {
fn handle(&mut self, runner: &Runner, msg: Message);
@ -224,9 +225,43 @@ pub fn check_err(msg: &Message) -> RpcResult {
Ok(None)
}
/// Convenience function for turning a list of `(&str, serde::Value)` pairs into
/// a Payload.
pub fn mk_payload(payload: &[(&str, Value)]) -> Payload {
payload
.iter()
.map(|p| (p.0.to_string(), p.1.clone()))
.collect()
}
/// Convenience function for turning a `topology` message into a map of node ->
/// neighbors (String -> Vec<String>).
pub fn parse_toplogy(msg: &Message) -> Option<Topology> {
if msg.typ() != "topology" {
return None;
}
let topology = msg
.body
.payload
.get("topology")
.unwrap()
.as_object()
.cloned()
.unwrap();
Some(
topology
.into_iter()
.map(|(node, neighbors)| {
(
node,
neighbors
.as_array()
.unwrap()
.iter()
.map(|neighbor| neighbor.as_str().unwrap().to_string())
.collect(),
)
})
.collect(),
)
}