Skip to main content

khive_graph_diff/
parse.rs

1use std::collections::{btree_map::Entry, BTreeMap};
2
3use khive_types::ParseIdError;
4use serde_json::Value;
5
6use crate::{Id128, Records, Substrate};
7
8/// Input refusal with the substrate and one-based physical NDJSON line.
9#[derive(Debug, thiserror::Error)]
10pub enum DiffInputError {
11    #[error("{substrate} line {line}: invalid JSON: {source}")]
12    InvalidJson {
13        substrate: Substrate,
14        line: usize,
15        #[source]
16        source: serde_json::Error,
17    },
18    #[error("{substrate} line {line}: expected a JSON object")]
19    NotObject { substrate: Substrate, line: usize },
20    #[error("{substrate} line {line}: missing identity field {field}")]
21    MissingIdentity {
22        substrate: Substrate,
23        line: usize,
24        field: &'static str,
25    },
26    #[error("{substrate} line {line}: identity field {field} must be a string")]
27    NonStringIdentity {
28        substrate: Substrate,
29        line: usize,
30        field: &'static str,
31    },
32    #[error("{substrate} line {line}: invalid identity: {source}")]
33    InvalidIdentity {
34        substrate: Substrate,
35        line: usize,
36        #[source]
37        source: ParseIdError,
38    },
39    #[error("{substrate} line {line}: duplicate identity {id}")]
40    DuplicateIdentity {
41        substrate: Substrate,
42        line: usize,
43        id: Id128,
44    },
45}
46
47pub(crate) fn records(input: &str, substrate: Substrate) -> Result<Records, DiffInputError> {
48    let mut records = Records::new();
49    for (offset, text) in input.lines().enumerate() {
50        if text.trim().is_empty() {
51            continue;
52        }
53        let line = offset + 1;
54        let value: Value =
55            serde_json::from_str(text).map_err(|source| DiffInputError::InvalidJson {
56                substrate,
57                line,
58                source,
59            })?;
60        let Value::Object(mut fields) = value else {
61            return Err(DiffInputError::NotObject { substrate, line });
62        };
63        let field = substrate.identity_field();
64        let identity = fields
65            .remove(field)
66            .ok_or(DiffInputError::MissingIdentity {
67                substrate,
68                line,
69                field,
70            })?;
71        let Value::String(identity) = identity else {
72            return Err(DiffInputError::NonStringIdentity {
73                substrate,
74                line,
75                field,
76            });
77        };
78        let id = identity
79            .parse()
80            .map_err(|source| DiffInputError::InvalidIdentity {
81                substrate,
82                line,
83                source,
84            })?;
85        let Entry::Vacant(entry) = records.entry(id) else {
86            return Err(DiffInputError::DuplicateIdentity {
87                substrate,
88                line,
89                id,
90            });
91        };
92        entry.insert(
93            fields
94                .into_iter()
95                .map(|(key, value)| (key, canonical_value(value)))
96                .collect(),
97        );
98    }
99    Ok(records)
100}
101
102// Reinsert sorted keys even when serde_json's globally additive preserve_order
103// feature is enabled. Arrays keep their order and all scalar types are retained.
104fn canonical_value(value: Value) -> Value {
105    match value {
106        Value::Object(fields) => {
107            let sorted: BTreeMap<_, _> = fields.into_iter().collect();
108            Value::Object(
109                sorted
110                    .into_iter()
111                    .map(|(key, value)| (key, canonical_value(value)))
112                    .collect(),
113            )
114        }
115        Value::Array(values) => Value::Array(values.into_iter().map(canonical_value).collect()),
116        scalar => scalar,
117    }
118}