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.

feat(notif): email notification decision tree (#1451)

Sean Ayec33982370683
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 872f2004c8..959642d12b 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -270,6 +270,20 @@ version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34ac096ce696dc2fcabef30516bb13c0a68a11d30131d3df6f04711467681b04"
+[[package]]
+name = "aquamarine"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f50776554130342de4836ba542aa85a4ddb361690d7e8df13774d7284c3d5c2"
+dependencies = [
+ "include_dir",
+ "itertools 0.10.5",
+ "proc-macro-error2",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.98",
+]
+
[[package]]
name = "arbitrary"
version = "1.4.1"
@@ -4499,6 +4513,25 @@ version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0263a3d970d5c054ed9312c0057b4f3bde9c0b33836d3637361d4a9e6e7a408"
+[[package]]
+name = "include_dir"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "923d117408f1e49d914f1a379a309cffe4f18c05cf4e3d12e613a15fc81bd0dd"
+dependencies = [
+ "include_dir_macros",
+]
+
+[[package]]
+name = "include_dir_macros"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7cab85a7ed0bd5f0e76d93846e0147172bed2e2d3f859bcc33a8d9699cad1a75"
+dependencies = [
+ "proc-macro2",
+ "quote",
+]
+
[[package]]
name = "indent_write"
version = "2.2.0"
@@ -4615,6 +4648,15 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "itertools"
+version = "0.10.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
+dependencies = [
+ "either",
+]
+
[[package]]
name = "itertools"
version = "0.12.1"
@@ -5877,6 +5919,7 @@ checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8"
name = "notification"
version = "0.1.0"
dependencies = [
+ "aquamarine",
"aws-sdk-sesv2",
"aws-sdk-sns",
"aws-sdk-sqs",
@@ -6679,6 +6722,27 @@ dependencies = [
"syn 2.0.98",
]
+[[package]]
+name = "proc-macro-error-attr2"
+version = "2.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+]
+
+[[package]]
+name = "proc-macro-error2"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802"
+dependencies = [
+ "proc-macro-error-attr2",
+ "proc-macro2",
+ "quote",
+]
+
[[package]]
name = "proc-macro2"
version = "1.0.103"
diff --git a/rust/cloud-storage/notification/Cargo.toml b/rust/cloud-storage/notification/Cargo.toml
index 7709ff295b..02a79658d5 100644
--- a/rust/cloud-storage/notification/Cargo.toml
+++ b/rust/cloud-storage/notification/Cargo.toml
@@ -13,9 +13,11 @@ axum = [
"models_pagination/axum",
"schema",
]
+docs = ["dep:aquamarine"]
schema = ["dep:utoipa"]
[dependencies]
+aquamarine = { version = "0.6", optional = true }
aws-sdk-sesv2 = { workspace = true }
aws-sdk-sns = { workspace = true }
aws-sdk-sqs = { workspace = true }
diff --git a/rust/cloud-storage/notification/src/domain/models.rs b/rust/cloud-storage/notification/src/domain/models.rs
index 5093974486..609f206cec 100644
--- a/rust/cloud-storage/notification/src/domain/models.rs
+++ b/rust/cloud-storage/notification/src/domain/models.rs
@@ -5,6 +5,8 @@ use serde::{Deserialize, Serialize, de::DeserializeOwned};
pub(crate) mod android;
pub mod apple;
+
+pub mod email_notification_digest;
pub mod mobile;
pub(crate) mod queue_message;
pub mod rate_limit;
@@ -35,7 +37,7 @@ pub struct NotificationIdAndCollapseKey {
///
/// The metadata field is generic so callers can deserialize it into
/// whatever type they need without this crate depending on the caller's models.
-#[derive(Debug, Clone, Serialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserNotificationRow<T> {
/// The user who owns this notification.
pub owner_id: MacroUserIdStr<'static>,
@@ -66,6 +68,44 @@ pub struct UserNotificationRow<T> {
pub sender_id: Option<MacroUserIdStr<'static>>,
}
+impl<T> UserNotificationRow<T> {
+ /// map the inner T to some U
+ pub fn map<F, U>(self, f: F) -> UserNotificationRow<U>
+ where
+ F: FnOnce(T) -> U,
+ {
+ let UserNotificationRow {
+ owner_id,
+ notification_id,
+ notification_event_type,
+ entity,
+ sent,
+ done,
+ created_at,
+ viewed_at,
+ updated_at,
+ deleted_at,
+ notification_metadata,
+ sender_id,
+ } = self;
+
+ UserNotificationRow {
+ owner_id,
+ notification_id,
+ notification_event_type,
+ entity,
+ sent,
+ done,
+ created_at,
+ viewed_at,
+ updated_at,
+ deleted_at,
+ notification_metadata: f(notification_metadata),
+ sender_id,
+ }
+ }
+}
+
/// A notification metadata value tagged with the notification event type.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaggedContent<T> {
@@ -81,6 +121,15 @@ impl<T: Notification> TaggedContent<T> {
content: val,
}
}
+
+ /// convert the inner to a type erased json value
+ pub fn serialize(self) -> TaggedContent<serde_json::Value> {
+ let TaggedContent { tag, content } = self;
+ TaggedContent {
+ tag,
+ content: serde_json::to_value(&content).expect("serde json serialize cant fail"),
+ }
+ }
}
impl<T> UserNotificationRow<T> {
diff --git a/rust/cloud-storage/notification/src/domain/models/email_notification_digest.rs b/rust/cloud-storage/notification/src/domain/models/email_notification_digest.rs
new file mode 100644
index 0000000000..7d5b996ba3
--- /dev/null
+++ b/rust/cloud-storage/notification/src/domain/models/email_notification_digest.rs
@@ -0,0 +1,277 @@
+//! Email notification digest decision logic.
+//!
+//! This module implements a state machine for determining whether to send
+//! email notifications, following the decision flow:
+//! 1. Check if notification type is blocked (e.g., new_email notifications)
+//! 2. Check if user has a Macro account
+//! 3. If no account: decide between single send (for invites) or batch send
+//! 4. If account exists: check push notification settings
+
+use crate::domain::models::{
+ Notification, TaggedContent, UserNotificationRow,
+ email_notification_digest::ports::{
+ LastOnlineChecker, PushNotificationChecker, UserExistenceChecker,
+ },
+};
+use either::Either;
+use macro_user_id::cowlike::CowLike;
+use rootcause::Report;
+use serde::{Deserialize, Serialize};
+use std::{collections::HashSet, time::Duration};
+
+/// Port traits for external dependencies (user existence, push notification checks).
+pub mod ports;
+
+#[cfg(test)]
+mod test;
+
+/// Send as part of a batched digest email (collected over 5-30 minutes).
+pub struct BatchSend<T>(T);
+
+/// Send immediately as a single notification email.
+pub struct SingleSend<T>(T);
+
+/// Do not send an email for this notification.
+pub struct DontSend(());
+
+struct NotificationSet(HashSet<&'static str>);
+
+/// trait used to create a set of notifications.
+/// implemented by [EmailBlockList] and [ExplicitInviteAllowList]
+pub trait NotificationSetBuilder {
+ /// create a new instance of self, blocking notifications of a specific value
+ /// from being sent via email digest
+ fn new<T: Notification>() -> Self;
+
+ /// append another value to the block list
+ fn append<T: Notification>(self) -> Self;
+}
+
+impl NotificationSetBuilder for NotificationSet {
+ /// create a new instance of self, blocking notifications of a specific value
+ /// from being sent via email digest
+ fn new<T: Notification>() -> Self {
+ Self([T::TYPE_NAME].into())
+ }
+
+ /// append another value to the block list
+ fn append<T: Notification>(mut self) -> Self {
+ self.0.insert(T::TYPE_NAME);
+ self
+ }
+}
+
+impl NotificationSet {
+ fn is_member<T: Notification>(&self) -> bool {
+ self.0.contains(&T::TYPE_NAME)
+ }
+}
+
+#[cfg_attr(feature = "docs", aquamarine::aquamarine)]
+/// A set of notification types that should never trigger email notifications.
+///
+/// For example, `new_email` notifications are blocked since users already
+/// received the email in their inbox.
+///
+/// # Decision Flow
+///
+/// ```mermaid
+/// flowchart TD
+/// Start["Send email for notification?"]
+/// IsNewEmail{"Is new_email notification?"}
+/// HasAccount{"Has Macro account?"}
+/// HasPush{"Push notifications on?"}
+/// IsOnline{"Online recently?"}
+/// GotPush{"Got push notification?"}
+/// IsInvite{"Explicit invite?"}
+///
+/// DontSend(["DON'T SEND"]):::red
+/// Send(["SEND"]):::green
+/// BatchSend(["BATCH SEND"]):::blue
+///
+/// Start --> IsNewEmail
+/// IsNewEmail -->|NO| HasAccount
+/// IsNewEmail -->|YES| DontSend
+///
+/// HasAccount -->|YES| HasPush
+/// HasAccount -->|NO| IsInvite
+///
+/// HasPush -->|NO| IsOnline
+/// HasPush -->|YES| GotPush
+///
+/// IsOnline -->|YES| DontSend
+/// IsOnline -->|NO| BatchSend
+///
+/// GotPush -->|YES| DontSend
+/// GotPush -->|NO| BatchSend
+///
+/// IsInvite -->|YES| Send
+/// IsInvite -->|NO| BatchSend
+///
+/// classDef red fill:#8B0000,stroke:#FF6B6B,color:#fff
+/// classDef green fill:#006400,stroke:#90EE90,color:#fff
+/// classDef blue fill:#00008B,stroke:#6495ED,color:#fff
+/// ```
+pub struct EmailBlockList(NotificationSet);
+
+impl NotificationSetBuilder for EmailBlockList {
+ fn new<T: Notification>() -> Self {
+ Self(NotificationSet::new::<T>())
+ }
+
+ fn append<T: Notification>(self) -> Self {
+ Self(NotificationSet::append::<T>(self.0))
+ }
+}
+
+impl EmailBlockList {
+ /// Check if a notification type is allowed to trigger an email.
+ ///
+ /// Returns [`Decision::DontSend`] if the notification type is blocked,
+ /// or [`Decision::Next`] with an [`AllowedNotification`] to continue the flow.
+ pub fn notification_is_allowed<T: Notification>(
+ &self,
+ notif: UserNotificationRow<T>,
+ ) -> Either<AllowedNotification<T>, DontSend> {
+ match self.0.is_member::<T>() {
+ true => Either::Right(DontSend(())),
+ false => Either::Left(AllowedNotification { inner: notif }),
+ }
+ }
+}
+
+/// represents a notification that is allowed to be sent as part of a [EmailSendDecision]
+pub struct AllowedNotification<T> {
+ inner: UserNotificationRow<T>,
+}
+
+/// State indicating the notification recipient has a Macro account.
+///
+/// Next step: check if push notifications are enabled.
+pub struct AccountExists<T> {
+ prev: AllowedNotification<T>,
+}
+
+/// State indicating the notification recipient does not have a Macro account.
+///
+/// Next step: decide between single send (for invites) or batch send.
+pub struct AccountDoesNotExist<T> {
+ prev: AllowedNotification<T>,
+}
+
+impl<T: Notification> AllowedNotification<T> {
+ /// Check if the notification recipient has a Macro account.
+ ///
+ /// Returns [`AccountExists`] if the user has an account (check push settings next),
+ /// or [`AccountDoesNotExist`] if they don't (decide batch vs single send).
+ pub async fn check_user_existence(
+ self,
+ checker: &impl UserExistenceChecker,
+ ) -> Result<Either<AccountExists<T>, AccountDoesNotExist<T>>, Report> {
+ let owner = self.inner.owner_id.copied();
+ match checker.user_exists(owner).await {
+ Ok(true) => Ok(Either::Left(AccountExists { prev: self })),
+ Ok(false) => Ok(Either::Right(AccountDoesNotExist { prev: self })),
+ Err(e) => Err(e),
+ }
+ }
+}
+
+/// A set of notification types that should be sent immediately (not batched).
+///
+/// These are typically invite notifications where timely delivery matters
+/// more than batching for digest efficiency.
+pub struct ExplicitInviteAllowList(NotificationSet);
+
+impl NotificationSetBuilder for ExplicitInviteAllowList {
+ fn new<T: Notification>() -> Self {
+ Self(NotificationSet::new::<T>())
+ }
+
+ fn append<T: Notification>(self) -> Self {
+ Self(NotificationSet::append::<T>(self.0))
+ }
+}
+
+/// type alias for the data returned from [AccountDoesNotExist::batch_or_single_send]
+pub type EmailSendDecision<T> = Either<SingleSend<T>, BatchSend<T>>;
+impl<T: Notification> AccountDoesNotExist<T> {
+ /// Decide whether to send immediately or batch for digest.
+ ///
+ /// Returns [`EmailSendDecision::SingleSend`] for explicit invite notifications,
+ /// or [`EmailSendDecision::BatchSend`] for all other notification types.
+ pub fn batch_or_single_send(
+ self,
+ invite_list: &ExplicitInviteAllowList,
+ ) -> EmailSendDecision<UserNotificationRow<T>> {
+ match invite_list.0.is_member::<T>() {
+ true => EmailSendDecision::Left(SingleSend(self.prev.inner)),
+ false => EmailSendDecision::Right(BatchSend(self.prev.inner)),
+ }
+ }
+}
+
+/// State indicating the user has push notifications enabled.
+///
+/// If push was delivered successfully, don't send email. Otherwise, batch send.
+#[derive(Serialize, Deserialize)]
+pub struct PushNotificationsEnabled {
+ /// the inner value which has become adjacently tagged
+ /// We lose the compiler typing here because we need to store this value
+ /// to be retrieved during the SNS event handling.
+ /// The deserialization cannot handle some specific T it needs to handle the general case
+ /// of some json value
+ inner: UserNotificationRow<TaggedContent<serde_json::Value>>,
+}
+
+/// State indicating the user has push notifications disabled.
+///
+/// Since they can't receive push, check if they're online before deciding.
+pub struct PushNotificationsDisabled<T> {
+ prev: AccountExists<T>,
+}
+
+impl<T: Notification> AccountExists<T> {
+ /// Check if the user has push notifications enabled.
+ ///
+ /// Returns [`PushNotificationsEnabled`] to check if push was delivered,
+ /// or [`PushNotificationsDisabled`] to check online status instead.
+ pub async fn push_notifications_enabled(
+ self,
+ checker: &impl PushNotificationChecker,
+ ) -> Result<Either<PushNotificationsEnabled, PushNotificationsDisabled<T>>, Report> {
+ match checker
+ .push_notification_enabled(self.prev.inner.owner_id.copied())
+ .await
+ {
+ Ok(true) => Ok(Either::Left(PushNotificationsEnabled {
+ inner: self
+ .prev
+ .inner
+ .map(TaggedContent::new)
+ .map(TaggedContent::serialize),
+ })),
+ Ok(false) => Ok(Either::Right(PushNotificationsDisabled { prev: self })),
+ Err(e) => Err(e),
+ }
+ }
+}
+
+impl<T: Notification> PushNotificationsDisabled<T> {
+ /// check if the user has been logged in more recently than the threshold for notifications
+ /// If the user has been online within the time window then we do not send email notifications.
+ /// If the user has not been online within the threshold then we queue the notification for batch delivery
+ pub async fn check_last_online_time(
+ self,
+ checker: &impl LastOnlineChecker,
+ threshold: Duration,
+ ) -> Result<Either<BatchSend<UserNotificationRow<T>>, DontSend>, Report> {
+ let last_online = checker
+ .last_online_checker(self.prev.prev.inner.owner_id.copied())
+ .await?;
+ Ok(match last_online.cmp(&threshold) {
+ std::cmp::Ordering::Less | std::cmp::Ordering::Equal => Either::Right(DontSend(())),
+ std::cmp::Ordering::Greater => Either::Left(BatchSend(self.prev.prev.inner)),
+ })
+ }
+}
diff --git a/rust/cloud-storage/notification/src/domain/models/email_notification_digest/ports.rs b/rust/cloud-storage/notification/src/domain/models/email_notification_digest/ports.rs
new file mode 100644
index 0000000000..e930a2e6f3
--- /dev/null
+++ b/rust/cloud-storage/notification/src/domain/models/email_notification_digest/ports.rs
@@ -0,0 +1,31 @@
+use std::time::Duration;
+
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+
+/// trait for checking whether or not a user exists
+pub trait UserExistenceChecker: Send + Sync + 'static {
+ /// does the user exist in the database?
+ fn user_exists<'a>(
+ &self,
+ id: MacroUserIdStr<'a>,
+ ) -> impl Future<Output = Result<bool, Report>> + Send;
+}
+
+/// trait for checking whether or not a user has push notifications enabled
+pub trait PushNotificationChecker: Send + Sync + 'static {
+ /// does the user have push notifications enabled?
+ fn push_notification_enabled<'a>(
+ &self,
+ user: MacroUserIdStr<'a>,
+ ) -> impl Future<Output = Result<bool, Report>> + Send;
+}
+
+/// trait for checking the duration since the last known online time of the user
+pub trait LastOnlineChecker: Send + Sync + 'static {
+ /// return the duration since the last known online time of the user
+ fn last_online_checker<'a>(
+ &self,
+ user: MacroUserIdStr<'a>,
+ ) -> impl Future<Output = Result<Duration, Report>> + Send;
+}
diff --git a/rust/cloud-storage/notification/src/domain/models/email_notification_digest/test.rs b/rust/cloud-storage/notification/src/domain/models/email_notification_digest/test.rs
new file mode 100644
index 0000000000..b3bf36ed19
--- /dev/null
+++ b/rust/cloud-storage/notification/src/domain/models/email_notification_digest/test.rs
@@ -0,0 +1,1013 @@
+//! Tests for the email notification digest state machine.
+
+use super::*;
+use crate::domain::models::{Notification, RateLimitConfig, RateLimitKey, UserNotificationRow};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::EntityType;
+use rootcause::Report;
+use serde::{Deserialize, Serialize};
+use std::future::Future;
+use std::time::Duration;
+
+// ============================================================================
+// Test Notification Types
+// ============================================================================
+
+/// A general test notification that is not blocked and not an invite.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+struct TestNotification {
+ message: String,
+}
+
+impl Notification for TestNotification {
+ const TYPE_NAME: &'static str = "test_notification";
+
+ fn rate_limit_config() -> Option<RateLimitConfig> {
+ None
+ }
+
+ fn rate_limit_key(&self) -> Option<RateLimitKey> {
+ None
+ }
+}
+
+/// A notification type that should be blocked from email delivery.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+struct BlockedNotification;
+
+impl Notification for BlockedNotification {
+ const TYPE_NAME: &'static str = "blocked_notification";
+
+ fn rate_limit_config() -> Option<RateLimitConfig> {
+ None
+ }
+
+ fn rate_limit_key(&self) -> Option<RateLimitKey> {
+ None
+ }
+}
+
+/// An invite notification that should be sent immediately (single send).
+#[derive(Debug, Clone, Serialize, Deserialize)]
+struct InviteNotification {
+ workspace_name: String,
+}
+
+impl Notification for InviteNotification {
+ const TYPE_NAME: &'static str = "invite_notification";
+
+ fn rate_limit_config() -> Option<RateLimitConfig> {
+ None
+ }
+
+ fn rate_limit_key(&self) -> Option<RateLimitKey> {
+ None
+ }
+}
+
+/// A workspace invite notification for testing multiple invite types.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+struct WorkspaceInviteNotification;
+
+impl Notification for WorkspaceInviteNotification {
+ const TYPE_NAME: &'static str = "workspace_invite_notification";
+
+ fn rate_limit_config() -> Option<RateLimitConfig> {
+ None
+ }
+
+ fn rate_limit_key(&self) -> Option<RateLimitKey> {
+ None
+ }
+}
+
+// ============================================================================
+// Mock Implementations
+// ============================================================================
+
+/// Mock user existence checker with configurable behavior.
+struct MockUserExistenceChecker {
+ user_exists: Option<bool>,
+ error: Option<String>,
+}
+
+impl MockUserExistenceChecker {
+ fn with_user_exists() -> Self {
+ Self {
+ user_exists: Some(true),
+ error: None,
+ }
+ }
+
+ fn with_user_not_exists() -> Self {
+ Self {
+ user_exists: Some(false),
+ error: None,
+ }
+ }
+
+ fn with_error(msg: &str) -> Self {
+ Self {
+ user_exists: None,
+ error: Some(msg.to_string()),
+ }
+ }
+}
+
+impl UserExistenceChecker for MockUserExistenceChecker {
+ fn user_exists<'a>(
+ &self,
+ _id: MacroUserIdStr<'a>,
+ ) -> impl Future<Output = Result<bool, Report>> + Send {
+ let error = self.error.clone();
+ let user_exists = self.user_exists;
+ async move {
+ match (error, user_exists) {
+ (Some(err), _) => rootcause::bail!("{}", err),
+ (None, Some(exists)) => Ok(exists),
+ (None, None) => panic!("MockUserExistenceChecker not configured"),
+ }
+ }
+ }
+}
+
+/// Mock push notification checker with configurable behavior.
+struct MockPushNotificationChecker {
+ push_enabled: Option<bool>,
+ error: Option<String>,
+}
+
+impl MockPushNotificationChecker {
+ fn with_push_enabled() -> Self {
+ Self {
+ push_enabled: Some(true),
+ error: None,
+ }
+ }
+
+ fn with_push_disabled() -> Self {
+ Self {
+ push_enabled: Some(false),
+ error: None,
+ }
+ }
+
+ fn with_error(msg: &str) -> Self {
+ Self {
+ push_enabled: None,
+ error: Some(msg.to_string()),
+ }
+ }
+}
+
+impl PushNotificationChecker for MockPushNotificationChecker {
+ fn push_notification_enabled<'a>(
+ &self,
+ _user: MacroUserIdStr<'a>,
+ ) -> impl Future<Output = Result<bool, Report>> + Send {
+ let error = self.error.clone();
+ let push_enabled = self.push_enabled;
+ async move {
+ match (error, push_enabled) {
+ (Some(err), _) => rootcause::bail!("{}", err),
+ (None, Some(enabled)) => Ok(enabled),
+ (None, None) => panic!("MockPushNotificationChecker not configured"),
+ }
+ }
+ }
+}
+
+/// Mock last online checker with configurable behavior.
+struct MockLastOnlineChecker {
+ last_online: Option<Duration>,
+ error: Option<String>,
+}
+
+impl MockLastOnlineChecker {
+ fn with_last_online(duration: Duration) -> Self {
+ Self {
+ last_online: Some(duration),
+ error: None,
+ }
+ }
+
+ fn with_error(msg: &str) -> Self {
+ Self {
+ last_online: None,
+ error: Some(msg.to_string()),
+ }
+ }
+}
+
+impl LastOnlineChecker for MockLastOnlineChecker {
+ fn last_online_checker<'a>(
+ &self,
+ _user: MacroUserIdStr<'a>,
+ ) -> impl Future<Output = Result<Duration, Report>> + Send {
+ let error = self.error.clone();
+ let last_online = self.last_online;
+ async move {
+ match (error, last_online) {
+ (Some(err), _) => rootcause::bail!("{}", err),
+ (None, Some(duration)) => Ok(duration),
+ (None, None) => panic!("MockLastOnlineChecker not configured"),
+ }
+ }
+ }
+}
+
+// ============================================================================
+// Test Helpers
+// ============================================================================
+
+fn test_user_id() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+fn create_test_notification_row<T>(metadata: T) -> UserNotificationRow<T> {
+ UserNotificationRow {
+ owner_id: test_user_id(),
+ notification_id: uuid::Uuid::now_v7(),
+ notification_event_type: "test".to_string(),
+ entity: EntityType::Document.with_entity_str("doc_123"),
+ sent: false,
+ done: false,
+ created_at: None,
+ viewed_at: None,
+ updated_at: None,
+ deleted_at: None,
+ notification_metadata: metadata,
+ sender_id: None,
+ }
+}
+
+fn create_block_list() -> EmailBlockList {
+ EmailBlockList::new::<BlockedNotification>()
+}
+
+fn create_invite_list() -> ExplicitInviteAllowList {
+ ExplicitInviteAllowList::new::<InviteNotification>().append::<WorkspaceInviteNotification>()
+}
+
+// ============================================================================
+// EmailBlockList Tests
+// ============================================================================
+
+#[test]
+fn test_notification_is_allowed_returns_dont_send_when_blocked() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(BlockedNotification);
+
+ let result = block_list.notification_is_allowed(notif);
+
+ assert!(
+ result.is_right(),
+ "Blocked notification should return DontSend"
+ );
+}
+
+#[test]
+fn test_notification_is_allowed_returns_allowed_when_not_blocked() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ let result = block_list.notification_is_allowed(notif);
+
+ assert!(
+ result.is_left(),
+ "Non-blocked notification should return AllowedNotification"
+ );
+}
+
+// ============================================================================
+// AllowedNotification::check_user_existence Tests
+// ============================================================================
+
+#[tokio::test]
+async fn test_check_user_existence_returns_account_exists() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ let checker = MockUserExistenceChecker::with_user_exists();
+ let result = allowed.check_user_existence(&checker).await.unwrap();
+
+ assert!(
+ result.is_left(),
+ "Should return AccountExists when user exists"
+ );
+}
+
+#[tokio::test]
+async fn test_check_user_existence_returns_account_does_not_exist() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ let checker = MockUserExistenceChecker::with_user_not_exists();
+ let result = allowed.check_user_existence(&checker).await.unwrap();
+
+ assert!(
+ result.is_right(),
+ "Should return AccountDoesNotExist when user does not exist"
+ );
+}
+
+#[tokio::test]
+async fn test_check_user_existence_propagates_error() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ let checker = MockUserExistenceChecker::with_error("database connection failed");
+ let result = allowed.check_user_existence(&checker).await;
+
+ match result {
+ Err(err) => assert!(
+ err.to_string().contains("database connection failed"),
+ "Error message should be preserved"
+ ),
+ Ok(_) => panic!("Should propagate error from checker"),
+ }
+}
+
+// ============================================================================
+// AccountExists::push_notifications_enabled Tests
+// ============================================================================
+
+#[tokio::test]
+async fn test_push_notifications_enabled_returns_enabled() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ let user_checker = MockUserExistenceChecker::with_user_exists();
+ let account_exists = allowed
+ .check_user_existence(&user_checker)
+ .await
+ .unwrap()
+ .left()
+ .expect("Should be AccountExists");
+
+ let push_checker = MockPushNotificationChecker::with_push_enabled();
+ let result = account_exists
+ .push_notifications_enabled(&push_checker)
+ .await
+ .unwrap();
+
+ assert!(
+ result.is_left(),
+ "Should return PushNotificationsEnabled when push is enabled"
+ );
+}
+
+#[tokio::test]
+async fn test_push_notifications_enabled_returns_disabled() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ let user_checker = MockUserExistenceChecker::with_user_exists();
+ let account_exists = allowed
+ .check_user_existence(&user_checker)
+ .await
+ .unwrap()
+ .left()
+ .expect("Should be AccountExists");
+
+ let push_checker = MockPushNotificationChecker::with_push_disabled();
+ let result = account_exists
+ .push_notifications_enabled(&push_checker)
+ .await
+ .unwrap();
+
+ assert!(
+ result.is_right(),
+ "Should return PushNotificationsDisabled when push is disabled"
+ );
+}
+
+#[tokio::test]
+async fn test_push_notifications_enabled_propagates_error() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ let user_checker = MockUserExistenceChecker::with_user_exists();
+ let account_exists = allowed
+ .check_user_existence(&user_checker)
+ .await
+ .unwrap()
+ .left()
+ .expect("Should be AccountExists");
+
+ let push_checker = MockPushNotificationChecker::with_error("push service unavailable");
+ let result = account_exists
+ .push_notifications_enabled(&push_checker)
+ .await;
+
+ match result {
+ Err(err) => assert!(
+ err.to_string().contains("push service unavailable"),
+ "Error message should be preserved"
+ ),
+ Ok(_) => panic!("Should propagate error from checker"),
+ }
+}
+
+// ============================================================================
+// PushNotificationsDisabled::check_last_online_time Tests
+// ============================================================================
+
+#[tokio::test]
+async fn test_check_last_online_time_returns_dont_send_when_recently_online() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ let user_checker = MockUserExistenceChecker::with_user_exists();
+ let account_exists = allowed
+ .check_user_existence(&user_checker)
+ .await
+ .unwrap()
+ .left()
+ .expect("Should be AccountExists");
+
+ let push_checker = MockPushNotificationChecker::with_push_disabled();
+ let push_disabled = account_exists
+ .push_notifications_enabled(&push_checker)
+ .await
+ .unwrap()
+ .right()
+ .expect("Should be PushNotificationsDisabled");
+
+ // User was online 5 minutes ago, threshold is 30 minutes
+ let online_checker = MockLastOnlineChecker::with_last_online(Duration::from_secs(5 * 60));
+ let threshold = Duration::from_secs(30 * 60);
+
+ let result = push_disabled
+ .check_last_online_time(&online_checker, threshold)
+ .await
+ .unwrap();
+
+ assert!(
+ result.is_right(),
+ "Should return DontSend when user was recently online (within threshold)"
+ );
+}
+
+#[tokio::test]
+async fn test_check_last_online_time_returns_dont_send_when_exactly_at_threshold() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ let user_checker = MockUserExistenceChecker::with_user_exists();
+ let account_exists = allowed
+ .check_user_existence(&user_checker)
+ .await
+ .unwrap()
+ .left()
+ .expect("Should be AccountExists");
+
+ let push_checker = MockPushNotificationChecker::with_push_disabled();
+ let push_disabled = account_exists
+ .push_notifications_enabled(&push_checker)
+ .await
+ .unwrap()
+ .right()
+ .expect("Should be PushNotificationsDisabled");
+
+ // User was online exactly at the threshold
+ let threshold = Duration::from_secs(30 * 60);
+ let online_checker = MockLastOnlineChecker::with_last_online(threshold);
+
+ let result = push_disabled
+ .check_last_online_time(&online_checker, threshold)
+ .await
+ .unwrap();
+
+ assert!(
+ result.is_right(),
+ "Should return DontSend when user was online exactly at threshold (boundary condition)"
+ );
+}
+
+#[tokio::test]
+async fn test_check_last_online_time_returns_batch_send_when_past_threshold() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ let user_checker = MockUserExistenceChecker::with_user_exists();
+ let account_exists = allowed
+ .check_user_existence(&user_checker)
+ .await
+ .unwrap()
+ .left()
+ .expect("Should be AccountExists");
+
+ let push_checker = MockPushNotificationChecker::with_push_disabled();
+ let push_disabled = account_exists
+ .push_notifications_enabled(&push_checker)
+ .await
+ .unwrap()
+ .right()
+ .expect("Should be PushNotificationsDisabled");
+
+ // User was online 1 hour ago, threshold is 30 minutes
+ let online_checker = MockLastOnlineChecker::with_last_online(Duration::from_secs(60 * 60));
+ let threshold = Duration::from_secs(30 * 60);
+
+ let result = push_disabled
+ .check_last_online_time(&online_checker, threshold)
+ .await
+ .unwrap();
+
+ assert!(
+ result.is_left(),
+ "Should return BatchSend when user has been offline longer than threshold"
+ );
+}
+
+#[tokio::test]
+async fn test_check_last_online_time_propagates_error() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ let user_checker = MockUserExistenceChecker::with_user_exists();
+ let account_exists = allowed
+ .check_user_existence(&user_checker)
+ .await
+ .unwrap()
+ .left()
+ .expect("Should be AccountExists");
+
+ let push_checker = MockPushNotificationChecker::with_push_disabled();
+ let push_disabled = account_exists
+ .push_notifications_enabled(&push_checker)
+ .await
+ .unwrap()
+ .right()
+ .expect("Should be PushNotificationsDisabled");
+
+ let online_checker = MockLastOnlineChecker::with_error("redis connection failed");
+ let threshold = Duration::from_secs(30 * 60);
+
+ let result = push_disabled
+ .check_last_online_time(&online_checker, threshold)
+ .await;
+
+ match result {
+ Err(err) => assert!(
+ err.to_string().contains("redis connection failed"),
+ "Error message should be preserved"
+ ),
+ Ok(_) => panic!("Should propagate error from checker"),
+ }
+}
+
+#[tokio::test]
+async fn test_check_last_online_time_edge_case_zero_threshold() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ let user_checker = MockUserExistenceChecker::with_user_exists();
+ let account_exists = allowed
+ .check_user_existence(&user_checker)
+ .await
+ .unwrap()
+ .left()
+ .expect("Should be AccountExists");
+
+ let push_checker = MockPushNotificationChecker::with_push_disabled();
+ let push_disabled = account_exists
+ .push_notifications_enabled(&push_checker)
+ .await
+ .unwrap()
+ .right()
+ .expect("Should be PushNotificationsDisabled");
+
+ // Zero threshold - any non-zero last online should trigger batch send
+ let online_checker = MockLastOnlineChecker::with_last_online(Duration::from_secs(1));
+ let threshold = Duration::ZERO;
+
+ let result = push_disabled
+ .check_last_online_time(&online_checker, threshold)
+ .await
+ .unwrap();
+
+ assert!(
+ result.is_left(),
+ "Should return BatchSend when threshold is zero and user has any offline time"
+ );
+}
+
+#[tokio::test]
+async fn test_check_last_online_time_edge_case_zero_last_online() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ let user_checker = MockUserExistenceChecker::with_user_exists();
+ let account_exists = allowed
+ .check_user_existence(&user_checker)
+ .await
+ .unwrap()
+ .left()
+ .expect("Should be AccountExists");
+
+ let push_checker = MockPushNotificationChecker::with_push_disabled();
+ let push_disabled = account_exists
+ .push_notifications_enabled(&push_checker)
+ .await
+ .unwrap()
+ .right()
+ .expect("Should be PushNotificationsDisabled");
+
+ // User was online just now (0 seconds ago)
+ let online_checker = MockLastOnlineChecker::with_last_online(Duration::ZERO);
+ let threshold = Duration::from_secs(30 * 60);
+
+ let result = push_disabled
+ .check_last_online_time(&online_checker, threshold)
+ .await
+ .unwrap();
+
+ assert!(
+ result.is_right(),
+ "Should return DontSend when user was online just now (zero duration)"
+ );
+}
+
+// ============================================================================
+// AccountDoesNotExist::batch_or_single_send Tests
+// ============================================================================
+
+#[tokio::test]
+async fn test_batch_or_single_send_returns_single_send_for_invite() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(InviteNotification {
+ workspace_name: "Test Workspace".to_string(),
+ });
+
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ let user_checker = MockUserExistenceChecker::with_user_not_exists();
+ let account_not_exists = allowed
+ .check_user_existence(&user_checker)
+ .await
+ .unwrap()
+ .right()
+ .expect("Should be AccountDoesNotExist");
+
+ let invite_list = create_invite_list();
+ let result = account_not_exists.batch_or_single_send(&invite_list);
+
+ assert!(
+ result.is_left(),
+ "Should return SingleSend for invite notifications"
+ );
+}
+
+#[tokio::test]
+async fn test_batch_or_single_send_returns_batch_send_for_non_invite() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ let user_checker = MockUserExistenceChecker::with_user_not_exists();
+ let account_not_exists = allowed
+ .check_user_existence(&user_checker)
+ .await
+ .unwrap()
+ .right()
+ .expect("Should be AccountDoesNotExist");
+
+ let invite_list = create_invite_list();
+ let result = account_not_exists.batch_or_single_send(&invite_list);
+
+ assert!(
+ result.is_right(),
+ "Should return BatchSend for non-invite notifications"
+ );
+}
+
+#[tokio::test]
+async fn test_batch_or_single_send_with_multiple_invite_types() {
+ // Test that workspace invite also gets single send
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(WorkspaceInviteNotification);
+
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ let user_checker = MockUserExistenceChecker::with_user_not_exists();
+ let account_not_exists = allowed
+ .check_user_existence(&user_checker)
+ .await
+ .unwrap()
+ .right()
+ .expect("Should be AccountDoesNotExist");
+
+ let invite_list = create_invite_list();
+ let result = account_not_exists.batch_or_single_send(&invite_list);
+
+ assert!(
+ result.is_left(),
+ "Should return SingleSend for workspace invite notifications"
+ );
+}
+
+// ============================================================================
+// Full Flow Integration Tests
+// ============================================================================
+
+#[test]
+fn test_full_flow_blocked_notification() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(BlockedNotification);
+
+ let result = block_list.notification_is_allowed(notif);
+
+ assert!(
+ result.is_right(),
+ "Full flow: blocked notification should immediately return DontSend"
+ );
+}
+
+#[tokio::test]
+async fn test_full_flow_user_exists_push_enabled() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ // Step 1: Check if allowed
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ // Step 2: Check user existence
+ let user_checker = MockUserExistenceChecker::with_user_exists();
+ let account_exists = allowed
+ .check_user_existence(&user_checker)
+ .await
+ .unwrap()
+ .left()
+ .expect("Should be AccountExists");
+
+ // Step 3: Check push notifications
+ let push_checker = MockPushNotificationChecker::with_push_enabled();
+ let result = account_exists
+ .push_notifications_enabled(&push_checker)
+ .await
+ .unwrap();
+
+ assert!(
+ result.is_left(),
+ "Full flow: user exists with push enabled should return PushNotificationsEnabled"
+ );
+}
+
+#[tokio::test]
+async fn test_full_flow_user_exists_push_disabled_recently_online() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ // Step 1: Check if allowed
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ // Step 2: Check user existence
+ let user_checker = MockUserExistenceChecker::with_user_exists();
+ let account_exists = allowed
+ .check_user_existence(&user_checker)
+ .await
+ .unwrap()
+ .left()
+ .expect("Should be AccountExists");
+
+ // Step 3: Check push notifications - disabled
+ let push_checker = MockPushNotificationChecker::with_push_disabled();
+ let push_disabled = account_exists
+ .push_notifications_enabled(&push_checker)
+ .await
+ .unwrap()
+ .right()
+ .expect("Should be PushNotificationsDisabled");
+
+ // Step 4: Check last online time - recently online
+ let online_checker = MockLastOnlineChecker::with_last_online(Duration::from_secs(5 * 60));
+ let threshold = Duration::from_secs(30 * 60);
+ let result = push_disabled
+ .check_last_online_time(&online_checker, threshold)
+ .await
+ .unwrap();
+
+ assert!(
+ result.is_right(),
+ "Full flow: user exists, push disabled, recently online should return DontSend"
+ );
+}
+
+#[tokio::test]
+async fn test_full_flow_user_exists_push_disabled_offline() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ // Step 1: Check if allowed
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ // Step 2: Check user existence
+ let user_checker = MockUserExistenceChecker::with_user_exists();
+ let account_exists = allowed
+ .check_user_existence(&user_checker)
+ .await
+ .unwrap()
+ .left()
+ .expect("Should be AccountExists");
+
+ // Step 3: Check push notifications - disabled
+ let push_checker = MockPushNotificationChecker::with_push_disabled();
+ let push_disabled = account_exists
+ .push_notifications_enabled(&push_checker)
+ .await
+ .unwrap()
+ .right()
+ .expect("Should be PushNotificationsDisabled");
+
+ // Step 4: Check last online time - offline for a while
+ let online_checker = MockLastOnlineChecker::with_last_online(Duration::from_secs(60 * 60));
+ let threshold = Duration::from_secs(30 * 60);
+ let result = push_disabled
+ .check_last_online_time(&online_checker, threshold)
+ .await
+ .unwrap();
+
+ assert!(
+ result.is_left(),
+ "Full flow: user exists, push disabled, offline should return BatchSend"
+ );
+}
+
+#[tokio::test]
+async fn test_full_flow_user_not_exists_invite() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(InviteNotification {
+ workspace_name: "Test Workspace".to_string(),
+ });
+
+ // Step 1: Check if allowed
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ // Step 2: Check user existence - does not exist
+ let user_checker = MockUserExistenceChecker::with_user_not_exists();
+ let account_not_exists = allowed
+ .check_user_existence(&user_checker)
+ .await
+ .unwrap()
+ .right()
+ .expect("Should be AccountDoesNotExist");
+
+ // Step 3: Decide batch vs single - invite should be single
+ let invite_list = create_invite_list();
+ let result = account_not_exists.batch_or_single_send(&invite_list);
+
+ assert!(
+ result.is_left(),
+ "Full flow: user does not exist, invite notification should return SingleSend"
+ );
+}
+
+#[tokio::test]
+async fn test_full_flow_user_not_exists_non_invite() {
+ let block_list = create_block_list();
+ let notif = create_test_notification_row(TestNotification {
+ message: "hello".to_string(),
+ });
+
+ // Step 1: Check if allowed
+ let allowed = block_list
+ .notification_is_allowed(notif)
+ .left()
+ .expect("Should be allowed");
+
+ // Step 2: Check user existence - does not exist
+ let user_checker = MockUserExistenceChecker::with_user_not_exists();
+ let account_not_exists = allowed
+ .check_user_existence(&user_checker)
+ .await
+ .unwrap()
+ .right()
+ .expect("Should be AccountDoesNotExist");
+
+ // Step 3: Decide batch vs single - non-invite should be batch
+ let invite_list = create_invite_list();
+ let result = account_not_exists.batch_or_single_send(&invite_list);
+
+ assert!(
+ result.is_right(),
+ "Full flow: user does not exist, non-invite notification should return BatchSend"
+ );
+}
diff --git a/rust/cloud-storage/notification/src/domain/models/queue_message.rs b/rust/cloud-storage/notification/src/domain/models/queue_message.rs
index f0802799b7..0654a3421a 100644
--- a/rust/cloud-storage/notification/src/domain/models/queue_message.rs
+++ b/rust/cloud-storage/notification/src/domain/models/queue_message.rs
@@ -65,8 +65,6 @@ pub struct ConnGatewayInnerNotif<T> {
pub(crate) sender_id: Option<MacroUserIdStr<'static>>,
}
-impl<T> ConnGatewayInnerNotif<T> where T: Notification + Clone {}
-
/// Connection gateway (WebSocket) notification payload.
#[derive(Debug, Serialize, Deserialize)]
pub struct ConnGatewayNotification<'a, T> {