Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(teams): backfill contacts for team members on team join (#5003)
Will Hutchinsonb110c8b0ee0d
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 873cc37cad..1200823c68 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -5240,6 +5240,7 @@"crates/authentication_service_client","crates/bot_id","crates/channel_sender",+ "crates/contacts","crates/cowlike","crates/crm","crates/decode_jwt",@@ -5287,6 +5288,7 @@"crates/roles_and_permissions","crates/s3_key","crates/sqs_client",+ "crates/sqs_worker","crates/system_properties","crates/teams","crates/unfurl",diff --git a/Cargo.lock b/Cargo.lockindex cfea9335dd..89ef639d9d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -966,6 +966,7 @@ dependencies = ["base64 0.22.1","chrono","comms_db_client",+ "contacts","cookie","cool_asserts","database_env_vars",@@ -3109,6 +3110,7 @@ dependencies = ["tower 0.5.3","tracing","utoipa",+ "uuid","workspace-hack",]@@ -14070,6 +14072,7 @@ dependencies = ["async-trait","axum","chrono",+ "contacts","entity_access","macro_authorization","macro_db_migrator",diff --git a/crates/contacts/Cargo.toml b/crates/contacts/Cargo.tomlindex 231e360040..9e96b27c72 100644--- a/crates/contacts/Cargo.toml+++ b/crates/contacts/Cargo.toml@@ -35,6 +35,7 @@ sqs_worker = { path = "../sqs_worker", optional = true }tokio = { workspace = true }tracing = { workspace = true }utoipa = { workspace = true, optional = true }+uuid = { workspace = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]diff --git a/crates/contacts/src/domain/ports.rs b/crates/contacts/src/domain/ports.rsindex 8a4afcb91d..2a0f093e7d 100644--- a/crates/contacts/src/domain/ports.rs+++ b/crates/contacts/src/domain/ports.rs@@ -1,8 +1,8 @@use crate::domain::models::messages::{ContactConnection, ContactConnections, ContactsNodes};use macro_user_id::user_id::MacroUserIdStr;use rootcause::Report;-use sqlx::types::Uuid;use std::collections::HashSet;+use uuid::Uuid;/// Port trait for accessing the contacts data store.pub trait ContactsRepository: Send + Sync + 'static {diff --git a/crates/teams/Cargo.toml b/crates/teams/Cargo.tomlindex b23af31119..d9515988b8 100644--- a/crates/teams/Cargo.toml+++ b/crates/teams/Cargo.toml@@ -26,6 +26,7 @@ default = ["ai_tools", "axum", "inbound", "outbound", "ports"]inbound = ["axum", "ports"]outbound = ["dep:analytics_client",+ "dep:contacts","dep:sqlx","dep:sqs_client","dep:models_email",@@ -50,6 +51,7 @@ async-stripe = { workspace = true, default-features = false, features = [] }async-trait = { workspace = true, optional = true }chrono = { workspace = true }+contacts = { path = "../contacts", default-features = false, optional = true }macro_authorization = { path = "../macro_authorization", optional = true, default-features = false, features = ["axum",] }diff --git a/crates/teams/src/domain.rs b/crates/teams/src/domain.rsindex 7e80140bc3..71412264a1 100644--- a/crates/teams/src/domain.rs+++ b/crates/teams/src/domain.rs@@ -1,3 +1,4 @@+pub mod contacts_enqueuer;pub mod crm_enqueuer;pub mod customer_repo;pub mod model;diff --git a/crates/teams/src/domain/contacts_enqueuer.rs b/crates/teams/src/domain/contacts_enqueuer.rsnew file mode 100644index 0000000000..ba513aa1af--- /dev/null+++ b/crates/teams/src/domain/contacts_enqueuer.rs@@ -0,0 +1,35 @@+//! Outbound port for enqueueing contact connections created through team membership.+//!+//! The teams service uses this port to publish explicit connections between a+//! joining user and their teammates without depending on a particular queue or+//! contacts service implementation.++use macro_user_id::user_id::MacroUserIdStr;+use std::convert::Infallible;++/// Enqueues contact connections created when a user joins a team.+pub trait ContactsEnqueuer: Clone + Send + Sync + 'static {+ /// Error type returned by enqueue operations.+ type Err: std::fmt::Display + std::fmt::Debug + Send;++ /// Enqueues owned pairs of users that should be connected.+ fn enqueue_contact_connections(+ &self,+ connections: Vec<(MacroUserIdStr<'static>, MacroUserIdStr<'static>)>,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;+}++/// No-op contact enqueuer for callers that do not need contact synchronization.+#[derive(Clone, Debug)]+pub struct NoOpContactsEnqueuer;++impl ContactsEnqueuer for NoOpContactsEnqueuer {+ type Err = Infallible;++ async fn enqueue_contact_connections(+ &self,+ _connections: Vec<(MacroUserIdStr<'static>, MacroUserIdStr<'static>)>,+ ) -> Result<(), Self::Err> {+ Ok(())+ }+}diff --git a/crates/teams/src/domain/team_service.rs b/crates/teams/src/domain/team_service.rsindex 4ed4ef584d..a3c7a2e4a7 100644--- a/crates/teams/src/domain/team_service.rs+++ b/crates/teams/src/domain/team_service.rs@@ -22,6 +22,7 @@ use model_notifications::InviteToTeamMetadata;use notification::domain::{models::SendNotificationRequestBuilder, service::NotificationIngress};use crate::domain::{+ contacts_enqueuer::{ContactsEnqueuer, NoOpContactsEnqueuer},crm_enqueuer::CrmEnqueuer,customer_repo::CustomerRepository,model::{@@ -39,8 +40,17 @@ use crate::domain::{/// Implementation of the TeamService using a TeamRepository#[derive(Debug)]-pub struct TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA = NoOpTeamAnalytics>-where+pub struct TeamServiceImpl<+ TR,+ CR,+ TCR,+ URPS,+ NI,+ CE,+ TCRMS,+ TA = NoOpTeamAnalytics,+ CNE = NoOpContactsEnqueuer,+> whereTR: TeamRepository,CR: CustomerRepository,TCR: TeamChannelsRepository,@@ -49,6 +59,7 @@ whereCE: CrmEnqueuer,TCRMS: TeamCrmSettingsRepository,TA: TeamAnalytics,+ CNE: ContactsEnqueuer,{/// The underlying team repositoryteam_repository: TR,@@ -69,10 +80,12 @@ whereteam_crm_settings_repository: TCRMS,/// Outbound port for best-effort team lifecycle analytics events.team_analytics: TA,+ /// Outbound port for contact connections created through team membership.+ contacts_enqueuer: CNE,}-impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA> Clone- for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA>+impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE> Clone+ for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE>whereTR: TeamRepository,CR: CustomerRepository,@@ -82,6 +95,7 @@ whereCE: CrmEnqueuer,TCRMS: TeamCrmSettingsRepository,TA: TeamAnalytics,+ CNE: ContactsEnqueuer,{fn clone(&self) -> Self {Self {@@ -93,12 +107,13 @@ wherecrm_enqueuer: self.crm_enqueuer.clone(),team_crm_settings_repository: self.team_crm_settings_repository.clone(),team_analytics: self.team_analytics.clone(),+ contacts_enqueuer: self.contacts_enqueuer.clone(),}}}impl<TR, CR, TCR, URPS, NI, CE, TCRMS>- TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, NoOpTeamAnalytics>+ TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, NoOpTeamAnalytics, NoOpContactsEnqueuer>whereTR: TeamRepository,CR: CustomerRepository,@@ -131,7 +146,8 @@ where}}-impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA> TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA>+impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA>+ TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, NoOpContactsEnqueuer>whereTR: TeamRepository,CR: CustomerRepository,@@ -166,6 +182,42 @@ wherecrm_enqueuer,team_crm_settings_repository,team_analytics,+ contacts_enqueuer: NoOpContactsEnqueuer,+ }+ }+}++impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE>+ TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE>+where+ TR: TeamRepository,+ CR: CustomerRepository,+ TCR: TeamChannelsRepository,+ URPS: UserRolesAndPermissionsService,+ NI: NotificationIngress,+ CE: CrmEnqueuer,+ TCRMS: TeamCrmSettingsRepository,+ TA: TeamAnalytics,+ CNE: ContactsEnqueuer,+{+ /// 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>+ where+ CNE2: ContactsEnqueuer,+ {+ 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,}}@@ -182,6 +234,61 @@ where.ok();}+ async fn enqueue_joining_user_contacts(+ &self,+ team_id: &uuid::Uuid,+ user_id: &MacroUserIdStr<'_>,+ ) {+ let Some(team_with_members) = self+ .team_repository+ .get_team_by_id(team_id)+ .await+ .inspect_err(|error| {+ tracing::error!(+ error = ?error,+ team_id = %team_id,+ user_id = %user_id,+ "failed to load team roster for contact connections"+ );+ })+ .ok()+ else {+ return;+ };++ let joining_user = user_id.clone().into_owned();+ let teammates: HashSet<_> = std::iter::once(team_with_members.team.owner_id)+ .chain(+ team_with_members+ .members+ .into_iter()+ .map(|member| member.user_id),+ )+ .filter(|teammate| teammate != &joining_user)+ .collect();+ let connections = teammates+ .into_iter()+ .map(|teammate| (joining_user.clone(), teammate))+ .collect::<Vec<_>>();++ if connections.is_empty() {+ return;+ }++ self.contacts_enqueuer+ .enqueue_contact_connections(connections)+ .await+ .inspect_err(|error| {+ tracing::error!(+ error = ?error,+ team_id = %team_id,+ user_id = %user_id,+ "failed to enqueue team contact connections"+ );+ })+ .ok();+ }+/// Gets the teams subscription id/// If the team doesn't have a subscription yet, it will convert the owners personal subscription into a team subscription#[tracing::instrument(skip(self), err)]@@ -372,8 +479,8 @@ impl GetTeamSubscriptionError {}}-impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA> TeamMembersService- for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA>+impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE> TeamMembersService+ for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE>whereTR: TeamRepository,CR: CustomerRepository,@@ -383,6 +490,7 @@ whereCE: CrmEnqueuer,TCRMS: TeamCrmSettingsRepository,TA: TeamAnalytics,+ CNE: ContactsEnqueuer,{#[tracing::instrument(skip(self), err)]async fn list_team_members(@@ -399,8 +507,8 @@ where}}-impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA> TeamService- for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA>+impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE> TeamService+ for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE>whereTR: TeamRepository,CR: CustomerRepository,@@ -410,6 +518,7 @@ whereCE: CrmEnqueuer,TCRMS: TeamCrmSettingsRepository,TA: TeamAnalytics,+ CNE: ContactsEnqueuer,{#[tracing::instrument(skip(self), err)]async fn create_team(@@ -1093,6 +1202,9 @@ where);}+ self.enqueue_joining_user_contacts(&team_member.team_id, user_id)+ .await;+self.track_team_analytics_event(TeamAnalyticsEvent::TeamJoined {team_id: team_member.team_id,team_invite_id: accepted_invite.invite.id,@@ -1542,6 +1654,8 @@ where);}+ self.enqueue_joining_user_contacts(&team_id, user_id).await;+// NOTE: no TeamJoined analytics event here — that event is tied to// the team invite that was accepted, and a domain auto-join has none.diff --git a/crates/teams/src/domain/team_service/test.rs b/crates/teams/src/domain/team_service/test.rsindex b23a192866..fb03948256 100644--- a/crates/teams/src/domain/team_service/test.rs+++ b/crates/teams/src/domain/team_service/test.rs@@ -21,6 +21,7 @@ use roles_and_permissions::domain::{};use crate::domain::{+ contacts_enqueuer::ContactsEnqueuer,crm_enqueuer::{CrmEnqueuer, NoOpCrmEnqueuer},team_analytics::{TeamAnalytics, TeamAnalyticsEvent},team_crm_settings_repo::NoOpTeamCrmSettingsRepository,@@ -457,12 +458,10 @@ impl TeamRepository for MockTeamRepository {) -> impl Future<Output = Result<TeamWithMembers, TeamError>> + Send {*self.get_team_by_id_calls.lock().unwrap() += 1;let team = self.team_for_get_by_id.clone();+ let members = self.team_members.clone();async move {let team = team.ok_or(TeamError::TeamDoesNotExist)?;- Ok(TeamWithMembers {- team,- members: Vec::new(),- })+ Ok(TeamWithMembers { team, members })}}@@ -916,6 +915,40 @@ impl TeamAnalytics for MockTeamAnalytics {}}+type ContactPair = (MacroUserIdStr<'static>, MacroUserIdStr<'static>);+type ContactBatches = Arc<Mutex<Vec<Vec<ContactPair>>>>;++#[derive(Clone, Default)]+struct RecordingContactsEnqueuer {+ batches: ContactBatches,+ fail: bool,+}++impl RecordingContactsEnqueuer {+ fn failing() -> Self {+ Self {+ fail: true,+ ..Default::default()+ }+ }+}++impl ContactsEnqueuer for RecordingContactsEnqueuer {+ type Err = &'static str;++ async fn enqueue_contact_connections(+ &self,+ connections: Vec<ContactPair>,+ ) -> Result<(), Self::Err> {+ self.batches.lock().unwrap().push(connections);+ if self.fail {+ Err("contacts enqueue failed")+ } else {+ Ok(())+ }+ }+}+// -- Helpers --fn make_invite(email: &str, invite_id: uuid::Uuid, team_id: uuid::Uuid) -> TeamInvite<'static> {@@ -939,6 +972,18 @@ fn make_team_member(team_id: uuid::Uuid, user_id: &str, role: TeamRole) -> TeamM}}+fn contact_connection_set(connections: &[ContactPair]) -> HashSet<(String, String)> {+ connections+ .iter()+ .map(|(user_id, teammate_id)| {+ (+ user_id.as_ref().to_string(),+ teammate_id.as_ref().to_string(),+ )+ })+ .collect()+}+fn make_accepted_invite(team_id: uuid::Uuid,invite_id: uuid::Uuid,@@ -3878,6 +3923,336 @@ async fn remove_user_from_team_enterprise_status_read_precedes_membership_removaassert!(events.lock().unwrap().is_empty());}+#[tokio::test]+async fn team_contacts_invite_join_enqueues_distinct_owner_and_member_edges() {+ let team_id = uuid::Uuid::from_u128(6001);+ let invite_id = uuid::Uuid::from_u128(6002);+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let first_teammate = "macro|[email protected]";+ let second_teammate = "macro|[email protected]";+ let team = Team::new(+ team_id,+ "Contacts Team".to_string(),+ "contacts-team".to_string(),+ owner_id.clone().into_owned(),+ false,+ true,+ );+ let team_repository = make_enterprise_join_team_repository(team_id, invite_id, &user_id)+ .with_team(team)+ .with_team_members(vec![+ make_team_member(team_id, owner_id.as_ref(), TeamRole::Owner),+ make_team_member(team_id, first_teammate, TeamRole::Member),+ make_team_member(team_id, first_teammate, TeamRole::Admin),+ make_team_member(team_id, second_teammate, TeamRole::Member),+ make_team_member(team_id, user_id.as_ref(), TeamRole::Member),+ make_team_member(team_id, user_id.as_ref(), TeamRole::Admin),+ ]);+ let contacts_enqueuer = RecordingContactsEnqueuer::default();+ let service = TeamServiceImpl::new(+ team_repository,+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ )+ .with_contacts_enqueuer(contacts_enqueuer.clone());++ service.join_team(&invite_id, &user_id).await.unwrap();++ let batches = contacts_enqueuer.batches.lock().unwrap();+ assert_eq!(batches.len(), 1);+ assert_eq!(batches[0].len(), 3);+ assert_eq!(+ contact_connection_set(&batches[0]),+ HashSet::from([+ (user_id.as_ref().to_string(), owner_id.as_ref().to_string()),+ (user_id.as_ref().to_string(), first_teammate.to_string()),+ (user_id.as_ref().to_string(), second_teammate.to_string()),+ ])+ );+}++#[tokio::test]+async fn team_contacts_invite_join_swallows_enqueue_failure_without_rollback() {+ let team_id = uuid::Uuid::from_u128(6003);+ let invite_id = uuid::Uuid::from_u128(6004);+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let team = Team::new(+ team_id,+ "Contacts Team".to_string(),+ "contacts-team".to_string(),+ owner_id.into_owned(),+ false,+ true,+ );+ let team_repository =+ make_enterprise_join_team_repository(team_id, invite_id, &user_id).with_team(team);+ let contacts_enqueuer = RecordingContactsEnqueuer::failing();+ let service = TeamServiceImpl::new(+ team_repository.clone(),+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ )+ .with_contacts_enqueuer(contacts_enqueuer.clone());++ let member = service.join_team(&invite_id, &user_id).await.unwrap();++ assert_eq!(member.user_id, user_id);+ assert_eq!(*team_repository.rollback_accept_calls.lock().unwrap(), 0);+ assert_eq!(contacts_enqueuer.batches.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn team_contacts_invite_join_swallows_roster_failure() {+ let team_id = uuid::Uuid::from_u128(6005);+ let invite_id = uuid::Uuid::from_u128(6006);+ 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 contacts_enqueuer = RecordingContactsEnqueuer::default();+ let service = TeamServiceImpl::new(+ team_repository.clone(),+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ )+ .with_contacts_enqueuer(contacts_enqueuer.clone());++ let member = service.join_team(&invite_id, &user_id).await.unwrap();++ assert_eq!(member.user_id, user_id);+ assert_eq!(*team_repository.get_team_by_id_calls.lock().unwrap(), 1);+ assert_eq!(*team_repository.rollback_accept_calls.lock().unwrap(), 0);+ assert!(contacts_enqueuer.batches.lock().unwrap().is_empty());+}++#[tokio::test]+async fn team_contacts_invite_join_skips_empty_connection_batch() {+ let team_id = uuid::Uuid::from_u128(6007);+ let invite_id = uuid::Uuid::from_u128(6008);+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let team = Team::new(+ team_id,+ "Contacts Team".to_string(),+ "contacts-team".to_string(),+ user_id.clone().into_owned(),+ false,+ true,+ );+ let team_repository =+ make_enterprise_join_team_repository(team_id, invite_id, &user_id).with_team(team);+ let contacts_enqueuer = RecordingContactsEnqueuer::default();+ let service = TeamServiceImpl::new(+ team_repository,+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ )+ .with_contacts_enqueuer(contacts_enqueuer.clone());++ service.join_team(&invite_id, &user_id).await.unwrap();++ assert!(contacts_enqueuer.batches.lock().unwrap().is_empty());+}++#[tokio::test]+async fn team_contacts_invite_join_does_not_enqueue_when_channel_work_rolls_back() {+ let team_id = uuid::Uuid::from_u128(6009);+ let invite_id = uuid::Uuid::from_u128(6010);+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let team = Team::new(+ team_id,+ "Contacts Team".to_string(),+ "contacts-team".to_string(),+ owner_id.into_owned(),+ false,+ true,+ );+ let team_repository =+ make_enterprise_join_team_repository(team_id, invite_id, &user_id).with_team(team);+ let contacts_enqueuer = RecordingContactsEnqueuer::default();+ let service = TeamServiceImpl::new(+ team_repository.clone(),+ MockCustomerRepository::default(),+ MockTeamChannelsRepository {+ fail_add: true,+ ..Default::default()+ },+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ )+ .with_contacts_enqueuer(contacts_enqueuer.clone());++ let error = service.join_team(&invite_id, &user_id).await.unwrap_err();++ assert!(matches!(error, JoinTeamError::TeamError(_)));+ assert_eq!(*team_repository.rollback_accept_calls.lock().unwrap(), 1);+ assert_eq!(*team_repository.get_team_by_id_calls.lock().unwrap(), 0);+ assert!(contacts_enqueuer.batches.lock().unwrap().is_empty());+}++#[tokio::test]+async fn team_contacts_domain_join_enqueues_distinct_owner_and_member_edges() {+ let team_id = uuid::Uuid::from_u128(6011);+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let teammate_id = "macro|[email protected]";+ let team = Team::new(+ team_id,+ "Contacts Team".to_string(),+ "contacts-team".to_string(),+ owner_id.clone().into_owned(),+ false,+ true,+ );+ let team_repository = make_enterprise_domain_join_team_repository(team_id, &user_id)+ .with_team(team)+ .with_team_members(vec![+ make_team_member(team_id, teammate_id, TeamRole::Member),+ make_team_member(team_id, teammate_id, TeamRole::Admin),+ make_team_member(team_id, user_id.as_ref(), TeamRole::Member),+ ]);+ let contacts_enqueuer = RecordingContactsEnqueuer::default();+ let service = TeamServiceImpl::new(+ team_repository,+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ )+ .with_contacts_enqueuer(contacts_enqueuer.clone());++ service+ .try_join_team_by_domain(&user_id)+ .await+ .unwrap()+ .expect("user should join the team");++ let batches = contacts_enqueuer.batches.lock().unwrap();+ assert_eq!(batches.len(), 1);+ assert_eq!(batches[0].len(), 2);+ assert_eq!(+ contact_connection_set(&batches[0]),+ HashSet::from([+ (user_id.as_ref().to_string(), owner_id.as_ref().to_string()),+ (user_id.as_ref().to_string(), teammate_id.to_string()),+ ])+ );+}++#[tokio::test]+async fn team_contacts_domain_join_does_not_enqueue_without_matching_team() {+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let team_repository = MockTeamRepository::new(+ Vec::new(),+ "Contacts Team",+ Arc::new(Mutex::new(Vec::new())),+ );+ let contacts_enqueuer = RecordingContactsEnqueuer::default();+ let service = TeamServiceImpl::new(+ team_repository.clone(),+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ )+ .with_contacts_enqueuer(contacts_enqueuer.clone());++ let member = service.try_join_team_by_domain(&user_id).await.unwrap();++ assert!(member.is_none());+ assert_eq!(*team_repository.get_team_by_id_calls.lock().unwrap(), 0);+ assert!(contacts_enqueuer.batches.lock().unwrap().is_empty());+}++#[tokio::test]+async fn team_contacts_domain_join_does_not_enqueue_for_existing_member() {+ let team_id = uuid::Uuid::from_u128(6012);+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let mut team_repository = MockTeamRepository::new(+ Vec::new(),+ "Contacts Team",+ Arc::new(Mutex::new(Vec::new())),+ );+ team_repository.team_id_for_domain = Some(team_id);+ team_repository.add_user_to_team_result = None;+ let contacts_enqueuer = RecordingContactsEnqueuer::default();+ let service = TeamServiceImpl::new(+ team_repository.clone(),+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ )+ .with_contacts_enqueuer(contacts_enqueuer.clone());++ let member = service.try_join_team_by_domain(&user_id).await.unwrap();++ assert!(member.is_none());+ assert_eq!(*team_repository.get_team_by_id_calls.lock().unwrap(), 0);+ assert!(contacts_enqueuer.batches.lock().unwrap().is_empty());+}++#[tokio::test]+async fn team_contacts_domain_join_does_not_enqueue_at_seat_cap() {+ let team_id = uuid::Uuid::from_u128(6013);+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let mut team_repository = MockTeamRepository::new(+ Vec::new(),+ "Contacts Team",+ Arc::new(Mutex::new(Vec::new())),+ );+ team_repository.team_id_for_domain = Some(team_id);+ team_repository.team_plan = Some(TeamPlan::Idea);+ team_repository.seat_count = TeamPlan::Idea.seat_cap();+ team_repository.add_user_to_team_result = Some(make_team_member(+ team_id,+ user_id.as_ref(),+ TeamRole::Member,+ ));+ let contacts_enqueuer = RecordingContactsEnqueuer::default();+ let service = TeamServiceImpl::new(+ team_repository.clone(),+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ )+ .with_contacts_enqueuer(contacts_enqueuer.clone());++ let member = service.try_join_team_by_domain(&user_id).await.unwrap();++ assert!(member.is_none());+ assert_eq!(*team_repository.add_user_to_team_calls.lock().unwrap(), 0);+ assert_eq!(*team_repository.get_team_by_id_calls.lock().unwrap(), 0);+ assert!(contacts_enqueuer.batches.lock().unwrap().is_empty());+}+#[tokio::test]async fn try_join_team_by_domain_enterprise_status_read_precedes_membership_mutation() {let team_id = uuid::Uuid::from_u128(85);diff --git a/crates/teams/src/outbound.rs b/crates/teams/src/outbound.rsindex 111fddf5a9..9ad53cd5cd 100644--- a/crates/teams/src/outbound.rs+++ b/crates/teams/src/outbound.rs@@ -1,3 +1,4 @@+pub mod contacts_enqueuer;pub mod crm_enqueuer;pub mod customer_repo;pub mod team_analytics;diff --git a/crates/teams/src/outbound/contacts_enqueuer.rs b/crates/teams/src/outbound/contacts_enqueuer.rsnew file mode 100644index 0000000000..83a0111f97--- /dev/null+++ b/crates/teams/src/outbound/contacts_enqueuer.rs@@ -0,0 +1,54 @@+//! [`ContactsEnqueuer`] adapter backed by the contacts ingress.++#[cfg(test)]+mod test;++use std::sync::Arc;++use contacts::domain::{models::messages::ContactConnection, ports::ContactsIngress};+use macro_user_id::user_id::MacroUserIdStr;++use crate::domain::contacts_enqueuer::ContactsEnqueuer;++/// Contacts enqueuer that delegates to a shared contacts ingress.+pub struct ContactsIngressEnqueuer<I> {+ ingress: Arc<I>,+}++impl<I> Clone for ContactsIngressEnqueuer<I> {+ fn clone(&self) -> Self {+ Self {+ ingress: self.ingress.clone(),+ }+ }+}++impl<I> ContactsIngressEnqueuer<I> {+ /// Creates a contacts enqueuer over the given shared ingress.+ pub fn new(ingress: Arc<I>) -> Self {+ Self { ingress }+ }+}++impl<I> ContactsEnqueuer for ContactsIngressEnqueuer<I>+where+ I: ContactsIngress,+{+ type Err = anyhow::Error;++ #[tracing::instrument(skip(self, connections), err)]+ async fn enqueue_contact_connections(+ &self,+ connections: Vec<(MacroUserIdStr<'static>, MacroUserIdStr<'static>)>,+ ) -> Result<(), Self::Err> {+ let connections = connections+ .into_iter()+ .map(|(first, second)| ContactConnection::new(first, second))+ .collect();++ self.ingress+ .enqueue_contact_connections(connections)+ .await+ .map_err(|e| anyhow::anyhow!("{e:?}"))+ }+}diff --git a/crates/teams/src/outbound/contacts_enqueuer/test.rs b/crates/teams/src/outbound/contacts_enqueuer/test.rsnew file mode 100644index 0000000000..905f560915--- /dev/null+++ b/crates/teams/src/outbound/contacts_enqueuer/test.rs@@ -0,0 +1,68 @@+use std::{+ collections::HashSet,+ sync::{Arc, Mutex},+};++use contacts::domain::{models::messages::ContactConnection, ports::ContactsIngress};+use macro_user_id::user_id::MacroUserIdStr;+use rootcause::Report;++use super::*;++#[derive(Default)]+struct FakeContactsIngress {+ connection_batches: Mutex<Vec<Vec<ContactConnection>>>,+}++impl ContactsIngress for FakeContactsIngress {+ async fn enqueue_contacts(+ &self,+ _users: HashSet<MacroUserIdStr<'static>>,+ ) -> Result<(), Report> {+ panic!("unexpected complete-graph contacts enqueue")+ }++ async fn enqueue_contact_connections(+ &self,+ connections: Vec<ContactConnection>,+ ) -> Result<(), Report> {+ self.connection_batches+ .lock()+ .expect("connection batches lock should not be poisoned")+ .push(connections);+ Ok(())+ }+}++fn macro_user_id(value: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(value.to_string()).expect("valid macro user id")+}++#[tokio::test]+async fn contacts_ingress_enqueuer_maps_pairs() {+ let ingress = Arc::new(FakeContactsIngress::default());+ let enqueuer = ContactsIngressEnqueuer::new(ingress.clone()).clone();+ let first = macro_user_id("macro|[email protected]");+ let second = macro_user_id("macro|[email protected]");+ let third = macro_user_id("macro|[email protected]");++ enqueuer+ .enqueue_contact_connections(vec![+ (first.clone(), second.clone()),+ (third.clone(), first.clone()),+ ])+ .await+ .expect("contacts enqueue should succeed");++ let batches = ingress+ .connection_batches+ .lock()+ .expect("connection batches lock should not be poisoned");+ assert_eq!(+ *batches,+ vec![vec![+ ContactConnection::new(first.clone(), second),+ ContactConnection::new(third, first),+ ]]+ );+}diff --git a/infra/stacks/authentication-service/index.ts b/infra/stacks/authentication-service/index.tsindex efa37d10d1..6292f8d7eb 100644--- a/infra/stacks/authentication-service/index.ts+++ b/infra/stacks/authentication-service/index.ts@@ -101,6 +101,17 @@ const fusionAuthStack = new pulumi.StackReference('fusion-auth-stack', {name: `macro-inc/fusion-auth/${stack}`,});+const contactsServiceStack = new pulumi.StackReference(+ 'contacts-service-stack',+ {+ name: `macro-inc/contacts-service/${stack}`,+ }+);++const contactsQueueArn: pulumi.Output<string> = contactsServiceStack+ .getOutput('contactsQueueArn')+ .apply((arn) => arn as string);+const fusionAuthClusterArn: pulumi.Output<string> = fusionAuthStack.getOutput('fusionAuthClusterArn').apply((fusionAuthClusterArn) => fusionAuthClusterArn as string);@@ -135,6 +146,7 @@ const service = new AuthenticationService('authentication-service', {searchEventQueueArn,linkManagerQueueArn,backfillQueueArn,+ contactsQueueArn,],containerEnvVars: [{ name: 'ENVIRONMENT', value: stack },diff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.tomlindex 4dc61cc7ca..9562a4660c 100644--- a/services/authentication_service/Cargo.toml+++ b/services/authentication_service/Cargo.toml@@ -42,6 +42,9 @@ axum = { workspace = true, features = ["macros"] }base64 = { workspace = true }chrono = { workspace = true }comms_db_client = { path = "../../crates/comms_db_client" }+contacts = { path = "../../crates/contacts", default-features = false, features = [+ "outbound",+] }cookie = { workspace = true }decode_jwt = { path = "../../crates/decode_jwt" }document_storage_service_client = { path = "../../crates/document_storage_service_client" }diff --git a/services/authentication_service/src/api/context.rs b/services/authentication_service/src/api/context.rsindex b88d47dd64..39fd68c490 100644--- a/services/authentication_service/src/api/context.rs+++ b/services/authentication_service/src/api/context.rs@@ -2,6 +2,7 @@ use std::sync::Arc;use analytics_client::AnalyticsClient;use axum::extract::FromRef;+use contacts::{domain::service::SqsContactsIngress, outbound::ingress::SqsContactsQueue};use entity_access::domain::service::EntityAccessServiceImpl;use entity_access::outbound::PgAccessRepository;use foreign_entity::domain::service::ForeignEntityServiceImpl;@@ -45,6 +46,9 @@ pub(crate) type TeamsServiceType = teams::domain::team_service::TeamServiceImpl<teams::outbound::crm_enqueuer::SqsCrmEnqueuer,teams::outbound::team_crm_settings_repo::TeamCrmSettingsRepositoryImpl,teams::outbound::team_analytics::AnalyticsClientTeamAnalytics,+ teams::outbound::contacts_enqueuer::ContactsIngressEnqueuer<+ SqsContactsIngress<SqsContactsQueue>,+ >,>;pub(crate) type RateLimiter = RateLimitServiceImpl<RedisRateLimitAdapter<redis::Client>>;diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rsindex 145aada54e..0c8dd2acb7 100644--- a/services/authentication_service/src/main.rs+++ b/services/authentication_service/src/main.rs@@ -4,6 +4,7 @@ use analytics_client::{};use anyhow::{Context, anyhow};use config::{Config, Environment};+use contacts::{domain::service::SqsContactsIngress, outbound::ingress::SqsContactsQueue};use document_storage_service_client::DocumentStorageServiceClient;use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};use foreign_entity::{@@ -41,7 +42,8 @@ use sqlx::postgres::PgPoolOptions;use teams::{domain::team_service::TeamServiceImpl,outbound::{- customer_repo::CustomerRepositoryImpl, team_analytics::AnalyticsClientTeamAnalytics,+ contacts_enqueuer::ContactsIngressEnqueuer, customer_repo::CustomerRepositoryImpl,+ team_analytics::AnalyticsClientTeamAnalytics,team_channels_repo::TeamChannelsRepositoryImpl, team_repo::TeamRepositoryImpl,},};@@ -287,6 +289,13 @@ async fn main() -> anyhow::Result<()> {let notification_ingress_service = Arc::new(notification_ingress_service);let crm_enqueuer = teams::outbound::crm_enqueuer::SqsCrmEnqueuer::new(sqs_client.clone());+ let contacts_ingress = Arc::new(SqsContactsIngress {+ queue: SqsContactsQueue::new(+ aws_sdk_sqs::Client::new(&aws_config),+ macro_queues::ContactsQueue::new().to_string(),+ ),+ });+ let contacts_enqueuer = ContactsIngressEnqueuer::new(contacts_ingress);let team_analytics = AnalyticsClientTeamAnalytics::new(analytics_client.clone());let teams_service_impl = TeamServiceImpl::new_with_analytics(@@ -298,7 +307,8 @@ async fn main() -> anyhow::Result<()> {crm_enqueuer,team_crm_settings_repo_impl,team_analytics,- );+ )+ .with_contacts_enqueuer(contacts_enqueuer);let foreign_entity_service =ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone()));