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 crate::secret_gate::check_at(physical_key, "note", "key")?;
67 let namespace = specs[0].token.namespace().as_str().to_owned();
68 if specs.iter().any(|spec| spec.kind != "message")
69 || specs[1].token.namespace().as_str() != namespace
70 || specs[0].token.actor().id != specs[1].token.actor().id
71 || specs[0].id.is_none()
72 || specs[1].id.is_none()
73 || specs[0].id == specs[1].id
74 {
75 return Err(RuntimeError::InvalidInput(
76 "a keyed message pair requires distinct IDs in one actor namespace".into(),
77 ));
78 }
79 let mut prepared =
80 prepare_atomic_notes(runtime, specs.into(), AtomicNoteOptions::default()).await?;
81 crate::atomic_message::append_note_attachments(&mut prepared, attachments)?;
82 for note in &prepared.notes {
83 crate::secret_gate::reject_reserved_secret_gate_property(note.properties.as_ref())?;
84 }
85 let outbound_id = prepared.notes[0].id;
86 for (plan, note) in prepared.plans.iter_mut().zip(&prepared.notes) {
87 let AtomicOpPlan::AddNote(plan) = plan else {
88 return Err(RuntimeError::Internal(
89 "expected prepared message note".into(),
90 ));
91 };
92 plan.statements[0].statement =
94 khive_db::stores::note::note_insert_if_absent_statement(note);
95 }
96 let Some(AtomicOpPlan::AddNote(last)) = prepared.plans.last_mut() else {
97 return Err(RuntimeError::Internal(
98 "expected recipient message plan".into(),
99 ));
100 };
101 last.statements.push(PlanStatement {
102 statement: SqlStatement {
103 sql: "UPDATE OR IGNORE notes SET key = ?1 WHERE id = ?2 AND namespace = ?3 \
104 AND kind = 'message' AND key IS NULL AND deleted_at IS NULL"
105 .into(),
106 params: vec![
107 SqlValue::Text(physical_key.to_owned()),
108 SqlValue::Text(outbound_id.to_string()),
109 SqlValue::Text(namespace.clone()),
110 ],
111 label: Some(KEY_CLAIM.into()),
112 },
113 guard: Some(AffectedRowGuard::exactly(1)),
114 });
115 crate::atomic_message::append_extra_statements(&mut prepared, extra_statements)?;
120
121 match run_atomic_unit(runtime.sql().as_ref(), prepared.plans).await {
122 Ok(AtomicRunOutcome::Committed { .. }) => {
123 prepared.notes[0].key = Some(physical_key.to_owned());
124 Ok(KeyedMessageWrite::Created {
125 notes: prepared.notes,
126 embedding_truncation: prepared.embedding_truncation,
127 })
128 }
129 Ok(AtomicRunOutcome::RolledBack {
130 failure:
131 AtomicOpFailure::GuardFailed {
132 statement_label,
133 observed: 0,
134 ..
135 },
136 ..
137 }) if statement_label.as_deref() == Some(KEY_CLAIM) => {
138 find_keyed_message_holder(runtime, &namespace, physical_key)
139 .await?
140 .map(KeyedMessageWrite::Existing)
141 .ok_or_else(|| {
142 KhiveError::unavailable("message key holder disappeared during reconciliation")
143 .with_details(Details::new_owned([(
144 "reason",
145 "key_holder_unresolved".into(),
146 )]))
147 .into()
148 })
149 }
150 Ok(AtomicRunOutcome::RolledBack {
151 failed_op_index,
152 failure,
153 }) => Err(RuntimeError::Internal(format!(
154 "atomic message pair rolled back at op {failed_op_index}: {failure:?}"
155 ))),
156 Err(error) => Err(RuntimeError::Storage(error.0)),
157 }
158}
159
160pub async fn find_keyed_message_holder(
163 runtime: &KhiveRuntime,
164 namespace: &str,
165 physical_key: &str,
166) -> RuntimeResult<Option<Uuid>> {
167 let holder = runtime
168 .sql()
169 .reader()
170 .await?
171 .query_scalar(SqlStatement {
172 sql: "SELECT id FROM notes WHERE namespace = ?1 AND kind = 'message' \
173 AND key = ?2 AND deleted_at IS NULL LIMIT 1"
174 .into(),
175 params: vec![
176 SqlValue::Text(namespace.to_owned()),
177 SqlValue::Text(physical_key.to_owned()),
178 ],
179 label: Some("message-key-holder".into()),
180 })
181 .await?;
182 match holder {
183 Some(SqlValue::Text(id)) => Uuid::parse_str(&id)
184 .map(Some)
185 .map_err(|error| RuntimeError::Internal(format!("invalid message holder id: {error}"))),
186 None => Ok(None),
187 Some(_) => Err(RuntimeError::Internal(
188 "message holder id is not text".into(),
189 )),
190 }
191}
192
193#[cfg(test)]
194#[path = "keyed_message_tests.rs"]
195mod tests;