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.

6.8 KB
Raw Blame
use super::models::MarkedPassage;
use super::ports::{CommentMarks, ConversationAccess};
use async_trait::async_trait;
use entity_access::domain::models::{
    AccessLevel, BotReceiptScope, EntityAccessReceipt, EntityPermission, EntityType,
    ParticipantRole,
};
use macro_user_id::user_id::MacroUserIdStr;
use messages::domain::{
    api::MockMessageServiceApi,
    events::MessagePostedMetadata,
    models::{Message, MessageParent, MessageThread, ThreadAnchor, ThreadState},
    service::MessageWrite,
};
use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
};
use uuid::Uuid;

pub(super) struct Admission {
    pub result: Result<(), ai_billing::AiAdmissionError>,
    pub calls: std::sync::atomic::AtomicUsize,
}

impl Admission {
    pub fn new(result: Result<(), ai_billing::AiAdmissionError>) -> Arc<Self> {
        Arc::new(Self {
            result,
            calls: std::sync::atomic::AtomicUsize::new(0),
        })
    }
}

impl ai_billing::AiAdmissionService for Admission {
    fn admit<'a>(
        &'a self,
        caller: &'a MacroUserIdStr<'_>,
        feature: ai_billing::AiFeature,
    ) -> ai_billing::AdmissionFuture<'a> {
        assert_eq!(caller, &user());
        assert_eq!(feature, ai_billing::AiFeature::ChannelBot);
        self.calls.fetch_add(1, Ordering::SeqCst);
        Box::pin(async { self.result })
    }
}

pub(super) fn admission_failures() -> [ai_billing::AiAdmissionError; 2] {
    [
        ai_billing::AiAdmissionError::Denied(ai_billing::DenyReason::AllowanceExhausted),
        ai_billing::AiAdmissionError::Unavailable,
    ]
}

pub(super) fn user() -> MacroUserIdStr<'static> {
    "macro|[email protected]".to_string().try_into().unwrap()
}
pub(super) fn parent() -> MessageParent {
    MessageParent::parse("document", "discussion-document").unwrap()
}
pub(crate) fn message(id: u128, thread: Option<Uuid>, body: &str) -> Message {
    Message {
        kind: messages::domain::models::MessageKind::Message,
        id: Uuid::from_u128(id),
        parent: parent(),
        thread_id: thread,
        sender_id: channel_sender::ChannelSender::new_from_user(user()),
        bot_profile: None,
        mentions: vec![],
        guest_name: None,
        imported_author: None,
        triggered_via: None,
        triggered_by: None,
        content: body.into(),
        created_at: chrono::Utc::now(),
        updated_at: chrono::Utc::now(),
        edited_at: None,
        deleted_at: None,
        attachments: vec![],
        reactions: vec![],
    }
}
pub(super) fn event(message: &Message) -> MessagePostedMetadata {
    MessagePostedMetadata::from_message(message, message.mentions.clone())
}
pub(super) fn thread(root: Message, replies: Vec<Message>) -> MessageThread {
    MessageThread {
        state: ThreadState {
            root_id: root.id,
            user_id: user().to_string(),
            anchor: None,
            resolved: false,
            created_at: root.created_at,
            updated_at: root.updated_at,
            deleted_at: None,
        },
        root,
        replies,
    }
}
/// A discussion anchored to marked document text, as the editor records it.
pub(super) fn marked_thread(root: Message, marked_text: Option<&str>) -> MessageThread {
    let mut thread = thread(root, vec![]);
    thread.state.anchor = Some(ThreadAnchor::Markdown {
        mark_id: Uuid::from_u128(0xaa),
        marked_text: marked_text.map(ToOwned::to_owned),
    });
    thread
}
pub(super) fn configure_reads(
    api: &mut MockMessageServiceApi,
    trigger: &Message,
    history: MessageThread,
) {
    let current = trigger.clone();
    api.expect_get().returning(move |receipt, id| {
        assert_eq!(receipt.entity().entity_id, current.parent.entity_id());
        assert_eq!(id, current.id);
        Ok(current.clone())
    });
    api.expect_get_thread().returning(move |receipt, id| {
        assert_eq!(receipt.entity().entity_id, history.root.parent.entity_id());
        assert_eq!(id, history.root.id);
        Ok(history.clone())
    });
}
/// Live mark lookups answering one fixed result.
pub(super) struct Marks(pub Result<Option<MarkedPassage>, &'static str>);
impl Marks {
    pub fn none() -> Arc<Self> {
        Arc::new(Self(Ok(None)))
    }
}
#[async_trait]
impl CommentMarks for Marks {
    async fn resolve(
        &self,
        document_id: &str,
        _mark_id: Uuid,
    ) -> anyhow::Result<Option<MarkedPassage>> {
        assert_eq!(document_id, "discussion-document");
        self.0.clone().map_err(|error| anyhow::anyhow!(error))
    }
}
#[derive(Default)]
pub(super) struct Access {
    pub revoked: Arc<AtomicBool>,
}
impl Access {
    pub fn revoke(&self) {
        self.revoked.store(true, Ordering::SeqCst);
    }
    fn permission(
        &self,
        parent: &MessageParent,
    ) -> Result<(entity_access::domain::models::Entity, EntityPermission), rootcause::Report> {
        if self.revoked.load(Ordering::SeqCst) {
            return Err(rootcause::report!("document access revoked"));
        }
        Ok(match parent {
            MessageParent::Document(_)
            | MessageParent::Call(_)
            | MessageParent::Initiative(_)
            | MessageParent::CrmCompany(_)
            | MessageParent::CrmContact(_) => (
                entity_access::domain::models::Entity {
                    entity_type: parent.access_entity_type(),
                    entity_id: parent.entity_id(),
                },
                EntityPermission::AccessLevel {
                    access_level: AccessLevel::Comment,
                },
            ),
            MessageParent::Channel(_) => (
                entity_access::domain::models::Entity {
                    entity_type: EntityType::Channel,
                    entity_id: parent.entity_id(),
                },
                EntityPermission::ChannelRole {
                    role: ParticipantRole::Member,
                },
            ),
        })
    }
}
#[async_trait]
impl ConversationAccess for Access {
    async fn user_write(
        &self,
        user: &MacroUserIdStr<'static>,
        parent: &MessageParent,
    ) -> Result<EntityAccessReceipt<MessageWrite>, rootcause::Report> {
        let (entity, permission) = self.permission(parent)?;
        Ok(EntityAccessReceipt::try_new_authenticated_user(
            user.clone(),
            entity,
            permission,
        )?)
    }
    async fn bot_write(
        &self,
        user: &MacroUserIdStr<'static>,
        parent: &MessageParent,
    ) -> Result<EntityAccessReceipt<MessageWrite>, rootcause::Report> {
        let (entity, permission) = self.permission(parent)?;
        Ok(EntityAccessReceipt::try_new_bot(
            bot_id::MACRO_AI_BOT_ID.into_storage_id(),
            BotReceiptScope::User {
                acting_user: user.clone(),
            },
            entity,
            permission,
        )?)
    }
}