Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

12.1 KB
Raw Blame
//! [`AttachmentService`] implementation for documents.

use std::str::FromStr;
use std::sync::Arc;

use attachment::image::ImageData;
use attachment::{
    AttachmentContent, AttachmentError, AttachmentPart, AttachmentService, Attachments,
    ResolutionError,
};
use entity_access::domain::{
    models::{EntityAccessReceipt, ViewAccessLevel},
    ports::EntityAccessService,
};
use futures::future::join_all;
use lexical_client::LexicalClient;
use macro_user_id::user_id::MacroUserIdStr;
use model::document::DocumentBasic;
use model_entity::{Entity, EntityType};
use model_file_type::{FileAssociation, FileType};
use non_empty::NonEmpty;

use crate::domain::{
    models::LocationQueryParams, ports::DocumentService, response::LocationResponseV3,
};

use super::markdown;

/// Resolves document IDs into [`Attachments`].
pub struct DocumentAttachmentService<DSvc, ESvc> {
    pub(super) document_service: Arc<DSvc>,
    pub(super) entity_access_service: Arc<ESvc>,
    pub(super) lexical_client: Arc<LexicalClient>,
}

impl<DSvc, ESvc> DocumentAttachmentService<DSvc, ESvc> {
    /// Create a new document attachment service.
    pub fn new(
        document_service: Arc<DSvc>,
        entity_access_service: Arc<ESvc>,
        lexical_client: Arc<LexicalClient>,
    ) -> Self {
        Self {
            document_service,
            entity_access_service,
            lexical_client,
        }
    }
}

impl<DSvc: DocumentService, ESvc: EntityAccessService> AttachmentService
    for DocumentAttachmentService<DSvc, ESvc>
{
    #[tracing::instrument(skip_all)]
    async fn resolve_attachments<'a>(
        &self,
        user_id: MacroUserIdStr<'_>,
        ids: NonEmpty<&[&'a Entity<'a>]>,
    ) -> Attachments<'a> {
        let user_id = &user_id;
        let results = join_all(ids.iter().map(|entity| async move {
            let owned_ref = entity
                .entity_type
                .with_entity_string(entity.entity_id.to_string());
            match entity.entity_type {
                EntityType::Document => self
                    .resolve_document(user_id, &entity.entity_id)
                    .await
                    .map_err(|error| ResolutionError::new(owned_ref, error)),
                EntityType::Project => self
                    .resolve_project(user_id, &entity.entity_id)
                    .await
                    .map_err(|error| ResolutionError::new(owned_ref, error)),
                EntityType::Skill => self
                    .resolve_skill(user_id, &entity.entity_id)
                    .await
                    .map_err(|error| ResolutionError::new(owned_ref, error)),
                other => Err(ResolutionError::new(
                    owned_ref,
                    AttachmentError::RoutingError("DocumentAttachmentService".to_string(), other),
                )),
            }
        }))
        .await;
        Attachments::new(NonEmpty::new(results).expect("ids was non-empty"))
    }
}

impl<DSvc: DocumentService, ESvc: EntityAccessService> DocumentAttachmentService<DSvc, ESvc> {
    #[tracing::instrument(skip(self), err)]
    async fn resolve_project(
        &self,
        user_id: &MacroUserIdStr<'_>,
        id: &str,
    ) -> Result<AttachmentContent<'static>, AttachmentError> {
        self.entity_access_service
            .generate_entity_access_receipt::<ViewAccessLevel>(
                user_id,
                None,
                id,
                EntityType::Project,
            )
            .await
            .map_err(|e| AttachmentError::PermissionDenied(Box::new(e)))?;

        let name = self
            .document_service
            .get_project_name(id)
            .await
            .map_err(|e| AttachmentError::Internal(e.into()))?;

        let children = self
            .document_service
            .get_project_children(id)
            .await
            .map_err(|e| AttachmentError::Internal(e.into()))?;

        let content: Vec<AttachmentPart<'static>> = children
            .into_iter()
            .map(AttachmentPart::ChildReference)
            .collect();

        let content = NonEmpty::new(content).map_err(|_| AttachmentError::NoContent)?;

        Ok(AttachmentContent {
            reference: EntityType::Project.with_entity_string(id.to_string()),
            name: Some(name),
            content,
        })
    }

    /// Resolve a skill reference: either a built-in system skill (static,
    /// code-defined content with a well-known id, visible to every user) or a
    /// skill document (an ordinary markdown document with the skill sub-type,
    /// access-checked like any other document).
    #[tracing::instrument(skip(self), err)]
    async fn resolve_skill(
        &self,
        user_id: &MacroUserIdStr<'_>,
        id: &str,
    ) -> Result<AttachmentContent<'static>, AttachmentError> {
        if let Some(skill) = uuid::Uuid::from_str(id)
            .ok()
            .and_then(system_skills::system_skill)
        {
            return Ok(AttachmentContent {
                reference: EntityType::Skill.with_entity_string(id.to_string()),
                name: Some(skill.name.to_string()),
                content: NonEmpty::new(vec![
                    skill_type_metadata(),
                    AttachmentPart::Content(skill.render_content()),
                ])
                .expect("content is non-empty"),
            });
        }

        self.entity_access_service
            .generate_entity_access_receipt::<ViewAccessLevel>(
                user_id,
                None,
                id,
                EntityType::Document,
            )
            .await
            .map_err(|e| AttachmentError::PermissionDenied(Box::new(e)))?;

        let document = self
            .document_service
            .internal_get_basic_document(id)
            .await
            .map_err(|e| AttachmentError::Internal(e.into()))?;

        let mut content = markdown::resolve_markdown(self, user_id, id, &document).await?;
        content.reference = EntityType::Skill.with_entity_string(id.to_string());
        Ok(content)
    }

    #[tracing::instrument(skip(self), err)]
    async fn resolve_document(
        &self,
        user_id: &MacroUserIdStr<'_>,
        id: &str,
    ) -> Result<AttachmentContent<'static>, AttachmentError> {
        let receipt = self
            .entity_access_service
            .generate_entity_access_receipt(user_id, None, id, EntityType::Document)
            .await
            .map_err(|e| AttachmentError::Internal(e.into()))?;

        let document = self
            .document_service
            .internal_get_basic_document(id)
            .await
            .map_err(|e| AttachmentError::PermissionDenied(Box::new(e)))?;

        let file_type = document
            .file_type
            .as_ref()
            .ok_or(AttachmentError::UnknownFileType)
            .and_then(|ft| {
                FileType::from_str(ft).map_err(|_| AttachmentError::UnsupportedFileType(ft.clone()))
            })?;

        if let Some(context) = crate::domain::content::spreadsheet_attachment_context(&document)
            .or_else(|| crate::domain::content::presentation_attachment_context(&document))
            .or_else(|| crate::domain::content::design_attachment_context(&document))
            .or_else(|| crate::domain::content::photoshop_attachment_context(&document))
            .or_else(|| crate::domain::content::illustrator_attachment_context(&document))
        {
            return Ok(AttachmentContent {
                reference: EntityType::Document.with_entity_string(id.to_string()),
                name: Some(document.document_name),
                content: NonEmpty::one(AttachmentPart::Content(context)),
            });
        }

        let content = match file_type.macro_app_path() {
            FileAssociation::Pdf(_) | FileAssociation::Write(_) => {
                let text = self
                    .document_service
                    .get_document_text(receipt)
                    .await
                    .map_err(|e| AttachmentError::Internal(e.into()))?;
                let mut parts = vec![AttachmentPart::Content(text)];
                if let Some(context) =
                    crate::domain::content::word_document_attachment_context(&document)
                {
                    parts.push(AttachmentPart::Content(context));
                }
                NonEmpty::new(parts).expect("content is non-empty")
            }
            FileAssociation::Md(_) => {
                return markdown::resolve_markdown(self, user_id, id, &document).await;
            }
            FileAssociation::Code(_) | FileAssociation::Document(_) => {
                let text = self.get_text_from_location(&document, receipt).await?;
                NonEmpty::one(AttachmentPart::Content(text))
            }
            FileAssociation::Image(_) => {
                let data = self.get_image_from_location(&document, receipt).await?;
                NonEmpty::one(AttachmentPart::Image(data))
            }
            _ => return Err(AttachmentError::UnsupportedFileType(file_type.to_string())),
        };

        Ok(AttachmentContent {
            reference: EntityType::Document.with_entity_string(id.to_string()),
            name: Some(document.document_name.clone()),
            content,
        })
    }

    pub(super) async fn get_text_from_location(
        &self,
        document: &DocumentBasic,
        receipt: EntityAccessReceipt<ViewAccessLevel>,
    ) -> Result<String, AttachmentError> {
        let url = self.presigned_url_for(document, receipt).await?;
        let bytes = fetch_url_bytes(&url).await?;
        String::from_utf8(bytes).map_err(|e| {
            AttachmentError::Internal(anyhow::anyhow!("document content is not valid UTF-8: {e}"))
        })
    }

    pub(super) async fn get_image_from_location(
        &self,
        document: &DocumentBasic,
        receipt: EntityAccessReceipt<ViewAccessLevel>,
    ) -> Result<ImageData, AttachmentError> {
        let url = self.presigned_url_for(document, receipt).await?;
        let bytes = fetch_url_bytes(&url).await?;
        ImageData::try_from_bytes(bytes).map_err(AttachmentError::Internal)
    }

    pub(super) async fn presigned_url_for(
        &self,
        document: &DocumentBasic,
        receipt: EntityAccessReceipt<ViewAccessLevel>,
    ) -> Result<String, AttachmentError> {
        let location = self
            .document_service
            .get_document_location(
                document,
                receipt,
                LocationQueryParams {
                    get_converted_docx_url: Some(true),
                    document_version_id: None,
                },
            )
            .await
            .map_err(|e| AttachmentError::Internal(e.into()))?;

        match location {
            LocationResponseV3::PresignedUrl { presigned_url, .. } => Ok(presigned_url),
            _ => Err(AttachmentError::Internal(anyhow::anyhow!(
                "unexpected location response for document"
            ))),
        }
    }
}

/// Metadata part marking an attachment as a skill, so the AI treats its
/// content as instructions to follow (see the `skills` section of the system
/// prompt) rather than as a document under discussion.
pub(super) fn skill_type_metadata() -> AttachmentPart<'static> {
    AttachmentPart::Metadata {
        key: "type".to_string(),
        value: "skill".to_string(),
    }
}

pub(super) async fn fetch_url_bytes(url: &str) -> Result<Vec<u8>, AttachmentError> {
    // Presigned/distribution URLs are minted with the browser-facing `localhost`
    // host; rewrite to the in-network LocalStack host so this server-side fetch
    // works inside Docker. No-op outside local AWS.
    let url = macro_aws_config::transform_aws_url_for_internal_fetch(url);
    let url = url.as_str();
    let response = reqwest::get(url)
        .await
        .map_err(|e| AttachmentError::Internal(e.into()))?;
    if !response.status().is_success() {
        return Err(AttachmentError::Internal(anyhow::anyhow!(
            "failed to fetch {url}: HTTP {}",
            response.status()
        )));
    }
    response
        .bytes()
        .await
        .map(|b| b.to_vec())
        .map_err(|e| AttachmentError::Internal(e.into()))
}