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(notification): better collapse + testing (#904)
Sean Ayee2f4c78cc751
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex e795d90ed1..969ce75ac0 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -128,7 +128,7 @@ aws-sdk-s3 = "1.119.0"aws-sdk-secretsmanager = "1.93.0"aws-sdk-sesv2 = "1.103.0"aws-sdk-sns = "1.61.0"-aws-sdk-sqs = "1.89.0"+aws-sdk-sqs = "1.91.0"aws-smithy-types = "1.2.13"aws_lambda_events = { version = "0.16.0", default-features = false }axum = { version = "0.7.9", features = [diff --git a/rust/cloud-storage/model_notifications/src/lib.rs b/rust/cloud-storage/model_notifications/src/lib.rsindex e2365fbb64..261cda33f4 100644--- a/rust/cloud-storage/model_notifications/src/lib.rs+++ b/rust/cloud-storage/model_notifications/src/lib.rs@@ -4,6 +4,7 @@ use macro_user_id::user_id::MacroUserIdStr;use model_entity::Entity;use models_pagination::{CreatedAt, Identify, SortOn};use serde::{Deserialize, Serialize};+use std::hash::{DefaultHasher, Hash, Hasher};use strum::{Display, EnumDiscriminants, EnumString};use utoipa::ToSchema;mod device;@@ -16,7 +17,11 @@ pub use raw::*;pub use unsubscribe::*;use uuid::Uuid;+#[cfg(test)]+mod tests;+#[derive(Debug, Clone, Serialize, Deserialize, EnumDiscriminants, ToSchema)]+#[deny(missing_docs)]#[strum_discriminants(name(NotificationEventType))]#[strum_discriminants(derive(Serialize, Deserialize, ToSchema, EnumString, Display))]#[strum_discriminants(serde(rename_all = "snake_case"))]@@ -26,6 +31,7 @@ use uuid::Uuid;content = "notificationMetadata",rename_all = "snake_case")]+/// The types of events that the notification system is aware ofpub enum NotificationEvent {/// An Item was shared with a specific userItemSharedUser(ItemSharedMetadata),@@ -164,6 +170,76 @@ pub struct UserNotification {pub notification_event: NotificationEvent,}+impl UserNotification {+ pub fn build_key(&self) -> NotifCollapseKey {+ match &self.notification_event {+ NotificationEvent::ChannelMention(channel_mention_metadata) => {+ NotifCollapseKey::new(&channel_mention_metadata.message_id)+ }+ NotificationEvent::ChannelMessageSend(channel_message_send_metadata) => {+ NotifCollapseKey::new(&channel_message_send_metadata.message_id)+ }+ NotificationEvent::ChannelMessageReply(channel_reply_metadata) => {+ NotifCollapseKey::new(&channel_reply_metadata.message_id)+ }+ NotificationEvent::ItemSharedOrganization(_)+ | NotificationEvent::DocumentMention(_)+ | NotificationEvent::ChannelInvite(_)+ | NotificationEvent::ChannelMessageDocument(_)+ | NotificationEvent::ItemSharedUser(_)+ | NotificationEvent::RejectTeamInvite+ | NotificationEvent::NewEmail(_)+ | NotificationEvent::InviteToTeam(_)+ | NotificationEvent::TaskAssigned(_) => {+ let entity_type: &'static str = self.notification_entity.entity_type.into();+ NotifCollapseKey::new(entity_type).append(&self.notification_entity.entity_id)+ }+ }+ }+}++/// used to build up the data to construct a [HashedCollapseKey]+pub struct NotifCollapseKey(DefaultHasher);++/// contains the string representation of a notification collapse key+/// this is used to uniquely identify notifications delivered to an ios device+#[derive(Debug, Clone)]+pub struct HashedCollapseKey(String);++impl AsRef<str> for HashedCollapseKey {+ fn as_ref(&self) -> &str {+ &self.0+ }+}++impl HashedCollapseKey {+ pub fn from_hashed(s: String) -> Self {+ Self(s)+ }++ pub fn into_inner(self) -> String {+ self.0+ }+}++impl NotifCollapseKey {+ pub fn new(s: &str) -> Self {+ let mut hasher = DefaultHasher::new();+ hasher.write(s.as_bytes());+ NotifCollapseKey(hasher)+ }++ pub fn append(mut self, s: &str) -> Self {+ self.0.write(s.as_bytes());+ self+ }++ pub fn into_hashed(self) -> HashedCollapseKey {+ let bytes = self.0.finish();+ HashedCollapseKey::from_hashed(format!("{bytes:x}"))+ }+}+// CAUTION: for hash map purposes we need Hash+Eq impl on UserNotification// User notifications are considered equal based only on their iddiff --git a/rust/cloud-storage/model_notifications/src/tests.rs b/rust/cloud-storage/model_notifications/src/tests.rsnew file mode 100644index 0000000000..272f95a802--- /dev/null+++ b/rust/cloud-storage/model_notifications/src/tests.rs@@ -0,0 +1,471 @@+use super::*;+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::EntityType;++fn make_user_id(email: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from_email(email).expect("valid test email")+}++fn create_base_notification(+ notification_event: NotificationEvent,+ entity_type: EntityType,+ entity_id: &str,+) -> UserNotification {+ UserNotification {+ id: Uuid::new_v4(),+ notification_entity: entity_type.with_entity_string(entity_id.to_string()),+ sent: false,+ done: false,+ sender_id: Some(make_user_id("[email protected]")),+ temporal: NotificationTemporalData::default(),+ notification_event,+ }+}++#[test]+fn test_build_key_channel_mention_uses_message_id() {+ let notif = create_base_notification(+ NotificationEvent::ChannelMention(ChannelMentionMetadata {+ message_id: "msg_123".to_string(),+ message_content: "Hello @user".to_string(),+ thread_id: None,+ common: CommonChannelMetadata {+ channel_type: ChannelType::Public,+ channel_name: "general".to_string(),+ },+ }),+ EntityType::Channel,+ "channel_abc",+ );++ let key = notif.build_key().into_hashed();++ // Two notifications with the same message_id should produce the same collapse key+ let notif2 = create_base_notification(+ NotificationEvent::ChannelMention(ChannelMentionMetadata {+ message_id: "msg_123".to_string(),+ message_content: "Different content".to_string(),+ thread_id: Some("thread_1".to_string()),+ common: CommonChannelMetadata {+ channel_type: ChannelType::Private,+ channel_name: "different-channel".to_string(),+ },+ }),+ EntityType::Channel,+ "different_channel_id",+ );++ let key2 = notif2.build_key().into_hashed();+ assert_eq!(key.as_ref(), key2.as_ref());+}++#[test]+fn test_build_key_channel_mention_different_message_ids_produce_different_keys() {+ let notif1 = create_base_notification(+ NotificationEvent::ChannelMention(ChannelMentionMetadata {+ message_id: "msg_123".to_string(),+ message_content: "Hello".to_string(),+ thread_id: None,+ common: CommonChannelMetadata {+ channel_type: ChannelType::Public,+ channel_name: "general".to_string(),+ },+ }),+ EntityType::Channel,+ "channel_abc",+ );++ let notif2 = create_base_notification(+ NotificationEvent::ChannelMention(ChannelMentionMetadata {+ message_id: "msg_456".to_string(),+ message_content: "Hello".to_string(),+ thread_id: None,+ common: CommonChannelMetadata {+ channel_type: ChannelType::Public,+ channel_name: "general".to_string(),+ },+ }),+ EntityType::Channel,+ "channel_abc",+ );++ let key1 = notif1.build_key().into_hashed();+ let key2 = notif2.build_key().into_hashed();+ assert_ne!(key1.as_ref(), key2.as_ref());+}++#[test]+fn test_build_key_channel_message_send_uses_message_id() {+ let notif = create_base_notification(+ NotificationEvent::ChannelMessageSend(ChannelMessageSendMetadata {+ sender: make_user_id("[email protected]"),+ message_content: "Hello world".to_string(),+ message_id: "msg_send_123".to_string(),+ common: CommonChannelMetadata {+ channel_type: ChannelType::Public,+ channel_name: "general".to_string(),+ },+ }),+ EntityType::Channel,+ "channel_abc",+ );++ let key = notif.build_key().into_hashed();++ // Same message_id should produce same key regardless of other fields+ let notif2 = create_base_notification(+ NotificationEvent::ChannelMessageSend(ChannelMessageSendMetadata {+ sender: make_user_id("[email protected]"),+ message_content: "Different message".to_string(),+ message_id: "msg_send_123".to_string(),+ common: CommonChannelMetadata {+ channel_type: ChannelType::Private,+ channel_name: "other-channel".to_string(),+ },+ }),+ EntityType::Channel,+ "different_channel",+ );++ let key2 = notif2.build_key().into_hashed();+ assert_eq!(key.as_ref(), key2.as_ref());+}++#[test]+fn test_build_key_channel_message_reply_uses_message_id() {+ let notif = create_base_notification(+ NotificationEvent::ChannelMessageReply(ChannelReplyMetadata {+ thread_id: "thread_abc".to_string(),+ message_id: "reply_msg_123".to_string(),+ user_id: make_user_id("[email protected]"),+ message_content: "This is a reply".to_string(),+ common: CommonChannelMetadata {+ channel_type: ChannelType::Public,+ channel_name: "general".to_string(),+ },+ }),+ EntityType::Channel,+ "channel_abc",+ );++ let key = notif.build_key().into_hashed();++ // Same message_id should produce same key+ let notif2 = create_base_notification(+ NotificationEvent::ChannelMessageReply(ChannelReplyMetadata {+ thread_id: "different_thread".to_string(),+ message_id: "reply_msg_123".to_string(),+ user_id: make_user_id("[email protected]"),+ message_content: "Different reply".to_string(),+ common: CommonChannelMetadata {+ channel_type: ChannelType::Private,+ channel_name: "other".to_string(),+ },+ }),+ EntityType::Channel,+ "different_channel",+ );++ let key2 = notif2.build_key().into_hashed();+ assert_eq!(key.as_ref(), key2.as_ref());+}++#[test]+fn test_build_key_item_shared_user_uses_entity() {+ let notif = create_base_notification(+ NotificationEvent::ItemSharedUser(ItemSharedMetadata {+ user_ids: vec!["user1".to_string()],+ item_type: EntityType::Document,+ item_id: "doc_123".to_string(),+ item_name: Some("My Document".to_string()),+ shared_by: make_user_id("[email protected]"),+ permission_level: Some("read".to_string()),+ }),+ EntityType::Document,+ "doc_entity_123",+ );++ let key = notif.build_key().into_hashed();++ // Same entity_type + entity_id should produce same key+ let notif2 = create_base_notification(+ NotificationEvent::ItemSharedUser(ItemSharedMetadata {+ user_ids: vec!["user2".to_string(), "user3".to_string()],+ item_type: EntityType::Project,+ item_id: "different_item".to_string(),+ item_name: Some("Different Name".to_string()),+ shared_by: make_user_id("[email protected]"),+ permission_level: Some("write".to_string()),+ }),+ EntityType::Document,+ "doc_entity_123",+ );++ let key2 = notif2.build_key().into_hashed();+ assert_eq!(key.as_ref(), key2.as_ref());+}++#[test]+fn test_build_key_item_shared_user_different_entities_produce_different_keys() {+ let notif1 = create_base_notification(+ NotificationEvent::ItemSharedUser(ItemSharedMetadata {+ user_ids: vec!["user1".to_string()],+ item_type: EntityType::Document,+ item_id: "doc_123".to_string(),+ item_name: None,+ shared_by: make_user_id("[email protected]"),+ permission_level: None,+ }),+ EntityType::Document,+ "doc_entity_123",+ );++ let notif2 = create_base_notification(+ NotificationEvent::ItemSharedUser(ItemSharedMetadata {+ user_ids: vec!["user1".to_string()],+ item_type: EntityType::Document,+ item_id: "doc_123".to_string(),+ item_name: None,+ shared_by: make_user_id("[email protected]"),+ permission_level: None,+ }),+ EntityType::Document,+ "doc_entity_456", // Different entity_id+ );++ let key1 = notif1.build_key().into_hashed();+ let key2 = notif2.build_key().into_hashed();+ assert_ne!(key1.as_ref(), key2.as_ref());+}++#[test]+fn test_build_key_different_entity_types_produce_different_keys() {+ let notif1 = create_base_notification(+ NotificationEvent::ItemSharedUser(ItemSharedMetadata {+ user_ids: vec!["user1".to_string()],+ item_type: EntityType::Document,+ item_id: "item_123".to_string(),+ item_name: None,+ shared_by: make_user_id("[email protected]"),+ permission_level: None,+ }),+ EntityType::Document,+ "entity_123",+ );++ let notif2 = create_base_notification(+ NotificationEvent::ItemSharedUser(ItemSharedMetadata {+ user_ids: vec!["user1".to_string()],+ item_type: EntityType::Document,+ item_id: "item_123".to_string(),+ item_name: None,+ shared_by: make_user_id("[email protected]"),+ permission_level: None,+ }),+ EntityType::Project, // Different entity_type+ "entity_123",+ );++ let key1 = notif1.build_key().into_hashed();+ let key2 = notif2.build_key().into_hashed();+ assert_ne!(key1.as_ref(), key2.as_ref());+}++#[test]+fn test_build_key_document_mention_uses_entity() {+ let notif = create_base_notification(+ NotificationEvent::DocumentMention(DocumentMentionMetadata {+ document_name: "My Doc".to_string(),+ owner: make_user_id("[email protected]"),+ file_type: Some("pdf".to_string()),+ metadata: None,+ }),+ EntityType::Document,+ "doc_mention_entity",+ );++ let key = notif.build_key().into_hashed();+ assert!(!key.as_ref().is_empty());+}++#[test]+fn test_build_key_channel_invite_uses_entity() {+ let notif = create_base_notification(+ NotificationEvent::ChannelInvite(ChannelInviteMetadata {+ invited_by: make_user_id("[email protected]"),+ common: CommonChannelMetadata {+ channel_type: ChannelType::Private,+ channel_name: "secret-channel".to_string(),+ },+ }),+ EntityType::Channel,+ "channel_invite_entity",+ );++ let key = notif.build_key().into_hashed();+ assert!(!key.as_ref().is_empty());+}++#[test]+fn test_build_key_new_email_uses_entity() {+ let notif = create_base_notification(+ NotificationEvent::NewEmail(NewEmailMetadata {+ sender: Some("[email protected]".to_string()),+ to_email: "[email protected]".to_string(),+ thread_id: "thread_123".to_string(),+ subject: "Test Subject".to_string(),+ snippet: "Email snippet...".to_string(),+ }),+ EntityType::Email,+ "email_entity_123",+ );++ let key = notif.build_key().into_hashed();+ assert!(!key.as_ref().is_empty());+}++#[test]+fn test_build_key_invite_to_team_uses_entity() {+ let notif = create_base_notification(+ NotificationEvent::InviteToTeam(InviteToTeamMetadata {+ team_name: "Engineering".to_string(),+ team_id: "team_123".to_string(),+ invited_by: make_user_id("[email protected]"),+ role: Some("member".to_string()),+ }),+ EntityType::Team,+ "team_entity_123",+ );++ let key = notif.build_key().into_hashed();+ assert!(!key.as_ref().is_empty());+}++#[test]+fn test_build_key_reject_team_invite_uses_entity() {+ let notif = create_base_notification(+ NotificationEvent::RejectTeamInvite,+ EntityType::Team,+ "team_entity_123",+ );++ let key = notif.build_key().into_hashed();+ assert!(!key.as_ref().is_empty());+}++#[test]+fn test_build_key_task_assigned_uses_entity() {+ let notif = create_base_notification(+ NotificationEvent::TaskAssigned(TaskAssignedMetadata {+ task_id: "task_123".to_string(),+ task_name: Some("Complete feature".to_string()),+ assigned_by: make_user_id("[email protected]"),+ }),+ EntityType::Document, // Tasks might be associated with documents+ "task_entity_123",+ );++ let key = notif.build_key().into_hashed();+ assert!(!key.as_ref().is_empty());+}++#[test]+fn test_build_key_item_shared_organization_uses_entity() {+ let notif = create_base_notification(+ NotificationEvent::ItemSharedOrganization(ItemSharedOrganizationMetadata {+ org_user_ids: vec!["user1".to_string(), "user2".to_string()],+ item_type: EntityType::Project,+ item_id: "project_123".to_string(),+ item_name: Some("Shared Project".to_string()),+ shared_by: make_user_id("[email protected]"),+ permission_level: Some("admin".to_string()),+ }),+ EntityType::Project,+ "project_entity_123",+ );++ let key = notif.build_key().into_hashed();+ assert!(!key.as_ref().is_empty());+}++#[test]+fn test_build_key_channel_message_document_uses_entity() {+ let notif = create_base_notification(+ NotificationEvent::ChannelMessageDocument(ChannelMessageDocumentMetadata(+ DocumentMentionMetadata {+ document_name: "Attached Doc".to_string(),+ owner: make_user_id("[email protected]"),+ file_type: Some("docx".to_string()),+ metadata: None,+ },+ )),+ EntityType::Document,+ "doc_attachment_entity",+ );++ let key = notif.build_key().into_hashed();+ assert!(!key.as_ref().is_empty());+}++#[test]+fn test_build_key_produces_hex_string() {+ let notif = create_base_notification(+ NotificationEvent::ChannelMention(ChannelMentionMetadata {+ message_id: "msg_123".to_string(),+ message_content: "Hello".to_string(),+ thread_id: None,+ common: CommonChannelMetadata {+ channel_type: ChannelType::Public,+ channel_name: "general".to_string(),+ },+ }),+ EntityType::Channel,+ "channel_abc",+ );++ let key = notif.build_key().into_hashed();+ let key_str = key.as_ref();++ // Should be a valid hex string (only hex characters)+ assert!(key_str.chars().all(|c| c.is_ascii_hexdigit()));+ // Should be 16 hex chars (64-bit hash = 8 bytes = 16 hex chars)+ assert_eq!(key_str.len(), 16);+}++#[test]+fn test_build_key_is_deterministic() {+ let notif = create_base_notification(+ NotificationEvent::ChannelMention(ChannelMentionMetadata {+ message_id: "msg_deterministic".to_string(),+ message_content: "Test".to_string(),+ thread_id: None,+ common: CommonChannelMetadata {+ channel_type: ChannelType::Public,+ channel_name: "test".to_string(),+ },+ }),+ EntityType::Channel,+ "channel_test",+ );++ let key1 = notif.build_key().into_hashed();++ // Create an identical notification+ let notif2 = create_base_notification(+ NotificationEvent::ChannelMention(ChannelMentionMetadata {+ message_id: "msg_deterministic".to_string(),+ message_content: "Test".to_string(),+ thread_id: None,+ common: CommonChannelMetadata {+ channel_type: ChannelType::Public,+ channel_name: "test".to_string(),+ },+ }),+ EntityType::Channel,+ "channel_test",+ );++ let key2 = notif2.build_key().into_hashed();++ assert_eq!(key1.as_ref(), key2.as_ref());+}diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-5fd1abfdae31c22ce5c71a9c3e9607566b99dbd819d7bca5a88e62fac00098d4.json b/rust/cloud-storage/notification_db_client/.sqlx/query-5fd1abfdae31c22ce5c71a9c3e9607566b99dbd819d7bca5a88e62fac00098d4.jsonnew file mode 100644index 0000000000..ad058d2085--- /dev/null+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-5fd1abfdae31c22ce5c71a9c3e9607566b99dbd819d7bca5a88e62fac00098d4.json@@ -0,0 +1,41 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE notification\n SET apns_collapse_key = $2\n WHERE id = $1\n RETURNING\n event_item_id,\n event_item_type,\n notification_event_type,\n apns_collapse_key as \"apns_collapse_key!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "event_item_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "event_item_type",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "notification_event_type",+ "type_info": "Varchar"+ },+ {+ "ordinal": 3,+ "name": "apns_collapse_key!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true+ ]+ },+ "hash": "5fd1abfdae31c22ce5c71a9c3e9607566b99dbd819d7bca5a88e62fac00098d4"+}diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-68bf7d8dec24932a9826a9e3b9a305e7813c98254bea3ff0f3f3dc5643431449.json b/rust/cloud-storage/notification_db_client/.sqlx/query-7d904128ec24b17b4f1b25a2084b42476455160ba50f8e599a47acca06484cd7.jsonsimilarity index 67%rename from rust/cloud-storage/notification_db_client/.sqlx/query-68bf7d8dec24932a9826a9e3b9a305e7813c98254bea3ff0f3f3dc5643431449.jsonrename to rust/cloud-storage/notification_db_client/.sqlx/query-7d904128ec24b17b4f1b25a2084b42476455160ba50f8e599a47acca06484cd7.jsonindex 0e67fa4d5e..c79d9c592c 100644--- a/rust/cloud-storage/notification_db_client/.sqlx/query-68bf7d8dec24932a9826a9e3b9a305e7813c98254bea3ff0f3f3dc5643431449.json+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-7d904128ec24b17b4f1b25a2084b42476455160ba50f8e599a47acca06484cd7.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n n.event_item_id,\n n.event_item_type,\n n.notification_event_type\n FROM notification n\n WHERE n.id = $1\n ",+ "query": "\n SELECT\n n.event_item_id,\n n.event_item_type,\n n.notification_event_type,\n n.apns_collapse_key\n FROM notification n\n WHERE n.id = $1\n ","describe": {"columns": [{@@ -17,6 +17,11 @@"ordinal": 2,"name": "notification_event_type","type_info": "Varchar"+ },+ {+ "ordinal": 3,+ "name": "apns_collapse_key",+ "type_info": "Text"}],"parameters": {@@ -27,8 +32,9 @@"nullable": [false,false,- false+ false,+ true]},- "hash": "68bf7d8dec24932a9826a9e3b9a305e7813c98254bea3ff0f3f3dc5643431449"+ "hash": "7d904128ec24b17b4f1b25a2084b42476455160ba50f8e599a47acca06484cd7"}diff --git a/rust/cloud-storage/notification_db_client/fixtures/basic_notification.sql b/rust/cloud-storage/notification_db_client/fixtures/basic_notification.sqlnew file mode 100644index 0000000000..f5e5fe0261--- /dev/null+++ b/rust/cloud-storage/notification_db_client/fixtures/basic_notification.sql@@ -0,0 +1,22 @@+INSERT INTO+ notification (+ id,+ notification_event_type,+ event_item_id,+ event_item_type,+ service_sender,+ metadata,+ sender_id,+ apns_collapse_key+ )+VALUES+ (+ '0193b1ea-a542-7589-893b-2b4a509c1e76',+ 'message',+ 'item-123',+ 'document',+ 'test-service',+ NULL,+ 'macro|[email protected]',+ NULL+ );diff --git a/rust/cloud-storage/notification_db_client/migrations/20260105154225_add_apns_collapse_key.sql b/rust/cloud-storage/notification_db_client/migrations/20260105154225_add_apns_collapse_key.sqlnew file mode 100644index 0000000000..991681c793--- /dev/null+++ b/rust/cloud-storage/notification_db_client/migrations/20260105154225_add_apns_collapse_key.sql@@ -0,0 +1,4 @@+-- Add apns_collapse_key column to notification table for iOS push notification management.+-- This allows each notification to have a unique collapse key, enabling notifications+-- to stack in the notification center while still being individually clearable.+ALTER TABLE notification ADD COLUMN apns_collapse_key TEXT;diff --git a/rust/cloud-storage/notification_db_client/src/notification/get.rs b/rust/cloud-storage/notification_db_client/src/notification/get.rsindex dcae55c3a5..8a53304d63 100644--- a/rust/cloud-storage/notification_db_client/src/notification/get.rs+++ b/rust/cloud-storage/notification_db_client/src/notification/get.rs@@ -1,30 +1,118 @@+use sqlx::PgPool;+use uuid::Uuid;++#[cfg(test)]+mod tests;+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]-pub struct BasicNotification {+pub struct DbBasicNotification<T> {pub event_item_id: String,pub event_item_type: String,pub notification_event_type: String,+ pub apns_collapse_key: T,+}++impl<T> DbBasicNotification<Option<T>> {+ pub fn transpose(self) -> Option<DbBasicNotification<T>> {+ let DbBasicNotification {+ event_item_id,+ event_item_type,+ notification_event_type,+ apns_collapse_key,+ } = self;+ match apns_collapse_key {+ Some(val) => Some(DbBasicNotification {+ event_item_id,+ event_item_type,+ notification_event_type,+ apns_collapse_key: val,+ }),+ None => None,+ }+ }}/// Gets a notification by id-#[tracing::instrument(skip(db))]+#[tracing::instrument(err, skip(db))]pub async fn get_basic_notification(db: &sqlx::PgPool,- notification_id: &str,-) -> anyhow::Result<BasicNotification> {+ notification_id: &Uuid,+) -> anyhow::Result<DbBasicNotification<Option<String>>> {let notification = sqlx::query_as!(- BasicNotification,+ DbBasicNotification,r#"SELECTn.event_item_id,n.event_item_type,- n.notification_event_type+ n.notification_event_type,+ n.apns_collapse_keyFROM notification nWHERE n.id = $1"#,- macro_uuid::string_to_uuid(notification_id)?+ notification_id+ )+ .fetch_one(db)+ .await?;++ Ok(notification)+}++/// Updates the APNS collapse key for a notification and returns the updated notification+#[tracing::instrument(err, skip(db))]+pub async fn update_collapse_key(+ db: &sqlx::PgPool,+ notification_id: &Uuid,+ collapse_key: &str,+) -> anyhow::Result<DbBasicNotification<String>> {+ let notification = sqlx::query_as!(+ DbBasicNotification,+ r#"+ UPDATE notification+ SET apns_collapse_key = $2+ WHERE id = $1+ RETURNING+ event_item_id,+ event_item_type,+ notification_event_type,+ apns_collapse_key as "apns_collapse_key!"+ "#,+ notification_id,+ collapse_key).fetch_one(db).await?;Ok(notification)}++pub trait BasicNotificationRepo: Send + Sync + 'static {+ fn update_collapse_key(+ &self,+ notification_id: &Uuid,+ collapse_key: &str,+ ) -> impl Future<Output = anyhow::Result<DbBasicNotification<String>>> + Send;++ fn get_basic_notification(+ &self,+ notification_id: &Uuid,+ ) -> impl Future<Output = anyhow::Result<DbBasicNotification<Option<String>>>> + Send;+}++pub struct BasicNotifRepoImpl(pub PgPool);++impl BasicNotificationRepo for BasicNotifRepoImpl {+ fn update_collapse_key(+ &self,+ notification_id: &Uuid,+ collapse_key: &str,+ ) -> impl Future<Output = anyhow::Result<DbBasicNotification<String>>> + Send {+ update_collapse_key(&self.0, notification_id, collapse_key)+ }++ fn get_basic_notification(+ &self,+ notification_id: &Uuid,+ ) -> impl Future<Output = anyhow::Result<DbBasicNotification<Option<String>>>> + Send {+ get_basic_notification(&self.0, notification_id)+ }+}diff --git a/rust/cloud-storage/notification_db_client/src/notification/get/tests.rs b/rust/cloud-storage/notification_db_client/src/notification/get/tests.rsnew file mode 100644index 0000000000..41d86a8ae2--- /dev/null+++ b/rust/cloud-storage/notification_db_client/src/notification/get/tests.rs@@ -0,0 +1,31 @@+use super::*;+use sqlx::{Pool, Postgres};++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("basic_notification")))]+async fn test_get_basic_notification(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let notification_id = macro_uuid::string_to_uuid("0193b1ea-a542-7589-893b-2b4a509c1e76")?;++ let result = get_basic_notification(&pool, ¬ification_id).await?;++ assert_eq!(result.event_item_id, "item-123");+ assert_eq!(result.event_item_type, "document");+ assert_eq!(result.notification_event_type, "message");+ assert!(result.apns_collapse_key.is_none());++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("basic_notification")))]+async fn test_update_basic_notification(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let notification_id = macro_uuid::string_to_uuid("0193b1ea-a542-7589-893b-2b4a509c1e76")?;+ let collapse_key = "test-collapse-key";++ let result = update_collapse_key(&pool, ¬ification_id, collapse_key).await?;++ assert_eq!(result.event_item_id, "item-123");+ assert_eq!(result.event_item_type, "document");+ assert_eq!(result.notification_event_type, "message");+ assert_eq!(result.apns_collapse_key, collapse_key);++ Ok(())+}diff --git a/rust/cloud-storage/notification_service/examples/send_push_notification.rs b/rust/cloud-storage/notification_service/examples/send_push_notification.rsindex d5b22ca4a2..9792f770a3 100644--- a/rust/cloud-storage/notification_service/examples/send_push_notification.rs+++ b/rust/cloud-storage/notification_service/examples/send_push_notification.rs@@ -1,13 +1,9 @@-use std::collections::HashMap;-use anyhow::Context;use aws_sdk_sns::types::MessageAttributeValue;use macro_entrypoint::MacroEntrypoint;use serde::Serialize;-use sns_client::{- APNSPushNotification, Alert, AlertDictionary, Aps, FCMMessage, MessageAttributes,- NotifCollapseKey, SnsTarget,-};+use sns_client::{APNSPushNotification, Alert, AlertDictionary, Aps, MessageAttributes, SnsTarget};+use std::collections::HashMap;/// Sends a push notification to the provided ENDPOINT_ARN environment variable#[tokio::main]@@ -25,11 +21,11 @@ async fn main() -> anyhow::Result<()> {let collapse_key = "collapse";// Sends the first push notification- send_first(&sns_client, &endpoint_arn, collapse_key).await?;+ send_first(&sns_client, &endpoint_arn, collapse_key.to_string()).await?;// Sends an empty push notification with the same collapse key.// this will remove the notification from the device.- send_empty(&sns_client, &endpoint_arn, collapse_key).await?;+ send_empty(&sns_client, &endpoint_arn, collapse_key.to_string()).await?;Ok(())}@@ -74,7 +70,7 @@ fn message_attributes(collapse_key: &str) -> Option<HashMap<String, MessageAttriasync fn send_first(sns_client: &sns_client::SNS,endpoint_arn: &str,- collapse_key: &str,+ collapse_key: String,) -> anyhow::Result<()> {let apns = SnsTarget::Ios(Box::new(APNSPushNotification {aps: Aps {@@ -95,7 +91,7 @@ async fn send_first(MessageAttributes {push_type: sns_client::PushType::Alert,apns_bundle_id: "com.macro.app.prod",- collapse_key: NotifCollapseKey::new_str(collapse_key),+ collapse_key,},).await@@ -107,7 +103,7 @@ async fn send_first(async fn send_empty(sns_client: &sns_client::SNS,endpoint_arn: &str,- collapse_key: &str,+ collapse_key: String,) -> anyhow::Result<()> {#[derive(Debug, Serialize)]struct ExtraData {@@ -131,7 +127,7 @@ async fn send_empty(MessageAttributes {push_type: sns_client::PushType::Alert,apns_bundle_id: "com.macro.app.prod",- collapse_key: NotifCollapseKey::new_str(collapse_key),+ collapse_key,},).awaitdiff --git a/rust/cloud-storage/notification_service/src/api/user_notification/bulk_mark_user_notification_done_by_event.rs b/rust/cloud-storage/notification_service/src/api/user_notification/bulk_mark_user_notification_done_by_event.rsindex 56eae2540c..87bce31df8 100644--- a/rust/cloud-storage/notification_service/src/api/user_notification/bulk_mark_user_notification_done_by_event.rs+++ b/rust/cloud-storage/notification_service/src/api/user_notification/bulk_mark_user_notification_done_by_event.rs@@ -1,3 +1,5 @@+use std::borrow::Cow;+use axum::{Extension, Json,extract::{Path, State},@@ -52,24 +54,21 @@ pub async fn handler(.into_response()})?;- if !notification_ids.is_empty() {+ if let Some(first_uuid) = notification_ids.first() {// We only need the first notification as all basic info will be the samelet basic_notification_information =- notification_db_client::notification::get::get_basic_notification(- &ctx.db,- ¬ification_ids[0].to_string(),- )- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to get basic notification information");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "failed to get basic notification information",- }),- )- .into_response()- })?;+ notification_db_client::notification::get::get_basic_notification(&ctx.db, first_uuid)+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "failed to get basic notification information");+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "failed to get basic notification information",+ }),+ )+ .into_response()+ })?;if basic_notification_information.event_item_type == "channel" {tokio::spawn({@@ -90,20 +89,11 @@ pub async fn handler(}tokio::spawn({- let ctx = ctx.clone();- let user_id = user_context.user_id.clone();- let basic_notification_information = basic_notification_information.clone();- async move {- if let Err(e) = notification::send::push::remove::clear_push_notifications_basic(- ctx.clone(),- &user_id,- &basic_notification_information,- )- .await- {- tracing::error!(error=?e, "failed to remove push notifications");- }- }+ notification::send::push::remove::clear_push_notifications_basic(+ ctx,+ Cow::Owned(user_context.user_id.clone()),+ basic_notification_information,+ )});}diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/bulk_mark_user_notification_seen_by_event.rs b/rust/cloud-storage/notification_service/src/api/user_notification/bulk_mark_user_notification_seen_by_event.rsindex a96ed754bf..2ba6653e12 100644--- a/rust/cloud-storage/notification_service/src/api/user_notification/bulk_mark_user_notification_seen_by_event.rs+++ b/rust/cloud-storage/notification_service/src/api/user_notification/bulk_mark_user_notification_seen_by_event.rs@@ -1,3 +1,5 @@+use std::borrow::Cow;+use axum::{Extension, Json,extract::{Path, State},@@ -52,24 +54,21 @@ pub async fn handler(.into_response()})?;- if !notification_ids.is_empty() {+ if let Some(first_uuid) = notification_ids.first() {// We only need the first notification as all basic info will be the samelet basic_notification_information =- notification_db_client::notification::get::get_basic_notification(- &ctx.db,- ¬ification_ids[0].to_string(),- )- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to get basic notification information");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "failed to get basic notification information",- }),- )- .into_response()- })?;+ notification_db_client::notification::get::get_basic_notification(&ctx.db, first_uuid)+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "failed to get basic notification information");+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "failed to get basic notification information",+ }),+ )+ .into_response()+ })?;if basic_notification_information.event_item_type == "channel" {tokio::spawn({@@ -90,20 +89,11 @@ pub async fn handler(}tokio::spawn({- let ctx = ctx.clone();- let user_id = user_context.user_id.clone();- let basic_notification_information = basic_notification_information.clone();- async move {- if let Err(e) = notification::send::push::remove::clear_push_notifications_basic(- ctx.clone(),- &user_id,- &basic_notification_information,- )- .await- {- tracing::error!(error=?e, "failed to remove push notifications");- }- }+ notification::send::push::remove::clear_push_notifications_basic(+ ctx,+ Cow::Owned(user_context.user_id.clone()),+ basic_notification_information,+ )});}diff --git a/rust/cloud-storage/notification_service/src/config.rs b/rust/cloud-storage/notification_service/src/config.rsindex ee2d446c12..210a742080 100644--- a/rust/cloud-storage/notification_service/src/config.rs+++ b/rust/cloud-storage/notification_service/src/config.rs@@ -6,8 +6,9 @@ use std::sync::LazyLock;pub static BASE_URL: LazyLock<String> = LazyLock::new(|| std::env::var("BASE_URL").unwrap());/// The apple bundle id-pub static APPLE_BUNDLE_ID: LazyLock<String> =- LazyLock::new(|| std::env::var("APPLE_BUNDLE_ID").unwrap());+pub static APPLE_BUNDLE_ID: LazyLock<String> = LazyLock::new(|| {+ std::env::var("APPLE_BUNDLE_ID").unwrap_or_else(|_| "com.macro.app.prod".to_string())+});#[derive(Debug)]pub struct Config {diff --git a/rust/cloud-storage/notification_service/src/notification/mod.rs b/rust/cloud-storage/notification_service/src/notification/mod.rsindex e164298804..b42fb15f70 100644--- a/rust/cloud-storage/notification_service/src/notification/mod.rs+++ b/rust/cloud-storage/notification_service/src/notification/mod.rs@@ -1,3 +1,7 @@+use std::time::Duration;++use tokio::time::error::Elapsed;+mod comms_utils;pub mod context;mod create;@@ -11,61 +15,35 @@ mod user_ids;/// Runs the notification worker in a loop to handle restarting should it fail.pub async fn run_notification_worker(queue_worker_context: context::QueueWorkerContext) {use futures::StreamExt;+ tracing::info!("notification worker started");loop {- let worker_result = tokio::spawn({- let queue_worker_context = queue_worker_context.clone();- async move {- tracing::info!("notification worker started");- loop {- match queue_worker_context.worker.receive_messages().await {- Ok(messages) => {- if messages.is_empty() {- continue;- }-- futures::stream::iter(messages.iter())- .then(|message| {- let queue_worker_context = queue_worker_context.clone();- async move {- let processing_future = process::process_message(queue_worker_context,message);- let result = tokio::time::timeout(std::time::Duration::from_secs(30), processing_future).await;-- match result {- Ok(Ok(_)) => {}- Ok(Err(e)) => {- tracing::error!(message_id=?message.message_id, error=?e, "error processing message");- }- Err(e) => {- tracing::error!(message_id=?message.message_id, error=?e, "timeout processing message");- }- }- Ok(())- }- })- .collect::<Vec<anyhow::Result<()>>>()- .await;- }- Err(e) => {- tracing::error!(error=?e, "error receiving messages");- }- }+ match queue_worker_context.worker.receive_messages().await {+ Ok(messages) => {+ if messages.is_empty() {+ continue;}- }- })- .await;- match worker_result {- Ok(_) => {- // This should never be hit- tracing::error!("notification worker exited successfully?");+ futures::stream::iter(messages)+ .map(|message| {+ let ctx = queue_worker_context.clone();+ async move {+ let processing_future = process::process_message(ctx, &message);+ let _ = with_timeout(Duration::from_secs(30), processing_future).await;+ Ok::<(), anyhow::Error>(())+ }+ })+ .buffer_unordered(10)+ .collect::<Vec<anyhow::Result<()>>>()+ .await;}Err(e) => {- tracing::error!(error=?e, "notification worker crashed with error");+ tracing::error!(error=?e, "error receiving messages");}}-- // Add a delay before restarting to avoid rapid restart loops- tracing::info!("NOTIFICATION WORKER RESTARTING...");- tokio::time::sleep(std::time::Duration::from_secs(5)).await;}}++#[tracing::instrument(err, skip(fut))]+async fn with_timeout<F: Future>(duration: Duration, fut: F) -> Result<F::Output, Elapsed> {+ tokio::time::timeout(duration, fut).await+}diff --git a/rust/cloud-storage/notification_service/src/notification/process.rs b/rust/cloud-storage/notification_service/src/notification/process.rsindex 4f8a9a40fb..d900138602 100644--- a/rust/cloud-storage/notification_service/src/notification/process.rs+++ b/rust/cloud-storage/notification_service/src/notification/process.rs@@ -199,8 +199,8 @@ pub(crate) async fn process_message(#[cfg(feature = "push_notification")]{send::push::process::process_push_notifications(- &ctx.db,- &ctx.sns_client,+ ctx.db.clone(),+ ctx.sns_client.clone(),¬ifications_with_user_data,).await?diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs b/rust/cloud-storage/notification_service/src/notification/send/push/generate.rsindex 97a9dab5a6..ad6ee9d6eb 100644--- a/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs+++ b/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs@@ -76,6 +76,7 @@ impl XmlFormatter for PlainTextFormatter {}}+#[tracing::instrument(err)]pub fn generate_apns_notification<T: XmlFormatter>(notif: &NotificationWithRecipient,) -> Result<Option<APNSPushNotification<PushNotificationData>>, NotificationErr> {diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/process.rs b/rust/cloud-storage/notification_service/src/notification/send/push/process.rsindex afd5d70c46..6e16fae0d1 100644--- a/rust/cloud-storage/notification_service/src/notification/send/push/process.rs+++ b/rust/cloud-storage/notification_service/src/notification/send/push/process.rs@@ -1,95 +1,172 @@use crate::{config::APPLE_BUNDLE_ID,- notification::send::push::generate::{PlainTextFormatter, generate_apns_notification},+ notification::send::push::{+ PushNotificationData,+ generate::{PlainTextFormatter, generate_apns_notification},+ },};-use aws_sdk_sns::operation::publish::PublishOutput;-use futures::{Stream, StreamExt};+use futures::StreamExt;use macro_user_id::user_id::MacroUserIdStr;-use model_notifications::{DeviceEndpoint, NotificationWithRecipient, UserNotification};-use sns_client::{NotifCollapseKey, SnsTarget};+use model_notifications::{+ DeviceEndpoint, DeviceType, HashedCollapseKey, NotificationWithRecipient,+};+use notification_db_client::notification::get::{BasicNotifRepoImpl, BasicNotificationRepo};+use sns_client::{MessageAttributes, NotificationSender, SnsTarget};use std::{- borrow::Cow,collections::{HashMap, HashSet},- hash::{DefaultHasher, Hash, Hasher},+ sync::Arc,};+use tokio::sync::mpsc::error::SendError;+use uuid::Uuid;-trait NotifCollapseKeyExt {- fn collapse_key(&self) -> NotifCollapseKey<'static>;-}--impl NotifCollapseKeyExt for UserNotification {- fn collapse_key(&self) -> NotifCollapseKey<'static> {- let collapse_key = format!(- "{}{}",- self.notification_entity.entity_id,- self.notification_event.event_type()- );-- // hash the collapse key to shorten it- let mut hasher = DefaultHasher::new();- collapse_key.hash(&mut hasher);- let hash = hasher.finish();- let collapse_key = format!("{:x}", hash);- NotifCollapseKey(Cow::Owned(collapse_key))- }-}+#[cfg(test)]+mod tests;pub type NotificationsForDevices<'a> = HashMap<&'a NotificationWithRecipient, Vec<DeviceEndpoint>>;-pub type NotificationResult = (PublishOutput, MacroUserIdStr<'static>, DeviceEndpoint);-pub fn stream_push_notifs_to_user<'a>(- sns_client: &'a sns_client::SNS,- notifs: &'a NotificationsForDevices<'a>,-) -> impl Stream<Item = Result<NotificationResult, anyhow::Error>> + 'a {+async fn stream_push_notifs_to_user<'a>(+ worker: PushNotifWorker,+ notifs: NotificationsForDevices<'a>,+) {futures::stream::iter(notifs- .iter()- .flat_map(|(notif, devices)| devices.iter().map(move |d| (notif, d))),+ .into_iter()+ .flat_map(|(notif, devices)| devices.into_iter().map(move |d| (notif, d))),)- .filter_map(- async |(notif, endpoint)| -> Option<Result<NotificationResult, anyhow::Error>> {+ .for_each_concurrent(10, move |(notif, endpoint)| {+ let worker = worker.clone();+ async move {let payload = match endpoint {DeviceEndpoint::Android(_) => {- return Some(Err(anyhow::anyhow!("android not implemented")));+ tracing::warn!("android not implemented");+ return;}DeviceEndpoint::Ios(_) => {- match generate_apns_notification::<PlainTextFormatter>(notif).transpose()? {- Ok(n) => SnsTarget::Ios(Box::new(n)),- Err(e) => return Some(Err(anyhow::Error::from(e))),+ match generate_apns_notification::<PlainTextFormatter>(notif).transpose() {+ Some(Ok(n)) => SnsTarget::Ios(Box::new(n)),+ _ => return,}}};- let res = sns_client- .push_notification(- endpoint.arn(),- &payload,- sns_client::MessageAttributes {+ let collapse_key = notif.inner.build_key().into_hashed();+ let _ = worker+ .enqueue(PushNotifMsg::Notify(NotifyData {+ notification_id: notif.inner.id,+ endpoint: endpoint.clone(),+ payload,+ attrs: sns_client::MessageAttributes {push_type: sns_client::PushType::Alert,apns_bundle_id: &APPLE_BUNDLE_ID,- collapse_key: notif.inner.collapse_key(),+ collapse_key: collapse_key.clone().into_inner(),},- )+ notif_collapse_key: collapse_key,+ recipient: notif.recipient_id.clone(),+ })).await;- let out: Result<NotificationResult, anyhow::Error> =- res.map(|r| (r, notif.recipient_id.clone(), endpoint.clone()));- Some(out)- },- )+ }+ })+ .await;+}++#[derive(Clone)]+struct PushNotifWorker {+ inner: tokio::sync::mpsc::Sender<PushNotifMsg>,+}++impl PushNotifWorker {+ pub fn new<T: BasicNotificationRepo, U: NotificationSender>(+ sns_client: Arc<U>,+ repo: T,+ ) -> (+ Self,+ tokio::task::JoinHandle<HashSet<MacroUserIdStr<'static>>>,+ ) {+ let (tx, mut rx) = tokio::sync::mpsc::channel(100);+ let task = tokio::task::spawn(async move {+ let mut users_sent_push = HashSet::new();++ while let Some(msg) = rx.recv().await {+ match msg {+ PushNotifMsg::Notify(NotifyData {+ notification_id,+ endpoint,+ payload,+ attrs,+ notif_collapse_key,+ recipient,+ }) => {+ let Ok(_) = repo+ .update_collapse_key(¬ification_id, notif_collapse_key.as_ref())+ .await+ else {+ continue;+ };+ let Ok(_) = sns_client+ .push_notification(endpoint.arn(), &payload, attrs)+ .await+ else {+ continue;+ };+ users_sent_push.insert(recipient);+ }+ }+ }+ users_sent_push+ });++ (PushNotifWorker { inner: tx }, task)+ }++ #[tracing::instrument(err, skip(self))]+ async fn enqueue(&self, msg: PushNotifMsg) -> Result<(), SendError<PushNotifMsg>> {+ self.inner.send(msg).await+ }+}++#[derive(Debug)]+enum PushNotifMsg {+ Notify(NotifyData),+}++#[derive(Debug)]+struct NotifyData {+ notification_id: Uuid,+ endpoint: DeviceEndpoint,+ payload: SnsTarget<PushNotificationData>,+ attrs: MessageAttributes,+ notif_collapse_key: HashedCollapseKey,+ recipient: MacroUserIdStr<'static>,}/// Attempts to send push notifications to provided users/// Returns a list of users who were sent push notifications.#[tracing::instrument(skip(db, sns_client))]pub async fn process_push_notifications(- db: &sqlx::Pool<sqlx::Postgres>,- sns_client: &sns_client::SNS,+ db: sqlx::Pool<sqlx::Postgres>,+ sns_client: Arc<sns_client::SNS>,notifications: &HashMap<MacroUserIdStr<'static>, Vec<NotificationWithRecipient>>,) -> Result<HashSet<MacroUserIdStr<'static>>, anyhow::Error> {let user_ids: Vec<_> = notifications.keys().cloned().collect();- let mut user_device_endpoints =- notification_db_client::device::get_users_device_endpoints(db, user_ids.as_slice()).await?;+ let user_device_endpoints =+ notification_db_client::device::get_users_device_endpoints(&db, user_ids.as_slice())+ .await?;++ process_push_notifications_inner(+ user_device_endpoints,+ notifications,+ sns_client,+ BasicNotifRepoImpl(db),+ )+ .await+}+async fn process_push_notifications_inner<U: NotificationSender, T: BasicNotificationRepo>(+ mut user_device_endpoints: HashMap<MacroUserIdStr<'static>, Vec<(String, DeviceType)>>,+ notifications: &HashMap<MacroUserIdStr<'static>, Vec<NotificationWithRecipient>>,+ sns_client: Arc<U>,+ notif_repo: T,+) -> Result<HashSet<MacroUserIdStr<'static>>, anyhow::Error> {let to_send: HashMap<_, _> = notifications.iter().flat_map(|(user_id, notifs)| {@@ -113,14 +190,11 @@ pub async fn process_push_notifications(}).collect();- let mut users_sent_push = HashSet::new();- stream_push_notifs_to_user(sns_client, &to_send)- .for_each_concurrent(10, |res| {- if let Ok(r) = res.inspect_err(|e| tracing::error!("{e}")) {- users_sent_push.insert(r.1);- }- async {}- })- .await;+ let (worker, handle) = PushNotifWorker::new(sns_client, notif_repo);++ stream_push_notifs_to_user(worker, to_send).await;++ let users_sent_push = handle.await.unwrap_or_default();+Ok(users_sent_push)}diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/process/tests.rs b/rust/cloud-storage/notification_service/src/notification/send/push/process/tests.rsnew file mode 100644index 0000000000..638158d108--- /dev/null+++ b/rust/cloud-storage/notification_service/src/notification/send/push/process/tests.rs@@ -0,0 +1,384 @@+use super::*;+use model_entity::EntityType;+use model_notifications::{+ ChannelMessageSendMetadata, ChannelType, CommonChannelMetadata, NotificationEvent,+ NotificationTemporalData, NotificationWithRecipient, UserNotification,+};+use notification_db_client::notification::get::DbBasicNotification;+use std::sync::atomic::{AtomicUsize, Ordering};++struct MockNotifRepo {+ update_count: AtomicUsize,+}++impl MockNotifRepo {+ fn new() -> Self {+ Self {+ update_count: AtomicUsize::new(0),+ }+ }+}++impl BasicNotificationRepo for MockNotifRepo {+ async fn update_collapse_key(+ &self,+ _notification_id: &Uuid,+ collapse_key: &str,+ ) -> anyhow::Result<DbBasicNotification<String>> {+ self.update_count.fetch_add(1, Ordering::SeqCst);+ Ok(DbBasicNotification {+ event_item_id: "test_entity_id".to_string(),+ event_item_type: "channel".to_string(),+ notification_event_type: "channel_message_send".to_string(),+ apns_collapse_key: collapse_key.to_string(),+ })+ }++ async fn get_basic_notification(+ &self,+ _notification_id: &Uuid,+ ) -> anyhow::Result<DbBasicNotification<Option<String>>> {+ Ok(DbBasicNotification {+ event_item_id: "test_entity_id".to_string(),+ event_item_type: "channel".to_string(),+ notification_event_type: "channel_message_send".to_string(),+ apns_collapse_key: None,+ })+ }+}++struct MockSnsClient {+ push_count: AtomicUsize,+ should_fail: bool,+}++impl MockSnsClient {+ fn new() -> Self {+ Self {+ push_count: AtomicUsize::new(0),+ should_fail: false,+ }+ }++ fn failing() -> Self {+ Self {+ push_count: AtomicUsize::new(0),+ should_fail: true,+ }+ }+}++impl NotificationSender for MockSnsClient {+ async fn push_notification<T>(+ &self,+ _endpoint_arn: &str,+ _message_json: &SnsTarget<T>,+ _message_attributes: MessageAttributes,+ ) -> anyhow::Result<aws_sdk_sns::operation::publish::PublishOutput>+ where+ T: serde::Serialize + std::fmt::Debug + Sync,+ {+ if self.should_fail {+ return Err(anyhow::anyhow!("mock sns failure"));+ }+ self.push_count.fetch_add(1, Ordering::SeqCst);+ Ok(aws_sdk_sns::operation::publish::PublishOutput::builder()+ .message_id("mock_message_id")+ .build())+ }+}++fn make_user_id(email: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from_email(email).expect("valid test email")+}++fn create_test_notification(+ id: Uuid,+ recipient_email: &str,+ message_id: &str,+) -> NotificationWithRecipient {+ let sender = make_user_id("[email protected]");+ NotificationWithRecipient {+ inner: UserNotification {+ id,+ notification_entity: EntityType::Channel+ .with_entity_string("test_channel_id".to_string()),+ sent: false,+ done: false,+ sender_id: Some(sender.clone()),+ temporal: NotificationTemporalData::default(),+ notification_event: NotificationEvent::ChannelMessageSend(ChannelMessageSendMetadata {+ sender,+ message_content: "Hello, world!".to_string(),+ message_id: message_id.to_string(),+ common: CommonChannelMetadata {+ channel_type: ChannelType::Public,+ channel_name: "general".to_string(),+ },+ }),+ },+ recipient_id: make_user_id(recipient_email),+ }+}++#[tokio::test]+async fn test_process_push_notifications_inner_no_devices() {+ let user_id = make_user_id("[email protected]");+ let notif = create_test_notification(Uuid::new_v4(), "[email protected]", "msg_1");++ let mut notifications = HashMap::new();+ notifications.insert(user_id, vec![notif]);++ // Empty device endpoints - no devices registered+ let user_device_endpoints: HashMap<MacroUserIdStr<'static>, Vec<(String, DeviceType)>> =+ HashMap::new();++ let result = process_push_notifications_inner(+ user_device_endpoints,+ ¬ifications,+ Arc::new(MockSnsClient::new()),+ MockNotifRepo::new(),+ )+ .await;++ assert!(result.is_ok());+ let users_sent = result.unwrap();+ // No users should have been sent push notifications since no devices registered+ assert!(users_sent.is_empty());+}++#[tokio::test]+async fn test_process_push_notifications_inner_with_ios_device() {+ let user_id = make_user_id("[email protected]");+ let notif = create_test_notification(Uuid::new_v4(), "[email protected]", "msg_1");++ let mut notifications = HashMap::new();+ notifications.insert(user_id.clone(), vec![notif]);++ let mut user_device_endpoints = HashMap::new();+ user_device_endpoints.insert(+ user_id.clone(),+ vec![(+ "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device".to_string(),+ DeviceType::Ios,+ )],+ );++ let sns_client = Arc::new(MockSnsClient::new());+ let notif_repo = MockNotifRepo::new();++ let result = process_push_notifications_inner(+ user_device_endpoints,+ ¬ifications,+ sns_client.clone(),+ notif_repo,+ )+ .await;++ assert!(result.is_ok());+ let users_sent = result.unwrap();+ assert_eq!(users_sent.len(), 1);+ assert!(users_sent.contains(&make_user_id("[email protected]")));+}++#[tokio::test]+async fn test_process_push_notifications_inner_android_not_implemented() {+ let user_id = make_user_id("[email protected]");+ let notif = create_test_notification(Uuid::new_v4(), "[email protected]", "msg_1");++ let mut notifications = HashMap::new();+ notifications.insert(user_id.clone(), vec![notif]);++ let mut user_device_endpoints = HashMap::new();+ user_device_endpoints.insert(+ user_id.clone(),+ vec![(+ "arn:aws:sns:us-east-1:123:endpoint/GCM/app/device".to_string(),+ DeviceType::Android,+ )],+ );++ let sns_client = Arc::new(MockSnsClient::new());++ let result = process_push_notifications_inner(+ user_device_endpoints,+ ¬ifications,+ sns_client.clone(),+ MockNotifRepo::new(),+ )+ .await;++ assert!(result.is_ok());+ let users_sent = result.unwrap();+ // Android is not implemented, so no push should be sent+ assert!(users_sent.is_empty());+}++#[tokio::test]+async fn test_process_push_notifications_inner_multiple_users() {+ let user_1 = make_user_id("[email protected]");+ let user_2 = make_user_id("[email protected]");+ let notif_1 = create_test_notification(Uuid::new_v4(), "[email protected]", "msg_1");+ let notif_2 = create_test_notification(Uuid::new_v4(), "[email protected]", "msg_2");++ let mut notifications = HashMap::new();+ notifications.insert(user_1.clone(), vec![notif_1]);+ notifications.insert(user_2.clone(), vec![notif_2]);++ let mut user_device_endpoints = HashMap::new();+ user_device_endpoints.insert(+ user_1.clone(),+ vec![(+ "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),+ DeviceType::Ios,+ )],+ );+ user_device_endpoints.insert(+ user_2.clone(),+ vec![(+ "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device2".to_string(),+ DeviceType::Ios,+ )],+ );++ let sns_client = Arc::new(MockSnsClient::new());++ let result = process_push_notifications_inner(+ user_device_endpoints,+ ¬ifications,+ sns_client.clone(),+ MockNotifRepo::new(),+ )+ .await;++ assert!(result.is_ok());+ let users_sent = result.unwrap();+ assert_eq!(users_sent.len(), 2);+ assert!(users_sent.contains(&user_1));+ assert!(users_sent.contains(&user_2));+}++#[tokio::test]+async fn test_process_push_notifications_inner_user_with_multiple_devices() {+ let user_id = make_user_id("[email protected]");+ let notif = create_test_notification(Uuid::new_v4(), "[email protected]", "msg_1");++ let mut notifications = HashMap::new();+ notifications.insert(user_id.clone(), vec![notif]);++ let mut user_device_endpoints = HashMap::new();+ user_device_endpoints.insert(+ user_id.clone(),+ vec![+ (+ "arn:aws:sns:us-east-1:123:endpoint/APNS/app/iphone".to_string(),+ DeviceType::Ios,+ ),+ (+ "arn:aws:sns:us-east-1:123:endpoint/APNS/app/ipad".to_string(),+ DeviceType::Ios,+ ),+ ],+ );++ let sns_client = Arc::new(MockSnsClient::new());++ let result = process_push_notifications_inner(+ user_device_endpoints,+ ¬ifications,+ sns_client.clone(),+ MockNotifRepo::new(),+ )+ .await;++ assert!(result.is_ok());+ let users_sent = result.unwrap();+ // User should still only appear once in the result set+ assert_eq!(users_sent.len(), 1);+ assert!(users_sent.contains(&user_id));+}++#[tokio::test]+async fn test_process_push_notifications_inner_sns_failure_skips_user() {+ let user_id = make_user_id("[email protected]");+ let notif = create_test_notification(Uuid::new_v4(), "[email protected]", "msg_1");++ let mut notifications = HashMap::new();+ notifications.insert(user_id.clone(), vec![notif]);++ let mut user_device_endpoints = HashMap::new();+ user_device_endpoints.insert(+ user_id.clone(),+ vec![(+ "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device".to_string(),+ DeviceType::Ios,+ )],+ );++ let sns_client = Arc::new(MockSnsClient::failing());++ let result = process_push_notifications_inner(+ user_device_endpoints,+ ¬ifications,+ sns_client,+ MockNotifRepo::new(),+ )+ .await;++ assert!(result.is_ok());+ let users_sent = result.unwrap();+ // SNS failed, so user should not be in the sent set+ assert!(users_sent.is_empty());+}++#[tokio::test]+async fn test_process_push_notifications_inner_empty_notifications() {+ let notifications: HashMap<MacroUserIdStr<'static>, Vec<NotificationWithRecipient>> =+ HashMap::new();+ let user_device_endpoints: HashMap<MacroUserIdStr<'static>, Vec<(String, DeviceType)>> =+ HashMap::new();++ let result = process_push_notifications_inner(+ user_device_endpoints,+ ¬ifications,+ Arc::new(MockSnsClient::new()),+ MockNotifRepo::new(),+ )+ .await;++ assert!(result.is_ok());+ assert!(result.unwrap().is_empty());+}++#[tokio::test]+async fn test_process_push_notifications_inner_notification_without_matching_device() {+ let user_1 = make_user_id("[email protected]");+ let user_2 = make_user_id("[email protected]");+ let notif = create_test_notification(Uuid::new_v4(), "[email protected]", "msg_1");++ let mut notifications = HashMap::new();+ notifications.insert(user_1.clone(), vec![notif]);++ // Device endpoints only for user_2, not user_1+ let mut user_device_endpoints = HashMap::new();+ user_device_endpoints.insert(+ user_2.clone(),+ vec![(+ "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device".to_string(),+ DeviceType::Ios,+ )],+ );++ let result = process_push_notifications_inner(+ user_device_endpoints,+ ¬ifications,+ Arc::new(MockSnsClient::new()),+ MockNotifRepo::new(),+ )+ .await;++ assert!(result.is_ok());+ let users_sent = result.unwrap();+ // user_1 has notification but no device, user_2 has device but no notification+ assert!(users_sent.is_empty());+}diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/remove.rs b/rust/cloud-storage/notification_service/src/notification/send/push/remove.rsindex 3cfed2b30a..f9460af36a 100644--- a/rust/cloud-storage/notification_service/src/notification/send/push/remove.rs+++ b/rust/cloud-storage/notification_service/src/notification/send/push/remove.rs@@ -1,10 +1,10 @@use crate::{api::context::ApiContext, config::APPLE_BUNDLE_ID};use anyhow::Context;use futures::StreamExt;-use notification_db_client::notification::get::BasicNotification;+use notification_db_client::notification::get::DbBasicNotification;use serde::Serialize;-use sns_client::{APNSPushNotification, MessageAttributes, NotifCollapseKey, PushType, SnsTarget};-use std::hash::{DefaultHasher, Hash, Hasher};+use sns_client::{APNSPushNotification, MessageAttributes, PushType, SnsTarget};+use std::borrow::Cow;/// Clears out push notifications for a user in bulk#[tracing::instrument(skip(ctx))]@@ -42,23 +42,18 @@ pub fn clear_push_notifications(.then(|notification_id| {let sns_client = sns_client.clone();let db = db.clone();- let user_id = user_id.clone();let device_endpoints = device_endpoints.clone();async move {- if let Err(e) =- clear_push_notification(+ let notif =+ notification_db_client::notification::get::get_basic_notification(&db,- &sns_client,- &device_endpoints,- Some(¬ification_id.to_string()),- None,+ notification_id,)- .await- {- tracing::error!(error=?e, notification_id=notification_id.to_string(), user_id=user_id, "failed to remove push notification");- }+ .await?+ .transpose()+ .context("Cannot clear a notification without an apns collapse key")?;- Ok(())+ clear_push_notification(&sns_client, &device_endpoints, notif).await}}).collect::<Vec<anyhow::Result<()>>>()@@ -73,38 +68,15 @@ pub fn clear_push_notifications(/// When a notification is marked as "done" or "seen" for a user, we need to potentially send a/// remove notification sns notification to the user to clear it from their device.-#[tracing::instrument(skip(db, sns_client))]+#[tracing::instrument(err, skip(sns_client))]pub async fn clear_push_notification(- db: &sqlx::Pool<sqlx::Postgres>,sns_client: &sns_client::SNS,device_endpoints: &[String],- notification_id: Option<&str>,- basic_notification: Option<&BasicNotification>,+ basic_notification: DbBasicNotification<String>,) -> anyhow::Result<()> {// As of right now, we can only do this for APNS notifications since android requires a// custom push notification handler in order to clear the notification on the mobile application side- let BasicNotification {- event_item_id,- event_item_type: _,- notification_event_type,- } = if let Some(basic_notification) = basic_notification {- basic_notification- } else {- ¬ification_db_client::notification::get::get_basic_notification(- db,- notification_id.context("expected notification_id")?,- )- .await- .context("failed to get notification")?- };-- let collapse_key = format!("{}{}", event_item_id, notification_event_type);-- // hash the collapse key to shorten it- let mut hasher = DefaultHasher::new();- collapse_key.hash(&mut hasher);- let hash = hasher.finish();- let collapse_key = format!("{:x}", hash);+ let collapse_key = basic_notification.apns_collapse_key;#[derive(Debug, Serialize, Clone)]struct CustomData {@@ -123,7 +95,7 @@ pub async fn clear_push_notification(let attributes = MessageAttributes {push_type: PushType::Background,apns_bundle_id: &APPLE_BUNDLE_ID,- collapse_key: NotifCollapseKey::new_str(&collapse_key),+ collapse_key,};futures::stream::iter(device_endpoints.iter())@@ -132,12 +104,9 @@ pub async fn clear_push_notification(tracing::trace!("skipping non-apns endpoint");return;}- if let Err(e) = sns_client+ let _ = sns_client.push_notification(endpoint, &apns, attributes.clone())- .await- {- tracing::warn!(error=?e, "unable to send push notification");- }+ .await;}).collect::<Vec<_>>().await;@@ -146,50 +115,36 @@ pub async fn clear_push_notification(}/// Clears out push notifications for a user by notification event-#[tracing::instrument(skip(ctx))]+#[tracing::instrument(err, skip(ctx))]pub async fn clear_push_notifications_basic(ctx: ApiContext,- user_id: &str,- notification: &BasicNotification,+ user_id: Cow<'_, str>,+ notification: DbBasicNotification<Option<String>>,) -> anyhow::Result<()> {tracing::trace!("clearing potential push notifications");- tokio::spawn({- let db = ctx.db.clone();- let sns_client = ctx.sns_client.clone();- let user_id = user_id.to_string();- let basic_notification = notification.clone();- async move {- tracing::trace!("removing push notifications");+ let db = ctx.db.clone();+ let sns_client = ctx.sns_client.clone();+ let user_id = user_id.to_string();+ tracing::trace!("removing push notifications");- let device_endpoints =- notification_db_client::device::get_user_device_endpoints(&db, &user_id)- .await- .inspect_err(|e| {- tracing::error!(error=?e, "failed to get device endpoints");- })- .unwrap_or(Vec::new());+ let device_endpoints = notification_db_client::device::get_user_device_endpoints(&db, &user_id)+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, "failed to get device endpoints");+ })+ .unwrap_or(Vec::new());- if device_endpoints.is_empty() {- tracing::trace!(- "user has no device endpoints, skipping push notification clearing"- );- return;- }- if let Err(e) = clear_push_notification(- &db,- &sns_client,- &device_endpoints,- None,- Some(&basic_notification),- )- .await- {- tracing::error!(error=?e, basic_notification=?basic_notification, user_id=user_id, "failed to remove push notification");- }+ if device_endpoints.is_empty() {+ tracing::trace!("user has no device endpoints, skipping push notification clearing");+ return Ok(());+ }- tracing::trace!(basic_notification=?basic_notification, user_id=user_id, "removing push notifications complete");- }- });+ let Some(basic_notification) = notification.transpose() else {+ tracing::trace!("cannot clear a notification that is missing a collapse key");+ return Ok(());+ };++ let _ = clear_push_notification(&sns_client, &device_endpoints, basic_notification).await;Ok(())}diff --git a/rust/cloud-storage/sns_client/src/lib.rs b/rust/cloud-storage/sns_client/src/lib.rsindex adacc4fa0e..838454574f 100644--- a/rust/cloud-storage/sns_client/src/lib.rs+++ b/rust/cloud-storage/sns_client/src/lib.rs@@ -1,6 +1,6 @@use aws_sdk_sns::{operation::publish::PublishOutput, types::MessageAttributeValue};use serde::{Serialize, Serializer};-use std::{borrow::Cow, collections::HashMap};+use std::collections::HashMap;#[derive(Clone, Debug)]pub struct SNS {@@ -105,12 +105,13 @@ pub enum InterruptionLevel {Critical,}-// Your updated struct#[derive(Serialize, Debug)]#[serde(rename_all = "camelCase")]pub struct APNSPushNotification<T> {pub aps: Aps,+ /// custom data payload to send to the client.+ /// This data has no effect on 'how' the notification is delivered#[serde(flatten)]pub push_notification_data: T,}@@ -258,22 +259,13 @@ impl PushType {}#[derive(Debug, Clone)]-pub struct NotifCollapseKey<'a>(pub Cow<'a, str>);--impl<'a> NotifCollapseKey<'a> {- pub fn new_str(s: &'a str) -> Self {- NotifCollapseKey(Cow::Borrowed(s))- }-}--#[derive(Debug, Clone)]-pub struct MessageAttributes<'a> {+pub struct MessageAttributes {pub push_type: PushType,pub apns_bundle_id: &'static str,- pub collapse_key: NotifCollapseKey<'a>,+ pub collapse_key: String,}-impl<'a> MessageAttributes<'a> {+impl MessageAttributes {pub fn into_json(self) -> HashMap<String, MessageAttributeValue> {HashMap::from([(@@ -304,7 +296,7 @@ impl<'a> MessageAttributes<'a> {"AWS.SNS.MOBILE.APNS.COLLAPSE_ID".to_string(),MessageAttributeValue::builder().data_type("String")- .string_value(self.collapse_key.0.into_owned())+ .string_value(self.collapse_key).build().unwrap(),),@@ -312,6 +304,32 @@ impl<'a> MessageAttributes<'a> {}}+pub trait NotificationSender: Send + Sync + 'static {+ fn push_notification<T>(+ &self,+ endpoint_arn: &str,+ message_json: &SnsTarget<T>,+ message_attributes: MessageAttributes,+ ) -> impl Future<Output = anyhow::Result<PublishOutput>> + Send+ where+ T: Serialize + std::fmt::Debug + Sync;+}++impl NotificationSender for SNS {+ async fn push_notification<T>(+ &self,+ endpoint_arn: &str,+ message_json: &SnsTarget<T>,+ message_attributes: MessageAttributes,+ ) -> anyhow::Result<PublishOutput>+ where+ T: Serialize + std::fmt::Debug + Sync,+ {+ self.push_notification(endpoint_arn, message_json, message_attributes)+ .await+ }+}+impl SNS {pub fn new(inner: aws_sdk_sns::Client) -> Self {Self { inner }@@ -410,7 +428,7 @@ impl SNS {&self,endpoint_arn: &str,message_json: &SnsTarget<T>,- message_attributes: MessageAttributes<'_>,+ message_attributes: MessageAttributes,) -> anyhow::Result<PublishOutput>whereT: Serialize + std::fmt::Debug,