Skip to main content

khive_runtime/operations/
entity_key_add.rs

1//! Adding a caller key to a live entity (ADR-221 Amendment 1).
2//!
3//! A key added here is held exactly as one a keyed create claimed: unique per
4//! `(namespace, kind, key)` over held rows, under the entity's own base kind,
5//! released by a delete, taken back by a restore and moved by a merge. A
6//! pack that writes names as keys on entities it already holds joins
7//! [`entity_key_add_plans`] to its own atomic unit; [`KhiveRuntime::add_entity_key`]
8//! commits one add by itself.
9
10use khive_db::stores::entity::entity_key_claim_statement;
11
12use super::*;
13
14/// Label of the statement that holds an add to an entity that is live, not
15/// merged away and of the kind the key is added under.
16pub const ENTITY_KEY_ADD_LIVE_LABEL: &str = "entity-key-add-live";
17
18/// Label of the statement that holds an add only while the entity holds the
19/// key once the claim has run. It fails when another live entity holds it.
20pub const ENTITY_KEY_ADD_HELD_LABEL: &str = "entity-key-add-held";
21
22/// Units lost to a concurrent writer before an add gives up. Each lost unit
23/// reads the entity and the key's holder again.
24const ENTITY_KEY_ADD_ATTEMPTS: usize = 3;
25
26/// Outcome of [`KhiveRuntime::add_entity_key`].
27#[derive(Debug)]
28pub enum EntityKeyAdd {
29    /// The key was free: this call claimed it for `entity`.
30    Added { entity: Entity },
31    /// `entity` already held the key. Nothing was written.
32    Held { entity: Entity },
33    /// Another live entity holds the key. Nothing was written.
34    Conflict { existing_id: Uuid },
35}
36
37fn assertion_plan(target_id: Uuid, statement: SqlStatement) -> AtomicOpPlan {
38    AtomicOpPlan::Update(Box::new(UpdatePlan {
39        target_id,
40        statements: vec![PlanStatement {
41            statement,
42            guard: Some(AffectedRowGuard::exactly(1)),
43        }],
44        post_commit: PostCommitEffect::None,
45        edge_natural_key: None,
46        idempotent_noop: true,
47        entity_guard: None,
48        note_guard: None,
49        note_vector_purge: None,
50        note_embedding_inheritance: None,
51        graph_effects: Vec::new(),
52    }))
53}
54
55/// The plans that add caller key `key` to entity `entity_id`, of base kind
56/// `kind` in `namespace`, claimed at `at` (ADR-221 Amendment 1).
57///
58/// The key is validated and secret-gated before anything else, as a keyed
59/// create's is. Joined to an atomic unit in the order returned, the plans
60/// hold only while the entity is live, not merged away and of kind `kind`
61/// ([`ENTITY_KEY_ADD_LIVE_LABEL`]); they claim the key when no live entity
62/// holds it under `kind`; and they hold only while the entity then holds it
63/// ([`ENTITY_KEY_ADD_HELD_LABEL`]). A key the entity already holds passes
64/// and writes nothing, so adding it twice leaves one row. A key another live
65/// entity holds fails the last guard and rolls the whole unit back.
66pub fn entity_key_add_plans(
67    namespace: &str,
68    entity_id: Uuid,
69    kind: &str,
70    key: &str,
71    at: i64,
72) -> RuntimeResult<Vec<AtomicOpPlan>> {
73    validate_entity_key(key)?;
74    let live = SqlStatement {
75        sql: "SELECT 1 FROM entities WHERE id = ?1 AND namespace = ?2 AND kind = ?3 \
76              AND deleted_at IS NULL AND merged_into IS NULL"
77            .into(),
78        params: vec![
79            SqlValue::Text(entity_id.to_string()),
80            SqlValue::Text(namespace.to_owned()),
81            SqlValue::Text(kind.to_owned()),
82        ],
83        label: Some(ENTITY_KEY_ADD_LIVE_LABEL.into()),
84    };
85    let claim = AtomicOpPlan::Update(Box::new(UpdatePlan {
86        target_id: entity_id,
87        statements: vec![PlanStatement {
88            statement: entity_key_claim_statement(namespace, kind, key, entity_id, at),
89            guard: None,
90        }],
91        post_commit: PostCommitEffect::None,
92        edge_natural_key: None,
93        idempotent_noop: false,
94        entity_guard: None,
95        note_guard: None,
96        note_vector_purge: None,
97        note_embedding_inheritance: None,
98        graph_effects: Vec::new(),
99    }));
100    let held = SqlStatement {
101        sql: "SELECT 1 FROM entity_keys WHERE namespace = ?1 AND kind = ?2 AND key = ?3 \
102              AND entity_id = ?4 AND released_at IS NULL"
103            .into(),
104        params: vec![
105            SqlValue::Text(namespace.to_owned()),
106            SqlValue::Text(kind.to_owned()),
107            SqlValue::Text(key.to_owned()),
108            SqlValue::Text(entity_id.to_string()),
109        ],
110        label: Some(ENTITY_KEY_ADD_HELD_LABEL.into()),
111    };
112    Ok(vec![
113        assertion_plan(entity_id, live),
114        claim,
115        assertion_plan(entity_id, held),
116    ])
117}
118
119/// `entity_deleted` for an add to an entity that a delete removed.
120fn entity_deleted(id: Uuid) -> RuntimeError {
121    KhiveError::conflict(format!(
122        "entity_deleted: entity {id} is deleted, so no key can be added to it"
123    ))
124    .with_details(khive_types::Details::new_owned([
125        ("reason", "entity_deleted".to_string()),
126        ("id", id.to_string()),
127    ]))
128    .into()
129}
130
131/// `entity_merged` for an add to an entity merged into `kept_id`: its keys
132/// now live on the kept entity.
133fn entity_merged(id: Uuid, kept_id: Uuid) -> RuntimeError {
134    KhiveError::conflict(format!(
135        "entity_merged: entity {id} was merged into {kept_id}, so no key can be added to it"
136    ))
137    .with_details(khive_types::Details::new_owned([
138        ("reason", "entity_merged".to_string()),
139        ("id", id.to_string()),
140        ("merged_into", kept_id.to_string()),
141    ]))
142    .into()
143}
144
145impl KhiveRuntime {
146    /// Add caller key `key` to live entity `id` in the caller's primary
147    /// namespace, under the entity's own base kind (ADR-221 Amendment 1).
148    ///
149    /// The key is validated and secret-gated before any read. A free key is
150    /// claimed in one transaction that also holds the entity live and of the
151    /// kind it was read with. A key the entity holds answers
152    /// [`EntityKeyAdd::Held`] and one another live entity holds answers
153    /// [`EntityKeyAdd::Conflict`]; neither writes anything. A missing entity
154    /// is `NotFound`; a deleted one is refused as `entity_deleted` and a
155    /// merged-away one as `entity_merged`, naming the kept entity.
156    pub async fn add_entity_key(
157        &self,
158        token: &NamespaceToken,
159        id: Uuid,
160        key: &str,
161    ) -> RuntimeResult<EntityKeyAdd> {
162        validate_entity_key(key)?;
163        let namespace = token.namespace().as_str();
164        for _ in 0..ENTITY_KEY_ADD_ATTEMPTS {
165            let entity = self
166                .entities(token)?
167                .get_entity_including_deleted(id)
168                .await?
169                .filter(|entity| entity.namespace == namespace)
170                .ok_or_else(|| RuntimeError::NotFound(format!("entity {id}")))?;
171            if let Some(kept_id) = entity.merged_into {
172                return Err(entity_merged(id, kept_id));
173            }
174            if entity.deleted_at.is_some() {
175                return Err(entity_deleted(id));
176            }
177            match self
178                .entities(token)?
179                .get_entity_by_key(namespace, &entity.kind, key)
180                .await?
181            {
182                Some(holder) if holder.id == id => return Ok(EntityKeyAdd::Held { entity }),
183                Some(holder) => {
184                    return Ok(EntityKeyAdd::Conflict {
185                        existing_id: holder.id,
186                    })
187                }
188                None => {}
189            }
190            let at = Utc::now().timestamp_micros();
191            let plans = entity_key_add_plans(namespace, id, &entity.kind, key, at)?;
192            match run_atomic_unit(self.sql().as_ref(), plans).await {
193                Ok(AtomicRunOutcome::Committed { .. }) => {
194                    return Ok(EntityKeyAdd::Added { entity });
195                }
196                // The entity or the key's holder changed after they were
197                // read: read both again.
198                Ok(AtomicRunOutcome::RolledBack {
199                    failure: AtomicOpFailure::GuardFailed { .. },
200                    ..
201                }) => continue,
202                Ok(AtomicRunOutcome::RolledBack { failure, .. }) => {
203                    return Err(RuntimeError::Internal(format!(
204                        "entity key add rolled back: {failure:?}"
205                    )));
206                }
207                Err(error) => return Err(RuntimeError::Storage(error.0)),
208            }
209        }
210        Err(RuntimeError::Internal(format!(
211            "entity key add: entity {id} or the holder of key {key:?} changed during \
212             {ENTITY_KEY_ADD_ATTEMPTS} attempts"
213        )))
214    }
215}
216
217#[cfg(test)]
218#[path = "entity_key_add_tests.rs"]
219mod tests;