use arora_types::call::Call;
use arora_types::value::StructureField;
use arora_types::value_serde;
use serde::de::DeserializeOwned;
use serde::Serialize;
use uuid::{uuid, Uuid};
use crate::graph::{Graph, GraphDiff};
pub const ID: Uuid = uuid!("61726f72-6100-0000-0000-000000000001");
pub const EDIT: Uuid = uuid!("61726f72-6100-0000-0000-000000000002");
pub const EDIT_ARG: Uuid = uuid!("61726f72-6100-0000-0000-000000000003");
pub const LOAD: Uuid = uuid!("61726f72-6100-0000-0000-000000000004");
pub const LOAD_ARG: Uuid = uuid!("61726f72-6100-0000-0000-000000000005");
pub fn encode_edit(diff: &GraphDiff) -> Call {
encode(EDIT, EDIT_ARG, diff)
}
pub fn decode_edit(call: &Call) -> Result<GraphDiff, String> {
decode(call, EDIT, EDIT_ARG, "GraphDiff")
}
pub fn encode_load(graph: &Graph) -> Call {
encode(LOAD, LOAD_ARG, graph)
}
pub fn decode_load(call: &Call) -> Result<Graph, String> {
decode(call, LOAD, LOAD_ARG, "Graph")
}
fn encode<T: Serialize>(function: Uuid, arg: Uuid, payload: &T) -> Call {
let value = value_serde::to_value(payload).expect("a graph payload converts to a Value");
Call {
module_id: Some(ID),
id: function,
args: vec![StructureField {
id: arg,
value: Box::new(value),
}],
}
}
fn decode<T: DeserializeOwned>(
call: &Call,
function: Uuid,
arg: Uuid,
what: &str,
) -> Result<T, String> {
if call.id != function {
return Err(format!(
"not the expected interpreter function: {}",
call.id
));
}
let field = call
.args
.iter()
.find(|field| field.id == arg)
.ok_or_else(|| format!("the call is missing its {what} argument"))?;
value_serde::from_value(field.value.as_ref().clone())
.map_err(|e| format!("malformed {what}: {e}"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn edit_call_round_trips_the_diff() {
let diff = GraphDiff {
remove_nodes: vec![Uuid::from_u128(7)],
set_root: Some(Uuid::from_u128(9)),
..Default::default()
};
let call = encode_edit(&diff);
assert_eq!(call.module_id, Some(ID));
assert_eq!(call.id, EDIT);
assert_eq!(decode_edit(&call).unwrap(), diff);
}
#[test]
fn load_call_round_trips_the_graph() {
let mut graph = Graph::empty();
graph.root = Some(Uuid::from_u128(3));
let call = encode_load(&graph);
assert_eq!(call.module_id, Some(ID));
assert_eq!(call.id, LOAD);
assert_eq!(decode_load(&call).unwrap(), graph);
}
#[test]
fn decode_rejects_malformed_calls() {
let mut call = encode_edit(&GraphDiff::default());
call.id = Uuid::from_u128(1);
assert!(decode_edit(&call).is_err());
let mut call = encode_edit(&GraphDiff::default());
call.args.clear();
assert!(decode_edit(&call).is_err());
let mut call = encode_edit(&GraphDiff::default());
call.args[0].value = Box::new(arora_types::value::Value::Boolean(true));
assert!(decode_edit(&call).is_err());
let mut call = encode_load(&Graph::empty());
call.args[0].value = Box::new(arora_types::value::Value::String("not a graph".to_string()));
assert!(decode_load(&call).is_err());
}
}