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.

feat(channels): generalize mentions into a macro.mentions Kafka topic (#5125)

Eric Hayes2096abb92bc3
diff --git a/.github/kafka-cluster-topics.json b/.github/kafka-cluster-topics.json
index 461a84a529..0f2caa1020 100644
--- a/.github/kafka-cluster-topics.json
+++ b/.github/kafka-cluster-topics.json
@@ -4,6 +4,7 @@
"macro.documents",
"macro.email",
"macro.example",
+ "macro.mentions",
"macro.projects",
"macro.soup",
"macro.teams",
diff --git a/.sqlx/query-2c43085ba82d0b0d8eaed4069d88ff07b946b491d99000290a84f7c80b8916c0.json b/.sqlx/query-2c43085ba82d0b0d8eaed4069d88ff07b946b491d99000290a84f7c80b8916c0.json
new file mode 100644
index 0000000000..2469fff07b
--- /dev/null
+++ b/.sqlx/query-2c43085ba82d0b0d8eaed4069d88ff07b946b491d99000290a84f7c80b8916c0.json
@@ -0,0 +1,58 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM comms_entity_mentions\n WHERE id = $1\n RETURNING id, source_entity_type, source_entity_id, entity_type, entity_id, user_id, created_at\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "source_entity_type",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 2,
+ "name": "source_entity_id",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 3,
+ "name": "entity_type",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "entity_id",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 5,
+ "name": "user_id",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false
+ ]
+ },
+ "hash": "2c43085ba82d0b0d8eaed4069d88ff07b946b491d99000290a84f7c80b8916c0"
+}
diff --git a/.sqlx/query-f1afe1bb26ffc5e97fe3a5db39ca0fe594d449939c99f3dd8e338aff9d26753b.json b/.sqlx/query-f1afe1bb26ffc5e97fe3a5db39ca0fe594d449939c99f3dd8e338aff9d26753b.json
deleted file mode 100644
index cbe9dea652..0000000000
--- a/.sqlx/query-f1afe1bb26ffc5e97fe3a5db39ca0fe594d449939c99f3dd8e338aff9d26753b.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n DELETE FROM comms_entity_mentions\n WHERE id = $1\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "f1afe1bb26ffc5e97fe3a5db39ca0fe594d449939c99f3dd8e338aff9d26753b"
-}
diff --git a/crates/channels/src/domain/events.rs b/crates/channels/src/domain/events.rs
index e5506c3fb3..500fda4543 100644
--- a/crates/channels/src/domain/events.rs
+++ b/crates/channels/src/domain/events.rs
@@ -1,8 +1,9 @@
//! Domain events emitted by channel mutation workflows.
use crate::domain::models::{
- ChannelMetadata, ChannelParticipant, ChannelType, CountedReaction, MutatedAttachment,
- MutatedMessage, PostMessageNotificationPolicy, Sender, SimpleMention, TypingAction,
+ ChannelMetadata, ChannelParticipant, ChannelType, CountedReaction, EntityMention,
+ MutatedAttachment, MutatedMessage, PostMessageNotificationPolicy, Sender, SimpleMention,
+ TypingAction,
};
use channel_sender::ChannelSender;
use macro_user_id::user_id::MacroUserIdStr;
@@ -193,4 +194,14 @@ pub enum ChannelEvent {
/// Users removed by this mutation.
removed_user_ids: Vec<MacroUserIdStr<'static>>,
},
+ /// A generic entity mention (e.g. a doc mentioning another entity) was recorded.
+ EntityMentionCreated {
+ /// The persisted mention row.
+ mention: EntityMention,
+ },
+ /// A generic entity mention was removed.
+ EntityMentionDeleted {
+ /// The mention row that was deleted.
+ mention: EntityMention,
+ },
}
diff --git a/crates/channels/src/domain/mention_events.rs b/crates/channels/src/domain/mention_events.rs
new file mode 100644
index 0000000000..1a781def1c
--- /dev/null
+++ b/crates/channels/src/domain/mention_events.rs
@@ -0,0 +1,135 @@
+//! Kafka event models for the `macro.mentions` topic.
+//!
+//! Follows the canonical pattern in `broker_events.rs`: a metadata struct, a
+//! [`TopicEvent`] enum tagged by `event_type`, and a [`MacroEvent`] wrapper.
+//! Unlike per-domain topics, this one is keyed by the *mentioned* entity id
+//! rather than the source, so a consumer (e.g. a bot) can find mentions of
+//! its own id across both channel messages and docs. The payload is kept
+//! intentionally minimal: a reference (id + kind) to the source and the
+//! mentioned entity, nothing else.
+
+#[cfg(test)]
+mod test;
+
+use macro_event_broker::{Event, MacroEvent, TopicEvent};
+use macro_event_topics::MacroMentionsTopic;
+use serde::{Deserialize, Serialize};
+
+use crate::domain::models::EntityMention;
+
+/// A reference to an entity by id and kind (e.g. `"user"`, `"bot"`, `"doc"`, `"message"`).
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct EntityRef {
+ /// The entity's id.
+ pub id: String,
+ /// The entity's kind.
+ pub kind: String,
+}
+
+/// Metadata shared by every [`MentionTopicEvent`] variant.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct MentionMetadata {
+ /// The entity that owns the mention (e.g. the message or doc it appears in).
+ pub source: EntityRef,
+ /// The entity that was mentioned.
+ pub mentioned: EntityRef,
+}
+
+impl From<&EntityMention> for MentionMetadata {
+ fn from(mention: &EntityMention) -> Self {
+ Self {
+ source: EntityRef {
+ id: mention.source_entity_id.clone(),
+ kind: mention.source_entity_type.clone(),
+ },
+ mentioned: EntityRef {
+ id: mention.entity_id.clone(),
+ kind: mention.entity_type.clone(),
+ },
+ }
+ }
+}
+
+/// Events that can be published to [`MacroMentionsTopic`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "event_type", content = "metadata")]
+pub enum MentionTopicEvent {
+ /// A mention was recorded outside of a thread (e.g. a doc mentioning another entity).
+ #[serde(rename = "mention.created")]
+ Created(MentionMetadata),
+ /// A mention was removed outside of a thread.
+ #[serde(rename = "mention.deleted")]
+ Deleted(MentionMetadata),
+ /// A mention was included in a message sent to a thread (chat/email/channel).
+ #[serde(rename = "mention.message_sent")]
+ MessageSent(MentionMetadata),
+}
+
+impl TopicEvent for MentionTopicEvent {
+ type Topic = MacroMentionsTopic;
+
+ fn schema_version(&self) -> u8 {
+ 1
+ }
+}
+
+/// Publishable event for [`MacroMentionsTopic`], keyed by the mentioned
+/// entity id.
+pub struct MentionMacroEvent {
+ key: String,
+ event: Event<MentionTopicEvent>,
+}
+
+impl MentionMacroEvent {
+ /// Build a created event keyed by the mentioned entity id.
+ pub fn created(metadata: MentionMetadata) -> Self {
+ Self::new(
+ metadata.mentioned.id.clone(),
+ MentionTopicEvent::Created(metadata),
+ )
+ }
+
+ /// Build a deleted event keyed by the mentioned entity id.
+ pub fn deleted(metadata: MentionMetadata) -> Self {
+ Self::new(
+ metadata.mentioned.id.clone(),
+ MentionTopicEvent::Deleted(metadata),
+ )
+ }
+
+ /// Build a message-sent event keyed by the mentioned entity id.
+ pub fn message_sent(metadata: MentionMetadata) -> Self {
+ Self::new(
+ metadata.mentioned.id.clone(),
+ MentionTopicEvent::MessageSent(metadata),
+ )
+ }
+
+ fn new(key: String, event: MentionTopicEvent) -> Self {
+ Self::with_event(key, Event::new(event))
+ }
+
+ /// Build an event from a pre-built envelope.
+ pub fn with_event(key: impl Into<String>, event: Event<MentionTopicEvent>) -> Self {
+ Self {
+ key: key.into(),
+ event,
+ }
+ }
+}
+
+impl MacroEvent for MentionMacroEvent {
+ type EventPayload = MentionTopicEvent;
+
+ fn key(&self) -> &str {
+ &self.key
+ }
+
+ fn event(&self) -> &Event<Self::EventPayload> {
+ &self.event
+ }
+
+ fn from_event(key: String, event: Event<Self::EventPayload>) -> Self {
+ Self::with_event(key, event)
+ }
+}
diff --git a/crates/channels/src/domain/mention_events/test.rs b/crates/channels/src/domain/mention_events/test.rs
new file mode 100644
index 0000000000..fb1fafa606
--- /dev/null
+++ b/crates/channels/src/domain/mention_events/test.rs
@@ -0,0 +1,87 @@
+use chrono::Utc;
+use macro_event_broker::Event;
+use serde_json::json;
+use uuid::Uuid;
+
+use super::*;
+
+fn metadata() -> MentionMetadata {
+ MentionMetadata {
+ source: EntityRef {
+ id: "doc-1".to_string(),
+ kind: "doc".to_string(),
+ },
+ mentioned: EntityRef {
+ id: "bot-1".to_string(),
+ kind: "bot".to_string(),
+ },
+ }
+}
+
+#[test]
+fn created_event_wire_shape() {
+ let event = Event::with_event_id(Uuid::nil(), MentionTopicEvent::Created(metadata()));
+
+ let value = serde_json::to_value(&event).expect("serializable");
+ assert_eq!(
+ value,
+ json!({
+ "event_id": "00000000-0000-0000-0000-000000000000",
+ "schema_version": 1,
+ "event_type": "mention.created",
+ "metadata": {
+ "source": { "id": "doc-1", "kind": "doc" },
+ "mentioned": { "id": "bot-1", "kind": "bot" },
+ },
+ })
+ );
+}
+
+#[test]
+fn event_type_strings_follow_dot_convention() {
+ assert_eq!(
+ serde_json::to_value(MentionTopicEvent::Created(metadata())).unwrap()["event_type"],
+ json!("mention.created")
+ );
+ assert_eq!(
+ serde_json::to_value(MentionTopicEvent::Deleted(metadata())).unwrap()["event_type"],
+ json!("mention.deleted")
+ );
+ assert_eq!(
+ serde_json::to_value(MentionTopicEvent::MessageSent(metadata())).unwrap()["event_type"],
+ json!("mention.message_sent")
+ );
+}
+
+#[test]
+fn events_are_keyed_by_mentioned_entity_id() {
+ assert_eq!(MentionMacroEvent::created(metadata()).key(), "bot-1");
+ assert_eq!(MentionMacroEvent::deleted(metadata()).key(), "bot-1");
+ assert_eq!(MentionMacroEvent::message_sent(metadata()).key(), "bot-1");
+}
+
+#[test]
+fn decode_round_trips() {
+ let original = MentionMacroEvent::created(metadata());
+
+ let payload = serde_json::to_vec(original.event()).expect("serializable");
+ let decoded = MentionMacroEvent::decode(original.key(), &payload).expect("decodable payload");
+
+ assert_eq!(decoded.key(), "bot-1");
+ assert_eq!(decoded.event(), original.event());
+}
+
+#[test]
+fn metadata_from_entity_mention_maps_fields() {
+ let mention = EntityMention {
+ id: Uuid::nil(),
+ source_entity_type: "doc".to_string(),
+ source_entity_id: "doc-1".to_string(),
+ entity_type: "bot".to_string(),
+ entity_id: "bot-1".to_string(),
+ user_id: Some("macro|[email protected]".to_string()),
+ created_at: Utc::now(),
+ };
+
+ assert_eq!(MentionMetadata::from(&mention), metadata());
+}
diff --git a/crates/channels/src/domain/mod.rs b/crates/channels/src/domain/mod.rs
index c9063e424e..08feb11715 100644
--- a/crates/channels/src/domain/mod.rs
+++ b/crates/channels/src/domain/mod.rs
@@ -5,6 +5,8 @@ pub mod events;
/// Legacy channel list service implementation.
#[cfg(feature = "list")]
pub mod list_service;
+/// Kafka event models for the `macro.mentions` topic.
+pub mod mention_events;
/// Domain models for channel messages.
pub mod models;
#[cfg(feature = "ports")]
diff --git a/crates/channels/src/domain/ports.rs b/crates/channels/src/domain/ports.rs
index b932c260db..7c2a9acd8a 100644
--- a/crates/channels/src/domain/ports.rs
+++ b/crates/channels/src/domain/ports.rs
@@ -422,11 +422,11 @@ pub trait ChannelRepo: Send + Sync + 'static {
id: Uuid,
) -> impl Future<Output = Result<Option<EntityMention>, Self::Err>> + Send;
- /// Delete an entity mention by id. Returns whether a row was removed.
+ /// Delete an entity mention by id. Returns the deleted row, if one existed.
fn delete_entity_mention_by_id(
&self,
id: Uuid,
- ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+ ) -> impl Future<Output = Result<Option<EntityMention>, Self::Err>> + Send;
/// Patch message attachment state.
fn patch_message_attachments(
diff --git a/crates/channels/src/domain/service.rs b/crates/channels/src/domain/service.rs
index b9818a91df..03d6f17b61 100644
--- a/crates/channels/src/domain/service.rs
+++ b/crates/channels/src/domain/service.rs
@@ -1930,11 +1930,16 @@ where
&self,
options: CreateEntityMentionOptions,
) -> Result<EntityMention, ChannelMutationErr> {
- self.repo
+ let mention = self
+ .repo
.create_entity_mention(options)
.await
.map_err(anyhow::Error::from)
- .map_err(ChannelMutationErr::Repo)
+ .map_err(ChannelMutationErr::Repo)?;
+ self.events.dispatch(ChannelEvent::EntityMentionCreated {
+ mention: mention.clone(),
+ });
+ Ok(mention)
}
#[tracing::instrument(err, skip(self))]
@@ -1951,10 +1956,17 @@ where
#[tracing::instrument(err, skip(self))]
async fn delete_entity_mention(&self, id: Uuid) -> Result<bool, ChannelMutationErr> {
- self.repo
+ let mention = self
+ .repo
.delete_entity_mention_by_id(id)
.await
.map_err(anyhow::Error::from)
- .map_err(ChannelMutationErr::Repo)
+ .map_err(ChannelMutationErr::Repo)?;
+ let deleted = mention.is_some();
+ if let Some(mention) = mention {
+ self.events
+ .dispatch(ChannelEvent::EntityMentionDeleted { mention });
+ }
+ Ok(deleted)
}
}
diff --git a/crates/channels/src/domain/service/test.rs b/crates/channels/src/domain/service/test.rs
index 318bcec2c4..f1a66fd24b 100644
--- a/crates/channels/src/domain/service/test.rs
+++ b/crates/channels/src/domain/service/test.rs
@@ -764,8 +764,11 @@ impl ChannelRepo for FakeMutationRepo {
Ok(None)
}
- async fn delete_entity_mention_by_id(&self, _id: Uuid) -> Result<bool, Self::Err> {
- Ok(false)
+ async fn delete_entity_mention_by_id(
+ &self,
+ _id: Uuid,
+ ) -> Result<Option<EntityMention>, Self::Err> {
+ Ok(None)
}
async fn patch_message_attachments(
diff --git a/crates/channels/src/domain/side_effects.rs b/crates/channels/src/domain/side_effects.rs
index 08a9a90ec8..0dbf6a64d4 100644
--- a/crates/channels/src/domain/side_effects.rs
+++ b/crates/channels/src/domain/side_effects.rs
@@ -8,6 +8,7 @@ use crate::domain::{
ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelUpdatedMetadata,
},
events::ChannelEvent,
+ mention_events::{EntityRef, MentionMacroEvent, MentionMetadata},
models::{
BotId, BotSenderProfile, ChannelMetadata, ChannelParticipant, ChannelType, CountedReaction,
MutatedAttachment, MutatedMessage, PostMessageNotificationPolicy, SimpleMention,
@@ -439,11 +440,14 @@ where
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::ChannelCreated { .. } => {}
ChannelEvent::ChannelUpdated { .. } => {}
ChannelEvent::ParticipantsRemoved { .. } => {}
+ ChannelEvent::EntityMentionCreated { .. } => {}
+ ChannelEvent::EntityMentionDeleted { .. } => {}
ChannelEvent::ChannelDeleted { channel_id, .. } => {
self.search.remove_message(channel_id, None).await;
}
@@ -616,6 +620,14 @@ where
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");
+ });
+ }
}
}
@@ -1378,6 +1390,44 @@ fn broker_events_for_event(event: &ChannelEvent) -> Vec<ChannelMacroEvent> {
},
)],
ChannelEvent::ReactionChanged { .. } | ChannelEvent::TypingChanged { .. } => Vec::new(),
+ ChannelEvent::EntityMentionCreated { .. } | ChannelEvent::EntityMentionDeleted { .. } => {
+ 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(),
}
}
diff --git a/crates/channels/src/domain/side_effects/test.rs b/crates/channels/src/domain/side_effects/test.rs
index 79344c0884..253a710292 100644
--- a/crates/channels/src/domain/side_effects/test.rs
+++ b/crates/channels/src/domain/side_effects/test.rs
@@ -1,7 +1,7 @@
use super::*;
use crate::domain::{
events::MessageChangedNotificationContext,
- models::{BotId, ParticipantRole, Sender},
+ models::{BotId, EntityMention, ParticipantRole, Sender},
ports::{
ChannelEventHandler, ChannelNotificationSender, ChannelRealtimePublisher,
ChannelSearchIndexer, ChannelSideEffectContext,
@@ -1370,3 +1370,138 @@ fn broker_events_skip_reaction_changes() {
assert!(events.is_empty());
}
+
+fn entity_mention(entity_type: &str, entity_id: &str) -> EntityMention {
+ EntityMention {
+ id: Uuid::new_v4(),
+ source_entity_type: "document".to_string(),
+ source_entity_id: "doc-1".to_string(),
+ entity_type: entity_type.to_string(),
+ entity_id: entity_id.to_string(),
+ user_id: Some("macro|[email protected]".to_string()),
+ created_at: Utc::now(),
+ }
+}
+
+#[test]
+fn broker_events_skip_entity_mention_events() {
+ assert!(
+ broker_events_for_event(&ChannelEvent::EntityMentionCreated {
+ mention: entity_mention("bot", "bot-1"),
+ })
+ .is_empty()
+ );
+ assert!(
+ broker_events_for_event(&ChannelEvent::EntityMentionDeleted {
+ mention: entity_mention("bot", "bot-1"),
+ })
+ .is_empty()
+ );
+}
+
+#[test]
+fn mention_broker_events_map_message_posted_mentions() {
+ use macro_event_broker::MacroEvent as _;
+ let channel_id = Uuid::new_v4();
+ let message_id = Uuid::new_v4();
+ let now = Utc::now();
+
+ let events = mention_broker_events_for_event(&ChannelEvent::MessagePosted {
+ channel_id,
+ metadata: ChannelMetadata {
+ channel_type: ChannelType::Team,
+ channel_name: "Project".to_string(),
+ },
+ participants: Vec::new(),
+ message: MutatedMessage {
+ id: message_id,
+ channel_id,
+ thread_id: None,
+ sender_id: Sender::new_from_user(user("[email protected]")),
+ triggered_by: None,
+ content: "@bot @doc-1".to_string(),
+ created_at: now,
+ updated_at: now,
+ edited_at: None,
+ deleted_at: None,
+ },
+ mentions: vec![
+ SimpleMention {
+ entity_type: "bot".to_string(),
+ entity_id: "bot-1".to_string(),
+ },
+ SimpleMention {
+ entity_type: "document".to_string(),
+ entity_id: "doc-1".to_string(),
+ },
+ ],
+ has_attachments: false,
+ attachments: Vec::new(),
+ nonce: None,
+ notification_policy: PostMessageNotificationPolicy::Default,
+ });
+
+ assert_eq!(events.len(), 2);
+ assert_eq!(events[0].key(), "bot-1");
+ assert_eq!(events[1].key(), "doc-1");
+ let envelope = serde_json::to_value(events[0].event()).unwrap();
+ assert_eq!(envelope["event_type"], "mention.message_sent");
+ assert_eq!(envelope["metadata"]["source"]["kind"], "message");
+ assert_eq!(envelope["metadata"]["source"]["id"], message_id.to_string());
+ assert_eq!(envelope["metadata"]["mentioned"]["kind"], "bot");
+ assert_eq!(envelope["metadata"]["mentioned"]["id"], "bot-1");
+}
+
+#[test]
+fn mention_broker_events_map_entity_mention_created_and_deleted() {
+ use macro_event_broker::MacroEvent as _;
+ let mention = entity_mention("bot", "bot-1");
+
+ let created = mention_broker_events_for_event(&ChannelEvent::EntityMentionCreated {
+ mention: mention.clone(),
+ });
+ assert_eq!(created.len(), 1);
+ assert_eq!(created[0].key(), "bot-1");
+ let envelope = serde_json::to_value(created[0].event()).unwrap();
+ assert_eq!(envelope["event_type"], "mention.created");
+ assert_eq!(envelope["metadata"]["source"]["kind"], "document");
+ assert_eq!(envelope["metadata"]["source"]["id"], "doc-1");
+ assert_eq!(envelope["metadata"]["mentioned"]["kind"], "bot");
+ assert_eq!(envelope["metadata"]["mentioned"]["id"], "bot-1");
+
+ let deleted = mention_broker_events_for_event(&ChannelEvent::EntityMentionDeleted { mention });
+ assert_eq!(deleted.len(), 1);
+ let envelope = serde_json::to_value(deleted[0].event()).unwrap();
+ assert_eq!(envelope["event_type"], "mention.deleted");
+}
+
+#[test]
+fn mention_broker_events_skip_unrelated_events() {
+ let events = mention_broker_events_for_event(&ChannelEvent::ReactionChanged {
+ channel_id: Uuid::new_v4(),
+ actor: Sender::new_from_user(user("[email protected]")),
+ message_id: Uuid::new_v4(),
+ reactions: Vec::new(),
+ recipients: Vec::new(),
+ nonce: None,
+ });
+ assert!(events.is_empty());
+}
+
+#[tokio::test]
+async fn handle_publishes_mention_events_alongside_channel_events() {
+ let broker = TestEventBroker::default();
+ let service = broker_service(broker.clone());
+
+ service
+ .handle(ChannelEvent::EntityMentionCreated {
+ mention: entity_mention("bot", "bot-1"),
+ })
+ .await;
+
+ let published = broker.published.lock().unwrap();
+ assert_eq!(published.len(), 1);
+ assert_eq!(published[0].topic, "macro.mentions");
+ assert_eq!(published[0].key, "bot-1");
+ assert_eq!(published[0].envelope["event_type"], "mention.created");
+}
diff --git a/crates/channels/src/outbound/pg_channels_repo.rs b/crates/channels/src/outbound/pg_channels_repo.rs
index aa1825a75f..bfe27bfcfe 100644
--- a/crates/channels/src/outbound/pg_channels_repo.rs
+++ b/crates/channels/src/outbound/pg_channels_repo.rs
@@ -3400,18 +3400,23 @@ impl ChannelRepo for PgChannelsRepo {
Ok(mention)
}
- async fn delete_entity_mention_by_id(&self, id: Uuid) -> Result<bool, Self::Err> {
- let result = sqlx::query!(
+ async fn delete_entity_mention_by_id(
+ &self,
+ id: Uuid,
+ ) -> Result<Option<EntityMention>, Self::Err> {
+ let mention = sqlx::query_as!(
+ EntityMention,
r#"
DELETE FROM comms_entity_mentions
WHERE id = $1
+ RETURNING id, source_entity_type, source_entity_id, entity_type, entity_id, user_id, created_at
"#,
id,
)
- .execute(&self.pool)
+ .fetch_optional(&self.pool)
.await
.context("failed to delete entity mention")?;
- Ok(result.rows_affected() > 0)
+ Ok(mention)
}
async fn patch_message_attachments(
diff --git a/crates/channels/src/outbound/pg_channels_repo/tests.rs b/crates/channels/src/outbound/pg_channels_repo/tests.rs
index 5a20bd4959..f86d648b1d 100644
--- a/crates/channels/src/outbound/pg_channels_repo/tests.rs
+++ b/crates/channels/src/outbound/pg_channels_repo/tests.rs
@@ -2439,18 +2439,26 @@ async fn delete_entity_mention_by_id_removes_only_targeted_row(
.create_entity_mention(mention_opts("doc-3", "user", "user-w", None))
.await?;
- assert!(repo.delete_entity_mention_by_id(target.id).await?);
+ let deleted = repo
+ .delete_entity_mention_by_id(target.id)
+ .await?
+ .expect("deleted row should be returned");
+ assert_eq!(deleted.id, target.id);
assert!(repo.get_entity_mention_by_id(target.id).await?.is_none());
assert!(repo.get_entity_mention_by_id(other.id).await?.is_some());
Ok(())
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn delete_entity_mention_by_id_returns_false_when_missing(
+async fn delete_entity_mention_by_id_returns_none_when_missing(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let repo = repo(pool);
- assert!(!repo.delete_entity_mention_by_id(Uuid::new_v4()).await?);
+ assert!(
+ repo.delete_entity_mention_by_id(Uuid::new_v4())
+ .await?
+ .is_none()
+ );
Ok(())
}
diff --git a/crates/macro_event_topics/src/lib.rs b/crates/macro_event_topics/src/lib.rs
index 17adf90de5..bbe39f3bc5 100644
--- a/crates/macro_event_topics/src/lib.rs
+++ b/crates/macro_event_topics/src/lib.rs
@@ -63,4 +63,6 @@ topics! {
MacroEmailTopic => "macro.email",
/// Webhook configuration lifecycle events (created / updated / deleted / validated).
MacroWebhooksTopic => "macro.webhooks",
+ /// Entity mention events (created / deleted) across channels and docs.
+ MacroMentionsTopic => "macro.mentions",
}
diff --git a/crates/macro_event_topics/src/test.rs b/crates/macro_event_topics/src/test.rs
index 39b00a8999..ead779135f 100644
--- a/crates/macro_event_topics/src/test.rs
+++ b/crates/macro_event_topics/src/test.rs
@@ -25,4 +25,5 @@ fn all_topic_names_includes_declared_topics() {
assert!(all_topic_names().contains(&MacroChannelsTopic::TOPIC_STR));
assert!(all_topic_names().contains(&MacroBotsTopic::TOPIC_STR));
assert!(all_topic_names().contains(&MacroWebhooksTopic::TOPIC_STR));
+ assert!(all_topic_names().contains(&MacroMentionsTopic::TOPIC_STR));
}