Skip to main content

khive_runtime/operations/
entity_aliases.rs

1//! Caller aliases on entities (ADR-221 section 2).
2//!
3//! An alias is another exact name of an entity. A caller names aliases on
4//! `create`, changes them with `update(add_aliases, remove_aliases)`, and a
5//! keyed reload replaces them. Each alias row carries the origin that wrote
6//! it, and a caller request reaches caller-origin rows only.
7
8use std::collections::BTreeSet;
9
10use super::*;
11use khive_db::stores::entity::{
12    entity_alias_insert_statement, entity_caller_alias_delete_statement,
13    entity_name_alias_delete_statement,
14};
15use khive_storage::entity::{EntityAlias, EntityAliasOrigin};
16
17/// The refusal text for an empty alias, one over 512 UTF-8 bytes, or one
18/// holding U+0000.
19pub(crate) const ENTITY_ALIAS_REFUSAL: &str =
20    "alias must be non-empty, at most 512 UTF-8 bytes and must not contain U+0000";
21
22/// Validate one caller alias and scan its exact bytes with the secret gate.
23///
24/// Callers run this before any read, so a refused alias never reaches one.
25pub fn validate_entity_alias(alias: &str) -> RuntimeResult<()> {
26    if alias.is_empty() || alias.len() > 512 || alias.contains('\0') {
27        return Err(RuntimeError::InvalidInput(ENTITY_ALIAS_REFUSAL.into()));
28    }
29    crate::secret_gate::check_at(alias, "entity", "aliases")
30}
31
32fn validated_set(aliases: &[String]) -> RuntimeResult<BTreeSet<String>> {
33    for alias in aliases {
34        validate_entity_alias(alias)?;
35    }
36    Ok(aliases.iter().cloned().collect())
37}
38
39/// A change to an entity's caller-origin aliases, validated when it is made.
40#[derive(Clone, Debug, Default, PartialEq, Eq)]
41pub struct EntityAliasChange {
42    add: BTreeSet<String>,
43    remove: BTreeSet<String>,
44    replace: bool,
45    /// `keep_old_name: false`: a rename keeps no `rename` alias.
46    drop_old_name: bool,
47}
48
49impl EntityAliasChange {
50    /// `update(add_aliases, remove_aliases)`. One alias may not be both
51    /// added and removed by the same call.
52    pub fn update(add: &[String], remove: &[String]) -> RuntimeResult<Self> {
53        let add = validated_set(add)?;
54        let remove = validated_set(remove)?;
55        if let Some(both) = add.intersection(&remove).next() {
56            return Err(RuntimeError::InvalidInput(format!(
57                "alias {both:?} is both added and removed"
58            )));
59        }
60        Ok(Self {
61            add,
62            remove,
63            replace: false,
64            drop_old_name: false,
65        })
66    }
67
68    /// The entity's caller aliases become exactly `aliases`, as a create and
69    /// a keyed reload write them. Rename- and merge-origin aliases stay.
70    pub fn replace(aliases: &[String]) -> RuntimeResult<Self> {
71        Ok(Self {
72            add: validated_set(aliases)?,
73            remove: BTreeSet::new(),
74            replace: true,
75            drop_old_name: false,
76        })
77    }
78
79    /// `keep_old_name`: whether a write that renames the entity keeps the
80    /// old name as a `rename` alias (ADR-221 section 3). Kept by default.
81    pub fn keeping_old_name(mut self, keep: bool) -> Self {
82        self.drop_old_name = !keep;
83        self
84    }
85
86    /// Whether the change asks for nothing.
87    pub fn is_empty(&self) -> bool {
88        self.add.is_empty() && self.remove.is_empty() && !self.replace
89    }
90
91    /// The requested aliases equal to `name`, which are not stored.
92    pub fn not_stored(&self, name: &str) -> Vec<String> {
93        self.add
94            .iter()
95            .filter(|alias| *alias == name)
96            .cloned()
97            .collect()
98    }
99
100    /// The caller aliases an entity named `name` holds once a replacing
101    /// change is applied to it.
102    pub(crate) fn wanted(&self, name: &str) -> BTreeSet<&str> {
103        self.add
104            .iter()
105            .map(String::as_str)
106            .filter(|alias| *alias != name)
107            .collect()
108    }
109}
110
111/// What an alias change asked for and did not do.
112#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
113pub struct EntityAliasReport {
114    /// Requested aliases equal to the entity's name, which are not stored.
115    #[serde(skip_serializing_if = "Vec::is_empty")]
116    pub not_stored: Vec<String>,
117    /// Requested removals the entity holds no caller alias for. Aliases a
118    /// rename or a merge wrote are listed here too: a caller cannot remove
119    /// them.
120    #[serde(skip_serializing_if = "Vec::is_empty")]
121    pub not_removed: Vec<String>,
122}
123
124impl EntityAliasReport {
125    /// Whether every requested alias was stored or removed.
126    pub fn is_empty(&self) -> bool {
127        self.not_stored.is_empty() && self.not_removed.is_empty()
128    }
129}
130
131/// The caller-origin aliases `entity` holds.
132pub(crate) fn caller_alias_set(entity: &Entity) -> BTreeSet<&str> {
133    entity
134        .aliases
135        .iter()
136        .filter(|held| held.origin == EntityAliasOrigin::Caller)
137        .map(|held| held.alias.as_str())
138        .collect()
139}
140
141/// Apply `change` to `entity.aliases` once the entity's name is final, and
142/// return whether the aliases changed, the statements that write the change
143/// at time `at`, and what the change left out.
144///
145/// `previous_name` is the name the stored row had before this write, `None`
146/// for a row this write creates. When the write renames the entity, the old
147/// name becomes a `rename` alias unless the change drops it, the entity
148/// already holds it, or the old name is empty.
149///
150/// The projection is what the statements leave in `entity_aliases`, so the
151/// text and vector bodies built from `entity` index the aliases the stored
152/// row has.
153pub(crate) fn apply_entity_alias_change(
154    entity: &mut Entity,
155    change: &EntityAliasChange,
156    at: i64,
157    previous_name: Option<&str>,
158) -> (bool, Vec<SqlStatement>, EntityAliasReport) {
159    let before = entity.aliases.clone();
160    let mut report = EntityAliasReport {
161        not_stored: change.not_stored(&entity.name),
162        not_removed: Vec::new(),
163    };
164    let wanted: BTreeSet<String> = change
165        .wanted(&entity.name)
166        .into_iter()
167        .map(str::to_owned)
168        .collect();
169    let name = entity.name.clone();
170    // An alias never equals its entity's name: an entity renamed to an alias
171    // it holds loses that row, whatever wrote it. That delete is its own
172    // statement; the caller's removals reach caller-origin rows only.
173    let renamed_onto = entity.aliases.iter().any(|held| held.alias == name);
174    let held = caller_alias_set(entity);
175    let removed: Vec<String> = if change.replace {
176        held.iter()
177            .filter(|alias| !wanted.contains(**alias) && **alias != name)
178            .map(|alias| (*alias).to_owned())
179            .collect()
180    } else {
181        let (removed, not_removed): (Vec<String>, Vec<String>) =
182            change.remove.iter().cloned().partition(|alias| {
183                held.contains(alias.as_str()) || (renamed_onto && *alias == name)
184            });
185        report.not_removed = not_removed;
186        removed.into_iter().filter(|alias| *alias != name).collect()
187    };
188    let namespace = entity.namespace.clone();
189    let mut statements: Vec<SqlStatement> = removed
190        .iter()
191        .map(|alias| entity_caller_alias_delete_statement(&namespace, entity.id, alias))
192        .collect();
193    if renamed_onto {
194        statements.push(entity_name_alias_delete_statement(
195            &namespace, entity.id, &name,
196        ));
197    }
198    entity.aliases.retain(|held| {
199        held.alias != name
200            && (held.origin != EntityAliasOrigin::Caller || !removed.contains(&held.alias))
201    });
202    for alias in wanted {
203        if entity.aliases.iter().any(|held| held.alias == alias) {
204            continue;
205        }
206        statements.push(entity_alias_insert_statement(
207            &namespace,
208            entity.id,
209            &alias,
210            EntityAliasOrigin::Caller,
211            at,
212        ));
213        entity.aliases.push(EntityAlias {
214            alias,
215            origin: EntityAliasOrigin::Caller,
216        });
217    }
218    // ADR-221 section 3: a rename keeps the old name as a `rename` alias in
219    // the same transaction. A caller alias of that string named by this same
220    // change was written above and is left as it is.
221    if let Some(previous) =
222        previous_name.filter(|previous| *previous != name && !previous.is_empty())
223    {
224        if !change.drop_old_name && !entity.aliases.iter().any(|held| held.alias == previous) {
225            statements.push(entity_alias_insert_statement(
226                &namespace,
227                entity.id,
228                previous,
229                EntityAliasOrigin::Rename,
230                at,
231            ));
232            entity.aliases.push(EntityAlias {
233                alias: previous.to_owned(),
234                origin: EntityAliasOrigin::Rename,
235            });
236        }
237    }
238    entity.aliases.sort();
239    (entity.aliases != before, statements, report)
240}
241
242/// The `entity_updated` event payload. A write that renames the entity names
243/// the previous name and the new one, so the record's history keeps the old
244/// name even when no alias is kept (ADR-221 section 3).
245pub(crate) fn entity_updated_payload(
246    entity: &Entity,
247    changed_fields: &[&str],
248    previous_name: Option<&str>,
249) -> serde_json::Value {
250    let mut payload = serde_json::json!({
251        "id": entity.id,
252        "namespace": entity.namespace,
253        "changed_fields": changed_fields,
254    });
255    if let Some(previous) = previous_name.filter(|previous| *previous != entity.name) {
256        payload["previous_name"] = serde_json::Value::from(previous);
257        payload["name"] = serde_json::Value::from(entity.name.as_str());
258    }
259    payload
260}
261
262/// The statements as plan statements: an alias row affects one row or none,
263/// so none is guarded.
264pub(crate) fn unguarded(statements: Vec<SqlStatement>) -> impl Iterator<Item = PlanStatement> {
265    statements.into_iter().map(|statement| PlanStatement {
266        statement,
267        guard: None,
268    })
269}
270
271#[cfg(test)]
272#[path = "entity_aliases_tests.rs"]
273mod tests;