Skip to main content

khive_changeset/
preimage.rs

1//! Field-scoped comparison against the record visible to an applying writer.
2
3use khive_types::{Entity, Header, Link, Note};
4
5use crate::record::same_set;
6use crate::{
7    DeleteOp, DeletePreimage, EdgePreimage, EntityPreimage, EntityRecord, NotePreimage, UpdateOp,
8    UpdatePreimage,
9};
10
11#[derive(Clone, Copy, Debug)]
12/// A caller-supplied record from the applying transaction, without a storage handle.
13///
14/// An entity is read whole, with the keys it holds and its aliases.
15pub enum CanonicalRecordRef<'a> {
16    Entity(&'a EntityRecord),
17    Note(&'a Note),
18    Edge(&'a Link),
19}
20
21#[derive(Clone, Debug, PartialEq, Eq)]
22/// A stable field path without captured or current record contents.
23pub struct PreimageMismatch {
24    pub field_path: String,
25}
26
27impl std::fmt::Display for PreimageMismatch {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        write!(f, "captured preimage differs at {}", self.field_path)
30    }
31}
32
33impl std::error::Error for PreimageMismatch {}
34
35fn equal<T: PartialEq + ?Sized>(
36    field: &str,
37    captured: &T,
38    live: &T,
39) -> Result<(), PreimageMismatch> {
40    if captured == live {
41        Ok(())
42    } else {
43        Err(PreimageMismatch {
44            field_path: field.into(),
45        })
46    }
47}
48
49/// Two lists compared as sets: a carried set may list its members in any order.
50fn equal_set<T: Ord + Clone>(
51    field: &str,
52    captured: &[T],
53    live: &[T],
54) -> Result<(), PreimageMismatch> {
55    if same_set(captured, live) {
56        Ok(())
57    } else {
58        Err(PreimageMismatch {
59            field_path: field.into(),
60        })
61    }
62}
63
64fn touched<T: PartialEq>(
65    field: &str,
66    captured: &Option<T>,
67    live: &T,
68) -> Result<(), PreimageMismatch> {
69    match captured {
70        Some(captured) => equal(field, captured, live),
71        None => Ok(()),
72    }
73}
74
75/// The caller must read `live` inside the same transaction that applies `op`.
76pub fn check_update(op: &UpdateOp, live: CanonicalRecordRef<'_>) -> Result<(), PreimageMismatch> {
77    match (op.preimage(), live) {
78        (UpdatePreimage::Entity(preimage), CanonicalRecordRef::Entity(record)) => {
79            let live = &record.entity;
80            equal("id", &op.target_id(), &live.header.id)?;
81            let EntityPreimage {
82                name,
83                description,
84                properties,
85                tags,
86                entity_type,
87                aliases,
88            } = preimage;
89            touched("name", name, &live.name)?;
90            touched("description", description, &live.description)?;
91            touched("properties", properties, &live.properties)?;
92            touched("tags", tags, &live.tags)?;
93            touched("entity_type", entity_type, &live.entity_type)?;
94            match aliases {
95                Some(aliases) => equal_set("aliases", aliases, &record.aliases),
96                None => Ok(()),
97            }
98        }
99        (UpdatePreimage::Note(preimage), CanonicalRecordRef::Note(live)) => {
100            equal("id", &op.target_id(), &live.header.id)?;
101            let NotePreimage {
102                content,
103                salience,
104                decay_factor,
105                properties,
106                tags,
107            } = preimage;
108            touched("content", content, &live.content)?;
109            touched("salience", salience, &live.salience)?;
110            touched("decay_factor", decay_factor, &live.decay_factor)?;
111            touched("properties", properties, &live.properties)?;
112            touched("tags", tags, &live.tags)
113        }
114        (UpdatePreimage::Edge(preimage), CanonicalRecordRef::Edge(live)) => {
115            equal("id", &op.target_id(), &live.id)?;
116            let EdgePreimage { relation, weight } = preimage;
117            touched("relation", relation, &live.relation)?;
118            touched("weight", weight, &live.weight)
119        }
120        _ => Err(PreimageMismatch {
121            field_path: "substrate".into(),
122        }),
123    }
124}
125
126fn header(captured: &Header, live: &Header) -> Result<(), PreimageMismatch> {
127    let Header {
128        id,
129        namespace,
130        created_at,
131        updated_at: _,
132    } = captured;
133    equal("id", id, &live.id)?;
134    equal("namespace", namespace, &live.namespace)?;
135    equal("created_at", created_at, &live.created_at)
136}
137
138/// The captured record is exact except for its applier-stamped `updated_at`.
139/// An entity's keys and aliases are compared as sets.
140pub fn check_delete(op: &DeleteOp, live: CanonicalRecordRef<'_>) -> Result<(), PreimageMismatch> {
141    match (&op.preimage, live) {
142        (DeletePreimage::Entity(captured_record), CanonicalRecordRef::Entity(live_record)) => {
143            let live = &live_record.entity;
144            equal("id", &op.target_id, &live.header.id)?;
145            let Entity {
146                header: captured_header,
147                kind,
148                entity_type,
149                name,
150                description,
151                properties,
152                tags,
153                deleted_at,
154            } = &captured_record.entity;
155            header(captured_header, &live.header)?;
156            equal("kind", kind, &live.kind)?;
157            equal("entity_type", entity_type, &live.entity_type)?;
158            equal("name", name, &live.name)?;
159            equal("description", description, &live.description)?;
160            equal("properties", properties, &live.properties)?;
161            equal("tags", tags, &live.tags)?;
162            equal("deleted_at", deleted_at, &live.deleted_at)?;
163            equal_set("keys", &captured_record.keys, &live_record.keys)?;
164            equal_set("aliases", &captured_record.aliases, &live_record.aliases)
165        }
166        (DeletePreimage::Note(captured), CanonicalRecordRef::Note(live)) => {
167            equal("id", &op.target_id, &live.header.id)?;
168            let Note {
169                header: captured_header,
170                kind,
171                status,
172                content,
173                properties,
174                tags,
175                salience,
176                decay_factor,
177                expires_at,
178                deleted_at,
179            } = captured.as_ref();
180            header(captured_header, &live.header)?;
181            equal("kind", kind, &live.kind)?;
182            equal("status", status, &live.status)?;
183            equal("content", content, &live.content)?;
184            equal("properties", properties, &live.properties)?;
185            equal("tags", tags, &live.tags)?;
186            equal("salience", salience, &live.salience)?;
187            equal("decay_factor", decay_factor, &live.decay_factor)?;
188            equal("expires_at", expires_at, &live.expires_at)?;
189            equal("deleted_at", deleted_at, &live.deleted_at)
190        }
191        (DeletePreimage::Edge(captured), CanonicalRecordRef::Edge(live)) => {
192            equal("id", &op.target_id, &live.id)?;
193            let Link {
194                id,
195                namespace,
196                source,
197                target,
198                relation,
199                properties,
200                weight,
201                created_at,
202                updated_at: _,
203                deleted_at,
204            } = captured.as_ref();
205            equal("id", id, &live.id)?;
206            equal("namespace", namespace, &live.namespace)?;
207            equal("source", source, &live.source)?;
208            equal("target", target, &live.target)?;
209            equal("relation", relation, &live.relation)?;
210            equal("properties", properties, &live.properties)?;
211            equal("weight", weight, &live.weight)?;
212            equal("created_at", created_at, &live.created_at)?;
213            equal("deleted_at", deleted_at, &live.deleted_at)
214        }
215        _ => Err(PreimageMismatch {
216            field_path: "substrate".into(),
217        }),
218    }
219}
220
221#[cfg(test)]
222#[path = "preimage_tests.rs"]
223mod tests;