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.

44.6 KB
Raw Blame
//! Domain policies for channel side effects.

use crate::domain::{
    access_requests::ChannelAccessRequest,
    broker_events::{
        ChannelAccessRequestedMetadata, ChannelCreatedMetadata, ChannelDeletedMetadata,
        ChannelMacroEvent, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata,
        ChannelUpdatedMetadata,
    },
    events::ChannelEvent,
    mention_events::{EntityRef, MentionMacroEvent, MentionMetadata},
    models::{
        BotId, BotSenderProfile, ChannelMetadata, ChannelParticipant, ChannelType, MutatedMessage,
    },
    ports::{
        ChannelContactsDispatcher, ChannelEventDispatcher, ChannelEventHandler,
        ChannelNotificationSender, ChannelRealtimePublisher, ChannelSideEffectContext,
    },
};
use bot_id::BotIdStr;
use macro_event_broker::{MacroEventBroker, NoopMacroEventBroker};
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use messages::domain::models::{PostMessageNotificationPolicy, SimpleMention};
use std::collections::HashSet;
use tracing::Instrument as _;
use uuid::Uuid;

mod dm_email;

/// Parse a mention entity id in the canonical `bot|<uuid>` principal form.
fn mention_bot_id(entity_id: &str) -> Option<BotId> {
    BotIdStr::parse_from_str(entity_id)
        .ok()
        .map(|id| id.bot_id())
}

/// Whether a `user`-tagged mention actually targets a bot (and so must not be
/// treated as a user recipient). Real user ids are `macro|<email>` strings,
/// never `bot|<uuid>` principals, so this only matches the Macro AI bot
/// surfaced through the user-mention UI.
fn is_bot_user_mention(mention: &SimpleMention) -> bool {
    mention.entity_type == "user"
        && mention_bot_id(&mention.entity_id) == Some(bot_id::MACRO_AI_BOT_ID)
}

/// Realtime update requested by the channel domain.
#[derive(Debug, Clone)]
pub enum ChannelRealtimeEffect {
    /// Invalidate a channel picture after a durable change.
    PictureChanged {
        /// Recipients whose picture caches should be refreshed.
        recipients: Vec<MacroUserIdStr<'static>>,
        /// Channel whose picture changed.
        channel_id: Uuid,
    },
    /// Refresh a request to join after it was made or answered.
    AccessRequestChanged {
        /// Participants and the requester.
        recipients: Vec<MacroUserIdStr<'static>>,
        /// Channel the request is for.
        channel_id: Uuid,
        /// The changed attempt.
        request_id: Uuid,
    },
}

/// The sender of a channel message for notification purposes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NotificationSender {
    /// A user sender.
    User(MacroUserIdStr<'static>),
    /// A bot sender resolved to its public display name.
    Bot {
        /// Bot display name.
        name: String,
    },
}

impl NotificationSender {
    /// The sender's user id, when the sender is a user.
    pub fn as_user(&self) -> Option<&MacroUserIdStr<'static>> {
        match self {
            NotificationSender::User(id) => Some(id),
            NotificationSender::Bot { .. } => None,
        }
    }

    /// The sender's display name, when the sender is a bot.
    pub fn display_name(&self) -> Option<&str> {
        match self {
            NotificationSender::User(_) => None,
            NotificationSender::Bot { name } => Some(name),
        }
    }
}

/// Shared channel-message notification payload.
#[derive(Debug, Clone)]
pub struct ChannelMentionNotification {
    /// Channel containing the message.
    pub channel_id: Uuid,
    /// Message body.
    pub message_content: String,
    /// Message id.
    pub message_id: Uuid,
    /// Whether the message has attachments.
    pub has_attachments: bool,
    /// Optional thread parent id.
    pub thread_id: Option<Uuid>,
    /// Channel display metadata.
    pub metadata: ChannelMetadata,
    /// Optional sender profile picture URL.
    pub sender_profile_picture_url: Option<String>,
    /// Message sender.
    pub sender: NotificationSender,
}

/// Metadata for a mentioned document.
#[derive(Debug, Clone)]
pub struct ChannelDocumentMention {
    /// Document display name.
    pub document_name: String,
    /// Document owner.
    pub owner: MacroUserIdStr<'static>,
    /// Optional document file type.
    pub file_type: Option<String>,
    /// Optional document subtype.
    pub sub_type: Option<String>,
}

/// Thread context needed for reply notifications.
#[derive(Debug, Clone, Default)]
pub struct ThreadNotificationContext {
    /// Users participating in the thread.
    pub participants: Vec<MacroUserIdStr<'static>>,
    /// Sender of the thread parent message.
    pub parent_sender_id: Option<MacroUserIdStr<'static>>,
    /// People connected to the call, when the thread belongs to a live call.
    /// They read it in the call, so its notifications are dropped for them.
    /// They stay followers, and later replies reach them once they leave.
    pub connected_call_participants: Vec<MacroUserIdStr<'static>>,
}

/// Notification requested by the channel domain.
#[derive(Debug, Clone)]
pub enum ChannelNotificationEffect {
    /// A user was mentioned in a channel message.
    UserMention {
        /// Common mention payload.
        mention: ChannelMentionNotification,
        /// Users that should receive the notification.
        recipient_ids: HashSet<MacroUserIdStr<'static>>,
    },
    /// A document was mentioned in a channel message.
    DocumentMention {
        /// Common mention payload.
        mention: ChannelMentionNotification,
        /// Mentioned document metadata.
        document: ChannelDocumentMention,
        /// Users that should receive the notification.
        recipient_ids: HashSet<MacroUserIdStr<'static>>,
    },
    /// A reply was posted in a thread.
    Reply {
        /// Channel containing the message.
        channel_id: Uuid,
        /// Thread parent id.
        thread_id: Uuid,
        /// Reply message id.
        message_id: Uuid,
        /// Message sender.
        sender: NotificationSender,
        /// Reply body.
        message_content: String,
        /// Whether the reply has attachments.
        has_attachments: bool,
        /// Sender of the thread parent message.
        thread_parent_sender_id: Option<MacroUserIdStr<'static>>,
        /// Channel display metadata.
        metadata: ChannelMetadata,
        /// Optional sender profile picture URL.
        sender_profile_picture_url: Option<String>,
        /// Users that should receive the notification.
        recipient_ids: HashSet<MacroUserIdStr<'static>>,
    },
    /// A reaction was added to a user's message.
    Reaction {
        /// Channel containing the message.
        channel_id: Uuid,
        /// Reacted-to message id.
        message_id: Uuid,
        /// Root thread id when the message is a reply.
        thread_id: Option<Uuid>,
        /// Reacted-to message body.
        message_content: String,
        /// Emoji added by the reactor.
        emoji: String,
        /// User who added the reaction.
        sender_id: MacroUserIdStr<'static>,
        /// Channel display metadata.
        metadata: ChannelMetadata,
        /// Optional reactor profile picture URL.
        sender_profile_picture_url: Option<String>,
        /// Message author who should receive the notification.
        recipient_id: MacroUserIdStr<'static>,
    },
    /// A normal channel message was posted.
    ChannelMessage {
        /// Channel containing the message.
        channel_id: Uuid,
        /// Message id.
        message_id: Uuid,
        /// Message sender.
        sender: NotificationSender,
        /// Message body.
        message_content: String,
        /// Whether the message has attachments.
        has_attachments: bool,
        /// Channel display metadata.
        metadata: ChannelMetadata,
        /// Optional sender profile picture URL.
        sender_profile_picture_url: Option<String>,
        /// Users that should receive the notification.
        recipient_ids: HashSet<MacroUserIdStr<'static>>,
    },
    /// Someone asked to join a channel.
    AccessRequested {
        /// The new attempt.
        request: ChannelAccessRequest,
        /// Optional requester profile picture URL.
        sender_profile_picture_url: Option<String>,
        /// Channel display metadata.
        metadata: ChannelMetadata,
        /// Participants who may answer it.
        recipient_ids: HashSet<MacroUserIdStr<'static>>,
    },
    /// A request to join was answered or withdrawn; its notifications are done.
    AccessRequestResolved {
        /// The resolved attempt, which is also its notification id.
        request_id: Uuid,
        /// Participants who were notified about it.
        recipient_ids: HashSet<MacroUserIdStr<'static>>,
    },
    /// Participants were invited to a channel.
    Invite {
        /// Stable identity for a DM email; ordinary invitations have no message key.
        message_id: Option<Uuid>,
        /// Channel receiving participants.
        channel_id: Uuid,
        /// User that invited the participants.
        invited_by_user_id: MacroUserIdStr<'static>,
        /// Existing application users.
        registered_recipient_ids: HashSet<MacroUserIdStr<'static>>,
        /// Recipients that do not yet exist as application users.
        unregistered_recipient_ids: HashSet<MacroUserIdStr<'static>>,
        /// Optional inviter profile picture URL.
        sender_profile_picture_url: Option<String>,
        /// Optional message content associated with the invite.
        message_content: Option<String>,
        /// Channel display metadata.
        metadata: ChannelMetadata,
    },
}

/// Domain service that derives and dispatches side effects for channel events.
#[derive(Clone)]
pub struct ChannelSideEffectService<C, R, N, K, B = NoopMacroEventBroker> {
    context: C,
    realtime: R,
    notifications: N,
    contacts: K,
    macro_event_broker: B,
}

struct InviteNotificationRequest {
    message_id: Option<Uuid>,
    channel_id: Uuid,
    invited_by_user_id: MacroUserIdStr<'static>,
    recipient_user_ids: Vec<MacroUserIdStr<'static>>,
    existing_user_ids: HashSet<String>,
    sender_profile_picture_url: Option<String>,
    message_content: Option<String>,
    metadata: ChannelMetadata,
}

impl<C, R, N, K> ChannelSideEffectService<C, R, N, K> {
    /// Create a channel side-effect service that drops broker events.
    ///
    /// Use [`Self::with_macro_event_broker`] to publish channel events to the
    /// macro event broker.
    pub fn new(context: C, realtime: R, notifications: N, contacts: K) -> Self {
        Self {
            context,
            realtime,
            notifications,
            contacts,
            macro_event_broker: NoopMacroEventBroker,
        }
    }
}

impl<C, R, N, K, B> ChannelSideEffectService<C, R, N, K, B> {
    /// Configure a macro event broker to publish channel events to.
    pub fn with_macro_event_broker<B2: MacroEventBroker>(
        self,
        macro_event_broker: B2,
    ) -> ChannelSideEffectService<C, R, N, K, B2> {
        ChannelSideEffectService {
            context: self.context,
            realtime: self.realtime,
            notifications: self.notifications,
            contacts: self.contacts,
            macro_event_broker,
        }
    }
}

/// Channel event dispatcher that handles events on spawned tasks.
#[derive(Clone)]
pub struct SpawnedChannelEventDispatcher<H> {
    handler: H,
}

impl<H> SpawnedChannelEventDispatcher<H> {
    /// Create a spawned event dispatcher.
    pub fn new(handler: H) -> Self {
        Self { handler }
    }
}

impl<H> ChannelEventDispatcher for SpawnedChannelEventDispatcher<H>
where
    H: ChannelEventHandler,
{
    fn dispatch(&self, event: ChannelEvent) {
        let handler = self.handler.clone();
        tokio::spawn(agent_correlation::context::capture(
            async move {
                handler.handle(event).await;
            }
            .instrument(tracing::info_span!("channel.side_effects")),
        ));
    }
}

impl<C, R, N, K, B> ChannelEventHandler for ChannelSideEffectService<C, R, N, K, B>
where
    C: ChannelSideEffectContext + Clone,
    R: ChannelRealtimePublisher + Clone,
    N: ChannelNotificationSender + Clone,
    K: ChannelContactsDispatcher + Clone,
    B: MacroEventBroker + Clone,
{
    async fn handle(&self, event: ChannelEvent) {
        let contact_sync_users = contact_sync_users_for_event(&event);
        let broker_events = broker_events_for_event(&event);
        let mention_broker_events = mention_broker_events_for_event(&event);

        match event {
            ChannelEvent::PictureChanged {
                channel_id,
                recipients,
                ..
            } => {
                if let Err(error) = self
                    .realtime
                    .publish(ChannelRealtimeEffect::PictureChanged {
                        channel_id,
                        recipients,
                    })
                    .await
                {
                    let error: anyhow::Error = error.into();
                    tracing::error!(error=?error, "unable to publish channel picture change");
                }
            }
            ChannelEvent::ChannelCreated { .. } => {}
            ChannelEvent::ChannelUpdated { .. } => {}
            ChannelEvent::ParticipantsRemoved { .. } => {}
            ChannelEvent::EntityMentionCreated { .. } => {}
            ChannelEvent::EntityMentionDeleted { .. } => {}
            ChannelEvent::ChannelDeleted { .. } => {}
            ChannelEvent::MessagePosted {
                channel_id,
                metadata,
                participants,
                message,
                mentions,
                has_attachments,
                notification_policy,
            } => {
                if notification_policy == PostMessageNotificationPolicy::Silent {
                    return;
                }
                let bot_profile = self.bot_profile_for_message(&message).await;
                self.send_message_posted_notifications(PostedMessageNotificationInputs {
                    channel_id,
                    metadata,
                    participants,
                    message,
                    mentions,
                    has_attachments,
                    bot_profile,
                    notification_policy,
                })
                .await;
            }
            ChannelEvent::ReactionAdded {
                channel_id,
                actor,
                message_id,
                notification,
            } => {
                if let (Some(sender_id), Some(recipient_id)) = (
                    actor.as_user().cloned(),
                    notification.message_sender.as_user().cloned(),
                ) && sender_id != recipient_id
                {
                    let sender_profile_picture_url = self
                        .context
                        .get_sender_profile_picture_url(sender_id.clone())
                        .await;
                    self.send_notification(ChannelNotificationEffect::Reaction {
                        channel_id,
                        message_id,
                        thread_id: notification.thread_id,
                        message_content: notification.message_content,
                        emoji: notification.emoji,
                        sender_id,
                        metadata: notification.metadata,
                        sender_profile_picture_url,
                        recipient_id,
                    })
                    .await;
                }
            }
            ChannelEvent::ParticipantsAdded {
                channel_id,
                invited_by,
                recipient_user_ids,
                metadata,
                message_content,
                ..
            } => {
                if let Some(invited_by_user_id) = invited_by.as_user().cloned() {
                    self.send_participants_added_notification(
                        channel_id,
                        invited_by_user_id,
                        recipient_user_ids,
                        metadata,
                        message_content,
                    )
                    .await;
                }
            }
            ChannelEvent::ParticipantJoined { .. } => {}
            ChannelEvent::AccessRequested {
                request,
                participant_user_ids,
                metadata,
            } => {
                self.publish_access_request_change(&request, &participant_user_ids)
                    .await;
                let sender_profile_picture_url = self
                    .context
                    .get_sender_profile_picture_url(request.requester_id.clone())
                    .await;
                self.send_notification(ChannelNotificationEffect::AccessRequested {
                    request,
                    sender_profile_picture_url,
                    metadata,
                    recipient_ids: participant_user_ids.into_iter().collect(),
                })
                .await;
            }
            ChannelEvent::AccessRequestResolved {
                request,
                participant_user_ids,
            } => {
                self.publish_access_request_change(&request, &participant_user_ids)
                    .await;
                self.send_notification(ChannelNotificationEffect::AccessRequestResolved {
                    request_id: request.id,
                    recipient_ids: participant_user_ids.into_iter().collect(),
                })
                .await;
            }
        }

        if let Some(users) = contact_sync_users
            && let Err(err) = self.contacts.enqueue_contacts(users).await
        {
            let err: anyhow::Error = err.into();
            tracing::error!(error=?err, "unable to enqueue channel contact sync");
        }

        // Published after the other side effects so broker latency never
        // delays realtime updates or notifications; failures are logged and
        // dropped.
        for broker_event in broker_events {
            let _ = self
                .macro_event_broker
                .send_event(&broker_event)
                .inspect_err(|e| {
                    tracing::error!(error=?e, "failed to publish channel event");
                });
        }
        for mention_event in mention_broker_events {
            let _ = self
                .macro_event_broker
                .send_event(&mention_event)
                .inspect_err(|e| {
                    tracing::error!(error=?e, "failed to publish mention event");
                });
        }
    }
}

impl<C, R, N, K, B> ChannelSideEffectService<C, R, N, K, B>
where
    C: ChannelSideEffectContext + Clone,
    R: ChannelRealtimePublisher + Clone,
    N: ChannelNotificationSender + Clone,
    K: ChannelContactsDispatcher + Clone,
{
    /// Resolve the public bot profile when the message sender is a bot. A post
    /// a user made through a client, such as an MCP client, is that client's.
    async fn bot_profile_for_message(&self, message: &MutatedMessage) -> Option<BotSenderProfile> {
        let bot_id = message.sender_id.as_bot()?.bot_id();
        if let Some(client) = &message.triggered_via {
            return Some(BotSenderProfile {
                name: client.clone(),
                avatar_url: None,
            });
        }
        if bot_id == bot_id::MACRO_AI_BOT_ID {
            return Some(BotSenderProfile {
                name: bot_id::MACRO_AI_NAME.to_string(),
                avatar_url: None,
            });
        }
        self.context.get_bot_sender_profile(bot_id).await
    }

    /// Tell participants and the requester to refresh a request to join.
    async fn publish_access_request_change(
        &self,
        request: &ChannelAccessRequest,
        participant_user_ids: &[MacroUserIdStr<'static>],
    ) {
        let mut recipients = participant_user_ids.to_vec();
        recipients.push(request.requester_id.clone());
        if let Err(error) = self
            .realtime
            .publish(ChannelRealtimeEffect::AccessRequestChanged {
                recipients,
                channel_id: request.channel_id,
                request_id: request.id,
            })
            .await
        {
            let error: anyhow::Error = error.into();
            tracing::error!(error=?error, "unable to publish channel access request change");
        }
    }

    async fn send_notification(&self, effect: ChannelNotificationEffect) {
        if let Err(err) = self.notifications.send(effect).await {
            let err: anyhow::Error = err.into();
            tracing::error!(error=?err, "unable to dispatch channel notification event");
        }
    }

    async fn send_message_posted_notifications(&self, inputs: PostedMessageNotificationInputs) {
        let PostedMessageNotificationInputs {
            channel_id,
            metadata,
            participants,
            message,
            mentions,
            has_attachments,
            bot_profile,
            notification_policy,
        } = inputs;
        let resolved_sender = if let Some(user_id) = message.sender_id.as_user() {
            let user_id = user_id.clone();
            ResolvedNotificationSender {
                sender: NotificationSender::User(user_id.clone()),
                profile_picture_url: self
                    .context
                    .get_sender_profile_picture_url(user_id.clone())
                    .await,
            }
        } else if let Some(bot_id) = message.sender_id.as_bot().map(|id| id.bot_id()) {
            match bot_profile {
                Some(profile) => ResolvedNotificationSender {
                    sender: NotificationSender::Bot { name: profile.name },
                    profile_picture_url: profile.avatar_url,
                },
                None => {
                    tracing::warn!(bot_id = %bot_id, "missing bot profile, skipping message notifications");
                    return;
                }
            }
        } else {
            return;
        };
        let mut context = match self
            .build_posted_message_context(
                channel_id,
                metadata,
                &participants,
                &message,
                resolved_sender,
                mentions,
            )
            .await
        {
            Ok(context) => context,
            Err(err) => {
                tracing::error!(error=?err, "unable to build channel notification context");
                return;
            }
        };

        if notification_policy == PostMessageNotificationPolicy::Default {
            self.send_unregistered_dm_email(channel_id, &message, &mut context)
                .await;
        }

        self.send_user_mention_notifications(channel_id, &message, has_attachments, &context)
            .await;
        self.send_document_mention_notifications(channel_id, &message, has_attachments, &context)
            .await;

        if notification_policy == PostMessageNotificationPolicy::MentionsOnly {
            return;
        }

        if let Some(thread_id) = message.thread_id {
            self.send_reply_notification(
                thread_id,
                channel_id,
                &message,
                has_attachments,
                &context,
            )
            .await;
        } else if context.is_first_top_level_message && context.sender.as_user().is_some() {
            // Bot first messages fall through to a regular channel-message
            // notification; invites (which can email unregistered users) are
            // only sent on behalf of user senders.
            self.send_first_message_invites(channel_id, &message, context)
                .await;
        } else {
            self.send_channel_message_notification(channel_id, &message, has_attachments, &context)
                .await;
        }
    }

    async fn build_posted_message_context(
        &self,
        channel_id: Uuid,
        metadata: ChannelMetadata,
        participants: &[ChannelParticipant],
        message: &MutatedMessage,
        resolved_sender: ResolvedNotificationSender,
        mentions: Vec<SimpleMention>,
    ) -> anyhow::Result<PostedMessageNotificationContext> {
        let ResolvedNotificationSender {
            sender,
            profile_picture_url: sender_profile_picture_url,
        } = resolved_sender;
        let message_count = self
            .context
            .get_channel_message_count(channel_id)
            .await
            .map_err(Into::into)?;
        let is_first_top_level_message = message_count <= 1 && message.thread_id.is_none();

        let (user_mentions, document_mention_ids) = mentions.into_iter().fold(
            (Vec::new(), Vec::new()),
            |(mut users, mut docs), mention| {
                match mention.entity_type.as_str() {
                    // The Macro AI bot is mentioned via the user-mention UI; it
                    // is handled as a bot trigger, not a user notification.
                    "user" if !is_bot_user_mention(&mention) => users.push(mention.entity_id),
                    "document" => docs.push(mention.entity_id),
                    _ => {}
                }
                (users, docs)
            },
        );
        let document_mentions = self.load_document_mentions(document_mention_ids).await;
        let thread_context = self
            .load_thread_notification_context(message.thread_id)
            .await;
        let excluded_user_ids = sender
            .as_user()
            .map(|user_id| user_id.as_ref().to_string())
            .into_iter()
            .chain(user_mentions.iter().cloned())
            .chain(
                thread_context
                    .connected_call_participants
                    .iter()
                    .map(|user_id| user_id.as_ref().to_string()),
            )
            .collect::<Vec<_>>();
        let recipients_without_sender = recipients_excluding(
            participants
                .iter()
                .map(|participant| participant.user_id.as_str()),
            sender.as_user().map(|user_id| user_id.as_ref()),
        )
        .collect();
        let recipients_without_sender_and_mentions = recipients_excluding(
            participants
                .iter()
                .map(|participant| participant.user_id.as_str()),
            excluded_user_ids.iter().map(String::as_str),
        )
        .collect();

        Ok(PostedMessageNotificationContext {
            metadata,
            sender,
            sender_profile_picture_url,
            user_mentions,
            document_mentions,
            thread_context,
            excluded_user_ids,
            recipients_without_sender,
            recipients_without_sender_and_mentions,
            is_first_top_level_message,
        })
    }

    async fn load_document_mentions(
        &self,
        document_mention_ids: Vec<String>,
    ) -> Vec<ChannelDocumentMention> {
        if document_mention_ids.is_empty() {
            return Vec::new();
        }

        match self
            .context
            .get_document_mentions(document_mention_ids)
            .await
        {
            Ok(document_mentions) => document_mentions,
            Err(err) => {
                let err: anyhow::Error = err.into();
                tracing::error!(error=?err, "unable to get documents metadata");
                Vec::new()
            }
        }
    }

    async fn load_thread_notification_context(
        &self,
        thread_id: Option<Uuid>,
    ) -> ThreadNotificationContext {
        match thread_id {
            Some(thread_id) => self
                .context
                .get_thread_notification_context(thread_id)
                .await
                .unwrap_or_default(),
            None => ThreadNotificationContext::default(),
        }
    }

    async fn send_user_mention_notifications(
        &self,
        channel_id: Uuid,
        message: &MutatedMessage,
        has_attachments: bool,
        context: &PostedMessageNotificationContext,
    ) {
        if context.user_mentions.is_empty() {
            return;
        }

        self.send_notification(ChannelNotificationEffect::UserMention {
            mention: ChannelMentionNotification {
                channel_id,
                message_content: message.content.clone(),
                message_id: message.id,
                has_attachments,
                thread_id: message.thread_id,
                metadata: context.metadata.clone(),
                sender_profile_picture_url: context.sender_profile_picture_url.clone(),
                sender: context.sender.clone(),
            },
            recipient_ids: recipients_excluding(
                context.user_mentions.iter().map(String::as_str),
                context
                    .sender
                    .as_user()
                    .map(|user_id| user_id.as_ref())
                    .into_iter()
                    .chain(context.connected_in_thread()),
            )
            .collect(),
        })
        .await;
    }

    async fn send_document_mention_notifications(
        &self,
        channel_id: Uuid,
        message: &MutatedMessage,
        has_attachments: bool,
        context: &PostedMessageNotificationContext,
    ) {
        if context.document_mentions.is_empty() {
            return;
        }

        // A mention inside a thread is thread news, like the reply carrying it:
        // the notification is filed against the thread root, so sending it to
        // the whole channel would pull members who never joined the thread into
        // it. A top-level mention still reaches everyone, who see the message in
        // the channel anyway.
        let recipient_ids = match message.thread_id {
            Some(_) => recipients_excluding(
                context
                    .thread_context
                    .participants
                    .iter()
                    .map(|participant| participant.as_ref()),
                context
                    .sender
                    .as_user()
                    .map(|user_id| user_id.as_ref())
                    .into_iter()
                    .chain(context.connected_in_thread()),
            )
            .collect(),
            None => context.recipients_without_sender.clone(),
        };
        if recipient_ids.is_empty() {
            return;
        }

        for document in &context.document_mentions {
            self.send_notification(ChannelNotificationEffect::DocumentMention {
                mention: ChannelMentionNotification {
                    channel_id,
                    message_content: message.content.clone(),
                    message_id: message.id,
                    has_attachments,
                    thread_id: message.thread_id,
                    metadata: context.metadata.clone(),
                    sender_profile_picture_url: context.sender_profile_picture_url.clone(),
                    sender: context.sender.clone(),
                },
                document: document.clone(),
                recipient_ids: recipient_ids.clone(),
            })
            .await;
        }
    }

    async fn send_reply_notification(
        &self,
        thread_id: Uuid,
        channel_id: Uuid,
        message: &MutatedMessage,
        has_attachments: bool,
        context: &PostedMessageNotificationContext,
    ) {
        if context.thread_context.participants.is_empty() {
            tracing::warn!(thread_id = %thread_id, "thread participants is empty, but message has thread id");
            return;
        }

        self.send_notification(ChannelNotificationEffect::Reply {
            channel_id,
            thread_id,
            message_id: message.id,
            sender: context.sender.clone(),
            message_content: message.content.clone(),
            has_attachments,
            thread_parent_sender_id: context.thread_context.parent_sender_id.clone(),
            metadata: context.metadata.clone(),
            sender_profile_picture_url: context.sender_profile_picture_url.clone(),
            recipient_ids: recipients_excluding(
                context
                    .thread_context
                    .participants
                    .iter()
                    .map(|participant| participant.as_ref()),
                context.excluded_user_ids.iter().map(String::as_str),
            )
            .collect(),
        })
        .await;
    }

    async fn send_first_message_invites(
        &self,
        channel_id: Uuid,
        message: &MutatedMessage,
        context: PostedMessageNotificationContext,
    ) {
        let Some(invited_by_user_id) = context.sender.as_user().cloned() else {
            return;
        };
        let recipient_user_ids: Vec<_> = context
            .recipients_without_sender_and_mentions
            .into_iter()
            .collect();
        let existing_user_ids = match self
            .context
            .get_existing_user_ids(recipient_user_ids.clone())
            .await
        {
            Ok(existing_user_ids) => existing_user_ids,
            Err(err) => {
                let err: anyhow::Error = err.into();
                tracing::error!(error=?err, "unable to get existing users for first-message invite");
                return;
            }
        };
        self.send_invite_notification(InviteNotificationRequest {
            message_id: (context.metadata.channel_type == ChannelType::DirectMessage)
                .then_some(message.id),
            channel_id,
            invited_by_user_id,
            recipient_user_ids,
            existing_user_ids,
            sender_profile_picture_url: context.sender_profile_picture_url,
            message_content: Some(message.content.clone()),
            metadata: context.metadata,
        })
        .await;
    }

    async fn send_channel_message_notification(
        &self,
        channel_id: Uuid,
        message: &MutatedMessage,
        has_attachments: bool,
        context: &PostedMessageNotificationContext,
    ) {
        self.send_notification(ChannelNotificationEffect::ChannelMessage {
            channel_id,
            message_id: message.id,
            sender: context.sender.clone(),
            message_content: message.content.clone(),
            has_attachments,
            metadata: context.metadata.clone(),
            sender_profile_picture_url: context.sender_profile_picture_url.clone(),
            recipient_ids: context.recipients_without_sender_and_mentions.clone(),
        })
        .await;
    }

    async fn send_participants_added_notification(
        &self,
        channel_id: Uuid,
        invited_by_user_id: MacroUserIdStr<'static>,
        recipient_user_ids: Vec<MacroUserIdStr<'static>>,
        metadata: ChannelMetadata,
        message_content: Option<String>,
    ) {
        let sender_profile_picture_url = self
            .context
            .get_sender_profile_picture_url(invited_by_user_id.clone())
            .await;
        let existing_user_ids = match self
            .context
            .get_existing_user_ids(recipient_user_ids.clone())
            .await
        {
            Ok(existing_user_ids) => existing_user_ids,
            Err(err) => {
                let err: anyhow::Error = err.into();
                tracing::error!(error=?err, "unable to get existing users for invite");
                HashSet::new()
            }
        };

        self.send_invite_notification(InviteNotificationRequest {
            message_id: None,
            channel_id,
            invited_by_user_id,
            recipient_user_ids,
            existing_user_ids,
            sender_profile_picture_url,
            message_content,
            metadata,
        })
        .await;
    }

    async fn send_invite_notification(&self, req: InviteNotificationRequest) {
        let InviteNotificationRequest {
            message_id,
            channel_id,
            invited_by_user_id,
            recipient_user_ids,
            existing_user_ids,
            sender_profile_picture_url,
            message_content,
            metadata,
        } = req;
        let (registered_recipient_ids, unregistered_recipient_ids): (HashSet<_>, HashSet<_>) =
            recipient_user_ids
                .into_iter()
                .partition(|id| existing_user_ids.contains(id.as_ref()));

        self.send_notification(ChannelNotificationEffect::Invite {
            message_id,
            channel_id,
            invited_by_user_id,
            registered_recipient_ids,
            unregistered_recipient_ids,
            sender_profile_picture_url,
            message_content,
            metadata,
        })
        .await;
    }
}

/// Inputs for deriving notifications from a posted message.
struct PostedMessageNotificationInputs {
    channel_id: Uuid,
    metadata: ChannelMetadata,
    participants: Vec<ChannelParticipant>,
    message: MutatedMessage,
    mentions: Vec<SimpleMention>,
    has_attachments: bool,
    bot_profile: Option<BotSenderProfile>,
    notification_policy: PostMessageNotificationPolicy,
}

/// Sender identity and avatar resolved for notification delivery.
struct ResolvedNotificationSender {
    sender: NotificationSender,
    profile_picture_url: Option<String>,
}

struct PostedMessageNotificationContext {
    metadata: ChannelMetadata,
    sender: NotificationSender,
    sender_profile_picture_url: Option<String>,
    user_mentions: Vec<String>,
    document_mentions: Vec<ChannelDocumentMention>,
    thread_context: ThreadNotificationContext,
    excluded_user_ids: Vec<String>,
    recipients_without_sender: HashSet<MacroUserIdStr<'static>>,
    recipients_without_sender_and_mentions: HashSet<MacroUserIdStr<'static>>,
    is_first_top_level_message: bool,
}

impl PostedMessageNotificationContext {
    /// Who the thread's call is showing this message to already.
    fn connected_in_thread(&self) -> impl Iterator<Item = &str> {
        self.thread_context
            .connected_call_participants
            .iter()
            .map(|user_id| user_id.as_ref())
    }
}

/// Whether a participant principal id refers to a bot (e.g. `bot|<uuid>`).
/// Bots are not user recipients and are not valid `MacroUserIdStr`s, so they are
/// skipped before parsing to avoid spurious parse warnings.
fn is_bot_principal(id: &str) -> bool {
    BotIdStr::parse_from_str(id).is_ok()
}

fn recipients_excluding<'a>(
    recipients: impl IntoIterator<Item = &'a str>,
    exclude: impl IntoIterator<Item = &'a str>,
) -> impl Iterator<Item = MacroUserIdStr<'static>> {
    let exclude_set: HashSet<&str> = exclude.into_iter().collect();
    recipients
        .into_iter()
        .filter(move |id| !exclude_set.contains(id))
        .filter(|id| !is_bot_principal(id))
        .filter_map(|id| MacroUserIdStr::parse_from_str(id).ok())
        .map(|u| u.into_owned())
}

fn contact_sync_users_for_event(event: &ChannelEvent) -> Option<HashSet<MacroUserIdStr<'static>>> {
    match event {
        ChannelEvent::ChannelCreated {
            channel_type: ChannelType::Private | ChannelType::DirectMessage,
            actor,
            on_behalf_of,
            participant_user_ids,
            ..
        } if actor.as_user().is_some() || on_behalf_of.is_some() => {
            Some(participant_user_ids.iter().cloned().collect())
        }
        ChannelEvent::ParticipantsAdded {
            channel_type: ChannelType::Private | ChannelType::Team,
            invited_by,
            active_participant_user_ids,
            ..
        } if invited_by.as_user().is_some() => {
            Some(active_participant_user_ids.iter().cloned().collect())
        }
        ChannelEvent::ParticipantJoined {
            channel_type: ChannelType::Public | ChannelType::Private | ChannelType::Team,
            user_id,
            active_participant_user_ids,
            ..
        } if user_id.as_user().is_some() && active_participant_user_ids.len() > 1 => {
            Some(active_participant_user_ids.iter().cloned().collect())
        }
        _ => None,
    }
}

/// Map an internal channel event to the wire events published to the
/// `macro.channels` topic.
fn broker_events_for_event(event: &ChannelEvent) -> Vec<ChannelMacroEvent> {
    match event {
        ChannelEvent::PictureChanged {
            channel_id, actor, ..
        } => vec![ChannelMacroEvent::picture_changed(
            super::broker_events::ChannelPictureChangedMetadata {
                channel_id: *channel_id,
                actor: actor.clone(),
            },
        )],
        ChannelEvent::ChannelCreated {
            channel_id,
            actor,
            on_behalf_of,
            channel_type,
            channel_name,
            participant_user_ids,
        } => vec![ChannelMacroEvent::created(ChannelCreatedMetadata {
            channel_id: *channel_id,
            actor: actor.clone(),
            on_behalf_of: on_behalf_of.clone(),
            channel_type: *channel_type,
            channel_name: channel_name.clone(),
            participant_user_ids: participant_user_ids.clone(),
        })],
        ChannelEvent::ChannelUpdated {
            channel_id,
            actor,
            previous_name,
            channel_name,
        } => vec![ChannelMacroEvent::updated(ChannelUpdatedMetadata {
            channel_id: *channel_id,
            actor: actor.clone(),
            previous_name: previous_name.clone(),
            channel_name: channel_name.clone(),
        })],
        ChannelEvent::ChannelDeleted { channel_id, actor } => {
            vec![ChannelMacroEvent::deleted(ChannelDeletedMetadata {
                channel_id: *channel_id,
                actor: actor.clone(),
            })]
        }
        // Message facts travel on `macro.messages` with their parent.
        ChannelEvent::MessagePosted { .. } | ChannelEvent::ReactionAdded { .. } => Vec::new(),
        ChannelEvent::ParticipantsAdded {
            channel_id,
            channel_type,
            invited_by,
            recipient_user_ids,
            ..
        } => vec![ChannelMacroEvent::participant_added(
            ChannelParticipantAddedMetadata {
                channel_id: *channel_id,
                channel_type: *channel_type,
                added_by: invited_by.clone(),
                added_user_ids: recipient_user_ids.clone(),
            },
        )],
        ChannelEvent::ParticipantJoined {
            channel_id,
            channel_type,
            user_id,
            ..
        } => user_id
            .as_user()
            .map(|joined| {
                vec![ChannelMacroEvent::participant_added(
                    ChannelParticipantAddedMetadata {
                        channel_id: *channel_id,
                        channel_type: *channel_type,
                        added_by: user_id.clone(),
                        added_user_ids: vec![joined.clone()],
                    },
                )]
            })
            .unwrap_or_default(),
        ChannelEvent::ParticipantsRemoved {
            channel_id,
            channel_type,
            actor,
            removed_user_ids,
        } => vec![ChannelMacroEvent::participant_removed(
            ChannelParticipantRemovedMetadata {
                channel_id: *channel_id,
                channel_type: *channel_type,
                removed_by: actor.clone(),
                removed_user_ids: removed_user_ids.clone(),
            },
        )],
        ChannelEvent::AccessRequested { request, .. } => {
            vec![ChannelMacroEvent::access_requested(
                ChannelAccessRequestedMetadata {
                    channel_id: request.channel_id,
                    request_id: request.id,
                    requester_id: request.requester_id.clone(),
                },
            )]
        }
        ChannelEvent::EntityMentionCreated { .. }
        | ChannelEvent::EntityMentionDeleted { .. }
        | ChannelEvent::AccessRequestResolved { .. } => Vec::new(),
    }
}

/// Map an internal channel event to the wire events published to the
/// `macro.mentions` topic.
///
/// Channel messages publish on-send only (`message.sent`, no on-delete for
/// message mentions); generic entity mentions (e.g. docs) publish on-create
/// and on-delete (`mention.created`/`mention.deleted`).
fn mention_broker_events_for_event(event: &ChannelEvent) -> Vec<MentionMacroEvent> {
    match event {
        ChannelEvent::MessagePosted {
            message, mentions, ..
        } => mentions
            .iter()
            .map(|mention| {
                MentionMacroEvent::message_sent(MentionMetadata {
                    source: EntityRef {
                        id: message.id.to_string(),
                        kind: "message".to_string(),
                    },
                    mentioned: EntityRef {
                        id: mention.entity_id.clone(),
                        kind: mention.entity_type.clone(),
                    },
                })
            })
            .collect(),
        ChannelEvent::EntityMentionCreated { mention } => {
            vec![MentionMacroEvent::created(mention.into())]
        }
        ChannelEvent::EntityMentionDeleted { mention } => {
            vec![MentionMacroEvent::deleted(mention.into())]
        }
        _ => Vec::new(),
    }
}

#[cfg(test)]
mod test;