use std::collections::{BTreeMap, BTreeSet};
pub use khive_types::Id128;
use serde::Serialize;
use serde_json::Value;
mod parse;
pub use parse::DiffInputError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Substrate {
Entity,
Edge,
Note,
}
impl Substrate {
pub const fn identity_field(self) -> &'static str {
match self {
Self::Entity | Self::Note => "id",
Self::Edge => "edge_id",
}
}
}
impl std::fmt::Display for Substrate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Entity => "entity",
Self::Edge => "edge",
Self::Note => "note",
})
}
}
pub type Fields = BTreeMap<String, Value>;
type Records = BTreeMap<Id128, Fields>;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GraphState {
entities: Records,
edges: Records,
notes: Records,
}
impl GraphState {
pub fn from_ndjson(entities: &str, edges: &str, notes: &str) -> Result<Self, DiffInputError> {
Ok(Self {
entities: parse::records(entities, Substrate::Entity)?,
edges: parse::records(edges, Substrate::Edge)?,
notes: parse::records(notes, Substrate::Note)?,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Record {
pub id: Id128,
pub fields: Fields,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FieldChange {
pub field: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub before: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub after: Option<Value>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ModifiedRecord {
pub id: Id128,
pub changes: Vec<FieldChange>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct SubstrateDiff {
pub added: Vec<Record>,
pub removed: Vec<Record>,
pub modified: Vec<ModifiedRecord>,
}
impl SubstrateDiff {
pub fn is_empty(&self) -> bool {
self.added.is_empty() && self.removed.is_empty() && self.modified.is_empty()
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct GraphDiff {
pub entities: SubstrateDiff,
pub edges: SubstrateDiff,
pub notes: SubstrateDiff,
}
impl GraphDiff {
pub fn is_empty(&self) -> bool {
self.entities.is_empty() && self.edges.is_empty() && self.notes.is_empty()
}
}
pub fn diff(before: &GraphState, after: &GraphState) -> GraphDiff {
GraphDiff {
entities: diff_records(&before.entities, &after.entities),
edges: diff_records(&before.edges, &after.edges),
notes: diff_records(&before.notes, &after.notes),
}
}
fn diff_records(before: &Records, after: &Records) -> SubstrateDiff {
let mut result = SubstrateDiff::default();
for (&id, fields) in before {
let Some(next) = after.get(&id) else {
result.removed.push(Record {
id,
fields: fields.clone(),
});
continue;
};
let keys: BTreeSet<_> = fields.keys().chain(next.keys()).collect();
let changes: Vec<_> = keys
.into_iter()
.filter_map(|field| {
let old = fields.get(field);
let new = next.get(field);
if old != new {
Some(FieldChange {
field: field.clone(),
before: old.cloned(),
after: new.cloned(),
})
} else {
None
}
})
.collect();
if !changes.is_empty() {
result.modified.push(ModifiedRecord { id, changes });
}
}
for (&id, fields) in after {
if !before.contains_key(&id) {
result.added.push(Record {
id,
fields: fields.clone(),
});
}
}
result
}