1use std::collections::HashSet;
6use std::fmt;
7use crate::sidecar_value::{DocumentValue as Value, JsString};
8use crate::sidecar_json;
9pub use crate::sidecar_parse::parse_ordered_json;
10use crate::sidecar_validation::{validate_identity_document, validate_lineage_document};
11
12#[derive(Debug, Clone, Copy)]
13pub enum SidecarKind { Identity, Lineage }
14impl SidecarKind {
15 fn format(self) -> &'static str { match self { Self::Identity => "ifc-lite/identity-map", Self::Lineage => "ifc-lite/lineage" } }
16 fn label(self) -> &'static str { match self { Self::Identity => "identity-map", Self::Lineage => "lineage" } }
17}
18#[derive(Debug)]
21pub struct SidecarDocumentError { message: JsString }
22impl SidecarDocumentError {
23 pub fn to_json(&self) -> String { serialize_sidecar(&Value::String(self.message.clone())) }
24 fn validation(kind: SidecarKind, errors: Vec<JsString>) -> Self {
25 let mut units: Vec<_> = format!("Invalid {} sidecar: ", kind.label()).encode_utf16().collect();
26 for (index, error) in errors.iter().enumerate() {
27 if index > 0 { units.extend("; ".encode_utf16()); }
28 units.extend_from_slice(error.units());
29 }
30 Self { message: JsString::from_units(units) }
31 }
32}
33impl fmt::Display for SidecarDocumentError {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.message, f) }
35}
36impl std::error::Error for SidecarDocumentError {}
37fn errors(value: &Value, kind: SidecarKind, valid_date: impl Fn(&str) -> bool) -> Vec<JsString> {
38 match kind { SidecarKind::Identity => validate_identity_document(value, valid_date),
39 SidecarKind::Lineage => validate_lineage_document(value, valid_date) }
40}
41fn validate(value: &Value, kind: SidecarKind, valid_date: impl Fn(&str) -> bool) -> Result<(), SidecarDocumentError> {
42 let errors = errors(value, kind, valid_date);
43 if errors.is_empty() { Ok(()) } else { Err(SidecarDocumentError::validation(kind, errors)) }
44}
45pub fn validate_sidecar_document(value: &Value, kind: SidecarKind, valid_date: impl Fn(&str) -> bool) -> Value {
47 Value::Array(errors(value, kind, valid_date).into_iter().map(Value::String).collect())
48}
49fn select(value: &Value, required: &[&str], optional: &[&str]) -> Value {
50 let mut fields: Vec<_> = required.iter().map(|&key| (key.into(), value[key].clone())).collect();
51 fields.extend(optional.iter().filter_map(|&key| value.get(key).map(|v| (key.into(), v.clone()))));
52 Value::Object(fields)
53}
54fn key(value: &Value) -> &[u16] { value.as_string().map(JsString::units).unwrap_or(&[]) }
55fn keys(value: &Value) -> Vec<Vec<u16>> {
56 value.as_array().into_iter().flatten().map(|item| key(item).to_vec()).collect()
57}
58pub fn create_sidecar(init: &serde_json::Value, kind: SidecarKind, valid_date: impl Fn(&str) -> bool) -> Result<Value, String> {
60 create_sidecar_document(&init.into(), kind, valid_date).map_err(|error| error.to_string())
61}
62pub fn create_sidecar_document(init: &Value, kind: SidecarKind, valid_date: impl Fn(&str) -> bool) -> Result<Value, SidecarDocumentError> {
64 let lineage = matches!(kind, SidecarKind::Lineage);
65 let Some(input) = init["entries"].as_array() else {
66 return Err(SidecarDocumentError { message: format!("Invalid {} sidecar: entries must be an array", kind.label()).into() });
67 };
68 let mut seen = HashSet::new();
69 let mut entries = vec![];
70 for entry in input {
71 let signature = if lineage {
74 (key(&entry["relation"]).to_vec(), keys(&entry["base"]), keys(&entry["head"]))
75 } else {
76 (key(&entry["base"]).to_vec(), vec![key(&entry["here"]).to_vec()], vec![])
77 };
78 if !seen.insert(signature) { continue; }
79 entries.push(if lineage { select(entry, &["base", "head", "relation", "reason"], &["shares"]) }
80 else { select(entry, &["base", "here", "reason"], &[]) });
81 }
82 entries.sort_by(|a, b| {
83 let (ab, bb, ah, bh) = if lineage { (&a["base"][0], &b["base"][0], &a["head"][0], &b["head"][0]) }
84 else { (&a["base"], &b["base"], &a["here"], &b["here"]) };
85 key(ab).cmp(key(bb)).then_with(|| key(ah).cmp(key(bh)))
86 });
87 let mut fields = vec![
88 ("format".into(), Value::String(kind.format().into())),
89 ("version".into(), Value::Number(if init.get("keyProperty").is_some() { 2.0 } else { 1.0 })),
90 ("base".into(), select(&init["base"], &["hash"], &["path"])),
91 ("head".into(), select(&init["head"], &["hash"], &["path"])),
92 ("entries".into(), Value::Array(entries)),
93 ];
94 if lineage {
95 let mut seen = HashSet::new();
96 let mut deleted: Vec<_> = init["deleted"].as_array().into_iter().flatten()
97 .filter(|v| v.as_string().is_none_or(|s| seen.insert(s.clone()))).cloned().collect();
98 deleted.sort_by(|a, b| key(a).cmp(key(b)));
99 fields.push(("deleted".into(), Value::Array(deleted)));
100 }
101 for field in ["created", "keyProperty"] { if let Some(value) = init.get(field) { fields.push((field.into(), value.clone())); } }
102 let result = Value::Object(fields);
103 validate(&result, kind, valid_date)?;
104 Ok(result)
105}
106pub fn parse_sidecar(text: &str, kind: SidecarKind, valid_date: impl Fn(&str) -> bool) -> Result<Value, String> {
108 let value = parse_ordered_json(text).map_err(|e| format!("Invalid {} sidecar: not JSON ({e})", kind.label()))?;
109 validate(&value, kind, valid_date).map_err(|error| error.to_string())?;
110 Ok(value)
111}
112pub fn serialize_sidecar(value: &Value) -> String { sidecar_json::serialize(value) }