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.

15.4 KB
Raw Blame
//! Domain models for the notification service.

pub mod android;
pub mod apple;
pub mod device;
pub mod email_notification_digest;
pub mod entity_query;
pub mod mobile;
pub mod push_notification_event;
pub mod queue_message;
pub mod rate_limit;
pub mod recipient;
pub mod request;
/// Cryptographic URL signing and verification.
pub mod signing;
/// Broker event models for WebSocket notification delivery.
pub mod websocket_notification_event;

use crate::domain::models::{apple::APNSPushNotification, queue_message::EmailContent};
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
pub use mobile::{DeviceEndpoint, HashedCollapseKey, NotifCollapseKey};
use model_entity::Entity;
use models_pagination::{CreatedAt, CursorVal, Identify, SortOn};
pub use notification_state::{NotificationAction, NotificationState};
pub use rate_limit::{RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitResult};
pub use recipient::{ExclusionReason, FilteredRecipient, RecipientExclusion};
pub use request::{NotificationResult, SendNotificationRequest, SendNotificationRequestBuilder};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::{borrow::Cow, collections::HashSet, sync::Arc};
use uuid::Uuid;

/// Notification ID paired with its APNS collapse key, for push clearing.
#[derive(Debug, Clone)]
pub struct NotificationIdAndCollapseKey {
    /// The notification ID.
    pub id: uuid::Uuid,
    /// The APNS collapse key used to identify the push notification to clear.
    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>,
    /// Registered mobile endpoints, retaining ordinary devices for fallback decisions.
    pub endpoints: Vec<DeviceEndpoint>,
}

/// Recipients grouped by mobile platform for delivery or exclusion.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct MobilePushRecipients {
    /// Users whose iOS devices are included.
    pub ios: HashSet<MacroUserIdStr<'static>>,
    /// Users whose Android devices are included.
    pub android: HashSet<MacroUserIdStr<'static>>,
}

/// Native call delivery results used to select ordinary mobile fallbacks.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct NativeCallPushResult {
    /// Users with a successful native delivery on each platform.
    pub delivered: MobilePushRecipients,
    /// Users whose registered mobile platforms were all handled natively.
    pub fully_delivered: HashSet<MacroUserIdStr<'static>>,
}

/// A compact patch describing user notification status fields that changed.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotificationStatusPatch {
    /// The authoritative notification state after the update.
    pub state: NotificationState,
    /// When the notification was viewed/seen after the update.
    pub viewed_at: Option<DateTime<Utc>>,
    /// The time this status change was persisted.
    pub updated_at: DateTime<Utc>,
}

/// A patch-or-delete update for an entity identified by `I`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "t", content = "c")]
pub enum PatchDelete<I, T> {
    /// The value with id I should be patched with data T.
    Patch {
        /// The data to patch, including its identifier.
        #[serde(flatten)]
        diff: T,
    },
    /// The value with id I should be deleted.
    Delete {
        /// The id to delete.
        id: I,
    },
}

/// A deletion update for an entity identified by `I`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "t", content = "c")]
pub enum NotificationDelete<I> {
    /// The value with id `I` should be deleted.
    Delete {
        /// The id to delete.
        id: I,
    },
}

/// A user-scoped notification update delivered to realtime subscribers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NotificationSubscriptionUpdate<T> {
    /// A notification was newly delivered to the user.
    New(Arc<UserNotificationRow<T>>),
    /// An existing notification was updated.
    Updated(Arc<UserNotificationRow<T>>),
    /// A notification should be removed from the normalized cache.
    Deleted(Uuid),
}

/// Realtime payload emitted when notification seen/done state changes.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NotificationStatusUpdate<'a> {
    /// Constant event discriminator for frontend consumers.
    #[serde(rename = "type")]
    pub event_type: String,
    /// The changed notification rows.
    pub updates: Vec<PatchDelete<Uuid, Cow<'a, UserNotificationRow<serde_json::Value>>>>,
}

/// A realtime notification status update with explicit user/notification cardinality.
#[derive(Debug, Clone)]
pub enum NotificationStatusPayload<'a> {
    /// One notification deletion applied to many users.
    NotificationForUsers {
        /// Users who should receive the deletion.
        users: Vec<MacroUserIdStr<'a>>,
        /// The notification deletion shared by the users.
        update: Box<NotificationDelete<Uuid>>,
    },
    /// Many notification updates applied to one user.
    UserNotifications {
        /// User who should receive the updates.
        user: MacroUserIdStr<'a>,
        /// Notification patches and deletions for the user.
        updates: Vec<PatchDelete<Uuid, Cow<'a, UserNotificationRow<serde_json::Value>>>>,
    },
}

impl<'a> NotificationStatusUpdate<'a> {
    /// The connection-gateway message type for notification status changes.
    pub const MESSAGE_TYPE: &'static str = "notification_status_updated";

    /// Build a realtime status update payload.
    pub fn new(
        updates: Vec<PatchDelete<Uuid, Cow<'a, UserNotificationRow<serde_json::Value>>>>,
    ) -> Self {
        Self {
            event_type: Self::MESSAGE_TYPE.to_string(),
            updates,
        }
    }
}

/// A row from the `user_notification` + `notification` join query.
///
/// The metadata field is generic so callers can deserialize it into
/// whatever type they need without this crate depending on the caller's models.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UserNotificationRow<T> {
    /// The user who owns this notification.
    pub owner_id: MacroUserIdStr<'static>,
    /// The notification ID.
    #[serde(rename = "id")]
    pub notification_id: uuid::Uuid,
    /// The notification event type string (e.g. "channel_mention").
    /// TODO make this a new type
    pub notification_event_type: String,
    /// The entity the notification is about.
    #[serde(flatten)]
    pub entity: Entity<'static>,
    /// Whether the notification has been sent.
    pub sent: bool,
    /// The authoritative lifecycle state, independent of viewing timestamps.
    pub state: NotificationState,
    /// When the notification was created.
    pub created_at: DateTime<Utc>,
    /// When the notification was viewed/seen.
    pub viewed_at: Option<DateTime<Utc>>,
    /// When the notification was last updated.
    pub updated_at: DateTime<Utc>,
    /// When the notification was deleted.
    pub deleted_at: Option<DateTime<Utc>>,
    /// Deserialized notification metadata.
    pub notification_metadata: T,
    /// The user who triggered the notification.
    pub sender_id: Option<MacroUserIdStr<'static>>,
}

impl<T> UserNotificationRow<T> {
    /// Map the inner T to some U.
    pub fn map<F, U>(self, f: F) -> UserNotificationRow<U>
    where
        F: FnOnce(T) -> U,
    {
        let UserNotificationRow {
            owner_id,
            notification_id,
            notification_event_type,
            entity,
            sent,
            state,
            created_at,
            viewed_at,
            updated_at,
            deleted_at,
            notification_metadata,
            sender_id,
        } = self;

        UserNotificationRow {
            owner_id,
            notification_id,
            notification_event_type,
            entity,
            sent,
            state,
            created_at,
            viewed_at,
            updated_at,
            deleted_at,
            notification_metadata: f(notification_metadata),
            sender_id,
        }
    }

    /// Map the inner T to some U, with a fallible mapping function.
    pub fn try_map<F, U, E>(self, f: F) -> Result<UserNotificationRow<U>, E>
    where
        F: FnOnce(T) -> Result<U, E>,
    {
        let UserNotificationRow {
            owner_id,
            notification_id,
            notification_event_type,
            entity,
            sent,
            state,
            created_at,
            viewed_at,
            updated_at,
            deleted_at,
            notification_metadata,
            sender_id,
        } = self;

        Ok(UserNotificationRow {
            owner_id,
            notification_id,
            notification_event_type,
            entity,
            sent,
            state,
            created_at,
            viewed_at,
            updated_at,
            deleted_at,
            notification_metadata: f(notification_metadata)?,
            sender_id,
        })
    }

    /// create a notification typename from this row.
    /// This is dangerous because the compiler cannot assert that the T: Notification
    pub(crate) fn dangerous_get_typename(&self) -> NotificationTypeName {
        NotificationTypeName(Cow::Owned(self.notification_event_type.clone()))
    }
}

/// newtype wrapper for the the typename of a Notification
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(transparent)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
pub(crate) struct NotificationTypeName(Cow<'static, str>);

impl NotificationTypeName {
    pub(crate) fn new_from_notif<T: Notification>(_v: &T) -> Self {
        NotificationTypeName(Cow::Borrowed(T::TYPE_NAME))
    }
}

impl AsRef<str> for NotificationTypeName {
    fn as_ref(&self) -> &str {
        self.0.as_ref()
    }
}

/// A notification metadata value tagged with the notification event type.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
pub struct TaggedContent<T> {
    pub(crate) tag: NotificationTypeName,
    pub(crate) content: T,
}

impl<T: Notification> TaggedContent<Arc<T>> {
    /// create a new value from a notification T
    pub fn new_arc(val: Arc<T>) -> Self {
        TaggedContent {
            tag: NotificationTypeName::new_from_notif(&*val),
            content: val,
        }
    }
}

impl<T: Notification> TaggedContent<T> {
    /// create a new value from a notification T
    pub fn new(val: T) -> Self {
        TaggedContent {
            tag: NotificationTypeName::new_from_notif(&val),
            content: val,
        }
    }
}

impl UserNotificationRow<serde_json::Value> {
    /// Deserialize the row's tagged metadata without cloning or consuming the row.
    pub fn deserialize_metadata_ref<T: DeserializeOwned>(&self) -> Result<T, serde_json::Error> {
        let mut encoded = Vec::new();
        {
            let mut serializer = serde_json::Serializer::new(&mut encoded);
            let mut map = serde::Serializer::serialize_map(&mut serializer, Some(2))?;
            serde::ser::SerializeMap::serialize_entry(
                &mut map,
                "tag",
                &self.notification_event_type,
            )?;
            serde::ser::SerializeMap::serialize_entry(
                &mut map,
                "content",
                &self.notification_metadata,
            )?;
            serde::ser::SerializeMap::end(map)?;
        }
        serde_json::from_slice(&encoded)
    }

    /// Wrap the raw JSON metadata in a [`TaggedContent`] using the row's
    /// `notification_event_type` as the tag. This produces the adjacently-tagged
    /// shape produced by [`UserNotificationRow::into_tagged`] +
    /// [`UserNotificationRow::into_json`].
    pub fn into_tagged(self) -> UserNotificationRow<TaggedContent<serde_json::Value>> {
        let tag = self.notification_event_type.clone();
        self.map(|v| TaggedContent {
            tag: NotificationTypeName(Cow::Owned(tag)),
            content: v,
        })
    }
}

impl TaggedContent<serde_json::Value> {
    /// Deserialize the adjacently-tagged content directly into `T` without
    /// an intermediate serialization roundtrip.
    pub fn deserialize<T: DeserializeOwned>(self) -> Result<T, serde_json::Error> {
        let val = serde_json::json!({
            "tag": self.tag,
            "content": self.content,
        });
        serde_json::from_value(val)
    }
}

impl UserNotificationRow<TaggedContent<serde_json::Value>> {
    /// Deserialize the adjacently-tagged metadata into a concrete type `T`.
    pub fn deserialize_metadata<T: DeserializeOwned>(
        self,
    ) -> Result<UserNotificationRow<T>, serde_json::Error> {
        self.try_map(|tagged| tagged.deserialize())
    }
}

impl<T> Identify for UserNotificationRow<T> {
    type Id = uuid::Uuid;
    fn id(&self) -> Self::Id {
        self.notification_id
    }
}

impl<T> SortOn<CreatedAt> for UserNotificationRow<T> {
    fn sort_on(sort: CreatedAt) -> impl FnMut(&Self) -> CursorVal<CreatedAt> {
        move |v| {
            let last_val = v.created_at;
            CursorVal {
                sort_type: sort,
                last_val,
            }
        }
    }
}

/// A notification type that a user has disabled.
///
/// Presence of a row means the user has opted out of this type.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DisabledNotificationType {
    /// The user who disabled this type.
    pub user_id: MacroUserIdStr<'static>,
    /// The notification event type (e.g. "channel_message_send").
    pub notification_event_type: String,
}

/// Trait that all notification types must implement.
pub trait Notification: Serialize + DeserializeOwned + Send + Sync + 'static {
    /// The type name of this notification.
    const TYPE_NAME: &'static str;
}

/// Extension trait for notifications that can be delivered via email.
pub trait NotificationExtEmail: Notification {
    /// Convert this notification into email content.
    fn format_email(&self) -> EmailContent;

    /// The configuration for how often the notification can be triggered on a certain key.
    fn rate_limit_config() -> RateLimitConfig;
    /// The actual key for the rate limit bucket.
    fn rate_limit_key(&self) -> RateLimitKey;
}

/// Extension trait for notifications that have a user-facing title and body.
///
/// Used for formatting push notification alerts (APNS) and notification previews.
pub trait NotificationTitle {
    /// Format the notification into a user-facing title.
    fn format_title(
        &self,
        sender_id: Option<MacroUserIdStr<'_>>,
    ) -> Result<String, rootcause::Report>;

    /// Format the notification into a user-facing body.
    fn format_body(
        &self,
        sender_id: Option<MacroUserIdStr<'_>>,
    ) -> Result<String, rootcause::Report>;
}

/// Extension trait for notifications that can be delivered via iOS push (APNS).
pub trait NotificationExtIos: Notification {
    /// The custom data type included in the APNS push notification payload.
    type NotifData: Send;
    /// Build the collapse key for this push notification.
    fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey;
    /// Convert this notification into an APNS push notification.
    fn as_apns<'a>(
        &self,
        sender_id: Option<MacroUserIdStr<'a>>,
        entity: &Entity<'_>,
        notification_id: uuid::Uuid,
    ) -> Option<APNSPushNotification<Self::NotifData>>;
}