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.

refactor notifications (#1215)

Sean Ayec94d9ea763bf
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index e7e09e9ac8..cec76b6e76 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -5836,6 +5836,29 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8"
+[[package]]
+name = "notification"
+version = "0.1.0"
+dependencies = [
+ "aws-sdk-sesv2",
+ "aws-sdk-sns",
+ "aws-sdk-sqs",
+ "hex",
+ "itertools 0.14.0",
+ "macro_user_id",
+ "model-entity",
+ "redis",
+ "reqwest",
+ "rootcause",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "thiserror 2.0.17",
+ "tokio",
+ "tracing",
+ "uuid",
+]
+
[[package]]
name = "notification_db_client"
version = "0.1.0"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 66fcbdd079..e69f12d6d2 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -32,9 +32,9 @@ members = [
"email_db_client",
"email_refresh_handler",
"email_scheduled_handler",
- "email_sfs_delete_handler",
"email_service",
"email_service_client",
+ "email_sfs_delete_handler",
"email_suppression_handler",
"email_utils",
"email_validator",
@@ -76,6 +76,7 @@ members = [
"models_team",
"name_search",
"non_empty",
+ "notification",
"notification_db_client",
"notification_service",
"notification_service_client",
@@ -153,6 +154,7 @@ futures = "0.3.31"
hex = "0.4.3"
http = "1"
http-body-util = "0.1.2"
+itertools = "0.14"
jsonwebtoken = "9.3.1"
lambda_runtime = "0.13.0"
lazy_static = "1.5.0"
@@ -169,6 +171,7 @@ redis = "0.29.0"
regex = "1.11.1"
reqwest = { version = "0.12.12", features = ["json"] }
reqwest-middleware = { git = "https://github.com/seanaye/reqwest-middleware" }
+rootcause = "0.11"
schemars = { version = "1.0.4", features = ["chrono04", "uuid1"] }
serde = { version = "1.0.214", features = ["derive"] }
serde_dynamo = { version = "4", features = ["aws-sdk-dynamodb+1"] }
diff --git a/rust/cloud-storage/comms/Cargo.toml b/rust/cloud-storage/comms/Cargo.toml
index a003b67a44..e2a3cf0f3b 100644
--- a/rust/cloud-storage/comms/Cargo.toml
+++ b/rust/cloud-storage/comms/Cargo.toml
@@ -23,7 +23,7 @@ models_comms = { path = "../models_comms" }
models_pagination = { path = "../models_pagination" }
recursion = { workspace = true }
reqwest = { workspace = true, optional = true }
-rootcause = "0.11"
+rootcause = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
diff --git a/rust/cloud-storage/connection_gateway/Cargo.toml b/rust/cloud-storage/connection_gateway/Cargo.toml
index 8c197662db..19cf6bc2e8 100644
--- a/rust/cloud-storage/connection_gateway/Cargo.toml
+++ b/rust/cloud-storage/connection_gateway/Cargo.toml
@@ -39,7 +39,7 @@ frecency = { path = "../frecency", features = [
] }
futures = { workspace = true }
http-body-util = { workspace = true }
-itertools = "0.14.0"
+itertools = { workspace = true }
macro_auth = { path = "../macro_auth" }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
diff --git a/rust/cloud-storage/notification/Cargo.toml b/rust/cloud-storage/notification/Cargo.toml
new file mode 100644
index 0000000000..eed6885f13
--- /dev/null
+++ b/rust/cloud-storage/notification/Cargo.toml
@@ -0,0 +1,27 @@
+[package]
+edition = "2024"
+name = "notification"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+aws-sdk-sesv2 = { workspace = true }
+aws-sdk-sns = { workspace = true }
+aws-sdk-sqs = { workspace = true }
+hex = { workspace = true }
+itertools = { workspace = true }
+macro_user_id = { path = "../macro_user_id" }
+model-entity = { path = "../model-entity" }
+redis = { workspace = true, features = ["tokio-native-tls-comp"] }
+reqwest = { workspace = true }
+rootcause = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+sqlx = { workspace = true }
+thiserror = { workspace = true }
+tokio = { workspace = true, features = ["time"] }
+tracing = { workspace = true }
+uuid = { workspace = true }
+
+[dev-dependencies]
+tokio = { workspace = true, features = ["macros", "rt"] }
diff --git a/rust/cloud-storage/notification/src/domain.rs b/rust/cloud-storage/notification/src/domain.rs
new file mode 100644
index 0000000000..901e625fda
--- /dev/null
+++ b/rust/cloud-storage/notification/src/domain.rs
@@ -0,0 +1,3 @@
+pub mod models;
+pub mod ports;
+pub mod service;
diff --git a/rust/cloud-storage/notification/src/domain/models.rs b/rust/cloud-storage/notification/src/domain/models.rs
new file mode 100644
index 0000000000..7c419b2ea1
--- /dev/null
+++ b/rust/cloud-storage/notification/src/domain/models.rs
@@ -0,0 +1,38 @@
+//! Domain models for the notification service.
+
+use crate::domain::models::apple::APNSPushNotification;
+use serde::{Serialize, de::DeserializeOwned};
+
+pub(crate) mod android;
+pub(crate) mod apple;
+pub(crate) mod mobile;
+pub(crate) mod queue_message;
+pub mod rate_limit;
+pub mod recipient;
+pub mod request;
+
+pub use mobile::DeviceEndpoint;
+pub use rate_limit::{RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitResult};
+pub use recipient::{ExclusionReason, FilteredRecipient, RecipientExclusion};
+pub use request::{NotificationResult, SendNotificationRequest, SendNotificationRequestBuilder};
+
+/// Trait that all notification types must implement.
+pub trait Notification: Serialize + DeserializeOwned + Send + Sync {
+ /// The type name of this notification.
+ const TYPE_NAME: &'static str;
+
+ /// The user visible title of the notification.
+ fn title(&self) -> String;
+ /// The user visible body of the notification.
+ fn body(&self) -> String;
+ /// The configuration for how often the notification can be triggered on a certain key.
+ fn rate_limit_config() -> Option<RateLimitConfig>;
+ /// The actual key for the rate limit bucket.
+ fn rate_limit_key(&self) -> Option<RateLimitKey>;
+}
+
+/// Trait for notifications that can build APNS push payloads.
+pub trait BuildApnsNotification<T>: Notification {
+ /// Build an APNS push notification from this notification.
+ fn build_apns(&self) -> APNSPushNotification<T>;
+}
diff --git a/rust/cloud-storage/notification/src/domain/models/android.rs b/rust/cloud-storage/notification/src/domain/models/android.rs
new file mode 100644
index 0000000000..5ebc3174ab
--- /dev/null
+++ b/rust/cloud-storage/notification/src/domain/models/android.rs
@@ -0,0 +1,36 @@
+use serde::Serialize;
+
+#[derive(Debug, Serialize)]
+pub struct FCMMessage<T> {
+ pub(crate) android: AndroidData,
+ data: T,
+}
+
+impl<T> FCMMessage<T> {
+ /// temporary method since android is currently out of scope for mobile
+ /// this just instantiates a majority blank notif
+ pub fn new_temporary_empty(data: T) -> Self {
+ FCMMessage {
+ android: AndroidData {
+ notification: "Temporary placeholder".to_string(),
+ priority: AndroidNotifPrio::Normal,
+ collapse_key: String::new(),
+ },
+ data,
+ }
+ }
+}
+
+#[derive(Debug, Serialize)]
+pub enum AndroidNotifPrio {
+ Normal,
+ #[expect(dead_code)]
+ High,
+}
+
+#[derive(Debug, Serialize)]
+pub struct AndroidData {
+ pub(crate) notification: String,
+ pub(crate) priority: AndroidNotifPrio,
+ pub(crate) collapse_key: String,
+}
diff --git a/rust/cloud-storage/notification/src/domain/models/apple.rs b/rust/cloud-storage/notification/src/domain/models/apple.rs
new file mode 100644
index 0000000000..6a170be6af
--- /dev/null
+++ b/rust/cloud-storage/notification/src/domain/models/apple.rs
@@ -0,0 +1,129 @@
+use serde::{Deserialize, Serialize};
+
+use crate::domain::models::Notification;
+
+#[derive(Serialize, Debug, Default, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub struct Aps {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub alert: Option<Alert>,
+
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub badge: Option<u32>,
+
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub sound: Option<Sound>,
+
+ /// Set to 1 for background/silent notifications
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub content_available: Option<u8>,
+
+ /// Set to 1 to allow Notification Service Extension to modify
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub mutable_content: Option<u8>,
+
+ /// Category identifier for actionable notifications
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub category: Option<String>,
+
+ /// Identifier for grouping notifications
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub thread_id: Option<String>,
+
+ /// Relevance score for notification summary (0.0 to 1.0)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub relevance_score: Option<f64>,
+
+ /// Interruption level: passive, active, time-sensitive, critical
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub interruption_level: Option<InterruptionLevel>,
+}
+
+#[derive(Serialize, Debug, Deserialize)]
+#[serde(untagged)]
+pub enum Alert {
+ Simple(String),
+ Dictionary(AlertDictionary),
+}
+
+#[derive(Serialize, Debug, Default, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub struct AlertDictionary {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub title: Option<String>,
+
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub subtitle: Option<String>,
+
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub body: Option<String>,
+
+ /// Localization key for title
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub title_loc_key: Option<String>,
+
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub title_loc_args: Option<Vec<String>>,
+
+ /// Localization key for body
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub loc_key: Option<String>,
+
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub loc_args: Option<Vec<String>>,
+
+ /// Custom launch image filename
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub launch_image: Option<String>,
+}
+
+#[derive(Serialize, Debug, Deserialize)]
+#[serde(untagged)]
+pub enum Sound {
+ Default(String), // Usually "default"
+ Critical(CriticalSound),
+}
+
+#[derive(Serialize, Debug, Deserialize)]
+pub struct CriticalSound {
+ pub critical: u8, // 1 for critical
+ pub name: String,
+ pub volume: f64, // 0.0 to 1.0
+}
+
+#[derive(Serialize, Debug, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum InterruptionLevel {
+ Passive,
+ Active,
+ TimeSensitive,
+ Critical,
+}
+
+#[derive(Serialize, Debug, Deserialize)]
+#[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,
+}
+
+impl APNSPushNotification<()> {
+ /// construct a simple apple notification using the input notifications title and body
+ pub fn default_new<T: Notification>(notif: &T) -> Self {
+ APNSPushNotification {
+ aps: Aps {
+ alert: Some(Alert::Dictionary(AlertDictionary {
+ title: Some(notif.title()),
+ body: Some(notif.body()),
+ ..Default::default()
+ })),
+ ..Default::default()
+ },
+ push_notification_data: (),
+ }
+ }
+}
diff --git a/rust/cloud-storage/notification/src/domain/models/mobile.rs b/rust/cloud-storage/notification/src/domain/models/mobile.rs
new file mode 100644
index 0000000000..604b01981b
--- /dev/null
+++ b/rust/cloud-storage/notification/src/domain/models/mobile.rs
@@ -0,0 +1,106 @@
+use serde::{Deserialize, Serialize, Serializer};
+
+use crate::domain::models::{
+ android::FCMMessage,
+ apple::{APNSPushNotification, Alert},
+};
+
+#[derive(Debug)]
+pub enum SnsTarget<'a, T> {
+ Ios(&'a APNSPushNotification<T>),
+ Android(&'a FCMMessage<T>),
+}
+
+#[derive(Debug, Serialize)]
+#[serde(bound = "T: Serialize", untagged)]
+pub enum SnsPayload<'a, T> {
+ Ios {
+ default: String,
+ #[serde(rename = "APNS", serialize_with = "stringified_json")]
+ apns: &'a APNSPushNotification<T>,
+ #[serde(rename = "APNS_SANDBOX", serialize_with = "stringified_json")]
+ apns_sandbox: &'a APNSPushNotification<T>,
+ },
+ Android {
+ default: String,
+ #[serde(rename = "GCM", serialize_with = "stringified_json")]
+ gcm: &'a FCMMessage<T>,
+ },
+}
+
+fn stringified_json<T, S>(val: &T, ser: S) -> Result<S::Ok, S::Error>
+where
+ S: Serializer,
+ T: Serialize,
+{
+ let s = serde_json::to_string(val).expect("json serialize cant fail");
+ ser.serialize_str(&s)
+}
+
+impl<'a, T> SnsPayload<'a, T>
+where
+ T: Serialize,
+{
+ fn as_json(&self) -> Result<String, serde_json::Error> {
+ serde_json::to_string(self)
+ }
+}
+
+impl<T> SnsTarget<'_, T> {
+ fn default_string(&self) -> String {
+ match self {
+ SnsTarget::Ios(apnspush_notification) => apnspush_notification
+ .aps
+ .alert
+ .as_ref()
+ .and_then(|a| match a {
+ Alert::Simple(s) => Some(s.clone()),
+ Alert::Dictionary(alert_dictionary) => alert_dictionary.title.clone(),
+ })
+ .unwrap_or(String::new()),
+ SnsTarget::Android(fcmmessage) => fcmmessage.android.notification.clone(),
+ }
+ }
+
+ fn as_payload(&self) -> SnsPayload<'_, T> {
+ match self {
+ SnsTarget::Ios(apnspush_notification) => SnsPayload::Ios {
+ default: self.default_string(),
+ apns: apnspush_notification,
+ apns_sandbox: apnspush_notification,
+ },
+ SnsTarget::Android(fcmmessage) => SnsPayload::Android {
+ default: self.default_string(),
+ gcm: fcmmessage,
+ },
+ }
+ }
+}
+
+impl<T: Serialize> SnsTarget<'_, T> {
+ /// Serialize the target to JSON for SNS.
+ pub fn as_json(&self) -> Result<String, serde_json::Error> {
+ self.as_payload().as_json()
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MessageAttributes {
+ pub push_type: PushType,
+ pub collapse_key: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub enum PushType {
+ Background,
+ Alert,
+}
+
+/// A device endpoint for push notifications.
+#[derive(Debug, Clone)]
+pub enum DeviceEndpoint {
+ /// Android device endpoint (FCM).
+ Android(String),
+ /// iOS device endpoint (APNS).
+ Ios(String),
+}
diff --git a/rust/cloud-storage/notification/src/domain/models/queue_message.rs b/rust/cloud-storage/notification/src/domain/models/queue_message.rs
new file mode 100644
index 0000000000..ffd8815435
--- /dev/null
+++ b/rust/cloud-storage/notification/src/domain/models/queue_message.rs
@@ -0,0 +1,104 @@
+use crate::domain::models::{
+ RateLimitConfig, RateLimitKey, apple::APNSPushNotification, mobile::MessageAttributes,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use serde::{Deserialize, Serialize};
+use thiserror::Error;
+
+/// APNS push notification targets.
+#[derive(Debug, Serialize, Deserialize)]
+pub struct APNSTargets<T> {
+ /// The APNS notification payload.
+ pub notif: APNSPushNotification<T>,
+ pub attributes: MessageAttributes,
+ /// The iOS device endpoints to deliver to.
+ pub ios_device_endpoints: Vec<String>,
+}
+
+/// Email notification payload.
+#[derive(Debug, Serialize, Deserialize)]
+pub struct EmailContent {
+ /// The email subject line.
+ pub subject: String,
+ /// The email body content.
+ pub body: String,
+}
+
+/// Email notification payload.
+#[derive(Debug, Serialize, Deserialize)]
+pub struct EmailNotification<'a> {
+ /// The recipient email/user ID.
+ pub to: MacroUserIdStr<'a>,
+ pub content: EmailContent,
+}
+
+/// Connection gateway (WebSocket) notification payload.
+#[derive(Debug, Serialize, Deserialize)]
+pub struct ConnGatewayNotification<'a, T> {
+ /// The notification payload to send.
+ pub notif: T,
+ /// The recipients to deliver to.
+ pub recipients: Vec<MacroUserIdStr<'a>>,
+}
+
+/// The delivery channel variants.
+#[derive(Debug, Serialize, Deserialize)]
+pub enum NotificationChannel<'a, T> {
+ /// Delivering to an iOS device with APNS.
+ Ios(Box<APNSTargets<T>>),
+ /// Delivering to a user's email inbox.
+ Email(EmailNotification<'a>),
+ /// Delivering a foreground notification via connection gateway.
+ ConnGateway(ConnGatewayNotification<'a, T>),
+}
+
+/// A delivery node with optional fallback on failure.
+#[derive(Debug, Serialize, Deserialize)]
+pub struct Node<'a, T> {
+ /// The channel of notification we are delivering on.
+ pub notif: NotificationChannel<'a, T>,
+ /// The optional next channel we will attempt to deliver on if this method fails.
+ pub on_failure: Option<Box<Node<'a, T>>>,
+}
+
+/// Message published to SQS after DB persistence.
+/// Contains everything needed for delivery.
+#[derive(Debug, Serialize, Deserialize)]
+pub struct QueueMessage<'a, T> {
+ /// The notification type name (e.g., "channel_message_send").
+ pub message_type: String,
+ /// The rate limit key for this notification.
+ /// The configuration for this rate limiter.
+ pub rate_limit: Option<(RateLimitKey, RateLimitConfig)>,
+ /// The methods on which we will attempt to deliver.
+ /// This is an ALL relationship.
+ pub content: Node<'a, T>,
+}
+
+/// Raw message received from SQS.
+#[derive(Debug)]
+pub struct RawQueueMessage {
+ /// The deserialized queue message body.
+ pub body: QueueMessage<'static, serde_json::Value>,
+ /// The receipt handle for deleting the message after processing.
+ pub receipt_handle: String,
+}
+
+/// Successful delivery result.
+#[derive(Debug)]
+pub enum DeliverySuccess {
+ /// Delivered via iOS push.
+ Ios,
+ /// Delivered via connection gateway (WebSocket).
+ ConnGateway,
+ /// Delivered via email.
+ Email,
+}
+
+#[derive(Debug, Error)]
+pub enum DeliveryFailure {
+ #[error("The rate limit was exceeded")]
+ RateLimit,
+ #[error("A delivery error occured")]
+ Other,
+}
diff --git a/rust/cloud-storage/notification/src/domain/models/rate_limit.rs b/rust/cloud-storage/notification/src/domain/models/rate_limit.rs
new file mode 100644
index 0000000000..a71f9f7c13
--- /dev/null
+++ b/rust/cloud-storage/notification/src/domain/models/rate_limit.rs
@@ -0,0 +1,90 @@
+//! Rate limiting models for the notification service.
+
+use serde::{Deserialize, Serialize};
+use std::time::Duration;
+use thiserror::Error;
+
+/// Newtype for rate limit keys.
+///
+/// Callers control what gets rate limited by constructing a key from relevant
+/// data (e.g., event type + sender email). The internal value is a hash.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct RateLimitKey(Vec<u8>);
+
+impl RateLimitKey {
+ /// Create a new rate limit key from raw bytes.
+ pub fn new(bytes: Vec<u8>) -> Self {
+ Self(bytes)
+ }
+
+ /// Create a rate limit key by hashing the input string.
+ pub fn from_str_hashed(input: &str) -> Self {
+ use std::hash::{DefaultHasher, Hash, Hasher};
+ let mut hasher = DefaultHasher::new();
+ input.hash(&mut hasher);
+ Self(hasher.finish().to_le_bytes().to_vec())
+ }
+
+ /// Get the internal bytes.
+ pub fn as_bytes(&self) -> &[u8] {
+ &self.0
+ }
+
+ /// Convert to a hex string for use as a cache key.
+ pub fn to_hex_string(&self) -> String {
+ hex::encode(&self.0)
+ }
+}
+
+/// Result of a rate limit check.
+#[derive(Debug)]
+pub enum RateLimitResult {
+ /// The action is allowed. Contains the current count after increment.
+ Allowed {
+ /// The current count after increment.
+ current_count: u64,
+ },
+ /// The rate limit has been exceeded.
+ Exceeded(RateLimitExceeded),
+}
+
+/// Error returned when a rate limit is exceeded.
+#[derive(Debug, Error)]
+#[error(
+ "Rate limit key: {key} was exceeded. Current count is {current_count} but max count is {max_count}"
+)]
+pub struct RateLimitExceeded {
+ /// The key that is exceeded.
+ pub key: String,
+ /// The current count.
+ pub current_count: u64,
+ /// The maximum allowed count.
+ pub max_count: u64,
+}
+
+/// Configuration for rate limiting.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RateLimitConfig {
+ /// Maximum number of actions allowed in the window.
+ pub max_count: u64,
+ /// Time window for rate limiting.
+ pub window: Duration,
+}
+
+impl RateLimitConfig {
+ /// Create a new rate limit config.
+ pub fn new(max_count: u64, window: Duration) -> Self {
+ Self { max_count, window }
+ }
+
+ /// Rate limit for channel invites: 10 per hour.
+ pub fn channel_invite() -> Self {
+ Self::new(10, Duration::from_secs(3600))
+ }
+
+ /// Rate limit for team invites: 5 per hour.
+ pub fn team_invite() -> Self {
+ Self::new(5, Duration::from_secs(3600))
+ }
+}
diff --git a/rust/cloud-storage/notification/src/domain/models/recipient.rs b/rust/cloud-storage/notification/src/domain/models/recipient.rs
new file mode 100644
index 0000000000..c77aa7701e
--- /dev/null
+++ b/rust/cloud-storage/notification/src/domain/models/recipient.rs
@@ -0,0 +1,42 @@
+//! Recipient filtering models for the notification service.
+
+use macro_user_id::user_id::MacroUserIdStr;
+
+/// Result of filtering a recipient.
+pub enum FilteredRecipient<'a> {
+ /// Recipient is allowed to receive the notification.
+ Allowed(MacroUserIdStr<'a>),
+ /// Recipient was excluded from receiving the notification.
+ Excluded(RecipientExclusion<'a>),
+}
+
+/// A recipient that was excluded from receiving a notification.
+#[derive(Debug, Clone)]
+pub struct RecipientExclusion<'a> {
+ /// The user who was excluded.
+ pub user_id: MacroUserIdStr<'a>,
+ /// The reason for exclusion.
+ pub reason: ExclusionReason,
+}
+
+/// Reasons why a recipient might be excluded from a notification.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ExclusionReason {
+ /// The recipient is the sender of the notification.
+ IsSender,
+ /// The recipient has muted notifications.
+ MutedNotifications,
+ /// The recipient has unsubscribed from notifications for this item.
+ UnsubscribedFromItem,
+}
+
+impl ExclusionReason {
+ /// Get a human-readable description of the exclusion reason.
+ pub fn description(&self) -> &'static str {
+ match self {
+ ExclusionReason::IsSender => "User is the sender",
+ ExclusionReason::MutedNotifications => "User has muted notifications",
+ ExclusionReason::UnsubscribedFromItem => "User has unsubscribed from this item",
+ }
+ }
+}
diff --git a/rust/cloud-storage/notification/src/domain/models/request.rs b/rust/cloud-storage/notification/src/domain/models/request.rs
new file mode 100644
index 0000000000..177b951d80
--- /dev/null
+++ b/rust/cloud-storage/notification/src/domain/models/request.rs
@@ -0,0 +1,121 @@
+//! Request and response models for the notification service.
+
+use crate::domain::{
+ models::{
+ Notification, RateLimitConfig, RateLimitKey, apple::APNSPushNotification,
+ mobile::MessageAttributes, queue_message::EmailContent,
+ },
+ service::SendNotificationError,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
+use rootcause::{Report, report};
+use serde::{Deserialize, Serialize};
+use std::collections::HashSet;
+use uuid::Uuid;
+
+/// Request to send a notification.
+///
+/// Generic over the notification payload type `T`, which must implement
+/// the `Notification` trait. The event type is derived from `T::TYPE_NAME`.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(bound = "T: Notification")]
+pub struct SendNotificationRequestBuilder<'a, T> {
+ /// The entity associated with this notification (e.g., Channel, Team, Document).
+ pub notification_entity: Entity<'a>,
+ /// The notification payload (implements `Notification` trait).
+ pub notification: T,
+ /// The user who triggered this notification (optional).
+ pub sender_id: Option<MacroUserIdStr<'a>>,
+ /// The users who should receive this notification.
+ pub recipient_ids: HashSet<MacroUserIdStr<'a>>,
+}
+
+impl<'a, T> SendNotificationRequestBuilder<'a, T> {
+ /// Convert this builder into a full request with optional delivery customizers.
+ pub fn into_request(self) -> SendNotificationRequest<'a, T> {
+ SendNotificationRequest {
+ req: self,
+ build_apns: None,
+ build_email: None,
+ send_conn_gateway: false,
+ }
+ }
+}
+
+type BuildApns<T> = Box<dyn FnMut(T) -> (APNSPushNotification<T>, MessageAttributes)>;
+
+/// Full notification request with optional delivery channel builders.
+///
+/// Created from [`SendNotificationRequestBuilder::into_request`] and can be
+/// customized with APNS and email builders.
+pub struct SendNotificationRequest<'a, T> {
+ pub(crate) req: SendNotificationRequestBuilder<'a, T>,
+ /// define how to turn t into an APNSPushNotitication T to be sent to ios
+ pub(crate) build_apns: Option<BuildApns<T>>,
+ /// define how to turn T into an email content to be sent as an email
+ pub(crate) build_email: Option<Box<dyn FnMut(T) -> EmailContent>>,
+ /// connection gateway accepts arbitrary json so we just ask if its enabled or not
+ pub(crate) send_conn_gateway: bool,
+}
+
+impl<'a, T> SendNotificationRequest<'a, T> {
+ /// Add a custom APNS notification builder.
+ pub fn with_apns(
+ mut self,
+ cb: Box<dyn FnMut(T) -> (APNSPushNotification<T>, MessageAttributes)>,
+ ) -> Self {
+ self.build_apns.replace(cb);
+ self
+ }
+
+ /// Add a custom email content builder.
+ pub fn with_email(mut self, cb: Box<dyn FnMut(T) -> EmailContent>) -> Self {
+ self.build_email.replace(cb);
+ self
+ }
+
+ /// Enable delivery via connection gateway (WebSocket).
+ pub fn with_conn_gateway(mut self) -> Self {
+ self.send_conn_gateway = true;
+ self
+ }
+
+ pub(crate) fn update_recipients(mut self, recipients: HashSet<MacroUserIdStr<'a>>) -> Self {
+ self.req.recipient_ids = recipients;
+ self
+ }
+}
+
+impl<'a, T: Notification> SendNotificationRequestBuilder<'a, T> {
+ /// Get the event type name from the notification.
+ pub fn event_type(&self) -> &'static str {
+ T::TYPE_NAME
+ }
+
+ /// return the valid rate limit for this notification if it exists,
+ /// return none if there is no rate limit or error if there is a misconfig
+ pub fn get_rate_limit(
+ &self,
+ ) -> Result<Option<(RateLimitKey, RateLimitConfig)>, Report<SendNotificationError>> {
+ let config = T::rate_limit_config();
+ let key = self.notification.rate_limit_key();
+
+ match (config, key) {
+ (Some(config), Some(key)) => Ok(Some((key, config))),
+ (None, None) => Ok(None),
+ (Some(_), None) | (None, Some(_)) => {
+ Err(report!(SendNotificationError::RateLimitConfigErr))
+ }
+ }
+ }
+}
+
+/// Result of sending a notification.
+#[derive(Debug, Clone)]
+pub struct NotificationResult<'a> {
+ /// The unique ID of the created notification.
+ pub notification_id: Uuid,
+ /// The users who were actually notified (after filtering).
+ pub notified_recipients: HashSet<MacroUserIdStr<'a>>,
+}
diff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rs
new file mode 100644
index 0000000000..0b56887e22
--- /dev/null
+++ b/rust/cloud-storage/notification/src/domain/ports.rs
@@ -0,0 +1,137 @@
+//! Port definitions (interfaces) for the notification service.
+//!
+//! These traits define the boundaries between the domain logic and external
+//! dependencies, following hexagonal architecture principles.
+
+use std::collections::{HashMap, HashSet};
+use std::future::Future;
+
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+use serde::Serialize;
+use uuid::Uuid;
+
+use crate::domain::models::{
+ DeviceEndpoint, Notification, RateLimitConfig, RateLimitKey, RateLimitResult,
+ SendNotificationRequestBuilder, android::FCMMessage, apple::APNSPushNotification,
+ mobile::MessageAttributes,
+};
+
+/// Port for sending mobile push notifications (iOS/Android via SNS).
+pub trait NotificationSender {
+ /// Send an iOS push notification via APNS.
+ fn send_ios_push_notification<T: Serialize + Send + Sync>(
+ &self,
+ endpoint_arn: &str,
+ notification: &APNSPushNotification<T>,
+ attributes: &MessageAttributes,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+
+ /// Send an Android push notification via FCM.
+ fn send_android_push_notification<T: Serialize + Send + Sync>(
+ &self,
+ endpoint_arn: &str,
+ notification: &FCMMessage<T>,
+ attributes: &MessageAttributes,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+}
+
+/// Port for rate limiting operations.
+pub trait RateLimitPort {
+ /// Check if the action is allowed and increment the counter.
+ ///
+ /// The `RateLimitKey` is a hashed value - callers control what gets rate
+ /// limited by constructing the key from relevant data.
+ fn check_and_increment(
+ &self,
+ key: RateLimitKey,
+ config: RateLimitConfig,
+ ) -> impl Future<Output = Result<RateLimitResult, Report>> + Send;
+}
+
+/// Port for notification persistence operations.
+pub trait NotificationRepository {
+ /// Get users who have muted notifications.
+ fn get_muted_users<'a>(
+ &self,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> impl Future<Output = Result<HashSet<MacroUserIdStr<'static>>, Report>> + Send;
+
+ /// Get users who have unsubscribed from notifications for a specific item.
+ fn get_unsubscribed_users<'a>(
+ &self,
+ item_id: &str,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> impl Future<Output = Result<HashSet<MacroUserIdStr<'static>>, Report>> + Send;
+
+ /// Create a notification and user notification records.
+ ///
+ /// Returns the notification ID if successful, or None if it already exists
+ /// (idempotent operation).
+ fn create_notification<'a, T: Notification + Send + Sync>(
+ &self,
+ request: &SendNotificationRequestBuilder<'a, T>,
+ notification_id: Uuid,
+ service_sender: &str,
+ recipient_ids: &[MacroUserIdStr<'a>],
+ ) -> impl Future<Output = Result<Option<Uuid>, Report>> + Send;
+
+ /// Update the sent status for users who received the notification.
+ fn update_sent_status<'a>(
+ &self,
+ notification_id: Uuid,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+
+ /// Get device endpoints for push notifications.
+ fn get_device_endpoints<'a>(
+ &self,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> impl Future<Output = Result<HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>, Report>> + Send;
+}
+
+/// Port for WebSocket delivery via connection gateway.
+pub trait WebSocketSender {
+ /// Send notifications to users via WebSocket.
+ ///
+ /// Returns the set of users who successfully received the notification
+ /// (i.e., they were online and the message was delivered).
+ fn send_notifications<'a, T: Serialize + Send + Sync>(
+ &self,
+ message_type: &str,
+ notifications: Vec<(MacroUserIdStr<'a>, &T)>,
+ ) -> impl Future<Output = Result<HashSet<MacroUserIdStr<'static>>, Report>> + Send;
+}
+
+use crate::domain::models::queue_message::EmailContent;
+
+/// Port for email delivery.
+pub trait EmailSender {
+ /// Send an email with pre-built content to a user.
+ fn send_email(
+ &self,
+ recipient: MacroUserIdStr<'_>,
+ content: &EmailContent,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+}
+
+use crate::domain::models::queue_message::{QueueMessage, RawQueueMessage};
+
+/// Port for publishing notifications to delivery queue and receiving them.
+pub trait NotificationQueue {
+ /// Publish notifications for async delivery (after DB persistence).
+ fn publish<T: Serialize + Send + Sync>(
+ &self,
+ messages: &[QueueMessage<'_, T>],
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+
+ /// Receive messages from the queue (for worker).
+ fn receive_messages(&self)
+ -> impl Future<Output = Result<Vec<RawQueueMessage>, Report>> + Send;
+
+ /// Delete a message from the queue (after successful delivery).
+ fn delete_message(
+ &self,
+ receipt_handle: &str,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+}
diff --git a/rust/cloud-storage/notification/src/domain/service.rs b/rust/cloud-storage/notification/src/domain/service.rs
new file mode 100644
index 0000000000..806fd01cdf
--- /dev/null
+++ b/rust/cloud-storage/notification/src/domain/service.rs
@@ -0,0 +1,29 @@
+//! Core notification service implementation.
+//!
+//! Contains two services:
+//! - [`NotificationIngressService`]: For callers to send notifications (filter, persist, publish to queue)
+//! - [`NotificationEgressService`]: For workers to deliver notifications (consume from queue, deliver)
+
+mod egress;
+mod ingress;
+#[cfg(test)]
+mod test;
+
+use thiserror::Error;
+
+pub use egress::NotificationEgressService;
+pub use ingress::NotificationIngressService;
+
+/// Error returned when sending a notification fails.
+#[derive(Debug, Error)]
+pub enum SendNotificationError {
+ /// Rate limit was exceeded.
+ #[error("Rate limit exceeded")]
+ RateLimitExceeded,
+ /// Invalid rate limit config, either a key was provided but a key was not, or vice versa.
+ #[error("Rate limit config error")]
+ RateLimitConfigErr,
+ /// An internal error occurred.
+ #[error("Internal error")]
+ Other,
+}
diff --git a/rust/cloud-storage/notification/src/domain/service/egress.rs b/rust/cloud-storage/notification/src/domain/service/egress.rs
new file mode 100644
index 0000000000..7b17ffdb06
--- /dev/null
+++ b/rust/cloud-storage/notification/src/domain/service/egress.rs
@@ -0,0 +1,146 @@
+//! Egress service for delivering notifications.
+//!
+//! This service handles the worker-facing side of notifications:
+//! consuming from the queue and delivering via WebSocket, push, and email.
+
+use crate::domain::models::queue_message::{
+ ConnGatewayNotification, DeliveryFailure, DeliverySuccess, EmailNotification, Node,
+ NotificationChannel, QueueMessage,
+};
+use crate::domain::ports::{
+ EmailSender, NotificationRepository, NotificationSender, RateLimitPort, WebSocketSender,
+};
+use rootcause::prelude::ResultExt;
+use rootcause::{Report, report};
+
+/// Service for delivering notifications (egress side).
+///
+/// Handles consuming from queue and delivering via WebSocket, push, and email.
+pub struct NotificationEgressService<N, W, M, E, R> {
+ #[allow(dead_code)]
+ repository: N,
+ websocket: W,
+ mobile: M,
+ email: E,
+ rate_limiter: R,
+}
+
+impl<N, W, M, E, R> NotificationEgressService<N, W, M, E, R>
+where
+ N: NotificationRepository,
+ W: WebSocketSender,
+ M: NotificationSender,
+ E: EmailSender,
+ R: RateLimitPort,
+{
+ /// Create a new egress service.
+ pub fn new(repository: N, websocket: W, mobile: M, email: E, rate_limiter: R) -> Self {
+ Self {
+ repository,
+ websocket,
+ mobile,
+ email,
+ rate_limiter,
+ }
+ }
+
+ /// Deliver a notification from a queue message.
+ ///
+ /// Processes the delivery chain, attempting each channel and falling back
+ /// on failure. Returns a list of results for each delivery attempt.
+ ///
+ /// If a rate limit is configured and exceeded, returns an empty list (no delivery).
+ pub async fn deliver_notification(
+ &self,
+ message: QueueMessage<'static, serde_json::Value>,
+ ) -> Vec<Result<DeliverySuccess, Report<DeliveryFailure>>> {
+ // Check rate limit if configured
+ if let Some((key, config)) = message.rate_limit {
+ match self.rate_limiter.check_and_increment(key, config).await {
+ Ok(crate::domain::models::RateLimitResult::Exceeded(exceeded)) => {
+ return vec![Err(report!(exceeded).context(DeliveryFailure::RateLimit))];
+ }
+ Err(e) => return vec![Err(e.context(DeliveryFailure::RateLimit))],
+ Ok(_) => {
+ // Rate limit allowed, continue
+ }
+ }
+ }
+
+ self.deliver_notification_inner(&message.message_type, message.content, Vec::new())
+ .await
+ .into_iter()
+ .map(|r| r.context(DeliveryFailure::Other))
+ .collect()
+ }
+
+ /// Deliver a single node, with fallback on failure.
+ async fn deliver_notification_inner(
+ &self,
+ message_type: &str,
+ node: Node<'static, serde_json::Value>,
+ mut recursion_tail: Vec<Result<DeliverySuccess, Report>>,
+ ) -> Vec<Result<DeliverySuccess, Report>> {
+ let result = match &node.notif {
+ NotificationChannel::ConnGateway(conn) => {
+ self.deliver_conn_gateway(message_type, conn).await
+ }
+ NotificationChannel::Ios(apns) => self.deliver_ios(apns).await,
+ NotificationChannel::Email(email) => self.deliver_email(email).await,
+ };
+ recursion_tail.push(result);
+ let res = recursion_tail
+ .last()
+ .expect("we just pushed, this cannot fail");
+
+ match (res, node.on_failure) {
+ (Ok(_), _) | (Err(_), None) => recursion_tail,
+ (Err(_), Some(fallback)) => {
+ Box::pin(self.deliver_notification_inner(message_type, *fallback, recursion_tail))
+ .await
+ }
+ }
+ }
+
+ /// Deliver via connection gateway (WebSocket).
+ async fn deliver_conn_gateway(
+ &self,
+ message_type: &str,
+ conn: &ConnGatewayNotification<'static, serde_json::Value>,
+ ) -> Result<DeliverySuccess, Report> {
+ let notifications: Vec<_> = conn
+ .recipients
+ .iter()
+ .map(|r| (r.clone(), &conn.notif))
+ .collect();
+
+ self.websocket
+ .send_notifications(message_type, notifications)
+ .await?;
+ Ok(DeliverySuccess::ConnGateway)
+ }
+
+ /// Deliver via iOS push (APNS).
+ async fn deliver_ios(
+ &self,
+ apns: &crate::domain::models::queue_message::APNSTargets<serde_json::Value>,
+ ) -> Result<DeliverySuccess, Report> {
+ for endpoint in &apns.ios_device_endpoints {
+ self.mobile
+ .send_ios_push_notification(endpoint, &apns.notif, &apns.attributes)
+ .await?;
+ }
+ Ok(DeliverySuccess::Ios)
+ }
+
+ /// Deliver via email.
+ async fn deliver_email(
+ &self,
+ email: &EmailNotification<'static>,
+ ) -> Result<DeliverySuccess, Report> {
+ self.email
+ .send_email(email.to.clone(), &email.content)
+ .await?;
+ Ok(DeliverySuccess::Email)
+ }
+}
diff --git a/rust/cloud-storage/notification/src/domain/service/ingress.rs b/rust/cloud-storage/notification/src/domain/service/ingress.rs
new file mode 100644
index 0000000000..61b58e8383
--- /dev/null
+++ b/rust/cloud-storage/notification/src/domain/service/ingress.rs
@@ -0,0 +1,265 @@
+//! Ingress service for sending notifications.
+//!
+//! This service handles the caller-facing side of notifications:
+//! filtering recipients, persisting to DB, and publishing to the queue.
+
+use crate::domain::models::queue_message::{
+ APNSTargets, ConnGatewayNotification, EmailNotification, Node, NotificationChannel,
+ QueueMessage,
+};
+use crate::domain::models::recipient::FilteredRecipient;
+use crate::domain::models::{
+ DeviceEndpoint, ExclusionReason, Notification, NotificationResult, RecipientExclusion,
+ SendNotificationRequest,
+};
+use crate::domain::ports::{NotificationQueue, NotificationRepository};
+use crate::domain::service::SendNotificationError;
+use itertools::Itertools;
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+use rootcause::prelude::ResultExt;
+use serde::Serialize;
+use std::collections::HashSet;
+use uuid::Uuid;
+
+/// Service for sending notifications (ingress side).
+///
+/// Handles recipient filtering, DB persistence, and queue publishing.
+/// Does NOT handle delivery - that's done by [`super::NotificationEgressService`].
+pub struct NotificationIngressService<N, Q> {
+ repository: N,
+ queue: Q,
+ service_name: String,
+}
+
+impl<N, Q> NotificationIngressService<N, Q>
+where
+ N: NotificationRepository,
+ Q: NotificationQueue,
+{
+ /// Create a new ingress service.
+ pub fn new(repository: N, queue: Q, service_name: impl Into<String>) -> Self {
+ Self {
+ repository,
+ queue,
+ service_name: service_name.into(),
+ }
+ }
+
+ /// Send a notification to the specified recipients.
+ ///
+ /// This method performs the following steps:
+ /// 1. Filter recipients (remove sender, muted users, unsubscribed users)
+ /// 2. Create notification in the database
+ /// 3. Build and publish QueueMessage to SQS
+ /// 4. Return result (delivery happens async via worker)
+ pub async fn send_notification<'a, T: Notification + Serialize + Clone + Send + Sync>(
+ &self,
+ request: SendNotificationRequest<'a, T>,
+ ) -> Result<Option<NotificationResult<'a>>, Report<SendNotificationError>> {
+ let recipients: Vec<_> = request.req.recipient_ids.iter().cloned().collect();
+ let (allowed, _excluded): (Vec<_>, Vec<_>) = self
+ .filter_recipients(
+ request.req.sender_id.as_ref(),
+ &recipients,
+ &request.req.notification_entity.entity_id,
+ )
+ .await
+ .context(SendNotificationError::Other)?
+ .into_iter()
+ .partition_map(|r| match r {
+ FilteredRecipient::Allowed(macro_user_id_str) => {
+ itertools::Either::Left(macro_user_id_str)
+ }
+ FilteredRecipient::Excluded(recipient_exclusion) => {
+ itertools::Either::Right(recipient_exclusion)
+ }
+ });
+
+ if allowed.is_empty() {
+ return Ok(None);
+ }
+
+ // Create notification in DB
+ let notification_id = Uuid::now_v7();
+ let created = self
+ .repository
+ .create_notification(&request.req, notification_id, &self.service_name, &allowed)
+ .await
+ .context(SendNotificationError::Other)?;
+
+ // If notification already exists (idempotent), return early
+ let Some(notification_id) = created else {
+ return Ok(Some(NotificationResult {
+ notification_id,
+ notified_recipients: HashSet::new(),
+ }));
+ };
+
+ let mut req =
+ request.update_recipients(allowed.into_iter().map(CowLike::into_owned).collect());
+
+ // Build and publish QueueMessage
+ let queue_messages = self.build_queue_message(&mut req).await?;
+
+ self.queue
+ .publish(&queue_messages)
+ .await
+ .context(SendNotificationError::Other)?;
+
+ // Return result (delivery happens async)
+ Ok(Some(NotificationResult {
+ notification_id,
+ notified_recipients: req.req.recipient_ids,
+ }))
+ }
+
+ /// Filter recipients based on:
+ /// - Sender (sender cannot receive their own notification)
+ /// - Muted notifications
+ /// - Unsubscribed from item
+ async fn filter_recipients<'a>(
+ &self,
+ sender_id: Option<&MacroUserIdStr<'a>>,
+ recipient_ids: &'a [MacroUserIdStr<'a>],
+ item_id: &str,
+ ) -> Result<Vec<FilteredRecipient<'a>>, Report> {
+ // Fetch all filter data upfront
+ let (muted_users, unsubscribed_users) = tokio::try_join!(
+ self.repository.get_muted_users(recipient_ids),
+ self.repository
+ .get_unsubscribed_users(item_id, recipient_ids),
+ )?;
+
+ let recipient_is_sender = |id: FilteredRecipient<'a>| match (id, sender_id) {
+ (FilteredRecipient::Allowed(macro_user_id_str), Some(sender))
+ if sender == &macro_user_id_str =>
+ {
+ FilteredRecipient::Excluded(RecipientExclusion {
+ user_id: macro_user_id_str,
+ reason: ExclusionReason::IsSender,
+ })
+ }
+ (x, _) => x,
+ };
+
+ let user_muted_notifs = |id: FilteredRecipient<'a>| match id {
+ FilteredRecipient::Allowed(macro_user_id_str)
+ if muted_users.contains(&macro_user_id_str) =>
+ {
+ FilteredRecipient::Excluded(RecipientExclusion {
+ user_id: macro_user_id_str,
+ reason: ExclusionReason::MutedNotifications,
+ })
+ }
+ x => x,
+ };
+
+ let notif_type_is_ignored = |id: FilteredRecipient<'a>| match id {
+ FilteredRecipient::Allowed(macro_user_id_str)
+ if unsubscribed_users.contains(&macro_user_id_str) =>
+ {
+ FilteredRecipient::Excluded(RecipientExclusion {
+ user_id: macro_user_id_str,
+ reason: ExclusionReason::UnsubscribedFromItem,
+ })
+ }
+ x => x,
+ };
+
+ // Build exclusion reasons for excluded recipients
+ Ok(recipient_ids
+ .iter()
+ .map(CowLike::copied)
+ .map(FilteredRecipient::Allowed)
+ .map(recipient_is_sender)
+ .map(user_muted_notifs)
+ .map(notif_type_is_ignored)
+ .collect())
+ }
+
+ /// Build queue messages for each delivery channel.
+ ///
+ /// - `send_conn_gateway`: Creates a single message for all recipients (1:M)
+ /// - `build_apns`: Creates one message per recipient with their device endpoints (1:1)
+ /// - `build_email`: Creates one message per recipient (1:1)
+ async fn build_queue_message<'a, T: Notification + Serialize + Clone>(
+ &self,
+ notification: &mut SendNotificationRequest<'a, T>,
+ ) -> Result<Vec<QueueMessage<'a, T>>, Report<SendNotificationError>> {
+ let rate_limit = notification.req.get_rate_limit()?;
+ let message_type = T::TYPE_NAME.to_string();
+ let mut messages = Vec::new();
+
+ // Connection gateway: 1:M (single message for all recipients)
+ if notification.send_conn_gateway {
+ messages.push(QueueMessage {
+ message_type: message_type.clone(),
+ rate_limit: rate_limit.clone(),
+ content: Node {
+ notif: NotificationChannel::ConnGateway(ConnGatewayNotification {
+ notif: notification.req.notification.clone(),
+ recipients: notification.req.recipient_ids.iter().cloned().collect(),
+ }),
+ on_failure: None,
+ },
+ });
+ }
+
+ // APNS (iOS push): 1:M (single message for all recipients' device endpoints)
+ if let Some(ref mut build_apns) = notification.build_apns {
+ let recipients_vec: Vec<_> = notification.req.recipient_ids.iter().cloned().collect();
+ let device_endpoints = self
+ .repository
+ .get_device_endpoints(&recipients_vec)
+ .await
+ .context(SendNotificationError::Other)?;
+
+ let ios_endpoints: Vec<String> = device_endpoints
+ .values()
+ .flatten()
+ .filter_map(|e| match e {
+ DeviceEndpoint::Ios(arn) => Some(arn.clone()),
+ DeviceEndpoint::Android(_) => None,
+ })
+ .collect();
+
+ if !ios_endpoints.is_empty() {
+ let (apns_notif, attributes) = build_apns(notification.req.notification.clone());
+ messages.push(QueueMessage {
+ message_type: message_type.clone(),
+ rate_limit: rate_limit.clone(),
+ content: Node {
+ notif: NotificationChannel::Ios(Box::new(APNSTargets {
+ notif: apns_notif,
+ attributes,
+ ios_device_endpoints: ios_endpoints,
+ })),
+ on_failure: None,
+ },
+ });
+ }
+ }
+
+ // Email: 1:1 (one message per recipient)
+ if let Some(ref mut build_email) = notification.build_email {
+ for recipient in &notification.req.recipient_ids {
+ let email_content = build_email(notification.req.notification.clone());
+ messages.push(QueueMessage {
+ message_type: message_type.clone(),
+ rate_limit: rate_limit.clone(),
+ content: Node {
+ notif: NotificationChannel::Email(EmailNotification {
+ to: recipient.clone(),
+ content: email_content,
+ }),
+ on_failure: None,
+ },
+ });
+ }
+ }
+
+ Ok(messages)
+ }
+}
diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rs
new file mode 100644
index 0000000000..4b89d57ed0
--- /dev/null
+++ b/rust/cloud-storage/notification/src/domain/service/test.rs
@@ -0,0 +1,618 @@
+//! Unit tests for the notification services.
+
+use crate::domain::models::queue_message::{
+ ConnGatewayNotification, Node, NotificationChannel, QueueMessage, RawQueueMessage,
+};
+use crate::domain::models::{
+ DeviceEndpoint, Notification, RateLimitConfig, RateLimitExceeded, RateLimitKey,
+ RateLimitResult, SendNotificationRequestBuilder,
+};
+use crate::domain::ports::{
+ EmailSender, NotificationQueue, NotificationRepository, NotificationSender, RateLimitPort,
+ WebSocketSender,
+};
+use crate::domain::service::{NotificationEgressService, NotificationIngressService};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::EntityType;
+use rootcause::Report;
+use serde::{Deserialize, Serialize};
+use serde_json::json;
+use std::collections::{HashMap, HashSet};
+use std::sync::Mutex;
+use std::time::Duration;
+use uuid::Uuid;
+
+/// A test notification type.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+struct TestNotification {
+ message: String,
+}
+
+impl Notification for TestNotification {
+ const TYPE_NAME: &'static str = "test_notification";
+
+ fn title(&self) -> String {
+ "Test".to_string()
+ }
+
+ fn body(&self) -> String {
+ self.message.clone()
+ }
+
+ fn rate_limit_config() -> Option<RateLimitConfig> {
+ None
+ }
+
+ fn rate_limit_key(&self) -> Option<RateLimitKey> {
+ None
+ }
+}
+
+/// Helper to create a test user ID.
+fn test_user_id(email: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email(email).unwrap()
+}
+
+/// Mock repository that tracks calls.
+struct MockRepository {
+ muted_users: HashSet<MacroUserIdStr<'static>>,
+ unsubscribed_users: HashSet<MacroUserIdStr<'static>>,
+ device_endpoints: HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>,
+ created_notifications: Mutex<Vec<Uuid>>,
+}
+
+impl MockRepository {
+ fn new() -> Self {
+ Self {
+ muted_users: HashSet::new(),
+ unsubscribed_users: HashSet::new(),
+ device_endpoints: HashMap::new(),
+ created_notifications: Mutex::new(Vec::new()),
+ }
+ }
+
+ fn with_muted_user(mut self, user_id: MacroUserIdStr<'static>) -> Self {
+ self.muted_users.insert(user_id);
+ self
+ }
+
+ fn with_unsubscribed_user(mut self, user_id: MacroUserIdStr<'static>) -> Self {
+ self.unsubscribed_users.insert(user_id);
+ self
+ }
+
+ fn with_device_endpoint(
+ mut self,
+ user_id: MacroUserIdStr<'static>,
+ endpoint: DeviceEndpoint,
+ ) -> Self {
+ self.device_endpoints
+ .entry(user_id)
+ .or_default()
+ .push(endpoint);
+ self
+ }
+}
+
+impl NotificationRepository for MockRepository {
+ async fn get_muted_users<'a>(
+ &self,
+ _user_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {
+ Ok(self.muted_users.clone())
+ }
+
+ async fn get_unsubscribed_users<'a>(
+ &self,
+ _item_id: &str,
+ _user_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {
+ Ok(self.unsubscribed_users.clone())
+ }
+
+ async fn create_notification<'a, T: Notification + Send + Sync>(
+ &self,
+ _request: &SendNotificationRequestBuilder<'a, T>,
+ notification_id: Uuid,
+ _service_sender: &str,
+ _recipient_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<Option<Uuid>, Report> {
+ self.created_notifications
+ .lock()
+ .unwrap()
+ .push(notification_id);
+ Ok(Some(notification_id))
+ }
+
+ async fn update_sent_status<'a>(
+ &self,
+ _notification_id: Uuid,
+ _user_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<(), Report> {
+ Ok(())
+ }
+
+ async fn get_device_endpoints<'a>(
+ &self,
+ _user_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>, Report> {
+ Ok(self.device_endpoints.clone())
+ }
+}
+
+/// Mock queue that tracks published messages.
+struct MockQueue {
+ /// Stores serialized messages as JSON strings for inspection.
+ published: Mutex<Vec<serde_json::Value>>,
+}
+
+impl MockQueue {
+ fn new() -> Self {
+ Self {
+ published: Mutex::new(Vec::new()),
+ }
+ }
+
+ fn get_published(&self) -> Vec<serde_json::Value> {
+ self.published.lock().unwrap().clone()
+ }
+}
+
+impl NotificationQueue for MockQueue {
+ async fn publish<T: serde::Serialize + Send + Sync>(
+ &self,
+ messages: &[QueueMessage<'_, T>],
+ ) -> Result<(), Report> {
+ let mut published = self.published.lock().unwrap();
+ for message in messages {
+ let json = serde_json::to_value(message).unwrap();
+ published.push(json);
+ }
+ Ok(())
+ }
+
+ async fn receive_messages(&self) -> Result<Vec<RawQueueMessage>, Report> {
+ Ok(Vec::new())
+ }
+
+ async fn delete_message(&self, _receipt_handle: &str) -> Result<(), Report> {
+ Ok(())
+ }
+}
+
+impl NotificationQueue for std::sync::Arc<MockQueue> {
+ async fn publish<T: serde::Serialize + Send + Sync>(
+ &self,
+ messages: &[QueueMessage<'_, T>],
+ ) -> Result<(), Report> {
+ (**self).publish(messages).await
+ }
+
+ async fn receive_messages(&self) -> Result<Vec<RawQueueMessage>, Report> {
+ (**self).receive_messages().await
+ }
+
+ async fn delete_message(&self, _receipt_handle: &str) -> Result<(), Report> {
+ (**self).delete_message(_receipt_handle).await
+ }
+}
+
+fn create_service<N, Q>(repository: N, queue: Q) -> NotificationIngressService<N, Q>
+where
+ N: NotificationRepository,
+ Q: NotificationQueue,
+{
+ NotificationIngressService::new(repository, queue, "test_service")
+}
+
+#[tokio::test]
+async fn test_send_notification_success() {
+ let service = create_service(MockRepository::new(), MockQueue::new());
+
+ let recipient = test_user_id("[email protected]");
+ let request = SendNotificationRequestBuilder {
+ notification_entity: EntityType::Document.with_entity_str("entity_1"),
+ notification: TestNotification {
+ message: "Hello".to_string(),
+ },
+ sender_id: None,
+ recipient_ids: HashSet::from([recipient.clone()]),
+ }
+ .into_request();
+
+ let result = service.send_notification(request).await.unwrap().unwrap();
+
+ assert!(result.notified_recipients.contains(&recipient));
+}
+
+#[tokio::test]
+async fn test_sender_excluded_from_recipients() {
+ let service = create_service(MockRepository::new(), MockQueue::new());
+
+ let sender = test_user_id("[email protected]");
+ let request = SendNotificationRequestBuilder {
+ notification_entity: EntityType::Document.with_entity_str("entity_1"),
+ notification: TestNotification {
+ message: "Hello".to_string(),
+ },
+ sender_id: Some(sender.clone()),
+ recipient_ids: HashSet::from([sender.clone()]),
+ }
+ .into_request();
+
+ let result = service.send_notification(request).await.unwrap();
+
+ // Sender should be excluded, no valid recipients remain
+ assert!(result.is_none());
+}
+
+#[tokio::test]
+async fn test_muted_user_excluded() {
+ let muted_user = test_user_id("[email protected]");
+ let service = create_service(
+ MockRepository::new().with_muted_user(muted_user.clone()),
+ MockQueue::new(),
+ );
+
+ let request = SendNotificationRequestBuilder {
+ notification_entity: EntityType::Document.with_entity_str("entity_1"),
+ notification: TestNotification {
+ message: "Hello".to_string(),
+ },
+ sender_id: None,
+ recipient_ids: HashSet::from([muted_user]),
+ }
+ .into_request();
+
+ let result = service.send_notification(request).await.unwrap();
+
+ // Muted user should be excluded, no valid recipients remain
+ assert!(result.is_none());
+}
+
+#[tokio::test]
+async fn test_unsubscribed_user_excluded() {
+ let unsubscribed_user = test_user_id("[email protected]");
+ let service = create_service(
+ MockRepository::new().with_unsubscribed_user(unsubscribed_user.clone()),
+ MockQueue::new(),
+ );
+
+ let request = SendNotificationRequestBuilder {
+ notification_entity: EntityType::Document.with_entity_str("entity_1"),
+ notification: TestNotification {
+ message: "Hello".to_string(),
+ },
+ sender_id: None,
+ recipient_ids: HashSet::from([unsubscribed_user]),
+ }
+ .into_request();
+
+ let result = service.send_notification(request).await.unwrap();
+
+ // Unsubscribed user should be excluded, no valid recipients remain
+ assert!(result.is_none());
+}
+
+#[tokio::test]
+async fn test_queue_message_conn_gateway_only() {
+ use std::sync::Arc;
+
+ let queue = Arc::new(MockQueue::new());
+ let service =
+ NotificationIngressService::new(MockRepository::new(), queue.clone(), "test_service");
+
+ let recipient = test_user_id("[email protected]");
+ let request = SendNotificationRequestBuilder {
+ notification_entity: EntityType::Document.with_entity_str("entity_1"),
+ notification: TestNotification {
+ message: "Hello".to_string(),
+ },
+ sender_id: None,
+ recipient_ids: HashSet::from([recipient.clone()]),
+ }
+ .into_request()
+ .with_conn_gateway();
+
+ service.send_notification(request).await.unwrap();
+
+ let published = queue.get_published();
+ assert_eq!(published.len(), 1);
+
+ let msg = &published[0];
+ assert_eq!(msg["message_type"], "test_notification");
+ assert!(msg["content"]["notif"]["ConnGateway"].is_object());
+}
+
+#[tokio::test]
+async fn test_queue_message_email_per_recipient() {
+ use crate::domain::models::queue_message::EmailContent;
+ use std::sync::Arc;
+
+ let queue = Arc::new(MockQueue::new());
+ let service =
+ NotificationIngressService::new(MockRepository::new(), queue.clone(), "test_service");
+
+ let recipient1 = test_user_id("[email protected]");
+ let recipient2 = test_user_id("[email protected]");
+ let request = SendNotificationRequestBuilder {
+ notification_entity: EntityType::Document.with_entity_str("entity_1"),
+ notification: TestNotification {
+ message: "Hello".to_string(),
+ },
+ sender_id: None,
+ recipient_ids: HashSet::from([recipient1.clone(), recipient2.clone()]),
+ }
+ .into_request()
+ .with_email(Box::new(|notif| EmailContent {
+ subject: "Test".to_string(),
+ body: notif.message,
+ }));
+
+ service.send_notification(request).await.unwrap();
+
+ let published = queue.get_published();
+ // Email is 1:1, so we should have 2 messages (one per recipient)
+ assert_eq!(published.len(), 2);
+
+ for msg in &published {
+ assert_eq!(msg["message_type"], "test_notification");
+ assert!(msg["content"]["notif"]["Email"].is_object());
+ }
+}
+
+#[tokio::test]
+async fn test_queue_message_multiple_channels() {
+ use crate::domain::models::apple::APNSPushNotification;
+ use crate::domain::models::mobile::{MessageAttributes, PushType};
+ use crate::domain::models::queue_message::EmailContent;
+ use std::sync::Arc;
+
+ let recipient = test_user_id("[email protected]");
+ let queue = Arc::new(MockQueue::new());
+ let repo = MockRepository::new().with_device_endpoint(
+ recipient.clone(),
+ DeviceEndpoint::Ios("arn:aws:sns:test".to_string()),
+ );
+ let service = NotificationIngressService::new(repo, queue.clone(), "test_service");
+
+ let request = SendNotificationRequestBuilder {
+ notification_entity: EntityType::Document.with_entity_str("entity_1"),
+ notification: TestNotification {
+ message: "Hello".to_string(),
+ },
+ sender_id: None,
+ recipient_ids: HashSet::from([recipient.clone()]),
+ }
+ .into_request()
+ .with_conn_gateway()
+ .with_apns(Box::new(|notif| {
+ (
+ APNSPushNotification {
+ aps: Default::default(),
+ push_notification_data: notif,
+ },
+ MessageAttributes {
+ push_type: PushType::Alert,
+ collapse_key: "test".to_string(),
+ },
+ )
+ }))
+ .with_email(Box::new(|notif| EmailContent {
+ subject: "Test".to_string(),
+ body: notif.message,
+ }));
+
+ service.send_notification(request).await.unwrap();
+
+ let published = queue.get_published();
+ // Should have 3 messages: 1 conn_gateway + 1 iOS + 1 email
+ assert_eq!(published.len(), 3);
+
+ let has_conn_gateway = published
+ .iter()
+ .any(|m| m["content"]["notif"]["ConnGateway"].is_object());
+ let has_ios = published
+ .iter()
+ .any(|m| m["content"]["notif"]["Ios"].is_object());
+ let has_email = published
+ .iter()
+ .any(|m| m["content"]["notif"]["Email"].is_object());
+
+ assert!(has_conn_gateway, "Should have ConnGateway message");
+ assert!(has_ios, "Should have iOS message");
+ assert!(has_email, "Should have Email message");
+}
+
+// ============================================================================
+// Egress Service Tests
+// ============================================================================
+
+/// Mock WebSocket sender that always succeeds.
+struct MockWebSocketSender;
+
+impl WebSocketSender for MockWebSocketSender {
+ async fn send_notifications<'a, T: Serialize + Send + Sync>(
+ &self,
+ _message_type: &str,
+ _notifications: Vec<(MacroUserIdStr<'a>, &T)>,
+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {
+ Ok(HashSet::new())
+ }
+}
+
+/// Mock mobile push sender.
+struct MockMobileSender;
+
+impl NotificationSender for MockMobileSender {
+ async fn send_ios_push_notification<T: Serialize + Send + Sync>(
+ &self,
+ _endpoint_arn: &str,
+ _notification: &crate::domain::models::apple::APNSPushNotification<T>,
+ _attributes: &crate::domain::models::mobile::MessageAttributes,
+ ) -> Result<(), Report> {
+ Ok(())
+ }
+
+ async fn send_android_push_notification<T: Serialize + Send + Sync>(
+ &self,
+ _endpoint_arn: &str,
+ _notification: &crate::domain::models::android::FCMMessage<T>,
+ _attributes: &crate::domain::models::mobile::MessageAttributes,
+ ) -> Result<(), Report> {
+ Ok(())
+ }
+}
+
+/// Mock email sender.
+struct MockEmailSender;
+
+impl EmailSender for MockEmailSender {
+ async fn send_email(
+ &self,
+ _recipient: MacroUserIdStr<'_>,
+ _content: &crate::domain::models::queue_message::EmailContent,
+ ) -> Result<(), Report> {
+ Ok(())
+ }
+}
+
+/// Mock rate limiter that can be configured to allow or exceed.
+struct MockRateLimiter {
+ should_exceed: bool,
+}
+
+impl MockRateLimiter {
+ fn allowing() -> Self {
+ Self {
+ should_exceed: false,
+ }
+ }
+
+ fn exceeding() -> Self {
+ Self {
+ should_exceed: true,
+ }
+ }
+}
+
+impl RateLimitPort for MockRateLimiter {
+ async fn check_and_increment(
+ &self,
+ _key: RateLimitKey,
+ config: RateLimitConfig,
+ ) -> Result<RateLimitResult, Report> {
+ if self.should_exceed {
+ Ok(RateLimitResult::Exceeded(RateLimitExceeded {
+ key: "test_key".to_string(),
+ current_count: config.max_count + 1,
+ max_count: config.max_count,
+ }))
+ } else {
+ Ok(RateLimitResult::Allowed { current_count: 1 })
+ }
+ }
+}
+
+fn create_egress_service<R: RateLimitPort>(
+ rate_limiter: R,
+) -> NotificationEgressService<
+ MockRepository,
+ MockWebSocketSender,
+ MockMobileSender,
+ MockEmailSender,
+ R,
+> {
+ NotificationEgressService::new(
+ MockRepository::new(),
+ MockWebSocketSender,
+ MockMobileSender,
+ MockEmailSender,
+ rate_limiter,
+ )
+}
+
+#[tokio::test]
+async fn test_egress_rate_limit_exceeded() {
+ let service = create_egress_service(MockRateLimiter::exceeding());
+
+ let recipient = test_user_id("[email protected]");
+ let message = QueueMessage {
+ message_type: "test_notification".to_string(),
+ rate_limit: Some((
+ RateLimitKey::from_str_hashed("test"),
+ RateLimitConfig::new(10, Duration::from_secs(3600)),
+ )),
+ content: Node {
+ notif: NotificationChannel::ConnGateway(ConnGatewayNotification {
+ notif: json!({"message": "Hello"}),
+ recipients: vec![recipient],
+ }),
+ on_failure: None,
+ },
+ };
+
+ let results = service.deliver_notification(message).await;
+
+ // Should have exactly one error result for rate limit exceeded
+ assert_eq!(results.len(), 1);
+ assert!(results[0].is_err());
+
+ let err = results[0].as_ref().unwrap_err();
+ assert!(
+ err.to_string().contains("rate limit"),
+ "Error should mention rate limit: {}",
+ err
+ );
+}
+
+#[tokio::test]
+async fn test_egress_rate_limit_allowed() {
+ let service = create_egress_service(MockRateLimiter::allowing());
+
+ let recipient = test_user_id("[email protected]");
+ let message = QueueMessage {
+ message_type: "test_notification".to_string(),
+ rate_limit: Some((
+ RateLimitKey::from_str_hashed("test"),
+ RateLimitConfig::new(10, Duration::from_secs(3600)),
+ )),
+ content: Node {
+ notif: NotificationChannel::ConnGateway(ConnGatewayNotification {
+ notif: json!({"message": "Hello"}),
+ recipients: vec![recipient],
+ }),
+ on_failure: None,
+ },
+ };
+
+ let results = service.deliver_notification(message).await;
+
+ // Should succeed
+ assert_eq!(results.len(), 1);
+ assert!(results[0].is_ok());
+}
+
+#[tokio::test]
+async fn test_egress_no_rate_limit_configured() {
+ let service = create_egress_service(MockRateLimiter::exceeding());
+
+ let recipient = test_user_id("[email protected]");
+ let message = QueueMessage {
+ message_type: "test_notification".to_string(),
+ rate_limit: None, // No rate limit configured
+ content: Node {
+ notif: NotificationChannel::ConnGateway(ConnGatewayNotification {
+ notif: json!({"message": "Hello"}),
+ recipients: vec![recipient],
+ }),
+ on_failure: None,
+ },
+ };
+
+ let results = service.deliver_notification(message).await;
+
+ // Should succeed even though rate limiter would exceed - because no rate limit is configured
+ assert_eq!(results.len(), 1);
+ assert!(results[0].is_ok());
+}
diff --git a/rust/cloud-storage/notification/src/inbound.rs b/rust/cloud-storage/notification/src/inbound.rs
new file mode 100644
index 0000000000..887e8966a1
--- /dev/null
+++ b/rust/cloud-storage/notification/src/inbound.rs
@@ -0,0 +1,2 @@
+pub mod http;
+pub mod worker;
diff --git a/rust/cloud-storage/notification/src/inbound/http.rs b/rust/cloud-storage/notification/src/inbound/http.rs
new file mode 100644
index 0000000000..bf430c6f0d
--- /dev/null
+++ b/rust/cloud-storage/notification/src/inbound/http.rs
@@ -0,0 +1,62 @@
+//! HTTP handlers for notification endpoints.
+//!
+//! These handlers expose the notification service via HTTP for internal
+//! service-to-service communication.
+
+use std::sync::Arc;
+
+use rootcause::Report;
+use serde::Serialize;
+
+use crate::domain::models::{Notification, NotificationResult, SendNotificationRequest};
+use crate::domain::ports::{NotificationQueue, NotificationRepository};
+use crate::domain::service::{NotificationIngressService, SendNotificationError};
+
+/// Client for sending notifications.
+///
+/// This is the main entry point for other services to send notifications.
+/// It wraps the `NotificationIngressService` and provides a convenient API.
+pub struct NotificationClient<N, Q> {
+ service: Arc<NotificationIngressService<N, Q>>,
+}
+
+impl<N, Q> Clone for NotificationClient<N, Q> {
+ fn clone(&self) -> Self {
+ Self {
+ service: Arc::clone(&self.service),
+ }
+ }
+}
+
+impl<N, Q> NotificationClient<N, Q>
+where
+ N: NotificationRepository + Send + Sync,
+ Q: NotificationQueue + Send + Sync,
+{
+ /// Create a new notification client.
+ pub fn new(service: NotificationIngressService<N, Q>) -> Self {
+ Self {
+ service: Arc::new(service),
+ }
+ }
+
+ /// Send a notification to the specified recipients.
+ ///
+ /// This method performs recipient filtering before persisting the notification
+ /// and publishing it to the queue for async delivery.
+ ///
+ /// # Arguments
+ ///
+ /// * `request` - The notification request containing recipients and content
+ ///
+ /// # Returns
+ ///
+ /// Returns the notification result including the ID and notified recipients,
+ /// or `None` if no valid recipients remain after filtering.
+ pub async fn send<'a, T: Notification + Serialize + Clone + Send + Sync>(
+ &self,
+ request: SendNotificationRequest<'a, T>,
+ ) -> Result<Option<NotificationResult<'a>>, Report<SendNotificationError>> {
+ self.service.send_notification(request).await
+ }
+}
diff --git a/rust/cloud-storage/notification/src/inbound/worker.rs b/rust/cloud-storage/notification/src/inbound/worker.rs
new file mode 100644
index 0000000000..cdd6aced1b
--- /dev/null
+++ b/rust/cloud-storage/notification/src/inbound/worker.rs
@@ -0,0 +1,96 @@
+//! Worker for processing queued notifications.
+//!
+//! This module handles delivery of notifications that have been validated
+//! and persisted. The main work (rate limiting, filtering) is done pre-queue,
+//! so this worker focuses on delivery.
+
+use rootcause::Report;
+use tracing::instrument;
+
+use crate::domain::ports::{
+ EmailSender, NotificationQueue, NotificationRepository, NotificationSender, RateLimitPort,
+ WebSocketSender,
+};
+use crate::domain::service::NotificationEgressService;
+
+/// Worker that processes notifications from the queue and delivers them.
+pub struct NotificationWorker<Q, N, W, M, E, R> {
+ queue: Q,
+ egress: NotificationEgressService<N, W, M, E, R>,
+}
+
+impl<Q, N, W, M, E, R> NotificationWorker<Q, N, W, M, E, R>
+where
+ Q: NotificationQueue,
+ N: NotificationRepository,
+ W: WebSocketSender,
+ M: NotificationSender,
+ E: EmailSender,
+ R: RateLimitPort,
+{
+ /// Create a new notification worker.
+ pub fn new(queue: Q, egress: NotificationEgressService<N, W, M, E, R>) -> Self {
+ Self { queue, egress }
+ }
+
+ /// Run a single iteration of the worker loop.
+ ///
+ /// Receives messages from the queue, processes each one, and deletes
+ /// successfully processed messages.
+ ///
+ /// Returns the number of messages successfully processed.
+ #[instrument(skip(self), err)]
+ pub async fn poll_and_process(&self) -> Result<usize, Report> {
+ let messages = self.queue.receive_messages().await?;
+ let count = messages.len();
+
+ for message in messages {
+ let receipt_handle = message.receipt_handle.clone();
+
+ // Process the message through egress service
+ let results = self.egress.deliver_notification(message.body).await;
+
+ // Check if any delivery failed
+ let has_failure = results.iter().any(|r| r.is_err());
+
+ if has_failure {
+ // Log failures - message will be retried via visibility timeout
+ for result in &results {
+ if let Err(e) = result {
+ tracing::error!(error = ?e, "failed to deliver notification");
+ }
+ }
+ } else {
+ // All deliveries succeeded, delete from queue
+ if let Err(e) = self.queue.delete_message(&receipt_handle).await {
+ tracing::error!(error = ?e, "failed to delete message from queue");
+ }
+ }
+ }
+
+ Ok(count)
+ }
+
+ /// Run the worker loop continuously.
+ ///
+ /// This method runs forever, polling the queue and processing messages.
+ /// It includes a small delay between empty polls to avoid hammering the queue.
+ pub async fn run(&self) -> ! {
+ loop {
+ match self.poll_and_process().await {
+ Ok(0) => {
+ // No messages, wait a bit before next poll
+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;
+ }
+ Ok(count) => {
+ tracing::debug!(count, "processed messages");
+ }
+ Err(e) => {
+ tracing::error!(error = ?e, "worker poll failed");
+ // Wait before retrying after error
+ tokio::time::sleep(std::time::Duration::from_secs(5)).await;
+ }
+ }
+ }
+ }
+}
diff --git a/rust/cloud-storage/notification/src/lib.rs b/rust/cloud-storage/notification/src/lib.rs
new file mode 100644
index 0000000000..00bf72f29d
--- /dev/null
+++ b/rust/cloud-storage/notification/src/lib.rs
@@ -0,0 +1,13 @@
+//! Notification service library.
+//!
+//! This crate provides a hexagonal architecture-based notification system
+//! for sending notifications via multiple channels (WebSocket, push, email).
+
+#![deny(missing_docs)]
+
+/// Domain layer containing core business logic, models, and port definitions.
+pub mod domain;
+/// Inbound adapters (HTTP handlers, clients).
+pub mod inbound;
+/// Outbound adapters (database, Redis, WebSocket gateway, SNS, SES).
+pub mod outbound;
diff --git a/rust/cloud-storage/notification/src/outbound.rs b/rust/cloud-storage/notification/src/outbound.rs
new file mode 100644
index 0000000000..223a6436d8
--- /dev/null
+++ b/rust/cloud-storage/notification/src/outbound.rs
@@ -0,0 +1,11 @@
+//! Outbound adapters for external services.
+//!
+//! These modules contain implementations of the domain ports that connect
+//! to external services like Redis, PostgreSQL, WebSocket gateways, etc.
+
+pub mod email;
+pub mod mobile;
+pub mod queue;
+pub mod rate_limit;
+pub mod repository;
+pub mod websocket;
diff --git a/rust/cloud-storage/notification/src/outbound/email.rs b/rust/cloud-storage/notification/src/outbound/email.rs
new file mode 100644
index 0000000000..4d3e4b9e45
--- /dev/null
+++ b/rust/cloud-storage/notification/src/outbound/email.rs
@@ -0,0 +1,93 @@
+//! Email notification adapter.
+
+use aws_sdk_sesv2::types::{Body, Content, Destination, EmailContent as SesEmailContent, Message};
+use macro_user_id::email::ReadEmailParts;
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+
+use crate::domain::models::queue_message::EmailContent;
+use crate::domain::ports::EmailSender;
+
+/// Email notification adapter.
+///
+/// This adapter sends email notifications through the configured email service.
+pub struct EmailAdapter<E> {
+ email_service: E,
+ from_email: String,
+}
+
+impl<E> EmailAdapter<E> {
+ /// Create a new email adapter.
+ pub fn new(email_service: E, from_email: String) -> Self {
+ Self {
+ email_service,
+ from_email,
+ }
+ }
+}
+
+/// Trait for email service operations.
+///
+/// This allows the adapter to work with different email service implementations.
+pub trait EmailServiceOps {
+ /// Send an email to the given address.
+ fn send_email(
+ &self,
+ from_email: &str,
+ to_email: &str,
+ subject: &str,
+ html_body: &str,
+ ) -> impl std::future::Future<Output = Result<(), Report>> + Send;
+}
+
+impl EmailServiceOps for aws_sdk_sesv2::Client {
+ async fn send_email(
+ &self,
+ from_email: &str,
+ to_email: &str,
+ subject: &str,
+ html_body: &str,
+ ) -> Result<(), Report> {
+ let dest = Destination::builder().to_addresses(to_email).build();
+
+ let subject_content = Content::builder().data(subject).charset("UTF-8").build()?;
+
+ let body_content = Content::builder()
+ .data(html_body)
+ .charset("UTF-8")
+ .build()?;
+
+ let body = Body::builder().html(body_content).build();
+
+ let msg = Message::builder()
+ .subject(subject_content)
+ .body(body)
+ .build();
+
+ let email_content = SesEmailContent::builder().simple(msg).build();
+
+ self.send_email()
+ .from_email_address(from_email)
+ .destination(dest)
+ .content(email_content)
+ .send()
+ .await?;
+
+ Ok(())
+ }
+}
+
+impl<E: EmailServiceOps + Send + Sync> EmailSender for EmailAdapter<E> {
+ async fn send_email(
+ &self,
+ recipient: MacroUserIdStr<'_>,
+ content: &EmailContent,
+ ) -> Result<(), Report> {
+ let email_part = recipient.email_part();
+ let to_email = email_part.email_str();
+
+ self.email_service
+ .send_email(&self.from_email, to_email, &content.subject, &content.body)
+ .await
+ }
+}
diff --git a/rust/cloud-storage/notification/src/outbound/mobile.rs b/rust/cloud-storage/notification/src/outbound/mobile.rs
new file mode 100644
index 0000000000..b514c39b29
--- /dev/null
+++ b/rust/cloud-storage/notification/src/outbound/mobile.rs
@@ -0,0 +1,138 @@
+//! Mobile push notification adapter.
+
+use aws_sdk_sns::types::MessageAttributeValue;
+use rootcause::Report;
+use serde::Serialize;
+use std::collections::HashMap;
+
+use crate::domain::models::android::FCMMessage;
+use crate::domain::models::apple::APNSPushNotification;
+use crate::domain::models::mobile::{MessageAttributes, PushType, SnsTarget};
+use crate::domain::ports::NotificationSender;
+
+/// Mobile push notification adapter.
+///
+/// This adapter sends push notifications to mobile devices via APNS (iOS)
+/// and FCM (Android) through SNS.
+pub struct MobilePushAdapter<P> {
+ push_service: P,
+ apns_bundle_id: &'static str,
+}
+
+impl<P> MobilePushAdapter<P> {
+ /// Create a new mobile push adapter.
+ pub fn new(push_service: P, apns_bundle_id: &'static str) -> Self {
+ Self {
+ push_service,
+ apns_bundle_id,
+ }
+ }
+}
+
+/// Trait for mobile push service operations via SNS.
+///
+/// This allows the adapter to work with different SNS client implementations.
+pub trait MobilePushOps {
+ /// Send a push notification to the specified endpoint ARN.
+ fn push_notification<T: Serialize + Send + Sync>(
+ &self,
+ endpoint_arn: &str,
+ message: &SnsTarget<'_, T>,
+ attributes: HashMap<String, MessageAttributeValue>,
+ ) -> impl std::future::Future<Output = Result<(), Report>> + Send;
+}
+
+impl MobilePushOps for aws_sdk_sns::Client {
+ async fn push_notification<T: Serialize + Send + Sync>(
+ &self,
+ endpoint_arn: &str,
+ message: &SnsTarget<'_, T>,
+ attributes: HashMap<String, MessageAttributeValue>,
+ ) -> Result<(), Report> {
+ let payload = message.as_json()?;
+
+ self.publish()
+ .target_arn(endpoint_arn)
+ .message_structure("json")
+ .message(payload)
+ .set_message_attributes(Some(attributes))
+ .send()
+ .await?;
+
+ Ok(())
+ }
+}
+
+impl<P: MobilePushOps + Send + Sync> NotificationSender for MobilePushAdapter<P> {
+ async fn send_ios_push_notification<T: Serialize + Send + Sync>(
+ &self,
+ endpoint_arn: &str,
+ notification: &APNSPushNotification<T>,
+ attributes: &MessageAttributes,
+ ) -> Result<(), Report> {
+ let target = SnsTarget::Ios(notification);
+ let sns_attributes = build_sns_attributes(self.apns_bundle_id, attributes);
+ self.push_service
+ .push_notification(endpoint_arn, &target, sns_attributes)
+ .await
+ }
+
+ async fn send_android_push_notification<T: Serialize + Send + Sync>(
+ &self,
+ endpoint_arn: &str,
+ notification: &FCMMessage<T>,
+ attributes: &MessageAttributes,
+ ) -> Result<(), Report> {
+ let target = SnsTarget::Android(notification);
+ let sns_attributes = build_sns_attributes(self.apns_bundle_id, attributes);
+ self.push_service
+ .push_notification(endpoint_arn, &target, sns_attributes)
+ .await
+ }
+}
+
+/// Build SNS message attributes from our domain attributes.
+fn build_sns_attributes(
+ apns_bundle_id: &str,
+ attributes: &MessageAttributes,
+) -> HashMap<String, MessageAttributeValue> {
+ let push_type_str = match attributes.push_type {
+ PushType::Background => "background",
+ PushType::Alert => "alert",
+ };
+
+ HashMap::from([
+ (
+ "AWS.SNS.MOBILE.APNS.TOPIC".to_string(),
+ MessageAttributeValue::builder()
+ .data_type("String")
+ .string_value(apns_bundle_id)
+ .build()
+ .expect("valid attribute"),
+ ),
+ (
+ "AWS.SNS.MOBILE.APNS.PUSH_TYPE".to_string(),
+ MessageAttributeValue::builder()
+ .data_type("String")
+ .string_value(push_type_str)
+ .build()
+ .expect("valid attribute"),
+ ),
+ (
+ "AWS.SNS.MOBILE.APNS.PRIORITY".to_string(),
+ MessageAttributeValue::builder()
+ .data_type("String")
+ .string_value("5")
+ .build()
+ .expect("valid attribute"),
+ ),
+ (
+ "AWS.SNS.MOBILE.APNS.COLLAPSE_ID".to_string(),
+ MessageAttributeValue::builder()
+ .data_type("String")
+ .string_value(&attributes.collapse_key)
+ .build()
+ .expect("valid attribute"),
+ ),
+ ])
+}
diff --git a/rust/cloud-storage/notification/src/outbound/queue.rs b/rust/cloud-storage/notification/src/outbound/queue.rs
new file mode 100644
index 0000000000..50a55f5dcb
--- /dev/null
+++ b/rust/cloud-storage/notification/src/outbound/queue.rs
@@ -0,0 +1,77 @@
+//! SQS queue adapter for notification delivery.
+
+use aws_sdk_sqs::Client as SqsClient;
+use rootcause::Report;
+use serde::Serialize;
+
+use crate::domain::models::queue_message::{QueueMessage, RawQueueMessage};
+use crate::domain::ports::NotificationQueue;
+
+/// SQS-backed implementation of the notification queue port.
+pub struct SqsNotificationQueue {
+ client: SqsClient,
+ queue_url: String,
+}
+
+impl SqsNotificationQueue {
+ /// Create a new SQS notification queue adapter.
+ pub fn new(client: SqsClient, queue_url: String) -> Self {
+ Self { client, queue_url }
+ }
+}
+
+impl NotificationQueue for SqsNotificationQueue {
+ async fn publish<T: Serialize + Send + Sync>(
+ &self,
+ messages: &[QueueMessage<'_, T>],
+ ) -> Result<(), Report> {
+ for message in messages {
+ let body = serde_json::to_string(message)?;
+ self.client
+ .send_message()
+ .queue_url(&self.queue_url)
+ .message_body(body)
+ .send()
+ .await?;
+ }
+ Ok(())
+ }
+
+ async fn receive_messages(&self) -> Result<Vec<RawQueueMessage>, Report> {
+ let result = self
+ .client
+ .receive_message()
+ .queue_url(&self.queue_url)
+ .max_number_of_messages(10)
+ .wait_time_seconds(20)
+ .send()
+ .await?;
+
+ let messages = result
+ .messages
+ .unwrap_or_default()
+ .into_iter()
+ .filter_map(|msg| {
+ let body_str = msg.body?;
+ let body = serde_json::from_str(&body_str).ok()?;
+ let receipt_handle = msg.receipt_handle?;
+ Some(RawQueueMessage {
+ body,
+ receipt_handle,
+ })
+ })
+ .collect();
+
+ Ok(messages)
+ }
+
+ async fn delete_message(&self, receipt_handle: &str) -> Result<(), Report> {
+ self.client
+ .delete_message()
+ .queue_url(&self.queue_url)
+ .receipt_handle(receipt_handle)
+ .send()
+ .await?;
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/notification/src/outbound/rate_limit.rs b/rust/cloud-storage/notification/src/outbound/rate_limit.rs
new file mode 100644
index 0000000000..02b18f0ce9
--- /dev/null
+++ b/rust/cloud-storage/notification/src/outbound/rate_limit.rs
@@ -0,0 +1,106 @@
+//! Redis-based rate limit adapter.
+
+use redis::AsyncCommands;
+use rootcause::Report;
+
+use crate::domain::models::{RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitResult};
+use crate::domain::ports::RateLimitPort;
+
+/// Redis-based implementation of the rate limit port.
+///
+/// This adapter uses Redis to store and check rate limit counters.
+/// The key is provided by the caller (already hashed), and this adapter
+/// handles the Redis operations.
+pub struct RedisRateLimitAdapter<R> {
+ redis: R,
+}
+
+impl<R> RedisRateLimitAdapter<R> {
+ /// Create a new Redis rate limit adapter.
+ pub fn new(redis: R) -> Self {
+ Self { redis }
+ }
+}
+
+/// Trait for Redis operations needed by the rate limit adapter.
+///
+/// This allows the adapter to work with different Redis client implementations.
+pub trait RedisRateLimitOps {
+ /// Get the current count for a key.
+ fn get_count(
+ &self,
+ key: &str,
+ ) -> impl std::future::Future<Output = Result<Option<u64>, Report>> + Send;
+
+ /// Increment a key and set expiry if it's new.
+ fn increment_with_expiry(
+ &self,
+ key: &str,
+ expiry_seconds: u64,
+ ) -> impl std::future::Future<Output = Result<u64, Report>> + Send;
+}
+
+impl RedisRateLimitOps for redis::Client {
+ async fn get_count(&self, key: &str) -> Result<Option<u64>, Report> {
+ let mut conn = self.get_multiplexed_async_connection().await?;
+ let count: Option<u64> = conn.get(key).await?;
+ Ok(count)
+ }
+
+ async fn increment_with_expiry(&self, key: &str, expiry_seconds: u64) -> Result<u64, Report> {
+ let mut conn = self.get_multiplexed_async_connection().await?;
+
+ // Use atomic pipeline: INCR + EXPIRE
+ let (new_count,): (u64,) = redis::pipe()
+ .atomic()
+ .incr(key, 1u64)
+ .expire(key, expiry_seconds as i64)
+ .ignore()
+ .query_async(&mut conn)
+ .await?;
+
+ Ok(new_count)
+ }
+}
+
+impl<R: RedisRateLimitOps + Send + Sync> RateLimitPort for RedisRateLimitAdapter<R> {
+ async fn check_and_increment(
+ &self,
+ key: RateLimitKey,
+ config: RateLimitConfig,
+ ) -> Result<RateLimitResult, Report> {
+ let key_str = format!("rtl:{}", key.to_hex_string());
+ let expiry_seconds = config.window.as_secs();
+
+ // Get current count
+ let current_count = self.redis.get_count(&key_str).await?.unwrap_or(0);
+
+ // Check if already exceeded
+ if current_count >= config.max_count {
+ return Ok(RateLimitResult::Exceeded(RateLimitExceeded {
+ key: key_str,
+ current_count,
+ max_count: config.max_count,
+ }));
+ }
+
+ // Increment and set expiry
+ let new_count = self
+ .redis
+ .increment_with_expiry(&key_str, expiry_seconds)
+ .await?;
+
+ // Check again after increment (in case of race condition)
+ if new_count > config.max_count {
+ Ok(RateLimitResult::Exceeded(RateLimitExceeded {
+ key: key_str,
+ current_count: new_count,
+ max_count: config.max_count,
+ }))
+ } else {
+ Ok(RateLimitResult::Allowed {
+ current_count: new_count,
+ })
+ }
+ }
+}
diff --git a/rust/cloud-storage/notification/src/outbound/repository.rs b/rust/cloud-storage/notification/src/outbound/repository.rs
new file mode 100644
index 0000000000..d1a2c04b6e
--- /dev/null
+++ b/rust/cloud-storage/notification/src/outbound/repository.rs
@@ -0,0 +1,288 @@
+//! Database repository adapter for notifications.
+
+use std::collections::{HashMap, HashSet};
+
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use crate::domain::models::{DeviceEndpoint, Notification, SendNotificationRequestBuilder};
+use crate::domain::ports::NotificationRepository;
+
+/// Database-backed implementation of the notification repository port.
+///
+/// This adapter handles all database operations for notifications including
+/// creating notifications, checking user preferences, and managing device endpoints.
+pub struct DbNotificationRepository<D> {
+ db: D,
+}
+
+impl<D> DbNotificationRepository<D> {
+ /// Create a new database notification repository.
+ pub fn new(db: D) -> Self {
+ Self { db }
+ }
+}
+
+/// Trait for database operations needed by the notification repository.
+///
+/// This allows the adapter to work with different database client implementations.
+pub trait NotificationDbOps {
+ /// Get users who have muted all notifications.
+ fn get_muted_users<'a>(
+ &self,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> impl std::future::Future<Output = Result<HashSet<MacroUserIdStr<'static>>, Report>> + Send;
+
+ /// Get users who have unsubscribed from notifications for a specific item.
+ fn get_unsubscribed_users<'a>(
+ &self,
+ item_id: &str,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> impl std::future::Future<Output = Result<HashSet<MacroUserIdStr<'static>>, Report>> + Send;
+
+ /// Get device endpoints for the given users.
+ fn get_device_endpoints<'a>(
+ &self,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> impl std::future::Future<
+ Output = Result<HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>, Report>,
+ > + Send;
+
+ /// Create a notification record in the database.
+ ///
+ /// Returns `Some(notification_id)` if created, `None` if it already exists (idempotent).
+ fn create_notification<'a, T: Notification + Send + Sync>(
+ &self,
+ request: &SendNotificationRequestBuilder<'a, T>,
+ notification_id: Uuid,
+ service_name: &str,
+ recipient_ids: &[MacroUserIdStr<'a>],
+ ) -> impl std::future::Future<Output = Result<Option<Uuid>, Report>> + Send;
+
+ /// Update the sent status for recipients who received the notification.
+ fn update_sent_status<'a>(
+ &self,
+ notification_id: Uuid,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> impl std::future::Future<Output = Result<(), Report>> + Send;
+}
+
+impl NotificationDbOps for PgPool {
+ async fn get_muted_users<'a>(
+ &self,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {
+ let ids: Vec<String> = user_ids.iter().map(|id| id.to_string()).collect();
+
+ let muted_users: Vec<String> = sqlx::query_scalar(
+ r#"
+ SELECT user_id FROM user_mute_notification
+ WHERE user_id = ANY($1)
+ "#,
+ )
+ .bind(&ids)
+ .fetch_all(self)
+ .await?;
+
+ let result = muted_users
+ .into_iter()
+ .filter_map(|id| {
+ MacroUserIdStr::parse_from_str(&id)
+ .map(CowLike::into_owned)
+ .ok()
+ })
+ .map(|id| id.into_owned())
+ .collect();
+
+ Ok(result)
+ }
+
+ async fn get_unsubscribed_users<'a>(
+ &self,
+ item_id: &str,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {
+ let ids: Vec<String> = user_ids.iter().map(|id| id.to_string()).collect();
+
+ let unsubscribed: Vec<String> = sqlx::query_scalar(
+ r#"
+ SELECT user_id FROM user_notification_item_unsubscribe
+ WHERE item_id = $1 AND user_id = ANY($2)
+ "#,
+ )
+ .bind(item_id)
+ .bind(&ids)
+ .fetch_all(self)
+ .await?;
+
+ let result = unsubscribed
+ .into_iter()
+ .filter_map(|id| {
+ MacroUserIdStr::parse_from_str(&id)
+ .map(CowLike::into_owned)
+ .ok()
+ })
+ .map(|id| id.into_owned())
+ .collect();
+
+ Ok(result)
+ }
+
+ async fn get_device_endpoints<'a>(
+ &self,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>, Report> {
+ let ids: Vec<String> = user_ids.iter().map(|id| id.to_string()).collect();
+
+ let rows: Vec<(String, String, String)> = sqlx::query_as(
+ r#"
+ SELECT user_id, device_endpoint, device_type
+ FROM user_device_registration
+ WHERE user_id = ANY($1)
+ "#,
+ )
+ .bind(&ids)
+ .fetch_all(self)
+ .await?;
+
+ let mut result: HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>> = HashMap::new();
+
+ for (user_id, endpoint, device_type) in rows {
+ let Ok(parsed_id) = MacroUserIdStr::parse_from_str(&user_id) else {
+ continue;
+ };
+
+ let device = match device_type.as_str() {
+ "ios" => DeviceEndpoint::Ios(endpoint),
+ "android" => DeviceEndpoint::Android(endpoint),
+ _ => continue,
+ };
+
+ result
+ .entry(parsed_id.into_owned())
+ .or_default()
+ .push(device);
+ }
+
+ Ok(result)
+ }
+
+ async fn create_notification<'a, T: Notification + Send + Sync>(
+ &self,
+ request: &SendNotificationRequestBuilder<'a, T>,
+ notification_id: Uuid,
+ service_name: &str,
+ recipient_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<Option<Uuid>, Report> {
+ let entity_type: &str = request.notification_entity.entity_type.into();
+ let metadata = serde_json::to_value(&request.notification).ok();
+
+ let mut tx = self.begin().await?;
+
+ // Insert notification
+ sqlx::query(
+ r#"
+ INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ ON CONFLICT (id) DO NOTHING
+ "#,
+ )
+ .bind(notification_id)
+ .bind(T::TYPE_NAME)
+ .bind(request.notification_entity.entity_id.as_ref())
+ .bind(entity_type)
+ .bind(service_name)
+ .bind(&metadata)
+ .bind(request.sender_id.as_ref().map(|id| id.to_string()))
+ .execute(&mut *tx)
+ .await?;
+
+ // Insert user notifications
+ let user_ids: Vec<String> = recipient_ids.iter().map(|id| id.to_string()).collect();
+
+ sqlx::query(
+ r#"
+ INSERT INTO user_notification (notification_id, user_id)
+ SELECT $1, user_id
+ FROM UNNEST($2::text[]) as user_id
+ "#,
+ )
+ .bind(notification_id)
+ .bind(&user_ids)
+ .execute(&mut *tx)
+ .await?;
+
+ tx.commit().await?;
+
+ Ok(Some(notification_id))
+ }
+
+ async fn update_sent_status<'a>(
+ &self,
+ notification_id: Uuid,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<(), Report> {
+ let ids: Vec<String> = user_ids.iter().map(|id| id.to_string()).collect();
+
+ sqlx::query(
+ r#"
+ UPDATE user_notification
+ SET sent = true
+ WHERE notification_id = $1 AND user_id = ANY($2)
+ "#,
+ )
+ .bind(notification_id)
+ .bind(&ids)
+ .execute(self)
+ .await?;
+
+ Ok(())
+ }
+}
+
+impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificationRepository<D> {
+ async fn get_muted_users<'a>(
+ &self,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {
+ self.db.get_muted_users(user_ids).await
+ }
+
+ async fn get_unsubscribed_users<'a>(
+ &self,
+ item_id: &str,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {
+ self.db.get_unsubscribed_users(item_id, user_ids).await
+ }
+
+ async fn get_device_endpoints<'a>(
+ &self,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>, Report> {
+ self.db.get_device_endpoints(user_ids).await
+ }
+
+ async fn create_notification<'a, T: Notification + Send + Sync>(
+ &self,
+ request: &SendNotificationRequestBuilder<'a, T>,
+ notification_id: Uuid,
+ service_name: &str,
+ recipient_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<Option<Uuid>, Report> {
+ self.db
+ .create_notification(request, notification_id, service_name, recipient_ids)
+ .await
+ }
+
+ async fn update_sent_status<'a>(
+ &self,
+ notification_id: Uuid,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<(), Report> {
+ self.db.update_sent_status(notification_id, user_ids).await
+ }
+}
diff --git a/rust/cloud-storage/notification/src/outbound/websocket.rs b/rust/cloud-storage/notification/src/outbound/websocket.rs
new file mode 100644
index 0000000000..8541200e16
--- /dev/null
+++ b/rust/cloud-storage/notification/src/outbound/websocket.rs
@@ -0,0 +1,163 @@
+//! WebSocket gateway adapter for real-time notification delivery.
+
+use std::collections::HashSet;
+
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::{Entity, EntityType};
+use rootcause::Report;
+use serde::Serialize;
+
+use crate::domain::ports::WebSocketSender;
+
+/// WebSocket gateway implementation of the WebSocket sender port.
+///
+/// This adapter sends notifications to users via WebSocket connections
+/// through the connection gateway service.
+pub struct WebSocketGatewayAdapter<W> {
+ gateway: W,
+}
+
+impl<W> WebSocketGatewayAdapter<W> {
+ /// Create a new WebSocket gateway adapter.
+ pub fn new(gateway: W) -> Self {
+ Self { gateway }
+ }
+}
+
+/// Trait for WebSocket gateway operations.
+///
+/// This allows the adapter to work with different WebSocket gateway implementations.
+pub trait WebSocketGatewayOps {
+ /// Send a notification payload to users via WebSocket.
+ ///
+ /// Returns the set of user IDs that were successfully delivered to
+ /// (i.e., users who had an active WebSocket connection).
+ fn send_to_users<'a, T: Serialize + Send + Sync>(
+ &self,
+ message_type: &str,
+ user_ids: &[MacroUserIdStr<'a>],
+ payload: &T,
+ ) -> impl std::future::Future<Output = Result<HashSet<MacroUserIdStr<'static>>, Report>> + Send;
+}
+
+/// Receipt from the connection gateway indicating delivery status.
+#[derive(serde::Deserialize, Debug)]
+pub struct MessageReceipt {
+ /// The user id of the user who received the message.
+ pub user_id: String,
+ /// The number of times the message was delivered to the user.
+ pub delivery_count: u64,
+}
+
+/// Response from the connection gateway batch send endpoint.
+#[derive(serde::Deserialize, Debug)]
+struct GatewayResponse {
+ receipts: Vec<MessageReceipt>,
+}
+
+/// Connection gateway client for sending WebSocket messages.
+#[derive(Clone, Debug)]
+pub struct ConnectionGatewayClient {
+ connection_gateway_url: String,
+ client: reqwest::Client,
+}
+
+impl ConnectionGatewayClient {
+ /// Create a new connection gateway client.
+ pub fn new(internal_auth_key: String, connection_gateway_url: String) -> Self {
+ let mut headers = reqwest::header::HeaderMap::new();
+ headers.insert(
+ "x-internal-auth-key",
+ internal_auth_key.parse().expect("valid header value"),
+ );
+
+ let client = reqwest::Client::builder()
+ .default_headers(headers)
+ .build()
+ .expect("client build should succeed");
+
+ Self {
+ connection_gateway_url,
+ client,
+ }
+ }
+}
+
+/// Request body for batch sending messages.
+#[derive(serde::Serialize)]
+struct BatchSendMessageBody<'a> {
+ message_type: &'a str,
+ message: serde_json::Value,
+ entities: Vec<Entity<'a>>,
+}
+
+impl WebSocketGatewayOps for ConnectionGatewayClient {
+ async fn send_to_users<'a, T: Serialize + Send + Sync>(
+ &self,
+ message_type: &str,
+ 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 body = BatchSendMessageBody {
+ message_type,
+ message: serde_json::to_value(payload)?,
+ entities,
+ };
+
+ let res = self
+ .client
+ .post(format!(
+ "{}/message/batch_send",
+ self.connection_gateway_url
+ ))
+ .json(&body)
+ .send()
+ .await?;
+
+ let json = res.json().await?;
+ let response: GatewayResponse = serde_json::from_value(json)?;
+
+ // Convert receipts to user IDs that were delivered
+ let delivered = response
+ .receipts
+ .into_iter()
+ .filter(|r| r.delivery_count > 0)
+ .filter_map(|r| {
+ MacroUserIdStr::parse_from_str(&r.user_id)
+ .map(CowLike::into_owned)
+ .ok()
+ })
+ .collect();
+
+ Ok(delivered)
+ }
+}
+
+impl<W: WebSocketGatewayOps + Send + Sync> WebSocketSender for WebSocketGatewayAdapter<W> {
+ async fn send_notifications<'a, T: Serialize + Send + Sync>(
+ &self,
+ message_type: &str,
+ notifications: Vec<(MacroUserIdStr<'a>, &T)>,
+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {
+ // Get the first notification to serialize, return empty if none
+ let Some((_, notification)) = notifications.first() else {
+ return Ok(HashSet::new());
+ };
+
+ let user_ids: Vec<_> = notifications.iter().map(|(id, _)| id.clone()).collect();
+
+ self.gateway
+ .send_to_users(message_type, &user_ids, *notification)
+ .await
+ }
+}
diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.toml
index 24489e9dc5..4428adc67b 100644
--- a/rust/cloud-storage/soup/Cargo.toml
+++ b/rust/cloud-storage/soup/Cargo.toml
@@ -51,17 +51,17 @@ models_pagination = { path = "../models_pagination" }
models_properties = { path = "../models_properties" }
models_soup = { path = "../models_soup" }
non_empty = { path = "../non_empty" }
+properties_db_client = { path = "../properties_db_client/" }
recursion = { workspace = true }
schemars = { workspace = true, optional = true }
serde = { workspace = true }
sqlx = { workspace = true }
+system_properties = { path = "../system_properties" }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["macros"], optional = true }
tracing = { workspace = true }
utoipa = { workspace = true, optional = true }
uuid = { workspace = true }
-system_properties = { path = "../system_properties" }
-properties_db_client = { path = "../properties_db_client/" }
[dev-dependencies]
cool_asserts = "2"
@@ -73,7 +73,7 @@ item_filters = { path = "../item_filters", features = ["mock"] }
macro_db_migrator = { path = "../macro_db_migrator" }
mockall = { workspace = true }
ordered-float = { workspace = true }
-rootcause = "0.11"
+rootcause = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
tower = { workspace = true }