use std::collections::BTreeSet;
use super::entity_create::EntityCreateWrite;
use super::*;
use khive_storage::EntityKeyHolder;
pub(crate) const ENTITY_KEY_REFUSAL: &str =
"key must be at most 512 UTF-8 bytes and must not contain U+0000";
const KEYED_CREATE_ATTEMPTS: usize = 3;
#[derive(Debug)]
pub enum KeyedEntityCreate {
Created {
entity: Entity,
embedding: crate::retrieval::EmbeddingTruncationReport,
degradations: Vec<PostCommitDegradation>,
},
Replayed { entity: Entity },
Conflict { existing_id: Uuid },
}
#[derive(Debug)]
pub enum KeyedEntityReload {
Updated {
entity: Entity,
report: crate::curation::EntityUpdateReport,
},
Replayed { entity: Entity },
Moved,
}
#[derive(Debug)]
pub struct PendingEntityId(pub(super) Uuid);
impl PendingEntityId {
pub fn mint() -> Self {
Self(Uuid::new_v4())
}
pub fn id(&self) -> Uuid {
self.0
}
}
pub fn keyed_replay_assertion_plan(holder: &Entity) -> AtomicOpPlan {
crate::canonical_apply::unchanged_entity_assertion_plan(holder, "keyed-replay-assertion")
}
pub fn entity_carries_create_payload(holder: &Entity, spec: &EntityCreateSpec) -> bool {
same_entity_payload(
holder,
spec.entity_type.as_deref(),
&spec.name,
spec.description.as_deref(),
spec.properties.as_ref(),
&spec.tags,
&spec_aliases(spec),
)
}
fn spec_aliases(spec: &EntityCreateSpec) -> BTreeSet<&str> {
spec.aliases
.iter()
.map(String::as_str)
.filter(|alias| *alias != spec.name)
.collect()
}
pub fn same_create_payload(first: &EntityCreateSpec, second: &EntityCreateSpec) -> bool {
let mut held =
Entity::new("", &first.kind, &first.name).with_entity_type(first.entity_type.as_deref());
held.description = first.description.clone();
held.properties = first.properties.clone();
held.tags = first.tags.clone();
held.aliases = spec_aliases(first)
.into_iter()
.map(|alias| khive_storage::entity::EntityAlias {
alias: alias.to_owned(),
origin: khive_storage::entity::EntityAliasOrigin::Caller,
})
.collect();
entity_carries_create_payload(&held, second)
}
fn properties_to_remove(holder: &Entity, wanted: Option<&serde_json::Value>) -> Vec<String> {
match caller_properties(holder.properties.as_ref()) {
Some(serde_json::Value::Object(held)) => held
.keys()
.filter(|held_key| {
!wanted
.and_then(serde_json::Value::as_object)
.is_some_and(|asked| asked.contains_key(*held_key))
})
.cloned()
.collect(),
_ => Vec::new(),
}
}
fn reload_patch(
entity_type: Option<&str>,
name: &str,
description: Option<&str>,
wanted: Option<serde_json::Value>,
tags: &[String],
) -> crate::EntityPatch {
crate::EntityPatch {
name: Some(name.to_owned()),
description: Some(description.map(str::to_owned)),
properties: wanted,
tags: Some(tags.to_vec()),
entity_type: Some(entity_type.map(str::to_owned)),
}
}
fn is_version_conflict(error: &RuntimeError) -> bool {
matches!(
error,
RuntimeError::Khive(error)
if error.details().and_then(|details| details.get("reason"))
== Some("version_conflict")
)
}
pub(crate) fn validate_entity_key(key: &str) -> RuntimeResult<()> {
crate::note_validation::validate_key(key, ENTITY_KEY_REFUSAL)?;
crate::secret_gate::check_at(key, "entity", "key")
}
fn caller_properties(properties: Option<&serde_json::Value>) -> Option<serde_json::Value> {
let value = properties?;
let serde_json::Value::Object(map) = value else {
return Some(value.clone());
};
let reserved = crate::secret_gate::RESERVED_PROPERTY_KEYS;
let kept: serde_json::Map<String, serde_json::Value> = map
.iter()
.filter(|(key, _)| !reserved.contains(&key.as_str()))
.map(|(key, value)| (key.clone(), value.clone()))
.collect();
(!kept.is_empty()).then_some(serde_json::Value::Object(kept))
}
fn same_entity_payload(
holder: &Entity,
entity_type: Option<&str>,
name: &str,
description: Option<&str>,
properties: Option<&serde_json::Value>,
tags: &[String],
aliases: &BTreeSet<&str>,
) -> bool {
let stored: BTreeSet<&str> = aliases
.iter()
.copied()
.filter(|alias| {
!holder.aliases.iter().any(|held| {
held.alias == *alias
&& held.origin != khive_storage::entity::EntityAliasOrigin::Caller
})
})
.collect();
if super::entity_aliases::caller_alias_set(holder) != stored {
return false;
}
if holder.name != name
|| holder.description.as_deref() != description
|| holder.entity_type.as_deref() != entity_type
{
return false;
}
if caller_properties(holder.properties.as_ref()) != caller_properties(properties) {
return false;
}
let held: BTreeSet<&str> = holder.tags.iter().map(String::as_str).collect();
let asked: BTreeSet<&str> = tags.iter().map(String::as_str).collect();
held == asked
}
pub fn entity_key_conflict(key: &str, existing_id: Option<Uuid>) -> RuntimeError {
let mut details = vec![
("reason", "key_conflict".to_string()),
("key", key.to_owned()),
];
if let Some(existing_id) = existing_id {
details.push(("existing_id", existing_id.to_string()));
}
KhiveError::conflict(format!(
"key_conflict: key {key:?} is already held by a live entity with a different payload"
))
.with_details(khive_types::Details::new_owned(details))
.into()
}
fn restore_entity_key_conflict(
id: Uuid,
taken: &[EntityKeyHolder],
disclose: &(dyn Fn(&str) -> bool + Sync),
) -> RuntimeError {
let named: Vec<String> = taken
.iter()
.map(|taken| {
if disclose(&taken.kind) {
format!("{}:{:?} held by {}", taken.kind, taken.key, taken.holder_id)
} else {
format!("{}:{:?}", taken.kind, taken.key)
}
})
.collect();
let listed: Vec<serde_json::Value> = taken
.iter()
.map(|taken| {
let mut entry = serde_json::json!({"kind": taken.kind, "key": taken.key});
if disclose(&taken.kind) {
entry["existing_id"] = serde_json::json!(taken.holder_id.to_string());
}
entry
})
.collect();
KhiveError::conflict(format!(
"restore_key_conflict: entity {id} stays deleted; keys taken by live entities: {}",
named.join(", ")
))
.with_details(khive_types::Details::new_owned([
("reason", "restore_key_conflict".to_string()),
("taken_keys", serde_json::Value::Array(listed).to_string()),
]))
.into()
}
impl KhiveRuntime {
#[allow(clippy::too_many_arguments)]
pub async fn create_keyed_entity_with_post_commit_report(
&self,
token: &NamespaceToken,
kind: &str,
key: &str,
entity_type: Option<&str>,
name: &str,
description: Option<&str>,
properties: Option<serde_json::Value>,
tags: Vec<String>,
aliases: &EntityAliasChange,
) -> RuntimeResult<KeyedEntityCreate> {
validate_entity_key(key)?;
self.validate_entity_kind(kind)?;
crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
let namespace = token.namespace().as_str();
let wanted_aliases = aliases.wanted(name);
for _ in 0..KEYED_CREATE_ATTEMPTS {
let holder = self
.entities(token)?
.get_entity_by_key(namespace, kind, key)
.await?;
if let Some(holder) = holder {
return Ok(
if same_entity_payload(
&holder,
entity_type,
name,
description,
properties.as_ref(),
&tags,
&wanted_aliases,
) {
KeyedEntityCreate::Replayed { entity: holder }
} else {
KeyedEntityCreate::Conflict {
existing_id: holder.id,
}
},
);
}
match self
.create_entity_with_embedding_report_inner(
token,
kind,
entity_type,
name,
description,
properties.clone(),
tags.clone(),
Vec::new(),
Some(key),
aliases,
)
.await?
{
EntityCreateWrite::Written(entity, embedding, degradations) => {
return Ok(KeyedEntityCreate::Created {
entity: *entity,
embedding,
degradations,
});
}
EntityCreateWrite::KeyHeld => continue,
}
}
let holder = self
.entities(token)?
.get_entity_by_key(namespace, kind, key)
.await?;
match holder {
Some(holder)
if same_entity_payload(
&holder,
entity_type,
name,
description,
properties.as_ref(),
&tags,
&wanted_aliases,
) =>
{
Ok(KeyedEntityCreate::Replayed { entity: holder })
}
Some(holder) => Ok(KeyedEntityCreate::Conflict {
existing_id: holder.id,
}),
None => Err(RuntimeError::Internal(format!(
"keyed entity create: key {key:?} was claimed and released again during \
{KEYED_CREATE_ATTEMPTS} claims"
))),
}
}
#[allow(clippy::too_many_arguments)]
pub async fn reload_keyed_entity(
&self,
token: &NamespaceToken,
kind: &str,
key: &str,
holder_id: Uuid,
entity_type: Option<&str>,
name: &str,
description: Option<&str>,
properties: Option<serde_json::Value>,
tags: Vec<String>,
aliases: &EntityAliasChange,
) -> RuntimeResult<KeyedEntityReload> {
validate_entity_key(key)?;
crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
let namespace = token.namespace().as_str();
let wanted = caller_properties(properties.as_ref());
let wanted_aliases = aliases.wanted(name);
for _ in 0..KEYED_CREATE_ATTEMPTS {
let holder = self
.entities(token)?
.get_entity_by_key(namespace, kind, key)
.await?;
let Some(holder) = holder.filter(|holder| holder.id == holder_id) else {
return Ok(KeyedEntityReload::Moved);
};
if same_entity_payload(
&holder,
entity_type,
name,
description,
wanted.as_ref(),
&tags,
&wanted_aliases,
) {
return Ok(KeyedEntityReload::Replayed { entity: holder });
}
let removed = properties_to_remove(&holder, wanted.as_ref());
let removed: Vec<&str> = removed.iter().map(String::as_str).collect();
let patch = reload_patch(entity_type, name, description, wanted.clone(), &tags);
match self
.update_entity_with_removals_and_index_report(
token,
holder.id,
patch,
&removed,
Some(holder.version),
aliases,
)
.await
{
Ok((entity, report)) => {
return Ok(KeyedEntityReload::Updated { entity, report });
}
Err(error) if is_version_conflict(&error) => continue,
Err(error) => return Err(error),
}
}
Err(RuntimeError::Internal(format!(
"keyed entity reload: the holder of key {key:?} changed during \
{KEYED_CREATE_ATTEMPTS} attempts"
)))
}
pub async fn prepare_keyed_entity_reload_plan(
&self,
token: &NamespaceToken,
holder: &Entity,
spec: &EntityCreateSpec,
) -> RuntimeResult<(Entity, AtomicOpPlan)> {
crate::secret_gate::reject_reserved_secret_gate_property(spec.properties.as_ref())?;
let aliases = EntityAliasChange::replace(&spec.aliases)?;
let wanted = caller_properties(spec.properties.as_ref());
let removed = properties_to_remove(holder, wanted.as_ref());
let removed: Vec<&str> = removed.iter().map(String::as_str).collect();
let patch = reload_patch(
spec.entity_type.as_deref(),
&spec.name,
spec.description.as_deref(),
wanted,
&spec.tags,
);
crate::atomic_prepare::prepare_keyed_reload_entity_record(
self,
token,
holder.id,
patch,
&removed,
holder.version,
&aliases,
)
.await
}
pub async fn get_entity_by_key(
&self,
token: &NamespaceToken,
kind: &str,
key: &str,
) -> RuntimeResult<Option<Entity>> {
validate_entity_key(key)?;
Ok(self
.entities(token)?
.get_entity_by_key(token.namespace().as_str(), kind, key)
.await?)
}
pub(super) async fn refuse_restore_over_taken_keys(
&self,
token: &NamespaceToken,
id: Uuid,
disclose: &(dyn Fn(&str) -> bool + Sync),
) -> RuntimeResult<()> {
let taken = self.entities(token)?.taken_entity_keys(id).await?;
if taken.is_empty() {
Ok(())
} else {
Err(restore_entity_key_conflict(id, &taken, disclose))
}
}
}
#[cfg(test)]
#[path = "entity_keys_tests.rs"]
mod tests;