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(ios): native call backend support (#3568)

Peter Chinman7d0227e905d3
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 8106012144..a6a849d453 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -1861,6 +1861,7 @@ dependencies = [
"entity_access",
"entity_access_db_utils",
"filter_ast",
+ "futures",
"item_filters",
"livekit-api",
"livekit-protocol",
diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rs
index 78ad8c9a48..3ed7961766 100644
--- a/rust/cloud-storage/ai_tools/src/tool_context.rs
+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs
@@ -167,6 +167,16 @@ impl CallRtcClient for NoOpCallRtcClient {
anyhow::bail!("call RTC client not configured")
}
+ async fn build_voip_push_payloads<'a>(
+ &self,
+ _request: call::domain::models::VoipPushPayloadRequest<'a>,
+ ) -> Vec<(
+ MacroUserIdStr<'static>,
+ notification::domain::models::apple::VoipPushPayload,
+ )> {
+ Vec::new()
+ }
+
async fn remove_participant<'a>(
&self,
_room_name: &str,
diff --git a/rust/cloud-storage/call/Cargo.toml b/rust/cloud-storage/call/Cargo.toml
index f0da5f99ca..ba2cb81f89 100644
--- a/rust/cloud-storage/call/Cargo.toml
+++ b/rust/cloud-storage/call/Cargo.toml
@@ -20,6 +20,7 @@ outbound = [
"dep:aws-sdk-s3",
"comms/outbound",
"dep:entity_access_db_utils",
+ "dep:futures",
"dep:livekit-api",
"dep:livekit-protocol",
"dep:macro_aws_config",
@@ -46,6 +47,7 @@ entity_access = { path = "../entity_access", optional = true, default-features =
] }
entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }
filter_ast = { path = "../filter_ast" }
+futures = { workspace = true, optional = true }
item_filters = { path = "../item_filters" }
livekit-api = { workspace = true, optional = true }
livekit-protocol = { workspace = true, optional = true }
diff --git a/rust/cloud-storage/call/src/domain/models.rs b/rust/cloud-storage/call/src/domain/models.rs
index f48657b6b4..bd6338ad35 100644
--- a/rust/cloud-storage/call/src/domain/models.rs
+++ b/rust/cloud-storage/call/src/domain/models.rs
@@ -53,6 +53,24 @@ pub struct CallTokenResponse {
pub server_url: String,
}
+/// Inputs required by the RTC adapter to produce native VoIP invite payloads.
+pub struct VoipPushPayloadRequest<'a> {
+ /// Users with resolved PushKit endpoints that should receive native VoIP invites.
+ pub recipients: &'a [MacroUserIdStr<'static>],
+ /// RTC room name the recipient will join.
+ pub room_name: &'a str,
+ /// Call record ID exposed to the client.
+ pub call_id: Uuid,
+ /// Channel ID associated with the call.
+ pub channel_id: &'a str,
+ /// Channel display name shown in the native incoming-call UI.
+ pub channel_name: &'a str,
+ /// Caller display name shown in the native incoming-call UI.
+ pub caller_name: &'a str,
+ /// RTC server URL the native client should connect to.
+ pub livekit_server_url: &'a str,
+}
+
/// Response for the leave/end call operation.
#[derive(Debug, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
diff --git a/rust/cloud-storage/call/src/domain/ports.rs b/rust/cloud-storage/call/src/domain/ports.rs
index f75e99bd00..ffc94afe99 100644
--- a/rust/cloud-storage/call/src/domain/ports.rs
+++ b/rust/cloud-storage/call/src/domain/ports.rs
@@ -10,6 +10,7 @@ use macro_user_id::user_id::MacroUserIdStr;
use uuid::Uuid;
use item_filters::ast::{LiteralTree, call::CallLiteral};
+use notification::domain::models::apple::VoipPushPayload;
use crate::domain::models::{
CustomSpeakerAssignment, EditCallRecordRequest, EditCallTranscriptRequest,
@@ -20,7 +21,7 @@ use super::models::{
CallRecordPreview, CallRecordTranscriptSegment, CallTokenResponse,
CallTranscriptCustomSpeakerResult, CallWebhookEvent, EgressS3Config, EnrichedCallTranscript,
GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetCallRecordsRequest,
- LeaveCallResponse, TranscriptSegmentRequest,
+ LeaveCallResponse, TranscriptSegmentRequest, VoipPushPayloadRequest,
};
/// Repository port for persisting call state to the database.
@@ -440,6 +441,12 @@ pub trait CallRtcClient: Send + Sync + 'static {
participant_identity: MacroUserIdStr<'a>,
) -> impl Future<Output = anyhow::Result<String>> + Send;
+ /// Build VoIP payloads for native incoming-call delivery.
+ fn build_voip_push_payloads<'a>(
+ &self,
+ request: VoipPushPayloadRequest<'a>,
+ ) -> impl Future<Output = Vec<(MacroUserIdStr<'static>, VoipPushPayload)>> + Send;
+
/// Remove a participant from a room.
fn remove_participant<'a>(
&self,
diff --git a/rust/cloud-storage/call/src/domain/service.rs b/rust/cloud-storage/call/src/domain/service.rs
index 55b6b13c29..ea11198f99 100644
--- a/rust/cloud-storage/call/src/domain/service.rs
+++ b/rust/cloud-storage/call/src/domain/service.rs
@@ -20,11 +20,13 @@ use notification::domain::models::{
use notification::domain::ports::VoipPushSender;
use notification::domain::service::NotificationIngress;
use serde::{Deserialize, Serialize};
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use uuid::Uuid;
-use crate::domain::models::{EditCallRecordRequest, EditCallTranscriptRequest};
+use crate::domain::models::{
+ EditCallRecordRequest, EditCallTranscriptRequest, VoipPushPayloadRequest,
+};
use super::models::{
AddParticipantError, CallActiveResponse, CallError, CallRecord, CallRecordTranscriptSegment,
@@ -489,23 +491,76 @@ impl<
// Send VoIP push for the native iOS incoming-call sheet first.
// Recipients with successful VoIP delivery do not need the regular
// APNS alert banner as well.
- let recipient_vec: Vec<MacroUserIdStr<'_>> =
- recipient_ids.iter().cloned().collect();
- let voip_payload = VoipPushPayload {
- aps: Default::default(),
- call_id: call.id.to_string(),
- channel_id: channel_id_str.clone(),
- channel_name: channel_name.clone().unwrap_or_default(),
- caller_name,
- };
- let voip_recipient_ids = self
+ let recipient_vec: Vec<MacroUserIdStr<'static>> = recipient_ids
+ .iter()
+ .cloned()
+ .map(CowLike::into_owned)
+ .collect();
+
+ // Resolve VoIP endpoints before minting tokens:
+ // users without PushKit endpoints should not get
+ // LiveKit tokens minted for them. If endpoint
+ // resolution fails, fall back to normal APNS for
+ // everyone rather than dropping the notification.
+ let voip_targets = match self
.voip_push_sender
- .send_voip_push(&recipient_vec, &voip_payload)
+ .get_voip_push_targets(&recipient_vec)
+ .await
+ {
+ Ok(targets) => targets,
+ Err(e) => {
+ tracing::error!(
+ error=?e,
+ "failed to resolve VoIP push targets; falling back to APNS"
+ );
+ Vec::new()
+ }
+ };
+ let voip_target_recipient_ids: Vec<MacroUserIdStr<'static>> =
+ voip_targets
+ .iter()
+ .map(|target| target.recipient_id.clone())
+ .collect();
+
+ let voip_channel_name = channel_name.clone().unwrap_or_default();
+ let payloads = self
+ .rtc_client
+ .build_voip_push_payloads(VoipPushPayloadRequest {
+ recipients: &voip_target_recipient_ids,
+ room_name: &call.room_name,
+ call_id: call.id,
+ channel_id: &channel_id_str,
+ channel_name: &voip_channel_name,
+ caller_name: &caller_name,
+ livekit_server_url: &self.server_url,
+ })
.await;
+ let mut payloads_by_recipient: HashMap<
+ MacroUserIdStr<'static>,
+ VoipPushPayload,
+ > = payloads.into_iter().collect();
+ // Rejoin resolved endpoints with successfully
+ // minted payloads. A failed token mint skips only
+ // that recipient's VoIP push.
+ let pushes = voip_targets
+ .into_iter()
+ .filter_map(|target| {
+ payloads_by_recipient
+ .remove(&target.recipient_id)
+ .map(|payload| (target, payload))
+ })
+ .collect();
+
+ let voip_recipient_ids =
+ self.voip_push_sender.send_voip_pushes(pushes).await;
+
let apns_recipient_ids =
exclude_voip_recipients(recipient_ids, &voip_recipient_ids);
+ // APNS is the fallback/default path. Recipients
+ // with a successful VoIP delivery skip the regular
+ // alert to avoid duplicate incoming-call UI.
if !apns_recipient_ids.is_empty() {
let req = SendNotificationRequestBuilder {
notification_entity: EntityType::Channel
diff --git a/rust/cloud-storage/call/src/domain/service/test.rs b/rust/cloud-storage/call/src/domain/service/test.rs
index bb123b15df..ab8485bb8f 100644
--- a/rust/cloud-storage/call/src/domain/service/test.rs
+++ b/rust/cloud-storage/call/src/domain/service/test.rs
@@ -1,18 +1,136 @@
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
+use std::sync::Mutex;
+use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
+use notification::domain::models::apple::VoipPushPayload;
+use uuid::Uuid;
+
+use crate::domain::models::{CallError, CallWebhookEvent, EgressS3Config, VoipPushPayloadRequest};
+use crate::domain::ports::CallRtcClient;
use super::{exclude_voip_recipients, extract_recording_key};
#[cfg(feature = "outbound")]
use macro_db_migrator::MACRO_DB_MIGRATIONS;
-#[cfg(feature = "outbound")]
-use uuid::Uuid;
fn user(email: &'static str) -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from_email(email).unwrap()
}
+struct MockRtcClient {
+ tokens: Mutex<HashMap<String, anyhow::Result<String>>>,
+ generate_calls: Mutex<Vec<(String, String)>>,
+}
+
+impl MockRtcClient {
+ fn new() -> Self {
+ Self {
+ tokens: Mutex::new(HashMap::new()),
+ generate_calls: Mutex::new(Vec::new()),
+ }
+ }
+
+ fn set_token(&self, identity: &str, token: anyhow::Result<String>) {
+ self.tokens
+ .lock()
+ .unwrap()
+ .insert(identity.to_string(), token);
+ }
+
+ fn calls(&self) -> Vec<(String, String)> {
+ self.generate_calls.lock().unwrap().clone()
+ }
+}
+
+impl CallRtcClient for MockRtcClient {
+ async fn create_room(&self, _room_name: &str) -> anyhow::Result<()> {
+ unreachable!("create_room not exercised by these tests")
+ }
+
+ async fn delete_room(&self, _room_name: &str) -> anyhow::Result<()> {
+ unreachable!("delete_room not exercised by these tests")
+ }
+
+ async fn generate_token<'a>(
+ &self,
+ room_name: &str,
+ participant_identity: MacroUserIdStr<'a>,
+ ) -> anyhow::Result<String> {
+ let key = participant_identity.as_ref().to_string();
+ self.generate_calls
+ .lock()
+ .unwrap()
+ .push((room_name.to_string(), key.clone()));
+ let mut tokens = self.tokens.lock().unwrap();
+ tokens
+ .remove(&key)
+ .unwrap_or_else(|| Ok(format!("default-token-{key}")))
+ }
+
+ async fn build_voip_push_payloads<'a>(
+ &self,
+ request: VoipPushPayloadRequest<'a>,
+ ) -> Vec<(MacroUserIdStr<'static>, VoipPushPayload)> {
+ let mut payloads = Vec::new();
+ for recipient_id in request.recipients {
+ let livekit_token = match self
+ .generate_token(request.room_name, recipient_id.clone())
+ .await
+ {
+ Ok(livekit_token) => livekit_token,
+ Err(_) => continue,
+ };
+ payloads.push((
+ recipient_id.clone(),
+ VoipPushPayload {
+ aps: Default::default(),
+ call_id: request.call_id.to_string(),
+ channel_id: request.channel_id.to_string(),
+ channel_name: request.channel_name.to_string(),
+ caller_name: request.caller_name.to_string(),
+ livekit_server_url: Some(request.livekit_server_url.to_string()),
+ livekit_token: Some(livekit_token),
+ },
+ ));
+ }
+
+ payloads
+ }
+
+ async fn remove_participant<'a>(
+ &self,
+ _room_name: &str,
+ _participant_identity: MacroUserIdStr<'a>,
+ ) -> anyhow::Result<()> {
+ unreachable!("remove_participant not exercised by these tests")
+ }
+
+ async fn start_room_composite_egress(
+ &self,
+ _room_name: &str,
+ _s3_config: &EgressS3Config,
+ ) -> anyhow::Result<String> {
+ unreachable!("start_room_composite_egress not exercised by these tests")
+ }
+
+ async fn stop_egress(&self, _egress_id: &str) -> anyhow::Result<()> {
+ unreachable!("stop_egress not exercised by these tests")
+ }
+
+ fn receive_webhook(
+ &self,
+ _body: &str,
+ _auth_token: &str,
+ ) -> Result<CallWebhookEvent, CallError> {
+ unreachable!("receive_webhook not exercised by these tests")
+ }
+
+ async fn dispatch_transcription_agent(&self, _room_name: &str) -> anyhow::Result<()> {
+ unreachable!("dispatch_transcription_agent not exercised by these tests")
+ }
+}
+
#[cfg(feature = "outbound")]
const CALL1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca110);
#[cfg(feature = "outbound")]
@@ -123,6 +241,97 @@ fn exclude_voip_recipients_returns_empty_when_all_users_received_voip() {
assert!(filtered.is_empty());
}
+#[tokio::test]
+async fn build_voip_push_payloads_mints_a_distinct_token_per_recipient() {
+ let alice = user("[email protected]").into_owned();
+ let bob = user("[email protected]").into_owned();
+ let mock = MockRtcClient::new();
+ mock.set_token(alice.as_ref(), Ok("token-alice".to_string()));
+ mock.set_token(bob.as_ref(), Ok("token-bob".to_string()));
+
+ let recipients = vec![alice.clone(), bob.clone()];
+ let payloads = mock
+ .build_voip_push_payloads(VoipPushPayloadRequest {
+ recipients: &recipients,
+ room_name: "room-1",
+ call_id: Uuid::nil(),
+ channel_id: "channel-1",
+ channel_name: "general",
+ caller_name: "Carla",
+ livekit_server_url: "wss://lk.example",
+ })
+ .await;
+
+ assert_eq!(payloads.len(), 2);
+ let by_id: HashMap<String, String> = payloads
+ .into_iter()
+ .map(|(id, p)| {
+ (
+ id.as_ref().to_string(),
+ p.livekit_token.expect("livekit_token populated on success"),
+ )
+ })
+ .collect();
+ assert_eq!(by_id.get(alice.as_ref()).unwrap(), "token-alice");
+ assert_eq!(by_id.get(bob.as_ref()).unwrap(), "token-bob");
+ assert_eq!(mock.calls().len(), 2);
+ for (room, _) in mock.calls() {
+ assert_eq!(room, "room-1");
+ }
+}
+
+#[tokio::test]
+async fn build_voip_push_payloads_drops_recipients_whose_token_mint_fails() {
+ let alice = user("[email protected]").into_owned();
+ let bob = user("[email protected]").into_owned();
+ let mock = MockRtcClient::new();
+ mock.set_token(alice.as_ref(), Ok("token-alice".to_string()));
+ mock.set_token(bob.as_ref(), Err(anyhow::anyhow!("livekit unreachable")));
+
+ let recipients = vec![alice.clone(), bob.clone()];
+ let payloads = mock
+ .build_voip_push_payloads(VoipPushPayloadRequest {
+ recipients: &recipients,
+ room_name: "room-1",
+ call_id: Uuid::nil(),
+ channel_id: "channel-1",
+ channel_name: "general",
+ caller_name: "Carla",
+ livekit_server_url: "wss://lk.example",
+ })
+ .await;
+
+ assert_eq!(
+ payloads.len(),
+ 1,
+ "bob's failed token mint should not block alice's payload"
+ );
+ let (id, payload) = &payloads[0];
+ assert_eq!(id.as_ref(), alice.as_ref());
+ assert_eq!(payload.livekit_token.as_deref(), Some("token-alice"));
+}
+
+#[tokio::test]
+async fn build_voip_push_payloads_returns_empty_for_no_recipients() {
+ let mock = MockRtcClient::new();
+ let recipients: Vec<MacroUserIdStr<'static>> = Vec::new();
+
+ let payloads = mock
+ .build_voip_push_payloads(VoipPushPayloadRequest {
+ recipients: &recipients,
+ room_name: "room-1",
+ call_id: Uuid::nil(),
+ channel_id: "channel-1",
+ channel_name: "general",
+ caller_name: "Carla",
+ livekit_server_url: "wss://lk.example",
+ })
+ .await;
+
+ assert!(payloads.is_empty());
+ assert!(mock.calls().is_empty());
+}
+
#[cfg(feature = "outbound")]
#[sqlx::test(
fixtures(path = "../../../fixtures", scripts("call_repo")),
diff --git a/rust/cloud-storage/call/src/outbound/livekit_rtc_client.rs b/rust/cloud-storage/call/src/outbound/livekit_rtc_client.rs
index a1b6c0b477..d943242d3b 100644
--- a/rust/cloud-storage/call/src/outbound/livekit_rtc_client.rs
+++ b/rust/cloud-storage/call/src/outbound/livekit_rtc_client.rs
@@ -3,6 +3,7 @@
//! Wraps the `livekit-api` crate to provide room management, token generation,
//! egress recording, and webhook validation.
+use futures::future;
use livekit_api::access_token::{AccessToken, TokenVerifier, VideoGrants};
use livekit_api::services::agent_dispatch::AgentDispatchClient;
use livekit_api::services::egress::{EgressClient, EgressOutput, RoomCompositeOptions};
@@ -13,10 +14,13 @@ use livekit_protocol::{
};
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
+use notification::domain::models::apple::VoipPushPayload;
-use crate::domain::models::{CallError, CallWebhookEvent, EgressS3Config};
+use crate::domain::models::{CallError, CallWebhookEvent, EgressS3Config, VoipPushPayloadRequest};
use crate::domain::ports::CallRtcClient;
+const VOIP_TOKEN_MINT_CONCURRENCY: usize = 16;
+
/// LiveKit implementation of [`CallRtcClient`].
pub struct LivekitRtcClient {
room_client: RoomClient,
@@ -96,8 +100,11 @@ impl CallRtcClient for LivekitRtcClient {
room_name: &str,
participant_identity: MacroUserIdStr<'_>,
) -> anyhow::Result<String> {
+ // Pinned so VoIP-delivered tokens survive push delay and lock-screen ringing.
+ // TODO(call-phase-2): add token refresh before supporting calls over 6h.
let token = AccessToken::with_api_key(&self.api_key, &self.api_secret)
.with_identity(participant_identity.as_ref())
+ .with_ttl(std::time::Duration::from_secs(6 * 3600))
.with_grants(VideoGrants {
room_join: true,
room: room_name.to_string(),
@@ -110,6 +117,61 @@ impl CallRtcClient for LivekitRtcClient {
Ok(token)
}
+ #[tracing::instrument(
+ skip(self, request),
+ fields(
+ recipient_count = request.recipients.len(),
+ room_name = request.room_name,
+ call_id = %request.call_id,
+ channel_id = request.channel_id,
+ )
+ )]
+ async fn build_voip_push_payloads<'a>(
+ &self,
+ request: VoipPushPayloadRequest<'a>,
+ ) -> Vec<(MacroUserIdStr<'static>, VoipPushPayload)> {
+ let room_name = request.room_name;
+ let call_id = request.call_id;
+ let channel_id = request.channel_id;
+ let channel_name = request.channel_name;
+ let caller_name = request.caller_name;
+ let livekit_server_url = request.livekit_server_url;
+
+ let mut payloads = Vec::new();
+ for batch in request.recipients.chunks(VOIP_TOKEN_MINT_CONCURRENCY) {
+ let results = future::join_all(batch.iter().map(|recipient_id| {
+ let recipient_id = recipient_id.clone();
+ async move {
+ match self.generate_token(room_name, recipient_id.clone()).await {
+ Ok(livekit_token) => Some((
+ recipient_id,
+ VoipPushPayload {
+ aps: Default::default(),
+ call_id: call_id.to_string(),
+ channel_id: channel_id.to_string(),
+ channel_name: channel_name.to_string(),
+ caller_name: caller_name.to_string(),
+ livekit_server_url: Some(livekit_server_url.to_string()),
+ livekit_token: Some(livekit_token),
+ },
+ )),
+ Err(e) => {
+ tracing::error!(
+ error=?e,
+ "failed to mint LiveKit token for VoIP push"
+ );
+ None
+ }
+ }
+ }
+ }))
+ .await;
+ payloads.extend(results.into_iter().flatten());
+ }
+
+ payloads
+ }
+
#[tracing::instrument(err, skip(self))]
async fn remove_participant(
&self,
diff --git a/rust/cloud-storage/notification/src/domain/models.rs b/rust/cloud-storage/notification/src/domain/models.rs
index 0280a801bd..f10b3722c2 100644
--- a/rust/cloud-storage/notification/src/domain/models.rs
+++ b/rust/cloud-storage/notification/src/domain/models.rs
@@ -35,6 +35,15 @@ pub struct NotificationIdAndCollapseKey {
pub apns_collapse_key: String,
}
+/// Recipient/endpoints pair resolved before LiveKit token minting.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct VoipPushTarget {
+ /// Recipient whose VoIP-capable endpoints were resolved.
+ pub recipient_id: MacroUserIdStr<'static>,
+ /// SNS endpoints registered for APNS_VOIP delivery.
+ pub endpoint_arns: Vec<String>,
+}
+
/// A compact patch describing user notification status fields that changed.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotificationStatusPatch {
diff --git a/rust/cloud-storage/notification/src/domain/models/apple.rs b/rust/cloud-storage/notification/src/domain/models/apple.rs
index ee49f1c86c..344ef6c96c 100644
--- a/rust/cloud-storage/notification/src/domain/models/apple.rs
+++ b/rust/cloud-storage/notification/src/domain/models/apple.rs
@@ -181,6 +181,12 @@ pub struct VoipPushPayload {
pub channel_name: String,
/// Display name of the caller shown in the CallKit incoming-call UI.
pub caller_name: String,
+ /// LiveKit websocket URL for native lock-screen answers.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub livekit_server_url: Option<String>,
+ /// Recipient-specific LiveKit JWT for native lock-screen answers.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub livekit_token: Option<String>,
}
/// the value we send as the payload in the ios notification
diff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rs
index 5c9a42f72e..2cb3a76311 100644
--- a/rust/cloud-storage/notification/src/domain/ports.rs
+++ b/rust/cloud-storage/notification/src/domain/ports.rs
@@ -22,7 +22,7 @@ use crate::domain::models::email_notification_digest::ports::{ClaimResult, Diges
use crate::domain::models::request::NotificationListFilters;
use crate::domain::models::{
DeviceEndpoint, DisabledNotificationType, NotificationExtEmail, NotificationIdAndCollapseKey,
- NotificationStatusPatch, SendNotificationRequestBuilder, UserNotificationRow,
+ NotificationStatusPatch, SendNotificationRequestBuilder, UserNotificationRow, VoipPushTarget,
android::FCMMessage,
apple::{APNSPushNotification, VoipPushPayload},
mobile::MessageAttributes,
@@ -409,35 +409,56 @@ pub trait NotificationIngressQueue: Send + Sync + 'static {
/// immediately without DB persistence and wake the app via PushKit so that
/// CallKit can display the native incoming-call UI.
pub trait VoipPushSender: Send + Sync + 'static {
- /// Send a VoIP push to all registered VoIP device endpoints of the given users.
+ /// Batch-resolve VoIP endpoints before the caller mints per-recipient tokens.
+ fn get_voip_push_targets(
+ &self,
+ recipient_ids: &[MacroUserIdStr<'_>],
+ ) -> impl Future<Output = Result<Vec<VoipPushTarget>, Report>> + Send;
+
+ /// Send recipient-specific payloads to already-resolved VoIP endpoints.
///
/// Errors are logged but do not propagate. The returned set contains users
/// that received at least one successful VoIP push delivery.
- fn send_voip_push(
+ fn send_voip_pushes(
&self,
- recipient_ids: &[MacroUserIdStr<'_>],
- payload: &VoipPushPayload,
+ pushes: Vec<(VoipPushTarget, VoipPushPayload)>,
) -> impl std::future::Future<Output = HashSet<MacroUserIdStr<'static>>> + Send;
}
impl VoipPushSender for () {
- async fn send_voip_push(
+ async fn get_voip_push_targets(
&self,
_: &[MacroUserIdStr<'_>],
- _: &VoipPushPayload,
+ ) -> Result<Vec<VoipPushTarget>, Report> {
+ Ok(Vec::new())
+ }
+
+ async fn send_voip_pushes(
+ &self,
+ _: Vec<(VoipPushTarget, VoipPushPayload)>,
) -> HashSet<MacroUserIdStr<'static>> {
HashSet::new()
}
}
impl<V: VoipPushSender> VoipPushSender for Option<V> {
- async fn send_voip_push(
+ async fn get_voip_push_targets(
&self,
recipient_ids: &[MacroUserIdStr<'_>],
- payload: &VoipPushPayload,
+ ) -> Result<Vec<VoipPushTarget>, Report> {
+ if let Some(inner) = self {
+ inner.get_voip_push_targets(recipient_ids).await
+ } else {
+ Ok(Vec::new())
+ }
+ }
+
+ async fn send_voip_pushes(
+ &self,
+ pushes: Vec<(VoipPushTarget, VoipPushPayload)>,
) -> HashSet<MacroUserIdStr<'static>> {
if let Some(inner) = self {
- inner.send_voip_push(recipient_ids, payload).await
+ inner.send_voip_pushes(pushes).await
} else {
HashSet::new()
}
diff --git a/rust/cloud-storage/notification/src/domain/service/voip.rs b/rust/cloud-storage/notification/src/domain/service/voip.rs
index 27a25926d3..277b41b1d5 100644
--- a/rust/cloud-storage/notification/src/domain/service/voip.rs
+++ b/rust/cloud-storage/notification/src/domain/service/voip.rs
@@ -6,27 +6,28 @@
#[cfg(test)]
mod test;
-use std::collections::HashSet;
-
+use futures::future;
use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+use std::collections::HashSet;
+use crate::domain::models::VoipPushTarget;
use crate::domain::models::apple::VoipPushPayload;
use crate::domain::models::mobile::DeviceEndpoint;
use crate::domain::ports::{NotificationRepository, VoipPushSender};
use crate::outbound::mobile::MobilePushAdapter;
use crate::outbound::mobile::MobilePushOps;
-/// Concrete implementation of [`VoipPushSender`].
-///
-/// Looks up VoIP device endpoints from the repository, then dispatches each
-/// push directly via SNS APNS_VOIP — no queue, no persistence.
+const VOIP_PUSH_DELIVERY_CONCURRENCY: usize = 32;
+
+/// Direct APNS_VOIP sender for CallKit pushes.
pub struct VoipPushServiceImpl<R, P> {
repository: R,
mobile: MobilePushAdapter<P>,
}
impl<R, P> VoipPushServiceImpl<R, P> {
- /// Create a new [`VoipPushServiceImpl`].
+ /// Builds a sender that resolves endpoints through the repository and delivers through SNS.
pub fn new(repository: R, mobile: MobilePushAdapter<P>) -> Self {
Self { repository, mobile }
}
@@ -37,40 +38,68 @@ where
R: NotificationRepository,
P: MobilePushOps + Send + Sync + 'static,
{
- async fn send_voip_push(
+ async fn get_voip_push_targets(
&self,
recipient_ids: &[MacroUserIdStr<'_>],
- payload: &VoipPushPayload,
+ ) -> Result<Vec<VoipPushTarget>, Report> {
+ let device_map = self.repository.get_device_endpoints(recipient_ids).await?;
+
+ Ok(device_map
+ .into_iter()
+ .filter_map(|(recipient_id, endpoints)| {
+ let endpoint_arns: Vec<String> = endpoints
+ .into_iter()
+ .filter_map(|endpoint| match endpoint {
+ DeviceEndpoint::IosVoip(arn) => Some(arn),
+ _ => None,
+ })
+ .collect();
+
+ (!endpoint_arns.is_empty()).then_some(VoipPushTarget {
+ recipient_id,
+ endpoint_arns,
+ })
+ })
+ .collect())
+ }
+
+ async fn send_voip_pushes(
+ &self,
+ pushes: Vec<(VoipPushTarget, VoipPushPayload)>,
) -> HashSet<MacroUserIdStr<'static>> {
- let device_map = match self.repository.get_device_endpoints(recipient_ids).await {
- Ok(m) => m,
- Err(e) => {
- tracing::error!(error=?e, "voip push: failed to fetch device endpoints");
- return HashSet::new();
- }
- };
+ let jobs: Vec<(MacroUserIdStr<'static>, String, VoipPushPayload)> = pushes
+ .into_iter()
+ .flat_map(|(target, payload)| {
+ let recipient_id = target.recipient_id;
+ target
+ .endpoint_arns
+ .into_iter()
+ .map(move |arn| (recipient_id.clone(), arn, payload.clone()))
+ })
+ .collect();
- let mut delivered_user_ids = HashSet::new();
- for (user_id, endpoints) in &device_map {
- for endpoint in endpoints {
- let DeviceEndpoint::IosVoip(arn) = endpoint else {
- continue;
- };
- match self.mobile.send_voip_push(arn, payload).await {
- Ok(_) => {
- delivered_user_ids.insert(user_id.clone());
- }
- Err(e) => {
- tracing::error!(
- error=?e,
- user_id=%user_id,
- "voip push: SNS delivery failed"
- );
+ let mut delivered = HashSet::new();
+ for batch in jobs.chunks(VOIP_PUSH_DELIVERY_CONCURRENCY) {
+ let results = future::join_all(batch.iter().map(|(user_id, arn, payload)| {
+ let user_id = user_id.clone();
+ async move {
+ let mobile = &self.mobile;
+ match mobile.send_voip_push(arn, payload).await {
+ Ok(_) => Some(user_id),
+ Err(e) => {
+ tracing::error!(
+ error=?e,
+ "voip push: SNS delivery failed"
+ );
+ None
+ }
}
}
- }
+ }))
+ .await;
+ delivered.extend(results.into_iter().flatten());
}
- delivered_user_ids
+ delivered
}
}
diff --git a/rust/cloud-storage/notification/src/domain/service/voip/test.rs b/rust/cloud-storage/notification/src/domain/service/voip/test.rs
index 9a68603f61..dd2dc32623 100644
--- a/rust/cloud-storage/notification/src/domain/service/voip/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/voip/test.rs
@@ -26,6 +26,8 @@ fn payload() -> VoipPushPayload {
channel_id: "ch-1".to_string(),
channel_name: "general".to_string(),
caller_name: "Alice".to_string(),
+ livekit_server_url: Some("wss://livekit.example".to_string()),
+ livekit_token: Some("test-token".to_string()),
}
}
@@ -282,12 +284,21 @@ async fn dispatches_to_ios_voip_endpoint() {
push,
);
+ let targets = svc
+ .get_voip_push_targets(&[user("[email protected]")])
+ .await
+ .unwrap();
+ assert_eq!(targets.len(), 1);
+
let result = svc
- .send_voip_push(&[user("[email protected]")], &payload())
+ .send_voip_pushes(vec![(targets[0].clone(), payload())])
.await;
assert_eq!(*calls.lock().unwrap(), vec!["arn:voip-alice"]);
- assert!(result.contains(&user("[email protected]")));
+ assert_eq!(
+ result,
+ std::collections::HashSet::from([user("[email protected]")])
+ );
}
#[tokio::test]
@@ -304,56 +315,26 @@ async fn skips_non_voip_endpoints() {
push,
);
- let result = svc
- .send_voip_push(&[user("[email protected]")], &payload())
- .await;
+ let targets = svc
+ .get_voip_push_targets(&[user("[email protected]")])
+ .await
+ .unwrap();
+ assert!(targets.is_empty());
assert!(calls.lock().unwrap().is_empty());
- assert!(result.is_empty());
}
#[tokio::test]
-async fn sends_to_multiple_recipients() {
- let (push, calls) = tracked_push();
- let svc = make_service(
- MockRepo::with_endpoints(HashMap::from([
- (
- vec![DeviceEndpoint::IosVoip("arn:voip-alice".to_string())],
- ),
- (
- vec![DeviceEndpoint::IosVoip("arn:voip-bob".to_string())],
- ),
- ])),
- push,
- );
-
- let result = svc
- .send_voip_push(
- &[user("[email protected]"), user("[email protected]")],
- &payload(),
- )
- .await;
-
- let mut recorded = calls.lock().unwrap().clone();
- recorded.sort();
- assert_eq!(recorded, vec!["arn:voip-alice", "arn:voip-bob"]);
- assert!(result.contains(&user("[email protected]")));
- assert!(result.contains(&user("[email protected]")));
-}
-
-#[tokio::test]
-async fn repo_error_does_not_panic() {
+async fn repo_error_is_propagated() {
let (push, calls) = tracked_push();
let svc = make_service(MockRepo::failing(), push);
let result = svc
- .send_voip_push(&[user("[email protected]")], &payload())
+ .get_voip_push_targets(&[user("[email protected]")])
.await;
+ assert!(result.is_err());
assert!(calls.lock().unwrap().is_empty());
- assert!(result.is_empty());
}
#[tokio::test]
@@ -366,8 +347,12 @@ async fn sns_failure_does_not_panic() {
MockPush::failing(),
);
+ let targets = svc
+ .get_voip_push_targets(&[user("[email protected]")])
+ .await
+ .unwrap();
let result = svc
- .send_voip_push(&[user("[email protected]")], &payload())
+ .send_voip_pushes(vec![(targets[0].clone(), payload())])
.await;
assert!(result.is_empty());