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.

9.3 KB
Raw Blame
//! Mobile push notification adapter.

use aws_sdk_sns::operation::publish::PublishError;
use aws_sdk_sns::types::MessageAttributeValue;
use rootcause::Report;
use serde::Serialize;
use std::collections::HashMap;

use crate::domain::models::android::FCMMessage;
use crate::domain::models::apple::{APNSPushNotification, VoipPushPayload};
use crate::domain::models::mobile::{MessageAttributes, PushEndpointUnavailable, PushType};
use crate::domain::ports::NotificationSender;

mod payload;
pub use payload::SnsTarget;

#[cfg(test)]
mod test;

/// Mobile push notification adapter.
///
/// This adapter sends push notifications to mobile devices via APNS (iOS)
/// and FCM (Android) through SNS.
pub struct MobilePushAdapter<P> {
    /// Push service implementation used to send SNS messages.
    pub push_service: P,
    /// APNS topic / bundle ID for regular iOS push notifications.
    pub apns_bundle_id: String,
    /// Set to `<bundle_id>.voip` when VoIP push is configured.
    pub voip_bundle_id: Option<String>,
}

/// Trait for mobile push service operations via SNS.
///
/// This allows the adapter to work with different SNS client implementations.
pub trait MobilePushOps {
    /// Send a push notification to the specified endpoint ARN using a typed SNS target.
    ///
    /// Returns the SNS message ID on success.
    fn push_notification<T: Serialize + Send + Sync>(
        &self,
        endpoint_arn: &str,
        message: &SnsTarget<'_, T>,
        attributes: HashMap<String, MessageAttributeValue>,
    ) -> impl std::future::Future<Output = Result<String, Report>> + Send;
}

impl MobilePushOps for aws_sdk_sns::Client {
    async fn push_notification<T: Serialize + Send + Sync>(
        &self,
        endpoint_arn: &str,
        message: &SnsTarget<'_, T>,
        attributes: HashMap<String, MessageAttributeValue>,
    ) -> Result<String, Report> {
        let payload = message.as_json()?;
        let output = self
            .publish()
            .target_arn(endpoint_arn)
            .message_structure("json")
            .message(payload)
            .set_message_attributes(Some(attributes))
            .send()
            .await
            .map_err(|e| {
                let report = rootcause::report!(
                    "SNS publish to {endpoint_arn} failed: {}",
                    aws_sdk_sns::error::DisplayErrorContext(&e)
                );
                if e.as_service_error().is_some_and(is_unavailable_endpoint) {
                    report.context(PushEndpointUnavailable).into_dynamic()
                } else {
                    report
                }
            })?;

        Ok(output.message_id.unwrap_or_default())
    }
}

/// Whether SNS rejected the publish because the target endpoint can no longer receive pushes,
/// as opposed to a problem with the message or the platform application.
fn is_unavailable_endpoint(err: &PublishError) -> bool {
    match err {
        PublishError::EndpointDisabledException(_) | PublishError::NotFoundException(_) => true,
        PublishError::InvalidParameterException(e) => e
            .message()
            .is_some_and(|message| message.contains("No endpoint found")),
        _ => false,
    }
}

impl<P: MobilePushOps + Send + Sync + 'static> NotificationSender for MobilePushAdapter<P> {
    async fn send_ios_push_notification<T: Serialize + Send + Sync>(
        &self,
        endpoint_arn: &str,
        notification: &APNSPushNotification<T>,
        attributes: &MessageAttributes,
    ) -> Result<String, Report> {
        let target = SnsTarget::Ios(notification);
        let sns_attributes = build_sns_attributes(&self.apns_bundle_id, attributes);
        self.push_service
            .push_notification(endpoint_arn, &target, sns_attributes)
            .await
    }

    async fn send_android_push_notification<T: Serialize + Send + Sync>(
        &self,
        endpoint_arn: &str,
        notification: &FCMMessage<T>,
        _attributes: &MessageAttributes,
    ) -> Result<String, Report> {
        let target = SnsTarget::Android(notification);
        self.push_service
            .push_notification(endpoint_arn, &target, HashMap::new())
            .await
    }
}

impl<P: MobilePushOps + Send + Sync + 'static> MobilePushAdapter<P> {
    /// Send a VoIP push notification via APNS_VOIP.
    ///
    /// Bypasses the normal notification pipeline — sent immediately without
    /// DB persistence. Wakes the app via PushKit so CallKit can report an
    /// incoming call.
    #[tracing::instrument(name = "call.push.send", err, skip_all, fields(call.id = %payload.call_id, otel.kind = "producer"))]
    pub async fn send_voip_push(
        &self,
        endpoint_arn: &str,
        recipient_id: &macro_user_id::user_id::MacroUserIdStr<'_>,
        payload: &VoipPushPayload,
    ) -> Result<String, Report> {
        if endpoint_arn.contains(":endpoint/GCM/") {
            let recipient = recipient_id.to_string();
            let target: SnsTarget<'_, ()> = SnsTarget::AndroidCall(payload, &recipient);
            return self
                .push_service
                .push_notification(endpoint_arn, &target, HashMap::new())
                .await;
        }
        let voip_bundle_id = self.voip_bundle_id.as_deref().ok_or_else(|| {
            rootcause::report!("voip_bundle_id not configured on MobilePushAdapter")
        })?;

        let target: SnsTarget<'_, ()> = SnsTarget::Voip(payload);
        let attrs = build_voip_sns_attributes(voip_bundle_id);
        self.push_service
            .push_notification(endpoint_arn, &target, attrs)
            .await
    }
}

/// Build SNS message attributes for a regular APNS notification.
fn build_sns_attributes(
    apns_bundle_id: &str,
    attributes: &MessageAttributes,
) -> HashMap<String, MessageAttributeValue> {
    let push_type_str = match attributes.push_type {
        PushType::Background => "background",
        PushType::Alert => "alert",
    };

    HashMap::from([
        (
            "AWS.SNS.MOBILE.APNS.TOPIC".to_string(),
            MessageAttributeValue::builder()
                .data_type("String")
                .string_value(apns_bundle_id)
                .build()
                .expect("valid attribute"),
        ),
        (
            "AWS.SNS.MOBILE.APNS.PUSH_TYPE".to_string(),
            MessageAttributeValue::builder()
                .data_type("String")
                .string_value(push_type_str)
                .build()
                .expect("valid attribute"),
        ),
        (
            "AWS.SNS.MOBILE.APNS.PRIORITY".to_string(),
            MessageAttributeValue::builder()
                .data_type("String")
                .string_value("5")
                .build()
                .expect("valid attribute"),
        ),
        (
            "AWS.SNS.MOBILE.APNS.COLLAPSE_ID".to_string(),
            MessageAttributeValue::builder()
                .data_type("String")
                .string_value(&attributes.collapse_key)
                .build()
                .expect("valid attribute"),
        ),
    ])
}

/// Build SNS message attributes for a VoIP (APNS_VOIP) notification.
fn build_voip_sns_attributes(voip_bundle_id: &str) -> HashMap<String, MessageAttributeValue> {
    HashMap::from([
        (
            "AWS.SNS.MOBILE.APNS.TOPIC".to_string(),
            MessageAttributeValue::builder()
                .data_type("String")
                .string_value(voip_bundle_id)
                .build()
                .expect("valid attribute"),
        ),
        (
            "AWS.SNS.MOBILE.APNS.PUSH_TYPE".to_string(),
            MessageAttributeValue::builder()
                .data_type("String")
                .string_value("voip")
                .build()
                .expect("valid attribute"),
        ),
        (
            "AWS.SNS.MOBILE.APNS.PRIORITY".to_string(),
            MessageAttributeValue::builder()
                .data_type("String")
                .string_value("10")
                .build()
                .expect("valid attribute"),
        ),
        // TTL is the one SNS attribute that is named per platform application
        // (unlike TOPIC/PUSH_TYPE/PRIORITY, which are shared across APNs
        // platforms). `AWS.SNS.MOBILE.APNS.TTL` is silently ignored on
        // APNS_VOIP endpoints, leaving the SNS default of 4 weeks — APNs then
        // stores the push while the device is unreachable and replays a dead
        // call ring when it reconnects. TTL 0 means "deliver now or drop".
        (
            "AWS.SNS.MOBILE.APNS_VOIP.TTL".to_string(),
            MessageAttributeValue::builder()
                .data_type("String")
                .string_value("0")
                .build()
                .expect("valid attribute"),
        ),
        (
            "AWS.SNS.MOBILE.APNS_VOIP_SANDBOX.TTL".to_string(),
            MessageAttributeValue::builder()
                .data_type("String")
                .string_value("0")
                .build()
                .expect("valid attribute"),
        ),
    ])
}

impl<P: MobilePushOps + Send + Sync + 'static> crate::domain::ports::VoipPushDelivery
    for MobilePushAdapter<P>
{
    async fn send_voip_push(
        &self,
        endpoint_arn: &str,
        recipient_id: &macro_user_id::user_id::MacroUserIdStr<'_>,
        payload: &VoipPushPayload,
    ) -> Result<String, Report> {
        MobilePushAdapter::send_voip_push(self, endpoint_arn, recipient_id, payload).await
    }
}