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(teams): kafka producer (#5036)

Will Hutchinson6f0e6cc16154
diff --git a/.github/kafka-cluster-topics.json b/.github/kafka-cluster-topics.json
index c5d6c94750..fa43baa313 100644
--- a/.github/kafka-cluster-topics.json
+++ b/.github/kafka-cluster-topics.json
@@ -5,5 +5,6 @@
"macro.email",
"macro.example",
"macro.projects",
+ "macro.teams",
"macro.webhooks"
]
diff --git a/Cargo.lock b/Cargo.lock
index a8fe9d4fdc..33836d655e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -996,6 +996,7 @@ dependencies = [
"macro_entrypoint",
"macro_env",
"macro_env_var",
+ "macro_event_broker",
"macro_middleware",
"macro_queues",
"macro_service_urls",
@@ -14077,6 +14078,8 @@ dependencies = [
"entity_access",
"macro_authorization",
"macro_db_migrator",
+ "macro_event_broker",
+ "macro_event_topics",
"macro_user_id",
"macro_uuid",
"model-entity",
diff --git a/crates/macro_event_topics/src/lib.rs b/crates/macro_event_topics/src/lib.rs
index 5a4917017d..b2295c4b1a 100644
--- a/crates/macro_event_topics/src/lib.rs
+++ b/crates/macro_event_topics/src/lib.rs
@@ -55,6 +55,8 @@ topics! {
MacroDocumentsTopic => "macro.documents",
/// Project lifecycle events (created, updated, deleted, restored, permanently deleted, and uploaded).
MacroProjectsTopic => "macro.projects",
+ /// Team lifecycle, invite, and membership events.
+ MacroTeamsTopic => "macro.teams",
/// Channel lifecycle, message, participant, and attachment events.
MacroChannelsTopic => "macro.channels",
/// Email lifecycle events (links, messages, threads, labels).
diff --git a/crates/macro_event_topics/src/test.rs b/crates/macro_event_topics/src/test.rs
index ad3d191e02..593bce01e8 100644
--- a/crates/macro_event_topics/src/test.rs
+++ b/crates/macro_event_topics/src/test.rs
@@ -20,6 +20,7 @@ fn all_topic_names_includes_declared_topics() {
assert!(all_topic_names().contains(&MacroExampleTopic.as_str()));
assert!(all_topic_names().contains(&MacroDocumentsTopic.as_str()));
assert!(all_topic_names().contains(&MacroProjectsTopic.as_str()));
+ assert!(all_topic_names().contains(&MacroTeamsTopic.as_str()));
assert!(all_topic_names().contains(&MacroChannelsTopic.as_str()));
assert!(all_topic_names().contains(&MacroBotsTopic.as_str()));
assert!(all_topic_names().contains(&MacroWebhooksTopic.as_str()));
diff --git a/crates/teams/Cargo.toml b/crates/teams/Cargo.toml
index f87055a286..42b8923556 100644
--- a/crates/teams/Cargo.toml
+++ b/crates/teams/Cargo.toml
@@ -38,6 +38,7 @@ ports = [
"dep:model_notifications",
"dep:notification",
"dep:tokio",
+ "macro_event_broker/ports",
]
[dependencies]
@@ -55,6 +56,8 @@ contacts = { path = "../contacts", default-features = false, optional = true }
macro_authorization = { path = "../macro_authorization", optional = true, default-features = false, features = [
"axum",
] }
+macro_event_broker = { path = "../macro_event_broker", default-features = false }
+macro_event_topics = { path = "../macro_event_topics" }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
non_empty = { path = "../non_empty" }
diff --git a/crates/teams/README.md b/crates/teams/README.md
new file mode 100644
index 0000000000..bc1e78f729
--- /dev/null
+++ b/crates/teams/README.md
@@ -0,0 +1,104 @@
+# Teams crate
+
+This crate owns team models, persistence ports, service policy, and HTTP adapters.
+The team service also produces sanitized lifecycle, invitation, and membership
+events for successful team mutations.
+
+## Team event producer
+
+The events below use schema version 1 and are published to the `macro.teams`
+Kafka topic. Every record uses the subject team's bare UUID string as its Kafka
+key (for example, `3f6f8b0a-6f9f-4a3f-9c3a-2b1e5d4c7a90`, without a `team|`
+prefix). The key is not part of the JSON envelope. Events for one team
+therefore use the same Kafka partition and retain per-team ordering; ordering
+between different teams is unspecified.
+
+| Event name | Emitted after | Metadata |
+| --- | --- | --- |
+| `team.created` | Team creation and all rollback-capable creation side effects succeed | `team_id`, `name`, `slug`, `owner`, `enterprise`, `paid`, `auto_join_domain` |
+| `team.updated` | A team PATCH containing `name` or `slug` is persisted | `team_id`, `actor_user_id`, requested `name`, requested `slug` |
+| `team.deleted` | Team deletion succeeds | `team_id`, `actor_user_id`, `member_user_ids` |
+| `team.invite_created` | A new invite is persisted; one event is produced per newly invited lowercase email | `team_id`, `invite_id`, `email`, `invited_by`, `team_name` |
+| `team.invite_rejected` | The invitee successfully rejects and deletes an invite | `team_id`, `invite_id`, `email`, `actor_user_id` |
+| `team.invite_revoked` | An administrator successfully deletes an invite | `team_id`, `invite_id`, `email`, `actor_user_id` |
+| `team.member_joined` | An invited or domain-auto-joined membership and all rollback-capable side effects succeed | `team_id`, `member_id`, `role`, `join_method` |
+| `team.member_removed` | Membership removal and all rollback-capable side effects succeed | `team_id`, `member_id`, `removed_by`, `role` |
+| `team.member_role_changed` | Each individual member role update succeeds | `team_id`, `actor_user_id`, `member_id`, `role`, `previous_role` |
+| `team.auto_join_domain_toggled` | An explicit auto-join-domain toggle succeeds | `team_id`, `actor_user_id`, `auto_join_domain` |
+
+Roles are lowercase (`member`, `admin`, or `owner`). Optional metadata is
+serialized as `null`: the mutable fields on an updated event describe the
+requested PATCH, and `null` means that field was omitted. `team_name` is a
+best-effort invite-time lookup. `previous_role` is the role in the pre-PATCH
+team snapshot when known. `auto_join_domain` is the resulting domain or `null`
+when disabled. Team deletion produces one event whose `member_user_ids` lists
+the members present before deletion; it does not produce an individual removal
+event for every member. For self-service removal, `removed_by` equals
+`member_id`.
+
+The automatic domain toggle performed during creation is represented only by
+`auto_join_domain` on the created event. The explicit settings operation
+produces the toggle event. A role-only PATCH produces role-change events but no
+updated event. Role updates are committed in request order: if a later update
+fails, earlier successful updates and their events remain committed, while no
+event is produced for the failed update.
+
+`join_method` is a tagged union. An accepted invite includes its invite UUID and
+the inviter; a domain auto-join is encoded as `{"type":"domain_auto_join"}`.
+A complete invite-accepted membership envelope has this shape:
+
+```json
+{
+ "event_id": "01998a30-1a2b-7c3d-9e4f-5a6b7c8d9e0f",
+ "schema_version": 1,
+ "event_type": "team.member_joined",
+ "metadata": {
+ "team_id": "3f6f8b0a-6f9f-4a3f-9c3a-2b1e5d4c7a90",
+ "member_id": "macro|[email protected]",
+ "role": "member",
+ "join_method": {
+ "type": "invite_accepted",
+ "invite_id": "0197f776-6e7b-7c69-a251-780ae754d3e4",
+ "invited_by": "macro|[email protected]"
+ }
+ }
+}
+```
+
+## Sanitization and excluded flows
+
+Event payloads exclude Stripe subscription IDs, customer IDs, payment state,
+and all other billing identifiers. The only billing-derived value is the
+`paid: bool` field on creation.
+
+Only the successful mutations in the table produce these events. Billing flows,
+including Stripe-webhook subscription and payment-status changes and premium
+role revocation or restoration, do not publish them. CRM-setting changes,
+read/list operations, invite resends and their `mark_invites_sent` updates, and
+notification outcomes also do not publish team events. Best-effort CRM,
+contact, and notification work after a committed mutation does not suppress the
+corresponding event.
+
+This change provides production only. It adds no team-event consumer, and the
+webhook Kafka consumer and webhook delivery pipeline do not consume or deliver
+these events.
+
+## Delivery semantics and compatibility
+
+Publication occurs after the relevant committed mutation and is
+fire-and-forget. The API does not wait for Kafka delivery, and a scheduling or
+publication failure is logged without rolling back or failing an otherwise
+successful request. There is no transaction, outbox, or retry coupling database
+persistence to publication. Delivery is therefore at-most-once relative to team
+mutations: a committed mutation can have no corresponding event.
+
+Consumers must tolerate unknown `event_type` values and unknown metadata fields
+so new event variants and additive fields remain forward compatible. Consumers
+should use `schema_version` when interpreting a known event; every event in this
+contract currently uses version 1.
+
+Provision the `macro.teams` topic before deploying the producer. The rollout
+order is: deploy the Kafka-cluster stack, configure `KAFKA_BROKERS` for the
+authentication service in Doppler, then deploy the authentication service. If
+the producer is deployed before the topic is available, team mutations still
+succeed, but events can be lost under the at-most-once contract.
diff --git a/crates/teams/src/domain.rs b/crates/teams/src/domain.rs
index 71412264a1..c73b69f9e2 100644
--- a/crates/teams/src/domain.rs
+++ b/crates/teams/src/domain.rs
@@ -1,6 +1,7 @@
pub mod contacts_enqueuer;
pub mod crm_enqueuer;
pub mod customer_repo;
+pub mod events;
pub mod model;
pub mod team_analytics;
pub mod team_crm_settings_repo;
diff --git a/crates/teams/src/domain/events.rs b/crates/teams/src/domain/events.rs
new file mode 100644
index 0000000000..b3b347fb8e
--- /dev/null
+++ b/crates/teams/src/domain/events.rs
@@ -0,0 +1,298 @@
+//! Kafka event models for the `macro.teams` topic.
+//!
+//! Event payloads deliberately exclude subscription, customer, Stripe, payment,
+//! and other billing identifiers. Creation exposes only whether a team is paid.
+
+#[cfg(test)]
+mod test;
+
+use macro_event_broker::{Event, MacroEvent, TopicEvent};
+use macro_event_topics::MacroTeamsTopic;
+use macro_user_id::user_id::MacroUserIdStr;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::model::TeamRole;
+
+/// Metadata for [`TeamTopicEvent::Created`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TeamCreatedMetadata {
+ /// Identifier of the created team.
+ pub team_id: Uuid,
+ /// Display name of the team.
+ pub name: String,
+ /// Stable team slug.
+ pub slug: String,
+ /// User who owns the team.
+ pub owner: MacroUserIdStr<'static>,
+ /// Whether the team has enterprise features.
+ pub enterprise: bool,
+ /// Whether the team has a paid subscription, without exposing billing identifiers.
+ pub paid: bool,
+ /// Corporate domain enabled for automatic joining, if any.
+ pub auto_join_domain: Option<String>,
+}
+
+/// Metadata for [`TeamTopicEvent::Updated`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TeamUpdatedMetadata {
+ /// Identifier of the updated team.
+ pub team_id: Uuid,
+ /// Authenticated user who updated the team.
+ pub actor_user_id: MacroUserIdStr<'static>,
+ /// Requested display name, or `None` when the PATCH omitted it.
+ pub name: Option<String>,
+ /// Requested slug, or `None` when the PATCH omitted it.
+ pub slug: Option<String>,
+}
+
+/// Metadata for [`TeamTopicEvent::Deleted`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TeamDeletedMetadata {
+ /// Identifier of the deleted team.
+ pub team_id: Uuid,
+ /// Authenticated owner who deleted the team.
+ pub actor_user_id: MacroUserIdStr<'static>,
+ /// Users who belonged to the team when it was deleted.
+ pub member_user_ids: Vec<MacroUserIdStr<'static>>,
+}
+
+/// Metadata for [`TeamTopicEvent::InviteCreated`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TeamInviteCreatedMetadata {
+ /// Identifier of the team receiving the invite.
+ pub team_id: Uuid,
+ /// Identifier of the invite.
+ pub invite_id: Uuid,
+ /// Lowercase email address invited to the team.
+ pub email: String,
+ /// User who created the invite.
+ pub invited_by: MacroUserIdStr<'static>,
+ /// Team display name when it could be retrieved.
+ pub team_name: Option<String>,
+}
+
+/// Metadata for [`TeamTopicEvent::InviteRejected`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TeamInviteRejectedMetadata {
+ /// Identifier of the team associated with the invite.
+ pub team_id: Uuid,
+ /// Identifier of the rejected invite.
+ pub invite_id: Uuid,
+ /// Lowercase email address that rejected the invite.
+ pub email: String,
+ /// Invited user who rejected the invite.
+ pub actor_user_id: MacroUserIdStr<'static>,
+}
+
+/// Metadata for [`TeamTopicEvent::InviteRevoked`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TeamInviteRevokedMetadata {
+ /// Identifier of the team associated with the invite.
+ pub team_id: Uuid,
+ /// Identifier of the revoked invite.
+ pub invite_id: Uuid,
+ /// Lowercase email address whose invite was revoked.
+ pub email: String,
+ /// Authenticated administrator who revoked the invite.
+ pub actor_user_id: MacroUserIdStr<'static>,
+}
+
+/// How a user joined a team.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum TeamJoinMethod {
+ /// The user accepted a team invitation.
+ InviteAccepted {
+ /// Identifier of the accepted invite.
+ invite_id: Uuid,
+ /// User who originally sent the invite.
+ invited_by: MacroUserIdStr<'static>,
+ },
+ /// The user joined because their email matched the team's automatic-join domain.
+ DomainAutoJoin,
+}
+
+/// Metadata for [`TeamTopicEvent::MemberJoined`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TeamMemberJoinedMetadata {
+ /// Identifier of the joined team.
+ pub team_id: Uuid,
+ /// User who joined the team.
+ pub member_id: MacroUserIdStr<'static>,
+ /// Role assigned to the new member.
+ pub role: TeamRole,
+ /// Mechanism by which the member joined.
+ pub join_method: TeamJoinMethod,
+}
+
+/// Metadata for [`TeamTopicEvent::MemberRemoved`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TeamMemberRemovedMetadata {
+ /// Identifier of the team the member left.
+ pub team_id: Uuid,
+ /// User removed from the team.
+ pub member_id: MacroUserIdStr<'static>,
+ /// User who performed the removal.
+ pub removed_by: MacroUserIdStr<'static>,
+ /// Member's role before removal.
+ pub role: TeamRole,
+}
+
+/// Metadata for [`TeamTopicEvent::MemberRoleChanged`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TeamMemberRoleChangedMetadata {
+ /// Identifier of the team whose member changed role.
+ pub team_id: Uuid,
+ /// Authenticated user who changed the role.
+ pub actor_user_id: MacroUserIdStr<'static>,
+ /// User whose role changed.
+ pub member_id: MacroUserIdStr<'static>,
+ /// Newly assigned role.
+ pub role: TeamRole,
+ /// Role held before the change, when known.
+ pub previous_role: Option<TeamRole>,
+}
+
+/// Metadata for [`TeamTopicEvent::AutoJoinDomainToggled`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TeamAutoJoinDomainToggledMetadata {
+ /// Identifier of the team whose setting changed.
+ pub team_id: Uuid,
+ /// Authenticated user who changed the setting.
+ pub actor_user_id: MacroUserIdStr<'static>,
+ /// Newly enabled automatic-join domain, or `None` when disabled.
+ pub auto_join_domain: Option<String>,
+}
+
+/// Lifecycle, invite, and membership events published to [`MacroTeamsTopic`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "event_type", content = "metadata")]
+pub enum TeamTopicEvent {
+ /// A team was created.
+ #[serde(rename = "team.created")]
+ Created(TeamCreatedMetadata),
+ /// Team metadata was updated.
+ #[serde(rename = "team.updated")]
+ Updated(TeamUpdatedMetadata),
+ /// A team was deleted.
+ #[serde(rename = "team.deleted")]
+ Deleted(TeamDeletedMetadata),
+ /// A team invitation was created.
+ #[serde(rename = "team.invite_created")]
+ InviteCreated(TeamInviteCreatedMetadata),
+ /// A team invitation was rejected by its recipient.
+ #[serde(rename = "team.invite_rejected")]
+ InviteRejected(TeamInviteRejectedMetadata),
+ /// A team invitation was revoked by an administrator.
+ #[serde(rename = "team.invite_revoked")]
+ InviteRevoked(TeamInviteRevokedMetadata),
+ /// A user joined a team.
+ #[serde(rename = "team.member_joined")]
+ MemberJoined(TeamMemberJoinedMetadata),
+ /// A user was removed from a team.
+ #[serde(rename = "team.member_removed")]
+ MemberRemoved(TeamMemberRemovedMetadata),
+ /// A team member's role changed.
+ #[serde(rename = "team.member_role_changed")]
+ MemberRoleChanged(TeamMemberRoleChangedMetadata),
+ /// A team's automatic-join domain setting changed.
+ #[serde(rename = "team.auto_join_domain_toggled")]
+ AutoJoinDomainToggled(TeamAutoJoinDomainToggledMetadata),
+}
+
+impl TopicEvent for TeamTopicEvent {
+ type Topic = MacroTeamsTopic;
+
+ fn schema_version(&self) -> u8 {
+ 1
+ }
+}
+
+/// Publishable event for [`MacroTeamsTopic`], keyed by the team's bare UUID.
+pub struct TeamMacroEvent {
+ key: String,
+ event: Event<TeamTopicEvent>,
+}
+
+impl TeamMacroEvent {
+ /// Build a team-created event.
+ pub fn created(metadata: TeamCreatedMetadata) -> Self {
+ Self::new(metadata.team_id, TeamTopicEvent::Created(metadata))
+ }
+
+ /// Build a team-updated event.
+ pub fn updated(metadata: TeamUpdatedMetadata) -> Self {
+ Self::new(metadata.team_id, TeamTopicEvent::Updated(metadata))
+ }
+
+ /// Build a team-deleted event.
+ pub fn deleted(metadata: TeamDeletedMetadata) -> Self {
+ Self::new(metadata.team_id, TeamTopicEvent::Deleted(metadata))
+ }
+
+ /// Build a team-invite-created event.
+ pub fn invite_created(metadata: TeamInviteCreatedMetadata) -> Self {
+ Self::new(metadata.team_id, TeamTopicEvent::InviteCreated(metadata))
+ }
+
+ /// Build a team-invite-rejected event.
+ pub fn invite_rejected(metadata: TeamInviteRejectedMetadata) -> Self {
+ Self::new(metadata.team_id, TeamTopicEvent::InviteRejected(metadata))
+ }
+
+ /// Build a team-invite-revoked event.
+ pub fn invite_revoked(metadata: TeamInviteRevokedMetadata) -> Self {
+ Self::new(metadata.team_id, TeamTopicEvent::InviteRevoked(metadata))
+ }
+
+ /// Build a team-member-joined event.
+ pub fn member_joined(metadata: TeamMemberJoinedMetadata) -> Self {
+ Self::new(metadata.team_id, TeamTopicEvent::MemberJoined(metadata))
+ }
+
+ /// Build a team-member-removed event.
+ pub fn member_removed(metadata: TeamMemberRemovedMetadata) -> Self {
+ Self::new(metadata.team_id, TeamTopicEvent::MemberRemoved(metadata))
+ }
+
+ /// Build a team-member-role-changed event.
+ pub fn member_role_changed(metadata: TeamMemberRoleChangedMetadata) -> Self {
+ Self::new(
+ metadata.team_id,
+ TeamTopicEvent::MemberRoleChanged(metadata),
+ )
+ }
+
+ /// Build a team-auto-join-domain-toggled event.
+ pub fn auto_join_domain_toggled(metadata: TeamAutoJoinDomainToggledMetadata) -> Self {
+ Self::new(
+ metadata.team_id,
+ TeamTopicEvent::AutoJoinDomainToggled(metadata),
+ )
+ }
+
+ fn new(team_id: Uuid, event: TeamTopicEvent) -> Self {
+ Self::with_event(team_id.to_string(), Event::new(event))
+ }
+
+ fn with_event(key: String, event: Event<TeamTopicEvent>) -> Self {
+ Self { key, event }
+ }
+}
+
+impl MacroEvent for TeamMacroEvent {
+ type EventPayload = TeamTopicEvent;
+
+ 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/teams/src/domain/events/test.rs b/crates/teams/src/domain/events/test.rs
new file mode 100644
index 0000000000..3416f2d825
--- /dev/null
+++ b/crates/teams/src/domain/events/test.rs
@@ -0,0 +1,326 @@
+use macro_event_broker::{Event, MacroEvent};
+use macro_event_topics::Topic;
+use macro_user_id::user_id::MacroUserIdStr;
+use serde_json::{Value, json};
+use uuid::Uuid;
+
+use super::*;
+
+const TEAM_ID: &str = "3f6f8b0a-6f9f-4a3f-9c3a-2b1e5d4c7a90";
+const INVITE_ID: &str = "0197f776-6e7b-7c69-a251-780ae754d3e4";
+const EVENT_ID: &str = "01998a30-1a2b-7c3d-9e4f-5a6b7c8d9e0f";
+
+fn team_id() -> Uuid {
+ Uuid::parse_str(TEAM_ID).expect("valid team id")
+}
+
+fn invite_id() -> Uuid {
+ Uuid::parse_str(INVITE_ID).expect("valid invite id")
+}
+
+fn user_id(value: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(value.to_string()).expect("valid user id")
+}
+
+fn topic_events() -> Vec<(TeamTopicEvent, Value)> {
+ vec![
+ (
+ TeamTopicEvent::Created(TeamCreatedMetadata {
+ team_id: team_id(),
+ name: "Acme".to_string(),
+ slug: "acme".to_string(),
+ owner: user_id("macro|[email protected]"),
+ enterprise: true,
+ paid: true,
+ auto_join_domain: Some("acme.com".to_string()),
+ }),
+ json!({
+ "event_type": "team.created",
+ "metadata": {
+ "team_id": TEAM_ID,
+ "name": "Acme",
+ "slug": "acme",
+ "owner": "macro|[email protected]",
+ "enterprise": true,
+ "paid": true,
+ "auto_join_domain": "acme.com"
+ }
+ }),
+ ),
+ (
+ TeamTopicEvent::Updated(TeamUpdatedMetadata {
+ team_id: team_id(),
+ actor_user_id: user_id("macro|[email protected]"),
+ name: Some("Acme Inc".to_string()),
+ slug: None,
+ }),
+ json!({
+ "event_type": "team.updated",
+ "metadata": {
+ "team_id": TEAM_ID,
+ "actor_user_id": "macro|[email protected]",
+ "name": "Acme Inc",
+ "slug": null
+ }
+ }),
+ ),
+ (
+ TeamTopicEvent::Deleted(TeamDeletedMetadata {
+ team_id: team_id(),
+ actor_user_id: user_id("macro|[email protected]"),
+ member_user_ids: vec![
+ user_id("macro|[email protected]"),
+ user_id("macro|[email protected]"),
+ ],
+ }),
+ json!({
+ "event_type": "team.deleted",
+ "metadata": {
+ "team_id": TEAM_ID,
+ "actor_user_id": "macro|[email protected]",
+ "member_user_ids": ["macro|[email protected]", "macro|[email protected]"]
+ }
+ }),
+ ),
+ (
+ TeamTopicEvent::InviteCreated(TeamInviteCreatedMetadata {
+ team_id: team_id(),
+ invite_id: invite_id(),
+ email: "[email protected]".to_string(),
+ invited_by: user_id("macro|[email protected]"),
+ team_name: Some("Acme".to_string()),
+ }),
+ json!({
+ "event_type": "team.invite_created",
+ "metadata": {
+ "team_id": TEAM_ID,
+ "invite_id": INVITE_ID,
+ "email": "[email protected]",
+ "invited_by": "macro|[email protected]",
+ "team_name": "Acme"
+ }
+ }),
+ ),
+ (
+ TeamTopicEvent::InviteRejected(TeamInviteRejectedMetadata {
+ team_id: team_id(),
+ invite_id: invite_id(),
+ email: "[email protected]".to_string(),
+ actor_user_id: user_id("macro|[email protected]"),
+ }),
+ json!({
+ "event_type": "team.invite_rejected",
+ "metadata": {
+ "team_id": TEAM_ID,
+ "invite_id": INVITE_ID,
+ "email": "[email protected]",
+ "actor_user_id": "macro|[email protected]"
+ }
+ }),
+ ),
+ (
+ TeamTopicEvent::InviteRevoked(TeamInviteRevokedMetadata {
+ team_id: team_id(),
+ invite_id: invite_id(),
+ email: "[email protected]".to_string(),
+ actor_user_id: user_id("macro|[email protected]"),
+ }),
+ json!({
+ "event_type": "team.invite_revoked",
+ "metadata": {
+ "team_id": TEAM_ID,
+ "invite_id": INVITE_ID,
+ "email": "[email protected]",
+ "actor_user_id": "macro|[email protected]"
+ }
+ }),
+ ),
+ (
+ TeamTopicEvent::MemberJoined(TeamMemberJoinedMetadata {
+ team_id: team_id(),
+ member_id: user_id("macro|[email protected]"),
+ role: TeamRole::Member,
+ join_method: TeamJoinMethod::InviteAccepted {
+ invite_id: invite_id(),
+ invited_by: user_id("macro|[email protected]"),
+ },
+ }),
+ json!({
+ "event_type": "team.member_joined",
+ "metadata": {
+ "team_id": TEAM_ID,
+ "member_id": "macro|[email protected]",
+ "role": "member",
+ "join_method": {
+ "type": "invite_accepted",
+ "invite_id": INVITE_ID,
+ "invited_by": "macro|[email protected]"
+ }
+ }
+ }),
+ ),
+ (
+ TeamTopicEvent::MemberRemoved(TeamMemberRemovedMetadata {
+ team_id: team_id(),
+ member_id: user_id("macro|[email protected]"),
+ removed_by: user_id("macro|[email protected]"),
+ role: TeamRole::Admin,
+ }),
+ json!({
+ "event_type": "team.member_removed",
+ "metadata": {
+ "team_id": TEAM_ID,
+ "member_id": "macro|[email protected]",
+ "removed_by": "macro|[email protected]",
+ "role": "admin"
+ }
+ }),
+ ),
+ (
+ TeamTopicEvent::MemberRoleChanged(TeamMemberRoleChangedMetadata {
+ team_id: team_id(),
+ actor_user_id: user_id("macro|[email protected]"),
+ member_id: user_id("macro|[email protected]"),
+ role: TeamRole::Admin,
+ previous_role: Some(TeamRole::Member),
+ }),
+ json!({
+ "event_type": "team.member_role_changed",
+ "metadata": {
+ "team_id": TEAM_ID,
+ "actor_user_id": "macro|[email protected]",
+ "member_id": "macro|[email protected]",
+ "role": "admin",
+ "previous_role": "member"
+ }
+ }),
+ ),
+ (
+ TeamTopicEvent::AutoJoinDomainToggled(TeamAutoJoinDomainToggledMetadata {
+ team_id: team_id(),
+ actor_user_id: user_id("macro|[email protected]"),
+ auto_join_domain: None,
+ }),
+ json!({
+ "event_type": "team.auto_join_domain_toggled",
+ "metadata": {
+ "team_id": TEAM_ID,
+ "actor_user_id": "macro|[email protected]",
+ "auto_join_domain": null
+ }
+ }),
+ ),
+ ]
+}
+
+fn macro_events() -> Vec<TeamMacroEvent> {
+ topic_events()
+ .into_iter()
+ .map(|(event, _)| match event {
+ TeamTopicEvent::Created(metadata) => TeamMacroEvent::created(metadata),
+ TeamTopicEvent::Updated(metadata) => TeamMacroEvent::updated(metadata),
+ TeamTopicEvent::Deleted(metadata) => TeamMacroEvent::deleted(metadata),
+ TeamTopicEvent::InviteCreated(metadata) => TeamMacroEvent::invite_created(metadata),
+ TeamTopicEvent::InviteRejected(metadata) => TeamMacroEvent::invite_rejected(metadata),
+ TeamTopicEvent::InviteRevoked(metadata) => TeamMacroEvent::invite_revoked(metadata),
+ TeamTopicEvent::MemberJoined(metadata) => TeamMacroEvent::member_joined(metadata),
+ TeamTopicEvent::MemberRemoved(metadata) => TeamMacroEvent::member_removed(metadata),
+ TeamTopicEvent::MemberRoleChanged(metadata) => {
+ TeamMacroEvent::member_role_changed(metadata)
+ }
+ TeamTopicEvent::AutoJoinDomainToggled(metadata) => {
+ TeamMacroEvent::auto_join_domain_toggled(metadata)
+ }
+ })
+ .collect()
+}
+
+#[test]
+fn every_variant_has_exact_json_envelope() {
+ let event_id = Uuid::parse_str(EVENT_ID).expect("valid event id");
+
+ for (event, expected_payload) in topic_events() {
+ let mut expected = expected_payload;
+ let object = expected.as_object_mut().expect("expected object");
+ object.insert("event_id".to_string(), json!(EVENT_ID));
+ object.insert("schema_version".to_string(), json!(1));
+
+ assert_eq!(
+ serde_json::to_value(Event::with_event_id(event_id, event))
+ .expect("serializable event"),
+ expected
+ );
+ }
+}
+
+#[test]
+fn every_variant_round_trips() {
+ for original in macro_events() {
+ let payload = serde_json::to_vec(original.event()).expect("serializable event");
+ let decoded = TeamMacroEvent::decode(original.key(), &payload).expect("decodable event");
+
+ assert_eq!(decoded.key(), TEAM_ID);
+ assert_eq!(decoded.event(), original.event());
+ assert_eq!(decoded.topic().as_str(), "macro.teams");
+ }
+}
+
+#[test]
+fn constructors_use_teams_topic_bare_uuid_key_and_schema_version_one() {
+ for event in macro_events() {
+ assert_eq!(event.key(), TEAM_ID);
+ assert!(!event.key().starts_with("team|"));
+ assert_eq!(event.topic().as_str(), "macro.teams");
+ assert_eq!(event.event().schema_version, 1);
+ }
+}
+
+#[test]
+fn roles_and_join_methods_serialize_lowercase() {
+ let invite_join = serde_json::to_value(TeamJoinMethod::InviteAccepted {
+ invite_id: invite_id(),
+ invited_by: user_id("macro|[email protected]"),
+ })
+ .expect("serializable join method");
+ let domain_join =
+ serde_json::to_value(TeamJoinMethod::DomainAutoJoin).expect("serializable join method");
+
+ assert_eq!(invite_join["type"], "invite_accepted");
+ assert_eq!(domain_join, json!({ "type": "domain_auto_join" }));
+ assert_eq!(serde_json::to_value(TeamRole::Member).unwrap(), "member");
+ assert_eq!(serde_json::to_value(TeamRole::Admin).unwrap(), "admin");
+ assert_eq!(serde_json::to_value(TeamRole::Owner).unwrap(), "owner");
+}
+
+#[test]
+fn payloads_recursively_exclude_billing_fields() {
+ let forbidden_terms = ["subscription", "customer", "stripe", "payment"];
+
+ for event in macro_events() {
+ let payload = serde_json::to_value(event.event()).expect("serializable event");
+ assert_no_forbidden_fields(&payload, &forbidden_terms);
+ }
+}
+
+fn assert_no_forbidden_fields(value: &Value, forbidden_terms: &[&str]) {
+ match value {
+ Value::Object(object) => {
+ for (field, child) in object {
+ let normalized_field = field.to_ascii_lowercase();
+ for forbidden in forbidden_terms {
+ assert!(
+ !normalized_field.contains(forbidden),
+ "payload included forbidden field {field}"
+ );
+ }
+ assert_no_forbidden_fields(child, forbidden_terms);
+ }
+ }
+ Value::Array(values) => {
+ for child in values {
+ assert_no_forbidden_fields(child, forbidden_terms);
+ }
+ }
+ _ => {}
+ }
+}
diff --git a/crates/teams/src/domain/team_service.rs b/crates/teams/src/domain/team_service.rs
index b650d54823..69e9f705e6 100644
--- a/crates/teams/src/domain/team_service.rs
+++ b/crates/teams/src/domain/team_service.rs
@@ -8,6 +8,7 @@ use std::{collections::HashSet, sync::Arc};
use entity_access::domain::models::{
AdminTeamRole, EntityAccessReceipt, MemberTeamRole, OwnerTeamRole,
};
+use macro_event_broker::{MacroEventBroker, NoopMacroEventBroker};
use macro_user_id::{
cowlike::CowLike,
email::{Email, ReadEmailParts},
@@ -27,6 +28,12 @@ use crate::domain::{
contacts_enqueuer::{ContactsEnqueuer, NoOpContactsEnqueuer},
crm_enqueuer::CrmEnqueuer,
customer_repo::CustomerRepository,
+ events::{
+ TeamAutoJoinDomainToggledMetadata, TeamCreatedMetadata, TeamDeletedMetadata,
+ TeamInviteCreatedMetadata, TeamInviteRejectedMetadata, TeamInviteRevokedMetadata,
+ TeamJoinMethod, TeamMacroEvent, TeamMemberJoinedMetadata, TeamMemberRemovedMetadata,
+ TeamMemberRoleChangedMetadata, TeamUpdatedMetadata,
+ },
model::{
CreateTeamError, CustomerError, DeleteTeamError, FREE_TEAM_MAX_MEMBERS,
InviteUsersToTeamError, JoinTeamError, PatchTeamCrmSettingsResponse, PatchTeamRequest,
@@ -52,6 +59,7 @@ pub struct TeamServiceImpl<
TCRMS,
TA = NoOpTeamAnalytics,
CNE = NoOpContactsEnqueuer,
+ EB = NoopMacroEventBroker,
> where
TR: TeamRepository,
CR: CustomerRepository,
@@ -62,6 +70,7 @@ pub struct TeamServiceImpl<
TCRMS: TeamCrmSettingsRepository,
TA: TeamAnalytics,
CNE: ContactsEnqueuer,
+ EB: MacroEventBroker,
{
/// The underlying team repository
team_repository: TR,
@@ -84,10 +93,12 @@ pub struct TeamServiceImpl<
team_analytics: TA,
/// Outbound port for contact connections created through team membership.
contacts_enqueuer: CNE,
+ /// Outbound port for best-effort team events.
+ event_broker: EB,
}
-impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE> Clone
- for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE>
+impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE, EB> Clone
+ for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE, EB>
where
TR: TeamRepository,
CR: CustomerRepository,
@@ -98,6 +109,7 @@ where
TCRMS: TeamCrmSettingsRepository,
TA: TeamAnalytics,
CNE: ContactsEnqueuer,
+ EB: MacroEventBroker + Clone,
{
fn clone(&self) -> Self {
Self {
@@ -110,12 +122,24 @@ where
team_crm_settings_repository: self.team_crm_settings_repository.clone(),
team_analytics: self.team_analytics.clone(),
contacts_enqueuer: self.contacts_enqueuer.clone(),
+ event_broker: self.event_broker.clone(),
}
}
}
impl<TR, CR, TCR, URPS, NI, CE, TCRMS>
- TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, NoOpTeamAnalytics, NoOpContactsEnqueuer>
+ TeamServiceImpl<
+ TR,
+ CR,
+ TCR,
+ URPS,
+ NI,
+ CE,
+ TCRMS,
+ NoOpTeamAnalytics,
+ NoOpContactsEnqueuer,
+ NoopMacroEventBroker,
+ >
where
TR: TeamRepository,
CR: CustomerRepository,
@@ -149,7 +173,18 @@ where
}
impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA>
- TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, NoOpContactsEnqueuer>
+ TeamServiceImpl<
+ TR,
+ CR,
+ TCR,
+ URPS,
+ NI,
+ CE,
+ TCRMS,
+ TA,
+ NoOpContactsEnqueuer,
+ NoopMacroEventBroker,
+ >
where
TR: TeamRepository,
CR: CustomerRepository,
@@ -185,12 +220,13 @@ where
team_crm_settings_repository,
team_analytics,
contacts_enqueuer: NoOpContactsEnqueuer,
+ event_broker: NoopMacroEventBroker,
}
}
}
-impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE>
- TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE>
+impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE, EB>
+ TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE, EB>
where
TR: TeamRepository,
CR: CustomerRepository,
@@ -201,12 +237,13 @@ where
TCRMS: TeamCrmSettingsRepository,
TA: TeamAnalytics,
CNE: ContactsEnqueuer,
+ EB: MacroEventBroker,
{
/// Replaces the contacts enqueuer while preserving every other service dependency.
pub fn with_contacts_enqueuer<CNE2>(
self,
contacts_enqueuer: CNE2,
- ) -> TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE2>
+ ) -> TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE2, EB>
where
CNE2: ContactsEnqueuer,
{
@@ -220,9 +257,42 @@ where
team_crm_settings_repository: self.team_crm_settings_repository,
team_analytics: self.team_analytics,
contacts_enqueuer,
+ event_broker: self.event_broker,
+ }
+ }
+
+ /// Replaces the event broker while preserving every other service dependency.
+ pub fn with_event_broker<EB2>(
+ self,
+ event_broker: EB2,
+ ) -> TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE, EB2>
+ where
+ EB2: MacroEventBroker,
+ {
+ TeamServiceImpl {
+ team_repository: self.team_repository,
+ customer_repository: self.customer_repository,
+ team_channels_repository: self.team_channels_repository,
+ user_roles_and_permissions_service: self.user_roles_and_permissions_service,
+ notification_ingress: self.notification_ingress,
+ crm_enqueuer: self.crm_enqueuer,
+ team_crm_settings_repository: self.team_crm_settings_repository,
+ team_analytics: self.team_analytics,
+ contacts_enqueuer: self.contacts_enqueuer,
+ event_broker,
}
}
+ #[allow(
+ dead_code,
+ reason = "team mutations publish events in follow-up changes"
+ )]
+ fn publish_team_event(&self, event: &TeamMacroEvent) {
+ drop(self.event_broker.send_event(event).inspect_err(|error| {
+ tracing::error!(error = ?error, "failed to schedule team event");
+ }));
+ }
+
async fn track_team_analytics_event(&self, event: TeamAnalyticsEvent) {
self.team_analytics
.track_team_event(event)
@@ -434,8 +504,8 @@ impl GetTeamSubscriptionError {
}
}
-impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE> TeamMembersService
- for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE>
+impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE, EB> TeamMembersService
+ for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE, EB>
where
TR: TeamRepository,
CR: CustomerRepository,
@@ -446,6 +516,7 @@ where
TCRMS: TeamCrmSettingsRepository,
TA: TeamAnalytics,
CNE: ContactsEnqueuer,
+ EB: MacroEventBroker + Clone,
{
#[tracing::instrument(skip(self), err)]
async fn list_team_members(
@@ -462,8 +533,8 @@ where
}
}
-impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE> TeamService
- for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE>
+impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE, EB> TeamService
+ for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE, EB>
where
TR: TeamRepository,
CR: CustomerRepository,
@@ -474,6 +545,7 @@ where
TCRMS: TeamCrmSettingsRepository,
TA: TeamAnalytics,
CNE: ContactsEnqueuer,
+ EB: MacroEventBroker + Clone,
{
#[tracing::instrument(skip(self), err)]
async fn create_team(
@@ -506,13 +578,16 @@ where
// Owners can turn it off in settings. Best-effort - creation
// succeeds even if this fails.
let owner_email = user_id.email_part().lowercase();
- if !is_generic_email_domain(owner_email.domain_part()) {
+ let auto_join_domain = if is_generic_email_domain(owner_email.domain_part()) {
+ None
+ } else {
self.team_repository
.toggle_auto_join_domain(team.id())
.await
.inspect_err(|e| tracing::error!(error=?e, "unable to default auto-join domain on"))
- .ok();
- }
+ .ok()
+ .flatten()
+ };
self.track_team_analytics_event(TeamAnalyticsEvent::TeamCreated {
team_id: *team.id(),
@@ -520,6 +595,15 @@ where
team_name: team.name().to_owned(),
})
.await;
+ self.publish_team_event(&TeamMacroEvent::created(TeamCreatedMetadata {
+ team_id: *team.id(),
+ name: team.name().to_owned(),
+ slug: team.slug().to_owned(),
+ owner: user_id.clone().into_owned(),
+ enterprise: team.enterprise(),
+ paid: subscription_id.is_some(),
+ auto_join_domain,
+ }));
Ok(team)
}
@@ -695,6 +779,13 @@ where
team_name: team_name.clone(),
})
.await;
+ self.publish_team_event(&TeamMacroEvent::invite_created(TeamInviteCreatedMetadata {
+ team_id,
+ invite_id: invite.team_invite_id,
+ email: invite.email.as_ref().to_owned(),
+ invited_by: invited_by.clone().into_owned(),
+ team_name: team_name.clone(),
+ }));
}
Ok(invited)
@@ -866,10 +957,16 @@ where
self.track_team_analytics_event(TeamAnalyticsEvent::TeamLeft {
team_id,
member_id: removed_member.user_id.clone().into_owned(),
- removed_by_id,
+ removed_by_id: removed_by_id.clone(),
role: removed_member.role,
})
.await;
+ self.publish_team_event(&TeamMacroEvent::member_removed(TeamMemberRemovedMetadata {
+ team_id,
+ member_id: removed_member.user_id.into_owned(),
+ removed_by: removed_by_id,
+ role: removed_member.role,
+ }));
Ok(())
}
@@ -893,6 +990,15 @@ where
.delete_team_invite(&team_invite.team_id, team_invite_id)
.await?;
+ self.publish_team_event(&TeamMacroEvent::invite_rejected(
+ TeamInviteRejectedMetadata {
+ team_id: team_invite.team_id,
+ invite_id: team_invite.team_invite_id,
+ email: team_invite.email.as_ref().to_owned(),
+ actor_user_id: user_id.clone().into_owned(),
+ },
+ ));
+
Ok(())
}
@@ -904,11 +1010,27 @@ where
) -> Result<(), RemoveTeamInviteError> {
let team_id =
macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
+ let actor_user_id = entity_access_receipt
+ .get_authenticated_user()
+ .map_err(|error| RemoveTeamInviteError::TeamError(TeamError::AccessError(error)))?
+ .clone()
+ .into_owned();
+ let team_invite = self
+ .team_repository
+ .get_team_invite_by_id(team_invite_id)
+ .await?;
self.team_repository
.delete_team_invite(&team_id, team_invite_id)
.await?;
+ self.publish_team_event(&TeamMacroEvent::invite_revoked(TeamInviteRevokedMetadata {
+ team_id,
+ invite_id: team_invite.team_invite_id,
+ email: team_invite.email.as_ref().to_owned(),
+ actor_user_id,
+ }));
+
Ok(())
}
@@ -919,8 +1041,17 @@ where
) -> Result<(), DeleteTeamError> {
let team_id =
macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
+ let actor_user_id = entity_access_receipt
+ .get_authenticated_user()
+ .map_err(|error| DeleteTeamError::TeamError(TeamError::AccessError(error)))?
+ .clone()
+ .into_owned();
let members = self.team_repository.get_all_team_members(&team_id).await?;
+ let member_user_ids = members
+ .iter()
+ .map(|member| member.user_id.clone().into_owned())
+ .collect();
let subscription_id = self
.team_repository
@@ -938,6 +1069,11 @@ where
.delete_team(&team_id)
.await
.map_err(DeleteTeamError::TeamError)?;
+ self.publish_team_event(&TeamMacroEvent::deleted(TeamDeletedMetadata {
+ team_id,
+ actor_user_id,
+ member_user_ids,
+ }));
// Remove roles for team members
let roles = vec![RoleId::TeamSubscriber];
@@ -1272,6 +1408,15 @@ where
role: team_member.role,
})
.await;
+ self.publish_team_event(&TeamMacroEvent::member_joined(TeamMemberJoinedMetadata {
+ team_id: team_member.team_id,
+ member_id: team_member.user_id.clone().into_owned(),
+ role: team_member.role,
+ join_method: TeamJoinMethod::InviteAccepted {
+ invite_id: accepted_invite.invite.id,
+ invited_by: accepted_invite.invite.invited_by,
+ },
+ }));
Ok(team_member)
}
@@ -1391,6 +1536,11 @@ where
entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,
req: &PatchTeamRequest,
) -> Result<(), TeamError> {
+ let actor_user_id = entity_access_receipt
+ .get_authenticated_user()
+ .map_err(TeamError::AccessError)?
+ .clone()
+ .into_owned();
let team_id =
macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
@@ -1414,14 +1564,38 @@ where
}
for update in user_role_updates {
+ let previous_role = team
+ .members
+ .iter()
+ .find(|member| member.user_id == update.team_user_id)
+ .map(|member| member.role);
self.team_repository
.patch_team_user_role(&team_id, &update.team_user_id, update.role)
.await?;
+ self.publish_team_event(&TeamMacroEvent::member_role_changed(
+ TeamMemberRoleChangedMetadata {
+ team_id,
+ actor_user_id: actor_user_id.clone(),
+ member_id: update.team_user_id.clone(),
+ role: update.role,
+ previous_role,
+ },
+ ));
}
}
}
- self.team_repository.patch_team(&team_id, req).await
+ self.team_repository.patch_team(&team_id, req).await?;
+ if req.name.is_some() || req.slug.is_some() {
+ self.publish_team_event(&TeamMacroEvent::updated(TeamUpdatedMetadata {
+ team_id,
+ actor_user_id,
+ name: req.name.clone(),
+ slug: req.slug.clone(),
+ }));
+ }
+
+ Ok(())
}
#[tracing::instrument(skip(self), err)]
@@ -1523,10 +1697,27 @@ where
&self,
entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,
) -> Result<Option<String>, ToggleAutoJoinDomainError> {
+ let actor_user_id = entity_access_receipt
+ .get_authenticated_user()
+ .map_err(TeamError::AccessError)?
+ .clone()
+ .into_owned();
let team_id =
macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
- self.team_repository.toggle_auto_join_domain(&team_id).await
+ let auto_join_domain = self
+ .team_repository
+ .toggle_auto_join_domain(&team_id)
+ .await?;
+ self.publish_team_event(&TeamMacroEvent::auto_join_domain_toggled(
+ TeamAutoJoinDomainToggledMetadata {
+ team_id,
+ actor_user_id,
+ auto_join_domain: auto_join_domain.clone(),
+ },
+ ));
+
+ Ok(auto_join_domain)
}
#[tracing::instrument(skip(self), err)]
@@ -1786,6 +1977,12 @@ where
// NOTE: no TeamJoined analytics event here - that event is tied to
// the team invite that was accepted, and a domain auto-join has none.
+ self.publish_team_event(&TeamMacroEvent::member_joined(TeamMemberJoinedMetadata {
+ team_id,
+ member_id: team_member.user_id.clone().into_owned(),
+ role: team_member.role,
+ join_method: TeamJoinMethod::DomainAutoJoin,
+ }));
Ok(Some(team_member))
}
diff --git a/crates/teams/src/domain/team_service/test.rs b/crates/teams/src/domain/team_service/test.rs
index 4a9deff228..1b77dbaa09 100644
--- a/crates/teams/src/domain/team_service/test.rs
+++ b/crates/teams/src/domain/team_service/test.rs
@@ -8,8 +8,10 @@ use std::{
};
use entity_access::domain::models::{
- AdminTeamRole, EntityAccessReceipt, EntityType, MemberTeamRole, RequiredPermission,
+ AdminTeamRole, EntityAccessReceipt, EntityType, MemberTeamRole, OwnerTeamRole,
+ RequiredPermission,
};
+use macro_event_broker::{EventBrokerError, MacroEvent, MacroEventBroker, Topic as _};
use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr};
use notification::domain::{
models::{Notification, NotificationResult, request::SendNotificationRequest},
@@ -23,6 +25,7 @@ use roles_and_permissions::domain::{
use crate::domain::{
contacts_enqueuer::ContactsEnqueuer,
crm_enqueuer::{CrmEnqueuer, NoOpCrmEnqueuer},
+ events::TeamCreatedMetadata,
team_analytics::{TeamAnalytics, TeamAnalyticsEvent},
team_crm_settings_repo::NoOpTeamCrmSettingsRepository,
};
@@ -78,7 +81,9 @@ struct MockTeamRepository {
fail_rollback_accept: bool,
fail_rollback_remove: bool,
patch_team_user_role_calls: Arc<Mutex<Vec<(uuid::Uuid, String, TeamRole)>>>,
+ fail_patch_team_user_role_at: Option<usize>,
patch_team_name_calls: Arc<Mutex<Vec<(uuid::Uuid, Option<String>, Option<String>)>>>,
+ fail_patch_team: bool,
created_team: Team,
github_installation_move_calls: Arc<Mutex<Vec<(String, uuid::Uuid)>>>,
subscription_update_calls: Arc<Mutex<Vec<(uuid::Uuid, String)>>>,
@@ -86,6 +91,10 @@ struct MockTeamRepository {
fail_github_installation_move: bool,
fail_invite_users_to_team: bool,
invite_users_to_team_calls: Arc<Mutex<usize>>,
+ new_invite_emails: Option<Vec<String>>,
+ invite_by_id: Option<TeamInvite<'static>>,
+ delete_invite_calls: Arc<Mutex<Vec<(uuid::Uuid, uuid::Uuid)>>>,
+ fail_delete_invite: bool,
get_team_by_id_calls: Arc<Mutex<usize>>,
team_id_for_domain: Option<uuid::Uuid>,
team_plan: Option<TeamPlan>,
@@ -94,9 +103,14 @@ struct MockTeamRepository {
add_user_to_team_calls: Arc<Mutex<usize>>,
remove_user_calls: Arc<Mutex<usize>>,
auto_join_toggle_calls: Arc<Mutex<Vec<uuid::Uuid>>>,
+ auto_join_toggle_result: Option<String>,
+ fail_auto_join_toggle: bool,
allow_non_admin_invites: bool,
caller_team_role: Option<TeamRole>,
non_admin_invites_toggle_calls: Arc<Mutex<Vec<uuid::Uuid>>>,
+ delete_team_calls: Arc<Mutex<Vec<uuid::Uuid>>>,
+ fail_delete_team: bool,
+ fail_get_all_team_members: bool,
}
impl MockTeamRepository {
@@ -130,7 +144,9 @@ impl MockTeamRepository {
fail_rollback_accept: false,
fail_rollback_remove: false,
patch_team_user_role_calls: Arc::new(Mutex::new(Vec::new())),
+ fail_patch_team_user_role_at: None,
patch_team_name_calls: Arc::new(Mutex::new(Vec::new())),
+ fail_patch_team: false,
created_team: Team::new(
uuid::Uuid::from_u128(1000),
"Created Team".to_string(),
@@ -147,6 +163,10 @@ impl MockTeamRepository {
fail_github_installation_move: false,
fail_invite_users_to_team: false,
invite_users_to_team_calls: Arc::new(Mutex::new(0)),
+ new_invite_emails: None,
+ invite_by_id: None,
+ delete_invite_calls: Arc::new(Mutex::new(Vec::new())),
+ fail_delete_invite: false,
get_team_by_id_calls: Arc::new(Mutex::new(0)),
team_id_for_domain: None,
team_plan: None,
@@ -155,9 +175,14 @@ impl MockTeamRepository {
add_user_to_team_calls: Arc::new(Mutex::new(0)),
remove_user_calls: Arc::new(Mutex::new(0)),
auto_join_toggle_calls: Arc::new(Mutex::new(Vec::new())),
+ auto_join_toggle_result: Some("example.com".to_string()),
+ fail_auto_join_toggle: false,
allow_non_admin_invites: true,
caller_team_role: Some(TeamRole::Member),
non_admin_invites_toggle_calls: Arc::new(Mutex::new(Vec::new())),
+ delete_team_calls: Arc::new(Mutex::new(Vec::new())),
+ fail_delete_team: false,
+ fail_get_all_team_members: false,
}
}
@@ -320,16 +345,23 @@ impl TeamRepository for MockTeamRepository {
invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,
) -> impl Future<Output = Result<Vec<Email<Lowercase<'static>>>, InviteUsersToTeamError>> + Send
{
- let invites = invites
- .iter()
- .map(|email| {
- Email::parse_from_str(email.as_ref())
- .expect("test emails should be valid")
- .into_owned()
- .lowercase()
- })
- .collect();
- async move { Ok(invites) }
+ let invites = self.new_invite_emails.clone().unwrap_or_else(|| {
+ invites
+ .iter()
+ .map(|email| email.as_ref().to_owned())
+ .collect()
+ });
+ async move {
+ Ok(invites
+ .iter()
+ .map(|email| {
+ Email::parse_from_str(email)
+ .expect("test emails should be valid")
+ .into_owned()
+ .lowercase()
+ })
+ .collect())
+ }
}
fn mark_invites_sent(
@@ -357,15 +389,29 @@ impl TeamRepository for MockTeamRepository {
&self,
_: &uuid::Uuid,
) -> impl Future<Output = Result<TeamInvite<'_>, TeamError>> + Send {
- async { unimplemented!() }
+ let invite = self.invite_by_id.clone();
+ async move { invite.ok_or(TeamError::TeamInviteDoesNotExist) }
}
fn delete_team_invite(
&self,
- _: &uuid::Uuid,
- _: &uuid::Uuid,
+ team_id: &uuid::Uuid,
+ invite_id: &uuid::Uuid,
) -> impl Future<Output = Result<(), RemoveTeamInviteError>> + Send {
- async { unimplemented!() }
+ self.delete_invite_calls
+ .lock()
+ .unwrap()
+ .push((*team_id, *invite_id));
+ let fail = self.fail_delete_invite;
+ async move {
+ if fail {
+ Err(RemoveTeamInviteError::StorageLayerError(anyhow::anyhow!(
+ "invite deletion failed"
+ )))
+ } else {
+ Ok(())
+ }
+ }
}
fn update_team_subscription(
@@ -393,15 +439,38 @@ impl TeamRepository for MockTeamRepository {
async { Ok(()) }
}
- fn delete_team(&self, _: &uuid::Uuid) -> impl Future<Output = Result<(), TeamError>> + Send {
- async { unimplemented!() }
+ fn delete_team(
+ &self,
+ team_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<(), TeamError>> + Send {
+ self.delete_team_calls.lock().unwrap().push(*team_id);
+ let fail = self.fail_delete_team;
+ async move {
+ if fail {
+ Err(TeamError::StorageLayerError(anyhow::anyhow!(
+ "team deletion failed"
+ )))
+ } else {
+ Ok(())
+ }
+ }
}
fn get_all_team_members(
&self,
_: &uuid::Uuid,
) -> impl Future<Output = Result<Vec<TeamMember<'_>>, TeamError>> + Send {
- async { unimplemented!() }
+ let members = self.team_members.clone();
+ let fail = self.fail_get_all_team_members;
+ async move {
+ if fail {
+ Err(TeamError::StorageLayerError(anyhow::anyhow!(
+ "member lookup failed"
+ )))
+ } else {
+ Ok(members)
+ }
+ }
}
fn accept_team_invite(
@@ -451,7 +520,7 @@ impl TeamRepository for MockTeamRepository {
&self,
_: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<bool, TeamError>> + Send {
- async { unimplemented!() }
+ async { Ok(true) }
}
fn get_team_members(
@@ -522,7 +591,16 @@ impl TeamRepository for MockTeamRepository {
req.name.clone(),
req.slug.clone(),
));
- async { Ok(()) }
+ let fail = self.fail_patch_team;
+ async move {
+ if fail {
+ Err(TeamError::StorageLayerError(anyhow::anyhow!(
+ "team patch failed"
+ )))
+ } else {
+ Ok(())
+ }
+ }
}
fn get_team_role(
@@ -548,12 +626,20 @@ impl TeamRepository for MockTeamRepository {
user_id: &MacroUserIdStr<'_>,
role: TeamRole,
) -> impl Future<Output = Result<(), TeamError>> + Send {
- self.patch_team_user_role_calls.lock().unwrap().push((
- *team_id,
- user_id.as_ref().to_string(),
- role,
- ));
- async { Ok(()) }
+ let mut calls = self.patch_team_user_role_calls.lock().unwrap();
+ calls.push((*team_id, user_id.as_ref().to_string(), role));
+ let call_number = calls.len();
+ let fail = self.fail_patch_team_user_role_at == Some(call_number);
+ drop(calls);
+ async move {
+ if fail {
+ Err(TeamError::StorageLayerError(anyhow::anyhow!(
+ "role patch failed"
+ )))
+ } else {
+ Ok(())
+ }
+ }
}
fn get_team_seat_count(
@@ -585,7 +671,17 @@ impl TeamRepository for MockTeamRepository {
team_id: &uuid::Uuid,
) -> impl Future<Output = Result<Option<String>, ToggleAutoJoinDomainError>> + Send {
self.auto_join_toggle_calls.lock().unwrap().push(*team_id);
- async { Ok(Some("example.com".to_string())) }
+ let result = self.auto_join_toggle_result.clone();
+ let fail = self.fail_auto_join_toggle;
+ async move {
+ if fail {
+ Err(ToggleAutoJoinDomainError::TeamError(
+ TeamError::StorageLayerError(anyhow::anyhow!("toggle failed")),
+ ))
+ } else {
+ Ok(result)
+ }
+ }
}
fn get_team_allow_non_admin_invites(
@@ -955,6 +1051,53 @@ impl TeamAnalytics for MockTeamAnalytics {
}
}
+#[derive(Clone, Debug, PartialEq)]
+struct PublishedTeamEvent {
+ topic: &'static str,
+ key: String,
+ envelope: serde_json::Value,
+}
+
+#[derive(Clone, Default)]
+struct RecordingEventBroker {
+ events: Arc<Mutex<Vec<PublishedTeamEvent>>>,
+ fail_scheduling: bool,
+}
+
+impl RecordingEventBroker {
+ fn failing() -> Self {
+ Self {
+ fail_scheduling: true,
+ ..Self::default()
+ }
+ }
+
+ fn events(&self) -> Vec<PublishedTeamEvent> {
+ self.events.lock().unwrap().clone()
+ }
+}
+
+impl MacroEventBroker for RecordingEventBroker {
+ fn send_event<E: MacroEvent + ?Sized>(
+ &self,
+ event: &E,
+ ) -> Result<tokio::task::JoinHandle<Result<(), EventBrokerError>>, EventBrokerError> {
+ if self.fail_scheduling {
+ return Err(EventBrokerError::Publish(
+ "intentional scheduling failure".to_string(),
+ ));
+ }
+
+ self.events.lock().unwrap().push(PublishedTeamEvent {
+ topic: event.topic().as_str(),
+ key: event.key().to_string(),
+ envelope: serde_json::to_value(event.event())?,
+ });
+
+ Ok(tokio::spawn(async { Ok(()) }))
+ }
+}
+
type ContactPair = (MacroUserIdStr<'static>, MacroUserIdStr<'static>);
type ContactBatches = Arc<Mutex<Vec<Vec<ContactPair>>>>;
@@ -1208,6 +1351,22 @@ fn build_service(
(service, notification_ingress)
}
+fn build_service_with_event_broker(
+ team_repo: MockTeamRepository,
+ event_broker: RecordingEventBroker,
+) -> impl TeamService {
+ TeamServiceImpl::new(
+ team_repo,
+ MockCustomerRepository::default(),
+ MockTeamChannelsRepository::default(),
+ MockUserRolesAndPermissionsService::default(),
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ NoOpTeamCrmSettingsRepository,
+ )
+ .with_event_broker(event_broker)
+}
+
fn build_service_with_analytics(
team_repo: MockTeamRepository,
customer_repo: MockCustomerRepository,
@@ -1229,6 +1388,324 @@ fn build_service_with_analytics(
// -- Tests --
+#[tokio::test]
+async fn event_broker_can_be_replaced_and_is_preserved_by_service_reconstruction() {
+ let team_id = uuid::Uuid::from_u128(6000);
+ let event = TeamMacroEvent::created(TeamCreatedMetadata {
+ team_id,
+ name: "Event Team".to_string(),
+ slug: "EVENT_TEAM".to_string(),
+ owner: MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
+ enterprise: false,
+ paid: false,
+ auto_join_domain: None,
+ });
+ let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));
+ let default_service = TeamServiceImpl::new(
+ MockTeamRepository::new(Vec::new(), "Event Team", mark_sent_calls),
+ MockCustomerRepository::default(),
+ MockTeamChannelsRepository::default(),
+ MockUserRolesAndPermissionsService::default(),
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ NoOpTeamCrmSettingsRepository,
+ );
+
+ default_service.publish_team_event(&event);
+
+ let recording_broker = RecordingEventBroker::default();
+ let service = default_service
+ .with_event_broker(recording_broker.clone())
+ .with_contacts_enqueuer(RecordingContactsEnqueuer::default());
+ service.clone().publish_team_event(&event);
+
+ let events = recording_broker.events();
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0].topic, "macro.teams");
+ assert_eq!(events[0].key, team_id.to_string());
+ assert_eq!(events[0].envelope["event_type"], "team.created");
+ assert_eq!(
+ events[0].envelope["metadata"]["team_id"],
+ team_id.to_string()
+ );
+
+ service
+ .with_event_broker(RecordingEventBroker::failing())
+ .publish_team_event(&event);
+
+ let analytics_service = TeamServiceImpl::new_with_analytics(
+ MockTeamRepository::new(Vec::new(), "Event Team", Arc::new(Mutex::new(Vec::new()))),
+ MockCustomerRepository::default(),
+ MockTeamChannelsRepository::default(),
+ MockUserRolesAndPermissionsService::default(),
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ NoOpTeamCrmSettingsRepository,
+ MockTeamAnalytics::new(Arc::new(Mutex::new(Vec::new()))),
+ );
+ analytics_service.publish_team_event(&event);
+}
+
+#[tokio::test]
+async fn team_event_create_publishes_actual_domain_and_billing_flags() {
+ let owner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let team_id = uuid::Uuid::from_u128(6100);
+ let mut team_repository = MockTeamRepository::new(
+ Vec::new(),
+ "Enterprise Team",
+ Arc::new(Mutex::new(Vec::new())),
+ );
+ team_repository.created_team = Team::new(
+ team_id,
+ "Enterprise Team".to_string(),
+ "ENTERPRISE_TEAM".to_string(),
+ owner.clone().into_owned(),
+ false,
+ true,
+ );
+ let event_broker = RecordingEventBroker::default();
+ let service = build_service_with_event_broker(team_repository, event_broker.clone());
+ let subscription_id: stripe::SubscriptionId = "sub_test".parse().unwrap();
+
+ service
+ .create_team(&owner, "Enterprise Team", Some(&subscription_id))
+ .await
+ .unwrap();
+
+ let events = event_broker.events();
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0].envelope["event_type"], "team.created");
+ let metadata = &events[0].envelope["metadata"];
+ assert_eq!(metadata["team_id"], team_id.to_string());
+ assert_eq!(metadata["enterprise"], true);
+ assert_eq!(metadata["paid"], true);
+ assert_eq!(metadata["auto_join_domain"], "example.com");
+}
+
+#[tokio::test]
+async fn team_event_create_generic_domain_is_unpaid_without_auto_join() {
+ let owner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let team_repository = MockTeamRepository::new(
+ Vec::new(),
+ "Personal Team",
+ Arc::new(Mutex::new(Vec::new())),
+ );
+ let event_broker = RecordingEventBroker::default();
+ let service = build_service_with_event_broker(team_repository, event_broker.clone());
+
+ service
+ .create_team(&owner, "Personal Team", None)
+ .await
+ .unwrap();
+
+ let events = event_broker.events();
+ assert_eq!(events.len(), 1);
+ let metadata = &events[0].envelope["metadata"];
+ assert_eq!(metadata["enterprise"], false);
+ assert_eq!(metadata["paid"], false);
+ assert!(metadata["auto_join_domain"].is_null());
+}
+
+#[tokio::test]
+async fn team_event_create_failure_emits_nothing_and_broker_failure_is_swallowed() {
+ let owner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let mut team_repository =
+ MockTeamRepository::new(Vec::new(), "Failed Team", Arc::new(Mutex::new(Vec::new())));
+ team_repository.fail_github_installation_move = true;
+ let event_broker = RecordingEventBroker::default();
+ let service = build_service_with_event_broker(team_repository, event_broker.clone());
+
+ assert!(
+ service
+ .create_team(&owner, "Failed Team", None)
+ .await
+ .is_err()
+ );
+ assert!(event_broker.events().is_empty());
+
+ let team_repository = MockTeamRepository::new(
+ Vec::new(),
+ "Successful Team",
+ Arc::new(Mutex::new(Vec::new())),
+ );
+ let service = build_service_with_event_broker(team_repository, RecordingEventBroker::failing());
+ assert!(
+ service
+ .create_team(&owner, "Successful Team", None)
+ .await
+ .is_ok()
+ );
+}
+
+#[tokio::test]
+async fn invite_team_event_is_published_only_for_new_lowercase_email() {
+ let team_id = uuid::Uuid::from_u128(6110);
+ let new_invite_id = uuid::Uuid::from_u128(6111);
+ let existing_invite_id = uuid::Uuid::from_u128(6112);
+ let inviter = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let mut team_repository = MockTeamRepository::new(
+ vec![
+ make_invite("[email protected]", new_invite_id, team_id),
+ make_invite("[email protected]", existing_invite_id, team_id),
+ ],
+ "Invite Team",
+ Arc::new(Mutex::new(Vec::new())),
+ );
+ team_repository.new_invite_emails = Some(vec!["[email protected]".to_string()]);
+ let event_broker = RecordingEventBroker::default();
+ let service = build_service_with_event_broker(team_repository, event_broker.clone());
+ let emails = vec![
+ Email::parse_from_str("[email protected]")
+ .unwrap()
+ .lowercase(),
+ Email::parse_from_str("[email protected]")
+ .unwrap()
+ .lowercase(),
+ ];
+
+ service
+ .invite_users_to_team(
+ test_team_receipt::<MemberTeamRole>(team_id, &inviter),
+ non_empty::NonEmpty::new(emails.as_slice()).unwrap(),
+ )
+ .await
+ .unwrap();
+
+ let events = event_broker.events();
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0].envelope["event_type"], "team.invite_created");
+ let metadata = &events[0].envelope["metadata"];
+ assert_eq!(metadata["invite_id"], new_invite_id.to_string());
+ assert_eq!(metadata["email"], "[email protected]");
+ assert_eq!(metadata["invited_by"], inviter.as_ref());
+ assert_eq!(metadata["team_name"], "Invite Team");
+}
+
+#[tokio::test]
+async fn invite_team_event_repository_failure_emits_nothing_and_broker_failure_is_swallowed() {
+ let team_id = uuid::Uuid::from_u128(6115);
+ let invite_id = uuid::Uuid::from_u128(6116);
+ let inviter = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let email = Email::parse_from_str("[email protected]")
+ .unwrap()
+ .lowercase();
+ let emails = [email];
+ let mut team_repository = MockTeamRepository::new(
+ vec![make_invite("[email protected]", invite_id, team_id)],
+ "Invite Team",
+ Arc::new(Mutex::new(Vec::new())),
+ );
+ team_repository.fail_invite_users_to_team = true;
+ let event_broker = RecordingEventBroker::default();
+ let service = build_service_with_event_broker(team_repository, event_broker.clone());
+
+ assert!(
+ service
+ .invite_users_to_team(
+ test_team_receipt::<MemberTeamRole>(team_id, &inviter),
+ non_empty::NonEmpty::new(emails.as_slice()).unwrap(),
+ )
+ .await
+ .is_err()
+ );
+ assert!(event_broker.events().is_empty());
+
+ let team_repository = MockTeamRepository::new(
+ vec![make_invite("[email protected]", invite_id, team_id)],
+ "Invite Team",
+ Arc::new(Mutex::new(Vec::new())),
+ );
+ let service = build_service_with_event_broker(team_repository, RecordingEventBroker::failing());
+ assert!(
+ service
+ .invite_users_to_team(
+ test_team_receipt::<MemberTeamRole>(team_id, &inviter),
+ non_empty::NonEmpty::new(emails.as_slice()).unwrap(),
+ )
+ .await
+ .is_ok()
+ );
+}
+
+#[tokio::test]
+async fn invite_team_event_rejected_and_revoked_payloads_follow_successful_deletion() {
+ let team_id = uuid::Uuid::from_u128(6120);
+ let invite_id = uuid::Uuid::from_u128(6121);
+ let invite = make_invite("[email protected]", invite_id, team_id);
+ let recipient = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let mut team_repository =
+ MockTeamRepository::new(Vec::new(), "Invite Team", Arc::new(Mutex::new(Vec::new())));
+ team_repository.invite_by_id = Some(invite.clone());
+ let event_broker = RecordingEventBroker::default();
+ let service = build_service_with_event_broker(team_repository, event_broker.clone());
+
+ service
+ .reject_invitation(&recipient, &invite_id)
+ .await
+ .unwrap();
+
+ let events = event_broker.events();
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0].envelope["event_type"], "team.invite_rejected");
+ assert_eq!(
+ events[0].envelope["metadata"]["email"],
+ );
+ assert_eq!(
+ events[0].envelope["metadata"]["actor_user_id"],
+ recipient.as_ref()
+ );
+
+ let admin = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let mut team_repository =
+ MockTeamRepository::new(Vec::new(), "Invite Team", Arc::new(Mutex::new(Vec::new())));
+ team_repository.invite_by_id = Some(invite);
+ let event_broker = RecordingEventBroker::default();
+ let service = build_service_with_event_broker(team_repository, event_broker.clone());
+
+ service
+ .delete_team_invite(
+ test_team_receipt::<AdminTeamRole>(team_id, &admin),
+ &invite_id,
+ )
+ .await
+ .unwrap();
+
+ let events = event_broker.events();
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0].envelope["event_type"], "team.invite_revoked");
+ assert_eq!(
+ events[0].envelope["metadata"]["actor_user_id"],
+ admin.as_ref()
+ );
+}
+
+#[tokio::test]
+async fn invite_team_event_deletion_failure_emits_nothing() {
+ let team_id = uuid::Uuid::from_u128(6130);
+ let invite_id = uuid::Uuid::from_u128(6131);
+ let admin = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let mut team_repository =
+ MockTeamRepository::new(Vec::new(), "Invite Team", Arc::new(Mutex::new(Vec::new())));
+ team_repository.invite_by_id = Some(make_invite("[email protected]", invite_id, team_id));
+ team_repository.fail_delete_invite = true;
+ let event_broker = RecordingEventBroker::default();
+ let service = build_service_with_event_broker(team_repository, event_broker.clone());
+
+ assert!(
+ service
+ .delete_team_invite(
+ test_team_receipt::<AdminTeamRole>(team_id, &admin),
+ &invite_id,
+ )
+ .await
+ .is_err()
+ );
+ assert!(event_broker.events().is_empty());
+}
+
#[tokio::test]
async fn team_payment_revoke_removes_exact_premium_roles_from_members() {
let team_id = uuid::Uuid::from_u128(5000);
@@ -2178,10 +2655,20 @@ async fn test_get_team_reports_crm_enabled() {
struct RecordingCrmEnqueuer {
populated: Arc<Mutex<Vec<String>>>,
depopulated: Arc<Mutex<Vec<(uuid::Uuid, String)>>>,
+ fail: bool,
+}
+
+impl RecordingCrmEnqueuer {
+ fn failing() -> Self {
+ Self {
+ fail: true,
+ ..Self::default()
+ }
+ }
}
impl CrmEnqueuer for RecordingCrmEnqueuer {
- type Err = std::convert::Infallible;
+ type Err = &'static str;
async fn enqueue_populate_crm_for_user(
&self,
@@ -2191,7 +2678,11 @@ impl CrmEnqueuer for RecordingCrmEnqueuer {
.lock()
.unwrap()
.push(macro_id.as_ref().to_string());
- Ok(())
+ if self.fail {
+ Err("CRM enqueue failed")
+ } else {
+ Ok(())
+ }
}
async fn enqueue_depopulate_crm_for_user(
@@ -2203,7 +2694,11 @@ impl CrmEnqueuer for RecordingCrmEnqueuer {
.lock()
.unwrap()
.push((*team_id, macro_id.as_ref().to_string()));
- Ok(())
+ if self.fail {
+ Err("CRM enqueue failed")
+ } else {
+ Ok(())
+ }
}
}
@@ -2290,6 +2785,22 @@ async fn test_enable_crm_without_backfill_skips_enqueue() {
assert!(populated.lock().unwrap().is_empty());
}
+fn build_service_with_repo_and_broker(
+ team_repo: MockTeamRepository,
+ event_broker: RecordingEventBroker,
+) -> impl TeamService {
+ TeamServiceImpl::new(
+ team_repo,
+ MockCustomerRepository::default(),
+ MockTeamChannelsRepository::default(),
+ MockUserRolesAndPermissionsService::default(),
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ NoOpTeamCrmSettingsRepository,
+ )
+ .with_event_broker(event_broker)
+}
+
fn build_service_with_team(
team: Team,
) -> (
@@ -2486,6 +2997,266 @@ async fn test_patch_team_empty_role_updates() {
assert_eq!(name_calls[0], (team_id, Some("New Name".to_string()), None));
}
+#[tokio::test]
+async fn test_patch_team_metadata_publishes_updated_with_omitted_fields() {
+ let team_id = uuid::Uuid::from_u128(801);
+ let actor = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let broker = RecordingEventBroker::default();
+ let service = build_service_with_repo_and_broker(
+ MockTeamRepository::new(Vec::new(), "Team", Arc::new(Mutex::new(Vec::new()))),
+ broker.clone(),
+ );
+ let request = PatchTeamRequest {
+ name: Some("Renamed".to_string()),
+ slug: None,
+ user_role_updates: None,
+ };
+
+ service
+ .patch_team(
+ test_team_receipt::<AdminTeamRole>(team_id, &actor),
+ &request,
+ )
+ .await
+ .unwrap();
+
+ let events = broker.events();
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0].envelope["event_type"], "team.updated");
+ let metadata = &events[0].envelope["metadata"];
+ assert_eq!(metadata["actor_user_id"], actor.as_ref());
+ assert_eq!(metadata["name"], "Renamed");
+ assert!(metadata["slug"].is_null());
+}
+
+#[tokio::test]
+async fn test_patch_team_role_only_publishes_previous_role_without_updated_event() {
+ let team_id = uuid::Uuid::from_u128(802);
+ let owner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let member = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let mut repo = MockTeamRepository::new(Vec::new(), "Team", Arc::new(Mutex::new(Vec::new())))
+ .with_team(Team::new(
+ team_id,
+ "Team".to_string(),
+ "team".to_string(),
+ owner.clone().into_owned(),
+ false,
+ false,
+ ));
+ repo.team_members = vec![make_team_member(team_id, member.as_ref(), TeamRole::Member)];
+ let broker = RecordingEventBroker::default();
+ let service = build_service_with_repo_and_broker(repo, broker.clone());
+ let request = PatchTeamRequest {
+ name: None,
+ slug: None,
+ user_role_updates: Some(vec![PatchTeamUserRole {
+ team_user_id: member.clone().into_owned(),
+ role: TeamRole::Admin,
+ }]),
+ };
+
+ service
+ .patch_team(
+ test_team_receipt::<AdminTeamRole>(team_id, &owner),
+ &request,
+ )
+ .await
+ .unwrap();
+
+ let events = broker.events();
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0].envelope["event_type"], "team.member_role_changed");
+ let metadata = &events[0].envelope["metadata"];
+ assert_eq!(metadata["previous_role"], "member");
+ assert_eq!(metadata["role"], "admin");
+ assert_eq!(metadata["actor_user_id"], owner.as_ref());
+}
+
+#[tokio::test]
+async fn test_patch_team_partial_role_failure_keeps_ordered_success_events() {
+ let team_id = uuid::Uuid::from_u128(803);
+ let owner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let first = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let second = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let mut repo = MockTeamRepository::new(Vec::new(), "Team", Arc::new(Mutex::new(Vec::new())))
+ .with_team(Team::new(
+ team_id,
+ "Team".to_string(),
+ "team".to_string(),
+ owner.clone().into_owned(),
+ false,
+ false,
+ ));
+ repo.team_members = vec![
+ make_team_member(team_id, first.as_ref(), TeamRole::Member),
+ make_team_member(team_id, second.as_ref(), TeamRole::Admin),
+ ];
+ repo.fail_patch_team_user_role_at = Some(2);
+ let broker = RecordingEventBroker::default();
+ let service = build_service_with_repo_and_broker(repo, broker.clone());
+ let request = PatchTeamRequest {
+ name: None,
+ slug: None,
+ user_role_updates: Some(vec![
+ PatchTeamUserRole {
+ team_user_id: first.clone().into_owned(),
+ role: TeamRole::Admin,
+ },
+ PatchTeamUserRole {
+ team_user_id: second.clone().into_owned(),
+ role: TeamRole::Member,
+ },
+ ]),
+ };
+
+ assert!(
+ service
+ .patch_team(
+ test_team_receipt::<AdminTeamRole>(team_id, &owner),
+ &request
+ )
+ .await
+ .is_err()
+ );
+
+ let events = broker.events();
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0].envelope["metadata"]["member_id"], first.as_ref());
+}
+
+#[tokio::test]
+async fn test_patch_team_repository_failure_does_not_publish_updated() {
+ let team_id = uuid::Uuid::from_u128(804);
+ let actor = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let mut repo = MockTeamRepository::new(Vec::new(), "Team", Arc::new(Mutex::new(Vec::new())));
+ repo.fail_patch_team = true;
+ let broker = RecordingEventBroker::default();
+ let service = build_service_with_repo_and_broker(repo, broker.clone());
+ let request = PatchTeamRequest {
+ name: Some("Renamed".to_string()),
+ slug: None,
+ user_role_updates: None,
+ };
+
+ assert!(
+ service
+ .patch_team(
+ test_team_receipt::<AdminTeamRole>(team_id, &actor),
+ &request
+ )
+ .await
+ .is_err()
+ );
+ assert!(broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn test_toggle_auto_join_domain_publishes_enabled_and_disabled_states() {
+ let team_id = uuid::Uuid::from_u128(805);
+ let actor = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ for expected_domain in [Some("example.com".to_string()), None] {
+ let mut repo =
+ MockTeamRepository::new(Vec::new(), "Team", Arc::new(Mutex::new(Vec::new())));
+ repo.auto_join_toggle_result = expected_domain.clone();
+ let broker = RecordingEventBroker::default();
+ let service = build_service_with_repo_and_broker(repo, broker.clone());
+
+ let result = service
+ .toggle_auto_join_domain(test_team_receipt::<AdminTeamRole>(team_id, &actor))
+ .await
+ .unwrap();
+
+ assert_eq!(result, expected_domain);
+ let events = broker.events();
+ assert_eq!(events.len(), 1);
+ assert_eq!(
+ events[0].envelope["event_type"],
+ "team.auto_join_domain_toggled"
+ );
+ assert_eq!(
+ events[0].envelope["metadata"]["auto_join_domain"],
+ serde_json::to_value(expected_domain).unwrap()
+ );
+ assert_eq!(
+ events[0].envelope["metadata"]["actor_user_id"],
+ actor.as_ref()
+ );
+ }
+}
+
+#[tokio::test]
+async fn test_toggle_auto_join_domain_failure_does_not_publish_event() {
+ let team_id = uuid::Uuid::from_u128(806);
+ let actor = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let mut repo = MockTeamRepository::new(Vec::new(), "Team", Arc::new(Mutex::new(Vec::new())));
+ repo.fail_auto_join_toggle = true;
+ let broker = RecordingEventBroker::default();
+ let service = build_service_with_repo_and_broker(repo, broker.clone());
+
+ assert!(
+ service
+ .toggle_auto_join_domain(test_team_receipt::<AdminTeamRole>(team_id, &actor))
+ .await
+ .is_err()
+ );
+ assert!(broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn test_delete_team_publishes_single_event_with_member_snapshot() {
+ let team_id = uuid::Uuid::from_u128(807);
+ let owner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let member = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let mut repo = MockTeamRepository::new(Vec::new(), "Team", Arc::new(Mutex::new(Vec::new())));
+ repo.team_members = vec![
+ make_team_member(team_id, owner.as_ref(), TeamRole::Owner),
+ make_team_member(team_id, member.as_ref(), TeamRole::Member),
+ ];
+ let broker = RecordingEventBroker::default();
+ let service = build_service_with_repo_and_broker(repo, broker.clone());
+
+ service
+ .delete_team(test_team_receipt::<OwnerTeamRole>(team_id, &owner))
+ .await
+ .unwrap();
+
+ let events = broker.events();
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0].envelope["event_type"], "team.deleted");
+ let metadata = &events[0].envelope["metadata"];
+ assert_eq!(metadata["actor_user_id"], owner.as_ref());
+ assert_eq!(
+ metadata["member_user_ids"],
+ serde_json::json!([owner.as_ref(), member.as_ref()])
+ );
+}
+
+#[tokio::test]
+async fn test_delete_team_repository_failures_do_not_publish_event() {
+ let team_id = uuid::Uuid::from_u128(808);
+ let owner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ for failure_step in 0..3 {
+ let mut repo =
+ MockTeamRepository::new(Vec::new(), "Team", Arc::new(Mutex::new(Vec::new())));
+ repo.team_members = vec![make_team_member(team_id, owner.as_ref(), TeamRole::Owner)];
+ repo.fail_get_all_team_members = failure_step == 0;
+ repo.fail_team_subscription_id_lookup = failure_step == 1;
+ repo.fail_delete_team = failure_step == 2;
+ let broker = RecordingEventBroker::default();
+ let service = build_service_with_repo_and_broker(repo, broker.clone());
+
+ assert!(
+ service
+ .delete_team(test_team_receipt::<OwnerTeamRole>(team_id, &owner))
+ .await
+ .is_err()
+ );
+ assert!(broker.events().is_empty());
+ }
+}
+
#[tokio::test]
async fn test_invite_users_to_team_backfills_legacy_team_subscription() {
let team_id = uuid::Uuid::from_u128(42);
@@ -3049,6 +3820,44 @@ async fn team_analytics_join_team_emits_joined_event_with_team_id() {
}
}
+#[tokio::test]
+async fn team_event_invite_join_uses_accepted_invite_snapshot() {
+ let team_id = uuid::Uuid::from_u128(333);
+ let invite_id = uuid::Uuid::from_u128(334);
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let team_repository = make_enterprise_join_team_repository(team_id, invite_id, &user_id);
+ let event_broker = RecordingEventBroker::default();
+ let service = TeamServiceImpl::new(
+ team_repository,
+ MockCustomerRepository::default(),
+ MockTeamChannelsRepository::default(),
+ MockUserRolesAndPermissionsService::default(),
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ RecordingCrmEnqueuer::failing(),
+ NoOpTeamCrmSettingsRepository,
+ )
+ .with_contacts_enqueuer(RecordingContactsEnqueuer::failing())
+ .with_event_broker(event_broker.clone());
+
+ service.join_team(&invite_id, &user_id).await.unwrap();
+
+ let events = event_broker.events();
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0].topic, "macro.teams");
+ assert_eq!(events[0].key, team_id.to_string());
+ assert_eq!(events[0].envelope["event_type"], "team.member_joined");
+ let metadata = &events[0].envelope["metadata"];
+ assert_eq!(metadata["team_id"], team_id.to_string());
+ assert_eq!(metadata["member_id"], user_id.as_ref());
+ assert_eq!(metadata["role"], "member");
+ assert_eq!(metadata["join_method"]["type"], "invite_accepted");
+ assert_eq!(metadata["join_method"]["invite_id"], invite_id.to_string());
+ assert_eq!(
+ metadata["join_method"]["invited_by"],
+ );
+}
+
#[tokio::test]
async fn test_join_team_rolls_back_accept_when_customer_increment_fails() {
let team_id = uuid::Uuid::from_u128(1);
@@ -3073,6 +3882,7 @@ async fn test_join_team_rolls_back_accept_when_customer_increment_fails() {
let roles_service = MockUserRolesAndPermissionsService::default();
let upsert_role_calls = roles_service.upsert_calls.clone();
+ let event_broker = RecordingEventBroker::default();
let service = TeamServiceImpl::new(
team_repo,
customer_repo,
@@ -3081,11 +3891,13 @@ async fn test_join_team_rolls_back_accept_when_customer_increment_fails() {
Arc::new(MockNotificationIngress::new(HashSet::new())),
NoOpCrmEnqueuer,
NoOpTeamCrmSettingsRepository,
- );
+ )
+ .with_event_broker(event_broker.clone());
let err = service.join_team(&invite_id, &user_id).await.err().unwrap();
assert!(matches!(err, JoinTeamError::CustomerError(_)));
+ assert!(event_broker.events().is_empty());
assert_eq!(
*increment_calls.lock().unwrap(),
vec![(subscription_id.to_string(), 1)]
@@ -3209,6 +4021,42 @@ async fn team_analytics_remove_user_from_team_emits_left_event_with_team_id() {
}
}
+#[tokio::test]
+async fn team_event_self_service_removal_uses_member_as_actor_and_previous_role() {
+ let team_id = uuid::Uuid::from_u128(335);
+ let member_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let team_repository =
+ make_enterprise_remove_user_repository(team_id, &member_id, TeamRole::Admin);
+ let event_broker = RecordingEventBroker::default();
+ let service = TeamServiceImpl::new(
+ team_repository,
+ MockCustomerRepository::default(),
+ MockTeamChannelsRepository::default(),
+ MockUserRolesAndPermissionsService::default(),
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ RecordingCrmEnqueuer::failing(),
+ NoOpTeamCrmSettingsRepository,
+ )
+ .with_event_broker(event_broker.clone());
+
+ service
+ .remove_user_from_team(
+ test_team_receipt::<AdminTeamRole>(team_id, &member_id),
+ &member_id,
+ )
+ .await
+ .unwrap();
+
+ let events = event_broker.events();
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0].envelope["event_type"], "team.member_removed");
+ let metadata = &events[0].envelope["metadata"];
+ assert_eq!(metadata["team_id"], team_id.to_string());
+ assert_eq!(metadata["member_id"], member_id.as_ref());
+ assert_eq!(metadata["removed_by"], member_id.as_ref());
+ assert_eq!(metadata["role"], "admin");
+}
+
#[tokio::test]
async fn test_remove_user_from_team_rolls_back_remove_when_customer_decrement_fails() {
let team_id = uuid::Uuid::from_u128(1);
@@ -3561,6 +4409,7 @@ async fn test_try_join_team_by_domain_returns_none_when_already_member() {
let customer_repo = MockCustomerRepository::default();
let increment_calls = customer_repo.increment_calls.clone();
+ let event_broker = RecordingEventBroker::default();
let service = TeamServiceImpl::new(
team_repo,
customer_repo,
@@ -3569,12 +4418,14 @@ async fn test_try_join_team_by_domain_returns_none_when_already_member() {
Arc::new(MockNotificationIngress::new(HashSet::new())),
NoOpCrmEnqueuer,
NoOpTeamCrmSettingsRepository,
- );
+ )
+ .with_event_broker(event_broker.clone());
let member = service.try_join_team_by_domain(&user_id).await.unwrap();
assert!(member.is_none());
assert!(increment_calls.lock().unwrap().is_empty());
+ assert!(event_broker.events().is_empty());
}
#[tokio::test]
@@ -3598,6 +4449,7 @@ async fn test_try_join_team_by_domain_skips_team_at_seat_cap() {
let customer_repo = MockCustomerRepository::default();
let increment_calls = customer_repo.increment_calls.clone();
+ let event_broker = RecordingEventBroker::default();
let service = TeamServiceImpl::new(
team_repo,
customer_repo,
@@ -3606,12 +4458,14 @@ async fn test_try_join_team_by_domain_skips_team_at_seat_cap() {
Arc::new(MockNotificationIngress::new(HashSet::new())),
NoOpCrmEnqueuer,
NoOpTeamCrmSettingsRepository,
- );
+ )
+ .with_event_broker(event_broker.clone());
let member = service.try_join_team_by_domain(&user_id).await.unwrap();
assert!(member.is_none());
assert!(increment_calls.lock().unwrap().is_empty());
+ assert!(event_broker.events().is_empty());
}
#[tokio::test]
@@ -3642,6 +4496,7 @@ async fn test_try_join_team_by_domain_rolls_back_membership_when_roles_fail() {
..Default::default()
};
+ let event_broker = RecordingEventBroker::default();
let service = TeamServiceImpl::new(
team_repo,
customer_repo,
@@ -3650,7 +4505,8 @@ async fn test_try_join_team_by_domain_rolls_back_membership_when_roles_fail() {
Arc::new(MockNotificationIngress::new(HashSet::new())),
NoOpCrmEnqueuer,
NoOpTeamCrmSettingsRepository,
- );
+ )
+ .with_event_broker(event_broker.clone());
let err = service
.try_join_team_by_domain(&user_id)
@@ -3673,6 +4529,7 @@ async fn test_try_join_team_by_domain_rolls_back_membership_when_roles_fail() {
vec![(subscription_id.to_string(), 1)]
);
assert_eq!(*remove_user_calls.lock().unwrap(), 1);
+ assert!(event_broker.events().is_empty());
}
#[tokio::test]
@@ -3734,6 +4591,7 @@ async fn try_join_team_by_domain_enterprise_bypasses_billing_and_preserves_side_
let crm_enqueuer = RecordingCrmEnqueuer::default();
let events = Arc::new(Mutex::new(Vec::new()));
+ let event_broker = RecordingEventBroker::default();
let service = TeamServiceImpl::new_with_analytics(
team_repository.clone(),
customer_repository.clone(),
@@ -3743,7 +4601,8 @@ async fn try_join_team_by_domain_enterprise_bypasses_billing_and_preserves_side_
crm_enqueuer.clone(),
NoOpTeamCrmSettingsRepository,
MockTeamAnalytics::new(events.clone()),
- );
+ )
+ .with_event_broker(event_broker.clone());
let member = service
.try_join_team_by_domain(&user_id)
@@ -3782,6 +4641,17 @@ async fn try_join_team_by_domain_enterprise_bypasses_billing_and_preserves_side_
vec![user_id.as_ref().to_string()]
);
assert!(events.lock().unwrap().is_empty());
+ let published_events = event_broker.events();
+ assert_eq!(published_events.len(), 1);
+ assert_eq!(
+ published_events[0].envelope["event_type"],
+ "team.member_joined"
+ );
+ let metadata = &published_events[0].envelope["metadata"];
+ assert_eq!(metadata["team_id"], team_id.to_string());
+ assert_eq!(metadata["member_id"], user_id.as_ref());
+ assert_eq!(metadata["role"], "member");
+ assert_eq!(metadata["join_method"]["type"], "domain_auto_join");
}
#[tokio::test]
@@ -3925,6 +4795,7 @@ async fn remove_user_from_team_enterprise_bypasses_billing_and_preserves_side_ef
let crm_enqueuer = RecordingCrmEnqueuer::default();
let events = Arc::new(Mutex::new(Vec::new()));
+ let event_broker = RecordingEventBroker::default();
let service = TeamServiceImpl::new_with_analytics(
team_repository.clone(),
customer_repository.clone(),
@@ -3934,7 +4805,8 @@ async fn remove_user_from_team_enterprise_bypasses_billing_and_preserves_side_ef
crm_enqueuer.clone(),
NoOpTeamCrmSettingsRepository,
MockTeamAnalytics::new(events.clone()),
- );
+ )
+ .with_event_broker(event_broker.clone());
service
.remove_user_from_team(
@@ -3975,10 +4847,20 @@ async fn remove_user_from_team_enterprise_bypasses_billing_and_preserves_side_ef
vec![TeamAnalyticsEvent::TeamLeft {
team_id,
member_id: member_id.clone().into_owned(),
- removed_by_id: owner_id.into_owned(),
+ removed_by_id: owner_id.clone().into_owned(),
role: TeamRole::Admin,
}]
);
+ let published_events = event_broker.events();
+ assert_eq!(published_events.len(), 1);
+ assert_eq!(
+ published_events[0].envelope["event_type"],
+ "team.member_removed"
+ );
+ let metadata = &published_events[0].envelope["metadata"];
+ assert_eq!(metadata["member_id"], member_id.as_ref());
+ assert_eq!(metadata["removed_by"], owner_id.as_ref());
+ assert_eq!(metadata["role"], "admin");
}
#[tokio::test]
@@ -3997,6 +4879,7 @@ async fn remove_user_from_team_enterprise_rolls_back_membership_when_channel_rem
let crm_enqueuer = RecordingCrmEnqueuer::default();
let events = Arc::new(Mutex::new(Vec::new()));
+ let event_broker = RecordingEventBroker::default();
let service = TeamServiceImpl::new_with_analytics(
team_repository.clone(),
customer_repository.clone(),
@@ -4006,7 +4889,8 @@ async fn remove_user_from_team_enterprise_rolls_back_membership_when_channel_rem
crm_enqueuer.clone(),
NoOpTeamCrmSettingsRepository,
MockTeamAnalytics::new(events.clone()),
- );
+ )
+ .with_event_broker(event_broker.clone());
let error = service
.remove_user_from_team(
@@ -4017,6 +4901,7 @@ async fn remove_user_from_team_enterprise_rolls_back_membership_when_channel_rem
.unwrap_err();
assert!(matches!(error, RemoveUserFromTeamError::TeamError(_)));
+ assert!(event_broker.events().is_empty());
assert_eq!(*team_repository.remove_user_calls.lock().unwrap(), 1);
assert_eq!(*team_repository.rollback_remove_calls.lock().unwrap(), 1);
assert_no_enterprise_remove_user_billing_calls(&team_repository, &customer_repository);
diff --git a/infra/stacks/authentication-service/service.ts b/infra/stacks/authentication-service/service.ts
index 486ad1d052..de75ee4ce8 100644
--- a/infra/stacks/authentication-service/service.ts
+++ b/infra/stacks/authentication-service/service.ts
@@ -14,6 +14,7 @@ import {
BASE_DOMAIN,
CLOUD_TRAIL_SNS_TOPIC_ARN,
DopplerEcsEnvironment,
+ getKafkaClusterPolicy,
stack,
} from '../../packages/shared';
@@ -151,7 +152,12 @@ export class AuthenticationService extends pulumi.ComponentResource {
name: `${BASE_NAME}-role-${stack}`,
assumeRolePolicy: ecsTaskAssumeRolePolicy,
tags: this.tags,
- managedPolicyArns: [secretsPolicy.arn, sesPolicy.arn, queuePolicy.arn],
+ managedPolicyArns: [
+ secretsPolicy.arn,
+ sesPolicy.arn,
+ queuePolicy.arn,
+ getKafkaClusterPolicy(),
+ ],
},
{ parent: this }
);
diff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.toml
index 9562a4660c..47c184a1dc 100644
--- a/services/authentication_service/Cargo.toml
+++ b/services/authentication_service/Cargo.toml
@@ -84,6 +84,7 @@ macro_db_client = { path = "../../crates/macro_db_client", default-features = fa
] }
macro_entrypoint = { path = "../../crates/macro_entrypoint" }
macro_env = { path = "../../crates/macro_env" }
+macro_event_broker = { path = "../../crates/macro_event_broker" }
macro_env_var = { path = "../../crates/macro_env_var" }
macro_queues = { path = "../../crates/macro_queues" }
macro_middleware = { path = "../../crates/macro_middleware", default-features = false, features = [
diff --git a/services/authentication_service/src/api/context.rs b/services/authentication_service/src/api/context.rs
index 39fd68c490..e8e9c6db90 100644
--- a/services/authentication_service/src/api/context.rs
+++ b/services/authentication_service/src/api/context.rs
@@ -19,6 +19,7 @@ use macro_authorization::{
use macro_cache_client::MacroCache;
use macro_env::Environment;
use macro_env_var::env_var;
+use macro_event_broker::{KafkaEventPublisher, MacroEventBrokerService};
use native_app_service::{domain::service::NativeAppServiceImpl, outbound::DefaultBundleFetcher};
use notification::outbound::queue::SqsQueue;
use notification::{
@@ -49,6 +50,7 @@ pub(crate) type TeamsServiceType = teams::domain::team_service::TeamServiceImpl<
teams::outbound::contacts_enqueuer::ContactsIngressEnqueuer<
SqsContactsIngress<SqsContactsQueue>,
>,
+ MacroEventBrokerService<KafkaEventPublisher>,
>;
pub(crate) type RateLimiter = RateLimitServiceImpl<RedisRateLimitAdapter<redis::Client>>;
diff --git a/services/authentication_service/src/config.rs b/services/authentication_service/src/config.rs
index c0260b9936..3eb8cbccab 100644
--- a/services/authentication_service/src/config.rs
+++ b/services/authentication_service/src/config.rs
@@ -30,6 +30,8 @@ env_vars! {
pub struct GithubClientSecret;
pub struct GithubIdpId;
pub struct StripePriceId;
+ /// Comma-separated Kafka bootstrap servers for the macro event broker.
+ pub struct KafkaBrokers;
}
maybe_env_vars! {
@@ -113,6 +115,8 @@ pub struct Config {
pub stripe_price_id: StripePriceId,
/// The internal api key
pub internal_api_key: InternalApiKey,
+ /// Comma-separated Kafka bootstrap servers for the macro event broker.
+ pub kafka_brokers: KafkaBrokers,
}
impl Config {
diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rs
index 0c8dd2acb7..1a8208fe68 100644
--- a/services/authentication_service/src/main.rs
+++ b/services/authentication_service/src/main.rs
@@ -22,6 +22,7 @@ use loops_client::LoopsClient;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_authorization::{InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationState};
use macro_entrypoint::MacroEntrypoint;
+use macro_event_broker::{KafkaEventPublisher, MacroEventBrokerService};
use macro_service_urls::AppServiceUrl;
use macro_service_urls::DocumentStorageServiceUrl;
use macro_service_urls::EmailServiceUrl;
@@ -297,6 +298,10 @@ async fn main() -> anyhow::Result<()> {
});
let contacts_enqueuer = ContactsIngressEnqueuer::new(contacts_ingress);
let team_analytics = AnalyticsClientTeamAnalytics::new(analytics_client.clone());
+ let macro_event_broker = MacroEventBrokerService::new(
+ KafkaEventPublisher::new(config.kafka_brokers.as_ref())
+ .context("failed to create kafka event publisher")?,
+ );
let teams_service_impl = TeamServiceImpl::new_with_analytics(
teams_repo_impl,
@@ -308,7 +313,8 @@ async fn main() -> anyhow::Result<()> {
team_crm_settings_repo_impl,
team_analytics,
)
- .with_contacts_enqueuer(contacts_enqueuer);
+ .with_contacts_enqueuer(contacts_enqueuer)
+ .with_event_broker(macro_event_broker);
let foreign_entity_service =
ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone()));