Skip to main content

khive_runtime/portability/
names.rs

1//! Keys and aliases on archive entities (ADR-221 section 4).
2//!
3//! The portable archive and the NDJSON snapshot carry each entity's held
4//! keys, as plain strings under the entity's own kind, and its aliases with
5//! the origin that wrote each. Importing an archive over an entity that is
6//! already stored adds what the archive carries and removes nothing.
7
8use std::collections::{hash_map::Entry, BTreeSet, HashMap};
9
10use khive_db::stores::entity::{
11    entity_alias_insert_statement, entity_key_claim_statement, entity_name_alias_delete_statement,
12    entity_upsert_statement, ENTITY_KEY_HOLDER_SQL, NAMESPACE_KEY_ROWS_SQL,
13};
14use khive_storage::entity::EntityAlias;
15use khive_storage::types::SqlRow;
16use khive_storage::{Entity, SqlStatement, SqlValue};
17use khive_types::KhiveError;
18use uuid::Uuid;
19
20use crate::atomic_plan::{AffectedRowGuard, PlanStatement};
21use crate::atomic_runner::{
22    run_prepared_atomic_unit, PreparedAtomicError, PreparedAtomicOp, PreparedAtomicOutcome,
23};
24use crate::{KhiveRuntime, NamespaceToken, RuntimeError, RuntimeResult};
25
26/// Validate the keys and aliases one archive entity carries, before any
27/// read: each key and each alias as a caller write validates it, none listed
28/// twice, and no alias equal to the entity's name.
29pub fn validate_entity_names(
30    id: Uuid,
31    name: &str,
32    keys: &[String],
33    aliases: &[EntityAlias],
34) -> RuntimeResult<()> {
35    let mut seen_keys = BTreeSet::new();
36    for key in keys {
37        crate::operations::validate_entity_key(key)?;
38        if !seen_keys.insert(key.as_str()) {
39            return Err(RuntimeError::InvalidInput(format!(
40                "archive entity {id} lists key {key:?} more than once"
41            )));
42        }
43    }
44    let mut seen_aliases = BTreeSet::new();
45    for alias in aliases {
46        crate::operations::validate_entity_alias(&alias.alias)?;
47        if alias.alias == name {
48            return Err(RuntimeError::InvalidInput(format!(
49                "archive entity {id} lists its own name as an alias"
50            )));
51        }
52        if !seen_aliases.insert(alias.alias.as_str()) {
53            return Err(RuntimeError::InvalidInput(format!(
54                "archive entity {id} lists alias {:?} more than once",
55                alias.alias
56            )));
57        }
58    }
59    Ok(())
60}
61
62/// Refuse an archive in which two entities carry the same key under the same
63/// kind. Each item is one entity's id, kind and keys.
64pub fn validate_archive_key_uniqueness<'a, I>(entities: I) -> RuntimeResult<()>
65where
66    I: IntoIterator<Item = (Uuid, &'a str, &'a [String])>,
67{
68    let mut holders = HashMap::<(&'a str, &'a str), Uuid>::new();
69    for (id, kind, keys) in entities {
70        for key in keys {
71            match holders.entry((kind, key.as_str())) {
72                Entry::Occupied(first) if *first.get() != id => {
73                    return Err(RuntimeError::InvalidInput(format!(
74                        "archive entities {} and {id} both carry {kind} key {key:?}",
75                        first.get()
76                    )));
77                }
78                Entry::Occupied(_) => {}
79                Entry::Vacant(slot) => {
80                    slot.insert(id);
81                }
82            }
83        }
84    }
85    Ok(())
86}
87
88/// `import_key_conflict`: archive entity `entity_id` carries `key` under
89/// `kind`, and another live entity holds it. The holder is not named.
90pub fn import_key_conflict(entity_id: Uuid, kind: &str, key: &str) -> RuntimeError {
91    KhiveError::conflict(format!(
92        "import_key_conflict: archive entity {entity_id} carries {kind} key {key:?}, \
93         which another live entity holds"
94    ))
95    .with_details(khive_types::Details::new_owned([
96        ("reason", "import_key_conflict".to_string()),
97        ("entity_id", entity_id.to_string()),
98        ("kind", kind.to_owned()),
99        ("key", key.to_owned()),
100    ]))
101    .into()
102}
103
104fn column_error(error: impl std::fmt::Display) -> RuntimeError {
105    RuntimeError::Internal(format!("read entity keys: {error}"))
106}
107
108/// The read of the entity holding `key` under `kind`, if any.
109pub(super) fn key_holder_statement(namespace: &str, kind: &str, key: &str) -> SqlStatement {
110    SqlStatement::new(
111        ENTITY_KEY_HOLDER_SQL,
112        vec![
113            SqlValue::Text(namespace.to_owned()),
114            SqlValue::Text(kind.to_owned()),
115            SqlValue::Text(key.to_owned()),
116        ],
117    )
118    .labelled("import-key-holder")
119}
120
121/// The holder a [`key_holder_statement`] read names, if any.
122pub(super) fn key_holder(rows: &[SqlRow]) -> RuntimeResult<Option<Uuid>> {
123    rows.first()
124        .map(|row| row.uuid("entity_id"))
125        .transpose()
126        .map_err(column_error)
127}
128
129/// One key row of an entity.
130pub(super) struct KeyRow {
131    pub(super) kind: String,
132    pub(super) key: String,
133    /// Whether the key is held, rather than released by a delete.
134    pub(super) held: bool,
135}
136
137/// Every key row in one namespace, held or released.
138pub(super) struct NamespaceKeys {
139    /// The live holder of each held `(kind, key)`.
140    pub(super) holders: HashMap<(String, String), Uuid>,
141    /// Each entity's key rows, ordered by kind then key.
142    pub(super) rows: HashMap<Uuid, Vec<KeyRow>>,
143}
144
145impl NamespaceKeys {
146    /// The keys the rows of entity `id` name under `kind`, held or released.
147    pub(super) fn named_by(&self, id: Uuid, kind: &str) -> BTreeSet<&str> {
148        self.rows
149            .get(&id)
150            .into_iter()
151            .flatten()
152            .filter(|row| row.kind == kind)
153            .map(|row| row.key.as_str())
154            .collect()
155    }
156}
157
158/// The writes that add an archive entity's keys and aliases to its row.
159pub(super) struct ArchiveNameWrites {
160    /// Key claims first, then alias writes.
161    pub(super) statements: Vec<PlanStatement>,
162    /// The key each leading claim statement takes, in statement order.
163    pub(super) claimed: Vec<String>,
164}
165
166/// The writes that add an archive entity's keys and aliases to `entity`,
167/// written at its `updated_at`, with `entity.aliases` set to what they leave
168/// stored (ADR-221 section 4).
169///
170/// `named` lists the keys the entity's own rows already name under its kind:
171/// those stay as they are, and every other key is claimed, guarded to one
172/// row, so a key another live entity took since it was read rolls the write
173/// back. An alias the entity holds keeps its row and origin; any other is
174/// stored with the origin the archive names. Nothing the entity holds is
175/// removed, except an alias equal to its name, which an alias never is.
176pub(super) fn archive_name_writes(
177    entity: &mut Entity,
178    keys: &[String],
179    aliases: &[EntityAlias],
180    named: &BTreeSet<&str>,
181) -> ArchiveNameWrites {
182    let namespace = entity.namespace.clone();
183    let name = entity.name.clone();
184    let at = entity.updated_at;
185    let mut writes = ArchiveNameWrites {
186        statements: Vec::new(),
187        claimed: Vec::new(),
188    };
189    for key in keys {
190        if named.contains(key.as_str()) {
191            continue;
192        }
193        writes.statements.push(PlanStatement {
194            statement: entity_key_claim_statement(&namespace, &entity.kind, key, entity.id, at),
195            guard: Some(AffectedRowGuard::exactly(1)),
196        });
197        writes.claimed.push(key.clone());
198    }
199    if entity.aliases.iter().any(|stored| stored.alias == name) {
200        writes.statements.push(PlanStatement {
201            statement: entity_name_alias_delete_statement(&namespace, entity.id, &name),
202            guard: None,
203        });
204        entity.aliases.retain(|stored| stored.alias != name);
205    }
206    for alias in aliases {
207        if alias.alias == name
208            || entity
209                .aliases
210                .iter()
211                .any(|stored| stored.alias == alias.alias)
212        {
213            continue;
214        }
215        writes.statements.push(PlanStatement {
216            statement: entity_alias_insert_statement(
217                &namespace,
218                entity.id,
219                &alias.alias,
220                alias.origin,
221                at,
222            ),
223            guard: None,
224        });
225        entity.aliases.push(alias.clone());
226    }
227    entity.aliases.sort();
228    writes
229}
230
231impl KhiveRuntime {
232    /// Every key row in the token's namespace.
233    pub(super) async fn namespace_keys(
234        &self,
235        token: &NamespaceToken,
236    ) -> RuntimeResult<NamespaceKeys> {
237        let statement = SqlStatement::new(
238            NAMESPACE_KEY_ROWS_SQL,
239            vec![SqlValue::Text(token.namespace().as_str().to_owned())],
240        )
241        .labelled("archive-namespace-keys");
242        let rows = {
243            let mut reader = self.sql().reader().await?;
244            reader.query_all(statement).await?
245        };
246        let mut keys = NamespaceKeys {
247            holders: HashMap::new(),
248            rows: HashMap::new(),
249        };
250        for row in &rows {
251            let id = row.uuid("entity_id").map_err(column_error)?;
252            let kind = row.text("kind").map_err(column_error)?.to_owned();
253            let key = row.text("key").map_err(column_error)?.to_owned();
254            let held = row.opt_i64("released_at").map_err(column_error)?.is_none();
255            if held {
256                keys.holders.insert((kind.clone(), key.clone()), id);
257            }
258            keys.rows
259                .entry(id)
260                .or_default()
261                .push(KeyRow { kind, key, held });
262        }
263        Ok(keys)
264    }
265
266    /// Write one legacy-imported entity row together with its archive keys
267    /// and aliases in one transaction. A key another live entity claimed
268    /// since it was read refuses with `import_key_conflict` and writes
269    /// nothing.
270    pub(super) async fn upsert_archive_entity(
271        &self,
272        entity: &Entity,
273        writes: ArchiveNameWrites,
274    ) -> RuntimeResult<()> {
275        crate::secret_gate::reject_reserved_secret_gate_property(entity.properties.as_ref())?;
276        let id = entity.id;
277        let kind = entity.kind.clone();
278        let upsert = entity_upsert_statement(entity);
279        let op: PreparedAtomicOp<(), RuntimeError> = Box::new(move |writer| {
280            Box::pin(async move {
281                writer.execute(upsert).await?;
282                for (index, planned) in writes.statements.into_iter().enumerate() {
283                    let affected = writer.execute(planned.statement).await?;
284                    if planned
285                        .guard
286                        .is_some_and(|guard| !guard.holds_for(affected))
287                    {
288                        let failure = match writes.claimed.get(index) {
289                            Some(key) => import_key_conflict(id, &kind, key),
290                            None => RuntimeError::Internal(
291                                "archive name write affected an unexpected row count".into(),
292                            ),
293                        };
294                        return Err(PreparedAtomicError::Refused {
295                            failure,
296                            message: "archive key claim refused".into(),
297                        });
298                    }
299                }
300                Ok(((), Vec::new()))
301            })
302        });
303        let access = self.sql();
304        match run_prepared_atomic_unit(access.as_ref(), op).await? {
305            PreparedAtomicOutcome::Committed { .. } => Ok(()),
306            PreparedAtomicOutcome::RolledBack(error) => Err(error),
307        }
308    }
309
310    /// Write the keys and aliases a snapshot gives each entity, into a store
311    /// whose rows for those entities hold none yet, in one transaction.
312    ///
313    /// Snapshot sync rebuilds a store from the snapshot, so the entities end
314    /// with exactly the snapshot's keys and aliases (ADR-221 section 4). Each
315    /// item is an entity id, its kind, its keys and its aliases; the entity
316    /// rows are written first.
317    pub async fn write_snapshot_entity_names(
318        &self,
319        token: &NamespaceToken,
320        entities: Vec<(Uuid, String, Vec<String>, Vec<EntityAlias>)>,
321    ) -> RuntimeResult<()> {
322        let namespace = token.namespace().as_str().to_owned();
323        let at = chrono::Utc::now().timestamp_micros();
324        let mut statements = Vec::new();
325        for (id, kind, keys, aliases) in entities {
326            for key in keys {
327                let claim = entity_key_claim_statement(&namespace, &kind, &key, id, at);
328                statements.push((claim, Some((id, kind.clone(), key))));
329            }
330            for alias in aliases {
331                let insert =
332                    entity_alias_insert_statement(&namespace, id, &alias.alias, alias.origin, at);
333                statements.push((insert, None));
334            }
335        }
336        if statements.is_empty() {
337            return Ok(());
338        }
339        let op: PreparedAtomicOp<(), RuntimeError> = Box::new(move |writer| {
340            Box::pin(async move {
341                for (statement, claim) in statements {
342                    let affected = writer.execute(statement).await?;
343                    if affected != 1 {
344                        let failure = match claim {
345                            Some((id, kind, key)) => import_key_conflict(id, &kind, &key),
346                            None => RuntimeError::InvalidInput(
347                                "snapshot alias is already stored for its entity".into(),
348                            ),
349                        };
350                        return Err(PreparedAtomicError::Refused {
351                            failure,
352                            message: "snapshot name write refused".into(),
353                        });
354                    }
355                }
356                Ok(((), Vec::new()))
357            })
358        });
359        let access = self.sql();
360        match run_prepared_atomic_unit(access.as_ref(), op).await? {
361            PreparedAtomicOutcome::Committed { .. } => Ok(()),
362            PreparedAtomicOutcome::RolledBack(error) => Err(error),
363        }
364    }
365}
366
367#[cfg(test)]
368#[path = "names_tests.rs"]
369mod tests;