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
feat(notif): refactor sns event queue into hex (#1611)
Sean Ayef1462670d08a
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 900e2a110f..65f03e9e40 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -6248,7 +6248,6 @@ dependencies = ["axum","chrono","email_validator",- "futures","http-body-util","macro_auth","macro_aws_config",@@ -6279,7 +6278,6 @@ dependencies = ["ses_client","sns_client","sqlx",- "sqs_worker","thiserror 2.0.17","tokio","tower 0.5.2",diff --git a/rust/cloud-storage/notification/.sqlx/query-06a72bfcfbcc5f5bbed6cd093436309607f9375d2ba7b151e9dc1a8493f88e44.json b/rust/cloud-storage/notification/.sqlx/query-06a72bfcfbcc5f5bbed6cd093436309607f9375d2ba7b151e9dc1a8493f88e44.jsonnew file mode 100644index 0000000000..4c5afc274a--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-06a72bfcfbcc5f5bbed6cd093436309607f9375d2ba7b151e9dc1a8493f88e44.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM notification_user_device_registration\n WHERE device_endpoint = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "06a72bfcfbcc5f5bbed6cd093436309607f9375d2ba7b151e9dc1a8493f88e44"+}diff --git a/rust/cloud-storage/notification/src/domain/models.rs b/rust/cloud-storage/notification/src/domain/models.rsindex 1f3ac9dfc6..793e19e755 100644--- a/rust/cloud-storage/notification/src/domain/models.rs+++ b/rust/cloud-storage/notification/src/domain/models.rs@@ -10,6 +10,7 @@ pub mod apple;pub mod email_notification_digest;pub mod mobile;+pub mod push_notification_event;pub mod queue_message;pub mod rate_limit;pub mod recipient;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 bf1f2e7f07..f470d9a109 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,7 @@use crate::domain::models::{TaggedContent, UserNotificationRow};use macro_user_id::user_id::MacroUserIdStr;use rootcause::Report;+use serde::Deserialize;use std::time::Duration;use uuid::Uuid;@@ -81,7 +82,8 @@ pub trait LastOnlineChecker: Send + Sync + 'static {}/// The id of a message that was send as a push notification to SNS-#[derive(Debug)]+#[derive(Debug, Deserialize)]+#[serde(transparent)]pub struct MessageId(pub String);/// trait for storage a message_id associated with a user_notification PKdiff --git a/rust/cloud-storage/notification/src/domain/models/push_notification_event.rs b/rust/cloud-storage/notification/src/domain/models/push_notification_event.rsnew file mode 100644index 0000000000..0fa6c76e93--- /dev/null+++ b/rust/cloud-storage/notification/src/domain/models/push_notification_event.rs@@ -0,0 +1,38 @@+//! Domain models for SNS push notification platform events.+//!+//! These events are published by AWS SNS when push notification delivery fails+//! or when a platform endpoint is deleted.++use crate::domain::models::email_notification_digest::ports::MessageId;++/// The type of SNS push notification platform event.+#[derive(Debug, serde::Deserialize)]+pub enum EventType {+ /// A push notification delivery failed.+ #[serde(rename = "DeliveryFailure")]+ DeliveryFailure,+ /// An SNS platform endpoint was deleted.+ #[serde(rename = "EndpointDeleted")]+ EndpointDeleted,+}++/// An SNS push notification platform event received from the event queue.+#[derive(Debug, serde::Deserialize)]+#[serde(rename_all = "PascalCase")]+pub struct SnsPushNotificationEvent {+ /// The ARN of the SNS platform endpoint.+ pub endpoint_arn: String,+ /// The type of event that occurred.+ pub event_type: EventType,+ /// the SNS message unique identifier+ pub message_id: MessageId,+}++/// A raw push notification event message received from the queue.+#[derive(Debug)]+pub struct RawPushNotificationEventMessage {+ /// The message body as a raw string.+ pub body: Option<String>,+ /// The receipt handle for deleting the message from the queue.+ pub receipt_handle: Option<String>,+}diff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rsindex 1150bd504a..d8659194e9 100644--- a/rust/cloud-storage/notification/src/domain/ports.rs+++ b/rust/cloud-storage/notification/src/domain/ports.rs@@ -189,6 +189,7 @@ pub trait EmailSender: Send + Sync + 'static {) -> impl Future<Output = Result<(), Report>> + Send;}+use crate::domain::models::push_notification_event::RawPushNotificationEventMessage;use crate::domain::models::queue_message::{DeliverySuccess, QueueMessage, RawQueueMessage};/// Port for publishing notifications to delivery queue and receiving them.@@ -222,3 +223,35 @@ pub trait NotificationEgress: Send + Sync + 'static {fn poll_and_deliver(&self)-> impl Future<Output = Vec<Result<DeliverySuccess, Report>>> + Send;}++/// Port for deleting a device registration from the database by its SNS endpoint ARN.+pub trait DeviceRegistrationDeleter: Send + Sync + 'static {+ /// Delete a device registration by its endpoint ARN.+ fn delete_device_by_endpoint(+ &self,+ endpoint_arn: &str,+ ) -> impl Future<Output = Result<(), Report>> + Send;+}++/// Port for deleting an SNS platform endpoint.+pub trait SnsEndpointDeleter: Send + Sync + 'static {+ /// Delete an SNS platform endpoint by its ARN.+ fn delete_endpoint(+ &self,+ endpoint_arn: &str,+ ) -> impl Future<Output = Result<(), Report>> + Send;+}++/// Port for receiving and acknowledging push notification event messages from a queue.+pub trait PushNotificationEventQueue: Send + Sync + 'static {+ /// Receive a batch of raw push notification event messages from the queue.+ fn receive_messages(+ &self,+ ) -> impl Future<Output = Result<Vec<RawPushNotificationEventMessage>, Report>> + Send;++ /// Delete a message from the queue after successful processing.+ fn delete_message(+ &self,+ receipt_handle: &str,+ ) -> impl Future<Output = Result<(), Report>> + Send;+}diff --git a/rust/cloud-storage/notification/src/domain/service.rs b/rust/cloud-storage/notification/src/domain/service.rsindex e7c7846eed..4992aaf989 100644--- a/rust/cloud-storage/notification/src/domain/service.rs+++ b/rust/cloud-storage/notification/src/domain/service.rs@@ -6,6 +6,7 @@mod egress;mod ingress;+mod push_notification_event;#[cfg(test)]mod test;@@ -16,6 +17,8 @@ pub use ingress::NotificationIngress;pub use ingress::NotificationIngressService;pub use ingress::NotificationReader;pub use ingress::NotificationReaderService;+pub use push_notification_event::PushNotificationEventHandler;+pub use push_notification_event::PushNotificationEventService;/// Error returned when sending a notification fails.#[derive(Debug, Error)]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.rsnew file mode 100644index 0000000000..decfbe21e6--- /dev/null+++ b/rust/cloud-storage/notification/src/domain/service/push_notification_event/mod.rs@@ -0,0 +1,80 @@+//! Service for handling SNS push notification platform events.+//!+//! When an SNS push notification fails delivery or an endpoint is deleted,+//! this service deletes the device registration from the database and+//! optionally removes the SNS endpoint.++#[cfg(test)]+mod test;++use crate::domain::models::push_notification_event::SnsPushNotificationEvent;+use crate::domain::ports::{DeviceRegistrationDeleter, SnsEndpointDeleter};+use rootcause::Report;+use std::future::Future;++/// Trait for handling push notification platform events.+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.+ fn handle_event(+ &self,+ event: &SnsPushNotificationEvent,+ ) -> impl Future<Output = Result<(), Report>> + Send;+}++/// 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> {+ device_deleter: D,+ sns_deleter: S,+}++impl<D, S> PushNotificationEventService<D, S>+where+ D: DeviceRegistrationDeleter,+ S: SnsEndpointDeleter,+{+ /// Create a new push notification event service.+ pub fn new(device_deleter: D, sns_deleter: S) -> Self {+ Self {+ device_deleter,+ sns_deleter,+ }+ }+}++impl<D, S> PushNotificationEventHandler for PushNotificationEventService<D, S>+where+ D: DeviceRegistrationDeleter,+ S: SnsEndpointDeleter,+{+ #[tracing::instrument(err, skip(self))]+ async fn handle_event(&self, event: &SnsPushNotificationEvent) -> Result<(), Report> {+ use crate::domain::models::push_notification_event::EventType;++ tracing::info!(+ device_endpoint = event.endpoint_arn,+ event_type = ?event.event_type,+ "deleting endpoint"+ );++ self.device_deleter+ .delete_device_by_endpoint(&event.endpoint_arn)+ .await?;++ match event.event_type {+ EventType::DeliveryFailure => {+ self.sns_deleter+ .delete_endpoint(&event.endpoint_arn)+ .await?;+ }+ EventType::EndpointDeleted => {}+ }++ Ok(())+ }+}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.rsnew file mode 100644index 0000000000..d8c5a437b8--- /dev/null+++ b/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs@@ -0,0 +1,173 @@+use super::*;+use crate::domain::models::email_notification_digest::ports::MessageId;+use crate::domain::models::push_notification_event::{EventType, SnsPushNotificationEvent};+use crate::domain::ports::{DeviceRegistrationDeleter, SnsEndpointDeleter};+use rootcause::Report;+use std::sync::Mutex;++/// Mock device registration deleter that tracks calls.+struct MockDeviceDeleter {+ deleted_endpoints: Mutex<Vec<String>>,+ should_fail: bool,+}++impl MockDeviceDeleter {+ fn new() -> Self {+ Self {+ deleted_endpoints: Mutex::new(Vec::new()),+ should_fail: false,+ }+ }++ fn failing() -> Self {+ Self {+ deleted_endpoints: Mutex::new(Vec::new()),+ should_fail: true,+ }+ }++ fn get_deleted(&self) -> Vec<String> {+ self.deleted_endpoints.lock().unwrap().clone()+ }+}++impl DeviceRegistrationDeleter for MockDeviceDeleter {+ async fn delete_device_by_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {+ self.deleted_endpoints+ .lock()+ .unwrap()+ .push(endpoint_arn.to_string());+ if self.should_fail {+ rootcause::bail!("mock device deletion failure");+ }+ Ok(())+ }+}++/// Mock SNS endpoint deleter that tracks calls.+struct MockSnsDeleter {+ deleted_endpoints: Mutex<Vec<String>>,+ should_fail: bool,+}++impl MockSnsDeleter {+ fn new() -> Self {+ Self {+ deleted_endpoints: Mutex::new(Vec::new()),+ should_fail: false,+ }+ }++ fn failing() -> Self {+ Self {+ deleted_endpoints: Mutex::new(Vec::new()),+ should_fail: true,+ }+ }++ fn get_deleted(&self) -> Vec<String> {+ self.deleted_endpoints.lock().unwrap().clone()+ }+}++impl SnsEndpointDeleter for MockSnsDeleter {+ async fn delete_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {+ self.deleted_endpoints+ .lock()+ .unwrap()+ .push(endpoint_arn.to_string());+ if self.should_fail {+ rootcause::bail!("mock SNS deletion failure");+ }+ Ok(())+ }+}++#[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 event = SnsPushNotificationEvent {+ endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),+ event_type: EventType::DeliveryFailure,+ message_id: MessageId(String::new()),+ };++ service.handle_event(&event).await.unwrap();++ assert_eq!(+ service.device_deleter.get_deleted(),+ vec![event.endpoint_arn.clone()]+ );+ assert_eq!(service.sns_deleter.get_deleted(), vec![event.endpoint_arn]);+}++#[tokio::test]+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 event = SnsPushNotificationEvent {+ endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),+ event_type: EventType::EndpointDeleted,+ message_id: MessageId(String::new()),+ };++ service.handle_event(&event).await.unwrap();++ assert_eq!(+ service.device_deleter.get_deleted(),+ vec![event.endpoint_arn]+ );+ assert!(+ service.sns_deleter.get_deleted().is_empty(),+ "SNS endpoint should not be deleted for EndpointDeleted events"+ );+}++#[tokio::test]+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 event = SnsPushNotificationEvent {+ endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),+ event_type: EventType::DeliveryFailure,+ message_id: MessageId(String::new()),+ };++ let result = service.handle_event(&event).await;+ assert!(result.is_err());++ // SNS deletion should not be attempted when DB deletion fails+ assert!(+ service.sns_deleter.get_deleted().is_empty(),+ "SNS endpoint should not be deleted when device deletion fails"+ );+}++#[tokio::test]+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 event = SnsPushNotificationEvent {+ endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),+ event_type: EventType::DeliveryFailure,+ message_id: MessageId(String::new()),+ };++ let result = service.handle_event(&event).await;+ assert!(result.is_err());++ // Device should still have been deleted before the SNS failure+ assert_eq!(+ service.device_deleter.get_deleted(),+ vec![event.endpoint_arn]+ );+}diff --git a/rust/cloud-storage/notification/src/inbound.rs b/rust/cloud-storage/notification/src/inbound.rsindex c39b6d0396..29c492e62e 100644--- a/rust/cloud-storage/notification/src/inbound.rs+++ b/rust/cloud-storage/notification/src/inbound.rs@@ -2,4 +2,5 @@pub mod ai_tool;#[cfg(feature = "axum")]pub mod http;+pub mod push_notification_event_worker;pub mod worker;diff --git a/rust/cloud-storage/notification/src/inbound/push_notification_event_worker.rs b/rust/cloud-storage/notification/src/inbound/push_notification_event_worker.rsnew file mode 100644index 0000000000..adb7edbb41--- /dev/null+++ b/rust/cloud-storage/notification/src/inbound/push_notification_event_worker.rs@@ -0,0 +1,81 @@+//! Worker for processing SNS push notification platform events.+//!+//! This module handles events like delivery failures and endpoint deletions+//! by polling an SQS queue and delegating to the push notification event service.++use crate::domain::models::push_notification_event::SnsPushNotificationEvent;+use crate::domain::ports::PushNotificationEventQueue;+use crate::domain::service::PushNotificationEventHandler;++#[cfg(test)]+mod test;++/// Worker that processes push notification platform events from a queue.+///+/// This is a thin wrapper that runs the poll loop continuously,+/// deserializing messages and delegating to a [`PushNotificationEventHandler`].+pub struct PushNotificationEventWorker<S, Q> {+ service: S,+ queue: Q,+}++impl<S, Q> PushNotificationEventWorker<S, Q>+where+ S: PushNotificationEventHandler,+ Q: PushNotificationEventQueue,+{+ /// Create a new push notification event worker.+ pub fn new(service: S, queue: Q) -> Self {+ Self { service, queue }+ }++ /// Run the worker loop continuously.+ ///+ /// This method runs forever, polling the queue and processing messages.+ /// Errors on individual messages are logged but do not stop the worker.+ pub async fn run(&self) -> ! {+ tracing::info!("starting push notification event worker");+ loop {+ if let Ok(messages) = self.queue.receive_messages().await {+ if messages.is_empty() {+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;+ continue;+ }++ self.process_messages(&messages).await;+ }+ }+ }++ /// Process a batch of raw messages from the queue.+ ///+ /// For each message: deserializes the body, calls the service, and deletes+ /// the message from the queue on success. Errors are logged per-message.+ async fn process_messages(+ &self,+ messages: &[crate::domain::models::push_notification_event::RawPushNotificationEventMessage],+ ) {+ for message in messages {+ let Some(body) = message.body.as_ref() else {+ tracing::warn!("received message with no body, skipping");+ continue;+ };++ let event: SnsPushNotificationEvent = match serde_json::from_str(body) {+ Ok(event) => event,+ Err(e) => {+ tracing::error!(error=?e, "failed to deserialize push notification event");+ continue;+ }+ };++ if self.service.handle_event(&event).await.is_err() {+ continue;+ }++ if let Some(receipt_handle) = message.receipt_handle.as_ref() {+ let _ = self.queue.delete_message(receipt_handle).await;+ }+ }+ }+}diff --git a/rust/cloud-storage/notification/src/inbound/push_notification_event_worker/test.rs b/rust/cloud-storage/notification/src/inbound/push_notification_event_worker/test.rsnew file mode 100644index 0000000000..2c916a4508--- /dev/null+++ b/rust/cloud-storage/notification/src/inbound/push_notification_event_worker/test.rs@@ -0,0 +1,94 @@+use super::*;+use crate::domain::models::push_notification_event::{+ RawPushNotificationEventMessage, SnsPushNotificationEvent,+};+use crate::domain::ports::PushNotificationEventQueue;+use crate::domain::service::PushNotificationEventHandler;+use rootcause::Report;+use std::sync::Mutex;++struct MockHandler {+ should_fail: bool,+}++impl PushNotificationEventHandler for MockHandler {+ async fn handle_event(&self, _event: &SnsPushNotificationEvent) -> Result<(), Report> {+ if self.should_fail {+ rootcause::bail!("mock handler failure");+ }+ Ok(())+ }+}++struct MockQueue {+ deleted_receipts: Mutex<Vec<String>>,+}++impl MockQueue {+ fn new() -> Self {+ Self {+ deleted_receipts: Mutex::new(Vec::new()),+ }+ }++ fn get_deleted_receipts(&self) -> Vec<String> {+ self.deleted_receipts.lock().unwrap().clone()+ }+}++impl PushNotificationEventQueue for MockQueue {+ async fn receive_messages(&self) -> Result<Vec<RawPushNotificationEventMessage>, Report> {+ Ok(Vec::new())+ }++ async fn delete_message(&self, receipt_handle: &str) -> Result<(), Report> {+ self.deleted_receipts+ .lock()+ .unwrap()+ .push(receipt_handle.to_string());+ Ok(())+ }+}++fn make_valid_message(receipt_handle: &str) -> RawPushNotificationEventMessage {+ let body = serde_json::json!({+ "EndpointArn": "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1",+ "EventType": "DeliveryFailure",+ "MessageId": "test-message-id"+ });+ RawPushNotificationEventMessage {+ body: Some(body.to_string()),+ receipt_handle: Some(receipt_handle.to_string()),+ }+}++#[tokio::test]+async fn test_deletes_queue_message_on_success() {+ let handler = MockHandler { should_fail: false };+ let queue = MockQueue::new();+ let worker = PushNotificationEventWorker::new(handler, queue);++ let messages = vec![make_valid_message("receipt-1")];+ worker.process_messages(&messages).await;++ assert_eq!(+ worker.queue.get_deleted_receipts(),+ vec!["receipt-1"],+ "should delete the queue message after successful handling"+ );+}++#[tokio::test]+async fn test_does_not_delete_queue_message_on_handler_error() {+ let handler = MockHandler { should_fail: true };+ let queue = MockQueue::new();+ let worker = PushNotificationEventWorker::new(handler, queue);++ let messages = vec![make_valid_message("receipt-1")];+ worker.process_messages(&messages).await;++ assert!(+ worker.queue.get_deleted_receipts().is_empty(),+ "should not delete the queue message when handling fails"+ );+}diff --git a/rust/cloud-storage/notification/src/outbound.rs b/rust/cloud-storage/notification/src/outbound.rsindex e984f4d1b2..b56e4a7b0b 100644--- a/rust/cloud-storage/notification/src/outbound.rs+++ b/rust/cloud-storage/notification/src/outbound.rs@@ -3,14 +3,17 @@//! These modules contain implementations of the domain ports that connect//! to external services like Redis, PostgreSQL, WebSocket gateways, etc.+pub mod device_registration;pub mod digest_batcher;pub mod email;pub mod last_online_checker;pub mod message_receipt_repository;pub mod mobile;pub mod push_notification_checker;+pub mod push_notification_event_queue;pub mod queue;pub mod rate_limit;pub mod repository;+pub mod sns_endpoint;pub mod user_existence_checker;pub mod websocket;diff --git a/rust/cloud-storage/notification/src/outbound/device_registration.rs b/rust/cloud-storage/notification/src/outbound/device_registration.rsnew file mode 100644index 0000000000..943c0c0de5--- /dev/null+++ b/rust/cloud-storage/notification/src/outbound/device_registration.rs@@ -0,0 +1,51 @@+//! Database adapter for deleting device registrations.++use crate::domain::ports::DeviceRegistrationDeleter;+use rootcause::Report;+use sqlx::PgPool;++/// Trait for device registration database operations.+///+/// This allows the adapter to work with different database client implementations.+pub trait DeviceRegistrationDbOps: Send + Sync + 'static {+ /// Delete a device registration by its SNS endpoint ARN.+ fn delete_by_endpoint(+ &self,+ endpoint_arn: &str,+ ) -> impl std::future::Future<Output = Result<(), Report>> + Send;+}++impl DeviceRegistrationDbOps for PgPool {+ async fn delete_by_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {+ sqlx::query!(+ r#"+ DELETE FROM notification_user_device_registration+ WHERE device_endpoint = $1+ "#,+ endpoint_arn+ )+ .execute(self)+ .await?;++ Ok(())+ }+}++/// Database-backed adapter for deleting device registrations.+pub struct DbDeviceRegistrationDeleter<D> {+ db: D,+}++impl<D> DbDeviceRegistrationDeleter<D> {+ /// Create a new database device registration deleter.+ pub fn new(db: D) -> Self {+ Self { db }+ }+}++impl<D: DeviceRegistrationDbOps> DeviceRegistrationDeleter for DbDeviceRegistrationDeleter<D> {+ #[tracing::instrument(err, skip(self))]+ async fn delete_device_by_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {+ self.db.delete_by_endpoint(endpoint_arn).await+ }+}diff --git a/rust/cloud-storage/notification/src/outbound/push_notification_event_queue.rs b/rust/cloud-storage/notification/src/outbound/push_notification_event_queue.rsnew file mode 100644index 0000000000..a66a271893--- /dev/null+++ b/rust/cloud-storage/notification/src/outbound/push_notification_event_queue.rs@@ -0,0 +1,68 @@+//! SQS adapter for receiving push notification event messages.++use crate::domain::models::push_notification_event::RawPushNotificationEventMessage;+use crate::domain::ports::PushNotificationEventQueue;+use rootcause::Report;++/// SQS-backed queue for receiving push notification platform events.+pub struct SqsPushNotificationEventQueue {+ client: aws_sdk_sqs::Client,+ queue_url: String,+ max_messages: i32,+ wait_time_seconds: i32,+}++impl SqsPushNotificationEventQueue {+ /// Create a new SQS push notification event queue.+ pub fn new(+ client: aws_sdk_sqs::Client,+ queue_url: String,+ max_messages: i32,+ wait_time_seconds: i32,+ ) -> Self {+ Self {+ client,+ queue_url,+ max_messages,+ wait_time_seconds,+ }+ }+}++impl PushNotificationEventQueue for SqsPushNotificationEventQueue {+ #[tracing::instrument(err, skip(self))]+ async fn receive_messages(&self) -> Result<Vec<RawPushNotificationEventMessage>, Report> {+ let output = self+ .client+ .receive_message()+ .queue_url(&self.queue_url)+ .max_number_of_messages(self.max_messages)+ .wait_time_seconds(self.wait_time_seconds)+ .send()+ .await?;++ let messages = output+ .messages+ .unwrap_or_default()+ .into_iter()+ .map(|m| RawPushNotificationEventMessage {+ body: m.body,+ receipt_handle: m.receipt_handle,+ })+ .collect();++ Ok(messages)+ }++ #[tracing::instrument(err, skip(self))]+ async fn delete_message(&self, receipt_handle: &str) -> Result<(), Report> {+ self.client+ .delete_message()+ .queue_url(&self.queue_url)+ .receipt_handle(receipt_handle)+ .send()+ .await?;++ Ok(())+ }+}diff --git a/rust/cloud-storage/notification/src/outbound/sns_endpoint.rs b/rust/cloud-storage/notification/src/outbound/sns_endpoint.rsnew file mode 100644index 0000000000..3381b66f8c--- /dev/null+++ b/rust/cloud-storage/notification/src/outbound/sns_endpoint.rs@@ -0,0 +1,45 @@+//! SNS adapter for deleting platform endpoints.++use crate::domain::ports::SnsEndpointDeleter;+use rootcause::Report;++/// Trait for SNS endpoint operations.+///+/// This allows the adapter to work with different SNS client implementations.+pub trait SnsEndpointOps: Send + Sync + 'static {+ /// Delete an SNS platform endpoint by its ARN.+ fn delete_endpoint(+ &self,+ endpoint_arn: &str,+ ) -> impl std::future::Future<Output = Result<(), Report>> + Send;+}++impl SnsEndpointOps for aws_sdk_sns::Client {+ async fn delete_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {+ self.delete_endpoint()+ .endpoint_arn(endpoint_arn)+ .send()+ .await?;++ Ok(())+ }+}++/// SNS adapter for deleting platform endpoints.+pub struct SnsEndpointDeletionAdapter<S> {+ sns: S,+}++impl<S> SnsEndpointDeletionAdapter<S> {+ /// Create a new SNS endpoint deletion adapter.+ pub fn new(sns: S) -> Self {+ Self { sns }+ }+}++impl<S: SnsEndpointOps> SnsEndpointDeleter for SnsEndpointDeletionAdapter<S> {+ #[tracing::instrument(err, skip(self))]+ async fn delete_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {+ self.sns.delete_endpoint(endpoint_arn).await+ }+}diff --git a/rust/cloud-storage/notification_service/Cargo.toml b/rust/cloud-storage/notification_service/Cargo.tomlindex e0b1f46bac..17bc32838d 100644--- a/rust/cloud-storage/notification_service/Cargo.toml+++ b/rust/cloud-storage/notification_service/Cargo.toml@@ -27,7 +27,6 @@ aws-sdk-sqs = { workspace = true }axum = { workspace = true }chrono = { workspace = true }email_validator = { path = "../email_validator" }-futures = { workspace = true }http-body-util = { workspace = true }macro_auth = { path = "../macro_auth" }macro_aws_config = { path = "../macro_aws_config" }@@ -60,7 +59,6 @@ serde_json = { workspace = true }ses_client = { path = "../ses_client" }sns_client = { path = "../sns_client" }sqlx = { workspace = true }-sqs_worker = { path = "../sqs_worker" }thiserror = { workspace = true }tokio = { workspace = true }tower = { workspace = true }diff --git a/rust/cloud-storage/notification_service/src/main.rs b/rust/cloud-storage/notification_service/src/main.rsindex 7249f2acb2..9d6079091b 100644--- a/rust/cloud-storage/notification_service/src/main.rs+++ b/rust/cloud-storage/notification_service/src/main.rs@@ -21,7 +21,6 @@ mod config;mod env;mod model;mod notification;-mod push_notification_event;#[allow(dead_code)]mod templates;@@ -63,27 +62,32 @@ pub async fn main() -> anyhow::Result<()> {.get_maybe_secret_value(config.environment, InternalApiSecretKey::new()?).await?;- let push_notification_event_handler_worker = sqs_worker::SQSWorker::new(- aws_sdk_sqs::Client::new(&aws_config),- config.push_notification_event_handler_queue.clone(),- config.notification_queue_max_messages,- config.notification_queue_wait_time_seconds,- );-- let sns_client = sns_client::SNS::new(aws_sdk_sns::Client::new(&aws_config));-#[cfg(feature = "push_notification_event_handler")]{- let db = db.clone();- let sns_client = sns_client.clone();- tokio::spawn(async move {- push_notification_event::run_push_notification_event_worker(- db,- sns_client,- push_notification_event_handler_worker,- )- .await- });+ let device_deleter =+ ::notification::outbound::device_registration::DbDeviceRegistrationDeleter::new(+ db.clone(),+ );+ let sns_deleter = ::notification::outbound::sns_endpoint::SnsEndpointDeletionAdapter::new(+ aws_sdk_sns::Client::new(&aws_config),+ );+ let event_service = ::notification::domain::service::PushNotificationEventService::new(+ device_deleter,+ sns_deleter,+ );+ let event_queue =+ ::notification::outbound::push_notification_event_queue::SqsPushNotificationEventQueue::new(+ aws_sdk_sqs::Client::new(&aws_config),+ config.push_notification_event_handler_queue.clone(),+ config.notification_queue_max_messages,+ config.notification_queue_wait_time_seconds,+ );+ let event_worker =+ ::notification::inbound::push_notification_event_worker::PushNotificationEventWorker::new(+ event_service,+ event_queue,+ );+ tokio::spawn(async move { event_worker.run().await });}let sns_client = sns_client::SNS::new(aws_sdk_sns::Client::new(&aws_config));diff --git a/rust/cloud-storage/notification_service/src/openapi.rs b/rust/cloud-storage/notification_service/src/openapi.rsindex 9a5ac859d1..4f713cb65e 100644--- a/rust/cloud-storage/notification_service/src/openapi.rs+++ b/rust/cloud-storage/notification_service/src/openapi.rs@@ -5,7 +5,6 @@ mod config;mod env;mod model;mod notification;-mod push_notification_event;mod templates;use utoipa::OpenApi;diff --git a/rust/cloud-storage/notification_service/src/push_notification_event/mod.rs b/rust/cloud-storage/notification_service/src/push_notification_event/mod.rsdeleted file mode 100644index 283663afca..0000000000--- a/rust/cloud-storage/notification_service/src/push_notification_event/mod.rs+++ /dev/null@@ -1,150 +0,0 @@-use anyhow::Context;-use futures::StreamExt;--#[derive(Debug, serde::Deserialize)]-enum EventType {- #[serde(rename = "DeliveryFailure")]- DeliveryFailure,- #[serde(rename = "EndpointDeleted")]- EndpointDeleted,-}--#[derive(Debug, serde::Deserialize)]-struct SnsPushNotificationEvent {- // #[serde(rename = "DeliveryAttempts")]- // delivery_attempts: u32,- #[serde(rename = "EndpointArn")]- endpoint_arn: String,- #[serde(rename = "EventType")]- event_type: EventType,- // #[serde(rename = "FailureMessage")]- // failure_message: String,- // #[serde(rename = "FailureType")]- // failure_type: String,- // #[serde(rename = "MessageId")]- // message_id: String,- // #[serde(rename = "Resource")]- // resource: String,- // #[serde(rename = "Service")]- // service: String,- // #[serde(rename = "Time")]- // time: String,-}--/// Runs the push notification event worker in a loop to handle restarting should it fail.-pub async fn run_push_notification_event_worker(- db: sqlx::Pool<sqlx::Postgres>,- sns_client: sns_client::SNS,- push_notification_event_handler_worker: sqs_worker::SQSWorker,-) {- loop {- let worker_result = tokio::spawn({- let db = db.clone();- let worker = push_notification_event_handler_worker.clone();- let sns_client = sns_client.clone();- async move {- tracing::info!("initiated push notification event handler worker");- loop {- match worker.receive_messages().await {- Ok(messages) => {- if messages.is_empty() {- continue;- }- futures::stream::iter(messages.iter())- .then(|message| {- let db = db.clone();- let worker = worker.clone();- let sns_client = sns_client.clone();- async move {- handle_message(&db, &sns_client, &worker, message).await- }- })- .collect::<Vec<anyhow::Result<()>>>()- .await;- }- Err(e) => {- tracing::error!(error=?e, "error receiving messages");- }- }- }- }- })- .await;-- match worker_result {- Ok(_) => {- // This should never be hit- tracing::error!("worker exited successfully?");- }- Err(e) => {- tracing::error!(error=?e, "worker crashed with error");- }- }-- // Add a delay before restarting to avoid rapid restart loops- tracing::info!("PUSH NOTIFICATION EVENT WORKER RESTARTING...");- tokio::time::sleep(std::time::Duration::from_secs(5)).await;- }-}--/// Processes a push notification event message-#[tracing::instrument(skip(db, sns_client, worker, message))]-pub async fn handle_message(- db: &sqlx::Pool<sqlx::Postgres>,- sns_client: &sns_client::SNS,- worker: &sqs_worker::SQSWorker,- message: &aws_sdk_sqs::types::Message,-) -> anyhow::Result<()> {- tracing::info!(message=?message, "processing push notification event");-- let sns_push_notification_event: SnsPushNotificationEvent = serde_json::from_slice(- message- .body- .as_ref()- .context("failed to get body")?- .as_bytes(),- )- .context("unable to deserialize message")?;-- // we may eventually want to handle the events separately but for now we can easily just delete- // the endpoints- tracing::info!(- device_endpoint=sns_push_notification_event.endpoint_arn,- event_type=?sns_push_notification_event.event_type,- "deleting endpoint"- );-- notification_db_client::device::delete_user_device_by_endpoint(- db,- &sns_push_notification_event.endpoint_arn,- )- .await- .context("unable to delete endpoint")?;-- match sns_push_notification_event.event_type {- EventType::DeliveryFailure => {- sns_client- .delete_endpoint(&sns_push_notification_event.endpoint_arn)- .await- .context("unable to delete endpoint")?;- }- EventType::EndpointDeleted => {}- }-- cleanup_message(worker, message)- .await- .context("unable to delete message")?;-- Ok(())-}--async fn cleanup_message(- worker: &sqs_worker::SQSWorker,- message: &aws_sdk_sqs::types::Message,-) -> anyhow::Result<()> {- if let Some(receipt_handle) = message.receipt_handle.as_ref() {- tracing::trace!(message_id=?message.message_id, message_receipt_handle=?receipt_handle, "deleting message");- worker.delete_message(receipt_handle).await?;- }- Ok(())-}