khive_runtime/
keyed_message.rs1use khive_storage::{Note, SqlStatement, SqlValue};
7use khive_types::{Details, KhiveError};
8use uuid::Uuid;
9
10use crate::atomic_message::{prepare_atomic_notes, AtomicNoteOptions, AtomicNoteSpec};
11use crate::atomic_plan::{AffectedRowGuard, PlanStatement};
12use crate::atomic_runner::{run_atomic_unit, AtomicOpFailure, AtomicOpPlan, AtomicRunOutcome};
13use crate::{KhiveRuntime, RuntimeError, RuntimeResult};
14
15const KEY_CLAIM: &str = "message-key-claim";
16
17pub enum KeyedMessageWrite {
18 Created {
19 notes: Vec<Note>,
20 embedding_truncation: crate::retrieval::EmbeddingTruncationReport,
21 },
22 Existing(Uuid),
23}
24
25pub async fn create_keyed_message_pair(
29 runtime: &KhiveRuntime,
30 specs: [AtomicNoteSpec<'_>; 2],
31 physical_key: &str,
32) -> RuntimeResult<KeyedMessageWrite> {
33 create_keyed_message_pair_with_attachments(runtime, specs, physical_key, &[]).await
34}
35
36pub async fn create_keyed_message_pair_with_attachments(
38 runtime: &KhiveRuntime,
39 specs: [AtomicNoteSpec<'_>; 2],
40 physical_key: &str,
41 attachments: &[khive_storage::NewAttachment],
42) -> RuntimeResult<KeyedMessageWrite> {
43 create_keyed_message_pair_with_extra_statements(
44 runtime,
45 specs,
46 physical_key,
47 attachments,
48 Vec::new(),
49 )
50 .await
51}
52
53pub async fn create_keyed_message_pair_with_extra_statements(
59 runtime: &KhiveRuntime,
60 specs: [AtomicNoteSpec<'_>; 2],
61 physical_key: &str,
62 attachments: &[khive_storage::NewAttachment],
63 extra_statements: Vec<SqlStatement>,
64) -> RuntimeResult<KeyedMessageWrite> {
65 crate::atomic_message::validate_note_attachments(runtime, attachments)?;
66 let namespace = specs[0].token.namespace().as_str().to_owned();
67 if specs.iter().any(|spec| spec.kind != "message")
68 || specs[1].token.namespace().as_str() != namespace
69 || specs[0].token.actor().id != specs[1].token.actor().id
70 || specs[0].id.is_none()
71 || specs[1].id.is_none()
72 || specs[0].id == specs[1].id
73 {
74 return Err(RuntimeError::InvalidInput(
75 "a keyed message pair requires distinct IDs in one actor namespace".into(),
76 ));
77 }
78 let mut prepared =
79 prepare_atomic_notes(runtime, specs.into(), AtomicNoteOptions::default()).await?;
80 crate::atomic_message::append_note_attachments(&mut prepared, attachments)?;
81 for note in &prepared.notes {
82 crate::secret_gate::reject_reserved_secret_gate_property(note.properties.as_ref())?;
83 }
84 let outbound_id = prepared.notes[0].id;
85 for (plan, note) in prepared.plans.iter_mut().zip(&prepared.notes) {
86 let AtomicOpPlan::AddNote(plan) = plan else {
87 return Err(RuntimeError::Internal(
88 "expected prepared message note".into(),
89 ));
90 };
91 plan.statements[0].statement =
93 khive_db::stores::note::note_insert_if_absent_statement(note);
94 }
95 let Some(AtomicOpPlan::AddNote(last)) = prepared.plans.last_mut() else {
96 return Err(RuntimeError::Internal(
97 "expected recipient message plan".into(),
98 ));
99 };
100 last.statements.push(PlanStatement {
101 statement: SqlStatement {
102 sql: "UPDATE OR IGNORE notes SET key = ?1 WHERE id = ?2 AND namespace = ?3 \
103 AND kind = 'message' AND key IS NULL AND deleted_at IS NULL"
104 .into(),
105 params: vec![
106 SqlValue::Text(physical_key.to_owned()),
107 SqlValue::Text(outbound_id.to_string()),
108 SqlValue::Text(namespace.clone()),
109 ],
110 label: Some(KEY_CLAIM.into()),
111 },
112 guard: Some(AffectedRowGuard::exactly(1)),
113 });
114 crate::atomic_message::append_extra_statements(&mut prepared, extra_statements)?;
119
120 match run_atomic_unit(runtime.sql().as_ref(), prepared.plans).await {
121 Ok(AtomicRunOutcome::Committed { .. }) => {
122 prepared.notes[0].key = Some(physical_key.to_owned());
123 Ok(KeyedMessageWrite::Created {
124 notes: prepared.notes,
125 embedding_truncation: prepared.embedding_truncation,
126 })
127 }
128 Ok(AtomicRunOutcome::RolledBack {
129 failure:
130 AtomicOpFailure::GuardFailed {
131 statement_label,
132 observed: 0,
133 ..
134 },
135 ..
136 }) if statement_label.as_deref() == Some(KEY_CLAIM) => {
137 find_keyed_message_holder(runtime, &namespace, physical_key)
138 .await?
139 .map(KeyedMessageWrite::Existing)
140 .ok_or_else(|| {
141 KhiveError::unavailable("message key holder disappeared during reconciliation")
142 .with_details(Details::new_owned([(
143 "reason",
144 "key_holder_unresolved".into(),
145 )]))
146 .into()
147 })
148 }
149 Ok(AtomicRunOutcome::RolledBack {
150 failed_op_index,
151 failure,
152 }) => Err(RuntimeError::Internal(format!(
153 "atomic message pair rolled back at op {failed_op_index}: {failure:?}"
154 ))),
155 Err(error) => Err(RuntimeError::Storage(error.0)),
156 }
157}
158
159pub async fn find_keyed_message_holder(
162 runtime: &KhiveRuntime,
163 namespace: &str,
164 physical_key: &str,
165) -> RuntimeResult<Option<Uuid>> {
166 let holder = runtime
167 .sql()
168 .reader()
169 .await?
170 .query_scalar(SqlStatement {
171 sql: "SELECT id FROM notes WHERE namespace = ?1 AND kind = 'message' \
172 AND key = ?2 AND deleted_at IS NULL LIMIT 1"
173 .into(),
174 params: vec![
175 SqlValue::Text(namespace.to_owned()),
176 SqlValue::Text(physical_key.to_owned()),
177 ],
178 label: Some("message-key-holder".into()),
179 })
180 .await?;
181 match holder {
182 Some(SqlValue::Text(id)) => Uuid::parse_str(&id)
183 .map(Some)
184 .map_err(|error| RuntimeError::Internal(format!("invalid message holder id: {error}"))),
185 None => Ok(None),
186 Some(_) => Err(RuntimeError::Internal(
187 "message holder id is not text".into(),
188 )),
189 }
190}