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): clean up notification trait (#1673)

Sean Ayed3406caef666
diff --git a/rust/cloud-storage/model_notifications/src/metadata.rs b/rust/cloud-storage/model_notifications/src/metadata.rs
index 1d5af50970..21505a1cbb 100644
--- a/rust/cloud-storage/model_notifications/src/metadata.rs
+++ b/rust/cloud-storage/model_notifications/src/metadata.rs
@@ -4,8 +4,6 @@ use mention_utils::parse::{ParsedXmlText, XmlFormatter};
use model_entity::Entity;
use model_entity::EntityType;
use notification::domain::models::Notification;
-use notification::domain::models::RateLimitConfig;
-use notification::domain::models::RateLimitKey;
use notification::domain::models::{
NotifCollapseKey, NotificationExtIos,
apple::{APNSPushNotification, AlertDictionary, Aps, PushNotificationData},
@@ -207,96 +205,34 @@ pub struct NewEmailMetadata {
impl notification::domain::models::Notification for NewEmailMetadata {
const TYPE_NAME: &'static str = "new_email";
-
- fn rate_limit_config() -> Option<notification::domain::models::RateLimitConfig> {
- None
- }
-
- fn rate_limit_key(&self) -> Option<notification::domain::models::RateLimitKey> {
- None
- }
}
impl notification::domain::models::Notification for ChannelInviteMetadata {
const TYPE_NAME: &'static str = "channel_invite";
-
- fn rate_limit_config() -> Option<notification::domain::models::RateLimitConfig> {
- None
- }
-
- fn rate_limit_key(&self) -> Option<notification::domain::models::RateLimitKey> {
- None
- }
}
impl notification::domain::models::Notification for AiResponseMetadata {
const TYPE_NAME: &'static str = "ai_response";
- fn rate_limit_config() -> Option<RateLimitConfig> {
- None
- }
- fn rate_limit_key(&self) -> Option<RateLimitKey> {
- None
- }
}
impl notification::domain::models::Notification for ChannelMessageSendMetadata {
const TYPE_NAME: &'static str = "channel_message_send";
-
- fn rate_limit_config() -> Option<notification::domain::models::RateLimitConfig> {
- None
- }
-
- fn rate_limit_key(&self) -> Option<notification::domain::models::RateLimitKey> {
- None
- }
}
impl notification::domain::models::Notification for ChannelMentionMetadata {
const TYPE_NAME: &'static str = "channel_mention";
-
- fn rate_limit_config() -> Option<notification::domain::models::RateLimitConfig> {
- None
- }
-
- fn rate_limit_key(&self) -> Option<notification::domain::models::RateLimitKey> {
- None
- }
}
impl notification::domain::models::Notification for ChannelReplyMetadata {
const TYPE_NAME: &'static str = "channel_message_reply";
-
- fn rate_limit_config() -> Option<notification::domain::models::RateLimitConfig> {
- None
- }
-
- fn rate_limit_key(&self) -> Option<notification::domain::models::RateLimitKey> {
- None
- }
}
impl notification::domain::models::Notification for DocumentMentionMetadata {
const TYPE_NAME: &'static str = "document_mention";
-
- fn rate_limit_config() -> Option<notification::domain::models::RateLimitConfig> {
- None
- }
-
- fn rate_limit_key(&self) -> Option<notification::domain::models::RateLimitKey> {
- None
- }
}
impl notification::domain::models::Notification for InviteToTeamMetadata {
const TYPE_NAME: &'static str = "invite_to_team";
-
- fn rate_limit_config() -> Option<notification::domain::models::RateLimitConfig> {
- None
- }
-
- fn rate_limit_key(&self) -> Option<notification::domain::models::RateLimitKey> {
- None
- }
}
/// Metadata for when a user is assigned to a task
@@ -553,14 +489,6 @@ impl NotificationExtIos for DocumentMentionMetadata {
impl notification::domain::models::Notification for TaskAssignedMetadata {
const TYPE_NAME: &'static str = "task_assigned";
-
- fn rate_limit_config() -> Option<RateLimitConfig> {
- None
- }
-
- fn rate_limit_key(&self) -> Option<RateLimitKey> {
- None
- }
}
impl NotificationExtIos for TaskAssignedMetadata {
@@ -614,14 +542,6 @@ pub struct MentionedInDocumentCommentMetadata {
impl Notification for MentionedInDocumentCommentMetadata {
const TYPE_NAME: &'static str = "mentioned_in_document_comment";
-
- fn rate_limit_config() -> Option<RateLimitConfig> {
- None
- }
-
- fn rate_limit_key(&self) -> Option<RateLimitKey> {
- None
- }
}
impl NotificationExtIos for MentionedInDocumentCommentMetadata {
diff --git a/rust/cloud-storage/notification/src/domain/models.rs b/rust/cloud-storage/notification/src/domain/models.rs
index 793e19e755..6c2cac4d69 100644
--- a/rust/cloud-storage/notification/src/domain/models.rs
+++ b/rust/cloud-storage/notification/src/domain/models.rs
@@ -5,7 +5,7 @@ use std::sync::Arc;
use macro_user_id::user_id::MacroUserIdStr;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
-pub(crate) mod android;
+pub mod android;
pub mod apple;
pub mod email_notification_digest;
@@ -218,17 +218,17 @@ impl<T> SortOn<CreatedAt> for UserNotificationRow<T> {
pub trait Notification: Serialize + DeserializeOwned + Send + Sync {
/// The type name of this notification.
const TYPE_NAME: &'static str;
-
- /// 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>;
}
/// Extension trait for notifications that can be delivered via email.
pub trait NotificationExtEmail: Notification {
/// Convert this notification into email content.
- fn into_email(self) -> EmailContent;
+ fn format_email(&self) -> EmailContent;
+
+ /// The configuration for how often the notification can be triggered on a certain key.
+ fn rate_limit_config() -> RateLimitConfig;
+ /// The actual key for the rate limit bucket.
+ fn rate_limit_key(&self) -> RateLimitKey;
}
/// Extension trait for notifications that can be delivered via iOS push (APNS).
diff --git a/rust/cloud-storage/notification/src/domain/models/android.rs b/rust/cloud-storage/notification/src/domain/models/android.rs
index 5ebc3174ab..8805958467 100644
--- a/rust/cloud-storage/notification/src/domain/models/android.rs
+++ b/rust/cloud-storage/notification/src/domain/models/android.rs
@@ -1,5 +1,8 @@
+//! Android push notification models (FCM via SNS).
+
use serde::Serialize;
+/// FCM push notification message for Android devices.
#[derive(Debug, Serialize)]
pub struct FCMMessage<T> {
pub(crate) android: AndroidData,
@@ -21,13 +24,16 @@ impl<T> FCMMessage<T> {
}
}
+/// Android notification priority level.
#[derive(Debug, Serialize)]
pub enum AndroidNotifPrio {
+ /// Normal priority.
Normal,
- #[expect(dead_code)]
+ /// High priority.
High,
}
+/// Android FCM notification data.
#[derive(Debug, Serialize)]
pub struct AndroidData {
pub(crate) notification: String,
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
index c66ce33320..f85429e320 100644
--- a/rust/cloud-storage/notification/src/domain/models/email_notification_digest.rs
+++ b/rust/cloud-storage/notification/src/domain/models/email_notification_digest.rs
@@ -40,6 +40,11 @@ impl<T> BatchSend<T> {
pub(crate) fn inner(&self) -> &T {
&self.0
}
+
+ /// Consume self and return the inner value.
+ pub fn into_inner(self) -> T {
+ self.0
+ }
}
#[cfg(test)]
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
index 0f49ee29b5..f70a3ee2e1 100644
--- 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
@@ -1,7 +1,7 @@
//! Tests for the email notification digest state machine.
use super::*;
-use crate::domain::models::{Notification, RateLimitConfig, RateLimitKey, UserNotificationRow};
+use crate::domain::models::{Notification, UserNotificationRow};
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::EntityType;
use rootcause::Report;
@@ -22,14 +22,6 @@ struct TestNotification {
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.
@@ -38,14 +30,6 @@ 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).
@@ -56,14 +40,6 @@ struct InviteNotification {
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.
@@ -72,14 +48,6 @@ 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
- }
}
// ============================================================================
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 e9e13520c6..90227fd93d 100644
--- a/rust/cloud-storage/notification/src/domain/models/queue_message.rs
+++ b/rust/cloud-storage/notification/src/domain/models/queue_message.rs
@@ -1,7 +1,8 @@
//! Queue message models for notification delivery via SQS.
use crate::domain::models::{
- Notification, RateLimitConfig, RateLimitKey, SendNotificationRequest, TaggedContent,
+ Notification, NotificationExtEmail, RateLimitConfig, RateLimitKey, SendNotificationRequest,
+ TaggedContent,
apple::APNSPushNotification,
email_notification_digest::{BatchSend, PushNotificationsEnabled, StateMachineDecisionA},
mobile::MessageAttributes,
@@ -53,9 +54,63 @@ pub struct EmailContent {
#[derive(Debug, Serialize, Deserialize)]
pub struct EmailNotification<'a> {
/// The recipient email/user ID.
- pub to: MacroUserIdStr<'a>,
+ to: MacroUserIdStr<'a>,
/// The email content (subject and body).
pub content: EmailContent,
+
+ rate_limit_config: RateLimitConfig,
+
+ rate_limit_key: RateLimitKey,
+}
+
+pub(crate) struct EmailCreateBundle {
+ /// The email content (subject and body).
+ content: EmailContent,
+
+ /// the configuration for the rate limit of the email
+ rate_limit_config: RateLimitConfig,
+
+ /// the key for this particular rate limit bucket
+ rate_limit_key: RateLimitKey,
+}
+
+impl EmailCreateBundle {
+ pub(crate) fn new<T: NotificationExtEmail>(notif: &T) -> Self {
+ let rate_limit_config = T::rate_limit_config();
+ let rate_limit_key = notif.rate_limit_key();
+ let content = notif.format_email();
+ EmailCreateBundle {
+ content,
+ rate_limit_config,
+ rate_limit_key,
+ }
+ }
+
+ pub(crate) fn with_recipient<'a>(self, to: MacroUserIdStr<'a>) -> EmailNotification<'a> {
+ let EmailCreateBundle {
+ content,
+ rate_limit_config,
+ rate_limit_key,
+ } = self;
+ EmailNotification {
+ to,
+ content,
+ rate_limit_config,
+ rate_limit_key,
+ }
+ }
+}
+
+impl<'a> EmailNotification<'a> {
+ /// return the value of the recipient of the email
+ pub fn to(&'a self) -> MacroUserIdStr<'a> {
+ self.to.copied()
+ }
+
+ /// return the rate limit configuration
+ pub fn rate_limit(&self) -> (&RateLimitConfig, &RateLimitKey) {
+ (&self.rate_limit_config, &self.rate_limit_key)
+ }
}
/// the value of the inner payload inside [ConnGatewayNotification]
@@ -89,11 +144,11 @@ pub struct ConnGatewayInnerNotif<T> {
/// Connection gateway (WebSocket) notification payload.
#[derive(Debug, Serialize, Deserialize)]
-pub struct ConnGatewayNotification<'a, T> {
+pub(crate) struct ConnGatewayNotification<'a, T> {
/// The notification payload to send.
- pub notif: ConnGatewayInnerNotif<T>,
+ pub(crate) notif: ConnGatewayInnerNotif<T>,
/// The recipients to deliver to.
- pub recipients: Vec<MacroUserIdStr<'a>>,
+ pub(crate) recipients: Vec<MacroUserIdStr<'a>>,
}
impl<'a, T: Notification + Clone> ConnGatewayNotification<'a, T> {
@@ -163,7 +218,7 @@ impl<'a, T: Notification> ConnGatewayNotification<'a, T> {
/// The delivery channel variants.
#[derive(Debug, Serialize, Deserialize)]
-pub enum NotificationChannel<'a, T, U> {
+pub(crate) enum NotificationChannel<'a, T, U> {
/// Delivering to an iOS device with APNS.
Ios(Box<APNSTargets<U>>),
/// Delivering to a user's email inbox.
@@ -174,16 +229,42 @@ pub enum NotificationChannel<'a, T, U> {
/// Message published to SQS after DB persistence.
/// Contains everything needed for delivery.
+///
+/// Fields are private — construct via [`QueueMessage::new`] which requires `T: Notification`.
#[derive(Debug, Serialize, Deserialize)]
pub struct QueueMessage<'a, T, U> {
- /// 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: NotificationChannel<'a, T, U>,
+ message_type: String,
+ content: NotificationChannel<'a, T, U>,
+}
+
+impl<'a, T: Notification, U> QueueMessage<'a, T, U> {
+ /// Create a new queue message. Only valid notification types can be published.
+ ///
+ /// The `message_type` is derived from [`Notification::TYPE_NAME`].
+ pub(crate) fn new(content: NotificationChannel<'a, T, U>) -> Self {
+ Self {
+ message_type: T::TYPE_NAME.to_string(),
+ content,
+ }
+ }
+}
+
+impl<'a, T, U> QueueMessage<'a, T, U> {
+ /// Consume the message and return its content.
+ pub(crate) fn into_inner(self) -> NotificationChannel<'a, T, U> {
+ self.content
+ }
+}
+
+#[cfg(test)]
+impl<'a, T, U> QueueMessage<'a, T, U> {
+ /// Test-only constructor that doesn't require `T: Notification`.
+ pub(crate) fn new_test(message_type: String, content: NotificationChannel<'a, T, U>) -> Self {
+ Self {
+ message_type,
+ content,
+ }
+ }
}
/// a wrapper type over [QueueMessage] which can only be opened by providing the decision from the bulk digest state machine
@@ -221,7 +302,6 @@ impl<'a, T, U> QueueMessageNeedsStateMachine<'a, T, U> {
let map_msg = move |msg: QueueMessage<'a, T, U>| {
let QueueMessage {
message_type,
- rate_limit,
mut content,
} = msg;
@@ -238,7 +318,6 @@ impl<'a, T, U> QueueMessageNeedsStateMachine<'a, T, U> {
QueueMessage {
message_type,
- rate_limit,
content,
}
};
@@ -249,12 +328,16 @@ impl<'a, T, U> QueueMessageNeedsStateMachine<'a, T, U> {
/// Custom data payload for a silent background push that clears a previously
/// delivered notification from the user's device.
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClearPushIdentifier {
/// The collapse key identifier used to match the notification to clear.
pub identifier: String,
}
+impl Notification for ClearPushIdentifier {
+ const TYPE_NAME: &'static str = "clear_push_notification";
+}
+
/// Raw message received from SQS.
#[derive(Debug)]
pub struct RawQueueMessage {
diff --git a/rust/cloud-storage/notification/src/domain/models/rate_limit.rs b/rust/cloud-storage/notification/src/domain/models/rate_limit.rs
index a71f9f7c13..6356335af4 100644
--- a/rust/cloud-storage/notification/src/domain/models/rate_limit.rs
+++ b/rust/cloud-storage/notification/src/domain/models/rate_limit.rs
@@ -13,11 +13,6 @@ use thiserror::Error;
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};
diff --git a/rust/cloud-storage/notification/src/domain/models/request.rs b/rust/cloud-storage/notification/src/domain/models/request.rs
index 27f98223ee..06c9bfb972 100644
--- a/rust/cloud-storage/notification/src/domain/models/request.rs
+++ b/rust/cloud-storage/notification/src/domain/models/request.rs
@@ -1,18 +1,16 @@
//! Request and response models for the notification service.
-use crate::domain::{
- models::{
- ExclusionReason, FilteredRecipient, Notification, NotificationExtEmail, NotificationExtIos,
- RateLimitConfig, RateLimitKey, RecipientExclusion, apple::APNSPushNotification, mobile,
- mobile::MessageAttributes, queue_message::EmailContent,
- },
- service::SendNotificationError,
+use crate::domain::models::{
+ ExclusionReason, FilteredRecipient, Notification, NotificationExtEmail, NotificationExtIos,
+ RecipientExclusion,
+ apple::APNSPushNotification,
+ mobile::{self, MessageAttributes},
+ queue_message::EmailCreateBundle,
};
use cowlike::CowLike;
use itertools::Itertools;
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;
@@ -49,6 +47,8 @@ impl<'a, T> SendNotificationRequestBuilder<'a, T> {
type BuildApns<T, U> =
Box<dyn FnMut(T, uuid::Uuid) -> Option<(APNSPushNotification<U>, MessageAttributes)> + Send>;
+type BuildEmail<T> = Box<dyn FnMut(&T) -> EmailCreateBundle + Send>;
+
/// Full notification request with optional delivery channel builders.
///
/// Created from [`SendNotificationRequestBuilder::into_request`] and can be
@@ -58,7 +58,7 @@ pub struct SendNotificationRequest<'a, T, U> {
/// define how to turn t into an APNSPushNotitication T to be sent to ios
pub(crate) build_apns: Option<BuildApns<T, U>>,
/// 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 + Send>>,
+ pub(crate) build_email: Option<BuildEmail<T>>,
/// connection gateway accepts arbitrary json so we just ask if its enabled or not
pub(crate) send_conn_gateway: bool,
}
@@ -97,7 +97,7 @@ impl<'a, T: NotificationExtIos, U> SendNotificationRequest<'a, T, U> {
impl<'a, T: NotificationExtEmail, U> SendNotificationRequest<'a, T, U> {
/// Add a custom email content builder.
pub fn with_email(mut self) -> Self {
- self.build_email = Some(Box::new(|notif: T| notif.into_email()));
+ self.build_email = Some(Box::new(|notif: &T| EmailCreateBundle::new(notif)));
self
}
}
@@ -176,23 +176,6 @@ impl<'a, T: Notification> SendNotificationRequestBuilder<'a, T> {
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.
diff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rs
index d8659194e9..0bf9b000bb 100644
--- a/rust/cloud-storage/notification/src/domain/ports.rs
+++ b/rust/cloud-storage/notification/src/domain/ports.rs
@@ -15,6 +15,8 @@ use uuid::Uuid;
use models_pagination::{CreatedAt, Query};
+use crate::domain::models::NotificationExtEmail;
+use crate::domain::models::email_notification_digest::ports::DigestBatch;
use crate::domain::models::{
DeviceEndpoint, Notification, NotificationIdAndCollapseKey, RateLimitConfig, RateLimitKey,
RateLimitResult, SendNotificationRequestBuilder, UserNotificationRow, android::FCMMessage,
@@ -52,8 +54,8 @@ pub trait RateLimitPort: Send + Sync + 'static {
/// limited by constructing the key from relevant data.
fn check_and_increment(
&self,
- key: RateLimitKey,
- config: RateLimitConfig,
+ key: &RateLimitKey,
+ config: &RateLimitConfig,
) -> impl Future<Output = Result<RateLimitResult, Report>> + Send;
}
@@ -222,6 +224,12 @@ pub trait NotificationEgress: Send + Sync + 'static {
/// Messages are automatically deleted from the queue after successful delivery.
fn poll_and_deliver(&self)
-> impl Future<Output = Vec<Result<DeliverySuccess, Report>>> + Send;
+
+ /// Poll for ready digest batches, template them as emails, and send.
+ fn poll_email_digests<T: NotificationExtEmail>(
+ &self,
+ f: fn(DigestBatch) -> Result<T, Report>,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
}
/// Port for deleting a device registration from the database by its SNS endpoint ARN.
diff --git a/rust/cloud-storage/notification/src/domain/service/egress.rs b/rust/cloud-storage/notification/src/domain/service/egress.rs
index f68543c500..efa15e56dd 100644
--- a/rust/cloud-storage/notification/src/domain/service/egress.rs
+++ b/rust/cloud-storage/notification/src/domain/service/egress.rs
@@ -3,17 +3,19 @@
//! This service handles the worker-facing side of notifications:
//! consuming from the queue and delivering via WebSocket, push, and email.
-use crate::domain::models::RateLimitResult;
use crate::domain::models::apple::APNSPushNotification;
-use crate::domain::models::email_notification_digest::ports::{MessageId, NotificationSendChecker};
+use crate::domain::models::email_notification_digest::ports::{
+ ClaimResult, DigestBatch, DigestBatcher, MessageId, NotificationSendChecker,
+};
use crate::domain::models::email_notification_digest::{
BulkDigestEgressStateMachine, ResumeMachineBRequest,
};
use crate::domain::models::mobile::MessageAttributes;
use crate::domain::models::queue_message::{
- APNSTargets, ConnGatewayNotification, DeliveryFailure, DeliverySuccess, EmailNotification,
- NotificationChannel, QueueMessage,
+ APNSTargets, ConnGatewayNotification, DeliveryFailure, DeliverySuccess, EmailCreateBundle,
+ EmailNotification, NotificationChannel, QueueMessage,
};
+use crate::domain::models::{NotificationExtEmail, RateLimitResult};
use crate::domain::ports::{
EmailSender, NotificationEgress, NotificationQueue, NotificationRepository, NotificationSender,
RateLimitPort, WebSocketSender,
@@ -51,18 +53,26 @@ impl<M: NotificationSender> NotificationSendChecker for IosPushSend<'_, M> {
/// Service for delivering notifications (egress side).
///
/// Handles consuming from queue and delivering via WebSocket, push, and email.
-pub struct NotificationEgressService<Q, N, W, M, E, R, S> {
- queue: Q,
- #[allow(dead_code)]
- repository: N,
- websocket: W,
- mobile: M,
- email: E,
- rate_limiter: R,
- state_machine: S,
+pub struct NotificationEgressService<Q, N, W, M, E, R, S, D> {
+ /// Queue for receiving notification messages.
+ pub queue: Q,
+ /// Notification repository for DB operations.
+ pub repository: N,
+ /// WebSocket sender for real-time delivery.
+ pub websocket: W,
+ /// Mobile push sender (APNS/FCM).
+ pub mobile: M,
+ /// Email sender.
+ pub email: E,
+ /// Rate limiter.
+ pub rate_limiter: R,
+ /// Bulk digest egress state machine.
+ pub state_machine: S,
+ /// Digest batcher for claiming ready email digests.
+ pub digest_batcher: D,
}
-impl<Q, N, W, M, E, R, S> NotificationEgressService<Q, N, W, M, E, R, S>
+impl<Q, N, W, M, E, R, S, D> NotificationEgressService<Q, N, W, M, E, R, S, D>
where
Q: NotificationQueue,
N: NotificationRepository,
@@ -71,28 +81,8 @@ where
E: EmailSender,
R: RateLimitPort,
S: BulkDigestEgressStateMachine,
+ D: DigestBatcher,
{
- /// Create a new egress service.
- pub fn new(
- queue: Q,
- repository: N,
- websocket: W,
- mobile: M,
- email: E,
- rate_limiter: R,
- state_machine: S,
- ) -> Self {
- Self {
- queue,
- repository,
- websocket,
- mobile,
- email,
- rate_limiter,
- state_machine,
- }
- }
-
/// Deliver a notification from a queue message.
///
/// Processes the delivery chain, attempting each channel and falling back
@@ -103,33 +93,25 @@ where
&self,
message: QueueMessage<'static, serde_json::Value, 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(RateLimitResult::Exceeded(exceeded)) => {
- return vec![Err(report!(exceeded).context(DeliveryFailure::RateLimit))];
- }
- Ok(RateLimitResult::Allowed { .. }) => {
- // Rate limit allowed, continue
- }
- Err(e) => return vec![Err(e.context(DeliveryFailure::Other))],
- }
- }
+ let content = message.into_inner();
- let results = match message.content {
- NotificationChannel::ConnGateway(ref conn) => {
- Either::Left([self.deliver_conn_gateway(conn).await])
- }
+ let results = match content {
+ NotificationChannel::ConnGateway(ref conn) => Either::Left([self
+ .deliver_conn_gateway(conn)
+ .await
+ .context(DeliveryFailure::Other)]),
NotificationChannel::Email(ref email) => {
Either::Left([self.deliver_email(email).await])
}
- NotificationChannel::Ios(apns) => Either::Right(self.deliver_ios(&apns).await),
+ NotificationChannel::Ios(apns) => Either::Right(
+ self.deliver_ios(&apns)
+ .await
+ .into_iter()
+ .map(|r| r.context(DeliveryFailure::Other)),
+ ),
};
- results
- .into_iter()
- .map(|r| r.context(DeliveryFailure::Other))
- .collect()
+ results.into_iter().collect()
}
/// Deliver via connection gateway (WebSocket).
@@ -209,15 +191,29 @@ where
async fn deliver_email(
&self,
email: &EmailNotification<'static>,
- ) -> Result<DeliverySuccess, Report> {
+ ) -> Result<DeliverySuccess, Report<DeliveryFailure>> {
+ let (config, key) = email.rate_limit();
+
+ match self.rate_limiter.check_and_increment(key, config).await {
+ Ok(RateLimitResult::Exceeded(exceeded)) => {
+ return Err(report!(exceeded).context(DeliveryFailure::RateLimit));
+ }
+ Ok(RateLimitResult::Allowed { .. }) => {
+ // Rate limit allowed, continue
+ }
+ Err(e) => return Err(e.context(DeliveryFailure::Other)),
+ }
+
self.email
- .send_email(email.to.clone(), &email.content)
- .await?;
+ .send_email(email.to().clone(), &email.content)
+ .await
+ .context(DeliveryFailure::Other)?;
Ok(DeliverySuccess::Email)
}
}
-impl<Q, N, W, M, E, R, S> NotificationEgress for NotificationEgressService<Q, N, W, M, E, R, S>
+impl<Q, N, W, M, E, R, S, D> NotificationEgress
+ for NotificationEgressService<Q, N, W, M, E, R, S, D>
where
Q: NotificationQueue,
N: NotificationRepository,
@@ -226,6 +222,7 @@ where
E: EmailSender,
R: RateLimitPort,
S: BulkDigestEgressStateMachine,
+ D: DigestBatcher,
{
#[tracing::instrument(ret, skip(self))]
async fn poll_and_deliver(&self) -> Vec<Result<DeliverySuccess, Report>> {
@@ -261,4 +258,31 @@ where
results
}
+
+ #[tracing::instrument(err, skip(self))]
+ async fn poll_email_digests<T: NotificationExtEmail>(
+ &self,
+ f: fn(DigestBatch) -> Result<T, Report>,
+ ) -> Result<(), Report> {
+ let batch = match self.digest_batcher.claim_ready_digest().await? {
+ ClaimResult::Ready(batch) => batch,
+ ClaimResult::Empty | ClaimResult::Wait(_) => return Ok(()),
+ };
+
+ let recipient = batch.user_id.clone();
+ let email_notif: T = f(batch)?;
+ let email_content = EmailCreateBundle::new(&email_notif).with_recipient(recipient);
+
+ let message: QueueMessage<'_, T, ()> =
+ QueueMessage::new(NotificationChannel::Email(email_content));
+
+ self.queue
+ .publish(std::iter::once(message))
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, "failed to queue digest email");
+ })?;
+
+ Ok(())
+ }
}
diff --git a/rust/cloud-storage/notification/src/domain/service/ingress.rs b/rust/cloud-storage/notification/src/domain/service/ingress.rs
index 22732842fb..6b259e1b32 100644
--- a/rust/cloud-storage/notification/src/domain/service/ingress.rs
+++ b/rust/cloud-storage/notification/src/domain/service/ingress.rs
@@ -7,8 +7,8 @@ use crate::domain::models::apple::{APNSPushNotification, Aps};
use crate::domain::models::email_notification_digest::BulkDigestStateMachine;
use crate::domain::models::mobile::{MessageAttributes, PushType};
use crate::domain::models::queue_message::{
- APNSTargets, ClearPushIdentifier, ConnGatewayNotification, EmailNotification,
- NotificationChannel, QueueMessage, QueueMessageNeedsStateMachine, UserApnsEndpoints,
+ APNSTargets, ClearPushIdentifier, ConnGatewayNotification, NotificationChannel, QueueMessage,
+ QueueMessageNeedsStateMachine, UserApnsEndpoints,
};
use crate::domain::models::request::{
GetNotificationsByEventItemIdsRequest, NotificationStatus, UpdateNotificationsRequest,
@@ -241,20 +241,14 @@ where
(QueueMessageNeedsStateMachine<'a, T, U>, Option<String>),
Report<SendNotificationError>,
> {
- let rate_limit = notification.req.get_rate_limit()?;
- let message_type = T::TYPE_NAME.to_string();
let mut messages = Vec::new();
let mut apns_collapse_key = None;
// 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: NotificationChannel::ConnGateway(
- ConnGatewayNotification::clone_from_request(notification_id, notification),
- ),
- });
+ messages.push(QueueMessage::new(NotificationChannel::ConnGateway(
+ ConnGatewayNotification::clone_from_request(notification_id, notification),
+ )));
}
// APNS (iOS push): 1:M (single message for all recipients' device endpoints)
@@ -295,30 +289,23 @@ where
build_apns(notification.req.notification.clone(), notification_id)
{
apns_collapse_key = Some(attributes.collapse_key.clone());
- messages.push(QueueMessage {
- message_type: message_type.clone(),
- rate_limit: rate_limit.clone(),
- content: NotificationChannel::Ios(Box::new(APNSTargets {
+ messages.push(QueueMessage::new(NotificationChannel::Ios(Box::new(
+ APNSTargets {
notif: apns_notif,
attributes,
ios_device_endpoints: ios_endpoints,
- })),
- });
+ },
+ ))));
}
}
// 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: NotificationChannel::Email(EmailNotification {
- to: recipient.clone(),
- content: email_content,
- }),
- });
+ let email_content = build_email(&notification.req.notification);
+ messages.push(QueueMessage::new(NotificationChannel::Email(
+ email_content.with_recipient(recipient.clone()),
+ )));
}
}
@@ -425,27 +412,23 @@ where
.into_iter()
.map(|n| {
let collapse_key = n.apns_collapse_key;
- QueueMessage {
- message_type: "clear_push_notification".to_string(),
- rate_limit: None,
- content: NotificationChannel::Ios(Box::new(APNSTargets {
- notif: APNSPushNotification {
- aps: Aps {
- content_available: Some(1),
- sound: None,
- ..Default::default()
- },
- push_notification_data: ClearPushIdentifier {
- identifier: collapse_key.clone(),
- },
+ QueueMessage::new(NotificationChannel::Ios(Box::new(APNSTargets {
+ notif: APNSPushNotification {
+ aps: Aps {
+ content_available: Some(1),
+ sound: None,
+ ..Default::default()
},
- attributes: MessageAttributes {
- push_type: PushType::Background,
- collapse_key,
+ push_notification_data: ClearPushIdentifier {
+ identifier: collapse_key.clone(),
},
- ios_device_endpoints: ios_endpoints.clone(),
- })),
- }
+ },
+ attributes: MessageAttributes {
+ push_type: PushType::Background,
+ collapse_key,
+ },
+ ios_device_endpoints: ios_endpoints.clone(),
+ })))
})
.collect();
diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rs
index 9a623fd83c..850eb4219d 100644
--- a/rust/cloud-storage/notification/src/domain/service/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/test.rs
@@ -2,10 +2,12 @@
use crate::domain::models::apple::APNSPushNotification;
use crate::domain::models::email_notification_digest::BulkDigestStateMachine;
+use crate::domain::models::email_notification_digest::ports::DigestBatch;
+use crate::domain::models::email_notification_digest::ports::{ClaimResult, DigestBatcher};
use crate::domain::models::mobile::NotifCollapseKey;
use crate::domain::models::queue_message::{
- ConnGatewayInnerNotif, ConnGatewayNotification, EmailContent, NotificationChannel,
- QueueMessage, RawQueueMessage,
+ ConnGatewayInnerNotif, ConnGatewayNotification, EmailContent, EmailCreateBundle,
+ NotificationChannel, QueueMessage, RawQueueMessage,
};
use crate::domain::models::request::{NotificationStatus, UpdateNotificationsRequest};
use crate::domain::models::{
@@ -14,8 +16,8 @@ use crate::domain::models::{
RateLimitResult, SendNotificationRequestBuilder, TaggedContent, UserNotificationRow,
};
use crate::domain::ports::{
- EmailSender, NotificationQueue, NotificationRepository, NotificationSender, RateLimitPort,
- WebSocketSender,
+ EmailSender, NotificationEgress, NotificationQueue, NotificationRepository, NotificationSender,
+ RateLimitPort, WebSocketSender,
};
use crate::domain::service::{
NotificationEgressService, NotificationIngress, NotificationIngressService, NotificationReader,
@@ -41,14 +43,6 @@ struct TestNotification {
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
- }
}
impl NotificationExtIos for TestNotification {
@@ -72,12 +66,23 @@ impl NotificationExtIos for TestNotification {
}
impl NotificationExtEmail for TestNotification {
- fn into_email(self) -> crate::domain::models::queue_message::EmailContent {
+ fn format_email(&self) -> crate::domain::models::queue_message::EmailContent {
EmailContent {
subject: "Test".to_string(),
- body: self.message,
+ body: self.message.clone(),
+ }
+ }
+
+ fn rate_limit_config() -> RateLimitConfig {
+ RateLimitConfig {
+ max_count: u64::MAX,
+ window: Duration::from_hours(1),
}
}
+
+ fn rate_limit_key(&self) -> RateLimitKey {
+ RateLimitKey::from_str_hashed("test-key")
+ }
}
/// Helper to create a test user ID.
@@ -940,13 +945,13 @@ impl MockRateLimiter {
impl RateLimitPort for MockRateLimiter {
async fn check_and_increment(
&self,
- _key: RateLimitKey,
- config: RateLimitConfig,
+ _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,
+ current_count: config.max_count.saturating_add(1),
max_count: config.max_count,
}))
} else {
@@ -956,6 +961,22 @@ impl RateLimitPort for MockRateLimiter {
}
/// Mock egress state machine that forwards sends without recording message IDs or batching.
+struct MockDigestBatcher;
+
+impl DigestBatcher for MockDigestBatcher {
+ async fn add_to_digest(
+ &self,
+ _notification: &UserNotificationRow<serde_json::Value>,
+ _send_after: Duration,
+ ) -> Result<(), Report> {
+ Ok(())
+ }
+
+ async fn claim_ready_digest(&self) -> Result<ClaimResult, Report> {
+ Ok(ClaimResult::Empty)
+ }
+}
+
struct MockEgressStateMachine;
impl crate::domain::models::email_notification_digest::BulkDigestEgressStateMachine
@@ -1010,16 +1031,18 @@ fn create_egress_service<R: RateLimitPort>(
MockEmailSender,
R,
MockEgressStateMachine,
+ MockDigestBatcher,
> {
- NotificationEgressService::new(
- MockQueue::new(),
- MockRepository::new(),
- MockWebSocketSender,
- MockMobileSender,
- MockEmailSender,
+ NotificationEgressService {
+ queue: MockQueue::new(),
+ repository: MockRepository::new(),
+ websocket: MockWebSocketSender,
+ mobile: MockMobileSender,
+ email: MockEmailSender,
rate_limiter,
- MockEgressStateMachine,
- )
+ state_machine: MockEgressStateMachine,
+ digest_batcher: MockDigestBatcher,
+ }
}
fn create_mock_notif<T: Notification>(meta: T) -> ConnGatewayInnerNotif<T> {
@@ -1043,22 +1066,14 @@ 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: NotificationChannel::ConnGateway(
- ConnGatewayNotification {
- notif: create_mock_notif(TestNotification {
- message: "Hello".to_string(),
- }),
- recipients: vec![recipient],
- }
- .testing_to_value(),
- ),
- };
+ let email = EmailCreateBundle::new(&TestNotification {
+ message: "Hello".to_string(),
+ })
+ .with_recipient(recipient);
+ let message = QueueMessage::new_test(
+ "test_notification".to_string(),
+ NotificationChannel::Email(email),
+ );
let results = service.deliver_notification(message).await;
@@ -1079,23 +1094,14 @@ 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: NotificationChannel::ConnGateway(
- ConnGatewayNotification {
- notif: create_mock_notif(TestNotification {
- message: "Hello".to_string(),
- }),
-
- recipients: vec![recipient],
- }
- .testing_to_value(),
- ),
- };
+ let email = EmailCreateBundle::new(&TestNotification {
+ message: "Hello".to_string(),
+ })
+ .with_recipient(recipient);
+ let message = QueueMessage::new_test(
+ "test_notification".to_string(),
+ NotificationChannel::Email(email),
+ );
let results = service.deliver_notification(message).await;
@@ -1105,14 +1111,13 @@ async fn test_egress_rate_limit_allowed() {
}
#[tokio::test]
-async fn test_egress_no_rate_limit_configured() {
+async fn test_egress_conn_gateway_not_rate_limited() {
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: NotificationChannel::ConnGateway(
+ let message = QueueMessage::new_test(
+ "test_notification".to_string(),
+ NotificationChannel::ConnGateway(
ConnGatewayNotification {
notif: create_mock_notif(TestNotification {
message: "Hello".to_string(),
@@ -1121,11 +1126,11 @@ async fn test_egress_no_rate_limit_configured() {
}
.testing_to_value(),
),
- };
+ );
let results = service.deliver_notification(message).await;
- // Should succeed even though rate limiter would exceed - because no rate limit is configured
+ // Should succeed - ConnGateway messages are not rate limited
assert_eq!(results.len(), 1);
assert!(results[0].is_ok());
}
@@ -1440,22 +1445,22 @@ async fn test_egress_ios_attempts_all_endpoints_even_if_some_fail() {
let failing_endpoints: HashSet<String> = [endpoint1.to_string(), endpoint3.to_string()].into();
let mobile_sender = std::sync::Arc::new(TrackingMobileSender::new(failing_endpoints));
- let service = NotificationEgressService::new(
- MockQueue::new(),
- MockRepository::new(),
- MockWebSocketSender,
- mobile_sender.clone(),
- MockEmailSender,
- MockRateLimiter::allowing(),
- MockEgressStateMachine,
- );
+ let service = NotificationEgressService {
+ queue: MockQueue::new(),
+ repository: MockRepository::new(),
+ websocket: MockWebSocketSender,
+ mobile: mobile_sender.clone(),
+ email: MockEmailSender,
+ rate_limiter: MockRateLimiter::allowing(),
+ state_machine: MockEgressStateMachine,
+ digest_batcher: MockDigestBatcher,
+ };
let user1 = test_user_id("[email protected]");
let user2 = test_user_id("[email protected]");
- let message = QueueMessage {
- message_type: "test_notification".to_string(),
- rate_limit: None,
- content: NotificationChannel::Ios(Box::new(APNSTargets {
+ let message = QueueMessage::new_test(
+ "test_notification".to_string(),
+ NotificationChannel::Ios(Box::new(APNSTargets {
notif: APNSPushNotification {
aps: Aps::default(),
push_notification_data: json!({"message": "Hello"}),
@@ -1481,7 +1486,7 @@ async fn test_egress_ios_attempts_all_endpoints_even_if_some_fail() {
),
]),
})),
- };
+ );
let results = service.deliver_notification(message).await;
@@ -1520,6 +1525,98 @@ async fn test_egress_ios_attempts_all_endpoints_even_if_some_fail() {
assert_eq!(failures, 2, "Should have 2 failed deliveries");
}
+// --- poll_email_digests tests ---
+
+struct ReadyDigestBatcher {
+ batch: Mutex<Option<DigestBatch>>,
+}
+
+impl DigestBatcher for ReadyDigestBatcher {
+ async fn add_to_digest(
+ &self,
+ _notification: &UserNotificationRow<serde_json::Value>,
+ _send_after: Duration,
+ ) -> Result<(), Report> {
+ Ok(())
+ }
+
+ async fn claim_ready_digest(&self) -> Result<ClaimResult, Report> {
+ match self.batch.lock().unwrap().take() {
+ Some(batch) => Ok(ClaimResult::Ready(batch)),
+ None => Ok(ClaimResult::Empty),
+ }
+ }
+}
+
+#[tokio::test]
+async fn test_poll_email_digests_sends_email_for_ready_batch() {
+ use std::sync::Arc;
+
+ let user = test_user_id("[email protected]");
+ let notif = UserNotificationRow {
+ owner_id: user.clone(),
+ notification_id: Uuid::nil(),
+ notification_event_type: "test_notification".to_string(),
+ entity: EntityType::Document.with_entity_str("doc-1"),
+ sent: false,
+ done: false,
+ created_at: None,
+ viewed_at: None,
+ updated_at: None,
+ deleted_at: None,
+ notification_metadata: serde_json::to_value(TestNotification {
+ message: "hello from digest".to_string(),
+ })
+ .unwrap(),
+ sender_id: None,
+ };
+
+ let batch = DigestBatch {
+ user_id: user.clone(),
+ notifications: vec![notif.into_tagged()],
+ };
+
+ let batcher = ReadyDigestBatcher {
+ batch: Mutex::new(Some(batch)),
+ };
+
+ let queue = Arc::new(MockQueue::new());
+ let service = NotificationEgressService {
+ queue: queue.clone(),
+ repository: MockRepository::new(),
+ websocket: MockWebSocketSender,
+ mobile: MockMobileSender,
+ email: MockEmailSender,
+ rate_limiter: MockRateLimiter::allowing(),
+ state_machine: MockEgressStateMachine,
+ digest_batcher: batcher,
+ };
+
+ fn digest_to_notif(batch: DigestBatch) -> Result<TestNotification, Report> {
+ Ok(TestNotification {
+ message: format!("You have {} notification(s)", batch.notifications.len()),
+ })
+ }
+
+ service.poll_email_digests(digest_to_notif).await.unwrap();
+
+ let published = queue.get_published();
+ assert_eq!(published.len(), 1);
+ assert!(published[0]["content"]["Email"].is_object());
+}
+
+#[tokio::test]
+async fn test_poll_email_digests_noop_when_empty() {
+ let service = create_egress_service(MockRateLimiter::allowing());
+
+ fn digest_to_notif(_batch: DigestBatch) -> Result<TestNotification, Report> {
+ panic!("should not be called when empty")
+ }
+
+ // MockDigestBatcher always returns Empty
+ service.poll_email_digests(digest_to_notif).await.unwrap();
+}
+
impl NotificationSender for std::sync::Arc<TrackingMobileSender> {
async fn send_ios_push_notification<T: Serialize + Send + Sync>(
&self,
diff --git a/rust/cloud-storage/notification/src/outbound/digest_batcher.rs b/rust/cloud-storage/notification/src/outbound/digest_batcher.rs
index 0a76c41441..7a8c05c3c3 100644
--- a/rust/cloud-storage/notification/src/outbound/digest_batcher.rs
+++ b/rust/cloud-storage/notification/src/outbound/digest_batcher.rs
@@ -159,7 +159,11 @@ impl DigestBatcher for RedisDigestBatcher {
let notifications = items
.into_iter()
- .filter_map(|s| serde_json::from_str(&s).ok())
+ .filter_map(|s| {
+ serde_json::from_str::<UserNotificationRow<serde_json::Value>>(&s)
+ .ok()
+ .map(|n| n.into_tagged())
+ })
.collect();
Ok(ClaimResult::Ready(DigestBatch {
diff --git a/rust/cloud-storage/notification/src/outbound/digest_batcher/test.rs b/rust/cloud-storage/notification/src/outbound/digest_batcher/test.rs
index 788376de46..0f8233640e 100644
--- a/rust/cloud-storage/notification/src/outbound/digest_batcher/test.rs
+++ b/rust/cloud-storage/notification/src/outbound/digest_batcher/test.rs
@@ -12,14 +12,6 @@ struct TestNotification {
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
- }
}
async fn get_redis_connection() -> MultiplexedConnection {
@@ -78,6 +70,32 @@ fn create_test_notification(
}
}
+/// Creates a notification with raw metadata (no TaggedContent wrapper),
+/// matching how production code stores via `inner_store_batch` and `mark_message_as_failed`.
+fn create_raw_test_notification(
+ user_id: MacroUserIdStr<'static>,
+ message: &str,
+) -> UserNotificationRow<serde_json::Value> {
+ let notification = TestNotification {
+ message: message.to_string(),
+ };
+
+ UserNotificationRow {
+ owner_id: user_id,
+ notification_id: Uuid::new_v4(),
+ notification_event_type: TestNotification::TYPE_NAME.to_string(),
+ entity: EntityType::Document.with_entity_string(Uuid::new_v4().to_string()),
+ sent: false,
+ done: false,
+ created_at: Some(Utc::now()),
+ viewed_at: None,
+ updated_at: Some(Utc::now()),
+ deleted_at: None,
+ notification_metadata: serde_json::to_value(notification).expect("serialize cannot fail"),
+ sender_id: None,
+ }
+}
+
#[tokio::test]
async fn test_add_to_digest_creates_pending_entry() {
let mut conn = get_redis_connection().await;
@@ -259,6 +277,48 @@ async fn test_new_notifications_during_processing_not_lost() {
cleanup_prefix(&mut conn, &prefix).await;
}
+#[tokio::test]
+async fn test_claim_digest_tags_raw_metadata() {
+ let mut conn = get_redis_connection().await;
+ let prefix = test_prefix("tags_raw_metadata");
+ let batcher = RedisDigestBatcher::with_key_prefix(conn.clone(), &prefix);
+ let user = test_user("tags_raw");
+
+ // Store with raw metadata (no TaggedContent wrapper), matching production code paths
+ let notification = create_raw_test_notification(user.clone(), "raw message");
+ let expected_id = notification.notification_id;
+
+ batcher
+ .add_to_digest(&notification, Duration::from_secs(0))
+ .await
+ .unwrap();
+
+ tokio::time::sleep(Duration::from_millis(100)).await;
+
+ let result = batcher.claim_ready_digest().await.unwrap();
+
+ match result {
+ ClaimResult::Ready(batch) => {
+ assert_eq!(batch.user_id.as_ref(), user.as_ref());
+ assert_eq!(
+ batch.notifications.len(),
+ 1,
+ "notification must not be silently dropped"
+ );
+ let tagged = &batch.notifications[0];
+ assert_eq!(tagged.notification_id, expected_id);
+ // Verify the metadata was wrapped in TaggedContent by round-tripping
+ // back to JSON and checking for the { "tag": ..., "content": ... } shape
+ let meta_json = serde_json::to_value(&tagged.notification_metadata).unwrap();
+ assert_eq!(meta_json["tag"], TestNotification::TYPE_NAME);
+ assert_eq!(meta_json["content"]["message"], "raw message");
+ }
+ other => panic!("Expected ClaimResult::Ready, got {:?}", other),
+ }
+
+ cleanup_prefix(&mut conn, &prefix).await;
+}
+
#[tokio::test]
async fn test_multiple_users_independent() {
let mut conn = get_redis_connection().await;
diff --git a/rust/cloud-storage/notification/src/outbound/rate_limit.rs b/rust/cloud-storage/notification/src/outbound/rate_limit.rs
index 587b167504..9e259a9e07 100644
--- a/rust/cloud-storage/notification/src/outbound/rate_limit.rs
+++ b/rust/cloud-storage/notification/src/outbound/rate_limit.rs
@@ -66,8 +66,8 @@ impl RedisRateLimitOps for redis::Client {
impl<R: RedisRateLimitOps + Send + Sync + 'static> RateLimitPort for RedisRateLimitAdapter<R> {
async fn check_and_increment(
&self,
- key: RateLimitKey,
- config: RateLimitConfig,
+ key: &RateLimitKey,
+ config: &RateLimitConfig,
) -> Result<RateLimitResult, Report> {
let key_str = format!("rtl:{}", key.to_hex_string());
let expiry_seconds = config.window.as_secs();
diff --git a/rust/cloud-storage/notification/src/outbound/repository/test.rs b/rust/cloud-storage/notification/src/outbound/repository/test.rs
index 2fc6e6cb8d..df7a11959d 100644
--- a/rust/cloud-storage/notification/src/outbound/repository/test.rs
+++ b/rust/cloud-storage/notification/src/outbound/repository/test.rs
@@ -13,14 +13,6 @@ struct TestNotification {
impl Notification for TestNotification {
const TYPE_NAME: &'static str = "test_notification";
-
- fn rate_limit_config() -> Option<crate::domain::models::RateLimitConfig> {
- None
- }
-
- fn rate_limit_key(&self) -> Option<crate::domain::models::RateLimitKey> {
- None
- }
}
fn test_user(email: &str) -> MacroUserIdStr<'static> {
diff --git a/rust/cloud-storage/notification_service/src/main.rs b/rust/cloud-storage/notification_service/src/main.rs
index 354bc56977..b8996c06bc 100644
--- a/rust/cloud-storage/notification_service/src/main.rs
+++ b/rust/cloud-storage/notification_service/src/main.rs
@@ -164,20 +164,24 @@ pub async fn main() -> anyhow::Result<()> {
db.clone(),
),
digest_batcher: ::notification::outbound::digest_batcher::RedisDigestBatcher::new(
- redis_multiplexed_conn,
+ redis_multiplexed_conn.clone(),
),
digest_window: std::time::Duration::from_secs(30 * 60),
};
- let egress_service = NotificationEgressService::new(
- notification_queue,
- egress_repository,
- websocket_adapter,
- mobile_adapter,
- email_adapter,
- rate_limit_adapter,
- egress_state_machine,
- );
+ let egress_digest_batcher =
+ ::notification::outbound::digest_batcher::RedisDigestBatcher::new(redis_multiplexed_conn);
+
+ let egress_service = NotificationEgressService {
+ queue: notification_queue,
+ repository: egress_repository,
+ websocket: websocket_adapter,
+ mobile: mobile_adapter,
+ email: email_adapter,
+ rate_limiter: rate_limit_adapter,
+ state_machine: egress_state_machine,
+ digest_batcher: egress_digest_batcher,
+ };
let worker = NotificationWorker::new(egress_service);