use std::io::Read;
use serde_json::{Map, Value};
pub(crate) struct GraphNode {
pub(crate) id: String,
pub(crate) ids: Vec<String>,
pub(crate) sources: Vec<String>,
pub(crate) rest: Map<String, Value>,
}
pub(crate) struct GraphEdge {
pub(crate) from: String,
pub(crate) to: String,
pub(crate) relation: String,
pub(crate) sources: Vec<String>,
pub(crate) rest: Map<String, Value>,
}
pub(crate) struct GraphReader {
pub(crate) nodes: Vec<GraphNode>,
pub(crate) edges: Vec<GraphEdge>,
pub(crate) sources: Vec<String>,
pub(crate) rest: Map<String, Value>,
}
impl GraphReader {
pub(crate) fn read(mut reader: impl Read) -> Result<Self, String> {
let mut body = Vec::new();
reader
.read_to_end(&mut body)
.map_err(|error| error.to_string())?;
let parsed: Value = serde_json::from_slice(&body).map_err(|error| error.to_string())?;
let Value::Object(mut fields) = parsed else {
return Err("a knowledge graph is a JSON object with `nodes` and `edges`".to_owned());
};
let nodes = fields
.remove("nodes")
.ok_or_else(|| "no `nodes` array: a knowledge graph needs one".to_owned())?;
let edges = fields
.remove("edges")
.ok_or_else(|| "no `edges` array: a knowledge graph needs one".to_owned())?;
let sources = match fields.remove("sources") {
Some(value) => names(&value, "the graph's `sources`")?,
None => Vec::new(),
};
Ok(Self {
nodes: array("nodes", nodes)?
.into_iter()
.map(node)
.collect::<Result<_, _>>()?,
edges: array("edges", edges)?
.into_iter()
.map(edge)
.collect::<Result<_, _>>()?,
sources,
rest: fields,
})
}
pub(crate) fn every_source(&self) -> Vec<&str> {
self.sources
.iter()
.chain(self.nodes.iter().flat_map(|node| node.sources.iter()))
.chain(self.edges.iter().flat_map(|edge| edge.sources.iter()))
.map(String::as_str)
.collect()
}
}
fn array(key: &str, value: Value) -> Result<Vec<Value>, String> {
match value {
Value::Array(items) => Ok(items),
_ => Err(format!("`{key}` is not an array")),
}
}
fn object(key: &str, value: Value) -> Result<Map<String, Value>, String> {
match value {
Value::Object(fields) => Ok(fields),
_ => Err(format!("an entry of `{key}` is not an object")),
}
}
fn string(fields: &mut Map<String, Value>, key: &str, what: &str) -> Result<String, String> {
match fields.remove(key) {
Some(Value::String(found)) if !found.trim().is_empty() => Ok(found.trim().to_owned()),
Some(_) => Err(format!("{what} has a `{key}` that is not a name")),
None => Err(format!("{what} has no `{key}`")),
}
}
fn names(value: &Value, what: &str) -> Result<Vec<String>, String> {
let Value::Array(items) = value else {
return Err(format!("{what} is not an array"));
};
items
.iter()
.map(|item| match item {
Value::String(found) => Ok(found.trim().to_owned()),
_ => Err(format!("{what} holds something that is not a name")),
})
.collect()
}
fn optional_names(
fields: &mut Map<String, Value>,
key: &str,
what: &str,
) -> Result<Vec<String>, String> {
match fields.remove(key) {
Some(value) => names(&value, &format!("{what}'s `{key}`")),
None => Ok(Vec::new()),
}
}
fn node(value: Value) -> Result<GraphNode, String> {
let mut fields = object("nodes", value)?;
let id = string(&mut fields, "id", "a node")?;
let ids = optional_names(&mut fields, "ids", "a node")?;
let sources = optional_names(&mut fields, "sources", "a node")?;
Ok(GraphNode {
id,
ids,
sources,
rest: fields,
})
}
fn edge(value: Value) -> Result<GraphEdge, String> {
let mut fields = object("edges", value)?;
let from = string(&mut fields, "source", "an edge")?;
let to = string(&mut fields, "target", "an edge")?;
let relation = string(&mut fields, "type", "an edge")?;
let sources = optional_names(&mut fields, "sources", "an edge")?;
Ok(GraphEdge {
from,
to,
relation,
sources,
rest: fields,
})
}