Skip to main content

khive_runtime/operations/
attachments.rs

1//! Existing-record attachment publication; no external I/O while holding the writer.
2
3use std::any::Any;
4
5use khive_db::stores::attachment::attachment_upsert_statement;
6use khive_storage::{
7    Attachment, AttachmentSubstrate, NewAttachment, SqlStatement, SqlValue, StorageCapability,
8    StorageError,
9};
10use uuid::Uuid;
11
12use crate::{KhiveRuntime, NamespaceToken, Resolved, RuntimeError, RuntimeResult};
13
14impl KhiveRuntime {
15    /// Publish one role on a live main-backend entity or note.
16    ///
17    /// Bytes are confirmed before writer admission. The owner snapshot, replacement
18    /// decision and attachment row share one transaction. A refused row write can
19    /// leave unreferenced bytes, but never a newly published row pointing at a failed put.
20    pub async fn publish_record_attachment(
21        &self,
22        token: &NamespaceToken,
23        id: Uuid,
24        role: String,
25        bytes: Vec<u8>,
26        media_type: Option<String>,
27    ) -> RuntimeResult<(Attachment, bool)> {
28        if self.backend_id().as_str() != crate::BackendId::MAIN {
29            return Err(StorageError::Unsupported {
30                capability: StorageCapability::Attachments,
31                operation: "attach".into(),
32                message: format!(
33                    "attachment publication requires the canonical main backend; runtime backend {:?} cannot publish atomically there",
34                    self.backend_id().as_str()
35                ),
36            }
37            .into());
38        }
39        // Retain the canonical attachment accessor's capability checks.
40        drop(self.attachments()?);
41        khive_storage::attachment::validate_attachment_role(&role)?;
42        let (substrate, namespace, version, updated_at, entity_type) =
43            match self.resolve_by_id(token, id).await? {
44                Some(Resolved::Entity(entity)) => (
45                    AttachmentSubstrate::Entity,
46                    entity.namespace,
47                    entity.version,
48                    entity.updated_at,
49                    entity.entity_type,
50                ),
51                Some(Resolved::Note(note)) => (
52                    AttachmentSubstrate::Note,
53                    note.namespace,
54                    note.version,
55                    note.updated_at,
56                    None,
57                ),
58                _ => return Err(RuntimeError::NotFound(format!("attachment record {id}"))),
59            };
60        if (role == "fann-network" && entity_type.as_deref() == Some("moodboard_model"))
61            || (role == "content"
62                && matches!(
63                    entity_type.as_deref(),
64                    Some("visual_asset" | "moodboard_model")
65                ))
66        {
67            return Err(RuntimeError::InvalidInput(format!(
68                "attachment role {role:?} on this record is owned by the moodboard pack; use its publication verbs"
69            )));
70        }
71
72        let size = bytes.len() as u64;
73        let content_ref = self.require_blob_store()?.put(bytes).await?;
74        let attachment = Attachment::from_new(
75            id,
76            substrate,
77            NewAttachment {
78                role: role.clone(),
79                content_ref,
80                media_type,
81                size_bytes: Some(size),
82            },
83            chrono::Utc::now().timestamp_micros(),
84        );
85        let upsert = attachment_upsert_statement(&attachment)?;
86        let table = match substrate {
87            AttachmentSubstrate::Entity => "entities",
88            AttachmentSubstrate::Note => "notes",
89        };
90        let owner = SqlStatement::new(
91            format!(
92                "SELECT 1 FROM {table} WHERE id = ?1 AND namespace = ?2 \
93                 AND version = ?3 AND updated_at = ?4 AND deleted_at IS NULL"
94            ),
95            vec![
96                SqlValue::Text(id.to_string()),
97                SqlValue::Text(namespace),
98                SqlValue::Integer(version),
99                SqlValue::Integer(updated_at),
100            ],
101        )
102        .labelled("attach-owner-snapshot");
103        let prior = SqlStatement::new(
104            "SELECT substrate FROM attachments WHERE record_uuid = ?1 AND role = ?2",
105            vec![SqlValue::Text(id.to_string()), SqlValue::Text(role)],
106        )
107        .labelled("attach-replacement");
108        let result = self
109            .sql()
110            .atomic_unit(Box::new(move |writer| {
111                Box::pin(async move {
112                    if writer.query_row(owner).await?.is_none() {
113                        return Err(StorageError::InvalidInput {
114                            capability: StorageCapability::Attachments,
115                            operation: "attach".into(),
116                            message: format!(
117                                "attachment record {id} changed or was deleted before publication"
118                            ),
119                        });
120                    }
121                    let old = writer.query_row(prior).await?;
122                    if old
123                        .as_ref()
124                        .is_some_and(|row| row.text("substrate").ok() != Some(substrate.as_str()))
125                    {
126                        return Err(StorageError::InvalidInput {
127                            capability: StorageCapability::Attachments,
128                            operation: "attach".into(),
129                            message: format!("attachment record {id} has a conflicting substrate"),
130                        });
131                    }
132                    writer.execute(upsert).await?;
133                    Ok(Box::new(old.is_some()) as Box<dyn Any + Send>)
134                })
135            }))
136            .await?;
137        let replaced = *result.downcast::<bool>().map_err(|_| {
138            RuntimeError::Internal("attach transaction returned an unexpected result".into())
139        })?;
140        Ok((attachment, replaced))
141    }
142}