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): integrate state machine c (#1674)

Sean Ayef558d75149cc
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 4ac841dc31..c66ce33320 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
@@ -649,3 +649,30 @@ where
Ok(StateMachineDecisionC::BatchWasQueued(BatchSend(())))
}
}
+
+/// Port for reconciling async SNS delivery failures with the digest batching system.
+///
+/// This abstracts [`StateMachineDriverC`] so callers only depend on the capability,
+/// not the specific implementation or its generic adapter parameters.
+pub trait BulkDigestFailureStateMachine: Send + Sync + 'static {
+ /// Mark a push notification message as failed and, if all pushes for that
+ /// user+notification have now failed, queue the notification for batch email digest.
+ fn mark_message_as_failed(
+ &self,
+ message_id: MessageId,
+ ) -> impl Future<Output = Result<StateMachineDecisionC, Report>> + Send;
+}
+
+impl<B, R, N> BulkDigestFailureStateMachine for StateMachineDriverC<B, R, N>
+where
+ B: DigestBatcher,
+ R: MessageReceiptRepo,
+ N: NotificationRepository,
+{
+ fn mark_message_as_failed(
+ &self,
+ message_id: MessageId,
+ ) -> impl Future<Output = Result<StateMachineDecisionC, Report>> + Send {
+ self.mark_message_as_failed(message_id)
+ }
+}
diff --git a/rust/cloud-storage/notification/src/domain/models/email_notification_digest/ports.rs b/rust/cloud-storage/notification/src/domain/models/email_notification_digest/ports.rs
index f470d9a109..e3427beb47 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
@@ -82,7 +82,7 @@ pub trait LastOnlineChecker: Send + Sync + 'static {
}
/// The id of a message that was send as a push notification to SNS
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Clone, Deserialize)]
#[serde(transparent)]
pub struct MessageId(pub String);
diff --git a/rust/cloud-storage/notification/src/domain/service/push_notification_event/mod.rs b/rust/cloud-storage/notification/src/domain/service/push_notification_event/mod.rs
index decfbe21e6..0df723b85f 100644
--- a/rust/cloud-storage/notification/src/domain/service/push_notification_event/mod.rs
+++ b/rust/cloud-storage/notification/src/domain/service/push_notification_event/mod.rs
@@ -7,6 +7,7 @@
#[cfg(test)]
mod test;
+use crate::domain::models::email_notification_digest::BulkDigestFailureStateMachine;
use crate::domain::models::push_notification_event::SnsPushNotificationEvent;
use crate::domain::ports::{DeviceRegistrationDeleter, SnsEndpointDeleter};
use rootcause::Report;
@@ -17,7 +18,8 @@ pub trait PushNotificationEventHandler: Send + Sync + 'static {
/// Handle a single push notification event.
///
/// Deletes the device from the DB. If the event is a `DeliveryFailure`,
- /// also deletes the SNS endpoint.
+ /// also deletes the SNS endpoint and records the failure in the digest
+ /// state machine.
fn handle_event(
&self,
event: &SnsPushNotificationEvent,
@@ -26,31 +28,35 @@ pub trait PushNotificationEventHandler: Send + Sync + 'static {
/// Service for handling SNS push notification platform events.
///
-/// Generic over the two outbound ports: device registration deletion (DB) and
-/// SNS endpoint deletion.
-pub struct PushNotificationEventService<D, S> {
+/// Generic over three outbound ports: device registration deletion (DB),
+/// SNS endpoint deletion, and digest failure state machine.
+pub struct PushNotificationEventService<D, S, F> {
device_deleter: D,
sns_deleter: S,
+ digest_failure_sm: F,
}
-impl<D, S> PushNotificationEventService<D, S>
+impl<D, S, F> PushNotificationEventService<D, S, F>
where
D: DeviceRegistrationDeleter,
S: SnsEndpointDeleter,
+ F: BulkDigestFailureStateMachine,
{
/// Create a new push notification event service.
- pub fn new(device_deleter: D, sns_deleter: S) -> Self {
+ pub fn new(device_deleter: D, sns_deleter: S, digest_failure_sm: F) -> Self {
Self {
device_deleter,
sns_deleter,
+ digest_failure_sm,
}
}
}
-impl<D, S> PushNotificationEventHandler for PushNotificationEventService<D, S>
+impl<D, S, F> PushNotificationEventHandler for PushNotificationEventService<D, S, F>
where
D: DeviceRegistrationDeleter,
S: SnsEndpointDeleter,
+ F: BulkDigestFailureStateMachine,
{
#[tracing::instrument(err, skip(self))]
async fn handle_event(&self, event: &SnsPushNotificationEvent) -> Result<(), Report> {
@@ -71,6 +77,14 @@ where
self.sns_deleter
.delete_endpoint(&event.endpoint_arn)
.await?;
+
+ self.digest_failure_sm
+ .mark_message_as_failed(event.message_id.clone())
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, "failed to record delivery failure in digest state machine");
+ })
+ .ok();
}
EventType::EndpointDeleted => {}
}
diff --git a/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs b/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs
index d8c5a437b8..07780465d7 100644
--- a/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs
@@ -1,5 +1,8 @@
use super::*;
use crate::domain::models::email_notification_digest::ports::MessageId;
+use crate::domain::models::email_notification_digest::{
+ BulkDigestFailureStateMachine, StateMachineDecisionC,
+};
use crate::domain::models::push_notification_event::{EventType, SnsPushNotificationEvent};
use crate::domain::ports::{DeviceRegistrationDeleter, SnsEndpointDeleter};
use rootcause::Report;
@@ -83,11 +86,51 @@ impl SnsEndpointDeleter for MockSnsDeleter {
}
}
+/// Mock digest failure state machine that tracks calls.
+struct MockDigestFailureStateMachine {
+ calls: Mutex<Vec<String>>,
+ should_fail: bool,
+}
+
+impl MockDigestFailureStateMachine {
+ fn new() -> Self {
+ Self {
+ calls: Mutex::new(Vec::new()),
+ should_fail: false,
+ }
+ }
+
+ fn failing() -> Self {
+ Self {
+ calls: Mutex::new(Vec::new()),
+ should_fail: true,
+ }
+ }
+
+ fn get_calls(&self) -> Vec<String> {
+ self.calls.lock().unwrap().clone()
+ }
+}
+
+impl BulkDigestFailureStateMachine for MockDigestFailureStateMachine {
+ async fn mark_message_as_failed(
+ &self,
+ message_id: MessageId,
+ ) -> Result<StateMachineDecisionC, Report> {
+ self.calls.lock().unwrap().push(message_id.0.clone());
+ if self.should_fail {
+ rootcause::bail!("mock digest failure state machine error");
+ }
+ Ok(StateMachineDecisionC::NoAction)
+ }
+}
+
#[tokio::test]
async fn test_delivery_failure_deletes_device_and_sns_endpoint() {
let device_deleter = MockDeviceDeleter::new();
let sns_deleter = MockSnsDeleter::new();
- let service = PushNotificationEventService::new(device_deleter, sns_deleter);
+ let digest_sm = MockDigestFailureStateMachine::new();
+ let service = PushNotificationEventService::new(device_deleter, sns_deleter, digest_sm);
let event = SnsPushNotificationEvent {
endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),
@@ -108,7 +151,8 @@ async fn test_delivery_failure_deletes_device_and_sns_endpoint() {
async fn test_endpoint_deleted_only_deletes_device() {
let device_deleter = MockDeviceDeleter::new();
let sns_deleter = MockSnsDeleter::new();
- let service = PushNotificationEventService::new(device_deleter, sns_deleter);
+ let digest_sm = MockDigestFailureStateMachine::new();
+ let service = PushNotificationEventService::new(device_deleter, sns_deleter, digest_sm);
let event = SnsPushNotificationEvent {
endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),
@@ -132,7 +176,8 @@ async fn test_endpoint_deleted_only_deletes_device() {
async fn test_device_deletion_failure_propagates_error() {
let device_deleter = MockDeviceDeleter::failing();
let sns_deleter = MockSnsDeleter::new();
- let service = PushNotificationEventService::new(device_deleter, sns_deleter);
+ let digest_sm = MockDigestFailureStateMachine::new();
+ let service = PushNotificationEventService::new(device_deleter, sns_deleter, digest_sm);
let event = SnsPushNotificationEvent {
endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),
@@ -154,7 +199,8 @@ async fn test_device_deletion_failure_propagates_error() {
async fn test_sns_deletion_failure_propagates_error() {
let device_deleter = MockDeviceDeleter::new();
let sns_deleter = MockSnsDeleter::failing();
- let service = PushNotificationEventService::new(device_deleter, sns_deleter);
+ let digest_sm = MockDigestFailureStateMachine::new();
+ let service = PushNotificationEventService::new(device_deleter, sns_deleter, digest_sm);
let event = SnsPushNotificationEvent {
endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),
@@ -171,3 +217,67 @@ async fn test_sns_deletion_failure_propagates_error() {
vec![event.endpoint_arn]
);
}
+
+#[tokio::test]
+async fn test_delivery_failure_calls_digest_state_machine() {
+ let device_deleter = MockDeviceDeleter::new();
+ let sns_deleter = MockSnsDeleter::new();
+ let digest_sm = MockDigestFailureStateMachine::new();
+ let service = PushNotificationEventService::new(device_deleter, sns_deleter, digest_sm);
+
+ let event = SnsPushNotificationEvent {
+ endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),
+ event_type: EventType::DeliveryFailure,
+ message_id: MessageId("msg-123".to_string()),
+ };
+
+ service.handle_event(&event).await.unwrap();
+
+ assert_eq!(service.digest_failure_sm.get_calls(), vec!["msg-123"]);
+}
+
+#[tokio::test]
+async fn test_endpoint_deleted_does_not_call_digest_state_machine() {
+ let device_deleter = MockDeviceDeleter::new();
+ let sns_deleter = MockSnsDeleter::new();
+ let digest_sm = MockDigestFailureStateMachine::new();
+ let service = PushNotificationEventService::new(device_deleter, sns_deleter, digest_sm);
+
+ let event = SnsPushNotificationEvent {
+ endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),
+ event_type: EventType::EndpointDeleted,
+ message_id: MessageId("msg-456".to_string()),
+ };
+
+ service.handle_event(&event).await.unwrap();
+
+ assert!(
+ service.digest_failure_sm.get_calls().is_empty(),
+ "digest state machine should not be called for EndpointDeleted events"
+ );
+}
+
+#[tokio::test]
+async fn test_digest_state_machine_failure_does_not_propagate() {
+ let device_deleter = MockDeviceDeleter::new();
+ let sns_deleter = MockSnsDeleter::new();
+ let digest_sm = MockDigestFailureStateMachine::failing();
+ let service = PushNotificationEventService::new(device_deleter, sns_deleter, digest_sm);
+
+ let event = SnsPushNotificationEvent {
+ endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),
+ event_type: EventType::DeliveryFailure,
+ message_id: MessageId("msg-789".to_string()),
+ };
+
+ let result = service.handle_event(&event).await;
+ assert!(result.is_ok(), "digest SM failure should not propagate");
+
+ assert_eq!(service.digest_failure_sm.get_calls(), vec!["msg-789"]);
+
+ assert_eq!(
+ service.device_deleter.get_deleted(),
+ vec![event.endpoint_arn.clone()]
+ );
+ assert_eq!(service.sns_deleter.get_deleted(), vec![event.endpoint_arn]);
+}
diff --git a/rust/cloud-storage/notification_service/src/main.rs b/rust/cloud-storage/notification_service/src/main.rs
index 9d6079091b..354bc56977 100644
--- a/rust/cloud-storage/notification_service/src/main.rs
+++ b/rust/cloud-storage/notification_service/src/main.rs
@@ -62,6 +62,10 @@ pub async fn main() -> anyhow::Result<()> {
.get_maybe_secret_value(config.environment, InternalApiSecretKey::new()?)
.await?;
+ let vars = config::Vars::new()?;
+ let redis_client =
+ redis::Client::open(vars.redis_uri.as_ref()).expect("failed to create redis client");
+
#[cfg(feature = "push_notification_event_handler")]
{
let device_deleter =
@@ -71,9 +75,30 @@ pub async fn main() -> anyhow::Result<()> {
let sns_deleter = ::notification::outbound::sns_endpoint::SnsEndpointDeletionAdapter::new(
aws_sdk_sns::Client::new(&aws_config),
);
+
+ let push_event_redis_conn = redis_client
+ .get_multiplexed_async_connection()
+ .await
+ .context("failed to get redis connection for push event digest state machine")?;
+
+ let digest_failure_sm =
+ ::notification::domain::models::email_notification_digest::StateMachineDriverC {
+ message_receipt_repo:
+ ::notification::outbound::message_receipt_repository::DbMessageReceiptRepository::new(
+ db.clone(),
+ ),
+ digest_batcher: ::notification::outbound::digest_batcher::RedisDigestBatcher::new(
+ push_event_redis_conn,
+ ),
+ notif_repo:
+ ::notification::outbound::repository::DbNotificationRepository::new(db.clone()),
+ digest_window: std::time::Duration::from_secs(30 * 60),
+ };
+
let event_service = ::notification::domain::service::PushNotificationEventService::new(
device_deleter,
sns_deleter,
+ digest_failure_sm,
);
let event_queue =
::notification::outbound::push_notification_event_queue::SqsPushNotificationEventQueue::new(
@@ -96,7 +121,6 @@ pub async fn main() -> anyhow::Result<()> {
JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client)
.await?;
- let vars = config::Vars::new()?;
let notification_repository =
::notification::outbound::repository::DbNotificationRepository::new(db.clone());
@@ -127,8 +151,6 @@ pub async fn main() -> anyhow::Result<()> {
let ses_client = aws_sdk_sesv2::Client::new(&aws_config);
let email_adapter = EmailAdapter::new(ses_client, config.sender_base_address.clone());
- let redis_client =
- redis::Client::open(vars.redis_uri.as_ref()).expect("failed to create redis client");
let redis_multiplexed_conn = redis_client
.get_multiplexed_async_connection()
.await