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(call): add push notifications (#2502)
Sean Aye87bbce2a1940
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex ef8cf79e63..35563aae4d 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -107,6 +107,7 @@ dependencies = ["item_filters","lazy_static","macro_db_client",+ "macro_user_id","model","model_notifications","models_dcs",@@ -758,9 +759,9 @@ dependencies = [[[package]]name = "aws-lc-rs"-version = "1.16.1"+version = "1.16.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "94bffc006df10ac2a68c83692d734a465f8ee6c5b384d8545a636f81d858f4bf"+checksum = "a054912289d18629dc78375ba2c3726a3afe3ff71b4edba9dedfca0e3446d1fc"dependencies = ["aws-lc-sys","zeroize",@@ -768,9 +769,9 @@ dependencies = [[[package]]name = "aws-lc-sys"-version = "0.38.0"+version = "0.39.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4321e568ed89bb5a7d291a7f37997c2c0df89809d7b6d12062c81ddb54aa782e"+checksum = "83a25cf98105baa966497416dbd42565ce3a8cf8dbfd59803ec9ad46f3126399"dependencies = ["cc","cmake",@@ -1749,9 +1750,11 @@ dependencies = ["macro_db_migrator","macro_user_id","mockall",+ "model-entity","model-error-response","model_user","models_permissions",+ "notification","serde","serde_json","sqlx",diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.tomlindex ad3721b399..1416075e77 100644--- a/rust/cloud-storage/ai_tools/Cargo.toml+++ b/rust/cloud-storage/ai_tools/Cargo.toml@@ -26,6 +26,7 @@ frecency = { path = "../frecency", features = ["outbound", "postgres"] }item_filters = { path = "../item_filters" }lazy_static.workspace = truemacro_db_client = { path = "../macro_db_client" }+macro_user_id = { path = "../macro_user_id" }model = { path = "../model" }model_notifications = { path = "../model_notifications" }models_dcs = { path = "../models_dcs" }diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rsindex 6bc01dbd8d..058e374b66 100644--- a/rust/cloud-storage/ai_tools/src/tool_context.rs+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs@@ -16,6 +16,7 @@ use email::{};use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};+use macro_user_id::user_id::MacroUserIdStr;use properties::inbound::toolset::PropertiesToolContext;use scribe::{ScribeClient, channel::ChannelClient, dcs::DcsClient, document::DocumentClient,@@ -79,12 +80,11 @@ impl ConnectionService for NoOpConnectionService {Ok(())}- async fn send_channel_message(+ async fn send_channel_message<'a>(&self,- _channel_id: &str,+ _users: &[MacroUserIdStr<'a>],_message_type: &str,_message: serde_json::Value,- _triggered_by: connection::domain::models::EntityAccessAuth,) -> Result<(), connection::domain::models::ConnectionError> {Ok(())}diff --git a/rust/cloud-storage/call/.sqlx/query-d2faac5b9aa6421d1f5c1d2f07a73ee093cd91bca7aa1c9fc76049354963a158.json b/rust/cloud-storage/call/.sqlx/query-d2faac5b9aa6421d1f5c1d2f07a73ee093cd91bca7aa1c9fc76049354963a158.jsonnew file mode 100644index 0000000000..e16ec89bc6--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-d2faac5b9aa6421d1f5c1d2f07a73ee093cd91bca7aa1c9fc76049354963a158.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT mui.profile_picture\n FROM macro_user_info mui\n JOIN \"User\" u ON mui.macro_user_id = u.macro_user_id\n WHERE u.macro_user_id::text = $1 AND mui.profile_picture IS NOT NULL\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "profile_picture",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "d2faac5b9aa6421d1f5c1d2f07a73ee093cd91bca7aa1c9fc76049354963a158"+}diff --git a/rust/cloud-storage/call/Cargo.toml b/rust/cloud-storage/call/Cargo.tomlindex 9bd48ec5bd..4f156ff186 100644--- a/rust/cloud-storage/call/Cargo.toml+++ b/rust/cloud-storage/call/Cargo.toml@@ -8,38 +8,39 @@ version = "0.1.0"default = ["inbound", "outbound", "ports"]inbound = ["dep:axum",- "dep:entity_access","dep:model-error-response","dep:model_user","dep:utoipa",+ "entity_access/inbound","ports",]outbound = [- "dep:entity_access","dep:livekit-api","dep:livekit-protocol","dep:models_permissions","dep:sqlx","ports",]-ports = ["dep:tokio"]+ports = ["dep:entity_access", "dep:tokio"][dependencies]anyhow = { workspace = true }+axum = { workspace = true, optional = true }+chrono = { workspace = true }connection = { path = "../connection", default-features = false, features = ["ports",] }-axum = { workspace = true, optional = true }-chrono = { workspace = true }entity_access = { path = "../entity_access", optional = true, default-features = false, features = [- "inbound",+ "ports",] }livekit-api = { workspace = true, optional = true }livekit-protocol = { workspace = true, optional = true }macro_user_id = { path = "../macro_user_id" }+model-entity = { path = "../model-entity" }model-error-response = { path = "../model-error-response", optional = true }model_user = { path = "../model_user", optional = true, features = ["axum"] }models_permissions = { path = "../models_permissions", optional = true }+notification = { path = "../notification" }serde = { workspace = true }serde_json = { workspace = true }sqlx = { workspace = true, optional = true }diff --git a/rust/cloud-storage/call/src/domain/models.rs b/rust/cloud-storage/call/src/domain/models.rsindex 23f06a5469..69e5d55230 100644--- a/rust/cloud-storage/call/src/domain/models.rs+++ b/rust/cloud-storage/call/src/domain/models.rs@@ -3,6 +3,7 @@use std::fmt;use chrono::{DateTime, Utc};+use macro_user_id::user_id::MacroUserIdStr;use uuid::Uuid;/// Represents an active call in a channel.@@ -108,7 +109,7 @@ pub struct CallWebhookEvent {/// Room name associated with the event, if any.pub room_name: Option<String>,/// Participant identity associated with the event, if any.- pub participant_identity: Option<String>,+ pub participant_identity: Option<MacroUserIdStr<'static>>,/// Egress ID associated with the event, if any.pub egress_id: Option<String>,/// File download URL from a completed egress, if any.diff --git a/rust/cloud-storage/call/src/domain/ports.rs b/rust/cloud-storage/call/src/domain/ports.rsindex a54e3e4463..7f3de59a00 100644--- a/rust/cloud-storage/call/src/domain/ports.rs+++ b/rust/cloud-storage/call/src/domain/ports.rs@@ -5,6 +5,7 @@use std::fmt::Debug;use std::future::Future;+use macro_user_id::user_id::MacroUserIdStr;use uuid::Uuid;use super::models::{@@ -20,12 +21,12 @@ pub trait CallRepository: Send + Sync + 'static {/// Create a new call record, or return `None` if one already exists for/// this channel (unique-constraint conflict).- fn create_call(+ fn create_call<'a>(&self,call_id: &Uuid,channel_id: &Uuid,room_name: &str,- created_by: &str,+ created_by: MacroUserIdStr<'a>,) -> impl Future<Output = Result<Option<Call>, Self::Err>> + Send;/// Get an active call by channel ID.@@ -47,17 +48,17 @@ pub trait CallRepository: Send + Sync + 'static {) -> impl Future<Output = Result<Option<Call>, Self::Err>> + Send;/// Add a participant to a call.- fn add_participant(+ fn add_participant<'a>(&self,call_id: &Uuid,- user_id: &str,+ user_id: MacroUserIdStr<'a>,) -> impl Future<Output = Result<CallParticipant, Self::Err>> + Send;/// Remove a participant from a call.- fn remove_participant(+ fn remove_participant<'a>(&self,call_id: &Uuid,- user_id: &str,+ user_id: MacroUserIdStr<'a>,) -> impl Future<Output = Result<(), Self::Err>> + Send;/// Get all active participants for a call.@@ -123,6 +124,12 @@ pub trait CallRepository: Send + Sync + 'static {call_id: &Uuid,segment: &TranscriptSegmentRequest,) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Get the profile picture URL for a user by their `MacroUserIdStr`.+ fn get_user_profile_picture<'a>(+ &self,+ user_id: MacroUserIdStr<'a>,+ ) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;}/// RTC client port for interacting with the real-time communication service (e.g., LiveKit).@@ -135,17 +142,17 @@ pub trait CallRtcClient: Send + Sync + 'static {fn delete_room(&self, room_name: &str) -> impl Future<Output = anyhow::Result<()>> + Send;/// Generate an access token for a participant to join a room.- fn generate_token(+ fn generate_token<'a>(&self,room_name: &str,- participant_identity: &str,+ participant_identity: MacroUserIdStr<'a>,) -> impl Future<Output = anyhow::Result<String>> + Send;/// Remove a participant from a room.- fn remove_participant(+ fn remove_participant<'a>(&self,room_name: &str,- participant_identity: &str,+ participant_identity: MacroUserIdStr<'a>,) -> impl Future<Output = anyhow::Result<()>> + Send;/// Start a room composite egress (recording). Returns the egress ID.@@ -187,14 +194,14 @@ pub trait CallService: Send + Sync + 'static {fn get_or_create_call(&self,channel_id: &Uuid,- user_id: &str,+ user_id: MacroUserIdStr<'_>,) -> impl Future<Output = Result<CallTokenResponse, CallError>> + Send;/// Leave or end a call. Removes the user; if last participant, also deletes the room and call.- fn leave_or_end_call(+ fn leave_or_end_call<'a>(&self,channel_id: &Uuid,- user_id: &str,+ user_id: MacroUserIdStr<'a>,) -> impl Future<Output = Result<LeaveCallResponse, CallError>> + Send;/// Validate and process a raw webhook event from the RTC provider.diff --git a/rust/cloud-storage/call/src/domain/service.rs b/rust/cloud-storage/call/src/domain/service.rsindex 4d4a5576d3..22e95870d1 100644--- a/rust/cloud-storage/call/src/domain/service.rs+++ b/rust/cloud-storage/call/src/domain/service.rs@@ -1,7 +1,19 @@//! Call service implementation.-use connection::domain::models::EntityAccessAuth;use connection::domain::ports::ConnectionService;+use entity_access::domain::models::EntityType;+use entity_access::domain::ports::EntityAccessService;+use macro_user_id::cowlike::CowLike;+use macro_user_id::user_id::MacroUserIdStr;+use notification::domain::models::apple::{+ APNSPushNotification, Alert, AlertDictionary, Aps, PushNotificationData,+};+use notification::domain::models::{+ NotifCollapseKey, Notification, NotificationExtIos, SendNotificationRequestBuilder,+};+use notification::domain::service::NotificationIngress;+use serde::{Deserialize, Serialize};+use std::collections::HashSet;use uuid::Uuid;use super::models::{@@ -11,27 +23,46 @@ use super::models::{use super::ports::{CallRepository, CallRtcClient, CallService};/// The concrete call service implementation.-pub struct CallServiceImpl<R: CallRepository, C: CallRtcClient, Cn: ConnectionService> {+pub struct CallServiceImpl<+ R: CallRepository,+ C: CallRtcClient,+ Cn: ConnectionService,+ E: EntityAccessService,+ N: NotificationIngress,+> {repo: R,rtc_client: C,connection_service: Cn,+ entity_access_service: E,+ notification_ingress: N,server_url: String,egress_s3_config: Option<EgressS3Config>,internal_call_secret: Option<String>,}-impl<R: CallRepository, C: CallRtcClient, Cn: ConnectionService> CallServiceImpl<R, C, Cn> {+impl<+ R: CallRepository,+ C: CallRtcClient,+ Cn: ConnectionService,+ E: EntityAccessService,+ N: NotificationIngress,+> CallServiceImpl<R, C, Cn, E, N>+{/// Create a new call service.pub fn new(repo: R,rtc_client: C,connection_service: Cn,+ entity_access_service: E,+ notification_ingress: N,server_url: impl Into<String>,) -> Self {Self {repo,rtc_client,connection_service,+ entity_access_service,+ notification_ingress,server_url: server_url.into(),egress_s3_config: None,internal_call_secret: None,@@ -56,32 +87,95 @@ impl<R: CallRepository, C: CallRtcClient, Cn: ConnectionService> CallServiceImplchannel_id: &Uuid,message_type: &str,message: &serde_json::Value,- triggered_by_user_id: Option<&str>,+ triggered_by_user_id: Option<MacroUserIdStr<'_>>,) {- let triggered_by = match triggered_by_user_id {- Some(uid) => uid- .to_string()- .try_into()- .map(EntityAccessAuth::Authenticated)- .unwrap_or(EntityAccessAuth::Internal),- None => EntityAccessAuth::Internal,+ let channel_id_str = channel_id.to_string();+ let users = match self+ .entity_access_service+ .get_users_by_entity(&channel_id_str, EntityType::Channel)+ .await+ {+ Ok(users) => users,+ Err(e) => {+ tracing::error!(error=?e, "failed to fetch channel users for call event");+ return;+ }};+ let users: Vec<MacroUserIdStr<'_>> = users+ .into_iter()+ .filter_map(|u| {+ if triggered_by_user_id+ .as_ref()+ .is_some_and(|t| u.as_ref() == t.as_ref())+ {+ None+ } else {+ Some(u)+ }+ })+ .collect();+let _ = self.connection_service- .send_channel_message(- &channel_id.to_string(),- message_type,- message.clone(),- triggered_by,- )+ .send_channel_message(&users, message_type, message.clone()).await.inspect_err(|e| tracing::error!(error=?e, message_type, "failed to send call event"));}}-impl<R: CallRepository, C: CallRtcClient, Cn: ConnectionService> CallService- for CallServiceImpl<R, C, Cn>+#[derive(Serialize, Deserialize, Clone)]+struct CallStartedNotification {+ sender_profile_picture_url: Option<String>,+}++impl Notification for CallStartedNotification {+ const TYPE_NAME: &'static str = "call-started";+}++impl NotificationExtIos for CallStartedNotification {+ type NotifData = PushNotificationData;++ fn collapse_key(&self, entity: &model_entity::Entity<'_>) -> NotifCollapseKey {+ NotifCollapseKey::new(Self::TYPE_NAME).append(&entity.entity_id)+ }++ fn as_apns<'a>(+ &self,+ sender_id: Option<MacroUserIdStr<'a>>,+ _entity: &model_entity::Entity<'_>,+ notification_id: uuid::Uuid,+ ) -> Option<APNSPushNotification<Self::NotifData>> {+ Some(APNSPushNotification {+ aps: Aps {+ alert: Some(Alert::Dictionary(AlertDictionary {+ title: Some("Incoming Call".to_string()),+ body: Some(format!(+ "{} is calling you",+ sender_id+ .as_ref()+ .map(|e| e.email_str())+ .unwrap_or("Someone")+ )),+ ..Default::default()+ })),+ ..Default::default()+ },+ push_notification_data: PushNotificationData {+ notification_id,+ sender_profile_picture_url: self.sender_profile_picture_url.clone(),+ },+ })+ }+}++impl<+ R: CallRepository,+ C: CallRtcClient,+ Cn: ConnectionService,+ E: EntityAccessService,+ N: NotificationIngress,+> CallService for CallServiceImpl<R, C, Cn, E, N>{fn validate_internal_call(&self, token: &str) -> bool {self.internal_call_secret@@ -112,7 +206,7 @@ impl<R: CallRepository, C: CallRtcClient, Cn: ConnectionService> CallServiceasync fn get_or_create_call(&self,channel_id: &Uuid,- user_id: &str,+ user_id: MacroUserIdStr<'_>,) -> Result<CallTokenResponse, CallError> {let call = match self.repo@@ -135,7 +229,7 @@ impl<R: CallRepository, C: CallRtcClient, Cn: ConnectionService> CallService// the ON CONFLICT returns None — re-read the existing call.match self.repo- .create_call(&call_id, channel_id, &room_name, user_id)+ .create_call(&call_id, channel_id, &room_name, user_id.copied()).await.map_err(|e| CallError::Internal(e.into()))?{@@ -177,10 +271,55 @@ impl<R: CallRepository, C: CallRtcClient, Cn: ConnectionService> CallService"call_id": call.id,"created_by": user_id,}),- Some(user_id),+ Some(user_id.copied()),).await;+ // Send push notification to channel members (best-effort).+ let channel_id_str = channel_id.to_string();+ let recipient_ids: HashSet<MacroUserIdStr<'_>> = match self+ .entity_access_service+ .get_users_by_entity(&channel_id_str, EntityType::Channel)+ .await+ {+ Ok(users) => users+ .into_iter()+ .filter(|u| u.as_ref() != user_id.as_ref())+ .collect(),+ Err(e) => {+ tracing::error!(error=?e, "failed to fetch channel users for call notification");+ HashSet::new()+ }+ };++ let sender_profile_picture_url = self+ .repo+ .get_user_profile_picture(user_id.copied())+ .await+ .ok()+ .flatten();++ let req = SendNotificationRequestBuilder {+ notification_entity: EntityType::Channel+ .with_entity_string(channel_id_str),+ notification: CallStartedNotification {+ sender_profile_picture_url,+ },+ sender_id: Some(user_id.copied()),+ recipient_ids,+ }+ .into_request()+ .with_apns()+ .with_conn_gateway();++ let _ = self+ .notification_ingress+ .send_notification(req)+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, "failed to send call started notification")+ });+call}None => {@@ -197,7 +336,7 @@ impl<R: CallRepository, C: CallRtcClient, Cn: ConnectionService> CallService// Idempotent upsert — handles concurrent joins and rejoin after leave.self.repo- .add_participant(&call.id, user_id)+ .add_participant(&call.id, user_id.copied()).await.map_err(|e| CallError::Internal(e.into()))?;@@ -221,7 +360,7 @@ impl<R: CallRepository, C: CallRtcClient, Cn: ConnectionService> CallServiceasync fn leave_or_end_call(&self,channel_id: &Uuid,- user_id: &str,+ user_id: MacroUserIdStr<'_>,) -> Result<LeaveCallResponse, CallError> {let call = self.repo@@ -232,7 +371,7 @@ impl<R: CallRepository, C: CallRtcClient, Cn: ConnectionService> CallService// Remove participant from DB (idempotent — no-op if already removed by webhook).self.repo- .remove_participant(&call.id, user_id)+ .remove_participant(&call.id, user_id.copied()).await.map_err(|e| CallError::Internal(e.into()))?;@@ -318,12 +457,12 @@ impl<R: CallRepository, C: CallRtcClient, Cn: ConnectionService> CallService// Reconcile: idempotent upsert (handles reconnect/race conditions).self.repo- .add_participant(&call.id, participant_identity)+ .add_participant(&call.id, participant_identity.copied()).await.map_err(|e| CallError::Internal(e.into()))?;tracing::info!(call_id = %call.id,- participant = participant_identity,+ participant = participant_identity.as_ref(),"reconciled participant_joined via webhook");}@@ -349,7 +488,7 @@ impl<R: CallRepository, C: CallRtcClient, Cn: ConnectionService> CallService// Remove participant from DB (idempotent — no-op if already left).self.repo- .remove_participant(&call.id, participant_identity)+ .remove_participant(&call.id, participant_identity.copied()).await.map_err(|e| CallError::Internal(e.into()))?;diff --git a/rust/cloud-storage/call/src/inbound/axum_router.rs b/rust/cloud-storage/call/src/inbound/axum_router.rsindex f59e974e89..4cf133fa54 100644--- a/rust/cloud-storage/call/src/inbound/axum_router.rs+++ b/rust/cloud-storage/call/src/inbound/axum_router.rs@@ -240,11 +240,10 @@ pub async fn get_or_create_call_handler<S: CallService, Svc: EntityAccessService) -> Result<Json<CallTokenResponse>, CallError> {let channel_id = Uuid::parse_str(&access.entity_access_receipt.entity().entity_id).map_err(|_| CallError::Internal(anyhow::anyhow!("invalid channel_id")))?;- let user_id = user.macro_user_id.as_ref();let response = state.service- .get_or_create_call(&channel_id, user_id)+ .get_or_create_call(&channel_id, user.macro_user_id).await?;Ok(Json(response))@@ -303,11 +302,10 @@ pub async fn leave_or_end_call_handler<S: CallService, Svc: EntityAccessService>user: MacroUserExtractor,) -> Result<Json<LeaveCallResponse>, CallError> {let channel_id = access.channel_id;- let user_id = user.macro_user_id.as_ref();let response = state.service- .leave_or_end_call(&channel_id, user_id)+ .leave_or_end_call(&channel_id, user.macro_user_id).await?;Ok(Json(response))diff --git a/rust/cloud-storage/call/src/outbound/livekit_rtc_client.rs b/rust/cloud-storage/call/src/outbound/livekit_rtc_client.rsindex 9adc354112..6f4c29dcd7 100644--- a/rust/cloud-storage/call/src/outbound/livekit_rtc_client.rs+++ b/rust/cloud-storage/call/src/outbound/livekit_rtc_client.rs@@ -11,6 +11,8 @@ use livekit_api::webhooks::WebhookReceiver;use livekit_protocol::{CreateAgentDispatchRequest, EncodedFileOutput, S3Upload, encoded_file_output,};+use macro_user_id::cowlike::CowLike;+use macro_user_id::user_id::MacroUserIdStr;use crate::domain::models::{CallError, CallWebhookEvent, EgressS3Config};use crate::domain::ports::CallRtcClient;@@ -86,10 +88,10 @@ impl CallRtcClient for LivekitRtcClient {async fn generate_token(&self,room_name: &str,- participant_identity: &str,+ participant_identity: MacroUserIdStr<'_>,) -> anyhow::Result<String> {let token = AccessToken::with_api_key(&self.api_key, &self.api_secret)- .with_identity(participant_identity)+ .with_identity(participant_identity.as_ref()).with_grants(VideoGrants {room_join: true,room: room_name.to_string(),@@ -106,10 +108,10 @@ impl CallRtcClient for LivekitRtcClient {async fn remove_participant(&self,room_name: &str,- participant_identity: &str,+ participant_identity: MacroUserIdStr<'_>,) -> anyhow::Result<()> {self.room_client- .remove_participant(room_name, participant_identity)+ .remove_participant(room_name, participant_identity.as_ref()).await?;Ok(())}@@ -191,7 +193,20 @@ impl CallRtcClient for LivekitRtcClient {event: event.event,id: event.id,room_name: event.room.map(|r| r.name),- participant_identity: event.participant.map(|p| p.identity),+ participant_identity: event+ .participant+ .and_then(|p| {+ // The transcription agent joins with its agent name as the+ // identity, which is not a MacroUserId — short-circuit so+ // join/leave events for the agent don't fail parsing.+ if Some(p.identity.as_str()) == self.transcription_agent_name.as_deref() {+ None+ } else {+ Some(MacroUserIdStr::parse_from_str(&p.identity).map(CowLike::into_owned))+ }+ })+ .transpose()+ .map_err(anyhow::Error::from)?,egress_id,file_url,created_at: event.created_at,diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo.rsindex 92421f093e..b93617ed6c 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs@@ -5,6 +5,7 @@ mod test;use chrono::Utc;use entity_access::domain::models::AccessLevel;+use macro_user_id::user_id::MacroUserIdStr;use models_permissions::share_permission::SharePermissionV2;use models_permissions::share_permission::channel_share_permission::ChannelSharePermission;use sqlx::PgPool;@@ -34,7 +35,7 @@ impl CallRepository for PgCallRepo {call_id: &Uuid,channel_id: &Uuid,room_name: &str,- created_by: &str,+ created_by: MacroUserIdStr<'_>,) -> Result<Option<Call>, Self::Err> {// Create share permissionlet share_permission_id = uuid::Uuid::now_v7();@@ -90,7 +91,7 @@ impl CallRepository for PgCallRepo {call_id,channel_id,room_name,- created_by,+ created_by.as_ref(),&share_permission_id.to_string(),).fetch_optional(tx.as_mut())@@ -192,7 +193,7 @@ impl CallRepository for PgCallRepo {async fn add_participant(&self,call_id: &Uuid,- user_id: &str,+ user_id: MacroUserIdStr<'_>,) -> Result<CallParticipant, Self::Err> {let row = sqlx::query!(r#"@@ -202,7 +203,7 @@ impl CallRepository for PgCallRepo {RETURNING call_id, user_id, joined_at"#,call_id,- user_id,+ user_id.as_ref(),).fetch_one(&self.pool).await?;@@ -215,7 +216,11 @@ impl CallRepository for PgCallRepo {}#[tracing::instrument(err, skip(self))]- async fn remove_participant(&self, call_id: &Uuid, user_id: &str) -> Result<(), Self::Err> {+ async fn remove_participant(+ &self,+ call_id: &Uuid,+ user_id: MacroUserIdStr<'_>,+ ) -> Result<(), Self::Err> {sqlx::query!(r#"UPDATE call_participants@@ -223,7 +228,7 @@ impl CallRepository for PgCallRepo {WHERE call_id = $1 AND user_id = $2 AND left_at IS NULL"#,call_id,- user_id,+ user_id.as_ref(),).execute(&self.pool).await?;@@ -475,4 +480,24 @@ impl CallRepository for PgCallRepo {.await?;Ok(())}++ #[tracing::instrument(err, skip(self))]+ async fn get_user_profile_picture<'a>(+ &self,+ user_id: MacroUserIdStr<'a>,+ ) -> Result<Option<String>, Self::Err> {+ sqlx::query_scalar!(+ r#"+ SELECT mui.profile_picture+ FROM macro_user_info mui+ JOIN "User" u ON mui.macro_user_id = u.macro_user_id+ WHERE u.macro_user_id::text = $1 AND mui.profile_picture IS NOT NULL+ LIMIT 1+ "#,+ user_id.as_ref(),+ )+ .fetch_optional(&self.pool)+ .await+ .map(|opt| opt.flatten())+ }}diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rsindex 924f63d56d..33c4253aea 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs@@ -1,17 +1,23 @@+use std::{ops::Deref, sync::LazyLock};+use crate::domain::models::TranscriptSegmentRequest;use crate::domain::ports::CallRepository;use crate::outbound::pg_call_repo::PgCallRepo;use chrono::Utc;use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use sqlx::{Pool, Postgres};use uuid::Uuid;const CH1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c01);const CH2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c02);const CALL1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca110);-const USER_A: &str = "macro|[email protected]";-const USER_B: &str = "macro|[email protected]";-const USER_C: &str = "macro|[email protected]";+static USER_A: LazyLock<MacroUserIdStr<'static>> =+ LazyLock::new(|| MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());+static USER_B: LazyLock<MacroUserIdStr<'static>> =+ LazyLock::new(|| MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());+static USER_C: LazyLock<MacroUserIdStr<'static>> =+ LazyLock::new(|| MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());fn repo(pool: Pool<Postgres>) -> PgCallRepo {PgCallRepo::new(pool)@@ -27,14 +33,14 @@ async fn create_call_returns_call(pool: Pool<Postgres>) -> anyhow::Result<()> {let repo = repo(pool);let id = Uuid::now_v7();let call = repo- .create_call(&id, &CH2, "room-ch2", USER_B)+ .create_call(&id, &CH2, "room-ch2", USER_B.deref().copied()).await?.expect("should create new call");assert_eq!(call.id, id);assert_eq!(call.channel_id, CH2);assert_eq!(call.room_name, "room-ch2");- assert_eq!(call.created_by, USER_B);+ assert_eq!(call.created_by, USER_B.as_ref());Ok(())}@@ -46,7 +52,7 @@ async fn create_call_returns_none_on_duplicate_channel(pool: Pool<Postgres>) ->let repo = repo(pool);// CH1 already has an active call from the fixture.let result = repo- .create_call(&Uuid::now_v7(), &CH1, "room-dup", USER_A)+ .create_call(&Uuid::now_v7(), &CH1, "room-dup", USER_A.deref().copied()).await?;assert!(result.is_none(), "should return None on conflict");@@ -120,13 +126,15 @@ async fn add_and_check_participant(pool: Pool<Postgres>) -> anyhow::Result<()> {let repo = repo(pool);// user-c is not in the call yet.- assert!(!repo.is_participant(&CALL1, USER_C).await?);+ assert!(!repo.is_participant(&CALL1, &USER_C.as_ref()).await?);- let participant = repo.add_participant(&CALL1, USER_C).await?;+ let participant = repo+ .add_participant(&CALL1, USER_C.deref().copied())+ .await?;assert_eq!(participant.call_id, CALL1);- assert_eq!(participant.user_id, USER_C);+ assert_eq!(participant.user_id, USER_C.as_ref());- assert!(repo.is_participant(&CALL1, USER_C).await?);+ assert!(repo.is_participant(&CALL1, &USER_C.as_ref()).await?);Ok(())}@@ -137,9 +145,10 @@ async fn add_and_check_participant(pool: Pool<Postgres>) -> anyhow::Result<()> {async fn remove_participant_removes_from_db(pool: Pool<Postgres>) -> anyhow::Result<()> {let repo = repo(pool);- assert!(repo.is_participant(&CALL1, USER_B).await?);- repo.remove_participant(&CALL1, USER_B).await?;- assert!(!repo.is_participant(&CALL1, USER_B).await?);+ assert!(repo.is_participant(&CALL1, &USER_B.as_ref()).await?);+ repo.remove_participant(&CALL1, USER_B.deref().copied())+ .await?;+ assert!(!repo.is_participant(&CALL1, &USER_B.as_ref()).await?);Ok(())}@@ -155,8 +164,8 @@ async fn get_participants_returns_all(pool: Pool<Postgres>) -> anyhow::Result<()assert_eq!(participants.len(), 2);let user_ids: Vec<&str> = participants.iter().map(|p| p.user_id.as_str()).collect();- assert!(user_ids.contains(&USER_A));- assert!(user_ids.contains(&USER_B));+ assert!(user_ids.contains(&USER_A.as_ref()));+ assert!(user_ids.contains(&USER_B.as_ref()));Ok(())}@@ -171,7 +180,8 @@ async fn get_participant_count_correct(pool: Pool<Postgres>) -> anyhow::Result<(assert_eq!(repo.get_participant_count(&CALL1).await?, 2);- repo.remove_participant(&CALL1, USER_B).await?;+ repo.remove_participant(&CALL1, USER_B.deref().copied())+ .await?;assert_eq!(repo.get_participant_count(&CALL1).await?, 1);Ok(())}@@ -223,7 +233,7 @@ async fn archive_call_creates_record_and_deletes_ephemeral(.await?;assert_eq!(record.channel_id, CH1);- assert_eq!(record.created_by, USER_A);+ assert_eq!(record.created_by, USER_A.as_ref());assert!(record.duration_ms >= 0);assert!(record.ended_at >= record.started_at);@@ -258,8 +268,10 @@ async fn archive_call_preserves_soft_deleted_participants(let repo = repo(pool.clone());// Soft-delete both participants (simulates leave_or_end_call flow).- repo.remove_participant(&CALL1, USER_A).await?;- repo.remove_participant(&CALL1, USER_B).await?;+ repo.remove_participant(&CALL1, USER_A.deref().copied())+ .await?;+ repo.remove_participant(&CALL1, USER_B.deref().copied())+ .await?;// Active count should be 0 but rows still exist.assert_eq!(repo.get_participant_count(&CALL1).await?, 0);@@ -282,8 +294,8 @@ async fn archive_call_preserves_soft_deleted_participants(assert_eq!(rows.len(), 2);let user_ids: Vec<&str> = rows.iter().map(|r| r.user_id.as_str()).collect();- assert!(user_ids.contains(&USER_A));- assert!(user_ids.contains(&USER_B));+ assert!(user_ids.contains(&USER_A.as_ref()));+ assert!(user_ids.contains(&USER_B.as_ref()));// Both should have left_at set since they were soft-deleted.assert!(rows.iter().all(|r| r.left_at.is_some()));@@ -474,7 +486,7 @@ async fn archive_call_copies_transcripts(pool: Pool<Postgres>) -> anyhow::Resultassert_eq!(transcripts.len(), 1);assert_eq!(transcripts[0].content, "test transcript");- assert_eq!(transcripts[0].speaker_id, USER_A);+ assert_eq!(transcripts[0].speaker_id, USER_A.as_ref());assert_eq!(transcripts[0].sequence_num, 1);// Ephemeral transcripts should be gone (cascaded).diff --git a/rust/cloud-storage/connection/src/domain/ports.rs b/rust/cloud-storage/connection/src/domain/ports.rsindex 744690eb38..7b985ab000 100644--- a/rust/cloud-storage/connection/src/domain/ports.rs+++ b/rust/cloud-storage/connection/src/domain/ports.rs@@ -2,10 +2,12 @@//!//! These traits define the contracts that adapters must implement.-use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};+use macro_user_id::{+ lowercased::Lowercase,+ user_id::{MacroUserId, MacroUserIdStr},+};use crate::domain::models::{ConnectionError, InvalidationEvent};-use entity_access::domain::models::EntityAccessAuth;/// Repository for handling github oauth related actions.pub trait ConnectionGateway: Send + Sync + 'static {@@ -22,7 +24,7 @@ pub trait ConnectionGateway: Send + Sync + 'static {/// Sends an arbitrary message to a list of users.fn batch_send_message<'a>(&self,- users: &[MacroUserId<Lowercase<'a>>],+ users: &[MacroUserIdStr<'a>],message_type: &str,message: serde_json::Value,) -> impl Future<Output = Result<(), Self::Err>> + Send;@@ -36,15 +38,11 @@ pub trait ConnectionService: Send + Sync + 'static {invalidation_event: InvalidationEvent<'a, T>,) -> impl Future<Output = Result<(), ConnectionError>> + Send;- /// Sends an arbitrary message to all users in a channel.- ///- /// Resolves channel members internally, filters out the triggering user,- /// and sends via the connection gateway.- fn send_channel_message(+ /// Sends an arbitrary message to the given list of users via the connection gateway.+ fn send_channel_message<'a>(&self,- channel_id: &str,+ users: &[MacroUserIdStr<'a>],message_type: &str,message: serde_json::Value,- triggered_by: EntityAccessAuth,) -> impl Future<Output = Result<(), ConnectionError>> + Send;}diff --git a/rust/cloud-storage/connection/src/domain/service.rs b/rust/cloud-storage/connection/src/domain/service.rsindex ccd9837123..901217c23e 100644--- a/rust/cloud-storage/connection/src/domain/service.rs+++ b/rust/cloud-storage/connection/src/domain/service.rs@@ -3,9 +3,10 @@use std::sync::Arc;use entity_access::domain::ports::EntityAccessService;-use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};--use entity_access::domain::models::EntityType;+use macro_user_id::{+ lowercased::Lowercase,+ user_id::{MacroUserId, MacroUserIdStr},+};use crate::domain::{models::{ConnectionError, InvalidationEvent},@@ -82,45 +83,19 @@ impl<E: EntityAccessService, Cgw: ConnectionGateway> ConnectionService}#[tracing::instrument(skip(self), err)]- async fn send_channel_message(+ async fn send_channel_message<'a>(&self,- channel_id: &str,+ users: &[MacroUserIdStr<'a>],message_type: &str,message: serde_json::Value,- triggered_by: entity_access::domain::models::EntityAccessAuth,) -> Result<(), ConnectionError> {- let users = self- .entity_access_service- .get_users_by_entity(channel_id, EntityType::Channel)- .await- .map_err(|e| ConnectionError::Internal(e.into()))?;-- let users = match &triggered_by {- entity_access::domain::models::EntityAccessAuth::Authenticated(macro_user_id_str) => {- users- .into_iter()- .filter_map(|p| {- if p.as_ref() != macro_user_id_str.as_ref() {- Some(p.0)- } else {- None- }- })- .collect::<Vec<MacroUserId<Lowercase<'_>>>>()- }- entity_access::domain::models::EntityAccessAuth::Unauthenticated- | entity_access::domain::models::EntityAccessAuth::Internal => {- users.into_iter().map(|s| s.0.to_owned()).collect()- }- };-if users.is_empty() {tracing::trace!("no users to send channel message to");return Ok(());}self.connection_gateway- .batch_send_message(&users, message_type, message)+ .batch_send_message(users, message_type, message).await.map_err(|e| ConnectionError::Internal(e.into()))?;diff --git a/rust/cloud-storage/connection/src/outbound/connection_gateway_client.rs b/rust/cloud-storage/connection/src/outbound/connection_gateway_client.rsindex 3bdaeabfc7..6607c56563 100644--- a/rust/cloud-storage/connection/src/outbound/connection_gateway_client.rs+++ b/rust/cloud-storage/connection/src/outbound/connection_gateway_client.rs@@ -1,7 +1,10 @@//! Implementation of GW port using the ConnectionGatewayClientuse connection_gateway_client::ConnectionGatewayClient;-use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};+use macro_user_id::{+ lowercased::Lowercase,+ user_id::{MacroUserId, MacroUserIdStr},+};use crate::domain::{models::{INVALIDATION_MESSAGE_TYPE, InvalidationEvent},@@ -51,7 +54,7 @@ impl ConnectionGateway for ConnectionGatewayImpl {#[tracing::instrument(skip(self), err)]async fn batch_send_message<'a>(&self,- users: &[MacroUserId<Lowercase<'a>>],+ users: &[MacroUserIdStr<'a>],message_type: &str,message: serde_json::Value,) -> Result<(), Self::Err> {diff --git a/rust/cloud-storage/deny.toml b/rust/cloud-storage/deny.tomlindex bd70d6356b..506cb19c0e 100644--- a/rust/cloud-storage/deny.toml+++ b/rust/cloud-storage/deny.toml@@ -264,7 +264,6 @@ skip = [{ crate = "thiserror-impl", reason = "Error handling dependencies" },{ crate = "tokio-rustls", reason = "AWS SDK and reqwest version mismatch" },{ crate = "tower", reason = "Service framework dependencies" },- { crate = "tungstenite", reason = "WebSocket dependencies" },{ crate = "unicode-width", reason = "Unicode dependencies" },{ crate = "wasi", reason = "WebAssembly system interface dependencies" },{ crate = "windows-sys", reason = "Windows dependencies version mismatch" },diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex f3c818ac59..f1c5fa5a60 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -163,8 +163,13 @@ pub(crate) type CallConnectionService =ConnectionServiceImpl<EntityAccessService, ConnectionGatewayImpl>;/// Type alias for the call service.-pub(crate) type DssCallService =- CallServiceImpl<PgCallRepo, LivekitRtcClient, CallConnectionService>;+pub(crate) type DssCallService = CallServiceImpl<+ PgCallRepo,+ LivekitRtcClient,+ CallConnectionService,+ EntityAccessService,+ NotificationIngressType,+>;/// Type alias for the call router state.pub(crate) type DssCallState = CallRouterState<DssCallService, EntityAccessService>;diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 864748e81d..305b824a26 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -372,6 +372,8 @@ async fn main() -> anyhow::Result<()> {call_repo,livekit_rtc_client,call_connection_service,+ (*entity_access_service).clone(),+ (*notification_ingress_service).clone(),config.vars.livekit_server_url.as_ref(),);if let Some(secret) = internal_call_secret {diff --git a/rust/cloud-storage/documents/examples/documents_toolset.rs b/rust/cloud-storage/documents/examples/documents_toolset.rsindex df119bd1d7..fe26d8373c 100644--- a/rust/cloud-storage/documents/examples/documents_toolset.rs+++ b/rust/cloud-storage/documents/examples/documents_toolset.rs@@ -48,12 +48,11 @@ impl ConnectionService for NoOpConnectionService {Ok(())}- async fn send_channel_message(+ async fn send_channel_message<'a>(&self,- _channel_id: &str,+ _users: &[MacroUserIdStr<'a>],_message_type: &str,_message: serde_json::Value,- _triggered_by: connection::domain::models::EntityAccessAuth,) -> Result<(), connection::domain::models::ConnectionError> {Ok(())}