Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
seanaye/feat/add digest state machines (#1531)
Sean Aye154ce80ccd27
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260213120000_create_notification_message_receipt.sql b/rust/cloud-storage/macro_db_client/migrations/20260213120000_create_notification_message_receipt.sqlnew file mode 100644index 0000000000..cfacded68b--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260213120000_create_notification_message_receipt.sql@@ -0,0 +1,19 @@+-- Table for tracking message receipts and their delivery status+-- Associates message_ids (from push notification services) with user_notification records++CREATE TABLE notification_message_receipt (+ message_id TEXT PRIMARY KEY,+ user_id TEXT NOT NULL,+ notification_id UUID NOT NULL,+ failed BOOLEAN NOT NULL DEFAULT FALSE,+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,+ failed_at TIMESTAMP,+ CONSTRAINT fk_user_notification+ FOREIGN KEY (user_id, notification_id)+ REFERENCES user_notification (user_id, notification_id)+ ON DELETE CASCADE+);++-- Index for checking all messages for a given user_notification+CREATE INDEX idx_notification_message_receipt_user_notification+ ON notification_message_receipt (user_id, notification_id);diff --git a/rust/cloud-storage/notification/.sqlx/query-3357165799ff1f7bf1de3891174668e0ab16c64bd9dfc905213681e6021474fa.json b/rust/cloud-storage/notification/.sqlx/query-3357165799ff1f7bf1de3891174668e0ab16c64bd9dfc905213681e6021474fa.jsonnew file mode 100644index 0000000000..6696253445--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-3357165799ff1f7bf1de3891174668e0ab16c64bd9dfc905213681e6021474fa.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT EXISTS(\n SELECT 1 FROM notification_message_receipt\n WHERE user_id = $1\n AND notification_id = $2\n AND failed = false\n ) as \"exists!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "exists!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "3357165799ff1f7bf1de3891174668e0ab16c64bd9dfc905213681e6021474fa"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-92edc80110af7b96f7f908989461a4abb11652671a95454969369a0484ed9239.json b/rust/cloud-storage/notification/.sqlx/query-92edc80110af7b96f7f908989461a4abb11652671a95454969369a0484ed9239.jsonnew file mode 100644index 0000000000..a8520fdfd0--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-92edc80110af7b96f7f908989461a4abb11652671a95454969369a0484ed9239.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO notification_message_receipt (message_id, user_id, notification_id)\n VALUES ($1, $2, $3)\n ON CONFLICT (message_id) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "92edc80110af7b96f7f908989461a4abb11652671a95454969369a0484ed9239"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-b6705d3675950d0bbbd4a0ba10f7716a24694cfd98741fc0508d607684b1c8a9.json b/rust/cloud-storage/notification/.sqlx/query-b6705d3675950d0bbbd4a0ba10f7716a24694cfd98741fc0508d607684b1c8a9.jsonnew file mode 100644index 0000000000..1168d26a34--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-b6705d3675950d0bbbd4a0ba10f7716a24694cfd98741fc0508d607684b1c8a9.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE notification_message_receipt\n SET failed = true, failed_at = NOW()\n WHERE message_id = $1\n RETURNING user_id, notification_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "notification_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "b6705d3675950d0bbbd4a0ba10f7716a24694cfd98741fc0508d607684b1c8a9"+}diff --git a/rust/cloud-storage/notification/Cargo.toml b/rust/cloud-storage/notification/Cargo.tomlindex 9aa2e5329c..3fe1b8bfa8 100644--- a/rust/cloud-storage/notification/Cargo.toml+++ b/rust/cloud-storage/notification/Cargo.toml@@ -14,16 +14,17 @@ axum = ["schema",]docs = ["dep:aquamarine"]+redis-tests = []schema = ["dep:utoipa"][dependencies]aquamarine = { version = "0.6", optional = true }aws-sdk-sesv2 = { workspace = true }-cowlike = { path = "../cowlike" }aws-sdk-sns = { workspace = true }aws-sdk-sqs = { workspace = true }axum = { workspace = true, optional = true }chrono = { workspace = true }+cowlike = { path = "../cowlike" }either = { workspace = true }hex = { workspace = true }itertools = { workspace = true }@@ -32,7 +33,11 @@ model-entity = { path = "../model-entity" }model-error-response = { path = "../model-error-response", optional = true }model_user = { path = "../model_user", optional = true, features = ["axum"] }models_pagination = { path = "../models_pagination" }-redis = { workspace = true, features = ["tokio-native-tls-comp"] }+redis = { workspace = true, features = [+ "aio",+ "tokio-comp",+ "tokio-native-tls-comp",+] }reqwest = { workspace = true }rootcause = { workspace = true }serde = { workspace = true }diff --git a/rust/cloud-storage/notification/fixtures/message_receipts.sql b/rust/cloud-storage/notification/fixtures/message_receipts.sqlnew file mode 100644index 0000000000..6633fef15b--- /dev/null+++ b/rust/cloud-storage/notification/fixtures/message_receipts.sql@@ -0,0 +1,12 @@+-- Setup: Create a notification and user_notification first+INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata)+VALUES ('0193b1ea-c742-7589-893b-2b4a509c1e77', 'test', 'item-2', 'document', 'test_service', '{}');++INSERT INTO user_notification (user_id, notification_id, created_at)+VALUES ('macro|[email protected]', '0193b1ea-c742-7589-893b-2b4a509c1e77', '2025-01-01 00:00:00');++-- Insert message receipts for testing+INSERT INTO notification_message_receipt (message_id, user_id, notification_id, failed)+VALUES+ ('msg-1', 'macro|[email protected]', '0193b1ea-c742-7589-893b-2b4a509c1e77', false),+ ('msg-2', 'macro|[email protected]', '0193b1ea-c742-7589-893b-2b4a509c1e77', true);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.rsindex 7d5b996ba3..02ccbf7190 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@@ -7,15 +7,19 @@//! 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 crate::domain::{+ models::{+ Notification, TaggedContent, UserNotificationRow,+ email_notification_digest::ports::{+ DigestBatcher, LastOnlineChecker, MessageId, MessageReceiptRepo,+ NotificationSendChecker, PushNotificationChecker, UserExistenceChecker,+ },},+ ports::NotificationRepository,};use either::Either;use macro_user_id::cowlike::CowLike;-use rootcause::Report;+use rootcause::{Report, report};use serde::{Deserialize, Serialize};use std::{collections::HashSet, time::Duration};@@ -26,6 +30,8 @@ pub mod ports;mod test;/// Send as part of a batched digest email (collected over 5-30 minutes).+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(transparent)]pub struct BatchSend<T>(T);/// Send immediately as a single notification email.@@ -214,7 +220,7 @@ impl<T: Notification> AccountDoesNotExist<T> {/// State indicating the user has push notifications enabled.////// If push was delivered successfully, don't send email. Otherwise, batch send.-#[derive(Serialize, Deserialize)]+#[derive(Debug, 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@@ -224,6 +230,14 @@ pub struct PushNotificationsEnabled {inner: UserNotificationRow<TaggedContent<serde_json::Value>>,}+impl PushNotificationsEnabled {+ /// assert that the push notification failed to deliver and therefore+ /// we should queue a bulk email notification+ fn assert_failed(self) -> BatchSend<UserNotificationRow<TaggedContent<serde_json::Value>>> {+ BatchSend(self.inner)+ }+}+/// State indicating the user has push notifications disabled.////// Since they can't receive push, check if they're online before deciding.@@ -275,3 +289,249 @@ impl<T: Notification> PushNotificationsDisabled<T> {})}}++/// a struct which is able to drive the state machine to a decision on a given notification+/// This state machine does not model the entire decision tree because it runs at a place in the program+/// where not all actions have been taken yet.+pub struct StateMachineDriverA<U, N, O, B> {+ /// adapter which implements [UserExistenceChecker]+ pub user_checker: U,+ /// adapter which implements [PushNotificationChecker]+ pub notification_checker: N,+ /// adapter which implements [LastOnlineChecker]+ pub online_checker: O,+ /// adapter which allows inserting a notification for bulk digest email+ /// implements [DigestBatcher]+ pub digest_batcher: B,+ /// the blocklist for notifications which are never forwarded to bulk+ pub block_list: EmailBlockList,+ /// the allow list for checking if a notification is analagous to an "invite to macro" notification+ pub invite_list: ExplicitInviteAllowList,+ /// the window of time in which the digest emails are collected for before sending+ pub digest_window: Duration,+ /// the duration for how recently a user has been online+ /// used to abort sending a bulk email if the user is below the+ /// threshold+ pub online_duration_threshold: Duration,+}++/// the initial decision created during notification ingress+pub enum StateMachineDecisionA<T> {+ /// we will not send a batch email+ DontSend(DontSend),+ /// we already queued a batch email to send+ BatchWasQueued(BatchSend<()>),+ /// we don't yet have the required information to know if we need to send a batch or not+ /// if a caller receives this message the enqueued push notification (if it exists) should contain this data.+ ///+ /// This allows the egress worker to continue the state machine after we know what the status+ /// of the push notification is.+ Indeterminate(BatchSend<PushNotificationsEnabled>),+ /// we should template the contained notification into an email to send immediately.+ /// The caller is responsible for templating this notification into an email and queuing it for delivery+ SendImmediate(SingleSend<UserNotificationRow<T>>),+}++impl<U, N, O, B> StateMachineDriverA<U, N, O, B>+where+ U: UserExistenceChecker,+ N: PushNotificationChecker,+ O: LastOnlineChecker,+ B: DigestBatcher,+{+ /// given an input notification, drive the state machine to an initial decision about the notification.+ /// This attempts to handle as many cases internally as possible although the caller is responsible for picking up certain decisions.+ /// See [StateMachineInitialDecision] for more info.+ pub async fn ingest<T: Notification>(+ &self,+ notif: UserNotificationRow<T>,+ ) -> Result<StateMachineDecisionA<T>, Report> {+ let allowed = match self.block_list.notification_is_allowed(notif) {+ Either::Left(l) => l,+ Either::Right(r) => {+ return Ok(StateMachineDecisionA::DontSend(r));+ }+ };+ let push_notification_state = match allowed+ .check_user_existence(&self.user_checker)+ .await?+ .map_right(|r| r.batch_or_single_send(&self.invite_list))+ {+ Either::Left(l) => {+ l.push_notifications_enabled(&self.notification_checker)+ .await?+ }+ Either::Right(Either::Left(rl)) => {+ return Ok(StateMachineDecisionA::SendImmediate(rl));+ }+ Either::Right(Either::Right(rr)) => {+ return Ok(StateMachineDecisionA::BatchWasQueued(+ self.inner_store_batch(rr).await?,+ ));+ }+ };+ let last_online = match push_notification_state {+ Either::Left(l) => {+ return Ok(StateMachineDecisionA::Indeterminate(BatchSend(l)));+ }+ Either::Right(r) => {+ r.check_last_online_time(&self.online_checker, self.online_duration_threshold)+ .await?+ }+ };+ Ok(match last_online {+ Either::Left(l) => {+ StateMachineDecisionA::BatchWasQueued(self.inner_store_batch(l).await?)+ }+ Either::Right(r) => StateMachineDecisionA::DontSend(r),+ })+ }++ async fn inner_store_batch<T: Notification>(+ &self,+ batch: BatchSend<UserNotificationRow<T>>,+ ) -> Result<BatchSend<()>, Report> {+ let notif = batch.0.into_tagged().map(TaggedContent::serialize);+ let () = self+ .digest_batcher+ .add_to_digest(¬if, self.digest_window)+ .await?;+ Ok(BatchSend(()))+ }+}++/// This state machine driver is able to pick up at a different place in the program+/// Once we know what the delivery state of a push Notification to a users device is+pub struct StateMachineDriverB<B, R> {+ /// some R that implements [MessageReceiptRepo]+ pub message_receipt_repo: R,+ /// Some B that implements [DigestBatcher]+ pub digest_batcher: B,+ /// the window of time in which the digest emails are collected for before sending+ pub digest_window: Duration,+}++/// the request used to call [StateMachineDriverB::continue_machine]+pub struct ResumeMachineBRequest<N> {+ /// the notification enabled value as received from [StateMachineDecisionA::Indeterminate]+ pub notification_enabled: PushNotificationsEnabled,+ /// a value which abstracts away the sending of the notification+ /// implements [NotificationSendChecker]+ pub send_notif: N,+}++impl<B, R> StateMachineDriverB<B, R>+where+ B: DigestBatcher,+ R: MessageReceiptRepo,+{+ /// this picks up where we left off if we received a [StateMachineDecisionA::Indeterminate]+ /// We call this when its time to send the notification, on the egress side of the queue+ pub async fn continue_machine<N: NotificationSendChecker>(+ &self,+ req: ResumeMachineBRequest<N>,+ ) -> Result<(N::Ok, DontSend), (N::Err, Result<BatchSend<()>, Report>)> {+ let ResumeMachineBRequest {+ notification_enabled,+ send_notif,+ } = req;+ let res = send_notif.send_notification().await;++ match res {+ // the notification succeeded (probably) so we dont send a bulk email+ Ok(r) => {+ // record the message id in the repo+ let message_id = N::extract_message_id(&r);++ // cant really do anything if this fails, so we just ignore the error+ let _ = self+ .message_receipt_repo+ .record_message_id(+ message_id,+ notification_enabled.inner.owner_id,+ notification_enabled.inner.notification_id,+ )+ .await;++ Ok((r, DontSend(())))+ }+ // the notification failed to send, queue the batch+ Err(e) => {+ let next = notification_enabled.assert_failed();+ let res = self+ .digest_batcher+ .add_to_digest(&next.0, self.digest_window)+ .await+ .map(BatchSend);+ Err((e, res))+ }+ }+ }+}++/// the driver of the state machine which is used to reconcile the SNS failure messages+/// with the digests that should be sent due to failure+pub struct StateMachineDriverC<B, R, N> {+ /// some R that implements [MessageReceiptRepo]+ pub message_receipt_repo: R,+ /// Some B that implements [DigestBatcher]+ pub digest_batcher: B,+ /// some N that implements [NotificationRepository]+ pub notif_repo: N,+ /// the window of time in which the digest emails are collected for before sending+ pub digest_window: Duration,+}++/// the outcome of a [StateMachineDriverC]+pub enum StateMachineDecisionC {+ /// No batch message was queued+ NoAction,+ /// the digest message was queued+ BatchWasQueued(BatchSend<()>),+}++impl<B, R, N> StateMachineDriverC<B, R, N>+where+ B: DigestBatcher,+ R: MessageReceiptRepo,+ N: NotificationRepository,+{+ /// mark a message as failed, this will enqueue messages to the batch only once all the+ /// push notifs for this user_notification have failed+ pub async fn mark_message_as_failed(+ &self,+ message_id: MessageId,+ ) -> Result<StateMachineDecisionC, Report> {+ let (user_id, notif_id) = self+ .message_receipt_repo+ .mark_message_failed(message_id)+ .await?;+ let did_all_pushes_fail = self+ .message_receipt_repo+ .did_all_messages_fail(user_id.copied(), notif_id)+ .await?;+ let true = did_all_pushes_fail else {+ return Ok(StateMachineDecisionC::NoAction);+ };++ // retrieve the notification data and add it to the batch+ let Some(notif) = self+ .notif_repo+ .get_user_notification_by_id::<serde_json::Value>(user_id.as_ref(), notif_id)+ .await?+ else {+ return Err(report!(+ "No user_notification was found for {} + {}",+ user_id,+ notif_id+ ));+ };+ let notif = notif.into_tagged();++ let () = self+ .digest_batcher+ .add_to_digest(¬if, self.digest_window)+ .await?;+ Ok(StateMachineDecisionC::BatchWasQueued(BatchSend(())))+ }+}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.rsindex ac4b7ee66e..8403612627 100644--- 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@@ -1,6 +1,8 @@+use crate::domain::models::{TaggedContent, UserNotificationRow};use macro_user_id::user_id::MacroUserIdStr;use rootcause::Report;use std::time::Duration;+use uuid::Uuid;/// trait for checking whether or not a user existspub trait UserExistenceChecker: Send + Sync + 'static {@@ -11,6 +13,55 @@ pub trait UserExistenceChecker: Send + Sync + 'static {) -> impl Future<Output = Result<bool, Report>> + Send;}+/// A batch of notifications ready to be sent as a digest email.+#[derive(Debug)]+pub struct DigestBatch {+ /// The user to send the digest to.+ pub user_id: MacroUserIdStr<'static>,+ /// The notifications to include in the digest.+ pub notifications: Vec<UserNotificationRow<TaggedContent<serde_json::Value>>>,+}++/// Result of attempting to claim a digest batch.+#[derive(Debug)]+pub enum ClaimResult {+ /// A digest batch is ready and was claimed.+ Ready(DigestBatch),+ /// No digests are pending.+ Empty,+ /// Digests are pending but none are ready yet. Contains duration until the next one is ready.+ Wait(Duration),+}++/// Trait for batching notifications into digests for delayed email delivery.+///+/// Implementations should handle:+/// - Adding notifications to a user's pending digest+/// - Scheduling when the digest should be sent+/// - Atomically claiming digests for processing to prevent duplicates+pub trait DigestBatcher: Send + Sync + 'static {+ /// Add a notification to a user's pending digest batch.+ ///+ /// If this is the first notification for the user, schedules the digest+ /// to be sent after `send_after` duration.+ fn add_to_digest(+ &self,+ notification: &UserNotificationRow<TaggedContent<serde_json::Value>>,+ send_after: Duration,+ ) -> impl Future<Output = Result<(), Report>> + Send;++ /// Claim and return one digest batch that is ready to be sent.+ ///+ /// Returns:+ /// - `ClaimResult::Ready(batch)` - a batch was claimed and is ready to send+ /// - `ClaimResult::Empty` - no digests are pending+ /// - `ClaimResult::Wait(duration)` - digests are pending but not ready; wait this long+ ///+ /// The claim is atomic - only one caller will receive a given user's digest+ /// even with concurrent workers.+ fn claim_ready_digest(&self) -> impl Future<Output = Result<ClaimResult, Report>> + Send;+}+/// trait for checking whether or not a user has push notifications enabledpub trait PushNotificationChecker: Send + Sync + 'static {/// does the user have push notifications enabled?@@ -28,3 +79,45 @@ pub trait LastOnlineChecker: Send + Sync + 'static {user: MacroUserIdStr<'a>,) -> impl Future<Output = Result<Duration, Report>> + Send;}++/// The id of a message that was send as a push notification to SNS+pub struct MessageId(pub String);++/// trait for storage a message_id associated with a user_notification PK+/// the user notification PK is (notification uuid, userid)+pub trait MessageReceiptRepo {+ /// create a record in the database which associates the PK message_id with the FK to user_notifications (user_id, notification_id)+ fn record_message_id(+ &self,+ message_id: MessageId,+ user_id: MacroUserIdStr<'_>,+ notification_id: Uuid,+ ) -> impl Future<Output = Result<(), Report>> + Send;++ /// given a message_id mark the row in the database as failed and then return the associated FK for the failed record+ fn mark_message_failed(+ &self,+ message_id: MessageId,+ ) -> impl Future<Output = Result<(MacroUserIdStr<'static>, Uuid), Report>> + Send;++ /// given the user_notification FK, check if all messages for this notification have failed+ fn did_all_messages_fail(+ &self,+ user_id: MacroUserIdStr<'_>,+ notification_id: Uuid,+ ) -> impl Future<Output = Result<bool, Report>> + Send;+}++/// trait which abstracts away the sending of a notification+pub trait NotificationSendChecker {+ /// the type returned when the notification was sent successfully+ type Ok;+ /// the error type of the request+ type Err;++ /// try to send the notification+ fn send_notification(self) -> impl Future<Output = Result<Self::Ok, Self::Err>> + Send;++ /// extract the message Id from the return value+ fn extract_message_id(res: &Self::Ok) -> MessageId;+}diff --git a/rust/cloud-storage/notification/src/domain/models/queue_message.rs b/rust/cloud-storage/notification/src/domain/models/queue_message.rsindex 69851eb3d7..15784acc74 100644--- a/rust/cloud-storage/notification/src/domain/models/queue_message.rs+++ b/rust/cloud-storage/notification/src/domain/models/queue_message.rs@@ -2,7 +2,9 @@use crate::domain::models::{Notification, RateLimitConfig, RateLimitKey, SendNotificationRequest, TaggedContent,- apple::APNSPushNotification, mobile::MessageAttributes,+ apple::APNSPushNotification,+ email_notification_digest::{BatchSend, PushNotificationsEnabled},+ mobile::MessageAttributes,};use chrono::{DateTime, Utc};use cowlike::CowLike;@@ -12,6 +14,9 @@ use serde::{Deserialize, Serialize};use thiserror::Error;use uuid::Uuid;+#[cfg(test)]+mod test;+/// APNS push notification targets.#[derive(Debug, Serialize, Deserialize)]pub struct APNSTargets<T> {@@ -21,6 +26,11 @@ pub struct APNSTargets<T> {pub attributes: MessageAttributes,/// The iOS device endpoints to deliver to.pub ios_device_endpoints: Vec<String>,+ /// if the state machine returned that the decision is incomplete+ /// then we pass the state of the machine into the queue such that it+ /// can be resumed on the egress side.+ #[serde(default)]+ pub bulk_digest_state_machine: Option<BatchSend<PushNotificationsEnabled>>,}/// Email notification payload.diff --git a/rust/cloud-storage/notification/src/domain/models/queue_message/test.rs b/rust/cloud-storage/notification/src/domain/models/queue_message/test.rsnew file mode 100644index 0000000000..6d229f2f28--- /dev/null+++ b/rust/cloud-storage/notification/src/domain/models/queue_message/test.rs@@ -0,0 +1,36 @@+use super::*;++#[test]+fn test_apns_targets_deserializes_old_format_without_bulk_digest_state_machine() {+ // Old format did not have the bulk_digest_state_machine field+ let old_json = r#"{+ "notif": {+ "aps": {+ "alert": {+ "title": "Test Title",+ "body": "Test Body"+ },+ "sound": "default"+ },+ "notificationId": "550e8400-e29b-41d4-a716-446655440000"+ },+ "attributes": {+ "push_type": "Alert",+ "collapse_key": "test-collapse-key"+ },+ "ios_device_endpoints": ["endpoint1", "endpoint2"]+ }"#;++ let result: Result<APNSTargets<serde_json::Value>, _> = serde_json::from_str(old_json);++ assert!(+ result.is_ok(),+ "Old JSON format without bulk_digest_state_machine should deserialize successfully: {:?}",+ result.err()+ );++ let targets = result.unwrap();+ assert!(targets.bulk_digest_state_machine.is_none());+ assert_eq!(targets.ios_device_endpoints.len(), 2);+ assert_eq!(targets.attributes.collapse_key, "test-collapse-key");+}diff --git a/rust/cloud-storage/notification/src/domain/service/egress.rs b/rust/cloud-storage/notification/src/domain/service/egress.rsindex b5b21eabbd..07a4ff687b 100644--- a/rust/cloud-storage/notification/src/domain/service/egress.rs+++ b/rust/cloud-storage/notification/src/domain/service/egress.rs@@ -3,6 +3,7 @@//! 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::queue_message::{ConnGatewayNotification, DeliveryFailure, DeliverySuccess, EmailNotification, Node,NotificationChannel, QueueMessage,@@ -69,13 +70,13 @@ where// Check rate limit if configuredif let Some((key, config)) = message.rate_limit {match self.rate_limiter.check_and_increment(key, config).await {- Ok(crate::domain::models::RateLimitResult::Exceeded(exceeded)) => {+ Ok(RateLimitResult::Exceeded(exceeded)) => {return vec![Err(report!(exceeded).context(DeliveryFailure::RateLimit))];}- Err(e) => return vec![Err(e.context(DeliveryFailure::RateLimit))],- Ok(_) => {+ Ok(RateLimitResult::Allowed { .. }) => {// Rate limit allowed, continue}+ Err(e) => return vec![Err(e.context(DeliveryFailure::Other))],}}diff --git a/rust/cloud-storage/notification/src/domain/service/ingress.rs b/rust/cloud-storage/notification/src/domain/service/ingress.rsindex b81f336124..4b956e8904 100644--- a/rust/cloud-storage/notification/src/domain/service/ingress.rs+++ b/rust/cloud-storage/notification/src/domain/service/ingress.rs@@ -176,6 +176,7 @@ wherecollapse_key,},ios_device_endpoints: ios_endpoints.clone(),+ bulk_digest_state_machine: None,})),on_failure: None,},@@ -424,6 +425,7 @@ wherenotif: apns_notif,attributes,ios_device_endpoints: ios_endpoints,+ bulk_digest_state_machine: None,})),on_failure: None,},diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rsindex b441dd7ac0..6cd6acb4d9 100644--- a/rust/cloud-storage/notification/src/domain/service/test.rs+++ b/rust/cloud-storage/notification/src/domain/service/test.rs@@ -1381,6 +1381,7 @@ async fn test_egress_ios_attempts_all_endpoints_even_if_some_fail() {endpoint3.to_string(),endpoint4.to_string(),],+ bulk_digest_state_machine: None,})),on_failure: None,},diff --git a/rust/cloud-storage/notification/src/outbound.rs b/rust/cloud-storage/notification/src/outbound.rsindex c2b244c0e4..e0b739e977 100644--- a/rust/cloud-storage/notification/src/outbound.rs+++ b/rust/cloud-storage/notification/src/outbound.rs@@ -3,7 +3,9 @@//! These modules contain implementations of the domain ports that connect//! to external services like Redis, PostgreSQL, WebSocket gateways, etc.+pub mod digest_batcher;pub mod email;+pub mod message_receipt_repository;pub mod mobile;pub mod push_notification_checker;pub mod queue;diff --git a/rust/cloud-storage/notification/src/outbound/digest_batcher.rs b/rust/cloud-storage/notification/src/outbound/digest_batcher.rsnew file mode 100644index 0000000000..d52b877c3e--- /dev/null+++ b/rust/cloud-storage/notification/src/outbound/digest_batcher.rs@@ -0,0 +1,139 @@+//! Redis-backed implementation of [DigestBatcher].++#[cfg(all(test, feature = "redis-tests"))]+mod test;++use crate::domain::models::email_notification_digest::ports::{+ ClaimResult, DigestBatch, DigestBatcher,+};+use crate::domain::models::{TaggedContent, UserNotificationRow};+use chrono::Utc;+use macro_user_id::user_id::MacroUserIdStr;+use redis::aio::MultiplexedConnection;+use redis::{AsyncCommands, SortedSetAddOptions};+use rootcause::Report;+use std::time::Duration;++/// Redis-backed implementation of [DigestBatcher].+///+/// Uses the following Redis keys:+/// - `digest:{user_id}` - List of serialized notifications pending for this user+/// - `digest_pending_users` - Sorted set of user IDs with score = send_at timestamp+///+/// ## Atomicity Strategy+///+/// To prevent race conditions where notifications arriving during processing could be lost,+/// we use the RENAME command to atomically snapshot the pending list:+///+/// 1. `ZPOPMIN` atomically claims a user (only one worker gets them)+/// 2. `RENAME digest:{user_id} digest_processing:{user_id}` atomically snapshots the list+/// 3. Any new notifications now go to a fresh `digest:{user_id}` list+/// 4. Process from `digest_processing:{user_id}` and delete when done+///+/// This ensures no notifications are lost even if new ones arrive during processing.+pub struct RedisDigestBatcher {+ conn: MultiplexedConnection,+}++impl RedisDigestBatcher {+ /// Create a new [RedisDigestBatcher] with the given Redis connection.+ pub fn new(conn: MultiplexedConnection) -> Self {+ Self { conn }+ }++ fn digest_key(user_id: &str) -> String {+ format!("digest:{user_id}")+ }++ fn processing_key(user_id: &str) -> String {+ format!("digest_processing:{user_id}")+ }+}++impl DigestBatcher for RedisDigestBatcher {+ async fn add_to_digest(+ &self,+ notification: &UserNotificationRow<TaggedContent<serde_json::Value>>,+ send_after: Duration,+ ) -> Result<(), Report> {+ let mut conn = self.conn.clone();+ let user_id_str = notification.owner_id.as_ref();+ let digest_key = Self::digest_key(user_id_str);++ let serialized = serde_json::to_string(notification)?;++ // Add notification to user's digest list+ conn.rpush::<_, _, ()>(&digest_key, &serialized).await?;++ // Schedule when to send - NX ensures we only set the time on first notification,+ // subsequent notifications don't push back the send time+ let send_at = Utc::now().timestamp() + send_after.as_secs() as i64;+ conn.zadd_options::<_, _, _, ()>(+ "digest_pending_users",+ user_id_str,+ send_at,+ &SortedSetAddOptions::add_only(),+ )+ .await?;++ Ok(())+ }++ async fn claim_ready_digest(&self) -> Result<ClaimResult, Report> {+ let mut conn = self.conn.clone();+ let now = Utc::now().timestamp();++ // Step 1: Atomically pop one user from the pending set+ // Only one worker will receive this user+ let result: Vec<(String, f64)> = conn.zpopmin("digest_pending_users", 1).await?;++ let Some((user_id_str, score)) = result.into_iter().next() else {+ return Ok(ClaimResult::Empty);+ };++ // Check if this digest is actually ready to send+ if score > now as f64 {+ // Not ready yet, put it back+ conn.zadd::<_, _, _, ()>("digest_pending_users", &user_id_str, score)+ .await?;++ // Return how long to wait until this digest is ready+ let wait_secs = (score as i64) - now;+ return Ok(ClaimResult::Wait(Duration::from_secs(wait_secs as u64)));+ }++ let digest_key = Self::digest_key(&user_id_str);+ let processing_key = Self::processing_key(&user_id_str);++ // Step 2: Atomically snapshot the list via RENAME+ // After this, any new notifications for this user go to a fresh digest:{user_id}+ // and won't be affected by our processing+ let rename_result: Result<(), redis::RedisError> =+ conn.rename(&digest_key, &processing_key).await;++ if rename_result.is_err() {+ // Key doesn't exist - digest was empty (shouldn't happen, but handle gracefully)+ return Ok(ClaimResult::Empty);+ }++ // Step 3: Read from the snapshot and clean up+ let items: Vec<String> = conn.lrange(&processing_key, 0, -1).await?;+ conn.del::<_, ()>(&processing_key).await?;++ if items.is_empty() {+ return Ok(ClaimResult::Empty);+ }++ let user_id = MacroUserIdStr::try_from(user_id_str)?;++ let notifications = items+ .into_iter()+ .filter_map(|s| serde_json::from_str(&s).ok())+ .collect();++ Ok(ClaimResult::Ready(DigestBatch {+ user_id,+ notifications,+ }))+ }+}diff --git a/rust/cloud-storage/notification/src/outbound/digest_batcher/test.rs b/rust/cloud-storage/notification/src/outbound/digest_batcher/test.rsnew file mode 100644index 0000000000..19f4c01988--- /dev/null+++ b/rust/cloud-storage/notification/src/outbound/digest_batcher/test.rs@@ -0,0 +1,307 @@+use super::*;+use crate::domain::models::{Notification, RateLimitConfig, RateLimitKey};+use model_entity::EntityType;+use redis::AsyncCommands;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++#[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+ }+}++async fn get_redis_connection() -> MultiplexedConnection {+ let redis_url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".into());+ let client = redis::Client::open(redis_url).expect("Failed to create Redis client");+ client+ .get_multiplexed_async_connection()+ .await+ .expect("Failed to connect to Redis")+}++async fn cleanup_redis(conn: &mut MultiplexedConnection, prefix: &str) {+ let keys: Vec<String> = redis::cmd("KEYS")+ .arg(format!("{}*", prefix))+ .query_async(conn)+ .await+ .unwrap_or_default();++ for key in keys {+ conn.del::<_, ()>(&key).await.unwrap();+ }++ conn.del::<_, ()>("digest_pending_users")+ .await+ .unwrap_or_default();+}++fn test_user(suffix: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(format!("macro|test_{}@example.com", suffix)).unwrap()+}++fn create_test_notification(+ user_id: MacroUserIdStr<'static>,+ message: &str,+) -> UserNotificationRow<TaggedContent<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: TaggedContent::new(notification).serialize(),+ sender_id: None,+ }+}++// #[tokio::test]+async fn test_add_to_digest_creates_pending_entry() {+ let mut conn = get_redis_connection().await;+ cleanup_redis(&mut conn, "digest:").await;++ let batcher = RedisDigestBatcher::new(conn.clone());+ let user = test_user("add_creates_entry");+ let notification = create_test_notification(user.clone(), "test message");++ batcher+ .add_to_digest(¬ification, Duration::from_secs(60))+ .await+ .expect("Failed to add to digest");++ // Verify the notification was added to the list+ let digest_key = format!("digest:{}", user.as_ref());+ let items: Vec<String> = conn.lrange(&digest_key, 0, -1).await.unwrap();+ assert_eq!(items.len(), 1);++ // Verify user was added to pending set+ let score: Option<f64> = conn+ .zscore("digest_pending_users", user.as_ref())+ .await+ .unwrap();+ assert!(score.is_some());++ cleanup_redis(&mut conn, "digest:").await;+}++// #[tokio::test]+async fn test_add_multiple_notifications_same_user() {+ let mut conn = get_redis_connection().await;+ cleanup_redis(&mut conn, "digest:").await;++ let batcher = RedisDigestBatcher::new(conn.clone());+ let user = test_user("multiple_same_user");++ let notif1 = create_test_notification(user.clone(), "message 1");+ let notif2 = create_test_notification(user.clone(), "message 2");+ let notif3 = create_test_notification(user.clone(), "message 3");++ batcher+ .add_to_digest(¬if1, Duration::from_secs(60))+ .await+ .unwrap();+ batcher+ .add_to_digest(¬if2, Duration::from_secs(60))+ .await+ .unwrap();+ batcher+ .add_to_digest(¬if3, Duration::from_secs(60))+ .await+ .unwrap();++ // Verify all notifications were added+ let digest_key = format!("digest:{}", user.as_ref());+ let items: Vec<String> = conn.lrange(&digest_key, 0, -1).await.unwrap();+ assert_eq!(items.len(), 3);++ // Verify user appears only once in pending set (NX semantics)+ let count: usize = conn.zcard("digest_pending_users").await.unwrap();+ assert_eq!(count, 1);++ cleanup_redis(&mut conn, "digest:").await;+}++// #[tokio::test]+async fn test_claim_ready_digest_returns_empty_when_none_pending() {+ let mut conn = get_redis_connection().await;+ cleanup_redis(&mut conn, "digest:").await;++ let batcher = RedisDigestBatcher::new(conn.clone());++ let result = batcher.claim_ready_digest().await.unwrap();+ assert!(matches!(result, ClaimResult::Empty));++ cleanup_redis(&mut conn, "digest:").await;+}++// #[tokio::test]+async fn test_claim_ready_digest_returns_wait_when_not_ready() {+ let mut conn = get_redis_connection().await;+ cleanup_redis(&mut conn, "digest:").await;++ let batcher = RedisDigestBatcher::new(conn.clone());+ let user = test_user("not_ready");+ let notification = create_test_notification(user.clone(), "test");++ // Add with 60 second delay+ batcher+ .add_to_digest(¬ification, Duration::from_secs(60))+ .await+ .unwrap();++ let result = batcher.claim_ready_digest().await.unwrap();++ match result {+ ClaimResult::Wait(duration) => {+ // Should be close to 60 seconds (allow some margin)+ assert!(duration.as_secs() >= 58 && duration.as_secs() <= 60);+ }+ other => panic!("Expected ClaimResult::Wait, got {:?}", other),+ }++ cleanup_redis(&mut conn, "digest:").await;+}++// #[tokio::test]+async fn test_claim_ready_digest_returns_batch_when_ready() {+ let mut conn = get_redis_connection().await;+ cleanup_redis(&mut conn, "digest:").await;++ let batcher = RedisDigestBatcher::new(conn.clone());+ let user = test_user("ready_batch");+ let notification = create_test_notification(user.clone(), "ready message");++ // Add with 0 second delay (immediately ready)+ batcher+ .add_to_digest(¬ification, Duration::from_secs(0))+ .await+ .unwrap();++ // Small delay to ensure the timestamp is in the past+ 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);+ }+ other => panic!("Expected ClaimResult::Ready, got {:?}", other),+ }++ // Verify the digest was cleaned up+ let digest_key = format!("digest:{}", user.as_ref());+ let items: Vec<String> = conn.lrange(&digest_key, 0, -1).await.unwrap();+ assert!(items.is_empty());++ // Verify user was removed from pending set+ let score: Option<f64> = conn+ .zscore("digest_pending_users", user.as_ref())+ .await+ .unwrap();+ assert!(score.is_none());++ cleanup_redis(&mut conn, "digest:").await;+}++// #[tokio::test]+async fn test_new_notifications_during_processing_not_lost() {+ let mut conn = get_redis_connection().await;+ cleanup_redis(&mut conn, "digest:").await;++ let batcher = RedisDigestBatcher::new(conn.clone());+ let user = test_user("during_processing");++ // Add first notification (immediately ready)+ let notif1 = create_test_notification(user.clone(), "first");+ batcher+ .add_to_digest(¬if1, Duration::from_secs(0))+ .await+ .unwrap();++ tokio::time::sleep(Duration::from_millis(100)).await;++ // Claim the digest+ let result = batcher.claim_ready_digest().await.unwrap();+ assert!(matches!(result, ClaimResult::Ready(_)));++ // Add another notification after the claim (simulating concurrent add)+ let notif2 = create_test_notification(user.clone(), "second");+ batcher+ .add_to_digest(¬if2, Duration::from_secs(0))+ .await+ .unwrap();++ tokio::time::sleep(Duration::from_millis(100)).await;++ // The second notification should be in a new batch+ let result2 = batcher.claim_ready_digest().await.unwrap();+ match result2 {+ ClaimResult::Ready(batch) => {+ assert_eq!(batch.notifications.len(), 1);+ }+ other => panic!("Expected second batch to be ready, got {:?}", other),+ }++ cleanup_redis(&mut conn, "digest:").await;+}++// #[tokio::test]+async fn test_multiple_users_independent() {+ let mut conn = get_redis_connection().await;+ cleanup_redis(&mut conn, "digest:").await;++ let batcher = RedisDigestBatcher::new(conn.clone());++ let user1 = test_user("multi_user_1");+ let user2 = test_user("multi_user_2");++ let notif1 = create_test_notification(user1.clone(), "user1 message");+ let notif2 = create_test_notification(user2.clone(), "user2 message");++ // Add notifications for both users+ batcher+ .add_to_digest(¬if1, Duration::from_secs(0))+ .await+ .unwrap();+ batcher+ .add_to_digest(¬if2, Duration::from_secs(0))+ .await+ .unwrap();++ tokio::time::sleep(Duration::from_millis(100)).await;++ // Claim both batches+ let result1 = batcher.claim_ready_digest().await.unwrap();+ let result2 = batcher.claim_ready_digest().await.unwrap();++ assert!(matches!(result1, ClaimResult::Ready(_)));+ assert!(matches!(result2, ClaimResult::Ready(_)));++ // Third claim should be empty+ let result3 = batcher.claim_ready_digest().await.unwrap();+ assert!(matches!(result3, ClaimResult::Empty));++ cleanup_redis(&mut conn, "digest:").await;+}diff --git a/rust/cloud-storage/notification/src/outbound/message_receipt_repository.rs b/rust/cloud-storage/notification/src/outbound/message_receipt_repository.rsnew file mode 100644index 0000000000..0962e5448b--- /dev/null+++ b/rust/cloud-storage/notification/src/outbound/message_receipt_repository.rs@@ -0,0 +1,107 @@+//! Database-backed implementation of [MessageReceiptRepo].+//!+//! This module provides a PostgreSQL adapter for tracking push notification+//! message delivery status and associating message IDs with user notifications.++#[cfg(test)]+mod test;++use crate::domain::models::email_notification_digest::ports::{MessageId, MessageReceiptRepo};+use macro_user_id::cowlike::CowLike;+use macro_user_id::user_id::MacroUserIdStr;+use rootcause::Report;+use sqlx::PgPool;+use uuid::Uuid;++/// Database-backed implementation of [MessageReceiptRepo].+///+/// Tracks push notification message IDs and their delivery status,+/// allowing the system to determine if all push notifications for+/// a user_notification have failed (triggering email fallback).+pub struct DbMessageReceiptRepository {+ db: PgPool,+}++impl DbMessageReceiptRepository {+ /// Create a new [DbMessageReceiptRepository] with the given database pool.+ pub fn new(db: PgPool) -> Self {+ Self { db }+ }+}++impl MessageReceiptRepo for DbMessageReceiptRepository {+ async fn record_message_id(+ &self,+ message_id: MessageId,+ user_id: MacroUserIdStr<'_>,+ notification_id: Uuid,+ ) -> Result<(), Report> {+ let user_id_str = user_id.to_string();++ sqlx::query!(+ r#"+ INSERT INTO notification_message_receipt (message_id, user_id, notification_id)+ VALUES ($1, $2, $3)+ ON CONFLICT (message_id) DO NOTHING+ "#,+ message_id.0.as_str(),+ user_id_str,+ notification_id+ )+ .execute(&self.db)+ .await?;++ Ok(())+ }++ async fn mark_message_failed(+ &self,+ message_id: MessageId,+ ) -> Result<(MacroUserIdStr<'static>, Uuid), Report> {+ let row = sqlx::query!(+ r#"+ UPDATE notification_message_receipt+ SET failed = true, failed_at = NOW()+ WHERE message_id = $1+ RETURNING user_id, notification_id+ "#,+ message_id.0.as_str()+ )+ .fetch_one(&self.db)+ .await?;++ let user_id = MacroUserIdStr::parse_from_str(&row.user_id)+ .map(CowLike::into_owned)+ .map_err(|e| rootcause::report!(e))?;++ Ok((user_id, row.notification_id))+ }++ async fn did_all_messages_fail(+ &self,+ user_id: MacroUserIdStr<'_>,+ notification_id: Uuid,+ ) -> Result<bool, Report> {+ let user_id_str = user_id.to_string();++ // Check if there are ANY non-failed messages for this user_notification+ // If none exist that are not failed, then all have failed+ let has_non_failed = sqlx::query_scalar!(+ r#"+ SELECT EXISTS(+ SELECT 1 FROM notification_message_receipt+ WHERE user_id = $1+ AND notification_id = $2+ AND failed = false+ ) as "exists!"+ "#,+ user_id_str,+ notification_id+ )+ .fetch_one(&self.db)+ .await?;++ // If no non-failed messages exist, all have failed+ Ok(!has_non_failed)+ }+}diff --git a/rust/cloud-storage/notification/src/outbound/message_receipt_repository/test.rs b/rust/cloud-storage/notification/src/outbound/message_receipt_repository/test.rsnew file mode 100644index 0000000000..aabb41b7b2--- /dev/null+++ b/rust/cloud-storage/notification/src/outbound/message_receipt_repository/test.rs@@ -0,0 +1,149 @@+use super::*;++use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::{Pool, Postgres};++fn test_user(email: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from_email(email).unwrap()+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("message_receipts"))+)]+async fn test_record_message_id(pool: Pool<Postgres>) {+ let repo = DbMessageReceiptRepository::new(pool.clone());+ let user = test_user("[email protected]");+ let notification_id = uuid::Uuid::parse_str("0193b1ea-c742-7589-893b-2b4a509c1e77").unwrap();++ let result = repo+ .record_message_id(MessageId("new-msg-1".to_string()), user, notification_id)+ .await;++ assert!(result.is_ok());++ // Verify insertion+ let row = sqlx::query!(+ "SELECT message_id FROM notification_message_receipt WHERE message_id = $1",+ "new-msg-1"+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(row.message_id, "new-msg-1");+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("message_receipts"))+)]+async fn test_record_message_id_idempotent(pool: Pool<Postgres>) {+ let repo = DbMessageReceiptRepository::new(pool.clone());+ let user = test_user("[email protected]");+ let notification_id = uuid::Uuid::parse_str("0193b1ea-c742-7589-893b-2b4a509c1e77").unwrap();++ // First insert+ repo.record_message_id(+ MessageId("idempotent-msg".to_string()),+ user.copied(),+ notification_id,+ )+ .await+ .unwrap();++ // Second insert with same message_id should not error+ let result = repo+ .record_message_id(+ MessageId("idempotent-msg".to_string()),+ user,+ notification_id,+ )+ .await;++ assert!(result.is_ok());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("message_receipts"))+)]+async fn test_mark_message_failed(pool: Pool<Postgres>) {+ let repo = DbMessageReceiptRepository::new(pool.clone());++ // msg-1 is inserted by fixture and not failed+ let (user_id, notification_id) = repo+ .mark_message_failed(MessageId("msg-1".to_string()))+ .await+ .unwrap();++ assert_eq!(user_id.email_part().as_ref(), "[email protected]");+ assert_eq!(+ notification_id,+ uuid::Uuid::parse_str("0193b1ea-c742-7589-893b-2b4a509c1e77").unwrap()+ );++ // Verify failed flag is set+ let row = sqlx::query!(+ "SELECT failed FROM notification_message_receipt WHERE message_id = $1",+ "msg-1"+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert!(row.failed);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("message_receipts"))+)]+async fn test_did_all_messages_fail_returns_false_when_some_not_failed(pool: Pool<Postgres>) {+ let repo = DbMessageReceiptRepository::new(pool);+ let user = test_user("[email protected]");+ let notification_id = uuid::Uuid::parse_str("0193b1ea-c742-7589-893b-2b4a509c1e77").unwrap();++ // Fixture has msg-1 (not failed) and msg-2 (failed)+ let result = repo+ .did_all_messages_fail(user, notification_id)+ .await+ .unwrap();++ assert!(!result);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("message_receipts"))+)]+async fn test_did_all_messages_fail_returns_true_when_all_failed(pool: Pool<Postgres>) {+ let repo = DbMessageReceiptRepository::new(pool);+ let user = test_user("[email protected]");+ let notification_id = uuid::Uuid::parse_str("0193b1ea-c742-7589-893b-2b4a509c1e77").unwrap();++ // Mark msg-1 as failed too (msg-2 is already failed in fixture)+ repo.mark_message_failed(MessageId("msg-1".to_string()))+ .await+ .unwrap();++ let result = repo+ .did_all_messages_fail(user, notification_id)+ .await+ .unwrap();++ assert!(result);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_did_all_messages_fail_returns_true_when_no_messages(pool: Pool<Postgres>) {+ let repo = DbMessageReceiptRepository::new(pool);+ let user = test_user("[email protected]");+ let notification_id = uuid::Uuid::new_v4();++ // No messages exist - should return true (vacuously all failed)+ let result = repo+ .did_all_messages_fail(user, notification_id)+ .await+ .unwrap();++ assert!(result);+}