khive_runtime/
note_create.rs1use khive_storage::types::{Edge, LinkId, SqlValue};
4use khive_storage::{EdgeRelation, SqlStatement};
5use serde_json::{json, Value};
6use uuid::Uuid;
7
8use crate::atomic_message::{
9 prepare_atomic_notes, AtomicNoteOptions, AtomicNoteSpec, PreparedAtomicNotes,
10};
11use crate::atomic_plan::{AffectedRowGuard, PlanStatement};
12use crate::atomic_runner::AtomicOpPlan;
13use crate::{KhiveRuntime, RuntimeError, RuntimeResult};
14
15pub enum EffectiveCreateTags<'a> {
18 TopLevel(&'a [String]),
19 Properties(Option<&'a Value>),
20}
21
22impl EffectiveCreateTags<'_> {
23 pub fn to_value(&self) -> Value {
26 match self {
27 Self::TopLevel(tags) => json!(tags),
28 Self::Properties(tags) => tags.cloned().unwrap_or(Value::Null),
29 }
30 }
31}
32
33pub fn effective_create_tags<'a>(
39 tags: Option<&'a [String]>,
40 properties: Option<&'a Value>,
41) -> EffectiveCreateTags<'a> {
42 match tags {
43 Some(tags) if !tags.is_empty() => EffectiveCreateTags::TopLevel(tags),
44 _ => EffectiveCreateTags::Properties(properties.and_then(|value| value.get("tags"))),
45 }
46}
47
48pub(crate) enum KeyPublication {
49 AtInsert,
50 AfterDependents,
51}
52
53pub(crate) const KEY_CLAIM: &str = "memory-key-claim";
54pub(crate) const KEYED_ANNOTATION_ENDPOINT: &str = "memory-annotation-endpoint";
55
56pub(crate) enum NoteCreatePrepareError {
57 MissingAnnotation(Uuid),
58 Other(RuntimeError),
59}
60
61impl From<RuntimeError> for NoteCreatePrepareError {
62 fn from(error: RuntimeError) -> Self {
63 Self::Other(error)
64 }
65}
66
67impl NoteCreatePrepareError {
68 pub(crate) fn into_runtime(self) -> RuntimeError {
69 match self {
70 Self::MissingAnnotation(target) => {
71 RuntimeError::NotFound(format!("create_note annotates target {target} not found"))
72 }
73 Self::Other(error) => error,
74 }
75 }
76}
77
78pub(crate) async fn prepare_note_create(
79 runtime: &KhiveRuntime,
80 spec: AtomicNoteSpec<'_>,
81 options: AtomicNoteOptions<'_>,
82 annotates: &[Uuid],
83 publication: KeyPublication,
84) -> RuntimeResult<(PreparedAtomicNotes, Vec<Uuid>)> {
85 prepare_note_create_classified(runtime, spec, options, annotates, publication)
86 .await
87 .map_err(NoteCreatePrepareError::into_runtime)
88}
89
90pub(crate) async fn prepare_note_create_classified(
91 runtime: &KhiveRuntime,
92 spec: AtomicNoteSpec<'_>,
93 mut options: AtomicNoteOptions<'_>,
94 annotates: &[Uuid],
95 publication: KeyPublication,
96) -> Result<(PreparedAtomicNotes, Vec<Uuid>), NoteCreatePrepareError> {
97 for target in annotates {
98 if !runtime.substrate_exists_by_id(spec.token, *target).await? {
99 return Err(NoteCreatePrepareError::MissingAnnotation(*target));
100 }
101 }
102 let claim_last = match publication {
103 KeyPublication::AtInsert => None,
104 KeyPublication::AfterDependents => Some(
105 options
106 .key
107 .take()
108 .ok_or_else(|| {
109 RuntimeError::InvalidInput("deferred key publication requires a key".into())
110 })?
111 .to_owned(),
112 ),
113 };
114 let mut prepared = prepare_atomic_notes(runtime, vec![spec], options).await?;
115 let note = &prepared.notes[0];
116 crate::secret_gate::reject_reserved_secret_gate_property(note.properties.as_ref())?;
117 let AtomicOpPlan::AddNote(plan) = &mut prepared.plans[0] else {
118 return Err(RuntimeError::Internal("expected prepared note creation".into()).into());
119 };
120 if claim_last.is_some() {
121 plan.statements[0].statement =
122 khive_db::stores::note::note_insert_if_absent_statement(note);
123 }
124 let mut annotation_ids = Vec::with_capacity(annotates.len());
125 for target in annotates {
126 let now = chrono::Utc::now();
127 let id = Uuid::new_v4();
128 let edge = Edge {
129 id: LinkId::from(id),
130 namespace: note.namespace.clone(),
131 source_id: note.id,
132 target_id: *target,
133 relation: EdgeRelation::Annotates,
134 weight: 1.0,
135 created_at: now,
136 updated_at: now,
137 deleted_at: None,
138 metadata: None,
139 target_backend: None,
140 };
141 let mut statement =
142 khive_db::stores::graph::edge_insert_only_guarded_by_endpoints_statement(&edge);
143 if claim_last.is_some() {
144 statement.label = Some(KEYED_ANNOTATION_ENDPOINT.into());
145 }
146 plan.statements.push(PlanStatement {
147 statement,
148 guard: Some(AffectedRowGuard::exactly(1)),
149 });
150 annotation_ids.push(id);
151 }
152 if let Some(key) = claim_last {
153 plan.statements.push(PlanStatement {
154 statement: SqlStatement {
155 sql: "UPDATE OR IGNORE notes SET key = ?1 WHERE id = ?2 AND namespace = ?3 \
156 AND kind = ?4 AND key IS NULL AND deleted_at IS NULL"
157 .into(),
158 params: vec![
159 SqlValue::Text(key),
160 SqlValue::Text(note.id.to_string()),
161 SqlValue::Text(note.namespace.clone()),
162 SqlValue::Text(note.kind.clone()),
163 ],
164 label: Some(KEY_CLAIM.into()),
165 },
166 guard: Some(AffectedRowGuard::exactly(1)),
167 });
168 }
169 Ok((prepared, annotation_ids))
170}