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.

Seanaye/feat/realtime notifs (#3406)

Sean Aye65937658c91e
diff --git a/rust/cloud-storage/.sqlx/query-015a45b5c16b4bcc135372478d585af4ce10f5f6ae5e3578637b66655ea6d67e.json b/rust/cloud-storage/.sqlx/query-015a45b5c16b4bcc135372478d585af4ce10f5f6ae5e3578637b66655ea6d67e.json
new file mode 100644
index 0000000000..4d54ccbb50
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-015a45b5c16b4bcc135372478d585af4ce10f5f6ae5e3578637b66655ea6d67e.json
@@ -0,0 +1,42 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH updated AS (\n UPDATE user_notification\n SET done = $3\n WHERE user_id = $1 AND notification_id = ANY($2) AND deleted_at IS NULL\n RETURNING notification_id, done, seen_at::timestamptz as viewed_at\n )\n SELECT\n updated.notification_id,\n updated.done,\n updated.viewed_at,\n NOW()::timestamptz as \"updated_at!\"\n FROM updated\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "notification_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "done",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 2,
+ "name": "viewed_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 3,
+ "name": "updated_at!",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "UuidArray",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "015a45b5c16b4bcc135372478d585af4ce10f5f6ae5e3578637b66655ea6d67e"
+}
diff --git a/rust/cloud-storage/.sqlx/query-3293eab63193f1b3822a59e9a6a9621520f26e6ec8248abed103985281ef7ff1.json b/rust/cloud-storage/.sqlx/query-3293eab63193f1b3822a59e9a6a9621520f26e6ec8248abed103985281ef7ff1.json
deleted file mode 100644
index e4a18ac5f0..0000000000
--- a/rust/cloud-storage/.sqlx/query-3293eab63193f1b3822a59e9a6a9621520f26e6ec8248abed103985281ef7ff1.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE user_notification\n SET done = $3\n WHERE user_id = $1 AND notification_id = ANY($2)\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text",
- "UuidArray",
- "Bool"
- ]
- },
- "nullable": []
- },
- "hash": "3293eab63193f1b3822a59e9a6a9621520f26e6ec8248abed103985281ef7ff1"
-}
diff --git a/rust/cloud-storage/.sqlx/query-8284a5f2fb0c00c676f11b91457b8338692087d259f3c0dc0975b6b2053a7b45.json b/rust/cloud-storage/.sqlx/query-8284a5f2fb0c00c676f11b91457b8338692087d259f3c0dc0975b6b2053a7b45.json
new file mode 100644
index 0000000000..42aa0d66c3
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-8284a5f2fb0c00c676f11b91457b8338692087d259f3c0dc0975b6b2053a7b45.json
@@ -0,0 +1,41 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH updated AS (\n UPDATE user_notification\n SET seen_at = NOW()\n WHERE user_id = $1 AND notification_id = ANY($2) AND deleted_at IS NULL\n RETURNING notification_id, done, seen_at::timestamptz as viewed_at\n )\n SELECT\n updated.notification_id,\n updated.done,\n updated.viewed_at,\n NOW()::timestamptz as \"updated_at!\"\n FROM updated\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "notification_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "done",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 2,
+ "name": "viewed_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 3,
+ "name": "updated_at!",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "8284a5f2fb0c00c676f11b91457b8338692087d259f3c0dc0975b6b2053a7b45"
+}
diff --git a/rust/cloud-storage/.sqlx/query-a5d9f358b5382c0eaed918f903bc6aa328f527e6e47d649c37dfcf1c9f3a7139.json b/rust/cloud-storage/.sqlx/query-a5d9f358b5382c0eaed918f903bc6aa328f527e6e47d649c37dfcf1c9f3a7139.json
deleted file mode 100644
index 7626c0a06b..0000000000
--- a/rust/cloud-storage/.sqlx/query-a5d9f358b5382c0eaed918f903bc6aa328f527e6e47d649c37dfcf1c9f3a7139.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE user_notification\n SET seen_at = NOW()\n WHERE user_id = $1 AND notification_id = ANY($2)\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text",
- "UuidArray"
- ]
- },
- "nullable": []
- },
- "hash": "a5d9f358b5382c0eaed918f903bc6aa328f527e6e47d649c37dfcf1c9f3a7139"
-}
diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rs
index 5f01e4dc0f..762f9d1b0e 100644
--- a/rust/cloud-storage/ai_tools/src/build_context.rs
+++ b/rust/cloud-storage/ai_tools/src/build_context.rs
@@ -251,16 +251,17 @@ pub async fn build_tool_service_context_from_env(
(*entity_access_service).clone(),
);
- let notification_reader_service = NotificationReaderService::new(
- DbNotificationRepository::new(pool.clone()),
- notification_queue,
- NoOpSnsEndpointManager,
- PlatformArnConfig {
+ let notification_reader_service = NotificationReaderService {
+ repository: DbNotificationRepository::new(pool.clone()),
+ queue: notification_queue,
+ sns_endpoint: NoOpSnsEndpointManager,
+ platform_config: PlatformArnConfig {
apns_platform_arn: String::new(),
fcm_platform_arn: String::new(),
apns_voip_platform_arn: String::new(),
},
- );
+ realtime: notification::domain::ports::NoopNotificationRealtimePublisher,
+ };
let notification_tool_context =
notification::inbound::ai_tool::NotificationToolContext::new(notification_reader_service);
diff --git a/rust/cloud-storage/connection_gateway_client/src/client/email.rs b/rust/cloud-storage/connection_gateway_client/src/client/email.rs
index 56d7d8b374..c4ae6c8cd6 100644
--- a/rust/cloud-storage/connection_gateway_client/src/client/email.rs
+++ b/rust/cloud-storage/connection_gateway_client/src/client/email.rs
@@ -1,5 +1,6 @@
use super::ConnectionGatewayClient;
use connection_gateway_models::MessageReceipt;
+use model_entity::EntityType;
use serde_json::json;
impl ConnectionGatewayClient {
@@ -11,8 +12,7 @@ impl ConnectionGatewayClient {
event_type: &str,
) -> anyhow::Result<Vec<MessageReceipt>> {
self.send_message(
- "user",
- user_id,
+ EntityType::User.with_entity_str(user_id),
"refresh_email".to_string(),
json!(event_type),
)
diff --git a/rust/cloud-storage/connection_gateway_client/src/client/mod.rs b/rust/cloud-storage/connection_gateway_client/src/client/mod.rs
index 8cf5a158f4..47a04fd121 100644
--- a/rust/cloud-storage/connection_gateway_client/src/client/mod.rs
+++ b/rust/cloud-storage/connection_gateway_client/src/client/mod.rs
@@ -8,7 +8,6 @@ use connection_gateway_models::{
use model_entity::Entity;
mod email;
-mod project;
/// HTTP client for communicating with the connection gateway service.
#[derive(Clone, Debug)]
@@ -39,11 +38,10 @@ impl ConnectionGatewayClient {
}
}
- /// Send a message to an entity
+ /// Send a message to an entity.
pub async fn send_message(
&self,
- entity_type: &str,
- entity_id: &str,
+ entity: Entity<'_>,
message_type: String,
message: serde_json::Value,
) -> anyhow::Result<Vec<MessageReceipt>> {
@@ -56,7 +54,7 @@ impl ConnectionGatewayClient {
.client
.post(format!(
"{}/message/send/{}/{}",
- self.connection_gateway_url, entity_type, entity_id
+ self.connection_gateway_url, entity.entity_type, entity.entity_id
))
.json(&body)
.send()
@@ -121,17 +119,13 @@ impl ConnectionGatewayClient {
Ok(receipts.receipts)
}
- /// Get users who are interacting with a given item
- pub async fn track_entity_users(
- &self,
- entity_type: String,
- entity_id: String,
- ) -> anyhow::Result<Vec<String>> {
+ /// Get users who are interacting with a given entity.
+ pub async fn track_entity_users(&self, entity: Entity<'_>) -> anyhow::Result<Vec<String>> {
let res = self
.client
.get(format!(
"{}/track/{}/{}",
- self.connection_gateway_url, entity_type, entity_id
+ self.connection_gateway_url, entity.entity_type, entity.entity_id
))
.send()
.await?;
diff --git a/rust/cloud-storage/connection_gateway_client/src/client/project.rs b/rust/cloud-storage/connection_gateway_client/src/client/project.rs
deleted file mode 100644
index c7f4418c16..0000000000
--- a/rust/cloud-storage/connection_gateway_client/src/client/project.rs
+++ /dev/null
@@ -1,18 +0,0 @@
-use super::ConnectionGatewayClient;
-use connection_gateway_models::MessageReceipt;
-use serde_json::json;
-
-impl ConnectionGatewayClient {
- /// Send a project update notification
- #[tracing::instrument(skip(self))]
- pub async fn project_update(&self, project_id: &str) -> anyhow::Result<Vec<MessageReceipt>> {
- tracing::info!(project_id, "sending project update");
- self.send_message(
- "project",
- project_id,
- "update".to_string(),
- json!(project_id),
- )
- .await
- }
-}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index 90415332b7..35c619ed21 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -192,16 +192,17 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
aws_sdk_sqs::Client::from_conf(sqs_config),
"test-notification-queue".to_string(),
);
- let notification_reader_service = NotificationReaderService::new(
- DbNotificationRepository::new(pool.clone()),
- ai_tools::ToolNotificationQueue::Sqs(notification_reader_queue),
- ai_tools::NoOpSnsEndpointManager,
- PlatformArnConfig {
+ let notification_reader_service = NotificationReaderService {
+ repository: DbNotificationRepository::new(pool.clone()),
+ queue: ai_tools::ToolNotificationQueue::Sqs(notification_reader_queue),
+ sns_endpoint: ai_tools::NoOpSnsEndpointManager,
+ platform_config: PlatformArnConfig {
apns_platform_arn: String::new(),
fcm_platform_arn: String::new(),
apns_voip_platform_arn: String::new(),
},
- );
+ realtime: notification::domain::ports::NoopNotificationRealtimePublisher,
+ };
let notification_tool_context =
notification::inbound::ai_tool::NotificationToolContext::new(notification_reader_service);
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index f01816a2e3..8815b7b039 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -182,16 +182,17 @@ async fn main() -> anyhow::Result<()> {
aws_sdk_sqs::Client::new(&aws_config),
config.notification_queue.clone(),
);
- let notification_reader_service = NotificationReaderService::new(
- DbNotificationRepository::new(db.clone()),
- ai_tools::ToolNotificationQueue::Sqs(notification_reader_queue),
- ai_tools::NoOpSnsEndpointManager,
- PlatformArnConfig {
+ let notification_reader_service = NotificationReaderService {
+ repository: DbNotificationRepository::new(db.clone()),
+ queue: ai_tools::ToolNotificationQueue::Sqs(notification_reader_queue),
+ sns_endpoint: ai_tools::NoOpSnsEndpointManager,
+ platform_config: PlatformArnConfig {
apns_platform_arn: String::new(),
fcm_platform_arn: String::new(),
apns_voip_platform_arn: String::new(),
},
- );
+ realtime: notification::domain::ports::NoopNotificationRealtimePublisher,
+ };
let notification_tool_context =
notification::inbound::ai_tool::NotificationToolContext::new(notification_reader_service);
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260520152848_notify_user_notif_deletes.sql b/rust/cloud-storage/macro_db_client/migrations/20260520152848_notify_user_notif_deletes.sql
new file mode 100644
index 0000000000..3b21e8a211
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260520152848_notify_user_notif_deletes.sql
@@ -0,0 +1,42 @@
+-- Notify notification-service when deleting notifications removes user_notification rows.
+--
+-- The existing FK from user_notification.notification_id to notification.id uses
+-- ON DELETE CASCADE. This BEFORE DELETE trigger runs while those rows are still
+-- visible, so listeners can learn which users need realtime notification-delete
+-- updates before the cascade removes the rows.
+
+CREATE OR REPLACE FUNCTION notify_user_notification_deletes()
+RETURNS TRIGGER AS $$
+DECLARE
+ affected_user_ids JSONB;
+BEGIN
+ SELECT jsonb_agg(user_id)
+ INTO affected_user_ids
+ FROM user_notification
+ WHERE notification_id = OLD.id;
+
+ IF affected_user_ids IS NOT NULL THEN
+ BEGIN
+ PERFORM pg_notify(
+ 'notification_events',
+ jsonb_build_object(
+ 'type', 'user_notification_deletes',
+ 'notificationId', OLD.id,
+ 'userIds', affected_user_ids
+ )::TEXT
+ );
+ EXCEPTION WHEN OTHERS THEN
+ RAISE WARNING 'pg_notify failed: %', SQLERRM;
+ END;
+ END IF;
+
+ RETURN OLD;
+END;
+$$ LANGUAGE plpgsql;
+
+DROP TRIGGER IF EXISTS trg_notify_user_notification_deletes ON notification;
+
+CREATE TRIGGER trg_notify_user_notification_deletes
+BEFORE DELETE ON notification
+FOR EACH ROW
+EXECUTE FUNCTION notify_user_notification_deletes();
diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rs
index 5ebc7b7043..a130fddb79 100644
--- a/rust/cloud-storage/mcp_service/src/context.rs
+++ b/rust/cloud-storage/mcp_service/src/context.rs
@@ -275,16 +275,17 @@ async fn build_tool_context(
EntityAccessServiceImpl::new(PgAccessRepository::new(db.clone())),
);
- let notification_reader_service = NotificationReaderService::new(
- DbNotificationRepository::new(db.clone()),
- ToolNotificationQueue::NoOp,
- NoOpSnsEndpointManager,
- PlatformArnConfig {
+ let notification_reader_service = NotificationReaderService {
+ repository: DbNotificationRepository::new(db.clone()),
+ queue: ToolNotificationQueue::NoOp,
+ sns_endpoint: NoOpSnsEndpointManager,
+ platform_config: PlatformArnConfig {
apns_platform_arn: String::new(),
fcm_platform_arn: String::new(),
apns_voip_platform_arn: String::new(),
},
- );
+ realtime: notification::domain::ports::NoopNotificationRealtimePublisher,
+ };
let notification_tool_context =
notification::inbound::ai_tool::NotificationToolContext::new(notification_reader_service);
diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rs
index 60759fa6e2..fd172ac191 100644
--- a/rust/cloud-storage/memory/src/context.rs
+++ b/rust/cloud-storage/memory/src/context.rs
@@ -173,16 +173,17 @@ pub async fn build_tool_service_context(
(*entity_access_service).clone(),
);
- let notification_reader_service = NotificationReaderService::new(
- DbNotificationRepository::new(pool.clone()),
- ToolNotificationQueue::NoOp,
- NoOpSnsEndpointManager,
- PlatformArnConfig {
+ let notification_reader_service = NotificationReaderService {
+ repository: DbNotificationRepository::new(pool.clone()),
+ queue: ToolNotificationQueue::NoOp,
+ sns_endpoint: NoOpSnsEndpointManager,
+ platform_config: PlatformArnConfig {
apns_platform_arn: String::new(),
fcm_platform_arn: String::new(),
apns_voip_platform_arn: String::new(),
},
- );
+ realtime: notification::domain::ports::NoopNotificationRealtimePublisher,
+ };
let notification_tool_context =
notification::inbound::ai_tool::NotificationToolContext::new(notification_reader_service);
diff --git a/rust/cloud-storage/notification/src/domain/models.rs b/rust/cloud-storage/notification/src/domain/models.rs
index 0785b3a058..515731457f 100644
--- a/rust/cloud-storage/notification/src/domain/models.rs
+++ b/rust/cloud-storage/notification/src/domain/models.rs
@@ -24,6 +24,7 @@ pub use recipient::{ExclusionReason, FilteredRecipient, RecipientExclusion};
pub use request::{NotificationResult, SendNotificationRequest, SendNotificationRequestBuilder};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::{borrow::Cow, sync::Arc};
+use uuid::Uuid;
/// Notification ID paired with its APNS collapse key, for push clearing.
#[derive(Debug, Clone)]
@@ -34,6 +35,70 @@ pub struct NotificationIdAndCollapseKey {
pub apns_collapse_key: String,
}
+/// A compact patch describing user notification status fields that changed.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct NotificationStatusPatch {
+ /// Whether the notification is marked as done after the update.
+ pub done: bool,
+ /// 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, Serialize, Deserialize)]
+#[serde(untagged)]
+pub enum PatchDelete<I, T> {
+ /// The value with id I should be patched with data T.
+ Patch {
+ /// The id to patch.
+ id: I,
+ /// The data to patch.
+ #[serde(flatten)]
+ diff: T,
+ },
+ /// The value with id I should be deleted.
+ Delete {
+ /// The id to delete.
+ id: I,
+ },
+}
+
+/// Realtime payload emitted when notification seen/done state changes.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NotificationStatusUpdate {
+ /// Constant event discriminator for frontend consumers.
+ #[serde(rename = "type")]
+ pub event_type: String,
+ /// The changed notification rows.
+ pub updates: Vec<PatchDelete<Uuid, NotificationStatusPatch>>,
+}
+
+/// A realtime notification status update scoped to one user.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct UserNotificationStatusUpdate<'a> {
+ /// The user who should receive the update.
+ pub user: MacroUserIdStr<'a>,
+ /// The status update payload for that user.
+ pub update: NotificationStatusUpdate,
+}
+
+impl NotificationStatusUpdate {
+ /// 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, NotificationStatusPatch>>) -> 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
diff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rs
index 777804d10d..5c9a42f72e 100644
--- a/rust/cloud-storage/notification/src/domain/ports.rs
+++ b/rust/cloud-storage/notification/src/domain/ports.rs
@@ -15,14 +15,14 @@ use uuid::Uuid;
use models_pagination::{CreatedAt, Query};
-use crate::domain::models::TaggedContent;
use crate::domain::models::device::DeviceType;
+use crate::domain::models::{PatchDelete, TaggedContent, UserNotificationStatusUpdate};
use crate::domain::models::email_notification_digest::ports::{ClaimResult, DigestBatch};
use crate::domain::models::request::NotificationListFilters;
use crate::domain::models::{
DeviceEndpoint, DisabledNotificationType, NotificationExtEmail, NotificationIdAndCollapseKey,
- SendNotificationRequestBuilder, UserNotificationRow,
+ NotificationStatusPatch, SendNotificationRequestBuilder, UserNotificationRow,
android::FCMMessage,
apple::{APNSPushNotification, VoipPushPayload},
mobile::MessageAttributes,
@@ -98,7 +98,7 @@ pub trait NotificationRepository: Send + Sync + 'static {
&self,
user_id: MacroUserIdStr<'_>,
notification_ids: &[Uuid],
- ) -> impl Future<Output = Result<(), Report>> + Send;
+ ) -> impl Future<Output = Result<Vec<PatchDelete<Uuid, NotificationStatusPatch>>, Report>> + Send;
/// Mark notifications as done or undone for a user.
fn mark_notifications_done(
@@ -106,7 +106,7 @@ pub trait NotificationRepository: Send + Sync + 'static {
user_id: &MacroUserIdStr<'_>,
notification_ids: &[Uuid],
done: bool,
- ) -> impl Future<Output = Result<(), Report>> + Send;
+ ) -> impl Future<Output = Result<Vec<PatchDelete<Uuid, NotificationStatusPatch>>, Report>> + Send;
/// Get basic notification data (collapse keys) needed for push clearing.
fn get_basic_notifications(
@@ -227,6 +227,31 @@ pub trait NotificationRepository: Send + Sync + 'static {
) -> impl Future<Output = Result<(), Report>> + Send;
}
+/// Port for receiving realtime notification database events.
+pub trait NotificationEventsReceiver: Send + 'static {
+ /// Receive the next raw notification database event payload.
+ fn receive(&mut self) -> impl Future<Output = Result<String, Report>> + Send;
+}
+
+/// Port for publishing realtime notification updates.
+pub trait NotificationRealtimePublisher: Send + Sync + 'static {
+ /// Publish notification status updates to the users who own the notifications.
+ fn publish_updates(
+ &self,
+ updates: &[UserNotificationStatusUpdate<'_>],
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+}
+
+/// No-op realtime publisher for consumers that do not wire connection gateway.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct NoopNotificationRealtimePublisher;
+
+impl NotificationRealtimePublisher for NoopNotificationRealtimePublisher {
+ async fn publish_updates(&self, _: &[UserNotificationStatusUpdate<'_>]) -> Result<(), Report> {
+ Ok(())
+ }
+}
+
/// Port for WebSocket delivery via connection gateway.
pub trait WebSocketSender: Send + Sync + 'static {
/// Send notifications to users via WebSocket.
diff --git a/rust/cloud-storage/notification/src/domain/service/device/test.rs b/rust/cloud-storage/notification/src/domain/service/device/test.rs
index fa9c9b8bb1..238eaf406d 100644
--- a/rust/cloud-storage/notification/src/domain/service/device/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/device/test.rs
@@ -132,7 +132,15 @@ impl NotificationRepository for MockNotifRepo {
&self,
_: macro_user_id::user_id::MacroUserIdStr<'_>,
_: &[uuid::Uuid],
- ) -> Result<(), Report> {
+ ) -> Result<
+ Vec<
+ crate::domain::models::PatchDelete<
+ uuid::Uuid,
+ crate::domain::models::NotificationStatusPatch,
+ >,
+ >,
+ Report,
+ > {
unimplemented!()
}
async fn mark_notifications_done(
@@ -140,7 +148,15 @@ impl NotificationRepository for MockNotifRepo {
_: &macro_user_id::user_id::MacroUserIdStr<'_>,
_: &[uuid::Uuid],
_: bool,
- ) -> Result<(), Report> {
+ ) -> Result<
+ Vec<
+ crate::domain::models::PatchDelete<
+ uuid::Uuid,
+ crate::domain::models::NotificationStatusPatch,
+ >,
+ >,
+ Report,
+ > {
unimplemented!()
}
async fn get_basic_notifications(
@@ -340,7 +356,13 @@ fn make_service(
db: MockNotifRepo,
sns: MockSnsManager,
) -> NotificationReaderService<MockNotifRepo, MockQueue, MockSnsManager> {
- NotificationReaderService::new(db, MockQueue, sns, test_config())
+ NotificationReaderService {
+ repository: db,
+ queue: MockQueue,
+ sns_endpoint: sns,
+ platform_config: test_config(),
+ realtime: crate::domain::ports::NoopNotificationRealtimePublisher,
+ }
}
// ─── Register Tests ──────────────────────────────────────────────────────
diff --git a/rust/cloud-storage/notification/src/domain/service/ingress.rs b/rust/cloud-storage/notification/src/domain/service/ingress.rs
index d44f56c2ee..22b1bf0535 100644
--- a/rust/cloud-storage/notification/src/domain/service/ingress.rs
+++ b/rust/cloud-storage/notification/src/domain/service/ingress.rs
@@ -18,10 +18,12 @@ use crate::domain::models::request::{
};
use crate::domain::models::{
DeviceEndpoint, DisabledNotificationType, Notification, NotificationResult,
- NotificationTypeName, UserNotificationRow,
+ NotificationStatusUpdate, NotificationTypeName, UserNotificationRow,
+ UserNotificationStatusUpdate,
};
use crate::domain::ports::{
- NotificationIngressQueue, NotificationQueue, NotificationRepository, SnsEndpointManager,
+ NoopNotificationRealtimePublisher, NotificationIngressQueue, NotificationQueue,
+ NotificationRealtimePublisher, NotificationRepository, SnsEndpointManager,
};
use crate::domain::service::SendNotificationError;
use ::futures::future::join_all;
@@ -442,34 +444,26 @@ pub struct PlatformArnConfig {
///
/// Handles notification queries, status updates, and deletion.
/// Does not require a bulk-digest state machine.
-pub struct NotificationReaderService<N, Q, S> {
- pub(crate) repository: N,
- pub(crate) queue: Q,
- pub(crate) sns_endpoint: S,
- pub(crate) platform_config: PlatformArnConfig,
+pub struct NotificationReaderService<N, Q, S, R = NoopNotificationRealtimePublisher> {
+ /// Notification repository.
+ pub repository: N,
+ /// Queue used to enqueue notification work.
+ pub queue: Q,
+ /// SNS endpoint manager.
+ pub sns_endpoint: S,
+ /// Platform ARN configuration.
+ pub platform_config: PlatformArnConfig,
+ /// Realtime update publisher.
+ pub realtime: R,
}
-impl<N, Q, S> NotificationReaderService<N, Q, S>
+impl<N, Q, S, R> NotificationReaderService<N, Q, S, R>
where
N: NotificationRepository,
Q: NotificationQueue,
S: SnsEndpointManager,
+ R: NotificationRealtimePublisher,
{
- /// Create a new reader service.
- pub fn new(
- repository: N,
- queue: Q,
- sns_endpoint: S,
- platform_config: PlatformArnConfig,
- ) -> Self {
- Self {
- repository,
- queue,
- sns_endpoint,
- platform_config,
- }
- }
-
/// Update notification status for a user and optionally enqueue push notification clearing.
///
/// This method performs the following steps:
@@ -483,16 +477,26 @@ where
&self,
req: UpdateNotificationsRequest<'_>,
) -> Result<(), Report> {
- match &req.status {
+ let changed = match &req.status {
NotificationStatus::Seen => {
self.repository
.mark_notifications_seen(req.user_id.copied(), req.notification_ids)
- .await?;
+ .await?
}
NotificationStatus::Done(done) => {
self.repository
.mark_notifications_done(&req.user_id, req.notification_ids, *done)
- .await?;
+ .await?
+ }
+ };
+
+ if !changed.is_empty() {
+ let update = UserNotificationStatusUpdate {
+ user: req.user_id.copied(),
+ update: NotificationStatusUpdate::new(changed),
+ };
+ if let Err(err) = self.realtime.publish_updates(&[update]).await {
+ tracing::warn!(error = ?err, "failed to publish notification status realtime update");
}
}
@@ -581,11 +585,12 @@ where
}
}
-impl<N, Q, S> NotificationReader for NotificationReaderService<N, Q, S>
+impl<N, Q, S, R> NotificationReader for NotificationReaderService<N, Q, S, R>
where
N: NotificationRepository,
Q: NotificationQueue,
S: SnsEndpointManager,
+ R: NotificationRealtimePublisher,
{
fn update_notifications(
&self,
diff --git a/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs b/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs
index 3834c52fda..f759b29a8f 100644
--- a/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs
@@ -99,7 +99,15 @@ impl NotificationRepository for MockNotifRepo {
&self,
_: macro_user_id::user_id::MacroUserIdStr<'_>,
_: &[uuid::Uuid],
- ) -> Result<(), Report> {
+ ) -> Result<
+ Vec<
+ crate::domain::models::PatchDelete<
+ uuid::Uuid,
+ crate::domain::models::NotificationStatusPatch,
+ >,
+ >,
+ Report,
+ > {
unimplemented!()
}
async fn mark_notifications_done(
@@ -107,7 +115,15 @@ impl NotificationRepository for MockNotifRepo {
_: &macro_user_id::user_id::MacroUserIdStr<'_>,
_: &[uuid::Uuid],
_: bool,
- ) -> Result<(), Report> {
+ ) -> Result<
+ Vec<
+ crate::domain::models::PatchDelete<
+ uuid::Uuid,
+ crate::domain::models::NotificationStatusPatch,
+ >,
+ >,
+ Report,
+ > {
unimplemented!()
}
async fn get_basic_notifications(
diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rs
index 63855d5d6e..ae50f33539 100644
--- a/rust/cloud-storage/notification/src/domain/service/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/test.rs
@@ -13,8 +13,9 @@ use crate::domain::models::queue_message::{
use crate::domain::models::request::{NotificationStatus, UpdateNotificationsRequest};
use crate::domain::models::{
DeviceEndpoint, Notification, NotificationExtEmail, NotificationExtIos,
- NotificationIdAndCollapseKey, RateLimitConfig, RateLimitExceeded, RateLimitKey,
- RateLimitResult, SendNotificationRequestBuilder, TaggedContent, UserNotificationRow,
+ NotificationIdAndCollapseKey, NotificationStatusPatch, PatchDelete, RateLimitConfig,
+ RateLimitExceeded, RateLimitKey, RateLimitResult, SendNotificationRequestBuilder,
+ TaggedContent, UserNotificationRow,
};
use crate::domain::ports::{
EmailSender, NotificationEgress, NotificationQueue, NotificationRepository, NotificationSender,
@@ -243,12 +244,12 @@ impl NotificationRepository for MockRepository {
&self,
user_id: MacroUserIdStr<'_>,
notification_ids: &[Uuid],
- ) -> Result<(), Report> {
+ ) -> Result<Vec<PatchDelete<Uuid, NotificationStatusPatch>>, Report> {
self.mark_seen_calls
.lock()
.unwrap()
.push((user_id.to_string(), notification_ids.to_vec()));
- Ok(())
+ Ok(Vec::new())
}
async fn mark_notifications_done(
@@ -256,13 +257,13 @@ impl NotificationRepository for MockRepository {
user_id: &MacroUserIdStr<'_>,
notification_ids: &[Uuid],
done: bool,
- ) -> Result<(), Report> {
+ ) -> Result<Vec<PatchDelete<Uuid, NotificationStatusPatch>>, Report> {
self.mark_done_calls.lock().unwrap().push((
user_id.to_string(),
notification_ids.to_vec(),
done,
));
- Ok(())
+ Ok(Vec::new())
}
async fn get_basic_notifications(
@@ -429,7 +430,7 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {
&self,
user_id: MacroUserIdStr<'_>,
notification_ids: &[Uuid],
- ) -> Result<(), Report> {
+ ) -> Result<Vec<PatchDelete<Uuid, NotificationStatusPatch>>, Report> {
(**self)
.mark_notifications_seen(user_id, notification_ids)
.await
@@ -440,7 +441,7 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {
user_id: &MacroUserIdStr<'_>,
notification_ids: &[Uuid],
done: bool,
- ) -> Result<(), Report> {
+ ) -> Result<Vec<PatchDelete<Uuid, NotificationStatusPatch>>, Report> {
(**self)
.mark_notifications_done(user_id, notification_ids, done)
.await
@@ -1404,12 +1405,13 @@ async fn test_mark_seen_publishes_ios_clear_message() {
),
);
let queue = Arc::new(MockQueue::new());
- let service = NotificationReaderService::new(
- repo.clone(),
- queue.clone(),
- MockSnsEndpoint,
- test_platform_config(),
- );
+ let service = NotificationReaderService {
+ repository: repo.clone(),
+ queue: queue.clone(),
+ sns_endpoint: MockSnsEndpoint,
+ platform_config: test_platform_config(),
+ realtime: crate::domain::ports::NoopNotificationRealtimePublisher,
+ };
let notification_ids = [notif_id];
service
@@ -1482,12 +1484,13 @@ async fn test_mark_seen_skips_push_when_no_collapse_key() {
DeviceEndpoint::Ios("arn:aws:sns:us-east-1:111:endpoint/APNS/app/bob".to_string()),
));
let queue = Arc::new(MockQueue::new());
- let service = NotificationReaderService::new(
- repo.clone(),
- queue.clone(),
- MockSnsEndpoint,
- test_platform_config(),
- );
+ let service = NotificationReaderService {
+ repository: repo.clone(),
+ queue: queue.clone(),
+ sns_endpoint: MockSnsEndpoint,
+ platform_config: test_platform_config(),
+ realtime: crate::domain::ports::NoopNotificationRealtimePublisher,
+ };
let notification_ids = [notif_id];
service
@@ -1523,12 +1526,13 @@ async fn test_mark_seen_skips_push_when_no_device_endpoints() {
// No device endpoints registered
);
let queue = Arc::new(MockQueue::new());
- let service = NotificationReaderService::new(
- repo.clone(),
- queue.clone(),
- MockSnsEndpoint,
- test_platform_config(),
- );
+ let service = NotificationReaderService {
+ repository: repo.clone(),
+ queue: queue.clone(),
+ sns_endpoint: MockSnsEndpoint,
+ platform_config: test_platform_config(),
+ realtime: crate::domain::ports::NoopNotificationRealtimePublisher,
+ };
let notification_ids = [notif_id];
service
@@ -1570,12 +1574,13 @@ async fn test_mark_done_updates_db_and_clears_push() {
),
);
let queue = Arc::new(MockQueue::new());
- let service = NotificationReaderService::new(
- repo.clone(),
- queue.clone(),
- MockSnsEndpoint,
- test_platform_config(),
- );
+ let service = NotificationReaderService {
+ repository: repo.clone(),
+ queue: queue.clone(),
+ sns_endpoint: MockSnsEndpoint,
+ platform_config: test_platform_config(),
+ realtime: crate::domain::ports::NoopNotificationRealtimePublisher,
+ };
let notification_ids = [notif_id];
service
@@ -1620,12 +1625,13 @@ async fn test_mark_undone_updates_db_no_push_clear() {
),
);
let queue = Arc::new(MockQueue::new());
- let service = NotificationReaderService::new(
- repo.clone(),
- queue.clone(),
- MockSnsEndpoint,
- test_platform_config(),
- );
+ let service = NotificationReaderService {
+ repository: repo.clone(),
+ queue: queue.clone(),
+ sns_endpoint: MockSnsEndpoint,
+ platform_config: test_platform_config(),
+ realtime: crate::domain::ports::NoopNotificationRealtimePublisher,
+ };
let notification_ids = [notif_id];
service
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 41ba292ccf..9a68603f61 100644
--- a/rust/cloud-storage/notification/src/domain/service/voip/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/voip/test.rs
@@ -116,7 +116,15 @@ impl NotificationRepository for MockRepo {
&self,
_: MacroUserIdStr<'_>,
_: &[uuid::Uuid],
- ) -> Result<(), Report> {
+ ) -> Result<
+ Vec<
+ crate::domain::models::PatchDelete<
+ uuid::Uuid,
+ crate::domain::models::NotificationStatusPatch,
+ >,
+ >,
+ Report,
+ > {
unimplemented!()
}
async fn mark_notifications_done(
@@ -124,7 +132,15 @@ impl NotificationRepository for MockRepo {
_: &MacroUserIdStr<'_>,
_: &[uuid::Uuid],
_: bool,
- ) -> Result<(), Report> {
+ ) -> Result<
+ Vec<
+ crate::domain::models::PatchDelete<
+ uuid::Uuid,
+ crate::domain::models::NotificationStatusPatch,
+ >,
+ >,
+ Report,
+ > {
unimplemented!()
}
async fn get_basic_notifications(
diff --git a/rust/cloud-storage/notification/src/inbound.rs b/rust/cloud-storage/notification/src/inbound.rs
index 872de00897..1dd65f382b 100644
--- a/rust/cloud-storage/notification/src/inbound.rs
+++ b/rust/cloud-storage/notification/src/inbound.rs
@@ -4,6 +4,8 @@ pub mod ai_tool;
pub mod http;
/// Worker for processing notification requests from the ingress queue.
pub mod ingress_worker;
+/// Listener for notification database events emitted via Postgres NOTIFY.
+pub mod notification_events_listener;
/// Worker for processing push notification delivery events.
pub mod push_notification_event_worker;
/// Worker for delivering notifications from the delivery queue.
diff --git a/rust/cloud-storage/notification/src/inbound/notification_events_listener.rs b/rust/cloud-storage/notification/src/inbound/notification_events_listener.rs
new file mode 100644
index 0000000000..1d1d73a322
--- /dev/null
+++ b/rust/cloud-storage/notification/src/inbound/notification_events_listener.rs
@@ -0,0 +1,98 @@
+//! Listener for notification database events.
+
+use std::time::Duration;
+
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
+use serde::Deserialize;
+use uuid::Uuid;
+
+use crate::domain::models::{NotificationStatusUpdate, PatchDelete, UserNotificationStatusUpdate};
+use crate::domain::ports::{NotificationEventsReceiver, NotificationRealtimePublisher};
+
+/// Worker that listens for notification database events and forwards them to realtime clients.
+pub struct NotificationEventsListener<E, R> {
+ receiver: E,
+ realtime: R,
+}
+
+impl<E, R> NotificationEventsListener<E, R>
+where
+ E: NotificationEventsReceiver,
+ R: NotificationRealtimePublisher,
+{
+ /// Create a new notification database event listener.
+ pub fn new(receiver: E, realtime: R) -> Self {
+ Self { receiver, realtime }
+ }
+
+ /// Run the listener forever, reconnecting after receiver failures.
+ pub async fn run(&mut self) -> ! {
+ loop {
+ match self.receiver.receive().await {
+ Ok(payload) => self.handle_payload(&payload).await,
+ Err(err) => {
+ tracing::error!(error = ?err, "notification event listener receive failed");
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ }
+ }
+ }
+ }
+
+ async fn handle_payload(&self, payload: &str) {
+ let event = match serde_json::from_str::<NotificationDatabaseEvent>(payload) {
+ Ok(event) => event,
+ Err(err) => {
+ tracing::warn!(error = ?err, payload, "failed to deserialize notification database event");
+ return;
+ }
+ };
+
+ match event {
+ NotificationDatabaseEvent::UserNotificationDeletes {
+ notification_id,
+ user_ids,
+ } => {
+ let user_ids = user_ids
+ .into_iter()
+ .filter_map(|user_id| match MacroUserIdStr::parse_from_str(&user_id) {
+ Ok(user_id) => Some(user_id.into_owned()),
+ Err(err) => {
+ tracing::warn!(error = ?err, user_id, "invalid user id in notification delete event");
+ None
+ }
+ })
+ .collect::<Vec<_>>();
+
+ if user_ids.is_empty() {
+ return;
+ }
+
+ let updates = user_ids
+ .iter()
+ .map(|user| UserNotificationStatusUpdate {
+ user: user.copied(),
+ update: NotificationStatusUpdate::new(vec![PatchDelete::Delete {
+ id: notification_id,
+ }]),
+ })
+ .collect::<Vec<_>>();
+
+ if let Err(err) = self.realtime.publish_updates(&updates).await {
+ tracing::warn!(error = ?err, "failed to publish notification delete realtime update");
+ }
+ }
+ }
+ }
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub(crate) enum NotificationDatabaseEvent {
+ UserNotificationDeletes {
+ #[serde(rename = "notificationId")]
+ notification_id: Uuid,
+ #[serde(rename = "userIds")]
+ user_ids: Vec<String>,
+ },
+}
diff --git a/rust/cloud-storage/notification/src/outbound.rs b/rust/cloud-storage/notification/src/outbound.rs
index b56e4a7b0b..d75a9af3fb 100644
--- a/rust/cloud-storage/notification/src/outbound.rs
+++ b/rust/cloud-storage/notification/src/outbound.rs
@@ -9,6 +9,8 @@ pub mod email;
pub mod last_online_checker;
pub mod message_receipt_repository;
pub mod mobile;
+/// Postgres LISTEN adapter for notification database events.
+pub mod notification_events;
pub mod push_notification_checker;
pub mod push_notification_event_queue;
pub mod queue;
diff --git a/rust/cloud-storage/notification/src/outbound/notification_events.rs b/rust/cloud-storage/notification/src/outbound/notification_events.rs
new file mode 100644
index 0000000000..9a9d8c4cf9
--- /dev/null
+++ b/rust/cloud-storage/notification/src/outbound/notification_events.rs
@@ -0,0 +1,56 @@
+//! Postgres LISTEN adapter for notification database events.
+
+use rootcause::Report;
+use sqlx::{PgPool, postgres::PgListener};
+
+use crate::domain::ports::NotificationEventsReceiver;
+
+const CHANNEL: &str = "notification_events";
+
+/// Postgres-backed receiver for notification events emitted with `pg_notify`.
+pub struct PgNotificationEventsReceiver {
+ pool: PgPool,
+ listener: Option<PgListener>,
+}
+
+impl PgNotificationEventsReceiver {
+ /// Create a new Postgres notification events receiver.
+ pub fn new(pool: PgPool) -> Self {
+ Self {
+ pool,
+ listener: None,
+ }
+ }
+
+ async fn listener(&mut self) -> Result<&mut PgListener, Report> {
+ if self.listener.is_none() {
+ let mut listener = PgListener::connect_with(&self.pool).await?;
+ listener.listen(CHANNEL).await?;
+ tracing::info!(
+ channel = CHANNEL,
+ "listening for notification database events"
+ );
+ self.listener = Some(listener);
+ }
+
+ Ok(self
+ .listener
+ .as_mut()
+ .expect("listener is initialized above"))
+ }
+}
+
+impl NotificationEventsReceiver for PgNotificationEventsReceiver {
+ async fn receive(&mut self) -> Result<String, Report> {
+ match self.listener().await?.recv().await {
+ Ok(notification) => Ok(notification.payload().to_string()),
+ Err(err) => {
+ self.listener = None;
+ Err(err.into())
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/notification/src/outbound/notification_events/test.rs b/rust/cloud-storage/notification/src/outbound/notification_events/test.rs
new file mode 100644
index 0000000000..7cc12ff320
--- /dev/null
+++ b/rust/cloud-storage/notification/src/outbound/notification_events/test.rs
@@ -0,0 +1,66 @@
+use super::*;
+
+use crate::inbound::notification_events_listener::NotificationDatabaseEvent;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::Postgres;
+use uuid::Uuid;
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn notification_delete_trigger_notifies_affected_users(pool: sqlx::Pool<Postgres>) {
+ let mut receiver = PgNotificationEventsReceiver::new(pool.clone());
+ receiver.listener().await.unwrap();
+
+ let notification_id = Uuid::new_v4();
+ let user_a = "macro|[email protected]";
+ let user_b = "macro|[email protected]";
+
+ sqlx::query(
+ r#"
+ INSERT INTO notification (
+ id,
+ notification_event_type,
+ event_item_id,
+ event_item_type,
+ service_sender
+ ) VALUES ($1, 'test_notification', 'doc-1', 'document', 'test_service')
+ "#,
+ )
+ .bind(notification_id)
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ sqlx::query(
+ r#"
+ INSERT INTO user_notification (user_id, notification_id)
+ VALUES ($1, $3), ($2, $3)
+ "#,
+ )
+ .bind(user_a)
+ .bind(user_b)
+ .bind(notification_id)
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ sqlx::query("DELETE FROM notification WHERE id = $1")
+ .bind(notification_id)
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ let payload = tokio::time::timeout(std::time::Duration::from_secs(2), receiver.receive())
+ .await
+ .expect("notification should be received")
+ .unwrap();
+ let payload: NotificationDatabaseEvent = serde_json::from_str(&payload).unwrap();
+
+ let NotificationDatabaseEvent::UserNotificationDeletes {
+ notification_id: received_notification_id,
+ mut user_ids,
+ } = payload;
+
+ assert_eq!(received_notification_id, notification_id);
+ user_ids.sort();
+ assert_eq!(user_ids, vec![user_a.to_string(), user_b.to_string()]);
+}
diff --git a/rust/cloud-storage/notification/src/outbound/repository.rs b/rust/cloud-storage/notification/src/outbound/repository.rs
index 5ac53a01c3..676b6179b2 100644
--- a/rust/cloud-storage/notification/src/outbound/repository.rs
+++ b/rust/cloud-storage/notification/src/outbound/repository.rs
@@ -7,7 +7,8 @@ use crate::domain::models::device::DeviceType;
use crate::domain::models::request::NotificationListFilters;
use crate::domain::models::{
DeviceEndpoint, DisabledNotificationType, NotificationIdAndCollapseKey,
- SendNotificationRequestBuilder, TaggedContent, UserNotificationRow,
+ NotificationStatusPatch, PatchDelete, SendNotificationRequestBuilder, TaggedContent,
+ UserNotificationRow,
};
use crate::domain::ports::NotificationRepository;
use crate::outbound::device_registration::DeviceRegistrationDbOps;
@@ -313,7 +314,9 @@ pub trait NotificationDbOps: DeviceRegistrationDbOps + Send + Sync + 'static {
&self,
user_id: &MacroUserIdStr<'_>,
notification_ids: &[Uuid],
- ) -> impl std::future::Future<Output = Result<(), Report>> + Send;
+ ) -> impl std::future::Future<
+ Output = Result<Vec<PatchDelete<Uuid, NotificationStatusPatch>>, Report>,
+ > + Send;
/// Mark notifications as done or undone for a user.
fn mark_notifications_done(
@@ -321,7 +324,9 @@ pub trait NotificationDbOps: DeviceRegistrationDbOps + Send + Sync + 'static {
user_id: &MacroUserIdStr<'_>,
notification_ids: &[Uuid],
done: bool,
- ) -> impl std::future::Future<Output = Result<(), Report>> + Send;
+ ) -> impl std::future::Future<
+ Output = Result<Vec<PatchDelete<Uuid, NotificationStatusPatch>>, Report>,
+ > + Send;
/// Get basic notification data (collapse keys) for push clearing.
fn get_basic_notifications(
@@ -619,22 +624,41 @@ impl NotificationDbOps for PgPool {
&self,
user_id: &MacroUserIdStr<'_>,
notification_ids: &[Uuid],
- ) -> Result<(), Report> {
+ ) -> Result<Vec<PatchDelete<Uuid, NotificationStatusPatch>>, Report> {
let user_id_str = user_id.to_string();
- sqlx::query!(
+ let rows = sqlx::query!(
r#"
- UPDATE user_notification
- SET seen_at = NOW()
- WHERE user_id = $1 AND notification_id = ANY($2)
+ WITH updated AS (
+ UPDATE user_notification
+ SET seen_at = NOW()
+ WHERE user_id = $1 AND notification_id = ANY($2) AND deleted_at IS NULL
+ RETURNING notification_id, done, seen_at::timestamptz as viewed_at
+ )
+ SELECT
+ updated.notification_id,
+ updated.done,
+ updated.viewed_at,
+ NOW()::timestamptz as "updated_at!"
+ FROM updated
"#,
user_id_str,
notification_ids
)
- .execute(self)
+ .fetch_all(self)
.await?;
- Ok(())
+ Ok(rows
+ .into_iter()
+ .map(|row| PatchDelete::Patch {
+ id: row.notification_id,
+ diff: NotificationStatusPatch {
+ done: row.done,
+ viewed_at: row.viewed_at,
+ updated_at: row.updated_at,
+ },
+ })
+ .collect())
}
async fn mark_notifications_done(
@@ -642,23 +666,42 @@ impl NotificationDbOps for PgPool {
user_id: &MacroUserIdStr<'_>,
notification_ids: &[Uuid],
done: bool,
- ) -> Result<(), Report> {
+ ) -> Result<Vec<PatchDelete<Uuid, NotificationStatusPatch>>, Report> {
let user_id_str = user_id.to_string();
- sqlx::query!(
+ let rows = sqlx::query!(
r#"
- UPDATE user_notification
- SET done = $3
- WHERE user_id = $1 AND notification_id = ANY($2)
+ WITH updated AS (
+ UPDATE user_notification
+ SET done = $3
+ WHERE user_id = $1 AND notification_id = ANY($2) AND deleted_at IS NULL
+ RETURNING notification_id, done, seen_at::timestamptz as viewed_at
+ )
+ SELECT
+ updated.notification_id,
+ updated.done,
+ updated.viewed_at,
+ NOW()::timestamptz as "updated_at!"
+ FROM updated
"#,
user_id_str,
notification_ids,
done
)
- .execute(self)
+ .fetch_all(self)
.await?;
- Ok(())
+ Ok(rows
+ .into_iter()
+ .map(|row| PatchDelete::Patch {
+ id: row.notification_id,
+ diff: NotificationStatusPatch {
+ done: row.done,
+ viewed_at: row.viewed_at,
+ updated_at: row.updated_at,
+ },
+ })
+ .collect())
}
async fn get_basic_notifications(
@@ -1156,7 +1199,7 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati
&self,
user_id: MacroUserIdStr<'_>,
notification_ids: &[Uuid],
- ) -> Result<(), Report> {
+ ) -> Result<Vec<PatchDelete<Uuid, NotificationStatusPatch>>, Report> {
self.db
.mark_notifications_seen(&user_id, notification_ids)
.await
@@ -1167,7 +1210,7 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati
user_id: &MacroUserIdStr<'_>,
notification_ids: &[Uuid],
done: bool,
- ) -> Result<(), Report> {
+ ) -> Result<Vec<PatchDelete<Uuid, NotificationStatusPatch>>, Report> {
self.db
.mark_notifications_done(user_id, notification_ids, done)
.await
diff --git a/rust/cloud-storage/notification/src/outbound/websocket.rs b/rust/cloud-storage/notification/src/outbound/websocket.rs
index 3c82bd090c..a9612e3ac5 100644
--- a/rust/cloud-storage/notification/src/outbound/websocket.rs
+++ b/rust/cloud-storage/notification/src/outbound/websocket.rs
@@ -8,7 +8,8 @@ use model_entity::{Entity, EntityType};
use rootcause::Report;
use serde::Serialize;
-use crate::domain::ports::WebSocketSender;
+use crate::domain::models::{NotificationStatusUpdate, UserNotificationStatusUpdate};
+use crate::domain::ports::{NotificationRealtimePublisher, WebSocketSender};
/// WebSocket gateway implementation of the WebSocket sender port.
///
@@ -91,24 +92,33 @@ struct BatchSendMessageBody<'a> {
entities: Vec<Entity<'a>>,
}
-impl WebSocketGatewayOps for ConnectionGatewayClient {
- #[tracing::instrument(err, skip(self, payload))]
- async fn send_to_users<'a, T: Serialize + Send + Sync>(
+/// A unique message for a single entity.
+#[derive(serde::Serialize)]
+struct UniqueMessage<'a> {
+ message_type: &'a str,
+ message_content: serde_json::Value,
+ entity: Entity<'a>,
+}
+
+/// Request body for batch sending unique messages.
+#[derive(serde::Serialize)]
+struct BatchSendUniqueMessagesBody<'a> {
+ messages: Vec<UniqueMessage<'a>>,
+}
+
+impl ConnectionGatewayClient {
+ async fn batch_send_to_entities<T: Serialize + Send + Sync>(
&self,
- user_ids: &[MacroUserIdStr<'a>],
+ message_type: &str,
payload: &T,
- ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {
- if user_ids.is_empty() {
- return Ok(HashSet::new());
+ entities: Vec<Entity<'_>>,
+ ) -> Result<Vec<MessageReceipt>, Report> {
+ if entities.is_empty() {
+ return Ok(Vec::new());
}
- let entities: Vec<Entity<'_>> = user_ids
- .iter()
- .map(|id| EntityType::User.with_entity_str(id.as_ref()))
- .collect();
-
let body = BatchSendMessageBody {
- message_type: "notification",
+ message_type,
message: serde_json::to_value(payload)?,
entities,
};
@@ -126,10 +136,58 @@ impl WebSocketGatewayOps for ConnectionGatewayClient {
let json = res.json().await?;
let response: GatewayResponse = serde_json::from_value(json)?;
+ Ok(response.receipts)
+ }
+
+ async fn batch_send_unique_messages(
+ &self,
+ messages: Vec<UniqueMessage<'_>>,
+ ) -> Result<Vec<MessageReceipt>, Report> {
+ if messages.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let body = BatchSendUniqueMessagesBody { messages };
+
+ let res = self
+ .client
+ .post(format!(
+ "{}/message/batch_send_unique",
+ self.connection_gateway_url
+ ))
+ .json(&body)
+ .send()
+ .await?
+ .error_for_status()?;
+
+ let json = res.json().await?;
+ let response: GatewayResponse = serde_json::from_value(json)?;
+ Ok(response.receipts)
+ }
+}
+
+impl WebSocketGatewayOps for ConnectionGatewayClient {
+ #[tracing::instrument(err, skip(self, payload))]
+ async fn send_to_users<'a, T: Serialize + Send + Sync>(
+ &self,
+ user_ids: &[MacroUserIdStr<'a>],
+ payload: &T,
+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {
+ if user_ids.is_empty() {
+ return Ok(HashSet::new());
+ }
+
+ let entities: Vec<Entity<'_>> = user_ids
+ .iter()
+ .map(|id| EntityType::User.with_entity_str(id.as_ref()))
+ .collect();
+
+ let receipts = self
+ .batch_send_to_entities("notification", payload, entities)
+ .await?;
// Convert receipts to user IDs that were delivered
- let delivered = response
- .receipts
+ let delivered = receipts
.into_iter()
.filter(|r| r.delivery_count > 0)
.filter_map(|r| {
@@ -154,3 +212,24 @@ impl<W: WebSocketGatewayOps + Send + Sync + 'static> WebSocketSender
self.gateway.send_to_users(recipients, notification).await
}
}
+
+impl NotificationRealtimePublisher for WebSocketGatewayAdapter<ConnectionGatewayClient> {
+ async fn publish_updates(
+ &self,
+ updates: &[UserNotificationStatusUpdate<'_>],
+ ) -> Result<(), Report> {
+ let messages = updates
+ .iter()
+ .map(|update| {
+ Ok(UniqueMessage {
+ message_type: NotificationStatusUpdate::MESSAGE_TYPE,
+ message_content: serde_json::to_value(&update.update)?,
+ entity: EntityType::User.with_entity_str(update.user.as_ref()),
+ })
+ })
+ .collect::<Result<Vec<_>, serde_json::Error>>()?;
+
+ self.gateway.batch_send_unique_messages(messages).await?;
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs
index 1f66870c42..41cafcdf7a 100644
--- a/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs
+++ b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs
@@ -3,8 +3,8 @@ use models_pagination::{CreatedAt, Query};
use notification::domain::models::TaggedContent;
use notification::domain::models::request::NotificationListFilters;
use notification::domain::models::{
- DeviceEndpoint, NotificationIdAndCollapseKey, SendNotificationRequestBuilder,
- UserNotificationRow, device::DeviceType,
+ DeviceEndpoint, NotificationIdAndCollapseKey, NotificationStatusPatch,
+ SendNotificationRequestBuilder, UserNotificationRow, device::DeviceType,
};
use notification::domain::ports::NotificationRepository;
use notification::outbound::repository::DbNotificationRepository;
@@ -89,7 +89,8 @@ impl NotificationRepository for SandboxNotificationRepository {
&self,
user_id: MacroUserIdStr<'_>,
notification_ids: &[Uuid],
- ) -> Result<(), Report> {
+ ) -> Result<Vec<notification::domain::models::PatchDelete<Uuid, NotificationStatusPatch>>, Report>
+ {
self.inner
.mark_notifications_seen(user_id, notification_ids)
.await
@@ -100,7 +101,8 @@ impl NotificationRepository for SandboxNotificationRepository {
user_id: &MacroUserIdStr<'_>,
notification_ids: &[Uuid],
done: bool,
- ) -> Result<(), Report> {
+ ) -> Result<Vec<notification::domain::models::PatchDelete<Uuid, NotificationStatusPatch>>, Report>
+ {
self.inner
.mark_notifications_done(user_id, notification_ids, done)
.await
diff --git a/rust/cloud-storage/notification_service/src/main.rs b/rust/cloud-storage/notification_service/src/main.rs
index e8a001711f..e27d3abea0 100644
--- a/rust/cloud-storage/notification_service/src/main.rs
+++ b/rust/cloud-storage/notification_service/src/main.rs
@@ -3,9 +3,11 @@ use crate::api::context::ApiContext;
use crate::api::user_notification::BLOCKABLE_NOTIFICATIONS;
use ::notification::domain::models::email_notification_digest::ports::DigestBatch;
use ::notification::domain::service::NotificationEgressService;
+use ::notification::inbound::notification_events_listener::NotificationEventsListener;
use ::notification::inbound::worker::NotificationWorker;
use ::notification::outbound::email::EmailAdapter;
use ::notification::outbound::mobile::MobilePushAdapter;
+use ::notification::outbound::notification_events::PgNotificationEventsReceiver;
use ::notification::outbound::rate_limit::RedisRateLimitAdapter;
use ::notification::outbound::websocket::{ConnectionGatewayClient, WebSocketGatewayAdapter};
use ::rate_limit::RateLimitServiceImpl;
@@ -148,12 +150,32 @@ pub async fn main() -> anyhow::Result<()> {
fcm_platform_arn: config.sns_fcm_platform_arn.clone(),
apns_voip_platform_arn: config.sns_apns_voip_platform_arn.clone(),
};
- let reader_service = ::notification::domain::service::NotificationReaderService::new(
- notification_repository,
- notification_queue.clone(),
- sns_endpoint_manager,
- platform_config,
+ let reader_realtime_adapter = WebSocketGatewayAdapter::new(ConnectionGatewayClient::new(
+ internal_secret_key.as_ref().to_string(),
+ vars.connection_gateway_url.as_ref().to_string(),
+ ));
+ let notification_events_realtime_adapter =
+ WebSocketGatewayAdapter::new(ConnectionGatewayClient::new(
+ internal_secret_key.as_ref().to_string(),
+ vars.connection_gateway_url.as_ref().to_string(),
+ ));
+ let notification_events_receiver = PgNotificationEventsReceiver::new(db.clone());
+ let mut notification_events_listener = NotificationEventsListener::new(
+ notification_events_receiver,
+ notification_events_realtime_adapter,
);
+ tokio::spawn(async move {
+ tracing::info!("starting notification database event listener");
+ notification_events_listener.run().await
+ });
+
+ let reader_service = ::notification::domain::service::NotificationReaderService {
+ repository: notification_repository,
+ queue: notification_queue.clone(),
+ sns_endpoint: sns_endpoint_manager,
+ platform_config,
+ realtime: reader_realtime_adapter,
+ };
let ingress_state = ::notification::inbound::http::NotificationRouterState::new(
reader_service,
&BLOCKABLE_NOTIFICATIONS,