Skip to main content

khive_changeset/
record.rs

1//! A whole entity as a change set carries it (ADR-221 section 4).
2
3use khive_types::{Entity, EntityAlias};
4use serde::{Deserialize, Deserializer, Serialize};
5
6use crate::strict::StrictEntity;
7
8/// An entity with the caller keys it holds and its aliases.
9///
10/// Every change-set carrier that copies a whole entity uses this record: a
11/// delete preimage, a restore record, both sides of a merge preimage, and the
12/// current entities an inversion reads. `keys` are the caller keys the entity
13/// holds under its own kind; `aliases` are its aliases with the origin that
14/// wrote each one. A change set is a trusted carrier for origins, with the same
15/// standing as an archive: they are written as given.
16///
17/// Both lists are omitted from the wire when empty, so an entity that holds
18/// neither serializes exactly as the bare entity record. Comparisons read each
19/// list as a set; see [`EntityRecord::same_names`]. A record that names one
20/// key or one alias twice, whatever the origins, is refused when it is read.
21#[derive(Clone, Debug, Serialize)]
22pub struct EntityRecord {
23    /// The entity row.
24    #[serde(flatten)]
25    pub entity: Entity,
26    /// Caller keys the entity holds under its kind.
27    #[serde(skip_serializing_if = "Vec::is_empty")]
28    pub keys: Vec<String>,
29    /// Aliases the entity holds, with their origins.
30    #[serde(skip_serializing_if = "Vec::is_empty")]
31    pub aliases: Vec<EntityAlias>,
32}
33
34impl EntityRecord {
35    /// A record of `entity` holding no keys and no aliases.
36    pub fn new(entity: Entity) -> Self {
37        Self {
38            entity,
39            keys: Vec::new(),
40            aliases: Vec::new(),
41        }
42    }
43
44    /// Whether both records hold the same keys and the same aliases with the
45    /// same origins, each read as a set.
46    pub fn same_names(&self, other: &Self) -> bool {
47        same_set(&self.keys, &other.keys) && same_set(&self.aliases, &other.aliases)
48    }
49}
50
51impl From<Entity> for EntityRecord {
52    fn from(entity: Entity) -> Self {
53        Self::new(entity)
54    }
55}
56
57impl<'de> Deserialize<'de> for EntityRecord {
58    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
59    where
60        D: Deserializer<'de>,
61    {
62        StrictEntity::deserialize(deserializer)?
63            .try_into()
64            .map_err(serde::de::Error::custom)
65    }
66}
67
68/// Whether two lists hold the same elements, order aside. A list holding an
69/// element twice equals no list holding it once.
70pub(crate) fn same_set<T: Ord + Clone>(first: &[T], second: &[T]) -> bool {
71    if first.len() != second.len() {
72        return false;
73    }
74    let mut first = first.to_vec();
75    let mut second = second.to_vec();
76    first.sort();
77    second.sort();
78    first == second
79}
80
81/// The first name a list holds twice.
82pub(crate) fn repeated<'a>(names: impl IntoIterator<Item = &'a str>) -> Option<&'a str> {
83    let mut seen = std::collections::BTreeSet::new();
84    names.into_iter().find(|name| !seen.insert(*name))
85}